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.

53 lines
1.6 KiB

  1. <?php
  2. namespace App\Service;
  3. use AlibabaCloud\Client\AlibabaCloud;
  4. use AlibabaCloud\Client\Exception\ClientException;
  5. use AlibabaCloud\Client\Exception\ServerException;
  6. use App\Commons\Log;
  7. use App\Constants\LogLabel;
  8. use Hyperf\Di\Annotation\Inject;
  9. class IOTAliService implements IOTServiceInterface
  10. {
  11. /**
  12. * @Inject
  13. * @var Log
  14. */
  15. protected $log;
  16. public function pub($device_name, $msg)
  17. {
  18. AlibabaCloud::accessKeyClient(env('ALI_IOT_KEY'), env('ALI_IOT_SECRET'))
  19. ->regionId(env('ALI_IOT_REGION'))
  20. ->asDefaultClient();
  21. try {
  22. AlibabaCloud::rpc()
  23. ->product('Iot')
  24. ->version('2018-01-20')
  25. ->action('Pub')
  26. ->method('POST')
  27. ->host(env('ALI_IOT_HOST'))
  28. ->options([
  29. 'query' => [
  30. 'RegionId' => "cn-shanghai",
  31. 'TopicFullName' => "/".env('ALI_IOT_PRODUCT_KEY')."/".$device_name."/user/get",
  32. 'MessageContent' => base64_encode($msg),
  33. 'ProductKey' => env('ALI_IOT_PRODUCT_KEY'),
  34. ],
  35. ])
  36. ->request();
  37. } catch (ClientException $e) {
  38. $this->log->event(LogLabel::DEVICE_LOG, ['msg' => 'ClientException发布失败:'.$e->getErrorMessage()]);
  39. return false;
  40. } catch (ServerException $e) {
  41. $this->log->event(LogLabel::DEVICE_LOG, ['msg' => 'ServerException发布失败:'.$e->getErrorMessage()]);
  42. return false;
  43. }
  44. return true;
  45. }
  46. }