-
Notifications
You must be signed in to change notification settings - Fork 56
/
WriteSingleCoilRequest.php
87 lines (75 loc) · 2.31 KB
/
WriteSingleCoilRequest.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
<?php
declare(strict_types=1);
namespace ModbusTcpClient\Packet\ModbusFunction;
use ModbusTcpClient\Packet\ErrorResponse;
use ModbusTcpClient\Packet\ModbusPacket;
use ModbusTcpClient\Packet\ModbusRequest;
use ModbusTcpClient\Packet\ProtocolDataUnitRequest;
use ModbusTcpClient\Utils\Types;
/**
* Request for Write Single Coil (FC=05)
*
* Example packet: \x00\x01\x00\x00\x00\x06\x11\x05\x00\x6B\xFF\x00
* \x00\x01 - transaction id
* \x00\x00 - protocol id
* \x00\x06 - number of bytes in the message (PDU = ProtocolDataUnit) to follow
* \x11 - unit id
* \x05 - function code
* \x00\x6B - start address
* \xFF\x00 - coil data (true)
*
*/
class WriteSingleCoilRequest extends ProtocolDataUnitRequest implements ModbusRequest
{
const ON = 0xFF;
const OFF = 0x0;
/**
* @var bool value to be sent to modbus
*/
private bool $coil;
public function __construct(int $startAddress, bool $coil, int $unitId = 0, int $transactionId = null)
{
parent::__construct($startAddress, $unitId, $transactionId);
$this->coil = $coil;
$this->validate();
}
public function getFunctionCode(): int
{
return ModbusPacket::WRITE_SINGLE_COIL;
}
public function __toString(): string
{
return parent::__toString()
. Types::toByte($this->isCoil() ? self::ON : self::OFF)
. chr(0x0);
}
/**
* @return bool
*/
public function isCoil(): bool
{
return $this->coil;
}
protected function getLengthInternal(): int
{
return parent::getLengthInternal() + 2; // coil size (1 byte + 1 byte)
}
/**
* Parses binary string to WriteSingleCoilRequest or return ErrorResponse on failure
*
* @param string $binaryString
* @return WriteSingleCoilRequest|ErrorResponse
*/
public static function parse(string $binaryString): ErrorResponse|WriteSingleCoilRequest
{
return self::parseStartAddressPacket(
$binaryString,
12,
ModbusPacket::WRITE_SINGLE_COIL,
function (int $transactionId, int $unitId, int $startAddress) use ($binaryString) {
$coil = Types::parseByte($binaryString[10]) === self::ON;
return new self($startAddress, $coil, $unitId, $transactionId);
}
);
}
}