Commit 3e42114a by banice

复用cdzgateway_v2代码

parent 9986903a
...@@ -33,12 +33,15 @@ class ChargerController extends Controller ...@@ -33,12 +33,15 @@ class ChargerController extends Controller
$chargerCommand->setMethod('Cmd_Res'); $chargerCommand->setMethod('Cmd_Res');
$send = new Send($chargerCommand); $send = new Send($chargerCommand);
$send->setCallBackUrl(route('deviceChargerReceiver')); $send->setCallBackUrl(route('deviceChargerReceiver'));
$send->setDeviceId('d245d3fd-26e1-4818-95b9-37e6af3cfcf7'); $send->setDeviceId('d245d3fd-26e1-4818-95b9-37e6af3cfcf7');
if ($send->send() === true) { if ($send->send() === true) {
dd('success'); $response = $send->getResponse();
Log::debug($response->getBody());
//todo 记录下发日志回复发送是否成功
} }
......
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/30
* Time: 下午3:24
*/
namespace App\Http\Controllers\device;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Lib\Api;
use Src\route\Route;
class MessageController extends Controller
{
public function receiver(Request $request)
{
Log::debug($request->all());
$command = 'ff';
$api = new Api();
$api->boot();
if (isset($api->route[$command])) {
$clientId = 'deviceCode';
$message = '';
$route = $api->route[$command];
if ($route instanceof Route) {
$reflection = $route->getController();
$controller = $reflection->newInstanceArgs([$clientId, $message, $command]);
$method = $route->getMethod();
try {
$controller->$method();
} catch (\Exception $exception) {
Log::error($exception->getMessage());
}
unset($route);
unset($controller);
unset($api);
}
}
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/10
* Time: 上午11:11
*/
namespace App\Http\Controllers\subscribe;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Lib\iot\IotClient;
use Lib\iot\subscribe\QueryMass;
class QueryController extends Controller
{
public function single(Request $request)
{
}
public function mass(Request $request)
{
$iotClient = new IotClient(new QueryMass());
$iotClient->setDefaultHeader();
$iotClient->request();
Log::debug($iotClient->getResponse()->getBody()->getContents());
dd($iotClient->getResponse()->getBody()->getContents());
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/10
* Time: 上午10:50
*/
namespace App\Http\Controllers\subscribe;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Lib\iot\AccessToken;
use Lib\iot\IotClient;
use Lib\iot\subscribe\Business;
class SettingController extends Controller
{
public function set(Request $request)
{
$subscribe = new Business();
$iotClient = new IotClient($subscribe);
$iotClient->setHeaders([
'app_key' => config('iot.app_key'),
'Authorization' => 'Bearer ' . AccessToken::getAccessTokenCache(),
'Content-Type' => 'application/json'
]);
$iotClient->request($subscribe->getReturnCode());
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/10
* Time: 下午2:55
*/
use Workerman\MySQL\Connection;
use Lib\Crc;
use Lib\log\Log;
use Application\route\Api;
use Src\route\Route;
use Lib\station\gateway\Gateway;
use Lib\station\gateway\port\Port;
class Events
{
/**
* @var Connection
*/
private static $db;
/**
* @var \Redis
*/
private static $redis;
/**
*
*/
public static function onWorkerStart()
{
static::$db = new Connection(getenv('DB_HOST'), getenv('DB_PORT'), getenv('DB_USERNAME'), getenv('DB_PASSWORD'), getenv('DB_DATABASE'));
static::$redis = new \Redis();
static::$redis->pconnect(getenv('REDIS_HOST'), getenv('REDIS_PORT'), 0);
if (getenv('REDIS_AUTH') !== false) {
static::$redis->auth(getenv('REDIS_AUTH'));
}
static::$redis->select('4');
\Lib\log\Log::bootLog();
}
public static function onConnect($clientId)
{
}
/**
* 验证message
* 提取command字段
* 查找路由,验证路由
* 按照路由创建控制器和执行方法
* 日志收集
* @param $clientId
* @param $message
*/
public static function onMessage($clientId, $message)
{
$crc = substr($message, -2);
$crcConfirm = sprintf('%08x', Crc::crc(substr($message, 0, strlen($message) - 2)));
if ($crc != mb_strtoupper(substr($crcConfirm, 0, 2))) {
Log::error("message crc wrong ($message)");
return;
}
$command = substr($message, 6, 2);
$api = new Api();
$api->boot();
if (isset($api->route[$command])) {
$route = $api->route[$command];
if ($route instanceof Route) {
$reflection = $route->getController();
$controller = $reflection->newInstanceArgs([$clientId, $message, $command]);
$method = $route->getMethod();
try {
$controller->$method();
} catch (Exception $exception) {
Log::error($exception->getMessage());
}
unset($route);
unset($controller);
unset($api);
}
}
}
/**
* @param $clientId
*/
public static function onClose($clientId)
{
$gatewayId = isset($_SESSION['gateway_id']) ? $_SESSION['gateway_id'] : '';
$stationId = isset($_SESSION['station_id']) ? $_SESSION['station_id'] : '';
$stationName = isset($_SESSION['station_name']) ? $_SESSION['station_name'] : '';
$gatewayName = isset($_SESSION['gateway_name']) ? $_SESSION['gateway_name'] : '';
if ($gatewayId === '' || $stationId === '' || $gatewayName === '' || $stationName === '') {
Log::error('client close can not find station_id or gateway_id');
return;
}
Log::info('gateway offline', [
'gateway_id' => $gatewayId,
'station_id' => $stationId
]);
$exceptionModel = new \Application\model\ExceptionModel();
if (isset($_SESSION['station_id']) && isset($_SESSION['gateway_id'])) {
$exceptionModel->insertRow([
'message' => '网关离线',
'gateway_id' => $gatewayId,
'station_id' => $stationId,
'type' => 1,
]);
}
$gateway = new Gateway();
//网关状态设置为离线
$gateway->setState($gatewayId, 0);
if (isset($_SESSION['port_mac_id']) === false) {
Log::error('gateway close can not find port_mac_id in session');
return;
}
$portsMacId = $_SESSION['port_mac_id'];
$portsId = array_values($portsMacId);
$port = new Port();
$exceptionModel = new \Application\model\ExceptionModel();
$orderExceptionModel = new \Application\model\OrderExceptionModel();
$date = date('Y-m-d H:i:s');
foreach ($portsId as $portId) {
//所有端口状态设置为离线
$port->setPortId($portId);
$port->setGatewayId($gatewayId);
$port->setStationId($stationId);
$port->setState(\Lib\StateCode::PORT_OFFLINE);
$port->updatePortState();
$exceptionModel->insertRow([
'gateway_id' => $gatewayId,
'station_id' => $stationId,
'port_id' => $portId,
'message' => '口子离线',
'created_at' => $date,
'type' => 1,
]);
$portUsingOrderId = $port->getPortUsingOrderId();
//端口当前订单记录离线时间
if ($portUsingOrderId != false && $portUsingOrderId != '') {
$order = new \Lib\cdz\order\Order($portUsingOrderId);
if ($order->getOrderCache(static::$redis) != false) {
$order->setOfflineTime(time());
$saveOrder = new \Lib\cdz\order\save\OrderSaveRedis($order);
$saveOrder->save(['offlineTime']);
unset($saveOrder);
$orderExceptionModel->insertRow([
'order_id' => $order->getId(),
'state' => \Lib\StateCode::PORT_OFFLINE,
'created_at' => date('Y-m-d H:i:s'),
'desc' => '网关离线,订单离线',
]);
}
}
}
$broadcastToAgent = new \Src\BroadcastToAgent();
$broadcastToAgent->broadcast([
'notice_exception_code' => 15,
'gateway_id' => $gatewayId,
'station_id' => $stationId,
'station_name' => $stationName,
'gateway_mac' => isset($_SESSION['gateway_mac']) ? $_SESSION['gateway_mac'] : '',
]);
}
/**
*
*/
public static function pipe()
{
static::$redis->multi(2);
}
/**
*
*/
public static function exec()
{
static::$redis->exec();
}
/**
* @return Redis
*/
public static function getRedis()
{
return static::$redis;
}
/**
* @return Connection
*/
public static function getDb()
{
return static::$db;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/10
* Time: 上午10:49
*/
namespace Application\controller;
use Src\log\record\Record;
use Src\log\GatewayLogWriter;
use Src\request\Request;
use Src\response\Response;
use Src\route\Route;
class Controller
{
/**
* @var Record
*/
protected $logRecord;
/**
* 数据帧解析
* @var array
*/
protected $parameterMap = [];
/**
* 客户端id
*
* @var string
*/
protected $clientId;
/**
* 接受到的消息
*
* @var string
*/
protected $message;
/**
* 请求对象
*
* @var Request
*/
protected $request;
/**
* 是否加密
*
* @var bool
*/
protected $encrypt = false;
/**
* 数据帧基本结构
*
* @var array
*/
protected $defaultHeader = [
'preamble' => 2,
'headerFlag' => 1,
'headerCtrl' => 1,
'length' => 2,
'nonce' => 1,
];
/**
* 数据头
*
* @var string
*/
protected $preamble;
/**
* 是否加密字段
*
* @var string
*/
protected $headerFlag;
/**
* 消息命令
*
* @var string
*/
protected $headerCtrl;
/**
* 数据帧长度
*
* @var string
*/
protected $length;
/**
* 数据帧中的随机字符
*
* @var string
*/
protected $nonce;
/**
* 数据头
*
* @var array
*/
protected $headerBody = [];
/**
* 响应实例
*
* @var Response
*/
protected $response;
/**
* @var int
*/
protected $plc = 0;
protected $route;
protected $command = '';
/**
* Controller constructor.
* @param string $clientId
* @param string $message
* @param string $command
*/
public function __construct(string $clientId, string $message, string $command)
{
$this->clientId = $clientId;
$this->message = $message;
$this->parseHeader($message, $this->defaultHeader);
$this->command = $command;
$this->parseBody();
$this->response = new Response($this->clientId, $this->headerFlag);
$this->encrypt = $this->headerFlag === '05' ? true : false;
$this->logRecord = new Record();
$this->logRecord->setBody($this->message);
$this->logRecord->setCommand($command);
if (isset($_SESSION['station_id'])) {
$this->logRecord->setStationId($_SESSION['station_id']);
}
if (isset($_SESSION['gateway_id'])) {
$this->logRecord->setGatewayId($_SESSION['gateway_id']);
}
}
public function __destruct()
{
if($this->command === '00')
{
return ;
}
$logWriter = new GatewayLogWriter();
if($this->response->getResponseMessage() !== '')
{
$this->logRecord->setResponse($this->response->getResponseMessage());
}
$logWriter->write($this->logRecord);
}
/**
*
*/
private function parseBody()
{
$tmp = [];
foreach ($this->parameterMap[$this->command] as $key => $length) {
$start = $this->plc;
$length *= 2;
$tmp[$key] = substr($this->message, $start, $length);
$this->plc += $length;
}
$this->request = new Request($tmp);
}
private function parseHeader(string $message, array $map)
{
$parameters = [];
$start = 0;
foreach ($map as $key => $length) {
$length *= 2;
$parameters[$key] = substr($message, $start, $length);
if (property_exists($this, $key)) {
$this->$key = $parameters[$key];
}
$start += $length;
$this->plc += $length;
}
return $parameters;
}
/**
* Get 数据帧解析
*
* @return array
*/
public function getParameterMap()
{
return $this->parameterMap;
}
/**
* Set 数据帧解析
*
* @param array $parameterMap 数据帧解析
*
* @return self
*/
public function setParameterMap(array $parameterMap)
{
$this->parameterMap = $parameterMap;
return $this;
}
/**
* Get 客户端id
*
* @return string
*/
public function getClientId()
{
return $this->clientId;
}
/**
* Set 客户端id
*
* @param string $clientId 客户端id
*
* @return self
*/
public function setClientId(string $clientId)
{
$this->clientId = $clientId;
return $this;
}
/**
* Get 接受到的消息
*
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* Set 接受到的消息
*
* @param string $message 接受到的消息
*
* @return self
*/
public function setMessage(string $message)
{
$this->message = $message;
return $this;
}
/**
* Get 请求对象
*
* @return Request
*/
public function getRequest()
{
return $this->request;
}
/**
* Set 请求对象
*
* @param Request $request 请求对象
*
* @return self
*/
public function setRequest(Request $request)
{
$this->request = $request;
return $this;
}
/**
* Get 是否加密
*
* @return bool
*/
public function getEncrypt()
{
return $this->encrypt;
}
/**
* Set 是否加密
*
* @param bool $encrypt 是否加密
*
* @return self
*/
public function setEncrypt(bool $encrypt)
{
$this->encrypt = $encrypt;
return $this;
}
/**
* Get 数据帧基本结构
*
* @return array
*/
public function getDefaultHeader()
{
return $this->defaultHeader;
}
/**
* Set 数据帧基本结构
*
* @param array $defaultHeader 数据帧基本结构
*
* @return self
*/
public function setDefaultHeader(array $defaultHeader)
{
$this->defaultHeader = $defaultHeader;
return $this;
}
/**
* Get 响应实例
*
* @return Response
*/
public function getResponse()
{
return $this->response;
}
/**
* Set 响应实例
*
* @param Response $response 响应实例
*
* @return self
*/
public function setResponse(Response $response)
{
$this->response = $response;
return $this;
}
/**
* Get 消息命令
*
* @return string
*/
public function getHeaderCtrl()
{
return $this->headerCtrl;
}
/**
* Set 消息命令
*
* @param string $headerCtrl 消息命令
*
* @return self
*/
public function setHeaderCtrl(string $headerCtrl)
{
$this->headerCtrl = $headerCtrl;
return $this;
}
/**
* Get 数据帧长度
*
* @return string
*/
public function getLength()
{
return $this->length;
}
/**
* Set 数据帧长度
*
* @param string $length 数据帧长度
*
* @return self
*/
public function setLength(string $length)
{
$this->length = $length;
return $this;
}
/**
* Get 数据头
*
* @return string
*/
public function getPreamble()
{
return $this->preamble;
}
/**
* Set 数据头
*
* @param string $preamble 数据头
*
* @return self
*/
public function setPreamble(string $preamble)
{
$this->preamble = $preamble;
return $this;
}
/**
* Get 数据帧中的随机字符
*
* @return string
*/
public function getNonce()
{
return $this->nonce;
}
/**
* Set 数据帧中的随机字符
*
* @param string $nonce 数据帧中的随机字符
*
* @return self
*/
public function setNonce(string $nonce)
{
$this->nonce = $nonce;
return $this;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/20
* Time: 下午4:06
*/
namespace Application\controller;
use Src\route\Route;
class HeartController extends Controller
{
const GATEWAY_LAST_HEART_TIME = 'cdz:gateway:heart:last_time:hash';
const GATEWAY_HEART_TIMES = 'cdz:gateway:heart_times:zset';
protected $parameterMap = [
'00' => [
]
];
public function __construct(string $clientId, string $message, string $command)
{
parent::__construct($clientId, $message, $command);
}
public function break()
{
$time = time();
$redis = \Events::getRedis();
if (isset($_SESSION['gateway_id'])) {
$redis->hSet(self::GATEWAY_LAST_HEART_TIME, $_SESSION['gateway_id'], $time);
$redis->zIncrBy(self::GATEWAY_HEART_TIMES, 1, $_SESSION['gateway_id']);
}
$this->response->send('00', sprintf('%08x', time()));
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/21
* Time: 下午7:09
*/
namespace Application\controller;
class TestController
{
public function __construct()
{
var_dump('test construct');
}
public function __destruct()
{
var_dump('test destruct');
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/10
* Time: 下午3:29
*/
namespace Application\controller\accept;
use Application\controller\Controller;
use Application\model\DeviceModel;
use Application\model\GatewayModel;
use Lib\Aes;
use GatewayWorker\Lib\Gateway;
use Src\route\Route;
/**
* 设备认证
* Class CertifyController
* @package Application\controller\accept
*/
class CertifyController extends Controller
{
protected $parameterMap = [
'01' => [
'mac' => 6,
],
];
public function __construct(string $clientId, string $message, string $command)
{
parent::__construct($clientId, $message, $command);
}
public function __destruct()
{
parent::__destruct();
}
public function certify()
{
$nonce = $this->getNonce();
$mac = $this->request->get('mac');
$_SESSION['gateway_mac'] = $mac;
$_SESSION['certified'] = true;
$gatewayModel = new GatewayModel();
$gatewayModelResult = $gatewayModel->getColumns([
'station_id',
'id',
'name',
'type_id'
], 'mac_address = ' . "'$mac'");
if ($gatewayModelResult == false) {
Gateway::closeClient($this->clientId);
return;
}
$stationId = $gatewayModelResult['station_id'];
$gatewayId = $gatewayModelResult['id'];
$_SESSION['station_id'] = $stationId;
$_SESSION['gateway_id'] = $gatewayId;
$productId = 'A22E4F4CDB05C460E450E46241DD6F89';
$sign = bin2hex(Aes::encrypt($nonce, $productId));
$sign = substr($sign, 0, 8);
if (Gateway::isUidOnline($mac) === 1) {
$clients = Gateway::getclientIdByUid($mac);
foreach ($clients as $client) {
Gateway::closeClient($client);
}
}
Gateway::bindUid($this->clientId, $mac);
$this->response->send('01', $sign);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/17
* Time: 下午4:06
*/
namespace Application\controller\business\charger;
use Application\controller\Controller;
use Application\model\OrderExceptionModel;
use Application\model\OrderModel;
use Lib\cdz\order\Order;
use Lib\cdz\order\state\ChargerState;
use Lib\cdz\order\state\ShedState;
use Lib\cdz\order\state\WaitingState;
use Lib\Gateway;
use Lib\log\Log;
use Lib\StateCode;
use Lib\station\gateway\port\Port;
use Src\route\Route;
class OverController extends Controller
{
protected $parameterMap = [
'05' => [
'type' => 1,
'logic_id' => 1,
'state' => 1,
'order_id' => 6,
'capacity' => 4,
]
];
public function __construct(string $clientId, string $message, string $command)
{
parent::__construct($clientId, $message, $command);
}
/**
* 订单结束
* 更新数据库中的订单结束状态和结束电量等信息
* 释放口子,删除订单的redis缓存
* 推送必要的微信通知
* 订单记录异常
*/
public function over()
{
$type = $this->request->get('type');
$logicId = hexdec($this->request->get('logic_id'));
$state = hexdec($this->request->get('state'));
$orderId = hexdec($this->request->get('order_id'));
$capacity = hexdec($this->request->get('capacity'));
$this->logRecord->setOrderId($orderId);
$order = new Order($orderId);
if ($order->getOrderCache(\Events::getRedis()) != false) {
$orderStateCode = $order->getStateCode();
$order->setEndCapacity($capacity);
$order->setEndCode($state);
$portId = isset($_SESSION['port_logic_id'][$logicId]) ? $_SESSION['port_logic_id'][$logicId] : 0;
if ($portId !== 0) {
$this->logRecord->setPortId($portId);
}
// 逻辑地址不相同则认为已经更换过口子
// if ($logicId != $order->getPortLogicId()) {
// $this->response->send('15', sprintf('%02x', $logicId) . sprintf('%012x', $orderId));
// }
if (Gateway::isUidOnline($order->getUserId()) === 1) {
Gateway::sendToUid($order->getUserId(), json_encode(['code' => 10000]));
}
Log::debug('order state code ' . $orderStateCode);
switch ($orderStateCode) {
case StateCode::WAITING:
$orderState = new WaitingState($order);
break;
case StateCode::PORT_CHARGER:
$orderState = new ChargerState($order);
break;
case StateCode::PORT_SHED:
$orderState = new ShedState($order);
break;
default:
break;
}
if (isset($orderState)) {
switch ($state) {
case StateCode::PORT_EXCEPTION://口子打开失败,适配zegbee设备
$this->logRecord->setDesc('口子打开失败结束');
$port = new Port($order->getPortId());
$port->setStationId($order->getStationId());
$port->setGatewayId($order->getGatewayId());
$port->freePort($orderId);
$orderModel = new OrderModel();
$orderModel->update([
'is_stop' => StateCode::FINISH_REFUND,
'end_capacity' => $order->getEndCapacity(),
'end_time' => date('Y-m-d H:i:s'),
], 'id = ' . $order->getId());
break;
case StateCode::FINISH_USER: //用户主动结束
$this->logRecord->setDesc('用户主动结束充电');
$orderState->toUserFinish();
break;
case StateCode::FINISH_SHED_TIMEOUT: //端口脱落超时
$this->logRecord->setDesc('端口脱落超时结束');
$orderState->toShedTimeoutState();
break;
case StateCode::FINISH_REFUND: //充电失败退款
$this->logRecord->setDesc('充电失败退款结束');
$orderState->toRefundFinish();
break;
case StateCode::FINISH_EXCEED: //功率超限
$this->logRecord->setDesc('功率超限充电结束');
$orderState->toPowerExceedState();
break;
case StateCode::FINISH_FULL: //充满自停
$this->logRecord->setDesc('充满自停结束');
$orderState->toPowerFullState();
break;
case StateCode::FINISH_TIME_END: //充电时间结束
$this->logRecord->setDesc('充电时间完结束');
$orderState->toTimeoutState();
break;
case StateCode::CHANGE_PORT:
if (isset($_SESSION['port_logic_id'])) {
$portId = isset($_SESSION['port_logic_id'][$logicId]) ? $_SESSION['port_logic_id'][$logicId] : 0;
$port = new Port($portId);
$port->setState(StateCode::PORT_ONLINE);
$port->setGatewayId($order->getGatewayId());
$port->setStationId($order->getStationId());
$port->freePort();
$orderExceptionModel = new OrderExceptionModel();
$orderExceptionModel->insertRow([
'order_id' => $orderId,
'created_at' => date('Y-m-d H:i:s'),
'state' => '-1' . StateCode::CHANGE_PORT,
'desc' => '更换口子,' . $portId . '关闭成功',
]);
$this->logRecord->setDesc('更换口子,' . $portId . '关闭成功');
}
$this->response->send('15', sprintf('%02x', $logicId) . sprintf('%012x', $orderId));
return;
default:
break;
}
} else {
$this->logRecord->setException(0);
$this->logRecord->setDesc('redis副本订单状态异常,非可结束订单状态');
}
} else {
$this->logRecord->setException(0);
$this->logRecord->setDesc('未查找到订单redis副本');
}
$this->response->send('15', sprintf('%02x', $logicId) . sprintf('%012x', $orderId));
}
}
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/17
* Time: 下午3:54
*/
namespace Application\controller\business\charger;
use Application\controller\Controller;
use Lib\cdz\order\Order;
use Lib\cdz\order\state\ChargerState;
use Lib\cdz\order\state\WaitingState;
use Lib\Gateway;
use Lib\log\Log;
use Lib\StateCode;
class StartController extends Controller
{
protected $parameterMap = [
'04' => [
'type' => 1,
'logic_id' => 1,
'state' => 1,
'order_id' => 6,
'capacity' => 4,
],
];
public function __construct(string $clientId, string $message, string $command)
{
parent::__construct($clientId, $message, $command);
}
/**
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function start()
{
$type = hexdec($this->getRequest()->get('type'));
$logic = $this->getRequest()->get('logic_id');
$state = hexdec($this->getRequest()->get('state'));
$orderId = hexdec($this->getRequest()->get('order_id'));
$this->logRecord->setOrderId($orderId);
$capacity = hexdec($this->getRequest()->get('capacity'));
Log::debug('order_id-->' . $orderId);
Log::debug('capacity-->' . $capacity);
if ($type == 1) {
$order = new Order($orderId);
if ($order->getOrderCache(\Events::getRedis()) == false) {
$this->response->send('14', sprintf('%012x', $orderId));
return;
} else {
$orderLogicId = $order->getPortLogicId();
//logicId 与订单中的实际不相同则已更换口子
if ($orderLogicId != hexdec($logic)) {
$this->response->send('14', sprintf('%012x', $orderId));
return;
}
}
$order->setStartCapacity($capacity);
if (Gateway::isUidOnline($order->getUserId()) === 1) {
Gateway::sendToUid($order->getUserId(), json_encode(['code' => 10000]));
}
if (isset($_SESSION['agent_id'])) {
if (Gateway::isUidOnline($_SESSION['agent_id'])) {
$clientsId = Gateway::getClientIdByUid($_SESSION['agent_id']);
$clientId = $clientsId[0];
$uIds = Gateway::getUidByClientId($clientId);
Gateway::sendToUid($_SESSION['agent_id'], json_encode($order->getOrderCache(\Events::getRedis())));
} else {
Log::debug('agent is offline');
}
}
$lastState = $order->getStateCode();
$orderState = new WaitingState($order);
$portId = $orderState->getOrder()->getPortId();
$this->logRecord->setPortId($portId);
switch ($state) {
case StateCode::PORT_CHARGER:
$orderState->toChargerState();
break;
case StateCode::PORT_EXCEPTION:
$orderState->toExceptionState();
break;
case StateCode::PORT_SHED:
Log::debug('port_shed');
$orderState->toShedState();
break;
case StateCode::FINISH_EXCEED:
Log::debug('exceed');
$orderState->toPowerExceedState();
break;
default:
break;
}
}
$this->response->send('14', sprintf('%012x', $orderId));
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/21
* Time: 上午9:57
*/
namespace Application\controller\business\port;
use Application\controller\Controller;
use Application\model\ExceptionModel;
use Lib\log\Log;
use Lib\StateCode;
use Lib\station\gateway\port\Port;
use Src\BroadcastToAgent;
class OfflineController extends Controller
{
protected $parameterMap = [
'09' => [
'count' => 1,
]
];
public function __construct(string $clientId, string $message, string $command)
{
parent::__construct($clientId, $message, $command);
}
/**
* 口子离线
* 更新口子状态
* 记录离线记录
*/
public function offline()
{
$count = hexdec($this->request->get('count'));
$portsLogicMac = [];
$portsLogic = substr($this->message, $this->plc, $count * 2);
$portsLogic = str_split($portsLogic, 2);
$this->plc += ($count * 2);
$str = substr($this->message, $this->plc, -2);
$tmp = str_split($str, 16);
for ($i = 0; $i < $count; $i++) {
$portsLogicMac[hexdec($portsLogic[$i])] = $tmp[$i];
}
if (!isset($_SESSION['port_mac_id'])) {
return;
}
$portsMacId = $_SESSION['port_mac_id'];
$port = new Port();
$exceptionModel = new ExceptionModel();
if (!(isset($_SESSION['station_id']) || !isset($_SESSION['gateway_id']))) {
return;
}
$broadcastToAgent = new BroadcastToAgent();
$offlinePorts = [];
foreach ($portsLogicMac as $portLogic => $portMac) {
if (isset($portsMacId[$portMac])) {
$portId = $portsMacId[$portMac];
if (isset($_SESSION['port_id_name'][$portId])) {
array_push($offlinePorts, ['name' => $_SESSION['port_id_name'][$portId], 'id' => $portId]);
}
Log::debug('offline port_id' . $portId);
$port->setPortId($portId);
$port->setStationId($_SESSION['station_id']);
$port->setGatewayId($_SESSION['gateway_id']);
$port->setState(StateCode::PORT_OFFLINE);
$port->updatePortState();
// 记录口子离线
$exceptionModel->insertRow([
'message' => '口子离线',
'gateway_id' => isset($_SESSION['gateway_id']) ? $_SESSION['gateway_id'] : '',
'station_id' => isset($_SESSION['station_id']) ? $_SESSION['station_id'] : '',
'port_id' => $portId,
'created_at' => date('Y-m-d H:i:s'),
'type' => 1,
]);
}
}
$broadcastToAgent->broadcast([
'notice_exception_code' => StateCode::PORT_OFFLINE,
'ports' => $offlinePorts,
'station_name' => $_SESSION['station_name'],
'gateway_name' => $_SESSION['gateway_name'],
'station_id' => $_SESSION['station_id'],
'gateway_id' => $_SESSION['gateway_id'],
]);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/21
* Time: 上午9:57
*/
namespace Application\controller\business\port;
use Application\controller\Controller;
use Application\model\ExceptionModel;
use Lib\StateCode;
use Lib\station\gateway\port\Port;
class OnlineController extends Controller
{
protected $parameterMap = [
'08' => [
'count' => 1,
]
];
public function __construct(string $clientId, string $message, string $command)
{
parent::__construct($clientId, $message, $command);
}
/**
* 设备上线
*/
public function online()
{
$count = hexdec($this->request->get('count'));
$portsLogicMac = [];
$portsLogic = substr($this->message, $this->plc, $count * 2);
$portsLogic = str_split($portsLogic, 2);
$this->plc += ($count * 2);
$str = substr($this->message, $this->plc, -2);
$tmp = str_split($str, 16);
for ($i = 0; $i < $count; $i++) {
$portsLogicMac[hexdec($portsLogic[$i])] = $tmp[$i];
}
if (!isset($_SESSION['port_mac_id'])) {
return;
}
$portsMacId = $_SESSION['port_mac_id'];
$port = new Port();
$exceptionModel = new ExceptionModel();
if (!(isset($_SESSION['station_id']) && isset($_SESSION['gateway_id']))) {
return;
}
foreach ($portsLogicMac as $portLogic => $portMac) {
if (isset($portsMacId[$portMac])) {
$portId = $portsMacId[$portMac];
$port->setPortId($portId);
$port->setStationId($_SESSION['station_id']);
$port->setGatewayId($_SESSION['gateway_id']);
$port->setState(StateCode::PORT_ONLINE);
$port->updatePortState();
// 记录口子上线
$exceptionModel->insertRow([
'port_id' => $portId,
'gateway_id' => isset($_SESSION['gateway_id']) ? $_SESSION['gateway_id'] : '',
'station_id' => isset($_SESSION['station_id']) ? $_SESSION['station_id'] : '',
'created_at' => date('Y-m-d H:i:s'),
]);
}
}
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/17
* Time: 下午4:06
*/
namespace Application\controller\business\port;
use Application\controller\Controller;
use Application\model\DeviceModel;
use Lib\cdz\order\Order;
use Lib\cdz\order\state\ChargerState;
use Lib\cdz\order\state\ExceptionState;
use Lib\cdz\order\state\PowerExceedState;
use Lib\cdz\order\state\ShedState;
use Lib\cdz\order\state\WaitingState;
use Lib\Gateway;
use Lib\log\Log;
use Lib\StateCode;
use Lib\station\gateway\port\Port;
class StateController extends Controller
{
protected $parameterMap = [
'0B' => [
'port_logic' => 1,
'mac' => 8,
'state' => 1,
]
];
public function __construct(string $clientId, string $message, string $command)
{
parent::__construct($clientId, $message, $command);
}
/**
* 改变口子的状态
*/
public function change()
{
$portLogic = hexdec($this->request->get('port_logic'));
$mac = $this->request->get('mac');
$state = hexdec($this->request->get('state'));
if (isset($_SESSION['port_mac_id']) !== true) {
$deviceModel = new DeviceModel();
$portId = $deviceModel->getColumn('id', 'device_mac = ' . $mac);
if (isset($portId) === false || $portId == '') {
return;
}
} else {
$portsMacId = $_SESSION['port_mac_id'];
if (isset($portsMacId[$mac]) === false) {
return;
}
$portId = $portsMacId[$mac];
}
$port = new Port($portId);
$usingOrderId = $port->getPortUsingOrderId();
if ($usingOrderId == false || $usingOrderId == '') {
$port->setState($state);
$port->updatePortState();
} else {
$this->logRecord->setOrderId($usingOrderId);
$this->logRecord->setPortId($portId);
$order = new Order((int)$usingOrderId);
if ($order->getOrderCache(\Events::getRedis()) == false) {
$port->setState($state);
$port->updatePortState();
return;
}
if ($order->getPortLogicId() != $portLogic) {
return;
}
if (Gateway::isUidOnline($order->getUserId()) === 1) {
Gateway::sendToUid($order->getUserId(), json_encode(['code' => 10000]));
}
switch ($order->getStateCode()) {
case StateCode::PORT_CHARGER:
$orderState = new ChargerState($order);
break;
case StateCode::PORT_SHED:
$orderState = new ShedState($order);
break;
case StateCode::FINISH_EXCEED:
$orderState = new PowerExceedState($order);
break;
case StateCode::PORT_EXCEPTION:
$orderState = new ExceptionState($order);
break;
case StateCode::WAITING:
$orderState = new WaitingState($order);
break;
default:
return;
}
Log::debug('now state' . $state);
switch ($state) {
case StateCode::PORT_CHARGER:
$orderState->toChargerState();
break;
case StateCode::FINISH_EXCEED:
$orderState->toPowerExceedState();
break;
case StateCode::PORT_SHED:
$orderState->toShedState();
break;
default :
break;
}
}
}
}
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/21
* Time: 上午10:50
*/
namespace Application\controller\business\power;
use Application\controller\Controller;
class CapacityController extends Controller
{
protected $parameterMap = [
'capacity' => 4,
];
public function __construct(string $clientId, string $message, string $command)
{
parent::__construct($clientId, $message, $command);
}
public function capacity()
{
$gatewayId = $_SESSION['gateway_id'];
$capacity = hexdec($this->request->get('capacity'));
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/20
* Time: 下午4:36
*/
namespace Application\controller\business\power;
use Application\controller\Controller;
use Application\model\OrderModel;
use Application\model\OrderPowerModel;
use Lib\cdz\order\Order;
use Lib\cdz\order\save\OrderSaveRedis;
use Lib\log\Log;
use Lib\station\gateway\port\Port;
class PowerController extends Controller
{
protected $parameterMap = [
'17' => [
'logic_id' => 1,
'power' => 2,
'capacity' => 4,
],
'07' => [
'logic_id' => 1,
'start_time' => 4,
'interval_time' => 1,
'count' => 1,
]
];
public function __construct(string $clientId, string $message, string $command)
{
parent::__construct($clientId, $message, $command);
}
public function one()
{
$logicId = hexdec($this->request->get('logic_id'));
$power = hexdec($this->request->get('power'));
$capacity = hexdec($this->request->get('capacity'));
if (isset($_SESSION['port_logic_id']) == false) {
return;
}
$portsLogicId = $_SESSION['port_logic_id'];
if (isset($portsLogicId[$logicId])) {
$portId = $portsLogicId[$logicId];
$port = new Port($portId);
$orderId = $port->getPortUsingOrderId();
if ($orderId == false || $orderId == '') {
return;
}
$this->logRecord->setOrderId($orderId);
$this->logRecord->setPortId($portId);
$order = new Order($orderId);
if ($order->getOrderCache(\Events::getRedis()) != false) {
if ($order->getStartCapacity() === -1) {
$orderModel = new OrderModel();
$startCapacity = $orderModel->getColumn('start_capacity', 'id = ' . $orderId);
if ($startCapacity == -1) {
$orderModel->update(['start_capacity' => $capacity], 'id = ' . $orderId);
$saveOrderRedis = new OrderSaveRedis($order);
$saveOrderRedis->save(['startCapacity']);
}
} else {
$orderModel = new OrderModel();
$orderModel->update(['end_capacity' => $capacity], 'id = ' . $orderId);
}
}
$orderPowerModel = new OrderPowerModel();
$orderPowerModel->insertRow([
'order_id' => $orderId,
'capacity' => $capacity,
'power' => $power,
'port_id' => $portId,
'created_at' => date('Y-m-d H:i:s'),
]);
} else {
Log::debug('no port_id');
}
}
public function plural()
{
//todo 最近的用电量作为结束用电量更新
$logicId = hexdec($this->request->get('logic_id'));
$startTime = hexdec($this->request->get('start_time'));
$intervalTime = hexdec($this->request->get('interval_time'));
$count = hexdec($this->request->get('count'));
$powers = substr($this->message, $this->plc, $count * 4);
Log::debug($powers);
$this->plc += ($count * 4);
$capacitys = substr($this->message, $this->plc, $count * 8);
Log::debug($capacitys);
$powers = str_split($powers, 4);
$capacitys = str_split($capacitys, 8);
Log::debug('count -> ' . $count);
Log::debug('powers', $powers);
Log::debug('capacitys', $capacitys);
if (count($powers) != $count || count($capacitys) != $count) {
Log::error('plural miss power or capacity,less than count ');
return;
}
$portsLogicId = $_SESSION['port_logic_id'];
if (isset($portsLogicId[$logicId])) {
$portId = $portsLogicId[$logicId];
$port = new Port($portId);
$orderId = $port->getPortUsingOrderId();
if ($orderId == false || $orderId == '') {
Log::error('power data can not find order_id', [
'logic_id' => $logicId,
'message' => $this->message,
]);
return;
}
$this->logRecord->setPortId($portId);
$this->logRecord->setOrderId($orderId);
$orderPowerModel = new OrderPowerModel();
Log::debug('order_id->' . $orderId);
for ($i = 0; $i < $count; $i++) {
$orderPowerModel->insertRow([
'created_at' => date('Y-m-d H:i:s', $startTime),
'order_id' => $orderId,
'port_id' => $portId,
'power' => hexdec($powers[$i]),
'capacity' => hexdec($capacitys[$i]),
]);
$startTime += $intervalTime;
//更新结束充电用电量
if ($i === ($count - 1)) {
$orderModel = new OrderModel();
$orderModel->update([
'end_capacity' => hexdec($capacitys[$i]),
], 'id = ' . $orderId);
}
}
} else {
Log::error('can not find port_id by logic_id from session', [$portsLogicId]);
}
}
}
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/22
* Time: 上午10:17
*/
namespace Application\controller\business\power;
use Application\controller\Controller;
class ShutdownController extends Controller
{
protected $parameterMap = [
'04' => []
];
public function __construct(string $clientId, string $message, string $command)
{
parent::__construct($clientId, $message, $command);
}
public function shutdown()
{
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/28
* Time: 上午9:56
*/
namespace Application\controller\card;
use Application\controller\Controller;
use Application\model\CardModel;
class BalanceController extends Controller
{
protected $parameterMap = [
'32' => [
'card_id' => 3
]
];
/**
* 获取卡的余额
*/
public function get()
{
$cardId = $this->request->get('card_id');
$cardModel = new CardModel();
$balance = $cardModel->getColumn('balance', 'card_number = ' . $cardId);
$balance = isset($balance) ? $balance : 0;
$balance = sprintf('%08x', $balance);
var_dump($balance);
$this->response->send('32', $cardId . $balance);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/28
* Time: 上午9:52
*/
namespace Application\controller\card;
use Application\controller\Controller;
use Application\model\BillTmpModel;
use GatewayWorker\Lib\Gateway;
use Lib\log\Log;
class PayRuleController extends Controller
{
protected $parameterMap = [
'31' => [
]
];
/**
* 获取扣费套餐
*/
public function get()
{
$billingTmp = new BillTmpModel();
if (isset($_SESSION['station_id']) == false) {
Gateway::closeClient($this->clientId);
}
Log::debug($_SESSION['station_id']);
$rule = $billingTmp->getColumn('context', 'id = ' . $_SESSION['station_id']);
Log::debug($rule);
if (isset($rule)) {
$rule = json_decode($rule, true);
$back = [];
$count = count($rule);
foreach ($rule as $item) {
$time = sprintf('%04x', $item['time']);
$price = sprintf('%04x', $item['price']);
array_push($back, $time . $price);
}
$this->response->send('31', sprintf('%02x', $count) . implode($back));
}
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/29
* Time: 下午4:30
*/
namespace Application\controller\card\charger;
use Application\controller\Controller;
use Lib\cdz\order\Order;
use Lib\cdz_order\state\ChargerState;
use Lib\cdz_order\state\ShedState;
use Lib\cdz_order\state\WaitingState;
use Lib\StateCode;
use Lib\Tool;
class OverController extends Controller
{
protected $parameterMap = [
'35' => [
'type' => 1,
'logic_id' => 1,
'state' => 1,
'order_id' => 6,
'capacity' => 4,
]
];
/**
* 结束充电
*/
public function over()
{
$orderId = hexdec($this->request->get('order_id'));
$state = hexdec($this->request->get('state'));
$capacity = hexdec($this->request->get('capacity'));
$order = new Order($orderId);
$order->setEndCapacity($capacity);
$order->setEndCode($state);
$this->logRecord->setOrderId($orderId);
if ($order->getOrderCache(\Events::getRedis()) !== false) {
$orderStateCode = $order->getStateCode();
$this->logRecord->setPortId($order->getPortId());
switch ($orderStateCode) {
case StateCode::PORT_CHARGER:
$orderState = new ChargerState($order);
break;
case StateCode::PORT_SHED:
$orderState = new ShedState($order);
break;
case StateCode::WAITING:
$orderState = new WaitingState($order);
break;
default:
break;
}
if (isset($orderState)) {
switch ($state) {
case StateCode::FINISH_TIME_END:
$orderState->toTimeoutState();
break;
case StateCode::FINISH_SHED_TIMEOUT:
$orderState->toShedTimeoutState();
break;
case StateCode::FINISH_EXCEED:
$orderState->toPowerExceedState();
break;
default:
break;
}
}
}
$this->response->send('45', Tool::padding($orderId, 6));
}
}
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/29
* Time: 下午4:29
*/
namespace Application\controller\card\charger;
use Application\controller\Controller;
use Lib\log\Log;
use Lib\station\gateway\port\Port;
use Application\model\OrderPowerModel;
class PowerController extends Controller
{
protected $parameterMap = [
'17' => [
'logic_id' => 1,
'power' => 2,
'capacity' => 4,
],
];
public function power()
{
$logicId = hexdec($this->request->get('logic_id'));
$startTime = hexdec($this->request->get('start_time'));
$intervalTime = hexdec($this->request->get('interval_time')) * 60;
$count = $this->request->get('count');
$powers = substr($this->message, $this->plc, $count * 4);
$this->plc += ($count * 4);
$capacitys = substr($this->message, $this->plc, $count * 8);
$powers = explode($powers, 4);
$capacitys = explode($capacitys, 8);
if (count($powers) != $count || count($capacitys) != $count) {
Log::error('plural miss power or capacity,less than count ');
return;
}
if (isset($_SESSION['port_id_logic']) == false) {
return;
}
$portsLogicId = array_flip($_SESSION['port_logic_id']);
if (isset($portsLogicId[$logicId])) {
$portId = $portsLogicId[$logicId];
$port = new Port($portId);
$orderId = $port->getPortUsingOrderId();
if ($orderId == false || $orderId == '') {
Log::error('power data can not find order_id', [
'logic_id' => $logicId,
'message' => $this->message,
]);
return;
}
$this->logRecord->setPortId($portId);
$this->logRecord->setOrderId($orderId);
$orderPowerModel = new OrderPowerModel();
for ($i = 0; $i < $count; $i++) {
$orderPowerModel->insertRow([
'created_at' => date('Y-m-d H:i:s', $startTime),
'order_id' => $orderId,
'port_id' => $portId,
'power' => $powers[$i],
'capacity' => $capacitys[$i],
]);
$startTime += $intervalTime;
}
}
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/29
* Time: 上午9:48
*/
namespace Application\controller\card\charger;
use Application\controller\Controller;
use Application\model\CardModel;
use Application\model\OrderModel;
use Lib\cdz\order\Order;
use Lib\cdz\order\save\OrderSaveRedis;
use Lib\log\Log;
use Lib\Tool;
class RequestController extends Controller
{
protected $parameterMap = [
'33' => [
'type' => 1,
'logic_id' => 1,
'card_id' => 3,
'time' => 2,
'price' => 2,
],
];
/**
* 请求充电
*/
public function request()
{
$type = $this->request->get('type');
$logicId = hexdec($this->request->get('logic_id'));
$cardId = $this->request->get('card_id');
$time = hexdec($this->request->get('time'));
$price = hexdec($this->request->get('price'));
if ((isset($_SESSION['gateway_id']) && isset($_SESSION['station_id']) && isset($_SESSION['station_name'])) === false) {
Log::debug('miss gateway)id');
return;
}
if (isset($_SESSION['port_logic_id'])) {
Log::debug('port_logic_id', $_SESSION['port_logic_id']);
if (isset($_SESSION['port_logic_id'][$logicId])) {
$portId = $_SESSION['port_logic_id'][$logicId];
}
}
if (isset($portId) === false) {
return;
}
$cardModel = new CardModel();
$balance = $cardModel->getColumn('balance', 'card_number = ' . $cardId);
Log::debug($balance);
if (isset($balance) === false || $balance == '') {
return;
}
if ((int)$balance < (int)$price) {
$orderId = 0;
} else {
//添加订单记录.
$stationId = $_SESSION['station_id'];
$gatewayId = $_SESSION['gateway_id'];
$stationName = $_SESSION['station_name'];
$date = date('Y-m-d H:i:s');
$orderModel = new OrderModel();
$outTradeNo = '3' . time() . $stationId . $portId . $gatewayId;
$orderModel->insertRow([
'gateway_id' => $gatewayId,
'station_id' => $stationId,
'port_id' => $portId,
'out_trade_no' => $outTradeNo,
'pay_amount' => $price,
'charger_time' => $time,
'created_at' => $date,
'logic_num' => $logicId,
'pay_type' => 3,
'station_name' => $stationName,
]);
$orderId = $orderModel->getColumn('id', 'out_trade_no = ' . $outTradeNo);
}
$this->response->send('33', $type . Tool::padding($logicId, 1) . $cardId . Tool::padding($time, 2) . Tool::padding($price, 2) . Tool::padding($orderId, 6) . Tool::padding($balance, 4));
if ($orderId != 0) {
//todo 订单缓存存储
$order = new Order($orderId);
$order->setStationId($stationId);
$order->setGatewayId($gatewayId);
$order->setCardId($cardId);
$order->setStationId($stationId);
$order->setStationName($stationName);
$order->setCreatedTime(time());
$order->setPayAmount($price);
$order->setPurchaseTime($time);
$order->setPortLogicId($logicId);
$order->setStateCode(-1);
$saveOrder = new OrderSaveRedis($order);
$saveOrder->saveAll();
}
}
}
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/29
* Time: 上午10:35
*/
namespace Application\controller\card\charger;
use Application\controller\Controller;
use Lib\cdz\order\Order;
use Lib\cdz_order\state\WaitingState;
use Lib\StateCode;
use Lib\Tool;
class StartController extends Controller
{
protected $parameterMap = [
'34' => [
'type' => 1,
'logic_id' => 1,
'state' => 1,
'order_id' => 6,
'capacity' => 4,
]
];
/**
* 开始充电
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function start()
{
$logicId = $this->request->get('logic_id');
$state = hexdec($this->request->get('state'));
$orderId = hexdec($this->request->get('order_id'));
$capacity = hexdec($this->request->get('capacity'));
$order = new Order($orderId);
if ($order->getOrderCache(\Events::getRedis()) != false) {
$orderStateCode = $order->getStateCode();
$order->setStartCapacity($capacity);
$order->setStartTime(time());
$this->logRecord->setOrderId($orderId);
$this->logRecord->setPortId($order->getPortId());
switch ($orderStateCode) {
case StateCode::WAITING:
$orderState = new WaitingState($order);
break;
default:
return;
}
switch ($state) {
case StateCode::PORT_CHARGER:
$orderState->toChargerState();
break;
case StateCode::PORT_SHED:
$orderState->toShedState();
break;
case StateCode::PORT_EXCEPTION:
$orderState->toExceptionState();
break;
default:
break;
}
}
$this->response->send('34', Tool::padding($orderId, 6));
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/29
* Time: 下午4:29
*/
namespace Application\controller\card\port;
class StateController
{
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/9
* Time: 下午5:01
*/
namespace Application\controller\setting;
use Application\controller\Controller;
use Application\model\DeviceModel;
use Application\model\GatewayModel;
use Lib\Gateway;
class DeviceMacController extends Controller
{
protected $parameterMap = [
'0E' => [
]
];
public function getAll()
{
if (isset($_SESSION['gateway_id']) === true) {
$gatewayId = $_SESSION['gateway_id'];
$deviceModel = new DeviceModel();
$devicesMac = $deviceModel->getAllColumns(['device_mac'], 'gateway_id = ' . $gatewayId);
$count = count($devicesMac);
$tmp = [];
foreach ($devicesMac as $deviceMac) {
array_push($tmp, $deviceMac['device_mac']);
}
$devicesMacStr = implode('', $tmp);
$this->response->send('0e', sprintf('%02x', $count) . $devicesMacStr);
}
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/22
* Time: 上午10:05
*/
namespace Application\controller\setting;
use Application\controller\Controller;
use Application\model\ConfigModel;
use Application\model\StationModel;
use Lib\Gateway;
use Lib\log\Log;
class SettingController extends Controller
{
protected $parameterMap = [
'0A' => []
];
public function __construct(string $clientId, string $message, string $command)
{
parent::__construct($clientId, $message, $command);
}
/**
* 硬件获取设置参数
*/
public function get()
{
$configModel = new ConfigModel();
$configs = $configModel->getIdConfigValue();
$idConfigsValue = [];
foreach ($configs as $config) {
$idConfigsValue[$config['id']] = $config['config_value'];
}
$invertalTime = $idConfigsValue['5']; //设备上报数据间隔单位 秒
if (isset($_SESSION['station_id']) === false) {
Gateway::closeClient($this->clientId);
Log::error('setting miss station_id');
return;
}
$stationId = $_SESSION['station_id'];
$stationModel = new StationModel();
$stationMaxCep = $stationModel->getColumn('max_cep', 'id = ' . $stationId);
$powerUpperLimit = isset($stationMaxCep) ? $stationMaxCep : $idConfigsValue['1'];
$getPriceConfig = $idConfigsValue['6'];
$powerSaturateInvertalTime = $idConfigsValue['7'];
$extraTime = $idConfigsValue['8'];
$powerLowerLimit = getenv('LOW_POWER_LIMIT');
$detectTime = 5;
$afterFormat = $this->adaptor([
[$invertalTime, 4],
[$getPriceConfig, 2],
[$powerUpperLimit, 4],
[$powerSaturateInvertalTime, 2],
[$extraTime, 2],
[$powerLowerLimit, 2],
[$detectTime, 2],
]);
$this->response->send('0a', implode($afterFormat));
}
/**
* @param array $data
* @return array
*/
private function adaptor(array $data)
{
$afterFormat = [];
foreach ($data as $item) {
array_push($afterFormat, sprintf('%0' . $item[1] . 'x', $item[0]));
}
return $afterFormat;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/17
* Time: 上午10:52
*/
namespace Application\controller\update;
use Application\controller\Controller;
use Application\model\DeviceModel;
use Application\model\GatewayModel;
use Application\model\GatewayUpdateModel;
use GatewayWorker\Lib\Gateway;
use Lib\log\Log;
class QueryController extends Controller
{
protected $parameterMap = [
'D1' => [
'hardware_version' => 4,
'software_version' => 4,
],
'CD' => [
'hardware_version' => 4,
'software_version' => 4,
]
];
public function __construct(string $clientId, string $message, string $command)
{
parent::__construct($clientId, $message, $command);
}
public function __destruct()
{
parent::__destruct();
}
public function currentVersion()
{
$gatewayModel = new GatewayModel();
$gatewayModel->update([
'hardware_version' => $this->request->get('hardware_version'),
'software_version' => $this->request->get('software_version'),
], 'id = ' . $_SESSION['gateway_id']);
}
/**
* @throws \Exception
*/
public function check()
{
$hardwareVersion = $this->request->get('hardware_version');
$softwareVersion = $this->request->get('software_version');
$response = '';
Log::debug('session', Gateway::getSession($this->clientId));
$gatewayType = isset($_SESSION['gateway_type']) ? $_SESSION['gateway_type'] : false;
if ($gatewayType === false) {
Log::debug('can not find gateway type');
return;
}
$gatewayUpdateModel = new GatewayUpdateModel();
$updateInfo = $gatewayUpdateModel->getColumns(['hardware_version', 'software_version', 'sign'], 'gateway_type = ' . $gatewayType);
if (count($updateInfo) !== 0) {
$updateHardwareVersion = $updateInfo['hardware_version'];
$sign = $updateInfo['sign'];
// $updateSoftwareVersion = sprintf('%08x', $updateInfo['software_version']);
$updateSoftwareVersion = sprintf($updateInfo['software_version']);
if ($updateHardwareVersion == $hardwareVersion && $updateSoftwareVersion == $softwareVersion) {
$returnCode = '10';
} else {
//todo 检查下载资源
$returnCode = '12';
$host = getenv('DOWNLOAD_HOST');
if ($host === false) {
throw new \Exception('can not find download host');
}
$downloadUrl = $host . '/update/' . $updateHardwareVersion . $updateSoftwareVersion . '.bin';
$urlHex = '';
for ($i = 0; $i < strlen($downloadUrl); $i++) {
$hex = sprintf('%02x', ord($downloadUrl[$i]));
$urlHex .= $hex;
}
Log::debug($updateSoftwareVersion);
Log::debug($updateHardwareVersion);
Log::debug($sign);
Log::debug($urlHex);
$this->response->send('d1', $returnCode . $updateHardwareVersion . $updateSoftwareVersion . $sign . $urlHex);
return;
}
$this->response->send('d1', $returnCode);
return;
}
$this->response->send('d1', '11');
return;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/28
* Time: 上午9:54
*/
namespace Application\model;
class BillTmpModel extends Model
{
protected $table = 'billing_tpls';
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/28
* Time: 上午9:57
*/
namespace Application\model;
class CardModel extends Model
{
protected $table = 'cards';
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/22
* Time: 上午10:06
*/
namespace Application\model;
class ConfigModel extends Model
{
protected $table = 'configs';
public function getIdConfigValue()
{
return $this->db->query('SELECT id , config_value FROM '.$this->table);
}
//最大功率限制
public function getPowerUpperLimit()
{
return $this->getColumn('config_value', 'id = 1');
}
//数据上报间隔时间
public function getInvertalTime()
{
return $this->getColumn('config_value', 'id = 5');
}
//获取计价配置时间间隔
public function getPriceConfig()
{
return $this->getColumn('config_value', 'id = 6');
}
//充满自停的功率检测此时
public function getPowerSaturateInvertalTime()
{
return $this->getColumn('config_value', 'id = 7');
}
//充满自停额外的供电时间
public function getExtraTime()
{
return $this->getColumn('config_value', 'id = 8');
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/20
* Time: 下午2:29
*/
namespace Application\model;
class DeviceModel extends Model
{
protected $table = 'devices';
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/24
* Time: 上午10:15
*/
namespace Application\model;
class ExceptionModel extends Model
{
protected $table = 'exception';
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/21
* Time: 下午3:23
*/
namespace Application\model;
class GatewayLogModel extends Model
{
protected $table = 'gateway_log';
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/20
* Time: 下午2:24
*/
namespace Application\model;
class GatewayModel extends Model
{
protected $table = 'gateways';
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/17
* Time: 上午11:10
*/
namespace Application\model;
class GatewayUpdateModel extends Model
{
protected $table = 'gateway_update';
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/17
* Time: 下午2:48
*/
namespace Application\model;
use Illuminate\Support\Facades\DB;
class Model
{
protected $table;
/**
* Model constructor.
*/
/**
* @param $column
* @param $where
* @return string
*/
public function getColumn($column, $where)
{
$where = str_split($where, '=');
$result = DB::table($this->table)->where($where[0], $where[1])->whereNotNull('deleted_at')->first([$column]);
if (blank($result)) {
$result = '';
} else {
$result = $result->$column;
}
return $result;
}
/**
* @param array $columns
* @param $where
* @return array
*/
public function getColumns(Array $columns, $where)
{
$where = str_split($where, '=');
$result = DB::table($this->table)->where($where[0], $where[1])->whereNotNull('deleted_at')->first($columns);
if (blank($result)) {
$result = [];
} else {
$result = json_decode(json_encode($result), true);
}
return $result;
}
/**
* @param array $columns
* @param $where
* @return mixed
*/
public function getAllColumns(Array $columns, $where)
{
$where = str_split($where, '=');
$result = DB::table($this->table)->where($where[0], $where[1])->whereNotNull('deleted_at')->get($columns);
if (blank($result)) {
$result = [];
} else {
$result = $result->toArray();
}
return $result;
}
/**
* @param $where
* @return array
*/
public function getRow($where)
{
return $this->db->row("SELECT * FROM $this->table WHERE $where");
}
/**
* @param array $data
* @return mixed
*/
public function insertRow(Array $data)
{
return DB::table($this->table)->insert($data);
}
/**
* @param array $update
* @param $where
* @return mixed
*/
public function update(array $update, $where)
{
$where = str_split($where, '=');
return DB::table($this->table)->where($where[0], $where[1])->update($update);
}
}
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/17
* Time: 下午2:57
*/
namespace Application\model;
class OrderExceptionModel extends Model
{
protected $table = 'wx_charger_orders_exception';
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/17
* Time: 下午2:50
*/
namespace Application\model;
class OrderModel extends Model
{
protected $table = 'wx_charger_orders';
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/20
* Time: 下午9:22
*/
namespace Application\model;
class OrderPowerModel extends Model
{
protected $table = 'order_power_capacity';
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/23
* Time: 下午7:46
*/
namespace Application\model;
class ParkModel extends Model
{
protected $table = 'parks';
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/22
* Time: 上午10:11
*/
namespace Application\model;
class StationModel extends Model
{
protected $table = 'stations';
}
\ No newline at end of file
<?php
namespace Application\route;
use Application\controller\Controller;
use Src\route\Route;
class Api
{
public $route = [];
public function boot()
{
$this->add('01', 'accept\CertifyController@certify');
$this->add('00', 'HeartController@break');
$this->add('02', 'accept\AccessController@request');
$this->add('03', 'accept\AccessController@syncPort');
$this->add('04', 'business\charger\StartController@start');
$this->add('05', 'business\charger\OverController@over');
$this->add('0B', 'business\port\StateController@change');
$this->add('07', 'business\power\PowerController@plural');
$this->add('17', 'business\power\PowerController@one');
$this->add('06', 'business\power\CapacityController@capacity');
$this->add('08', 'business\port\OnlineController@online');
$this->add('09', 'business\port\OfflineController@offline');
// $this->add('0F', 'business\power\ShutdownController@shutdown');
$this->add('0A', 'setting\SettingController@get');
$this->add('31', 'card\PayRuleController@get');
$this->add('32', 'card\BalanceController@get');
$this->add('33', 'card\charger\RequestController@request');
$this->add('34', 'card\charger\StartController@start');
$this->add('35', 'card\charger\OverController@over');
$this->add('0E', 'setting\DeviceMacController@getAll');
$this->add('D1', 'update\QueryController@check');
$this->add('CD', 'update\QueryController@currentVersion');
}
/**
* 添加路由
*
* @param string $command
* @param string $controllerAction
* @param array $middlewar
* @return void
*/
public function add(string $command, string $controllerAction, array $middleware = [])
{
$route = new Route();
$route->setCommand($command);
if (strstr($controllerAction, '@')) {
$controllerAction = explode('@', $controllerAction);
try {
$controllerName = 'Application\\controller\\' . $controllerAction[0];
$controller = new \ReflectionClass($controllerName);
$route->setController($controller);
$methods = $controller->getMethods(\ReflectionMethod::IS_PUBLIC);
$result = false;
foreach ($methods as $method) {
if ($method->name === $controllerAction[1]) {
$result = true;
}
}
if ($result === false) {
exit($controllerAction[1] . 'method not find');
}
$route->setMethod($controllerAction[1]);
unset($controller);
} catch (\ReflectionException $exception) {
exit(__CLASS__ . '-->' . $exception->getMessage());
}
$this->route[$command] = $route;
} else {
exit('wrong route missing controller');
}
unset($route);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/10
* Time: 上午11:05
*/
$worker = new \GatewayWorker\BusinessWorker();
$worker->name = 'cdz_business';
$worker->count = 1;
$worker->registerAddress = getenv('REGISTER_IP') . ':' . getenv('REGISTER_PORT');
//$logs = fopen('./storage/logs/business.log','w');
//fclose($logs);
//\GatewayWorker\BusinessWorker::$stdoutFile = './storage/stdout.log';
//\GatewayWorker\BusinessWorker::$logFile = './storage/logs/business.log';
if (!defined('GLOBAL_START')) {
\Workerman\Worker::runAll();
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/10
* Time: 上午11:05
*/
$gateway = new \GatewayWorker\Gateway('bintohex://0.0.0.0:' . getenv('GATEWAY_PORT'));
$gateway->name = 'cdz';
$gateway->count = getenv('GATEWAY_COUNT');
$gateway->lanIp = getenv('GATEWAY_IP');
$gateway->startPort = getenv('GATEWAY_START_PORT');
$gateway->registerAddress = getenv('REGISTER_IP') . ':' . getenv('REGISTER_PORT');
// 心跳间隔
$gateway->pingInterval = 50;
// 心跳数据
$gateway->pingNotResponseLimit = 2;
if (!defined('GLOBAL_START')) {
\Workerman\Worker::runAll();
}
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/10
* Time: 上午11:05
*/
$register = new \GatewayWorker\Register('text://' . getenv('REGISTER_IP') . ':' . getenv('REGISTER_PORT'));
if (!defined('GLOBAL_START')) {
\Workerman\Worker::runAll();
}
\ No newline at end of file
{ {
"name": "laravel/lumen", "name": "laravel/lumen",
"description": "The Laravel Lumen Framework.", "description": "The Laravel Lumen Framework.",
"keywords": ["framework", "laravel", "lumen"], "keywords": [
"license": "MIT", "framework",
"type": "project", "laravel",
"require": { "lumen"
"php": ">=7.1.3", ],
"laravel/lumen-framework": "5.6.*", "license": "MIT",
"vlucas/phpdotenv": "~2.2", "type": "project",
"guzzlehttp/guzzle": "~6.0", "require": {
"overtrue/laravel-lang": "^3.0" "php": ">=7.1.3",
}, "laravel/lumen-framework": "5.6.*",
"require-dev": { "vlucas/phpdotenv": "~2.2",
"fzaninotto/faker": "~1.4", "guzzlehttp/guzzle": "~6.0",
"phpunit/phpunit": "~7.0", "overtrue/laravel-lang": "^3.0"
"mockery/mockery": "~1.0" },
}, "require-dev": {
"autoload": { "fzaninotto/faker": "~1.4",
"psr-4": { "phpunit/phpunit": "~7.0",
"App\\": "app/", "mockery/mockery": "~1.0"
"Lib\\": "lib/", },
"Src\\": "src/" "autoload": {
} "psr-4": {
}, "App\\": "app/",
"autoload-dev": { "Lib\\": "lib/",
"classmap": [ "Src\\": "src/",
"tests/", "Application\\": "application/",
"database/" "Route\\": "route/"
]
},
"scripts": {
"post-root-package-install": [
"php -r \"copy('.env.example', '.env');\""
]
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
"optimize-autoloader": true
} }
},
"autoload-dev": {
"classmap": [
"tests/",
"database/"
]
},
"scripts": {
"post-root-package-install": [
"php -r \"copy('.env.example', '.env');\""
]
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
"optimize-autoloader": true
}
} }
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
return [ return [
'cert_path' => storage_path('cert/key.pem'), 'cert_path' => storage_path('cert/key.pem'),
'password' => 'IoM@1234', 'password' => 'IoM@1234',
'host' => 'https://180.101.147.89:8743/', 'host' => 'https://180.101.147.89:8743/',
'app_key' => 'tWVEY6ruJIYnQ1XdadMZHU9IR0sa',
]; ];
<?php
namespace Lib;
class Aes
{
public static function encrypt($data, $key)
{
return openssl_encrypt(hex2bin($data), 'aes-128-ecb', hex2bin($key), 1);
}
public static function decrypt($data, $key)
{
return openssl_decrypt(hex2bin($data), 'aes-128-ecb', hex2bin($key), 1);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/10/16
* Time: 下午10:42
*/
namespace Lib;
use Src\route\Route;
class Api
{
public $route = [];
public function boot()
{
$this->add('01', 'accept\CertifyController@certify');
$this->add('00', 'HeartController@break');
$this->add('02', 'accept\AccessController@request');
$this->add('03', 'accept\AccessController@syncPort');
$this->add('04', 'business\charger\StartController@start');
$this->add('05', 'business\charger\OverController@over');
$this->add('0B', 'business\port\StateController@change');
$this->add('07', 'business\power\PowerController@plural');
$this->add('17', 'business\power\PowerController@one');
$this->add('06', 'business\power\CapacityController@capacity');
$this->add('08', 'business\port\OnlineController@online');
$this->add('09', 'business\port\OfflineController@offline');
// $this->add('0F', 'business\power\ShutdownController@shutdown');
$this->add('0A', 'setting\SettingController@get');
$this->add('31', 'card\PayRuleController@get');
$this->add('32', 'card\BalanceController@get');
$this->add('33', 'card\charger\RequestController@request');
$this->add('34', 'card\charger\StartController@start');
$this->add('35', 'card\charger\OverController@over');
$this->add('0E', 'setting\DeviceMacController@getAll');
$this->add('D1', 'update\QueryController@check');
$this->add('CD', 'update\QueryController@currentVersion');
}
/**
* 添加路由
*
* @param string $command
* @param string $controllerAction
* @param array $middlewar
* @return void
*/
public function add(string $command, string $controllerAction, array $middleware = [])
{
$route = new Route();
$route->setCommand($command);
if (strstr($controllerAction, '@')) {
$controllerAction = explode('@', $controllerAction);
try {
$controllerName = 'Application\\controller\\' . $controllerAction[0];
$controller = new \ReflectionClass($controllerName);
$route->setController($controller);
$methods = $controller->getMethods(\ReflectionMethod::IS_PUBLIC);
$result = false;
foreach ($methods as $method) {
if ($method->name === $controllerAction[1]) {
$result = true;
}
}
if ($result === false) {
exit($controllerAction[1] . 'method not find');
}
$route->setMethod($controllerAction[1]);
unset($controller);
} catch (\ReflectionException $exception) {
exit(__CLASS__ . '-->' . $exception->getMessage());
}
$this->route[$command] = $route;
} else {
exit('wrong route missing controller');
}
unset($route);
}
}
\ No newline at end of file
<?php
namespace Lib;
class Crc
{
const CRC_TABLE = [
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
];
/**
* @param $data
* @return int
*/
public static function crc($data)
{
$crc = 0xffffffff;
$size = strlen($data);
for($i=0;$i<$size;$i+=2)
{
$numHex = substr($data,$i,2);
$number = hexdec($numHex);
$tmp = ($crc^$number) & 0xff;
$crcRightMove = (hexdec(sprintf("%08x",$crc>>8)));
$crc = ($crcRightMove)^(self::CRC_TABLE[$tmp]);
}
return $crc ^ 0xffffffff;
}
}
\ No newline at end of file
This diff is collapsed. Click to expand it.
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/17
* Time: 下午2:51
*/
namespace Lib;
class StateCode
{
const WAITING = -1;
const PORT_OFFLINE = 10;
const PORT_ONLINE = 11;
const PORT_CHARGER = 12;
const PORT_EXCEPTION = 13;
const PORT_SHED = 14;
const CHARGER_FAIL = 21;
const CHARGER_SHED = 22;
const CHARGER_SUCCESS = 23;
const FINISH_TIME_END = 30;
const FINISH_REMOTE = 31;
const FINISH_SHED = 32;
const FINISH_FULL = 33;
const FINISH_EXCEED = 34;
const FINISH_FAIL = 35;
const FINISH_CHARGER = 36;
const FINISH_USER = 41;
const FINISH_SHED_TIMEOUT = 42;
const FINISH_REFUND = 43;
const FINISH_EXCEPTION_REFUND = 44;
const CHANGE_PORT = 47;
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/29
* Time: 上午10:25
*/
namespace Lib;
class Tool
{
public static function padding($data, $length)
{
$length *= 2;
return sprintf('%0' . $length . 'x', $data);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/13
* Time: 上午11:22
*/
namespace Lib\cdz_order\state;
use Lib\cdz\order\Order;
class ExceptionState extends State
{
public function __construct(Order $order)
{
parent::__construct($order);
}
public function toUserFinish()
{
// TODO: Implement toUserFinish() method.
}
public function toWaitingState()
{
// TODO: Implement toWaitingState() method.
}
public function toChargerState()
{
// TODO: Implement toChargerState() method.
}
public function toExceptionState()
{
// TODO: Implement toExceptionState() method.
}
public function toPowerExceedState()
{
// TODO: Implement toPowerExceedState() method.
}
public function toPowerFullState()
{
// TODO: Implement toPowerFullState() method.
}
public function toShedState()
{
// TODO: Implement toShedState() method.
}
public function toShedTimeoutState()
{
// TODO: Implement toShedTimeoutState() method.
}
public function toTimeoutState()
{
// TODO: Implement toTimeoutState() method.
}
public function stopFail()
{
// TODO: Implement stopFail() method.
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/20
* Time: 下午6:45
*/
namespace Lib\cdz_order\state;
use Lib\cdz\order\NoticePortShed;
use Lib\cdz\order\Order;
use Lib\log\Log;
class OfflineNetState extends State
{
use NoticePortShed;
/**
* @var int
*/
private $remainChargerTime = 0;
public function __construct(Order $order)
{
parent::__construct($order);
$startTime = $this->order->getStartTime();
if ($startTime === '' || $this->order->getOfflineTime() == '0') {
$this->remainChargerTime = (int)($this->order->getPurchaseTime());
} else {
$purchaseTime = $this->order->getPurchaseTime();
$this->remainChargerTime = $purchaseTime * 60 - ((int)$this->order->getOnlineTime() - $startTime);
Log::debug('remain charger time' . $this->remainChargerTime);
$this->remainChargerTime = (int)($this->remainChargerTime / 60);
}
}
public function toUserFinish()
{
// TODO: Implement toUserFinish() method.
}
public function toWaitingState()
{
// TODO: Implement toWaitingState() method.
}
public function toChargerState()
{
if ($this->order->getIsRefund() === 1) {
//已经退款 下发结束充电命令
$this->order->stop($this->order, $_SESSION['client_id'], 43);
return;
}
}
public function toExceptionState()
{
// TODO: Implement toExceptionState() method.
}
public function toPowerExceedState()
{
// TODO: Implement toPowerExceedState() method.
}
public function toPowerFullState()
{
// TODO: Implement toPowerFullState() method.
}
/**
* @throws \AMQPConnectionException
* @throws \AMQPExchangeException
*/
public function toShedState()
{
if ($this->remainChargerTime > 0) {
$this->publishPortShed($this->order);
}
// TODO: Implement toShedState() method.
}
public function toShedTimeoutState()
{
// TODO: Implement toShedTimeoutState() method.
}
public function toTimeoutState()
{
// TODO: Implement toTimeoutState() method.
}
/**
* @return int
*/
public function getRemainChargerTime(): int
{
return $this->remainChargerTime;
}
/**
* @param int $remainChargerTime
*/
public function setRemainChargerTime(int $remainChargerTime): void
{
$this->remainChargerTime = $remainChargerTime;
}
public function stopFail()
{
// TODO: Implement stopFail() method.
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/20
* Time: 下午6:45
*/
namespace Lib\cdz_order\state;
use Lib\cdz\order\Order;
class OfflinePowerState extends State
{
/**
* @var int
*/
private $remainChargerTime = 0;
public function __construct(Order $order)
{
parent::__construct($order);
if ($this->order->getIsRefund() === 1) {
//已经退款 下发结束充电命令
//$this->order->stop($this->order,$_SESSION['client_id'],43);
$this->remainChargerTime = 0;
return;
}
$offlineTime = $this->order->getOfflineTime();
$startTime = $this->order->getStartTime();
if ($startTime === '' || $this->order->getOfflineTime() == '0') {
$this->remainChargerTime = (int)($this->order->getPurchaseTime());
} else {
$purchaseTime = $this->order->getPurchaseTime();
$this->remainChargerTime = $purchaseTime * 60 - ($offlineTime - $startTime);
$this->remainChargerTime = (int)($this->remainChargerTime / 60);
}
}
public function toUserFinish()
{
// TODO: Implement toUserFinish() method.
}
public function toWaitingState()
{
// TODO: Implement toWaitingState() method.
}
public function toChargerState()
{
if ($this->order->getIsRefund() === 1) {
//已经退款 下发结束充电命令
//$this->order->stop($this->order,$_SESSION['client_id'],43);
$this->remainChargerTime = 0;
return;
}
$offlineTime = $this->order->getOfflineTime();
$startTime = $this->order->getStartTime();
$purchaseTime = $this->order->getPurchaseTime();
$this->remainChargerTime = $purchaseTime * 60 - ($offlineTime - $startTime);
$this->remainChargerTime = (int)($this->remainChargerTime / 60);
}
public function toExceptionState()
{
// TODO: Implement toExceptionState() method.
}
public function toPowerExceedState()
{
// TODO: Implement toPowerExceedState() method.
}
public function toPowerFullState()
{
// TODO: Implement toPowerFullState() method.
}
public function toShedState()
{
// TODO: Implement toShedState() method.
}
public function toShedTimeoutState()
{
// TODO: Implement toShedTimeoutState() method.
}
public function toTimeoutState()
{
// TODO: Implement toTimeoutState() method.
}
public function stopFail()
{
// TODO: Implement stopFail() method.
}
/**
* @return int
*/
public function getRemainChargerTime(): int
{
return $this->remainChargerTime;
}
/**
* @param int $remainChargerTime
*/
public function setRemainChargerTime(int $remainChargerTime): void
{
$this->remainChargerTime = $remainChargerTime;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/13
* Time: 上午11:22
*/
namespace Lib\cdz_order\state;
use Lib\cdz\order\Order;
class PowerExceedState extends State
{
public function __construct(Order $order)
{
parent::__construct($order);
}
public function toUserFinish()
{
// TODO: Implement toUserFinish() method.
}
public function toWaitingState()
{
// TODO: Implement toWaitingState() method.
}
public function toChargerState()
{
// TODO: Implement toChargerState() method.
}
public function toExceptionState()
{
// TODO: Implement toExceptionState() method.
}
public function toPowerExceedState()
{
// TODO: Implement toPowerExceedState() method.
}
public function toPowerFullState()
{
// TODO: Implement toPowerFullState() method.
}
public function toShedState()
{
// TODO: Implement toShedState() method.
}
public function toShedTimeoutState()
{
// TODO: Implement toShedTimeoutState() method.
}
public function toTimeoutState()
{
// TODO: Implement toTimeoutState() method.
}
public function stopFail()
{
// TODO: Implement stopFail() method.
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/13
* Time: 上午11:22
*/
namespace Lib\cdz_order\state;
use Lib\cdz\order\Order;
class PowerFullState extends State
{
public function __construct(Order $order)
{
parent::__construct($order);
}
public function toWaitingState()
{
// TODO: Implement toWaitingState() method.
}
public function toChargerState()
{
// TODO: Implement toChargerState() method.
}
public function toExceptionState()
{
// TODO: Implement toExceptionState() method.
}
public function toPowerExceedState()
{
// TODO: Implement toPowerExceedState() method.
}
public function toPowerFullState()
{
// TODO: Implement toPowerFullState() method.
}
public function toShedState()
{
// TODO: Implement toShedState() method.
}
public function toShedTimeoutState()
{
// TODO: Implement toShedTimeoutState() method.
}
public function toTimeoutState()
{
// TODO: Implement toTimeoutState() method.
}
public function toUserFinish()
{
// TODO: Implement toUserFinish() method.
}
public function stopFail()
{
// TODO: Implement stopFail() method.
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/13
* Time: 上午11:21
*/
namespace Lib\cdz_order\state;
use Application\model\OrderExceptionModel;
use Application\model\OrderModel;
use Lib\cdz\order\Order;
use Lib\cdz\order\save\OrderSaveRedis;
use Lib\log\Log;
use Lib\remote\api\message\ChargerReloadMessage;
use Lib\remote\api\message\ChargerShedTimeOutMessage;
use Lib\remote\api\message\ChargerTimeoutMessage;
use Lib\remote\api\message\FinishByUserMessage;
use Lib\remote\api\message\SendMessage;
use Lib\StateCode;
use Lib\station\gateway\port\Port;
class ShedState extends State
{
public function __construct(Order $order)
{
parent::__construct($order);
}
/**
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function toUserFinish()
{
$orderModel = new OrderModel();
$orderModel->update([
'is_stop' => $this->order->getEndCode(),
'end_capacity' => $this->order->getEndCapacity(),
'updated_at' => $this->nowDate,
'end_time' => $this->nowDate,
'state' => 1,
], 'id = ' . $this->order->getId());
$port = new Port();
$port->setState(StateCode::PORT_ONLINE);
$port->setPortId($this->order->getPortId());
$port->setGatewayId($this->order->getGatewayId());
$port->setStationId($this->order->getStationId());
$port->freePort($this->order->getId());
//用户主动结束充电推送
$finishByUserMessage = new FinishByUserMessage();
$finishByUserMessage->setOrderId($this->order->getId());
$finishByUserMessage->setAddress($this->order->getStationName() . '--' . $this->order->getPortName());
$finishByUserMessage->setUserId($this->order->getUserId());
$chargerTime = (int)time() - (int)$this->order->getStartTime();
$chargerTime /= 60;
$chargerTime = (int)$chargerTime;
$finishByUserMessage->setChargerTime($chargerTime);
$finishByUserMessage->setEndTime($this->nowDate);
$finishByUserMessage->setOrderAmount($this->order->getPayAmount());
$sendMessage = new SendMessage();
if ($sendMessage->request($finishByUserMessage) == false) {
Log::error('send finish by user message fail');
}
$orderException = new OrderExceptionModel();
$orderException->insertRow([
'order_id' => $this->order->getId(),
'state' => StateCode::PORT_SHED . StateCode::FINISH_USER,
'desc' => '用户主动结束充电',
'created_at' => $this->nowDate,
]);
}
public function toWaitingState()
{
Log::error('shed state can not change to waiting state');
}
/**
* 更新订单状态
* 更新口子状态
* 推送微信消息
* 记录订单异常
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function toChargerState()
{
$this->order->setStateCode(StateCode::PORT_CHARGER);
$orderSaveRedis = new OrderSaveRedis($this->order);
$orderSaveRedis->save([
'stateCode',
]);
Log::debug('shed to charger');
$port = new Port($this->order->getPortId());
$port->setState(StateCode::PORT_CHARGER);
$port->updatePortState($this->order->getId());
$chargerReloadMessage = new ChargerReloadMessage();
$chargerReloadMessage->setUserId($this->order->getUserId());
$chargerReloadMessage->setOrderId($this->order->getId());
$chargerReloadMessage->setPortName($this->order->getPortName());
$chargerReloadMessage->setStationName($this->order->getStationName());
$sendMessage = new SendMessage();
if ($sendMessage->request($chargerReloadMessage) === false) {
Log::error('send order reload message fail');
}
$orderExceptionModel = new OrderExceptionModel();
$orderExceptionModel->insertRow(
[
'order_id' => $this->order->getId(),
'state' => StateCode::PORT_SHED . StateCode::PORT_CHARGER,
'created_at' => $this->nowDate,
'desc' => '订单口子脱落重新插上',
]
);
}
public function toExceptionState()
{
//todo
}
public function toPowerExceedState()
{
Log::error('shed state can not change to power exceed state');
}
public function toPowerFullState()
{
Log::error('shed state can not change to power full state');
}
public function toShedState()
{
Log::error('shed state can not change to shed');
}
/**
* 记录订单异常
* 释放口子
* 推送用户消息
* 更新订单记录,记录结束用电量
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function toShedTimeoutState()
{
$orderExceptionModel = new OrderExceptionModel();
$orderExceptionModel->insertRow([
'order_id' => $this->order->getId(),
'state' => StateCode::PORT_SHED . StateCode::FINISH_SHED_TIMEOUT,
'created_at' => $this->nowDate,
'desc' => '订单口子脱落超时结束',
]);
$orderModel = new OrderModel();
$orderModel->update([
'state' => 1,
'updated_at' => $this->nowDate,
'end_time' => $this->nowDate,
'is_stop' => StateCode::FINISH_SHED_TIMEOUT,
'end_capacity' => $this->order->getEndCapacity(),
], 'id = ' . $this->order->getId());
$port = new Port($this->order->getPortId());
$port->setState(StateCode::PORT_ONLINE);
$port->setStationId($this->order->getStationId());
$port->setGatewayId($this->order->getGatewayId());
$port->freePort($this->order->getId());
$shedTimeoutMessage = new ChargerShedTimeOutMessage();
$shedTimeoutMessage->setUserId($this->order->getUserId());
$shedTimeoutMessage->setPurchaseTime($this->order->getPurchaseTime());
$shedTimeoutMessage->setStartTime(date('Y-m-d H:i:s', $this->order->getStartTime()));
$shedTimeoutMessage->setEndTime($this->nowDate);
$sendMessage = new SendMessage();
if ($sendMessage->request($shedTimeoutMessage) === false) {
Log::error('send shed timeout message fail');
}
$orderModel = new OrderModel();
$orderModel->update([
'is_stop' => StateCode::FINISH_SHED_TIMEOUT,
'end_capacity' => $this->order->getEndCapacity(),
'state' => 1,
], 'id = ' . $this->order->getId());
}
/**
* 记录订单异常
* 释放口子
* 推送结束消息
* 更新订单记录
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function toTimeoutState()
{
$orderExceptionModel = new OrderExceptionModel();
$orderExceptionModel->insertRow([
'order_id' => $this->order->getId(),
'state' => StateCode::PORT_SHED . StateCode::FINISH_TIME_END,
'created_at' => $this->nowDate,
'desc' => '订单充电时间结束',
]);
$orderModel = new OrderModel();
$orderModel->update([
'is_stop' => StateCode::FINISH_TIME_END,
'end_capacity' => $this->order->getEndCapacity(),
'state' => 1,
'updated_at' => $this->nowDate,
'end_time' => $this->nowDate,
], 'id = ' . $this->order->getId());
$port = new Port($this->order->getPortId());
$port->setState(StateCode::PORT_ONLINE);
$port->setStationId($this->order->getStationId());
$port->setGatewayId($this->order->getGatewayId());
$port->freePort($this->order->getId());
$chargerTimeoutMessage = new ChargerTimeoutMessage();
$chargerTimeoutMessage->setOrderAmount($this->order->getPayAmount());
$chargerTime = $this->nowTimeStamp - (int)$this->order->getStartTime();
$chargerTime /= 60;
$chargerTimeoutMessage->setChargerTime((int)$chargerTime);
$chargerTimeoutMessage->setEndTime($this->nowDate);
$chargerTimeoutMessage->setUserId($this->order->getUserId());
$chargerTimeoutMessage->setOrderId($this->order->getOutTradeNo());
$chargerTimeoutMessage->setPortName($this->order->getPortName());
$chargerTimeoutMessage->setStationName($this->order->getStationName());
$sendMessage = new SendMessage();
if ($sendMessage->request($chargerTimeoutMessage) === false) {
Log::error('shed state order send charger timeout message fail');
}
}
public function stopFail()
{
// TODO: Implement stopFail() method.
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/13
* Time: 上午11:23
*/
namespace Lib\cdz_order\state;
use Lib\cdz\order\Order;
class ShedTimeoutState extends State
{
public function __construct(Order $order)
{
parent::__construct($order);
}
public function toWaitingState()
{
// TODO: Implement toWaitingState() method.
}
public function toChargerState()
{
// TODO: Implement toChargerState() method.
}
public function toExceptionState()
{
// TODO: Implement toExceptionState() method.
}
public function toPowerExceedState()
{
// TODO: Implement toPowerExceedState() method.
}
public function toPowerFullState()
{
// TODO: Implement toPowerFullState() method.
}
public function toShedState()
{
// TODO: Implement toShedState() method.
}
public function toShedTimeoutState()
{
// TODO: Implement toShedTimeoutState() method.
}
public function toTimeoutState()
{
// TODO: Implement toTimeoutState() method.
}
public function toUserFinish()
{
// TODO: Implement toUserFinish() method.
}
public function stopFail()
{
// TODO: Implement stopFail() method.
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/8/13
* Time: 上午11:21
*/
namespace Lib\cdz_order\state;
use Lib\cdz\order\Order;
abstract class State
{
/**
* @var State
*/
protected $currentState;
/**
* @var Order
*/
protected $order;
/**
* @var int
*/
protected $nowTimeStamp;
/**
* @var string
*/
protected $nowDate;
public function __construct(Order $order)
{
$this->nowTimeStamp = time();
$this->nowDate = date('Y-m-d H:i:s', $this->nowTimeStamp);
$this->order = $order;
}
public abstract function toWaitingState();
public abstract function toChargerState();
public abstract function toExceptionState();//充电异常
public abstract function toPowerExceedState(); //功率超限
public abstract function toPowerFullState(); //充满自停
public abstract function toShedState(); //口子脱落
public abstract function toShedTimeoutState(); //口子脱落超时
public abstract function toTimeoutState(); //时间耗尽
public abstract function toUserFinish();
public abstract function stopFail();
/**
* @return Order
*/
public function getOrder(): Order
{
return $this->order;
}
/**
* @param Order $order
*/
public function setOrder(Order $order): void
{
$this->order = $order;
}
}
\ No newline at end of file
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
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