Instruction:
Can you create a Python 3 function that
handles responses to subscribe command. Registers a channel id with the client and assigns a data handler to it.

Response:
def _handle_subscribed(self, dtype, data, ts,):
        """Handles responses to subscribe() commands.

        Registers a channel id with the client and assigns a data handler to it.

        :param dtype:
        :param data:
        :param ts:
        :return:
        """
        self.log.debug("_handle_subscribed: %s - %s - %s", dtype, data, ts)
        channel_name = data.pop('channel')
        channel_id = data.pop('chanId')
        config = data

        if 'pair' in config:
            symbol = config['pair']
            if symbol.startswith('t'):
                symbol = symbol[1:]
        elif 'symbol' in config:
            symbol = config['symbol']
            if symbol.startswith('t'):
                symbol = symbol[1:]
        elif 'key' in config:
            symbol = config['key'].split(':')[2][1:]  #layout type:interval:tPair
        else:
            symbol = None

        if 'prec' in config and config['prec'].startswith('R'):
            channel_name = 'raw_' + channel_name

        self.channel_handlers[channel_id] = self._data_handlers[channel_name]

        # Create a channel_name, symbol tuple to identify channels of same type
        if 'key' in config:
            identifier = (channel_name, symbol, config['key'].split(':')[1])
        else:
            identifier = (channel_name, symbol)
        self.channel_handlers[channel_id] = identifier
        self.channel_directory[identifier] = channel_id
        self.channel_directory[channel_id] = identifier
        self.log.info("Subscription succesful for channel %s", identifier)


Instruction:
Implement a Python 3 function for
handling responses to unsubscribe() commands.

Response:
def _handle_unsubscribed(self, dtype, data, ts):
        """Handles responses to unsubscribe() commands.

        Removes a channel id from the client.

        :param dtype:
        :param data:
        :param ts:
        :return:
        """
        self.log.debug("_handle_unsubscribed: %s - %s - %s", dtype, data, ts)
        channel_id = data.pop('chanId')

        # Unregister the channel from all internal attributes
        chan_identifier = self.channel_directory.pop(channel_id)
        self.channel_directory.pop(chan_identifier)
        self.channel_handlers.pop(channel_id)
        self.last_update.pop(channel_id)
        self.log.info("Successfully unsubscribed from %s", chan_identifier)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _handle_auth(self, dtype, data, ts):
        # Contains keys status, chanId, userId, caps
        if dtype == 'unauth':
            raise NotImplementedError
        channel_id = data.pop('chanId')
        user_id = data.pop('userId')

        identifier = ('auth', user_id)
        self.channel_handlers[identifier] = channel_id
        self.channel_directory[identifier] = channel_id
        self.channel_directory[channel_id] = identifier

Response:
Handles authentication responses.

        :param dtype:
        :param data:
        :param ts:
        :return:


Instruction:
Make a summary of the following Python 3 code
def _handle_conf(self, dtype, data, ts):
        self.log.debug("_handle_conf: %s - %s - %s", dtype, data, ts)
        self.log.info("Configuration accepted: %s", dtype)
        return

Response:
Handles configuration messages.

        :param dtype:
        :param data:
        :param ts:
        :return:


Instruction:
Can you write a function in Python 3 where it
updates the timestamp for the given channel id.

Response:
def update_timestamps(self, chan_id, ts):
        """Updates the timestamp for the given channel id.

        :param chan_id:
        :param ts:
        :return:
        """
        try:
            self.last_update[chan_id] = ts
        except KeyError:
            self.log.warning("Attempted ts update of channel %s, but channel "
                             "not present anymore.",
                             self.channel_directory[chan_id])


Instruction:
Implement a Python 3 function for
handling related data for the account related data.

Response:
def _handle_account(self, data, ts):
        """ Handles Account related data.

        translation table for channel names:
            Data Channels
            os      -   Orders
            hos     -   Historical Orders
            ps      -   Positions
            hts     -   Trades (snapshot)
            te      -   Trade Event
            tu      -   Trade Update
            ws      -   Wallets
            bu      -   Balance Info
            miu     -   Margin Info
            fiu     -   Funding Info
            fos     -   Offers
            hfos    -   Historical Offers
            fcs     -   Credits
            hfcs    -   Historical Credits
            fls     -   Loans
            hfls    -   Historical Loans
            htfs    -   Funding Trades
            n       -   Notifications (WIP)

        :param dtype:
        :param data:
        :param ts:
        :return:
        """
        # channel_short, data
        chan_id, channel_short_name, *data = data
        entry = (channel_short_name, data, ts)
        self.account.put(entry)


Instruction:
Given the following Python 3 function, write the documentation
def _handle_ticker(self, dtype, data, ts):
        self.log.debug("_handle_ticker: %s - %s - %s", dtype, data, ts)
        channel_id, *data = data
        channel_identifier = self.channel_directory[channel_id]

        entry = (data, ts)
        self.tickers[channel_identifier].put(entry)

Response: Adds received ticker data to self. tickers dict.


Instruction:
Can you generate the documentation for the following Python 3 function
def _handle_book(self, dtype, data, ts):
        self.log.debug("_handle_book: %s - %s - %s", dtype, data, ts)
        channel_id, *data = data
        log.debug("ts: %s\tchan_id: %s\tdata: %s", ts, channel_id, data)
        channel_identifier = self.channel_directory[channel_id]
        entry = (data, ts)
        self.books[channel_identifier].put(entry)

Response: Handle a new order book.


Instruction:
Can you create a Python 3 function that
handles a raw order book.

Response:
def _handle_raw_book(self, dtype, data, ts):
        """Updates the raw order books stored in self.raw_books[chan_id].

        :param dtype:
        :param data:
        :param ts:
        :return:
        """
        self.log.debug("_handle_raw_book: %s - %s - %s", dtype, data, ts)
        channel_id, *data = data
        channel_identifier = self.channel_directory[channel_id]
        entry = (data, ts)
        self.raw_books[channel_identifier].put(entry)


Instruction:
How would you code a function in Python 3 to
handle trades from the channel.

Response:
def _handle_trades(self, dtype, data, ts):
        """Files trades in self._trades[chan_id].

        :param dtype:
        :param data:
        :param ts:
        :return:
        """
        self.log.debug("_handle_trades: %s - %s - %s", dtype, data, ts)
        channel_id, *data = data
        channel_identifier = self.channel_directory[channel_id]
        entry = (data, ts)
        self.trades[channel_identifier].put(entry)


Instruction:
Write a Python 3 script to
store the data received via wss in self. candles [ chan_id ].

Response:
def _handle_candles(self, dtype, data, ts):
        """Stores OHLC data received via wss in self.candles[chan_id].

        :param dtype:
        :param data:
        :param ts:
        :return:
        """
        self.log.debug("_handle_candles: %s - %s - %s", dtype, data, ts)
        channel_id, *data = data
        channel_identifier = self.channel_directory[channel_id]
        entry = (data, ts)
        self.candles[channel_identifier].put(entry)


Instruction:
Given the following Python 3 function, write the documentation
def reset(self):
        self.conn.reconnect()
        while not self.conn.connected.is_set():
            log.info("reset(): Waiting for connection to be set up..")
            time.sleep(1)

        for key in self.channel_configs:
            self.conn.send(**self.channel_configs[key])

Response:
Reset the client.

        :return:


Instruction:
Write a Python 3 function that can
return a queue containing all candles data for the given symbol pair.

Response:
def candles(self, pair, timeframe=None):
        """Return a queue containing all received candles data.

        :param pair: str, Symbol pair to request data for
        :param timeframe: str
        :return: Queue()
        """
        timeframe = '1m' if not timeframe else timeframe
        key = ('candles', pair, timeframe)
        return self.queue_processor.candles[key]


Instruction:
Can you write a function in Python 3 where it
sends configuration to the server

Response:
def config(self, decimals_as_strings=True, ts_as_dates=False,
               sequencing=False, ts=False, **kwargs):
        """Send configuration to websocket server

        :param decimals_as_strings: bool, turn on/off decimals as strings
        :param ts_as_dates: bool, decide to request timestamps as dates instead
        :param sequencing: bool, turn on sequencing
	:param ts: bool, request the timestamp to be appended to every array
               sent by the server
        :param kwargs:
        :return:
        """
        flags = 0
        if decimals_as_strings:
            flags += 8
        if ts_as_dates:
            flags += 32
        if ts:
            flags += 32768
        if sequencing:
            flags += 65536
        q = {'event': 'conf', 'flags': flags}
        q.update(kwargs)
        self.conn.bitfinex_config = q
        self.conn.send(**q)


Instruction:
Can you implement a function in Python 3 that
subscribes to the passed pair s ticker channel.

Response:
def subscribe_to_ticker(self, pair, **kwargs):
        """Subscribe to the passed pair's ticker channel.

        :param pair: str, Symbol pair to request data for
        :param kwargs:
        :return:
        """
        identifier = ('ticker', pair)
        self._subscribe('ticker', identifier, symbol=pair, **kwargs)


Instruction:
Make a summary of the following Python 3 code
def subscribe_to_order_book(self, pair, **kwargs):
        identifier = ('book', pair)
        self._subscribe('book', identifier, symbol=pair, **kwargs)

Response: Subscribe to the passed pair s order book channel.


Instruction:
Explain what the following Python 3 code does
def unsubscribe_from_order_book(self, pair, **kwargs):
        identifier = ('book', pair)
        self._unsubscribe('book', identifier, symbol=pair, **kwargs)

Response: Unsubscribe to the passed pair s order book channel.


Instruction:
How would you code a function in Python 3 to
subscribe to the passed pair s raw order book channel.

Response:
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)


Instruction:
Can you generate the documentation for the following Python 3 function
def unsubscribe_from_raw_order_book(self, pair, prec=None, **kwargs):
        identifier = ('raw_book', pair)
        prec = 'R0' if prec is None else prec
        self._unsubscribe('book', identifier, pair=pair, prec=prec, **kwargs)

Response: Unsubscribe to the passed pair s raw order book channel.


Instruction:
Write a Python 3 function for
subscribing to the passed pair s trades channel.

Response:
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)


Instruction:
How would you explain what the following Python 3 function does
def subscribe_to_candles(self, pair, timeframe=None, **kwargs):

        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)

Response: Subscribe to the passed pair s OHLC data channel.


Instruction:
How would you explain what the following Python 3 function does
def unsubscribe_from_candles(self, pair, timeframe=None, **kwargs):

        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)

Response: Unsubscribe to the passed pair s OHLC data channel.


Instruction:
How would you explain what the following Python 3 function does
def authenticate(self):
        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)

Response: Authenticate with the Bitfinex API.


Instruction:
Make a summary of the following Python 3 code
def cancel_order(self, multi=False, **order_identifiers):
        if multi:
            self._send_auth_command('oc_multi', order_identifiers)
        else:
            self._send_auth_command('oc', order_identifiers)

Response: Cancel one or multiple orders via Websocket.


Instruction:
Make a summary of the following Python 3 code
def parseEnvVars():

    # 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

Response:
Parses environment variables into a Python dictionary suitable for passing to the
    device client constructor as the options parameter.


Instruction:
Create a Python 3 function for
parsing a YAML configuration file into a Python dictionary suitable for passing to the device client constructor as the options parameter.

Response:
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


Instruction:
Can you tell what is the following Python 3 function doing
def _onCommand(self, client, userdata, pahoMessage):
        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)

Response: Internal callback for device command messages


Instruction:
Here you have a function in Python 3, explain what it does
def _onDeviceCommand(self, client, userdata, pahoMessage):
        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)

Response: Internal callback for gateway command messages


Instruction:
Can you generate the documentation for the following Python 3 function
def find(self, nameFilter=None, typeFilter=None, enabledFilter=None, serviceId=None):

        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)

Response: Gets the list of Historian connectors in a given service.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create(self, name, serviceId, timezone, description, enabled):

        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)

Response: This method creates a new connector for the organization in the Watson IoT Platform.


Instruction:
Write a Python 3 function that can
update 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.

Response:
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)


Instruction:
Can you write a function in Python 3 where it
gets a list of services that the Watson IoT Platform can connect to.

Response:
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)


Instruction:
Can you tell what is the following Python 3 function doing
def create(self, serviceBinding):
        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)

Response: This method creates a new external service.


Instruction:
Can you generate the documentation for the following Python 3 function
def update(self, serviceId, serviceName, credentials, description):

        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)

Response: This method updates the service with the specified id and credentials and description.


Instruction:
Given the following Python 3 function, write the documentation
def create(self, deviceType):

        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)

Response: Register one or more new device types


Instruction:
Write a Python 3 function for
publishing an event to Watson IoT Platform.

Response:
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)


Instruction:
Write a Python 3 script for
retrieving the organization - specific status of each of the services offered by the IBM Watson IoT Platform.

Response:
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)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create(self, devices):
        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)

Response: This method creates a new device in the bulk.


Instruction:
Given the following Python 3 function, write the documentation
def update(self, deviceUid, metadata=None, deviceInfo=None, status=None):

        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)

Response: Update an existing device in the system


Instruction:
Explain what the following Python 3 code does
def delete(self, devices):
        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)

Response: This method deletes one or more devices from the dictionary.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def find(self, status=None, connectedAfter=None):
        queryParms = {}
        if status:
            queryParms["status"] = status
        if connectedAfter:
            queryParms["connectedAfter"] = connectedAfter

        return IterableClientStatusList(self._apiClient, filters=queryParms)

Response: Iterate through all Connectors and return a list of all the Connectors that have the given status.


Instruction:
Create a Python 3 function to
list all device management extension packages

Response:
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)


Instruction:
Here you have a function in Python 3, explain what it does
def create(self, dmeData):
        url = "api/v0002/mgmt/custom/bundle"
        r = self._apiClient.post(url, dmeData)

        if r.status_code == 201:
            return r.json()
        else:
            raise ApiException(r)

Response: Create a new device management extension package


Instruction:
Can you write a function in Python 3 where it
deletes a device management extension package It accepts bundleId (string) as parameters In case of failure it throws APIException

Response:
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)


Instruction:
Make a summary of the following Python 3 code
def update(self, bundleId, dmeData):
        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)

Response: This method updates a device management extension package


Instruction:
Can you implement a function in Python 3 that
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

Response:
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)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def getThing(self, thingTypeId, thingId):
        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)

Response: Gets the details of a thing. It accepts thingTypeId thingId It accepts thingId


Instruction:
Write a Python 3 script for
getting details for multiple things of a type It accepts thingTypeId (string) and parameters In case of failure it throws APIException

Response:
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)


Instruction:
Explain what the following Python 3 code does
def removeThing(self, thingTypeId, thingId):
        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)

Response: This method deletes an existing thing. It returns True if the thing was successfully removed False otherwise.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def addDraftThingType(self, thingTypeId, name = None, description = None, schemaId = None, metadata = None):
        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)

Response: Adds a draft thing type to the current Thing Type.


Instruction:
Create a Python 3 function to
update 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

Response:
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)


Instruction:
Create a Python 3 function for
retrieving all existing draft thing types. It accepts accepts an optional query parameters (Dictionary) In case of failure it throws APIException

Response:
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)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def getDraftThingType(self, thingTypeId, parameters = None):
        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)

Response: This method returns all existing draft thing types. It accepts a query parameter dictionary which contains the values for the parameters parameter. It returns a dictionary containing the values for the parameters parameter.


Instruction:
Explain what the following Python 3 code does
def deleteDraftThingType(self, thingTypeId):
        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)

Response: This method deletes a draft Thing Type. It returns True if the thing type was deleted False otherwise.


Instruction:
How would you explain what the following Python 3 function does
def createSchema(self, schemaName, schemaFileName, schemaContents, description=None):
        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()

Response: Create a schema for the org.


Instruction:
Create a Python 3 function to
delete a schema. Parameter: schemaId (string). Throws APIException on failure.

Response:
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


Instruction:
Given the following Python 3 function, write the documentation
def updateSchema(self, schemaId, schemaDefinition):
        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()

Response: Update a schema. Returns a dict with the updated schema definition.


Instruction:
Can you tell what is the following Python 3 function doing
def getSchemaContent(self, schemaId, draft=False):
        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()

Response: Get the content for a schema.


Instruction:
Can you tell what is the following Python 3 function doing
def updateSchemaContent(self, schemaId, schemaFile):
        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()

Response: Updates the content for a specific schema.


Instruction:
Make a summary of the following Python 3 code
def updateEventType(self, eventTypeId, name, schemaId, description=None):
        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()

Response: Updates an event type.


Instruction:
Here you have a function in Python 3, explain what it does
def deleteEventType(self, eventTypeId):
        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

Response: Delete an event type.


Instruction:
Can you tell what is the following Python 3 function doing
def getEventType(self, eventTypeId, draft=False):
        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()

Response: Gets an event type.


Instruction:
How would you explain what the following Python 3 function does
def createPhysicalInterface(self, name, description=None):
        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()

Response: Method to create a physical interface.


Instruction:
How would you code a function in Python 3 to
update a physical interface.

Response:
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()


Instruction:
How would you code a function in Python 3 to
delete a physical interface.

Response:
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


Instruction:
How would you code a function in Python 3 to
get a physical interface.

Response:
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()


Instruction:
Make a summary of the following Python 3 code
def createEvent(self, physicalInterfaceId, eventTypeId, eventId):
        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()

Response: Create an event mapping for a specific event.


Instruction:
How would you explain what the following Python 3 function does
def deleteEvent(self, physicalInterfaceId, eventId):
        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

Response: Delete an event mapping from a physical interface.


Instruction:
Implement a Python 3 function for
getting all logical interfaces for an org.

Response:
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()


Instruction:
Given the following Python 3 function, write the documentation
def updateLogicalInterface(self, logicalInterfaceId, name, schemaId, description=None):
        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()

Response: Updates a logical interface.


Instruction:
Can you implement a function in Python 3 that
deletes a logical interface.

Response:
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


Instruction:
How would you code a function in Python 3 to
get a specific logical interface.

Response:
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()


Instruction:
Write a Python 3 function that can
get a rule for a logical interface. Parameters: - logicalInterfaceId (string) - ruleId (string) - draft (boolean) Throws APIException on failure.

Response:
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()


Instruction:
Write a Python 3 script to
add a rule to a logical interface.

Response:
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()


Instruction:
Can you tell what is the following Python 3 function doing
def updateRuleOnLogicalInterface(self, logicalInterfaceId, ruleId, name, condition, description=None):
        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()

Response: This method updates a rule on a logical interface.


Instruction:
Given the following Python 3 function, write the documentation
def deleteRuleOnLogicalInterface(self, logicalInterfaceId, ruleId):
        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

Response: Delete a rule from a logical interface


Instruction:
How would you implement a function in Python 3 that
adds a physical interface to a device type.

Response:
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()


Instruction:
Can you implement a function in Python 3 that
gets the physical interface associated with a device type.

Response:
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()


Instruction:
Can you generate the documentation for the following Python 3 function
def getLogicalInterfacesOnDeviceType(self, typeId, draft=False):
        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()

Response: Get all logical interfaces for a device type.


Instruction:
How would you implement a function in Python 3 that
adds a logical interface to a device type.

Response:
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()


Instruction:
How would you implement a function in Python 3 that
removes a logical interface from a device type.

Response:
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


Instruction:
Can you write a function in Python 3 where it
gets all the mappings for a device type.

Response:
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()


Instruction:
How would you code a function in Python 3 to
get 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.

Response:
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()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def validateDeviceTypeConfiguration(self, typeId):
        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()

Response: Validate the device type configuration.


Instruction:
How would you implement a function in Python 3 that
validates the logical interface configuration.

Response:
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()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def getDeviceStateForLogicalInterface(self, typeId, deviceId, logicalInterfaceId):
        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()

Response: Get the state of a device type and logical interface.


Instruction:
How would you implement a function in Python 3 that
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.

Response:
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()


Instruction:
Make a summary of the following Python 3 code
def resetThingStateForLogicalInterface(self, thingTypeId, thingId , logicalInterfaceId):
        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()

Response: This method resets the state of a thing for a logical interface.


Instruction:
Write a Python 3 function that can
get all logical interfaces for a thing type.

Response:
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()


Instruction:
Can you tell what is the following Python 3 function doing
def addLogicalInterfaceToThingType(self, thingTypeId, logicalInterfaceId, schemaId = None, name = None):
        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()

Response: Adds a logical interface to a thing type.


Instruction:
Implement a Python 3 function for
removing 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.

Response:
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


Instruction:
Explain what the following Python 3 code does
def getMappingsOnThingType(self, thingTypeId, draft=False):
        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()

Response: Get all the mappings for a thing type.


Instruction:
Create a Python 3 function to
get 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.

Response:
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()


Instruction:
Can you tell what is the following Python 3 function doing
def updateMappingsOnDeviceType(self, thingTypeId, logicalInterfaceId, mappingsObject, notificationStrategy = "never"):
        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()

Response: This method updates the mappings for a thing type on a specific logical interface.


Instruction:
Make a summary of the following Python 3 code
def connect(self):
        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)))
            )

Response: Connect the client to the IBM Watson IoT Platform using the underlying Paho MQTT client.


Instruction:
How would you explain what the following Python 3 function does
def disconnect(self):
        # 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")

Response: Disconnect the client from IBM Watson IoT Platform


Instruction:
Write a Python 3 function that can
call when the client has log information.

Response:
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))


Instruction:
Make a summary of the following Python 3 code
def _onConnect(self, mqttc, userdata, flags, rc):
        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)))

Response: Called when the broker responds to a connection request.


Instruction:
Implement a Python 3 function for
calling when the client disconnects from the IBM Watson IoT Platform.

Response:
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")


Instruction:
Can you generate the documentation for the following Python 3 function
def _onPublish(self, mqttc, obj, mid):
        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

Response: Called when a message has been successfully published to the IBM Watson IoT Platform.


Instruction:
How would you explain what the following Python 3 function does
def subscribeToDeviceEvents(self, typeId="+", deviceId="+", eventId="+", msgFormat="+", qos=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)

Response: Subscribe to device events.


Instruction:
Implement a function in Python 3 to
subscribe to device status messages

Response:
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)


Instruction:
Given the following Python 3 function, write the documentation
def subscribeToDeviceCommands(self, typeId="+", deviceId="+", commandId="+", msgFormat="+"):
        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)

Response: Subscribe to device command messages.


Instruction:
Given the following Python 3 function, write the documentation
def publishCommand(self, typeId, deviceId, commandId, msgFormat, data=None, qos=0, on_publish=None):
        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

Response: Publish a command to a device


Instruction:
Can you tell what is the following Python 3 function doing
def _onDeviceStatus(self, client, userdata, pahoMessage):
        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))

Response: Internal callback for device status messages


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _onAppStatus(self, client, userdata, pahoMessage):
        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))

Response: Internal callback for application status messages


Instruction:
Write a Python 3 script to
parse environment variables into a Python dictionary suitable for passing to the device client constructor as the options parameter.

Response:
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


Instruction:
Create a Python 3 function to
get the last cached message for a specific event from a specific device.

Response:
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)


Instruction:
Given the following Python 3 function, write the documentation
def getAll(self, deviceUid):

        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)

Response: Get all the last cached messages for a specific device.


Instruction:
Given the following Python 3 function, write the documentation
def _makeApiCall(self, parameters=None):
        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))

Response: This method is used to make an API call to retrieve bulk devices and set the local_key of the device. It accepts a list of parameters


Instruction:
Make a summary of the following Python 3 code
def decode(message):
        try:
            data = json.loads(message.payload.decode("utf-8"))
        except ValueError as e:
            raise InvalidEventException('Unable to parse JSON.  payload="%s" error=%s' % (message.payload, str(e)))

        timestamp = datetime.now(pytz.timezone("UTC"))

        # TODO: Flatten JSON, covert into array of key/value pairs
        return Message(data, timestamp)

Response: Convert a generic JSON message into a Message object