DeviceReportEvent.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. $device->status = 1;
  42. $device->save();
  43. } else {
  44. Device::insertGetId([
  45. "device_sn" => $device_id,
  46. "status" => 1
  47. ]);
  48. }
  49. }
  50. }