Guest User

Untitled

a guest
Nov 2nd, 2018
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. import pywemo
  2. from pprint import pformat as pf
  3. from influxdb import InfluxDBClient
  4. import time
  5. from datetime import datetime, timezone
  6.  
  7. ########################### INFLUXDB CONFIG ###########################
  8. influxdb_url = '192.168.1.20'
  9. influxdb_port = 8086
  10. influxdb_username = ''
  11. influxdb_password = ''
  12. db_name = 'homelab'
  13.  
  14. INFLUX_CLIENT = InfluxDBClient(influxdb_url,
  15. influxdb_port,
  16. influxdb_username,
  17. influxdb_password,
  18. db_name)
  19.  
  20.  
  21. def wemo_status():
  22. CURRENT_TIME = datetime.now(timezone.utc).astimezone().isoformat()
  23. for dev in pywemo.discover_devices():
  24. alias = str(dev).replace('<','')
  25. alias = alias.replace('>','')
  26. state = dev.get_state()
  27. time = CURRENT_TIME
  28. INFLUX_PAYLOAD = [
  29. {
  30. "measurement": "Homelab",
  31. "tags": {
  32. "alias": alias,
  33. "state": state,
  34. },
  35. "time": time,
  36. "fields": {
  37. "alias": alias,
  38. "state": state,
  39.  
  40. }
  41. }
  42. ]
  43. #IF THIS IS YOUR FIRST RUN UNCOMMENT LINE 44 and 45 AND COMMENT LINES 46 TO 53 LET IT RUN FOR 10-15 SECONDS AND THEN COMMENT 44 and 45 AND UNCOMMENT 46-53
  44. #INFLUX_CLIENT.write_points(INFLUX_PAYLOAD)
  45. #print(alias+' is: '+str(state)+': Test')
  46. INFLUX_QUERY = "SELECT state FROM Homelab WHERE (alias = '"+alias+"') ORDER BY time DESC limit 1"
  47. results = INFLUX_CLIENT.query(INFLUX_QUERY)
  48. PREV_STATE = results.raw['series'][0]['values'][0][1]
  49. if PREV_STATE == state:
  50. print(alias+' is: '+str(state)+': No State Change')
  51. else:
  52. INFLUX_CLIENT.write_points(INFLUX_PAYLOAD)
  53. print(alias+' is: '+str(state)+': State Has Changed')
  54.  
  55. while True:
  56. wemo_status()
  57. time.sleep(3)
Add Comment
Please, Sign In to add comment