AutoTask.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace app\admin\command;
  3. use app\admin\model\TaskSteps;
  4. use app\admin\services\MqttMessageClient;
  5. use think\console\Command;
  6. use think\console\Input;
  7. use think\console\Output;
  8. use think\Db;
  9. use think\helper\Arr;
  10. class AutoTask extends Command
  11. {
  12. public function configure()
  13. {
  14. $this
  15. ->setName('AutoTask')
  16. ->setDescription('自动下发定时指令');
  17. }
  18. public function execute(Input $input, Output $output)
  19. {
  20. while (true) {
  21. $time = Date('H:i');
  22. $list = TaskSteps::with(['task.device'])->whereRaw("DATE_FORMAT(start_time, '%H:%i')='{$time}'")->whereOrRaw("DATE_FORMAT(end_time, '%H:%i')='{$time}'")->select();
  23. if ($list) {
  24. foreach ($list as $item) {
  25. $device_sn = $item->task->device[0]->device_sn;
  26. if ($device_sn && substr($item->start_time, 0, 5) === $time) {
  27. // 发送开始
  28. $this->publish($device_sn, 'RUN', $item->name, [
  29. 'SCRIPT' => base64_encode("log('aa')"),
  30. 'CONFIG' => [],
  31. ]);
  32. $this->publish($device_sn, 'START', $item->name, []);
  33. }
  34. if ($device_sn && substr($item->end_time, 0, 5) === $time) {
  35. // 发送结束
  36. $this->publish($device_sn, 'STOP', $item->name, []);
  37. }
  38. }
  39. }
  40. sleep(60);
  41. }
  42. }
  43. public function publish($device_sn, $action, $name, $data = [])
  44. {
  45. MqttMessageClient::getInstance()->publish('/device/' . $device_sn . '/master', json_encode([
  46. 'SCRIPT_ACTION' => $action,
  47. 'SCRIPT_NAME' => $name,
  48. 'SCRIPT_DATA' => $data,
  49. ]), 0);
  50. echo sprintf("发送指令 %s %s %s %s\n", $device_sn, $action, $name, json_encode($data));
  51. }
  52. }