cul2mqtt.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  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 16 bit stripped, as in many cases this is only RSSI and not part of the code
  341. # in this case treat this last 16bit as sensor value
  342. rx_code_stripped = rx_code[0:-2]
  343. if not sucessfullyParsedITCode and rx_code_stripped in RXcodesToDevFunction_IT:
  344. if debug: log_write(" code found in device config with last 16 bit stripped")
  345. receivedForDevice = RXcodesToDevFunction_IT[rx_code_stripped][0]
  346. receivedCmnd = RXcodesToDevFunction_IT[rx_code_stripped][1]
  347. receivedValue = rx_code[-2:]
  348. # convert value to decimal if enabled for this device
  349. if "convertValueToDecimal" in devdata[receivedForDevice]:
  350. if devdata[receivedForDevice]["convertValueToDecimal"] == True:
  351. if debug: log_write(" converting value to decimal")
  352. receivedValue = str(int(receivedValue, base=16))
  353. sucessfullyParsedITCode = True
  354. if debug: log_write(" DEV: " + receivedForDevice + ", CMD: " + receivedCmnd + ", VALUE: " + receivedValue + ", RX: " + rx_code_stripped)
  355. if verbose:
  356. #log_write("")
  357. log_write(" CUL '" + source_cul + "' received '" + rx_code_stripped + "' => DEV: " + receivedForDevice + ", CMD: " + receivedCmnd + ", VALUE: " + receivedValue)
  358. # if this also did not work, try to parse it as "default/cheap" Intertechno code...
  359. if not sucessfullyParsedITCode:
  360. if debug: log_write(" treat code as 'default/cheap' Intertechno code...")
  361. try:
  362. receivedForDevice, receivedCmnd = decodeInterTechnoRX(rx_code_stripped)
  363. except:
  364. log_write(" Error parsing code as 'default/cheap' Intertechno code.")
  365. if debug:
  366. log_write(str(receivedForDevice) + ", " + str(receivedCmnd))
  367. else:
  368. # parse other/RAW RX code
  369. if debug: log_write(" PROTOCOL: OTHER/RAW")
  370. if rx_code in RXcodesToDevFunction_RAW:
  371. receivedForDevice = RXcodesToDevFunction_RAW[rx_code][0]
  372. receivedCmnd = RXcodesToDevFunction_RAW[rx_code][1]
  373. if debug: log_write(" DEV: " + receivedForDevice + ", CMD: " + receivedCmnd + ", RX: " + rx_code)
  374. if verbose:
  375. #log_write("")
  376. log_write(" CUL '" + source_cul + "' received '" + rx_code + "' => DEV: " + receivedForDevice + ", CMD: " + receivedCmnd)
  377. #if debug:
  378. # log_write(" DEV: " + str(receivedForDevice) + ", CMD: " + str(receivedCmnd) + ", RX: " + rx_code)
  379. if receivedForDevice != None and receivedCmnd != None and receivedForDevice != False and receivedCmnd != False:
  380. publish_device_statusupdate(receivedForDevice, receivedCmnd, receivedValue)
  381. def decodeInterTechnoRX(rx_code):
  382. # decode old fixed code from Intertechno remotes
  383. _housecode = None
  384. _devaddr = None
  385. _command = None
  386. _itname = None
  387. #print(rx_code[0:1])
  388. #print(rx_code[1:3])
  389. #print(rx_code[3:5])
  390. #print(rx_code[5:7])
  391. if rx_code[0:1] == "i":
  392. if rx_code[1:3] == "00": _housecode = "A"
  393. elif rx_code[1:3] == "40": _housecode = "B"
  394. elif rx_code[1:3] == "10": _housecode = "C"
  395. elif rx_code[1:3] == "50": _housecode = "D"
  396. elif rx_code[1:3] == "04": _housecode = "E"
  397. elif rx_code[1:3] == "44": _housecode = "F"
  398. elif rx_code[1:3] == "14": _housecode = "G"
  399. elif rx_code[1:3] == "54": _housecode = "H"
  400. elif rx_code[1:3] == "01": _housecode = "I"
  401. elif rx_code[1:3] == "41": _housecode = "J"
  402. elif rx_code[1:3] == "11": _housecode = "K"
  403. elif rx_code[1:3] == "51": _housecode = "L"
  404. elif rx_code[1:3] == "05": _housecode = "M"
  405. elif rx_code[1:3] == "45": _housecode = "N"
  406. elif rx_code[1:3] == "15": _housecode = "O"
  407. elif rx_code[1:3] == "55": _housecode = "P"
  408. if rx_code[3:5] == "00": _devaddr = "1"
  409. elif rx_code[3:5] == "40": _devaddr = "2"
  410. elif rx_code[3:5] == "10": _devaddr = "3"
  411. elif rx_code[3:5] == "50": _devaddr = "4"
  412. elif rx_code[3:5] == "04": _devaddr = "5"
  413. elif rx_code[3:5] == "44": _devaddr = "6"
  414. elif rx_code[3:5] == "14": _devaddr = "7"
  415. elif rx_code[3:5] == "54": _devaddr = "8"
  416. elif rx_code[3:5] == "01": _devaddr = "9"
  417. elif rx_code[3:5] == "41": _devaddr = "10"
  418. elif rx_code[3:5] == "11": _devaddr = "11"
  419. elif rx_code[3:5] == "51": _devaddr = "12"
  420. elif rx_code[3:5] == "05": _devaddr = "13"
  421. elif rx_code[3:5] == "45": _devaddr = "14"
  422. elif rx_code[3:5] == "15": _devaddr = "15"
  423. elif rx_code[3:5] == "55": _devaddr = "16"
  424. if rx_code[5:7] == "15": _command = "ON"
  425. elif rx_code[5:7] == "14": _command = "OFF"
  426. if _housecode != None and _devaddr != None and _command != None:
  427. _itname = "IT_" + _housecode + _devaddr
  428. if debug: log_write("valid IT code: '" + _itname + "' => '" + _command + "'")
  429. return _itname, _command
  430. else:
  431. if debug: log_write("unknown or invalid IT code '" + rx_code + "'")
  432. return False, False
  433. else:
  434. if debug: log_write("unknown or invalid IT code '" + rx_code + "'")
  435. def encodeInterTechnoRX(itname, cmd):
  436. # decode old fixed code from InterTechno remotes
  437. _housecode = None
  438. _devaddr = None
  439. _command = None
  440. #print(itname[0:3])
  441. #print(itname[3:4])
  442. #print(itname[4:])
  443. if itname[0:3] == "IT_":
  444. if itname[3:4] == "A": _housecode = "00"
  445. elif itname[3:4] == "B": _housecode = "40"
  446. elif itname[3:4] == "C": _housecode = "10"
  447. elif itname[3:4] == "D": _housecode = "50"
  448. elif itname[3:4] == "E": _housecode = "04"
  449. elif itname[3:4] == "F": _housecode = "44"
  450. elif itname[3:4] == "G": _housecode = "14"
  451. elif itname[3:4] == "H": _housecode = "54"
  452. elif itname[3:4] == "I": _housecode = "01"
  453. elif itname[3:4] == "J": _housecode = "41"
  454. elif itname[3:4] == "K": _housecode = "11"
  455. elif itname[3:4] == "L": _housecode = "51"
  456. elif itname[3:4] == "M": _housecode = "05"
  457. elif itname[3:4] == "N": _housecode = "45"
  458. elif itname[3:4] == "O": _housecode = "15"
  459. elif itname[3:4] == "P": _housecode = "55"
  460. if itname[4:] == "1": _devaddr = "00"
  461. elif itname[4:] == "2": _devaddr = "40"
  462. elif itname[4:] == "3": _devaddr = "10"
  463. elif itname[4:] == "4": _devaddr = "50"
  464. elif itname[4:] == "5": _devaddr = "04"
  465. elif itname[4:] == "6": _devaddr = "44"
  466. elif itname[4:] == "7": _devaddr = "14"
  467. elif itname[4:] == "8": _devaddr = "54"
  468. elif itname[4:] == "9": _devaddr = "01"
  469. elif itname[4:] == "10": _devaddr = "41"
  470. elif itname[4:] == "11": _devaddr = "11"
  471. elif itname[4:] == "12": _devaddr = "51"
  472. elif itname[4:] == "13": _devaddr = "05"
  473. elif itname[4:] == "14": _devaddr = "45"
  474. elif itname[4:] == "15": _devaddr = "15"
  475. elif itname[4:] == "16": _devaddr = "55"
  476. if cmd == "ON": _command = "15"
  477. elif cmd == "OFF": _command = "14"
  478. if debug: print("IT housecode=", _housecode, "- devaddr=", _devaddr, "- command=", _command)
  479. if _housecode != None and _devaddr != None and _command != None:
  480. _rxcode = "i" + _housecode + _devaddr + _command
  481. #print("encoded IT RX code: '" + itname + "' => '" + cmd + "' = '" + _rxcode)
  482. return _rxcode
  483. else:
  484. if debug: log_write(" unknown or invalid IT code '" + rx_code + "'")
  485. return False
  486. else:
  487. if debug: log_write(" unknown or invalid IT code '" + rx_code + "'")
  488. def cul_received(payload, source_cul):
  489. global lastReceivedTime, lastReceivedMaxAge, lastDataReceiveTime, lastReceivedStatusFile, lastReceivedStatusFileUpdateTime
  490. lastDataReceiveTime = time.time()
  491. if debug:
  492. print("DEBUG: lastDataReceiveTime=" + str(lastDataReceiveTime))
  493. # touch lastReceivedStatusFile if configured
  494. if lastReceivedStatusFile is not None:
  495. if (time.time() - lastReceivedStatusFileUpdateTime) >= 60:
  496. # try updating lastReceivedStatusFile if last time was >60s ago
  497. lastReceivedStatusFileUpdateTime = time.time()
  498. try:
  499. touch(lastReceivedStatusFile)
  500. if debug:
  501. print("DEBUG: lastReceivedStatusFile updated")
  502. except:
  503. if debug:
  504. print("ERROR: could not update lastReceivedStatusFile")
  505. else:
  506. if debug:
  507. print("DEBUG: lastReceivedStatusFile not defined")
  508. if payload[:2] == 'is': # msg is reply from CUL to raw send command
  509. pass
  510. elif payload[:1] == 'i': # is a IT compatible code - so look it up in the code table
  511. if culSendsRSSI:
  512. inCmd = payload[:-2] # strip last 2 chars, depending on used CUL receive mode - if enabled this is only RSSI
  513. else:
  514. inCmd = payload
  515. if verbose:
  516. log_write(" inCmd: " + inCmd + ", receiving CUL: " + source_cul)
  517. # filter fast repeated codes (strip first char on Intertechno codes as the repetation will come in as RAW without "i" prefix)
  518. ignoreCommand = False
  519. if inCmd in lastReceivedTime.keys():
  520. lastTime = int(lastReceivedTime[inCmd])
  521. now = int(round(time.time() * 1000))
  522. tdelta = (now - lastTime)
  523. if debug: log_write(" TDELTA = " + str(tdelta))
  524. if debug: log_write(" lastTime = " + str(lastTime))
  525. if tdelta < lastReceivedMaxAge:
  526. if verbose: log_write(" ignoring code from CUL '" + source_cul + "', CMD: '" + inCmd + "' - already received " + str(tdelta) + " ms ago")
  527. ignoreCommand = True
  528. if not ignoreCommand:
  529. lastReceivedTime[inCmd] = int(round(time.time() * 1000))
  530. parseRXCode(inCmd, source_cul)
  531. elif payload[:1] == 'p': # is RAW data
  532. # example: "p11 288 864 800 320 288 832 33 1 4 1 288 10224 0 A4CEF09580"
  533. # split string and extract last row as we dont need the rest
  534. splitPayload = payload.split(' ')
  535. actualPayload = splitPayload[len(splitPayload)-1]
  536. if debug: log_write(" actualPayload: '" + actualPayload)
  537. ignoreCommand = False
  538. # handle/filter repetations of Intertechno codes
  539. isITrepetation = False
  540. if ('i'+actualPayload) in lastReceivedTime.keys():
  541. isITrepetation = True
  542. if debug: log_write(" skipping repeated Intertechno code")
  543. lastTime = int(lastReceivedTime['i'+actualPayload])
  544. now = int(round(time.time() * 1000))
  545. tdelta = (now - lastTime)
  546. if debug: log_write(" TDELTA = " + str(tdelta))
  547. if tdelta < lastReceivedMaxAge:
  548. if verbose: log_write(" ignoring code from CUL '" + source_cul + "', CMD: '" + 'i'+actualPayload + "' - already received " + str(tdelta) + " ms ago")
  549. ignoreCommand = True
  550. # filter fast repeated codes
  551. if not isITrepetation:
  552. if actualPayload in lastReceivedTime.keys():
  553. lastTime = int(lastReceivedTime[actualPayload])
  554. now = int(round(time.time() * 1000))
  555. tdelta = (now - lastTime)
  556. if debug: log_write(" TDELTA = " + str(tdelta))
  557. if tdelta < lastReceivedMaxAge:
  558. if verbose: log_write(" ignoring code from CUL '" + source_cul + "', CMD: '" + actualPayload + "' - already received " + str(tdelta) + " ms ago")
  559. ignoreCommand = True
  560. if not ignoreCommand:
  561. if isITrepetation:
  562. # treat as Intertechno code
  563. lastReceivedTime['i'+actualPayload] = int(round(time.time() * 1000))
  564. parseRXCode('i'+actualPayload, source_cul)
  565. else:
  566. lastReceivedTime[actualPayload] = int(round(time.time() * 1000))
  567. parseRXCode(actualPayload, source_cul)
  568. #if repeat_received_commands:
  569. # lastSentLength = len(lastSent)
  570. # i = 0
  571. # dontRepeat = False
  572. # while i < lastSentLength:
  573. # #print(str(i) + ": " + lastReceived[i])
  574. # if lastSent[i] == decCmd:
  575. # lastTime = int(lastSentTime[i])
  576. # now = int(round(time.time() * 1000))
  577. # tdelta = (now - lastTime)
  578. # #print("TDELTA = " + str(tdelta))
  579. # if tdelta < lastSentMaxAge:
  580. # print("ignoring command as it originated from ourselfs " + inCmd + " " + str(tdelta) + " ms ago")
  581. # dontRepeat = True
  582. # #break
  583. # i += 1
  584. # #cmdToSend = culSendCmds[decCmd]
  585. # if not dontRepeat:
  586. # if device != "" and cmd != "":
  587. # print("REPEATING COMMAND: " + cmd + " TO DEVICE " + device)
  588. # cul_send(device, cmd)
  589. def IT_RXtoTXCode(itReceiveCode):
  590. if debug:
  591. statusstr = "IT_RXtoTXCode "
  592. statusstr += "RX: "
  593. statusstr += itReceiveCode
  594. #print("IT_RXtoTXCode ReceiveCode: " + itReceiveCode)
  595. itReceiveCode = itReceiveCode[1:] # remove first character "i"
  596. itReceiveCodeLengthBytes = int(len(itReceiveCode)/2)
  597. itReceiveCodeBytes = []
  598. itTransmitTristate = "is"
  599. for x in range(itReceiveCodeLengthBytes):
  600. itReceiveCodeBytes.append(bin(int(itReceiveCode[x*2:(x*2+2)],16))[2:].zfill(8))
  601. for x in range(len(itReceiveCodeBytes)):
  602. #print("IT REC byte " + str(x) + " = " + str(itReceiveCodeBytes[x]))
  603. for y in range(4):
  604. quarterbyte = str(itReceiveCodeBytes[x][y*2:y*2+2])
  605. if quarterbyte == "00":
  606. tmpTristate = "0";
  607. elif quarterbyte == "01":
  608. tmpTristate = "F";
  609. elif quarterbyte == "10":
  610. tmpTristate = "D";
  611. elif quarterbyte == "11":
  612. tmpTristate = "1";
  613. #print(quarterbyte + " -> " + tmpTristate)
  614. itTransmitTristate = itTransmitTristate + tmpTristate
  615. if debug:
  616. statusstr += " -> TX: "
  617. statusstr += itTransmitTristate
  618. #print("IT_RXtoTXCode TransmitCode: " + itTransmitTristate)
  619. log_write(statusstr)
  620. return(itTransmitTristate)
  621. def cul_send(device, cmd):
  622. global lastSentTime
  623. culCmd = ""
  624. culSendCmdsKeyName = device + ' ' + cmd
  625. if debug: log_write("CUL send '" + cmd + "' to device '" + device + "'")
  626. tx_code = False
  627. if 'TX' in devdata[device]:
  628. if debug: print("TX data available, cmd="+cmd)
  629. if debug: print(devdata[device]['TX'])
  630. if cmd in devdata[device]['TX'].keys():
  631. tx_code = devdata[device]['TX'][cmd]
  632. if verbose: log_write(" TX code for '" + cmd + "': " + tx_code)
  633. if not tx_code:
  634. if verbose: log_write(" deviceID: " + device)
  635. if 'RX' in devdata[device].keys():
  636. if verbose:
  637. log_write(" RX code configured, cmd=" + cmd)
  638. log_write(devdata[device]['RX'])
  639. if cmd in devdata[device]['RX'].keys():
  640. rx_code = devdata[device]['RX'][cmd]
  641. if debug: log_write(" RX code for '" + cmd + "': " + rx_code)
  642. tx_code = IT_RXtoTXCode(rx_code)
  643. if verbose: log_write(" TX code for '" + cmd + "': " + tx_code)
  644. else:
  645. log_write(" RX code for '" + cmd + "' NOT FOUND")
  646. elif device.startswith("IT_"):
  647. # InterTechno device with fixed code - encode RX code for IT device name and convert to TX code
  648. rx_code = encodeInterTechnoRX(device, cmd)
  649. if rx_code:
  650. if debug: log_write(" RX code for '" + cmd + "': " + rx_code)
  651. tx_code = IT_RXtoTXCode(rx_code)
  652. if verbose: log_write(" TX code for '" + cmd + "': " + tx_code)
  653. if not tx_code:
  654. if verbose: log_write(" no valid TX code for this device/command")
  655. else:
  656. now = int(round(time.time() * 1000))
  657. # look if this command has been sent in the past, and when
  658. if culSendCmdsKeyName in lastSentTime.keys():
  659. lastTime = lastSentTime[culSendCmdsKeyName]
  660. else:
  661. lastTime = 0
  662. lastTimeAge = now - lastTime
  663. if verbose: log_write(' lastTime: ' + str(lastTimeAge) + 'ms ago')
  664. if lastTimeAge > lastSentMinInterval: # only send if last time + min interval is exceeded
  665. lastSentTime[culSendCmdsKeyName] = now # save what we send, so that we dont repeat our own sent messages if repeating is enabled
  666. TX_interface = TX_interface_prefer
  667. if 'TX_interface' in devdata[device].keys():
  668. if verbose: log_write(" TX_interface: " + devdata[device]['TX_interface'])
  669. if TX_interface == "UART" and not serialCULAvailable:
  670. TX_interface = "MQTT"
  671. global lastSentCmd, lastSentCmdTime, lastSentDev, lastSentDevCmd
  672. lastSentCmd = tx_code
  673. lastSentCmdTime = now
  674. lastSentDev = device
  675. lastSentDevCmd = cmd
  676. if send_on_mqtt_cul and (TX_interface == "MQTT" or TX_interface == "both"):
  677. log_write(" TX via MQTT: " + tx_code)
  678. mqttc.publish(mqtt_cul_topic_send, tx_code, qos=0, retain=False)
  679. if serialCULAvailable and send_on_serial_cul and (TX_interface == "UART" or TX_interface == "both"):
  680. log_write(" TX via UART: " + tx_code)
  681. culCmd = tx_code + '\r\n'
  682. ser.write(culCmd.encode('ascii'))
  683. else:
  684. log_write("WARNING: CUL send command repeated too quickly.")
  685. publish_device_statusupdate(device, cmd, None)
  686. # main
  687. if receive_from_serial_cul or send_on_serial_cul:
  688. if not os.path.exists(serialPort):
  689. log_write("ERROR opening connection to serial CUL... device '" + serialPort + "' does not exist.")
  690. if log_enable: log_write("CUL2MQTT v"+str(version)+" starting")
  691. if receive_from_mqtt_cul:
  692. if forceSerialCULConnected:
  693. exit(2)
  694. else:
  695. log_write("resuming in MQTT-CUL only mode...")
  696. TX_interface_prefer = "MQTT"
  697. receive_from_serial_cul = False
  698. send_on_serial_cul = False
  699. serialCULAvailable = False
  700. log_write("")
  701. log_write("")
  702. else:
  703. log_write("opening connection to UART-CUL...")
  704. serLine = ""
  705. ser = serial.Serial(port=serialPort,baudrate=serialBaudrate,parity=serial.PARITY_NONE,stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS,timeout=serialTimeout)
  706. sleep(serialCulInitTimeout)
  707. ser.write('V\r\n'.encode('ascii')) # get CUL version info
  708. serLine = ser.readline()
  709. serLine = serLine.decode('ascii').rstrip('\r\n')
  710. if serLine.startswith("V ") and serLine.find("culfw") != -1:
  711. log_write("connected. CUL version: " + serLine)
  712. serialCULAvailable = True
  713. sleep(0.1)
  714. log_write('Initializing CUL with command: ' + culInitCmd.rstrip('\r\n'))
  715. ser.write(culInitCmd.encode('ascii')) # initialize CUL in normal receive mode
  716. sleep(0.5)
  717. else:
  718. log_write("WARNING: could not connect UART-CUL")
  719. receive_from_serial_cul = False
  720. send_on_serial_cul = False
  721. serialCULAvailable = False
  722. TX_interface_prefer = "MQTT"
  723. if forceSerialCULConnected:
  724. exit(2)
  725. mqttc = mqtt.Client()
  726. mqttc.on_connect = on_connect
  727. mqttc.on_disconnect = on_disconnect
  728. mqttc.on_message = on_message
  729. if mqtt_user is not None and mqtt_password is not None:
  730. if len(mqtt_user) > 0 and len(mqtt_password) > 0:
  731. mqttc.username_pw_set(mqtt_user, mqtt_password)
  732. mqttc.connect(mqtt_server, mqtt_port, 60)
  733. mqttc.loop_start()
  734. try:
  735. while True:
  736. if receive_from_serial_cul:
  737. serLine = ser.readline()
  738. if len(serLine) > 0:
  739. now = int(round(time.time() * 1000))
  740. recvCmd = serLine.decode('ascii')
  741. recvCmd = recvCmd.rstrip('\r\n')
  742. #if debug:
  743. # print("lastSentCmd: " + lastSentCmd + ", lastSentCmdTime=" + str(lastSentCmdTime))
  744. if recvCmd == lastSentCmd and (now - lastSentCmdTime) < filterSelfSentIncomingTimeout:
  745. pass
  746. else:
  747. if verbose:
  748. log_write("")
  749. log_write("UART-CUL RX: '" + recvCmd + "'")
  750. cul_received(recvCmd, "UART")
  751. #touch("/tmp/culagent_running")
  752. # check if receive timeout is exceeded
  753. # - if so there is possibly something wrong
  754. # -> quit program (will be restarted by systemd)
  755. if dataReceiveTimeout is not None:
  756. if (time.time() - lastDataReceiveTime) >= dataReceiveTimeout:
  757. print("WARNING: received no data from CUL for >" + str(dataReceiveTimeout) + "s -> something has gone wrong -> quitting program.")
  758. quit()
  759. ##else:
  760. ## print("dataReceiveTimeout not configured")
  761. sleep(0.05)
  762. except KeyboardInterrupt:
  763. print("\n")