blob: b68b78420ef226a5c30a1975f828e99357eca37a (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
<?php
class InverterdClient extends MySimpleSocketClient {
/**
* @throws Exception
*/
public function setProtocol(int $v): string
{
$this->send("v $v");
return $this->recv();
}
/**
* @throws Exception
*/
public function setFormat(string $fmt): string
{
$this->send("format $fmt");
return $this->recv();
}
/**
* @throws Exception
*/
public function exec(string $command, array $arguments = []): string
{
$buf = "exec $command";
if (!empty($arguments)) {
foreach ($arguments as $arg)
$buf .= " $arg";
}
$this->send($buf);
return $this->recv();
}
/**
* @throws Exception
*/
public function recv()
{
$recv_buf = '';
$buf = '';
while (true) {
$result = socket_recv($this->sock, $recv_buf, 1024, 0);
if ($result === false)
throw new Exception(__METHOD__ . ": socket_recv() failed: " . $this->getSocketError());
// peer disconnected
if ($result === 0)
break;
$buf .= $recv_buf;
if (endsWith($buf, "\r\n\r\n"))
break;
}
$response = explode("\r\n", $buf);
$status = array_shift($response);
if (!in_array($status, ['ok', 'err']))
throw new Exception(__METHOD__.': unexpected status ('.$status.')');
if ($status == 'err')
throw new Exception(empty($response) ? 'unknown inverterd error' : $response[0]);
return trim(implode("\r\n", $response));
}
}
|