rafgrando / portunus
PHP library for physical access control
Requires
- php: ^8.1
Requires (Dev)
- phpunit/phpunit: ^10.5 || ^11.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Portunus is a modern PHP library designed for seamless integration with physical access control hardware. It currently supports TCP/IP communication with the Nice / Linear-HCS MG3000 Gatekeeper Module (Módulo Guarita), a widely adopted industry standard for condominium and corporate security in Latin America, as well as with Comm5's MA I/O modules.
Why "Portunus"?
In ancient Roman religion and mythology, Portunus was the god of keys, doors, gates, and cattle. He was traditionally depicted holding a key, guarding the crossings and entryways.
This library acts as a digital key, bridging modern PHP applications with physical entryways, gates, and security barriers.
Features
- Common contracts:
Relay,SwitchableRelayandDigitalInputlet application code ignore the manufacturer. - TCP/IP native sockets behind a
Transportinterface, so drivers can be tested with a fake. - Typed errors: every failure is an exception implementing
PortunusExceptionInterface. No method returnsfalseto signal an error. - PSR-4, PHP 8.1+, no runtime dependencies.
Installation
composer require rafgrando/portunus
Upgrading from v1? See UPGRADE.md.
Usage
Nice / Linear-HCS Guarita (MG3000)
use Rafgrando\Portunus\Nice\GuaritaIP; use Rafgrando\Portunus\Nice\ReceiverType; use Rafgrando\Portunus\Transport\TcpTransport; $guarita = new GuaritaIP(new TcpTransport('192.168.0.10', 9000), accessCode: ''); $gate = $guarita->receiver(ReceiverType::CT, 2)->output(1); // Relay $gate->pulse(); // PC 13: time configured on the device $gate->pulse(5); // PC 92: 5 seconds (0-255) $sensor = $guarita->receiver(ReceiverType::CT, 2)->input(reader: 1, input: 1); // DigitalInput $sensor->isActive();
Receivers are addressed by type and CAN bus number (0-7). Outputs are 1-4, readers 1-4 and inputs 1-4.
Out-of-range values throw InvalidArgumentException. The Guarita only supports pulses: it cannot turn an output off or read its state.
Comm5 MA modules
use Rafgrando\Portunus\Comm5\MaModule; use Rafgrando\Portunus\Transport\TcpTransport; $module = new MaModule(new TcpTransport('192.168.0.103', 5000), defaultPulseSeconds: 1); $light = $module->output(3); // SwitchableRelay $light->turnOn(); $light->isOn(); $light->turnOff(); $light->pulse(2); // SET 3, wait 2 s, RESET 3 $module->input(4)->isActive(); // QUERY, bit 4
pulse()blocks. Comm5 modules have no native pulse command. The driver sendsSET, sleeps for the requested time withusleep(), then sendsRESET, all on one connection. Your script is blocked for the whole duration.RESETis always attempted onceSETwas sent. In every connection mode, if the connection fails during a pulse, the driver reconnects, triesRESETand throws the original exception. The pulse is not repeated, and the relay can stay on if the module cannot be reached.
Manufacturer-independent code
use Rafgrando\Portunus\Contracts\Relay; function openGate(Relay $relay): void { $relay->pulse(3); } openGate($guarita->receiver(ReceiverType::CT, 2)->output(1)); openGate($module->output(3));
Error handling
use Rafgrando\Portunus\Exceptions\PortunusExceptionInterface; try { $gate->pulse(); } catch (PortunusExceptionInterface $e) { // DeviceConnectionException, DeviceCommandException (InvalidPinException, UnsupportedCommandException), // AuthenticationException or InvalidArgumentException }
Supported commands
Guarita
| Method | Protocol command |
|---|---|
GuaritaIP::getIdentification() |
PC 3 |
GuaritaIP::getDateTime() |
PC 12 |
GuaritaOutput::pulse() |
PC 13 (no duration) / PC 92 (with duration) |
GuaritaIP::reboot() |
PC 18 |
GuaritaIP::pressResetButton() |
PC 24 |
GuaritaIP::updateReceivers() |
PC 29 |
GuaritaIP::enableRemoteMode() |
PC 39 |
Receiver::getFirmwareVersion() |
PC 61 |
Receiver::getDigitalInput() |
PC 66 (raw) |
GuaritaInput::isActive() |
PC 93 |
See docs/KNOWN_ISSUES.md for protocol details that are unverified.
Comm5 MA
| Method | Protocol command |
|---|---|
MaOutput::turnOn() / turnOff() |
SET n / RESET n |
MaOutput::isOn(), MaModule::getOutputStates() |
OUTPUTS |
MaModule::setOutputStates() |
OUT hhhh |
MaInput::isActive(), MaModule::getInputStates() |
QUERY |
MaOutput::pulse() |
SET, wait, RESET (blocking) |
MaModule::ping() |
PING |
MaModule::getHostname() / getMacAddress() / getFirmwareVersion() |
HOSTNAME / MACADDRESS / FWVERSION |
MaModule::getInputCount() / getOutputCount() |
INPUTCOUNT / OUTPUTCOUNT |
MaModule::getPulseCount() |
COUNTER n (resets the counter) |
NOTIFY, WAIT and NOTIFYFILTER are not supported.
Comm5 device behavior
- The module serves one TCP client at a time. While a session is open (including a blocking
pulse()), other connections are refused withDeviceConnectionException. - Reconnecting immediately after a close leaves an MA-5100-2 silent, so
MaModulewaits 20 ms after each session (reconnectDelayMsconstructor argument). - Firmware differs between models and versions. See below and docs/HARDWARE_FINDINGS.md.
Connection modes
Default: one connection per command. Nothing to manage, and the module is free between commands. Each command costs a connection, the greeting and the reconnect pause (about 29 ms on the tested unit).
Scoped session, for several commands in a row:
$active = $module->session(function () use ($module): bool { $module->output(1)->turnOn(); $module->output(2)->turnOff(); return $module->input(8)->isActive(); });
One connection and greeting, closed when the callback returns or throws. Nested sessions share
it. There is no retry: if a command leaves the connection in an unknown state (no reply, cut-off
or unexpected reply), it is dropped and later commands in that session throw
DeviceConnectionException.
Manual connection, for long-running processes:
$module->open(); try { while ($running) { $module->input(8)->isActive(); sleep(10); } } finally { $module->close(); }
- There is no automatic ping. PHP has no timer without an event loop: call
ping()periodically if you want to detect a dropped link. See also the TCP Recv timeout option in the module's web interface: with0the module never closes the connection; the manual suggests 30000 ms for clients that poll every 28 s. SET,RESET,OUT,OUTPUTS,QUERY,PING,helpand the identification and count commands are repeated once, on a new connection, after a connection failure or a timeout with no reply. If the second attempt fails, the exception propagates andisOpen()becomesfalse. A failing call can therefore take two timeouts.COUNTERis never repeated, because reading resets the counter.pulse()is never repeated (it still reconnects to sendRESET, as in the default mode).- Any other unexpected reply drops the socket without a retry; the next command reconnects.
isOpen()staystrue.
Trade-off: the module accepts one client at a time on port 5000 (see docs/HARDWARE_FINDINGS.md). While a persistent connection is open, no other process can reach the module. Use
session()in web requests, andopen()/close()only when a single process owns the module.
Firmware-dependent commands
Identification and channel count commands, and COUNTER, depend on the firmware: the 2017
programming manual refers to firmware 1.80/1.81, and a tested MA-5100 with firmware 1.30 has none
of them. Such a module sends no reply to an unknown command.
So before sending HOSTNAME, MACADDRESS, INPUTCOUNT, OUTPUTCOUNT, FWVERSION or COUNTER,
MaModule reads the module's help (at most once per instance) and fails immediately if the
command is not listed:
use Rafgrando\Portunus\Exceptions\UnsupportedCommandException; // extends DeviceCommandException try { echo $module->getFirmwareVersion(); } catch (UnsupportedCommandException $e) { echo $e->getMessage(); // names the command; check the module firmware version } $module->supportsCommand('COUNTER'); // bool $module->supportedCommands(); // ['QUERY', 'OUT', 'OUTPUTS', ...]
SET, RESET, OUT, OUTPUTS, QUERY and PING never read help. If a firmware implements a
command without listing it, disable the check with
new MaModule($transport, detectSupportedCommands: false).
Debugging: recording traffic
RecordingTransport wraps any transport and appends every operation to a JSON Lines file:
use Rafgrando\Portunus\Comm5\MaModule; use Rafgrando\Portunus\Transport\RecordingTransport; use Rafgrando\Portunus\Transport\TcpTransport; $transport = new RecordingTransport(new TcpTransport('192.168.0.103', 5000), '/tmp/module.jsonl'); (new MaModule($transport))->ping();
{"t":0.012,"op":"write","hex":"50494e470d0a","text":"PING\\r\\n"}
t is the number of seconds since connect; op is connect, write, read or close;
requested appears on fixed-length reads and error on failed or empty ones.
Everything is logged as sent, including Guarita access codes. Review a recording before sharing it.
Testing
composer install
composer test
Contributing
Contributions are welcome! If you want to add support for other physical access control devices, relay boards, or serial (RS232/RS485) communication, feel free to open a Pull Request or start an Issue.
License
Distributed under the MIT License. See LICENSE for more information. This ensures you are free to use this library in personal, open-source, or proprietary commercial products without licensing friction.
Developed with 💻 and ☕ by Rafael Grando.