cul2mqtt.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. #!/usr/bin/python3 -u
  2. #
  3. # pip3 install pyyaml paho-mqtt pyserial
  4. import yaml
  5. from yaml.constructor import ConstructorError
  6. import serial
  7. import sys
  8. import time
  9. from time import sleep
  10. from time import localtime, strftime
  11. import datetime
  12. import paho.mqtt.client as mqtt
  13. import json
  14. import os
  15. import re
  16. import configparser
  17. version = 0.4
  18. # Change working dir to the same dir as this script
  19. os.chdir(sys.path[0])
  20. config = configparser.ConfigParser()
  21. config.read('cul2mqtt.ini')
  22. # global variables
  23. verbose = False
  24. debug = False
  25. quiet = True
  26. serialCULAvailable = False
  27. devdata = {}
  28. RXcodesToDevFunction_IT = {}
  29. RXcodesToDevFunction_RAW = {}
  30. InTopicsToDevIds = {}
  31. lastDataReceiveTime = time.time()
  32. # config vars
  33. deviceConfigFile = config['main'].get('devices_config_yml')
  34. log_enable = config['main'].getboolean('log_enable')
  35. log_path = config['main'].get('log_path')
  36. if not os.path.exists(log_path):
  37. os.makedirs(log_path)
  38. mqtt_server = config['mqtt'].get('server')
  39. mqtt_port = config['mqtt'].getint('port')
  40. mqtt_user = config['mqtt'].get('user')
  41. mqtt_password = config['mqtt'].get('password')
  42. TX_interface_prefer = config['cul'].get('TX_interface_prefer') # UART or MQTT
  43. if TX_interface_prefer is None: # compatibility with old ini file structure
  44. TX_interface_prefer = config['main'].get('TX_interface_prefer') # UART or MQTT
  45. repeat_received_commands = False # not yet implemented
  46. if len(sys.argv) >= 2:
  47. if sys.argv[1] == "-q":
  48. verbose = False
  49. debug = False
  50. quiet = True
  51. elif sys.argv[1] == "-v":
  52. verbose = True
  53. debug = False
  54. quiet = False
  55. elif sys.argv[1] == "-d":
  56. verbose = True
  57. debug = True
  58. quiet = False
  59. # serial (USB) CUL device
  60. receive_from_serial_cul = config['cul'].getboolean('receive_from_serial_cul')
  61. send_on_serial_cul = config['cul'].getboolean('send_on_serial_cul')
  62. serialPort = config['cul'].get('serialPort')
  63. serialBaudrate = config['cul'].getint('serialBaudrate')
  64. serialTimeout = config['cul'].getint('serialTimeout')
  65. # CUL init command for normal operation, i.E. X21, X05
  66. culInitCmd = config['cul'].get('culInitCmd') + '\r\n'
  67. culSendsRSSI = config['cul'].getboolean('culSendsRSSI') # set depending on culInitCmd chosen
  68. serialCulInitTimeout = config['cul'].getint('serialCulInitTimeout')
  69. forceSerialCULConnected = config['cul'].getboolean('forceSerialCULConnected')
  70. # MQTT CUL
  71. receive_from_mqtt_cul = config['cul'].getboolean('receive_from_mqtt_cul')
  72. send_on_mqtt_cul = config['cul'].getboolean('send_on_mqtt_cul')
  73. mqtt_cul_topic_received = config['cul'].get('mqtt_cul_topic_received')
  74. mqtt_cul_topic_send = config['cul'].get('mqtt_cul_topic_send')
  75. filterSelfSentIncomingTimeout = config['main'].get('filterSelfSentIncomingTimeout')
  76. try:
  77. from yaml import CLoader as Loader
  78. except ImportError:
  79. from yaml import Loader
  80. def no_duplicates_constructor(loader, node, deep=False):
  81. """Check for duplicate keys."""
  82. mapping = {}
  83. for key_node, value_node in node.value:
  84. key = loader.construct_object(key_node, deep=deep)
  85. value = loader.construct_object(value_node, deep=deep)
  86. if key in mapping:
  87. raise ConstructorError("while constructing a mapping", node.start_mark, "found duplicate key (%s)" % key, key_node.start_mark)
  88. mapping[key] = value
  89. return loader.construct_mapping(node, deep)
  90. yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, no_duplicates_constructor)
  91. log_last_date = None
  92. logfilehandle = False
  93. def log_start():
  94. global logfilehandle, log_last_date
  95. if log_enable:
  96. if not os.path.exists(log_path):
  97. os.makedirs(log_path)
  98. try:
  99. _log_current_date = strftime("%Y%m%d")
  100. _logfilename = _log_current_date + ".log"
  101. logfilehandle = open(log_path + '/' + _logfilename, 'a')
  102. log_last_date = _log_current_date
  103. except:
  104. pass
  105. def log_rotate():
  106. global logfilehandle, log_last_date
  107. if log_enable:
  108. _log_current_date = strftime("%Y%m%d")
  109. if log_last_date != _log_current_date:
  110. try:
  111. logfilehandle.close()
  112. _logfilename = _log_current_date + ".log"
  113. logfilehandle = open(log_path + '/' + _logfilename, 'a')
  114. log_last_date = _log_current_date
  115. except:
  116. pass
  117. def log_write(_msg):
  118. global logfilehandle
  119. if not quiet: print(_msg)
  120. log_rotate()
  121. if log_enable:
  122. try:
  123. logfilehandle.write("[" + str(datetime.datetime.now()) + "] " + _msg + "\n")
  124. logfilehandle.flush()
  125. except:
  126. # guat dann hoit ned...
  127. pass
  128. log_start()
  129. log_write("CUL2MQTT v" + str(version))
  130. log_write("=====================================")
  131. try:
  132. with open(deviceConfigFile) as devfile:
  133. devdata = yaml.load(devfile, Loader=yaml.FullLoader)
  134. if debug:
  135. log_write("")
  136. log_write("")
  137. log_write("==== parsing config file ====")
  138. log_write("")
  139. log_write(devdata)
  140. log_write("")
  141. for deviceid in devdata:
  142. if debug:
  143. log_write("")
  144. log_write("")
  145. log_write("Device: " + deviceid)
  146. log_write(devdata[deviceid])
  147. if "RX" in devdata[deviceid].keys():
  148. if devdata[deviceid]["RX"] != "":
  149. if debug:
  150. log_write("RX codes:")
  151. for key, value in devdata[deviceid]["RX"].items():
  152. if debug:
  153. log_write(str(key) + "->" + str(value))
  154. if value.startswith("i"):
  155. # is Intertechno RX code
  156. if value in RXcodesToDevFunction_IT.keys():
  157. log_write("")
  158. log_write("")
  159. log_write("ERROR: RX-string '" + str(value) + "' is already defined for another device! Must be unique.")
  160. raise
  161. else:
  162. RXcodesToDevFunction_IT[value] = deviceid, key
  163. else:
  164. # is other RX code - lets call it RAW
  165. if value in RXcodesToDevFunction_RAW.keys():
  166. log_write("")
  167. log_write("")
  168. log_write("ERROR: RX-string '" + str(value) + "' is already defined for another device! Must be unique.")
  169. raise
  170. else:
  171. RXcodesToDevFunction_RAW[value] = deviceid, key
  172. if "cmdTopic" in devdata[deviceid].keys():
  173. if devdata[deviceid]["cmdTopic"] != "":
  174. cmdTopic = devdata[deviceid]["cmdTopic"]
  175. if debug:
  176. log_write("cmdTopic: " + cmdTopic)
  177. if cmdTopic in InTopicsToDevIds.keys():
  178. log_write("")
  179. log_write("")
  180. log_write("ERROR: cmdTopic '" + str(cmdTopic) + "' is already defined for another device! Must be unique.")
  181. raise
  182. else:
  183. InTopicsToDevIds[cmdTopic] = deviceid
  184. if debug:
  185. log_write("")
  186. log_write("")
  187. log_write("")
  188. log_write("RXcodesToDevFunction_IT:")
  189. log_write(RXcodesToDevFunction_IT)
  190. log_write("")
  191. log_write("")
  192. log_write("RXcodesToDevFunction_RAW:")
  193. log_write(RXcodesToDevFunction_RAW)
  194. log_write("")
  195. log_write("")
  196. log_write("InTopicsToDevIds:")
  197. log_write(InTopicsToDevIds)
  198. log_write("")
  199. log_write("")
  200. log_write("InTopicsToDevIds.keys():")
  201. log_write(InTopicsToDevIds.keys())
  202. log_write("")
  203. log_write("")
  204. log_write("devdata.keys():")
  205. log_write(devdata.keys())
  206. log_write("")
  207. log_write("")
  208. log_write("==== parsing config file complete ====")
  209. log_write("")
  210. log_write("")
  211. log_write("")
  212. log_write("")
  213. except ConstructorError as err:
  214. log_write("ERROR on parsing configfile:")
  215. log_write(err)
  216. exit(1)
  217. except:
  218. log_write("ERROR opening configfile")
  219. log_write("Unexpected error: " + str(sys.exc_info()[0]))
  220. exit(1)
  221. lastReceivedMaxAge = config['main'].getint('lastReceivedMaxAge') # ignore repeated messages when they are younger than x ms
  222. lastReceivedTime = dict()
  223. lastSentTime = {}
  224. lastSentMinInterval = config['main'].getint('lastSentMinInterval') # ignore repeated messages when they are younger than x ms, should be > 1500
  225. lastSentCmd = ""
  226. lastSentCmdTime = 0
  227. lastSentDev = ""
  228. lastSentDevCmd = ""
  229. def touch(fname, times=None):
  230. with open(fname, 'a'):
  231. os.utime(fname, times)
  232. def on_connect(client, userdata, flags, rc):
  233. if verbose:
  234. log_write("MQTT connected with result code " + str(rc))
  235. if receive_from_mqtt_cul:
  236. if mqtt_cul_topic_received != "":
  237. client.subscribe(mqtt_cul_topic_received)
  238. if mqtt_cul_topic_send != "":
  239. #client.publish
  240. mqttc.publish(mqtt_cul_topic_send, culInitCmd, qos=0, retain=False)
  241. for in_topic in InTopicsToDevIds.keys():
  242. if in_topic != "":
  243. client.subscribe(in_topic)
  244. if verbose:
  245. log_write("MQTT subscribed: " + in_topic)
  246. def on_disconnect(client, userdata, rc):
  247. if rc != 0:
  248. log_write("Unexpected MQTT disconnection. Will auto-reconnect")
  249. def on_message(client, userdata, msg):
  250. #print(msg.topic + ": " + str(msg.payload))
  251. payload = msg.payload.decode("utf-8")
  252. if verbose:
  253. log_write("")
  254. log_write("MQTT received: " + msg.topic + " -> " + str(payload))
  255. # MQTT message is output from CUL
  256. if receive_from_mqtt_cul and msg.topic == mqtt_cul_topic_received:
  257. payload = payload.rstrip()
  258. # support output from Tasmota SerialBridge on tele/[DEVICE]/RESULT topic
  259. # example: {"SerialReceived":"p10 144 80 480 48 32 1360 28 1 3 4 160 6336 0 735C1470"}
  260. if payload.startswith('{"SerialReceived":'):
  261. payload_json = json.loads(payload)
  262. payload = payload_json.get('SerialReceived')
  263. if payload != None:
  264. cul_received(payload, "MQTT") # to lower case as MQTT CUL via Tasmota SerialBridge with Rule changes output to all uppercase
  265. if verbose:
  266. log_write("MQTT-CUL RX: '" + payload + "'")
  267. elif not payload.startswith('{'):
  268. # ignore everything different starting with {
  269. cul_received(payload.lower(), "MQTT") # to lower case as MQTT CUL via Tasmota SerialBridge with Rule changes output to all uppercase
  270. if verbose:
  271. log_write("MQTT-CUL RX: '" + payload.lower() + "'")
  272. else:
  273. for in_topic, dev in InTopicsToDevIds.items():
  274. if msg.topic == in_topic:
  275. if verbose: log_write("MQTT received - '" + msg.topic + "' = '" + payload + "' => DEV: " + dev)
  276. if 'name' in devdata[dev].keys():
  277. log_write('devName: ' + devdata[dev]['name'])
  278. global lastSentDev, lastSentDevCmd, lastSentCmdTime
  279. now = int(round(time.time() * 1000))
  280. if debug:
  281. log_write("dev="+dev+", lastSentDevCmd="+lastSentDevCmd)
  282. if dev == lastSentDev and payload == lastSentDevCmd and (now - lastSentCmdTime) < 1000:
  283. if verbose:
  284. log_write("MQTT: ignored command as we just sent this.")
  285. else:
  286. cul_send(dev, payload)
  287. if 'statTopic' in devdata[dev].keys():
  288. if verbose: log_write('statTopic: ' + devdata[dev]['statTopic'])
  289. mqttc.publish(devdata[dev]['statTopic'], payload, qos=0, retain=False)
  290. if 'add_statTopics_on' in devdata[dev].keys():
  291. if verbose: log_write("add_statTopics_on:")
  292. for res in devdata[dev]['add_statTopics_on']:
  293. if 'on_payload' in res and 'topic' in res and 'payload' in res:
  294. if payload == res['on_payload'] and payload != "" and res['topic'] != "" and res['payload'] != "":
  295. if verbose: log_write(" on '" + payload + "': '" + res['payload'] + "' => '" + res['topic'] + "'")
  296. mqttc.publish(res['topic'], res['payload'], qos=0, retain=False)
  297. def publish_device_statusupdate(device, cmd, value):
  298. if device in devdata.keys():
  299. if 'statTopic' in devdata[device].keys():
  300. statTopic = devdata[device].get('statTopic')
  301. if value is not None and cmd == "%VALUE%":
  302. if verbose: log_write(" MQTT publish: '" + value + "' -> '" + statTopic + "'")
  303. mqttc.publish(statTopic, value, qos=0, retain=False)
  304. else:
  305. if verbose: log_write(" MQTT publish: '" + cmd + "' -> '" + statTopic + "'")
  306. mqttc.publish(statTopic, cmd, qos=0, retain=False)
  307. if 'add_statTopics_on' in devdata[device].keys():
  308. if verbose: log_write(" MQTT publish add_statTopics_on:")
  309. for res in devdata[device].get('add_statTopics_on'):
  310. if 'on_payload' in res and 'topic' in res and 'payload' in res:
  311. if cmd == res['on_payload']:
  312. if verbose: log_write(" on '" + res['on_payload'] + "' -> publish '" + res['payload'] + "' on topic '" + res['topic'] + "'")
  313. mqttc.publish(res['topic'], res['payload'], qos=0, retain=False)
  314. if 'add_statTopics' in devdata[device].keys():
  315. if verbose: log_write(" MQTT publish on add_statTopics:")
  316. for res in devdata[device]['add_statTopics']:
  317. if verbose: log_write(" '" + cmd + "' -> '" + res + "'")
  318. mqttc.publish(res, cmd, qos=0, retain=False)
  319. def parseRXCode(rx_code, source_cul):
  320. receivedForDevice = None
  321. receivedCmnd = None
  322. receivedValue = None
  323. if rx_code.startswith("i"):
  324. # parse Intertechno RX code
  325. if debug: log_write(" PROTOCOL: Intertechno")
  326. sucessfullyParsedITCode = False
  327. # look if this code is in the device_config
  328. if rx_code in RXcodesToDevFunction_IT:
  329. if debug: log_write(" code found in device config")
  330. receivedForDevice = RXcodesToDevFunction_IT[rx_code][0]
  331. receivedCmnd = RXcodesToDevFunction_IT[rx_code][1]
  332. sucessfullyParsedITCode = True
  333. if debug: log_write(" DEV: " + receivedForDevice + ", CMD: " + receivedCmnd + ", RX: " + rx_code)
  334. if verbose:
  335. #log_write("")
  336. log_write(" CUL '" + source_cul + "' received '" + rx_code + "' => DEV: " + receivedForDevice + ", CMD: " + receivedCmnd)
  337. # if this had no result -> try again with last 16 bit stripped, as in many cases this is only RSSI and not part of the code
  338. # in this case treat this last 16bit as sensor value
  339. rx_code_stripped = rx_code[0:-2]
  340. if not sucessfullyParsedITCode and rx_code_stripped in RXcodesToDevFunction_IT:
  341. if debug: log_write(" code found in device config with last 16 bit stripped")
  342. receivedForDevice = RXcodesToDevFunction_IT[rx_code_stripped][0]
  343. receivedCmnd = RXcodesToDevFunction_IT[rx_code_stripped][1]
  344. receivedValue = rx_code[-2:]
  345. # convert value to decimal if enabled for this device
  346. if "convertValueToDecimal" in devdata[receivedForDevice]:
  347. if devdata[receivedForDevice]["convertValueToDecimal"] == True:
  348. if debug: log_write(" converting value to decimal")
  349. receivedValue = str(int(receivedValue, base=16))
  350. sucessfullyParsedITCode = True
  351. if debug: log_write(" DEV: " + receivedForDevice + ", CMD: " + receivedCmnd + ", VALUE: " + receivedValue + ", RX: " + rx_code_stripped)
  352. if verbose:
  353. #log_write("")
  354. log_write(" CUL '" + source_cul + "' received '" + rx_code_stripped + "' => DEV: " + receivedForDevice + ", CMD: " + receivedCmnd + ", VALUE: " + receivedValue)
  355. # if this also did not work, try to parse it as "default/cheap" Intertechno code...
  356. if not sucessfullyParsedITCode:
  357. if debug: log_write(" treat code as 'default/cheap' Intertechno code...")
  358. try:
  359. receivedForDevice, receivedCmnd = decodeInterTechnoRX(rx_code_stripped)
  360. except:
  361. log_write(" Error parsing code as 'default/cheap' Intertechno code.")
  362. if debug:
  363. log_write(str(receivedForDevice) + ", " + str(receivedCmnd))
  364. else:
  365. # parse other/RAW RX code
  366. if debug: log_write(" PROTOCOL: OTHER/RAW")
  367. if rx_code in RXcodesToDevFunction_RAW:
  368. receivedForDevice = RXcodesToDevFunction_RAW[rx_code][0]
  369. receivedCmnd = RXcodesToDevFunction_RAW[rx_code][1]
  370. if debug: log_write(" DEV: " + receivedForDevice + ", CMD: " + receivedCmnd + ", RX: " + rx_code)
  371. if verbose:
  372. #log_write("")
  373. log_write(" CUL '" + source_cul + "' received '" + rx_code + "' => DEV: " + receivedForDevice + ", CMD: " + receivedCmnd)
  374. #if debug:
  375. # log_write(" DEV: " + str(receivedForDevice) + ", CMD: " + str(receivedCmnd) + ", RX: " + rx_code)
  376. if receivedForDevice != None and receivedCmnd != None and receivedForDevice != False and receivedCmnd != False:
  377. publish_device_statusupdate(receivedForDevice, receivedCmnd, receivedValue)
  378. def decodeInterTechnoRX(rx_code):
  379. # decode old fixed code from Intertechno remotes
  380. _housecode = None
  381. _devaddr = None
  382. _command = None
  383. _itname = None
  384. #print(rx_code[0:1])
  385. #print(rx_code[1:3])
  386. #print(rx_code[3:5])
  387. #print(rx_code[5:7])
  388. if rx_code[0:1] == "i":
  389. if rx_code[1:3] == "00": _housecode = "A"
  390. elif rx_code[1:3] == "40": _housecode = "B"
  391. elif rx_code[1:3] == "10": _housecode = "C"
  392. elif rx_code[1:3] == "50": _housecode = "D"
  393. elif rx_code[1:3] == "04": _housecode = "E"
  394. elif rx_code[1:3] == "44": _housecode = "F"
  395. elif rx_code[1:3] == "14": _housecode = "G"
  396. elif rx_code[1:3] == "54": _housecode = "H"
  397. elif rx_code[1:3] == "01": _housecode = "I"
  398. elif rx_code[1:3] == "41": _housecode = "J"
  399. elif rx_code[1:3] == "11": _housecode = "K"
  400. elif rx_code[1:3] == "51": _housecode = "L"
  401. elif rx_code[1:3] == "05": _housecode = "M"
  402. elif rx_code[1:3] == "45": _housecode = "N"
  403. elif rx_code[1:3] == "15": _housecode = "O"
  404. elif rx_code[1:3] == "55": _housecode = "P"
  405. if rx_code[3:5] == "00": _devaddr = "1"
  406. elif rx_code[3:5] == "40": _devaddr = "2"
  407. elif rx_code[3:5] == "10": _devaddr = "3"
  408. elif rx_code[3:5] == "50": _devaddr = "4"
  409. elif rx_code[3:5] == "04": _devaddr = "5"
  410. elif rx_code[3:5] == "44": _devaddr = "6"
  411. elif rx_code[3:5] == "14": _devaddr = "7"
  412. elif rx_code[3:5] == "54": _devaddr = "8"
  413. elif rx_code[3:5] == "01": _devaddr = "9"
  414. elif rx_code[3:5] == "41": _devaddr = "10"
  415. elif rx_code[3:5] == "11": _devaddr = "11"
  416. elif rx_code[3:5] == "51": _devaddr = "12"
  417. elif rx_code[3:5] == "05": _devaddr = "13"
  418. elif rx_code[3:5] == "45": _devaddr = "14"
  419. elif rx_code[3:5] == "15": _devaddr = "15"
  420. elif rx_code[3:5] == "55": _devaddr = "16"
  421. if rx_code[5:7] == "15": _command = "ON"
  422. elif rx_code[5:7] == "14": _command = "OFF"
  423. if _housecode != None and _devaddr != None and _command != None:
  424. _itname = "IT_" + _housecode + _devaddr
  425. if debug: log_write("valid IT code: '" + _itname + "' => '" + _command + "'")
  426. return _itname, _command
  427. else:
  428. if debug: log_write("unknown or invalid IT code '" + rx_code + "'")
  429. return False, False
  430. else:
  431. if debug: log_write("unknown or invalid IT code '" + rx_code + "'")
  432. def encodeInterTechnoRX(itname, cmd):
  433. # decode old fixed code from InterTechno remotes
  434. _housecode = None
  435. _devaddr = None
  436. _command = None
  437. #print(itname[0:3])
  438. #print(itname[3:4])
  439. #print(itname[4:])
  440. if itname[0:3] == "IT_":
  441. if itname[3:4] == "A": _housecode = "00"
  442. elif itname[3:4] == "B": _housecode = "40"
  443. elif itname[3:4] == "C": _housecode = "10"
  444. elif itname[3:4] == "D": _housecode = "50"
  445. elif itname[3:4] == "E": _housecode = "04"
  446. elif itname[3:4] == "F": _housecode = "44"
  447. elif itname[3:4] == "G": _housecode = "14"
  448. elif itname[3:4] == "H": _housecode = "54"
  449. elif itname[3:4] == "I": _housecode = "01"
  450. elif itname[3:4] == "J": _housecode = "41"
  451. elif itname[3:4] == "K": _housecode = "11"
  452. elif itname[3:4] == "L": _housecode = "51"
  453. elif itname[3:4] == "M": _housecode = "05"
  454. elif itname[3:4] == "N": _housecode = "45"
  455. elif itname[3:4] == "O": _housecode = "15"
  456. elif itname[3:4] == "P": _housecode = "55"
  457. if itname[4:] == "1": _devaddr = "00"
  458. elif itname[4:] == "2": _devaddr = "40"
  459. elif itname[4:] == "3": _devaddr = "10"
  460. elif itname[4:] == "4": _devaddr = "50"
  461. elif itname[4:] == "5": _devaddr = "04"
  462. elif itname[4:] == "6": _devaddr = "44"
  463. elif itname[4:] == "7": _devaddr = "14"
  464. elif itname[4:] == "8": _devaddr = "54"
  465. elif itname[4:] == "9": _devaddr = "01"
  466. elif itname[4:] == "10": _devaddr = "41"
  467. elif itname[4:] == "11": _devaddr = "11"
  468. elif itname[4:] == "12": _devaddr = "51"
  469. elif itname[4:] == "13": _devaddr = "05"
  470. elif itname[4:] == "14": _devaddr = "45"
  471. elif itname[4:] == "15": _devaddr = "15"
  472. elif itname[4:] == "16": _devaddr = "55"
  473. if cmd == "ON": _command = "15"
  474. elif cmd == "OFF": _command = "14"
  475. if debug: print("IT housecode=", _housecode, "- devaddr=", _devaddr, "- command=", _command)
  476. if _housecode != None and _devaddr != None and _command != None:
  477. _rxcode = "i" + _housecode + _devaddr + _command
  478. #print("encoded IT RX code: '" + itname + "' => '" + cmd + "' = '" + _rxcode)
  479. return _rxcode
  480. else:
  481. if debug: log_write(" unknown or invalid IT code '" + rx_code + "'")
  482. return False
  483. else:
  484. if debug: log_write(" unknown or invalid IT code '" + rx_code + "'")
  485. def cul_received(payload, source_cul):
  486. global lastReceivedTime, lastReceivedMaxAge, lastDataReceiveTime
  487. lastDataReceiveTime = time.time()
  488. if debug:
  489. print("lastDataReceiveTime=" + str(lastDataReceiveTime))
  490. if payload[:2] == 'is': # msg is reply from CUL to raw send command
  491. pass
  492. elif payload[:1] == 'i': # is a IT compatible code - so look it up in the code table
  493. if culSendsRSSI:
  494. inCmd = payload[:-2] # strip last 2 chars, depending on used CUL receive mode - if enabled this is only RSSI
  495. else:
  496. inCmd = payload
  497. if verbose:
  498. log_write(" inCmd: " + inCmd + ", receiving CUL: " + source_cul)
  499. # filter fast repeated codes (strip first char on Intertechno codes as the repetation will come in as RAW without "i" prefix)
  500. ignoreCommand = False
  501. if inCmd in lastReceivedTime.keys():
  502. lastTime = int(lastReceivedTime[inCmd])
  503. now = int(round(time.time() * 1000))
  504. tdelta = (now - lastTime)
  505. if debug: log_write(" TDELTA = " + str(tdelta))
  506. if debug: log_write(" lastTime = " + str(lastTime))
  507. if tdelta < lastReceivedMaxAge:
  508. if verbose: log_write(" ignoring code from CUL '" + source_cul + "', CMD: '" + inCmd + "' - already received " + str(tdelta) + " ms ago")
  509. ignoreCommand = True
  510. if not ignoreCommand:
  511. lastReceivedTime[inCmd] = int(round(time.time() * 1000))
  512. parseRXCode(inCmd, source_cul)
  513. elif payload[:1] == 'p': # is RAW data
  514. # example: "p11 288 864 800 320 288 832 33 1 4 1 288 10224 0 A4CEF09580"
  515. # split string and extract last row as we dont need the rest
  516. splitPayload = payload.split(' ')
  517. actualPayload = splitPayload[len(splitPayload)-1]
  518. if debug: log_write(" actualPayload: '" + actualPayload)
  519. ignoreCommand = False
  520. # handle/filter repetations of Intertechno codes
  521. isITrepetation = False
  522. if ('i'+actualPayload) in lastReceivedTime.keys():
  523. isITrepetation = True
  524. if debug: log_write(" skipping repeated Intertechno code")
  525. lastTime = int(lastReceivedTime['i'+actualPayload])
  526. now = int(round(time.time() * 1000))
  527. tdelta = (now - lastTime)
  528. if debug: log_write(" TDELTA = " + str(tdelta))
  529. if tdelta < lastReceivedMaxAge:
  530. if verbose: log_write(" ignoring code from CUL '" + source_cul + "', CMD: '" + 'i'+actualPayload + "' - already received " + str(tdelta) + " ms ago")
  531. ignoreCommand = True
  532. # filter fast repeated codes
  533. if not isITrepetation:
  534. if actualPayload in lastReceivedTime.keys():
  535. lastTime = int(lastReceivedTime[actualPayload])
  536. now = int(round(time.time() * 1000))
  537. tdelta = (now - lastTime)
  538. if debug: log_write(" TDELTA = " + str(tdelta))
  539. if tdelta < lastReceivedMaxAge:
  540. if verbose: log_write(" ignoring code from CUL '" + source_cul + "', CMD: '" + actualPayload + "' - already received " + str(tdelta) + " ms ago")
  541. ignoreCommand = True
  542. if not ignoreCommand:
  543. if isITrepetation:
  544. # treat as Intertechno code
  545. lastReceivedTime['i'+actualPayload] = int(round(time.time() * 1000))
  546. parseRXCode('i'+actualPayload, source_cul)
  547. else:
  548. lastReceivedTime[actualPayload] = int(round(time.time() * 1000))
  549. parseRXCode(actualPayload, source_cul)
  550. #if repeat_received_commands:
  551. # lastSentLength = len(lastSent)
  552. # i = 0
  553. # dontRepeat = False
  554. # while i < lastSentLength:
  555. # #print(str(i) + ": " + lastReceived[i])
  556. # if lastSent[i] == decCmd:
  557. # lastTime = int(lastSentTime[i])
  558. # now = int(round(time.time() * 1000))
  559. # tdelta = (now - lastTime)
  560. # #print("TDELTA = " + str(tdelta))
  561. # if tdelta < lastSentMaxAge:
  562. # print("ignoring command as it originated from ourselfs " + inCmd + " " + str(tdelta) + " ms ago")
  563. # dontRepeat = True
  564. # #break
  565. # i += 1
  566. # #cmdToSend = culSendCmds[decCmd]
  567. # if not dontRepeat:
  568. # if device != "" and cmd != "":
  569. # print("REPEATING COMMAND: " + cmd + " TO DEVICE " + device)
  570. # cul_send(device, cmd)
  571. def IT_RXtoTXCode(itReceiveCode):
  572. if debug:
  573. statusstr = "IT_RXtoTXCode "
  574. statusstr += "RX: "
  575. statusstr += itReceiveCode
  576. #print("IT_RXtoTXCode ReceiveCode: " + itReceiveCode)
  577. itReceiveCode = itReceiveCode[1:] # remove first character "i"
  578. itReceiveCodeLengthBytes = int(len(itReceiveCode)/2)
  579. itReceiveCodeBytes = []
  580. itTransmitTristate = "is"
  581. for x in range(itReceiveCodeLengthBytes):
  582. itReceiveCodeBytes.append(bin(int(itReceiveCode[x*2:(x*2+2)],16))[2:].zfill(8))
  583. for x in range(len(itReceiveCodeBytes)):
  584. #print("IT REC byte " + str(x) + " = " + str(itReceiveCodeBytes[x]))
  585. for y in range(4):
  586. quarterbyte = str(itReceiveCodeBytes[x][y*2:y*2+2])
  587. if quarterbyte == "00":
  588. tmpTristate = "0";
  589. elif quarterbyte == "01":
  590. tmpTristate = "F";
  591. elif quarterbyte == "10":
  592. tmpTristate = "D";
  593. elif quarterbyte == "11":
  594. tmpTristate = "1";
  595. #print(quarterbyte + " -> " + tmpTristate)
  596. itTransmitTristate = itTransmitTristate + tmpTristate
  597. if debug:
  598. statusstr += " -> TX: "
  599. statusstr += itTransmitTristate
  600. #print("IT_RXtoTXCode TransmitCode: " + itTransmitTristate)
  601. log_write(statusstr)
  602. return(itTransmitTristate)
  603. def cul_send(device, cmd):
  604. global lastSentTime
  605. culCmd = ""
  606. culSendCmdsKeyName = device + ' ' + cmd
  607. if debug: log_write("CUL send '" + cmd + "' to device '" + device + "'")
  608. tx_code = False
  609. if 'TX' in devdata[device]:
  610. if debug: print("TX data available, cmd="+cmd)
  611. if debug: print(devdata[device]['TX'])
  612. if cmd in devdata[device]['TX'].keys():
  613. tx_code = devdata[device]['TX'][cmd]
  614. if verbose: log_write(" TX code for '" + cmd + "': " + tx_code)
  615. if not tx_code:
  616. if verbose: log_write(" deviceID: " + device)
  617. if 'RX' in devdata[device].keys():
  618. if verbose:
  619. log_write(" RX code configured, cmd=" + cmd)
  620. log_write(devdata[device]['RX'])
  621. if cmd in devdata[device]['RX'].keys():
  622. rx_code = devdata[device]['RX'][cmd]
  623. if debug: log_write(" RX code for '" + cmd + "': " + rx_code)
  624. tx_code = IT_RXtoTXCode(rx_code)
  625. if verbose: log_write(" TX code for '" + cmd + "': " + tx_code)
  626. else:
  627. log_write(" RX code for '" + cmd + "' NOT FOUND")
  628. elif device.startswith("IT_"):
  629. # InterTechno device with fixed code - encode RX code for IT device name and convert to TX code
  630. rx_code = encodeInterTechnoRX(device, cmd)
  631. if rx_code:
  632. if debug: log_write(" RX code for '" + cmd + "': " + rx_code)
  633. tx_code = IT_RXtoTXCode(rx_code)
  634. if verbose: log_write(" TX code for '" + cmd + "': " + tx_code)
  635. if not tx_code:
  636. if verbose: log_write(" no valid TX code for this device/command")
  637. else:
  638. now = int(round(time.time() * 1000))
  639. # look if this command has been sent in the past, and when
  640. if culSendCmdsKeyName in lastSentTime.keys():
  641. lastTime = lastSentTime[culSendCmdsKeyName]
  642. else:
  643. lastTime = 0
  644. lastTimeAge = now - lastTime
  645. if verbose: log_write(' lastTime: ' + str(lastTimeAge) + 'ms ago')
  646. if lastTimeAge > lastSentMinInterval: # only send if last time + min interval is exceeded
  647. lastSentTime[culSendCmdsKeyName] = now # save what we send, so that we dont repeat our own sent messages if repeating is enabled
  648. TX_interface = TX_interface_prefer
  649. if 'TX_interface' in devdata[device].keys():
  650. if verbose: log_write(" TX_interface: " + devdata[device]['TX_interface'])
  651. if TX_interface == "UART" and not serialCULAvailable:
  652. TX_interface = "MQTT"
  653. global lastSentCmd, lastSentCmdTime, lastSentDev, lastSentDevCmd
  654. lastSentCmd = tx_code
  655. lastSentCmdTime = now
  656. lastSentDev = device
  657. lastSentDevCmd = cmd
  658. if send_on_mqtt_cul and (TX_interface == "MQTT" or TX_interface == "both"):
  659. log_write(" TX via MQTT: " + tx_code)
  660. mqttc.publish(mqtt_cul_topic_send, tx_code, qos=0, retain=False)
  661. if serialCULAvailable and send_on_serial_cul and (TX_interface == "UART" or TX_interface == "both"):
  662. log_write(" TX via UART: " + tx_code)
  663. culCmd = tx_code + '\r\n'
  664. ser.write(culCmd.encode('ascii'))
  665. else:
  666. log_write("WARNING: CUL send command repeated too quickly.")
  667. publish_device_statusupdate(device, cmd, None)
  668. # main
  669. if receive_from_serial_cul or send_on_serial_cul:
  670. if not os.path.exists(serialPort):
  671. log_write("ERROR opening connection to serial CUL... device '" + serialPort + "' does not exist.")
  672. if log_enable: log_write("CUL2MQTT v"+str(version)+" starting")
  673. if receive_from_mqtt_cul:
  674. if forceSerialCULConnected:
  675. exit(2)
  676. else:
  677. log_write("resuming in MQTT-CUL only mode...")
  678. TX_interface_prefer = "MQTT"
  679. receive_from_serial_cul = False
  680. send_on_serial_cul = False
  681. serialCULAvailable = False
  682. log_write("")
  683. log_write("")
  684. else:
  685. log_write("opening connection to UART-CUL...")
  686. serLine = ""
  687. ser = serial.Serial(port=serialPort,baudrate=serialBaudrate,parity=serial.PARITY_NONE,stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS,timeout=serialTimeout)
  688. sleep(serialCulInitTimeout)
  689. ser.write('V\r\n'.encode('ascii')) # get CUL version info
  690. serLine = ser.readline()
  691. serLine = serLine.decode('ascii').rstrip('\r\n')
  692. if serLine.startswith("V ") and serLine.find("culfw") != -1:
  693. log_write("connected. CUL version: " + serLine)
  694. serialCULAvailable = True
  695. sleep(0.1)
  696. log_write('Initializing CUL with command: ' + culInitCmd.rstrip('\r\n'))
  697. ser.write(culInitCmd.encode('ascii')) # initialize CUL in normal receive mode
  698. sleep(0.5)
  699. else:
  700. log_write("WARNING: could not connect UART-CUL")
  701. receive_from_serial_cul = False
  702. send_on_serial_cul = False
  703. serialCULAvailable = False
  704. TX_interface_prefer = "MQTT"
  705. if forceSerialCULConnected:
  706. exit(2)
  707. mqttc = mqtt.Client()
  708. mqttc.on_connect = on_connect
  709. mqttc.on_disconnect = on_disconnect
  710. mqttc.on_message = on_message
  711. if mqtt_user is not None and mqtt_password is not None:
  712. if len(mqtt_user) > 0 and len(mqtt_password) > 0:
  713. mqttc.username_pw_set(mqtt_user, mqtt_password)
  714. mqttc.connect(mqtt_server, mqtt_port, 60)
  715. mqttc.loop_start()
  716. try:
  717. while True:
  718. if receive_from_serial_cul:
  719. serLine = ser.readline()
  720. if len(serLine) > 0:
  721. now = int(round(time.time() * 1000))
  722. recvCmd = serLine.decode('ascii')
  723. recvCmd = recvCmd.rstrip('\r\n')
  724. #if debug:
  725. # print("lastSentCmd: " + lastSentCmd + ", lastSentCmdTime=" + str(lastSentCmdTime))
  726. if recvCmd == lastSentCmd and (now - lastSentCmdTime) < filterSelfSentIncomingTimeout:
  727. pass
  728. else:
  729. if verbose:
  730. log_write("")
  731. log_write("UART-CUL RX: '" + recvCmd + "'")
  732. cul_received(recvCmd, "UART")
  733. #touch("/tmp/culagent_running")
  734. # check if receive timeout is exceeded
  735. # - if so there is possibly something wrong
  736. # -> quit program (will be restarted by systemd)
  737. if config['main'].get('dataReceiveTimeout') is not None:
  738. if (time.time() - lastDataReceiveTime) >= float(config['main'].get('dataReceiveTimeout')):
  739. print("WARNING: received no data from CUL for >" + str(config['main'].get('dataReceiveTimeout')) + "s -> something has gone wrong -> quitting program.")
  740. quit()
  741. #else:
  742. # print("dataReceiveTimeout not configured")
  743. sleep(0.05)
  744. except KeyboardInterrupt:
  745. print("\n")