cul2mqtt.py 42 KB

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