cul2mqtt.py 43 KB

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