def initMQTTClient(host, port, rootCAPath, certificatePath, privateKeyPath, thingName):

    client = AWSIoTMQTTClient(thingName)
    client.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
    client.onMessage = customOnMessage
    client.configureEndpoint(host, port)
    
    return client
예제 #2
0
def send_readings():
    sensor = SHT31(address=TEMPHUM_ADDRESS)
    temp = sensor.read_temperature()
    humidity = sensor.read_humidity()

    payload = {
        'device_id': DEVICE_ID,
        'activity': random.choice([True, False]),
        'humidity': round(humidity, 2),
        'temp': round(temp, 2)
    }

    # Configure aws iot
    # General message notification callback
    def customOnMessage(message):
        print("Received a new message: ")
        print(message.payload)
        print("from topic: ")
        print(message.topic)
        print("--------------\n\n")

    # Suback callback
    def customSubackCallback(mid, data):
        print("Received SUBACK packet id: ")
        print(mid)
        print("Granted QoS: ")
        print(data)
        print("++++++++++++++\n\n")

    logger = logging.getLogger("AWSIoTPythonSDK.core")
    logger.setLevel(logging.WARN)
    streamHandler = logging.StreamHandler()
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    streamHandler.setFormatter(formatter)
    logger.addHandler(streamHandler)

    myAWSIoTMQTTClient = AWSIoTMQTTClient(CLIENT_ID)
    myAWSIoTMQTTClient.configureEndpoint(IOT_HOST, 8883)
    myAWSIoTMQTTClient.configureCredentials(ROOT_CA_PATH, PRIVATE_KEY_PATH,
                                            CERT_PATH)

    # 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
    myAWSIoTMQTTClient.onMessage = customOnMessage

    # Connect and subscribe to AWS IoT
    myAWSIoTMQTTClient.connect()
    myAWSIoTMQTTClient.publishAsync(TOPIC, json.dumps(payload), 1)
    def loopPlatform(self, variable_to_update):
        # General message notification callback
        def customOnMessage(message):
            print('Received message on topic %s: %s\n' % (message.topic, message.payload))
            variable_to_update[0] = message.payload

        myAWSIoTMQTTClient = AWSIoTMQTTClient(self.clientId)
        myAWSIoTMQTTClient.configureEndpoint(self.host, 8883)
        myAWSIoTMQTTClient.configureCredentials(self.rootCAPath, self.privateKeyPath, self.certificatePath)
        myAWSIoTMQTTClient.onMessage = customOnMessage

        # connect and subscribe to topic
        myAWSIoTMQTTClient.connect()
        myAWSIoTMQTTClient.subscribe(self.topic, 1, None)

        while True:
            time.sleep(1)
    def loop(self,variable_to_update):
        
        self.discover_core()
        
        #import random
        #while True:
        #    variable_to_update[0] = random.randint(20,100)
        #    time.sleep(1)

        # General message notification callback
        def customOnMessage(message):
            print('Received message on topic %s: %s\n' % (message.topic, message.payload))
            variable_to_update[0] = message.payload

        # Iterate through all connection options for the core and use the first successful one
        myAWSIoTMQTTClient = AWSIoTMQTTClient(self.clientId)
        myAWSIoTMQTTClient.configureCredentials(self.groupCA, self.privateKeyPath, self.certificatePath)
        myAWSIoTMQTTClient.onMessage = customOnMessage
        
        connected = False
        for connectivityInfo in self.coreInfo.connectivityInfoList:
            currentHost = connectivityInfo.host
            currentPort = connectivityInfo.port
            print("Trying to connect to core at %s:%d" % (currentHost, currentPort))
            myAWSIoTMQTTClient.configureEndpoint(currentHost, currentPort)
            try:
                myAWSIoTMQTTClient.connect()
                connected = True
                break
            except BaseException as e:
                print("Error in connect!")
                print("Type: %s" % str(type(e)))
                print("Error message: %s" % e.message)
        
        if not connected:
            print("Cannot connect to core %s. Exiting..." % self.coreInfo.coreThingArn)
            sys.exit(-2)
        
        # Successfully connected to the core
        myAWSIoTMQTTClient.subscribe(self.topic, 0, None)
        
        while True:
            time.sleep(1)
예제 #5
0
    def setup_client(self):
        if self._mqtt is None:
            accessKey = self._settings.get(["broker", "awsaccesskey"])
            secretAccessKey = self._settings.get([
                "broker", "secretawsaccesskey"
            ])

            if (not accessKey or not secretAccessKey):
                return

            os.environ["AWS_ACCESS_KEY_ID"] = accessKey
            os.environ["AWS_SECRET_ACCESS_KEY"] = secretAccessKey

            clientId = self._settings.get(["publish", "baseTopic"])
            host = self._settings.get(["broker", "url"])
            port = 443
            broker_tls = self._settings.get(["broker", "tls"], asdict=True)
            rootCAPath = broker_tls.get('ca_certs')

            # NOTE it's critical that the AWSIoTMQTTClient is constructed _before_ the socket is monkey patched with the default proxy, otherwise Paho (the MQTT client) just blocks when trying to connect to 127.0.0.1
            myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True)

            myAWSIoTMQTTClient.configureEndpoint(host, port)
            myAWSIoTMQTTClient.configureCredentials(rootCAPath)

            # AWSIoTMQTTClient connection configuration
            myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 3200, 20)
            myAWSIoTMQTTClient.configureOfflinePublishQueueing(
                -1
            )  # Infinite offline Publish queueing
            myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
            myAWSIoTMQTTClient.configureConnectDisconnectTimeout(30)  # 30 seconds
            myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 seconds

            myAWSIoTMQTTClient.onOffline = self._on_mqtt_disconnect
            myAWSIoTMQTTClient.onOnline = self._on_mqtt_connect
            myAWSIoTMQTTClient.onMessage = self._on_mqtt_message

            self._mqtt = myAWSIoTMQTTClient
예제 #6
0
def greengrass_iot_connect(): #連接Greengrass 的 aws iot mqtt
	global GreenGrassAWSIoTMQTTClient
	GreenGrassAWSIoTMQTTClient = AWSIoTMQTTClient(thingName)
	GreenGrassAWSIoTMQTTClient.configureCredentials(groupCA, privateKeyPath, certificatePath)
	GreenGrassAWSIoTMQTTClient.onMessage = customOnMessage
	connected = False
	for connectivityInfo in coreInfo.connectivityInfoList:
		currentHost = connectivityInfo.host
		currentPort = connectivityInfo.port
		print("Trying to connect to core at %s:%d" % (currentHost, currentPort))
		GreenGrassAWSIoTMQTTClient.configureEndpoint(currentHost, currentPort)
		try:
			GreenGrassAWSIoTMQTTClient.connect()
			connected = True
			break
		except BaseException as e:
			print("Error in connect!")
			print("Type: %s" % str(type(e)))
			print("Error message: %s" % e.message)
	if not connected:
		print("Cannot connect to core %s. Exiting..." % coreInfo.coreThingArn)
		subprocess.Popen(['mpg321', 'sound/AWSIOT.mp3'])
		sys.exit(-2)
# Suback callback
def customSubackCallback(mid, data):
    print("Received SUBACK packet id: ")
    print(mid)
    print("Granted QoS: ")
    print(data)
    print("++++++++++++++\n\n")


# AWSIoTMQTTClient connection configuration
myMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
myMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec
myMQTTClient.onMessage = customOnMessage

myMQTTClient.connect()
myMQTTClient.subscribeAsync("test/door", 1, ackCallback=customSubackCallback)


def play_gretting():
    global guest_name
    response = client.synthesize_speech(
        OutputFormat='mp3',
        Text='Welcome ' + guest_name + '. The door is open for you.',
        #Text=  'Welcome. The door is open for you.',
        TextType='text',
        VoiceId='Emma')
    guest_name = None
    #print response
예제 #8
0
    exit(2)

# configuration de la journalisation
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)

# établissement de la connexion MQTT
myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath,
                                        certificatePath)
myAWSIoTMQTTClient.onMessage = printMessage
myAWSIoTMQTTClient.configureEndpoint(host, 8883)
myAWSIoTMQTTClient.connect()
"""
@summary:		 Cette méthode permet de générer des UUID dans un fichier en fonction
                 du nombre de capteur passés en paramètres et de lire le meme fichier
                 afin de retourner les UUID stockés
				 
@param points: 	 sensorNb: nombre de capteur dans la maison 

@returns : 		 uuid    : liste des UUID générés
"""


def generateUUID(sensorNb):
    # nom du fichier dans lequel sera stocké nos différents UUID
예제 #9
0
def awsgreengrass_connect(distance):
    distance = distance

    AllowedActions = ['both', 'publish', 'subscribe']

    # General message notification callback
    def customOnMessage(message):
        print('Received message on topic %s: %s\n' %
              (message.topic, message.payload))

    MAX_DISCOVERY_RETRIES = 10
    GROUP_CA_PATH = "./groupCA/"

    host = "a3drj1nn7u6229.iot.us-east-1.amazonaws.com"
    rootCAPath = "root-ca-cert.pem"
    certificatePath = "62f5a3886d.cert.pem"
    privateKeyPath = "62f5a3886d.private.key"
    clientId = "rpi4"
    thingName = "rpi4"
    topic = "hello/world/send"
    mode = "publish"
    if mode not in AllowedActions:
        parser.error("Unknown --mode option %s. Must be one of %s" %
                     (mode, str(AllowedActions)))
        exit(2)

    if not certificatePath or not privateKeyPath:
        parser.error("Missing credentials for authentication.")
        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)

    # Progressive back off core
    backOffCore = ProgressiveBackOffCore()

    # Discover GGCs
    discoveryInfoProvider = DiscoveryInfoProvider()
    discoveryInfoProvider.configureEndpoint(host)
    discoveryInfoProvider.configureCredentials(rootCAPath, certificatePath,
                                               privateKeyPath)
    discoveryInfoProvider.configureTimeout(10)  # 10 sec

    retryCount = MAX_DISCOVERY_RETRIES
    discovered = False
    groupCA = None
    coreInfo = None
    while retryCount != 0:
        try:
            discoveryInfo = discoveryInfoProvider.discover(thingName)
            caList = discoveryInfo.getAllCas()
            coreList = discoveryInfo.getAllCores()

            # We only pick the first ca and core info
            groupId, ca = caList[0]
            coreInfo = coreList[0]
            print("Discovered GGC: %s from Group: %s" %
                  (coreInfo.coreThingArn, groupId))

            print("Now we persist the connectivity/identity information...")
            groupCA = GROUP_CA_PATH + groupId + "_CA_" + str(
                uuid.uuid4()) + ".crt"
            if not os.path.exists(GROUP_CA_PATH):
                os.makedirs(GROUP_CA_PATH)
            groupCAFile = open(groupCA, "w")
            groupCAFile.write(ca)
            groupCAFile.close()

            discovered = True
            print("Now proceed to the connecting flow...")
            break
        except DiscoveryInvalidRequestException as e:
            print("Invalid discovery request detected!")
            print("Type: %s" % str(type(e)))
            print("Error message: %s" % e.message)
            print("Stopping...")
            break
        except BaseException as e:
            print("Error in discovery!")
            print("Type: %s" % str(type(e)))
            print("Error message: %s" % e.message)
            retryCount -= 1
            print("\n%d/%d retries left\n" %
                  (retryCount, MAX_DISCOVERY_RETRIES))
            print("Backing off...\n")
            backOffCore.backOff()

    if not discovered:
        print("Discovery failed after %d retries. Exiting...\n" %
              (MAX_DISCOVERY_RETRIES))
        sys.exit(-1)

    # Iterate through all connection options for the core and use the first successful one
    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
    myAWSIoTMQTTClient.configureCredentials(groupCA, privateKeyPath,
                                            certificatePath)
    myAWSIoTMQTTClient.onMessage = customOnMessage

    connected = False
    for connectivityInfo in coreInfo.connectivityInfoList:
        currentHost = connectivityInfo.host
        currentPort = connectivityInfo.port
        print("Trying to connect to core at %s:%d" %
              (currentHost, currentPort))
        myAWSIoTMQTTClient.configureEndpoint(currentHost, currentPort)
        try:
            myAWSIoTMQTTClient.connect()
            connected = True
            break
        except BaseException as e:
            print("Error in connect!")
            print("Type: %s" % str(type(e)))
            print("Error message: %s" % e.message)

    if not connected:
        print("Cannot connect to core %s. Exiting..." % coreInfo.coreThingArn)
        sys.exit(-2)

    # Successfully connected to the core
    if mode == 'both' or mode == 'subscribe':
        myAWSIoTMQTTClient.subscribe(topic, 0, None)
    time.sleep(2)
    if mode == 'both' or mode == 'publish':
        # publish distance over greengrass
        message = {}
        message['message'] = "rpi4"
        message['distance4'] = distance
        messageJson = json.dumps(message)
        myAWSIoTMQTTClient.publish(topic, messageJson, 0)
        if mode == 'publish':
            print('Published topic %s: %s\n' % (topic, messageJson))

    time.sleep(2)
예제 #10
0
    img_based64_bytes = base64.urlsafe_b64decode(bytes(data, 'utf-8'))
    f = open('savetest.jpg', 'wb')
    f.write(img_based64_bytes)
    f.close()


MQTTClient = AWSIoTMQTTClient('finger_test')
MQTTClient.configureEndpoint(
    'az6ybpcj57i7z-ats.iot.ap-northeast-2.amazonaws.com', 8883)
MQTTClient.configureCredentials('AmazonRootCA1.pem',
                                'a7fdac8939-private.pem.key',
                                'a7fdac8939-certificate.pem.crt')
MQTTClient.connect()

for i in range(1):
    img_str = get_b64str_from_file('testfinger.jpg')
    print(len(img_str))
    #클라이언트 json 생성후 전송
    jsonobj = json.dumps({"room": "241-3", "hash": img_str})
    try:
        MQTTClient.publish(TOPIC, jsonobj, 1)
        print(MQTTClient.onMessage('stse'))
        MQTTClient.unsubscribe(TOPIC)
    except:
        pass
    #json 받은 상태라고 생각 --서버단
    jsonget = json.loads(jsonobj)
    room = jsonget['room']
    data = jsonget['img']
    get_file_from_b64str(data)
MQTTClient.disconnect()
예제 #11
0
    if not discovered:
        print("Discovery failed after %d retries. Exiting...\n" % (MAX_DISCOVERY_RETRIES))
        sys.exit(-1)

    # Iterate through all connection options for the core and use the first successful one
    myAWSIoTMQTTClient1 = AWSIoTMQTTClient(clientId)
    myAWSIoTMQTTClient2 = AWSIoTMQTTClient(clientId)
    myAWSIoTMQTTClient3 = AWSIoTMQTTClient(clientId)
    myAWSIoTMQTTClient4 = AWSIoTMQTTClient(clientId)

    myAWSIoTMQTTClient1.configureCredentials(groupCA, privateKeyPath, certificatePath)
    myAWSIoTMQTTClient2.configureCredentials(groupCA, privateKeyPath, certificatePath)
    myAWSIoTMQTTClient3.configureCredentials(groupCA, privateKeyPath, certificatePath)
    myAWSIoTMQTTClient4.configureCredentials(groupCA, privateKeyPath, certificatePath)

    myAWSIoTMQTTClient1.onMessage = customOnMessage
    myAWSIoTMQTTClient2.onMessage = customOnMessage
    myAWSIoTMQTTClient3.onMessage = customOnMessage
    myAWSIoTMQTTClient4.onMessage = customOnMessage

    connected = False
    for connectivityInfo in coreInfo.connectivityInfoList:
        currentPort = 8883
        print("Trying to connect to core at %s:%d" % (CLIENT1_HOST, currentPort))
        myAWSIoTMQTTClient1.configureEndpoint(CLIENT1_HOST, currentPort)

        print("Trying to connect to core at %s:%d" % (CLIENT2_HOST, currentPort))
        myAWSIoTMQTTClient2.configureEndpoint(CLIENT2_HOST, currentPort)

        print("Trying to connect to core at %s:%d" % (CLIENT3_HOST, currentPort))
        myAWSIoTMQTTClient3.configureEndpoint(CLIENT3_HOST, currentPort)
예제 #12
0
if useWebsocket:
    client = AWSIoTMQTTClient(clientId, useWebsocket=True)
    client.configureEndpoint(host, 443)
    client.configureCredentials(rootCAPath)
else:
    client = AWSIoTMQTTClient(clientId)
    client.configureEndpoint(host, 8883)
    client.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTClient connection configuration
client.configureAutoReconnectBackoffTime(1, 32, 20)
client.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
client.configureDrainingFrequency(2)  # Draining: 2 Hz
client.configureConnectDisconnectTimeout(10)  # 10 sec
client.configureMQTTOperationTimeout(5)  # 5 sec
client.onMessage = customOnMessage
# Connect and subscribe to AWS IoT
client.connect()
# Note that we are not putting a message callback here. We are using the general message notification callback.
client.subscribeAsync(topic, 1, ackCallback=customSubackCallback)
time.sleep(2)


if __name__ == '__main__':		
	setup()
	while True:
		e1, e2, e3 = on_message()
		print("msg sent: ", e1.data, e2.data, e3.data)
		client.publishAsync(e1.topic, "'timestamp':"+str(round(time.time())) + ", 'data' :'" + e1.data + "'", 1)#, ackCallback=customPubackCallback)
		if e2.data != "spam":
			client.publishAsync(e2.topic, "'timestamp':"+str(round(time.time())) + ", 'data' :'" + e2.data + "'", 1)#, ackCallback=customPubackCallback)
예제 #13
0
# Puback callback
def iotResponse(mid):
    print("Puback")

# Set Up AWS iot
myMQTTClient = AWSIoTMQTTClient(configs['iotDeviceName'])
myMQTTClient.configureEndpoint(configs['iotEndpoint'], configs['iotPort'])
myMQTTClient.configureCredentials(
    configs['iotCACert'], configs['iotPrivCert'], configs['iotCert'])
myMQTTClient.configureAutoReconnectBackoffTime(
    configs['baseReconnectQuietTimeSecond'], configs['maxReconnectQuietTimeSecond'], configs['stableConnectionTimeSecond'])
myMQTTClient.configureOfflinePublishQueueing(-1)
myMQTTClient.configureDrainingFrequency(2)
myMQTTClient.configureConnectDisconnectTimeout(configs['iotTimeout'])
myMQTTClient.configureMQTTOperationTimeout(configs['iotOpTimeout'])
myMQTTClient.onMessage = onMessage

# Now lets do connection
myMQTTClient.connect()

myMQTTClient.subscribeAsync("human/" + configs['iotDeviceName'] + "/getConfig", 0, ackCallback=subackCallback)
time.sleep(2)

# Push the config to AWS IoT so its available online to allow checking of config settings
# IoT Platform can then alert to any changes without the need to use a shadow and can push messages
msg = {}
msg['message'] = "Config"
msg['config'] = configs
jsonMsg = json.dumps(msg)
myMQTTClient.publishAsync(
    "human/" + configs['iotDeviceName'] + "/config", jsonMsg, 0, ackCallback=iotResponse)
        kit.motor1.throttle = 0
        kit.motor2.throttle = 0


# 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:
    time.sleep(0.2)
예제 #15
0
    try:
        print('Received message on topic %s: %s\n' %
              (message.topic, message.payload))
    except Exception as e:
        print(e)


def onOffline():
    global connected
    print('Lost connection.')
    connected = False


# Iterate through all connection options for the core and use the first successful one
myAWSIoTMQTTClient = AWSIoTMQTTClient(CLIENT_ID)
myAWSIoTMQTTClient.onMessage = onMessage
myAWSIoTMQTTClient.onOffline = onOffline

connected = False


def greengrass_run():

    global groupCA
    global connectivityInfoList
    global connected

    #############################################
    ## DISCOVER
    #############################################
    if connected == True:
        print("Error in discovery!")
        print("Type: %s" % str(type(e)))
        print("Error message: %s" % e.message)
        retryCount -= 1
        print("\n%d/%d retries left\n" % (retryCount, MAX_DISCOVERY_RETRIES))
        print("Backing off...\n")
        backOffCore.backOff()

if not discovered:
    print("Discovery failed after %d retries. Exiting...\n" % (MAX_DISCOVERY_RETRIES))
    sys.exit(-1)

# Iterate through all connection options for the core and use the first successful one
myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
myAWSIoTMQTTClient.configureCredentials(groupCA, privateKeyPath, certificatePath)
myAWSIoTMQTTClient.onMessage = customOnMessage

connected = False
for connectivityInfo in coreInfo.connectivityInfoList:
    currentHost = connectivityInfo.host
    currentPort = connectivityInfo.port
    print("Trying to connect to core at %s:%d" % (currentHost, currentPort))
    myAWSIoTMQTTClient.configureEndpoint(currentHost, currentPort)
    try:
        myAWSIoTMQTTClient.connect()
        connected = True
        break
    except BaseException as e:
        print("Error in connect!")
        print("Type: %s" % str(type(e)))
        print("Error message: %s" % e.message)
        print("Error message: %s" % e.message)
        retryCount -= 1
        print("\n%d/%d retries left\n" % (retryCount, MAX_DISCOVERY_RETRIES))
        print("Backing off...\n")
        backOffCore.backOff()

if not discovered:
    print("Discovery failed after %d retries. Exiting...\n" %
          (MAX_DISCOVERY_RETRIES))
    sys.exit(-1)

#After finding greengrass core, time to create MQTT connection with that core.
myAWSIoTMQTTClient = AWSIoTMQTTClient(thingName)
myAWSIoTMQTTClient.configureCredentials(groupCA, privateKeyPath,
                                        certificatePath)
myAWSIoTMQTTClient.onMessage = customOnMessage  #gets called for every received msg

#one core has many ip address configured in aws console. Thats why for loop
# Iterate through all connection options for the core and use the first successful one
connected = False
for connectivityInfo in coreInfo.connectivityInfoList:
    currentHost = connectivityInfo.host
    currentPort = connectivityInfo.port
    print("Trying to connect to core at %s:%d" % (currentHost, currentPort))
    myAWSIoTMQTTClient.configureEndpoint(currentHost, currentPort)
    try:
        myAWSIoTMQTTClient.connect()
        connected = True
        break
    except BaseException as e:
        print("Error in connect!")
        print("Error message: %s" % e.message)
        retryCount -= 1
        print("\n%d/%d retries left\n" % (retryCount, MAX_DISCOVERY_RETRIES))
        print("Backing off...\n")
        backOffCore.backOff()

if not discovered:
    print("Discovery failed after %d retries. Exiting...\n" %
          (MAX_DISCOVERY_RETRIES))
    sys.exit(-1)

# Iterate through all connection options for the core and use the first successful one
myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
myAWSIoTMQTTClient.configureCredentials(groupCA, privateKeyPath,
                                        certificatePath)
myAWSIoTMQTTClient.onMessage = customOnMessage

connected = False
for connectivityInfo in coreInfo.connectivityInfoList:
    currentHost = connectivityInfo.host
    currentPort = connectivityInfo.port
    print("Trying to connect to core at %s:%d" % (currentHost, currentPort))
    myAWSIoTMQTTClient.configureEndpoint(currentHost, currentPort)
    try:
        myAWSIoTMQTTClient.connect()
        connected = True
        break
    except BaseException as e:
        print("Error in connect!")
        print("Type: %s" % str(type(e)))
        print("Error message: %s" % e.message)
예제 #19
0
GPIO.add_event_callback(button_pin, callback=on_push_down)

# Turn off the LED
GPIO.output(led_pin, GPIO.LOW)

# Initialize MQTT
awsIoTClient = AWSIoTMQTTClient(
    "my_raspberry_pi_ID")  #clientId can be anything
awsIoTClient.configureEndpoint(host, port)
awsIoTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTClient connection configuration
awsIoTClient.configureAutoReconnectBackoffTime(1, 32, 20)
awsIoTClient.configureOfflinePublishQueueing(
    -1)  # Infinite offline Publish queueing
awsIoTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
awsIoTClient.configureConnectDisconnectTimeout(10)  # 10 sec
awsIoTClient.configureMQTTOperationTimeout(15)  # 5 sec
awsIoTClient.onMessage = on_message

#Connect and subscribe to AWS IoT
awsIoTClient.connect()
awsIoTClient.subscribeAsync("my_pi/led", 1, ackCallback=on_subscribe)
while True:
    try:
        time.sleep(2)
    except KeyboardInterrupt:
        GPIO.cleanup()
        awsIoTClient.disconnect()
        exit(0)