Commit f19360e9 by banice

修改topic共用同一个

parent a68a3ab6
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/11
* Time: 上午10:49
*/
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TestController extends Controller
{
public function test()
{
}
private function hello(Request $request)
{
return $request->all();
}
public function testDirection(Request $request)
{
dd($request->all());
}
}
\ No newline at end of file
...@@ -9,47 +9,128 @@ ...@@ -9,47 +9,128 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Http\model\BatteryModel;
use App\model\OrderModel;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Lib\aliyun\api\PublishToTopic; use Lib\aliyun\api\PublishToTopic;
use Lib\aliyun\Client; use Lib\aliyun\Client;
use Lib\command\ConfirmOpenDoor; use Lib\command\ConfirmOpenDoor;
use Lib\command\OpenDoor;
use phpDocumentor\Reflection\Types\Self_;
use Src\battery\Battery;
use Src\box\Box; use Src\box\Box;
use Src\box\door\Door;
use Src\order\Order;
use Src\order\OrderCache;
use Src\pay_rule\CashPay;
class UpdateController extends Controller class UpdateController extends Controller
{ {
public function update(Request $request) const COMMAND = [
'return_open_door' => 11,
'confirm_return_open_door' => 92,
'close_return_door' => 93,
];
public function update(Request $request, Order $order)
{ {
Log::debug('update'); $payload = $request->get('payload');
Log::debug($request->all()); return;
$payload = $request->get('payload'); $client = $payload['client'];
$door = $payload['doors'];
$boxNum = $door['box_num'];
$doorNum = $door['door_num'];
$operation = $door['operation'];
$orderId = $door['order_id'];
$boxCode = $request->get('box_code');
//todo 检查订单是否存在,websocket推送打开门成功,检查电池是否放入,
$confirmOpenDoor = new ConfirmOpenDoor();
$confirmOpenDoor->setOrderId($orderId);
$publishToTopic = new PublishToTopic();
$publishToTopic->setMessageContent($confirmOpenDoor->getMessage());
$publishToTopic->setProductKey(env('MQTT_PRODUCT_KEY'));
$publishToTopic->setTopicFullName(Box::getOpenDoorTopic($boxCode));
$client = new Client();
$client->setApi($publishToTopic);
if ($client->request() === true) {
Log::debug('confirm order -' . $orderId);
if ($client === 'battery') {
Log::debug('battery');
return;
} }
//hdg
$topic = $payload['hdg_topic'];
switch ($topic) {
case 'open_door':
break;
default:
break;
} }
switch ($payload['command']) {
case self::COMMAND['return_open_door']:
break;
case self::COMMAND['close_return_door']:
break;
case 0:
break;
default:
break;
}
//todo 根据订单号查找到用户的电池比对,比对打开舱门是否正确
break;
default:
break;
}
}
} }
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/12
* Time: 上午12:43
*/
namespace App\Http\Controllers\battery;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class UpdateController extends Controller
{
public function update(Request $request)
{
Log::debug($request->all());
}
}
\ No newline at end of file
...@@ -11,7 +11,7 @@ namespace App\Http\Controllers\door; ...@@ -11,7 +11,7 @@ namespace App\Http\Controllers\door;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use src\box\Box; use Src\box\Box;
use Validator; use Validator;
class InitController extends Controller class InitController extends Controller
......
...@@ -19,12 +19,14 @@ class StateController extends Controller ...@@ -19,12 +19,14 @@ class StateController extends Controller
public function state(Request $request) public function state(Request $request)
{ {
Log::debug('door');
Log::debug('haha');
$boxCode = $request->get('box_code'); $boxCode = $request->get('box_code');
$payload = $request->get('payload'); $payload = $request->get('payload');
Log::debug($payload);
$validator = Validator::make($payload, [ $validator = Validator::make($payload, [
'door_count' => 'required|integer', 'door_count' => 'required|integer',
'door' => 'required|array' 'door' => 'required|array'
...@@ -33,14 +35,9 @@ class StateController extends Controller ...@@ -33,14 +35,9 @@ class StateController extends Controller
$doorCount = $payload['door_count']; $doorCount = $payload['door_count'];
$doorArray = $payload['door']; $doorArray = $payload['door'];
if (count($doorArray) === (int)$doorCount) { // if (count($doorArray) === (int)$doorCount) {
//
foreach ($doorArray as $item) { // }
Log::debug($item);
}
}
} }
} }
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/11
* Time: 上午9:55
*/
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Closure;
use Illuminate\Support\Facades\Log;
use Lib\messageId\MessageExist;
class MessageLogMiddleware
{
/**
* @param Request $request
* @param Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
$response = $next($request);
$state = $request->get('message_state', MessageExist::STATE['handle']);
$messageId = $request->get('message_id');
$messageExist = new MessageExist();
$messageExist->add($messageId, $state);
return $response;
}
}
\ No newline at end of file
...@@ -14,6 +14,7 @@ use Closure; ...@@ -14,6 +14,7 @@ use Closure;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Response; use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Lib\messageId\MessageExist;
use Validator; use Validator;
class MqttMiddleware class MqttMiddleware
...@@ -21,9 +22,7 @@ class MqttMiddleware ...@@ -21,9 +22,7 @@ class MqttMiddleware
public function handle(Request $request, Closure $next) public function handle(Request $request, Closure $next)
{ {
$data = $request->all(); Log::debug($request->all());
Log::debug('mqtt middleware');
$validator = Validator::make($request->all(), [ $validator = Validator::make($request->all(), [
...@@ -39,28 +38,39 @@ class MqttMiddleware ...@@ -39,28 +38,39 @@ class MqttMiddleware
if ($validator->fails() === true) { if ($validator->fails() === true) {
Log::error($validator->errors()->first()); Log::error($validator->errors()->first());
return; return new Response();
abort(400, $validator->errors()->first());
} }
if (strtoupper(md5($request->get('Message'))) != $request->get('MessageMD5')) { if (strtoupper(md5($request->get('Message'))) != $request->get('MessageMD5')) {
Log::error('md5 error' . $request->get('MessageId')); Log::error('md5 error' . $request->get('MessageId'));
abort(400, ' invalid ');
return new Response(); return new Response();
} }
$message = json_decode($request->get('Message'), true); $message = json_decode($request->get('Message'), true);
$messageId = $message['MessageId'];
app()->register(RedisServiceProvider::class); Log::debug($message);
$messageId = $request->get('MessageId');
$messageExist = new MessageExist();
try {
if ($messageExist->exists($messageId) === true) {
Log::debug('message existed');
return new Response();
}
} catch (\Exception $exception) {
Log::error($exception->getMessage());
}
$boxCode = $message['box_code']; $boxCode = $message['box_code'];
$payload = json_decode($message['payload'], true); $payload = json_decode($message['payload'], true);
$request->merge(['box_code' => $boxCode, 'payload' => $payload]); $request->merge(['box_code' => $boxCode, 'payload' => $payload, 'message_id' => $messageId]);
return $next($request); return $next($request);
......
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/14
* Time: 下午8:51
*/
namespace App\Http\model;
use Illuminate\Database\Eloquent\Model;
class BatteryModel extends Model
{
protected $table = 'batteries';
}
\ No newline at end of file
...@@ -22,9 +22,7 @@ class RedisServiceProvider extends ServiceProvider ...@@ -22,9 +22,7 @@ class RedisServiceProvider extends ServiceProvider
$this->app->singleton('Redis', function ($app) { $this->app->singleton('Redis', function ($app) {
$redis = new \Redis(); $redis = new \Redis();
$config = config('database.redis.default'); $config = config('database.redis.default');
$redis->connect($config['host']); $redis->connect($config['host']);
$redis->select($config['database']); $redis->select($config['database']);
......
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/13
* Time: 下午7:29
*/
namespace App\model;
use Illuminate\Database\Eloquent\Model;
class ActivityModel extends Model
{
protected $table = 'activities';
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/17
* Time: 下午8:40
*/
namespace App\model;
use Illuminate\Database\Eloquent\Model;
class BoxModel extends Model
{
protected $table = 'boxes';
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/8
* Time: 上午10:43
*/
namespace App\model;
use Illuminate\Database\Eloquent\Model;
use Src\box\door\Door;
class DoorModel extends Model
{
protected $table = 'box_rooms';
public function add(Door $door)
{
$this->name = $door->getName();
$this->box_type = $door->getBoxType();
$this->box_id = $door->getBoxId();
return $this->save();
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/7
* Time: 下午9:22
*/
namespace App\model;
use Illuminate\Database\Eloquent\Model;
use Src\order\Order;
use DB;
class OrderModel extends Model
{
protected $table = 'orders';
public function initOrder(Order $order)
{
$this->code = $order->getOutTradeNo();
$this->guest_id = $order->getUserId();
$this->site_id = $order->getSite()->getId();
$this->site_name = $order->getSite()->getName();
$this->out_room_id = $order->getTakeDoor()->getId();
$this->out_box_id = $order->getTakeBox()->getId();
$this->out_room_name = $order->getTakeDoor()->getName();
$this->box_code = $order->getBoxCode();
$this->status = 1;
$this->out_date = date('Y-m-d H:i:s');
return $this->save();
}
public function searchLastOrder(int $userId)
{
return DB::select('select * from orders where id = (select max(id) from orders where guest_id = ' . $userId . ')');
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/13
* Time: 下午7:10
*/
namespace App\model;
use Illuminate\Database\Eloquent\Model;
class PayGroupModel extends Model
{
protected $table = 'pay_groups';
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/13
* Time: 下午2:28
*/
namespace App\model;
use Illuminate\Database\Eloquent\Model;
class SystemModel extends Model
{
protected $table = 'system';
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/13
* Time: 下午7:34
*/
namespace App\model;
use Illuminate\Database\Eloquent\Model;
use DB;
class TicketModel extends Model
{
protected $table = 'tickets';
/**
* @param int $userId
* @return int
*/
public function getUserTicket(int $userId): int
{
$today = date('Y-m-d H:i:s');
$ticketId = DB::table('tickets')->where([
['begin_date', '<', $today],
['end_date', '>', $today],
['guest_id', $userId],
['status', 1],
])->min('id');
if (blank($ticketId)) {
return 0;
}
$amount = DB::table('tickets')->where('id', $ticketId)->first(['amount']);
return $amount['amount'];
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/7
* Time: 上午11:37
*/
namespace App\model;
use Illuminate\Database\Eloquent\Model;
use Lib\wx\User;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Auth\Authenticatable;
use Illuminate\Support\Facades\Log;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
class UserModel extends Model implements JWTSubject, AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable;
protected $table = 'guests';
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
$return = [
'wx_authorize' => false
];
if (isset($this->open_id) === true) {
if ($this->open_id != null) {
$return['wx_authorize'] = true;
}
}
return $return;
}
public function addWxUser(User $user)
{
$this->open_id = $user->getOpenId();
$this->session_key = $user->getSessionId();
$this->telephone = $user->getPhone();
$this->pure_phone = $user->getPurePhone();
$this->country_code = $user->getCountryCode();
return $this->save();
}
}
\ No newline at end of file
...@@ -72,7 +72,8 @@ $app->singleton( ...@@ -72,7 +72,8 @@ $app->singleton(
$app->routeMiddleware([ $app->routeMiddleware([
// 'auth' => App\Http\Middleware\Authenticate::class, // 'auth' => App\Http\Middleware\Authenticate::class,
'mqtt' => \App\Http\Middleware\MqttMiddleware::class, 'mqtt' => \App\Http\Middleware\MqttMiddleware::class,
'message_exist' => \App\Http\Middleware\MessageLogMiddleware::class,
]); ]);
/* /*
...@@ -87,7 +88,7 @@ $app->routeMiddleware([ ...@@ -87,7 +88,7 @@ $app->routeMiddleware([
*/ */
$app->register(App\Providers\AppServiceProvider::class); $app->register(App\Providers\AppServiceProvider::class);
//$app->register(\App\Providers\RedisServiceProvider::class); $app->register(\App\Providers\RedisServiceProvider::class);
// $app->register(App\Providers\AuthServiceProvider::class); // $app->register(App\Providers\AuthServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class); // $app->register(App\Providers\EventServiceProvider::class);
......
...@@ -11,5 +11,6 @@ return [ ...@@ -11,5 +11,6 @@ return [
'AC_ALARM' => 'hdg:ac:alarm:hash', 'AC_ALARM' => 'hdg:ac:alarm:hash',
'MESSAGE_EXIST' => 'hdg:message:exist', 'MESSAGE_EXIST' => 'hdg:message:exist',
'BATTERY_QUANTITY' => 'hdg:battery:quantity:',
]; ];
This diff is collapsed. Click to expand it.
...@@ -16,6 +16,8 @@ class ConfirmOpenDoor implements Command ...@@ -16,6 +16,8 @@ class ConfirmOpenDoor implements Command
private $orderId = ''; private $orderId = '';
private $operationType = 1;
public function getMessage(): string public function getMessage(): string
{ {
...@@ -24,6 +26,8 @@ class ConfirmOpenDoor implements Command ...@@ -24,6 +26,8 @@ class ConfirmOpenDoor implements Command
'command' => $this->command, 'command' => $this->command,
'order_id' => $this->orderId, 'order_id' => $this->orderId,
'hdg_topic' => 'open_door',
'operation_type' => $this->operationType,
]); ]);
} }
...@@ -60,5 +64,21 @@ class ConfirmOpenDoor implements Command ...@@ -60,5 +64,21 @@ class ConfirmOpenDoor implements Command
$this->orderId = $orderId; $this->orderId = $orderId;
} }
/**
* @return int
*/
public function getOperationType(): int
{
return $this->operationType;
}
/**
* @param int $operationType
*/
public function setOperationType(int $operationType): void
{
$this->operationType = $operationType;
}
} }
\ No newline at end of file
...@@ -9,10 +9,23 @@ ...@@ -9,10 +9,23 @@
namespace Lib\command; namespace Lib\command;
use Src\box\Box;
use Src\box\door\Door;
class OpenDoor implements Command class OpenDoor implements Command
{ {
private $command = '11'; private $command = '11';
/**
* @var Box
*/
private $box;
/**
* @var Door
*/
private $door;
private $boxNum = 0; private $boxNum = 0;
private $doorNum = 0; private $doorNum = 0;
...@@ -21,23 +34,70 @@ class OpenDoor implements Command ...@@ -21,23 +34,70 @@ class OpenDoor implements Command
private $operation = 1; private $operation = 1;
private $operationType = 1;
private $boxId = 0;
private $doorId = 0;
public function getMessage(): string public function getMessage(): string
{ {
return json_encode([ return json_encode([
'command' => $this->command, 'command' => $this->command,
'hdg_topic' => 'open_door',
'doors' => [ 'doors' => [
'box_num' => $this->boxNum, 'box_num' => $this->boxNum,
'door_num' => $this->doorNum, 'door_num' => $this->doorNum,
'order_id' => $this->orderId, 'order_id' => $this->orderId,
'operation' => $this->operation 'operation' => $this->operation,
'door_id' => $this->doorId,
'box_id' => $this->boxId,
'operation_type' => $this->operationType,
] ]
]); ]);
} }
/** /**
* @return Box
*/
public function getBox(): Box
{
return $this->box;
}
/**
* @param Box $box
*/
public function setBox(Box $box): void
{
$this->boxId = $box->getId();
$this->boxNum = $box->getName();
$this->box = $box;
}
/**
* @return Door
*/
public function getDoor(): Door
{
return $this->door;
}
/**
* @param Door $door
*/
public function setDoor(Door $door): void
{
$this->doorId = $door->getId();
$this->doorNum = $door->getName();
$this->door = $door;
}
/**
* @return string * @return string
*/ */
public function getCommand(): string public function getCommand(): string
...@@ -117,5 +177,53 @@ class OpenDoor implements Command ...@@ -117,5 +177,53 @@ class OpenDoor implements Command
$this->operation = $operation; $this->operation = $operation;
} }
/**
* @return int
*/
public function getOperationType(): int
{
return $this->operationType;
}
/**
* @param int $operationType
*/
public function setOperationType(int $operationType): void
{
$this->operationType = $operationType;
}
/**
* @return int
*/
public function getBoxId(): int
{
return $this->boxId;
}
/**
* @param int $boxId
*/
public function setBoxId(int $boxId): void
{
$this->boxId = $boxId;
}
/**
* @return int
*/
public function getDoorId(): int
{
return $this->doorId;
}
/**
* @param int $doorId
*/
public function setDoorId(int $doorId): void
{
$this->doorId = $doorId;
}
} }
\ No newline at end of file
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
namespace Lib\messageId; namespace Lib\messageId;
use Illuminate\Support\Facades\Log;
use Mockery\Exception; use Mockery\Exception;
class MessageExist class MessageExist
...@@ -65,7 +66,7 @@ class MessageExist ...@@ -65,7 +66,7 @@ class MessageExist
{ {
$redis = app('Redis'); $redis = app('Redis');
if ($redis instanceof \Redis) { if ($redis instanceof \Redis) {
$redis->zAdd($this->todayKey(), $this->state, $this->id); $redis->zAdd($this->todayKey(), (int)$state, $id);
if ($redis->exists($this->yesterdayKey())) { if ($redis->exists($this->yesterdayKey())) {
$redis->setTimeout($this->yesterdayKey(), 7 * 60 * 60 * 24); $redis->setTimeout($this->yesterdayKey(), 7 * 60 * 60 * 24);
} }
......
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/11
* Time: 下午3:05
*/
namespace Lib\web_socket;
abstract class Message
{
protected $command = '';
abstract public function getMessage(): string;
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/11
* Time: 下午3:06
*/
namespace Lib\web_socket;
class OpenDoorResult extends Message
{
private $startTime = '';
/**
* @var string
*/
private $outTradeNo = '';
/**
* @var string
*/
private $operation = 'open';
/**
* @var string
*/
private $result = 'FAIL';
private $takeBoxNum = 0;
private $takeDoorNum = 0;
/**
* @return string
*/
public function getMessage(): string
{
return json_encode([
'command' => $this->command,
'data' => [
'out_trade_no' => $this->outTradeNo,
'operation' => $this->operation,
'result' => $this->result,
'start_time' => $this->startTime,
'take_box_num' => $this->takeBoxNum,
'take_door_num' => $this->takeDoorNum,
],
]);
}
/**
* @return int
*/
public function getTakeBoxNum(): int
{
return $this->takeBoxNum;
}
/**
* @param int $takeBoxNum
*/
public function setTakeBoxNum(int $takeBoxNum): void
{
$this->takeBoxNum = $takeBoxNum;
}
/**
* @return int
*/
public function getTakeDoorNum(): int
{
return $this->takeDoorNum;
}
/**
* @param int $takeDoorNum
*/
public function setTakeDoorNum(int $takeDoorNum): void
{
$this->takeDoorNum = $takeDoorNum;
}
/**
* @return string
*/
public function getOutTradeNo(): string
{
return $this->outTradeNo;
}
/**
* @param string $outTradeNo
*/
public function setOutTradeNo(string $outTradeNo): void
{
$this->outTradeNo = $outTradeNo;
}
/**
* @return string
*/
public function getOperation(): string
{
return $this->operation;
}
/**
* @param string $operation
*/
public function setOperation(string $operation): void
{
$this->operation = $operation;
}
/**
* @return string
*/
public function getResult(): string
{
return $this->result;
}
/**
* @param string $result
*/
public function setResult(string $result): void
{
$this->result = $result;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/11
* Time: 下午3:05
*/
namespace Lib\web_socket;
class PushClient
{
}
\ No newline at end of file
...@@ -16,20 +16,24 @@ $router->get('/', function () use ($router) { ...@@ -16,20 +16,24 @@ $router->get('/', function () use ($router) {
return $router->app->version(); return $router->app->version();
}); });
$router->group(['middleware' => ['mqtt']], function () use ($router) { $router->group(['middleware' => ['mqtt', 'message_exist']], function () use ($router) {
$router->get('ac/version_info', 'ac\VersionController@get'); $router->get('ac/version_info', 'ac\VersionController@get');
$router->post('ac/version_info', 'ac\VersionController@get'); $router->post('ac/version_info', 'ac\VersionController@get');
$router->get('ac/state', 'ac\StateController@get'); $router->get('ac/state', 'ac\StateController@get');
$router->post('ac/state', 'ac\StateController@post'); $router->post('ac/state', 'ac\StateController@post');
$router->post('door/lock/version', 'door\LockController@version'); $router->post('door/lock/version', 'door\LockController@version');
$router->post('door/state', 'door\StateController@post'); $router->post('door/state', 'door\StateController@state');
$router->post('ac/alarm/info', 'ac\AlarmController@post'); $router->post('ac/alarm/info', 'ac\AlarmController@post');
$router->post('update', 'UpdateController@update'); $router->post('update', 'UpdateController@update');
$router->post('battery/update', 'BatteryController@update');
}); });
$router->get('test', 'TestController@test');
$router->post('door/opening', 'door\OpenController@post'); $router->post('door/opening', 'door\OpenController@post');
$router->post('box/init', 'door\InitController@init'); $router->post('box/init', 'door\InitController@init');
......
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/8
* Time: 上午11:11
*/
namespace Src;
class Site
{
private $id = 0;
private $name = '';
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param int $id
*/
public function setId(int $id): void
{
$this->id = $id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $name
*/
public function setName(string $name): void
{
$this->name = $name;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/8
* Time: 上午11:12
*/
namespace Src\battery;
class Battery
{
use SearchMaxQuantity;
private $id = 0;
private $code = '';
private $voltage = 0;
private $quantity = 0;
private $mosTmp = 0;
private $maxTmp = 0;
private $minTmp = 0;
private $reserve = 0;
private $boxNum = 0;
private $doorNum = 0;
public static function getRedisKey(string $boxCode)
{
return config('redis_key.BATTERY_QUANTITY') . ':' . $boxCode;
}
public function updateQuantity(int $quantity)
{
$redis = app('Redis');
if ($redis instanceof \Redis) {
$redis->zAdd(static::getRedisKey($this->boxCode), $quantity, $this->id);
}
}
/**
* @return string
*/
public function getCode(): string
{
return $this->code;
}
/**
* @param string $code
*/
public function setCode(string $code): void
{
$this->code = $code;
}
/**
* @return int
*/
public function getVoltage(): int
{
return $this->voltage;
}
/**
* @param int $voltage
*/
public function setVoltage(int $voltage): void
{
$this->voltage = $voltage;
}
/**
* @return int
*/
public function getQuantity(): int
{
return $this->quantity;
}
/**
* @param int $quantity
*/
public function setQuantity(int $quantity): void
{
$this->quantity = $quantity;
}
/**
* @return int
*/
public function getMosTmp(): int
{
return $this->mosTmp;
}
/**
* @param int $mosTmp
*/
public function setMosTmp(int $mosTmp): void
{
$this->mosTmp = $mosTmp;
}
/**
* @return int
*/
public function getMaxTmp(): int
{
return $this->maxTmp;
}
/**
* @param int $maxTmp
*/
public function setMaxTmp(int $maxTmp): void
{
$this->maxTmp = $maxTmp;
}
/**
* @return int
*/
public function getMinTmp(): int
{
return $this->minTmp;
}
/**
* @param int $minTmp
*/
public function setMinTmp(int $minTmp): void
{
$this->minTmp = $minTmp;
}
/**
* @return int
*/
public function getReserve(): int
{
return $this->reserve;
}
/**
* @param int $reserve
*/
public function setReserve(int $reserve): void
{
$this->reserve = $reserve;
}
/**
* @return int
*/
public function getBoxNum(): int
{
return $this->boxNum;
}
/**
* @param int $boxNum
*/
public function setBoxNum(int $boxNum): void
{
$this->boxNum = $boxNum;
}
/**
* @return int
*/
public function getDoorNum(): int
{
return $this->doorNum;
}
/**
* @param int $doorNum
*/
public function setDoorNum(int $doorNum): void
{
$this->doorNum = $doorNum;
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param int $id
*/
public function setId(int $id): void
{
$this->id = $id;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/12
* Time: 上午12:49
*/
namespace src\battery;
trait SearchMaxQuantity
{
private $boxCode = '';
/**
* 查找电柜中电量最足的电池
* @param string $boxCode
* @return int
*/
public function searchMaxQuantity(string $boxCode): int
{
$this->boxCode = $boxCode;
$redis = app('Redis');
if ($redis instanceof \Redis) {
$max = $redis->zRange(Battery::getRedisKey($boxCode), -1, -1);
return blank($max) ? 0 : current($max);
}
}
/**
* @param string $batteryCode
* @param string $boxCode
* @return int
*/
public function getBatteryQuantity(string $batteryCode, string $boxCode): int
{
$redis = app('Redis');
if ($redis instanceof \Redis) {
$quantity = $redis->zScore(Battery::getRedisKey($boxCode), $batteryCode);
return blank($quantity) ? 0 : $quantity;
}
}
}
\ No newline at end of file
...@@ -37,9 +37,14 @@ class Box ...@@ -37,9 +37,14 @@ class Box
} }
public function __get($name)
{
return $this->$name;
}
public static function getOpenDoorTopic(string $boxCode) public static function getOpenDoorTopic(string $boxCode)
{ {
return env('MQTT_PRODUCT_KEY') . '/' . $boxCode . '/open_door'; return env('MQTT_PRODUCT_KEY') . '/' . $boxCode . '/hdg_get';
} }
......
...@@ -14,6 +14,11 @@ use Log; ...@@ -14,6 +14,11 @@ use Log;
class Door class Door
{ {
const OPERATION = [
'close' => 0,
'open' => 1,
];
const STATE = [ const STATE = [
...@@ -55,6 +60,11 @@ class Door ...@@ -55,6 +60,11 @@ class Door
private $boxNum = 0; private $boxNum = 0;
public function __get($name)
{
return $this->$name;
}
/** /**
* @var int * @var int
* 1: 开门 * 1: 开门
......
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/16
* Time: 上午9:36
*/
namespace src\client;
use Illuminate\Http\Request;
interface Client
{
public function handle(Request $request);
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/16
* Time: 上午9:56
*/
namespace src\client\open_door;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Lib\aliyun\api\PublishToTopic;
use Lib\command\OpenDoor;
use Src\battery\Battery;
use Src\box\Box;
use Src\box\door\Door;
use src\client\Client;
use Src\order\Order;
use Src\order\OrderCache;
use Src\pay_rule\CashPay;
class ReturnBattery implements Client
{
public function handle(Request $request)
{
$payload = $request->get('payload');
$payload = $payload['doors'];
$outTradeNo = $payload['order_id'];
$batteryCode = $payload['battery_code'];
$doorNum = $payload['door_num'];
$boxNum = $payload['box_num'];
$boxCode = $request->get('box_code');
$operationType = $payload['operation_type'];
$orderCache = new OrderCache();
$order = new Order();
$order->setOutTradeNo($outTradeNo);
$orderCache = new OrderCache();
$orderCache->setOrder($order);
$cache = $orderCache->getCache();
if (blank($cache) === true) {
Log::error('can not find order cache ---' . $outTradeNo);
return;
}
switch ($operationType) {
case 1:
if (blank($batteryCode) === true) {
//todo 提示未归还电池
Log::info('close return door without battery');
return;
} else {
$returnBoxId = $cache['returnBoxId'];
$returnDoorId = $cache['returnDoorId'];
//todo 更新订单结算支付金额,存入数据库
$orderModel = OrderModel::where('code', $outTradeNo)->firt();
$cashRule = new CashPay();
$cashRule->setOrderModel($orderModel);
$payAmount = $cashRule->getPayAmount();
$date = date('Y-m-d H:i:s');
DB::table('orders')->where('code', $outTradeNo)->update([
'in_date' => $date,
'in_box_id' => $returnBoxId,
'in_room_id' => $returnDoorId,
'in_battery_code' => $batteryCode,
'rent_money' => $payAmount,
'use_money' => $payAmount,
'in_room_name' => $boxNum,
'in_site_name' => '利尔达', //fixme 从boxcode反查获得,
'in_site_id' => 1, //fixme
]);
//todo web socket 推送还电成功,打开新的电池柜舱门
//todo 更新电池归属,更新电池电量
//todo 查找电量最大的电池仓下发打开命令
$orderCache = new OrderCache();
$order->setOutTradeNo($outTradeNo);
$cache = $orderCache->getCache();
$userId = $cache['useId'];
$battery = new Battery();
$maxBatteryId = $battery->searchMaxQuantity($boxCode);
$batteryModel = BatteryModel::find($maxBatteryId);
$outTradeNo = $boxCode . rand(10000, 999999);
$takeBox = new Box();
$takeBox->setName($batteryModel->box_type);
$takeBox->setId($batteryModel->box_id);
$takeDoor = new Door();
$takeDoor->setName($batteryModel->door_name);
$takeDoor->setId($batteryModel->room_id);
$order->setOutTradeNo($outTradeNo);
$order->setTakeBox($takeBox);
$order->setTakeDoor($takeDoor);
$order->setUserId($userId);
$orderModel = new OrderModel();
$orderModel->initOrder($order);
$openDoorCommand = new OpenDoor();
$openDoorCommand->setOrderId($order->getOutTradeNo());
$openDoorCommand->setBoxNum($order->getTakeBox()->getName());
$openDoorCommand->setDoorNum($order->getTakeDoor()->getName());
$openDoorCommand->setDoorId($order->getTakeDoor()->getId());
$openDoorCommand->setBoxId($order->getTakeBox()->getId());
$publishToTopic = new PublishToTopic();
$publishToTopic->setMessageContent($openDoorCommand->getMessage());
$publishToTopic->setProductKey(env('MQTT_PRODUCT_KEY'));
$publishToTopic->setTopicFullName(Box::getOpenDoorTopic($boxCode));
//todo websocket推送消息 取出舱门打开
}
}
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/16
* Time: 上午9:35
*/
namespace src\client\open_door;
use Illuminate\Http\Request;
use Lib\aliyun\api\PublishToTopic;
use Lib\command\ConfirmOpenDoor;
use Src\box\Box;
use src\client\Client;
use Src\order\OrderCache;
/**
* 确认归还电池舱门已经打开
* Class ReturnOpenDoor
* @package src\client\open_door
*/
class ReturnOpenDoor implements Client
{
public function handle(Request $request)
{
$payload = $request->get('payload');
$door = $payload['doors'];
$boxNum = $door['box_num'];
$doorNum = $door['door_num'];
$operation = $door['operation'];
$operationType = $door['operation_type'];
$orderId = $door['order_id'];
$boxCode = $request->get('box_code');
$boxId = $request->get('box_id');
$doorId = $request->get('door_id');
if ($operation !== Door::OPERATION['open']) {
//todo 根据operationType 发送打开舱门失败web socket.回复确认消息
} else {
//todo 根据operationType打开舱门成功推送web socket
}
switch ($operationType) {
case 1:
$orderCache = new OrderCache();
$orderCache->update([
'returnBoxId' => $boxId,
'returnDoorId' => $doorId,
'returnBoxNum' => $boxNum,
'returnDoorNum' => $doorNum
]);
//todo 检查订单是否存在,websocket推送打开门成功,检查电池是否放入,更新订单状态
$confirmOpenDoor = new ConfirmOpenDoor();
$confirmOpenDoor->setOrderId($orderId);
$publishToTopic = new PublishToTopic();
$publishToTopic->setMessageContent($confirmOpenDoor->getMessage());
$publishToTopic->setProductKey(env('MQTT_PRODUCT_KEY'));
$publishToTopic->setTopicFullName(Box::getOpenDoorTopic($boxCode));
$client = new \Lib\aliyun\Client();
$client->setApi($publishToTopic);
if ($client->request() === true) {
Log::debug('confirm order -' . $orderId);
}
break;
case 0:
break;
default:
break;
}
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/16
* Time: 上午9:56
*/
namespace src\client\open_door;
class TakeOpenDoor
{
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/7
* Time: 下午9:23
*/
namespace Src\order;
use Src\battery\Battery;
use Src\box\Box;
use Src\box\door\Door;
use Src\Site;
class Order
{
/**
* @var int
*/
private $id = 0;
/**
* @var string
*/
private $outTradeNo = '';
/**
* @var int
*/
private $userId = 0;
/**
* @var Site
*/
private $site;
/**
* @var string
*/
private $boxCode = '';
/**
* @var Box
*/
private $openBox;
/**
* @var Box
*/
private $returnBox;
/**
* @var Door
*/
private $openDoor;
/**
* @var Door
*/
private $returnDoor;
/**
* @var Battery
*/
private $returnBattery;
/**
* @var Door
*/
private $takeDoor;
/**
* @var Box
*/
private $takeBox;
/**
* @var Battery
*/
private $takeBattery;
public function __get($name)
{
return $this->$name;
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param int $id
*/
public function setId(int $id): void
{
$this->id = $id;
}
/**
* @return string
*/
public function getOutTradeNo(): string
{
return $this->outTradeNo;
}
/**
* @param string $outTradeNo
*/
public function setOutTradeNo(string $outTradeNo): void
{
$this->outTradeNo = $outTradeNo;
}
/**
* @return int
*/
public function getUserId(): int
{
return $this->userId;
}
/**
* @param int $userId
*/
public function setUserId(int $userId): void
{
$this->userId = $userId;
}
/**
* @return Site
*/
public function getSite(): Site
{
return $this->site;
}
/**
* @param Site $site
*/
public function setSite(Site $site): void
{
$this->site = $site;
}
/**
* @return string
*/
public function getBoxCode(): string
{
return $this->boxCode;
}
/**
* @param string $boxCode
*/
public function setBoxCode(string $boxCode): void
{
$this->boxCode = $boxCode;
}
/**
* @return Box
*/
public function getOpenBox(): Box
{
return $this->openBox;
}
/**
* @param Box $openBox
*/
public function setOpenBox(Box $openBox): void
{
$this->openBox = $openBox;
}
/**
* @return Box
*/
public function getReturnBox(): Box
{
return $this->returnBox;
}
/**
* @param Box $returnBox
*/
public function setReturnBox(Box $returnBox): void
{
$this->returnBox = $returnBox;
}
/**
* @return Door
*/
public function getOpenDoor(): Door
{
return $this->openDoor;
}
/**
* @param Door $openDoor
*/
public function setOpenDoor(Door $openDoor): void
{
$this->openDoor = $openDoor;
}
/**
* @return Door
*/
public function getReturnDoor(): Door
{
return $this->returnDoor;
}
/**
* @param Door $returnDoor
*/
public function setReturnDoor(Door $returnDoor): void
{
$this->returnDoor = $returnDoor;
}
/**
* @return Battery
*/
public function getReturnBattery(): Battery
{
return $this->returnBattery;
}
/**
* @param Battery $returnBattery
*/
public function setReturnBattery(Battery $returnBattery): void
{
$this->returnBattery = $returnBattery;
}
/**
* @return Battery
*/
public function getTakeBattery(): Battery
{
return $this->takeBattery;
}
/**
* @param Battery $takeBattery
*/
public function setTakeBattery(Battery $takeBattery): void
{
$this->takeBattery = $takeBattery;
}
/**
* @return Door
*/
public function getTakeDoor(): Door
{
return $this->takeDoor;
}
/**
* @param Door $takeDoor
*/
public function setTakeDoor(Door $takeDoor): void
{
$this->takeDoor = $takeDoor;
}
/**
* @return Box
*/
public function getTakeBox(): Box
{
return $this->takeBox;
}
/**
* @param Box $takeBox
*/
public function setTakeBox(Box $takeBox): void
{
$this->takeBox = $takeBox;
}
}
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/11
* Time: 下午4:05
*/
namespace Src\order;
use Src\order\Order;
class OrderCache
{
/**
* @var Order
*/
private $order;
private $startOpenReturnDoorTime = '';
private $startOpenTakeDoorTime = '';
private $state;
/**
* @var \Redis
*/
private $redis;
public function __construct()
{
$this->redis = app('Redis');
}
public function getRedisKey()
{
return config('redis_key.ORDER_CACHE') . ':' . $this->order->getOutTradeNo();
}
public function update(array $attribute)
{
$this->redis->hMset($this->getRedisKey(), $attribute);
return $this;
}
/**
* @return array
*/
public function getCache()
{
return $this->redis->hGetAll($this->getRedisKey());
}
public function saveState()
{
$this->redis->hSet($this->getRedisKey(), 'state', $this->state);
return $this;
}
/**
* @return $this
*/
public function saveStartOpenReturnDoorTime()
{
$this->redis->hSet($this->getRedisKey(), 'startOpenReturnDoorTime', $this->startOpenReturnDoorTime);
return $this;
}
public function saveOrder($attribute = '')
{
if (is_string($attribute)) {
$this->redis->hSet($this->getRedisKey(), $attribute, $this->order->$attribute);
} elseif (is_array($attribute)) {
foreach ($attribute as $item) {
$this->redis->hSet($this->getRedisKey(), $item, $this->order->$item);
}
}
}
public function getOrderCache()
{
$cache = $this->redis->hGetAll($this->getRedisKey());
if (is_array($cache)) {
foreach ($cache as $item) {
$this->$item = $item;
}
}
}
/**
* @return \Src\order\Order
*/
public function getOrder(): Order
{
return $this->order;
}
/**
* @param \Src\order\Order $order
*/
public function setOrder(Order $order)
{
$this->order = $order;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/11
* Time: 下午11:05
*/
namespace Src\pay_rule;
class CashPay extends Rule
{
private $startTime = '';
public function getPayAmount(): int
{
$this->startTime = $this->orderModel->out_date;
$today = time();
$startTime = strtotime($this->startTime);
$rentTime = $today - $startTime;
$rentDay = ceil($rentTime / (60 * 60));
$system = DB::table('system')->where('id', 1)->first(['free_day', 'day_money']);
if (blank($system) === true) {
abort(500, 'system config wrong');
Log::error('system config wrong');
}
$system = $system->toArray();
$this->freeDay = $system['free_day'];
$price = $system['day_money'];
if (($rentDay % 24) > 5) {
$rentDay = (int)($rentDay / 24) + 1;
} else {
$rentDay = (int)($rentDay / 24);
}
$payDay = ($rentDay - $this->freeDay) > 0 ? ($rentDay - $this->freeDay) : 0;
//todo 检查优惠券
return $price * $payDay;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/11
* Time: 下午11:03
*/
namespace Src\pay_rule;
use App\model\OrderModel;
abstract class Rule
{
/**
* @var OrderModel
*/
protected $orderModel;
protected $freeDay = 0;
/**
* @return int
*/
public function getFreeDay(): int
{
return $this->freeDay;
}
/**
* @param int $freeDay
*/
public function setFreeDay(int $freeDay): void
{
$this->freeDay = $freeDay;
}
/**
* @param OrderModel $orderModel
*/
public function setOrderModel(OrderModel $orderModel): void
{
$this->orderModel = $orderModel;
}
public function getOrderModel(): OrderModel
{
$this->orderModel;
}
abstract public function getPayAmount(): int;
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/12
* Time: 上午12:35
*/
namespace src\update;
use App\model\OrderModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Lib\aliyun\api\PublishToTopic;
use Lib\aliyun\Client;
use Lib\command\OpenDoor;
use Src\battery\Battery;
use src\battery\SearchMaxQuantity;
use Src\box\Box;
use Src\box\door\Door;
use Src\order\Order;
class ReturnDoor
{
use SearchMaxQuantity;
private $outTradeNo = '';
private $batteryCode = '';
private $doorNum = 0;
private $boxNum = 0;
private $boxCode = '';
private $boxId = 0;
private $doorId = 0;
//fixme 解耦职责链
public function handle()
{
//todo 检查订单的准确性,下发打开取电舱门,web socket 推送用户还电成功
$orderModel = OrderModel::where('code', $this->outTradeNo)->first(['in_box_id', 'in_room_id', 'guest_id']);
$userId = $orderModel->guest_id;
// 更新归还电池的box_id 和 door_id door_name box_type;
$returnBox = new Box();
$returnBox->setCode($this->boxCode);
$returnDoor = new Door();
DB::table('batteries')->where('code', $this->batteryCode)->update([
'box_id' => $this->boxId,
'door_id' => $this->doorId,
'door_name' => $this->doorNum,
'box_type' => $this->boxNum,
]);
$batteryQuantity = $this->getBatteryQuantity($this->batteryCode);
//fixme 归还站点更新
DB::table('orders')->where('code', $this->outTradeNo)->update([
'in_room_id' => $this->doorId,
'in_room_name' => $this->doorNum,
'in_battery_code' => $this->batteryCode,
'in_date' => date('Y-m-d H:i:s'),
'in_power' => $batteryQuantity,
]);
$battery = new Battery();
$maxQuantityBatteryId = $battery->searchMaxQuantity($this->boxCode);
//电量最大的电池舱门
if ($maxQuantityBatteryId !== 0) {
$battery = DB::table('batteries')->where('id', $maxQuantityBatteryId)->first(['box_type', 'door_name', 'box_id', 'room_id']);
//todo 检查电池是否在当前电柜下
//todo 打开满电舱门。生成新的订单
$order = new Order();
$order->setBoxCode($this->boxCode);
$order->setUserId($userId);
$outTradeNo = time() . $userId . rand(100000, 999999);
$order->setOutTradeNo($outTradeNo);
$takeBox = new Box();
$takeDoor = new Door();
$takeBox->setId($battery->box_id);
$takeDoor->setId($battery->room_id);
$takeDoor->setName($battery->door_name);
$order->setTakeDoor($takeDoor);
$order->setTakeBox($takeBox);
$order->setBoxCode($this->boxCode);
$newOrderModel = new OrderModel();
$newOrderModel->initOrder($order);
// 下发打开舱门命令
$openTakeDoor = new OpenDoor();
$openTakeDoor->setBox($takeBox);
$openTakeDoor->setDoor($takeDoor);
$openTakeDoor->setOperationType(0);
$openTakeDoor->setOrderId($outTradeNo);
$publishToTopic = new PublishToTopic();
$publishToTopic->setMessageContent($openTakeDoor->getMessage());
$publishToTopic->setProductKey(env('MQTT_PRODUCT_KEY'));
$publishToTopic->setTopicFullName(Box::getOpenDoorTopic($this->boxCode));
$client = new Client();
$client->setApi($publishToTopic);
if ($client->request() === true) {
//todo websocket 推送消息至客户端,内容包含订单号,打开舱门和电池编号
Log::debug('send open take door success');
} else {
Log::error('send open take door fail');
//todo websocket 推送打开舱门失败,请重试
}
}
}
/**
* @return string
*/
public function getOutTradeNo(): string
{
return $this->outTradeNo;
}
/**
* @param string $outTradeNo
*/
public function setOutTradeNo(string $outTradeNo): void
{
$this->outTradeNo = $outTradeNo;
}
/**
* @return string
*/
public function getBatteryCode(): string
{
return $this->batteryCode;
}
/**
* @param string $batteryCode
*/
public function setBatteryCode(string $batteryCode): void
{
$this->batteryCode = $batteryCode;
}
/**
* @return int
*/
public function getDoorNum(): int
{
return $this->doorNum;
}
/**
* @param int $doorNum
*/
public function setDoorNum(int $doorNum): void
{
$this->doorNum = $doorNum;
}
/**
* @return int
*/
public function getBoxNum(): int
{
return $this->boxNum;
}
/**
* @param int $boxNum
*/
public function setBoxNum(int $boxNum): void
{
$this->boxNum = $boxNum;
}
/**
* @return string
*/
public function getBoxCode(): string
{
return $this->boxCode;
}
/**
* @param string $boxCode
*/
public function setBoxCode(string $boxCode): void
{
$this->boxCode = $boxCode;
}
/**
* @return int
*/
public function getBoxId(): int
{
return $this->boxId;
}
/**
* @param int $boxId
*/
public function setBoxId(int $boxId): void
{
$this->boxId = $boxId;
}
/**
* @return int
*/
public function getDoorId(): int
{
return $this->doorId;
}
/**
* @param int $doorId
*/
public function setDoorId(int $doorId): void
{
$this->doorId = $doorId;
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment