policyCmd.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. <?php
  2. use \Workerman\Worker;
  3. use \Workerman\Lib\Timer;
  4. require_once __DIR__ . '/Autoloader.php';
  5. require_once './Lib/mysql/src/Connection.php';
  6. require_once './Mqtt.php';
  7. $task = new Worker();
  8. function crc16($string) {
  9. $crc = 0xFFFF;
  10. for ($x = 0; $x < strlen ($string); $x++) {
  11. $crc = $crc ^ ord($string[$x]);
  12. for ($y = 0; $y < 8; $y++) {
  13. if (($crc & 0x0001) == 0x0001) {
  14. $crc = (($crc >> 1) ^ 0xA001);
  15. } else { $crc = $crc >> 1; }
  16. }
  17. }
  18. $crc = strval(base_convert($crc, 10, 16));
  19. $crc = substr('0000'.$crc, -4);
  20. return substr($crc, -2).substr($crc, 0,2);
  21. }
  22. function lampMqttCmd($sendTopic,$backTopic,$sendData){
  23. // 订阅信息,接收一个信息后退出
  24. $server = 'streetserver.weclouds.xyz';
  25. $port = 1883;
  26. $username = 'weclouds';
  27. $password = 'weclouds@1234';
  28. $client_id = time().rand(100000,999999); // 设置你的连接客户端id
  29. $mqtt = new Mqtt($server, $port, $client_id);
  30. if($mqtt->connect(true, NULL, $username, $password)) { //链接不成功再重复执行监听连接
  31. $mqtt->publish($sendTopic, $sendData, 2);
  32. // $mqtt->publish('/WEGW/ReadIn/865860046894466', pack('H*','010AA00B'), 2);
  33. }else{
  34. return '';
  35. }
  36. $topics[$backTopic] = array("qos" => 2,"function" => "procmsg");
  37. // $topics['/WEGW/ReadOut/865860046894466'] = array("qos" => 2, "function" => "procmsg");
  38. // 订阅主题
  39. $mqtt->subscribe($topics, 0);
  40. $true = 1;
  41. $t = time();
  42. while($true == 1){
  43. $true = $mqtt->proc();
  44. if (time() - $t >= 10) {
  45. return '';
  46. }
  47. }
  48. $mqtt->close();
  49. return $true;
  50. }
  51. function send_cmd($cmd,$type = 0, $timeout = 30, $ms_timeout = 200) {
  52. $ip = '123.57.20.89';
  53. $port = '6800';
  54. $client = @stream_socket_client("tcp://{$ip}:{$port}", $errno, $errstr, 30);
  55. if ($client) {
  56. fwrite($client, $cmd);
  57. stream_set_timeout($client, $timeout, $ms_timeout);
  58. $result = fread($client, 8196);
  59. fclose($client);
  60. return $result;
  61. } else {
  62. sleep(1);
  63. send_cmd($cmd,$type, $timeout, $ms_timeout);
  64. }
  65. }
  66. $task->count = 1;
  67. $task->onWorkerStart = function($task)
  68. {
  69. global $websocketDB;
  70. global $mqttCmdList;
  71. global $beginDate;
  72. $beginDate = date('H:i',time());
  73. $mqttCmdList = array();
  74. $config = json_decode(file_get_contents('./db_config.php'),true);
  75. $websocketDB = new \Workerman\MySQL\Connection($config['hostname'], '3306', $config['username'], $config['password'], $config['dbname']);
  76. Timer::add(1, function()
  77. {
  78. global $websocketDB;
  79. global $mqttCmdList;
  80. global $beginDate;
  81. if ($beginDate != date('H:i',time())) {
  82. $beginDate = date('H:i',time());
  83. $sql = 'SELECT P.id,T.value FROM project AS P left join lampinfo as L on L.projectid = P.id left join timezone AS T on P.timezone = T.id where L.policyid != 0';
  84. $list = $websocketDB->query($sql);
  85. foreach ($list as $value) {
  86. $nowTime = time() - 8 * 3600 + $value['value'] * 3600;
  87. $nowDate = date('Y-m-d',$nowTime);
  88. $nowH = date('H:i',$nowTime);
  89. $sql = 'SELECT L.id as lampid,PI.*,N.protocoltype,L.protocoltype as lampprotocoltype,L.address FROM lampinfo AS L join (SELECT * from policy_cmd where starttime <= "'.$nowDate.'") as PI on L.policyid = PI.policyid join network as N on N.id = L.networkid where PI.policyid != 0 AND N.status = 1';
  90. $policyList = $websocketDB->query($sql);
  91. foreach ($policyList as $policy) {
  92. $index = 1;
  93. while ($index <= 10) {
  94. if (empty($policy['time'.$index])) {
  95. break;
  96. }
  97. if ($policy['time'.$index] == $nowH) {
  98. $data = array();
  99. $data['cmdtype'] = 0;
  100. $data['relateid'] = $policy['lampid'];
  101. $data['statuscmd'] = $policy['value'.$index];
  102. $data['updatetime'] = date("Y-m-d H:i:s");
  103. if ($policy['protocoltype'] == 4 && $policy['lampprotocoltype'] == 1) {
  104. $mqttCmdList[$policy['lampid']] = array('address'=>$policy['address'],'lampid'=>$policy['lampid'],'status'=>$data['statuscmd'],'cmdCount'=>0);
  105. }else{
  106. $sql = 'SELECT id from batch_switch_cmd where relateid = '.$policy['lampid'].' AND cmdtype = 0';
  107. $cmdList = $websocketDB->query($sql);
  108. if (empty($cmdList) || empty($cmdList[0]['id'])) {
  109. $cmdid = $websocketDB->insert('batch_switch_cmd')->cols($data)->query();
  110. }else{
  111. $websocketDB->update('batch_switch_cmd')->cols($data)->where('id='.$cmdList[0]['id']);
  112. $cmdid = $cmdList[0]['id'];
  113. }
  114. $cmd = '{"cmd_type":"batch_switch_cmd","cmd_id":'.$cmdid.',"broadcast":0}';
  115. send_cmd($cmd,1,0);
  116. }
  117. break;
  118. }
  119. $index ++;
  120. }
  121. }
  122. }
  123. }
  124. });
  125. // mqtt 设备异步发送指令
  126. Timer::add(30, function()
  127. {
  128. global $websocketDB;
  129. global $mqttCmdList;
  130. $temp = $mqttCmdList;
  131. foreach ($temp as $key => $value) {
  132. if ($value['cmdCount'] >= 3) {
  133. unset($mqttCmdList[$key]);
  134. continue;
  135. }
  136. if ($value['status'] == 1) { // 开灯
  137. $lightness = 100;
  138. }else{ // 关灯
  139. $lightness = 0;
  140. }
  141. $sendData = '0110df0a000204';
  142. $lightness = empty($lightness) ? '0000' : '0000'.base_convert($lightness, 10, 16);
  143. $sendData .= mb_strlen($lightness) == 4 ? $lightness : substr($lightness, -4);
  144. $sendData .= mb_substr('0000'.base_convert(600, 10, 16), -4);
  145. $sendData .= crc16(pack('H*',$sendData));
  146. $res = lampMqttCmd('/WE/TransIn/'.$policy['address'],'/WE/TransOut/'.$policy['address'],pack('H*','0001'.$sendData));
  147. if (empty($res)) {
  148. $mqttCmdList[$key]['cmdCount'] += 1;
  149. }else{
  150. if (strtolower(crc16(pack('H*',substr($res['msg'], 0,-4)))) == strtolower(substr($res['msg'], -4))) {
  151. if ($value['status'] == 1) {
  152. $websocketDB->update('lampinfo')->cols(array('status'=>1,'lighteness'=>100))->where('id='.$value['lampid']);
  153. }else{
  154. $websocketDB->update('lampinfo')->cols(array('status'=>0,'lighteness'=>0))->where('id='.$value['lampid']);
  155. }
  156. unset($mqttCmdList[$key]);
  157. }else{
  158. $mqttCmdList[$key]['cmdCount'] += 1;
  159. }
  160. }
  161. }
  162. });
  163. };
  164. // 运行worker
  165. Worker::runAll();