start.php
5.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
<?php
use Workerman\Worker;
use Workerman\Timer;
require_once __DIR__ . '/vendor/autoload.php';
// Define Heartbeat Interval
define('HEARTBEAT_TIME', 30);
// Create a WebSocket worker
$ws_worker = new Worker("websocket://0.0.0.0:8888");
// Emulate simple routing/state for now
// In production, use Redis for distributed state
$ws_worker->count = 1; // Single process for dev simplicity
// Redis Connection
$redis = null;
try {
$redis_host = getenv('REDIS_HOST') ?: '127.0.0.1';
$redis_port = getenv('REDIS_PORT') ?: 6379;
$redis_auth = getenv('REDIS_PASSWORD');
$redis_prefix = getenv('REDIS_PREFIX') ?: 'ai_';
$params = [
'scheme' => 'tcp',
'host' => $redis_host,
'port' => $redis_port,
];
if ($redis_auth) {
$params['password'] = $redis_auth;
}
// Predis Client
$redis = new Predis\Client($params, ['prefix' => $redis_prefix]);
$redis->connect();
echo "✅ Connected to Redis at $redis_host ($redis_prefix)\n";
} catch (Exception $e) {
echo "⚠️ Redis Connection Failed: " . $e->getMessage() . "\n";
}
// Store connections (Memory for now, can move to Redis later)
$clients = []; // ClientID -> Connection
$devices = []; // DeviceID -> Connection
$ws_worker->onWorkerStart = function ($worker) {
echo "Relay Server Started on 0.0.0.0:8888\n";
// Heartbeat check
Timer::add(10, function () use ($worker) {
$time_now = time();
foreach ($worker->connections as $connection) {
// Check if connection is alive possibly?
// Workerman handles basic disconnects, but we can enforce ping logic here if needed
}
});
};
$ws_worker->onConnect = function ($connection) {
echo "New connection: " . $connection->id . "\n";
$connection->authVerified = false;
};
$ws_worker->onMessage = function ($connection, $data) use (&$clients, &$devices) {
$msg = json_decode($data, true);
if (!$msg || !isset($msg['type'])) {
return;
}
// 1. Authenticate / Register
if ($msg['type'] === 'register') {
if ($msg['role'] === 'device') {
// Device 注册
$deviceId = $msg['id']; // TODO: Add secret validation
$devices[$deviceId] = $connection;
$connection->deviceId = $deviceId;
$connection->role = 'device';
$connection->authVerified = true;
$connection->send(json_encode(['type' => 'ack', 'status' => 'registered']));
echo "Device Registered: $deviceId\n";
} elseif ($msg['role'] === 'client') {
// Mini Program 注册
// TODO: Validate Token
$clientId = $msg['id'];
$clients[$clientId] = $connection;
$connection->clientId = $clientId;
$connection->role = 'client';
$connection->authVerified = true;
$connection->send(json_encode(['type' => 'ack', 'status' => 'connected']));
echo "Client Connected: $clientId\n";
}
return;
}
if (!$connection->authVerified) {
$connection->close();
return;
}
// 2. Proxy Logic
// Client -> Device
if ($msg['type'] === 'proxy' && $connection->role === 'client') {
$targetDeviceId = $msg['targetDeviceId'] ?? null;
if ($targetDeviceId && isset($devices[$targetDeviceId])) {
$payload = $msg['payload'];
// Wrap it so device knows who sent it
$forwardMsg = [
'type' => 'cmd:execute',
'fromClientId' => $connection->clientId,
'payload' => $payload
];
$devices[$targetDeviceId]->send(json_encode($forwardMsg));
echo "Forwarded msg from Client {$connection->clientId} to Device {$targetDeviceId}\n";
} else {
$connection->send(json_encode(['type' => 'error', 'msg' => 'Device offline or not found']));
}
}
// Device -> Client
if ($msg['type'] === 'proxy_response' && $connection->role === 'device') {
$targetClientId = $msg['targetClientId'] ?? null;
if ($targetClientId && isset($clients[$targetClientId])) {
$payload = $msg['payload'];
$forwardMsg = [
'type' => 'response',
'fromDeviceId' => $connection->deviceId,
'payload' => $payload
];
$clients[$targetClientId]->send(json_encode($forwardMsg));
echo "Forwarded response from Device {$connection->deviceId} to Client {$targetClientId}\n";
}
}
};
$ws_worker->onClose = function ($connection) use (&$clients, &$devices) {
if (isset($connection->role)) {
if ($connection->role === 'device' && isset($connection->deviceId)) {
unset($devices[$connection->deviceId]);
echo "Device disconnected: {$connection->deviceId}\n";
} elseif ($connection->role === 'client' && isset($connection->clientId)) {
unset($clients[$connection->clientId]);
echo "Client disconnected: {$connection->clientId}\n";
}
}
};
Worker::runAll();