From 9b039990a17e57bd3ae59b3a58be815d5c56859e Mon Sep 17 00:00:00 2001 From: psyciknz Date: Thu, 17 Dec 2020 21:42:41 +1300 Subject: [PATCH 01/18] Move main home to folder, add dockerfile --- BlueTooth/mqtt.homie.bluetooth/Dockerfile | 12 +++++ .../mqtt.homie.bluetooth.py | 44 +++++++++---------- 2 files changed, 34 insertions(+), 22 deletions(-) create mode 100644 BlueTooth/mqtt.homie.bluetooth/Dockerfile rename BlueTooth/{ => mqtt.homie.bluetooth}/mqtt.homie.bluetooth.py (81%) diff --git a/BlueTooth/mqtt.homie.bluetooth/Dockerfile b/BlueTooth/mqtt.homie.bluetooth/Dockerfile new file mode 100644 index 0000000..b85ece6 --- /dev/null +++ b/BlueTooth/mqtt.homie.bluetooth/Dockerfile @@ -0,0 +1,12 @@ +FROM python:3 + +WORKDIR /usr/src/app +mkdir bt + +#COPY requirements.txt ./ +RUN pip install --no-cache-dir pybluez homie + +COPY . ./bt +COPY bluemaestroscan.py . + +CMD [ "python", "./bt/your-daemon-or-script.py" ] \ No newline at end of file diff --git a/BlueTooth/mqtt.homie.bluetooth.py b/BlueTooth/mqtt.homie.bluetooth/mqtt.homie.bluetooth.py similarity index 81% rename from BlueTooth/mqtt.homie.bluetooth.py rename to BlueTooth/mqtt.homie.bluetooth/mqtt.homie.bluetooth.py index aec5924..e5e7312 100644 --- a/BlueTooth/mqtt.homie.bluetooth.py +++ b/BlueTooth/mqtt.homie.bluetooth/mqtt.homie.bluetooth.py @@ -9,7 +9,7 @@ # Credit jcs 6/8/2014 as basis -import bluemaestroscan #specific bluemaestro tempo disc scanner +from .. import bluemaestroscan #specific bluemaestro tempo disc scanner import json import sys import argparse @@ -40,13 +40,13 @@ def updatenode(Homie, nodelist,mac,nodevalue,newvalue): def main(configfile='homie-bluetooth.json'): Homie = homie.Homie(configfile) - Homie.setFirmware("bluemaestro-temperature","1.0.0") + Homie.setFirmware("bluemaestro-temperature","1.0.1") Homie.setup() - json_data=open(configfile).read() - data = json.loads(json_data) - FREQUENCY_SECONDS =data["bluetooth"]["frequency"] - LOG = data["bluetooth"]["log"] - logging.basicConfig(filename=LOG, level=logging.INFO,format='%(asctime)s %(levelname)s %(message)s') + json_data=open(configfile).read() + data = json.loads(json_data) + FREQUENCY_SECONDS =data["bluetooth"]["frequency"] + LOG = data["bluetooth"]["log"] + logging.basicConfig(filename=LOG, level=logging.INFO,format='%(asctime)s %(levelname)s %(message)s') try: @@ -54,7 +54,7 @@ def main(configfile='homie-bluetooth.json'): logging.info("ble thread started") except: - print "error accessing bluetooth device..." + print( "error accessing bluetooth device...") logging.info("error accessing bluetooth device...") sys.exit(1) @@ -66,7 +66,7 @@ def main(configfile='homie-bluetooth.json'): try: returnedList = bluemaestroscan.parse_events(sock, 2) nodes = {} - print "-------------------------------------------------------------------------------------------------------" + print("-------------------------------------------------------------------------------------------------------") logging.info("-------------------------------------------------------------------------------------------------------") mac = "" temp = 0 @@ -75,14 +75,14 @@ def main(configfile='homie-bluetooth.json'): logging.info('Date Time: {0}'.format(currentdate)) for beacon in returnedList: val = returnedList[beacon] - print beacon, val + print( beacon, val) mac = returnedList["mac"] temp = returnedList["temp"] - print "number of beacons found {0}".format(len(returnedList)) + print("number of beacons found {0}".format(len(returnedList))) logging.info("number of beacons found {0}".format(len(returnedList))) if len(returnedList) > 0: - print "%s/temperature = %.2f" % (returnedList["mac"],returnedList["temp"]) + print("%s/temperature = %.2f" % (returnedList["mac"],returnedList["temp"])) logging.info("%s/temperature = %.2f" % (returnedList["mac"],returnedList["temp"])) # Publish to the MQTT channel try: @@ -102,14 +102,14 @@ def main(configfile='homie-bluetooth.json'): # Homie.setNodeProperty(temperatureNode,"temperature",float(returnedList["temp"]),True) # nodes[mac+"temperature"] = temperatureNode # print("Added new temperature node for mac" + mac) - print 'Updating temp for {0} to {1}'.format(returnedList["mac"],float(returnedList["temp"])) + print('Updating temp for {0} to {1}'.format(returnedList["mac"],float(returnedList["temp"]))) logging.info('Updating temp for {0} to {1}'.format(returnedList["mac"],float(returnedList["temp"]))) print("CHecking nodes for " + mac+"humidity") updatenode(Homie, nodes,mac,"humidity",float(returnedList["humidity"])) #humidityNode = Homie.Node(mac,"humidity") #Homie.setNodeProperty(humidityNode,"humidity",float(returnedList["humidity"]),True) - print 'Updating humidity {0} = {1}'.format(returnedList["mac"],float(returnedList["humidity"])) + print ( 'Updating humidity {0} = {1}'.format(returnedList["mac"],float(returnedList["humidity"]))) logging.info('Updating humidity {0} = {1}'.format(returnedList["mac"],float(returnedList["humidity"]))) print("CHecking nodes for " + mac+"battery") @@ -117,14 +117,14 @@ def main(configfile='homie-bluetooth.json'): #batteryNode = Homie.Node(mac,"battery") #Homie.setNodeProperty(batteryNode,"battery",float(returnedList["battery"]),True) - print 'Updating battery {0}/battery = {1}'.format(returnedList["mac"],float(returnedList["battery"])) + print ('Updating battery {0}/battery = {1}'.format(returnedList["mac"],float(returnedList["battery"]))) logging.info('Updating battery {0}/battery = {1}'.format(returnedList["mac"],float(returnedList["battery"]))) print("CHecking nodes for " + mac+"dewpoint") updatenode(Homie, nodes,mac,"dewpoint",float(returnedList["dewpoint"])) #dewpointNode = Homie.Node(mac,"dewpoint") #Homie.setNodeProperty(dewpointNode,"dewpoint",float(returnedList["dewpoint"]),True) - print 'Updating {0}/dewpoint = {1}'.format( returnedList["mac"],returnedList["dewpoint"]) + print( 'Updating {0}/dewpoint = {1}'.format( returnedList["mac"],returnedList["dewpoint"])) logging.info('Updating {0}/dewpoint = {1}'.format( returnedList["mac"],returnedList["dewpoint"])) print("CHecking nodes for " + mac+"name") @@ -132,29 +132,29 @@ def main(configfile='homie-bluetooth.json'): #nameNode = Homie.Node(mac,"name") #Homie.setNodeProperty(nameNode,"name",returnedList["name"],True) - print 'Updating name {0}/name = {1}'.format(returnedList["mac"],returnedList["name"]) + print ( 'Updating name {0}/name = {1}'.format(returnedList["mac"],returnedList["name"])) logging.info('Updating name {0}/name = {1}'.format(returnedList["mac"],returnedList["name"])) time.sleep(1) - except Exception,e: + except Exception as e: # Null out the worksheet so a login is performed at the top of the loop. logging.error('Append error, logging in again: ' + str(e)) logging.error("Sleeping for 60 seconds") time.sleep(60) continue else: - print "Sleeping for 30 seconds" + print ("Sleeping for 30 seconds" ) logging.info("Sleeping for 30 seconds" ) time.sleep(30) logging.info("Sleeping for %s seconds" % FREQUENCY_SECONDS) print("Sleeping for %s seconds" % FREQUENCY_SECONDS) time.sleep(FREQUENCY_SECONDS) - except Exception,e: + except Exception as e: # Error appending data, most likely because credentials are stale. # Null out the worksheet so a login is performed at the top of the loop. print('Append error, logging in again: ' + str(e)) - print "Sleeping for 60 seconds" + print ("Sleeping for 60 seconds") time.sleep(60) continue @@ -165,5 +165,5 @@ def main(configfile='homie-bluetooth.json'): args = parser.parse_args() main(args.configfile) except (KeyboardInterrupt, SystemExit): - print "quitting." + print ("quitting.") From f0440b6b8c4c7dd75deede79905ac1e0f4679718 Mon Sep 17 00:00:00 2001 From: psyciknz Date: Thu, 17 Dec 2020 21:51:57 +1300 Subject: [PATCH 02/18] Added config, updated imports --- BlueTooth/mqtt.homie.bluetooth/Dockerfile | 9 +- .../mqtt.homie.bluetooth/bluemaestroscan.py | 203 ++++++++++++++++++ .../mqtt.homie.bluetooth.py | 2 +- 3 files changed, 208 insertions(+), 6 deletions(-) create mode 100644 BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py diff --git a/BlueTooth/mqtt.homie.bluetooth/Dockerfile b/BlueTooth/mqtt.homie.bluetooth/Dockerfile index b85ece6..398dad6 100644 --- a/BlueTooth/mqtt.homie.bluetooth/Dockerfile +++ b/BlueTooth/mqtt.homie.bluetooth/Dockerfile @@ -1,12 +1,11 @@ FROM python:3 WORKDIR /usr/src/app -mkdir bt +RUN mkdir /config #COPY requirements.txt ./ -RUN pip install --no-cache-dir pybluez homie +RUN pip install --no-cache-dir pybluez homie -COPY . ./bt -COPY bluemaestroscan.py . +COPY . . -CMD [ "python", "./bt/your-daemon-or-script.py" ] \ No newline at end of file +CMD [ "python", "./mqtt.homie.bluetooth.py -c /config/config.json" ] \ No newline at end of file diff --git a/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py b/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py new file mode 100644 index 0000000..70343d3 --- /dev/null +++ b/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py @@ -0,0 +1,203 @@ +# BlueMastro Tempo Disc Advertising packet decoder +# Called from bluemaestro.py +# This class has the specificis for decoding the advertising packets for the Blue Maestro Tempo Disc https://www.bluemaestro.com/product/tempo-disc-temperature/ +# Unsure if there are any other Blue Maestro products that it would work with. +# David@andc.nz 15/12/2016 + +DEBUG = True +# BLE Scanner based on from JCS 06/07/14 +# BLE scanner based on https://github.com/adamf/BLE/blob/master/ble-scanner.py +# BLE scanner, based on https://code.google.com/p/pybluez/source/browse/trunk/examples/advanced/inquiry-with-rssi.py + +# https://github.com/pauloborges/bluez/blob/master/tools/hcitool.c for lescan +# https://kernel.googlesource.com/pub/scm/bluetooth/bluez/+/5.6/lib/hci.h for opcodes +# https://github.com/pauloborges/bluez/blob/master/lib/hci.c#L2782 for functions used by lescan + +# performs a simple device inquiry, and returns a list of ble advertizements +# discovered device + +# NOTE: Python's struct.pack() will add padding bytes unless you make the endianness explicit. Little endian +# should be used for BLE. Always start a struct.pack() format string with "<" + +import collections +import os +import sys +import struct +import bluetooth._bluetooth as bluez + +LE_META_EVENT = 0x3e +LE_PUBLIC_ADDRESS=0x00 +LE_RANDOM_ADDRESS=0x01 +LE_SET_SCAN_PARAMETERS_CP_SIZE=7 +OGF_LE_CTL=0x08 +OCF_LE_SET_SCAN_PARAMETERS=0x000B +OCF_LE_SET_SCAN_ENABLE=0x000C +OCF_LE_CREATE_CONN=0x000D + +LE_ROLE_MASTER = 0x00 +LE_ROLE_SLAVE = 0x01 + +# these are actually subevents of LE_META_EVENT +EVT_LE_CONN_COMPLETE=0x01 +EVT_LE_ADVERTISING_REPORT=0x02 +EVT_LE_CONN_UPDATE_COMPLETE=0x03 +EVT_LE_READ_REMOTE_USED_FEATURES_COMPLETE=0x04 + +# Advertisment event types +ADV_IND=0x00 +ADV_DIRECT_IND=0x01 +ADV_SCAN_IND=0x02 +ADV_NONCONN_IND=0x03 +ADV_SCAN_RSP=0x04 + + +def returnnumberpacket(pkt): + myInteger = 0 + multiple = 256 + for c in pkt: + myInteger += struct.unpack("B",c)[0] * multiple + multiple = 1 + return myInteger + +def returnstringpacket(pkt): + myString = ""; + for c in pkt: + myString += "%02x" %struct.unpack("B",c)[0] + return myString + +def printpacket(pkt): + for c in pkt: + sys.stdout.write("%02x " % struct.unpack("B",c)[0]) + +def get_packed_bdaddr(bdaddr_string): + packable_addr = [] + addr = bdaddr_string.split(':') + addr.reverse() + for b in addr: + packable_addr.append(int(b, 16)) + return struct.pack(" Date: Thu, 17 Dec 2020 22:03:16 +1300 Subject: [PATCH 03/18] added example config --- .gitignore | 1 + BlueTooth/mqtt.homie.bluetooth/Dockerfile | 2 +- BlueTooth/mqtt.homie.bluetooth/config.json.example | 14 ++++++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 BlueTooth/mqtt.homie.bluetooth/config.json.example diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bf52449 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +BlueTooth/config.json diff --git a/BlueTooth/mqtt.homie.bluetooth/Dockerfile b/BlueTooth/mqtt.homie.bluetooth/Dockerfile index 398dad6..6d33dae 100644 --- a/BlueTooth/mqtt.homie.bluetooth/Dockerfile +++ b/BlueTooth/mqtt.homie.bluetooth/Dockerfile @@ -8,4 +8,4 @@ RUN pip install --no-cache-dir pybluez homie COPY . . -CMD [ "python", "./mqtt.homie.bluetooth.py -c /config/config.json" ] \ No newline at end of file +CMD [ "python", "mqtt.homie.bluetooth.py -c /config/config.json" ] \ No newline at end of file diff --git a/BlueTooth/mqtt.homie.bluetooth/config.json.example b/BlueTooth/mqtt.homie.bluetooth/config.json.example new file mode 100644 index 0000000..43ce9a9 --- /dev/null +++ b/BlueTooth/mqtt.homie.bluetooth/config.json.example @@ -0,0 +1,14 @@ +{ + "name":"Bluemaestro", + "device_id":"blue-maestro", + "mqtt": + { + "host":"localhost", + "port":1883, + "base_topic":"bluemaestro" + }, + "bluetooth": + { + "frequency": 500, + } "log": "stdout" +} \ No newline at end of file From a3d7efa3d1f1dace9440dbe6986198102ac58ef8 Mon Sep 17 00:00:00 2001 From: psyciknz Date: Thu, 17 Dec 2020 22:05:25 +1300 Subject: [PATCH 04/18] Debug build --- BlueTooth/mqtt.homie.bluetooth/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BlueTooth/mqtt.homie.bluetooth/Dockerfile b/BlueTooth/mqtt.homie.bluetooth/Dockerfile index 6d33dae..6606d1a 100644 --- a/BlueTooth/mqtt.homie.bluetooth/Dockerfile +++ b/BlueTooth/mqtt.homie.bluetooth/Dockerfile @@ -7,5 +7,5 @@ RUN mkdir /config RUN pip install --no-cache-dir pybluez homie COPY . . - +RUN ls -la CMD [ "python", "mqtt.homie.bluetooth.py -c /config/config.json" ] \ No newline at end of file From b1b0ab9eca70509df749bdb016a9e166598f31ed Mon Sep 17 00:00:00 2001 From: psyciknz Date: Thu, 17 Dec 2020 22:07:09 +1300 Subject: [PATCH 05/18] changed workdir --- BlueTooth/mqtt.homie.bluetooth/Dockerfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BlueTooth/mqtt.homie.bluetooth/Dockerfile b/BlueTooth/mqtt.homie.bluetooth/Dockerfile index 6606d1a..af7734f 100644 --- a/BlueTooth/mqtt.homie.bluetooth/Dockerfile +++ b/BlueTooth/mqtt.homie.bluetooth/Dockerfile @@ -1,6 +1,6 @@ FROM python:3 -WORKDIR /usr/src/app +WORKDIR /app RUN mkdir /config #COPY requirements.txt ./ @@ -8,4 +8,4 @@ RUN pip install --no-cache-dir pybluez homie COPY . . RUN ls -la -CMD [ "python", "mqtt.homie.bluetooth.py -c /config/config.json" ] \ No newline at end of file +CMD [ "python", "/app/mqtt.homie.bluetooth.py -c /config/config.json" ] \ No newline at end of file From 887838c21460bb8f5a68e919225e5b31f4380ebd Mon Sep 17 00:00:00 2001 From: psyciknz Date: Thu, 17 Dec 2020 22:11:12 +1300 Subject: [PATCH 06/18] Fixes --- BlueTooth/mqtt.homie.bluetooth/Dockerfile | 2 +- .../mqtt.homie.bluetooth.py | 32 +++++++++---------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/BlueTooth/mqtt.homie.bluetooth/Dockerfile b/BlueTooth/mqtt.homie.bluetooth/Dockerfile index af7734f..9c4a7a2 100644 --- a/BlueTooth/mqtt.homie.bluetooth/Dockerfile +++ b/BlueTooth/mqtt.homie.bluetooth/Dockerfile @@ -8,4 +8,4 @@ RUN pip install --no-cache-dir pybluez homie COPY . . RUN ls -la -CMD [ "python", "/app/mqtt.homie.bluetooth.py -c /config/config.json" ] \ No newline at end of file +CMD [ "python", "mqtt.homie.bluetooth.py", "-c","/config/config.json" ] \ No newline at end of file diff --git a/BlueTooth/mqtt.homie.bluetooth/mqtt.homie.bluetooth.py b/BlueTooth/mqtt.homie.bluetooth/mqtt.homie.bluetooth.py index bb9c77d..d1aeed1 100644 --- a/BlueTooth/mqtt.homie.bluetooth/mqtt.homie.bluetooth.py +++ b/BlueTooth/mqtt.homie.bluetooth/mqtt.homie.bluetooth.py @@ -56,7 +56,7 @@ def main(configfile='homie-bluetooth.json'): except: print( "error accessing bluetooth device...") logging.info("error accessing bluetooth device...") - sys.exit(1) + sys.exit(1) bluemaestroscan.hci_le_set_scan_parameters(sock) bluemaestroscan.hci_enable_le_scan(sock) @@ -65,7 +65,7 @@ def main(configfile='homie-bluetooth.json'): while True: try: returnedList = bluemaestroscan.parse_events(sock, 2) - nodes = {} + nodes = {} print("-------------------------------------------------------------------------------------------------------") logging.info("-------------------------------------------------------------------------------------------------------") mac = "" @@ -102,15 +102,15 @@ def main(configfile='homie-bluetooth.json'): # Homie.setNodeProperty(temperatureNode,"temperature",float(returnedList["temp"]),True) # nodes[mac+"temperature"] = temperatureNode # print("Added new temperature node for mac" + mac) - print('Updating temp for {0} to {1}'.format(returnedList["mac"],float(returnedList["temp"]))) - logging.info('Updating temp for {0} to {1}'.format(returnedList["mac"],float(returnedList["temp"]))) + print('Updating temp for {0} to {1}'.format(returnedList["mac"],float(returnedList["temp"]))) + logging.info('Updating temp for {0} to {1}'.format(returnedList["mac"],float(returnedList["temp"]))) print("CHecking nodes for " + mac+"humidity") updatenode(Homie, nodes,mac,"humidity",float(returnedList["humidity"])) #humidityNode = Homie.Node(mac,"humidity") #Homie.setNodeProperty(humidityNode,"humidity",float(returnedList["humidity"]),True) - print ( 'Updating humidity {0} = {1}'.format(returnedList["mac"],float(returnedList["humidity"]))) - logging.info('Updating humidity {0} = {1}'.format(returnedList["mac"],float(returnedList["humidity"]))) + print ( 'Updating humidity {0} = {1}'.format(returnedList["mac"],float(returnedList["humidity"]))) + logging.info('Updating humidity {0} = {1}'.format(returnedList["mac"],float(returnedList["humidity"]))) print("CHecking nodes for " + mac+"battery") updatenode(Homie, nodes,mac,"battery",float(returnedList["battery"])) @@ -146,12 +146,12 @@ def main(configfile='homie-bluetooth.json'): print ("Sleeping for 30 seconds" ) logging.info("Sleeping for 30 seconds" ) time.sleep(30) - logging.info("Sleeping for %s seconds" % FREQUENCY_SECONDS) - print("Sleeping for %s seconds" % FREQUENCY_SECONDS) + logging.info("Sleeping for %s seconds" % FREQUENCY_SECONDS) + print("Sleeping for %s seconds" % FREQUENCY_SECONDS) time.sleep(FREQUENCY_SECONDS) except Exception as e: - # Error appending data, most likely because credentials are stale. + # Error appending data, most likely because credentials are stale. # Null out the worksheet so a login is performed at the top of the loop. print('Append error, logging in again: ' + str(e)) print ("Sleeping for 60 seconds") @@ -159,11 +159,11 @@ def main(configfile='homie-bluetooth.json'): continue if __name__ == '__main__': - try: - parser= argparse.ArgumentParser(description="Homie Based Bluetooth Reader") - parser.add_argument('-c','--configfile', help='Configuration filename (json)',required=True) - args = parser.parse_args() - main(args.configfile) - except (KeyboardInterrupt, SystemExit): - print ("quitting.") + try: + parser= argparse.ArgumentParser(description="Homie Based Bluetooth Reader") + parser.add_argument('-c','--configfile', help='Configuration filename (json)',required=True) + args = parser.parse_args() + main(args.configfile) + except (KeyboardInterrupt, SystemExit): + print ("quitting.") From fad7f14ddeeedb7b3feb82fc4455c9a606340694 Mon Sep 17 00:00:00 2001 From: psyciknz Date: Thu, 17 Dec 2020 22:13:47 +1300 Subject: [PATCH 07/18] Formatting --- .../mqtt.homie.bluetooth.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/BlueTooth/mqtt.homie.bluetooth/mqtt.homie.bluetooth.py b/BlueTooth/mqtt.homie.bluetooth/mqtt.homie.bluetooth.py index d1aeed1..004621f 100644 --- a/BlueTooth/mqtt.homie.bluetooth/mqtt.homie.bluetooth.py +++ b/BlueTooth/mqtt.homie.bluetooth/mqtt.homie.bluetooth.py @@ -44,7 +44,7 @@ def main(configfile='homie-bluetooth.json'): Homie.setup() json_data=open(configfile).read() data = json.loads(json_data) - FREQUENCY_SECONDS =data["bluetooth"]["frequency"] + FREQUENCY_SECONDS =data["bluetooth"]["frequency"] LOG = data["bluetooth"]["log"] logging.basicConfig(filename=LOG, level=logging.INFO,format='%(asctime)s %(levelname)s %(message)s') @@ -56,7 +56,7 @@ def main(configfile='homie-bluetooth.json'): except: print( "error accessing bluetooth device...") logging.info("error accessing bluetooth device...") - sys.exit(1) + sys.exit(1) bluemaestroscan.hci_le_set_scan_parameters(sock) bluemaestroscan.hci_enable_le_scan(sock) @@ -65,7 +65,7 @@ def main(configfile='homie-bluetooth.json'): while True: try: returnedList = bluemaestroscan.parse_events(sock, 2) - nodes = {} + nodes = {} print("-------------------------------------------------------------------------------------------------------") logging.info("-------------------------------------------------------------------------------------------------------") mac = "" @@ -102,15 +102,15 @@ def main(configfile='homie-bluetooth.json'): # Homie.setNodeProperty(temperatureNode,"temperature",float(returnedList["temp"]),True) # nodes[mac+"temperature"] = temperatureNode # print("Added new temperature node for mac" + mac) - print('Updating temp for {0} to {1}'.format(returnedList["mac"],float(returnedList["temp"]))) - logging.info('Updating temp for {0} to {1}'.format(returnedList["mac"],float(returnedList["temp"]))) + print('Updating temp for {0} to {1}'.format(returnedList["mac"],float(returnedList["temp"]))) + logging.info('Updating temp for {0} to {1}'.format(returnedList["mac"],float(returnedList["temp"]))) print("CHecking nodes for " + mac+"humidity") updatenode(Homie, nodes,mac,"humidity",float(returnedList["humidity"])) #humidityNode = Homie.Node(mac,"humidity") #Homie.setNodeProperty(humidityNode,"humidity",float(returnedList["humidity"]),True) - print ( 'Updating humidity {0} = {1}'.format(returnedList["mac"],float(returnedList["humidity"]))) - logging.info('Updating humidity {0} = {1}'.format(returnedList["mac"],float(returnedList["humidity"]))) + print ( 'Updating humidity {0} = {1}'.format(returnedList["mac"],float(returnedList["humidity"]))) + logging.info('Updating humidity {0} = {1}'.format(returnedList["mac"],float(returnedList["humidity"]))) print("CHecking nodes for " + mac+"battery") updatenode(Homie, nodes,mac,"battery",float(returnedList["battery"])) @@ -146,8 +146,8 @@ def main(configfile='homie-bluetooth.json'): print ("Sleeping for 30 seconds" ) logging.info("Sleeping for 30 seconds" ) time.sleep(30) - logging.info("Sleeping for %s seconds" % FREQUENCY_SECONDS) - print("Sleeping for %s seconds" % FREQUENCY_SECONDS) + logging.info("Sleeping for %s seconds" % FREQUENCY_SECONDS) + print("Sleeping for %s seconds" % FREQUENCY_SECONDS) time.sleep(FREQUENCY_SECONDS) except Exception as e: From 7a48a9ce4679574225fe03f64f550b5850157e6c Mon Sep 17 00:00:00 2001 From: psyciknz Date: Thu, 17 Dec 2020 22:22:39 +1300 Subject: [PATCH 08/18] Update bluemaestro to python 3 --- .../mqtt.homie.bluetooth/bluemaestroscan.py | 43 +++++++++++-------- .../mqtt.homie.bluetooth.py | 6 ++- 2 files changed, 29 insertions(+), 20 deletions(-) diff --git a/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py b/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py index 70343d3..ac06db7 100644 --- a/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py +++ b/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py @@ -152,52 +152,59 @@ def parse_events(sock, loop_count=100): report_pkt_offset = 0 for i in range(0, num_reports): company = returnstringpacket(pkt[report_pkt_offset + 15: report_pkt_offset + 17]) - print "===============================================================================================================" + print("===============================================================================================================") if (DEBUG == True): - print "\tfullpacket: ", printpacket(pkt) + print("\tfullpacket: ", printpacket(pkt)) if (company == "3301"): - print "\tCompany: ",company + print("\tCompany: ",company) udid = returnstringpacket(pkt[report_pkt_offset + 22: report_pkt_offset - 6]) - print "\tUDID: ", udid + print("\tUDID: ", udid) myFullList["udid"] = udid - print "\tMAJOR: ", printpacket(pkt[report_pkt_offset -6: report_pkt_offset - 4]) - print "\tMINOR: ", printpacket(pkt[report_pkt_offset -4: report_pkt_offset - 2]) - print "\tMAC address: ", packed_bdaddr_to_string(pkt[report_pkt_offset + 3:report_pkt_offset + 9]) + print("\tMAJOR: ", printpacket(pkt[report_pkt_offset -6: report_pkt_offset - 4])) + print( "\tMINOR: ", printpacket(pkt[report_pkt_offset -4: report_pkt_offset - 2])) + print( "\tMAC address: ", packed_bdaddr_to_string(pkt[report_pkt_offset + 3:report_pkt_offset + 9])) mac = returnstringpacket(pkt[report_pkt_offset + 3: report_pkt_offset + 9]) myFullList["mac"] = mac - print "\tMAC Address string: ", returnstringpacket(pkt[report_pkt_offset + 3:report_pkt_offset + 9]) + print ("\tMAC Address string: ", returnstringpacket(pkt[report_pkt_offset + 3:report_pkt_offset + 9])) tempString = returnstringpacket(pkt[report_pkt_offset + 23: report_pkt_offset + 25]) - print "\tTemp: " , tempString + print ("\tTemp: " , tempString ) temp = float(returnnumberpacket(pkt[report_pkt_offset + 23:report_pkt_offset + 25]))/10 - print "\tTemp: " , temp + print ("\tTemp: " , temp) myFullList["temp"] = temp - print "\tHumidity: " ,printpacket(pkt[report_pkt_offset + 25:report_pkt_offset + 27]) + print ("\tHumidity: " ,printpacket(pkt[report_pkt_offset + 25:report_pkt_offset + 27])) humidity = float(returnnumberpacket(pkt[report_pkt_offset + 25:report_pkt_offset + 27]))/10 - print "\tHumidity: " ,humidity + print ("\tHumidity: " ,humidity ) myFullList["humidity"] = humidity dewpoint = float(returnnumberpacket(pkt[report_pkt_offset + 27:report_pkt_offset + 29]))/10 - print "\tDewpoint: " ,dewpoint + print ("\tDewpoint: " ,dewpoint ) myFullList["dewpoint"] = dewpoint nameLength = int(returnstringpacket(pkt[report_pkt_offset + 32])) - print "\tNameLength: ",nameLength + print ("\tNameLength: ",nameLength) name = returnstringpacket(pkt[report_pkt_offset + 33:report_pkt_offset + (33+nameLength-1)]) - print "\tName: %s %d " % (name.decode("hex"),nameLength) + print ("\tName: %s %d " % (name.decode("hex"),nameLength)) myFullList["name"] = name.decode("hex") - print "\tBattery: " ,printpacket(pkt[report_pkt_offset + 18:report_pkt_offset + 19]) + print ("\tBattery: " ,printpacket(pkt[report_pkt_offset + 18:report_pkt_offset + 19])) battery = float(float(returnnumberpacket(pkt[report_pkt_offset + 18]) / float(25500) ) * 100) - print "\tBattery: " ,battery + print ("\tBattery: " ,battery) myFullList["battery"] = battery done = True else: - print "\tNon blue maestro packet found" + print ("\tNon blue maestro packet found") sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter ) return myFullList +def le_handle_connection_complete(pkt): + status, handle, role, peer_bdaddr_type = struct.unpack(" 0: else: print ("Sleeping for 30 seconds" ) logging.info("Sleeping for 30 seconds" ) time.sleep(30) logging.info("Sleeping for %s seconds" % FREQUENCY_SECONDS) print("Sleeping for %s seconds" % FREQUENCY_SECONDS) + #for beacon in returnedList: time.sleep(FREQUENCY_SECONDS) - + #try except Exception as e: # Error appending data, most likely because credentials are stale. # Null out the worksheet so a login is performed at the top of the loop. @@ -157,7 +159,7 @@ def main(configfile='homie-bluetooth.json'): print ("Sleeping for 60 seconds") time.sleep(60) continue - + #while True: if __name__ == '__main__': try: parser= argparse.ArgumentParser(description="Homie Based Bluetooth Reader") From 112d0d11b50defda8a2b84f2b1b7418f94fb2cf8 Mon Sep 17 00:00:00 2001 From: psyciknz Date: Thu, 17 Dec 2020 22:25:51 +1300 Subject: [PATCH 09/18] Formatting --- .../mqtt.homie.bluetooth/bluemaestroscan.py | 232 +++++++++--------- 1 file changed, 116 insertions(+), 116 deletions(-) diff --git a/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py b/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py index ac06db7..684183b 100644 --- a/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py +++ b/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py @@ -52,39 +52,39 @@ def returnnumberpacket(pkt): - myInteger = 0 - multiple = 256 - for c in pkt: - myInteger += struct.unpack("B",c)[0] * multiple - multiple = 1 - return myInteger + myInteger = 0 + multiple = 256 + for c in pkt: + myInteger += struct.unpack("B",c)[0] * multiple + multiple = 1 + return myInteger def returnstringpacket(pkt): - myString = ""; - for c in pkt: - myString += "%02x" %struct.unpack("B",c)[0] - return myString + myString = ""; + for c in pkt: + myString += "%02x" %struct.unpack("B",c)[0] + return myString def printpacket(pkt): - for c in pkt: - sys.stdout.write("%02x " % struct.unpack("B",c)[0]) + for c in pkt: + sys.stdout.write("%02x " % struct.unpack("B",c)[0]) def get_packed_bdaddr(bdaddr_string): - packable_addr = [] - addr = bdaddr_string.split(':') - addr.reverse() - for b in addr: - packable_addr.append(int(b, 16)) - return struct.pack(" Date: Thu, 17 Dec 2020 22:29:12 +1300 Subject: [PATCH 10/18] formatting --- BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py b/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py index 684183b..a5149c1 100644 --- a/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py +++ b/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py @@ -153,8 +153,7 @@ def parse_events(sock, loop_count=100): for i in range(0, num_reports): company = returnstringpacket(pkt[report_pkt_offset + 15: report_pkt_offset + 17]) print("===============================================================================================================") - if (DEBUG == True): - print("\tfullpacket: ", printpacket(pkt)) + print("\tfullpacket: ", printpacket(pkt)) if (company == "3301"): print("\tCompany: ",company) From 2090d90d129f7fc3ef325ff2f4c84224e8b2723b Mon Sep 17 00:00:00 2001 From: psyciknz Date: Thu, 17 Dec 2020 22:36:48 +1300 Subject: [PATCH 11/18] Formatting --- BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py b/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py index a5149c1..652aaf3 100644 --- a/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py +++ b/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py @@ -154,7 +154,7 @@ def parse_events(sock, loop_count=100): company = returnstringpacket(pkt[report_pkt_offset + 15: report_pkt_offset + 17]) print("===============================================================================================================") print("\tfullpacket: ", printpacket(pkt)) - + if (company == "3301"): print("\tCompany: ",company) udid = returnstringpacket(pkt[report_pkt_offset + 22: report_pkt_offset - 6]) From 9697f96902752ae4e51e17936259a72957a236f8 Mon Sep 17 00:00:00 2001 From: psyciknz Date: Thu, 17 Dec 2020 22:41:34 +1300 Subject: [PATCH 12/18] formtting indents --- BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py b/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py index 652aaf3..066483e 100644 --- a/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py +++ b/BlueTooth/mqtt.homie.bluetooth/bluemaestroscan.py @@ -151,10 +151,9 @@ def parse_events(sock, loop_count=100): num_reports = struct.unpack("B", pkt[0])[0] report_pkt_offset = 0 for i in range(0, num_reports): - company = returnstringpacket(pkt[report_pkt_offset + 15: report_pkt_offset + 17]) - print("===============================================================================================================") + company = returnstringpacket(pkt[report_pkt_offset + 15: report_pkt_offset + 17]) + print("===============================================================================================================") print("\tfullpacket: ", printpacket(pkt)) - if (company == "3301"): print("\tCompany: ",company) udid = returnstringpacket(pkt[report_pkt_offset + 22: report_pkt_offset - 6]) From 3159c177f674c8268a2acc9249193df1e394fc7f Mon Sep 17 00:00:00 2001 From: psyciknz Date: Thu, 17 Dec 2020 22:56:42 +1300 Subject: [PATCH 13/18] Added non homie docker file --- BlueTooth/bluemaestroscan.py | 227 ++++++++++--------- BlueTooth/mqtt.bluetooth.py | 106 --------- BlueTooth/mqtt.bluetooth/Dockerfile | 11 + BlueTooth/mqtt.bluetooth/bluemaestroscan.py | 208 +++++++++++++++++ BlueTooth/mqtt.bluetooth/config.json.example | 21 ++ BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py | 156 +++++++++++++ 6 files changed, 512 insertions(+), 217 deletions(-) delete mode 100644 BlueTooth/mqtt.bluetooth.py create mode 100644 BlueTooth/mqtt.bluetooth/Dockerfile create mode 100644 BlueTooth/mqtt.bluetooth/bluemaestroscan.py create mode 100644 BlueTooth/mqtt.bluetooth/config.json.example create mode 100644 BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py diff --git a/BlueTooth/bluemaestroscan.py b/BlueTooth/bluemaestroscan.py index 70343d3..066483e 100644 --- a/BlueTooth/bluemaestroscan.py +++ b/BlueTooth/bluemaestroscan.py @@ -52,39 +52,39 @@ def returnnumberpacket(pkt): - myInteger = 0 - multiple = 256 - for c in pkt: - myInteger += struct.unpack("B",c)[0] * multiple - multiple = 1 - return myInteger + myInteger = 0 + multiple = 256 + for c in pkt: + myInteger += struct.unpack("B",c)[0] * multiple + multiple = 1 + return myInteger def returnstringpacket(pkt): - myString = ""; - for c in pkt: - myString += "%02x" %struct.unpack("B",c)[0] - return myString + myString = ""; + for c in pkt: + myString += "%02x" %struct.unpack("B",c)[0] + return myString def printpacket(pkt): - for c in pkt: - sys.stdout.write("%02x " % struct.unpack("B",c)[0]) + for c in pkt: + sys.stdout.write("%02x " % struct.unpack("B",c)[0]) def get_packed_bdaddr(bdaddr_string): - packable_addr = [] - addr = bdaddr_string.split(':') - addr.reverse() - for b in addr: - packable_addr.append(int(b, 16)) - return struct.pack(" 0: - print "%s/temperature = %.2f" % (returnedList["mac"],returnedList["temp"]) - # Publish to the MQTT channel - try: - mqttc.connect(MOSQUITTO_HOST,MOSQUITTO_PORT); - print 'Updating temp for {0} to {1}'.format(returnedList["mac"],float(returnedList["temp"])) - (result1,mid) = mqttc.publish("%s/temperature" % returnedList["mac"],float(returnedList["temp"])) - time.sleep(1) - - mqttc.connect(MOSQUITTO_HOST,MOSQUITTO_PORT); - (result2,mid) = mqttc.publish("%s/humidity" % returnedList["mac"],float(returnedList["humidity"])) - print 'Updating humidity {0} = {1}'.format(returnedList["mac"],float(returnedList["humidity"])) - time.sleep(1) - - mqttc.connect(MOSQUITTO_HOST,MOSQUITTO_PORT); - (result3,mid) = mqttc.publish("%s/dewpoint" % returnedList["mac"],float(returnedList["dewpoint"])) - print 'Updating {0}/dewpoint = {1}'.format( returnedList["mac"],returnedList["dewpoint"]) - time.sleep(1) - - mqttc.connect(MOSQUITTO_HOST,MOSQUITTO_PORT); - (result4,mid) = mqttc.publish("%s/name" % returnedList["mac"],returnedList["name"]) - print 'Updating name {0}/name = {1}'.format(returnedList["mac"],returnedList["name"]) - time.sleep(1) - - mqttc.connect(MOSQUITTO_HOST,MOSQUITTO_PORT); - (result5,mid) = mqttc.publish("%s/battery" % returnedList["mac"],float(returnedList["battery"])) - print 'Updating battery {0}/battery = {1}'.format(returnedList["mac"],float(returnedList["battery"])) - print 'Updated Battery' - #print 'MQTT Updated result {0} and {1} and {2} and {3} and {4} and {5}'.format(result1,result2,result3,result4,result5) - - if result1 == 1 or result2 == 1 or result3 == 1 or result4 == 1 or result5 ==1: - raise ValueError('Result for one message was not 0') -# mqttc.disconnect() - print "Sleeping for %d seconds" % FREQUENCY_SECONDS - time.sleep(FREQUENCY_SECONDS) - mqttc.loop(1) - - - except Exception,e: - # Null out the worksheet so a login is performed at the top of the loop. - mqttc.disconnect() - print('Append error, logging in again: ' + str(e)) - print "Sleeping for 60 seconds" - time.sleep(60) - continue - else: - print "Sleeping for 30 seconds" - time.sleep(30) - except Exception,e: - # Error appending data, most likely because credentials are stale. - # Null out the worksheet so a login is performed at the top of the loop. - print('Append error, logging in again: ' + str(e)) - print "Sleeping for 60 seconds" - time.sleep(60) - continue - diff --git a/BlueTooth/mqtt.bluetooth/Dockerfile b/BlueTooth/mqtt.bluetooth/Dockerfile new file mode 100644 index 0000000..9c4a7a2 --- /dev/null +++ b/BlueTooth/mqtt.bluetooth/Dockerfile @@ -0,0 +1,11 @@ +FROM python:3 + +WORKDIR /app +RUN mkdir /config + +#COPY requirements.txt ./ +RUN pip install --no-cache-dir pybluez homie + +COPY . . +RUN ls -la +CMD [ "python", "mqtt.homie.bluetooth.py", "-c","/config/config.json" ] \ No newline at end of file diff --git a/BlueTooth/mqtt.bluetooth/bluemaestroscan.py b/BlueTooth/mqtt.bluetooth/bluemaestroscan.py new file mode 100644 index 0000000..066483e --- /dev/null +++ b/BlueTooth/mqtt.bluetooth/bluemaestroscan.py @@ -0,0 +1,208 @@ +# BlueMastro Tempo Disc Advertising packet decoder +# Called from bluemaestro.py +# This class has the specificis for decoding the advertising packets for the Blue Maestro Tempo Disc https://www.bluemaestro.com/product/tempo-disc-temperature/ +# Unsure if there are any other Blue Maestro products that it would work with. +# David@andc.nz 15/12/2016 + +DEBUG = True +# BLE Scanner based on from JCS 06/07/14 +# BLE scanner based on https://github.com/adamf/BLE/blob/master/ble-scanner.py +# BLE scanner, based on https://code.google.com/p/pybluez/source/browse/trunk/examples/advanced/inquiry-with-rssi.py + +# https://github.com/pauloborges/bluez/blob/master/tools/hcitool.c for lescan +# https://kernel.googlesource.com/pub/scm/bluetooth/bluez/+/5.6/lib/hci.h for opcodes +# https://github.com/pauloborges/bluez/blob/master/lib/hci.c#L2782 for functions used by lescan + +# performs a simple device inquiry, and returns a list of ble advertizements +# discovered device + +# NOTE: Python's struct.pack() will add padding bytes unless you make the endianness explicit. Little endian +# should be used for BLE. Always start a struct.pack() format string with "<" + +import collections +import os +import sys +import struct +import bluetooth._bluetooth as bluez + +LE_META_EVENT = 0x3e +LE_PUBLIC_ADDRESS=0x00 +LE_RANDOM_ADDRESS=0x01 +LE_SET_SCAN_PARAMETERS_CP_SIZE=7 +OGF_LE_CTL=0x08 +OCF_LE_SET_SCAN_PARAMETERS=0x000B +OCF_LE_SET_SCAN_ENABLE=0x000C +OCF_LE_CREATE_CONN=0x000D + +LE_ROLE_MASTER = 0x00 +LE_ROLE_SLAVE = 0x01 + +# these are actually subevents of LE_META_EVENT +EVT_LE_CONN_COMPLETE=0x01 +EVT_LE_ADVERTISING_REPORT=0x02 +EVT_LE_CONN_UPDATE_COMPLETE=0x03 +EVT_LE_READ_REMOTE_USED_FEATURES_COMPLETE=0x04 + +# Advertisment event types +ADV_IND=0x00 +ADV_DIRECT_IND=0x01 +ADV_SCAN_IND=0x02 +ADV_NONCONN_IND=0x03 +ADV_SCAN_RSP=0x04 + + +def returnnumberpacket(pkt): + myInteger = 0 + multiple = 256 + for c in pkt: + myInteger += struct.unpack("B",c)[0] * multiple + multiple = 1 + return myInteger + +def returnstringpacket(pkt): + myString = ""; + for c in pkt: + myString += "%02x" %struct.unpack("B",c)[0] + return myString + +def printpacket(pkt): + for c in pkt: + sys.stdout.write("%02x " % struct.unpack("B",c)[0]) + +def get_packed_bdaddr(bdaddr_string): + packable_addr = [] + addr = bdaddr_string.split(':') + addr.reverse() + for b in addr: + packable_addr.append(int(b, 16)) + return struct.pack(" 0: + time.sleep( FREQUENCY_SECONDS ) + else: + time.sleep( 1 ) + + except Exception as e: + # Error appending data, most likely because credentials are stale. + # Null out the worksheet so a login is performed at the top of the loop. + print('Append error, logging in again: ' + str(e)) + print ("Sleeping for 60 seconds") + time.sleep(60) + continue + +if __name__ == '__main__': + try: + parser= argparse.ArgumentParser( description="MQTT Based Bluetooth Reader" ) + parser.add_argument( '-c','--configfile', help='Configuration filename (json)',required=True ) + args = parser.parse_args() + main(args.configfile) + except (KeyboardInterrupt, SystemExit): + mqttc.loop_stop() + mqttc.disconnect() + print ("Top-level exception - terminating.") \ No newline at end of file From e010707d7423ea9977d9dd787b282fed28b35442 Mon Sep 17 00:00:00 2001 From: psyciknz Date: Thu, 17 Dec 2020 22:57:35 +1300 Subject: [PATCH 14/18] Fixed dockerfile --- BlueTooth/mqtt.bluetooth/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BlueTooth/mqtt.bluetooth/Dockerfile b/BlueTooth/mqtt.bluetooth/Dockerfile index 9c4a7a2..6c383c3 100644 --- a/BlueTooth/mqtt.bluetooth/Dockerfile +++ b/BlueTooth/mqtt.bluetooth/Dockerfile @@ -8,4 +8,4 @@ RUN pip install --no-cache-dir pybluez homie COPY . . RUN ls -la -CMD [ "python", "mqtt.homie.bluetooth.py", "-c","/config/config.json" ] \ No newline at end of file +CMD [ "python", "mqtt.bluetooth.py", "-c","/config/config.json" ] \ No newline at end of file From fa80d8b0bd0d5970f6d68abedc50d010c3e02b61 Mon Sep 17 00:00:00 2001 From: psyciknz Date: Thu, 17 Dec 2020 22:59:59 +1300 Subject: [PATCH 15/18] formatting --- BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py | 28 +++++++++++----------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py b/BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py index c2ca164..a5e3f47 100644 --- a/BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py +++ b/BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py @@ -39,19 +39,19 @@ # Define event callbacks def on_connect(client, userdata, flags, rc): - print("rc: " + str(rc)) + print("rc: " + str(rc)) def on_message(client, obj, msg): - print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload)) + print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload)) def on_publish(client, obj, mid): - print("mid: " + str(mid)) + print("mid: " + str(mid)) def on_subscribe(client, obj, mid, granted_qos): - print("Subscribed: " + str(mid) + " " + str(granted_qos)) + print("Subscribed: " + str(mid) + " " + str(granted_qos)) def on_log(client, obj, level, string): - print(string) + print(string) # Initialize MQTT client and assign callbacks (global scope so we can disconnect from outer exception handler) mqttc = mqtt.Client() # Default parameters. Auto-generate client name @@ -96,7 +96,7 @@ def main( configfile='homie-bluetooth.json' ): except: print ("error accessing bluetooth device...") logging.error("error accessing bluetooth device...") - sys.exit(1) + sys.exit(1) bluemaestroscan.hci_le_set_scan_parameters(sock) bluemaestroscan.hci_enable_le_scan(sock) @@ -123,7 +123,7 @@ def main( configfile='homie-bluetooth.json' ): mqttc.publish( config["topics"]["battery"], battery ) mqttc.publish( config["topics"]["timestamp"], currentdatetime ) - except Exception,e: + except Exception as e: # Null out the worksheet so a login is performed at the top of the loop. logging.error('Append error, logging in again: ' + str(e)) logging.error("Sleeping for 60 seconds") @@ -137,7 +137,7 @@ def main( configfile='homie-bluetooth.json' ): time.sleep( 1 ) except Exception as e: - # Error appending data, most likely because credentials are stale. + # Error appending data, most likely because credentials are stale. # Null out the worksheet so a login is performed at the top of the loop. print('Append error, logging in again: ' + str(e)) print ("Sleeping for 60 seconds") @@ -145,12 +145,12 @@ def main( configfile='homie-bluetooth.json' ): continue if __name__ == '__main__': - try: - parser= argparse.ArgumentParser( description="MQTT Based Bluetooth Reader" ) - parser.add_argument( '-c','--configfile', help='Configuration filename (json)',required=True ) - args = parser.parse_args() - main(args.configfile) - except (KeyboardInterrupt, SystemExit): + try: + parser= argparse.ArgumentParser( description="MQTT Based Bluetooth Reader" ) + parser.add_argument( '-c','--configfile', help='Configuration filename (json)',required=True ) + args = parser.parse_args() + main(args.configfile) + except (KeyboardInterrupt, SystemExit): mqttc.loop_stop() mqttc.disconnect() print ("Top-level exception - terminating.") \ No newline at end of file From 68bb7698a08ea8356458678757e5b5ae5dba9607 Mon Sep 17 00:00:00 2001 From: psyciknz Date: Thu, 17 Dec 2020 23:04:42 +1300 Subject: [PATCH 16/18] fixed config reading --- BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py | 23 +++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py b/BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py index a5e3f47..5aa0b32 100644 --- a/BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py +++ b/BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py @@ -72,9 +72,22 @@ def main( configfile='homie-bluetooth.json' ): MOSQUITTO_HOST = config["MQTT"]["HOST"] MOSQUITTO_PORT = config["MQTT"]["PORT"] - MOSQUITTO_KEEPALIVE = config["MQTT"]["KEEPALIVE"] - MOSQUITTO_USER = config["MQTT"]["USERNAME"] - MOSQUITTO_PWD = config["MQTT"]["PASSWORD"] + try: + MOSQUITTO_KEEPALIVE = config["MQTT"]["KEEPALIVE"] + except: + pass + try: + MOSQUITTO_USER = config["MQTT"]["USERNAME"] + except: + pass + try: + MOSQUITTO_PWD = config["MQTT"]["PASSWORD"] + except: + pass + try: + MOSQUITTO_TLS = config["MQTT"]["TLS_CERT"] + except: + pass # Set freq and log filename FREQUENCY_SECONDS =config["bluetooth"]["frequency"] @@ -85,8 +98,8 @@ def main( configfile='homie-bluetooth.json' ): print ("Connecting to {0}:{1}".format( MOSQUITTO_HOST, MOSQUITTO_PORT )) if MOSQUITTO_USER is not None: mqttc.username_pw_set( MOSQUITTO_USER, MOSQUITTO_PWD ) - if "TLS_CERT" in config["MQTT"]: - mqttc.tls_set( ca_certs=config["MQTT"]["TLS_CERT"] ) + if MOSQUITTO_TLS is not None: + mqttc.tls_set( ca_certs=MOSQUITTO_TLS) mqttc.connect( MOSQUITTO_HOST, MOSQUITTO_PORT, MOSQUITTO_KEEPALIVE ) mqttc.loop_start() From be7fb92f902cf6b49c8b554b09442ad8768054ae Mon Sep 17 00:00:00 2001 From: psyciknz Date: Thu, 17 Dec 2020 23:06:03 +1300 Subject: [PATCH 17/18] config --- BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py b/BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py index 5aa0b32..a8cec1e 100644 --- a/BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py +++ b/BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py @@ -72,6 +72,11 @@ def main( configfile='homie-bluetooth.json' ): MOSQUITTO_HOST = config["MQTT"]["HOST"] MOSQUITTO_PORT = config["MQTT"]["PORT"] + MOSQUITTO_KEEPALIVE = None + MOSQUITTO_USER = None + MOSQUITTO_PWD = None + MOSQUITTO_TLS = None + try: MOSQUITTO_KEEPALIVE = config["MQTT"]["KEEPALIVE"] except: From d1459ef7e1ebfdc82dc6e6daa6f10a8850de2615 Mon Sep 17 00:00:00 2001 From: psyciknz Date: Thu, 17 Dec 2020 23:07:16 +1300 Subject: [PATCH 18/18] Keepalive --- BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py b/BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py index a8cec1e..754397b 100644 --- a/BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py +++ b/BlueTooth/mqtt.bluetooth/mqtt.bluetooth.py @@ -72,7 +72,7 @@ def main( configfile='homie-bluetooth.json' ): MOSQUITTO_HOST = config["MQTT"]["HOST"] MOSQUITTO_PORT = config["MQTT"]["PORT"] - MOSQUITTO_KEEPALIVE = None + MOSQUITTO_KEEPALIVE = 10 MOSQUITTO_USER = None MOSQUITTO_PWD = None MOSQUITTO_TLS = None