1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
| import requests
import json
import base64
import sys
import random
import time
from datetime import datetime
import datetime
# Insert your own info here as you defined when you created your APP
# Note that in a real app you would not want to hard-code these values
# Instead you would want to import them from the environment or even use
# a more secure solution like a keystore.
CLIENT_ID = "" # get from enphase
CLIENT_SECRET = "" # get from enphase
REDIRECT_URI = "https://api.enphaseenergy.com/oauth/redirect_uri"
DOMAIN = 'api.enphaseenergy.com' # use eu hostname if you are in EU
credentials = "" #filesystem location
api_key = '' # get from enphase
all_micros = [
'micro-serial1',
'micro-serial2',
'enz',
]
def get_micro(name,start_at):
"""
"""
print('Start time: ',start_at)
for micro in name:
fetch_data(micro=micro, start_at=start_at)
time.sleep(5)
def get_system():
"""
"""
with open(credentials, 'r') as f:
creds = json.load(f)
access_token = creds['access_token']
file = f'/opt/telegraf/enphase.json'
base_url = f'https://{DOMAIN}'
url = f"{base_url}/api/v4/systems/<system_ID>/telemetry/production_micro" #i know, should be a variable
headers = {
'Content-Type': "application/x-www-form-urlencoded",
'Authorization': f'Bearer {access_token}'
}
data = {'key': api_key,
# 'start_at': start_at,
# 'granularity': 'week'
}
r = requests.get(url, headers=headers, data=data)
if r.status_code == 401:
print('Trying a token refresh, losing data')
refresh_token()
if r.status_code == 429:
sleeptime = 60 - datetime.datetime.now().second
print('Sleeping for', sleeptime,'seconds')
time.sleep(sleeptime)
r = requests.get(url, headers=headers, data=data)
if r.status_code == 200:
response = r.json()
with open(file, 'w') as f:
json.dump(response, f, indent=4)
def fetch_data(micro='<ugly default micro serial>', start_at=False):
'''refresh existing token for a new one'''
with open(credentials, 'r') as f:
creds = json.load(f)
access_token = creds['access_token']
file = f'/opt/enphase/data/micro_{micro}_now.json'
# print(start_at)
base_url = f'https://{DOMAIN}'
url = f"{base_url}/api/v4/systems/<system_ID>/devices/micros/{micro}/telemetry" #i know, should be a variable
headers = {
'Content-Type': "application/x-www-form-urlencoded",
'Authorization': f'Bearer {access_token}'
}
if start_at:
data = {'key': api_key,
'start_at': start_at,
'granularity': 'week'
}
file = f'/opt/enphase/data/micro_{micro}_{start_at}.json'
else:
data = {'key': api_key,
# 'start_at': start_at,
'granularity': 'week'
}
r = requests.get(url, headers=headers, data=data)
if r.status_code == 401:
print('Trying a token refresh, losing data')
refresh_token()
if r.status_code == 429:
# time.sleep(60)
sleeptime = 60 - datetime.datetime.now().second
print('Sleeping for', sleeptime,'seconds')
time.sleep(sleeptime)
r = requests.get(url, headers=headers, data=data)
if r.status_code == 200:
response = r.json()
# print(response)
print(file)
with open(file, 'w') as f:
json.dump(response, f, indent=4)
def refresh_token():
'''refresh existing token for a new one'''
with open(credentials, 'r') as f:
creds = json.load(f)
refresh_token = creds['refresh_token']
base64_encoded_clientid_clientsecret = base64.b64encode(str.encode(f'{CLIENT_ID}:{CLIENT_SECRET}')) # concatenate with : and encode in base64
base64_encoded_clientid_clientsecret = base64_encoded_clientid_clientsecret.decode('ascii') # turn bytes object into ascii string
base_url = f'https://{DOMAIN}'
url = f"{base_url}/oauth/token"
headers = {
'Content-Type': "application/x-www-form-urlencoded",
'Authorization': f'Basic {base64_encoded_clientid_clientsecret}'
}
data = {'grant_type': 'refresh_token',
'redirect_uri': REDIRECT_URI,
'refresh_token': refresh_token,
'code': '' # get from yourself throug enphase autorisation URL and, yes this should be a variable in the beginning of the script
}
r = requests.post(url, headers=headers, data=data)
response = r.json()
print(response)
if response.get('access_token'):
# don't store creds in plaintext in a real app obviously
with open(credentials, 'w') as f:
json.dump(response, f, indent=4)
else:
print('There was an error refreshing your access token')
print(r.text)
def main():
# standard - load "args" list with cmd-line-args
args = sys.argv[1:]
# args is a list of the command line argument strings that follow
# the program.py file.
# So if the command is: python3 affirm.py aaa bbb ccc
# The args list will be:
# args == ['aaa', 'bbb', 'ccc']
# The args are all strings, whatever was typed in the terminal.
if args[0] == 'refresh_token':
refresh_token()
if len(args) > 1 and args[0] == 'getmicro':
start_at = args[1]
args.pop(0)
args.pop(0)
get_micro(args,start_at)
if len(args) == 2 and args[0] == 'getmicros':
start_at = args[1]
get_micro(all_micros,start_at)
if args[0] == 'getsystem':
get_system()
if __name__ == '__main__':
main() |