Lines 87.29% 158 / 181
Functions and Methods 78.72% 37 / 47
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
HaClient 87.29% 158 / 181 78.72% 37 / 47 127.62 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 fromConnectionConfig 100.00% 2 / 2 100.00% 1 / 1 1
 connect 100.00% 1 / 1 100.00% 1 / 1 1
 close 100.00% 1 / 1 100.00% 1 / 1 1
 isConnected 100.00% 1 / 1 100.00% 1 / 1 1
 onDisconnect 100.00% 1 / 1 100.00% 1 / 1 1
 getHaVersion 100.00% 1 / 1 100.00% 1 / 1 1
 flushEvents 100.00% 1 / 1 100.00% 1 / 1 1
 getStates 0.00% 0 / 6 0.00% 0 / 1 20
 getEntityRegistry 100.00% 7 / 7 100.00% 1 / 1 4
 getEntityRegistryEntry 100.00% 3 / 3 100.00% 1 / 1 2
 updateEntityRegistryEntry 100.00% 4 / 4 100.00% 1 / 1 2
 getAreaRegistry 100.00% 1 / 1 100.00% 1 / 1 1
 getFloorRegistry 100.00% 1 / 1 100.00% 1 / 1 1
 getLabelRegistry 100.00% 1 / 1 100.00% 1 / 1 1
 getDeviceRegistry 100.00% 1 / 1 100.00% 1 / 1 1
 getRegistry 100.00% 7 / 7 100.00% 1 / 1 1
 fetchCurrentUser 100.00% 1 / 1 100.00% 1 / 1 1
 getCurrentUserId 100.00% 1 / 1 100.00% 1 / 1 1
 getConfig 100.00% 1 / 1 100.00% 1 / 1 1
 getTimeZone 100.00% 1 / 1 100.00% 1 / 1 1
 getSiteSettings 100.00% 6 / 6 100.00% 1 / 1 3
 getServices 0.00% 0 / 1 0.00% 0 / 1 2
 callService 100.00% 11 / 11 100.00% 1 / 1 4
 fireEvent 100.00% 5 / 5 100.00% 1 / 1 3
 fetchHistory 100.00% 10 / 10 100.00% 1 / 1 6
 subscribeAllEvents 100.00% 1 / 1 100.00% 1 / 1 1
 subscribeStateUpdatesAndEvents 100.00% 1 / 1 100.00% 1 / 1 1
 subscribeTrigger 100.00% 9 / 9 100.00% 1 / 1 2
 findComponentVersion 80.00% 4 / 5 0.00% 0 / 1 4.13
 subscribeComponentSession 100.00% 9 / 9 100.00% 1 / 1 2
 answerComponentCommand 0.00% 0 / 6 0.00% 0 / 1 12
 upsertExposedEntity 0.00% 0 / 1 0.00% 0 / 1 2
 upsertExposedAction 0.00% 0 / 3 0.00% 0 / 1 6
 updateExposedEntityState 0.00% 0 / 1 0.00% 0 / 1 2
 removeExposedEntity 0.00% 0 / 2 0.00% 0 / 1 6
 reconcileExposedEntities 0.00% 0 / 1 0.00% 0 / 1 2
 unsubscribeEvents 100.00% 1 / 1 100.00% 1 / 1 1
 subscribeEventsWithStateDecoder 100.00% 11 / 11 100.00% 1 / 1 4
 subscribe 100.00% 5 / 5 100.00% 1 / 1 3
 decodeRows 100.00% 6 / 6 100.00% 1 / 1 4
 sendUnlessUnknown 100.00% 5 / 5 100.00% 1 / 1 4
 toHistoryException 100.00% 8 / 8 100.00% 1 / 1 6
 readEntityRegistryEntry 66.66% 2 / 3 0.00% 0 / 1 3.33
 toRegistryEditException 100.00% 8 / 8 100.00% 1 / 1 6
 toActionCallException 100.00% 12 / 12 100.00% 1 / 1 4
 toEventFireException 100.00% 6 / 6 100.00% 1 / 1 4
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Client;
6
7use Amp\Websocket\Client\WebsocketConnector;
8use Closure;
9use DateTimeZone;
10use Psr\Log\LoggerInterface;
11use Psr\Log\NullLogger;
12use Stewart\Client\Component\ComponentCommandAnswer;
13use Stewart\Client\Component\ComponentErrorCode;
14use Stewart\Client\Component\ComponentEventDecoder;
15use Stewart\Client\Component\ComponentSessionEvent;
16use Stewart\Client\Component\ComponentSessionRequest;
17use Stewart\Client\Component\ComponentVersion;
18use Stewart\Client\Component\ExposedEntityAddress;
19use Stewart\Client\Component\ExposedEntityDefinition;
20use Stewart\Client\Component\ExposedEntityReconcile;
21use Stewart\Client\Component\ExposedEntitySnapshotReader;
22use Stewart\Client\Component\ReconcileResultReader;
23use Stewart\Client\Connection\Command\CallService;
24use Stewart\Client\Connection\Command\Component\AnswerComponentCommand;
25use Stewart\Client\Connection\Command\Component\GetComponentVersion;
26use Stewart\Client\Connection\Command\Component\ReconcileExposedEntities;
27use Stewart\Client\Connection\Command\Component\RemoveExposedEntity;
28use Stewart\Client\Connection\Command\Component\SubscribeComponentSession;
29use Stewart\Client\Connection\Command\Component\UpdateExposedEntityState;
30use Stewart\Client\Connection\Command\Component\UpsertExposedEntity;
31use Stewart\Client\Connection\Command\FireEvent;
32use Stewart\Client\Connection\Command\GetAreaRegistry;
33use Stewart\Client\Connection\Command\GetConfig;
34use Stewart\Client\Connection\Command\GetCurrentUser;
35use Stewart\Client\Connection\Command\GetDeviceRegistry;
36use Stewart\Client\Connection\Command\GetEntityRegistry;
37use Stewart\Client\Connection\Command\GetEntityRegistryEntry;
38use Stewart\Client\Connection\Command\GetFloorRegistry;
39use Stewart\Client\Connection\Command\GetHistoryDuringPeriod;
40use Stewart\Client\Connection\Command\GetLabelRegistry;
41use Stewart\Client\Connection\Command\GetServices;
42use Stewart\Client\Connection\Command\GetStates;
43use Stewart\Client\Connection\Command\HaCommand;
44use Stewart\Client\Connection\Command\SubscribeEvents;
45use Stewart\Client\Connection\Command\SubscribeTrigger;
46use Stewart\Client\Connection\Command\SubscriptionCommand;
47use Stewart\Client\Connection\Command\UpdateEntityRegistryEntry;
48use Stewart\Client\Connection\ConnectionConfig;
49use Stewart\Client\Connection\HaConnection;
50use Stewart\Client\Event\EventDecoder;
51use Stewart\Client\Exception\HaClientError;
52use Stewart\Client\Exception\HaClientException;
53use Stewart\Client\Registry\Collection\EntityRegistryCollection;
54use Stewart\Client\Registry\EntityRegistryEntry;
55use Stewart\Client\Registry\RegistryDecoder;
56use Stewart\Client\State\EntityStateDecoder;
57use Stewart\Contracts\Action\ActionResponse;
58use Stewart\Contracts\Action\ActionTarget;
59use Stewart\Contracts\Entity\Collection\EntityIdCollection;
60use Stewart\Contracts\Entity\EntityId;
61use Stewart\Contracts\Event\HaEvent;
62use Stewart\Contracts\Exception\ActionCallException;
63use Stewart\Contracts\Exception\EventFireException;
64use Stewart\Contracts\Exception\HistoryError;
65use Stewart\Contracts\Exception\HistoryException;
66use Stewart\Contracts\Exception\IdentifierException;
67use Stewart\Contracts\Exception\RegistryEditException;
68use Stewart\Contracts\Exposure\ExposedEntitySnapshot;
69use Stewart\Contracts\Exposure\ExposedStateChange;
70use Stewart\Contracts\History\Collection\HistoricalStateCollection;
71use Stewart\Contracts\History\EntityStateHistory;
72use Stewart\Contracts\History\HistoryDetail;
73use Stewart\Contracts\History\HistoryWindow;
74use Stewart\Contracts\Registry\Collection\AreaCollection;
75use Stewart\Contracts\Registry\Collection\DeviceCollection;
76use Stewart\Contracts\Registry\Collection\FloorCollection;
77use Stewart\Contracts\Registry\Collection\LabelCollection;
78use Stewart\Contracts\Registry\Update\EntityRegistryUpdate;
79use Stewart\Contracts\State\Collection\EntityStateCollection;
80use Stewart\Contracts\State\EventContext;
81use Stewart\Contracts\State\StateChange;
82use Stewart\Contracts\Trigger\Collection\HaTriggerCollection;
83use Stewart\Contracts\Trigger\TriggerEvent;
84use Stewart\Support\Json\JsonShape;
85use Stewart\Support\State\IndexedRegistry;
86use Stewart\Support\State\StateUpdate;
87use Stewart\Support\Time\Deadlines;
88use Stewart\Support\Wire\EventPayload;
89
90final class HaClient
91{
92    private const string UNKNOWN_COMMAND_CODE = 'unknown_command';
93
94    private const string NOT_FOUND_CODE = 'not_found';
95
96    public function __construct(
97        private readonly HaConnection $connection,
98        private readonly EventDecoder $decoder,
99        private readonly EntityStateDecoder $states,
100        private readonly RegistryDecoder $registries,
101        private readonly ComponentEventDecoder $componentEvents,
102        private readonly LoggerInterface $logger = new NullLogger(),
103    ) {}
104
105    public static function fromConnectionConfig(
106        ConnectionConfig $config,
107        Deadlines $deadlines,
108        LoggerInterface $logger = new NullLogger(),
109        ?WebsocketConnector $connector = null,
110    ): self {
111        $states = new EntityStateDecoder($logger);
112
113        return new self(new HaConnection($config, $deadlines, $logger, $connector), new EventDecoder($states), $states, new RegistryDecoder($logger), new ComponentEventDecoder(), $logger);
114    }
115
116    public function connect(): void
117    {
118        $this->connection->connect();
119    }
120
121    public function close(): void
122    {
123        $this->connection->close();
124    }
125
126    public function isConnected(): bool
127    {
128        return $this->connection->isConnected();
129    }
130
131    /** @param Closure(HaClientException): void $handler */
132    public function onDisconnect(Closure $handler): void
133    {
134        $this->connection->onDisconnect($handler);
135    }
136
137    public function getHaVersion(): ?string
138    {
139        return $this->connection->haVersion;
140    }
141
142    public function flushEvents(): void
143    {
144        $this->connection->flushEvents();
145    }
146
147    public function getStates(): EntityStateCollection
148    {
149        $states = [];
150
151        foreach ($this->connection->send(new GetStates()) as $entry) {
152            $state = \is_array($entry) ? $this->states->decodeEntityStateOrSkip($entry) : null;
153
154            if ($state !== null) {
155                $states[] = $state;
156            }
157        }
158
159        return EntityStateCollection::keyedByEntityId($states);
160    }
161
162    public function getEntityRegistry(): EntityRegistryCollection
163    {
164        $entries = [];
165
166        foreach ($this->connection->send(new GetEntityRegistry()) as $entry) {
167            if (!\is_array($entry)) {
168                continue;
169            }
170
171            try {
172                $entries[] = EntityRegistryEntry::fromArray($entry);
173            } catch (IdentifierException $e) {
174                $this->logger->debug('Skipped an entity registry entry without a valid entity id', ['exception' => $e]);
175            }
176        }
177
178        return EntityRegistryCollection::keyedByEntityId($entries);
179    }
180
181    /** @throws RegistryEditException */
182    public function getEntityRegistryEntry(EntityId $entityId): EntityRegistryEntry
183    {
184        try {
185            return $this->readEntityRegistryEntry($this->connection->send(new GetEntityRegistryEntry($entityId)), 'config/entity_registry/get');
186        } catch (HaClientException $e) {
187            throw $this->toRegistryEditException($entityId, $e);
188        }
189    }
190
191    /** @throws RegistryEditException */
192    public function updateEntityRegistryEntry(EntityId $entityId, EntityRegistryUpdate $update): EntityRegistryEntry
193    {
194        try {
195            $result = $this->connection->send(new UpdateEntityRegistryEntry($entityId, $update));
196
197            return $this->readEntityRegistryEntry($result['entity_entry'] ?? null, 'config/entity_registry/update');
198        } catch (HaClientException $e) {
199            throw $this->toRegistryEditException($entityId, $e);
200        }
201    }
202
203    public function getAreaRegistry(): AreaCollection
204    {
205        return AreaCollection::keyedByAreaId($this->decodeRows($this->connection->send(new GetAreaRegistry()), $this->registries->decodeAreaOrSkip(...)));
206    }
207
208    public function getFloorRegistry(): FloorCollection
209    {
210        return FloorCollection::keyedByFloorId($this->decodeRows($this->sendUnlessUnknown(new GetFloorRegistry()), $this->registries->decodeFloorOrSkip(...)));
211    }
212
213    public function getLabelRegistry(): LabelCollection
214    {
215        return LabelCollection::keyedByLabelId($this->decodeRows($this->sendUnlessUnknown(new GetLabelRegistry()), $this->registries->decodeLabelOrSkip(...)));
216    }
217
218    public function getDeviceRegistry(): DeviceCollection
219    {
220        return DeviceCollection::keyedByDeviceId($this->decodeRows($this->connection->send(new GetDeviceRegistry()), $this->registries->decodeDeviceOrSkip(...)));
221    }
222
223    public function getRegistry(): IndexedRegistry
224    {
225        return IndexedRegistry::fromParts(
226            $this->getAreaRegistry(),
227            $this->getFloorRegistry(),
228            $this->getLabelRegistry(),
229            $this->getDeviceRegistry(),
230            $this->getEntityRegistry()->toRegisteredEntities(),
231        );
232    }
233
234    /** @throws HaClientException */
235    public function fetchCurrentUser(): HaUser
236    {
237        return HaUser::fromCurrentUserResult($this->connection->send(new GetCurrentUser()));
238    }
239
240    /** @throws HaClientException */
241    public function getCurrentUserId(): string
242    {
243        return $this->fetchCurrentUser()->id;
244    }
245
246    public function getConfig(): HaConfig
247    {
248        return HaConfig::fromGetConfigResult($this->connection->send(new GetConfig()));
249    }
250
251    public function getTimeZone(): DateTimeZone
252    {
253        return $this->getSiteSettings()->timeZone;
254    }
255
256    public function getSiteSettings(): HaSiteSettings
257    {
258        $config = $this->getConfig();
259
260        if ($config->timeZone === null && $config->timeZoneName !== null) {
261            $this->logger->warning('Home Assistant reported an unusable timezone; falling back to UTC.', [
262                'time_zone' => $config->timeZoneName,
263            ]);
264        }
265
266        return new HaSiteSettings($config->timeZone ?? new DateTimeZone('UTC'), $config->location);
267    }
268
269    /** @return array<string, mixed> */
270    public function getServices(): array
271    {
272        return JsonShape::treatKeysAsStrings($this->connection->send(new GetServices()));
273    }
274
275    /**
276     * @param array<string, mixed> $data
277     * @throws ActionCallException
278     */
279    public function callService(
280        string $domain,
281        string $service,
282        array $data = [],
283        ?ActionTarget $target = null,
284        bool $returnResponse = false,
285    ): ActionResponse {
286        try {
287            $result = $this->connection->send(new CallService($domain, $service, $data, $target, $returnResponse));
288        } catch (HaClientException $e) {
289            throw $this->toActionCallException($domain, $service, $e);
290        }
291
292        $response = $result['response'] ?? null;
293        $context = $result['context'] ?? null;
294
295        return new ActionResponse(
296            $domain,
297            $service,
298            \is_array($response) ? JsonShape::treatKeysAsStrings($response) : [],
299            \is_array($context) ? EventContext::fromArray($context) : null,
300        );
301    }
302
303    /** @throws EventFireException */
304    public function fireEvent(EventPayload $payload): EventContext
305    {
306        try {
307            $result = $this->connection->send(new FireEvent($payload));
308        } catch (HaClientException $e) {
309            throw $this->toEventFireException($payload->eventType, $e);
310        }
311
312        $context = $result['context'] ?? null;
313
314        return \is_array($context) ? EventContext::fromArray($context) : EventContext::unknown();
315    }
316
317    /** @throws HistoryException */
318    public function fetchHistory(EntityId $entityId, HistoryWindow $window, HistoryDetail $detail): EntityStateHistory
319    {
320        try {
321            $result = $this->connection->send(new GetHistoryDuringPeriod($entityId, $window, $detail));
322        } catch (HaClientException $e) {
323            throw $this->toHistoryException($entityId, $e);
324        }
325
326        $rows = $result[$entityId->value] ?? [];
327        $states = [];
328
329        foreach (\is_array($rows) ? $rows : [] as $row) {
330            $state = \is_array($row) ? $this->states->decodeCompressedHistoryRowOrSkip($entityId, $row) : null;
331
332            if ($state !== null) {
333                $states[] = $state;
334            }
335        }
336
337        return new EntityStateHistory($entityId, $window, HistoricalStateCollection::fromList($states));
338    }
339
340    /**
341     * @param Closure(StateChange): void $onStateChange
342     * @param Closure(HaEvent): void $onEvent
343     * @throws HaClientException
344     */
345    public function subscribeAllEvents(Closure $onStateChange, Closure $onEvent): int
346    {
347        return $this->subscribeEventsWithStateDecoder($this->decoder->decodeStateChange(...), $onStateChange, $onEvent);
348    }
349
350    /**
351     * @internal
352     * @param Closure(StateUpdate): void $onStateUpdate
353     * @param Closure(HaEvent): void $onEvent
354     * @throws HaClientException
355     */
356    public function subscribeStateUpdatesAndEvents(Closure $onStateUpdate, Closure $onEvent): int
357    {
358        return $this->subscribeEventsWithStateDecoder($this->decoder->decodeStateUpdate(...), $onStateUpdate, $onEvent);
359    }
360
361    /**
362     * @param array<string, mixed> $variables
363     * @param Closure(TriggerEvent): void $onTrigger
364     * @throws HaClientException
365     */
366    public function subscribeTrigger(HaTriggerCollection $triggers, array $variables, Closure $onTrigger): int
367    {
368        $decoder = $this->decoder;
369        $logger = $this->logger;
370
371        return $this->subscribe(new SubscribeTrigger($triggers, $variables), static function (array $event) use ($decoder, $logger, $onTrigger): void {
372            $decoded = $decoder->decodeTriggerEvent($event);
373
374            if ($decoded === null) {
375                $logger->warning('Skipped a trigger event without variables.trigger');
376
377                return;
378            }
379
380            $onTrigger($decoded);
381        });
382    }
383
384    /** @throws HaClientException */
385    public function findComponentVersion(): ?ComponentVersion
386    {
387        try {
388            return ComponentVersion::fromVersionResult($this->connection->send(new GetComponentVersion()));
389        } catch (HaClientException $e) {
390            if ($e->reason === HaClientError::CommandRejected && $e->findErrorCode() === self::UNKNOWN_COMMAND_CODE) {
391                return null;
392            }
393
394            throw $e;
395        }
396    }
397
398    /**
399     * @param Closure(ComponentSessionEvent): void $onEvent
400     * @throws HaClientException
401     */
402    public function subscribeComponentSession(ComponentSessionRequest $request, Closure $onEvent): int
403    {
404        $decoder = $this->componentEvents;
405        $logger = $this->logger;
406
407        return $this->subscribe(new SubscribeComponentSession($request), static function (array $event) use ($decoder, $logger, $onEvent): void {
408            $decoded = $decoder->decodeSessionEvent($event);
409
410            if ($decoded === null) {
411                $logger->debug('Skipped a Stewart component event of an unknown type', ['type' => $event['type'] ?? null]);
412
413                return;
414            }
415
416            $onEvent($decoded);
417        });
418    }
419
420    /** @throws HaClientException */
421    public function answerComponentCommand(ComponentCommandAnswer $answer): bool
422    {
423        try {
424            $this->connection->sendIgnoringResult(new AnswerComponentCommand($answer));
425        } catch (HaClientException $e) {
426            if (ComponentErrorCode::tryFromException($e) === ComponentErrorCode::NotFound) {
427                return false;
428            }
429
430            throw $e;
431        }
432
433        return true;
434    }
435
436    /** @throws HaClientException */
437    public function upsertExposedEntity(ExposedEntityAddress $address, ExposedEntityDefinition $definition, ExposedStateChange $change): ExposedEntitySnapshot
438    {
439        return ExposedEntitySnapshotReader::readUpsertResult($this->connection->send(new UpsertExposedEntity($address, $definition, $change)));
440    }
441
442    // An action registers a service, not an entity, so it has no snapshot to read back.
443    /** @throws HaClientException */
444    public function upsertExposedAction(ExposedEntityAddress $address, ExposedEntityDefinition $definition): void
445    {
446        $result = $this->connection->send(new UpsertExposedEntity($address, $definition, new ExposedStateChange()));
447
448        if (!\is_string($result['service'] ?? null)) {
449            throw HaClientException::protocolViolation('a stewart/entity/upsert result for an action without service');
450        }
451    }
452
453    /** @throws HaClientException */
454    public function updateExposedEntityState(ExposedEntityAddress $address, ExposedStateChange $change): void
455    {
456        $this->connection->sendIgnoringResult(new UpdateExposedEntityState($address, $change));
457    }
458
459    /** @throws HaClientException */
460    public function removeExposedEntity(ExposedEntityAddress $address): bool
461    {
462        $removed = $this->connection->send(new RemoveExposedEntity($address))['removed'] ?? null;
463
464        return \is_bool($removed) ? $removed : throw HaClientException::protocolViolation('a stewart/entity/remove result without removed');
465    }
466
467    /** @throws HaClientException */
468    public function reconcileExposedEntities(ExposedEntityReconcile $reconcile): EntityIdCollection
469    {
470        return ReconcileResultReader::readRemovedEntityIds($this->connection->send(new ReconcileExposedEntities($reconcile)));
471    }
472
473    /** @throws HaClientException */
474    public function unsubscribeEvents(int $subscriptionId): void
475    {
476        $this->connection->unsubscribeEvents($subscriptionId);
477    }
478
479    /**
480     * @template T of object
481     * @param Closure(array<string, mixed>): ?T $decodeState
482     * @param Closure(T): void $onState
483     * @param Closure(HaEvent): void $onEvent
484     * @throws HaClientException
485     */
486    private function subscribeEventsWithStateDecoder(Closure $decodeState, Closure $onState, Closure $onEvent): int
487    {
488        $decoder = $this->decoder;
489
490        return $this->subscribe(new SubscribeEvents(), static function (array $event) use ($decoder, $decodeState, $onState, $onEvent): void {
491            if (($event['event_type'] ?? null) === HaEvent::STATE_CHANGED) {
492                $state = $decodeState($event);
493
494                if ($state !== null) {
495                    $onState($state);
496                }
497
498                return;
499            }
500
501            $decoded = $decoder->decodeEvent($event);
502
503            if ($decoded !== null) {
504                $onEvent($decoded);
505            }
506        });
507    }
508
509    /**
510     * @param Closure(array<string, mixed>): void $handler
511     * @throws HaClientException
512     */
513    private function subscribe(SubscriptionCommand $command, Closure $handler): int
514    {
515        try {
516            return $this->connection->subscribeEvents($command, $handler);
517        } catch (HaClientException $e) {
518            throw $e->reason === HaClientError::CommandUnauthorized
519                ? HaClientException::createForReason(HaClientError::AdministratorRequired, $e)
520                : $e;
521        }
522    }
523
524    /**
525     * @template T of object
526     * @param array<array-key, mixed> $rows
527     * @param Closure(array<array-key, mixed>): ?T $decodeOrSkip
528     * @return list<T>
529     */
530    private function decodeRows(array $rows, Closure $decodeOrSkip): array
531    {
532        $decoded = [];
533
534        foreach ($rows as $row) {
535            $entry = \is_array($row) ? $decodeOrSkip($row) : null;
536
537            if ($entry !== null) {
538                $decoded[] = $entry;
539            }
540        }
541
542        return $decoded;
543    }
544
545    /** @return array<array-key, mixed> */
546    private function sendUnlessUnknown(HaCommand $command): array
547    {
548        // Floors and labels arrived in Home Assistant 2024.4.
549        try {
550            return $this->connection->send($command);
551        } catch (HaClientException $e) {
552            if ($e->reason === HaClientError::CommandRejected && $e->findErrorCode() === self::UNKNOWN_COMMAND_CODE) {
553                return [];
554            }
555
556            throw $e;
557        }
558    }
559
560    private function toHistoryException(EntityId $entityId, HaClientException $e): HistoryException
561    {
562        if ($e->reason === HaClientError::CommandRejected && $e->findErrorCode() === self::UNKNOWN_COMMAND_CODE) {
563            return HistoryException::createForReason(HistoryError::RecorderUnavailable, $e, entityId: $entityId->value);
564        }
565
566        return match ($e->reason) {
567            HaClientError::CommandRejected,
568            HaClientError::CommandUnauthorized,
569            HaClientError::CommandUnencodable => HistoryException::rejected($entityId, $e->findDetail() ?? $e->getMessage(), $e->findErrorCode(), $e),
570            HaClientError::CommandTimedOut => HistoryException::timedOut($entityId, $e->getMessage(), $e),
571            default => HistoryException::unreachable($entityId, $e->getMessage(), $e),
572        };
573    }
574
575    /** @throws HaClientException */
576    private function readEntityRegistryEntry(mixed $row, string $command): EntityRegistryEntry
577    {
578        try {
579            return \is_array($row) ? EntityRegistryEntry::fromArray($row) : throw HaClientException::protocolViolation(\sprintf('a %s result without an entity entry', $command));
580        } catch (IdentifierException $e) {
581            throw HaClientException::protocolViolation(\sprintf('a %s result without a valid entity id', $command), $e);
582        }
583    }
584
585    private function toRegistryEditException(EntityId $entityId, HaClientException $e): RegistryEditException
586    {
587        if ($e->reason === HaClientError::CommandRejected && $e->findErrorCode() === self::NOT_FOUND_CODE) {
588            return RegistryEditException::notFound($entityId);
589        }
590
591        return match ($e->reason) {
592            HaClientError::CommandRejected,
593            HaClientError::CommandUnauthorized,
594            HaClientError::CommandUnencodable => RegistryEditException::rejected($entityId, $e->findDetail() ?? $e->getMessage(), $e->findErrorCode(), $e),
595            HaClientError::CommandTimedOut => RegistryEditException::timedOut($entityId, $e->getMessage(), $e),
596            default => RegistryEditException::unreachable($entityId, $e->getMessage(), $e),
597        };
598    }
599
600    private function toActionCallException(string $domain, string $service, HaClientException $e): ActionCallException
601    {
602        return match ($e->reason) {
603            HaClientError::CommandRejected,
604            HaClientError::CommandUnauthorized,
605            HaClientError::CommandUnencodable => ActionCallException::rejected(
606                $domain,
607                $service,
608                $e->findDetail() ?? $e->getMessage(),
609                $e->findErrorCode(),
610                $e,
611            ),
612            HaClientError::CommandTimedOut => ActionCallException::timedOut($domain, $service, $e->getMessage(), $e),
613            default => ActionCallException::unreachable($domain, $service, $e->getMessage(), $e),
614        };
615    }
616
617    private function toEventFireException(string $eventType, HaClientException $e): EventFireException
618    {
619        return match ($e->reason) {
620            HaClientError::CommandRejected,
621            HaClientError::CommandUnauthorized,
622            HaClientError::CommandUnencodable => EventFireException::rejected($eventType, $e->findDetail() ?? $e->getMessage(), $e->findErrorCode(), $e),
623            HaClientError::CommandTimedOut => EventFireException::timedOut($eventType, $e->getMessage(), $e),
624            default => EventFireException::unreachable($eventType, $e->getMessage(), $e),
625        };
626    }
627}