DeviceReportEvent.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. var_dump($data);
  30. if (!isset($data['TYPE'])) return false;
  31. switch ($data['TYPE']) {
  32. case "ONLINE":
  33. $this->online($device_id, $data['DATA']);
  34. break;
  35. }
  36. return true;
  37. }
  38. protected function online($device_id, $data)
  39. {
  40. $device = Device::where("device_sn", $device_id)->find();
  41. if (!$device) {
  42. return false;
  43. }
  44. $device->status = 1;
  45. $device->save();
  46. }
  47. }