This repository has been archived by the owner on May 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhub.py
230 lines (182 loc) · 8.41 KB
/
hub.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
from __future__ import annotations
import asyncio
import random
from datetime import timedelta
import imaplib
from email.header import decode_header
import re
import pandas as pd
import functools
from .carbon_asset_calculator import get_tokens_to_burn, get_tokens_to_burn_thread
from homeassistant.core import HomeAssistant
from homeassistant.helpers.event import async_track_time_interval
import logging
_LOGGER = logging.getLogger(__name__)
def to_thread(func: tp.Callable) -> tp.Coroutine:
@functools.wraps(func)
async def wrapper(*args, **kwargs):
return await asyncio.to_thread(func, *args, **kwargs)
return wrapper
class Hub:
def __init__(self, hass: HomeAssistant, email_address: str, password: str) -> None:
"""Init hub."""
self._hass = hass
self._name = "Solarweb"
self._id = self._name.lower()
self.boards = [
Board(hass, f"{self._id}_energy", f"{self._name}_energy", email_address, password),
]
self.online = True
@property
def hub_id(self) -> str:
"""ID for hub."""
return self._id
async def test_connection(self) -> bool:
await asyncio.sleep(1)
return True
class Board:
def __init__(self, hass, board_id: str, name: str,
email_address: str, password: str,
imap_server: str = "imap.gmail.com",
sender_address: str = "[email protected]") -> None:
"""Init."""
_LOGGER.warning("Start setup board")
self._id = board_id
self.name = name
self._callbacks = set()
self._loop = asyncio.get_event_loop()
self.email_address: str = email_address
self.password: str = password
self.imap_server: str = imap_server
self.sender_address: str = sender_address
self._production = 0
self._consumption = 0
self._own_consumption = 0
self._to_grid_today = 0
self._from_grid_today = 0
self._last_hash = '0'
self._link = '0'
def read_from_file(state):
try:
with open(f'{state}.txt', 'r') as f:
value = f.read()
except Exception as e:
value = 0
return value
self._old_id = read_from_file('_old_id')
self._production_total = round(float(read_from_file('_production_total')), 2)
self._consumption_total = round(float(read_from_file('_consumption_total')), 2)
self._own_consumption_total = round(float(read_from_file('_own_consumption_total')), 2)
self._to_grid_total = round(float(read_from_file('_to_grid_total')), 2)
self._from_grid_total = round(float(read_from_file('_from_grid_total')), 2)
self._compensated = round(float(read_from_file('_compensated')), 2)
self._to_compensate = round(float(self._consumption_total) - float(self._production_total) - float(self._compensated), 2)
self._hass = hass
self._tokens_to_burn = 0
#check new emails once a minute
self._unsub = async_track_time_interval(hass, self.check_new_mails, timedelta(minutes=30))
@to_thread
def get_tokens(self, energy, hass):
geo = hass.states.get('zone.home')
geo_str = f'{geo.attributes["latitude"]}, {geo.attributes["longitude"]}'
tokens_to_burn = get_tokens_to_burn(geo=geo_str, kwh=energy)
self._tokens_to_burn = tokens_to_burn
return tokens_to_burn
@to_thread
def parse_url(self, url):
data = pd.read_csv(url)
info = self.parse_report(data)
return info
def parse_report(self, data):
info = data.iloc[1][1:]
info = pd.to_numeric(info, errors='coerce')
info = info.apply(lambda x: x / 1000)
info = info.apply(lambda x: round(x, 2))
#pd.to_numeric(s, errors='coerce')
return info
async def check_new_mails(self, event):
try:
#_LOGGER.warning(f"Time changed: {event}")
imap = imaplib.IMAP4_SSL(self.imap_server)
imap.login(self.email_address, self.password)
imap.select("INBOX")
messages = imap.uid('search', "ALL", None, f'(FROM "{self.sender_address}")')
try:
last_id = messages[1][0].decode().split()[-1]
#_LOGGER.warning(f"ids: {last_id} last, old {self._old_id}")
with open('_old_id.txt', 'w') as f:
#uncomment +1 to test updating
f.write(str(int(last_id)))#+1))
if self._old_id == last_id:
return
else:
self._old_id = last_id
except Exception as e:
_LOGGER.error(f"Exception: no such letters: {e}")
return
type, data = imap.uid( "fetch" , str(last_id), 'RFC822')
#TODO correct regex
link_pattern = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')
text = data[0][1].decode('UTF-8')
# _LOGGER.warning(f"Text message: \n{text}")
text = text.split("href='")
url = text[1].split("'>Download")
url = url[0]
url.replace('\r\n', '')
# text = text.replace('\r\n', '').replace('3D', '').replace('a=', 'a')
# search = link_pattern.search(text)
# url = search.group(0).rstrip("'>Download</a></td></tr></table><br")
_LOGGER.error(f"Link: {url}")
#_LOGGER.warning(f"{url}")
try:
[self._production, self._consumption, self._own_consumption, self._to_grid_today, self._from_grid_today] = await self.parse_url(url)
_LOGGER.warning(f"New data!")
except Exception as e:
_LOGGER.error(f"Error in parsing: {e}")
def write_to_file(state, file):
with open(f'{file}.txt', 'w') as f:
f.write(str(state))
self._production_total = float(self._production_total) + float(self._production)
self._consumption_total = float(self._consumption_total) + float(self._consumption)
self._own_consumption_total = float(self._own_consumption_total) + float(self._own_consumption)
self._to_grid_total = float(self._to_grid_total) + float(self._to_grid_today)
self._from_grid_total = float(self._from_grid_total) + float(self._from_grid_today)
self._to_compensate = round(float(self._consumption_total) - float(self._production_total) - float(self._compensated), 2)
geo = self._hass.states.get('zone.home')
geo_str = f'{geo.attributes["latitude"]}, {geo.attributes["longitude"]}'
self._tokens_to_burn = round(await get_tokens_to_burn_thread(self._to_compensate, geo_str) / 10 ** 9, 2)
_LOGGER.warning(f"Tokens calculated: {self._tokens_to_burn}")
write_to_file(self._production_total, '_production_total')
write_to_file(self._consumption_total, '_consumption_total')
write_to_file(self._own_consumption_total, '_own_consumption_total')
write_to_file(self._to_grid_total, '_to_grid_total')
write_to_file(self._from_grid_total, '_from_grid_total')
await self.publish_updates()
_LOGGER.warning(f"New energy states")
except Exception as e:
_LOGGER.error(f"Exception in check_new_mails: {e}")
@property
def board_id(self) -> str:
"""Return ID for board."""
return self._id
async def delayed_update(self) -> None:
"""Publish updates, with a random delay to emulate interaction with device."""
await asyncio.sleep(random.randint(1, 10))
await self.publish_updates()
def register_callback(self, callback: Callable[[], None]) -> None:
"""Register callback, called when board changes state."""
self._callbacks.add(callback)
def remove_callback(self, callback: Callable[[], None]) -> None:
"""Remove previously registered callback."""
self._callbacks.discard(callback)
async def publish_updates(self) -> None:
"""Schedule call all registered callbacks."""
for callback in self._callbacks:
callback()
@property
def online(self) -> float:
return True
@property
def battery_level(self) -> int:
"""Battery level as a percentage."""
return self._energy