12
12
use Amp \Websocket \WebsocketClient ;
13
13
use Closure ;
14
14
use Flat3 \RevPi \Exceptions \RemoteDeviceException ;
15
- use Flat3 \RevPi \Interfaces \Hardware \Device ;
16
15
use Flat3 \RevPi \JsonRpc \Request as JsonRpcRequest ;
17
16
use Flat3 \RevPi \JsonRpc \Response as JsonRpcResponse ;
18
17
use Throwable ;
22
21
/**
23
22
* @phpstan-type JsonRpcDeviceMethodT 'open'|'close'|'lseek'|'ioctl'|'read'|'write'|'cfgetispeed'|'cfgetospeed'|'cfsetispeed'|'cfsetospeed'|'tcflush'|'tcdrain'|'tcsendbreak'|'fdopen'
24
23
* @phpstan-type JsonRpcMethodT JsonRpcDeviceMethodT
25
- * @phpstan-type JsonRpcEventTypeT 'readable'
24
+ * @phpstan-type JsonRpcDeviceEventTypeT 'readable'
25
+ * @phpstan-type JsonRpcEventTypeT JsonRpcDeviceEventTypeT
26
26
* @phpstan-type JsonRpcRequestParamsT array<string, int|string|null>
27
27
* @phpstan-type JsonRpcRequestT array{id: string, method: JsonRpcMethodT, params: JsonRpcRequestParamsT }
28
28
* @phpstan-type JsonRpcResponseResultT int|string|array<string, int|string|null>
@@ -33,18 +33,26 @@ abstract class JsonRpcPeer implements WebsocketClientHandler
33
33
{
34
34
protected WebsocketClient $ socket ;
35
35
36
- protected Device $ device ;
37
-
38
36
/**
39
- * @var callable
37
+ * @var array{readable: array< callable>}
40
38
*/
41
- protected mixed $ eventReceiver ;
39
+ protected array $ callbacks = [
40
+ 'readable ' => [],
41
+ ];
42
42
43
43
/**
44
44
* @var array<DeferredFuture<JsonRpcResponseResultT>>
45
45
*/
46
46
protected array $ pending = [];
47
47
48
+ /**
49
+ * @param JsonRpcDeviceEventTypeT $event
50
+ */
51
+ public function on (string $ event , Closure $ callback ): void
52
+ {
53
+ $ this ->callbacks [$ event ][] = $ callback ;
54
+ }
55
+
48
56
public function withSocket (WebsocketClient $ socket ): self
49
57
{
50
58
$ this ->socket = $ socket ;
@@ -85,7 +93,7 @@ protected function handleResponse(): void
85
93
$ response = unserialize ($ payload );
86
94
87
95
if ($ response instanceof Event) {
88
- call_user_func ($ this ->eventReceiver , $ response );
96
+ collect ($ this ->callbacks [ $ response -> type ])-> each ( fn ( $ callback ) => $ callback ( $ response-> payload ) );
89
97
90
98
continue ;
91
99
}
@@ -121,11 +129,6 @@ protected function handleResponse(): void
121
129
}
122
130
}
123
131
124
- public function on (Closure $ callback ): void
125
- {
126
- $ this ->eventReceiver = $ callback ;
127
- }
128
-
129
132
public function handleClient (WebsocketClient $ client , Request $ request , Response $ response ): void
130
133
{
131
134
$ this ->socket = $ client ;
0 commit comments