Browse Source

语音播报订单流程走完

master
weigang 5 years ago
parent
commit
2b3adc7245
  1. 37
      app/Amqp/Consumer/DevicOrderConsumer.php
  2. 24
      app/Constants/LogLabel.php
  3. 73
      app/Controller/DeviceController.php
  4. 10
      app/Model/Order.php
  5. 10
      app/Model/OrderMain.php
  6. 9
      app/Model/Store.php
  7. 88
      app/Service/DeviceServiceImp.php
  8. 3
      app/Service/DeviceServiceInterFace.php
  9. 54
      app/Service/IOTAliService.php
  10. 8
      app/Service/IOTServiceInterface.php
  11. 89
      app/TaskWorker/AliIotTask.php
  12. 1
      config/autoload/dependencies.php
  13. 1
      config/routes.php

37
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

24
app/Constants/LogLabel.php

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Constants;
use Hyperf\Constants\AbstractConstants;
use Hyperf\Constants\Annotation\Constants;
/**
* @Constants
*/
class LogLabel extends AbstractConstants
{
/**
* @Message("Ssdb Log Label")
*/
const SSDB_LOG = 'ssdb_log';
/**
* @Message("Device Speaker Log Label")
*/
const DEVICE_LOG = 'device_log';
}

73
app/Controller/DeviceController.php

@ -3,9 +3,9 @@
namespace App\Controller;
use Hyperf\Di\Annotation\Inject;
use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Service\DeviceServiceInterFace;
use Hyperf\Validation\ValidationException;
class DeviceController extends BaseController
{
@ -24,7 +24,6 @@ class DeviceController extends BaseController
[
'store_id' => '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]);
}
}

10
app/Model/Order.php

@ -0,0 +1,10 @@
<?php
namespace App\Model;
class Order extends Model
{
protected $table = 'ims_cjdc_order';
}

10
app/Model/OrderMain.php

@ -0,0 +1,10 @@
<?php
namespace App\Model;
class OrderMain extends Model
{
protected $table = 'ims_cjdc_order_main';
}

9
app/Model/Store.php

@ -0,0 +1,9 @@
<?php
namespace App\Model;
class Store extends Model
{
protected $table = 'ims_cjdc_store';
}

88
app/Service/DeviceServiceImp.php

@ -1,29 +1,99 @@
<?php
namespace App\Service;
use App\Commons\Log;
use App\Constants\LogLabel;
use App\Model\SpeakerDevic;
use App\Model\Store;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\ApplicationContext;
use App\TaskWorker\AliIotTask;
class DeviceServiceImp implements DeviceServiceInterFace
{
/**
* @Inject
* @var Log
*/
protected $log;
public function getListByStoreId($store_id){
/**
* @Inject
* @var IOTServiceInterface
*/
protected $IOTService;
/**
* 获取绑定列表
* @param $store_id
* @return \Hyperf\Database\Model\Builder[]|\Hyperf\Database\Model\Collection
*/
public function getListByStoreId($store_id)
{
return SpeakerDevic::query()->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();
}
}

3
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);
}

54
app/Service/IOTAliService.php

@ -0,0 +1,54 @@
<?php
namespace App\Service;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Commons\Log;
use App\Constants\LogLabel;
use Hyperf\Di\Annotation\Inject;
class IOTAliService implements IOTServiceInterface
{
/**
* @Inject
* @var Log
*/
protected $log;
public function pub($device_name, $msg)
{
AlibabaCloud::accessKeyClient(env('ALI_IOT_KEY'), env('ALI_IOT_SECRET'))
->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;
}
}

8
app/Service/IOTServiceInterface.php

@ -0,0 +1,8 @@
<?php
namespace App\Service;
interface IOTServiceInterface
{
public function pub($device_name, $msg);
}

89
app/TaskWorker/AliIotTask.php

@ -1,14 +1,23 @@
<?php
namespace App\TaskWorker;
use App\Commons\Log;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Task\Annotation\Task;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Hyperf\Di\Annotation\Inject;
class AliIotTask
{
/**
* @Inject
* @var Log
*/
protected $log;
/**
* @var DefaultAcsClient
*/
@ -18,74 +27,36 @@ class AliIotTask
/**
* @Task
*/
public function exec($method,...$args)
public function exec($device_name, $msg)
{
AlibabaCloud::accessKeyClient('LTAI4GJEWrN6dVh7HmPKHMyF', 'wMae4ckfVGwMQPVw5ZlVDDpihVeUap')
->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;
// }
}

1
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,
];

1
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');
Loading…
Cancel
Save