Commit 9289eba3 by banice

iot获取accesstoken完成,测试下发comand

parent a069feb3
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/28
* Time: 上午10:55
*/
namespace App\Http\Controllers\access;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Lib\iot\AccessToken;
use Lib\iot\IotClient;
class AccessController extends Controller
{
public function accessToken(AccessToken $accessToken)
{
$iotClient = new IotClient($accessToken);
if ($iotClient->request() === true) {
$response = $iotClient->getResponse();
Log::debug($response->getBody());
}
dd(1);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/29
* Time: 下午3:23
*/
namespace App\Http\Controllers\device;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class ChargerController extends Controller
{
public function charger(Request $request)
{
dd(1);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/29
* Time: 上午11:13
*/
namespace App\Providers;
use Carbon\Laravel\ServiceProvider;
class AccessTokenProvider extends ServiceProvider
{
public function register()
{
}
}
\ No newline at end of file
<?php
require_once __DIR__.'/../vendor/autoload.php';
require_once __DIR__ . '/../vendor/autoload.php';
try {
(new Dotenv\Dotenv(__DIR__.'/../'))->load();
(new Dotenv\Dotenv(__DIR__ . '/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
//
}
......@@ -20,12 +20,15 @@ try {
*/
$app = new Laravel\Lumen\Application(
realpath(__DIR__.'/../')
realpath(__DIR__ . '/../')
);
// $app->withFacades();
$app->withFacades();
// $app->withEloquent();
$app->withEloquent();
$app->configure('logging');
$app->configure('iot');
/*
|--------------------------------------------------------------------------
......@@ -96,7 +99,7 @@ $app->singleton(
$app->router->group([
'namespace' => 'App\Http\Controllers',
], function ($router) {
require __DIR__.'/../routes/web.php';
require __DIR__ . '/../routes/web.php';
});
return $app;
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -18,7 +18,9 @@
},
"autoload": {
"psr-4": {
"App\\": "app/"
"App\\": "app/",
"Lib\\": "lib/",
"Src\\": "src/"
}
},
"autoload-dev": {
......
<?php
return [
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY', 'UqYFWOkD4q6L9duemwxrF5yGX2TF8XzN'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => env('APP_LOCALE', 'en'),
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
// 'aliases' => [
// 'Validator' => \Illuminate\Support\Facades\Validator::class
// ]
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'api'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "token"
|
*/
'guards' => [
'api' => ['driver' => 'jwt','provider' => 'users'],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
//
'users' => [
'driver' => 'eloquent',
'model' => \App\Model\WxUserModel::class
]
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| Here you may set the options for resetting passwords including the view
| that is your password reset e-mail. You may also set the name of the
| table that maintains all of the reset tokens for your application.
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
//
],
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Broadcaster
|--------------------------------------------------------------------------
|
| This option controls the default broadcaster that will be used by the
| framework when an event needs to be broadcast. You may set this to
| any of the connections defined in the "connections" array below.
|
*/
'default' => env('BROADCAST_DRIVER', 'pusher'),
/*
|--------------------------------------------------------------------------
| Broadcast Connections
|--------------------------------------------------------------------------
|
| Here you may define all of the broadcast connections that will be used
| to broadcast events to other systems or over websockets. Samples of
| each available type of connection are provided inside this array.
|
*/
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_KEY'),
'secret' => env('PUSHER_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
],
'redis' => [
'driver' => 'redis',
'connection' => env('BROADCAST_REDIS_CONNECTION', 'default'),
],
'log' => [
'driver' => 'log',
],
],
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache connection that gets used while
| using this caching library. This connection is used when another is
| not explicitly specified when executing a given caching function.
|
*/
'default' => env('CACHE_DRIVER', 'redis'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
*/
'stores' => [
'apc' => [
'driver' => 'apc',
],
'array' => [
'driver' => 'array',
],
'database' => [
'driver' => 'database',
'table' => env('CACHE_DATABASE_TABLE', 'cache'),
'connection' => env('CACHE_DATABASE_CONNECTION', null),
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache'),
],
'memcached' => [
'driver' => 'memcached',
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'), 'port' => env('MEMCACHED_PORT', 11211), 'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => env('CACHE_REDIS_CONNECTION', 'default'),
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing a RAM based store such as APC or Memcached, there might
| be other applications utilizing the same cache. So, we'll specify a
| value to get prefixed to all our keys so we can avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', 'laravel'),
];
<?php
return [
/*
|--------------------------------------------------------------------------
| PDO Fetch Style
|--------------------------------------------------------------------------
|
| By default, database results will be returned as instances of the PHP
| stdClass object; however, you may desire to retrieve records in an
| array format for simplicity. Here you can tweak the fetch style.
|
*/
'fetch' => PDO::FETCH_CLASS,
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'testing' => [
'driver' => 'sqlite',
'database' => ':memory:',
],
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', base_path('database/database.sqlite')),
'prefix' => env('DB_PREFIX', ''),
],
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', 3306),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => env('DB_PREFIX', ''),
'timezone' => env('DB_TIMEZONE', '+08:00'),
'strict' => env('DB_STRICT_MODE', false),
],
'old_cdz' => [
'driver' => 'mysql',
'host' => env('PRE_DB_HOST'),
'port' => env('PRE_DB_PORT', 3306),
'database' => env('PRE_DB_DATABASE'),
'username' => env('PRE_DB_USERNAME'),
'password' => env('PRE_DB_PASSWORD'),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => env('DB_PREFIX', ''),
'timezone' => env('DB_TIMEZONE', '+08:00'),
'strict' => env('DB_STRICT_MODE', false),
],
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', 5432),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => env('DB_PREFIX', ''),
'schema' => env('DB_SCHEMA', 'public'),
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => env('DB_PREFIX', ''),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'cluster' => env('REDIS_CLUSTER', false),
'default' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_DATABASE', 4),
'password' => env('REDIS_PASSWORD', null),
],
],
];
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/29
* Time: 上午10:34
*/
return [
'cert_path' => storage_path('cert/key.pem'),
'password' => 'IoM@1234',
'host' => 'https://180.101.147.89:8743/',
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that gets used when writing
| messages to the logs. The name specified in this option should match
| one of the channels defined in the "channels" configuration array.
|
*/
'default' => env('LOG_CHANNEL', 'daily'),
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: "single", "daily", "slack", "syslog",
| "errorlog", "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/lumen.log'),
'level' => 'debug',
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/lumen.log'),
'level' => 'debug',
'days' => 7,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Lumen Log',
'emoji' => ':boom:',
'level' => 'critical',
],
'syslog' => [
'driver' => 'syslog',
'level' => 'debug',
],
'errorlog' => [
'driver' => 'errorlog',
'level' => 'debug',
],
],
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Driver
|--------------------------------------------------------------------------
|
| The Laravel queue API supports a variety of back-ends via an unified
| API, giving you convenient access to each back-end using the same
| syntax for each one. Here you may set the default queue driver.
|
| Supported: "null", "sync", "database", "beanstalkd", "sqs", "redis"
|
*/
'default' => env('QUEUE_DRIVER', 'sync'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection information for each server that
| is used by your application. A default configuration has been added
| for each back-end shipped with Laravel. You are free to add more.
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 60,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 60,
],
'sqs' => [
'driver' => 'sqs',
'key' => 'your-public-key',
'secret' => 'your-secret-key',
'queue' => 'your-queue-url',
'region' => 'us-east-1',
],
'redis' => [
'driver' => 'redis',
'connection' => env('QUEUE_REDIS_CONNECTION', 'default'),
'queue' => 'default',
'retry_after' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control which database and table are used to store the jobs that
| have failed. You may change them to any database / table you wish.
|
*/
'failed' => [
'database' => env('DB_CONNECTION', 'mysql'),
'table' => env('QUEUE_FAILED_TABLE', 'failed_jobs'),
],
];
<?php
/**
* Created by PhpStorm.
* User: suhangyang
* Date: 2018/5/4
* Time: 上午10:05
*/
return [
'host' => env('RABBIT_HOST'),
'port' => env('RABBIT_PORT'),
'login' => env('RABBIT_LOGIN'),
'password' => env('RABBIT_PASSWORD'),
'vhost' => env('RABBIT_VHOST'),
];
<?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views. Of course
| the usual Laravel view path has already been registered for you.
|
*/
'paths' => [
realpath(base_path('resources/views')),
],
/*
|--------------------------------------------------------------------------
| Compiled View Path
|--------------------------------------------------------------------------
|
| This option determines where all the compiled Blade templates will be
| stored for your application. Typically, this is within the storage
| directory. However, as usual, you are free to change this value.
|
*/
'compiled' => realpath(storage_path('framework/views')),
];
<?php
/**
* Created by PhpStorm.
* User: suhangyang
* Date: 2018/4/27
* Time: 上午9:05
*/
return [
// 'appId' => 'wx2d049ccbde322c2e',
// 'appId' => 'wx72a0a0591e4e2539',
// 'appSecret' => '41e2827de3927f2c3de392c2800b90bf',
// 'appSecret' => '075401bcb54ae99b62cd9755f4bd939f',
// 'mch_id' => '1480201542',
'cache_user_token' => 'wx_user_token_',
'appId' => env('WX_APP_ID'),
'appSecret' => env('WX_APP_SECRET'),
'mch_id' => env('WX_MCH_ID'),
'lang' => env('WX_LANG'),
];
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/29
* Time: 下午2:27
*/
namespace Lib;
class ToHex
{
public static function toHex(int $data, int $length): string
{
return sprintf('%0' . $length * 2 . 'x', $data);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/28
* Time: 上午10:47
*/
namespace Lib\iot;
use Illuminate\Support\Facades\Cache;
use Psr\Http\Message\ResponseInterface;
class AccessToken implements Request
{
const ACCESS_CACHE_KEY = 'cdz:iot:access_token';
const REFRESH_ACCESS_CACHE_KEY = 'cdz:iot:refresh_token';
protected $url = 'iocm/app/sec/v1.1.0/login';
protected $method = 'POST';
protected $formData = [];
private $appId = '';
private $appSecret = '';
private $accessToken = '';
private $refreshToken = '';
public function __construct()
{
$this->appId = env('APP_ID');
$this->appSecret = env('APP_SECRET');
}
public function parseResponse(ResponseInterface $response)
{
$body = json_decode($response->getBody(), true);
$this->accessToken = $body['accessToken'];
$expiresLn = $body['expiresLn'];
$this->refreshToken = $body['refreshToken'];
Cache::put(self::ACCESS_CACHE_KEY, $this->accessToken, $expiresLn / 60);
Cache::put(self::REFRESH_ACCESS_CACHE_KEY, $this->refreshToken, 28 * 24 * 60);
}
public static function getAccessTokenCache()
{
if (Cache::has(self::ACCESS_CACHE_KEY) === true) {
return Cache::get(self::ACCESS_CACHE_KEY);
} else if (Cache::has(self::REFRESH_ACCESS_CACHE_KEY) === true) {
//todo refresh 换取token 并缓存新的token和新的refresh
$refreshToken = new RefreshToken();
$refreshToken->setRefreshToken(Cache::get(self::REFRESH_ACCESS_CACHE_KEY));
$iotClient = new IotClient($refreshToken);
if ($iotClient->request() === true) {
$response = $iotClient->getResponse();
$accessToken = $refreshToken->parseResponse($response);
return $accessToken->getAccessToken();
}
} else {
//todo 请求token
$accessToken = new AccessToken();
$iotClient = new IotClient($accessToken);
if ($iotClient->request() === true) {
$accessToken->parseResponse($iotClient->getResponse());
return $accessToken->getAccessToken();
}
}
}
/**
* @return mixed|string
*/
public function getAppId()
{
return $this->appId;
}
/**
* @param mixed|string $appId
*/
public function setAppId($appId): void
{
$this->appId = $appId;
}
/**
* @return mixed|string
*/
public function getAppSecret()
{
return $this->appSecret;
}
/**
* @param mixed|string $appSecret
*/
public function setAppSecret($appSecret): void
{
$this->appSecret = $appSecret;
}
/**
* @return string
*/
public function getAccessToken(): string
{
return $this->accessToken;
}
/**
* @param string $accessToken
*/
public function setAccessToken(string $accessToken): void
{
$this->accessToken = $accessToken;
}
/**
* @return string
*/
public function getRefreshToken(): string
{
return $this->refreshToken;
}
/**
* @param string $refreshToken
*/
public function setRefreshToken(string $refreshToken): void
{
$this->refreshToken = $refreshToken;
}
/**
* @return string
*/
public function getUrl(): string
{
return $this->url;
}
/**
* @param string $url
*/
public function setUrl(string $url): void
{
$this->url = $url;
}
/**
* @return string
*/
public function getMethod(): string
{
return $this->method;
}
/**
* @param string $method
*/
public function setMethod(string $method): void
{
$this->method = $method;
}
/**
* @return array
*/
public function getFormData(): array
{
$this->formData = [
'appId' => $this->appId,
'secret' => $this->appSecret,
];
return $this->formData;
}
/**
* @param array $formData
*/
public function setFormData(array $formData): void
{
$this->formData = $formData;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/28
* Time: 上午10:51
*/
namespace Lib\iot;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
use Psr\Http\Message\ResponseInterface;
class IotClient
{
/**
* @var Request
*/
private $request;
private $headers = [];
/**
* @var ResponseInterface
*/
private $response;
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* @return bool
*/
public function request(): bool
{
$client = new Client();
Log::debug(storage_path('cert/key.pem'));
$request = [
'form_params' => $this->request->getFormData(),
'verify' => false,
'cert' => [
config('cert.cert_path'),
'IoM@1234',
]
];
if (filled($this->headers) === true) {
$request['headers'] = $this->headers;
}
$this->response = $client->request($this->request->getMethod(), config('iot.host') . $this->request->getUrl(), $request);
return $this->response->getStatusCode() === 200;
}
/**
* @return ResponseInterface
*/
public function getResponse(): ResponseInterface
{
return $this->response;
}
/**
* @return Request
*/
public function getRequest(): Request
{
return $this->request;
}
/**
* @param Request $request
*/
public function setRequest(Request $request): void
{
$this->request = $request;
}
/**
* @return array
*/
public function getHeaders(): array
{
return $this->headers;
}
/**
* @param array $headers
*/
public function setHeaders(array $headers): void
{
$this->headers = $headers;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/29
* Time: 上午10:54
*/
namespace Lib\iot;
use Psr\Http\Message\ResponseInterface;
class RefreshToken implements Request
{
private $refreshToken = '';
/**
* @param ResponseInterface $response
* @return AccessToken
*/
public function parseResponse(ResponseInterface $response)
{
$accessToken = new AccessToken();
$accessToken->parseResponse($response);
return $accessToken;
}
public function getUrl(): string
{
return 'iocm/app/sec/v1.1.0/refreshToken';
}
public function getMethod(): string
{
return 'POST';
}
public function getFormData(): array
{
return [
'appId' => env('IOT_APP_ID'),
'secret' => env('IOT_APP_SECRET'),
'refreshToken' => $this->refreshToken
];
}
/**
* @return string
*/
public function getRefreshToken(): string
{
return $this->refreshToken;
}
/**
* @param string $refreshToken
*/
public function setRefreshToken(string $refreshToken): void
{
$this->refreshToken = $refreshToken;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/28
* Time: 上午10:49
*/
namespace Lib\iot;
use Psr\Http\Message\ResponseInterface;
interface Request
{
public function getUrl(): string;
public function getMethod(): string;
public function getFormData(): array;
public function parseResponse(ResponseInterface $response);
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/29
* Time: 上午11:45
*/
namespace Lib\iot\command;
use Lib\iot\Request;
use Lib\ToHex;
class ChargerCommand extends Command
{
protected $command = '04';
private $type = 1;
private $portLogic = 0;
private $orderId = 0;
private $time = 0;
public function organizeMessage()
{
$this->message = ToHex::toHex($this->type, 1) . ToHex::toHex($this->portLogic, 1) . ToHex::toHex($this->orderId, 6) . ToHex::toHex($this->time, 2);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/29
* Time: 上午11:38
*/
namespace Lib\iot\command;
use Lib\iot\Request;
use Psr\Http\Message\ResponseInterface;
abstract class Command
{
protected $crc = '';
protected $command = '';
protected $encrypt = '04';
protected $length = 0;
protected $serviceId = '';
protected $method = '';
protected $paras = [];
protected $message = '';
abstract public function organizeMessage();
/**
* @return string
*/
public function getCrc(): string
{
return $this->crc;
}
/**
* @param string $crc
*/
public function setCrc(string $crc): void
{
$this->crc = $crc;
}
/**
* @return string
*/
public function getCommand(): string
{
return $this->command;
}
/**
* @param string $command
*/
public function setCommand(string $command): void
{
$this->command = $command;
}
/**
* @return string
*/
public function getEncrypt(): string
{
return $this->encrypt;
}
/**
* @param string $encrypt
*/
public function setEncrypt(string $encrypt): void
{
$this->encrypt = $encrypt;
}
/**
* @return int
*/
public function getLength(): int
{
return $this->length;
}
/**
* @param int $length
*/
public function setLength(int $length): void
{
$this->length = $length;
}
/**
* @return string
*/
public function getServiceId(): string
{
return $this->serviceId;
}
/**
* @param string $serviceId
*/
public function setServiceId(string $serviceId): void
{
$this->serviceId = $serviceId;
}
/**
* @return string
*/
public function getMethod(): string
{
return $this->method;
}
/**
* @param string $method
*/
public function setMethod(string $method): void
{
$this->method = $method;
}
/**
* @return string
*/
public function getMessage(): string
{
return $this->message;
}
/**
* @param string $message
*/
public function setMessage(string $message): void
{
$this->message = $message;
}
public function getParas()
{
return json_encode($this->message);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: banice
* Date: 2018/9/29
* Time: 上午11:34
*/
namespace Lib\iot\command;
use Illuminate\Support\Facades\Log;
use Lib\iot\AccessToken;
use Lib\iot\IotClient;
use Lib\iot\Request;
use Lib\ToHex;
use Psr\Http\Message\ResponseInterface;
/**
* 发送命令至iot设备
* Class Send
* @package Lib\iot\command
*/
class Send implements Request
{
protected $accessToken = '';
protected $appKey = '';
protected $contentType = 'application/json';
protected $appId = '';
protected $deviceId = '';
protected $command = '';
protected $commandInstance;
protected $callBackUrl = '';
protected $expireTime = 0;
protected $maxRetransmit = 2;
/**
* Send constructor.
* @param Command $command
* @throws \Exception
*/
public function __construct(Command $command)
{
$this->commandInstance = $command;
$body = $this->commandInstance->getMessage();
$nonce = ToHex::toHex(rand(1, 255), 1);
$length = 7 + strlen($body) / 2;
$message = 'ffaa' . $this->commandInstance->getEncrypt() . ToHex::toHex($length, 2) . $nonce . $body;
if ($this->commandInstance->getEncrypt() === '04') {
$this->command = [
'serviceId' => $this->commandInstance->getServiceId(),
'method' => $this->commandInstance->getMethod(),
'paras' => json_encode($message),
];
} else {
throw new \Exception('no encrypt function');
}
}
public function send()
{
$iotClient = new IotClient($this);
$iotClient->setHeaders([
'app_key' => env('IOT_APP_KEY'),
'Authorization' => 'Bearer' . AccessToken::getAccessTokenCache(),
'Content-Type' => 'application/json'
]);
if ($iotClient->request() === true) {
$response = $iotClient->getResponse();
Log::debug($response->getBody());
}
}
public function getUrl(): string
{
return 'iocm/app/cmd/v1.4.0/deviceCommands';
}
public function getMethod(): string
{
return 'POST';
// TODO: Implement getMethod() method.
}
public function getFormData(): array
{
return [
'appId' => env('IOT_APP_ID'),
'deviceId' => $this->deviceId,
'command' => json_encode($this->command),
'callbackUrl' => $this->callBackUrl,
'expireTime' => $this->expireTime,
'maxRetransmit' => $this->maxRetransmit,
];
}
public function parseResponse(ResponseInterface $response)
{
// TODO: Implement parseResponse() method.
}
}
\ No newline at end of file
......@@ -12,5 +12,13 @@
*/
$router->get('/', function () use ($router) {
\Illuminate\Support\Facades\Log::debug('hello');
return $router->app->version();
});
$router->get('access', 'access\AccessController@accessToken');
$router->post('device/power/on', 'device\ChargerController@charger');
......@@ -18,12 +18,14 @@ return array(
'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'),
'Symfony\\Component\\Debug\\' => array($vendorDir . '/symfony/debug'),
'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
'Src\\' => array($baseDir . '/src'),
'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'),
'Psr\\Container\\' => array($vendorDir . '/psr/container/src'),
'Overtrue\\LaravelLang\\' => array($vendorDir . '/overtrue/laravel-lang/src'),
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
'Lib\\' => array($baseDir . '/lib'),
'Laravel\\Lumen\\' => array($vendorDir . '/laravel/lumen-framework/src'),
'Illuminate\\View\\' => array($vendorDir . '/illuminate/view'),
'Illuminate\\Validation\\' => array($vendorDir . '/illuminate/validation'),
......
......@@ -40,6 +40,7 @@ class ComposerStaticInitd4e1956f0fe9de6b5aca97be9b83adf5
'Symfony\\Component\\EventDispatcher\\' => 34,
'Symfony\\Component\\Debug\\' => 24,
'Symfony\\Component\\Console\\' => 26,
'Src\\' => 4,
),
'P' =>
array (
......@@ -58,6 +59,7 @@ class ComposerStaticInitd4e1956f0fe9de6b5aca97be9b83adf5
),
'L' =>
array (
'Lib\\' => 4,
'Laravel\\Lumen\\' => 14,
),
'I' =>
......@@ -165,6 +167,10 @@ class ComposerStaticInitd4e1956f0fe9de6b5aca97be9b83adf5
array (
0 => __DIR__ . '/..' . '/symfony/console',
),
'Src\\' =>
array (
0 => __DIR__ . '/../..' . '/src',
),
'Psr\\SimpleCache\\' =>
array (
0 => __DIR__ . '/..' . '/psr/simple-cache/src',
......@@ -189,6 +195,10 @@ class ComposerStaticInitd4e1956f0fe9de6b5aca97be9b83adf5
array (
0 => __DIR__ . '/..' . '/monolog/monolog/src/Monolog',
),
'Lib\\' =>
array (
0 => __DIR__ . '/../..' . '/lib',
),
'Laravel\\Lumen\\' =>
array (
0 => __DIR__ . '/..' . '/laravel/lumen-framework/src',
......
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