当前位置: 首页 > 后端技术 > Java

安卓设备接入阿里云物联网平台——设备连接

时间:2023-04-01 16:08:03 Java

一、准备工作1.1注册阿里云账号使用个人淘宝账号或手机号开通阿里云账号,并通过__实名认证(可使用支付宝认证)__1.2打开物联网IoT套件官网免费产品https://www.aliyun.com/product/iot1.3软件环境JDK安装编辑器IDEA2。开发步骤2.1云端开发1)创建产品高级版本2)功能定义,为产品对象模型添加属性添加产品属性,定义对象模型对应属性报告topic/sys/replacedbyproductKey/replacedbydeviceName/thing/event/property/postthingmodel对应的property上报payload{id:123452452,params:{temperature:26.2,humidity:60.4},method:"thing.event.property.post"}3)DeviceManagement>RegisterDevice,获取identitytriplet2.2设备端开发我们使用java程序模拟设备,建立连接,上报数据。1)build.gradle添加sdk依赖{implementation'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.0'}2)AliyunIoTSignUtil工具类importjavax.crypto.Mac;importjavax.crypto.SecretKey;importjavax.crypto.spec.SecretKeySpec;importjava.util.Arrays;importjava.util.Map;/***AliyunIoTSignUtil*/publicclassAliyunIoTSignUtil{publicstaticStringsign(Mapparams,StringdeviceSecret,StringsignMethod){//按照字典顺序对参数Keys进行排序String[]sortedKeys=params.keySet().toArray(newString[]{});Arrays.sort(sortedKeys);//生成规范化请求字符串StringBuildercanonicalizedQueryString=newStringBuilder();for(Stringkey:sortedKeys){if("sign".equalsIgnoreCase(key)){继续;}canonicalizedQueryString.append(key).append(params.get(key));}try{Stringkey=deviceSecret;returnencryptHMAC(signMethod,canonicalizedQueryString.toString(),key);}catch(Exceptione){thrownewRuntimeException(e);}}/***HMACSHA1加密**/publicstaticStringencryptHMAC(StringsignMethod,Stringcontent,Stringkey)throwsException{SecretKeysecretKey=newSecretKeySpec(key.getBytes("utf-8"),signMethod);Macmac=Mac.getInstance(secretKey.getAlgorithm());mac.init(密钥);byte[]data=mac.doFinal(内容.getBytes("utf-8"));返回bytesToHexString(数据);}publicstaticfinalStringbytesToHexString(byte[]bArray){StringBuffersb=newStringBuffer(bArray.length);字符串sTemp;对于(inti=0;i{newThread(()->initAliyunIoTClient()).start();});findViewById(R.id.post_button).setOnClickListener((l)->{mHandler.postDelayed(()->postDeviceProperties(),1000);});findViewById(R.id.quit_button).setOnClickListener((l)->{try{mqttClient.disconnect();}catch(MqttExceptione){e.printStackTrace();}});}/***使用productKey,deviceName,deviceSecret三元组构建IoTMQTT连接*/privatevoidinitAliyunIoTClient(){try{StringclientId="androidthings"+System.currentTimeMillis();Mapparams=newHashMap(16);params.put("productKey",productKey);params.put("设备名称",设备名称);参数.put("clientId",clientId);字符串时间戳=String.valueOf(System.currentTimeMillis());params.put("时间戳",时间戳);//cn-shanghaiStringtargetServer="tcp://"+productKey+".iot-as-mqtt.cn-shanghai.aliyuncs.com:1883";StringmqttclientId=clientId+"|securemode=3,signmethod=hmacsha1,timestamp="+timestamp+"|";StringmqttUsername=deviceName+"&"+productKey;StringmqttPassword=AliyunIoTSignUtil.sign(params,deviceSecret,"hmacsha1");connectMqtt(targetServer,mqttclientId,mqttUsername,mqttPassword);}catch(Exceptione){e.printStackTrace();responseBody=e.getMessage();mHandler.sendEmptyMessage(POST_DEVICE_PROPERTIES_ERROR);}}publicvoidconnectMqtt(Stringurl,StringclientId,StringmqttUsername,StringmqttPassword)throwsException{MemoryPersistence持久性=newMemoryPersistence();mqttClient=newMqttClient(url,clientId,persistence);MqttConnectOptionsconnOpts=newMqttConnectOptions();//MQTT3.1.1connOpts.setMqttVersion(4);connOpts.setAutomaticReconnect(true);connOpts.setCleanSession(true);connOpts.setUserName(mqttUsername);connOpts.setPassword(mqttPassword.toCharArray());connOpts.setKeepAliveInterval(60);mqttClient.connect(connOpts);Log.d(TAG,"connected"+url);}/***post数据*/privatevoidpostDeviceProperties(){try{Randomrandom=newRandom();//上报数据Stringpayload=String.format(payloadJson,String.valueOf(System.currentTimeMillis()),10+random.nextInt(20),50+random.nextInt(50));响应体=有效载荷;Mqtt消息emessage=newMqttMessage(payload.getBytes("utf-8"));message.setQos(1);StringpubTopic="/sys/"+productKey+"/"+deviceName+"/thing/event/property/post";mqttClient.publish(pubTopic,消息);Log.d(TAG,"publishtopic="+pubTopic+",payload="+payload);mHandler.sendEmptyMessage(POST_DEVICE_PROPERTIES_SUCCESS);mHandler.postDelayed(()->postDeviceProperties(),5*1000);}catch(Exceptione){e.printStackTrace();responseBody=e.getMessage();mHandler.sendEmptyMessage(POST_DEVICE_PROPERTIES_ERROR);Log.e(TAG,"postDevicePropertieserror"+e.getMessage(),e);}}privatevoidshowToast(Stringmsg){msgTextView.setText(msg+"\n"+responseBody);}}3.启动运行3.1设备启动3.2云端查看设备运行状态物联网平台产品介绍详情:https://www.aliyun.com/product/iot/iot_instc_public_cn阿里云物联网平台客户交流群