Package: micropython-iotc
Azure IoTCentral SDK for MicroPythonAn Azure IoT Central device client library for Micropython.This repository contains code for the Azure IoT Central SDK for Micropython. This enables micropython developers to easily create device solutions that semealessly connect to Azure IoT Central applications.
It can run on various boards with some tweaks for low-memory devices.PrerequisitesMicropython 1.12+ (recommended)ImportiotcIn most of the micropython capable boards, is sufficient to import library or install it if missing through upip.try:importiotcexcept:importupipupip.install('micropython-iotc')importiotcThe same commands apply when running through Micropython REPL.NOTE:for low-end devices like theESP8266, importing as external module can cause out-of-memory exception during execution because of the limited amount of heap space.
For this kind of boards, putting the library on flash memory as a frozen module might be the only available option.Details on how to build a custom firmware for specific boards with frozen modules can be found on official micropythongithub repositoryandwebsite.SamplesCheck out thesample repositoryfor example code showing how the SDK can be used in the various scenarios:ConnectingCurrently only connection through Shared Access Keys is supported.
You can use both device keys or group keys.InitfromiotcimportIoTCConnectTypeid_scope='scopeID'device_id='device_id'sasKey='masterKey'# or use device key directlyconn_type=IoTCConnectType.SYMM_KEY# or use DEVICE_KEY if working with device keysclient=IoTCClient(id_scope,device_id,conn_type,sasKey)You can pass a logger instance to have your custom log implementation. (see#Logging)e.g.fromiotcimportConsoleLogger,IoTCLogLevellogger=ConsoleLogger(IoTCLogLevel.ALL)client=IoTCClient(id_scope,device_id,conn_type,sasKey,logger)Connectclient.connect()After successfull connection, IOTC context is available for further commands.OperationsSend telemetryclient.send_telemetry(payload,properties=None)e.g. Send telemetry every 3 secondswhileclient.is_connected():print('Sending telemetry')client.send_telemetry({'temperature':randint(0,20),'pressure':randint(0,20),'acceleration':{'x':randint(0,20),'y':randint(0,20)}})sleep(3)An optionalpropertiesobject can be included in the send methods, to specify additional properties for the message (e.g. timestamp,etc... ).
Properties can be custom or part of the reserved ones (see listhere).NOTE:Payload content type and encoding are set by default to 'application/json' and 'utf-8'. Alternative values can be set using these functions:iotc.set_content_type(content_type)# .e.g 'text/plain'iotc.set_content_encoding(content_encoding)# .e.g 'ascii'Send property updateclient.send_property({'fieldName':'fieldValue'})Listen to eventsDue to limitations of the Mqtt library for micropython, you must explictely declare your will to listen for incoming messages. This client implements a non-blocking way of receiving messages so if no messages are present, it will not wait for them and continue execution.To make sure your client receives all messages just calllisten()function in your main loop. Be aware that some sleeping time (200 ms +) is needed in order to let the underlying library listen for messages and release the socket.whileclient.is_connected():client.listen()# listen for incoming messagesclient.send_telemetry(...)sleep(3)You also need to subscribe to specific events to effectively process messages, otherwise client would just skip them (see below).Listen to properties updateSubscribe to properties update event before callingconnect():client.on(IoTCEvents.PROPERTIES,callback)To provide property sync aknowledgement, the callback must return the
property value if has been successfully applied or nothing.e.g.defon_props(prop_name,prop_value):ifprop_value>10:# process propertyreturnprop_valueclient.on(IoTCEvents.PROPERTIES,on_props)Listen to commandsSubscribe to command events before callingconnect():client.on(IoTCEvents.COMMANDS,callback)To provide feedbacks for the command like execution result or progress, the client can call theackfunction available in the callback.The function accepts 2 arguments: the command instance and a custom response message.defon_commands(command,ack):print(command.name)ack(command,'Command received')client.on(IoTCEvents.COMMANDS,on_commands)LoggingThe default log prints to serial console operations status and errors.
This is theAPI_ONLYlogging level.
The functionset_log_level()can be used to change options or disable logs. It accepts aIoTCLogLevelvalue among the following:IoTCLogLevel.DISABLED (log disabled)IoTCLogLevel.API_ONLY (information and errors, default)IoTCLogLevel.ALL (all messages, debug and underlying errors)The device client also accepts an optional Logger instance to redirect logs to other targets than console.
The custom class must implement three methods:info(message)debug(message)set_log_level(message);Cache CredentialsThe IoT Central device client accepts a storage manager to cache connection credentials. This allows to skip unnecessary device re-provisioning and requests to provisioning service.
When valid credentials are present, device connects directly to IoT Central, otherwise it asks provisioning service for new credentials and eventually cache them.Provided class must have the following methods:defretrieve(self):# fetch credentials. return a Credentials objectdefpersist(self,credentials):# save credentials objectOne-touch device provisioning and approvalA device can send custom data during provision process: if a device is aware of its IoT Central template Id, then it can be automatically provisioned.How to set IoTC template ID in your deviceDevice template id (a.k.a Model Id) is used when obtaining authorization codes for new devices and automatically assign them to the right template. By providing template id during credentials generation, user doesn't need to manually migrate or assign device from IoT Central site.In order to get the unique identifier, open configuration page for required model under "Device templates" section.Click on "View Identity" and in next screen copy model urn.Then call this method before connect():client.set_model_id(model_id)Automatic approval (default)By default device auto-approval in IoT Central is enabled, which means that administrators don't need to approve device registration to complete the provisioning process when device is not already created.Manual approvalIf auto-approval is disabled, administrators need to manually approve new devices.
This can be done from explorer page after selecting the deviceLicenseThis samples is licensed with the MIT license. For more information, seeLICENSE