-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetrics.py
191 lines (167 loc) · 7.06 KB
/
metrics.py
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
188
189
190
191
# https://github.com/linsvensson/sensor.greenely
"""Greenely API"""
import logging
from datetime import datetime, timedelta
import calendar
import requests
import json
from prometheus_client import start_http_server, Gauge
import time
import os
_LOGGER = logging.getLogger(__name__)
jwt = ''
url_check_auth = 'https://api2.greenely.com/v1/checkauth'
url_login = 'https://api2.greenely.com/v1/login'
url_data = 'https://api2.greenely.com/v3/data/'
url_facilities_base = 'https://api2.greenely.com/v1/facilities/'
headers = {'Accept-Language': 'sv-SE',
'User-Agent': 'Android 2 111',
'Content-Type': 'application/json; charset=utf-8',
'Authorization': jwt}
email = os.getenv("GR_EMAIL")
password = os.getenv("GR_PASSWORD")
facility_id = "primary"
def get_facility_id():
result = requests.get(
url_facilities_base + 'primary?includes=retail_state&includes=consumption_limits&includes=parameters',
headers=headers)
if result.status_code == requests.codes.ok:
data = result.json()
facility_id = str(data['data']['parameters']['facility_id'])
_LOGGER.debug('Fetched facility id %s', facility_id)
else:
_LOGGER.error('Failed to fetch facility id %s', result.text)
def login():
"""Login to the Greenely API."""
result = False
loginInfo = {'email': email,
'password': password}
loginResult = requests.post(url_login, headers=headers, data=json.dumps(loginInfo))
if loginResult.status_code == requests.codes.ok:
jsonResult = loginResult.json()
jwt = "JWT " + jsonResult['jwt']
headers['Authorization'] = jwt
_LOGGER.debug('Successfully logged in and updated jwt')
if facility_id == 'primary':
get_facility_id()
else:
_LOGGER.debug('Facility id is %s', facility_id)
result = True
else:
_LOGGER.error(loginResult.text)
return result
def check_auth():
"""Check to see if our jwt is valid."""
result = requests.get(url_check_auth, headers=headers)
if result.status_code == requests.codes.ok:
_LOGGER.debug('jwt is valid!')
print(result.text)
return True
else:
if login() == False:
_LOGGER.debug(result.text)
print(result.text)
return False
return True
def get_price_data():
today = datetime.today()
start = "?from=" + str(today.year) + "-" + today.strftime("%m") + "-01"
endOfMonth = calendar.monthrange(today.year, today.month)[1]
end = "&to=" + str(today.year) + "-" + today.strftime("%m") + "-" + str(endOfMonth);
url = url_facilities_base + facility_id + '/consumption-cost' + start + end + "&resolution=monthly&prediction=false&exclude_additions=false&exclude_monthly_fee=false&exclude_vat=false"
response = requests.get(url, headers=headers)
data = {}
if response.status_code == requests.codes.ok:
data = response.json()
return data['data']
else:
_LOGGER.error('Failed to get price data, %s', response.text)
return data
def get_spot_price():
today = datetime.today()
yesterday = today - timedelta(days=1)
tomorrow = today + timedelta(days=2)
start = "?from=" + str(yesterday.year) + "-" + yesterday.strftime("%m") + "-" + yesterday.strftime("%d")
end = "&to=" + str(tomorrow.year) + "-" + tomorrow.strftime("%m") + "-" + tomorrow.strftime("%d")
url = url_facilities_base + facility_id + "/spot-price" + start + end + "&resolution=hourly"
response = requests.get(url, headers=headers)
data = {}
if response.status_code == requests.codes.ok:
data = response.json()
return data
else:
_LOGGER.error('Failed to get spot price data, %s', response.text)
return data
def get_usage():
endDate = datetime.now().replace(hour=0,
minute=0,
second=0,
microsecond=0) - timedelta(days=1)
startDate = endDate - timedelta(days=1)
start = "?from=" + str(startDate.year) + "-" + startDate.strftime("%m") + '-' + str(startDate.day)
end = "&to=" + str(endDate.year) + "-" + endDate.strftime("%m") + '-' + str(endDate.day)
url = url_facilities_base + facility_id + '/consumption' + start + end + "&resolution=" + "daily"
response = requests.get(url, headers=headers)
data = {}
if response.status_code == requests.codes.ok:
data = response.json()
for value in data['data']:
usage = data['data'][value]['usage']
return round(usage/1000, 1)
else:
_LOGGER.error('Failed to fetch usage data, %s', response.text)
return data
def get_current_spot_price():
today = datetime.today()
tomorrow = today + timedelta(days=1)
currentTime = today.strftime("%Y-%m-%d %H:00")
start = "?from=" + str(today.year) + "-" + today.strftime("%m") + "-" + today.strftime("%d")
end = "&to=" + str(tomorrow.year) + "-" + tomorrow.strftime("%m") + "-" + tomorrow.strftime("%d")
url = url_facilities_base + facility_id + "/spot-price" + start + end + "&resolution=hourly"
response = requests.get(url, headers=headers)
data = {}
if response.status_code == requests.codes.ok:
data = response.json()['data']
for value in data:
if data[value]['localtime'] == currentTime:
price = data[value]['price']
roundedPrice = round(price / 100000, 2)
return roundedPrice
else:
_LOGGER.error('Failed to get spot price data, %s', response.text)
return data
def get_daily_usage():
today = datetime.today()
endDate = datetime.now().replace(hour=0,
minute=0,
second=0,
microsecond=0) - timedelta(days=1)
startDate = endDate - timedelta(days=30)
start = "?from=" + str(startDate.year) + "-" + today.strftime("%m") + '-' + '01'
end = "&to=" + str(endDate.year) + "-" + endDate.strftime("%m") + '-' + str(endDate.day)
url = url_facilities_base + facility_id + '/consumption' + start + end + "&resolution=" + "daily"
response = requests.get(url, headers=headers)
data = {}
if response.status_code == requests.codes.ok:
data = response.json()
total_usage = 0
for value in data['data']:
total_usage += data['data'][value]['usage']
return round(total_usage / 1000, 1)
else:
_LOGGER.error('Failed to fetch usage data, %s', response.text)
return data
def main():
"""Main entry point"""
if check_auth():
spot_price = Gauge("greenely_spot_price", "current price per kWh")
el_usage = Gauge("greenely_el_usage", "last daily usage, kWh")
total_el_usage=Gauge("greenely_total_usage", "total usage from month beginning, kWh")
start_http_server(9101)
while True:
spot_price.set(get_current_spot_price())
el_usage.set(get_usage())
total_el_usage.set(get_daily_usage())
time.sleep(60)
if __name__ == "__main__":
main()