INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Unsubscribe to the passed pair s ticker channel.
def unsubscribe_from_ticker(self, pair, **kwargs): """Unsubscribe to the passed pair's ticker channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('ticker', pair) self._unsubscribe('ticker', identifier, symbol=pair, **kwargs)
Subscribe to the passed pair s order book channel.
def subscribe_to_order_book(self, pair, **kwargs): """Subscribe to the passed pair's order book channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('book', pair) self._subscribe('book', identifier, symbol=pair, **kwargs)
Unsubscribe to the passed pair s order book channel.
def unsubscribe_from_order_book(self, pair, **kwargs): """Unsubscribe to the passed pair's order book channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('book', pair) self._unsubscribe('book', identifier, symbol=pair, **kwargs)
Subscribe to the passed pair s raw order book channel.
def subscribe_to_raw_order_book(self, pair, prec=None, **kwargs): """Subscribe to the passed pair's raw order book channel. :param pair: str, Symbol pair to request data for :param prec: :param kwargs: :return: """ identifier = ('raw_book', pair) prec = 'R0' if prec is None else prec self._subscribe('book', identifier, pair=pair, prec=prec, **kwargs)
Unsubscribe to the passed pair s raw order book channel.
def unsubscribe_from_raw_order_book(self, pair, prec=None, **kwargs): """Unsubscribe to the passed pair's raw order book channel. :param pair: str, Symbol pair to request data for :param prec: :param kwargs: :return: """ identifier = ('raw_book', pair) prec = 'R0' if prec is None else prec self._unsubscribe('book', identifier, pair=pair, prec=prec, **kwargs)
Subscribe to the passed pair s trades channel.
def subscribe_to_trades(self, pair, **kwargs): """Subscribe to the passed pair's trades channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('trades', pair) self._subscribe('trades', identifier, symbol=pair, **kwargs)
Unsubscribe to the passed pair s trades channel.
def unsubscribe_from_trades(self, pair, **kwargs): """Unsubscribe to the passed pair's trades channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('trades', pair) self._unsubscribe('trades', identifier, symbol=pair, **kwargs)
Subscribe to the passed pair s OHLC data channel.
def subscribe_to_candles(self, pair, timeframe=None, **kwargs): """Subscribe to the passed pair's OHLC data channel. :param pair: str, Symbol pair to request data for :param timeframe: str, {1m, 5m, 15m, 30m, 1h, 3h, 6h, 12h, 1D, 7D, 14D, 1M} :param kwargs: :return: """ valid_tfs = ['1m', '5m', '15m', '30m', '1h', '3h', '6h', '12h', '1D', '7D', '14D', '1M'] if timeframe: if timeframe not in valid_tfs: raise ValueError("timeframe must be any of %s" % valid_tfs) else: timeframe = '1m' identifier = ('candles', pair, timeframe) pair = 't' + pair if not pair.startswith('t') else pair key = 'trade:' + timeframe + ':' + pair self._subscribe('candles', identifier, key=key, **kwargs)
Unsubscribe to the passed pair s OHLC data channel.
def unsubscribe_from_candles(self, pair, timeframe=None, **kwargs): """Unsubscribe to the passed pair's OHLC data channel. :param timeframe: str, {1m, 5m, 15m, 30m, 1h, 3h, 6h, 12h, 1D, 7D, 14D, 1M} :param kwargs: :return: """ valid_tfs = ['1m', '5m', '15m', '30m', '1h', '3h', '6h', '12h', '1D', '7D', '14D', '1M'] if timeframe: if timeframe not in valid_tfs: raise ValueError("timeframe must be any of %s" % valid_tfs) else: timeframe = '1m' identifier = ('candles', pair, timeframe) pair = 't' + pair if not pair.startswith('t') else pair key = 'trade:' + timeframe + ':' + pair self._unsubscribe('candles', identifier, key=key, **kwargs)
Authenticate with the Bitfinex API.
def authenticate(self): """Authenticate with the Bitfinex API. :return: """ if not self.key and not self.secret: raise ValueError("Must supply both key and secret key for API!") self.channel_configs['auth'] = {'api_key': self.key, 'secret': self.secret} self.conn.send(api_key=self.key, secret=self.secret, auth=True)
Cancel one or multiple orders via Websocket.
def cancel_order(self, multi=False, **order_identifiers): """Cancel one or multiple orders via Websocket. :param multi: bool, whether order_settings contains settings for one, or multiples orders :param order_identifiers: Identifiers for the order(s) you with to cancel :return: """ if multi: self._send_auth_command('oc_multi', order_identifiers) else: self._send_auth_command('oc', order_identifiers)
Parse environment variables into a Python dictionary suitable for passing to the device client constructor as the options parameter
def parseEnvVars(): """ Parse environment variables into a Python dictionary suitable for passing to the device client constructor as the `options` parameter - `WIOTP_IDENTITY_APPID` - `WIOTP_AUTH_KEY` - `WIOTP_AUTH_TOKEN` - `WIOTP_OPTIONS_DOMAIN` (optional) - `WIOTP_OPTIONS_LOGLEVEL` (optional) - `WIOTP_OPTIONS_MQTT_PORT` (optional) - `WIOTP_OPTIONS_MQTT_TRANSPORT` (optional) - `WIOTP_OPTIONS_MQTT_CAFILE` (optional) - `WIOTP_OPTIONS_MQTT_CLEANSTART` (optional) - `WIOTP_OPTIONS_MQTT_SESSIONEXPIRY` (optional) - `WIOTP_OPTIONS_MQTT_KEEPALIVE` (optional) - `WIOTP_OPTIONS_MQTT_SHAREDSUBSCRIPTION` (optional) - `WIOTP_OPTIONS_HTTP_VERIFY` (optional) """ # Auth authKey = os.getenv("WIOTP_AUTH_KEY", None) authToken = os.getenv("WIOTP_AUTH_TOKEN", None) # Also support WIOTP_API_KEY / WIOTP_API_TOKEN usage if authKey is None and authToken is None: authKey = os.getenv("WIOTP_API_KEY", None) authToken = os.getenv("WIOTP_API_TOKEN", None) # Identity appId = os.getenv("WIOTP_IDENTITY_APPID", str(uuid.uuid4())) # Options domain = os.getenv("WIOTP_OPTIONS_DOMAIN", None) logLevel = os.getenv("WIOTP_OPTIONS_LOGLEVEL", "info") port = os.getenv("WIOTP_OPTIONS_MQTT_PORT", None) transport = os.getenv("WIOTP_OPTIONS_MQTT_TRANSPORT", None) caFile = os.getenv("WIOTP_OPTIONS_MQTT_CAFILE", None) cleanStart = os.getenv("WIOTP_OPTIONS_MQTT_CLEANSTART", "True") sessionExpiry = os.getenv("WIOTP_OPTIONS_MQTT_SESSIONEXPIRY", "3600") keepAlive = os.getenv("WIOTP_OPTIONS_MQTT_KEEPALIVE", "60") sharedSubs = os.getenv("WIOTP_OPTIONS_MQTT_SHAREDSUBSCRIPTION", "False") verifyCert = os.getenv("WIOTP_OPTIONS_HTTP_VERIFY", "True") if port is not None: try: port = int(port) except ValueError as e: raise ConfigurationException("WIOTP_PORT must be a number") try: sessionExpiry = int(sessionExpiry) except ValueError as e: raise ConfigurationException("WIOTP_OPTIONS_MQTT_SESSIONEXPIRY must be a number") try: keepAlive = int(keepAlive) except ValueError as e: raise ConfigurationException("WIOTP_OPTIONS_MQTT_KEEPAIVE must be a number") if logLevel not in ["error", "warning", "info", "debug"]: raise ConfigurationException("WIOTP_OPTIONS_LOGLEVEL must be one of error, warning, info, debug") else: # Convert log levels from string to int (we need to upper case our strings from the config) logLevel = logging.getLevelName(logLevel.upper()) cfg = { "identity": {"appId": appId}, "options": { "domain": domain, "logLevel": logLevel, "mqtt": { "port": port, "transport": transport, "cleanStart": cleanStart in ["True", "true", "1"], "sessionExpiry": sessionExpiry, "keepAlive": keepAlive, "sharedSubscription": sharedSubs in ["True", "true", "1"], "caFile": caFile, }, "http": {"verify": verifyCert in ["True", "true", "1"]}, }, } # Quickstart doesn't support auth, so ensure we only add this if it's defined if authToken is not None: cfg["auth"] = {"key": authKey, "token": authToken} return cfg
Parse a yaml configuration file into a Python dictionary suitable for passing to the device client constructor as the options parameter # Example Configuration File identity: appId: myApp auth: key: a - 23gh56 - sdsdajhjnee token: Ab$76s ) asj8_s5 options: domain: internetofthings. ibmcloud. com logLevel: error|warning|info|debug mqtt: port: 8883 transport: tcp cleanStart: false sessionExpiry: 3600 keepAlive: 60 sharedSubscription: false caFile:/ path/ to/ certificateAuthorityFile. pem http: verify: true
def parseConfigFile(configFilePath): """ Parse a yaml configuration file into a Python dictionary suitable for passing to the device client constructor as the `options` parameter # Example Configuration File identity: appId: myApp auth: key: a-23gh56-sdsdajhjnee token: Ab$76s)asj8_s5 options: domain: internetofthings.ibmcloud.com logLevel: error|warning|info|debug mqtt: port: 8883 transport: tcp cleanStart: false sessionExpiry: 3600 keepAlive: 60 sharedSubscription: false caFile: /path/to/certificateAuthorityFile.pem http: verify: true """ try: with open(configFilePath) as f: data = yaml.load(f) except (OSError, IOError) as e: # In 3.3, IOError became an alias for OSError, and FileNotFoundError is a subclass of OSError reason = "Error reading device configuration file '%s' (%s)" % (configFilePath, e) raise ConfigurationException(reason) if "options" in data and "logLevel" in data["options"]: if data["options"]["logLevel"] not in ["error", "warning", "info", "debug"]: raise ConfigurationException("Optional setting options.logLevel must be one of error, warning, info, debug") else: # Convert log levels from string to int (we need to upper case our strings from the config) data["options"]["logLevel"] = logging.getLevelName(data["options"]["logLevel"].upper()) return data
Internal callback for device command messages parses source device from topic string and passes the information on to the registered device command callback
def _onCommand(self, client, userdata, pahoMessage): """ Internal callback for device command messages, parses source device from topic string and passes the information on to the registered device command callback """ try: command = Command(pahoMessage, self._messageCodecs) except InvalidEventException as e: self.logger.critical(str(e)) else: self.logger.debug("Received device command '%s'" % (command.command)) if self.commandCallback: self.commandCallback(command)
Internal callback for gateway command messages parses source device from topic string and passes the information on to the registered device command callback
def _onDeviceCommand(self, client, userdata, pahoMessage): """ Internal callback for gateway command messages, parses source device from topic string and passes the information on to the registered device command callback """ try: command = Command(pahoMessage, self._messageCodecs) except InvalidEventException as e: self.logger.critical(str(e)) else: self.logger.debug("Received gateway command '%s'" % (command.command)) if self.deviceCommandCallback: self.deviceCommandCallback(command)
Internal callback for gateway notification messages parses source device from topic string and passes the information on to the registered device command callback
def _onMessageNotification(self, client, userdata, pahoMessage): """ Internal callback for gateway notification messages, parses source device from topic string and passes the information on to the registered device command callback """ try: note = Notification(pahoMessage, self._messageCodecs) except InvalidEventException as e: self.logger.critical(str(e)) else: self.logger.debug("Received Notification") if self.notificationCallback: self.notificationCallback(note)
Gets the list of Historian connectors they are used to configure the Watson IoT Platform to store IoT data in compatible services. Parameters: - nameFilter ( string ) - Filter the results by the specified name - typeFilter ( string ) - Filter the results by the specified type Available values: cloudant eventstreams - enabledFilter ( boolean ) - Filter the results by the enabled flag - serviceId ( string ) - Filter the results by the service id - limit ( number ) - Max number of results returned defaults 25 - bookmark ( string ) - used for paging through results Throws APIException on failure.
def find(self, nameFilter=None, typeFilter=None, enabledFilter=None, serviceId=None): """ Gets the list of Historian connectors, they are used to configure the Watson IoT Platform to store IoT data in compatible services. Parameters: - nameFilter(string) - Filter the results by the specified name - typeFilter(string) - Filter the results by the specified type, Available values : cloudant, eventstreams - enabledFilter(boolean) - Filter the results by the enabled flag - serviceId(string) - Filter the results by the service id - limit(number) - Max number of results returned, defaults 25 - bookmark(string) - used for paging through results Throws APIException on failure. """ queryParms = {} if nameFilter: queryParms["name"] = nameFilter if typeFilter: queryParms["type"] = typeFilter if enabledFilter: queryParms["enabled"] = enabledFilter if serviceId: queryParms["serviceId"] = serviceId return IterableConnectorList(self._apiClient, filters=queryParms)
Create a connector for the organization in the Watson IoT Platform. The connector must reference the target service that the Watson IoT Platform will store the IoT data in. Parameters: - name ( string ) - Name of the service - serviceId ( string ) - must be either eventstreams or cloudant - timezone ( string ) - - description ( string ) - description of the service - enabled ( boolean ) - enabled Throws APIException on failure
def create(self, name, serviceId, timezone, description, enabled): """ Create a connector for the organization in the Watson IoT Platform. The connector must reference the target service that the Watson IoT Platform will store the IoT data in. Parameters: - name (string) - Name of the service - serviceId (string) - must be either eventstreams or cloudant - timezone (string) - - description (string) - description of the service - enabled (boolean) - enabled Throws APIException on failure """ connector = { "name": name, "description": description, "serviceId": serviceId, "timezone": timezone, "enabled": enabled, } url = "api/v0002/historianconnectors" r = self._apiClient.post(url, data=connector) if r.status_code == 201: return Connector(apiClient=self._apiClient, **r.json()) else: raise ApiException(r)
Updates the connector with the specified uuid. if description is empty the existing description will be removed. Parameters: - connector ( String ) Connnector Id which is a UUID - name ( string ) - Name of the service - timezone ( json object ) - Should have a valid structure for the service type. - description ( string ) - description of the service - enabled ( boolean ) - enabled Throws APIException on failure.
def update(self, connectorId, name, description, timezone, enabled): """ Updates the connector with the specified uuid. if description is empty, the existing description will be removed. Parameters: - connector (String), Connnector Id which is a UUID - name (string) - Name of the service - timezone (json object) - Should have a valid structure for the service type. - description (string) - description of the service - enabled (boolean) - enabled Throws APIException on failure. """ url = "api/v0002/historianconnectors/%s" % (connectorId) connectorBody = {} connectorBody["name"] = name connectorBody["description"] = description connectorBody["timezone"] = timezone connectorBody["enabled"] = enabled r = self._apiClient.put(url, data=connectorBody) if r.status_code == 200: return Connector(apiClient=self._apiClient, **r.json()) else: raise ApiException(r)
Gets the list of services that the Watson IoT Platform can connect to. The list can include a mixture of services that are either bound or unbound. Parameters: - nameFilter ( string ) - Filter the results by the specified name - typeFilter ( string ) - Filter the results by the specified type Available values: cloudant eventstreams - bindingModeFilter ( string ) - Filter the results by the specified binding mode Available values: automatic manual - boundFilter ( boolean ) - Filter the results by the bound flag Throws APIException on failure.
def find(self, nameFilter=None, typeFilter=None, bindingModeFilter=None, boundFilter=None): """ Gets the list of services that the Watson IoT Platform can connect to. The list can include a mixture of services that are either bound or unbound. Parameters: - nameFilter(string) - Filter the results by the specified name - typeFilter(string) - Filter the results by the specified type, Available values : cloudant, eventstreams - bindingModeFilter(string) - Filter the results by the specified binding mode, Available values : automatic, manual - boundFilter(boolean) - Filter the results by the bound flag Throws APIException on failure. """ queryParms = {} if nameFilter: queryParms["name"] = nameFilter if typeFilter: queryParms["type"] = typeFilter if bindingModeFilter: queryParms["bindingMode"] = bindingModeFilter if boundFilter: queryParms["bound"] = boundFilter return IterableServiceBindingsList(self._apiClient, filters=queryParms)
Create a new external service. The service must include all of the details required to connect and authenticate to the external service in the credentials property. Parameters: - serviceName ( string ) - Name of the service - serviceType ( string ) - must be either eventstreams or cloudant - credentials ( json object ) - Should have a valid structure for the service type. - description ( string ) - description of the service Throws APIException on failure
def create(self, serviceBinding): """ Create a new external service. The service must include all of the details required to connect and authenticate to the external service in the credentials property. Parameters: - serviceName (string) - Name of the service - serviceType (string) - must be either eventstreams or cloudant - credentials (json object) - Should have a valid structure for the service type. - description (string) - description of the service Throws APIException on failure """ if not isinstance(serviceBinding, ServiceBindingCreateRequest): if serviceBinding["type"] == "cloudant": serviceBinding = CloudantServiceBindingCreateRequest(**serviceBinding) elif serviceBinding["type"] == "eventstreams": serviceBinding = EventStreamsServiceBindingCreateRequest(**serviceBinding) else: raise Exception("Unsupported service binding type") url = "api/v0002/s2s/services" r = self._apiClient.post(url, data=serviceBinding) if r.status_code == 201: return ServiceBinding(**r.json()) else: raise ApiException(r)
Updates the service with the specified id. if description is empty the existing description will be removed. Parameters: - serviceId ( String ) Service Id which is a UUID - serviceName ( string ) name of service - credentials ( json ) json object of credentials - description - description of the service Throws APIException on failure.
def update(self, serviceId, serviceName, credentials, description): """ Updates the service with the specified id. if description is empty, the existing description will be removed. Parameters: - serviceId (String), Service Id which is a UUID - serviceName (string), name of service - credentials (json), json object of credentials - description - description of the service Throws APIException on failure. """ url = "api/v0002/s2s/services/%s" % (serviceId) serviceBody = {} serviceBody["name"] = serviceName serviceBody["description"] = description serviceBody["credentials"] = credentials r = self._apiClient.put(url, data=serviceBody) if r.status_code == 200: return ServiceBinding(**r.json()) else: raise ApiException(r)
Register one or more new device types each request can contain a maximum of 512KB.
def create(self, deviceType): """ Register one or more new device types, each request can contain a maximum of 512KB. """ r = self._apiClient.post("api/v0002/device/types", deviceType) if r.status_code == 201: return DeviceType(apiClient=self._apiClient, **r.json()) else: raise ApiException(r)
Publish an event to Watson IoT Platform.
def publishEvent(self, event, msgFormat, data, qos=0, on_publish=None): """ Publish an event to Watson IoT Platform. # Parameters event (string): Name of this event msgFormat (string): Format of the data for this event data (dict): Data for this event qos (int): MQTT quality of service level to use (`0`, `1`, or `2`) on_publish(function): A function that will be called when receipt of the publication is confirmed. # Callback and QoS The use of the optional #on_publish function has different implications depending on the level of qos used to publish the event: - qos 0: the client has asynchronously begun to send the event - qos 1 and 2: the client has confirmation of delivery from the platform """ topic = "iot-2/evt/{event}/fmt/{msg_format}".format(event=event, msg_format=msgFormat) return self._publishEvent(topic, event, msgFormat, data, qos, on_publish)
Retrieve the organization - specific status of each of the services offered by the IBM Watson IoT Platform. In case of failure it throws APIException
def serviceStatus(self): """ Retrieve the organization-specific status of each of the services offered by the IBM Watson IoT Platform. In case of failure it throws APIException """ r = self._apiClient.get("api/v0002/service-status") if r.status_code == 200: return ServiceStatus(**r.json()) else: raise ApiException(r)
Register one or more new devices each request can contain a maximum of 512KB. The response body will contain the generated authentication tokens for all devices. You must make sure to record these tokens when processing the response. We are not able to retrieve lost authentication tokens It accepts accepts a list of devices ( List of Dictionary of Devices ) or a single device If you provide a list as the parameter it will return a list in response If you provide a singular device it will return a singular response
def create(self, devices): """ Register one or more new devices, each request can contain a maximum of 512KB. The response body will contain the generated authentication tokens for all devices. You must make sure to record these tokens when processing the response. We are not able to retrieve lost authentication tokens It accepts accepts a list of devices (List of Dictionary of Devices), or a single device If you provide a list as the parameter it will return a list in response If you provide a singular device it will return a singular response """ if not isinstance(devices, list): listOfDevices = [devices] returnAsAList = False else: listOfDevices = devices returnAsAList = True r = self._apiClient.post("api/v0002/bulk/devices/add", listOfDevices) if r.status_code in [201, 202]: if returnAsAList: responseList = [] for entry in r.json(): responseList.append(DeviceCreateResponse(**entry)) return responseList else: return DeviceCreateResponse(**r.json()[0]) else: raise ApiException(r)
Update an existing device
def update(self, deviceUid, metadata=None, deviceInfo=None, status=None): """ Update an existing device """ if not isinstance(deviceUid, DeviceUid) and isinstance(deviceUid, dict): deviceUid = DeviceUid(**deviceUid) deviceUrl = "api/v0002/device/types/%s/devices/%s" % (deviceUid.typeId, deviceUid.deviceId) data = {"status": status, "deviceInfo": deviceInfo, "metadata": metadata} r = self._apiClient.put(deviceUrl, data) if r.status_code == 200: return Device(apiClient=self._apiClient, **r.json()) else: raise ApiException(r)
Delete one or more devices each request can contain a maximum of 512Kb It accepts accepts a list of devices ( List of Dictionary of Devices ) In case of failure it throws APIException
def delete(self, devices): """ Delete one or more devices, each request can contain a maximum of 512Kb It accepts accepts a list of devices (List of Dictionary of Devices) In case of failure it throws APIException """ if not isinstance(devices, list): listOfDevices = [devices] else: listOfDevices = devices r = self._apiClient.post("api/v0002/bulk/devices/remove", listOfDevices) if r.status_code in [200, 202]: return r.json() else: raise ApiException(r)
Iterate through all Connectors
def find(self, status=None, connectedAfter=None): """ Iterate through all Connectors """ queryParms = {} if status: queryParms["status"] = status if connectedAfter: queryParms["connectedAfter"] = connectedAfter return IterableClientStatusList(self._apiClient, filters=queryParms)
List all device management extension packages
def list(self): """ List all device management extension packages """ url = "api/v0002/mgmt/custom/bundle" r = self._apiClient.get(url) if r.status_code == 200: return r.json() else: raise ApiException(r)
Create a new device management extension package In case of failure it throws APIException
def create(self, dmeData): """ Create a new device management extension package In case of failure it throws APIException """ url = "api/v0002/mgmt/custom/bundle" r = self._apiClient.post(url, dmeData) if r.status_code == 201: return r.json() else: raise ApiException(r)
Delete a device management extension package It accepts bundleId ( string ) as parameters In case of failure it throws APIException
def delete(self, bundleId): """ Delete a device management extension package It accepts bundleId (string) as parameters In case of failure it throws APIException """ url = "api/v0002/mgmt/custom/bundle/%s" % (bundleId) r = self._apiClient.delete(url) if r.status_code == 204: return True else: raise ApiException(r)
Update a device management extension package It accepts bundleId ( string ) as parameters In case of failure it throws APIException
def update(self, bundleId, dmeData): """ Update a device management extension package It accepts bundleId (string) as parameters In case of failure it throws APIException """ url = "api/v0002/mgmt/custom/bundle/%s" % (bundleId) r = self._apiClient.put(url, dmeData) if r.status_code == 200: return r.json() else: raise ApiException(r)
Registers a new thing. It accepts thingTypeId ( string ) thingId ( string ) name ( string ) description ( string ) aggregatedObjects ( JSON ) and metadata ( JSON ) as parameters In case of failure it throws APIException
def registerThing(self, thingTypeId, thingId, name = None, description = None, aggregatedObjects = None, metadata=None): """ Registers a new thing. It accepts thingTypeId (string), thingId (string), name (string), description (string), aggregatedObjects (JSON) and metadata (JSON) as parameters In case of failure it throws APIException """ thingsUrl = ApiClient.thingsUrl % (self.host, thingTypeId) payload = {'thingId' : thingId, 'name' : name, 'description' : description, 'aggregatedObjects' : aggregatedObjects, 'metadata': metadata} r = requests.post(thingsUrl, auth=self.credentials, data=json.dumps(payload), headers = {'content-type': 'application/json'}, verify=self.verify) status = r.status_code if status == 201: self.logger.debug("Thing Instance Created") return r.json() elif status == 400: raise ibmiotf.APIException(400, "Invalid request (No body, invalid JSON, unexpected key, bad value)", r.json()) elif status == 401: raise ibmiotf.APIException(401, "The authentication token is empty or invalid", None) elif status == 403: raise ibmiotf.APIException(403, "The authentication method is invalid or the API key used does not exist", None) elif status == 404: raise ibmiotf.APIException(404, "The thing type with specified id does not exist", None) elif status == 409: raise ibmiotf.APIException(409, "A thing instance with the specified id already exists", r.json()) elif status == 500: raise ibmiotf.APIException(500, "Unexpected error", None) else: raise ibmiotf.APIException(None, "Unexpected error", None)
Gets thing details. It accepts thingTypeId ( string ) thingId ( string ) In case of failure it throws APIException
def getThing(self, thingTypeId, thingId): """ Gets thing details. It accepts thingTypeId (string), thingId (string) In case of failure it throws APIException """ thingUrl = ApiClient.thingUrl % (self.host, thingTypeId, thingId) r = requests.get(thingUrl, auth=self.credentials, verify=self.verify) status = r.status_code if status == 200: self.logger.debug("Thing instance was successfully retrieved") return r.json() elif status == 304: raise ibmiotf.APIException(304, "The state of the thing has not been modified (response to a conditional GET).", None) elif status == 401: raise ibmiotf.APIException(401, "The authentication token is empty or invalid", None) elif status == 403: raise ibmiotf.APIException(403, "The authentication method is invalid or the api key used does not exist", None) elif status == 404: raise ibmiotf.APIException(404, "A thing type with the specified id, or a thing with the specified id, does not exist.", None) elif status == 500: raise ibmiotf.APIException(500, "Unexpected error", None) else: raise ibmiotf.APIException(None, "Unexpected error", None)
Gets details for multiple things of a type It accepts thingTypeId ( string ) and parameters In case of failure it throws APIException
def getThingsForType(self, thingTypeId, parameters = None): """ Gets details for multiple things of a type It accepts thingTypeId (string) and parameters In case of failure it throws APIException """ thingsUrl = ApiClient.thingsUrl % (self.host, thingTypeId) r = requests.get(thingsUrl, auth=self.credentials, params = parameters, verify=self.verify) status = r.status_code if status == 200: self.logger.debug("List of things was successfully retrieved") return r.json() elif status == 401: raise ibmiotf.APIException(401, "The authentication token is empty or invalid", None) elif status == 403: raise ibmiotf.APIException(403, "The authentication method is invalid or the api key used does not exist", None) elif status == 404: raise ibmiotf.APIException(404, "The thing type does not exist", None) elif status == 500: raise ibmiotf.APIException(500, "Unexpected error", None) else: raise ibmiotf.APIException(None, "Unexpected error", None)
Delete an existing thing. It accepts thingTypeId ( string ) and thingId ( string ) as parameters In case of failure it throws APIException
def removeThing(self, thingTypeId, thingId): """ Delete an existing thing. It accepts thingTypeId (string) and thingId (string) as parameters In case of failure it throws APIException """ thingUrl = ApiClient.thingUrl % (self.host, thingTypeId, thingId) r = requests.delete(thingUrl, auth=self.credentials, verify=self.verify) status = r.status_code if status == 204: self.logger.debug("Thing was successfully removed") return True elif status == 401: raise ibmiotf.APIException(401, "The authentication token is empty or invalid", None) elif status == 403: raise ibmiotf.APIException(403, "The authentication method is invalid or the api key used does not exist", None) elif status == 404: raise ibmiotf.APIException(404, "A thing type or thing instance with the specified id does not exist.", None) elif status == 409: raise ibmiotf.APIException(409, "The thing instance is aggregated into another thing instance.", None) elif status == 500: raise ibmiotf.APIException(500, "Unexpected error", None) else: raise ibmiotf.APIException(None, "Unexpected error", None)
Creates a thing type. It accepts thingTypeId ( string ) name ( string ) description ( string ) schemaId ( string ) and metadata ( dict ) as parameter In case of failure it throws APIException
def addDraftThingType(self, thingTypeId, name = None, description = None, schemaId = None, metadata = None): """ Creates a thing type. It accepts thingTypeId (string), name (string), description (string), schemaId(string) and metadata(dict) as parameter In case of failure it throws APIException """ draftThingTypesUrl = ApiClient.draftThingTypesUrl % (self.host) payload = {'id' : thingTypeId, 'name' : name, 'description' : description, 'schemaId' : schemaId, 'metadata': metadata} r = requests.post(draftThingTypesUrl, auth=self.credentials, data=json.dumps(payload), headers = {'content-type': 'application/json'}, verify=self.verify) status = r.status_code if status == 201: self.logger.debug("The draft thing Type is created") return r.json() elif status == 400: raise ibmiotf.APIException(400, "Invalid request (No body, invalid JSON, unexpected key, bad value)", r.json()) elif status == 401: raise ibmiotf.APIException(401, "The authentication token is empty or invalid", None) elif status == 403: raise ibmiotf.APIException(403, "The authentication method is invalid or the api key used does not exist", None) elif status == 409: raise ibmiotf.APIException(409, "The draft thing type already exists", r.json()) elif status == 500: raise ibmiotf.APIException(500, "Unexpected error", None) else: raise ibmiotf.APIException(None, "Unexpected error", None)
Updates a thing type. It accepts thingTypeId ( string ) name ( string ) description ( string ) schemaId ( string ) and metadata ( JSON ) as the parameters In case of failure it throws APIException
def updateDraftThingType(self, thingTypeId, name, description, schemaId, metadata = None): """ Updates a thing type. It accepts thingTypeId (string), name (string), description (string), schemaId (string) and metadata(JSON) as the parameters In case of failure it throws APIException """ draftThingTypeUrl = ApiClient.draftThingTypeUrl % (self.host, thingTypeId) draftThingTypeUpdate = {'name' : name, 'description' : description, 'schemaId' : schemaId, 'metadata' : metadata} r = requests.put(draftThingTypeUrl, auth=self.credentials, data=json.dumps(draftThingTypeUpdate), headers = {'content-type': 'application/json'}, verify=self.verify) status = r.status_code if status == 200: self.logger.debug("Thing type was successfully modified") return r.json() elif status == 401: raise ibmiotf.APIException(401, "The authentication token is empty or invalid", None) elif status == 403: raise ibmiotf.APIException(403, "The authentication method is invalid or the api key used does not exist", None) elif status == 404: raise ibmiotf.APIException(404, "The Thing type does not exist", None) elif status == 409: raise ibmiotf.APIException(409, "The update could not be completed due to a conflict", r.json()) elif status == 500: raise ibmiotf.APIException(500, "Unexpected error", None) else: raise ibmiotf.APIException(None, "Unexpected error", None)
Retrieves all existing draft thing types. It accepts accepts an optional query parameters ( Dictionary ) In case of failure it throws APIException
def getDraftThingTypes(self, parameters = None): """ Retrieves all existing draft thing types. It accepts accepts an optional query parameters (Dictionary) In case of failure it throws APIException """ draftThingTypesUrl = ApiClient.draftThingTypesUrl % (self.host) r = requests.get(draftThingTypesUrl, auth=self.credentials, params = parameters, verify=self.verify) status = r.status_code if status == 200: self.logger.debug("Draft thing types successfully retrieved") self.logger.debug(json.dumps(r.json())) return r.json() elif status == 401: raise ibmiotf.APIException(401, "The authentication token is empty or invalid", None) elif status == 403: raise ibmiotf.APIException(403, "The authentication method is invalid or the api key used does not exist", None) elif status == 500: raise ibmiotf.APIException(500, "Unexpected error", None) else: raise ibmiotf.APIException(None, "Unexpected error", None)
Retrieves all existing draft thing types. It accepts accepts an optional query parameters ( Dictionary ) In case of failure it throws APIException
def getDraftThingType(self, thingTypeId, parameters = None): """ Retrieves all existing draft thing types. It accepts accepts an optional query parameters (Dictionary) In case of failure it throws APIException """ draftThingTypeUrl = ApiClient.draftThingTypeUrl % (self.host, thingTypeId) r = requests.get(draftThingTypeUrl, auth=self.credentials, params = parameters, verify=self.verify) status = r.status_code if status == 200: self.logger.debug("Draft thing type successfully retrieved") self.logger.debug(json.dumps(r.json())) return r.json() elif status == 304: raise ibmiotf.APIException(304, "The state of the thing type has not been modified (response to a conditional GET).", None) elif status == 401: raise ibmiotf.APIException(401, "The authentication token is empty or invalid", None) elif status == 403: raise ibmiotf.APIException(403, "The authentication method is invalid or the api key used does not exist", None) elif status == 404: raise ibmiotf.APIException(404, "A draft thing type with the specified id does not exist.", None) elif status == 500: raise ibmiotf.APIException(500, "Unexpected error", None) else: raise ibmiotf.APIException(None, "Unexpected error", None)
Deletes a Thing type. It accepts thingTypeId ( string ) as the parameter In case of failure it throws APIException
def deleteDraftThingType(self, thingTypeId): """ Deletes a Thing type. It accepts thingTypeId (string) as the parameter In case of failure it throws APIException """ draftThingTypeUrl = ApiClient.draftThingTypeUrl % (self.host, thingTypeId) r = requests.delete(draftThingTypeUrl, auth=self.credentials, verify=self.verify) status = r.status_code if status == 204: self.logger.debug("Device type was successfully deleted") return True elif status == 401: raise ibmiotf.APIException(401, "The authentication token is empty or invalid", None) elif status == 403: raise ibmiotf.APIException(403, "The authentication method is invalid or the api key used does not exist", None) elif status == 404: raise ibmiotf.APIException(404, "A thing type with the specified id does not exist.", None) elif status == 409: raise ibmiotf.APIException(409, "The draft thing type with the specified id is currently being referenced by another object.", None) elif status == 500: raise ibmiotf.APIException(500, "Unexpected error", None) else: raise ibmiotf.APIException(None, "Unexpected error", None)
Create a schema for the org. Returns: schemaId ( string ) response ( object ). Throws APIException on failure
def createSchema(self, schemaName, schemaFileName, schemaContents, description=None): """ Create a schema for the org. Returns: schemaId (string), response (object). Throws APIException on failure """ req = ApiClient.allSchemasUrl % (self.host, "/draft") fields={ 'schemaFile': (schemaFileName, schemaContents, 'application/json'), 'schemaType': 'json-schema', 'name': schemaName, } if description: fields["description"] = description multipart_data = MultipartEncoder(fields=fields) resp = requests.post(req, auth=self.credentials, data=multipart_data, headers={'Content-Type': multipart_data.content_type}, verify=self.verify) if resp.status_code == 201: self.logger.debug("Schema created") else: raise ibmiotf.APIException(resp.status_code, "HTTP error creating a schema", resp) return resp.json()["id"], resp.json()
Delete a schema. Parameter: schemaId ( string ). Throws APIException on failure.
def deleteSchema(self, schemaId): """ Delete a schema. Parameter: schemaId (string). Throws APIException on failure. """ req = ApiClient.oneSchemaUrl % (self.host, "/draft", schemaId) resp = requests.delete(req, auth=self.credentials, verify=self.verify) if resp.status_code == 204: self.logger.debug("Schema deleted") else: raise ibmiotf.APIException(resp.status_code, "HTTP error deleting schema", resp) return resp
Update a schema. Throws APIException on failure.
def updateSchema(self, schemaId, schemaDefinition): """ Update a schema. Throws APIException on failure. """ req = ApiClient.oneSchemaUrl % (self.host, "/draft", schemaId) body = {"schemaDefinition": schemaDefinition} resp = requests.put(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body), verify=self.verify) if resp.status_code == 200: self.logger.debug("Schema updated") else: raise ibmiotf.APIException(resp.status_code, "HTTP error updating schema", resp) return resp.json()
Get the content for a schema. Parameters: schemaId ( string ) draft ( boolean ). Throws APIException on failure.
def getSchemaContent(self, schemaId, draft=False): """ Get the content for a schema. Parameters: schemaId (string), draft (boolean). Throws APIException on failure. """ if draft: req = ApiClient.oneSchemaContentUrl % (self.host, "/draft", schemaId) else: req = ApiClient.oneSchemaContentUrl % (self.host, "", schemaId) resp = requests.get(req, auth=self.credentials, verify=self.verify) if resp.status_code == 200: self.logger.debug("Schema content retrieved") else: raise ibmiotf.APIException(resp.status_code, "HTTP error getting schema content", resp) return resp.json()
Updates the content for a schema. Parameters: schemaId ( string ). Throws APIException on failure.
def updateSchemaContent(self, schemaId, schemaFile): """ Updates the content for a schema. Parameters: schemaId (string). Throws APIException on failure. """ req = ApiClient.oneSchemaContentUrl % (self.host, "/draft", schemaId) body = {"schemaFile": schemaFile} resp = requests.put(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body), verify=self.verify) if resp.status_code == 200: self.logger.debug("Schema content updated") else: raise ibmiotf.APIException(resp.status_code, "HTTP error updating schema content", resp) return resp.json()
Updates an event type. Parameters: eventTypeId ( string ) name ( string ) schemaId ( string ) description ( string optional ). Throws APIException on failure.
def updateEventType(self, eventTypeId, name, schemaId, description=None): """ Updates an event type. Parameters: eventTypeId (string), name (string), schemaId (string), description (string, optional). Throws APIException on failure. """ req = ApiClient.oneEventTypesUrl % (self.host, "/draft", eventTypeId) body = {"name" : name, "schemaId" : schemaId} if description: body["description"] = description resp = requests.put(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body), verify=self.verify) if resp.status_code == 200: self.logger.debug("event type updated") else: raise ibmiotf.APIException(resp.status_code, "HTTP error updating event type", resp) return resp.json()
Deletes an event type. Parameters: eventTypeId ( string ). Throws APIException on failure.
def deleteEventType(self, eventTypeId): """ Deletes an event type. Parameters: eventTypeId (string). Throws APIException on failure. """ req = ApiClient.oneEventTypeUrl % (self.host, "/draft", eventTypeId) resp = requests.delete(req, auth=self.credentials, verify=self.verify) if resp.status_code == 204: self.logger.debug("event type deleted") else: raise ibmiotf.APIException(resp.status_code, "HTTP error deleting an event type", resp) return resp
Gets an event type. Parameters: eventTypeId ( string ) draft ( boolean ). Throws APIException on failure.
def getEventType(self, eventTypeId, draft=False): """ Gets an event type. Parameters: eventTypeId (string), draft (boolean). Throws APIException on failure. """ if draft: req = ApiClient.oneEventTypeUrl % (self.host, "/draft", eventTypeId) else: req = ApiClient.oneEventTypeUrl % (self.host, "", eventTypeId) resp = requests.get(req, auth=self.credentials, verify=self.verify) if resp.status_code == 200: self.logger.debug("event type retrieved") else: raise ibmiotf.APIException(resp.status_code, "HTTP error getting an event type", resp) return resp.json()
Create a physical interface. Parameters: - name ( string ) - description ( string optional ) Returns: physical interface id response. Throws APIException on failure.
def createPhysicalInterface(self, name, description=None): """ Create a physical interface. Parameters: - name (string) - description (string, optional) Returns: physical interface id, response. Throws APIException on failure. """ req = ApiClient.allPhysicalInterfacesUrl % (self.host, "/draft") body = {"name" : name} if description: body["description"] = description resp = requests.post(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body), verify=self.verify) if resp.status_code == 201: self.logger.debug("physical interface created") else: raise ibmiotf.APIException(resp.status_code, "HTTP error creating physical interface", resp) return resp.json()["id"], resp.json()
Update a physical interface. Parameters: - physicalInterfaceId ( string ) - name ( string ) - schemaId ( string ) - description ( string optional ) Throws APIException on failure.
def updatePhysicalInterface(self, physicalInterfaceId, name, schemaId, description=None): """ Update a physical interface. Parameters: - physicalInterfaceId (string) - name (string) - schemaId (string) - description (string, optional) Throws APIException on failure. """ req = ApiClient.onePhysicalInterfacesUrl % (self.host, "/draft", physicalInterfaceId) body = {"name" : name, "schemaId" : schemaId} if description: body["description"] = description resp = requests.put(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body), verify=self.verify) if resp.status_code == 200: self.logger.debug("physical interface updated") else: raise ibmiotf.APIException(resp.status_code, "HTTP error updating physical interface", resp) return resp.json()
Delete a physical interface. Parameters: physicalInterfaceId ( string ). Throws APIException on failure.
def deletePhysicalInterface(self, physicalInterfaceId): """ Delete a physical interface. Parameters: physicalInterfaceId (string). Throws APIException on failure. """ req = ApiClient.onePhysicalInterfaceUrl % (self.host, "/draft", physicalInterfaceId) resp = requests.delete(req, auth=self.credentials, verify=self.verify) if resp.status_code == 204: self.logger.debug("physical interface deleted") else: raise ibmiotf.APIException(resp.status_code, "HTTP error deleting a physical interface", resp) return resp
Get a physical interface. Parameters: - physicalInterfaceId ( string ) - draft ( boolean ) Throws APIException on failure.
def getPhysicalInterface(self, physicalInterfaceId, draft=False): """ Get a physical interface. Parameters: - physicalInterfaceId (string) - draft (boolean) Throws APIException on failure. """ if draft: req = ApiClient.onePhysicalInterfaceUrl % (self.host, "/draft", physicalInterfaceId) else: req = ApiClient.onePhysicalInterfaceUrl % (self.host, "", physicalInterfaceId) resp = requests.get(req, auth=self.credentials, verify=self.verify) if resp.status_code == 200: self.logger.debug("physical interface retrieved") else: raise ibmiotf.APIException(resp.status_code, "HTTP error getting a physical interface", resp) return resp.json()
Create an event mapping for a physical interface. Parameters: physicalInterfaceId ( string ) - value returned by the platform when creating the physical interface eventTypeId ( string ) - value returned by the platform when creating the event type eventId ( string ) - matches the event id used by the device in the MQTT topic Throws APIException on failure.
def createEvent(self, physicalInterfaceId, eventTypeId, eventId): """ Create an event mapping for a physical interface. Parameters: physicalInterfaceId (string) - value returned by the platform when creating the physical interface eventTypeId (string) - value returned by the platform when creating the event type eventId (string) - matches the event id used by the device in the MQTT topic Throws APIException on failure. """ req = ApiClient.allEventsUrl % (self.host, "/draft", physicalInterfaceId) body = {"eventId" : eventId, "eventTypeId" : eventTypeId} resp = requests.post(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body), verify=self.verify) if resp.status_code == 201: self.logger.debug("Event mapping created") else: raise ibmiotf.APIException(resp.status_code, "HTTP error creating event mapping", resp) return resp.json()
Delete an event mapping from a physical interface. Parameters: physicalInterfaceId ( string ) eventId ( string ). Throws APIException on failure.
def deleteEvent(self, physicalInterfaceId, eventId): """ Delete an event mapping from a physical interface. Parameters: physicalInterfaceId (string), eventId (string). Throws APIException on failure. """ req = ApiClient.oneEventUrl % (self.host, "/draft", physicalInterfaceId, eventId) resp = requests.delete(req, auth=self.credentials, verify=self.verify) if resp.status_code == 204: self.logger.debug("Event mapping deleted") else: raise ibmiotf.APIException(resp.status_code, "HTTP error deleting event mapping", resp) return resp
Get all logical interfaces for an org. Parameters: draft ( boolean ). Returns: - list of ids - response object Throws APIException on failure.
def getLogicalInterfaces(self, draft=False, name=None, schemaId=None): """ Get all logical interfaces for an org. Parameters: draft (boolean). Returns: - list of ids - response object Throws APIException on failure. """ if draft: req = ApiClient.allLogicalInterfacesUrl % (self.host, "/draft") else: req = ApiClient.allLogicalInterfacesUrl % (self.host, "") if name or schemaId: req += "?" if name: req += "name="+name if schemaId: if name: req += "&" req += "schemaId="+schemaId resp = requests.get(req, auth=self.credentials, verify=self.verify) if resp.status_code == 200: self.logger.debug("All logical interfaces retrieved") else: raise ibmiotf.APIException(resp.status_code, "HTTP error getting all logical interfaces", resp) return [x["id"] for x in resp.json()["results"]], resp.json()
Updates a logical interface. Parameters: logicalInterfaceId ( string ) name ( string ) schemaId ( string ) description ( string optional ). Throws APIException on failure.
def updateLogicalInterface(self, logicalInterfaceId, name, schemaId, description=None): """ Updates a logical interface. Parameters: logicalInterfaceId (string), name (string), schemaId (string), description (string, optional). Throws APIException on failure. """ req = ApiClient.oneLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId) body = {"name" : name, "schemaId" : schemaId, "id" : logicalInterfaceId} if description: body["description"] = description resp = requests.put(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body), verify=self.verify) if resp.status_code == 200: self.logger.debug("Logical interface updated") else: raise ibmiotf.APIException(resp.status_code, "HTTP error updating logical interface", resp) return resp.json()
Deletes a logical interface. Parameters: logicalInterfaceId ( string ). Throws APIException on failure.
def deleteLogicalInterface(self, logicalInterfaceId): """ Deletes a logical interface. Parameters: logicalInterfaceId (string). Throws APIException on failure. """ req = ApiClient.oneLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId) resp = requests.delete(req, auth=self.credentials, verify=self.verify) if resp.status_code == 204: self.logger.debug("logical interface deleted") else: raise ibmiotf.APIException(resp.status_code, "HTTP error deleting a logical interface", resp) return resp
Gets a logical interface. Parameters: - logicalInterfaceId ( string ) - draft ( boolean ) Throws APIException on failure.
def getLogicalInterface(self, logicalInterfaceId, draft=False): """ Gets a logical interface. Parameters: - logicalInterfaceId (string) - draft (boolean) Throws APIException on failure. """ if draft: req = ApiClient.oneLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId) else: req = ApiClient.oneLogicalInterfaceUrl % (self.host, "", logicalInterfaceId) resp = requests.get(req, auth=self.credentials, verify=self.verify) if resp.status_code == 200: self.logger.debug("logical interface retrieved") else: raise ibmiotf.APIException(resp.status_code, "HTTP error getting a logical interface", resp) return resp.json()
Gets a rule for a logical interface. Parameters: - logicalInterfaceId ( string ) - ruleId ( string ) - draft ( boolean ) Throws APIException on failure.
def getRuleForLogicalInterface(self, logicalInterfaceId, ruleId, draft=False): """ Gets a rule for a logical interface. Parameters: - logicalInterfaceId (string) - ruleId (string) - draft (boolean) Throws APIException on failure. """ if draft: req = ApiClient.oneRuleForLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId, ruleId) else: req = ApiClient.oneRuleForLogicalInterfaceUrl % (self.host, "", logicalInterfaceId, ruleId) resp = requests.get(req, auth=self.credentials, verify=self.verify) if resp.status_code == 200: self.logger.debug("logical interface rule retrieved") else: raise ibmiotf.APIException(resp.status_code, "HTTP error getting logical interface rule", resp) return resp.json()
Adds a rule to a logical interface. Parameters: - logicalInterfaceId ( string ) - name ( string ) - condition ( string ) - ( description ( string optional ) Returns: rule id ( string ) response ( object ). Throws APIException on failure.
def addRuleToLogicalInterface(self, logicalInterfaceId, name, condition, description=None, alias=None): """ Adds a rule to a logical interface. Parameters: - logicalInterfaceId (string) - name (string) - condition (string) - (description (string, optional) Returns: rule id (string), response (object). Throws APIException on failure. """ req = ApiClient.allRulesForLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId) body = {"name" : name, "condition" : condition} if description: body["description"] = description resp = requests.post(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body), verify=self.verify) if resp.status_code == 201: self.logger.debug("Logical interface rule created") else: raise ibmiotf.APIException(resp.status_code, "HTTP error creating logical interface rule", resp) return resp.json()["id"], resp.json()
Updates a rule on a logical interface.. Parameters: - logicalInterfaceId ( string ) - ruleId ( string ) - name ( string ) - condition ( string ) - description ( string optional ) Returns: response ( object ). Throws APIException on failure.
def updateRuleOnLogicalInterface(self, logicalInterfaceId, ruleId, name, condition, description=None): """ Updates a rule on a logical interface.. Parameters: - logicalInterfaceId (string), - ruleId (string) - name (string) - condition (string) - description (string, optional) Returns: response (object). Throws APIException on failure. """ req = ApiClient.oneRuleForLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId, ruleId) body = {"logicalInterfaceId" : logicalInterfaceId, "id" : ruleId, "name" : name, "condition" : condition} if description: body["description"] = description resp = requests.put(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body), verify=self.verify) if resp.status_code == 200: self.logger.debug("Logical interface rule updated") else: raise ibmiotf.APIException(resp.status_code, "HTTP error updating logical interface rule", resp) return resp.json()
Deletes a rule from a logical interface Parameters: - logicalInterfaceId ( string ) - ruleId ( string ) Returns: response ( object ) Throws APIException on failure
def deleteRuleOnLogicalInterface(self, logicalInterfaceId, ruleId): """ Deletes a rule from a logical interface Parameters: - logicalInterfaceId (string), - ruleId (string) Returns: response (object) Throws APIException on failure """ req = ApiClient.oneRuleForLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId, ruleId) resp = requests.delete(req, auth=self.credentials, verify=self.verify) if resp.status_code == 204: self.logger.debug("Logical interface rule deleted") else: raise ibmiotf.APIException(resp.status_code, "HTTP error deleting logical interface rule", resp) return resp
Adds a physical interface to a device type. Parameters: - typeId ( string ) - the device type - physicalInterfaceId ( string ) - the id returned by the platform on creation of the physical interface Throws APIException on failure.
def addPhysicalInterfaceToDeviceType(self, typeId, physicalInterfaceId): """ Adds a physical interface to a device type. Parameters: - typeId (string) - the device type - physicalInterfaceId (string) - the id returned by the platform on creation of the physical interface Throws APIException on failure. """ req = ApiClient.oneDeviceTypePhysicalInterfaceUrl % (self.host, "/draft", typeId) body = {"id" : physicalInterfaceId} resp = requests.post(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body), verify=self.verify) if resp.status_code == 201: self.logger.debug("Physical interface added to a device type") else: raise ibmiotf.APIException(resp.status_code, "HTTP error adding physical interface to a device type", resp) return resp.json()
Gets the physical interface associated with a device type. Parameters: - typeId ( string ) - the device type - draft ( boolean ) Throws APIException on failure.
def getPhysicalInterfaceOnDeviceType(self, typeId, draft=False): """ Gets the physical interface associated with a device type. Parameters: - typeId (string) - the device type - draft (boolean) Throws APIException on failure. """ if draft: req = ApiClient.oneDeviceTypePhysicalInterfaceUrl % (self.host, "/draft", typeId) else: req = ApiClient.oneDeviceTypePhysicalInterfaceUrl % (self.host, "", typeId) resp = requests.get(req, auth=self.credentials, headers={"Content-Type":"application/json"}, verify=self.verify) if resp.status_code == 200: self.logger.debug("Physical interface retrieved from a device type") else: raise ibmiotf.APIException(resp.status_code, "HTTP error getting physical interface on a device type", resp) return resp.json()["id"], resp.json()
Get all logical interfaces for a device type. Parameters: - typeId ( string ) - draft ( boolean ) Returns: - list of logical interface ids - HTTP response object Throws APIException on failure.
def getLogicalInterfacesOnDeviceType(self, typeId, draft=False): """ Get all logical interfaces for a device type. Parameters: - typeId (string) - draft (boolean) Returns: - list of logical interface ids - HTTP response object Throws APIException on failure. """ if draft: req = ApiClient.allDeviceTypeLogicalInterfacesUrl % (self.host, "/draft", typeId) else: req = ApiClient.allDeviceTypeLogicalInterfacesUrl % (self.host, "", typeId) resp = requests.get(req, auth=self.credentials, verify=self.verify) if resp.status_code == 200: self.logger.debug("All device type logical interfaces retrieved") else: raise ibmiotf.APIException(resp.status_code, "HTTP error getting all device type logical interfaces", resp) return [appintf["id"] for appintf in resp.json()], resp.json()
Adds a logical interface to a device type. Parameters: - typeId ( string ) - the device type - logicalInterfaceId ( string ) - the id returned by the platform on creation of the logical interface - description ( string ) - optional ( not used ) Throws APIException on failure.
def addLogicalInterfaceToDeviceType(self, typeId, logicalInterfaceId): """ Adds a logical interface to a device type. Parameters: - typeId (string) - the device type - logicalInterfaceId (string) - the id returned by the platform on creation of the logical interface - description (string) - optional (not used) Throws APIException on failure. """ req = ApiClient.allDeviceTypeLogicalInterfacesUrl % (self.host, "/draft", typeId) body = {"id" : logicalInterfaceId} # body = {"name" : "required but not used!!!", "id" : logicalInterfaceId, "schemaId" : schemaId} # if description: # body["description"] = description resp = requests.post(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body), verify=self.verify) if resp.status_code == 201: self.logger.debug("Logical interface added to a device type") else: raise ibmiotf.APIException(resp.status_code, "HTTP error adding logical interface to a device type", resp) return resp.json()
Removes a logical interface from a device type. Parameters: - typeId ( string ) - the device type - logicalInterfaceId ( string ) - the id returned by the platform on creation of the logical interface Throws APIException on failure.
def removeLogicalInterfaceFromDeviceType(self, typeId, logicalInterfaceId): """ Removes a logical interface from a device type. Parameters: - typeId (string) - the device type - logicalInterfaceId (string) - the id returned by the platform on creation of the logical interface Throws APIException on failure. """ req = ApiClient.oneDeviceTypeLogicalInterfaceUrl % (self.host, typeId, logicalInterfaceId) resp = requests.delete(req, auth=self.credentials, verify=self.verify) if resp.status_code == 204: self.logger.debug("Logical interface removed from a device type") else: raise ibmiotf.APIException(resp.status_code, "HTTP error removing logical interface from a device type", resp) return resp
Get all the mappings for a device type. Parameters: - typeId ( string ) - the device type - draft ( boolean ) - draft or active Throws APIException on failure.
def getMappingsOnDeviceType(self, typeId, draft=False): """ Get all the mappings for a device type. Parameters: - typeId (string) - the device type - draft (boolean) - draft or active Throws APIException on failure. """ if draft: req = ApiClient.allDeviceTypeMappingsUrl % (self.host, "/draft", typeId) else: req = ApiClient.allDeviceTypeMappingsUrl % (self.host, "", typeId) resp = requests.get(req, auth=self.credentials, verify=self.verify) if resp.status_code == 200: self.logger.debug("All device type mappings retrieved") else: raise ibmiotf.APIException(resp.status_code, "HTTP error getting all device type mappings", resp) return resp.json()
Gets the mappings for a logical interface from a device type. Parameters: - typeId ( string ) - the device type - logicalInterfaceId ( string ) - the platform returned id of the logical interface Throws APIException on failure.
def getMappingsOnDeviceTypeForLogicalInterface(self, typeId, logicalInterfaceId, draft=False): """ Gets the mappings for a logical interface from a device type. Parameters: - typeId (string) - the device type - logicalInterfaceId (string) - the platform returned id of the logical interface Throws APIException on failure. """ if draft: req = ApiClient.oneDeviceTypeMappingUrl % (self.host, "/draft", typeId, logicalInterfaceId) else: req = ApiClient.oneDeviceTypeMappingUrl % (self.host, "", typeId, logicalInterfaceId) resp = requests.get(req, auth=self.credentials, verify=self.verify) if resp.status_code == 200: self.logger.debug("Mappings retrieved from the device type") else: raise ibmiotf.APIException(resp.status_code, "HTTP error getting mappings for a logical interface from a device type", resp) return resp.json()
Validate the device type configuration. Parameters: - typeId ( string ) - the platform device type Throws APIException on failure.
def validateDeviceTypeConfiguration(self, typeId): """ Validate the device type configuration. Parameters: - typeId (string) - the platform device type Throws APIException on failure. """ req = ApiClient.draftDeviceTypeUrl % (self.host, typeId) body = {"operation" : "validate-configuration"} resp = requests.patch(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body), verify=self.verify) if resp.status_code == 200: self.logger.debug("Validation for device type configuration succeeded") else: raise ibmiotf.APIException(resp.status_code, "Validation for device type configuration failed", resp) return resp.json()
Validate the logical interface configuration. Parameters: - logicalInterfaceId ( string ) Throws APIException on failure.
def validateLogicalInterfaceConfiguration(self, logicalInterfaceId): """ Validate the logical interface configuration. Parameters: - logicalInterfaceId (string) Throws APIException on failure. """ req = ApiClient.oneLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId) body = {"operation" : "validate-configuration"} resp = requests.patch(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body), verify=self.verify) if resp.status_code == 200: self.logger.debug("Validation for logical interface configuration succeeded") else: raise ibmiotf.APIException(resp.status_code, "Validation for logical interface configuration failed", resp) return resp.json()
Gets the state for a logical interface for a device. Parameters: - typeId ( string ) - the platform device type - deviceId ( string ) - the platform device id - logicalInterfaceId ( string ) - the platform returned id of the logical interface Throws APIException on failure.
def getDeviceStateForLogicalInterface(self, typeId, deviceId, logicalInterfaceId): """ Gets the state for a logical interface for a device. Parameters: - typeId (string) - the platform device type - deviceId (string) - the platform device id - logicalInterfaceId (string) - the platform returned id of the logical interface Throws APIException on failure. """ req = ApiClient.deviceStateUrl % (self.host, typeId, deviceId, logicalInterfaceId) resp = requests.get(req, auth=self.credentials, verify=self.verify) if resp.status_code == 200: self.logger.debug("State retrieved from the device type for a logical interface") else: raise ibmiotf.APIException(resp.status_code, "HTTP error getting state for a logical interface from a device type", resp) return resp.json()
Gets the state for a logical interface for a thing. Parameters: - thingTypeId ( string ) - the platform thing type - thingId ( string ) - the platform thing id - logicalInterfaceId ( string ) - the platform returned id of the logical interface Throws APIException on failure.
def getThingStateForLogicalInterface(self, thingTypeId, thingId, logicalInterfaceId): """ Gets the state for a logical interface for a thing. Parameters: - thingTypeId (string) - the platform thing type - thingId (string) - the platform thing id - logicalInterfaceId (string) - the platform returned id of the logical interface Throws APIException on failure. """ req = ApiClient.thingStateUrl % (self.host, thingTypeId, thingId, logicalInterfaceId) resp = requests.get(req, auth=self.credentials, verify=self.verify) if resp.status_code == 200: self.logger.debug("State retrieved from the thing type for a logical interface") else: raise ibmiotf.APIException(resp.status_code, "HTTP error getting state for a logical interface from a thing type", resp) return resp.json()
Perform an operation against the thing state for a logical interface Parameters: - thingTypeId ( string ) - thingId ( string ) - logicalInterfaceId ( string ) Throws APIException on failure.
def resetThingStateForLogicalInterface(self, thingTypeId, thingId , logicalInterfaceId): """ Perform an operation against the thing state for a logical interface Parameters: - thingTypeId (string) - thingId (string) - logicalInterfaceId (string) Throws APIException on failure. """ req = ApiClient.thingStateUrl % (self.host, "", thingTypeId,thingId , logicalInterfaceId) body = {"operation" : "reset-state"} resp = requests.patch(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body), verify=self.verify) if (resp.status_code == 200): self.logger.debug("Reset ThingState For LogicalInterface succeeded") else: raise ibmiotf.APIException(resp.status_code, " HTTP error on reset ThingState For LogicalInterface ", resp) return resp.json()
Get all logical interfaces for a thing type. Parameters: - thingTypeId ( string ) - draft ( boolean ) Returns: - list of logical interface ids - HTTP response object Throws APIException on failure.
def getLogicalInterfacesOnThingType(self, thingTypeId, draft=False): """ Get all logical interfaces for a thing type. Parameters: - thingTypeId (string) - draft (boolean) Returns: - list of logical interface ids - HTTP response object Throws APIException on failure. """ if draft: req = ApiClient.allThingTypeLogicalInterfacesUrl % (self.host, "/draft", thingTypeId) else: req = ApiClient.allThingTypeLogicalInterfacesUrl % (self.host, "", thingTypeId) resp = requests.get(req, auth=self.credentials, verify=self.verify) if resp.status_code == 200: self.logger.debug("All thing type logical interfaces retrieved") else: raise ibmiotf.APIException(resp.status_code, "HTTP error getting all thing type logical interfaces", resp) return [appintf["id"] for appintf in resp.json()], resp.json()
Adds a logical interface to a thing type. Parameters: - thingTypeId ( string ) - the thing type - logicalInterfaceId ( string ) - the id returned by the platform on creation of the logical interface Throws APIException on failure.
def addLogicalInterfaceToThingType(self, thingTypeId, logicalInterfaceId, schemaId = None, name = None): """ Adds a logical interface to a thing type. Parameters: - thingTypeId (string) - the thing type - logicalInterfaceId (string) - the id returned by the platform on creation of the logical interface Throws APIException on failure. """ req = ApiClient.allThingTypeLogicalInterfacesUrl % (self.host, "/draft", thingTypeId) body = {"id" : logicalInterfaceId} # body = {"name" : name, "id" : logicalInterfaceId, "schemaId" : schemaId} # if description: # body["description"] = description resp = requests.post(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body), verify=self.verify) if resp.status_code == 201: self.logger.debug("The draft logical interface was successfully associated with the thing type.") else: raise ibmiotf.APIException(resp.status_code, "HTTP error adding logical interface to a thing type", resp) return resp.json()
Removes a logical interface from a thing type. Parameters: - thingTypeId ( string ) - the thing type - logicalInterfaceId ( string ) - the id returned by the platform on creation of the logical interface Throws APIException on failure.
def removeLogicalInterfaceFromThingType(self, thingTypeId, logicalInterfaceId): """ Removes a logical interface from a thing type. Parameters: - thingTypeId (string) - the thing type - logicalInterfaceId (string) - the id returned by the platform on creation of the logical interface Throws APIException on failure. """ req = ApiClient.oneThingTypeLogicalInterfaceUrl % (self.host, thingTypeId, logicalInterfaceId) resp = requests.delete(req, auth=self.credentials, verify=self.verify) if resp.status_code == 204: self.logger.debug("Logical interface removed from a thing type") else: raise ibmiotf.APIException(resp.status_code, "HTTP error removing logical interface from a thing type", resp) return resp
Get all the mappings for a thing type. Parameters: - thingTypeId ( string ) - the thing type - draft ( boolean ) - draft or active Throws APIException on failure.
def getMappingsOnThingType(self, thingTypeId, draft=False): """ Get all the mappings for a thing type. Parameters: - thingTypeId (string) - the thing type - draft (boolean) - draft or active Throws APIException on failure. """ if draft: req = ApiClient.allThingTypeMappingsUrl % (self.host, "/draft", thingTypeId) else: req = ApiClient.allThingTypeMappingsUrl % (self.host, "", thingTypeId) resp = requests.get(req, auth=self.credentials, verify=self.verify) if resp.status_code == 200: self.logger.debug("All thing type mappings retrieved") else: raise ibmiotf.APIException(resp.status_code, "HTTP error getting all thing type mappings", resp) return resp.json()
Gets the mappings for a logical interface from a thing type. Parameters: - thingTypeId ( string ) - the thing type - logicalInterfaceId ( string ) - the platform returned id of the logical interface Throws APIException on failure.
def getMappingsOnThingTypeForLogicalInterface(self, thingTypeId, logicalInterfaceId, draft=False): """ Gets the mappings for a logical interface from a thing type. Parameters: - thingTypeId (string) - the thing type - logicalInterfaceId (string) - the platform returned id of the logical interface Throws APIException on failure. """ if draft: req = ApiClient.oneThingTypeMappingUrl % (self.host, "/draft", thingTypeId, logicalInterfaceId) else: req = ApiClient.oneThingTypeMappingUrl % (self.host, "", thingTypeId, logicalInterfaceId) resp = requests.get(req, auth=self.credentials, verify=self.verify) if resp.status_code == 200: self.logger.debug("Mappings retrieved from the thing type") else: raise ibmiotf.APIException(resp.status_code, "HTTP error getting mappings for a logical interface from a thing type", resp) return resp.json()
Add mappings for a thing type. Parameters: - thingTypeId ( string ) - the thing type - logicalInterfaceId ( string ) - the id of the application interface these mappings are for - notificationStrategy ( string ) - the notification strategy to use for these mappings - mappingsObject ( Python dictionary corresponding to JSON object ) example:
def updateMappingsOnDeviceType(self, thingTypeId, logicalInterfaceId, mappingsObject, notificationStrategy = "never"): """ Add mappings for a thing type. Parameters: - thingTypeId (string) - the thing type - logicalInterfaceId (string) - the id of the application interface these mappings are for - notificationStrategy (string) - the notification strategy to use for these mappings - mappingsObject (Python dictionary corresponding to JSON object) example: { # eventid -> { property -> eventid property expression } "status" : { "eventCount" : "($state.eventCount == -1) ? $event.d.count : ($state.eventCount+1)", } } Throws APIException on failure. """ req = ApiClient.oneThingTypeMappingUrl % (self.host, "/draft", thingTypeId, logicalInterfaceId) try: mappings = json.dumps({ "logicalInterfaceId" : logicalInterfaceId, "notificationStrategy" : notificationStrategy, "propertyMappings" : mappingsObject }) except Exception as exc: raise ibmiotf.APIException(-1, "Exception formatting mappings object to JSON", exc) resp = requests.put(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=mappings, verify=self.verify) if resp.status_code == 200: self.logger.debug("Thing type mappings updated for logical interface") else: raise ibmiotf.APIException(resp.status_code, "HTTP error updating thing type mappings for logical interface", resp) return resp.json()
Connect the client to IBM Watson IoT Platform using the underlying Paho MQTT client # Raises ConnectionException: If there is a problem establishing the connection.
def connect(self): """ Connect the client to IBM Watson IoT Platform using the underlying Paho MQTT client # Raises ConnectionException: If there is a problem establishing the connection. """ self.logger.debug( "Connecting... (address = %s, port = %s, clientId = %s, username = %s)" % (self.address, self.port, self.clientId, self.username) ) try: self.connectEvent.clear() self.client.connect(self.address, port=self.port, keepalive=self.keepAlive) self.client.loop_start() if not self.connectEvent.wait(timeout=30): self.client.loop_stop() self._logAndRaiseException( ConnectionException( "Operation timed out connecting to IBM Watson IoT Platform: %s" % (self.address) ) ) except socket.error as serr: self.client.loop_stop() self._logAndRaiseException( ConnectionException("Failed to connect to IBM Watson IoT Platform: %s - %s" % (self.address, str(serr))) )
Disconnect the client from IBM Watson IoT Platform
def disconnect(self): """ Disconnect the client from IBM Watson IoT Platform """ # self.logger.info("Closing connection to the IBM Watson IoT Platform") self.client.disconnect() # If we don't call loop_stop() it appears we end up with a zombie thread which continues to process # network traffic, preventing any subsequent attempt to reconnect using connect() self.client.loop_stop() self.logger.info("Closed connection to the IBM Watson IoT Platform")
Called when the client has log information. See [ paho. mqtt. python#on_log ] ( https:// github. com/ eclipse/ paho. mqtt. python#on_log ) for more information # Parameters mqttc ( paho. mqtt. client. Client ): The client instance for this callback obj ( object ): The private user data as set in Client () or user_data_set () level ( int ): The severity of the message will be one of MQTT_LOG_INFO MQTT_LOG_NOTICE MQTT_LOG_WARNING MQTT_LOG_ERR and MQTT_LOG_DEBUG. string ( string ): The log message itself
def _onLog(self, mqttc, obj, level, string): """ Called when the client has log information. See [paho.mqtt.python#on_log](https://github.com/eclipse/paho.mqtt.python#on_log) for more information # Parameters mqttc (paho.mqtt.client.Client): The client instance for this callback obj (object): The private user data as set in Client() or user_data_set() level (int): The severity of the message, will be one of `MQTT_LOG_INFO`, `MQTT_LOG_NOTICE`, `MQTT_LOG_WARNING`, `MQTT_LOG_ERR`, and `MQTT_LOG_DEBUG`. string (string): The log message itself """ self.logger.debug("%d %s" % (level, string))
Called when the broker responds to our connection request.
def _onConnect(self, mqttc, userdata, flags, rc): """ Called when the broker responds to our connection request. The value of rc determines success or not: 0: Connection successful 1: Connection refused - incorrect protocol version 2: Connection refused - invalid client identifier 3: Connection refused - server unavailable 4: Connection refused - bad username or password 5: Connection refused - not authorised 6-255: Currently unused. """ if rc == 0: self.connectEvent.set() self.logger.info("Connected successfully: %s" % (self.clientId)) # Restoring previous subscriptions with self._subLock: if len(self._subscriptions) > 0: for subscription in self._subscriptions: # We use the underlying mqttclient subscribe method rather than _subscribe because we are # claiming a lock on the subscriptions list and do not want anything else to modify it, # which that method does (result, mid) = self.client.subscribe(subscription, qos=self._subscriptions[subscription]) if result != paho.MQTT_ERR_SUCCESS: self._logAndRaiseException(ConnectionException("Unable to subscribe to %s" % subscription)) self.logger.debug("Restored %s previous subscriptions" % len(self._subscriptions)) elif rc == 1: self._logAndRaiseException(ConnectionException("Incorrect protocol version")) elif rc == 2: self._logAndRaiseException(ConnectionException("Invalid client identifier")) elif rc == 3: self._logAndRaiseException(ConnectionException("Server unavailable")) elif rc == 4: self._logAndRaiseException( ConnectionException("Bad username or password: (%s, %s)" % (self.username, self.password)) ) elif rc == 5: self._logAndRaiseException( ConnectionException("Not authorized: s (%s, %s, %s)" % (self.clientId, self.username, self.password)) ) else: self._logAndRaiseException(ConnectionException("Unexpected connection failure: %s" % (rc)))
Called when the client disconnects from IBM Watson IoT Platform. See [ paho. mqtt. python#on_disconnect ] ( https:// github. com/ eclipse/ paho. mqtt. python#on_disconnect ) for more information # Parameters mqttc ( paho. mqtt. client. Client ): The client instance for this callback obj ( object ): The private user data as set in Client () or user_data_set () rc ( int ): indicates the disconnection state. If MQTT_ERR_SUCCESS ( 0 ) the callback was called in response to a disconnect () call. If any other value the disconnection was unexpected such as might be caused by a network error.
def _onDisconnect(self, mqttc, obj, rc): """ Called when the client disconnects from IBM Watson IoT Platform. See [paho.mqtt.python#on_disconnect](https://github.com/eclipse/paho.mqtt.python#on_disconnect) for more information # Parameters mqttc (paho.mqtt.client.Client): The client instance for this callback obj (object): The private user data as set in Client() or user_data_set() rc (int): indicates the disconnection state. If `MQTT_ERR_SUCCESS` (0), the callback was called in response to a `disconnect()` call. If any other value the disconnection was unexpected, such as might be caused by a network error. """ # Clear the event to indicate we're no longer connected self.connectEvent.clear() if rc != 0: self.logger.error("Unexpected disconnect from IBM Watson IoT Platform: %d" % (rc)) else: self.logger.info("Disconnected from IBM Watson IoT Platform")
Called when a message from the client has been successfully sent to IBM Watson IoT Platform. See [ paho. mqtt. python#on_publish ] ( https:// github. com/ eclipse/ paho. mqtt. python#on_publish ) for more information # Parameters mqttc ( paho. mqtt. client. Client ): The client instance for this callback obj ( object ): The private user data as set in Client () or user_data_set () mid ( int ): Gives the message id of the successfully published message.
def _onPublish(self, mqttc, obj, mid): """ Called when a message from the client has been successfully sent to IBM Watson IoT Platform. See [paho.mqtt.python#on_publish](https://github.com/eclipse/paho.mqtt.python#on_publish) for more information # Parameters mqttc (paho.mqtt.client.Client): The client instance for this callback obj (object): The private user data as set in Client() or user_data_set() mid (int): Gives the message id of the successfully published message. """ with self._messagesLock: if mid in self._onPublishCallbacks: midOnPublish = self._onPublishCallbacks.get(mid) del self._onPublishCallbacks[mid] if midOnPublish != None: midOnPublish() else: # record the fact that paho callback has already come through so it can be called inline # with the publish. self._onPublishCallbacks[mid] = None
Subscribe to device event messages
def subscribeToDeviceEvents(self, typeId="+", deviceId="+", eventId="+", msgFormat="+", qos=0): """ Subscribe to device event messages # Parameters typeId (string): typeId for the subscription, optional. Defaults to all device types (MQTT `+` wildcard) deviceId (string): deviceId for the subscription, optional. Defaults to all devices (MQTT `+` wildcard) eventId (string): eventId for the subscription, optional. Defaults to all events (MQTT `+` wildcard) msgFormat (string): msgFormat for the subscription, optional. Defaults to all formats (MQTT `+` wildcard) qos (int): MQTT quality of service level to use (`0`, `1`, or `2`) # Returns int: If the subscription was successful then the return Message ID (mid) for the subscribe request will be returned. The mid value can be used to track the subscribe request by checking against the mid argument if you register a subscriptionCallback method. If the subscription fails then the return value will be `0` """ if self._config.isQuickstart() and deviceId == "+": self.logger.warning( "QuickStart applications do not support wildcard subscription to events from all devices" ) return 0 topic = "iot-2/type/%s/id/%s/evt/%s/fmt/%s" % (typeId, deviceId, eventId, msgFormat) return self._subscribe(topic, qos)
Subscribe to device status messages
def subscribeToDeviceStatus(self, typeId="+", deviceId="+"): """ Subscribe to device status messages # Parameters typeId (string): typeId for the subscription, optional. Defaults to all device types (MQTT `+` wildcard) deviceId (string): deviceId for the subscription, optional. Defaults to all devices (MQTT `+` wildcard) # Returns int: If the subscription was successful then the return Message ID (mid) for the subscribe request will be returned. The mid value can be used to track the subscribe request by checking against the mid argument if you register a subscriptionCallback method. If the subscription fails then the return value will be `0` """ if self._config.isQuickstart() and deviceId == "+": self.logger.warning("QuickStart applications do not support wildcard subscription to device status") return 0 topic = "iot-2/type/%s/id/%s/mon" % (typeId, deviceId) return self._subscribe(topic, 0)
Subscribe to device command messages
def subscribeToDeviceCommands(self, typeId="+", deviceId="+", commandId="+", msgFormat="+"): """ Subscribe to device command messages # Parameters typeId (string): typeId for the subscription, optional. Defaults to all device types (MQTT `+` wildcard) deviceId (string): deviceId for the subscription, optional. Defaults to all devices (MQTT `+` wildcard) commandId (string): commandId for the subscription, optional. Defaults to all commands (MQTT `+` wildcard) msgFormat (string): msgFormat for the subscription, optional. Defaults to all formats (MQTT `+` wildcard) qos (int): MQTT quality of service level to use (`0`, `1`, or `2`) # Returns int: If the subscription was successful then the return Message ID (mid) for the subscribe request will be returned. The mid value can be used to track the subscribe request by checking against the mid argument if you register a subscriptionCallback method. If the subscription fails then the return value will be `0` """ if self._config.isQuickstart(): self.logger.warning("QuickStart applications do not support commands") return 0 topic = "iot-2/type/%s/id/%s/cmd/%s/fmt/%s" % (typeId, deviceId, commandId, msgFormat) return self._subscribe(topic, 0)
Publish a command to a device
def publishCommand(self, typeId, deviceId, commandId, msgFormat, data=None, qos=0, on_publish=None): """ Publish a command to a device # Parameters typeId (string) : The type of the device this command is to be published to deviceId (string): The id of the device this command is to be published to command (string) : The name of the command msgFormat (string) : The format of the command payload data (dict) : The command data qos (int) : The equivalent MQTT semantics of quality of service using the same constants (optional, defaults to `0`) on_publish (function) : A function that will be called when receipt of the publication is confirmed. This has different implications depending on the qos: - qos 0 : the client has asynchronously begun to send the event - qos 1 and 2 : the client has confirmation of delivery from WIoTP """ if self._config.isQuickstart(): self.logger.warning("QuickStart applications do not support sending commands") return False if not self.connectEvent.wait(timeout=10): return False else: topic = "iot-2/type/%s/id/%s/cmd/%s/fmt/%s" % (typeId, deviceId, commandId, msgFormat) # Raise an exception if there is no codec for this msgFormat if self.getMessageCodec(msgFormat) is None: raise MissingMessageEncoderException(msgFormat) payload = self.getMessageCodec(msgFormat).encode(data, datetime.now()) result = self.client.publish(topic, payload=payload, qos=qos, retain=False) if result[0] == paho.MQTT_ERR_SUCCESS: # Because we are dealing with aync pub/sub model and callbacks it is possible that # the _onPublish() callback for this mid is called before we obtain the lock to place # the mid into the _onPublishCallbacks list. # # _onPublish knows how to handle a scenario where the mid is not present (no nothing) # in this scenario we will need to invoke the callback directly here, because at the time # the callback was invoked the mid was not yet in the list. with self._messagesLock: if result[1] in self._onPublishCallbacks: # paho callback beat this thread so call callback inline now del self._onPublishCallbacks[result[1]] if on_publish is not None: on_publish() else: # this thread beat paho callback so set up for call later self._onPublishCallbacks[result[1]] = on_publish return True else: return False
Internal callback for messages that have not been handled by any of the specific internal callbacks these messages are not passed on to any user provided callback
def _onUnsupportedMessage(self, client, userdata, message): """ Internal callback for messages that have not been handled by any of the specific internal callbacks, these messages are not passed on to any user provided callback """ self.logger.warning( "Received messaging on unsupported topic '%s' on topic '%s'" % (message.payload, message.topic) )
Internal callback for device event messages parses source device from topic string and passes the information on to the registerd device event callback
def _onDeviceEvent(self, client, userdata, pahoMessage): """ Internal callback for device event messages, parses source device from topic string and passes the information on to the registerd device event callback """ try: event = Event(pahoMessage, self._messageCodecs) self.logger.debug("Received event '%s' from %s:%s" % (event.eventId, event.typeId, event.deviceId)) if self.deviceEventCallback: self.deviceEventCallback(event) except InvalidEventException as e: self.logger.critical(str(e))
Internal callback for device status messages parses source device from topic string and passes the information on to the registerd device status callback
def _onDeviceStatus(self, client, userdata, pahoMessage): """ Internal callback for device status messages, parses source device from topic string and passes the information on to the registerd device status callback """ try: status = Status(pahoMessage) self.logger.debug("Received %s action from %s" % (status.action, status.clientId)) if self.deviceStatusCallback: self.deviceStatusCallback(status) except InvalidEventException as e: self.logger.critical(str(e))
Internal callback for application command messages parses source application from topic string and passes the information on to the registerd applicaion status callback
def _onAppStatus(self, client, userdata, pahoMessage): """ Internal callback for application command messages, parses source application from topic string and passes the information on to the registerd applicaion status callback """ try: status = Status(pahoMessage) self.logger.debug("Received %s action from %s" % (status.action, status.clientId)) if self.appStatusCallback: self.appStatusCallback(status) except InvalidEventException as e: self.logger.critical(str(e))
Parse environment variables into a Python dictionary suitable for passing to the device client constructor as the options parameter
def parseEnvVars(): """ Parse environment variables into a Python dictionary suitable for passing to the device client constructor as the `options` parameter - `WIOTP_IDENTITY_ORGID` - `WIOTP_IDENTITY_TYPEID` - `WIOTP_IDENTITY_DEVICEID` - `WIOTP_AUTH_TOKEN` - `WIOTP_OPTIONS_DOMAIN` (optional) - `WIOTP_OPTIONS_LOGLEVEL` (optional) - `WIOTP_OPTIONS_MQTT_PORT` (optional) - `WIOTP_OPTIONS_MQTT_TRANSPORT` (optional) - `WIOTP_OPTIONS_MQTT_CAFILE` (optional) - `WIOTP_OPTIONS_MQTT_CLEANSTART` (optional) - `WIOTP_OPTIONS_MQTT_SESSIONEXPIRY` (optional) - `WIOTP_OPTIONS_MQTT_KEEPALIVE` (optional) """ # Identify orgId = os.getenv("WIOTP_IDENTITY_ORGID", None) typeId = os.getenv("WIOTP_IDENTITY_TYPEID", None) deviceId = os.getenv("WIOTP_IDENTITY_DEVICEID", None) # Auth authToken = os.getenv("WIOTP_AUTH_TOKEN", None) # Options domain = os.getenv("WIOTP_OPTIONS_DOMAIN", None) logLevel = os.getenv("WIOTP_OPTIONS_LOGLEVEL", "info") port = os.getenv("WIOTP_OPTIONS_MQTT_PORT", None) transport = os.getenv("WIOTP_OPTIONS_MQTT_TRANSPORT", None) caFile = os.getenv("WIOTP_OPTIONS_MQTT_CAFILE", None) cleanStart = os.getenv("WIOTP_OPTIONS_MQTT_CLEANSTART", "False") sessionExpiry = os.getenv("WIOTP_OPTIONS_MQTT_SESSIONEXPIRY", "3600") keepAlive = os.getenv("WIOTP_OPTIONS_MQTT_KEEPALIVE", "60") caFile = os.getenv("WIOTP_OPTIONS_MQTT_CAFILE", None) if orgId is None: raise ConfigurationException("Missing WIOTP_IDENTITY_ORGID environment variable") if typeId is None: raise ConfigurationException("Missing WIOTP_IDENTITY_TYPEID environment variable") if deviceId is None: raise ConfigurationException("Missing WIOTP_IDENTITY_DEVICEID environment variable") if orgId != "quickstart" and authToken is None: raise ConfigurationException("Missing WIOTP_AUTH_TOKEN environment variable") if port is not None: try: port = int(port) except ValueError as e: raise ConfigurationException("WIOTP_OPTIONS_MQTT_PORT must be a number") try: sessionExpiry = int(sessionExpiry) except ValueError as e: raise ConfigurationException("WIOTP_OPTIONS_MQTT_SESSIONEXPIRY must be a number") try: keepAlive = int(keepAlive) except ValueError as e: raise ConfigurationException("WIOTP_OPTIONS_MQTT_KEEPAIVE must be a number") if logLevel not in ["error", "warning", "info", "debug"]: raise ConfigurationException("WIOTP_OPTIONS_LOGLEVEL must be one of error, warning, info, debug") else: # Convert log levels from string to int (we need to upper case our strings from the config) logLevel = logging.getLevelName(logLevel.upper()) cfg = { "identity": {"orgId": orgId, "typeId": typeId, "deviceId": deviceId}, "options": { "domain": domain, "logLevel": logLevel, "mqtt": { "port": port, "transport": transport, "caFile": caFile, "cleanStart": cleanStart in ["True", "true", "1"], "sessionExpiry": sessionExpiry, "keepAlive": keepAlive, }, }, } # Quickstart doesn't support auth, so ensure we only add this if it's defined if authToken is not None: cfg["auth"] = {"token": authToken} return cfg
Retrieves the last cached message for specified event from a specific device.
def get(self, deviceUid, eventId): """ Retrieves the last cached message for specified event from a specific device. """ if not isinstance(deviceUid, DeviceUid) and isinstance(deviceUid, dict): deviceUid = DeviceUid(**deviceUid) url = "api/v0002/device/types/%s/devices/%s/events/%s" % (deviceUid.typeId, deviceUid.deviceId, eventId) r = self._apiClient.get(url) if r.status_code == 200: return LastEvent(**r.json()) else: raise ApiException(r)
Retrieves a list of the last cached message for all events from a specific device.
def getAll(self, deviceUid): """ Retrieves a list of the last cached message for all events from a specific device. """ if not isinstance(deviceUid, DeviceUid) and isinstance(deviceUid, dict): deviceUid = DeviceUid(**deviceUid) url = "api/v0002/device/types/%s/devices/%s/events" % (deviceUid.typeId, deviceUid.deviceId) r = self._apiClient.get(url) if r.status_code == 200: events = [] for event in r.json(): events.append(LastEvent(**event)) return events else: raise ApiException(r)
Retrieve bulk devices It accepts accepts a list of parameters In case of failure it throws Exception
def _makeApiCall(self, parameters=None): """ Retrieve bulk devices It accepts accepts a list of parameters In case of failure it throws Exception """ r = self._apiClient.get(self._url, parameters) if r.status_code == 200: return r.json() else: raise Exception("HTTP %s %s" % (r.status_code, r.text))