|
| 1 | +"""Service handlers for Growatt Server integration.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from datetime import datetime |
| 6 | +from typing import TYPE_CHECKING, Any |
| 7 | + |
| 8 | +from homeassistant.config_entries import ConfigEntryState |
| 9 | +from homeassistant.core import HomeAssistant, ServiceCall, SupportsResponse |
| 10 | +from homeassistant.exceptions import ServiceValidationError |
| 11 | +from homeassistant.helpers import device_registry as dr |
| 12 | + |
| 13 | +from .const import ( |
| 14 | + BATT_MODE_BATTERY_FIRST, |
| 15 | + BATT_MODE_GRID_FIRST, |
| 16 | + BATT_MODE_LOAD_FIRST, |
| 17 | + DOMAIN, |
| 18 | +) |
| 19 | + |
| 20 | +if TYPE_CHECKING: |
| 21 | + from .coordinator import GrowattCoordinator |
| 22 | + |
| 23 | + |
| 24 | +async def async_register_services(hass: HomeAssistant) -> None: |
| 25 | + """Register services for Growatt Server integration.""" |
| 26 | + |
| 27 | + def get_min_coordinators() -> dict[str, GrowattCoordinator]: |
| 28 | + """Get all MIN coordinators with V1 API from loaded config entries.""" |
| 29 | + min_coordinators: dict[str, GrowattCoordinator] = {} |
| 30 | + |
| 31 | + for entry in hass.config_entries.async_entries(DOMAIN): |
| 32 | + if entry.state != ConfigEntryState.LOADED: |
| 33 | + continue |
| 34 | + |
| 35 | + # Add MIN coordinators from this entry |
| 36 | + for coord in entry.runtime_data.devices.values(): |
| 37 | + if coord.device_type == "min" and coord.api_version == "v1": |
| 38 | + min_coordinators[coord.device_id] = coord |
| 39 | + |
| 40 | + return min_coordinators |
| 41 | + |
| 42 | + def get_coordinator(device_id: str) -> GrowattCoordinator: |
| 43 | + """Get coordinator by device_id. |
| 44 | +
|
| 45 | + Args: |
| 46 | + device_id: Device registry ID (not serial number) |
| 47 | + """ |
| 48 | + # Get current coordinators (they may have changed since service registration) |
| 49 | + min_coordinators = get_min_coordinators() |
| 50 | + |
| 51 | + if not min_coordinators: |
| 52 | + raise ServiceValidationError( |
| 53 | + "No MIN devices with token authentication are configured. " |
| 54 | + "Services require MIN devices with V1 API access." |
| 55 | + ) |
| 56 | + |
| 57 | + # Device registry ID provided - map to serial number |
| 58 | + device_registry = dr.async_get(hass) |
| 59 | + device_entry = device_registry.async_get(device_id) |
| 60 | + |
| 61 | + if not device_entry: |
| 62 | + raise ServiceValidationError(f"Device '{device_id}' not found") |
| 63 | + |
| 64 | + # Extract serial number from device identifiers |
| 65 | + serial_number = None |
| 66 | + for identifier in device_entry.identifiers: |
| 67 | + if identifier[0] == DOMAIN: |
| 68 | + serial_number = identifier[1] |
| 69 | + break |
| 70 | + |
| 71 | + if not serial_number: |
| 72 | + raise ServiceValidationError( |
| 73 | + f"Device '{device_id}' is not a Growatt device" |
| 74 | + ) |
| 75 | + |
| 76 | + # Find coordinator by serial number |
| 77 | + if serial_number not in min_coordinators: |
| 78 | + raise ServiceValidationError( |
| 79 | + f"MIN device '{serial_number}' not found or not configured for services" |
| 80 | + ) |
| 81 | + |
| 82 | + return min_coordinators[serial_number] |
| 83 | + |
| 84 | + async def handle_update_time_segment(call: ServiceCall) -> None: |
| 85 | + """Handle update_time_segment service call.""" |
| 86 | + segment_id: int = int(call.data["segment_id"]) |
| 87 | + batt_mode_str: str = call.data["batt_mode"] |
| 88 | + start_time_str: str = call.data["start_time"] |
| 89 | + end_time_str: str = call.data["end_time"] |
| 90 | + enabled: bool = call.data["enabled"] |
| 91 | + device_id: str = call.data["device_id"] |
| 92 | + |
| 93 | + # Validate segment_id range |
| 94 | + if not 1 <= segment_id <= 9: |
| 95 | + raise ServiceValidationError( |
| 96 | + f"segment_id must be between 1 and 9, got {segment_id}" |
| 97 | + ) |
| 98 | + |
| 99 | + # Validate and convert batt_mode string to integer |
| 100 | + valid_modes = { |
| 101 | + "load_first": BATT_MODE_LOAD_FIRST, |
| 102 | + "battery_first": BATT_MODE_BATTERY_FIRST, |
| 103 | + "grid_first": BATT_MODE_GRID_FIRST, |
| 104 | + } |
| 105 | + if batt_mode_str not in valid_modes: |
| 106 | + raise ServiceValidationError( |
| 107 | + f"batt_mode must be one of {list(valid_modes.keys())}, got '{batt_mode_str}'" |
| 108 | + ) |
| 109 | + batt_mode: int = valid_modes[batt_mode_str] |
| 110 | + |
| 111 | + # Convert time strings to datetime.time objects |
| 112 | + # UI time selector sends HH:MM:SS, but we only need HH:MM (strip seconds) |
| 113 | + try: |
| 114 | + # Take only HH:MM part (ignore seconds if present) |
| 115 | + start_parts = start_time_str.split(":") |
| 116 | + start_time_hhmm = f"{start_parts[0]}:{start_parts[1]}" |
| 117 | + start_time = datetime.strptime(start_time_hhmm, "%H:%M").time() |
| 118 | + except (ValueError, IndexError) as err: |
| 119 | + raise ServiceValidationError( |
| 120 | + "start_time must be in HH:MM or HH:MM:SS format" |
| 121 | + ) from err |
| 122 | + |
| 123 | + try: |
| 124 | + # Take only HH:MM part (ignore seconds if present) |
| 125 | + end_parts = end_time_str.split(":") |
| 126 | + end_time_hhmm = f"{end_parts[0]}:{end_parts[1]}" |
| 127 | + end_time = datetime.strptime(end_time_hhmm, "%H:%M").time() |
| 128 | + except (ValueError, IndexError) as err: |
| 129 | + raise ServiceValidationError( |
| 130 | + "end_time must be in HH:MM or HH:MM:SS format" |
| 131 | + ) from err |
| 132 | + |
| 133 | + # Get the appropriate MIN coordinator |
| 134 | + coordinator: GrowattCoordinator = get_coordinator(device_id) |
| 135 | + |
| 136 | + await coordinator.update_time_segment( |
| 137 | + segment_id, |
| 138 | + batt_mode, |
| 139 | + start_time, |
| 140 | + end_time, |
| 141 | + enabled, |
| 142 | + ) |
| 143 | + |
| 144 | + async def handle_read_time_segments(call: ServiceCall) -> dict[str, Any]: |
| 145 | + """Handle read_time_segments service call.""" |
| 146 | + device_id: str = call.data["device_id"] |
| 147 | + |
| 148 | + # Get the appropriate MIN coordinator |
| 149 | + coordinator: GrowattCoordinator = get_coordinator(device_id) |
| 150 | + |
| 151 | + time_segments: list[dict[str, Any]] = await coordinator.read_time_segments() |
| 152 | + |
| 153 | + return {"time_segments": time_segments} |
| 154 | + |
| 155 | + # Register services without schema - services.yaml will provide UI definition |
| 156 | + # Schema validation happens in the handler functions |
| 157 | + hass.services.async_register( |
| 158 | + DOMAIN, |
| 159 | + "update_time_segment", |
| 160 | + handle_update_time_segment, |
| 161 | + supports_response=SupportsResponse.NONE, |
| 162 | + ) |
| 163 | + |
| 164 | + hass.services.async_register( |
| 165 | + DOMAIN, |
| 166 | + "read_time_segments", |
| 167 | + handle_read_time_segments, |
| 168 | + supports_response=SupportsResponse.ONLY, |
| 169 | + ) |
0 commit comments