Using the Esper Python SDK to Automate Device Tagging

Author

James Schaefer

This post is written by James Schaefer

Device tags and friendly names are useful to add to your devices for more effective  fleet management. You can search by tags and names, and more importantly you can execute actions on the devices using tags and friendly names through our API and Python SDK. However, using the Esper Console to manually enter tags and device names is time consuming, as they need to be added to each device individually through the Console. A batch entry option is not currently available, but can be implemented by using Python. At times, you may also want to switch a Group or long list of devices either out of or into Kiosk mode. In this tutorial, we’ll show you how to use the Esper REST API to add or modify tags to introduce you to our APIs, and then we’ll walk through a Python script where you can switch a device in and out of Kiosk mode.

Using Esper’s REST API

To try out our REST APIs, we recommend using an API development tool such as Postman

Let’s start with Retrieving Device Information Using “GET”. To do this, you’ll need your endpoint name (e.g. foobar if your Esper cloud URL is https://foobar.esper.cloud), your Enterprise ID and API key (found in the Console under API Key Management), and finally the Device ID (found within the URL of a device summary)

 import requests
 url='https://{endpoint_name}-api.esper.cloud/api/enterprise/{enterprise_id}/device/{device_id}/?&format=json'
 headers={
       "Authorization": f"Bearer {{api_key}}”,
        "Content-Type": "application/json",
 }
 resp=requests.get(url, headers=headers)
 json_resp = resp.json()
 print(json_resp) 

Executing this command will return the following information. This can be used to track network status, policy and group assignment, and the current tags and aliases assigned to a device. More information on device retrieval can be found in our API documentation.

Next, we will modify Device Tags Using “PATCH”. 

 import requests
 url='https://{endpoint_name}-api.esper.cloud/api/enterprise/{enterprise_id}/device/{device_id}/?&format=json'
 headers={
       "Authorization": f"Bearer {{api_key}}”,
        "Content-Type": "application/json",
 }
 requests.patch(url, headers=headers, data=json.dumps({"tags": [‘A’,’B’,’C’]}))
 Tags can be added and removed using the following format,
 "tags": [‘A’,’B’,’C’]
 "tags": [‘A’,’B’]
 "tags": [‘A’]
 "tags": [] 

A successful response is indicated by a 2xx status code. A 204 or 200 status code may indicate that the payload format is incorrect. Note that a device does not need to be online in order to alter tags.

Using Python with The EsperClient and Commands Library

Next, let’s move to our Python SDK.

Requirements: pip install esperclient

The Esper client is downloadable at https://pypi.org/project/esperclient/

The first thing you need to do is set up a configuration for the Esper client. For that, you’ll need your Enterprise_ID, API_Key, and Endpoint URL. 

 import esperclient
 configuration = esperclient.Configuration()
 configuration.host = ’https://{my_endpoint}-api.esper.cloud’
 configuration.api_key["Authorization"] = ’AbCDeFgHIJkLmNOpQrstUVwXYZ1234’
 configuration.api_key_prefix["Authorization"] = ’Bearer’
 configuration.enterprise_id = ’12345678-9101-1121-3141-516171819202’
 Below are two functions for toggling a device into and out of kiosk mode, and for changing a device alias. 
 A device will need to be online in order to issue a command. 
 def toggleKioskMode(deviceid, appToUse, isKiosk, configuration, enterprise_id):
    """Toggles Kiosk Mode On/Off"""
    api_instance = esperclient.CommandsV2Api(esperclient.ApiClient(configuration))
    if isKiosk:
        command_args = esperclient.V0CommandArgs(package_name=appToUse)
    else:
        command_args = {}
    command = esperclient.V0CommandRequest(
        enterprise=enterprise_id,
        command_type="DEVICE",
        device_type="all",
        devices=[deviceid],
        command="SET_KIOSK_APP",
        command_args=command_args,
    )
    api_response = api_instance.create_command(enterprise_id, command)
    response = api_instance.get_command_request_status(
       enterprise_id, api_response.id
    )
    status = response.results[0].state
    status = waitForCommandToFinish(api_response.id)
    return status
 def setdevicename(deviceid, devicename, enterprise_id, configuration):
    api_instance = esperclient.CommandsV2Api(esperclient.ApiClient(configuration))
    args = esperclient.V0CommandArgs(device_alias_name=devicename)
    command = esperclient.V0CommandRequest(
        command_type="DEVICE",
        devices=[deviceid],
        command="UPDATE_DEVICE_CONFIG",
        command_args=args,
        device_type="all",
    )
    api_response = api_instance.create_command(enterprise_id, command)
    response = api_instance.get_command_request_status(enterprise_id, api_response.id)
    status = response.results[0].state
    status = waitForCommandToFinish(api_response.id)
    return status 

We can wait for a response with the following function.

 def waitForCommandToFinish(request_id, enterprise_id):
    api_instance = getCommandsApiInstance()
    response = api_instance.get_command_request_status(enterprise_id, request_id)
    status = response.results[0]
    while status.state not in [
        "Command Success",
        "Command Failure",
        "Command TimeOut",
        "Command Cancelled",
        "Command Queued",
    ]:
        response = api_instance.get_command_request_status(enterprise_id, request_id)
        status = response.results[0]
        time.sleep(1)
    return status 

Initially, the request will be queued and will be checked subsequently until a success, failure, cancelled, or timeout response is retrieved.  

Conclusion

Throughout this article we’ve shown you how to use our REST API to set tags for a device, use our Python SDK to switch a device in and out of Kiosk mode, and how to apply a device- friendly name. You can apply this to a set of devices, or use our API to query a group and set you up to perform these actions across a large set of devices. 

In our next installment, we will take this concept to the next level and make it even easier for you to perform these actions using Esper and our Python SDK. In the meantime, be sure to check out our REST API and install our Python SDK.

0