Package: vl-mqtt-client
ViraLink MQTT and HTTP client Python SDKViraLink is an IoT platform for data collection, processing, visualization, and device management.
This project ia a Python library that provides convenient client SDK for both Device andGatewayAPIs.This repository is the fork ofthingsboard-python-sdkSDK supports:Unencrypted and encrypted (TLS v1.2) connectionQoS 0 and 1 (MQTT only)Automatic reconnectAllDevice MQTTAPIs provided by ViraLinkAllGateway MQTTAPIs provided by ViraLinkMostDevice HTTPAPIs provided by ViraLinkDevice Claiming and Firmware updates are not supported yet.TheDevice MQTTAPI and theGateway MQTTAPI are base on the Paho MQTT library. TheDevice HTTPAPI is based on the Requests library.InstallationTo install using pip:pip3installvl-mqtt-clientGetting StartedClient initialization and telemetry publishingMQTTfromvl_device_mqttimportVLDeviceMqttClient,VLPublishInfotelemetry={"temperature":41.9,"enabled":False,"currentFirmwareVersion":"v1.2.2"}client=VLDeviceMqttClient("console.viralink.io","A1_TEST_TOKEN")# Connect to ViraLinkclient.connect()# Sending telemetry without checking the delivery statusclient.send_telemetry(telemetry)# Sending telemetry and checking the delivery status (QoS = 1 by default)result=client.send_telemetry(telemetry)# get is a blocking call that awaits delivery statussuccess=result.get()==VLPublishInfo.VL_ERR_SUCCESS# Disconnect from ViraLinkclient.disconnect()`Using Device APIsVLDeviceMqttClientprovides access to Device MQTT APIs of ViraLink platform. It allows to publish telemetry and attribute updates, subscribe to attribute changes, send and receive RPC commands, etc. UseVLHTTPClientfor the Device HTTP API.Subscription to attributesMQTTimporttimefromvl_device_mqttimportVLDeviceMqttClientdefon_attributes_change(client,result,exception):ifexceptionisnotNone:print("Exception: "+str(exception))else:print(result)client=VLDeviceMqttClient("console.viralink.io","A1_TEST_TOKEN")client.connect()client.subscribe_to_attribute("uploadFrequency",on_attributes_change)client.subscribe_to_all_attributes(on_attributes_change)whileTrue:time.sleep(1)HTTPNote: The HTTP API only allows a subscription to updates for all attribute.fromvl_device_httpimportVLHTTPClientclient=VLHTTPClient('https://console.viralink.io','secret-token')defcallback(data):print(data)# ...# Subscribeclient.subscribe('attributes',callback)# Unsubscribeclient.unsubscribe('attributes')Telemetry pack sendingMQTTimportloggingfromvl_device_mqttimportVLDeviceMqttClient,VLPublishInfoimporttimetelemetry_with_ts={"ts":int(round(time.time()*1000)),"values":{"temperature":42.1,"humidity":70}}client=VLDeviceMqttClient("console.viralink.io","A1_TEST_TOKEN")# we set maximum amount of messages sent to send them at the same time. it may stress memory but increases performanceclient.max_inflight_messages_set(100)client.connect()results=[]result=Trueforiinrange(0,100):results.append(client.send_telemetry(telemetry_with_ts))fortmp_resultinresults:result&=tmp_result.get()==VLPublishInfo.VL_ERR_SUCCESSprint("Result "+str(result))client.disconnect()HTTPUnsupported, the HTTP API does not allow the packing of values.Request attributes from serverMQTTimportloggingimporttimefromvl_device_mqttimportVLDeviceMqttClientdefon_attributes_change(client,result,exception):ifexceptionisnotNone:print("Exception: "+str(exception))else:print(result)client=VLDeviceMqttClient("console.viralink.io","A1_TEST_TOKEN")client.connect()client.request_attributes(["configuration","targetFirmwareVersion"],callback=on_attributes_change)whileTrue:time.sleep(1)HTTPfromvl_device_httpimportVLHTTPClientclient=VLHTTPClient('https://console.viralink.io','secret-token')client_keys=['attr1','attr2']shared_keys=['shared1','shared2']data=client.request_attributes(client_keys=client_keys,shared_keys=shared_keys)Respond to server RPC callMQTTimportpsutilimporttimeimportloggingfromvl_device_mqttimportVLDeviceMqttClient# dependently of request method we send different data backdefon_server_side_rpc_request(client,request_id,request_body):print(request_id,request_body)ifrequest_body["method"]=="getCPULoad":client.send_rpc_reply(request_id,{"CPU percent":psutil.cpu_percent()})elifrequest_body["method"]=="getMemoryUsage":client.send_rpc_reply(request_id,{"Memory":psutil.virtual_memory().percent})client=VLDeviceMqttClient("console.viralink.io","A1_TEST_TOKEN")client.set_server_side_rpc_request_handler(on_server_side_rpc_request)client.connect()whileTrue:time.sleep(1)HTTPfromvl_device_httpimportVLHTTPClientclient=VLHTTPClient('https://console.viralink.io','secret-token')defcallback(data):rpc_id=data['id']# ... do something with data['params'] and data['method']...response_params={'result':1}client.send_rpc(name='rpc_response',rpc_id=rpc_id,params=response_params)# Subscribeclient.subscribe('rpc',callback)# Unsubscribeclient.unsubscribe('rpc')Using Gateway APIsVLGatewayMqttClientextendsVLDeviceMqttClient, thus has access to all it's APIs as a regular device.
Besides, gateway is able to represent multiple devices connected to it. For example, sending telemetry or attributes on behalf of other, constrained, device. See more info about the gateway here:Telemetry and attributes sendingimporttimefromvl_gateway_mqttimportVLGatewayMqttClientgateway=VLGatewayMqttClient("console.viralink.io","GATEWAY_TEST_TOKEN")gateway.connect()gateway.gw_connect_device("Test Device A1")gateway.gw_send_telemetry("Test Device A1",{"ts":int(round(time.time()*1000)),"values":{"temperature":42.2}})gateway.gw_send_attributes("Test Device A1",{"firmwareVersion":"2.3.1"})gateway.gw_disconnect_device("Test Device A1")gateway.disconnect()Request attributesimportloggingimporttimefromvl_gateway_mqttimportVLGatewayMqttClientdefcallback(result,exception):ifexceptionisnotNone:print("Exception: "+str(exception))else:print(result)gateway=VLGatewayMqttClient("console.viralink.io","TEST_GATEWAY_TOKEN")gateway.connect()gateway.gw_request_shared_attributes("Test Device A1",["temperature"],callback)whileTrue:time.sleep(1)Respond to RPCimporttimefromvl_gateway_mqttimportVLGatewayMqttClientimportpsutildefrpc_request_response(client,request_id,request_body):# request body contains id, method and other parametersprint(request_body)method=request_body["data"]["method"]device=request_body["device"]req_id=request_body["data"]["id"]# dependently of request method we send different data backifmethod=='getCPULoad':gateway.gw_send_rpc_reply(device,req_id,{"CPU load":psutil.cpu_percent()})elifmethod=='getMemoryLoad':gateway.gw_send_rpc_reply(device,req_id,{"Memory":psutil.virtual_memory().percent})else:print('Unknown method: '+method)gateway=VLGatewayMqttClient("console.viralink.io","TEST_GATEWAY_TOKEN")gateway.connect()# now rpc_request_response will process rpc requests from serversgateway.gw_set_server_side_rpc_request_handler(rpc_request_response)# without device connection it is impossible to get any messagesgateway.gw_connect_device("Test Device A1")whileTrue:time.sleep(1)Other ExamplesThere are more examples for bothdeviceandgatewayin correspondingfolders.SupportTelegramLicensesThis project is released underApache 2.0 License.