cul2mqtt.py 32 KB

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