class MqttRos: AllowedActions = ['both', 'publish', 'subscribe'] def __init__(self, config): self.iot_data = config self.thing_name = self.iot_data["thingName"] self.subscribe_topic = self.iot_data["subscribeTopic"] self.publish_topic = self.iot_data["publishTopic"] self.client_id = self.thing_name + '_mqtt' self.init_mqtt_client() self.init_ros_pubs() self.init_ros_subs() self.mqtt_subs() def init_ros_pubs(self): # Place holder publisher into ros space. self.mqttToRosPub = rospy.Publisher('awsiot_to_ros', String, queue_size=1) def init_ros_subs(self): self.rosPubToMqtt = rospy.Subscriber('ros_to_awsiot', String, self.ros_to_mqtt_cb, queue_size=10) def ros_to_mqtt_cb(self, msg): self.ros_to_awsiot_publisher(msg) def ros_to_awsiot_publisher(self, msg): try: self.myAWSIoTMQTTClient.publish(self.publish_topic, msg.data, 1) except Exception as e: rospy.logwarn("MqttRos::ros_to_mqtt_cb got exception") rospy.logwarn(e) def gm_to_awsiot_publisher(self, message): try: self.myAWSIoTMQTTClient.publish('gm_{}'.format(self.publish_topic), str(message), 1) except Exception as e: rospy.logwarn(e) rospy.logwarn("MqttRos::gm_publisher got exception") # MQTT message callback def mqtt_callback(self, client, userdata, message): try: mqttToRosJson = {} mqttToRosJson['payload'] = json.loads(message.payload) mqttToRosJson['topic'] = message.topic self.mqttToRosPub.publish(json.dumps(mqttToRosJson)) except Exception as e: rospy.logwarn("MqttRos::mqtt_callback got exception") def gm_mqtt_callback(self, client, userdata, message): try: payload = json.loads(message.payload) self._game_command_handler(payload) except Exception as e: rospy.logwarn(e) rospy.logwarn("MqttRos::gm_mqtt_callback got exception") def init_mqtt_client(self): # Grab all required info from the parsed data folder_path = self.iot_data['configFilePath'] host = self.iot_data['endpoint'] rootCAPath = os.path.join(folder_path, self.iot_data['rootCAFile']) certificatePath = os.path.join(folder_path, self.iot_data['certFile']) privateKeyPath = os.path.join(folder_path, self.iot_data['privateKeyFile']) useWebsocket = self.iot_data['useWebsocket'] self.mode = self.iot_data['mqttMode'] if self.mode not in MqttRos.AllowedActions: rospy.logwarn("Unknown --mode option %s. Must be one of %s" % (self.mode, str(MqttRos.AllowedActions))) exit(2) if useWebsocket and certificatePath and privateKeyPath: rospy.logwarn( "X.509 cert authentication and WebSocket are mutual exclusive. Please pick one." ) exit(2) if not useWebsocket and (not certificatePath or not privateKeyPath): rospy.logwarn("Missing credentials for authentication.") exit(2) if useWebsocket: port = 443 if not useWebsocket: port = 8883 # Init AWSIoTMQTTClient self.myAWSIoTMQTTClient = None if useWebsocket: self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.client_id, useWebsocket=True) self.myAWSIoTMQTTClient.configureEndpoint(host, port) self.myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.client_id) self.myAWSIoTMQTTClient.configureEndpoint(host, port) self.myAWSIoTMQTTClient.configureCredentials( rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration self.myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) self.myAWSIoTMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing self.myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec def mqtt_subs(self): # Connect and subscribe to AWS IoT self.myAWSIoTMQTTClient.connect() if self.mode == 'both' or self.mode == 'subscribe': self.myAWSIoTMQTTClient.subscribe(self.subscribe_topic, 1, self.mqtt_callback) self.myAWSIoTMQTTClient.subscribe('gm_{}'.format(self.subscribe_topic), 1, self.gm_mqtt_callback) def set_game_command_cb(self, callback): self._game_command_handler = callback
ShadowClient.configureMQTTOperationTimeout(10) # 5 sec ShadowClient.connect() deviceShadowHandler = ShadowClient.createShadowHandlerWithName( devicename, True) #shadowCallbackContainer_Bot = shadowCallbackContainer(deviceShadowHandler) #deviceShadowHandler.shadowRegisterDeltaCallback(shadowCallbackContainer_Bot.customShadowCallback_Delta) # MQTT Connection establishement myMQTTClient = AWSIoTMQTTClient(devicename) myMQTTClient.configureEndpoint("a1oa9tg9lcso0.iot.eu-west-1.amazonaws.com", 8883) myMQTTClient.configureCredentials(get_rootca(), get_private(), get_cert()) myMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec #connect and publish myMQTTClient.connect() con = psycopg2.connect( "host='litterbugdb.c1ekrfqx70oj.eu-west-1.rds.amazonaws.com' dbname='littering' user='******' password='******'" ) cur = con.cursor() cur.execute("SELECT id FROM devices where mac_addr='%s'", [mac]) row = cur.fetchone() device_id = row[0] print(device_id) s3.download_file('littercam', 'device-' + str(mac) + '/parameters.txt', 'parameters.txt')
class AwsLib: clientId = None hostName = None rootCert = None certKey = None privKey = None topic = None message = None port = None myAWSIoTMQTTClient = None def __init__(self, clientId, hostName, port, rootCert, certKey, privKey): self.clientId = clientId self.hostName = hostName self.rootCert = rootCert self.certKey = certKey self.privKey = privKey self.port = port self.isConnected = False try: # Init AWSIoTMQTTClient self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.clientId) self.myAWSIoTMQTTClient.configureEndpoint(self.hostName, self.port) self.myAWSIoTMQTTClient.configureCredentials( self.rootCert, self.privKey, self.certKey) # AWSIoTMQTTClient connection configuration self.myAWSIoTMQTTClient.configureAutoReconnectBackoffTime( 1, 32, 20) self.myAWSIoTMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing self.myAWSIoTMQTTClient.configureDrainingFrequency( 2) # Draining: 2 Hz self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout( 10) # 10 sec self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec except Exception as e: print(e) def getInfoStatus(self): return self.isConnected def connect(self): if (self.isConnected == False): try: self.myAWSIoTMQTTClient.connect() self.isConnected = True except Exception as e: self.isConnected = False def disconnect(self): if self.isConnected: self.isConnected = False try: self.myAWSIoTMQTTClient.disconnect() except Exception as e: print(e) def subscribe(self, topic, callback): if self.isConnected: try: # self.myAWSIoTMQTTClient.subscribe(topic, 1, self.receiveCallback) self.myAWSIoTMQTTClient.subscribe(topic, 1, callback) except Exception as e: self.isConnected = False print(e) def publish(self, topic, message): if self.isConnected: try: self.myAWSIoTMQTTClient.publish(topic, message, 1) except Exception as e: self.isConnected = False print(e)
class ElfThread(threading.Thread): """ The abstract thread that sets up interaction with AWS IoT Things """ def __init__(self, thing_name, cli, thing, cfg, args=(), kwargs={}): super(ElfThread, self).__init__(name=thing_name, args=args, kwargs=kwargs) self.thing_name = thing_name self.thing = thing self.root_cert = cli.root_cert if cli.append_thing_name: self.shadow_topic = '{0}/{1}'.format(cli.shadow_topic, self.thing_name) self.audio_topic = '{0}/{1}'.format(cli.audio_topic, self.thing_name) else: self.shadow_topic = cli.shadow_topic self.audio_topic = cli.audio_topic self.region = cli.region self.cfg = cfg self.duration = cli.duration self.aws_iot = _get_iot_session(self.region, cli.profile_name) self.message_qos = cli.qos if policy_name_key not in thing.keys(): policy_name, policy_arn = _create_and_attach_policy( self.region, self.shadow_topic, self.thing_name, self.thing['certificateArn'], cli) self.policy_name = policy_name self.policy_arn = policy_arn log.debug("[elf_thread] attached policy on cert:{0}".format( thing['certificateArn'])) else: log.debug( "[elf_thread] policy_name:{0} exists.".format(policy_name_key)) self.policy_name = thing[policy_name_key] self.policy_arn = thing[policy_arn_key] # setup MQTT client eid = uuid.UUID(cfg[elf_id_key]) # use ELF ID and a random string since we must use unique Client ID per # client. cid = eid.urn.split(":")[2] + "_" + make_string(3) self.mqttc = AWSIoTMQTTClient(clientID=cid) t_name = cfg_dir + thing_name_template.format(0) endpoint = self.aws_iot.describe_endpoint() log.info("ELF connecting asynchronously to IoT endpoint:'{0}'".format( endpoint['endpointAddress'])) self.mqttc.configureEndpoint(hostName=endpoint['endpointAddress'], portNumber=AWS_IOT_MQTT_PORT) self.mqttc.configureCredentials(CAFilePath=self.root_cert, KeyPath=t_name + ".prv", CertificatePath=t_name + ".pem") self.mqttc.configureAutoReconnectBackoffTime(1, 128, 20) self.mqttc.configureOfflinePublishQueueing(90, DROP_OLDEST) self.mqttc.configureDrainingFrequency(3) self.mqttc.configureConnectDisconnectTimeout(20) self.mqttc.configureMQTTOperationTimeout(5) self.mqttc.connect() # keepalive default at 30 seconds
class RemoteControllIntentHandler(AbstractRequestHandler): """Handler for RemoteControll Intent.""" def __init__(self): # Init AWSIoTMQTTClient For Websocket connection self.myAWSIoTMQTTClient = None self.myAWSIoTMQTTClient = AWSIoTMQTTClient("", useWebsocket=True) self.myAWSIoTMQTTClient.configureEndpoint("a1xfsi89ntz6zn-ats.iot.ap-northeast-1.amazonaws.com", 443) self.myAWSIoTMQTTClient.configureCredentials("rootCA.pem") # AWSIoTMQTTClient connection configuration self.myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing self.myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Init device/action list self.device_list = {"001":"TV","002":"aircon","003":"light"} self.function_list = {"001":"power","002":"volume_up","003":"volume_down"} # topic self.topic = "$aws/things/RaspberryPi/shadow/update" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return ask_utils.is_intent_name("RemoteControllIntent")(handler_input) def handle(self, handler_input): # slots slots = handler_input.request_envelope.request.intent.slots # device_id device_id = "001" # speak_output = "ーーーーー" # create a payload if slots["btn"].resolutions.resolutions_per_authority[0].status.code == StatusCode.ER_SUCCESS_MATCH: btn_id = slots["btn"].resolutions.resolutions_per_authority[0].values[0].value.id if btn_id == "001": action_id = "001" payload = {"state":{"desired":{"{}".format(self.device_list[device_id]):{"{}".format(self.function_list[action_id]):1}}}} elif btn_id == "002": if slots["action"].resolutions.resolutions_per_authority[0].status.code == StatusCode.ER_SUCCESS_MATCH: action_id = slots["action"].resolutions.resolutions_per_authority[0].values[0].value.id num = slots["num"].value if num != None: payload = {"state":{"desired":{"{}".format(self.device_list[device_id]):{"{}".format(self.function_list[action_id]):int(num)}}}} else: payload = {"state":{"desired":{"{}".format(self.device_list[device_id]):{"{}".format(self.function_list[action_id]):1}}}} logger.debug(json.dumps(payload)) # connct to shadow self.myAWSIoTMQTTClient.connect() logger.debug('connect to shadow') self.myAWSIoTMQTTClient.publish(self.topic, json.dumps(payload), 0) logger.debug('update desired') self.myAWSIoTMQTTClient.disconnect() logger.debug('disconnect to shadow') speak_output = "ーーーーー" else: speak_output = "その操作はできません。テレビをつけたい場合は、テレビをつけて、と言ってください。" return ( handler_input.response_builder .speak(speak_output) .ask(speak_output) .response )
""" # Configure logging logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) """ # Init AWSIoTMQTTClient myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 128, 80) myAWSIoTMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureDrainingFrequency(100) # Draining: Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect to AWS IoT myAWSIoTMQTTClient.connect()
TOPIC = "iot-sensor/test" BROKER_PATH = "" ROOT_CA_PATH = './AmazonRootCA1.pem' PRIVATE_KEY_PATH = './private.pem.key' CERTIFICATE_PATH = './certificate.pem.crt' # Create and Configure the IoT Client IoTclient = AWSIoTMQTTClient(CLIENT_NAME) IoTclient.configureEndpoint(BROKER_PATH, 8883) IoTclient.configureCredentials(ROOT_CA_PATH, PRIVATE_KEY_PATH, CERTIFICATE_PATH) # Allow the device to queue infinite messages IoTclient.configureOfflinePublishQueueing(-1) # Number of messages to send after a connection returns IoTclient.configureDrainingFrequency(2) # 2 requests/second # How long to wait for a [dis]connection to complete (in seconds) IoTclient.configureConnectDisconnectTimeout(10) # How long to wait for publish/[un]subscribe (in seconds) IoTclient.configureMQTTOperationTimeout(5) IoTclient.connect() IoTclient.publish(TOPIC, "connected", 0) # Create and Send Payloads to the IoT Topic def create_payload(): payload = json.dumps({ "id": int(time.time()), "read_date":
def configure(topic="sdk/test/Python"): """AWS configuration """ AllowedActions = ['both', 'publish', 'subscribe'] # Read in command-line parameters parser = argparse.ArgumentParser() parser.add_argument("-e", "--endpoint", action="store", required=True, dest="host", help="Your AWS IoT custom endpoint") parser.add_argument("-r", "--rootCA", action="store", required=True, dest="rootCAPath", help="Root CA file path") parser.add_argument("-c", "--cert", action="store", dest="certificatePath", help="Certificate file path") parser.add_argument("-k", "--key", action="store", dest="privateKeyPath", help="Private key file path") parser.add_argument("-p", "--port", action="store", dest="port", type=int, help="Port number override") parser.add_argument("-w", "--websocket", action="store_true", dest="useWebsocket", default=False, help="Use MQTT over WebSocket") parser.add_argument("-id", "--clientId", action="store", dest="clientId", default="basicPubSub", help="Targeted client id") parser.add_argument("-t", "--topic", action="store", dest="topic", default="sdk/test/Python", help="Targeted topic") parser.add_argument("-m", "--mode", action="store", dest="mode", default="both", help="Operation modes: %s" % str(AllowedActions)) parser.add_argument("-M", "--message", action="store", dest="message", default="Hello World!", help="Message to publish") args = parser.parse_args() host = args.host rootCAPath = args.rootCAPath certificatePath = args.certificatePath privateKeyPath = args.privateKeyPath port = args.port useWebsocket = args.useWebsocket clientId = args.clientId # topic = args.topic topic = topic if args.mode not in AllowedActions: parser.error("Unknown --mode option %s. Must be one of %s" % (args.mode, str(AllowedActions))) exit(2) if args.useWebsocket and args.certificatePath and args.privateKeyPath: parser.error( "X.509 cert authentication and WebSocket are mutual exclusive. Please pick one." ) exit(2) if not args.useWebsocket and (not args.certificatePath or not args.privateKeyPath): parser.error("Missing credentials for authentication.") exit(2) # Port defaults if args.useWebsocket and not args.port: # When no port override for WebSocket, default to 443 port = 443 if not args.useWebsocket and not args.port: # When no port override for non-WebSocket, default to 8883 port = 8883 # Configure logging logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) # Init AWSIoTMQTTClient myAWSIoTMQTTClient = None if useWebsocket: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect() if args.mode == 'both' or args.mode == 'subscribe': myAWSIoTMQTTClient.subscribe(topic, 1, Argument.customCallback) time.sleep(2) return args, myAWSIoTMQTTClient, topic
streamHandler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) # Init AWSIoTMQTTClient mqttClient = AWSIoTMQTTClient(clientId) mqttClient.configureEndpoint(host, port) mqttClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration mqttClient.configureAutoReconnectBackoffTime(1, 32, 20) mqttClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing mqttClient.configureDrainingFrequency(2) # Draining: 2 Hz mqttClient.configureConnectDisconnectTimeout(10) # 10 sec mqttClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT mqttClient.connect() # Init AWSIoTMQTTShadowClient shadowClient = AWSIoTMQTTShadowClient('{}-{}'.format(clientId, 'shadowClient')) shadowClient.configureEndpoint(host, port) shadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTShadowClient configuration shadowClient.configureAutoReconnectBackoffTime(1, 32, 20) shadowClient.configureConnectDisconnectTimeout(10) # 10 sec shadowClient.configureMQTTOperationTimeout(5) # 5 sec
explorerhat.motor.stop() time.sleep(0.2) explorerhat.motor.stop() # Init AWSIoTMQTTClient awsClient = AWSIoTMQTTClient(clientId) awsClient.configureEndpoint(host, port) awsClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration awsClient.configureAutoReconnectBackoffTime(1, 32, 20) awsClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing awsClient.configureDrainingFrequency(2) # Draining: 2 Hz awsClient.configureConnectDisconnectTimeout(10) # 10 sec awsClient.configureMQTTOperationTimeout(5) # 5 sec awsClient.onMessage = handleMessage # Connect and subscribe to AWS IoT awsClient.connect() # Note that we are not putting a message callback here. We are using the general message notification callback. awsClient.subscribeAsync(topic, 1) time.sleep(2) # Start the Kinesis Video Gstreamer Sample App using IoT Credentials runKinesisVideoStream() time.sleep(1) while True:
class PingService(): def __init__(self): # Read in command-line parameters parser = argparse.ArgumentParser() parser.add_argument( "-e", "--endpoint", action="store", default="a3cezb6rg1vyed-ats.iot.us-west-2.amazonaws.com", dest="host", help="Your AWS IoT custom endpoint") parser.add_argument("-r", "--rootCA", action="store", default="{}/root-CA.crt".format(PATH_TO_HOME), dest="rootCAPath", help="Root CA file path") parser.add_argument( "-c", "--cert", action="store", default="{}/PL-student.cert.pem".format(PATH_TO_HOME), dest="certificatePath", help="Certificate file path") parser.add_argument( "-k", "--key", action="store", default="{}/PL-student.private.key".format(PATH_TO_HOME), dest="privateKeyPath", help="Private key file path") parser.add_argument("-p", "--port", action="store", dest="port", type=int, help="Port number override") parser.add_argument("-w", "--websocket", action="store_true", dest="useWebsocket", default=False, help="Use MQTT over WebSocket") parser.add_argument("-id", "--clientId", action="store", dest="clientId", default="pl19-99", help="Targeted client id") parser.add_argument("-t", "--topic", action="store", dest="topic", default="pl19/event", help="Event topic") parser.add_argument("-m", "--mode", action="store", dest="mode", default="both", help="Operation modes: %s" % str(AllowedActions)) parser.add_argument("-M", "--message", action="store", dest="message", default="Hello World!", help="Message to publish") args = parser.parse_args() self.host = args.host self.rootCAPath = args.rootCAPath self.certificatePath = args.certificatePath self.privateKeyPath = args.privateKeyPath self.port = args.port self.useWebsocket = args.useWebsocket self.clientId = args.clientId self.topic = args.topic if args.mode not in AllowedActions: parser.error("Unknown --mode option %s. Must be one of %s" % (args.mode, str(AllowedActions))) exit(2) if args.useWebsocket and args.certificatePath and args.privateKeyPath: parser.error( "X.509 cert authentication and WebSocket are mutual exclusive. Please pick one." ) exit(2) if not args.useWebsocket and (not args.certificatePath or not args.privateKeyPath): parser.error("Missing credentials for authentication.") exit(2) # Port defaults if args.useWebsocket and not args.port: # When no port override for WebSocket, default to 443 self.port = 443 if not args.useWebsocket and not args.port: # When no port override for non-WebSocket, default to 8883 self.port = 8883 # Configure logging streamHandler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) # Init AWSIoTMQTTClient self.mqtt_client = None self.mqtt_client = AWSIoTMQTTClient(self.clientId) self.mqtt_client.configureEndpoint(self.host, self.port) self.mqtt_client.configureCredentials(self.rootCAPath, self.privateKeyPath, self.certificatePath) # AWSIoTMQTTClient connection configuration self.mqtt_client.configureAutoReconnectBackoffTime(1, 32, 20) self.mqtt_client.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing self.mqtt_client.configureDrainingFrequency(2) # Draining: 2 Hz self.mqtt_client.configureConnectDisconnectTimeout(10) # 10 sec self.mqtt_client.configureMQTTOperationTimeout(5) # 5 sec def start(self): self.mqtt_client.connect() self.mqtt_client.subscribe("pl19/notification", 1, self.customCallback) time.sleep(2) while True: time.sleep(5) def replyToPing(self, sequence): pingData = {} pingData['sequence'] = sequence pingData['message'] = "Ping response." message = {} message['device_mac'] = "b8:27:eb:f1:96:c4" message['timestamp'] = str(datetime.datetime.now()) message['event_id'] = 1 message['event'] = pingData messageJson = json.dumps(message) self.mqtt_client.publishAsync("pl19/event", messageJson, 1) print('Published topic %s: %s\n' % (self.topic, messageJson)) # Custom MQTT message callback def customCallback(self, client, userdata, message): print("Received a new message: ") messageContent = json.loads(message.payload.decode('utf-8')) messageData = messageContent['event'] print(messageContent) print(messageData['message']) print("Sequence ", messageData['sequence']) print("from topic: ") print(message.topic) print("--------------\n\n") if messageContent['event_id'] == 0: self.replyToPing(messageData['sequence'])
def main(): parser = argparse.ArgumentParser() AllowedActions = ['both', 'publish', 'subscribe'] parser.add_argument("-l", "--logging", action="store", dest="logging_level", help="Set logging level for MQ", default="info") parser.add_argument( "-b", "--batch_messages", action="store", dest="batch_messages", help= "Set batching of messages instead of sending single lines. Give batch size in bytes", default="0") parser.add_argument("-e", "--endpoint", action="store", required=True, dest="host", help="Your AWS IoT custom endpoint") parser.add_argument("-r", "--rootCA", action="store", required=True, dest="rootCAPath", help="root_ca.pem") parser.add_argument("-c", "--cert", action="store", dest="certificatePath", help="aa6562034b-certificate.pem.crt") parser.add_argument("-k", "--key", action="store", dest="privateKeyPath", help="aa6562034b-private.pem.key") parser.add_argument("-p", "--port", action="store", dest="port", type=int, help="Port number override") parser.add_argument("-id", "--clientId", action="store", dest="clientId", default="serial-data-simulator", help="Targeted client id") parser.add_argument( "-t", "--topic", action="store", dest="topic", default="rules/DataToDynamo/teknoware/telemetry/RaspberryPI3", help="Targeted topic") parser.add_argument("-m", "--mode", action="store", dest="mode", default="both", help="Operation modes: %s" % str(AllowedActions)) args = parser.parse_args() if not args.certificatePath or not args.privateKeyPath: parser.error("Missing credentials for authentication.") exit(2) level = LEVELS.get(args.logging_level, logging.NOTSET) logging.basicConfig(level=level) logging.debug('Using debug logging ...') logging.info('Using info logging ...') AWSIotClient = AWSIoTMQTTClient(args.clientId) AWSIotClient.configureEndpoint(args.host, args.port) AWSIotClient.configureCredentials(args.rootCAPath, args.privateKeyPath, args.certificatePath) AWSIotClient.configureAutoReconnectBackoffTime(1, 32, 20) AWSIotClient.configureOfflinePublishQueueing( 4, 0) # Infinite offline Publish queueing AWSIotClient.configureDrainingFrequency(2) # Draining: 2 Hz AWSIotClient.configureConnectDisconnectTimeout(10) # 10 sec AWSIotClient.configureMQTTOperationTimeout(5) # 5 sec serialData = SerialData() serialDataConsumer = SerialDataConsumer( amqp_url='amqp://*****:*****@localhost:5672/%2F', iot_client=AWSIotClient, target_topic=args.topic, serial_data=serialData, batch_messages=args.batch_messages) try: logging.info('Establishing AWS IoT Connection ...') AWSIotClient.connect() if args.mode == 'both' or args.mode == 'subscribe': AWSIotClient.subscribe( args.topic, 1, serialDataConsumer.on_iot_client_message_received) time.sleep(2) # TODO: ensure the connection by using callbacks serialDataConsumer.run() except KeyboardInterrupt: serialDataConsumer.stop()
def startServer(muteoutput): global tv_listings_dict global tv_channels global tv_dict global mute mute = muteoutput if os.path.isfile('helpers/lineup.json'): with open('helpers/lineup.json') as json_data: tv_json = json.load(json_data) for chan in tv_json: tv_channels.append(chan[0]) tv_channels.append(chan[1]) tv_listings_dict[chan[0]] = chan tv_listings_dict[chan[1]] = chan else: tv_channels = [] tv_listings_dict = {} if 'wpvi' in tv_channels: tv_channels.append('abc') tv_listings_dict['abc'] = tv_listings_dict['wpvi'] if 'wtxf' in tv_channels: tv_channels.append('fox') tv_listings_dict['fox'] = tv_listings_dict['wtxf'] for tv in tvconfig.tvs: tv_dict[tv['tv_mac_address']] = tv clientid = prefHelper.deviceUUID() myMQTTClient = AWSIoTMQTTClient(clientid) myMQTTClient.configureEndpoint("afkx1f9takwol.iot.us-east-1.amazonaws.com", 8883) myMQTTClient.configureCredentials(".auth/root.pem", ".auth/private.pem.key", ".auth/certificate.pem.crt") myMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec print('starting server...') myMQTTClient.connect() myMQTTClient.subscribe("power/" + clientid, 1, power) myMQTTClient.subscribe("channel/" + clientid, 1, channel) myMQTTClient.subscribe("speaker/" + clientid, 1, speaker) myMQTTClient.subscribe("playback/" + clientid, 1, playback) #myMQTTClient.unsubscribe("myTopic") #myMQTTClient.disconnect() print('server running. Pres CTRL + C to stop') counter = 0 while True: time.sleep(1) if counter == 0: payload = {"uuid": prefHelper.deviceUUID()} headers = { 'content-type': 'application/json', 'jwt': prefHelper.deviceToken() } try: response = requests.post('https://alexasmarttv.tk/api/v1/ping', data=json.dumps(payload), headers=headers) except: print('failed to ping') counter += 1 counter = counter % 900
# -*- coding:utf8 -*- from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient import os import time def customCallback(client, userdata, message): print('message: ') print(message.payload) print('topic: ') print(message.topic) print('--------------\n\n') myMQTTClient = AWSIoTMQTTClient('python') myMQTTClient.configureEndpoint(os.environ['AWSIOT_HOST'], 8883) myMQTTClient.configureCredentials('keys/G5.pem', 'keys/private.pem.key', 'keys/certificate.pem.crt') myMQTTClient.configureOfflinePublishQueueing(-1) myMQTTClient.configureDrainingFrequency(2) myMQTTClient.configureConnectDisconnectTimeout(10) myMQTTClient.configureMQTTOperationTimeout(5) myMQTTClient.connect() while True: myMQTTClient.subscribe("test", 1, customCallback) time.sleep(1)
def main(): logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) args = parse_args() if args.region: region_name = args.region else: region_name = get_region() if args.domain: domain_name = args.domain else: domain_name = "prod" if args.cp_endpoint_url: cp_endpoint_url = args.cp_endpoint_url else: cp_endpoint_url = get_cp_endpoint_url(domain=domain_name, region=region_name) session = boto3.session.Session(region_name=region_name) if args.name: client_id = args.name else: client_id = ( get_client_id() ) # This will set the client-id based on the ec2 instance id if not client_id: logging.info("Failed to determine client_id, quitting") exit(1) logging.info( "Running agent with domain: {}, region: {}, clientId: {}, cp_endpoint_url: {}".format( domain_name, region_name, client_id, cp_endpoint_url ) ) ca_cert_file = get_root_ca() if args.mqtt_endpoint: mqtt_endpoint = args.mqtt_endpoint else: logging.info("Attempting to retrieve Mqtt endpoint") mqtt_endpoint = get_mqtt_endpoint(session, cp_endpoint_url) logging.info("Using Mqtt endpoint: {}".format(mqtt_endpoint)) iot_client = AWSIoTMQTTClient(client_id, useWebsocket=True) iot_client.configureEndpoint(mqtt_endpoint, 443, region_name) credentials = session.get_credentials() iot_client.configureCredentials(ca_cert_file.name) iot_client.configureIAMCredentials( credentials.access_key, credentials.secret_key, credentials.token ) # AWSIoTMQTTClient connection configuration iot_client.configureAutoReconnectBackoffTime(1, 32, 20) iot_client.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing iot_client.configureDrainingFrequency(2) # Draining: 2 Hz iot_client.configureConnectDisconnectTimeout(30) iot_client.configureMQTTOperationTimeout(20) # 5 sec # Connect and subscribe to AWS IoT iot_client.connect() sleep(2) topic = "$aws/things/{}/defender/metrics/{}".format(client_id, "json") # Subscribe to the accepted/rejected topics to indicate status of published metrics reports # topic=subscribe_to_topic, callback=callback, QoS=1, iot_client.subscribe( topic="{}/accepted".format(topic), callback=ack_callback, QoS=1 ) iot_client.subscribe( topic="{}/rejected".format(topic), callback=ack_callback, QoS=1 ) start_metrics_collection( region_name=region_name, cp_endpoint_url=cp_endpoint_url, client_id=client_id, iot_client=iot_client, topic=topic, sample_rate=300, ) ca_cert_file.close()
def setupMQTT(): # Usage usageInfo = """Usage: Use certificate based mutual authentication: python basicPubSub.py -e <endpoint> -r <rootCAFilePath> -c <certFilePath> -k <privateKeyFilePath> Use MQTT over WebSocket: python basicPubSub.py -e <endpoint> -r <rootCAFilePath> -w Type "python basicPubSub.py -h" for available options. """ # Help info helpInfo = """-e, --endpoint Your AWS IoT custom endpoint -r, --rootCA Root CA file path -c, --cert Certificate file path -k, --key Private key file path -w, --websocket Use MQTT over WebSocket -h, --help Help information """ # Read in command-line parameters useWebsocket = False host = "a19zzgl8s6zfsq.iot.us-east-1.amazonaws.com" rootCAPath = "rootCA.crt" certificatePath = "88df1a0b0b-certificate.pem.crt" privateKeyPath = "88df1a0b0b-private.pem.key" try: opts, args = getopt.getopt(sys.argv[1:], "hwe:k:c:r:", ["help", "endpoint=", "key=","cert=","rootCA=", "websocket"]) #if len(opts) == 0: #raise getopt.GetoptError("No input parameters!") for opt, arg in opts: if opt in ("-h", "--help"): print(helpInfo) exit(0) if opt in ("-e", "--endpoint"): host = arg if opt in ("-r", "--rootCA"): rootCAPath = arg if opt in ("-c", "--cert"): certificatePath = arg if opt in ("-k", "--key"): privateKeyPath = arg if opt in ("-w", "--websocket"): useWebsocket = True except getopt.GetoptError: print(usageInfo) exit(1) # Missing configuration notification missingConfiguration = False if not host: print("Missing '-e' or '--endpoint'") missingConfiguration = True if not rootCAPath: print("Missing '-r' or '--rootCA'") missingConfiguration = True if not useWebsocket: if not certificatePath: print("Missing '-c' or '--cert'") missingConfiguration = True if not privateKeyPath: print("Missing '-k' or '--key'") missingConfiguration = True if missingConfiguration: exit(2) # Configure logging logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) # Init AWSIoTMQTTClient global myAWSIoTMQTTClient if useWebsocket: myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSub", useWebsocket=True) myAWSIoTMQTTClient.configureEndpoint(host, 443) myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSub") myAWSIoTMQTTClient.configureEndpoint(host, 8883) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect() myAWSIoTMQTTClient.subscribe("sensor_data/temperature/", 1, customCallback) myAWSIoTMQTTClient.subscribe("sensor_data/sonar/", 1, customCallback) myAWSIoTMQTTClient.subscribe("sensor_data/gas/", 1, customCallback) myAWSIoTMQTTClient.subscribe("sensor_data/flame/", 1, customCallback)
print('blinkers') myMQTT.publish('to_robot', send_to_robot('blinkers'), 1) else: pass return '', 204 @app.route('/response', methods=["POST"]) def response(): global response_from_robot if flask.request.form['button'] == 'voltage': print('voltage') myMQTT.publish('to_robot', send_to_robot('voltage'), 1) while response_from_robot == '': pass print('robot responded') response_from_robot = response_from_robot + ' volts' return flask.render_template('index.html', voltage=response_from_robot) response_from_robot = '' myMQTT = AWSIoTMQTTClient('Web') myMQTT.configureEndpoint('a111amujev1y9r.iot.us-west-2.amazonaws.com', 8883) myMQTT.configureCredentials('root-CA.crt', 'Web.private.pem.key', 'Web.certificate.pem.crt') myMQTT.configureOfflinePublishQueueing(-1) myMQTT.configureDrainingFrequency(2) myMQTT.configureConnectDisconnectTimeout(10) myMQTT.connect() myMQTT.subscribe('from_robot', 1, from_robot)
class subscriber_actor: iot_mqtt_client = None QOS_LEVEL = 1 def __init__(self): self.iot_mqtt_client = AWSIoTMQTTClient(pfc_conf.PFC_AWS_IOT_CLIENT_ID) self.iot_mqtt_client.configureEndpoint(pfc_mqtt_topic.AWS_ENDPOINT,8883) self.iot_mqtt_client.configureCredentials(pfc_conf.CA_PATH, pfc_conf.PRIVATE_KEY_PATH, pfc_conf.CERTIFICATE_PATH) self.iot_mqtt_client.configureAutoReconnectBackoffTime(1, 32, 20) self.iot_mqtt_client.configureOfflinePublishQueueing(-1) self.iot_mqtt_client.configureDrainingFrequency(2) self.iot_mqtt_client.configureConnectDisconnectTimeout(10) self.iot_mqtt_client.configureMQTTOperationTimeout(5) def msg_callback(self, client, userdata, message): mes_pld = message.payload mes_tpc = message.topic f = open(pfc_conf.LOG_DIR_PATH + '/aws_subscribe.log','a+') f.write(mes_tpc + ' => ' + mes_pld + str(datetime.now())) f.write('\n') f.close() try : messageJson = json.loads(message.payload) except : print("Throw Message JSON Parse Error.") return False om_type = messageJson['TYPE'] om_target = messageJson['TARGET']if 'TARGET' in messageJson else None om_order = messageJson['ORDER'] if 'ORDER' in messageJson else None self.order_callback(om_type, om_target,om_order) def order_callback(self, om_type, om_target, om_order): global Timer kill_proc = lambda p: p.kill() if om_type == 'SENSOR': if om_target in command_mapper.SENSOR and om_order in command_mapper.SENSOR[om_target]: command_pfc_sensor = command_mapper.SENSOR_DIR_PATH +command_mapper.SENSOR[om_target][om_order] print(command_pfc_sensor) # Execute get sensor data python process through subprocess # It has a timeout setting to prevent permanent blocking sensor_proc = subprocess.Popen(shlex.split("python " + command_pfc_sensor), stdout=subprocess.PIPE, stderr=subprocess.PIPE) timer = Timer(30, kill_proc,[sensor_proc]) try : timer.start() stdout,stderr = sensor_proc.communicate() finally: timer.cancel() # Publish sensor data to AWS IOT DEVICE GATEWAY sensor_data = {"DATA" :stdout , "PFC_SERIAL" :str(pfc_conf.PFC_AWS_IOT_SERIAL), "DEVICE_DT" : str(datetime.now())} pub_proc = subprocess.Popen(shlex.split("python publisher_sensor_data.py -t '" + pfc_mqtt_topic.PUBLISH_SENSOR+ "' -m '" +json.dumps(sensor_data) + "'")) timer = Timer(30,kill_proc, [pub_proc]) try : timer.start() stdout,stderr = pub_proc.communicate() finally : timer.cancel() else : print("'TARGET' or 'ORDER' is not exists on the command_mapper") elif om_type == 'ACTUATOR': if om_target in command_mapper.ACTUATOR and om_order in command_mapper.ACTUATOR[om_target]: command_pfc_actuator = command_mapper.ACTUATOR_DIR_PATH + command_mapper.ACTUATOR[om_target][om_order] print(command_pfc_actuator) # Execute get sensor data python process through subprocess # It has a timeout setting to prevent permanent blocking actuator_proc = subprocess.Popen(shlex.split("python " + command_pfc_actuator), stdout=subprocess.PIPE, stderr=subprocess.PIPE) timer = Timer(30, kill_proc,[actuator_proc]) try : timer.start() stdout, stderr = actuator_proc.communicate() finally : timer.cancel() actuator_data = {'DATA':stdout, 'PFC_SERIAL': str(pfc_conf.PFC_AWS_IOT_SERIAL), 'DEVICE_DT' : str(datetime.now())} pub_proc = subprocess.Popen(shlex.split("python publisher_actuator_data.py -t '" + pfc_mqtt_topic.PUBLISH_ACTUATOR + "' -m '" +json.dumps(actuator_data) + "'")) timer = Timer(30,kill_proc, [pub_proc]) try : timer.start() stdout,stderr = pub_proc.communicate() finally : timer.cancel() else : print("'TARGET' or 'ORDER' is not exists on the command_mapper") elif om_type == 'LOCAL_IP' : pub_proc = subprocess.Popen(shlex.split("python " + command_mapper.LOCAL_IP['LOCAL_IP']['LOCAL_IP'])) timer = Timer(30,kill_proc, [pub_proc]) try : timer.start() stdout,stderr = pub_proc.communicate() finally : timer.cancel() elif om_type == 'HEARTBEAT' : pub_proc = subprocess.Popen(shlex.split("python " + command_mapper.LOCAL_IP['HEARTBEAT']['BEATING'])) timer = Timer(30, kill_proc, [pub_proc]) try : timer.start() stdout, stderr = pub_proc.communicate() finally : timer.cancel() elif om_type == 'DATA_LAKE' : command_pfc_data_lake = command_mapper.AWS_IOT_DIR_PATH +command_mapper.DATA_LAKE['S3_UPLOAD']['UPLOAD'] pub_proc = subprocess.Popen(shlex.split("python " + command_pfc_data_lake)) timer = Timer(600, kill_proc, [pub_proc]) try : timer.start() stdout, stderr = pub_proc.communicate() finally : timer.cancel() datalake_data = {'DATA' : stdout, 'PFC_SERIAL' : str(pfc_conf.PFC_AWS_IOT_SERIAL), 'DEVICE_DT' : str(datetime.now())} pub_proc = subprocess.Popen(shlex.split("python publisher_datalake_data.py -t '" + pfc_mqtt_topic.PUBLISH_DATALAKE + "' -m '" + json.dumps(datalake_data) + "'")) timer = Timer(30, kill_proc, [pub_proc]) try : timer.start() stdout,stderr = pub_proc.communicate() finally : timer.cancel() def subscribe_mqtt_broker(self): self.iot_mqtt_client.connect() self.iot_mqtt_client.subscribe(pfc_mqtt_topic.SUBSCRIBE_DEV,self.QOS_LEVEL,self.msg_callback) print("Subscribing topic : " + str(pfc_mqtt_topic.SUBSCRIBE_DEV)) while True: time.sleep(1) def logging(self): None
class CommunicationHandler(): """ This class handles the communication to AWS. Attributes: -mqtt_client - the client used to connect to AWS -initalized - used for testing """ def __init__(self, ENDPOINT, CA, CERT, PRIVATE_KEY): """ This method initializes the CommunicationHandler class with the MQTT client and handles errors on client creation. Args: -self -ENDPOINT - The endpoint for AWS Connection for IOT -CA - Certification Info for AWS -CERT - Certificate details for AWS -PRIVATE KEY - Private Key for AWS """ try: print("test") self.mqtt_client = AWSIoTMQTTClient("client") self.mqtt_client.configureEndpoint(ENDPOINT, 8883) self.mqtt_client.configureCredentials(CA, PRIVATE_KEY, CERT) self.mqtt_client.configureOfflinePublishQueueing(-1) self.mqtt_client.configureDrainingFrequency(2) self.mqtt_client.configureConnectDisconnectTimeout(10) self.mqtt_client.configureMQTTOperationTimeout(5) self.initilized = True except FailedToCreateMQTTConnection: print("Error: MQTTClient Construction Failed.") self.initilized = False def send_payload(self, data): """ Handles the sending of the data to AWS in a Json format. Args: -self - this object -data - the object that is to be formated into a json (will be gps data) Attributes: -PAYLOAD - the json object that is sent to aws """ if data in("", '', None): print("Error: Message Empty.") return False payload = {"deviceid": getSerial(), "data":data} try: self.mqtt_client.connect() self.mqtt_client.publish("pi", payload, 0) print("Publish Success.") return True except FailedToSendError: print("Publish Failed.") return False ##https://www.raspberrypi-spy.co.uk/2012/09/getting-your-raspberry-pi-serial-number-using-python/ def getSerial(): cpuserial = "0000000000000000" try: f = open('/proc/cpuinfo','r') for line in f: if line[0:6]=='Serial': cpuserial = line[10:26] f.close() except: cpuserial = "ERROR000000000"
root_ca = cert_path + "AmazonRootCA1.pem" certificate = cert_path + "certificate.pem.crt" private_key = cert_path + "private.pem.key" # connect to B-L475E bl475e = HTSensor(bl475e_mac_address) bl475e.connect() # construct the AWS Iot MQTT client #client = None client = AWSIoTMQTTClient(client_id) client.configureEndpoint(host, 8883) client.configureCredentials(root_ca, private_key, certificate) client.configureAutoReconnectBackoffTime(1, 32, 20) client.configureOfflinePublishQueueing(-1) client.configureDrainingFrequency(2) client.configureConnectDisconnectTimeout(10) client.configureMQTTOperationTimeout(5) # connect to AWS Iot Core attempts = 0 connected = 0 while attempts <= 3 and not connected: attempts += 1 try: client.connect() print("Connected to AWS IoT Core.") connected = 1 except connectTimeoutException: if attempts > 3: print("Unable to connect to AWS IoT Core.")
def main(): signal.signal(signal.SIGINT, signal_handler) print(device_id) ######################## ### #AWS IoT MQTT client setup global mqttClient mqttClient = AWSIoTMQTTClient(device_id) #Setup del client mqtt di aws iot mqttClient.disableMetricsCollection() mqttClient.configureEndpoint(endpoint, 8883) mqttClient.configureCredentials( rootCAPath, privateKeyPath, certificatePath, ) # Backoff per riconnessione in caso di mancanza di connessione mqttClient.configureAutoReconnectBackoffTime(1, 32, 20) # Coda dei messaggi in caso di mancanza di connessione # Infinite offline Publish queueing mqttClient.configureOfflinePublishQueueing(-1) mqttClient.configureDrainingFrequency(10) # Draining: 2 Hz mqttClient.configureConnectDisconnectTimeout(10) # 10 sec mqttClient.configureMQTTOperationTimeout(5) # 5 sec #callback in caso di mancanza di connessione mqttClient.onOffline = disconnessoAInternet ############################# #### DEVICE SHADOW setup global shadowClient shadow = AWSIoTMQTTShadowClient(shadow_clientId, awsIoTMQTTClient=mqttClient) shadowClient = shadow.createShadowHandlerWithName(thingName, True) shadowClient.shadowRegisterDeltaCallback(shadowDeltaCallback) ############################# connect() #avvia il tentativo di connessione (ASYNC) #iscrizione al topic di richiesta info mqttClient.subscribe("pcTelemetry/{}/infoRequest".format(device_id), 1, infoRequest) ## Avvia 3 thread: # - uno pubblica una misurazione ogni 10s # - uno pubblica un array di 30 misurazioni. Con una misurazione ogni secondo # - uno pubblica una misurazione ogni 2 min. Misurazioni possibili: batteria, spazio Disco t1 = threading.Thread(target=detailData, args=(parametri, 1)) t2 = threading.Thread(target=liveData, args=(parametri, 10)) t3 = threading.Thread(target=slowUpdateData, args=(parametri, 120)) t1.setDaemon(True) t2.setDaemon(True) t3.setDaemon(True) t1.start() t2.start() t3.start() while True: time.sleep(1)
print("from topic: ") print(message.topic) print("--------------\n\n") host = "a254690l1ektgk-ats.iot.us-east-1.amazonaws.com" rootCAPath = "rootca.pem" certificatePath = "certificate.pem.crt" privateKeyPath = "private.pem.key" my_rpi = AWSIoTMQTTClient("PubSub-p1749126") my_rpi.configureEndpoint(host, 8883) my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath) my_rpi.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing my_rpi.configureDrainingFrequency(2) # Draining: 2 Hz my_rpi.configureConnectDisconnectTimeout(10) # 10 sec my_rpi.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT my_rpi.connect() my_rpi.subscribe("sensors/home", 1, customCallback) sleep(2) # Publish to the same topic in a loop forever loopCount = 0 while True: light = round(1024 - (adc.value * 1024)) humidity, temperature = Adafruit_DHT.read_retry(sensor_name, sensor_pin) payload = '{ "temperature": ' + str(temperature) + ',"humidity": ' + str( humidity) + ',"light": ' + str(light) + ' }'
print(message.topic) print("--------------\n\n") # Init AWSIoTMQTTClient # aws_mqtt_client = None aws_mqtt_client = AWSIoTMQTTClient(client_id) aws_mqtt_client.configureEndpoint(iot_endpoint, port) aws_mqtt_client.configureCredentials( root_ca_path, private_key_path, certificate_path) # AWSIoTMQTTClient connection configuration aws_mqtt_client.configureAutoReconnectBackoffTime(1, 32, 20) # Infinite offline Publish queueing aws_mqtt_client.configureOfflinePublishQueueing(-1) aws_mqtt_client.configureDrainingFrequency(2) # Draining: 2 Hz aws_mqtt_client.configureConnectDisconnectTimeout(10) # 10 sec aws_mqtt_client.configureMQTTOperationTimeout(5) # 5 sec # # Connect and subscribe to AWS IoT aws_mqtt_client.connect() # aws_mqtt_client.subscribe(topic_name, 1, customCallback) # time.sleep(2) def random_measure(max, min, current): var = round(random.uniform(-1, 1), 2) value = round(current + var, 2) if value >= max:
db_obj.create_humidity_tb(cursor) # commit the changes db_obj.commit_db(dbase) widget.show() print("SETUP") # AWS IoT Setup mqttClient.configureEndpoint( "au6bjtfll29y2-ats.iot.us-east-1.amazonaws.com", 8883) mqttClient.configureCredentials( "/home/pi/project_03/Amazon_Root_CA_1.pem", "/home/pi/project_03/d770d71751-private.pem.key", "/home/pi/project_03/d770d71751-certificate.pem.crt") mqttClient.configureOfflinePublishQueueing(-1) mqttClient.configureDrainingFrequency(2) mqttClient.configureConnectDisconnectTimeout(10) mqttClient.configureMQTTOperationTimeout(5) # MQTT Connect and Publish mqttClient.connect() mqttClient.publish("thatpithing/lamda/topic", "Hey there! Connected.", 0) # Testing ''' while 1: payload = "temperature = 34" mqttClient.publish("thatpithing/lamda/topic", json.dumps(payload), 0) print (json.dumps(payload)) sleep(4) '''
def main(): import time import sys import argparse global myAWSIoTMQTTClient global host global tag parser = argparse.ArgumentParser() parser.add_argument('-host', action='store',help='MAC of BT device', default='68:C9:0B:06:44:09') parser.add_argument('-n', action='store', dest='count', default=0, type=int, help="Number of times to loop data") parser.add_argument('-t',action='store',type=float, default=1.0, help='time between polling') parser.add_argument('-T','--temperature', action="store_true",default=False) parser.add_argument('-A','--accelerometer', action='store_true', default=False) parser.add_argument('-H','--humidity', action='store_true', default=False) parser.add_argument('-M','--magnetometer', action='store_true', default=False) parser.add_argument('-B','--barometer', action='store_true', default=False) parser.add_argument('-G','--gyroscope', action='store_true', default=False) parser.add_argument('-K','--keypress', action='store_true', default=False) parser.add_argument('-L','--light', action='store_true', default=False) parser.add_argument('--all', action='store_true', default=True) arg = parser.parse_args(sys.argv[1:]) # Setup AWS IOT connection myAWSIoTMQTTClient = None myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSub") myAWSIoTMQTTClient.configureEndpoint(awsEndPoint, 8883) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect() myAWSIoTMQTTClient.subscribe("SensorTag/data", 1, customCallback) while True: tag = None try: host = arg.host print('Connecting to ' + host) tag = SensorTag(arg.host) print("After sensor tag call") # Enabling selected sensors tag.IRtemperature.enable() tag.humidity.enable() tag.barometer.enable() tag.accelerometer.enable() tag.magnetometer.enable() tag.gyroscope.enable() tag.keypress.enable() tag.setDelegate(KeypressDelegate()) tag.lightmeter.enable() # Some sensors (e.g., temperature, accelerometer) need some time for initialization. # Not waiting here after enabling a sensor, the first read value might be empty or incorrect. time.sleep(2.0) counter=1 while True: print ("Running cycle " + str(counter)) publish_readings() #client.disconnect() if counter >= arg.count and arg.count != 0: myAWSIoTMQTTClient.disconnect() break counter += 1 tag.waitForNotifications(0.5) time.sleep(10.0) except: print "Unexpected error:", sys.exc_info()[0] # if tag is not None: # tag.disconnect() del tag time.sleep(4.0) tag.disconnect() del tag
speech_with_polly(payload["speech_text"]) logger.info("done.") except: logging.exception("Caught Exception in on_alexa_control_message()") if __name__ == '__main__': myMQTTClient = AWSIoTMQTTClient(CLIENT_ID) myMQTTClient.configureEndpoint(AWS_IOT_ENDPOINT, 8883) myMQTTClient.configureCredentials(ROOT_CA_CERT, DEV_CERT_PRIV, DEV_CERT) myMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myMQTTClient.configureOfflinePublishQueueing(-1) myMQTTClient.configureDrainingFrequency(2) myMQTTClient.configureConnectDisconnectTimeout(10) myMQTTClient.configureMQTTOperationTimeout(5) myMQTTClient.onOnline = on_online myMQTTClient.onOffline = on_offline myMQTTClient.connect() time.sleep(2) logger.info("connexted to {} as {}".format(AWS_IOT_ENDPOINT, CLIENT_ID)) myMQTTClient.subscribe(SUBSCRIPTION_TOPIC, 1, on_alexa_control_message) logger.info("subscribed topic: {}".format(SUBSCRIPTION_TOPIC)) while True:
class MQTTClient: myAWSIoTMQTTClient = None def __init__(self, clientId, topic, host, rootCA, crtPath, privateKey, port): self.clientId = clientId self.topic = topic self.host = host self.rootCA = rootCA self.crtPath = crtPath self.privateKey = privateKey self.port = port # Custom MQTT message callback def customCallback(client, userdata, message): print("Received a new message: ") print(message.payload) print("from topic: ") print(message.topic) print("--------------\n\n") def ConfigureLogging(): logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) def InitClient(self): self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.clientId) self.myAWSIoTMQTTClient.configureEndpoint(self.host, self.port) self.myAWSIoTMQTTClient.configureCredentials(self.rootCA, self.privateKey, self.crtPath) # AWSIoTMQTTClient connection configuration self.myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) self.myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing self.myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT self.myAWSIoTMQTTClient.connect() time.sleep(2) def PublishJsonPayload(self, payload): self.myAWSIoTMQTTClient.publish(self.topic, payload, 1) print('Published topic %s: %s\n' % (self.topic, payload)) def StartPublish(self): # Publish to the same topic in a loop forever loopCount = 0 while True: message = {} message['device'] = "window_lars" message['timestamp'] = str(int(round(time.time() * 1000))) message['aq'] = "2" messageJson = json.dumps(message) self.myAWSIoTMQTTClient.publish(self.topic, messageJson, 1) print('Published topic %s: %s\n' % (self.topic, messageJson)) loopCount += 1 time.sleep(1)
class MQTTClient(object): """ classdocs """ __PORT = 8883 __QUEUE_SIZE = -1 # recommended: infinite __QUEUE_DROP_BEHAVIOUR = MQTTLib.DROP_OLDEST # not required for infinite queue __QUEUE_DRAINING_FREQUENCY = 1 # recommended: 2 (Hz) __RECONN_BASE = 1 # recommended: 1 (sec) __RECONN_MAX = 32 # recommended: 32 (sec) __RECONN_STABLE = 20 # recommended: 20 (sec) __DISCONNECT_TIMEOUT = 30 # recommended: 10 (sec) __OPERATION_TIMEOUT = 30 # recommended: 5 (sec) __PUB_QOS = 1 __SUB_QOS = 1 # ---------------------------------------------------------------------------------------------------------------- def __init__(self, *subscribers): """ Constructor """ self.__client = None self.__subscribers = subscribers # ---------------------------------------------------------------------------------------------------------------- def connect(self, auth): # client... self.__client = AWSIoTMQTTClient(auth.client_id) # configuration... self.__client.configureEndpoint(auth.endpoint, self.__PORT) self.__client.configureCredentials(auth.root_ca_file_path, auth.private_key_path, auth.certificate_path) self.__client.configureAutoReconnectBackoffTime(self.__RECONN_BASE, self.__RECONN_MAX, self.__RECONN_STABLE) self.__client.configureOfflinePublishQueueing(self.__QUEUE_SIZE) self.__client.configureDrainingFrequency(self.__QUEUE_DRAINING_FREQUENCY) self.__client.configureConnectDisconnectTimeout(self.__DISCONNECT_TIMEOUT) self.__client.configureMQTTOperationTimeout(self.__OPERATION_TIMEOUT) # subscriptions... for subscriber in self.__subscribers: self.__client.subscribe(subscriber.topic, self.__SUB_QOS, subscriber.handler) # connect... self.__client.connect() def disconnect(self): self.__client.disconnect() # ---------------------------------------------------------------------------------------------------------------- def publish(self, publication): payload = JSONify.dumps(publication.payload) self.__client.publish(publication.topic, payload, self.__PUB_QOS) # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): subscribers = '[' + ', '.join(str(subscriber) for subscriber in self.__subscribers) + ']' return "MQTTClient:{subscribers:%s}" % subscribers
logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) # AWS IoT client initialization ... thing = AWSIoTMQTTClient(config['client_id']) thing.configureEndpoint(config['endpoint'], config['port']) thing.configureCredentials(config['root_ca_path'], config['private_key_path'], config['cert_path']) thing.configureOfflinePublishQueueing(-1) thing.configureDrainingFrequency(2) thing.configureConnectDisconnectTimeout(10) thing.configureMQTTOperationTimeout(5) try: thing.connect() thing.subscribe(config['topic'], 1, doors_callback) while True: """ I'm loop """ except KeyboardInterrupt: print("Cleaning up GPIO") GPIO.cleanup() thing.unsubscribe(config['topic'])
class ElfThread(threading.Thread): """ The abstract thread that sets up interaction with AWS IoT Things """ def __init__(self, thing_name, cli, thing, cfg, args=(), kwargs={}): super(ElfThread, self).__init__( name=thing_name, args=args, kwargs=kwargs ) self.thing_name = thing_name self.thing = thing self.root_cert = cli.root_cert self.topic = '{0}/{1}'.format(cli.topic, self.thing_name) self.region = cli.region self.cfg = cfg self.duration = cli.duration self.aws_iot = _get_iot_session(self.region, cli.profile_name) self.message_qos = cli.qos if policy_name_key not in thing.keys(): policy_name, policy_arn = _create_and_attach_policy( self.region, self.topic, self.thing_name, self.thing['certificateArn'], cli ) self.policy_name = policy_name self.policy_arn = policy_arn log.debug("[elf_thread] attached policy on cert:{0}".format( thing['certificateArn'])) else: log.debug("[elf_thread] policy_name:{0} exists.".format( policy_name_key)) self.policy_name = thing[policy_name_key] self.policy_arn = thing[policy_arn_key] # setup MQTT client elf_id = uuid.UUID(cfg[elf_id_key]) # use ELF ID and a random string since we must use unique Client ID per # client. cid = elf_id.urn.split(":")[2] + "_" + make_string(3) self.mqttc = AWSIoTMQTTClient(clientID=cid) t_name = cfg_dir + thing_name_template.format(0) endpoint = self.aws_iot.describe_endpoint() log.info("ELF connecting asynchronously to IoT endpoint:'{0}'".format( endpoint['endpointAddress'])) self.mqttc.configureEndpoint( hostName=endpoint['endpointAddress'], portNumber=AWS_IOT_MQTT_PORT ) self.mqttc.configureCredentials( CAFilePath=self.root_cert, KeyPath=t_name + ".prv", CertificatePath=t_name + ".pem" ) self.mqttc.configureAutoReconnectBackoffTime(1, 128, 20) self.mqttc.configureOfflinePublishQueueing(90, DROP_OLDEST) self.mqttc.configureDrainingFrequency(3) self.mqttc.configureConnectDisconnectTimeout(20) self.mqttc.configureMQTTOperationTimeout(5) self.mqttc.connect() # keepalive default at 30 seconds
# Init Urbanova Cloud IoT MQTT Client using TLSv1.2 Mutual Authentication ucIoTDeviceClient = None # initialize var ucIoTDeviceClient = AWSIoTMQTTClient( deviceId ) # The client class that connects to and accesses AWS IoT over MQTT v3.1/3.1.1. ucIoTDeviceClient.configureEndpoint( ucIoTCustomEndpoint, 8883) # MQTT Broker host address and default port (TLS) ucIoTDeviceClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # certs and key # Configure Urbanova Cloud IoT Device Client Connection Settings (reference: https://s3.amazonaws.com/aws-iot-device-sdk-python-docs/sphinx/html/index.html) ucIoTDeviceClient.configureAutoReconnectBackoffTime(1, 32, 20) ucIoTDeviceClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing ucIoTDeviceClient.configureDrainingFrequency(2) # Draining: 2 Hz ucIoTDeviceClient.configureConnectDisconnectTimeout(10) # 10 sec ucIoTDeviceClient.configureMQTTOperationTimeout(5) # 5 sec # Connect to Urbanova Cloud IoT ucIoTDeviceClient.connect() time.sleep(2) # Publish `Hello Sensor ${sensorID}`to Urbanova Cloud once per second loopCount = 0 while True: message = {} # init empty message obj message['message'] = 'Hello Sensor ' + deviceId # add `message` element message['sequence'] = loopCount # add `sequence` element messageJson = json.dumps(message) # convert to json ucIoTDeviceClient.publish(deviceId, messageJson,
# Init AWSIoTMQTTClient myAWSIoTMQTTClient = None if useWebsocket: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect() if args.mode == 'both' or args.mode == 'subscribe': myAWSIoTMQTTClient.subscribe(topic, 1, customCallback) time.sleep(2) # Publish to the same topic in a loop forever loopCount = 0 while True: if args.mode == 'both' or args.mode == 'publish': message = {} message['message'] = args.message
class BpiController: def __init__(self): self.__host = 'axt811sti1q4w-ats.iot.us-east-2.amazonaws.com' self.__rootCA = '../certs/root-CA.crt' self.__certPem = '../certs/bpiController.cert.pem' self.__privateKey = '../certs/bpiController.private.key' self.__port = 8883 self.__clientId = 'bpiControllerDevice' self.__thingName = 'bpiController' self.__thingType = 'Gateway' self.mqttClient = None self.basicMqttClient = None self.deviceShadowHandler = None # Configure logging # logger = logging.getLogger('AWSIoTPythonSDK.core') # logger.setLevel(logging.DEBUG) # streamHandler = logging.StreamHandler() # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # streamHandler.setFormatter(formatter) # logger.addHandler(streamHandler) # Init AWSIoTMQTTShadowClient self.mqttClient = AWSIoTMQTTShadowClient(self.__clientId) self.mqttClient.configureEndpoint(self.__host, self.__port) self.mqttClient.configureCredentials(self.__rootCA, self.__privateKey, self.__certPem) # AWSIoTMQTTShadowClient configuration self.mqttClient.configureAutoReconnectBackoffTime(1, 32, 20) self.mqttClient.configureConnectDisconnectTimeout(10) # 10 sec self.mqttClient.configureMQTTOperationTimeout(5) # 5 sec def mqttConnect(self): # Connect to AWS IoT self.mqttClient.connect() # Create a deviceShadow with persistent subscription self.deviceShadowHandler = self.mqttClient.createShadowHandlerWithName(self.__thingName, True) return self.deviceShadowHandler def shadowUpdate(self, json_data): self.deviceShadowHandler.shadowUpdate(json.dumps({ 'state': { 'reported': json_data } }), self.shadowUpdateCallback, 5) def reportHistory(self, json_data): if not isinstance(self.basicMqttClient, AWSIoTMQTTClient): print('Create AWSIoTMQTTClient') self.basicMqttClient = AWSIoTMQTTClient('bpiControllerReporter') self.basicMqttClient.configureEndpoint(self.__host, self.__port) self.basicMqttClient.configureCredentials(self.__rootCA, self.__privateKey, self.__certPem) self.basicMqttClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing self.basicMqttClient.configureDrainingFrequency(2) # Draining: 2 Hz self.basicMqttClient.configureConnectDisconnectTimeout(10) # 10 sec self.basicMqttClient.configureMQTTOperationTimeout(5) # 5 sec self.basicMqttClient.connect() topic = '@sensor.live/thing_types/%s/things/%s/history' % (self.__thingType, self.__thingName) self.basicMqttClient.publish(topic, json.dumps(json_data), 0) # Shadow callback def shadowUpdateCallback(self, payload, responseStatus, token): # payload is a JSON string ready to be parsed using json.loads(...) # in both Py2.x and Py3.x if responseStatus == 'timeout': print('Update request ' + token + ' time out!') if responseStatus == 'accepted': payloadDict = json.loads(payload) print('~~~~~~~~~~~~~~~~~~~~~~~') print('Update request with token: ' + token + ' accepted!') # print('property: ' + str(payloadDict)) print('~~~~~~~~~~~~~~~~~~~~~~~\n\n') if responseStatus == 'rejected': print('Update request ' + token + ' rejected!') # Shadow delete callback def shadowDeleteCallback(self, payload, responseStatus, token): if responseStatus == 'timeout': print('Delete request ' + token + ' time out!') if responseStatus == 'accepted': print('~~~~~~~~~~~~~~~~~~~~~~~') print('Delete request with token: ' + token + ' accepted!') print('~~~~~~~~~~~~~~~~~~~~~~~\n\n') if responseStatus == 'rejected': print('Delete request ' + token + ' rejected!') # Listen on deltas def listenDeltaCallback(self, callback): if self.deviceShadowHandler is not None: self.deviceShadowHandler.shadowRegisterDeltaCallback(callback) else: raise Exception('deviceShadowHandler is None')