Exemplo n.º 1
0
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:
        instanceId: myInstance
        port: 8883
        transport: tcp
        cleanStart: false
        sessionExpiry: 3600
        keepAlive: 60
        caFile: /path/to/certificateAuthorityFile.pem
      http:
        verify: true    
    """

    try:
        with open(configFilePath) as f:
            data = yaml.full_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 ApplicationClientConfig(**data)
Exemplo n.º 2
0
def parseEnvVars():
    """
    Parse environment variables into a Python dictionary suitable for passing to the 
    device client constructor as the `options` parameter

    - `WIOTP_IDENTITY_APPID`
    - `WIOTP_AUTH_KEY`
    - `WIOTP_AUTH_TOKEN`
    - `WIOTP_OPTIONS_DOMAIN` (optional)
    - `WIOTP_OPTIONS_LOGLEVEL` (optional)
    - `WIOTP_OPTIONS_MQTT_INSTANCEID` (optional)
    - `WIOTP_OPTIONS_MQTT_PORT` (optional)
    - `WIOTP_OPTIONS_MQTT_TRANSPORT` (optional)
    - `WIOTP_OPTIONS_MQTT_CAFILE` (optional)
    - `WIOTP_OPTIONS_MQTT_CLEANSTART` (optional)
    - `WIOTP_OPTIONS_MQTT_SESSIONEXPIRY` (optional)
    - `WIOTP_OPTIONS_MQTT_KEEPALIVE` (optional)
    - `WIOTP_OPTIONS_HTTP_VERIFY` (optional)
    """

    # Auth
    authKey = os.getenv("WIOTP_AUTH_KEY", None)
    authToken = os.getenv("WIOTP_AUTH_TOKEN", None)

    # Also support WIOTP_API_KEY / WIOTP_API_TOKEN usage
    if authKey is None and authToken is None:
        authKey = os.getenv("WIOTP_API_KEY", None)
        authToken = os.getenv("WIOTP_API_TOKEN", None)

    # Identity
    appId = os.getenv("WIOTP_IDENTITY_APPID", str(uuid.uuid4()))
    # Options
    domain = os.getenv("WIOTP_OPTIONS_DOMAIN", None)
    logLevel = os.getenv("WIOTP_OPTIONS_LOGLEVEL", "info")
    instanceId = os.getenv("WIOTP_OPTIONS_MQTT_INSTANCEID", None)
    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")
    verifyCert = os.getenv("WIOTP_OPTIONS_HTTP_VERIFY", "True")

    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_KEEPALIVE 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": {
                "instanceId": instanceId,
                "port": port,
                "transport": transport,
                "cleanStart": cleanStart in ["True", "true", "1"],
                "sessionExpiry": sessionExpiry,
                "keepAlive": keepAlive,
                "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 ApplicationClientConfig(**cfg)
Exemplo n.º 3
0
    def __init__(self, **kwargs):
        # Note: Authentication is not supported for quickstart
        if "auth" in kwargs:
            if "key" not in kwargs["auth"] or kwargs["auth"]["key"] is None:
                raise ConfigurationException(
                    "Missing auth.key from configuration")
            if "token" not in kwargs["auth"] or kwargs["auth"]["token"] is None:
                raise ConfigurationException(
                    "Missing auth.token from configuration")

        if "options" in kwargs and "mqtt" in kwargs["options"]:
            if "port" in kwargs["options"]["mqtt"] and kwargs["options"][
                    "mqtt"]["port"] is not None:
                if not isinstance(kwargs["options"]["mqtt"]["port"], int):
                    raise ConfigurationException(
                        "Optional setting options.port must be a number if provided"
                    )
            if "cleanSession" in kwargs["options"]["mqtt"] and not isinstance(
                    kwargs["options"]["mqtt"]["cleanSession"], bool):
                raise ConfigurationException(
                    "Optional setting options.cleanSession must be a boolean if provided"
                )

        # Set defaults for optional configuration
        if "identity" not in kwargs:
            kwargs["identity"] = {}

        if "appId" not in kwargs["identity"]:
            kwargs["identity"]["appId"] = str(uuid.uuid4())

        if "options" not in kwargs:
            kwargs["options"] = {}

        if "domain" not in kwargs[
                "options"] or kwargs["options"]["domain"] is None:
            kwargs["options"]["domain"] = "internetofthings.ibmcloud.com"

        if "logLevel" not in kwargs[
                "options"] or kwargs["options"]["logLevel"] is None:
            kwargs["options"]["logLevel"] = logging.INFO

        if "mqtt" not in kwargs["options"]:
            kwargs["options"]["mqtt"] = {}

        if "instanceId" not in kwargs["options"]["mqtt"]:
            kwargs["options"]["mqtt"]["instanceId"] = None

        if "port" not in kwargs["options"]["mqtt"]:
            kwargs["options"]["mqtt"]["port"] = None

        if "transport" not in kwargs["options"][
                "mqtt"] or kwargs["options"]["mqtt"]["transport"] is None:
            kwargs["options"]["mqtt"]["transport"] = "tcp"

        if "cleanStart" not in kwargs["options"]["mqtt"]:
            kwargs["options"]["mqtt"]["cleanStart"] = False

        if "sessionExpiry" not in kwargs["options"]["mqtt"]:
            kwargs["options"]["mqtt"]["sessionExpiry"] = 3600

        if "keepAlive" not in kwargs["options"]["mqtt"]:
            kwargs["options"]["mqtt"]["keepAlive"] = 60

        if "caFile" not in kwargs["options"]["mqtt"]:
            kwargs["options"]["mqtt"]["caFile"] = None

        if "http" not in kwargs["options"]:
            kwargs["options"]["http"] = {}

        if "verify" not in kwargs["options"][
                "http"] or kwargs["options"]["http"]["verify"] is None:
            kwargs["options"]["http"]["verify"] = True

        dict.__init__(self, **kwargs)
Exemplo n.º 4
0
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_DOMAIN` (optional)
    - `WIOTP_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 is not "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
Exemplo n.º 5
0
    def __init__(self, **kwargs):
        # Validate the arguments
        if 'identity' not in kwargs:
            raise ConfigurationException("Missing identity from configuration")
        if 'orgId' not in kwargs[
                'identity'] or kwargs['identity']['orgId'] is None:
            raise ConfigurationException(
                "Missing identity.orgId from configuration")
        if 'typeId' not in kwargs[
                'identity'] or kwargs['identity']['typeId'] is None:
            raise ConfigurationException(
                "Missing identity.typeId from configuration")
        if 'deviceId' not in kwargs[
                'identity'] or kwargs['identity']['deviceId'] is None:
            raise ConfigurationException(
                "Missing identity.deviceId from configuration")

        # Authentication is not supported for quickstart
        if kwargs['identity']['orgId'] is "quickstart":
            if 'auth' in kwargs:
                raise ConfigurationException(
                    "Quickstart service does not support device authentication"
                )
        else:
            if 'auth' not in kwargs:
                raise ConfigurationException("Missing auth from configuration")
            if 'token' not in kwargs['auth'] or kwargs['auth']['token'] is None:
                raise ConfigurationException(
                    "Missing auth.token from configuration")

        if 'options' in kwargs and 'mqtt' in kwargs['options']:
            # validate port
            if 'port' in kwargs['options']['mqtt'] and kwargs['options'][
                    'mqtt']['port'] is not None:
                if not isinstance(kwargs['options']['mqtt']['port'], int):
                    raise ConfigurationException(
                        "Optional setting options.mqtt.port must be a number if provided"
                    )
            # Validate cleanStart
            if 'cleanStart' in kwargs['options']['mqtt'] and not isinstance(
                    kwargs['options']['mqtt']['cleanStart'], bool):
                raise ConfigurationException(
                    "Optional setting options.mqtt.cleanStart must be a boolean if provided"
                )

        # Set defaults for optional configuration
        if 'options' not in kwargs:
            kwargs['options'] = {}

        if "domain" not in kwargs['options']:
            kwargs['options']['domain'] = "internetofthings.ibmcloud.com"

        if "logLevel" not in kwargs['options']:
            kwargs['options']['logLevel'] = logging.INFO

        if 'mqtt' not in kwargs['options']:
            kwargs['options']['mqtt'] = {}

        if "port" not in kwargs['options']['mqtt']:
            kwargs['options']['mqtt']['port'] = None

        if "transport" not in kwargs['options']['mqtt']:
            kwargs['options']['mqtt']['transport'] = 'tcp'

        if "cleanStart" not in kwargs['options']['mqtt']:
            kwargs['options']['mqtt']['cleanStart'] = False

        if "sessionExpiry" not in kwargs['options']['mqtt']:
            kwargs['options']['mqtt']['sessionExpiry'] = 3600

        if "keepAlive" not in kwargs['options']['mqtt']:
            kwargs['options']['mqtt']['keepAlive'] = 60

        if "caFile" not in kwargs['options']['mqtt']:
            kwargs['options']['mqtt']['caFile'] = None

        dict.__init__(self, **kwargs)
Exemplo n.º 6
0
    def __init__(self, **kwargs):
        # Note: Authentication is not supported for quickstart
        if 'auth' in kwargs:
            if 'key' not in kwargs['auth'] or kwargs['auth']['key'] is None:
                raise ConfigurationException("Missing auth.key from configuration")
            if 'token' not in kwargs['auth'] or kwargs['auth']['token'] is None:
                raise ConfigurationException("Missing auth.token from configuration")
        
        if 'options' in kwargs and 'mqtt' in kwargs['options']:
            if 'port' in kwargs['options']['mqtt'] and kwargs['options']['mqtt']['port'] is not None:
                if not isinstance(kwargs['options']['mqtt']['port'], int):
                    raise ConfigurationException("Optional setting options.port must be a number if provided")
            if 'cleanSession' in kwargs['options']['mqtt'] and not isinstance(kwargs['options']['mqtt']['cleanSession'], bool):
                raise ConfigurationException("Optional setting options.cleanSession must be a boolean if provided")
        
        # Set defaults for optional configuration
        if 'identity' not in kwargs:
            kwargs['identity'] = {}

        if 'appId' not in kwargs['identity']:
            kwargs['identity']['appId'] = str(uuid.uuid4())

        if 'options' not in kwargs:
            kwargs['options'] = {}

        if "domain" not in kwargs['options'] or kwargs['options']['domain'] is None:
            kwargs['options']['domain'] = "internetofthings.ibmcloud.com"
        
        if "logLevel" not in kwargs['options'] or kwargs['options']['logLevel'] is None:
            kwargs['options']['logLevel'] = logging.INFO

        if 'mqtt' not in kwargs['options']:
            kwargs['options']['mqtt'] = {}
        
        if "port" not in kwargs['options']['mqtt']:
            kwargs['options']['mqtt']['port'] = None
        
        if "transport" not in kwargs['options']['mqtt']  or kwargs['options']['mqtt']['transport'] is None:
            kwargs['options']['mqtt']['transport'] = 'tcp'

        if "sharedSubscription" not in kwargs['options']['mqtt']:
            kwargs['options']['mqtt']['sharedSubscription'] = False

        if "cleanStart" not in kwargs['options']['mqtt']:
            kwargs['options']['mqtt']['cleanStart'] = False

        if "sessionExpiry" not in kwargs['options']['mqtt']:
            kwargs['options']['mqtt']['sessionExpiry'] = 3600

        if "keepAlive" not in kwargs['options']['mqtt']:
            kwargs['options']['mqtt']['keepAlive'] = 60

        if "caFile" not in kwargs['options']['mqtt']:
            kwargs['options']['mqtt']['caFile'] = None

        if 'http' not in kwargs['options']:
            kwargs['options']['http'] = {}

        if "verify" not in kwargs['options']['http'] or kwargs['options']['http']['verify'] is None:
            kwargs['options']['http']['verify'] = True

        dict.__init__(self, **kwargs)
Exemplo n.º 7
0
def parseEnvVars():
    """
    Parse environment variables into a Python dictionary suitable for passing to the 
    device client constructor as the `options` parameter

    - `WIOTP_IDENTITY_APPID`
    - `WIOTP_AUTH_KEY`
    - `WIOTP_AUTH_TOKEN`
    - `WIOTP_OPTIONS_DOMAIN` (optional)
    - `WIOTP_OPTIONS_LOGLEVEL` (optional)
    - `WIOTP_OPTIONS_MQTT_PORT` (optional)
    - `WIOTP_OPTIONS_MQTT_TRANSPORT` (optional)
    - `WIOTP_OPTIONS_MQTT_CAFILE` (optional)
    - `WIOTP_OPTIONS_MQTT_CLEANSTART` (optional)
    - `WIOTP_OPTIONS_MQTT_SESSIONEXPIRY` (optional)
    - `WIOTP_OPTIONS_MQTT_KEEPALIVE` (optional)
    - `WIOTP_OPTIONS_MQTT_SHAREDSUBSCRIPTION` (optional)
    - `WIOTP_OPTIONS_HTTP_VERIFY` (optional)
    """

    # Auth
    authKey   = os.getenv("WIOTP_AUTH_KEY", None)
    authToken = os.getenv("WIOTP_AUTH_TOKEN", None)

    # Also support WIOTP_API_KEY / WIOTP_API_TOKEN usage
    if authKey is None and authToken is None:
        authKey   = os.getenv("WIOTP_API_KEY", None)
        authToken = os.getenv("WIOTP_API_TOKEN", None)

    # Identity
    appId     = os.getenv("WIOTP_IDENTITY_APPID", str(uuid.uuid4()))
    # Options
    domain        = os.getenv("WIOTP_OPTIONS_DOMAIN", None)
    logLevel      = os.getenv("WIOTP_OPTIONS_LOGLEVEL", "info")
    port          = os.getenv("WIOTP_OPTIONS_MQTT_PORT", None)
    transport     = os.getenv("WIOTP_OPTIONS_MQTT_TRANSPORT", None)
    caFile        = os.getenv("WIOTP_OPTIONS_MQTT_CAFILE", None)
    cleanStart    = os.getenv("WIOTP_OPTIONS_MQTT_CLEANSTART", "True")
    sessionExpiry = os.getenv("WIOTP_OPTIONS_MQTT_SESSIONEXPIRY", "3600")
    keepAlive     = os.getenv("WIOTP_OPTIONS_MQTT_KEEPALIVE", "60")
    sharedSubs    = os.getenv("WIOTP_OPTIONS_MQTT_SHAREDSUBSCRIPTION", "False")
    verifyCert    = os.getenv("WIOTP_OPTIONS_HTTP_VERIFY", "True")
    
    if port is not None:
        try:
            port = int(port)
        except ValueError as e:
            raise ConfigurationException("WIOTP_PORT must be a number")

    try:
        sessionExpiry = int(sessionExpiry)
    except ValueError as e:
        raise ConfigurationException("WIOTP_OPTIONS_MQTT_SESSIONEXPIRY must be a number")
    
    try:
        keepAlive = int(keepAlive)
    except ValueError as e:
        raise ConfigurationException("WIOTP_OPTIONS_MQTT_KEEPAIVE must be a number")

    if logLevel not in ["error", "warning", "info", "debug"]:
        raise ConfigurationException("WIOTP_OPTIONS_LOGLEVEL must be one of error, warning, info, debug")  
    else:
        # Convert log levels from string to int (we need to upper case our strings from the config)
        logLevel = logging.getLevelName(logLevel.upper())
    
    cfg = {
        'identity': {
            'appId': appId
        },
        'options': {
            'domain': domain,
            'logLevel': logLevel,
            'mqtt': {
                'port': port,
                'transport': transport,
                'cleanStart': cleanStart in ["True", "true", "1"],
                'sessionExpiry': sessionExpiry,
                'keepAlive': keepAlive,
                'sharedSubscription': sharedSubs in ["True", "true", "1"],
                'caFile': caFile
            },
            "http": {
                "verify": verifyCert in ["True", "true", "1"]
            }
        }
    }

    # Quickstart doesn't support auth, so ensure we only add this if it's defined
    if authToken is not None:
        cfg['auth'] = { 'key': authKey, 'token': authToken }
    
    return cfg
Exemplo n.º 8
0
    def __init__(self, config, logHandlers=None, deviceInfo=None):
        if config['identity']['orgId'] == "quickstart":
            raise ConfigurationException("QuickStart does not support device management")

        DeviceClient.__init__(self, config, logHandlers)

        # Initialize user supplied callback
        self.deviceActionCallback = None
        self.firmwereActionCallback = None
        self.dmeActionCallback = None

        messages_callbacks = (
            ("iotdm-1/#", self.__onDeviceMgmtResponse),
            (ManagedDeviceClient.DM_REBOOT_TOPIC, self.__onRebootRequest),
            (ManagedDeviceClient.DM_FACTORY_REESET, self.__onFactoryResetRequest),
            (ManagedDeviceClient.DM_FIRMWARE_UPDATE_TOPIC, self.__onFirmwereUpdate),
            (ManagedDeviceClient.DM_OBSERVE_TOPIC, self.__onFirmwereObserve),
            (ManagedDeviceClient.DM_FIRMWARE_DOWNLOAD_TOPIC, self.__onFirmwereDownload),
            (ManagedDeviceClient.DM_UPDATE_TOPIC, self.__onUpdatedDevice),
            (ManagedDeviceClient.DM_CANCEL_OBSERVE_TOPIC, self.__onFirmwereCancel),
            (ManagedDeviceClient.DME_ACTION_TOPIC, self.__onDMEActionRequest),
        )

        # Add handler for supported device management commands
        for message, callback in messages_callbacks:
            self.client.message_callback_add(message, callback)

        # Initialize user supplied callback
        self.client.on_subscribe = self._onSubscribe
        self.client.on_disconnect = self._onDisconnect

        self.readyForDeviceMgmt = threading.Event()

        # List of DM requests that have not received a response yet
        self._deviceMgmtRequestsPendingLock = threading.Lock()
        self._deviceMgmtRequestsPending = {}

        # List of DM notify hook
        self._deviceMgmtObservationsLock = threading.Lock()
        self._deviceMgmtObservations = []

        # Initialize local device data model
        self.metadata = {}
        if deviceInfo is not None:
            self._deviceInfo = deviceInfo
        else:
            self._deviceInfo = DeviceInfo()

        self._location = None
        self._errorCode = None
        self.__firmwareUpdate = None

        self.manageTimer = None

        # Register startup subscription list
        self._subscriptions[self.DM_RESPONSE_TOPIC] = 1
        self._subscriptions[self.DM_OBSERVE_TOPIC] = 1
        self._subscriptions[self.DM_REBOOT_TOPIC] = 1
        self._subscriptions[self.DM_FACTORY_REESET] = 1
        self._subscriptions[self.DM_UPDATE_TOPIC] = 1
        self._subscriptions[self.DM_FIRMWARE_UPDATE_TOPIC] = 1
        self._subscriptions[self.DM_FIRMWARE_DOWNLOAD_TOPIC] = 1
        self._subscriptions[self.DM_CANCEL_OBSERVE_TOPIC] = 1
        self._subscriptions[self._COMMAND_TOPIC] = 1
        self._subscriptions[self.DME_ACTION_TOPIC] = 1
Exemplo n.º 9
0
    def __init__(self, config, logHandlers=None, deviceInfo=None):
        """
        Override the constructor
        """
        if config["identity"]["orgId"] == "quickstart":
            raise ConfigurationException(
                "QuickStart does not support device management")

        self._config = GatewayClientConfig(**config)

        AbstractClient.__init__(
            self,
            domain=self._config.domain,
            organization=self._config.orgId,
            clientId=self._config.clientId,
            username=self._config.username,
            password=self._config.password,
            port=self._config.port,
            transport=self._config.transport,
            cleanStart=self._config.cleanStart,
            sessionExpiry=self._config.sessionExpiry,
            keepAlive=self._config.keepAlive,
            caFile=self._config.caFile,
            logLevel=self._config.logLevel,
            logHandlers=logHandlers,
        )

        self.COMMAND_TOPIC = "iot-2/type/" + self._config.typeId + "/id/" + self._config.deviceId + "/cmd/+/fmt/+"

        gatewayCommandTopic = "iot-2/type/" + self._config.typeId + "/id/" + self._config.deviceId + "/cmd/+/fmt/json"
        deviceCommandTopic = "iot-2/type/+/id/+/cmd/+/fmt/+"
        messageNotificationTopic = "iot-2/type/" + self._config.typeId + "/id/" + self._config.deviceId + "/notify"

        self.client.message_callback_add(gatewayCommandTopic, self._onCommand)
        self.client.message_callback_add(deviceCommandTopic,
                                         self._onDeviceCommand)
        self.client.message_callback_add(messageNotificationTopic,
                                         self._onMessageNotification)

        # Initialize user supplied callback
        self.deviceCommandCallback = None
        self.notificationCallback = None

        # ---------------------------------------------------------------------
        # Device Management Specific code starts here
        # ---------------------------------------------------------------------
        self.readyForDeviceMgmt = threading.Event()

        # Add handler for supported device management commands
        self.client.message_callback_add("iotdm-1/#",
                                         self.__onDeviceMgmtResponse)

        # List of DM requests that have not received a response yet
        self._deviceMgmtRequestsPendingLock = threading.Lock()
        self._deviceMgmtRequestsPending = {}

        # List of DM notify hook
        self._deviceMgmtObservationsLock = threading.Lock()
        self._deviceMgmtObservations = []

        # Initialize local device data model
        self.metadata = {}
        if deviceInfo is not None:
            self._deviceInfo = deviceInfo
        else:
            self._deviceInfo = DeviceInfo()

        self._location = None
        self._errorCode = None

        # Initialize subscription list
        self._subscriptions[self.DM_RESPONSE_TOPIC_TEMPLATE %
                            (self._config.typeId, self._config.deviceId)] = 1
        self._subscriptions[self.DM_OBSERVE_TOPIC_TEMPLATE %
                            (self._config.typeId, self._config.deviceId)] = 1
        self._subscriptions[self.COMMAND_TOPIC] = 1
Exemplo n.º 10
0
    def __init__(self, **kwargs):
        # Validate the arguments
        if "identity" not in kwargs:
            raise ConfigurationException("Missing identity from configuration")
        if "orgId" not in kwargs[
                "identity"] or kwargs["identity"]["orgId"] is None:
            raise ConfigurationException(
                "Missing identity.orgId from configuration")
        if "typeId" not in kwargs[
                "identity"] or kwargs["identity"]["typeId"] is None:
            raise ConfigurationException(
                "Missing identity.typeId from configuration")
        if "deviceId" not in kwargs[
                "identity"] or kwargs["identity"]["deviceId"] is None:
            raise ConfigurationException(
                "Missing identity.deviceId from configuration")

        # Authentication is not supported for quickstart
        if kwargs["identity"]["orgId"] is "quickstart":
            if "auth" in kwargs:
                raise ConfigurationException(
                    "Quickstart service does not support device authentication"
                )
        else:
            if "auth" not in kwargs:
                raise ConfigurationException("Missing auth from configuration")
            if "token" not in kwargs["auth"] or kwargs["auth"]["token"] is None:
                raise ConfigurationException(
                    "Missing auth.token from configuration")

        if "options" in kwargs and "mqtt" in kwargs["options"]:
            # validate port
            if "port" in kwargs["options"]["mqtt"] and kwargs["options"][
                    "mqtt"]["port"] is not None:
                if not isinstance(kwargs["options"]["mqtt"]["port"], int):
                    raise ConfigurationException(
                        "Optional setting options.mqtt.port must be a number if provided"
                    )
            # Validate cleanStart
            if "cleanStart" in kwargs["options"]["mqtt"] and not isinstance(
                    kwargs["options"]["mqtt"]["cleanStart"], bool):
                raise ConfigurationException(
                    "Optional setting options.mqtt.cleanStart must be a boolean if provided"
                )

        # Set defaults for optional configuration
        if "options" not in kwargs:
            kwargs["options"] = {}

        if "domain" not in kwargs[
                "options"] or kwargs["options"]["domain"] is None:
            kwargs["options"]["domain"] = "internetofthings.ibmcloud.com"

        if "logLevel" not in kwargs[
                "options"] or kwargs["options"]["logLevel"] is None:
            kwargs["options"]["logLevel"] = logging.INFO

        if "mqtt" not in kwargs["options"]:
            kwargs["options"]["mqtt"] = {}

        if "port" not in kwargs["options"]["mqtt"]:
            kwargs["options"]["mqtt"]["port"] = None

        if "transport" not in kwargs["options"][
                "mqtt"] or kwargs["options"]["mqtt"]["transport"] is None:
            kwargs["options"]["mqtt"]["transport"] = "tcp"

        if "cleanStart" not in kwargs["options"]["mqtt"]:
            kwargs["options"]["mqtt"]["cleanStart"] = False

        if "sessionExpiry" not in kwargs["options"]["mqtt"]:
            kwargs["options"]["mqtt"]["sessionExpiry"] = 3600

        if "keepAlive" not in kwargs["options"]["mqtt"]:
            kwargs["options"]["mqtt"]["keepAlive"] = 60

        if "caFile" not in kwargs["options"]["mqtt"]:
            kwargs["options"]["mqtt"]["caFile"] = None

        dict.__init__(self, **kwargs)