|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Console\Commands; |
| 4 | + |
| 5 | +use Illuminate\Console\Command; |
| 6 | + |
| 7 | +/** |
| 8 | + * Minimal Modbus TCP *server* that simulates a machine, so the real |
| 9 | + * modbus:poll daemon has something to read end-to-end without hardware. |
| 10 | + * |
| 11 | + * Register map (holding & input registers share the same backing store): |
| 12 | + * 0 → state (1=RUNNING, 2=IDLE, 3=FAULT) |
| 13 | + * 1 → good counter (increments each second while RUNNING) |
| 14 | + * 2 → reject counter |
| 15 | + * 3 → temperature (telemetry, °C ×10) |
| 16 | + * |
| 17 | + * The machine cycles RUNNING → IDLE → RUNNING → FAULT … on a timer. |
| 18 | + * |
| 19 | + * php artisan modbus:simulate --port=5020 |
| 20 | + */ |
| 21 | +class ModbusSimulateCommand extends Command |
| 22 | +{ |
| 23 | + protected $signature = 'modbus:simulate {--port=5020} {--host=0.0.0.0}'; |
| 24 | + |
| 25 | + protected $description = 'Run a simulated Modbus TCP machine (for testing the poller)'; |
| 26 | + |
| 27 | + /** @var array<int,int> holding/input registers */ |
| 28 | + private array $reg = [0 => 1, 1 => 0, 2 => 0, 3 => 220]; |
| 29 | + |
| 30 | + public function handle(): int |
| 31 | + { |
| 32 | + $host = $this->option('host'); |
| 33 | + $port = (int) $this->option('port'); |
| 34 | + |
| 35 | + $server = @stream_socket_server("tcp://{$host}:{$port}", $errno, $errstr); |
| 36 | + if (! $server) { |
| 37 | + $this->error("Cannot bind {$host}:{$port}: {$errstr}"); |
| 38 | + |
| 39 | + return self::FAILURE; |
| 40 | + } |
| 41 | + stream_set_blocking($server, false); |
| 42 | + $this->info("Modbus simulator listening on {$host}:{$port} (Ctrl+C to stop)"); |
| 43 | + |
| 44 | + $clients = []; |
| 45 | + $lastTick = microtime(true); |
| 46 | + // Scripted state timeline (state, seconds) |
| 47 | + $script = [[1, 15], [2, 5], [1, 20], [3, 8], [1, 15], [2, 4]]; |
| 48 | + $phase = 0; |
| 49 | + $phaseElapsed = 0.0; |
| 50 | + |
| 51 | + while (true) { |
| 52 | + $read = array_merge([$server], $clients); |
| 53 | + $write = $except = null; |
| 54 | + if (@stream_select($read, $write, $except, 1) === false) { |
| 55 | + break; |
| 56 | + } |
| 57 | + |
| 58 | + foreach ($read as $sock) { |
| 59 | + if ($sock === $server) { |
| 60 | + $client = @stream_socket_accept($server, 0); |
| 61 | + if ($client) { |
| 62 | + stream_set_blocking($client, false); |
| 63 | + $clients[(int) $client] = $client; |
| 64 | + } |
| 65 | + |
| 66 | + continue; |
| 67 | + } |
| 68 | + |
| 69 | + $data = @fread($sock, 1024); |
| 70 | + if ($data === '' || $data === false) { |
| 71 | + fclose($sock); |
| 72 | + unset($clients[(int) $sock]); |
| 73 | + |
| 74 | + continue; |
| 75 | + } |
| 76 | + $response = $this->handleRequest($data); |
| 77 | + if ($response !== null) { |
| 78 | + @fwrite($sock, $response); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + // Advance simulation on ~1s ticks. |
| 83 | + $now = microtime(true); |
| 84 | + $dt = $now - $lastTick; |
| 85 | + if ($dt >= 1.0) { |
| 86 | + $lastTick = $now; |
| 87 | + $phaseElapsed += $dt; |
| 88 | + [$state, $duration] = $script[$phase]; |
| 89 | + $this->reg[0] = $state; |
| 90 | + if ($state === 1) { // RUNNING |
| 91 | + $this->reg[1] += 2; // good parts |
| 92 | + if (random_int(1, 10) === 1) { |
| 93 | + $this->reg[2] += 1; // occasional reject |
| 94 | + } |
| 95 | + $this->reg[3] = 220 + random_int(-5, 15); |
| 96 | + } |
| 97 | + if ($phaseElapsed >= $duration) { |
| 98 | + $phaseElapsed = 0; |
| 99 | + $phase = ($phase + 1) % count($script); |
| 100 | + } |
| 101 | + $label = [1 => 'RUNNING', 2 => 'IDLE', 3 => 'FAULT'][$this->reg[0]]; |
| 102 | + $this->line(sprintf('[sim] state=%s good=%d reject=%d temp=%.1f', $label, $this->reg[1], $this->reg[2], $this->reg[3] / 10)); |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + return self::SUCCESS; |
| 107 | + } |
| 108 | + |
| 109 | + /** |
| 110 | + * Parse a Modbus TCP frame and build a response. Supports FC 0x03/0x04 |
| 111 | + * (read holding/input registers) and 0x01/0x02 (read coils/discretes). |
| 112 | + */ |
| 113 | + private function handleRequest(string $data): ?string |
| 114 | + { |
| 115 | + if (strlen($data) < 12) { |
| 116 | + return null; |
| 117 | + } |
| 118 | + $mbap = unpack('ntid/nprot/nlen/Cunit', substr($data, 0, 7)); |
| 119 | + $fc = ord($data[7]); |
| 120 | + $body = substr($data, 8); |
| 121 | + $req = unpack('naddr/nqty', $body); |
| 122 | + $addr = $req['addr']; |
| 123 | + $qty = max(1, $req['qty']); |
| 124 | + |
| 125 | + if (in_array($fc, [0x03, 0x04], true)) { |
| 126 | + $payload = ''; |
| 127 | + for ($i = 0; $i < $qty; $i++) { |
| 128 | + $val = $this->reg[$addr + $i] ?? 0; |
| 129 | + $payload .= pack('n', $val & 0xFFFF); |
| 130 | + } |
| 131 | + $pdu = chr($fc).chr(strlen($payload)).$payload; |
| 132 | + } elseif (in_array($fc, [0x01, 0x02], true)) { |
| 133 | + $byteCount = intdiv($qty + 7, 8); |
| 134 | + $bits = 0; |
| 135 | + for ($i = 0; $i < $qty; $i++) { |
| 136 | + if (($this->reg[$addr + $i] ?? 0) > 0) { |
| 137 | + $bits |= (1 << $i); |
| 138 | + } |
| 139 | + } |
| 140 | + $pdu = chr($fc).chr($byteCount).pack('C', $bits & 0xFF); |
| 141 | + } else { |
| 142 | + // Illegal function exception |
| 143 | + $pdu = chr($fc | 0x80).chr(0x01); |
| 144 | + } |
| 145 | + |
| 146 | + $len = strlen($pdu) + 1; // + unit id |
| 147 | + |
| 148 | + return pack('nnn', $mbap['tid'], 0, $len).chr($mbap['unit']).$pdu; |
| 149 | + } |
| 150 | +} |
0 commit comments