当前位置:网站首页>AWS device shadow usage

AWS device shadow usage

2022-06-21 18:33:00 Enlarged EZ

AWS Device shadow yes AWS Official recommendation management control IOT The way the device works .

Device:aws iot device sdk(nodejs)
client End :aws sdk(nodejs)

About more AWS IOT Please refer to :AWS IoT Device Shadow service - AWS IoT Core

If you need to know device End C The shadow of language operation can be found in the following articles :

1 Device shadow Basic concepts

The device shadow is used to store and retrieve the current status information of the device JSON file .( Stored in AWS IOT cloud Inside )
Device Shadow The service can connect you to AWS IoT Keep a shadow for each device . You can use this shadow to pass through MQTT or HTTP Get and set the status of the device , Whether the device is connected to Internet. The shadow of each device is uniquely identified by the name of the corresponding thing .

Borrow here AWS The architect's two diagrams illustrate how to use shadow
 

1.1 Device shadow Control model

 Picture description here

 

1.2 AWS IOT How the device works

 Picture description here

1.3 Device shadow Some key attributes

 Picture description here

 

Device shadow stay AWS IOT Medium is JSON Format store There is a fixed format to be explained here :

state
    desired
         The expected state of things . The application can write data to this document section to update the status of things , And you don't have to connect directly to that thing .
    reported
         Reporting status of things . Things can write data to this part of the document , To report its new status . Applications can read sections of this document , To determine the state of things 
    Delta
         An incremental state is a virtual type of state , contain  desired  State and  reported  The difference between States .
timestamp
         To specify  AWS IoT  Time of message transmission . By using a timestamp in the message and  desired  or  reported  Different attributes in the section use timestamps , Things can determine the age of the updated item , Even if it doesn't have internal clock characteristics .
version
         Document version . Every time the document is updated , This version number will be incremented . Used to ensure that the document being updated is the latest version .

So the content in the figure is the current state engine by on,light color by GREEN, The expected state is engine by on,light color by RED.
You can define the relevant attributes for the specific content of the status .

1.4 DeviceShadow There are three kinds of API operation

GetThingShadow Get the shadow of things The returned content is 1.3 Format in the figure
UpdateThingShadow Update the shadow of specified things The parameter contains state in json:{ state:{…} }
DeleteThingShadow Delete the shadow of the specified thing

1.5 Deviceshadow Underlying implementation

Device Shadow The essence is the interior of a series of conventions topic Make up the control logic , It also provides the function of persistent data storage .
That is, internal fixation topic.
Here are a few that will be used topic type :

$aws/things/myLightBulb/shadow/update/accepted
When the shadow of the device is successfully updated ,Device Shadow The service will send a message to this topic .
$aws/things/myLightBulb/shadow/update/delta
When the shadow of the device is detected “reported” Part and “desired” When there are differences between parts ,Device Shadow The service will send a message to this topic . For more information , see also /update/delta.
$aws/things/myLightBulb/shadow/update/documents
Every time the shadow update of the device is successfully executed ,Device Shadow Services will publish status documents to this topic .

Mqtt client By updating shadows (UpdateThingShadow ) The bottom process of changing the light from red to green :
 Picture description here

 Mqtt client call UpdateThingShadow API after IOT Internet behavior

1 Mqtt client That is to say server Publish a $aws/things/myLightBulb/shadow/update news . The message carries the expected update status {“state”: {“desired”: {“color”: “green” }}}
2 IOT server Received this message , Will release $aws/things/myLightBulb/shadow/accepted Respond to update The request message indicates that the update has been received . At the same time, a message will be released $aws/things/myLightBulb/shadow/delta Notify the device to update . Release another $aws/things/myLightBulb/shadow/update/documents Messages as update records .
3 device I subscribed to it when I went online delta news , received IOT server released delta After the news ,device Perform the corresponding update operation , After completion, the equipment issues a message $aws/things/myLightbulb/shadow/update {“state”: {“reported”: {“color”: “green” }}} towards IOT server The notification status has been updated
4 IOT server received update news reported), Will release $aws/things/myLightBulb/shadow/accepted Respond to update The request message indicates that the update has been received . Release another $aws/things/myLightBulb/shadow/update/documents Messages as update records .

We write device You need to write your own code delta Processing function , After processing, you need to call update Go to reported Update results .
 

2 Sample

Sample mqtt End sum device All adopt  node To write .
device End use aws-iot-device-sdk Connect to AWS IOT cloud in
client End use AWS SDK adopt restful API visit device shadow

Device Node SDK API: https://github.com/aws/aws-iot-device-sdk-js
AWS SDK API: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IotData.html
 

2.1 device End code

var awsIot = require('aws-iot-device-sdk');

const thingShadows = awsIot.thingShadow({
    keyPath: `xxxxx-private.pem.key`,
    caPath: 'root-CA.crt',
    certPath: `xxxxxx-certificate.pem.crt`,
    // clientId: `arn:aws:iot:ap-northeast-1:xxxxxxx:thing/test_device_tokyo`,
    host: `xxxxxxxxxx.iot.ap-northeast-1.amazonaws.com`
});// obtain shadow object

var clientTokenUpdate;
var thingName = "test_device_tokyo";// Shadow unique identifier Thing name
var expectedClientToken;

 // go online Self inspection   To obtain state sync  
thingShadows.on('connect', function() {
    thingShadows.register(thingName, {}, function() {//shadow Register the shadow after the link succeeds , Only after registration can shadow related operations be used
        expectedClientToken = thingShadows.get(thingName);// call get api Detect current shadow state
    });
});

var devicestatus = {// Simulate device status There are three properties power stream streamurl
  stream : 0,
  power: 1,
  streamurl:"unavailable",
}

var updateLoaclStatus= function(cloudStatus){// Update local status ( Analog control operation )
  console.info("update local state:", cloudStatus);
  for(let key in cloudStatus){
    devicestatus[key] = cloudStatus[key];
  }
}

var getStatusFromShadow = function(stateObject){// from GET API Parse the message in the return
  let cloudStatus;
  if(stateObject.state.desired !== undefined){// If shadow in desired, That is to desired Subject to , Update status to expected status
      cloudStatus = stateObject.state.desired ;
  }
  else{                                       // No, desired Then synchronize the status to reported state .( The status before the last offline )
      cloudStatus = stateObject.state.reported;
  }
  updateLoaclStatus(cloudStatus);// Update local status ( Analog control operation )
}

thingShadows.on('status', function(thingName, stat, clientToken, stateObject) {//get API return Iot server in shadow result
  if (expectedClientToken === clientToken) {
    // console.log('got \'' + stat + '\' status on: ' + JSON.stringify(stateObject));
    getStatusFromShadow(stateObject);// adopt get obtain iot server in shadow state , And update the synchronization local status
    // console.info(devicestatus);     
    update();                        //reported current state
  } 
});

var update = function(){// update operation be used for reported Equipment status
    var CameraState = {state:{reported:devicestatus, desired:null}};// Read local status be used for reported
    clientTokenUpdate = thingShadows.update(thingName, CameraState);//updateshadow API
    if (clientTokenUpdate === null)
    {
      console.log('update shadow failed, operation still in progress');
    }
    else{
      console.log('update success');
    }
 }

 thingShadows.on('delta', function(thingName, stateObject) {// from mqtt client Status change request ( news )
    console.info(thingName, stateObject);
    updateLoaclStatus(stateObject.state);
    console.info(devicestatus);
    update();
 });

2.2MQTT client Code

Use AWS SDK adopt restful API The way update shadow or get shadow

var AWS = require('aws-sdk');
AWS.config.loadFromPath('./aws_config.json');
var awsDeviceShadow = new AWS.IotData({accessKeyId:"xxxxxx",secretAccessKey:"xxxxxx",endpoint: 'xxxxxx.iot.ap-northeast-1.amazonaws.com', region:'ap-northeast-1'});
// obtain AWS SDK shadow API Action object
var testThingName = "test_device_tokyo";// The thing name is the only sign of the shadow
var Devices = function() {
    var self = {};
    return self;
};

Devices.get = function(thingName, resmodel, callback){
    let params = {
        thingName: thingName/* required */
    };
    awsDeviceShadow.getThingShadow(params, function(err, data){// adopt sdk Use restful API obtain iot shadow
        if (err){
            console.error(err, err.stack); // an error occurred
            return callback(err);
        }
        return callback(null, data.payload);// Return results
    });
};
//only update shadow and No check device response
Devices.update= function(thingName, data, callback) {
    let payload = {state:{desired:data, reported:null}};
    let params = {
        payload: JSON.stringify(payload),
        thingName: thingName/* required */
    };
    console.log("\nupdate param:", payload)
    awsDeviceShadow.updateThingShadow(params, function(err, data) {// adopt sdk Use restful API to update iot shadow
        if (err){
            console.error(err, err.stack);
            return callback(err);
        } 
        return callback(null);
    });
};

Devices.get(testThingName, 0, function(err, state){// call get test
    if(err)
        console.error(err);
    else
        console.log("\nget thingShadow:",state);
});

let cmd = {stream:1, power:1}
Devices.update(testThingName,  cmd, function(err, data){// call update test
    if(err) 
        console.error(err)
    else
        console.info("\nupdate success");
});

2.3 test result

2.3.1device End printing

get thing shadow: {"state":{"reported":{"stream":1,"power":1,"streamurl":"unavailable"}},"metadata":{"reported":{"stream":{"timestamp":1531897249},"power":{"timestamp":1531897249},"streamurl":{"timestamp":1531897249}}},"version":839,"timestamp":1531897330}
// The program runs obtain iot shadow Status and synchronize
update local state: { stream: 1, power: 1, streamurl: 'unavailable' }
// Synchronization complete
update success
// send out reported
delta message: test_device_tokyo { version: 841,
  timestamp: 1531897399,
  state: { stream: 1, power: 1 },
  metadata:
   { stream: { timestamp: 1531897399 },
     power: { timestamp: 1531897399 } } }
// Received from client End update send out delta news  
update local state: { stream: 1, power: 1 }
// With delta Status pairs in messages device updated
update success
// send out reported

2.3.2 client End printing

get thingShadow: {"state":{"reported":{"stream":1,"power":1,"streamurl":"unavailable"}},"metadata":{"reported":{"stream":{"timestamp":1531897331},"power":{"timestamp":1531897331},"streamurl":{"timestamp":1531897331}}},"version":840,"timestamp":1531897397}
// obtain shadow state
update param: { state: { desired: { stream: 1, power: 1 }, reported: null } }
// Initiate in this state update
update success
// Received from IOT server accepted The message was printed successfully

Reprint of the article :

AWS Device Shadow Use

原网站

版权声明
本文为[Enlarged EZ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211657223904.html