Using Device Twins with Azure IoT Hub

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone in today's video we will be discussing how you can use device twins with azure iot hub we will give an explanation of what device twins are and how they are used and then we will be going over some code examples on how to use them with azure iot hub let's get started to start we need to define what a device twin is a device twin is a document that stores information about iot devices they can store state information as well as metadata about the device these documents are maintained by azure iot hub there will be one device twin created for each device that you have registered with your iot hub device twin documents are stored as json documents here is an example of a device twin document notice it is just straight json and has a specific structure here is what the structure of a device twin looks like a device twin document is comprised of sections that can be read or written by either the application on the device side or a back end solution on the cloud side tags in the yellow box are properties you define that are only used on the back end solution side these can be whatever you want but please be aware that tag properties are not visible to the device desired properties in the blue box are properties you define that the back-end solution can use to help synchronize the configuration of your device the back-end sets the desired property values and then the device application would receive a notification that a desired property has changed the device application can then perform some kind of action if necessary based on that notification event received reported properties in the green box are also properties you define that work with the desired properties to help synchronize device configurations the device application sets these reported properties and the back-end solution would then receive a change notification to state that the device reported properties have changed the back-end solution can then perform some kind of action if necessary based on that notification event received device identity properties are located at the root of the device twin document and contain the properties that define the identity of the device these properties are read only in our example the first section is the device identity properties notice it has a device id property which is the name of the device there are also properties that specify the status connection state and last activity time the next section is the tags section these can contain whatever information you need in our example the tags specify deployment location the next section is the properties section there are two sub-areas here desired properties and reported properties again you can put whatever information you need in these sections in our example there is a telemetry config property which holds ascend frequency property notice that in desired properties this send frequency property is specifying to the device what this value should be the backend solution would be writing this value and lastly reported properties is the other section contained under the properties section reported properties would be set by the device to report the actual values on the device side up to the back end solution in the cloud in our example the send frequency is being reported as five minutes and also specifies the status of success you can also see another reported property of the battery level on the device now that we know what device twins are and their structure how do we use them device twins can be used to report current state information about your device or to synchronize configurations for your device from the cloud in the diagram shown you can see the backend solution on the right which can update a desired property value to tell the device that we want to change something about that device this could be something like updating the frequency of a specific check like checking a sensor value on the device or specifying that there is a newer version of the firmware for that device the physical device is shown on the left and an application running on the device can be used to receive event notifications that a desired property has changed from the cloud at this point the device application can apply the configuration change requested and when finished could set values in the reported properties to inform the back-end solution of its progress or completion the back-end solution can also query for the device-reported properties or can be notified when a change is made to the reported properties of the device the back-end solution could then perform whatever actions are necessary based on the values and the reported properties that it queries let's write some code to see azure device twins in action you will need an instance of azure iot hub provisioned along with the registered device as you can see i'm in my azure portal and i've already provisioned an iot hub called device twins hub and if i go to the iot devices section you can see that i also registered a device called mxchip device one so first off let's create our application with visual studio so i want to create a console app using the.net framework so i'm going to select this click next i'm going to call this back end console app and hit the create button once this window comes up we'll need to add a package from nuget so if i go to manage nuget packages i want to browse for microsoft azure devices so this is the service sdk for azure iot hub and allows us to perform operations on there so i'm going to select this and hit install okay once it's installed we can go back to our program.cs and i'm ready to start adding code now the first thing i need to do is to add some variables that i'm going to be using throughout the program the first one here is a instance of registry manager this is going to allow me to call the different methods for the device twins so i'm just typing in a static here of type registry manager and then i'm just gonna going to add the using statement and then i also need a connection string for iot hub and i can get that from the portal i'm going to use the service policy and copy the primary key for the connection string now you can use other policies here as long as they have the service connect permission enabled so let me go back to our application and i'm going to paste that in for the connection string and then i'm also going to need a string for the name of our device so i'm calling it mxchip device name and the name of our device is mxchip device one now that i have these variables i can start coding up my main method so the first thing i want to do is i want to create a boolean since i'm going to do a do while here so inside this do while i'm going to have it ask to type in a selection for the things that we want to do here so there are five different choices number one is going to be reading device twins of the tags out of device twin number two is going to be writing those tags uh three and four will be reading and writing desired properties from the device twin and then five will be reading the reported properties of the device twin and then typing anything else will just end the program so now i can say switch and selection and then case one is gonna be i don't know read tags update and then break okay so i'm want to create a method called read tags so i'm going to put that up above the main method so i want to call public static i'm going to make these asynchronous and then i'm going to add the code to do that so basically what i can do here is i can call the registry manager to get the twin uh a reference to the twin which is going to be microsoft.azure.devices.shared.twin uh and then you you pass in the name of uh the device so that's going to go out to the azure iot hub look for a device of that name and then bring back the the twin that is saved there and then once i have that i'm just going to spit out to the console what the tags are so if you look at the twin intellisense is going to give you a number of things here like the device identity property so dot device id is going to be available and then there's also gonna be tags so i can just have that spit that back to um to the console now one thing i forgot here is in the main program we need to instantiate the registry manager so if we say registrymanager.createfromconnectionstring and then pass up the connection string of our azure iot hub that instantiates the registry manager for use so we're going to do this before we go into our do while loop and then now if i hit f5 and run this it's going to prompt me for one of the five selections so if i type in one for reading the device twin tags it camp comes back and notice how there's nothing there you can see tags for mxchip device one and it just has an empty string so which is correct we haven't added any tags yet so it's gonna come back with nothing so so let me control c out of this now what we're going to do and let me just add this because we need to be able to get out of the loop now what we want to do is we want to write to the tags you want to write information to the device twin tags so i'm going to put case 2 here and we're going to call this update tags complete now with the update tags we want to ask for a tag name and a tag value uh to add so what i'm going to do here is i'm going to prompt uh in the console to say enter the tag name and then the value and then put those in variables so tag name and sdr tag name and as here tag value which we'll want to pass to our update tags method so again up here then we will put uh we'll create our method so public static update tags the code for update tags is right here basically i'm going to get the twin into a variable i want to write the tags now the tags have to be in json format so uh we're putting it with the tags here and then name colon value so it's got to be in proper json format and we're putting that here in a variable called patch and then there's a method called update twin async that will update the twin based on what you tell it so i'm telling it update the twin for this device id i'm passing it in the json uh and then the twin has an e tag so that uh that needs to be passed in as well but the patch basically is telling it here's it looks at this and says this is what i want um to update so basically i can update that and then when i'm done uh when that completes i'll just get the twin again putting it back into our twin variable and then spin it out to the screen and that should show you the updated tag okay so now we're ready to run it again so if i hit f5 again just we're gonna start out by just typing in one here to make sure there's no tags uh and then number two if i type in number two we're gonna uh it's going to prompt me for a tag to enter so for the tag name i'm going to say test tag 1 and i'm going to put in the value 1 2 3 four five and now you can see it said tags for the um device the mx chip device one are this if i type in one again you can see now here that um it does return the tag that we wanted or that we updated now i can go ahead and update this again so if i type in two and type in the same type in the same tag name test tag one and go five four three two one now you can see that it updated the tag to the new value now that we have the tags being able to read and write the tags let's move on to reading and writing desired properties so for reading and writing desired properties we're just going to add a couple more to the case statements so 3 is for reading the device twin desired properties so i want to create a so let's call this read desired properties so we'll want to create a method called redesired properties so if i go up here and type in public static async task read desired properties with no parameters and here's the code for that so again we're using registry manager to get the twin into this variable and this is very similar to uh the other one where you're reading the tags we're just once we call this because this gets the entire twin we can um just pass it the device or just spit it out to the screen with the device id and then properties dot desired okay so that will read the desired properties and now to update the desired properties we're going to want to call update desired properties which is the method we'll create so update desired properties dot wait and again we're going to want to prop for a desired property name and value so it's very similar to the tags name and value when we prompted for that so let's just say desired property and let's call this desired property desired property there so and then we'll want to pass these in just like the other one desired property value and now we can create a method here public static update desired properties we're going to add in desired property name desired property value that's the parameters and then the code for this method is as follows so once again we're going to get the twin and let's just update this we do need it in we do need this in proper json format so in this case it's going to be properties and then underneath that desire you're going to have a desired section uh and then again it's just updating the twin passing at the device id the variable here of your json and the etag so once you do that and then we can get the twin again and then display it out to the screen so now if i hit f5 again and it prompts me now i'm going to type in three here for reading the device twin desired properties and you can see here now that the only desired properties that we have on the device here is the metadata when it was last updated and then a version number so if i want to add my own desired properties i can let's do that with four and let's say test desired property one and let's go four five six seven eight and then again if i go three again and you can see here that the test desired property one has been added with four five six seven eight and then it also puts something in the metadata to keep track of the last updated version and when it was updated again or when it was last updated so if i update it again say test the desired proper t1 and let's go 99999 now you can see that it did update the desired property but in the metadata now it increased the version to 3 and then it changes the last update date time value and then finally the last thing that we can do on this on the cloud side here is read device twin reported properties so let's do that so we want to create a method called read reported properties [Applause] and then come up here and create another method called read reported properties and here's the code for that and again getting the twin into the variable and then just spitting out the device id and then properties.reported let me put that weight here okay so if we run this now f5 and select five now you'll notice that there are no there's nothing really inside here for reported properties because we have not connected our mx chip device so it hasn't reported anything just yet so we're going to do that next now for the device side i'm using the mx chip iot dev kit device and i've already set up the workspace and project so please see my video on uh following that to get your device connected and once you have that we'll go through let's go through the code here on how to call and get the device twin information first thing we need to do is in your setup method we need to initialize the mqtt client so that we can start using the methods to get the device twins so there's a method here called dev kit mqtt client underscore init which we need to call and make sure that that works just fine so that it connect it can connect to uh your azure iot hub now what's important here is that you'll notice that there's a parameter there's actually two parameters that it can take uh and if you don't pass them in they default to false but the first one is whether or not it has a device twin and whether you want device twin support so you want to set that first flag our first parameter to true so that we can get at the device twin information the second one is for tracing i'll leave that off right now but once we have this and it once this init method is called the next thing to do then is to set a callback method for the device twin so this is needed when a desired property is set from the cloud we need a callback method that will fire when the change happens so that the device is notified of that so that's done by calling this dev kit mqtt uh client underscore set device twin callback and you basically pass it the method name of the callback that you want and i'm calling it device twin callback this is up here defined up here so it takes uh some parameters so it takes this update states as well as uh pointing to the payload and the size and what i do here is i'm basically grabbing what's in the payload and copying it to um memory pointer and basically i spit it out to the serial monitor so this is just going to show what the desired properties are so your callback can do other things obviously that you want but just for this example i'm just going to spit it out to the serial printer on what those desired properties are once that's done then we can look at the main loop what we're going to do here is call this dev kit mqtt client underscore check and this is going to check to see whether or not their message is coming from iot hub so this runs every time through the loop uh and then basically all this does is if the a button is pressed uh i'm going to serialize a json object with these reported properties so i'm just picking these at random because i know that they're we can get these from our wi-fi so i'm basically getting the local ip address and the subnet mask and making reported properties called wi-fi dot wi-fi ip and wi-fi dot wi-fi mask i'm also putting a random number in here so that every time you press the button it will change the random number so you can see the change and then basically what i do is i serialize this to strength to a string and then i'm going to show that what that state is in the serial monitor and then i call this method called dev kit mqtt client underscore report state so this is what uh sends the reported property state to iot hub so i'm passing it in the state variable uh just a a character pointer string so it's basically sending that json out to iot hub it will get stored in the device twin now once i've uploaded this to the device i can run this so i'm going to hit f1 upload code device code and this will upload this to the device that i have connected and then once that's done let me open the serial monitor here so we can see what's going on so you can see that connecting to my wi-fi and now if i go to my device and press the a button you can see that it's it says on the screen that the a button was pressed and let's go back to our serial monitor and now you can see here that um it says here a button pressed right here and then it spits out the state and then it sends it to iot hub which is done right here and the state code is 204 meaning it's good so it was sent there so now if i go back and i go back to my console application and i run this and if i read the device twin reported properties number five now you can see that here it got it wi-fi with wi-fi ip and wi-fi mask and these values are good and then of course the metadata again is going to have what they're when they were last updated and what their version is so now if i want to uh update the desired properties which is number four let's call this another test one and let's just say 91919 so another test one one 91919 has been created here and if i go back to my device uh application with the serial monitor running you'll notice that uh the design it spits out here the desired property change from iot hub and there's my desired properties i have another test one 91919 along with the version number and what that means is that the device twin callback method has fired and has notified the device of the change in the desired properties i hope this video was helpful on understanding device twins with azure iot hub if you would like to download the example source code please visit my github page listed in the description thanks for watching [Music] you
Info
Channel: TheTurkishDeveloper
Views: 1,172
Rating: undefined out of 5
Keywords:
Id: vrhhQhqf2fE
Channel Id: undefined
Length: 31min 58sec (1918 seconds)
Published: Sun May 31 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.