Lines 98.24% 56 / 57
Methods 85.71% 6 / 7
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 100.00% 2 / 2 100.00% 1 / 1 1
 onCommand 100.00% 1 / 1 100.00% 1 / 1 1
 onSessionEnded 100.00% 1 / 1 100.00% 1 / 1 1
 establishLink 100.00% 33 / 33 100.00% 1 / 1 9
 markLinkLost 100.00% 3 / 3 100.00% 1 / 1 2
 recordDetectedState 100.00% 3 / 3 100.00% 1 / 1 1
 handleSessionEvent 92.85% 13 / 14 0.00% 0 / 1 5.01
23final class ComponentLink
24{
25    private int $connectionGeneration = 0;
26
27    /** @var Closure(ComponentCommand): void */
28    private Closure $onCommand;
29
30    /** @var Closure(): void */
31    private Closure $onSessionEnded;
32
33    public function __construct(
34        private readonly HaClient $client,
35        private readonly LoggerInterface $logger,
36        private readonly ComponentTracker $tracker,
37        private readonly ExposeConfig $expose,
38        private readonly StewartVersion $stewartVersion,
39    ) {
40        $this->onCommand = static function (): void {};
41        $this->onSessionEnded = static function (): void {};
42    }
43
44    /** @param Closure(ComponentCommand): void $handler */
45    public function onCommand(Closure $handler): void
46    {
47        $this->onCommand = $handler;
48    }
49
50    /** @param Closure(): void $handler */
51    public function onSessionEnded(Closure $handler): void
52    {
53        $this->onSessionEnded = $handler;
54    }
55
56    /** @throws HaClientException */
57    public function establishLink(): void
58    {
59        if (!$this->expose->enabled) {
60            $this->tracker->recordState(ComponentState::Disabled, null);
61
62            return;
63        }
64
65        $generation = ++$this->connectionGeneration;
66        $version = null;
67
68        try {
69            $version = $this->client->findComponentVersion();
70
71            if ($version === null) {
72                if ($this->recordDetectedState(ComponentState::Missing, null)) {
73                    $this->logger->info('The stewart Home Assistant integration is not installed or not loaded yet; Stewart keeps checking, and apps cannot expose entities until it answers');
74                }
75
76                return;
77            }
78
79            if (!$version->isCompatible()) {
80                if ($this->recordDetectedState(ComponentState::ProtocolMismatch, $version)) {
81                    $this->logger->warning('The stewart Home Assistant integration speaks another protocol; update it or Stewart so they match', [
82                        'component_version' => $version->componentVersion,
83                        'component_protocol' => $version->protocol,
84                        'stewart_protocol' => ComponentProtocol::VERSION,
85                    ]);
86                }
87
88                return;
89            }
90
91            $this->client->subscribeComponentSession(
92                new ComponentSessionRequest($this->expose->instance, $this->stewartVersion->value, $this->expose->commandTimeout),
93                fn(ComponentSessionEvent $event) => $this->handleSessionEvent($event, $generation),
94            );
95        } catch (HaClientException $e) {
96            if (!$e->reason->isCommandRefusal()) {
97                throw $e;
98            }
99
100            if ($this->recordDetectedState(ComponentState::Refused, $version)) {
101                $this->logger->warning('Home Assistant refused the stewart integration session', ['exception' => $e]);
102            }
103
104            return;
105        }
106
107        $this->recordDetectedState(ComponentState::Active, $version);
108        $this->logger->info('Opened the stewart Home Assistant integration session', [
109            'component_version' => $version->componentVersion,
110            'instance' => (string) $this->expose->instance,
111        ]);
112    }
113
114    public function markLinkLost(): void
115    {
116        ++$this->connectionGeneration;
117
118        if ($this->expose->enabled) {
119            $this->tracker->recordStateKeepingVersion(ComponentState::Unchecked);
120        }
121    }
122
123    // A relink retries while the component is missing; only the first of those attempts logs.
124    private function recordDetectedState(ComponentState $state, ?ComponentVersion $version): bool
125    {
126        $changed = $this->tracker->detection->state !== $state;
127        $this->tracker->recordState($state, $version);
128
129        return $changed;
130    }
131
132    private function handleSessionEvent(ComponentSessionEvent $event, int $generation): void
133    {
134        if ($generation !== $this->connectionGeneration) {
135            return;
136        }
137
138        if ($event instanceof ComponentCommand) {
139            ($this->onCommand)($event);
140
141            return;
142        }
143
144        if ($event instanceof SessionEnded) {
145            ($this->onSessionEnded)();
146
147            return;
148        }
149
150        if (!$event instanceof SessionReplaced) {
151            return;
152        }
153
154        $this->logger->warning('Another Stewart took over the stewart integration session; give each daemon its own expose.instance', [
155            'instance' => (string) $this->expose->instance,
156        ]);
157        $this->tracker->recordStateKeepingVersion(ComponentState::Replaced);
158    }
159}