ex2.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import time
  2. import machine
  3. import onewire, ds18x20
  4. import ujson as json
  5. import ubinascii
  6. from umqtt.simple import MQTTClient
  7. class TempMon:
  8. def __init__(self, pin):
  9. self.cfg = {
  10. "broker": "192.168.1.153",
  11. "sensor_pin": 5,
  12. "client_id": b"esp8266_" + ubinascii.hexlify(machine.unique_id()),
  13. "topic": b"sensor_data",
  14. }
  15. self.load_config()
  16. dat = machine.Pin(self.cfg['sensor_pin'])
  17. # create the onewire object
  18. self.ds = ds18x20.DS18X20(onewire.OneWire(dat))
  19. # scan for devices on the bus
  20. self.roms = self.ds.scan()
  21. time.sleep_ms(750)
  22. print('found devices:', self.roms)
  23. self.client = MQTTClient(self.cfg['client_id'], self.cfg['broker'])
  24. self.client.connect()
  25. print("Connected to {}".format(self.cfg['broker']))
  26. def load_config(self):
  27. try:
  28. with open("/config.json") as f:
  29. config = json.loads(f.read())
  30. except (OSError, ValueError):
  31. print("Couldn't load /config.json")
  32. self.save_config()
  33. else:
  34. self.cfg.update(config)
  35. print("Loaded config from /config.json")
  36. def save_config(self):
  37. try:
  38. with open("/config.json", "w") as f:
  39. f.write(json.dumps(self.cfg))
  40. except OSError:
  41. print("Couldn't save /config.json")
  42. # loop 10 times and print all temperatures
  43. def read_temp(self):
  44. for i in range(10):
  45. try:
  46. print('temperatures:', end=' ')
  47. self.ds.convert_temp()
  48. time.sleep_ms(750)
  49. for rom in self.roms:
  50. val = self.ds.read_temp(rom)
  51. s_val = 'Device %s reading :%s' % (str(rom), val)
  52. print(s_val)
  53. self.client.publish(self.cfg['topic'], bytes(s_val, 'utf-8'))
  54. print()
  55. except Exception:
  56. print("error encountered...continuing")
  57. continue