From 2b3adc7245e65ea79fc0ff3714ccc4bed2e1c3a5 Mon Sep 17 00:00:00 2001 From: weigang Date: Tue, 4 Aug 2020 19:59:56 +0800 Subject: [PATCH] =?UTF-8?q?=E8=AF=AD=E9=9F=B3=E6=92=AD=E6=8A=A5=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E6=B5=81=E7=A8=8B=E8=B5=B0=E5=AE=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/DevicOrderConsumer.php | 37 ++++++++-- app/Constants/LogLabel.php | 24 +++++++ app/Controller/DeviceController.php | 73 ++++++++++++++++--- app/Model/Order.php | 10 +++ app/Model/OrderMain.php | 10 +++ app/Model/Store.php | 9 +++ app/Service/DeviceServiceImp.php | 88 ++++++++++++++++++++--- app/Service/DeviceServiceInterFace.php | 3 +- app/Service/IOTAliService.php | 54 ++++++++++++++ app/Service/IOTServiceInterface.php | 8 +++ app/TaskWorker/AliIotTask.php | 89 ++++++++---------------- config/autoload/dependencies.php | 1 + config/routes.php | 1 + 13 files changed, 323 insertions(+), 84 deletions(-) create mode 100644 app/Constants/LogLabel.php create mode 100644 app/Model/Order.php create mode 100644 app/Model/OrderMain.php create mode 100644 app/Model/Store.php create mode 100644 app/Service/IOTAliService.php create mode 100644 app/Service/IOTServiceInterface.php diff --git a/app/Amqp/Consumer/DevicOrderConsumer.php b/app/Amqp/Consumer/DevicOrderConsumer.php index ea4cc7d..773f0dd 100644 --- a/app/Amqp/Consumer/DevicOrderConsumer.php +++ b/app/Amqp/Consumer/DevicOrderConsumer.php @@ -4,26 +4,51 @@ declare(strict_types=1); namespace App\Amqp\Consumer; +use App\Model\Order; +use App\Model\SpeakerDevic; +use App\Service\DeviceServiceInterFace; use Hyperf\Amqp\Result; use Hyperf\Amqp\Annotation\Consumer; use Hyperf\Amqp\Message\ConsumerMessage; +use Hyperf\DbConnection\Db; use PhpAmqpLib\Message\AMQPMessage; +use Hyperf\Di\Annotation\Inject; /** * @Consumer(exchange="devicOrder", routingKey="devicOrder", queue="devicOrder", nums=1) */ class DevicOrderConsumer extends ConsumerMessage { - private $msgCount = 0; + /** + * @Inject + * @var DeviceServiceInterFace + */ + protected $deviceService; + public function consumeMessage($data, AMQPMessage $message): string { - var_dump($data); - var_dump($message->getBody()); - if($this->msgCount< 10){ - $this->msgCount += 1; + try { + + $orderMainId = $message->getBody(); + $order = Order::query() + ->select(['id', 'store_id', 'money']) + ->where(['order_main_id' => $orderMainId, 'type' => 4, 'dm_state' => 2]) + ->first(); + + $deviceName = SpeakerDevic::query()->where(['store_id' => $order['store_id']])->value('device_name'); + + $msg = "{\"msg\":\"到账".$order['money']."元\"}"; + $res = $this->deviceService->pubMsgToStoreByDevName($deviceName, $msg); + + if ($res == true) { + return Result::ACK; + } else { + return Result::REQUEUE; + } + + } catch (\Exception $e) { return Result::REQUEUE; } - return Result::ACK; } public function isEnable(): bool diff --git a/app/Constants/LogLabel.php b/app/Constants/LogLabel.php new file mode 100644 index 0000000..b3cadb4 --- /dev/null +++ b/app/Constants/LogLabel.php @@ -0,0 +1,24 @@ + 'required|nonempty|integer', 'device_name' => 'required|nonempty|alpha_num', - ], [ 'store_id.required' => '参数不正确', @@ -36,24 +35,80 @@ class DeviceController extends BaseController ] ); - if ($validator->fails()){ + if ($validator->fails()) { // Handle exception - $errorMessage = $validator->errors()->first(); - $this->result(200,[],$errorMessage); + throw new ValidationException($validator); + return; } - $store_id = $this->request->input('store_id'); $device_name = $this->request->input('device_name'); - $sd = $this->deviceService->bindByStoreId($device_name,$store_id); + $sd = $this->deviceService->bindByStoreId($device_name, $store_id); - return $this->result(0,[$sd],'绑定成功'); + if (is_null($sd)) { + return $this->result(100, '', '绑定失败: 设备号已经被绑定或不存在'); + } + + return $this->success($sd, '绑定成功'); } public function list() { - + $validator = $this->validationFactory->make( + $this->request->all(), + [ + 'store_id' => 'required|nonempty|integer', + ], + [ + 'store_id.required' => '参数不正确', + 'store_id.nonempty' => '参数不正确', + 'store_id.integer' => '参数不正确', + ] + ); + + if ($validator->fails()) { + // Handle exception + throw new ValidationException($validator); + return; + } + + $store_id = $this->request->input('store_id'); + + $devices = $this->deviceService->getListByStoreId($store_id); + + return $this->success($devices); + } + + public function unbind() + { + $validator = $this->validationFactory->make( + $this->request->all(), + [ + 'bind_id' => 'required|nonempty|integer', + ], + [ + 'bind_id.required' => '参数不正确', + 'bind_id.nonempty' => '参数不正确', + 'bind_id.integer' => '参数不正确', + ] + ); + + if ($validator->fails()) { + // Handle exception + throw new ValidationException($validator); + return; + } + + $bind_id = $this->request->input('bind_id'); + + $unbind_num = $this->deviceService->unbindById($bind_id); + + if ($unbind_num == 0) { + return $this->result(100, '', '解绑失败: 设备已经解绑或不存在'); + } + + return $this->success(['unbind' => $unbind_num]); } } \ No newline at end of file diff --git a/app/Model/Order.php b/app/Model/Order.php new file mode 100644 index 0000000..0a5bdd4 --- /dev/null +++ b/app/Model/Order.php @@ -0,0 +1,10 @@ +where(['store_id' => $store_id])->get(); } - public function bindByStoreId($dev_name,$store_id){ + + /** + * 绑定 + * @param $dev_name + * @param $store_id + * @return SpeakerDevic|null + * @throws \Throwable + */ + public function bindByStoreId($dev_name, $store_id) + { $sd = null; - try{ - $sd = new SpeakerDevic; + + if ($this->checkDeviceEnable($dev_name)) { + return $sd; + } + + try { + + // 获取市场ID + $market_id = Store::query()->where(['id' => $store_id])->value('market_id'); + + $sd = new SpeakerDevic; $sd->store_id = $store_id; $sd->device_name = $dev_name; - $sd->market_id = 1; + $sd->market_id = $market_id; $sd->bind_time = time(); $sd->saveOrFail(); - }catch(Exception $e){ - //var_dump($e); + } catch (Exception $e) { + $this->log->event(LogLabel::DEVICE_LOG, ['msg' => '绑定设备异常:'.$e->getMessage()]); } return $sd; } - public function pubMsgByStoreIdAndDevName($dev_name,$store_id,$msg){ + /** + * 解绑 + * @param $bind_id + * @return int + */ + public function unbindById($bind_id) + { + return SpeakerDevic::destroy($bind_id); + } + + /** + * 发布语音消息 + * @param $store_id + * @param $msg + */ + public function pubMsgToStoreByDevName($dev_name, $msg) + { + return $this->IOTService->pub($dev_name, $msg); } + + /** + * 当前设备是否已经被绑定 + * @param $dev_name + * @return bool + */ + protected function checkDeviceEnable($dev_name) + { + return SpeakerDevic::query()->where(['device_name' => $dev_name])->exists(); + } + } \ No newline at end of file diff --git a/app/Service/DeviceServiceInterFace.php b/app/Service/DeviceServiceInterFace.php index e22e184..2bb9cb0 100644 --- a/app/Service/DeviceServiceInterFace.php +++ b/app/Service/DeviceServiceInterFace.php @@ -6,5 +6,6 @@ interface DeviceServiceInterFace { public function getListByStoreId($store_id); public function bindByStoreId($dev_name,$store_id); - public function pubMsgByStoreIdAndDevName($dev_name,$store_id,$msg); + public function unbindById($bind_id); + public function pubMsgToStoreByDevName($dev_name,$msg); } \ No newline at end of file diff --git a/app/Service/IOTAliService.php b/app/Service/IOTAliService.php new file mode 100644 index 0000000..6b8a854 --- /dev/null +++ b/app/Service/IOTAliService.php @@ -0,0 +1,54 @@ +regionId(env('ALI_IOT_REGION')) + ->asDefaultClient(); + + try { + AlibabaCloud::rpc() + ->product('Iot') + ->version('2018-01-20') + ->action('Pub') + ->method('POST') + ->host(env('ALI_IOT_HOST')) + ->options([ + 'query' => [ + 'RegionId' => "cn-shanghai", + 'TopicFullName' => "/a1ZSurIJmO0/".$device_name."/user/get", + 'MessageContent' => base64_encode($msg), + 'ProductKey' => env('ALI_IOT_PRODUCT_KEY'), + ], + ]) + ->request(); + } catch (ClientException $e) { + $this->log->event(LogLabel::DEVICE_LOG, ['msg' => 'ClientException发布失败:'.$e->getErrorMessage()]); + return false; + } catch (ServerException $e) { + $this->log->event(LogLabel::DEVICE_LOG, ['msg' => 'ServerException发布失败:'.$e->getErrorMessage()]); + return false; + } + + return true; + } + +} \ No newline at end of file diff --git a/app/Service/IOTServiceInterface.php b/app/Service/IOTServiceInterface.php new file mode 100644 index 0000000..931aca6 --- /dev/null +++ b/app/Service/IOTServiceInterface.php @@ -0,0 +1,8 @@ +regionId('cn-shanghai') - ->asDefaultClient(); - $result2 = ''; - - $msg = "{\"msg\":\"收款123元\"}"; - try{ - AlibabaCloud::rpc() - ->product('Iot') - // ->scheme('https') // https | http - ->version('2018-01-20') - ->action('Pub') - ->method('POST') - ->host('iot.cn-shanghai.aliyuncs.com') - ->options([ - 'query' => [ - 'RegionId' => "cn-shanghai", - 'TopicFullName' => "/a1ZSurIJmO0/BOX0000000000003/user/get", - 'MessageContent' => base64_encode($msg), - 'ProductKey' => "a1ZSurIJmO0", - ], - ]) - ->request(); - //var_dump($result2->toArray()); + ->regionId('cn-shanghai') + ->asDefaultClient(); + + try { + AlibabaCloud::rpc() + ->product('Iot') + ->version('2018-01-20') + ->action('Pub') + ->method('POST') + ->host('iot.cn-shanghai.aliyuncs.com') + ->options([ + 'query' => [ + 'RegionId' => "cn-shanghai", + 'TopicFullName' => "/a1ZSurIJmO0/".$device_name."/user/get", + 'MessageContent' => base64_encode($msg), + 'ProductKey' => "a1ZSurIJmO0", + ], + ]) + ->request(); } catch (ClientException $e) { echo $e->getErrorMessage() . PHP_EOL; } catch (ServerException $e) { echo $e->getErrorMessage() . PHP_EOL; } - //print_r($response); - return ""; + return true; } -// protected function getClient(){ -// AlibabaCloud::accessKeyClient('LTAI4GJEWrN6dVh7HmPKHMyF', 'wMae4ckfVGwMQPVw5ZlVDDpihVeUap') -// ->regionId('cn-shanghai') -// ->asDefaultClient(); -// $result = ''; - -// $msg = "{\"msg\":\"收款123元\"}"; -// try{ -// $result = AlibabaCloud::rpc() -// ->product('Iot') -// // ->scheme('https') // https | http -// ->version('2018-01-20') -// ->action('Pub') -// ->method('POST') -// ->host('iot.cn-shanghai.aliyuncs.com') -// ->options([ -// 'query' => [ -// 'RegionId' => "cn-shanghai", -// 'TopicFullName' => "/a1ZSurIJmO0/BOX0000000000003/user/get", -// 'MessageContent' => base64_encode($msg), -// 'ProductKey' => "a1ZSurIJmO0", -// ], -// ]) -// ->request(); -// var_dump($result->toArray()); -// } catch (ClientException $e) { -// echo $e->getErrorMessage() . PHP_EOL; -// } catch (ServerException $e) { -// echo $e->getErrorMessage() . PHP_EOL; -// } -// return $result; - -// } } diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index 4b46ec8..c147e40 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -15,4 +15,5 @@ return [ \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class, \App\Service\DeviceServiceInterFace::class =>\App\Service\DeviceServiceImp::class, \App\Commons\Log::class => \App\Commons\Log::class, + \App\Service\IOTServiceInterface::class => \App\Service\IOTAliService::class, ]; diff --git a/config/routes.php b/config/routes.php index 0eebd7e..a067b45 100644 --- a/config/routes.php +++ b/config/routes.php @@ -32,6 +32,7 @@ Router::addGroup('/v1/',function (){ //播报器相关 Router::post('Device/bind', 'App\Controller\DeviceController@bind'); Router::post('Device/list', 'App\Controller\DeviceController@list'); + Router::post('Device/unbind', 'App\Controller\DeviceController@unbind'); //测试路由 Router::get('test/index1', 'App\Controller\TestController@index1');