All documentation

Using the phpts_kv_lock Cross-Process Mutex on an RS485 Half-Duplex Bus

When multiple PHP processes share one RS485 half-duplex bus, how to use phpts_kv_lock / phpts_kv_unlock for cross-process mutual exclusion: lock before sending HEX, unlock after the event script receives a response, with TTL as a fallback.

RS485 is a half-duplex bus: only one node can send at any given time. When multiple PHP processes write to the same bus simultaneously, frames overlap, and slave responses can be misattributed.

PHPTS's event-triggered tasks can connect an RS485-to-TCP data transmission device to a TCP server; ordinary Web pages, task pool scripts, and timers can all issue commands. phpts_kv_lock() / phpts_kv_unlock() are used to add a cross-process lock to this bus.

I. What is phpts_kv

phpts_kv is a PHP extension for PHPTS. Its underlying layer is a Windows named file mapping (backed by the page file, not persisted to disk), created by phpts.exe. Web pools, task pools, and CLI processes derived from the same phpts.exe see the same data, and all reads and writes are serialized by a named mutex. It is not Redis / Memcached, nor does it work across machines; capacity is about 14.9 MB and 100,000 entries, keys and values are 64 bytes each, and everything is cleared when the main PHPTS program exits.

The applicable prerequisites are PHP 8.5 / 8.6, the phpts_kv extension is loaded (enabled by default), and the process is derived from phpts.exe. If cross-machine sharing is required, Redis should still be chosen.

II. Semantics of the two functions

phpts_kv_lock(string $key, int $ttl_seconds = 0): bool
phpts_kv_unlock(string $key): bool
  • lock is a try-lock: when the key does not exist or has expired, it writes the lock marker phpts-lock and returns true; if the key is still held (not expired), it immediately returns false without overwriting the original value. The check and write are completed within the same named mutex, atomically across processes.
  • does not queue or block: failure is failure, there is no wait queue and no fairness guarantee; the retry strategy is up to the caller. Repeated calls to lock from the same process will also fail.
  • unlock only checks the value, not the owner: it deletes only if the key exists, has not expired, and its value equals phpts-lock. Any process can release any lock; the API has no owner / token.
  • TTL is a lease: second-level, lazy expiration, with no background sweeper thread; after expiration, the key is judged nonexistent only on the next access. ttl_seconds = 0 means it never expires, and a process crash will occupy the line permanently, so a TTL must be given in this scenario.
  • Lock keys and business keys share the same namespace: use a dedicated name for lock keys, such as bus:485-1; keys must not exceed 64 bytes.
  • phpts_kv_del_by_value() never deletes locks: when a WebSocket / TCP client disconnects, the gateway performs associated cleanup of registrations by client ID and will not accidentally delete locks.

III. Example Workflow

An RS485 bus has two slave stations, No. 1 and No. 2, connected to it and is connected through an RS485-to-TCP data transmission module; an event-triggered task opens a TCP server (for example, 59301), and the rule is bound to tcp485.php.

  1. The pushing party calls phpts_kv_lock('bus:485-1', 3) to seize the bus; if it fails, it abandons this delivery.
  2. After seizing it, use hex2bin() to convert the hexadecimal frame into raw bytes, and send it to the data transmission device through POST /tcp/send.
  3. The data transmission device forwards the frame to the RS485 bus, and the target slave responds.
  4. The event script receives the response and calls phpts_kv_unlock('bus:485-1') to release the bus.
  5. If the device goes offline, packets are lost, the slave does not respond, or the pushing process crashes, the lock automatically becomes invalid after the 3-second lease expires.

Key point: unlocking happens after the response comes back, not after sending is complete. If you unlock immediately after sending, another process can insert a new frame while the slave is responding, and the half-duplex bus will still collide.

IV. Code 1: Lock before sending HEX

<?php
// push.php:任意 Web 页面 / 任务脚本
$lockKey = 'bus:485-1';

// ① 发送前抢总线;抢不到就放弃本次下发
if (!phpts_kv_lock($lockKey, 3)) {
    exit('RS485 总线忙,请稍后重试');
}

// ② 要发送的十六进制帧(01 03 00 00 00 02 C4 0B:读 1 号从站 0x0000 起 2 个寄存器)
$frame = hex2bin('010300000002C40B');

// ③ 通过共用推送接口把原始字节交给 RS485 转 TCP 数传设备
$url = 'http://127.0.0.1:3379/tcp/send?key=device:485-1&token=<权限Token>';
$ctx = stream_context_create(['http' => [
    'method'  => 'POST',
    'header'  => "Content-Type: application/octet-stream\r\n",
    'content' => $frame,
    'timeout' => 2,
]]);
echo file_get_contents($url, false, $ctx);

// ④ 发送成功后不要解锁:总线要占到设备应答回来。
//    事件脚本收到应答后调用 phpts_kv_unlock();无应答时 3 秒 TTL 自动释放。

V. Code 2: Unlock after the event script receives the reply

<?php
// tcp485.php:事件触发任务 → TCP 服务器规则绑定的 PHP 脚本

// ① 登记连接 ID:推送方用 key=device:485-1 就能找到这条连接
$clientId = $_SERVER['PHPTS_EVENT_CLIENTID'] ?? '';
if ($clientId !== '') {
    phpts_kv_set('device:485-1', $clientId, 3600);
}

// ② 应答内容
$frame = file_get_contents('php://input');

// ③ 收到设备应答,释放总线
phpts_kv_unlock('bus:485-1');

// ④ 业务处理:入库、转发 MQTT、写日志……

VI. Notes and Boundaries

  • The simple example is “unlock upon receiving any frame”: if the same connection also receives heartbeats, registration packets, or the device may respond late, you should first confirm in the event script, according to protocol characteristics (slave address, function code, CRC), that it is the response to this request, and then unlock; otherwise, a late response may release the lock of a new request.
  • TTL must be greater than the maximum round-trip time: the example gives 3 seconds; if the device is slow, increase it. TTL is second-level and lazily expired; it is not actively cleared the moment it expires.
  • Do not loop endlessly when lock fails: the example exits directly; in production, you can add a short retry with an upper limit to prevent Web requests from being dragged to death.
  • Do not give a lock key the same name as a business key: set can overwrite the lock key; also do not call phpts_kv_clear(), as it will clear all locks.
  • Only applicable to processes derived from the same phpts.exe: for cross-machine or cross-PHPTS-instance use, use Redis.
  • Value upper limit is 64 bytes: this example only uses the lock and does not store request data in the lock.

VII. Self-check before going live

Confirm that get_extension_funcs('phpts_kv') already contains these two functions, then run a minimal semantic check:

<?php
var_dump(phpts_kv_lock('bus:485-1', 3));   // true
var_dump(phpts_kv_lock('bus:485-1', 3));   // false,锁不可重入
var_dump(phpts_kv_unlock('bus:485-1'));    // true

VIII. Summary

Lock with phpts_kv_lock() before sending, unlock with phpts_kv_unlock() after receiving the response, and rely on TTL as a fallback when there is no response. Three lines of core logic allow multiple PHP processes to safely share one RS485 half-duplex bus.

Comments 0 comments

No comments yet. Be the first to comment.

Leave a comment

Comments are plain text only. HTML and URLs are not allowed.

Your email will not be displayed in comments