def publishGatewayEvent(self, event, msgFormat, data, qos=0, on_publish=None): gatewayType = self._options['type'] gatewayId = self._options['id'] if not self.connectEvent.wait(): self.logger.warning("Unable to send event %s because gateway as a device is not currently connected") return False else: self.logger.debug("Sending event %s with data %s" % (event, json.dumps(data))) topic = 'iot-2/type/' + gatewayType + '/id/' + gatewayId +'/evt/'+event+'/fmt/' + msgFormat if msgFormat in self._messageEncoderModules: payload = self._messageEncoderModules[msgFormat].encode(data, datetime.now(pytz.timezone('UTC'))) try: result = self.client.publish(topic, payload=payload, qos=qos, retain=False) if result[0] == paho.MQTT_ERR_SUCCESS: if on_publish is not None: self._messagesLock.acquire() if result[1] in self._onPublishCallbacks: # paho callback beat this thread so call callback inline now on_publish() del self._onPublishCallbacks[result[1]] else: # this thread beat paho callback so set up for call later self._onPublishCallbacks[result[1]] = on_publish return True else: return False finally: if on_publish is not None: self._messagesLock.release() else: raise MissingMessageEncoderException(msgFormat)
def publishCommand(self, deviceType, deviceId, command, msgFormat, data=None, qos=0, on_publish=None): if self._options['org'] == "quickstart": self.logger.warning("QuickStart applications do not support sending commands") return False if not self.connectEvent.wait(): return False else: topic = 'iot-2/type/%s/id/%s/cmd/%s/fmt/%s' % (deviceType, deviceId, command, msgFormat) if msgFormat in self._messageEncoderModules: payload = self._messageEncoderModules[msgFormat].encode(data, datetime.now()) try: # need to take lock to ensure on_publish is not called before we know the mid if on_publish is not None: self._messagesLock.acquire() result = self.client.publish(topic, payload=payload, qos=qos, retain=False) if result[0] == paho.MQTT_ERR_SUCCESS: if on_publish is not None: self._onPublishCallbacks[result[1]] = on_publish return True else: return False finally: if on_publish is not None: self._messagesLock.release() else: raise MissingMessageEncoderException(msgFormat)
def publishEvent(self, event, msgFormat, data, qos=0, on_publish=None): if not self.connectEvent.wait(): self.logger.warning("Unable to send event %s because device is not currently connected") return False else: self.logger.debug("Sending event %s with data %s" % (event, json.dumps(data))) topic = 'iot-2/evt/'+event+'/fmt/' + msgFormat if msgFormat in self._messageEncoderModules: payload = self._messageEncoderModules[msgFormat].encode(data, datetime.now(pytz.timezone('UTC'))) try: # need to take lock to ensure on_publish is not called before we know the mid if on_publish is not None: self._messagesLock.acquire() result = self.client.publish(topic, payload=payload, qos=qos, retain=False) if result[0] == paho.MQTT_ERR_SUCCESS: if on_publish is not None: self._onPublishCallbacks[result[1]] = on_publish return True else: return False finally: if on_publish is not None: self._messagesLock.release() else: raise MissingMessageEncoderException(msgFormat)
def publishEvent(self, deviceType, deviceId, event, msgFormat, data, qos=0, on_publish=None): if not self.connectEvent.wait(timeout=10): return False else: topic = 'iot-2/type/%s/id/%s/evt/%s/fmt/%s' % (deviceType, deviceId, event, msgFormat) if msgFormat in self._messageEncoderModules: payload = self._messageEncoderModules[msgFormat].encode(data, datetime.now()) try: result = self.client.publish(topic, payload=payload, qos=qos, retain=False) if result[0] == paho.MQTT_ERR_SUCCESS: if on_publish is not None: self._messagesLock.acquire() if result[1] in self._onPublishCallbacks: # paho callback beat this thread so call callback inline now del self._onPublishCallbacks[result[1]] 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 finally: if on_publish is not None: self._messagesLock.release() else: raise MissingMessageEncoderException(msgFormat)
def publishEvent(self, deviceType, deviceId, event, msgFormat, data, qos=0, on_publish=None): if not self.connectEvent.wait(): return False else: topic = 'iot-2/type/%s/id/%s/evt/%s/fmt/%s' % (deviceType, deviceId, event, msgFormat) if msgFormat in self._messageEncoderModules: payload = self._messageEncoderModules[msgFormat].encode(data, datetime.now()) try: # need to take lock to ensure on_publish is not called before we know the mid if on_publish is not None: self._messagesLock.acquire() result = self.client.publish(topic, payload=payload, qos=qos, retain=False) if result[0] == paho.MQTT_ERR_SUCCESS: if on_publish is not None: self._onPublishCallbacks[result[1]] = on_publish return True else: return False finally: if on_publish is not None: self._messagesLock.release() else: raise MissingMessageEncoderException(msgFormat)
def publishCommand(self, deviceType, deviceId, command, msgFormat, data=None, qos=0, on_publish=None): if self._options['org'] == "quickstart": 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' % (deviceType, deviceId, command, msgFormat) if msgFormat in self._messageEncoderModules: payload = self._messageEncoderModules[msgFormat].encode(data, datetime.now()) try: result = self.client.publish(topic, payload=payload, qos=qos, retain=False) if result[0] == paho.MQTT_ERR_SUCCESS: if on_publish is not None: self._messagesLock.acquire() if result[1] in self._onPublishCallbacks: # paho callback beat this thread so call callback inline now del self._onPublishCallbacks[result[1]] 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 finally: if on_publish is not None: self._messagesLock.release() else: raise MissingMessageEncoderException(msgFormat)
def publishCommand(self, deviceType, deviceId, command, msgFormat, data=None, qos=0): if self._options['org'] == "quickstart": self.logger.warning( "QuickStart applications do not support sending commands") return False if not self.connectEvent.wait(): return False else: topic = 'iot-2/type/%s/id/%s/cmd/%s/fmt/%s' % ( deviceType, deviceId, command, msgFormat) if msgFormat in self._messageEncoderModules: payload = self._messageEncoderModules[msgFormat].encode( data, datetime.now()) self.client.publish(topic, payload=payload, qos=qos, retain=False) return True else: raise MissingMessageEncoderException(msgFormat)
def publishEvent(self, deviceType, deviceId, event, msgFormat, data, qos=0, on_publish=None): """ Publish an event on behalf of a device. # Parameters deviceType (string): The typeId of the device this event is to be published from deviceId (string): The deviceId of the device this event is to be published from event (string): The name of this event msgFormat (string): The format of the data for this event data (dict) : The data for this event qos (int) : The equivalent MQTT semantics of quality of service using the same constants (optional, defaults to `0`) on_publish (function) : A function that will be called when receipt of the publication is confirmed. This has different implications depending on the qos: - qos 0 : the client has asynchronously begun to send the event - qos 1 and 2 : the client has confirmation of delivery from IoTF """ if not self.connectEvent.wait(timeout=10): return False else: topic = 'iot-2/type/%s/id/%s/evt/%s/fmt/%s' % ( deviceType, deviceId, event, msgFormat) if msgFormat in self._messageEncoderModules: payload = self._messageEncoderModules[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 (do 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 else: raise MissingMessageEncoderException(msgFormat)
def publishCommand(self, deviceType, deviceId, command, msgFormat, data=None, qos=0, on_publish=None): """ Publish a command to a device # Parameters deviceType (string) : The type of the device this command is to be published to deviceId (string): The id of the device this command is to be published to command (string) : The name of the command msgFormat (string) : The format of the command payload data (dict) : The command data qos (int) : The equivalent MQTT semantics of quality of service using the same constants (optional, defaults to `0`) on_publish (function) : A function that will be called when receipt of the publication is confirmed. This has different implications depending on the qos: - qos 0 : the client has asynchronously begun to send the event - qos 1 and 2 : the client has confirmation of delivery from WIoTP """ if self._options['org'] == "quickstart": 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' % ( deviceType, deviceId, command, msgFormat) if msgFormat in self._messageEncoderModules: payload = self._messageEncoderModules[msgFormat].encode( data, datetime.now()) try: result = self.client.publish(topic, payload=payload, qos=qos, retain=False) if result[0] == paho.MQTT_ERR_SUCCESS: self._messagesLock.acquire() 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 finally: self._messagesLock.release() else: raise MissingMessageEncoderException(msgFormat)
def publishEvent(self, event, msgFormat, data, qos=0, on_publish=None): ''' Publish an event in IoTF. Parameters: event - the name of this event msgFormat - the format of the data for this event data - the data for this event Optional paramters: qos - the equivalent MQTT semantics of quality of service using the same constants (0, 1 and 2) on_publish - a function that will be called when receipt of the publication is confirmed. This has different implications depending on the qos: qos 0 - the client has asynchronously begun to send the event qos 1 and 2 - the client has confirmation of delivery from IoTF ''' if not self.connectEvent.wait(timeout=10): self.logger.warning( "Unable to send event %s because device is not currently connected" ) return False else: self.logger.debug("Sending event %s with data %s" % (event, json.dumps(data))) topic = 'iot-2/evt/' + event + '/fmt/' + msgFormat if msgFormat in self._messageEncoderModules: payload = self._messageEncoderModules[msgFormat].encode( data, datetime.now(pytz.timezone('UTC'))) try: result = self.client.publish(topic, payload=payload, qos=qos, retain=False) if result[0] == paho.MQTT_ERR_SUCCESS: if on_publish is not None: self._messagesLock.acquire() if result[1] in self._onPublishCallbacks: # paho callback beat this thread so call callback inline now del self._onPublishCallbacks[result[1]] 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 finally: if on_publish is not None: self._messagesLock.release() else: raise MissingMessageEncoderException(msgFormat)
def publishEvent(self, deviceType, deviceId, event, msgFormat, data, qos=0): if not self.connectEvent.wait(): return False else: topic = 'iot-2/type/%s/id/%s/evt/%s/fmt/%s' % (deviceType, deviceId, event, msgFormat) if msgFormat in self._messageEncoderModules: payload = self._messageEncoderModules[msgFormat].encode(data, datetime.now()) self.client.publish(topic, payload=payload, qos=qos, retain=False) return True else: raise MissingMessageEncoderException(msgFormat)
def publishDeviceEvent(self, deviceType, deviceId, event, msgFormat, data, qos=0, on_publish=None): if not self.connectEvent.wait(timeout=10): self.logger.warning( "Unable to send event %s because gateway as a device is not currently connected" ) return False else: if self.logger.isEnabledFor(logging.DEBUG): # The data object may not be serializable, e.g. if using a custom binary format try: dataString = json.dumps(data) except: dataString = str(data) self.logger.debug("Sending event %s with data %s" % (event, dataString)) topic = 'iot-2/type/' + deviceType + '/id/' + deviceId + '/evt/' + event + '/fmt/' + msgFormat if msgFormat in self._messageEncoderModules: payload = self._messageEncoderModules[msgFormat].encode( data, datetime.now(pytz.timezone('UTC'))) try: result = self.client.publish(topic, payload=payload, qos=qos, retain=False) if result[0] == paho.MQTT_ERR_SUCCESS: self._messagesLock.acquire() 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 finally: self._messagesLock.release() else: raise MissingMessageEncoderException(msgFormat)
def publishEvent(self, deviceType, deviceId, event, msgFormat, data, qos=0, on_publish=None): """ Publish an event in IoTF as if the application were a device. Parameters ---------- deviceType : string The type of the device this event is to be published from deviceId : string The id of the device this event is to be published from event : string The name of this event msgFormat : string The format of the data for this event data : string The data for this event qos : {0, 1, 2}, optional The equivalent MQTT semantics of quality of service using the same constants (defaults to `0`) on_publish : function A function that will be called when receipt of the publication is confirmed. This has different implications depending on the qos: - qos 0 : the client has asynchronously begun to send the event - qos 1 and 2 : the client has confirmation of delivery from IoTF """ if not self.connectEvent.wait(timeout=10): return False else: topic = 'iot-2/type/%s/id/%s/evt/%s/fmt/%s' % (deviceType, deviceId, event, msgFormat) if msgFormat in self._messageEncoderModules: payload = self._messageEncoderModules[msgFormat].encode(data, datetime.now()) try: result = self.client.publish(topic, payload=payload, qos=qos, retain=False) if result[0] == paho.MQTT_ERR_SUCCESS: if on_publish is not None: self._messagesLock.acquire() if result[1] in self._onPublishCallbacks: # paho callback beat this thread so call callback inline now del self._onPublishCallbacks[result[1]] 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 finally: if on_publish is not None: self._messagesLock.release() else: raise MissingMessageEncoderException(msgFormat)
def publishEvent(self, event, msgFormat, data, qos=0): if not self.connectEvent.wait(): self.logger.warning("Unable to send event %s because device is not currently connected") return False else: self.logger.debug("Sending event %s with data %s" % (event, json.dumps(data))) topic = 'iot-2/evt/'+event+'/fmt/' + msgFormat if msgFormat in self._messageEncoderModules: payload = self._messageEncoderModules[msgFormat].encode(data, datetime.now(pytz.timezone('UTC'))) self.client.publish(topic, payload=payload, qos=qos, retain=False) return True else: raise MissingMessageEncoderException(msgFormat)
def publishEvent(self, event, msgFormat, data): """ 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("Sending event %s with data %s" % (event, json.dumps(data))) if msgFormat in self._messageEncoderModules: payload = self._messageEncoderModules[msgFormat].encode( data, datetime.now(pytz.timezone('UTC'))) contentType = self.getContentType(msgFormat) response = requests.post(intermediateUrl, auth=credentials, data=payload, headers={'content-type': contentType}) else: raise MissingMessageEncoderException(msgFormat) except Exception as e: self.logger.error(e) raise e if response.status_code >= 300: self.logger.warning( "Unable to send event: HTTP response code = %s" % (response.status_code)) return response.status_code