天猫精灵云云接入——前端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
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);
function post_curls($url, $post)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($curl);
if (curl_errno($curl)) {
echo 'Errno'.curl_error($curl);
}
curl_close($curl);
return $res;
}
?>
- 获取返回值,并将其返回
注:我这边返回值放在了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());
}
}