cul2mqtt.py 39 KB

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