-
Notifications
You must be signed in to change notification settings - Fork 55
/
ReadRegisterRequest.php
89 lines (75 loc) · 2.35 KB
/
ReadRegisterRequest.php
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
declare(strict_types=1);
namespace ModbusTcpClient\Composer\Read\Register;
use ModbusTcpClient\Composer\Request;
use ModbusTcpClient\Exception\InvalidArgumentException;
use ModbusTcpClient\Exception\ModbusException;
use ModbusTcpClient\Packet\ErrorResponse;
use ModbusTcpClient\Packet\ModbusFunction\ReadHoldingRegistersRequest;
use ModbusTcpClient\Packet\ModbusFunction\ReadHoldingRegistersResponse;
use ModbusTcpClient\Packet\ResponseFactory;
class ReadRegisterRequest implements Request
{
/**
* @var string uri to modbus server. Example: 'tcp://192.168.100.1:502'
*/
private string $uri;
/** @var ReadRegisterAddress[] */
private array $addresses;
/** @var ReadHoldingRegistersRequest */
private ReadHoldingRegistersRequest $request;
/**
* @param string $uri
* @param ReadRegisterAddress[] $addresses
* @param ReadHoldingRegistersRequest $request
*/
public function __construct(string $uri, array $addresses, ReadHoldingRegistersRequest $request)
{
$this->addresses = $addresses;
$this->request = $request;
$this->uri = $uri;
}
/**
* @return ReadHoldingRegistersRequest
*/
public function getRequest(): ReadHoldingRegistersRequest
{
return $this->request;
}
public function getUri(): string
{
return $this->uri;
}
/**
* @return ReadRegisterAddress[]
*/
public function getAddresses(): array
{
return $this->addresses;
}
public function __toString()
{
return $this->request->__toString();
}
/**
* @param string $binaryData
* @return array<string, mixed>|ErrorResponse
* @throws ModbusException
* @throws \Exception
*/
public function parse(string $binaryData): array|ErrorResponse
{
$response = ResponseFactory::parseResponse($binaryData)->withStartAddress($this->request->getStartAddress());
if ($response instanceof ErrorResponse) {
return $response;
}
if (!$response instanceof ReadHoldingRegistersResponse) {
throw new InvalidArgumentException("given data is not valid modbus response");
}
$result = [];
foreach ($this->addresses as $address) {
$result[$address->getName()] = $address->extract($response);
}
return $result;
}
}