Beispiel #1
0
    def on_connect(self, client, userdata, flags, rc):
        """
        This is called after the client has received a CONNACK message from the broker 
        in response to calling connect().
        
        Parameters
        ----------
        client : ?
        userdata : ?
        flags : ?
        rc : {0,1,2,3,4,5}
            An integer giving the return code:
            0: Success
            1: Refused - unacceptable protocol version
            2: Refused - identifier rejected
            3: Refused - server unavailable
            4: Refused - bad user name or password (MQTT v3.1 broker only)
            5: Refused - not authorised (MQTT v3.1 broker only)
        """
        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:
                        self.client.subscribe(subscription, qos=self._subscriptions[subscription])
                    self.logger.debug("Restored %s previous subscriptions" % len(self._subscriptions))

        elif rc == 5:
            self.logAndRaiseException(ConnectionException("Not authorized: (%s, %s, %s)" % (self.clientId, self.username, self.password)))
        else:
            self.logAndRaiseException(ConnectionException("Connection failed: RC= %s" % (rc)))
Beispiel #2
0
    def on_connect(self, client, userdata, flags, rc):
        '''
        This is called after the client has received a CONNACK message from the broker in response to calling connect().
        The parameter rc is an integer giving the return code:

        0: Success
        1: Refused - unacceptable protocol version
        2: Refused - identifier rejected
        3: Refused - server unavailable
        4: Refused - bad user name or password
        5: Refused - not authorised
        '''
        if rc == 0:
            self.connectEvent.set()
            self.logger.info("Connected successfully: %s" % (self.clientId))
            if self._options['org'] != "quickstart":
                self.__subscribeToCommands()
        elif rc == 5:
            self.logAndRaiseException(
                ConnectionException(
                    "Not authorized: s (%s, %s, %s)" %
                    (self.clientId, self.username, self.password)))
        else:
            self.logAndRaiseException(
                ConnectionException("Connection failed: RC= %s" % (rc)))
Beispiel #3
0
    def on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            self.connectEvent.set()
            self.logger.info("Connected successfully: %s, Port: %s" %
                             (self.clientId, self.port))
            if self._options['org'] != "quickstart":
                dm_response_topic = ManagedClient.DM_RESPONSE_TOPIC_TEMPLATE % (
                    self._gatewayType, self._gatewayId)
                dm_observe_topic = ManagedClient.DM_OBSERVE_TOPIC_TEMPLATE % (
                    self._gatewayType, self._gatewayId)
                (self.dmSubscriptionResult,
                 self.dmSubscriptionMid) = self.client.subscribe([
                     (dm_response_topic, 1), (dm_observe_topic, 1),
                     (self.COMMAND_TOPIC, 1)
                 ])

                if self.dmSubscriptionResult != paho.MQTT_ERR_SUCCESS:
                    self._logAndRaiseException(
                        ConnectionException(
                            "Unable to subscribe to device management topics"))

        elif rc == 5:
            self._logAndRaiseException(
                ConnectionException(
                    "Not authorized: s (%s, %s, %s)" %
                    (self.clientId, self.username, self.password)))
        else:
            self._logAndRaiseException(
                ConnectionException("Connection failed: RC= %s" % (rc)))
Beispiel #4
0
 def on_connect(self, client, userdata, flags, rc):
     if rc == 0:
         self.connectEvent.set()
         self.logger.info("Connected successfully: %s, Port: %s" %
                          (self.clientId, self.port))
         if self._options['org'] != "quickstart":
             self.client.subscribe([
                 (ManagedClient.DM_RESPONSE_TOPIC, 1),
                 (ManagedClient.DM_OBSERVE_TOPIC, 1),
                 (ManagedClient.DM_REBOOT_TOPIC, 1),
                 (ManagedClient.DM_FACTORY_REESET, 1),
                 (ManagedClient.DM_UPDATE_TOPIC, 1),
                 (ManagedClient.DM_FIRMWARE_UPDATE_TOPIC, 1),
                 (ManagedClient.DM_FIRMWARE_DOWNLOAD_TOPIC, 1),
                 (ManagedClient.DM_CANCEL_OBSERVE_TOPIC, 1),
                 (Client.COMMAND_TOPIC, 1),
                 (ManagedClient.DME_ACTION_TOPIC, 1)
             ])
     elif rc == 5:
         self.logAndRaiseException(
             ConnectionException(
                 "Not authorized: s (%s, %s, %s)" %
                 (self.clientId, self.username, self.password)))
     else:
         self.logAndRaiseException(
             ConnectionException("Connection failed: RC= %s" % (rc)))
	def on_connect(self, client, userdata, flags, rc):
		if rc == 0:
			self.connectEvent.set()
			self.logger.info("Connected successfully: %s" % self.clientId)
		elif rc == 5:
			self.logAndRaiseException(ConnectionException("Not authorized: (%s, %s, %s)" % (self.clientId, self.username, self.password)))
		else:
			self.logAndRaiseException(ConnectionException("Connection failed: RC= %s" % (rc)))
Beispiel #6
0
	def on_connect(self, client, userdata, flags, rc):
		if rc == 0:
			self.connectEvent.set()
			self.logger.info("Connected successfully: %s" % self.clientId)
			if self._options['org'] != "quickstart":
				self.client.subscribe( [(ManagedClient.DM_RESPONSE_TOPIC, 1), (ManagedClient.DM_OBSERVE_TOPIC, 1), (Client.COMMAND_TOPIC, 1)] )
		elif rc == 5:
			self.logAndRaiseException(ConnectionException("Not authorized: s (%s, %s, %s)" % (self.clientId, self.username, self.password)))
		else:
			self.logAndRaiseException(ConnectionException("Connection failed: RC= %s" % (rc)))
Beispiel #7
0
 def on_connect(self, client, userdata, flags, rc):
     if rc == 0:
         self.connectEvent.set()
         self.logger.info("Connected successfully: %s" % (self.clientId))
         #if self._options['org'] != "quickstart":
             #self.subscribeToGatewayCommands()
     elif rc == 5:
         self.logAndRaiseException(ConnectionException("Not authorized: s (%s, %s, %s)" % (self.clientId, self.username, self.password)))
     else:
         self.logAndRaiseException(ConnectionException("Connection failed: RC= %s" % (rc)))
Beispiel #8
0
	def on_connect(self, client, userdata, flags, rc):
		if rc == 0:
			self.connectEvent.set()
			self.logger.info("Connected successfully: %s, Port: %s" % (self.clientId,self.port))
			if self._options['org'] != "quickstart":
				dm_response_topic = ManagedGateway.DM_RESPONSE_TOPIC_TEMPLATE %  (self._gatewayType,self._gatewayId)
				dm_observe_topic = ManagedGateway.DM_OBSERVE_TOPIC_TEMPLATE %  (self._gatewayType,self._gatewayId)
				self.client.subscribe( [(dm_response_topic, 1), (dm_observe_topic, 1), (Client.COMMAND_TOPIC, 1)] )
		elif rc == 5:
			self.logAndRaiseException(ConnectionException("Not authorized: s (%s, %s, %s)" % (self.clientId, self.username, self.password)))
		else:
			self.logAndRaiseException(ConnectionException("Connection failed: RC= %s" % (rc)))
Beispiel #9
0
	def on_connect(self, client, userdata, flags, rc):
		if rc == 0:
			self.connectEvent.set()
			self.logger.info("Connected successfully: %s" % self.clientId)
			
			# Restoring previous subscriptions
			if len(self._subscriptions) > 0:
				for subscription in self._subscriptions:
					self.client.subscribe(subscription["topic"], qos=subscription["qos"])
				self.logger.debug("Restored %s previous subscriptions" % len(self._subscriptions))
					
		elif rc == 5:
			self.logAndRaiseException(ConnectionException("Not authorized: (%s, %s, %s)" % (self.clientId, self.username, self.password)))
		else:
			self.logAndRaiseException(ConnectionException("Connection failed: RC= %s" % (rc)))
Beispiel #10
0
	def publishEventOverHTTP(self, event, data):
		self.logger.debug("Sending event %s with data %s" % (event, json.dumps(data)))

		templateUrl = '%s://%s.%s/api/v0002/device/types/%s/devices/%s/events/%s'

#		Extracting all the values needed for the ReST operation
#		Checking each value for 'None' is not needed as the device itself would not have got created, if it had any 'None' values
		orgid = self._options['org']
		deviceType = self._options['type']
		deviceId = self._options['id']
		authMethod = self._options['auth-method'] 
		authToken = self._options['auth-token']
		credentials = (authMethod, authToken)

		if orgid == 'quickstart':
			protocol = 'http'
		else:
			protocol = 'https'

#		String replacement from template to actual URL
		intermediateUrl = templateUrl % (protocol, orgid, self._options['domain'], deviceType, deviceId, event)

		try:
			msgFormat = "json"
			payload = self._messageEncoderModules[msgFormat].encode(data, datetime.now(pytz.timezone('UTC')))
			response = requests.post(intermediateUrl, auth = credentials, data = payload, headers = {'content-type': 'application/json'})
		except Exception as e:
			self.logger.error("POST Failed")
			self.logger.error(e)			
			raise ConnectionException("Server not found")

		if response.status_code >= 300:
			self.logger.warning(response.headers)
		return response.status_code
Beispiel #11
0
	def publishEventOverHTTP(self, event, data):
		self.logger.debug("Sending event %s with data %s" % (event, json.dumps(data)))

		templateUrl = '%s://%s.%s/api/v0002/device/types/%s/devices/%s/events/%s'

		orgid = self._options['org']
		deviceType = self._options['type']
		deviceId = self._options['id']
		authMethod = self._options['auth-method']
		authToken = self._options['auth-token']
		credentials = (authMethod, authToken)

		if orgid == 'quickstart':
			protocol = 'http'
		else:
			protocol = 'https'

		intermediateUrl = templateUrl % (protocol, orgid, self._options['domain'], deviceType, deviceId, event)

		try:
			msgFormat = "json"
			payload = self._messageEncoderModules[msgFormat].encode(data, datetime.now(pytz.timezone('UTC')))
			response = requests.post(intermediateUrl, auth = credentials, data = payload, headers = {'content-type': 'application/json'})
		except Exception as e:
			self.logger.error("POST Failed")
			self.logger.error(e)
			raise ConnectionException("Server not found")

#		print ("Response status = ", response.status_code, "\tResponse ", response.headers)
		if response.status_code >= 300:
			self.logger.warning(response.headers)
		return response.status_code
Beispiel #12
0
 def publishCommand(self, deviceType, deviceId, event, cmdData, cmdFormat="json"):
     '''
     This method is used by the application to publish device command over HTTP(s)
     Parameters - deviceType, deviceId, event, cmdData and cmdFormat by default JSON
     It throws a ConnectionException with the message "Server not found" if the
     application is unable to reach the server, Otherwise it returns the
     HTTP status code, (200 - 207 for success)
     '''
     self.logger.debug("Sending event %s with command format %s" % (event, json.dumps(cmdData)))
     templateUrl = 'https://%s.messaging.%s/api/v0002/application/types/%s/devices/%s/commands/%s'
     orgid = self._options['org']
     if orgid == 'quickstart':
         authKey = None
         authToken = None
     else:
         authKey = self._options['auth-key']
         authToken = self._options['auth-token']
     credentials = (authKey, authToken)
     #String replacement from template to actual URL
     intermediateUrl = templateUrl % (orgid, self._options['domain'], deviceType, deviceId, event)
     try:
         self.logger.debug("Data Format = %s",(cmdFormat))
         contentType = self.getContentType(cmdFormat)
         self.logger.debug("contentType = %s",(contentType))
         payload = self._messageEncoderModules[cmdFormat].encode(cmdData, datetime.now())
         response = requests.post(intermediateUrl, auth = credentials, data = payload, headers = {'content-type': contentType})
     except Exception as e:
         self.logger.error("POST Failed")
         self.logger.error(e)
         raise ConnectionException("Server not found")
     if response.status_code >= 300:
         self.logger.warning(response.headers)
     return response.status_code
Beispiel #13
0
    def _onConnect(self, mqttc, userdata, flags, rc):
        """
        This is called after the client has received a `CONNACK` message 
        from the broker in response to calling connect().
        
        See [paho.mqtt.python#on_connect](https://github.com/eclipse/paho.mqtt.python#on_connect) for more information
        
        # Parameters
        mqttc (paho.mqtt.client.Client): The client instance for this callback
        userdata: The private user data as set in `Client()` or `user_data_set()`
        flags: response flags sent by the broker
        rc (int): the connection result.
        
        The value of `rc` indicates success or not

        - `0` Success
        - `1` Refused - incorrect protocol version
        - `2` Refused - invalid client identifier
        - `3` Refused - server unavailable
        - `4` Refused - bad user name or password
        - `5` Refused - not authorised
        """

        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:
                        self.client.subscribe(
                            subscription,
                            qos=self._subscriptions[subscription])
                    self.logger.debug("Restored %s previous subscriptions" %
                                      len(self._subscriptions))

        elif rc == 5:
            self._logAndRaiseException(
                ConnectionException(
                    "Not authorized: (%s, %s, %s)" %
                    (self.clientId, self.username, self.password)))
        else:
            self._logAndRaiseException(
                ConnectionException("Connection failed: RC= %s" % (rc)))
Beispiel #14
0
    def publishEventOverHTTP(self, deviceType, deviceId, event, data):
        self.logger.debug("Sending event %s with data %s" %
                          (event, json.dumps(data)))

        #		Kept this as a template
        #		orgUrl = 'http://quickstart.internetofthings.ibmcloud.com/api/v0002/application/types/arduino/devices/00aabbccde02/events/status'
        templateUrl = '%s://%s.internetofthings.ibmcloud.com/api/v0002/application/types/%s/devices/%s/events/%s'

        #		Extracting all the values needed for the ReST operation
        #		Checking each value for 'None' is not needed as the application itself would not have got created, if it had any 'None' values
        orgid = self._options['org']
        authKey = self._options['auth-key']
        authToken = self._options['auth-token']

        credentials = (authKey, authToken)

        if orgid == 'quickstart':
            protocol = 'http'
        else:
            protocol = 'https'

#		String replacement from template to actual URL
        intermediateUrl = templateUrl % (protocol, orgid, deviceType, deviceId,
                                         event)

        try:
            msgFormat = "json"
            payload = self._messageEncoderModules[msgFormat].encode(
                data, datetime.now())
            response = requests.post(
                intermediateUrl,
                auth=credentials,
                data=payload,
                headers={'content-type': 'application/json'})
        except Exception as e:
            self.logger.error("POST Failed")
            self.logger.error(e)
            raise ConnectionException("Server not found")


#		print ("Response status = ", response.status_code, "\tResponse ", response.headers)
        if response.status_code >= 300:
            self.logger.warning(response.headers)
        return response.status_code
Beispiel #15
0
    def publishEvent(self, event, data, dataFormat="json"):
        """
		Publish an event over HTTP(s) as given supported format
		Throws a ConnectionException with the message "Server not found" if the client is unable to reach the server
		Otherwise it returns the HTTP status code, (200 - 207 for success)
		"""
        self.logger.debug("Sending event %s with data %s" %
                          (event, json.dumps(data)))

        templateUrl = 'https://%s.messaging.%s/api/v0002/device/types/%s/devices/%s/events/%s'

        orgid = self._options['org']
        deviceType = self._options['type']
        deviceId = self._options['id']
        authMethod = "use-token-auth"
        authToken = self._options['auth-token']
        credentials = (authMethod, authToken)

        if orgid == 'quickstart':
            authMethod = None
            authToken = None

        intermediateUrl = templateUrl % (orgid, self._options['domain'],
                                         deviceType, deviceId, event)
        self.logger.debug("URL: %s", intermediateUrl)
        try:
            self.logger.debug("Data Format = %s", (dataFormat))
            contentType = self.getContentType(dataFormat)
            self.logger.debug("contentType = %s", (contentType))
            payload = self._messageEncoderModules[dataFormat].encode(
                data, datetime.now(pytz.timezone('UTC')))
            self.logger.debug("payload = %s", (payload))
            response = requests.post(intermediateUrl,
                                     auth=credentials,
                                     data=payload,
                                     headers={'content-type': contentType})
        except Exception as e:
            self.logger.error("POST Failed")
            self.logger.error(e)
            raise ConnectionException("Server not found")

        if response.status_code >= 300:
            self.logger.warning(response.headers)
        return response.status_code
Beispiel #16
0
    def publishEvent(self, deviceType, deviceId, event, data):
        '''
		This method is used by the application to publish events over HTTP(s)
		It accepts 4 parameters, deviceType, deviceId, event which denotes event type and data which is the message to be posted
		It throws a ConnectionException with the message "Server not found" if the application is unable to reach the server
		Otherwise it returns the HTTP status code, (200 - 207 for success)
		'''
        self.logger.debug("Sending event %s with data %s" %
                          (event, json.dumps(data)))

        templateUrl = 'https://%s.messaging.%s/api/v0002/application/types/%s/devices/%s/events/%s'

        orgid = self._options['org']
        if orgid == 'quickstart':
            authKey = None
            authToken = None
        else:
            authKey = self._options['auth-key']
            authToken = self._options['auth-token']

        credentials = (authKey, authToken)
        #String replacement from template to actual URL
        intermediateUrl = templateUrl % (orgid, self._options['domain'],
                                         deviceType, deviceId, event)

        try:
            msgFormat = "json"
            payload = self._messageEncoderModules[msgFormat].encode(
                data, datetime.now())
            response = requests.post(
                intermediateUrl,
                auth=credentials,
                data=payload,
                headers={'content-type': 'application/json'})
        except Exception as e:
            self.logger.error("POST Failed")
            self.logger.error(e)
            raise ConnectionException("Server not found")

        if response.status_code >= 300:
            self.logger.warning(response.headers)
        return response.status_code
Beispiel #17
0
    def on_connect(self, client, 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:
                        self.client.subscribe(
                            subscription,
                            qos=self._subscriptions[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)))