Commit b2a37eb22fd4f28c12122b359c0a29a0f9453f77

Authored by 谭苏航
1 parent 2c928d83

feat: implement device auto-registration logic

Showing 1 changed file with 17 additions and 3 deletions
... ... @@ -159,10 +159,24 @@ $ws_worker->onMessage = function ($connection, $data) use (&$clients, &$devices,
159 159
160 160 // 验证设备(如果有 deviceService)
161 161 if ($deviceService && $secret) {
  162 + // Modified: Auto-Register if verification fails (or check existence first)
162 163 if (!$deviceService->verifyDevice($deviceId, $secret)) {
163   - $connection->send(json_encode(['type' => 'error', 'msg' => 'Invalid device credentials']));
164   - $connection->close();
165   - return;
  164 + // Check if it's a NEW device (not in DB)
  165 + // We need a way to check existence without secret verification failure masking it
  166 + // Let's rely on registerDevice's internal check or check explicitly
  167 +
  168 + // Ideally verifyDevice returns false if ID not found OR secret wrong.
  169 + // We can try to register it. If it succeeds, it was new. If it fails (ID exists), then it was a wrong secret.
  170 +
  171 + $regResult = $deviceService->registerDevice($deviceId, $secret, "New Device " . substr($deviceId, -4));
  172 + if ($regResult['ok']) {
  173 + echo "✨ Auto-Registered New Device: $deviceId\n";
  174 + } else {
  175 + // Registration failed (likely ID exists), so it must be a wrong secret
  176 + $connection->send(json_encode(['type' => 'error', 'msg' => 'Invalid device credentials or ID collision']));
  177 + $connection->close();
  178 + return;
  179 + }
166 180 }
167 181 // 更新设备状态为在线
168 182 $deviceService->updateDeviceStatus($deviceId, 'online');
... ...
Please register or login to post a comment