main.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import pyemvue
  2. import json
  3. import datetime
  4. from pyemvue.enums import Scale, Unit
  5. def printRecursive(usageDict, info, depth=0):
  6. for gid, device in usageDict.items():
  7. for channelNum, channel in device.channels.items():
  8. name = channel.name
  9. if name == 'Main':
  10. name = info[gid].device_name
  11. print('-'*depth, f'{gid}\t{channelNum}\t{name}\t{channel.usage}\tkWh')
  12. if channel.nested_devices:
  13. printRecursive(channel.nested_devices, info, depth+1)
  14. def usageOverTime(vue, device):
  15. now = datetime.datetime.now(datetime.timezone.utc)
  16. search_end = now
  17. # search_end = now - datetime.timedelta(hours=12)
  18. search_start = search_end - datetime.timedelta(hours=12)
  19. usage_over_time, start_time = vue.get_chart_usage(
  20. device.channels[0],
  21. search_start,
  22. search_end,
  23. scale=Scale.MINUTE.value,
  24. unit=Unit.KWH.value
  25. )
  26. print('Usage for the last 7 days, starting', start_time.isoformat())
  27. currTime = start_time
  28. for usage in usage_over_time:
  29. print(currTime, usage*1000, 'Wh')
  30. currTime += datetime.timedelta(minutes=1)
  31. if __name__ == '__main__':
  32. with open('keys.json') as f:
  33. keys = json.load(f)
  34. vue = pyemvue.PyEmVue()
  35. if 'id_token' in keys:
  36. # Login using access tokens.
  37. vue.login(
  38. id_token=keys['id_token'],
  39. access_token=keys['access_token'],
  40. refresh_token=keys['refresh_token'],
  41. token_storage_file='keys.json'
  42. )
  43. else:
  44. # Login with username & password, and update keys.json.
  45. vue.login(
  46. username=keys['username'],
  47. password=keys['password'],
  48. token_storage_file='keys.json'
  49. )
  50. devices = vue.get_devices()
  51. # Show current usage for all devices.
  52. deviceGIDs = []
  53. deviceInfo = {}
  54. for device in devices:
  55. gid = device.device_gid
  56. if not gid in deviceGIDs:
  57. deviceGIDs.append(gid)
  58. deviceInfo[gid] = device
  59. else:
  60. deviceInfo[gid].channels += device.channels
  61. usageDict = vue.get_device_list_usage(
  62. deviceGids=deviceGIDs,
  63. instant=None,
  64. scale=Scale.MINUTE.value,
  65. unit=Unit.KWH.value
  66. )
  67. print(f'device_gid\tchannel_num\tname\tusage\tunit')
  68. printRecursive(usageDict, deviceInfo)
  69. # Show previous usage for the first device.
  70. usageOverTime(vue, devices[0])