天貓精靈云云接入——前端VUE、伺服器PHP、後端java
阿新 • • 發佈:2021-01-24
天貓精靈云云接入——前端VUE、伺服器PHP、後端java
- 第一次寫部落格,如果有什麼問題或者疑問可以私信或者評論,謝謝。
AliGenie
- 接入流程:https://www.aligenie.com/doc/357554/sisusm
- 建立 https://iap.aligenie.com/console/skill/list 的內容與iot的技能
文件: https://www.aligenie.com/doc/357554/hf8wog - 請求方式:Oauth2授權-https://www.aligenie.com/doc/357554/chhley
- 云云接入協議:https://www.aligenie.com/doc/357554/bqd045
VUE
- 登陸頁面:登入名+密碼,登陸之後返回該使用者的code,然後跳轉url+code就OK了。
獲取引數
- 將下列方法放置在methods中,通過在mounted中給屬性賦值:this.getUrlKey(‘屬性值’,‘url);
注:屬性值是string型別,url是要獲取到的url(eg:window.location.href’ - 當前頁面的url)
getUrlKey(name, url) {
return (
decodeURIComponent(
(new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
url
) || [, ""])[1].replace(/\+/g, "%20")
) || null
);
獲取code
- 登陸之後,後端返回使用者的code
- eg:code
DigestUtils. md5DigestAsHex((UUID.randomUUID().toString() + System.currentTimeMillis()).getBytes()
跳轉頁面
window.location.href = this.urlPath + "&code=" +'code';
PHP
- 傳送請求
通過獲取code、grant_type換取token
- 獲取post裡面的引數
$code = $_POST['code'];
$type = $_POST['grant_type'];
$token = $_POST['refresh_token'];
- 為post請求攜帶上請求引數
$code = $_POST['code'];
$type = $_POST['grant_type'];
$token = $_POST['refresh_token'];
- 傳送請求並獲取返回的值
- 發請求
$res = post_curls('介面', $post);
- post請求方法
function post_curls($url, $post)
{
$curl = curl_init(); // 啟動一個CURL會話
curl_setopt($curl, CURLOPT_URL, $url); // 要訪問的地址
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 對認證證書來源的檢查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 從證書中檢查SSL加密演算法是否存在
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模擬使用者使用的瀏覽器
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自動跳轉
curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自動設定Referer
curl_setopt($curl, CURLOPT_POST, 1); // 傳送一個常規的Post請求
curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的資料包
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 設定超時限制防止死迴圈
curl_setopt($curl, CURLOPT_HEADER, 0); // 顯示返回的Header區域內容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 獲取的資訊以檔案流的形式返回
$res = curl_exec($curl); // 執行操作
if (curl_errno($curl)) {
echo 'Errno'.curl_error($curl);//捕抓異常
}
curl_close($curl); // 關閉CURL會話
return $res; // 返回資料,json格式
}
?>
- 獲取返回值,並將其返回
注:我這邊返回值放在了data裡面,所以$arr獲取的是data
$arr = json_decode($res, true);
$data = $arr['data'];
echo json_encode($data);
獲取使用者裝置
- 獲取到請求需要的引數
$arr = json_decode(file_get_contents("php://input"), true);
$namespace = $arr['header']['namespace'];
$name = $arr['header']['name'];
$messageId = $arr['header']['messageId'];
$payLoadVersion = $arr['header']['payLoadVersion'];
$accessToken = $arr['payload']['accessToken'];
$deviceId = $arr['payload']['deviceId'];
$value = $arr['payload']['value'];
- 給請求頭賦值
header('namespace:'.$namespace);
header('name:'.$name);
header('messageId:'.$messageId);
header('payLoadVersion:'.$payLoadVersion);
- 傳送請求並獲取返回的值
- 傳送請求
$res = post_curls('介面', $post);
- 獲取返回值,並將其返回
$arr = json_decode($res, true);
$data = $arr['data'];
echo json_encode($data);
JAVA
獲取code
- 確認登入名+密碼無誤後,將uuid+時間戳的md5之後的字串更新到伺服器資料庫,並將其值返回
獲取token
- 首先判斷獲取到的grant_Type是否為 authorization_code
- 然後將code遍歷伺服器資料庫,獲取到使用者的token,如果沒有就走一遍類似於code的流程;如果有就就獲取到
- 最後將當前使用者的 access_token、refresh_token、expires_in 返回
使用者裝置
- 通過判斷獲取到的 namespace、name 判斷請求當前介面是用來做什麼
- 然後寫好與 云云接入協議 匹配的介面就好了。
eg:
@RestController
public class AliGenieController {
@Autowired
private UserService userService;
@Autowired
private DeviceService deviceService;
@Autowired
private CdeviceService cdeviceService
//控制裝置
@Autowired
private TaskController taskController
@PostMapping("Oautho/User/login")
@CrossOrigin
public Result LoginUser(String telephone, String passwd, String urlPath) {
User user = userService.getUserByTelephone(telephone);
if (user != null) {
if (user.getPasswd().equals(passwd)) {
String string;
if(StringUtil.isEmpty(user.getCode())){
string = getStringFrom();
user.setCode(string);
userService.updateByID(user);
}else {
string = user.getCode();
}
return Result.ok(string);
}
return Result.build(-1, "手機號與密碼不匹配,請確認後再登入");
}
return Result.build(-1, "該手機號未被註冊,請確認後再登入");
}
@RequestMapping("Oautho/User/getToken")
public Result getUserTokne(String clientId, String grantType, String clientSecret, String code, String urlPath, String refresh_token) {
String accessToken;
if ("authorization_code".equals(grantType)) {
User user = userService.getUserByCode(code);
JSONObject jsonObject = new JSONObject();
try {
if (user != null) {
if (StringUtil.isNotEmpty(user.getAccess_Token())) {
jsonObject.put("access_token", user.getAccess_Token());
jsonObject.put("refresh_token", user.getRefresh_token());
} else {
accessToken = getStringFrom();
refresh_token = getStringFrom();
user.setAccess_Token(accessToken);
user.setRefresh_token(refresh_token);
userService.updateByID(user);
jsonObject.put("access_token", accessToken);
jsonObject.put("refresh_token", refresh_token);
}
jsonObject.put("expires_in", 17600000);
} else {
jsonObject.put("error", "100");
jsonObject.put("error_description", "請確認code");
}
return Result.ok(jsonObject);
} catch (Exception e) {
e.printStackTrace();
try {
jsonObject.put("error", "101");
jsonObject.put("error_description", e);
return Result.ok(jsonObject);
} catch (Exception jsonException) {
return Result.ok(jsonException);
}
}
} else if ("refresh_token".equals(grantType)) {
User user = userService.getUserByRefreshToken(refresh_token);
JSONObject jsonObject = new JSONObject();
try {
accessToken = getStringFrom();
refresh_token = getStringFrom();
user.setAccess_Token(accessToken);
user.setRefresh_token(refresh_token);
userService.updateByID(user);
jsonObject.put("access_token", accessToken);
jsonObject.put("refresh_token", refresh_token);
jsonObject.put("expires_in", 17600000);
return Result.ok(jsonObject);
} catch (Exception e) {
e.printStackTrace();
try {
jsonObject.put("error", "100");
jsonObject.put("error_description", e);
return Result.ok(jsonObject);
} catch (Exception jsonException) {
return Result.ok(jsonException);
}
}
}
return Result.build(-1, "請確認授權型別");
}
@RequestMapping("Oautho/device")
public Result getDevice(String namespace, String name, String messageId, @RequestParam(defaultValue = "1") Integer payLoadVersion,
String accessToken,
@RequestParam(defaultValue = "") String deviceId, @RequestParam(defaultValue = "") String deviceType,
@RequestParam(defaultValue = "") String attribute, @RequestParam(defaultValue = "") String value) {
Integer userId = userService.getUserByToken(accessToken);
AliGenieUtil aliGenieUtil = new AliGenieUtil();
Integer deviceid = null;
if(StringUtil.isNotEmpty(deviceType)){
deviceid = Integer.parseInt(deviceId);
}
if (userId != null) {
if ("AliGenie.Iot.Device.Discovery".equals(namespace)) {
//裝置發現
if ("DiscoveryDevices".equals(name)) {
//查詢裝置\
List<DeviceandCdevice> deviceUser;
try {
deviceUser = (List<DeviceandCdevice>) deviceService.sltDeviceAndCdevice(userId).getData();
} catch (ParseException parseException) {
return Result.ok(aliGenieUtil.getDevice(namespace, name, messageId, payLoadVersion, new JSONArray()));
}
JSONArray devices = new JSONArray();
for (DeviceandCdevice deviceUserinfo : deviceUser) {
if (deviceUserinfo.getType() == 1) {
devices.add(
aliGenieUtil.getJSONDeviceInfo(
deviceUserinfo.getDid(),
deviceUserinfo.getDevicename(),
"switch",
"",
deviceUserinfo.getType().toString(),
deviceUserinfo.getDid(),
"https://iot.mcl-electronic.com/smartswitch.png",
deviceUserinfo.getStatus()));
} else {
List<Cdevice> cdevices = (List<Cdevice>) cdeviceService.sltCdeviceByDeviceid(deviceUserinfo.getId()).getData();
for (Cdevice cdevice : cdevices) {
devices.add(
aliGenieUtil.getJSONDeviceInfo(
cdevice.getId().toString(),
cdevice.getCdevicename(),
"switch",
"",
deviceUserinfo.getType().toString(),
deviceUserinfo.getDid(),
"https://iot.mcl-electronic.com/smartswitch.png",
cdevice.getStatus()));
}
}
}
return Result.ok(aliGenieUtil.getDevice(namespace, name, messageId, payLoadVersion, devices));
}
return Result.build(-1, aliGenieUtil.getErrorMessage(namespace, name, messageId, payLoadVersion, 5, deviceId).toJSONString());
} else if ("AliGenie.Iot.Device.Control".equals(namespace)) {
//裝置控制
if ("TurnOn".equals(name) || "on".equals(value)) {
//開啟
Cdevice cdeviceInfo = (Cdevice) cdeviceService.sltCdeviceById(deviceid).getData();
if (cdeviceInfo != null) {
if (taskController.createdTask(cdeviceInfo.getDevicedid(), cdeviceInfo.getOrderd(), 1).getStatus() == 1
&&
cdeviceService.updateCdeviceStatusByDevicedidAndOrderdAndStatus(cdeviceInfo.getDevicedid(), cdeviceInfo.getOrderd(), 1).getStatus() == 1) {
return Result.ok(aliGenieUtil.OnOffSwitch(namespace, name, messageId, payLoadVersion, deviceId));
} else {
return Result.build(-1, aliGenieUtil.getErrorMessage(namespace, name, messageId, payLoadVersion, 5, deviceId).toJSONString());
}
}
Device deviceInfo = (Device) cdeviceService.sltCdeviceByDeviceDid(deviceId).getData();
if (deviceInfo != null) {
if (taskController.createdTask(deviceInfo.getDid(), deviceInfo.getType(), 1).getStatus() == 1
&&
cdeviceService.updateCdeviceStatusByDeviceid(deviceid, 1).getStatus() == 1) {
return Result.ok(aliGenieUtil.OnOffSwitch(namespace, name, messageId, payLoadVersion, deviceId));
}
return Result.build(-1, aliGenieUtil.getErrorMessage(namespace, name, messageId, payLoadVersion, 5, deviceId).toJSONString());
}
return Result.build(-1, aliGenieUtil.getErrorMessage(namespace, name, messageId, payLoadVersion, 2, deviceId).toJSONString());
} else if ("TurnOff".equals(name) || "off".equals(value)) {
//關閉
Cdevice cdeviceInfo = (Cdevice) cdeviceService.sltCdeviceById(deviceid).getData();
if (cdeviceInfo != null) {
if (taskController.createdTask(cdeviceInfo.getDevicedid(), cdeviceInfo.getOrderd(), 0).getStatus() == 1
&&
cdeviceService.updateCdeviceStatusByDevicedidAndOrderdAndStatus(cdeviceInfo.getDevicedid(), cdeviceInfo.getOrderd(), 0).getStatus() == 1) {
return Result.ok(aliGenieUtil.OnOffSwitch(namespace, name, messageId, payLoadVersion, deviceId));
} else {
return Result.build(-1, aliGenieUtil.getErrorMessage(namespace, name, messageId, payLoadVersion, 5, deviceId).toJSONString());
}
}
cdeviceInfo = (Cdevice) cdeviceService.sltCdeviceByDeviceDid(deviceId).getData();
if (cdeviceInfo != null) {
if (taskController.createdTask(cdeviceInfo.getDevicedid(), cdeviceInfo.getOrderd(), 0).getStatus() == 1
&&
cdeviceService.updateCdeviceStatusByDeviceid(deviceid, 0).getStatus() == 1) {
return Result.ok(aliGenieUtil.OnOffSwitch(namespace, name, messageId, payLoadVersion, deviceId));
}
return Result.build(-1, aliGenieUtil.getErrorMessage(namespace, name, messageId, payLoadVersion, 5, deviceId).toJSONString());
}
return Result.build(-1, aliGenieUtil.getErrorMessage(namespace, name, messageId, payLoadVersion, 2, deviceId).toJSONString());
}
return Result.build(-1, aliGenieUtil.getErrorMessage(namespace, name, messageId, payLoadVersion, 3, deviceId).toJSONString());
} else if ("AliGenie.Iot.Device.Query".equals(namespace)) {
//裝置屬性查詢
if ("Query".equals(name) || "QueryPowerState".equals(name)) {
//查詢開關狀態
Cdevice cdeviceInfo = (Cdevice) cdeviceService.sltCdeviceById(deviceid).getData();
if (cdeviceInfo != null) {
return Result.ok(aliGenieUtil.getDeviceState(namespace, name, messageId, payLoadVersion, deviceId, cdeviceInfo.getStatus()));
}
cdeviceInfo = (Cdevice) cdeviceService.sltCdeviceByDeviceDid(deviceId).getData();
if (cdeviceInfo != null) {
return Result.ok(aliGenieUtil.getDeviceState(namespace, name, messageId, payLoadVersion, deviceId, cdeviceInfo.getStatus()));
}
return Result.build(-1, aliGenieUtil.getErrorMessage(namespace, name, messageId, payLoadVersion, 2, deviceId).toJSONString());
}
return Result.build(-1, aliGenieUtil.getErrorMessage(namespace, name, messageId, payLoadVersion, 4, deviceId).toJSONString());
}
return Result.build(-1, aliGenieUtil.getErrorMessage(namespace, name, messageId, payLoadVersion, 1, deviceId).toJSONString());
}
return Result.build(-1, aliGenieUtil.getErrorMessage(namespace, name, messageId, payLoadVersion, 7, deviceId).toJSONString());
}
public static String getStringFrom() {
return DigestUtils.md5DigestAsHex((UUID.randomUUID().toString() + System.currentTimeMillis()).getBytes());
}
}