Fast Access
This section uses the smoke detector demo to create a product model, configure and start the demo, and use basic SDK functions. A smoke detector product model is provided to help you understand the product model. This smoke detector can report the smoke density, temperature, humidity, and smoke alarms, and execute the ring alarm command. The following uses the smoke detector as an example to introduce the procedures of message reporting, property reporting, and command response.
Creating a Product
A smoke detector product model is provided to help you understand the product model. This smoke detector can report the smoke density, temperature, humidity, and smoke alarms, and execute the ring alarm command. The following uses the smoke detector as an example to introduce the procedures of message reporting and property reporting.
- Access the IoTDA service page and click Access Console. Click the target instance card.
- Choose Products in the navigation pane and click .
Figure 1 Creating a product
- Set the parameters as prompted and click OK.
Basic Info
Resource Space
The platform automatically allocates the created product to the default resource space. You can also select an existing resource space from the drop-down list or create one.
Product Name
Customize the product name. The name can contain letters, numbers, underscores (_), and hyphens (-).
Protocol
Select MQTT.
Data Type
Select JSON.
Device Type Selection
Select Custom.
Device Type
Select smokeDetector.
Advanced Settings
Product ID
Leave this parameter blank.
Description
Set this parameter based on service requirements.
Figure 2 Creating a product - MQTT
Uploading a Product Model
- Download the smokeDetector product model file.
- Click the name of the created product to access its details page.
- On the Basic Information tab page, click Import from Local to upload the product model file obtained in 1.
Figure 3 Product - Uploading a product model
Registering a Device
- In the navigation pane, choose Devices > All Devices, and click Register Device.
- Set the parameters as prompted and click OK.
Parameter
Description
Resource Space
Ensure that the device and the created product belong to the same resource space.
Product
Select the created product.
Node ID
Customize a unique physical identifier for the device. The value consists of letters and digits.
Device Name
Customize the device name.
Authentication Type
Select Secret.
Secret
Customize the device secret. If this parameter is not set, the platform automatically generates a secret.
After the device is registered, save the node ID, device ID, and secret.
Accessing the Device
- Obtain the access address by choosing Overview > Access Details on the console.
Figure 4 Access information - MQTT access address on the device side
- In iot_device_demo/device/smoke_detector.py, enter the access address, device ID, and device secret.
server_uri = "access address" # Change it to the saved access address. port = 8883 device_id = "your device id" secret = "your device secret" # CA certificate of the IoT platform, used for server authentication. iot_ca_cert_path = "./resources/root.pem" connect_auth_info = ConnectAuthInfo() connect_auth_info.server_uri = server_uri connect_auth_info.port = port connect_auth_info.id = device_id connect_auth_info.secret = secret connect_auth_info.iot_cert_path = iot_ca_cert_path client_conf = ClientConf(connect_auth_info) device = IotDevice(client_conf)
You can download the platform certificate from /iot_device_demo/resources/root.pem in the source code.
- Write and run the code. Run the sample. If the output contains connect result is : true, the connection is successful.
Figure 5 Connection succeeded
- Check the device running status. On the device details page of the console, check whether the device is online and the reported product model data.
Figure 6 Device list - Device online status
Figure 7 Viewing reported data - smokeDetector
The SDK provides automatic reconnection by default. After the device is initialized, if the connection fails due to an unstable or unreachable network, or proactive disconnection by the platform, the SDK automatically initiates reconnection in the backend. To disable this function, see Disconnection and Connection.
Reporting a Message
Message reporting is the process in which a device reports messages to the platform.
- Report messages to the platform through the default topic with the report_device_message method or through a custom topic with the publish_raw_message method in the example of iot_device_demo/message/message_delivery_sample.py.
""" create device code here """ default_publish_listener = DefaultPublishActionListener() device_message = DeviceMessage() device_message.content = "Hello Huawei" device_message2 = DeviceMessage() device_message2.content = "Custom topic Message" device_message3 = DeviceMessage() device_message3.content = "Custom Policy topic Message" # Report messages as scheduled. while True: # Report messages through the default topic of the platform. device.get_client().report_device_message(device_message, default_publish_listener) time.sleep(1) payload = json.dumps(device_message2.to_dict()) # Report messages through a custom topic of the platform. device.get_client().publish_raw_message(RawMessage(custom_topic, payload, 1), default_publish_listener) time.sleep(1) payload = json.dumps(device_message3.to_dict()) # Report messages through the topic in the custom policy. device.get_client().publish_raw_message(RawMessage(custom_policy_topic, payload, 1), default_publish_listener) time.sleep(5) - On the IoTDA console, choose Devices > All Devices and check whether the device is online.
Figure 8 Device list - Device online status
- Select the device, click View, and enable message trace on the device details page.
Figure 9 Message tracing - Starting message tracing
- Check the message tracing result to see whether the platform has received messages from the device.
Message tracing may be delayed. If no data is displayed, wait for a while and refresh the page.
Figure 10 Message tracing - Viewing device_sdk_java tracing result
Reporting Properties
A device can report current property values to the platform.
- Report properties to the platform with the report_properties method in the example of ./iot_device_demo/device/properties_sample.py.
def run(): < create device code here ... > if device.connect() != 0: logger.error('init failed') return service_property = ServiceProperty() service_property.service_id = 'smokeDetector' service_property.properties = {'alarm': 10, 'smokeConcentration': 36, 'temperature': 64, 'humidity': 32} services = [service_property.to_dict()] while True: device.get_client().report_properties(services, DefaultPublishActionListener()) time.sleep(5) - In the example, the alarm, smokeConcentration, temperature, and humidity properties are periodically reported to the platform. In the navigation pane, choose Devices > All Devices. Click the target device to access its details page to check the product model data reported by the device.
Figure 11 Product model - Property reporting
If no property value is reported, check whether the product model has been uploaded. For details, see Uploading a Product Model.
Delivering Commands
You can set a command listener to receive commands delivered by the platform. The callback API needs to process the commands and report responses.
- ./samples/command/platform_command.go is an example of processing platform command delivery. In the code, the instance of CommandSampleListener is set as the command listener. The CommandSampleListener class inherits the CommandListener class and implements the on_command method.
device.get_client().set_command_listener(CommandSampleListener(device))
- When receiving a command, the device automatically calls the on_command method in the listener.
class CommandSampleListener(CommandListener): def __init__(self, iot_device: IotDevice): """ Pass an IotDevice instance. """ self.device = iot_device def on_command(self, request_id, service_id, command_name, paras): logger.info('on_command requestId: ' + request_id) # Process the command. logger.info('begin to handle command') """ code here """ logger.info(str(paras)) # Respond to the command. command_rsp = CommandRsp() command_rsp.result_code = 0 command_rsp.response_name = command_name command_rsp.paras = {"content": "Hello Huawei"} self.device.get_client().response_command(request_id, command_rsp) def run(): < create device code here ... > # Set the listener. device.get_client().set_command_listener(CommandSampleListener(device)) if device.connect() != 0: logger.error('init failed') return while True: time.sleep(5) - After a command is delivered from the platform to the device, the code log is shown as in the following figure.
Figure 12 Command delivery in Python
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot