天猫精灵云云接入——前端VUE、服务器PHP、后端java

  • 第一次写博客,如果有什么问题或者疑问可以私信或者评论,谢谢。

AliGenie

  1. 接入流程:https://www.aligenie.com/doc/357554/sisusm
  2. 创建 https://iap.aligenie.com/console/skill/list 的内容与iot的技能
    文档: https://www.aligenie.com/doc/357554/hf8wog
  3. 请求方式:Oauth2授权-https://www.aligenie.com/doc/357554/chhley
  4. 云云接入协议: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

  1. 获取post里面的参数
$code = $_POST['code'];
$type = $_POST['grant_type'];
$token = $_POST['refresh_token'];
  1. 为post请求携带上请求参数
$code = $_POST['code'];
$type = $_POST['grant_type'];
$token = $_POST['refresh_token'];
  1. 发送请求并获取返回的值
  • 发请求
$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);

获取用户设备

  1. 获取到请求需要的参数
$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'];

  1. 给请求头赋值
header('namespace:'.$namespace);
header('name:'.$name);
header('messageId:'.$messageId);
header('payLoadVersion:'.$payLoadVersion);
  1. 发送请求并获取返回的值
  • 发送请求
$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());
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 14
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值