import paho.mqtt.client as mqtt import smbus import time import os import sys time.sleep(30) #Sleep to allow wireless to connect before starting MQTT username = "1234567890" password = "abcdefgghi" clientid = "12345-abcd" mqttc = mqtt.Client(client_id=clientid) mqttc.username_pw_set(username, password=password) mqttc.connect("mqtt.mydevices.com", port=1883, keepalive=60) mqttc.loop_start() topic_si7021_temp = "v1/" + username + "/things/" + clientid + "/data/3" topic_si7021_humidity = "v1/" + username + "/things/" + clientid + "/data/4" while True: try: # Get I2C bus bus = smbus.SMBus(1) bus.write_byte(0x40, 0xF5) time.sleep(0.3) # SI7021 address, 0x40 Read 2 bytes, Humidity data0 = bus.read_byte(0x40) data1 = bus.read_byte(0x40) # Convert the data humidity = ((data0 * 256 + data1) * 125 / 65536.0) - 6 time.sleep(0.3) bus.write_byte(0x40, 0xF3) time.sleep(0.3) # SI7021 address, 0x40 Read data 2 bytes, Temperature data0 = bus.read_byte(0x40) data1 = bus.read_byte(0x40) # Convert the data and output it celsTemp = ((data0 * 256 + data1) * 175.72 / 65536.0) - 46.85 fahrTemp = celsTemp * 1.8 + 32 if fahrTemp is not None: fahrTemp = "temp,f=" + str(fahrTemp) mqttc.publish(topic_si7021_temp, payload=fahrTemp, retain=True) if humidity is not None: humidity = "rel_hum,p=" + str(humidity) mqttc.publish(topic_si7021_humidity, payload=humidity, retain=True) time.sleep(5) except (EOFError, SystemExit, KeyboardInterrupt): mqttc.disconnect() sys.exit()