Package: devicehive
DevicehiveThe simplest way to create a client is to useDeviceHiveApiclass.
If you need to handle server events such ashandle_command_insert,handle_command_updateorhandle_notificationyou’ll have to
extendHandlerclass and useDeviceHiveclass for it.Creating a client using DeviceHiveApi classFirst of all you need to createDeviceHiveApiobject. Then you can
use this object for for API calls.Example:fromdevicehiveimportDeviceHiveApiurl='http://playground.devicehive.com/api/rest'refresh_token='SOME_REFRESH_TOKEN'device_hive_api=DeviceHiveApi(url,refresh_token=refresh_token)Websocket protocolIf you want to useWebsocketprotocol you need only to specify the
url:url='ws://playground.devicehive.com/api/websocket'AuthenticationThere are three ways of initial authentication:Using refresh tokenUsing access tokenUsing login and passwordExamples:fromdevicehiveimportDeviceHiveApiurl='ws://playground.devicehive.com/api/websocket'device_hive_api=DeviceHiveApi(url,refresh_token='SOME_REFRESH_TOKEN')fromdevicehiveimportDeviceHiveApiurl='ws://playground.devicehive.com/api/websocket'device_hive_api=DeviceHiveApi(url,access_token='SOME_ACCESS_TOKEN')fromdevicehiveimportDeviceHiveApiurl='ws://playground.devicehive.com/api/websocket'device_hive_api=DeviceHiveApi(url,login='SOME_LOGIN',password='SOME_PASSWORD')Infoget_info()method returnsdictwith the next fields:api_versionserver_timestamprest_server_urlwebsocket_server_urlget_cluster_info()method returnsdictwith the next fields:bootstrap.serverszookeeper.connectExample:fromdevicehiveimportDeviceHiveApiurl='http://playground.devicehive.com/api/rest'refresh_token='SOME_REFRESH_TOKEN'device_hive_api=DeviceHiveApi(url,refresh_token=refresh_token)info=device_hive_api.get_info()print(info)cluster_info=device_hive_api.get_cluster_info()print(cluster_info)Propertiesget_property(name)method returnsdictwith the next fields:entity_versionnamevalueset_property(name, value)method returns entity version.delete_property(name)method does not return anything.Example:fromdevicehiveimportDeviceHiveApiurl='http://playground.devicehive.com/api/rest'refresh_token='SOME_REFRESH_TOKEN'device_hive_api=DeviceHiveApi(url,refresh_token=refresh_token)name='user.login.lastTimeoutSent'entity_version=device_hive_api.set_property(name,'value')print(entity_version)prop=device_hive_api.get_property(name)print(prop)device_hive_api.delete_property(name)Tokenscreate_token(user_id, expiration, actions, network_ids, device_ids)method returnsdictwith the next fields:access_tokenrefresh_tokenonlyuser_idis required.refresh_token()method refreshes the access token and returns it.Example:fromdevicehiveimportDeviceHiveApiurl='http://playground.devicehive.com/api/rest'refresh_token='SOME_REFRESH_TOKEN'device_hive_api=DeviceHiveApi(url,refresh_token=refresh_token)tokens=device_hive_api.create_token(1)print(tokens)access_token=device_hive_api.refresh_token()print(access_token)Deviceslist_devices(name, name_pattern, network_id, network_name, sort_field, sort_order, take, skip)method returns list ofDeviceobjects. All args are optional.get_device(device_id)method returnsDeviceobject.put_device(device_id, name, data, network_id, is_blocked)method
returnsDeviceobject. Onlydevice_idis required.list_commands(device_id, start, end, command, status, sort_field, sort_order, take, skip)method returns list ofCommandobjects. Onlydevice_idis
required.send_command(device_id, command_name, parameters, lifetime, timestamp, status, result)method returnsCommandobject. Onlydevice_idandcommand_nameare required.list_notifications(device_id, start, end, notification, sort_field, sort_order, take, skip)method returns list ofNotificationobject. Onlydevice_idis
required.send_notification(device_id, notification_name, parameters, timestamp)method returnsNotificationobject. Onlydevice_idandnotification_nameare required.Device objectProperties:id(read only)namedatanetwork_iddevice_type_idis_blockedMethods:save()method does not return anything.remove()method does not return anything.list_commands(start, end, command, status, sort_field, sort_order, take, skip)method returns list ofCommandobjects. All args are optional.send_command(command_name, parameters, lifetime, timestamp, status, result)method returnsCommandobject. Onlycommand_nameis required.list_notifications(start, end, notification, sort_field, sort_order, take, skip)method returns list ofNotificationobjects. All args are
optional.send_notification(notification_name, parameters, timestamp)method returnsNotificationobject. Onlynotification_nameis
required.Command objectProperties:id(read only)user_id(read only)command(read only)parameters(read only)lifetime(read only)timestamp(read only)last_updated(read only)statusresultMethods:save()method does not return anything.Notification objectProperties:device_id(read only)id(read only)notification(read only)parameters(read only)timestamp(read only)Example:fromdevicehiveimportDeviceHiveApiurl='http://playground.devicehive.com/api/rest'refresh_token='SOME_REFRESH_TOKEN'device_hive_api=DeviceHiveApi(url,refresh_token=refresh_token)device_id='example-device'device=device_hive_api.put_device(device_id)device.name='new-device-name'device.data={'key':'value'}device.save()devices=device_hive_api.list_devices()fordeviceindevices:print('Device:%s, name:%s, data:%s'%(device.id,device.name,device.data))device.remove()Networkslist_networks(name, name_pattern, sort_field, sort_order, take, skip)method returns list ofNetworkobjects. All args are optional.get_network(network_id)method returnsNetworkobject.create_network(name, description)method returnsNetworkobject.Network objectProperties:id(read only)namedescriptionMethods:save()method does not return anything.remove(force)method does not return anything. All args are
optional.Example:fromdevicehiveimportDeviceHiveApiurl='http://playground.devicehive.com/api/rest'refresh_token='SOME_REFRESH_TOKEN'device_hive_api=DeviceHiveApi(url,refresh_token=refresh_token)network_name='example-name'network_description='example-description'network=device_hive_api.create_network(network_name,network_description)print(network.name)Device typeslist_device_types(name, name_pattern, sort_field, sort_order, take, skip)method returns list ofDeviceTypeobjects. All args are optional.get_device_type(device_type_id)method returnsDeviceTypeobject.create_device_type(name, description)method returnsDeviceTypeobject.DeviceType objectProperties:id(read only)namedescriptionMethods:save()method does not return anything.remove(force)method does not return anything. All args are
optional.Example:fromdevicehiveimportDeviceHiveApiurl='http://playground.devicehive.com/api/rest'refresh_token='SOME_REFRESH_TOKEN'device_hive_api=DeviceHiveApi(url,refresh_token=refresh_token)device_type_name='example-name'device_type_description='example-description'device_type=device_hive_api.create_device_type(device_type_name,device_type_description)print(device_type.name)Userslist_users(login, login_pattern, role, status, sort_field, sort_order, take, skip)method returns list ofUserobjects. All args are optional.get_current_user()method returnsUserobject.get_user(user_id)method returnsUserobject.create_user(self, login, password, role, data, all_device_types_available)method returnsUserobject.User objectProperties:id(read only)login(read only)last_login(read only)intro_reviewed(read only)all_device_types_available(read only)rolestatusdataMethods:save()method does not return anything.update_password(password)method does not return anything.remove()method does not return anything.list_networks()method Returns list ofNetworkobjects.list_device_types()method Returns list ofDeviceTypeobjects.assign_network(network_id)method does not return anything.unassign_network(network_id)method does not return anything.assign_device_type(device_type_id)method does not return
anything.unassign_device_type(device_type_id)method does not return
anything.allow_all_device_types()method does not return anything.disallow_all_device_types()method does not return anything.Example:fromdevicehiveimportDeviceHiveApifromdevicehive.userimportUserurl='http://playground.devicehive.com/api/rest'refresh_token='SOME_REFRESH_TOKEN'device_hive_api=DeviceHiveApi(url,refresh_token=refresh_token)login='example-login'password='example-password'role=User.CLIENT_ROLEdata={'key':'value'}user=device_hive_api.create_user(login,password,role,data)print(user.login)Creating a client using DeviceHive classFirst of all you need to create customHandlerclass.Example of creating customHandlerclass:fromdevicehiveimportHandlerclassSimpleHandler(Handler):defhandle_connect(self):info=self.api.get_info()print(info)self.api.disconnect()handle_connectis the only one required method. If you want to
handle server events you’ll heed to implementhandle_command_insert,handle_command_updateandhandle_notificationmethods.Example:fromdevicehiveimportHandlerclassSimpleHandler(Handler):defhandle_connect(self):device_ids=['example-device-1','example-device-2']fordevice_idindevice_ids:device=self.api.put_device(device_id)device.subscribe_insert_commands()device.subscribe_update_commands()device.subscribe_notifications()defhandle_command_insert(self,command):print(command.command)defhandle_command_update(self,command):print(command.command)defhandle_notification(self,notification):print(notification.notification)The second step is to useDeviceHiveclass for creating connection
to the server.Example:fromdevicehiveimportHandlerfromdevicehiveimportDeviceHiveclassSimpleHandler(Handler):defhandle_connect(self):device_ids=['example-device-1','example-device-2']fordevice_idindevice_ids:device=self.api.put_device(device_id)device.subscribe_insert_commands()device.subscribe_update_commands()device.subscribe_notifications()defhandle_command_insert(self,command):print(command.command)defhandle_command_update(self,command):print(command.command)defhandle_notification(self,notification):print(notification.notification)url='http://playground.devicehive.com/api/rest'refresh_token='SOME_REFRESH_TOKEN'dh=DeviceHive(SimpleHandler)dh.connect(url,refresh_token=refresh_token)Custom handler argsIf you need to initialize your handler you can do it the next way:fromdevicehiveimportHandlerfromdevicehiveimportDeviceHiveclassSimpleHandler(Handler):def__init__(self,api,some_arg,some_kwarg):Handler.__init__(self,api)self._some_arg=some_argself._some_kwarg=some_kwargdefhandle_connect(self):info=self.api.get_info()print(info)self.api.disconnect()device_hive=DeviceHive(SimpleHandler,'some_arg',some_kwarg='some_kwarg')Websocket protocolIf you want to useWebsocketprotocol you need only to specify the
url:url='ws://playground.devicehive.com/api/websocket'AuthenticationThere are three ways of initial authentication:Using refresh tokenUsing access tokenUsing login and passwordExamples:url='ws://playground.devicehive.com/api/websocket'device_hive.connect(url,refresh_token='SOME_REFRESH_TOKEN')url='ws://playground.devicehive.com/api/websocket'device_hive.connect(url,access_token='SOME_ACCESS_TOKEN')url='ws://playground.devicehive.com/api/websocket'device_hive.connect(url,login='SOME_LOGIN',password='SOME_PASSWORD')APIAll api calls may be done viaapiobject. This object available
inside custom handler withself.apiproperty.API infoself.api.get_info()method returnsdict.get_infomethod ofDeviceHiveApiclass is the wrapper on top of this call.self.api.get_cluster_info()method returnsdict.get_cluster_infomethod ofDeviceHiveApiclass is the wrapper on
top of this call.See the description ofDeviceHiveApiinfomethods for
more details.Example:fromdevicehiveimportHandlerclassSimpleHandler(Handler):defhandle_connect(self):info=self.api.get_info()print(info)cluster_info=self.api.get_cluster_info()print(cluster_info)self.api.disconnect()API propertiesself.api.get_property(name)method returnsdict.get_propertymethod ofDeviceHiveApiclass is the wrapper on top
of this call.self.api.set_property(name, value)method returns entity version.set_propertymethod ofDeviceHiveApiclass is the wrapper on top
of this call.self.api.delete_property(name)method does not return anything.delete_propertymethod ofDeviceHiveApiclass is the wrapper on
top of this call.See the description ofDeviceHiveApipropertymethods for more details.Example:fromdevicehiveimportHandlerclassSimpleHandler(Handler):defhandle_connect(self):name='user.login.lastTimeoutSent'prop=self.api.get_property(name)print(prop)entity_version=self.api.get_property(name,'value')print(entity_version)self.api.delete_property(name)self.api.disconnect()API tokensself.api.create_token(user_id, expiration, actions, network_ids, device_ids)method returnsdict.create_tokenmethod ofDeviceHiveApiclass is the wrapper on top of this call.self.api.refresh_token()method refreshes the access token and
returns it.refresh_tokenmethod ofDeviceHiveApiclass is the
wrapper on top of this call.See the description ofDeviceHiveApitokenmethods for
more details.Example:fromdevicehiveimportHandlerclassSimpleHandler(Handler):defhandle_connect(self):tokens=self.api.create_token(1)print(tokens)access_token=self.api.refresh_token()print(access_token)self.api.disconnect()API commands subscriptionself.api.subscribe_insert_commands(device_id, network_ids, device_type_ids, names, timestamp)method returnsCommandsSubscriptionobject.self.api.subscribe_update_commands(device_id, network_ids, device_type_ids, names, timestamp)method returnsCommandsSubscriptionobject.API CommandsSubscription objectProperties:id(read only)Methods:remove()method does not return anything.Example:fromdevicehiveimportHandlerclassSimpleHandler(Handler):insert_subscription=Noneupdate_subscription=Nonedefhandle_connect(self):device_id='example-device'device=self.api.put_device(device_id)command_name='example-command'self.insert_subscription=self.api.subscribe_insert_commands(device_id,[command_name])self.update_subscription=self.api.subscribe_update_commands(device_id,[command_name])command=device.send_command(command_name)command.status='new-status'command.save()defhandle_command_insert(self,command):print('Command insert:%s, status:%s.'%(command.command,command.status))defhandle_command_update(self,command):print('Command update:%s, status:%s.'%(command.command,command.status))self.insert_subscription.remove()self.update_subscription.remove()API notifications subscriptionself.api.subscribe_notifications(device_id, network_ids, device_type_ids, names, timestamp)method returnsNotificationsSubscriptionobject.API NotificationsSubscription objectProperties:id(read only)Methods:remove()method does not return anything.Example:fromdevicehiveimportHandlerclassSimpleHandler(Handler):notification_subscription=Nonedefhandle_connect(self):device_id='example-device'device=self.api.put_device(device_id)notification_name='example-notification'self.notification_subscription=self.api.subscribe_notifications(device_id,[notification_name])device.send_notification(notification_name)defhandle_notification(self,notification):print('Notification:%s.'%notification.notification)self.notification_subscription.remove()API devicesself.api.list_devices(name, name_pattern, network_id, network_name, sort_field, sort_order, take, skip)method returns list ofDeviceobjects.list_devicesmethod ofDeviceHiveApiclass is the wrapper on top of this call.self.api.get_device(device_id)method returnsDeviceobject.get_devicemethod ofDeviceHiveApiclass is the wrapper on top
of this call.self.api.put_device(device_id, name, data, network_id, device_type_id, is_blocked)method does not return anything.put_devicemethod ofDeviceHiveApiclass is the wrapper on top of this call.self.api.list_commands(device_id, start, end, command, status, sort_field, sort_order, take, skip)method returns list ofCommandobjects.list_commandsmethod ofDeviceHiveApiclass is the wrapper on top of this call.self.api.send_command(device_id, command_name, parameters, lifetime, timestamp, status, result)method returnsCommandobject.send_commandmethod ofDeviceHiveApiclass is the wrapper on top of this call.self.api.list_notifications(device_id, start, end, notification, sort_field, sort_order, take, skip)method returns list ofNotificationobjects.list_notificationsmethod ofDeviceHiveApiclass is the wrapper on top of this call.self.api.send_notification(device_id, notification_name, parameters, timestamp)method returnsNotificationobject.send_notificationmethod ofDeviceHiveApiclass is the wrapper on top of this call.See the description ofDeviceHiveApidevicemethods
for more details.API device objectAPI device object has the same properties asdevice
object.API device object has all methods fromdevice
objectand extends these methods with:subscribe_insert_commands(names, timestamp)method returnsCommandsSubscriptionobject. All args are optional.subscribe_update_commands(names, timestamp)method returnsCommandsSubscriptionobject. All args are optional.subscribe_notifications(names, timestamp)method returnsNotificationsSubscriptionobject. All args are optional.API command objectAPI command object has the same properties ascommand
object.API command object has the same methods ascommand
object.API notification objectAPI notification object has the same properties asnotification
objectExample:fromdevicehiveimportHandlerclassSimpleHandler(Handler):defhandle_connect(self):device_id='example-device'device=self.api.put_device(device_id)device.name='new-device-name'device.data={'key':'value'}device.save()devices=self.api.list_devices()fordeviceindevices:print('Device:%s, name:%s, data:%s'%(device.id,device.name,device.data))device.remove()self.api.disconnect()API networksself.api.list_networks(name, name_pattern, sort_field, sort_order, take, skip)method returns list ofNetworkobjects.list_networksmethod ofDeviceHiveApiclass is the wrapper on top of this call.self.api.get_network(network_id)method returnsNetworkobject.get_networkmethod ofDeviceHiveApiclass is the wrapper on top
of this call.self.api.create_network(name, description)method returnsNetworkobject.create_networkmethod ofDeviceHiveApiclass
is the wrapper on top of this call.See the description ofDeviceHiveApinetworkmethods
for more details.API network objectAPI network object has the same properties asnetwork
object.API network object has all methods fromnetwork
objectand extends these methods with:list_devices(name, name_pattern, sort_field, sort_order, take, skip)method returns list ofDeviceobjects. All args are optional.subscribe_insert_commands(names, timestamp)method returnsCommandsSubscriptionobject. All args are optional.subscribe_update_commands(names, timestamp)method returnsCommandsSubscriptionobject. All args are optional.subscribe_notifications(names, timestamp)method returnsNotificationsSubscriptionobject. All args are optional.Example:fromdevicehiveimportHandlerclassSimpleHandler(Handler):defhandle_connect(self):network_name='example-name'network_description='example-description'network=self.api.create_network(network_name,network_description)print(network.name)self.api.disconnect()API device typesself.api.list_device_types(name, name_pattern, sort_field, sort_order, take, skip)method returns list ofDeviceTypeobjects.list_device_typesmethod ofDeviceHiveApiclass is the wrapper on top of this call.self.api.get_device_type(device_type_id)method returnsDeviceTypeobject.get_device_typemethod ofDeviceHiveApiclass is the wrapper on top of this call.self.api.create_device_type(name, description)method returnsDeviceTypeobject.create_device_typemethod ofDeviceHiveApiclass is the wrapper on top of this call.See the description ofDeviceHiveApidevice
typesmethods for more details.API device type objectAPI device type object has the same properties asdevice type
object.API device type object has all methods fromdevice type
objectand extends these methods with:list_devices(name, name_pattern, sort_field, sort_order, take, skip)method returns list ofDeviceobjects. All args are optional.subscribe_insert_commands(names, timestamp)method returnsCommandsSubscriptionobject. All args are optional.subscribe_update_commands(names, timestamp)method returnsCommandsSubscriptionobject. All args are optional.subscribe_notifications(names, timestamp)method returnsNotificationsSubscriptionobject. All args are optional.Example:fromdevicehiveimportHandlerclassSimpleHandler(Handler):defhandle_connect(self):device_type_name='example-name'device_type_description='example-description'device_type=self.api.create_device_type(device_type_name,device_type_description)print(device_type.name)self.api.disconnect()API usersself.api.list_users(login, login_pattern, role, status, sort_field, sort_order, take, skip)method returns list ofUserobjects.list_usersmethod ofDeviceHiveApiclass is the wrapper on top of this call.self.api.get_current_user()method returnsUserobject.get_current_usermethod ofDeviceHiveApiclass is the wrapper on
top of this call.self.api.get_user(user_id)method returnsUserobject.get_usermethod ofDeviceHiveApiclass is the wrapper on top of
this call.self.api.create_user(self, login, password, role, data, all_device_types_available)method returnsUserobject.create_usermethod ofDeviceHiveApiclass is the wrapper on top of this call.See the description ofDeviceHiveApiusermethods for
more details.API user objectAPI user object has the same properties asuser
object.API user object has the same methods asuser object.Example:fromdevicehiveimportHandlerfromdevicehive.userimportUserclassSimpleHandler(Handler):defhandle_connect(self):login='example-login'password='example-password'role=User.CLIENT_ROLEdata={'key':'value'}user=self.api.create_user(login,password,role,data)print(user.login)self.api.disconnect()API extended exampleHere we will create one endpoint which sends notifications and other
endpoint which receives these notifications.On the first we will createreceiver.py:fromdevicehiveimportHandlerfromdevicehiveimportDeviceHiveclassReceiverHandler(Handler):def__init__(self,api,device_id='simple-example-device',accept_command_name='accept_notifications'):Handler.__init__(self,api)self._device_id=device_idself._accept_command_name=accept_command_nameself._device=Nonedefhandle_connect(self):self._device=self.api.put_device(self._device_id)self._device.subscribe_insert_commands([self._accept_command_name])self._device.subscribe_notifications()defhandle_command_insert(self,command):print('Accept command "%s"'%self._accept_command_name)command.status='accepted'command.save()defhandle_notification(self,notification):print('Notification "%s" received'%notification.notification)url='ws://playground.devicehive.com/api/websocket'refresh_token='SOME_REFRESH_TOKEN'dh=DeviceHive(ReceiverHandler)dh.connect(url,refresh_token=refresh_token)On the next step we will createsender.pyfromdevicehiveimportHandlerfromdevicehiveimportDeviceHiveclassSenderHandler(Handler):def__init__(self,api,device_id='simple-example-device',accept_command_name='accept_notifications',num_notifications=10):Handler.__init__(self,api)self._device_id=device_idself._accept_command_name=accept_command_nameself._num_notifications=num_notificationsself._device=Nonedef_send_notifications(self):fornum_notificationinrange(self._num_notifications):notification='%s-notification'%num_notificationself._device.send_notification(notification)print('Sending notification "%s"'%notification)self.api.disconnect()defhandle_connect(self):self._device=self.api.get_device(self._device_id)self._device.send_command(self._accept_command_name)print('Sending command "%s"'%self._accept_command_name)self._device.subscribe_update_commands([self._accept_command_name])defhandle_command_update(self,command):ifcommand.status=='accepted':print('Command "%s" accepted'%self._accept_command_name)self._send_notifications()url='http://playground.devicehive.com/api/rest'refresh_token='SOME_REFRESH_TOKEN'dh=DeviceHive(SenderHandler)dh.connect(url,refresh_token=refresh_token)Runpython receiver.pyin the first terminal. Andpython sender.pyin the second. The order of run is important.receiver.pymust be started first.Docker testsBuild imagedocker build -f Dockerfile.tests -t devicehive-tests .Run testsYou can run tests with refresh_token by settingADMIN_REFRESH_TOKENand/orCLIENT_REFRESH_TOKENvariable:docker run -it -e ADMIN_REFRESH_TOKEN='SOME_ADMIN_REFRESH_TOKEN' devicehive-testsOr with access_token by settingADMIN_ACCESS_TOKENand/orCLIENT_ACCESS_TOKENvariable:docker run -it -e ADMIN_ACCESS_TOKEN='SOME_ADMIN_ACCESS_TOKEN' devicehive-testsOr with user login and password by settingADMIN_LOGINandADMIN_PASSWORDfor admin account and/orCLIENT_LOGINandCLIENT_PASSWORDfor client account.docker run -it -e ADMIN_LOGIN='SOME_ADMIN_LOGIN' -e ADMIN_PASSWORD='SOME_ADMIN_PASSWORD' devicehive-testsTo run tests with enabled requests logging you need to changeLOG_LEVELvariable:docker run -it -e ADMIN_REFRESH_TOKEN='SOME_ADMIN_REFRESH_TOKEN' -e LOG_LEVEL='DEBUG' devicehive-testsTo run the specific test you need to setTESTvariable:docker run -it -e TEST=test_api.py::test_get_info -e ADMIN_REFRESH_TOKEN='SOME_ADMIN_REFRESH_TOKEN' devicehive-tests