def yamltolosant(filename): """ change these five field based on you losant account """ email = "YOUR LOSANT EMAIL ID" password = "******" applicationId = 'YOUR APPLICATIOIN ID ' key = 'APPLICATION KEY' secret = 'APPLICATION SECRET KEY' op_data = {} client = Client() app_responce = client.auth.authenticate_user(credentials={'email':email, 'password':password}) app_token = app_responce['token'] app_client = Client(auth_token=app_token, url="https://api.losant.com") mydevice = {"name": "My New Device ", "description": "Description of my new device", "tags": [{"key": "TagKey", "value": "TagValue"}], "attributes": [{"name": "asset", "dataType": "string"}, {"name":"logger", "dataType":"string"}, {"name":"channel", "dataType":"string"}, {"name":"cycle", "dataType":"number"}, {"name":"class", "dataType":"string"}, {"name":"device_config", "dataType":"string"}, {"name":"ipaddr", "dataType":"string"}, {"name":"unit", "dataType":"number"}, {"name":"registers", "dataType":"string"}, {"name":"registers_to_log", "dataType":"string"}, {"name":"publish", "dataType":"boolean"}], "deviceClass": "standalone" } with open(filename) as f: data = yaml.load(f) for device in data['devices']: mydevice["name"] = device["asset"]+"name" new_device = app_client.devices.post(applicationId=applicationId, device=mydevice) device_id = new_device['deviceId'] op_data[mydevice["name"]] = device_id creds = { 'deviceId': device_id, 'key': key, 'secret': secret } response = client.auth.authenticate_device(credentials=creds) client.auth_token = response['token'] app_id = response['applicationId'] device["registers_to_log"] = str(device['registers_to_log']) device["registers"] = str(device['registers']) state = dict(data=device) response = client.device.send_state(deviceId=device_id, applicationId=app_id, deviceState=state) print(response) op_data = json.dumps(op_data) with open("new_device_info.json", "w") as f: f.write(op_data) print("New devices created the details are in new_device_info.json file")
def test_nested_query_param_call(self, mock): expected_body = {"count": 0, "items": []} expected_qs = { "_links": ["true"], "_actions": ["false"], "_embedded": ["true"], "tagFilter[0][key]": ["key2"], "tagFilter[1][value]": ["value1"], "tagFilter[1][key]": ["key1"], "tagFilter[2][value]": ["value2"] } mock.get("https://api.losant.com/applications/anapp/devices", json=expected_body) resp = Client("a token").devices.get(applicationId="anapp", tagFilter=[ { "key": "key2" }, { "key": "key1", "value": "value1" }, { "value": "value2" }, ]) self.assertEqual(resp, expected_body) request = mock.request_history[0] parsed_url = urlparse(request.url) self.assertEqual(expected_qs, parse_qs(parsed_url.query)) self.assertEqual(parsed_url.path, "/applications/anapp/devices") self.assertEqual(request.headers["Accept"], "application/json") self.assertEqual(request.headers["Authorization"], "Bearer a token") self.assertIsNone(request.body)
def test_failure_call(self, mock): expected_body = {"message": "Unauthorized", "type": "Unauthorized"} expected_qs = { "_links": ["true"], "_actions": ["false"], "_embedded": ["true"] } mock.post("https://api.losant.com/auth/user", json=expected_body, status_code=401) creds = {"email": "*****@*****.**", "password": "******"} with self.assertRaises(LosantError) as cm: Client().auth.authenticate_user(credentials=creds) the_exception = cm.exception self.assertEqual(the_exception.status, 401) self.assertEqual(the_exception.data, expected_body) request = mock.request_history[0] parsed_url = urlparse(request.url) self.assertEqual(expected_qs, parse_qs(parsed_url.query)) self.assertEqual(parsed_url.path, "/auth/user") self.assertEqual(request.headers["Accept"], "application/json") self.assertNotIn("Authorization", request.headers) self.assertEqual(json.loads(request.body), creds)
def test_basic_call_with_auth(self, mock): expected_body = { "name": "Python Client Testing", "_type": "device", "applicationId": "anapp", "id": "adevice" } expected_qs = { "_links": ["true"], "_actions": ["false"], "_embedded": ["true"] } mock.get("https://api.losant.com/applications/anapp/devices/adevice", json=expected_body) resp = Client("a token").device.get(applicationId="anapp", deviceId="adevice") self.assertEqual(resp, expected_body) request = mock.request_history[0] parsed_url = urlparse(request.url) self.assertEqual(expected_qs, parse_qs(parsed_url.query)) self.assertEqual(parsed_url.path, "/applications/anapp/devices/adevice") self.assertEqual(request.headers["Accept"], "application/json") self.assertEqual(request.headers["Authorization"], "Bearer a token") self.assertIsNone(request.body)
def test_json_query_param_call(self, mock): expected_body = {"count": 0, "items": []} expected_qs = { "_links": ["true"], "_actions": ["false"], "_embedded": ["true"], "query": ['{"$and": [{"level": "info"}, {"state": "new"}]}'] } mock.get("https://api.losant.com/applications/anapp/events", json=expected_body) resp = Client("a token").events.get( applicationId="anapp", query={"$and": [{ "level": "info" }, { "state": "new" }]}) self.assertEqual(resp, expected_body) request = mock.request_history[0] parsed_url = urlparse(request.url) self.assertEqual(expected_qs, parse_qs(parsed_url.query)) self.assertEqual(parsed_url.path, "/applications/anapp/events") self.assertEqual(request.headers["Accept"], "application/json") self.assertEqual(request.headers["Authorization"], "Bearer a token") self.assertIsNone(request.body)
def test_basic_call_no_auth(self, mock): expected_body = {"token": "a token", "userId": "theUserId"} expected_qs = { "_links": ["true"], "_actions": ["false"], "_embedded": ["true"] } creds = {"email": "*****@*****.**", "password": "******"} mock.post("https://api.losant.com/auth/user", json=expected_body) resp = Client().auth.authenticate_user(credentials=creds) self.assertEqual(resp, expected_body) request = mock.request_history[0] parsed_url = urlparse(request.url) self.assertEqual(expected_qs, parse_qs(parsed_url.query)) self.assertEqual(parsed_url.path, "/auth/user") self.assertEqual(parsed_url.path, "/auth/user") self.assertEqual(request.headers["Accept"], "application/json") self.assertEqual(request.headers["Content-Type"], "application/json") self.assertNotIn("Authorization", request.headers) self.assertEqual(json.loads(request.body), creds)
setColor(deviceId, new_color) if(command["name"] == "btnPressedAnim"): animColor = 'red' # assume failure if(command["payload"] and command["payload"]["status"] == "succeeded"): animColor = 'green' #yay! statusBlink(animColor, 150, 7) # Construct device device = Device(losantconfig.MY_DEVICE_ID, losantconfig.ACCESS_KEY, losantconfig.ACCESS_SECRET) # Listen for commands. device.add_event_observer("command", on_command) # Connect to Losant. device.connect(blocking=False) #### REST setup ### client = Client() creds = { 'deviceId': losantconfig.MY_DEVICE_ID, 'key': losantconfig.ACCESS_KEY, 'secret': losantconfig.ACCESS_SECRET } # Connect via REST and save the response for future connections rest_response = client.auth.authenticate_device(credentials=creds) client.auth_token = rest_response['token'] app_id = rest_response['applicationId'] #### GPIO setup #### GPIO.setmode(GPIO.BCM) GPIO.setup(losantconfig.BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(losantconfig.KEY_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
if (command["payload"] and command["payload"]["status"] == "succeeded"): animColor = 'green' #yay! statusBlink(animColor, 150, 7) # Construct device device = Device(losantconfig.MY_DEVICE_ID, losantconfig.ACCESS_KEY, losantconfig.ACCESS_SECRET) # Listen for commands. device.add_event_observer("command", on_command) # Connect to Losant. device.connect(blocking=False) #### REST setup ### client = Client() creds = { 'deviceId': losantconfig.MY_DEVICE_ID, 'key': losantconfig.ACCESS_KEY, 'secret': losantconfig.ACCESS_SECRET } # Connect via REST and save the response for future connections rest_response = client.auth.authenticate_device(credentials=creds) client.auth_token = rest_response['token'] app_id = rest_response['applicationId'] #### GPIO setup #### GPIO.setmode(GPIO.BCM) GPIO.setup(losantconfig.BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(losantconfig.KEY_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
from losantrest import Client client = Client('my_token') result = client.devices.get(applicationId='myAppId') print(result) """ Example result { 'page': 0, 'sortField': 'name', '_type': 'devices', 'totalCount': 1, '_links': { 'self': { 'href': '/applications/myAppId/devices' }, 'application': { 'href': '/applications/myAppId' } }, 'perPage': 100, 'count': 1, 'applicationId': 'myAppId', 'items': [{ 'deviceClass': 'standalone', '_type': 'device', 'connectionInfo': { 'connected': 0, 'time': '2016-06-01T17:16:02.324Z' }, '_links': { 'devices': {'href': '/applications/myAppId/devices' }, 'self': { 'href': '/applications/myAppId/devices/myDevId' }, 'application': { 'href': '/applications/myAppId' } }, 'attributes': [ { 'name': 'voltage', 'dataType': 'number' }, { 'name': 'isOn', 'dataType': 'boolean' }
from losantrest import Client client = Client() user_response = client.auth.authenticate_user(credentials={ 'email': '*****@*****.**', 'password': '******' }) print(user_response) """ Example user result { 'token': 'an auth token string', 'userId': 'theUserId' } """ device_response = client.auth.authenticate_device(credentials={ 'deviceId': 'myDeviceId', 'key': 'my_app_access_key', 'secret': 'my_app_access_secret' }) print(device_response) """ Example device result { 'applicationId': 'myAppId', 'token': 'an auth token string', 'restricted': False, 'deviceId': 'myDeviceId',