-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolaar_eric.py
More file actions
373 lines (304 loc) · 14.5 KB
/
Copy pathsolaar_eric.py
File metadata and controls
373 lines (304 loc) · 14.5 KB
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import socket
import struct
import xml.etree.ElementTree as ET
import time
import requests
import logging
import json
import os
from dotenv import load_dotenv
import asyncio
from telegram import Bot
# -----------------------------------------------------------
# CONFIGURAZIONE
# -----------------------------------------------------------
MCAST_GRP = '224.192.32.19'
MCAST_PORT = 22600
IFACE = '192.168.1.193'
WALLBOX_IP = '192.168.1.22'
WALLBOX_URL = f"http://{WALLBOX_IP}/index.json"
ULTIMA_LETTURA_FASI = None
ULTIMA_LETTURA_SOLARE = None
ULTIME_5_LETTURE_FASI = []
ULTIME_5_LETTURE_SOLARE = []
#parametri fasi
MONOFASE_MIN_POWER = 1380 #6A
MONOFASE_MAX_POWER = 7360 #32A
TRIFASE_MIN_POWER = 4140 #6A
TRIFASE_MAX_POWER = 22000 #32A
POTENZA_PROTEZIONE = 300
COOLDOWN_ACCENSIONE = 60
POTENZA_PRELEVABILE = 0
UPDATE_INTERVAL_S = 5
TIMER_SPEGNIMENTO = 60
load_dotenv()
API_KEY = os.getenv('API_KEY')
CHAT_ID = os.getenv('CHAT_ID')
logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(message)s', datefmt='%H:%M:%S')
# -----------------------------------------------------------
# GESTORE WALLBOX
# -----------------------------------------------------------
class WallboxController:
def __init__(self):
self.current_set_power = 0
self.is_on = False
self.last_update_time = 0
self.fase = 0
self.time_turned_off = 0
self.pending_off_until = 0
def send_command(self, params):
try:
response = requests.get(WALLBOX_URL, params=params, timeout=3)
return response.status_code == 200
except Exception:
return False
def set_power(self, watts):
if self.fase == 0:
watts = max(MONOFASE_MIN_POWER, min(MONOFASE_MAX_POWER, int(watts)))
elif self.fase == 1:
watts = max(TRIFASE_MIN_POWER, min(TRIFASE_MAX_POWER, int(watts)))
if abs(watts - self.current_set_power) < POTENZA_PROTEZIONE and self.is_on:
print(f"[INFO] Variazione potenza ({watts}W) inferiore alla soglia di protezione ({POTENZA_PROTEZIONE}W). Nessun cambiamento.")
return
now = time.time()
if self.last_update_time > 0 and (now - self.last_update_time < UPDATE_INTERVAL_S):
return
print(f"[AZIONE] CAMBIO POTENZA -> {watts} W")
if self.send_command({'btn': f'P{watts}'}):
self.current_set_power = watts
self.last_update_time = now
def turn_on(self):
if not self.is_on:
if self.time_turned_off > 0:
tempo_trascorso = time.time() - self.time_turned_off
if tempo_trascorso < COOLDOWN_ACCENSIONE: #almeno 1 min
print(f"[INFO] Attesa cooldown: {COOLDOWN_ACCENSIONE - tempo_trascorso:.1f}s prima di accendere")
return
print("[AZIONE] ACCENSIONE (ON)")
self.set_power(MONOFASE_MIN_POWER if self.fase == 0 else TRIFASE_MIN_POWER)
if self.send_command({'btn': 'i'}):
self.is_on = True
self.last_update_time = time.time()
def turn_off(self, force=False):
now = time.time()
if force and self.last_update_time != 0 and (now - self.last_update_time < UPDATE_INTERVAL_S):
return
if self.is_on or force:
print("[AZIONE] SPEGNIMENTO (OFF)")
if self.send_command({'btn': 'o'}):
self.is_on = False
self.time_turned_off = time.time()
self.last_update_time = time.time()
time.sleep(0.5)
self.send_command({'btn': f'P{MONOFASE_MIN_POWER if self.fase == 0 else TRIFASE_MIN_POWER}'})
self.current_set_power = MONOFASE_MIN_POWER if self.fase == 0 else TRIFASE_MIN_POWER
def initialize(self):
print("\n=== INIZIALIZZAZIONE SISTEMA ===")
try:
print(f"Richiesta dati a {WALLBOX_URL}...")
response = requests.get(WALLBOX_URL, timeout=5)
if response.status_code == 200:
dati = response.json()
valore_fase = dati.get("tfase")
if valore_fase == "1":
modalita = "TRIFASE"
self.fase = 1
else:
modalita = "MONOFASE"
self.fase = 0
print("\n--------------------------------")
print(f"TIPO IMPIANTO: {modalita}")
print("--------------------------------")
else:
print(f"Errore. centralina codice: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"Errore di connessione: {e}")
except json.JSONDecodeError:
print("Errore: La risposta del server non è un JSON valido.")
print("1. Metto in OFF (Attesa dati)...")
self.last_update_time = 0
self.turn_off(force=True)
if self.fase == 0:
print("1. Imposto potenza minima (1380W)...")
self.set_power(MONOFASE_MIN_POWER)
elif self.fase == 1:
print("1. Imposto potenza minima (4140)...")
self.set_power(TRIFASE_MIN_POWER)
time.sleep(1)
print("=== PRONTO. IN ATTESA PACCHETTI ===\n")
# -----------------------------------------------------------
# MONITOR DATI
# -----------------------------------------------------------
class EnergyMonitor:
def __init__(self):
self.solar_now = 0.0
self.total_grid_load = 0.0
self.fases = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
self.ctrletturefasi = 0
self.time = None
def parse_packet(self, data):
try:
xml_str = data.decode('utf-8', errors='ignore')
root = ET.fromstring(xml_str)
if root.tag == 'electricity':#fasi
channels = root.find('channels')
if channels:
p = {}
for c in channels.findall('chan'):
try:
val = float(c.find('curr').text)
except:
val = 0.0
p[c.get('id')] = val
l1, l2, l3 = p.get('0',0), p.get('1',0), p.get('2',0)
l4, l5, l6 = p.get('3',0), p.get('4',0), p.get('5',0)
self.total_grid_load = l1 + l2 + l3
self.solar_now = l4 + l5 + l6
self.exporting = self.solar_now - self.total_grid_load
self.fases = [l1, l2, l3, l4, l5, l6]
print("\n" + "="*60)
print(f" ⚡ DATO FASI")
print("-" * 60)
print(f" | RETE (Casa+WB) | L1: {l1:5.0f} | L2: {l2:5.0f} | L3: {l3:5.0f} | TOT: {self.total_grid_load:.0f}W")
print(f" | SOLARE (Inv) | L4: {l4:5.0f} | L5: {l5:5.0f} | L6: {l6:5.0f} | TOT: {self.solar_now:.0f}W")
print("="*60)
print(f"")
self.ctrletturefasi += 1
ULTIMA_LETTURA_FASI = time.time()
self.time = ULTIMA_LETTURA_FASI
ULTIME_5_LETTURE_FASI.append((self.total_grid_load, self.solar_now, self.fases, self.time))
if len(ULTIME_5_LETTURE_FASI) > 5:
ULTIME_5_LETTURE_FASI.pop(0)
return "TRIGGER"
elif root.tag == 'solar':#generata
curr = root.find('current')
if curr is not None:
gen = float(curr.find('generating').text)
self.solar_now = gen
ULTIMA_LETTURA_SOLARE = time.time()
self.time = ULTIMA_LETTURA_SOLARE
ULTIME_5_LETTURE_SOLARE.append((gen, self.time))
if len(ULTIME_5_LETTURE_SOLARE) > 5:
ULTIME_5_LETTURE_SOLARE.pop(0)
return "TRIGGER"
except Exception:
pass
return None
# -----------------------------------------------------------
# LOGICA DI CONTROLLO
# -----------------------------------------------------------
def run_logic(monitor, wallbox):
potenza_generata = monitor.solar_now
potenza_consumata = monitor.total_grid_load
potenza_carica = wallbox.current_set_power if wallbox.is_on else 0
live = abs(potenza_consumata - potenza_carica) + potenza_carica if wallbox.is_on else potenza_consumata
potenza_consumata = live
potenza_generata += POTENZA_PRELEVABILE
potenza_esportata = potenza_generata - potenza_consumata
potenza_minima = MONOFASE_MIN_POWER if wallbox.fase == 0 else TRIFASE_MIN_POWER
potenza_massima = MONOFASE_MAX_POWER if wallbox.fase == 0 else TRIFASE_MAX_POWER
consumata_casa = monitor.total_grid_load - potenza_carica if wallbox.is_on else potenza_consumata
if potenza_consumata == 0:
print("[INFO] Dati casa non ancora disponibili. Attendo...")
return
print(f"\n[INFO] Potenza Generata (+ prelevabile: {POTENZA_PRELEVABILE}W): {potenza_generata:.0f}W | Potenza Consumata: {monitor.total_grid_load:.0f}W | Consumata Live: {live:.0f}W | Potenza Esportata: {potenza_esportata:.0f}W | Wallbox: {'ON' if wallbox.is_on else 'OFF'} ({wallbox.current_set_power:.0f}W)")
#annullo timer spegnimento
if wallbox.pending_off_until and potenza_generata >= potenza_minima:
print("[INFO] Generazione ripristinata. Annullamento spegnimento programmato.")
wallbox.pending_off_until = 0
if not wallbox.is_on:
if potenza_esportata > potenza_minima:
print(f"[DECISIONE] Potenza esportata ({potenza_esportata:.0f}W) sufficiente per accendere. Accendo a {potenza_minima}W.")
wallbox.turn_on()#accendo al minimo
return
if wallbox.is_on:
# Controlla timer di spegnimento programmato in primo luogo
now = time.time()
if wallbox.pending_off_until > 0:
if now < wallbox.pending_off_until:
restante = wallbox.pending_off_until - now
print(f"[INFO] Timer spegnimento attivo: {restante:.0f}s restanti...")
# Continua a controllare se la generazione si è ripresa
if potenza_generata >= potenza_minima:
print("[INFO] Generazione ripristinata durante l'attesa. Annullo spegnimento.")
wallbox.pending_off_until = 0
else:
return # Continua ad aspettare
else:
# Timer scaduto: re-valuta la situazione
wallbox.pending_off_until = 0
if potenza_generata < potenza_minima:
print(f"[DECISIONE] Dopo attesa, sole ancora insufficiente ({potenza_generata:.0f}W). Spengo.")
try:
asyncio.run(invia_notifica(f"⚠️ Attenzione! La potenza generata è insufficiente ({potenza_generata:.0f}W). Spengo il wallbox."))
if wallbox.fase == 1:
asyncio.run(invia_notifica(f"⚠️ Consiglio: mettere l'impianto in modalità monofase per sfruttare meglio la potenza disponibile."))
else:
asyncio.run(invia_notifica(f"⚠️ Consiglio: staccare la macchina"))
except Exception as e:
print(f"[ERRORE] Invio notifica fallito: {e}")
wallbox.turn_off(force=True)
return
else:
print(f"[DECISIONE] Dopo attesa, generazione sufficiente. Continuo a {potenza_minima}W.")
wallbox.set_power(potenza_minima)
return
# Logica normale (senza timer attivo)
if potenza_carica > potenza_generata or potenza_esportata < 0: #devo diminuire
nuova_potenza = potenza_carica - abs(potenza_esportata)
if nuova_potenza < potenza_minima or potenza_generata < potenza_minima:
print(f"[DECISIONE] Sole insufficiente ({potenza_generata:.0f}W). Messo al minimo per {TIMER_SPEGNIMENTO}s prima di spegnere.")
wallbox.set_power(potenza_minima)
wallbox.pending_off_until = now + TIMER_SPEGNIMENTO
else:
print(f"[DECISIONE] Diminuisco potenza a {nuova_potenza:.0f}W")
wallbox.set_power(nuova_potenza)
else: #posso aumentare
nuova_potenza = potenza_carica + abs(potenza_esportata)
if nuova_potenza > potenza_generata:
return
if nuova_potenza + consumata_casa > potenza_generata:
nuova_potenza = potenza_generata - consumata_casa
if nuova_potenza > potenza_massima:
nuova_potenza = potenza_massima
print(f"[DECISIONE] Aumento potenza a {nuova_potenza:.0f}W")
wallbox.set_power(nuova_potenza)
async def invia_notifica(messaggio):
bot = Bot(token=API_KEY)
await bot.send_message(chat_id=CHAT_ID, text=messaggio)
print(f"[INFO] Messaggio telegram ('{messaggio}') inviato correttamente!")
# -----------------------------------------------------------
# MAIN
# -----------------------------------------------------------
def main():
try:
asyncio.run(invia_notifica(f"SISTEMA AVVIATO. Inizializzazione in corso..."))
except Exception as e:
print(f"[ERRORE] Invio notifica avvio fallito: {e}")
monitor = EnergyMonitor()
wallbox = WallboxController()
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind((IFACE, MCAST_PORT))
mreq = struct.pack("4s4s", socket.inet_aton(MCAST_GRP), socket.inet_aton(IFACE))
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
print(f"In ascolto su {IFACE}:{MCAST_PORT}...")
except OSError as e:
logging.critical(f"Errore Rete (Bind): {e}")
return
wallbox.initialize()
while True:
try:
data, _ = sock.recvfrom(65535)
evt = monitor.parse_packet(data)
# La logica parte per OGNI pacchetto ricevuto
if evt == "TRIGGER":
run_logic(monitor, wallbox)
except KeyboardInterrupt:
wallbox.turn_off(force=True)
break
except Exception as e:
time.sleep(0.5)
if __name__ == "__main__":
main()