Homevolt 0.2.4__py3-none-any.whl → 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
homevolt/device.py DELETED
@@ -1,804 +0,0 @@
1
- """Device class for Homevolt EMS devices."""
2
-
3
- from __future__ import annotations
4
-
5
- import logging
6
- from typing import Any
7
-
8
- import aiohttp
9
-
10
- from .const import (
11
- DEVICE_MAP,
12
- ENDPOINT_CONSOLE,
13
- ENDPOINT_EMS,
14
- ENDPOINT_PARAMS,
15
- ENDPOINT_SCHEDULE,
16
- SCHEDULE_TYPE,
17
- )
18
- from .exceptions import (
19
- HomevoltAuthenticationError,
20
- HomevoltConnectionError,
21
- HomevoltDataError,
22
- )
23
- from .models import DeviceMetadata, Sensor, SensorType
24
-
25
- _LOGGER = logging.getLogger(__name__)
26
-
27
-
28
- class Device:
29
- """Represents a Homevolt EMS device."""
30
-
31
- def __init__(
32
- self,
33
- base_url: str,
34
- password: str | None,
35
- websession: aiohttp.ClientSession,
36
- ) -> None:
37
- """Initialize the device.
38
-
39
- Args:
40
- base_url: Base URL of the Homevolt device (e.g., http://192.168.1.100)
41
- password: Optional password for authentication
42
- websession: aiohttp ClientSession for making requests
43
- """
44
- self.base_url = base_url
45
- self._password = password
46
- self._websession = websession
47
- self._auth = aiohttp.BasicAuth("admin", password) if password else None
48
-
49
- self.device_id: str | None = None
50
- self.sensors: dict[str, Sensor] = {}
51
- self.device_metadata: dict[str, DeviceMetadata] = {}
52
- self.current_schedule: dict[str, Any] | None = None
53
-
54
- async def update_info(self) -> None:
55
- """Fetch and update all device information."""
56
- await self.fetch_ems_data()
57
- await self.fetch_schedule_data()
58
-
59
- async def fetch_ems_data(self) -> None:
60
- """Fetch EMS data from the device."""
61
- try:
62
- url = f"{self.base_url}{ENDPOINT_EMS}"
63
- async with self._websession.get(url, auth=self._auth) as response:
64
- if response.status == 401:
65
- raise HomevoltAuthenticationError("Authentication failed")
66
- response.raise_for_status()
67
- ems_data = await response.json()
68
- except aiohttp.ClientError as err:
69
- raise HomevoltConnectionError(f"Failed to connect to device: {err}") from err
70
- except Exception as err:
71
- raise HomevoltDataError(f"Failed to parse EMS data: {err}") from err
72
-
73
- self._parse_ems_data(ems_data)
74
-
75
- async def fetch_schedule_data(self) -> None:
76
- """Fetch schedule data from the device."""
77
- try:
78
- url = f"{self.base_url}{ENDPOINT_SCHEDULE}"
79
- async with self._websession.get(url, auth=self._auth) as response:
80
- if response.status == 401:
81
- raise HomevoltAuthenticationError("Authentication failed")
82
- response.raise_for_status()
83
- schedule_data = await response.json()
84
- except aiohttp.ClientError as err:
85
- raise HomevoltConnectionError(f"Failed to connect to device: {err}") from err
86
- except Exception as err:
87
- raise HomevoltDataError(f"Failed to parse schedule data: {err}") from err
88
-
89
- self._parse_schedule_data(schedule_data)
90
-
91
- def _parse_ems_data(self, ems_data: dict[str, Any]) -> None:
92
- """Parse EMS JSON response."""
93
- if not ems_data.get("ems") or not ems_data["ems"]:
94
- raise HomevoltDataError("No EMS data found in response")
95
-
96
- device_id = str(ems_data["ems"][0]["ecu_id"])
97
- self.device_id = device_id
98
- ems_device_id = f"ems_{device_id}"
99
-
100
- # Initialize device metadata
101
- self.device_metadata = {
102
- ems_device_id: DeviceMetadata(name=f"Homevolt EMS {device_id}", model="Homevolt EMS"),
103
- "grid": DeviceMetadata(name="Homevolt Grid Sensor", model="Grid Sensor"),
104
- "solar": DeviceMetadata(name="Homevolt Solar Sensor", model="Solar Sensor"),
105
- "load": DeviceMetadata(name="Homevolt Load Sensor", model="Load Sensor"),
106
- }
107
-
108
- # Initialize sensors dictionary
109
- self.sensors = {}
110
-
111
- # EMS device sensors - all main EMS data
112
- ems = ems_data["ems"][0]
113
- self.sensors.update(
114
- {
115
- "L1 Voltage": Sensor(
116
- value=ems["ems_voltage"]["l1"] / 10,
117
- type=SensorType.VOLTAGE,
118
- device_identifier=ems_device_id,
119
- slug="l1_voltage",
120
- ),
121
- "L2 Voltage": Sensor(
122
- value=ems["ems_voltage"]["l2"] / 10,
123
- type=SensorType.VOLTAGE,
124
- device_identifier=ems_device_id,
125
- slug="l2_voltage",
126
- ),
127
- "L3 Voltage": Sensor(
128
- value=ems["ems_voltage"]["l3"] / 10,
129
- type=SensorType.VOLTAGE,
130
- device_identifier=ems_device_id,
131
- slug="l3_voltage",
132
- ),
133
- "L1_L2 Voltage": Sensor(
134
- value=ems["ems_voltage"]["l1_l2"] / 10,
135
- type=SensorType.VOLTAGE,
136
- device_identifier=ems_device_id,
137
- slug="l1_l2_voltage",
138
- ),
139
- "L2_L3 Voltage": Sensor(
140
- value=ems["ems_voltage"]["l2_l3"] / 10,
141
- type=SensorType.VOLTAGE,
142
- device_identifier=ems_device_id,
143
- slug="l2_l3_voltage",
144
- ),
145
- "L3_L1 Voltage": Sensor(
146
- value=ems["ems_voltage"]["l3_l1"] / 10,
147
- type=SensorType.VOLTAGE,
148
- device_identifier=ems_device_id,
149
- slug="l3_l1_voltage",
150
- ),
151
- "L1 Current": Sensor(
152
- value=ems["ems_current"]["l1"],
153
- type=SensorType.CURRENT,
154
- device_identifier=ems_device_id,
155
- slug="l1_current",
156
- ),
157
- "L2 Current": Sensor(
158
- value=ems["ems_current"]["l2"],
159
- type=SensorType.CURRENT,
160
- device_identifier=ems_device_id,
161
- slug="l2_current",
162
- ),
163
- "L3 Current": Sensor(
164
- value=ems["ems_current"]["l3"],
165
- type=SensorType.CURRENT,
166
- device_identifier=ems_device_id,
167
- slug="l3_current",
168
- ),
169
- "System Temperature": Sensor(
170
- value=ems["ems_data"]["sys_temp"] / 10.0,
171
- type=SensorType.TEMPERATURE,
172
- device_identifier=ems_device_id,
173
- slug="system_temperature",
174
- ),
175
- "Imported Energy": Sensor(
176
- value=ems["ems_aggregate"]["imported_kwh"],
177
- type=SensorType.ENERGY_INCREASING,
178
- device_identifier=ems_device_id,
179
- slug="imported_energy",
180
- ),
181
- "Exported Energy": Sensor(
182
- value=ems["ems_aggregate"]["exported_kwh"],
183
- type=SensorType.ENERGY_INCREASING,
184
- device_identifier=ems_device_id,
185
- slug="exported_energy",
186
- ),
187
- "Available Charging Power": Sensor(
188
- value=ems["ems_prediction"]["avail_ch_pwr"],
189
- type=SensorType.POWER,
190
- device_identifier=ems_device_id,
191
- slug="available_charging_power",
192
- ),
193
- "Available Discharge Power": Sensor(
194
- value=ems["ems_prediction"]["avail_di_pwr"],
195
- type=SensorType.POWER,
196
- device_identifier=ems_device_id,
197
- slug="available_discharge_power",
198
- ),
199
- "Available Charging Energy": Sensor(
200
- value=ems["ems_prediction"]["avail_ch_energy"],
201
- type=SensorType.ENERGY_TOTAL,
202
- device_identifier=ems_device_id,
203
- slug="available_charging_energy",
204
- ),
205
- "Available Discharge Energy": Sensor(
206
- value=ems["ems_prediction"]["avail_di_energy"],
207
- type=SensorType.ENERGY_TOTAL,
208
- device_identifier=ems_device_id,
209
- slug="available_discharge_energy",
210
- ),
211
- "Power": Sensor(
212
- value=ems["ems_data"]["power"],
213
- type=SensorType.POWER,
214
- device_identifier=ems_device_id,
215
- slug="power",
216
- ),
217
- "Frequency": Sensor(
218
- value=ems["ems_data"]["frequency"],
219
- type=SensorType.FREQUENCY,
220
- device_identifier=ems_device_id,
221
- slug="frequency",
222
- ),
223
- "Battery State of Charge": Sensor(
224
- value=ems["ems_data"]["soc_avg"] / 100,
225
- type=SensorType.PERCENTAGE,
226
- device_identifier=ems_device_id,
227
- slug="battery_state_of_charge",
228
- ),
229
- }
230
- )
231
-
232
- # Battery sensors
233
- for bat_id, battery in enumerate(ems.get("bms_data", [])):
234
- battery_device_id = f"battery_{bat_id}"
235
- self.device_metadata[battery_device_id] = DeviceMetadata(
236
- name=f"Homevolt Battery {bat_id}",
237
- model="Homevolt Battery",
238
- )
239
- if "soc" in battery:
240
- self.sensors[f"Homevolt battery {bat_id}"] = Sensor(
241
- value=battery["soc"] / 100,
242
- type=SensorType.PERCENTAGE,
243
- device_identifier=battery_device_id,
244
- slug="battery_state_of_charge",
245
- )
246
- if "tmin" in battery:
247
- self.sensors[f"Homevolt battery {bat_id} tmin"] = Sensor(
248
- value=battery["tmin"] / 10,
249
- type=SensorType.TEMPERATURE,
250
- device_identifier=battery_device_id,
251
- slug="tmin",
252
- )
253
- if "tmax" in battery:
254
- self.sensors[f"Homevolt battery {bat_id} tmax"] = Sensor(
255
- value=battery["tmax"] / 10,
256
- type=SensorType.TEMPERATURE,
257
- device_identifier=battery_device_id,
258
- slug="tmax",
259
- )
260
- if "cycle_count" in battery:
261
- self.sensors[f"Homevolt battery {bat_id} charge cycles"] = Sensor(
262
- value=battery["cycle_count"],
263
- type=SensorType.COUNT,
264
- device_identifier=battery_device_id,
265
- slug="charge_cycles",
266
- )
267
- if "voltage" in battery:
268
- self.sensors[f"Homevolt battery {bat_id} voltage"] = Sensor(
269
- value=battery["voltage"] / 100,
270
- type=SensorType.VOLTAGE,
271
- device_identifier=battery_device_id,
272
- slug="voltage",
273
- )
274
- if "current" in battery:
275
- self.sensors[f"Homevolt battery {bat_id} current"] = Sensor(
276
- value=battery["current"],
277
- type=SensorType.CURRENT,
278
- device_identifier=battery_device_id,
279
- slug="current",
280
- )
281
- if "power" in battery:
282
- self.sensors[f"Homevolt battery {bat_id} power"] = Sensor(
283
- value=battery["power"],
284
- type=SensorType.POWER,
285
- device_identifier=battery_device_id,
286
- slug="power",
287
- )
288
- if "soh" in battery:
289
- self.sensors[f"Homevolt battery {bat_id} soh"] = Sensor(
290
- value=battery["soh"] / 100,
291
- type=SensorType.PERCENTAGE,
292
- device_identifier=battery_device_id,
293
- slug="soh",
294
- )
295
-
296
- # External sensors (grid, solar, load)
297
- for sensor in ems_data.get("sensors", []):
298
- if not sensor.get("available"):
299
- continue
300
-
301
- sensor_type = sensor["type"]
302
- sensor_device_id = DEVICE_MAP.get(sensor_type)
303
-
304
- if not sensor_device_id:
305
- continue
306
-
307
- # Suffix for translation keys (e.g., "_grid", "_load")
308
- suffix = f"_{sensor_type}"
309
-
310
- # Calculate total power from all phases
311
- total_power = sum(phase["power"] for phase in sensor.get("phase", []))
312
-
313
- self.sensors[f"Power {sensor_type}"] = Sensor(
314
- value=total_power,
315
- type=SensorType.POWER,
316
- device_identifier=sensor_device_id,
317
- slug=f"power{suffix}",
318
- )
319
- self.sensors[f"Energy imported {sensor_type}"] = Sensor(
320
- value=sensor.get("energy_imported", 0),
321
- type=SensorType.ENERGY_INCREASING,
322
- device_identifier=sensor_device_id,
323
- slug=f"energy_imported{suffix}",
324
- )
325
- self.sensors[f"Energy exported {sensor_type}"] = Sensor(
326
- value=sensor.get("energy_exported", 0),
327
- type=SensorType.ENERGY_INCREASING,
328
- device_identifier=sensor_device_id,
329
- slug=f"energy_exported{suffix}",
330
- )
331
- self.sensors[f"RSSI {sensor_type}"] = Sensor(
332
- value=sensor.get("rssi"),
333
- type=SensorType.SIGNAL_STRENGTH,
334
- device_identifier=sensor_device_id,
335
- slug=f"rssi{suffix}",
336
- )
337
- self.sensors[f"Average RSSI {sensor_type}"] = Sensor(
338
- value=sensor.get("average_rssi"),
339
- type=SensorType.SIGNAL_STRENGTH,
340
- device_identifier=sensor_device_id,
341
- slug=f"average_rssi{suffix}",
342
- )
343
-
344
- # Phase-specific sensors
345
- for phase_name, phase in zip(["L1", "L2", "L3"], sensor.get("phase", [])):
346
- phase_lower = phase_name.lower()
347
- self.sensors[f"{phase_name} Voltage {sensor_type}"] = Sensor(
348
- value=phase.get("voltage"),
349
- type=SensorType.VOLTAGE,
350
- device_identifier=sensor_device_id,
351
- slug=f"{phase_lower}_voltage{suffix}",
352
- )
353
- self.sensors[f"{phase_name} Current {sensor_type}"] = Sensor(
354
- value=phase.get("amp"),
355
- type=SensorType.CURRENT,
356
- device_identifier=sensor_device_id,
357
- slug=f"{phase_lower}_current{suffix}",
358
- )
359
- self.sensors[f"{phase_name} Power {sensor_type}"] = Sensor(
360
- value=phase.get("power"),
361
- type=SensorType.POWER,
362
- device_identifier=sensor_device_id,
363
- slug=f"{phase_lower}_power{suffix}",
364
- )
365
-
366
- def _parse_schedule_data(self, schedule_data: dict[str, Any]) -> None:
367
- """Parse schedule JSON response."""
368
- self.current_schedule = schedule_data
369
-
370
- if not self.device_id:
371
- return
372
-
373
- ems_device_id = f"ems_{self.device_id}"
374
-
375
- self.sensors["Schedule id"] = Sensor(
376
- value=schedule_data.get("schedule_id"),
377
- type=SensorType.TEXT,
378
- device_identifier=ems_device_id,
379
- slug="schedule_id",
380
- )
381
-
382
- schedule = (
383
- schedule_data.get("schedule", [{}])[0]
384
- if schedule_data.get("schedule")
385
- else {"type": -1, "params": {}}
386
- )
387
-
388
- self.sensors["Schedule Type"] = Sensor(
389
- value=SCHEDULE_TYPE.get(schedule.get("type", -1)),
390
- type=SensorType.SCHEDULE_TYPE,
391
- device_identifier=ems_device_id,
392
- slug="schedule_type",
393
- )
394
- self.sensors["Schedule Power Setpoint"] = Sensor(
395
- value=schedule.get("params", {}).get("setpoint"),
396
- type=SensorType.POWER,
397
- device_identifier=ems_device_id,
398
- slug="schedule_power_setpoint",
399
- )
400
- self.sensors["Schedule Max Power"] = Sensor(
401
- value=schedule.get("max_charge"),
402
- type=SensorType.POWER,
403
- device_identifier=ems_device_id,
404
- slug="schedule_max_power",
405
- )
406
- self.sensors["Schedule Max Discharge"] = Sensor(
407
- value=schedule.get("max_discharge"),
408
- type=SensorType.POWER,
409
- device_identifier=ems_device_id,
410
- slug="schedule_max_discharge",
411
- )
412
-
413
- async def _execute_console_command(self, command: str) -> dict[str, Any]:
414
- """Execute a console command via the HTTP API.
415
-
416
- Args:
417
- command: The console command to execute
418
-
419
- Returns:
420
- The JSON response from the console endpoint
421
-
422
- Raises:
423
- HomevoltConnectionError: If connection fails
424
- HomevoltAuthenticationError: If authentication fails
425
- HomevoltDataError: If response parsing fails
426
- """
427
- try:
428
- url = f"{self.base_url}{ENDPOINT_CONSOLE}"
429
- async with self._websession.post(
430
- url,
431
- auth=self._auth,
432
- json={"cmd": command},
433
- ) as response:
434
- if response.status == 401:
435
- raise HomevoltAuthenticationError("Authentication failed")
436
- response.raise_for_status()
437
- return await response.json()
438
- except aiohttp.ClientError as err:
439
- raise HomevoltConnectionError(f"Failed to execute command: {err}") from err
440
- except Exception as err:
441
- raise HomevoltDataError(f"Failed to parse command response: {err}") from err
442
-
443
- async def set_battery_mode(
444
- self,
445
- mode: int,
446
- *,
447
- setpoint: int | None = None,
448
- max_charge: int | None = None,
449
- max_discharge: int | None = None,
450
- min_soc: int | None = None,
451
- max_soc: int | None = None,
452
- offline: bool = False,
453
- ) -> dict[str, Any]:
454
- """Set immediate battery control mode.
455
-
456
- Args:
457
- mode: Schedule type (0=Idle, 1=Inverter Charge, 2=Inverter Discharge,
458
- 3=Grid Charge, 4=Grid Discharge, 5=Grid Charge/Discharge,
459
- 6=Frequency Reserve, 7=Solar Charge, 8=Solar Charge/Discharge,
460
- 9=Full Solar Export)
461
- setpoint: Power setpoint in Watts (for grid modes)
462
- max_charge: Maximum charge power in Watts
463
- max_discharge: Maximum discharge power in Watts
464
- min_soc: Minimum state of charge percentage
465
- max_soc: Maximum state of charge percentage
466
- offline: Take inverter offline during idle mode
467
-
468
- Returns:
469
- Response from the console command
470
-
471
- Raises:
472
- HomevoltConnectionError: If connection fails
473
- HomevoltAuthenticationError: If authentication fails
474
- HomevoltDataError: If command execution fails
475
- """
476
- if mode not in SCHEDULE_TYPE:
477
- raise ValueError(f"Invalid mode: {mode}. Must be 0-9")
478
-
479
- cmd_parts = [f"sched_set {mode}"]
480
-
481
- if setpoint is not None:
482
- cmd_parts.append(f"-s {setpoint}")
483
- if max_charge is not None:
484
- cmd_parts.append(f"-c {max_charge}")
485
- if max_discharge is not None:
486
- cmd_parts.append(f"-d {max_discharge}")
487
- if min_soc is not None:
488
- cmd_parts.append(f"--min {min_soc}")
489
- if max_soc is not None:
490
- cmd_parts.append(f"--max {max_soc}")
491
- if offline:
492
- cmd_parts.append("-o")
493
-
494
- command = " ".join(cmd_parts)
495
- return await self._execute_console_command(command)
496
-
497
- async def add_schedule(
498
- self,
499
- mode: int,
500
- *,
501
- from_time: str | None = None,
502
- to_time: str | None = None,
503
- setpoint: int | None = None,
504
- max_charge: int | None = None,
505
- max_discharge: int | None = None,
506
- min_soc: int | None = None,
507
- max_soc: int | None = None,
508
- offline: bool = False,
509
- ) -> dict[str, Any]:
510
- """Add a scheduled battery control entry.
511
-
512
- Args:
513
- mode: Schedule type (0=Idle, 1=Inverter Charge, 2=Inverter Discharge,
514
- 3=Grid Charge, 4=Grid Discharge, 5=Grid Charge/Discharge,
515
- 6=Frequency Reserve, 7=Solar Charge, 8=Solar Charge/Discharge,
516
- 9=Full Solar Export)
517
- from_time: Start time in ISO format (YYYY-MM-DDTHH:mm:ss)
518
- to_time: End time in ISO format (YYYY-MM-DDTHH:mm:ss)
519
- setpoint: Power setpoint in Watts (for grid modes)
520
- max_charge: Maximum charge power in Watts
521
- max_discharge: Maximum discharge power in Watts
522
- min_soc: Minimum state of charge percentage
523
- max_soc: Maximum state of charge percentage
524
- offline: Take inverter offline during idle mode
525
-
526
- Returns:
527
- Response from the console command
528
-
529
- Raises:
530
- HomevoltConnectionError: If connection fails
531
- HomevoltAuthenticationError: If authentication fails
532
- HomevoltDataError: If command execution fails
533
- """
534
- if mode not in SCHEDULE_TYPE:
535
- raise ValueError(f"Invalid mode: {mode}. Must be 0-9")
536
-
537
- cmd_parts = [f"sched_add {mode}"]
538
-
539
- if from_time:
540
- cmd_parts.append(f"--from {from_time}")
541
- if to_time:
542
- cmd_parts.append(f"--to {to_time}")
543
- if setpoint is not None:
544
- cmd_parts.append(f"-s {setpoint}")
545
- if max_charge is not None:
546
- cmd_parts.append(f"-c {max_charge}")
547
- if max_discharge is not None:
548
- cmd_parts.append(f"-d {max_discharge}")
549
- if min_soc is not None:
550
- cmd_parts.append(f"--min {min_soc}")
551
- if max_soc is not None:
552
- cmd_parts.append(f"--max {max_soc}")
553
- if offline:
554
- cmd_parts.append("-o")
555
-
556
- command = " ".join(cmd_parts)
557
- return await self._execute_console_command(command)
558
-
559
- async def delete_schedule(self, schedule_id: int) -> dict[str, Any]:
560
- """Delete a schedule by ID.
561
-
562
- Args:
563
- schedule_id: The ID of the schedule to delete
564
-
565
- Returns:
566
- Response from the console command
567
-
568
- Raises:
569
- HomevoltConnectionError: If connection fails
570
- HomevoltAuthenticationError: If authentication fails
571
- HomevoltDataError: If command execution fails
572
- """
573
- return await self._execute_console_command(f"sched_del {schedule_id}")
574
-
575
- async def clear_all_schedules(self) -> dict[str, Any]:
576
- """Clear all schedules.
577
-
578
- Returns:
579
- Response from the console command
580
-
581
- Raises:
582
- HomevoltConnectionError: If connection fails
583
- HomevoltAuthenticationError: If authentication fails
584
- HomevoltDataError: If command execution fails
585
- """
586
- return await self._execute_console_command("sched_clear")
587
-
588
- async def enable_local_mode(self) -> dict[str, Any]:
589
- """Enable local mode to prevent remote schedule overrides.
590
-
591
- When enabled, remote schedules from Tibber/partners via MQTT will be blocked,
592
- and only local schedules will be used.
593
-
594
- Returns:
595
- Response from the params endpoint
596
-
597
- Raises:
598
- HomevoltConnectionError: If connection fails
599
- HomevoltAuthenticationError: If authentication fails
600
- HomevoltDataError: If parameter setting fails
601
- """
602
- return await self.set_parameter("settings_local", 1)
603
-
604
- async def disable_local_mode(self) -> dict[str, Any]:
605
- """Disable local mode to allow remote schedule overrides.
606
-
607
- When disabled, remote schedules from Tibber/partners via MQTT will replace
608
- local schedules.
609
-
610
- Returns:
611
- Response from the params endpoint
612
-
613
- Raises:
614
- HomevoltConnectionError: If connection fails
615
- HomevoltAuthenticationError: If authentication fails
616
- HomevoltDataError: If parameter setting fails
617
- """
618
- return await self.set_parameter("settings_local", 0)
619
-
620
- async def set_parameter(self, key: str, value: Any) -> dict[str, Any]:
621
- """Set a device parameter.
622
-
623
- Args:
624
- key: Parameter name
625
- value: Parameter value
626
-
627
- Returns:
628
- Response from the params endpoint
629
-
630
- Raises:
631
- HomevoltConnectionError: If connection fails
632
- HomevoltAuthenticationError: If authentication fails
633
- HomevoltDataError: If parameter setting fails
634
- """
635
- try:
636
- url = f"{self.base_url}{ENDPOINT_PARAMS}"
637
- async with self._websession.post(
638
- url,
639
- auth=self._auth,
640
- json={key: value},
641
- ) as response:
642
- if response.status == 401:
643
- raise HomevoltAuthenticationError("Authentication failed")
644
- response.raise_for_status()
645
- return await response.json()
646
- except aiohttp.ClientError as err:
647
- raise HomevoltConnectionError(f"Failed to set parameter: {err}") from err
648
- except Exception as err:
649
- raise HomevoltDataError(f"Failed to parse parameter response: {err}") from err
650
-
651
- async def get_parameter(self, key: str) -> Any:
652
- """Get a device parameter value.
653
-
654
- Args:
655
- key: Parameter name
656
-
657
- Returns:
658
- Parameter value
659
-
660
- Raises:
661
- HomevoltConnectionError: If connection fails
662
- HomevoltAuthenticationError: If authentication fails
663
- HomevoltDataError: If parameter retrieval fails
664
- """
665
- try:
666
- url = f"{self.base_url}{ENDPOINT_PARAMS}"
667
- async with self._websession.get(url, auth=self._auth) as response:
668
- if response.status == 401:
669
- raise HomevoltAuthenticationError("Authentication failed")
670
- response.raise_for_status()
671
- params = await response.json()
672
- return params.get(key)
673
- except aiohttp.ClientError as err:
674
- raise HomevoltConnectionError(f"Failed to get parameter: {err}") from err
675
- except Exception as err:
676
- raise HomevoltDataError(f"Failed to parse parameter response: {err}") from err
677
-
678
- async def charge_battery(
679
- self,
680
- *,
681
- max_power: int | None = None,
682
- max_soc: int | None = None,
683
- min_soc: int | None = None,
684
- ) -> dict[str, Any]:
685
- """Charge battery using inverter (immediate).
686
-
687
- Args:
688
- max_power: Maximum charge power in Watts
689
- max_soc: Maximum state of charge percentage (stops at this level)
690
- min_soc: Minimum state of charge percentage (only charges if below this)
691
-
692
- Returns:
693
- Response from the console command
694
- """
695
- return await self.set_battery_mode(
696
- 1, # Inverter Charge
697
- max_charge=max_power,
698
- max_soc=max_soc,
699
- min_soc=min_soc,
700
- )
701
-
702
- async def discharge_battery(
703
- self,
704
- *,
705
- max_power: int | None = None,
706
- min_soc: int | None = None,
707
- max_soc: int | None = None,
708
- ) -> dict[str, Any]:
709
- """Discharge battery using inverter (immediate).
710
-
711
- Args:
712
- max_power: Maximum discharge power in Watts
713
- min_soc: Minimum state of charge percentage (stops at this level)
714
- max_soc: Maximum state of charge percentage (only discharges if above this)
715
-
716
- Returns:
717
- Response from the console command
718
- """
719
- return await self.set_battery_mode(
720
- 2, # Inverter Discharge
721
- max_discharge=max_power,
722
- min_soc=min_soc,
723
- max_soc=max_soc,
724
- )
725
-
726
- async def set_battery_idle(self, *, offline: bool = False) -> dict[str, Any]:
727
- """Set battery to idle mode (immediate).
728
-
729
- Args:
730
- offline: If True, take inverter offline during idle
731
-
732
- Returns:
733
- Response from the console command
734
- """
735
- return await self.set_battery_mode(0, offline=offline)
736
-
737
- async def charge_from_grid(
738
- self,
739
- *,
740
- setpoint: int,
741
- max_power: int | None = None,
742
- max_soc: int | None = None,
743
- ) -> dict[str, Any]:
744
- """Charge battery from grid with power setpoint (immediate).
745
-
746
- Args:
747
- setpoint: Power setpoint in Watts
748
- max_power: Maximum charge power in Watts
749
- max_soc: Maximum state of charge percentage
750
-
751
- Returns:
752
- Response from the console command
753
- """
754
- return await self.set_battery_mode(
755
- 3, # Grid Charge
756
- setpoint=setpoint,
757
- max_charge=max_power,
758
- max_soc=max_soc,
759
- )
760
-
761
- async def discharge_to_grid(
762
- self,
763
- *,
764
- setpoint: int,
765
- max_power: int | None = None,
766
- min_soc: int | None = None,
767
- ) -> dict[str, Any]:
768
- """Discharge battery to grid with power setpoint (immediate).
769
-
770
- Args:
771
- setpoint: Power setpoint in Watts
772
- max_power: Maximum discharge power in Watts
773
- min_soc: Minimum state of charge percentage
774
-
775
- Returns:
776
- Response from the console command
777
- """
778
- return await self.set_battery_mode(
779
- 4, # Grid Discharge
780
- setpoint=setpoint,
781
- max_discharge=max_power,
782
- min_soc=min_soc,
783
- )
784
-
785
- async def charge_from_solar(
786
- self,
787
- *,
788
- max_power: int | None = None,
789
- max_soc: int | None = None,
790
- ) -> dict[str, Any]:
791
- """Charge battery from solar only (immediate).
792
-
793
- Args:
794
- max_power: Maximum charge power in Watts
795
- max_soc: Maximum state of charge percentage
796
-
797
- Returns:
798
- Response from the console command
799
- """
800
- return await self.set_battery_mode(
801
- 7, # Solar Charge
802
- max_charge=max_power,
803
- max_soc=max_soc,
804
- )