rCMD/php/sse.php
2023-11-27 19:18:41 +08:00

88 lines
1.7 KiB
PHP

<?php
require_once 'config.php';
$device = $_REQUEST['device'] ?? null;
if (is_null($device)) {
die(json_encode([
'status' => 'error',
'message' => $msg
], JSON_UNESCAPED_UNICODE));
}
if (strlen($device) > 128) {
die(json_encode([
'status' => 'error',
'message' => 'device 不能超过 128 个字符'
], JSON_UNESCAPED_UNICODE));
}
header('X-Accel-Buffering: no');
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
ob_end_clean();
ob_implicit_flush(1);
$data = [
"time" => time(),
"status" => 'success',
"cmd" => null,
"params" => []
];
returnEventData($data);
subscribeRedis($device);
while (1) {
sleep(1);
}
function subscribeRedis($to)
{
$channel = 'rCMD_' . md5($to);
global $redis;
$redis->subscribe([$channel], function ($redis, $channel, $msg) {
$msg = json_decode($msg, true);
if (!$msg) {
return;
}
if ($msg["cmd"] == 'close') {
$data = [
"status" => "close",
"message" => '连接已关闭'
];
returnEventData($data);
die();
}
$msg["status"] = "success";
returnEventData($msg);
});
}
function returnEventData($returnData, $event = 'message', $id = 0, $retry = 0)
{
$str = '';
if ($id > 0) {
$str .= "id: {$id}" . PHP_EOL;
}
if ($event) {
$str .= "event: {$event}" . PHP_EOL;
}
if ($retry > 0) {
$str .= "retry: {$retry}" . PHP_EOL;
}
if (is_array($returnData)) {
$returnData = json_encode($returnData);
}
$str .= "data: {$returnData}" . PHP_EOL;
$str .= PHP_EOL;
echo $str;
}