loraWan915.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. use Workerman\Worker;
  3. require_once __DIR__ . '/Autoloader.php';
  4. require_once './Lib/mysql/src/Connection.php';
  5. use \Workerman\Lib\Timer;
  6. $ws_worker = new Worker("tcp://0.0.0.0:8900");
  7. // 启动1个进程对外提供服务
  8. $ws_worker->count = 1;
  9. $ws_worker->onWorkerStart = function($ws_worker)
  10. {
  11. global $cmdList;
  12. global $resList;
  13. $cmdList = array();
  14. $resList = array();
  15. // 指令返回监测
  16. Timer::add(0.1, function()use($ws_worker){
  17. global $cmdList;
  18. global $resList;
  19. $cmdTemp = $cmdList;
  20. $resTemp = $resList;
  21. if (!empty($resTemp)) {
  22. foreach ($resTemp as $key => $value) {
  23. if (isset($cmdTemp[$value['deviceId']])) {
  24. $cmdTemp[$value['deviceId']]['client']->send('{"res":0,"info":"success","resInfo":"'.$value['resInfo'].'"}');
  25. unset($cmdList[$value['deviceId']]);
  26. }
  27. unset($resList[$key]);
  28. }
  29. }
  30. });
  31. // 超时监测
  32. Timer::add(1, function()use($ws_worker){
  33. global $cmdList;
  34. $cmdTemp = $cmdList;
  35. if (!empty($cmdTemp)) {
  36. foreach ($cmdTemp as $key => $value) {
  37. if (time() - $value['time'] >= 30){
  38. if (isset($value['client'])) {
  39. unset($cmdList[$key]);
  40. }
  41. }
  42. }
  43. }
  44. });
  45. };
  46. $ws_worker->onMessage = function($connection, $data)
  47. {
  48. global $cmdList;
  49. global $resList;
  50. var_dump($data);
  51. $data = json_decode($data,true);
  52. if ($data) {
  53. if ($data['type'] == 'cmd') {
  54. if (isset($data['deviceId']) && !empty($data['deviceId'])) {
  55. $cmdList[$data['deviceId']] = array('client'=>$connection,'time'=>time());
  56. }
  57. }elseif ($data['type'] == 'res'){
  58. if (isset($data['deviceId']) && !empty($data['deviceId'])) {
  59. $resList[$data['deviceId']] = array('deviceId'=>$data['deviceId'],'resInfo'=>isset($data['resInfo']) ? $data['resInfo'] : '');
  60. }
  61. }
  62. }
  63. };
  64. // 运行worker
  65. Worker::runAll();