2022IoT物聯(lián)網(wǎng)MOTT協(xié)議、設(shè)備上云、消息發(fā)與接收實戰(zhàn)接入技術(shù)_第1頁
2022IoT物聯(lián)網(wǎng)MOTT協(xié)議、設(shè)備上云、消息發(fā)與接收實戰(zhàn)接入技術(shù)_第2頁
2022IoT物聯(lián)網(wǎng)MOTT協(xié)議、設(shè)備上云、消息發(fā)與接收實戰(zhàn)接入技術(shù)_第3頁
2022IoT物聯(lián)網(wǎng)MOTT協(xié)議、設(shè)備上云、消息發(fā)與接收實戰(zhàn)接入技術(shù)_第4頁
2022IoT物聯(lián)網(wǎng)MOTT協(xié)議、設(shè)備上云、消息發(fā)與接收實戰(zhàn)接入技術(shù)_第5頁
已閱讀5頁,還剩152頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)

文檔簡介

MQTT協(xié)議與IoT物聯(lián)網(wǎng)平 CoAP協(xié)議詳 電信NB-IoT無縫對接阿里云 微信小程序MQTT模擬 IoT存量設(shè)備零改造遷移上 基于函數(shù)計算實現(xiàn)IoT設(shè)備動態(tài)注 Nodejs版mqtt接入阿里云 C#設(shè)備接入IoT物聯(lián)網(wǎng)平 IoT設(shè)備用HTTPS協(xié)議接入物聯(lián)網(wǎng)平 設(shè)備用X.509證書接入實戰(zhàn)(一 設(shè)備用X.509證書接入實戰(zhàn)(二 深度解讀IoT消息洪峰怎么 億級IoT設(shè)備連接底層邏 IoT平臺廣播消息Broadcast實 自定義Topic同步調(diào)用RRPC實戰(zhàn)(二 系統(tǒng)Topic實現(xiàn)云端同步調(diào)用RRPC(一 MQTT協(xié)議與MQTT協(xié)議與IoTMQTT協(xié)議與IoT一、MQTT協(xié)議介MQTTMQTT(消息隊列遙測傳輸)是基于TCP/IP協(xié)議棧而構(gòu)建的支持在各方之間異步通信的消息協(xié)議。MQTT在空間和時間上將消息發(fā)送者與接收者分離,因此可以在不可靠MQTTIoT這個輕量級協(xié)議可在嚴(yán)重受限的設(shè)備硬件和高延遲/IoTMQTTClientMQTTClient庫在很多語言中都有實現(xiàn),包括EmbeddedC、C、Java、JavaScript、Python、C++、C#、Go、i、AndroidEclipsePahoMQTT庫下載地址:MQTTFixed控制報文類型控制報文類型標(biāo)志位剩余長度Variable內(nèi)容根據(jù)報文類型的不同而不同??勺儓箢^的報文標(biāo)識符(PacketIdentifier)字段存在MQTTPUBLISH來說有效< 其中td,me,wo由設(shè)備三元組dcKydcmttp//helaliyncom/ocmnt_etil/7372html設(shè)備端代碼示例(Nodes版)client.js"dependencies":"dependencies":{"mqtt":"2.18.8"constmqtt=require('mqtt');//設(shè)備身份三元組+區(qū)域constdeviceConfig={productKey:"替換",deveNam:"替換",deviceSecret:"替換",regionId:"cn-shanghai"http://根據(jù)三元組生成mqttconstoptions=consturl=`tcp://${deviceCductKey}.iot-as-qt.$deiCoi.rioId.lynconstclient=mqtt.connect(url,client.on('packetsend',function(packet){console.log('send+pckecmd'packet=>',packet)client.on('packetreceive',function(packet){console.log('receive+ackecm+'packet=>',packet)functionnqOpndevcenfg){constparams={productKey:deviceCductKey,devceame:devcenfg.evceame,meamp:Date.now(),clientId://CONNECT參數(shù)//CONNECT參數(shù)keepalive:60,protocolVersion:4//MQTTv3.1.1//1.生成options.password=gnmacha1paa,deviceConfig.deviceSecret);options.clientId={param.lientIdecureoesignmethdhmaha1timetoon.uenae=return參考文檔:hp:hepaun.cmdoumenda742.hm?#h2url-functiongnmacha1paa,deviceSecret){letkeys=//按字典序排序keyskeys.sort();constlist=[];keys.map((key)=>{constcontentStr=returncp.ceemacha1,receivereceiveconnackpacket=>Packet{cmd:'connack',qos:0,length:2,payload:null,sessionPresent:payload:null,sessionPresent:false,returnCode:0}sendsendpingreqpacket=>{cmd:'pingreq'receivepingresppacketreceivepingresppacket=>Packet{cmd:'pingresp',qos:0,dup:false,length:0,topic:null,//3//3consttopic=`/sys/${deviceCductKey}/${deviceConfig.deviceNasetInterval(function()},},5*functiongetPostData(){constpayloadJson={id:Date.now(),params:{temperature:ah.ooahandm)*20)+humidity:ah.foah.ndo)*20)+method:console.log("===postData\ntopic="+topic)returnsendpublishpacket=>{cmd:topic:payload:d:148648116paam:empeau:2humd:}"meho:hngqos:1,messageId:38850,dup:false}receivereceivepubackpacket=>Packet{cmd:'puback',qos:0,dup:false,length:2,topic:null,messageId:38850//4//4constsubTopic=`/${deviceCductKey}/${deviceConfig.devcen.nmeage,function(topic,message){console.log("topic"+topic)cooe.omeage"+message)SUBSCRIBEsendsubscribepacket=>{cmd:'subscribe',[{topic:a1hFedeud1fgAP2eIdcono,qos:0}],qos:1,dup:false,messageId:38851SUBACKreceivesubackpacket=>Packet{cmd:'suback',receivesubackpacket=>Packet{cmd:'suback',qos:0,dup:false,length:3,topic:null,granted:[128],messageId:38851}sendunsubscribepacket=>{cmd:'unsubscribe',qos:1,sendunsubscribepacket=>{cmd:'unsubscribe',qos:1,messageId:unsubscriptions:[a1hFedeud1fgA2eIdcono']receivereceiveunsubackpacket=>Packet{cmd:'unsuback',qos:0,dup:false,length:2,topic:null,messageId:34323IoTunsubscribe,否則訂閱關(guān)TLSIoTTLSv1.2TLS加密,需要下載根證書。CONNECTclientIdsecuremode=2poom_m >CoAPCoAPCoAP協(xié)議詳解 CoAP|IoTCAP(CnstraindAplicatinrotocl)的縮寫。在T物聯(lián)網(wǎng)場景,為了讓小設(shè)備可以接入互聯(lián)網(wǎng),CoAP協(xié)議被設(shè)計出來。CoAP是一種應(yīng)用層協(xié)議,它運行于UDP協(xié)議之上而不是像HTTP那樣運行于TCP之上。CoAP協(xié)議非常4字節(jié)。CAPHTPESTHTPCAP既考CAP提供RIEST式的方法如GTOTUT和ELTE另一方面,CAP基于輕量級的DP協(xié)議,并且允許P多播。為了彌補UDP傳輸?shù)牟豢煽啃?,CoAP定義了帶有重傳機制的事務(wù)處理機制。并且提供資源發(fā)現(xiàn)機制,并帶有資請求/CoAPUDPCoAP報文:【Ver【T】報文類型,CoAP協(xié)議定了4種不同形式的報文,CON報文,NON報文,ACKRST報文?!綯KL】CoAP標(biāo)識符長度。CoAP協(xié)議中具有兩種功能相似的標(biāo)識符,一種【Code】功能碼/響應(yīng)碼。Code在CoAP請求報文和響應(yīng)報文中具有不同的表現(xiàn)形式,Code35c.dd0.XXCoAP2.XX、4.XX5.XXCoAP響應(yīng)的某種具體表現(xiàn)。【MessageID【Token】標(biāo)識符具體內(nèi)容,通過TKL指定Token長度?!緄nCoAP主機,CoAPURI,CoAP請求【11111111B】CoAP報文和具體負(fù)載之間的分隔符。0.01GET0.02POST:0.03PUT:0.04DELETE:刪除資源Success2.012.022.032.042.05ContentClientError4.xx:4.00Bad4.014.02Bad4.034.05MethodNot4.06Not4.12Precondition4.13RequestEntityToo4.15UnsupportedContent-FormatServerError5.xx:5.00InternalServer5.01Not5.03ServiceUnavailableCoAPHTTP的設(shè)計思路,同時也根據(jù)受限資源限制設(shè)備的具體情況改良CON:需要被確認(rèn)的請求,如果CONNON:不需要被確認(rèn)的請求,如果NONACK:應(yīng)答消息,接受到CONRST:復(fù)位消息,當(dāng)接收者接收到的消息包含一個錯誤,接收者解析消息或者不再關(guān)CoAPHTTPRESTFulWEB應(yīng)用中越來越受歡迎,這樣的道理同樣適用于CoAP。一個CoAP資源可以被一個URI所描述,例如一個設(shè)備可以測量溫度,那么這個溫度傳感器的URI被描述為CAPmchin.adCoAPUDP5683HTTPCoAP對比:HTTP代表超文本傳輸協(xié)議,CoAPHTTP協(xié)議的傳輸層采用了TCP,CoAP協(xié)議的傳輸層使用CoAPHTTPCoAPHTTPCoAPCoAPIoT/WSN/M2MCoAPMQTTMQTT協(xié)議使用發(fā)布/訂閱模型,CoAP協(xié)議使用請求/MQTT是長連接,CoAPMQTT通過中間代理傳遞消息的多對多協(xié)議,CoAPServerClientMQTTClients,CoAP內(nèi)置內(nèi)容協(xié)商IoTIoT >CoAPIoTLinuxAndroidArduino在操作系統(tǒng)層面,解決了不同通信模塊的差異,硬件端的應(yīng)用程序只需要集成云平臺的IoTSDK,或者MQTTSDK即可和云端建立長連接通信鏈路。ROTS系統(tǒng),甚至無操作系統(tǒng),采MCU+通信模組的方式,實現(xiàn)設(shè)備數(shù)據(jù)遠(yuǎn)程采集。(B-oT/2G/3G/4G)移遠(yuǎn)通信芯訊通合宙有方科技、廣和通、日海智能、高新興等,而各家的ATigBee設(shè)備,LoRa設(shè)備,Modbus設(shè)備,而不具有互聯(lián)網(wǎng)接入?yún)f(xié)議棧支持,此時需要借助DTU/網(wǎng)關(guān)設(shè)備QTT面對這種場景,可以通過自有系統(tǒng)集成泛化SDK通過HTTP/2協(xié)議,在不改造設(shè)備 >電信NB-IoT電信NB-IoT電信NB-IoTIoT< 電信NB-IoT無縫對接阿里云NB-IoTCW,無法直接在阿里云IoT,AWSIoTIoTNB-IoTIoTNB-IoTCig登陸電信Win控制臺,創(chuàng)建產(chǎn)品:上?;ǔ撬?,選擇智能水表,其他配置信產(chǎn)品創(chuàng)建成功后,查看服務(wù)定義用水量water_cnsumpo如下圖:在產(chǎn)品詳情-設(shè)備管理頁面添加NB-IoT設(shè)備,這里我們輸入NB-IoT水表設(shè)備的在應(yīng)用管理頁面添加應(yīng)用:上海花城水表管理,獲取到應(yīng)用的AppKey和CWing物聯(lián)網(wǎng)平臺,我們按需開通連接型在產(chǎn)品功能定義中添加物模型的屬性:用水量,標(biāo)識為watecnsumpo在產(chǎn)品數(shù)據(jù)解析Tn平臺的數(shù)據(jù)格式轉(zhuǎn)換IoT云網(wǎng)關(guān),用來解析電信平臺流轉(zhuǎn)過來的設(shè)備數(shù)據(jù),關(guān)聯(lián)前面創(chuàng)建的產(chǎn)品上?;ǔ撬鞢Wing${deviceId}來自動注冊設(shè)備,如下圖:URL,IoTTn控制臺,在產(chǎn)品詳情的訂閱管理IoT我們啟動手上的NB-IoTTn控制臺看到水表上報的數(shù)據(jù),IoT在日志服務(wù)也可以看到電信Tn平臺流轉(zhuǎn)過來的NB-IoT設(shè)備數(shù)據(jù)在阿里云IoTNB-IoT設(shè)備從電信CWig平臺流轉(zhuǎn)過來的完整數(shù)據(jù)報文至此,我們完成了NB-IoTIoT,充分享受阿里云的海量存IoT >LoRaWAN LoRaWAN隨著IoT物聯(lián)網(wǎng)的高速發(fā)展,低功耗,遠(yuǎn)距離,抗干擾的低功耗廣域網(wǎng)快速崛起,LoRaNB-IoTLoRaWANIoTLnW服務(wù)后,即可實現(xiàn)LoRaWAN設(shè)備的上云。LoRaWAN液位傳感器為例,完整方案如下:開通企業(yè)實例-LinN首先,我們按需開通基礎(chǔ)型企業(yè)物聯(lián)網(wǎng)實例,開啟inkWAN服務(wù),如下圖:添加LinAN在LinkWAN的網(wǎng)關(guān)管理頁面,添加網(wǎng)關(guān),錄入手中LinkWAN網(wǎng)關(guān)設(shè)備的GwEUI、PINCode和頻段、通信模式在LinkWAN的入網(wǎng)憑證在設(shè)備管理LoRa液位傳感器LoRaWAN連網(wǎng)模式,并LoRa入網(wǎng)憑證,如下圖:inkWAN的入網(wǎng)憑證LoRa產(chǎn)品和入網(wǎng)憑證在設(shè)備管理的設(shè)備頁面,添加LoRa液位傳感器具體設(shè)備,錄入手上LoRa設(shè)備的DevEUI,JoinEuiAppKey信息,如下圖:啟動LinkWAN網(wǎng)關(guān)oaRa當(dāng)前液位值 >MQTT一、IoTMQTT模擬器IoTTopicregion③基于當(dāng)前產(chǎn)品,注冊設(shè)備,并獲取身份三元組三、MQTTTopicTopicTopic①點擊屬性上報,輸入JSON結(jié)構(gòu)的屬性值。②物聯(lián)網(wǎng)平臺控制臺,設(shè)備詳情>物模型數(shù)據(jù)>運行狀態(tài)IdJSON四、設(shè)備三元組ChromeIoTChrome插件。點擊閱讀原文獲取插件安裝包。Chrome加載已解壓的擴展程序按鈕,選中本地擴展程序文件夾,然后點擊選擇①進入物聯(lián)網(wǎng)平臺控制臺,進入設(shè)備詳情,點擊查看DeviceSecret >IoTIoTIoT IoT|物聯(lián)網(wǎng)場景中,設(shè)備產(chǎn)線燒錄不同三元組成本很高,Android設(shè)備更是無法獨立燒錄我們進入IoT物聯(lián)網(wǎng)平臺控制臺,創(chuàng)建一個新產(chǎn)品:Android進入產(chǎn)品詳情,獲取productKey和productSecret。開啟動態(tài)注冊Node.js代碼演示設(shè)備動態(tài)注冊完整過程。CONNECTMQTT${productKey}.iot-as-mqtt.${regionId}.m8MQTTCONNECTmqttClientId:mqttClientId:cenIdecuemoe2auhpeegnandomxsgnmeho"mqttUserName:devceame&+poucKeymqttPassword:Topic:/ext/regnwl,返回IoTPayload"productKey":devceNme":"deviceToken":"xxx"functionfunctiondoDeviceRegister()constproductInfo=productKey:"產(chǎn)品productKey",productSecret:"產(chǎn)品productSecret",regionId:"cn-shanghai"productKey:"產(chǎn)品productKey",productSecret:"產(chǎn)品productSecret",regionId:"cn-shanghai"http://2.程序讀取的設(shè)備唯一標(biāo)識,比如A,ealNumber等poucInf.evceame=ahandm).ng6).ub2)varoptions=getRegisterOptions(productInfo,4clientIddeviceTokenvarregisterClient=mqconncoon);egeen.onmage,function(topic,message)if('/ext/regnwl'==topic)//6.斷開注冊連接7MQTTdevceOnneJO.pemeage)cn-poom_functiongetRegisterOptions(productInfo,rootCA){functiongetRegisterOptions(productInfo,rootCA){varrandom=Date.now();varcontent=devceame:productInfo.deviceName,productKey:productIductKey,random:randomvaroptions=options.clientId=Date.now()+"seueode=,atTyp=rgwl,ado=++opn.uename=poucInf.evceame+"&"+productIductKeyoptions.password=gnmacha1cnen,productIductSecret)options.port=1883;options.host=`${productIductKey}.iot-as-mqtt.${productInfo.regionId}.aliyuncs.coptions.host=`${productIductKey}.iot-as-mqtt.${productInfo.regionId}.aliyuncs.coptions.ca=rootCAoptions.keepalive=120returnoptions;ClientIDDeviceTokenMQTT連接,IoTCONNECT參數(shù)如下:mqttClientId:mqttClientId:cenIdecuemoe-2,authType=connwl"mqttUsername:deceNae+&+pduKeymqttPassword:deviceTokenmttClietIdClientIDmqttUserName:組成結(jié)構(gòu)為momqttPassword:設(shè)備動態(tài)注冊時獲得的設(shè)備建立MQTTfunctionfunctiondevcenneoegonId)MQTT連接參數(shù)varoptions={}options.clientId=opts.clientId+"securemode=-2,authType=connwl"opn.uename=op.evceame+"&"+ductKeyoptions.password=opts.deviceTokenoptions.port=options.host=`${ductKey}.iot-as-mqegonId}aunc.cm`tocol='mqtt'options.keepalive=vardeviceClient=//上報業(yè)務(wù)數(shù)據(jù)diele.pbls(/${dte}/{opt.diee/srupdt`"sdkclient"+Date.now(),{qos:1 >IoTIoT存量設(shè)備零改造遷移上云< IoT存量設(shè)備零改造遷移上云< IoT存量設(shè)備零改造遷移上云在物聯(lián)網(wǎng)實際項目中,有些設(shè)備采用私有協(xié)議接入了本地設(shè)備管理系統(tǒng),有些NB-IoT設(shè)備被迫接入了電信AEP平臺,有些設(shè)備接入了移動OneNET平臺。但甲方客戶IoTSDK接入的方案IoT設(shè)備零改造的前提下,幫助企業(yè)快速構(gòu)建云上橋接服務(wù),通過網(wǎng)橋?qū)崿F(xiàn)IoT終端設(shè)備與阿里云IoT物聯(lián)網(wǎng)SDK泛化協(xié)議SDKSDKServerSDK,SDK泛化協(xié)議僅支持Java開發(fā)語言,添加泛化協(xié)議SDK的項目Maven<artifactId>iot-as-bridge-sdk-您需要創(chuàng)建一個BridgeBootstrap對象實例,并調(diào)用bootstrap方法。泛化協(xié)議SDK初始化工作完成后,讀取網(wǎng)橋信息,并向云端發(fā)起網(wǎng)橋設(shè)備上線請求等。nnelHandlerBridgeBootstrapBridgeBootstrapbridgeBootstrap=newBridgeBootstrap();bridgeBootstrap.bootstrap(newDownlinkChannelHandler(){publicbooleanpushToDevice(Sessionsession,Stringtopic,byte[]payload)Stringcontent=newreturntrue;publicbooleanbroadcast(Stringtopic,byte[]payload){returnfalse;Java(src/mai/reurce/application.conf##Serverhttp2Endpointhttps://你的ProductK-hangha.aunccom44"productKey=${bridge-ProductKey}devceame=${bridge-evceame}deviceSecret=${bridge-DeviceSecret}Java工程的默認(rèn)資源文件路徑(一般是/an/esues/)下的devices.conf中讀${device-original-Identity}${device-original-Identity}{productKey:${device-ProductKey}deveName:${device-Devceame}deviceSecret:${device-DeviceSceret}設(shè)備上線時,需要傳Session。下行消息回調(diào)時,會把Session回調(diào)給網(wǎng)橋。SessionUplinkChannelHandlerUplinkChannelHandleruplinkHandler=newObjectchannel=newSessionsession=Session.newInstance(originalIdentity,booleanbooleansuccess=upnandedonneeon,originalIdentity);if(success){網(wǎng)橋使用泛化協(xié)議SDKDeviceIdentitydeviceIdentity=oaoy.Dcoiar.evIdiypoocoeage.etopctng.fomaOPI_MLATUSR_DFIN,deviceIdentitygetProductKey(),deviceIdentity.getDeviceName()));//uplinkChannelHandler.doPublishAsync(originalIdentity,PubAPIprivatestaticExecutorServiceexecutorServiceprivatestaticExecutorServiceexecutorService=newThreadPoolExecutor(RunmegeRune).avabeoceo)*2,60,newnewThreadFactoryBuilder().setDaemon(true).setNameFormat("bridge-downlink--newpublicstaticvoidmanngargs[])//Useapplication.conf&devices.confbydefaultbridgeBootstrap=newBridgeBootstrap();bridgeBootstrap.bootstrap(newDownlinkChannelHandler(){publicbooleanpushToDevice(Sessionsession,Stringtopic,byte[]payload)//getmessagefrom//getdownlinkmessagefromexecutorService.submit(()->handeonLnkeageeon,topic,payload));returntrue;publicbooleanbroadcast(Strings,byte[]bytes){returnfalse;privatestaticvoidhandeonLnkeageeonsession,Stringtopic,byte[]payload){Stringcontent=newString(payload);Objectchannel=session.getChannel();StringoriginalIdentity=//foreampleyoucansendthemessagetodeviceviachannel,itdependsonyouspecifcservermpemeaon 基于函數(shù)計算實現(xiàn)IoT基于函數(shù)計算實現(xiàn)IoT >基于函數(shù)計算實現(xiàn)IoTIoTdeviceIdHTTPSFC函數(shù)計算FC調(diào)用IoT平臺的RegisterDevice接口,傳遞productKey和IoTQueyDeceDetaproductKeydeviceId,獲MQTTIoTAPIRegisterDevicettp//helaliyncom/ocmnt_etil/9470htmlQuerDeveDetatts//helaliyncm/cumentdtail/959.tmlHTTPSNodejs版本實現(xiàn):constconstgetRawBody=equea-body');constco=require('co');constRPCClient=eqe@acoupo-constoptions=accessKey:"云賬號的AK",accessKeySecret:"云賬號的AKSecret"http://1.創(chuàng)建iotpopserverconstiotClient=newRPCClient({secretAccessKey:apiVersion:options.apiVersion'2018-01-20'}constproductKey='pduKe;moue.ep.haner=function(req,resp,context){getRawBody(req,function(err,body)body=constdeviceId=body.deviceId;co(function*(){constdeviceId=body.deviceId;co(function*(){tryconstregisterResponse=yieldiotClient.request(RegeDevce,{devceame:deviceIdsuccess:true,data:}catch(err)constqueryResponse=yieldiotClient.request(ueDevceDe,{deveNam:deviceIdconstreturnJson={success:true}returnJson.data={Devceame:quRepone.aa.evceNme,ProductKey:queryResponse.Data.ProductKey,DeviceSecret:queryResponse.Data.DeviceSecret,IotId:queryResponse.Data.IotIdHTTPSPOSTJSONNodejsNodejsmqtt接入阿里云IoT >NodejsmqttNodejsmqttIoTpwwodNodejsIoTnodejs2package.jsonpackage.jsonIoTsdk"name":"aliyun-iot-demo","dependencies":{"mqtt":npmIoT$$npm"dependencies":{"mqtt":"2.18.8"constmqtt=require('mqtt');constdeviceConfig{productKey:"替換產(chǎn)品",deveNam:"替換設(shè)備",regionId:"cn-shanghai"constparams=productKey:deviceCductKey,deveNam:deveonfgdeveNam,meam:Date.now(),clientId://CONNECTconstoptionskeepalive:60,clean:falsecleanSessionprotocolVersion:4//MQTTv3.1.1//1.生成options.password=gnmacha1aam,options.clientId={aa.lintdeurmeinetohah1tmtapopn.uename=consturl=`tcp://${deviceCductKey}.iot-as-mqtt.${deviceConfig.regionId}.aliyuconsturl=`tcp://${deviceCductKey}.iot-as-mqtt.${deviceConfig.regionId}.aliyuconstclient=consttopic=sy/$dvCoi.podty${diof.dva/i/e/psetInterval(function()//發(fā)布數(shù)據(jù)到topic},5*constpayloadJson={id:Date.now(),params:{temperature:ah.ooahandm)*20)+humidity:ah.foah.ndo)*20)+method:console.log("===postData\ntopic="+topic)return參考文檔:hp:hepaun.cmdoumenda742.hm?#h2url-*/functiongnmacha1pam,deviceSecret)letkeys=keys=keys.sort();constlist=[];keys.map((key)=>keys=keys.sort();constlist=[];keys.map((key)=>{constcontentStr=returncp.ceemacha1,IoTC#設(shè)備接入C#設(shè)備接入IoT >C#設(shè)備接入IoTC#設(shè)備接入IoT物聯(lián)網(wǎng)平臺IoT產(chǎn)品官網(wǎng):wm獲取設(shè)備身份三元組eIoT平臺接入password簽名規(guī)則參考:ttsw.yuu.cm/clu-dev/iot-接入IoTC#MQTTCmqttVisualStudioC#語言開發(fā)的傳感器設(shè)備接入阿里云IoTIoTIoTHTTPS協(xié)議接入物聯(lián)網(wǎng)平臺< >IoTHTTPSIoT設(shè)備用HTTPSIoTHTTPS協(xié)議棧,那么我們能否接入IoT物聯(lián)網(wǎng)平臺呢?答案是肯定的。本文就通過開發(fā)實戰(zhàn)給大家講解如何使用HTTPSIoT2(上海)區(qū)域。HTTPS接入的官網(wǎng)文檔ttphelaliyncom/ocmnt_etil/83.tmlHTTPS接入主要有兩個步驟:HTTPS設(shè)備身份認(rèn)證服務(wù)器接入點:-POSTPOST/authHost:-hanga.aunc.omContent-Type:application/jsonbody:"version":"default",gnmehod:"hmacsha1","sign":"productKey":"ZG1EvTEa7NN",devceNme:Naspuh8FB,"timestamp":"1501668289957""code0,//業(yè)務(wù)狀態(tài)碼"messagesuccess",//業(yè)務(wù)信息"info"token":IoT-POSTPOST/topic/a1GFjLP3xxC/device123/pubHost:-hanga.aunc.omContent-Type:application/octet-streambody:${your_data}"code0,//業(yè)務(wù)狀態(tài)碼"messagesuccess",//業(yè)務(wù)信息"info"messageId":三、使用HTTPS上報數(shù)據(jù)實戰(zhàn)設(shè)備詳情varvarrp=require('request-pme);constcrypto=require('crypto');constdeviceConfig{productKey"productKey",devceame:"devceame,deviceSecret:"替換consttopic=sy/$dty/{diCoi.dia/hgetpro//1.獲取身份token.then(function(parsedBody)console.log('AuthInfo//2pubData(topic,parsedB.token,.catch(function(err)console.log('AutherrfunctiongeAuhpondvceong)constparams=productKey:deviceCductKey,deveNam:devcenfg.evceame,meam:Date.now(),clientId://生成varpassword=gnmacha1paa,varoptions={method:O,uri:'-hanga.aunc.omauh,body:{"version":"default","clientId":paamcenId,gnmehod:"hmacsha1","sign":password,"productKey":deviceCductKey,devceNme:devcenfg.evceame,"timestamp":paammeampjson:functionpubData(topic,token,data)constoptions={method:uri:'-hanga.aunc.omoc'+topic,body:data,headers:password:password:onenType':'application/octet-.then(function(parsedBody){console.log('publishsuccess:'+parsedBody).catch(function(err)console.log('publisherr'+functiongetPostDatavarpayloadJson={id:Date.now(),params:{humidity:ah.ooahandm)*20)+temperature:ah.foah.ndo)*20)+method:console.log("===postData\ntopic="+topic)//HmacSha1functiongnmacha1pam,deviceSecret)letkeys=//按字典序排序constlist=[];keys.map((key)=>{constcontentStr=returncp.ceemacha1, >網(wǎng)關(guān)與子設(shè)備上云開發(fā)實戰(zhàn)<網(wǎng)關(guān)與子設(shè)備上云開發(fā)實戰(zhàn)< IoT無連接互聯(lián)網(wǎng)能力時,那么數(shù)據(jù)如何上IoTMQTT長連接通道,所有子設(shè)備可以復(fù)用網(wǎng)關(guān)的MQTT通道,高效傳輸數(shù)據(jù)到云端。IoTIoTMQTT連接,收發(fā)數(shù)據(jù),還要負(fù)責(zé)子設(shè)備管理,包括:mqtthttp、mqtt、ZigBee、Modbus、BLE、OPC-UA等,這部分邏輯由網(wǎng)關(guān)實現(xiàn)。整體架構(gòu)如下:JavaLinkKitSDK使用網(wǎng)關(guān)設(shè)備三元組身份,建立端到云上的MQTTLinkKitInitParamsLinkKitInitParamsparams=newDeviceInfogatewayInfo=newDeviceInfo();gaeaInfodeveName=gaea.evceNme;gatewayInfo.deviceSecret=gateway.deviceSecret;paamdevceIfo=gatewayInfo;IoTDeviceInfodeviceInfo=newDeviceInfo();deviceIductKeyDeviceInfodeviceInfo=newDeviceInfo();deviceIductKey=productKey;devceIfodevceame=devceame;deviceInfo.deviceSecret=deviceSecret;deviceInfo,//子設(shè)備身份DeviceInfodeviceInfo=newDeviceInfo();deviceIductKeyDeviceInfodeviceInfo=newDeviceInfo();deviceIductKey=productKey;devceIfodevceame=devceame;deviceInfo.deviceSecret=deviceSecret;deviceInfo,//子設(shè)備身份子設(shè)備成功上線后,我們在網(wǎng)關(guān)設(shè)備詳情,可以查看到子設(shè)備狀態(tài)為:IoTDeviceInfoDeviceInfodeviceInfo=newDeviceInfo();deviceIductKey=productKey;devceIfodevceame=devceame;deviceInfo.deviceSecret=deviceSecret;topic,//子設(shè)備topicdeviceInfo,//子設(shè)備身份DeviceInfoDeviceInfodeviceInfo=newDeviceInfo();deviceIductKey=productKey;devceIfodevceame=devceame;deviceInfo.deviceSecret=deviceSecret;topicTopicdeviceInfo,deviceInfo,DeviceInfoDeviceInfodeviceInfo=newDeviceInfo();deviceIductKey=productKey;devceIfodevceame=devceame;deviceInfo.deviceSecret=deviceSecret;deviceInfoDeviceInfoDeviceInfodeviceInfo=newDeviceInfo();deviceIductKey=productKey;devceIfodevceame=devceame;deviceInfo.deviceSecret=deviceSecret;deviceInfoCPython開發(fā),背后交互邏輯相同,具體可以參考阿里云IoT云產(chǎn)品開發(fā)文檔。 >X.509(一X.509X.509 X.509CA僅MQTT協(xié)議直連的設(shè)備可使用私有CA證書。目前僅2(上海)CA使用私有CA證書時,只支持RSA算法10CACAMacOpenSSLCAopensslopensslopensslversion-abuilton:Nov19platform:darwin64-x86_64-options:bn(64,64)m2n)rc4(ptr,char)des(idx,cisc,16,int)compiler:-archx86_64-fmessage-length=0-pipe-Wno-trigraphs-fpascal-strings--blocks-O3-D_REENTRANT-DDSO_DLFCN-DHAVE_DLFCN_H-DL_ENDIAN-DMD32_REG_T=int-DOPENSSL_NO_IDEA-DOPENSSL_PIC-DOPENSSL_THREADS-DZLB-mmacosx-version-min=10.6OPENSSLDIR:"/System/Library/OpenSSL"CAkey#生成私有CA#生成私有CAkey10opensslreq-new-x509-days3650-newkeyrsa:2048-keyoutmyIoTCARoot.key-outmyoTCARoot.crt-subj\#查看CA證書opensslx509-noout-text-inCA在左側(cè)導(dǎo)航欄,選擇設(shè)備管理>CACA證書管理頁,單擊CA證書CA注冊碼OpenSSLopensslgenrsa-outverificationCert.keyCSR,CommonNameIoTCA證書#生成驗證證書#生成驗證證書opensslreqnewkeyverificationCert.keyoutverificationCert.csrsubj使用由私有CA證書私鑰簽名的CSR#用私有#用私有CAkeyopensslx509-req-inverificationCert.csr-CAmyIoTCARoot.crt-CAkeymyIoTCARoot.key-CAcreateserial-outverificationCert.crt-days365-sha512opensslx509-noout-text-in三、上傳并驗證私有CA證書CAIoT >X.509(一X.509X.509 CACAIoTCAX.509IoTX.509X.509在左側(cè)導(dǎo)航欄,選擇產(chǎn)品X.509CA是 >X.509(二X.509X.509 基于已創(chuàng)建的空氣凈化器產(chǎn)品,添加設(shè)備,輸入設(shè)備evicNme注冊完成后,設(shè)備處于未激活X.509IoTCAopensslCNevicNme。pempemopensslgenrsaoutdevice-1.key2048CSRopensslreq-new-keydevice-1.key-outdevice-1.csr-newkeyrsa:2048-subj\set_serial#用私有CAopensslx509-req-indevice-1.csr-CAmyIoTCARoot.crt-CAkeymyIoTCARoot.key-CAceateserial-outdevice-1.crt-days3650-sha512#查看設(shè)備證書opensslx509-noout-text-indevice-SNIoToue,eeNm和設(shè)備證書SN的映射csvIoTCSVJavaJavaPKCS#8OpenSSL來進行轉(zhuǎn)換,命令如#轉(zhuǎn)換格式#轉(zhuǎn)換格式opensslpkcs8-topk8-informPEM-indevice-1.key-outdevice-1_pkcs8.key-使用TLS(securemode=2)iot_root.crt、設(shè)備證書、設(shè)備證書私鑰來構(gòu)造SSLSocketFactoryprotectedprotectedSSLSocketFactorycreateSSLSocket()throwsException//物聯(lián)網(wǎng)平臺根證書,可以從官網(wǎng)文檔中下載X.509用來驗證IoTCA證InputStreamin=lttiKeyStorekeyStore=KeyStore.getInstance(KeyStore.getDefaultType());keyStore.load(null,null);TrustManagerFactorytmf=TrustManagerFactory.getInstance(TrustManagerFactory.ge//InputStreamcertIn=mKeyStoreks=KeyStore.getInstance(KeyStore.getDefaultType());PrivateKeyprivateKey=ks.setKeyEntry("private-key",privateKey,privateKeyPassword.toCharArray(),newCertiicate[]{certCa});KeyManagerFactorykmf=KeyManagerFactory.getInstance(KeyManagerFactory.getDekmf.init(ks,//構(gòu)造SSLContextSSLContextcontext=SSLContext.getInstance("TLSV1.2");context.init(kmf.getKeyManagers(),tmf.getTrustManagers(),null);SSLSocketFactorysocketFactory=context.getSocketFactory();returnsocketFactory;MQTTCONNECT,usernamepassword////Stringbroker="ssl://x509.itls."+regionId+MQTTStringmqttClientId=em.cuenme)+ecuemode;emoeencepersistence=newemoeence);mqttClient=newqeneveURL,mqttClientId,persistence);qonncOpnsconnOpts=newqonncOpn);connOpts.setMqttVersion(4);//MQTT3.1.1TLSroot.crt,mqttClientIdsecuremode=2。connectmqeneCabacknewqabac){publicvoidmeageAvedngtopic,MqttMessagemessage)throwsExceptionif("/ext/auth/identity/response".equals(topic))JSONObjectjson=JSONObject.parseObject(newString(message.getPayload(),StanproductKeyStringproductKey=json.getString("productKey");StringdeveName=json.getString("deviceName");}else//publicvoiddeveopeeIDeveokentoken)publicvoidconnectionLost(Throwablecause)設(shè)備啟動,聯(lián)網(wǎng)后,我們可以在IoTX.509X.509IoT >深度解讀IoTIoTIoT消息洪峰怎么扛< 深度解讀IoT消息洪峰怎么扛 IoT傳統(tǒng)的消息隊列(Kafka、RocketMQ等)經(jīng)過多年打磨,在高性能、海量堆積、消息可靠性等諸多方面都已經(jīng)做得非常極致,但在IoT物聯(lián)網(wǎng)場景中,往往需要面臨著海量的列最大意義在于讓整個消息在不可控的環(huán)境中平穩(wěn)運行IoT支持設(shè)備級的海量息順序?qū)懳募?yōu)勢就會導(dǎo)致一個broker要退化到隨機寫,失去優(yōu)勢,另外要zookeeper是“海量topic盡量相互隔離,并且不影響整體性能”,盡量做到設(shè)備A的消息堆積topicB。有用。因此,實時生成消息優(yōu)先發(fā)送,堆積的消息進入降級模式。IoTbrokerbrokernosqlDB,高吞吐寫。取堆積消息,而拉取是由AMQP隊列網(wǎng)關(guān)來做,給到用戶接口始終是推送過去的onMessagebrokerconsumer來連接,而是把隊列網(wǎng)關(guān)剝離出來,這樣會更靈活,甚至對于部分用戶我們的queue可以切換到ons、kafka等實現(xiàn)。kafka、rocketmqbrokerbroker實時消息優(yōu)先推送給consumer,失敗才會落到queue;這是一個完整事件,producert。ACK線性擴展-broker三、一個思考一一如何解決海量topictopic數(shù)據(jù)生成,brokermqtttopictopictreeivemq有實現(xiàn)版本。AIoTAIoT為了降低接入成本,用戶可以使用AMQP1.0協(xié)議接入,符合開源生態(tài)。同時兼容傳統(tǒng)隊列和新隊列,交給用戶按場景來選擇,用戶即可選擇使用kafka、mq,也可以選用iot隊AIoTmq隊列、kafkaIoT >億級IoT億級IoT億級IoT IoTIoT標(biāo)準(zhǔn)化:物模型作為物聯(lián)網(wǎng)的抽象層,類似操作系統(tǒng)屏蔽硬件、JVMOS的差異ISV,SI,IHV可適配:由于行業(yè)里面已經(jīng)有不少設(shè)備模型和交互協(xié)議,比如工業(yè)場景的Modbus,opcble,zigbee早期大多數(shù)物聯(lián)網(wǎng)平臺比如Azure、AWS都只做連接和基礎(chǔ)管理能力,并沒有圍繞數(shù)大多數(shù)對于設(shè)備建模都采用的是面向?qū)ο笳Z言的思路,比如WoT、OPC、OMA、OCF、CWMP、AllJoin等,面向?qū)ο笳Z言的抽象能力在計算機編程發(fā)展的幾十年已經(jīng)被javaclassclassschema進行了一定的擴展,定義為屬性、服務(wù)(方法)和事件三要素,事件是一類特【圖為物模型基礎(chǔ)schema(沒有包括模塊化、多語言、多版本等一系列高階特性)AIoTschema描述設(shè)備的能力,但由于物聯(lián)網(wǎng)碎片化,大家對于設(shè)備IoTICAICA功能模塊:一組資源的集合。集合中的資源可以是標(biāo)準(zhǔn)庫中已有資源的組裝,也可以是物模板:一組功能模塊和一組資源的集合。集合中的模塊和資源可以是標(biāo)準(zhǔn)庫中已有模ICA >IoTBroadcastIoTIoTBroadcast< IoT平臺廣播消息Broadcast實戰(zhàn)Topic/broadcast/${YourProductKey/broadcast/${YourProductKeyPubBroadcastAPIpoom_注:broadcasttopicIoT*nodebroadcast-//constoptions=require("./iot-device-constclient=cen.nmeage,function(topic,message){console.log("topic"+topic)cooe.omeage"+message)"productKeyproductKey",devceame:deceNae,"deviceSecret":"替換deviceSecret","regionId":"cn-shanghai"*package.json添加依賴:@acoudppcore":"*/constco=constconstRPCClient=eqe@acoupo-constoptions=accessKey:"自己的accessKey",accessKeySecret:"自己的accessKeySecret"http://1.創(chuàng)建constclient=newRPCClient({secretAccessKey:options.accessKeySecret,apiVersion:'2018-01-20'2iot//這里是POPAPI的ActionconstactionubBoadc;constparams={ProductKey:opcFName:MessageContent:newBuffer('{"broadcast":"thisisbroadcastconstresponse=yieldclient.request(action,PubBroadcastAPI3 >IoTIoTIoT IoTIoT24設(shè)備沉睡處于離線狀態(tài);這些現(xiàn)狀帶來一個新的挑戰(zhàn):在MQTTQoS=1IoTQoS=1離線消息MQTT協(xié)議設(shè)計了一套保證消息穩(wěn)定傳輸?shù)臋C制,包括消息應(yīng)答、存儲和重傳。在這S(ualityofService):QoS=0QoS=1QoS=2QoS=1代表,Sender發(fā)送的一條消息,Receiver至少能收到一次,也就是說Sender向Receiver發(fā)送消息,如果發(fā)送失敗,會繼續(xù)重試,直到Receiver收到消息為止,但是因為重傳的原因,Receiver有可能會收到重復(fù)的消息;QoS=1方式發(fā)布消息到IoT物聯(lián)網(wǎng)平臺,即可保證消息至少到達(dá)設(shè)備端SessionMQTTCONNECTCleanSession=0,即保留之前sessionQoS=1QoS=1的消息。Node.jsCONNECT參數(shù)示例:constconstoptions=clientId:`decuemoesgnmehohmacha1meammeamp`,username:`devceNae}&poucKe}`,password:"根據(jù)文檔規(guī)則進行hmacsha1protocol:"mqtt",cleanfalseSessionkeepalive:300IoTPubAPIQos1APIpoom_mNode.jsPubAPI//1//1PubAPIconstparams={opcFName:"下行指令的完整Topic",MessageContent"base64",ProductKey:"產(chǎn)品ProductKey",IotInstanceIdId",Qos:1//設(shè)備離線時,IoT7//2.發(fā)起Pub//2.發(fā)起PubAPIIoT物聯(lián)網(wǎng)平臺提供設(shè)備影子功能,可以實現(xiàn)離線設(shè)備的消息觸達(dá),完整消息鏈路如為了實現(xiàn)設(shè)備影子功能,IoTochadwgtpdce}$eeNme以便實Node.js示例代碼如下:constconstmqtt=require('aliyun-iot-//constdeviceConfig={"productKey":"產(chǎn)品",devceNme:"設(shè)備","deviceSecretdeviceSecret","regionId":"cn-shanghai"http://1constclient=//2.訂閱設(shè)備影子constgetShadow=`/shadow/get/${deviceCductKey}/${deviceConfig.deviceNacen.nmeage,function(topic,message)if(topic==getShadow){message=console.log(newDate().Format("yyyy-MM-ddHH:mm:ss.S"))console.log("\tappConfig.content:",.sriyss.pyoad.t.dsid.ppooe.o"\ppog.s:",.tnysg.pod.ad.diconstupdateShadow=`/shadow/update/${deviceCductKey}/${deviceConfig.declient.publish(updateShadow,JONngfmehod:"get"}),{qos:1服務(wù)端調(diào)用設(shè)備影子接口UpdateDeviceShadow把新的配置參數(shù)保存到設(shè)備影子的desiredttp//helaliyncom/ocmnt_etil/9954htmlNode.js示例代碼如下:constconstco=constRPCClient=eqe@acoupo-constoptions={accessKey:"accessKey",accessKeySecret:"你的//1.初始化constclient=newRPCClient({accessKeyId:options.accessKey,apiVersion:'2018-01-20'constshadowMessage={method:"update",state:{desired:{maxTemperature:constparams=ProductKey:"你的ProductKey",Devceame:"你的Devceame,ShadowMessage:try{constresponse=yieldcen.eueUpaeDevchado,params);}catch(err){云端業(yè)務(wù)系統(tǒng)調(diào)用成功后,我們在IoT物聯(lián)網(wǎng)平臺的控制臺,設(shè)備詳情>設(shè)備影子, TopicTopic同步調(diào)用RRPC實戰(zhàn)(二)< TopicRRPC(二RRPC:Revert-RPC。RPC(RemoteProcedureCall)采用客戶機/服務(wù)器模RRPC則可以實現(xiàn)由服務(wù)端請求。動等業(yè)務(wù)場景,應(yīng)用服務(wù)器通過POPAPI發(fā)起RRPC調(diào)用,IoT設(shè)備端只需要在TmoutPubIoT。服務(wù)端同步RRPC調(diào)用業(yè)務(wù)流程如下:Topic:Topic:epc1242232chagngcmdPayload:{"power":200,"port":"3"}Topic:Topic:epc1242232chagngcmdPayload:{"bizCode":0,"errMsg":"xxxxx"}為了配合自定義Topic的RRPC調(diào)用,設(shè)備端需要在MQTT的CONNECT參數(shù)clientIdext=1標(biāo)識:constconstmqtt=require('aliyun-iot-constoptions={productKey:"YourproductKey",devceame:"Yourdevceame,deviceSecret:"YourdeviceSecret",//2;//3RRPC主題cen.nmeage,function(topic,message)console.log("topic<<="+topic)console.log("payload<<="+message)handleRrpc(topic,message)functionhandleRrpc(topic,//RRPCpayloadconstpayloadJsonbizCode:00400console.log("replytopic=>>"+console.log("replypayload=>>"+JONngfpaoadJo))client.publish(topic,JSON.stringify(payloadJson));RRPCAPIRRPCAPINode.jsconstconstco=constRPCClient=eqe@acoupo-constoptions=accessKey:"youraccessKey",accessKe

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論