gregorj / serial-port
PHP interfaces and classes for serial port communication.
Requires
- php: ^8.1
- ext-curl: *
- ext-sockets: *
- gregorj/to-string: ^1.0
- psr/container: ^2.0
Requires (Dev)
- ext-pcntl: *
- ext-posix: *
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^10.5
- squizlabs/php_codesniffer: ^4.0
This package is auto-updated.
Last update: 2026-05-06 15:15:13 UTC
README
PHP classes to connect to serial devices using streams or HTTP(S) gateways.
This library separates the command model from the transport:
Commanddefines command payload, terminators, timeout, and response mappingCommunicationexecutes the command (StreamCommunicationorHttpCommunication) viaquery()orwrite()- transport is provided by either
Stream(for sockets) orHttpTransport(for gateways)
BasicStringCommand, BasicVoidCommand, and StringResponse are reference implementations for common command/response patterns.
Usage
You can either:
- bridge a serial device to TCP (for example with pySerial
tcp_serial_redirect) and useTcpStream - call an HTTP(S) serial gateway and use
HttpCommunicationwithCurlTransportorStreamWrapperTransport
TCP stream communication
<?php use GregorJ\SerialPort\Commands\BasicStringCommand; use GregorJ\SerialPort\StreamCommunication; use GregorJ\SerialPort\TcpStream; $stream = new TcpStream('127.0.0.1', 5000); $communication = new StreamCommunication($stream); $command = new BasicStringCommand('HELLO', "\n", "\n"); $response = $command->invoke($communication); echo $response?->get('response');
HTTP gateway communication
<?php use GregorJ\SerialPort\Commands\BasicStringCommand; use GregorJ\SerialPort\CurlTransport; use GregorJ\SerialPort\HttpCommunication; $communication = new HttpCommunication( new CurlTransport(), 'https://example.com/query', 'ttyUSB0', HttpCommunication::DEVICE_TYPE_WIRED ); $command = new BasicStringCommand('HELLO', "\n", "\n"); $response = $command->invoke($communication); echo $response?->get('response');
HttpCommunication::setTimeout() configures the serial-device response timeout and sends it to the gateway as deviceTimeoutMs.
HTTP transport timeouts (connect and request) are configured separately in CurlTransport and StreamWrapperTransport.
Fire-and-forget commands
If your command does not expect a response, call Communication::write() directly (or use BasicVoidCommand, which now delegates to write()):
<?php use GregorJ\SerialPort\Commands\BasicVoidCommand; use GregorJ\SerialPort\StreamCommunication; use GregorJ\SerialPort\TcpStream; $communication = new StreamCommunication(new TcpStream('127.0.0.1', 5000)); $command = new BasicVoidCommand('AT+RESET', "\r\n"); $command->invoke($communication);
For custom command types, implement GregorJ\SerialPort\Interfaces\Command and decide per command whether to call query() or write().
For the expected HTTP JSON contract and fields, see src/Http/JsonSerialGatewayContract.php.