main.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # This script will find all devices in your installation and
  2. # output their per-minute usage for the previous DAYS_BACK days.
  3. # Per-minute data is stored for a maximum of 7 days.
  4. #
  5. # To change the timing, update the DAYS_BACK variable below.
  6. #
  7. # Reads credentials from `keys.json`
  8. #
  9. # To ensure data is not read for a minute that has not yet ended,
  10. # this will read up to 2 minutes ago.
  11. import pyemvue
  12. import json
  13. from pyemvue.enums import Scale, Unit
  14. from pyemvue import PyEmVue
  15. from pprint import pprint
  16. from datetime import datetime, timezone, timedelta
  17. NOW = datetime.now(timezone.utc) - timedelta(minutes=2)
  18. DAYS_BACK = 14 # Number of days in the past to get per-minute data for.
  19. MAX_HOURS = 12 # The maxinum number of hours that can be retrieved at once.
  20. # Get & display minutely data for all devices.
  21. def allUsageOverTime(vue: PyEmVue):
  22. devices = vue.get_devices()
  23. print(f'time\tdevice_gid\tchannel_num\twH\twatts\tmultiplier\tname')
  24. for device in devices:
  25. # print('=== Device ===')
  26. # pprint(vars(device))
  27. for channel in device.channels:
  28. # pprint(vars(channel))
  29. if not channel.name is None:
  30. channelUsageOverTime(vue, channel)
  31. def channelUsageOverTime(vue: PyEmVue, c):
  32. start_time = NOW - timedelta(days=DAYS_BACK)
  33. end_time = start_time + timedelta(hours=MAX_HOURS)
  34. while start_time < NOW:
  35. usage_over_time, start = vue.get_chart_usage(
  36. c,
  37. start_time, end_time,
  38. scale=Scale.MINUTE.value,
  39. unit=Unit.KWH.value
  40. )
  41. time = start
  42. for kwh in usage_over_time:
  43. if kwh is None:
  44. continue
  45. wattHours = kwh * 1000
  46. watts = wattHours * 60
  47. print(f'{time}\t{c.device_gid}\t{c.channel_num}\t{wattHours}\t{watts}\t{c.channel_multiplier}\t{c.name}')
  48. time += timedelta(minutes=1)
  49. # Jump to the next start time.
  50. start_time = end_time
  51. end_time += timedelta(minutes=(MAX_HOURS*60))
  52. if __name__ == '__main__':
  53. with open('keys.json') as f:
  54. keys = json.load(f)
  55. vue = pyemvue.PyEmVue()
  56. if 'id_token' in keys:
  57. # Login using access tokens.
  58. vue.login(
  59. id_token=keys['id_token'],
  60. access_token=keys['access_token'],
  61. refresh_token=keys['refresh_token'],
  62. token_storage_file='keys.json'
  63. )
  64. else:
  65. # Login with username & password, and update keys.json.
  66. vue.login(
  67. username=keys['username'],
  68. password=keys['password'],
  69. token_storage_file='keys.json'
  70. )
  71. allUsageOverTime(vue)