You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
2.7 KiB

5 years ago
  1. <?php
  2. namespace App\Service;
  3. use App\Commons\Log;
  4. use App\Constants\LogLabel;
  5. use App\Model\SpeakerDevic;
  6. use App\Model\Store;
  7. use Hyperf\Di\Annotation\Inject;
  8. use Hyperf\Utils\ApplicationContext;
  9. use App\TaskWorker\AliIotTask;
  10. class DeviceServiceImp implements DeviceServiceInterFace
  11. {
  12. /**
  13. * @Inject
  14. * @var Log
  15. */
  16. protected $log;
  17. /**
  18. * @Inject
  19. * @var IOTServiceInterface
  20. */
  21. protected $IOTService;
  22. /**
  23. * 获取绑定列表
  24. * @param $store_id
  25. * @return \Hyperf\Database\Model\Builder[]|\Hyperf\Database\Model\Collection
  26. */
  27. public function getListByStoreId($store_id)
  28. {
  29. return SpeakerDevic::query()->where(['store_id' => $store_id, 'is_bind' => SpeakerDevic::IS_BIND_YES])->get()->toArray();
  30. }
  31. /**
  32. * 绑定
  33. * @param $dev_name
  34. * @param $store_id
  35. * @return SpeakerDevic|null
  36. * @throws \Throwable
  37. */
  38. public function bindByStoreId($dev_name, $store_id)
  39. {
  40. $sd = null;
  41. if ($this->checkDeviceEnable($dev_name)) {
  42. return $sd;
  43. }
  44. try {
  45. // 获取市场ID
  46. $market_id = Store::query()->where(['id' => $store_id])->value('market_id');
  47. // $sd = new SpeakerDevic;
  48. // $sd->store_id = $store_id;
  49. // $sd->device_name = $dev_name;
  50. // $sd->market_id = $market_id;
  51. // $sd->bind_time = time();
  52. // $sd->saveOrFail();
  53. $sd = SpeakerDevic::query()->updateOrCreate(
  54. ['store_id' => $store_id, 'device_name' => $dev_name],
  55. ['market_id' => $market_id, 'bind_time' => time(), 'is_bind' => SpeakerDevic::IS_BIND_YES]
  56. );
  57. } catch (Exception $e) {
  58. $this->log->event(LogLabel::DEVICE_LOG, ['msg' => '绑定设备异常:'.$e->getMessage()]);
  59. }
  60. return $sd;
  61. }
  62. /**
  63. * 解绑
  64. * @param $bind_id
  65. * @return int
  66. */
  67. public function unbindById($bind_id)
  68. {
  69. return SpeakerDevic::query()->where(['id' => $bind_id])->update(['is_bind' => SpeakerDevic::IS_BIND_NO]);
  70. }
  71. /**
  72. * 发布语音消息
  73. * @param $store_id
  74. * @param $msg
  75. */
  76. public function pubMsgToStoreByDevName($dev_names, $msg)
  77. {
  78. foreach ($dev_names as $key => $dev_name) {
  79. $this->IOTService->pub($dev_name['device_name'], $msg);
  80. }
  81. return true;
  82. }
  83. /**
  84. * 当前设备是否已经被绑定
  85. * @param $dev_name
  86. * @return bool
  87. */
  88. protected function checkDeviceEnable($dev_name)
  89. {
  90. return SpeakerDevic::query()->where(['device_name' => $dev_name, 'is_bind' => SpeakerDevic::IS_BIND_YES])->exists();
  91. }
  92. }