import time import machine import onewire, ds18x20 import ujson as json import ubinascii from umqtt.simple import MQTTClient class TempMon: def __init__(self, pin): self.cfg = { "broker": "192.168.1.153", "sensor_pin": 5, "client_id": b"esp8266_" + ubinascii.hexlify(machine.unique_id()), "topic": b"sensor_data", } self.load_config() dat = machine.Pin(self.cfg['sensor_pin']) # create the onewire object self.ds = ds18x20.DS18X20(onewire.OneWire(dat)) # scan for devices on the bus self.roms = self.ds.scan() time.sleep_ms(750) print('found devices:', self.roms) self.client = MQTTClient(self.cfg['client_id'], self.cfg['broker']) self.client.connect() print("Connected to {}".format(self.cfg['broker'])) def load_config(self): try: with open("/config.json") as f: config = json.loads(f.read()) except (OSError, ValueError): print("Couldn't load /config.json") self.save_config() else: self.cfg.update(config) print("Loaded config from /config.json") def save_config(self): try: with open("/config.json", "w") as f: f.write(json.dumps(self.cfg)) except OSError: print("Couldn't save /config.json") # loop 10 times and print all temperatures def read_temp(self): for i in range(10): try: print('temperatures:', end=' ') self.ds.convert_temp() time.sleep_ms(750) for rom in self.roms: val = self.ds.read_temp(rom) s_val = 'Device %s reading :%s' % (str(rom), val) print(s_val) self.client.publish(self.cfg['topic'], bytes(s_val, 'utf-8')) print() except Exception: print("error encountered...continuing") continue