DeviceReportEvent.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace app\jobs;
  3. use app\admin\model\Device;
  4. use think\Exception;
  5. use think\queue\Job;
  6. class DeviceReportEvent
  7. {
  8. public function fire(Job $job, $data)
  9. {
  10. // 拆解是哪个设备发送的消息
  11. $topic = $data['topic'];
  12. $topicArray = explode('/', $topic);
  13. $device_id = $topicArray[2];
  14. $reportData = json_decode($data['message'], true);
  15. try {
  16. $this->eventRouter($device_id, $reportData);
  17. } catch (Exception $exception) {
  18. // 发送错误,跳过, 这里可以记录一下日志
  19. }
  20. $job->delete();
  21. }
  22. protected function eventRouter($device_id, $data)
  23. {
  24. // 消息体结构应该如下:
  25. // [
  26. // "TYPE" => "ONLINE", // 事件类型
  27. // "DATA" => [] // 事件参数
  28. // ];
  29. if (!isset($data['TYPE'])) return false;
  30. switch ($data['TYPE']) {
  31. case "ONLINE":
  32. $this->online($device_id, $data['DATA']);
  33. break;
  34. }
  35. return true;
  36. }
  37. protected function online($device_id, $data)
  38. {
  39. $device = Device::where("device_sn", $device_id)->find();
  40. if (!$device) {
  41. return false;
  42. }
  43. $device->status = 1;
  44. $device->save();
  45. }
  46. }