コード例 #1
0
def main(configfile='homie-bluetooth.json'):
    Homie = homie.Homie(configfile)
    Homie.setFirmware("bluemaestro-temperature", "1.0.0")
    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')

    try:
        sock = bluez.hci_open_dev(dev_id)
        logging.info("ble thread started")

    except:
        print "error accessing bluetooth device..."
        logging.info("error accessing bluetooth device...")
        sys.exit(1)

    bluemaestroscan.hci_le_set_scan_parameters(sock)
    bluemaestroscan.hci_enable_le_scan(sock)

    while True:
        try:
            returnedList = bluemaestroscan.parse_events(sock, 2)
            nodes = {}
            print "-------------------------------------------------------------------------------------------------------"
            logging.info(
                "-------------------------------------------------------------------------------------------------------"
            )
            mac = ""
            temp = 0
            currentdate = time.strftime('%Y-%m-%d %H:%M:%S')
            print('Date Time:   {0}'.format(currentdate))
            logging.info('Date Time:   {0}'.format(currentdate))
            for beacon in returnedList:
                val = returnedList[beacon]
                print beacon, val
                mac = returnedList["mac"]
                temp = returnedList["temp"]

                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"])
                    logging.info("%s/temperature = %.2f" %
                                 (returnedList["mac"], returnedList["temp"]))
                    # Publish to the MQTT channel
                    try:
                        print("CHecking nodes for " + mac + "temperature")
                        updatenode(Homie, nodes, mac, "temperature",
                                   float(returnedList["temp"]))

                        #if mac+"temperature" in nodes:
                        #	logging.info("Found existing temperature node: " +  mac+"temperature")
                        #	print("Found existing temperature node: " + mac+"temperature")
                        #	temperatureNode = nodes[mac+"temperature"]
                        #	print ("Obtained temperature node for updating")
                        #	Homie.setNodeProperty(tempNode,"temperature",float(returnedList["temp"]),True)
                        #else:
                        #	logging.info("Added new temperature node for mac" + mac)
                        #	print("Adding new temperature node for mac" + mac)
                        #	temperatureNode = Homie.Node(mac,"temperature")
                        #	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("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("CHecking nodes for " + mac + "battery")
                        updatenode(Homie, nodes, mac, "battery",
                                   float(returnedList["battery"]))

                        #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"]))
                        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"])
                        logging.info('Updating {0}/dewpoint = {1}'.format(
                            returnedList["mac"], returnedList["dewpoint"]))

                        print("CHecking nodes for " + mac + "name")
                        updatenode(Homie, nodes, mac, "name",
                                   returnedList["name"])

                        #nameNode = Homie.Node(mac,"name")
                        #Homie.setNodeProperty(nameNode,"name",returnedList["name"],True)
                        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:
                        # 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"
                    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:
            # 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
コード例 #2
0
def main(configfile='homie-bluetooth.json'):
    # Read config
    print "Loading config from: " + configfile
    with open(configfile) as json_file:
        config = json.load(json_file)

    print "Configuration:"
    print config

    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"]

    # Set freq and log filename
    FREQUENCY_SECONDS = config["bluetooth"]["frequency"]
    LOG = config["bluetooth"]["log"]
    logging.basicConfig(filename=LOG,
                        level=logging.ERROR,
                        format='%(asctime)s %(levelname)s %(message)s')

    # Set MQTT credentials, open connection and start background network loop
    print "Connecting to {0}:{1}".format(MOSQUITTO_HOST, MOSQUITTO_PORT)
    # mqttc.username_pw_set( MOSQUITTO_USER, MOSQUITTO_PWD )
    # mqttc.tls_set( ca_certs=config["MQTT"]["TLS_CERT"] )
    mqttc.connect(MOSQUITTO_HOST, MOSQUITTO_PORT, MOSQUITTO_KEEPALIVE)
    mqttc.loop_start()

    try:
        sock = bluez.hci_open_dev(dev_id)

    except:
        print "error accessing bluetooth device..."
        logging.error("error accessing bluetooth device...")
        sys.exit(1)

    bluemaestroscan.hci_le_set_scan_parameters(sock)
    bluemaestroscan.hci_enable_le_scan(sock)

    while True:
        try:
            returnedList = bluemaestroscan.parse_events(sock)
            currentdatetime = time.strftime(
                "%Y-%m-%dT%H:%M:%S")  # 2019-06-25T23:59:00
            print('Date Time:   {0}'.format(currentdatetime))
            print "number of beacons found {0}".format(len(returnedList))

            for beacon in returnedList:
                # Publish to the MQTT channel
                try:
                    mac = beacon["name"]
                    name = friendlyNames[beacon["name"]]
                    temp = float(beacon["temp"])
                    humidity = float(beacon["humidity"])
                    dewpoint = beacon["dewpoint"]
                    battery = "{:.2f}".format(beacon["battery"])

                    print "Mac: {0}, Name: {1}, Temp: {2} C, humidity: {3}%, dewpoint: {4} C, battery: {5}%".format(
                        mac, name, temp, humidity, dewpoint, battery)

                    mqttc.publish(
                        "/bluemaestro/{0}".format(name),
                        json.dumps({
                            "name": name,
                            "temp": temp,
                            "humidity": humidity,
                            "dewpoint": dewpoint,
                            "battery": battery,
                            "timestamp": currentdatetime
                        }))

                except Exception, 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

            # If we didn't find any matching BLE devices, wait 1 sec.; otherwise wait the speficied amount
            if len(returnedList) > 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
コード例 #3
0
def main(sock):
    # Set up for scanning
    bluemaestroscan.hci_le_set_scan_parameters(sock)
    bluemaestroscan.hci_enable_le_scan(sock)

    # Loop until killed
    while True:
        try:
            returnedList = bluemaestroscan.parse_events(sock, 10)
            currentdatetime = time.strftime(
                "%Y-%m-%dT%H:%M:%S")  # 2019-06-25T23:59:00
            print('Date Time:   {0}'.format(currentdatetime))
            print("number of beacons found {0}".format(len(returnedList)))
            date_time = currentdatetime.split('T')

            for beacon in returnedList:
                # Publish to the google sheet
                try:
                    temp = float(beacon["temp"])
                    humidity = float(beacon["humidity"])
                    dewpoint = beacon["dewpoint"]
                    battery = beacon["battery"]

                    print(
                        "Temp: {0} C, humidity: {1}%, dewpoint: {2} C, battery: {3}%"
                        .format(temp, humidity, dewpoint, battery))
                    # Write to file somewhere and direct to sheet
                    bluemaestroscan.hci_disable_le_scan(sock)
                    row = [
                        date_time[0], date_time[1], temp, humidity, dewpoint,
                        battery
                    ]
                    with open("/home/pi/Documents/RemoteTemperature/data.csv",
                              "a") as csvfile:
                        writer = csv.writer(csvfile, delimiter=',')
                        writer.writerow(row)
                    # Get rid of a row if there are too many
                    if sheet_instance.row_count > 5000:
                        sheet_instance.delete_row(2)
                    sheet_instance.append_row(row)
                    time.sleep(FREQUENCY_SECONDS)
                    bluemaestroscan.hci_enable_le_scan(sock)

                except Exception as e:
                    # Null out the worksheet so a login is performed at the top of the loop.
                    time.sleep(60)
                    continue

                    # If we didn't find any matching BLE devices, wait 1 sec.; otherwise wait the speficied amount
                    if len(returnedList) > 0:
                        time.sleep(FREQUENCY_SECONDS)
                    else:
                        time.sleep(10)

        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
コード例 #4
0
try:
    sock = bluez.hci_open_dev(dev_id)
    print "ble thread started"

except:
    print "error accessing bluetooth device..."
    sys.exit(1)
print('Connecting to MQTT on {0}'.format(MOSQUITTO_HOST))
mqttc = mqtt.Client("python_pub")
bluemaestroscan.hci_le_set_scan_parameters(sock)
bluemaestroscan.hci_enable_le_scan(sock)

while True:
    try:
        returnedList = bluemaestroscan.parse_events(sock, 2)
        print "-------------------------------------------------------------------------------------------------------"
        mac = ""
        temp = 0
        currentdate = time.strftime('%Y-%m-%d %H:%M:%S')
        print('Date Time:   {0}'.format(currentdate))
        for beacon in returnedList:
            val = returnedList[beacon]
            print beacon, val
            mac = returnedList["mac"]
            temp = returnedList["temp"]

        print "number of beacons found {0}".format(len(returnedList))
        if len(returnedList) > 0:
            print "%s/temperature = %.2f" % (returnedList["mac"],
                                             returnedList["temp"])
コード例 #5
0
def main(configfile='homie-bluetooth.json'):
    Homie = homie.Homie(configfile)
    Homie.setFirmware("bluemaestro-temperature", "1.0.0")
    Homie.setup()

    try:
        sock = bluez.hci_open_dev(dev_id)
        print "ble thread started"

    except:
        print "error accessing bluetooth device..."
        sys.exit(1)

    bluemaestroscan.hci_le_set_scan_parameters(sock)
    bluemaestroscan.hci_enable_le_scan(sock)

    try:
        returnedList = bluemaestroscan.parse_events(sock, 2)
        nodes = {}
        print "-------------------------------------------------------------------------------------------------------"
        mac = ""
        temp = 0
        currentdate = time.strftime('%Y-%m-%d %H:%M:%S')
        print('Date Time:   {0}'.format(currentdate))
        for beacon in returnedList:
            val = returnedList[beacon]
            print beacon, val
            mac = returnedList["mac"]
            temp = returnedList["temp"]

            print "number of beacons found {0}".format(len(returnedList))
            if len(returnedList) > 0:
                print "%s/temperature = %.2f" % (returnedList["mac"],
                                                 returnedList["temp"])
                # Publish to the MQTT channel
                try:
                    temperatureNode = Homie.Node(mac, "temperature")
                    Homie.setNodeProperty(temperatureNode, "temperature",
                                          float(returnedList["temp"]), True)
                    print 'Updating temp for {0} to {1}'.format(
                        returnedList["mac"], float(returnedList["temp"]))
                    humidityNode = Homie.Node(mac, "humidity")
                    Homie.setNodeProperty(humidityNode, "humidity",
                                          float(returnedList["humidity"]),
                                          True)
                    print 'Updating humidity {0} = {1}'.format(
                        returnedList["mac"], float(returnedList["humidity"]))
                    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"]))
                    dewpointNode = Homie.Node(mac, "dewpoint")
                    Homie.setNodeProperty(dewpointNode, "dewpoint",
                                          float(returnedList["dewpoint"]),
                                          True)
                    print 'Updating {0}/dewpoint = {1}'.format(
                        returnedList["mac"], returnedList["dewpoint"])
                    nameNode = Homie.Node(mac, "name")
                    Homie.setNodeProperty(nameNode, "name",
                                          returnedList["name"], True)
                    print 'Updating name {0}/name = {1}'.format(
                        returnedList["mac"], returnedList["name"])
                    time.sleep(1)

                    print "Sleeping for %d seconds" % FREQUENCY_SECONDS

                except Exception, e:
                    # 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"

    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"