ClientServer.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. <?php
  2. namespace App\Servers;
  3. use App\Common\ClientTrait;
  4. use App\Common\HelperTrait;
  5. use \GatewayWorker\Lib\Gateway;
  6. use Illuminate\Support\Facades\Redis;
  7. class ClientServer
  8. {
  9. use ClientTrait, HelperTrait;
  10. const RUN_CMD = '5a';
  11. //运行命令
  12. const STATUS_CMD = 'a5';
  13. //设备状态
  14. const LOCATION_CMD = 'a6';
  15. //设备位置
  16. const CACHE_KEY = 'qingyu_CMD:RESPONSE:';
  17. private static $registerAddress = '127.0.0.1:1238';
  18. /**
  19. * 开始命令
  20. * @param $box_no
  21. * @param $mode
  22. * @param $time
  23. * @param int $reset
  24. * @param bool $is_response
  25. * Author: Mead
  26. */
  27. public static function startBox($box_no, $mode, $time, $reset = 1, $is_response = true)
  28. {
  29. $time = dechex($time);
  30. $body = [
  31. "0{$reset}",
  32. "0{$mode}",
  33. $time
  34. ];
  35. return self::send(self::RUN_CMD, $box_no, $body, $is_response);
  36. }
  37. /**
  38. * @param $cmd
  39. * @param $box_no
  40. * @param array $body
  41. * @param bool $is_response
  42. * @return int -1离线 0发送失败(终端执行) 1正常 3超时
  43. * Author: Mead
  44. */
  45. private static function send($cmd, $box_no, $body = [], $is_response = true)
  46. {
  47. //是否在线
  48. if (!Gateway::isUidOnline($box_no)) return -1;
  49. $response = [
  50. 'aa',
  51. $cmd,
  52. count($body)
  53. ];
  54. $response = array_merge($response, $body);
  55. $response[] = self::sumDexArr($response);
  56. $responseBody = strtolower(implode('', $response)) . '0d0a';
  57. Gateway::sendToUid($box_no, $responseBody);
  58. if (!$is_response) {
  59. //不进行状态监测
  60. return 1;
  61. }
  62. $redis = Redis::connection();
  63. $result = 3;
  64. for ($i = 1; $i <= 30; $i++) {
  65. usleep(500000);
  66. $data = $redis->get(self::CACHE_KEY . $box_no . ':' . $cmd);
  67. if ($data != null) {
  68. $result = $data;
  69. break;
  70. }
  71. //补发
  72. if (in_array($i, [10, 20])) {
  73. Gateway::sendToUid($box_no, $responseBody);
  74. }
  75. }
  76. return $result;
  77. }
  78. /**
  79. * 获取设备状态
  80. * @param $box_no
  81. * @return int
  82. * Author: Mead
  83. */
  84. public static function getBoxStatus($box_no)
  85. {
  86. $body = [
  87. '5a'
  88. ];
  89. return self::send(self::STATUS_CMD, $box_no, $body, true);
  90. }
  91. /**
  92. * 获取定位
  93. * @param $box_no
  94. * @return int
  95. * Author: Mead
  96. */
  97. public static function getLocation($box_no)
  98. {
  99. $body = [
  100. 'a6'
  101. ];
  102. return self::send(self::LOCATION_CMD, $box_no, $body, true);
  103. }
  104. }