def discoverBroker(self): if self.hasDiscovered(): return # Discover GGCs discoveryInfoProvider = DiscoveryInfoProvider() discoveryInfoProvider.configureEndpoint(self.host) discoveryInfoProvider.configureCredentials(self.rootCA, self.cert, self.key) discoveryInfoProvider.configureTimeout(10) # 10 sec retryCount = self.MAX_DISCOVERY_RETRIES self.groupCA = None coreInfo = None while retryCount != 0: try: discoveryInfo = discoveryInfoProvider.discover(self.thingName) caList = discoveryInfo.getAllCas() coreList = discoveryInfo.getAllCores() # We only pick the first ca and core info groupId, ca = caList[0] self.coreInfo = coreList[0] self.logger.info("Discovered GGC: %s from Group: %s" % (self.coreInfo.coreThingArn, groupId)) self.groupCA = self.GROUP_CA_PATH + groupId + "_CA_" + str(uuid.uuid4()) + ".crt" if not os.path.exists(self.GROUP_CA_PATH): os.makedirs(self.GROUP_CA_PATH) groupCAFile = open(self.groupCA, "w") groupCAFile.write(ca) groupCAFile.close() self.discovered = True break except DiscoveryFailure as e: # device is not configured for greengrass, revert to IoT Core cl = Obj() cl.host = self.host cl.port = 8883 self.coreInfo = Obj() self.coreInfo.connectivityInfoList = [cl] 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, self.MAX_DISCOVERY_RETRIES)) print("Backing off...\n") self.backOffCore.backOff()
def discover_core(self): # Progressive back off core backOffCore = ProgressiveBackOffCore() # Discover GGCs discoveryInfoProvider = DiscoveryInfoProvider() discoveryInfoProvider.configureEndpoint(self.host) discoveryInfoProvider.configureCredentials(self.rootCAPath, self.certificatePath, self.privateKeyPath) discoveryInfoProvider.configureTimeout(10) # 10 sec retryCount = Visualizador.MAX_DISCOVERY_RETRIES discovered = False self.groupCA = None self.coreInfo = None while retryCount != 0: try: discoveryInfo = discoveryInfoProvider.discover(self.thingName) caList = discoveryInfo.getAllCas() coreList = discoveryInfo.getAllCores() # We only pick the first ca and core info groupId, ca = caList[0] self.coreInfo = coreList[0] print("Discovered GGC: %s from Group: %s" % (self.coreInfo.coreThingArn, groupId)) print("Now we persist the connectivity/identity information...") self.groupCA = Visualizador.GROUP_CA_PATH + groupId + "_CA_" + str(uuid.uuid4()) + ".crt" if not os.path.exists(Visualizador.GROUP_CA_PATH): os.makedirs(Visualizador.GROUP_CA_PATH) groupCAFile = open(self.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, Visualizador.MAX_DISCOVERY_RETRIES)) print("Backing off...\n") backOffCore.backOff() if not discovered: print("Discovery failed after %d retries. Exiting...\n" % (Visualizador.MAX_DISCOVERY_RETRIES)) sys.exit(-1)
class GGDiscovery(): def checkfile(self, f): if not os.path.exists(f): print("{} is not found.".format(f)) def __init__(self, host, rootCAPath, certificatePath, privateKeyPath, thingName, gropCaDeleteOnExit=True): self.checkfile(rootCAPath) self.checkfile(certificatePath) self.checkfile(privateKeyPath) self.discoveryInfoProvider = DiscoveryInfoProvider() self.discoveryInfoProvider.configureEndpoint(host) self.discoveryInfoProvider.configureCredentials( rootCAPath, certificatePath, privateKeyPath) self.discoveryInfoProvider.configureTimeout(10) self.certificatePath = certificatePath self.privateKeyPath = privateKeyPath self.thingName = thingName self.discovered = False self.gropCaDeleteOnExit = gropCaDeleteOnExit def discover(self): try: discoveryInfo = self.discoveryInfoProvider.discover(self.thingName) caList = discoveryInfo.getAllCas() coreList = discoveryInfo.getAllCores() self.groupId, self.ca = caList[0] self.coreInfo = coreList[0] self.groupCA = GROUP_CA_PATH + self.groupId + \ "_CA_" + str(uuid.uuid4()) + ".crt" if not os.path.exists(GROUP_CA_PATH): os.makedirs(GROUP_CA_PATH) groupCAFile = open(self.groupCA, "w") groupCAFile.write(self.ca) groupCAFile.close() self.discovered = True except DiscoveryInvalidRequestException as e: print("Invalid discovery request detected!") print("Type: %s" % str(type(e))) print("Error message: %s" % e.message) raise e except BaseException as e: print("Error in discovery!") print("Type: %s" % str(type(e))) print("Error message: %s" % e.message) def remove_group_ca(self): if self.gropCaDeleteOnExit and self.discovered: os.remove(self.groupCA)
def GreenGrassConnect(): logger.debug("connecting to {}", endpoint) discoveryInfoProvider = DiscoveryInfoProvider() discoveryInfoProvider.configureEndpoint(endpoint) discoveryInfoProvider.configureCredentials(rootCAPath, certificatePath, privateKeyPath) discoveryInfoProvider.configureTimeout(10) # 10 sec 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] logger.debug("Discovered GGC: %s from Group: %s" % (coreInfo.coreThingArn, groupId)) logger.debug("Saving GGC certificate...") groupCA = GROUPCERTFOLDER + groupId + "_CA_" + str( uuid.uuid4()) + ".crt" if not os.path.exists(GROUPCERTFOLDER): os.makedirs(GROUPCERTFOLDER) groupCAFile = open(groupCA, "w") groupCAFile.write(ca) groupCAFile.close() logger.debug("Done saving GGC certificate") for connectivityInfo in coreInfo.connectivityInfoList: currentHost = connectivityInfo.host currentPort = connectivityInfo.port logger.debug("currentHost: %s, currentPort: %s", currentHost, currentPort) try: iotClient = awsIotClientConnect(currentHost, currentPort, groupCA) connected = True logger.info("Connected to host %s:%s", currentHost, currentPort) break except BaseException as e: logger.error("Error connecting to host %s:%s", currentHost, currentPort) logger.error("Error message: %s" % e.message) except DiscoveryInvalidRequestException as e: logger.error("Error GG discovery: %s", e)
def GreenGrassCoreDiscovery(): global retryCount, discovered, groupCA, coreInfo # Progressive back off core backOffCore = ProgressiveBackOffCore() # Discover GGCs discoveryInfoProvider = DiscoveryInfoProvider() discoveryInfoProvider.configureEndpoint(host) discoveryInfoProvider.configureCredentials(rootCAPath, certificatePath, privateKeyPath) discoveryInfoProvider.configureTimeout(10) # 10 sec 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: subprocess.Popen(['mpg321', 'sound/GreenGrass.mp3']).wait() print("Discovery failed after %d retries. Exiting...\n" % (MAX_DISCOVERY_RETRIES)) sys.exit(-1)
def dicovery_greengrass(): ggHostDict = {} discoveryInfoProvider = DiscoveryInfoProvider() discoveryInfoProvider.configureEndpoint(IOT_ENDPOINT) discoveryInfoProvider.configureCredentials(ROOT_CA_FILE, CERT_FILE, PRIVATE_KEY_FILE) discoveryInfoProvider.configureTimeout(10) # 10 sec discoveryInfo = discoveryInfoProvider.discover(THING_NAME) caList = discoveryInfo.getAllCas() coreList = discoveryInfo.getAllCores() groupId, ca = caList[0] coreInfo = coreList[0] with open(GROUP_CA_FILE, "w") as f: f.write(ca) return coreInfo
# 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()
class Switch: ENDPOINT = 'greengrass.iot.ap-northeast-1.amazonaws.com' ROOT_CA_PATH = 'certs/switch/root-ca.pem' CERTIFICATE_PATH = 'certs/switch/a20b621e05-certificate.pem.crt' PRIVATE_KEY_PATH = 'certs/switch/a20b621e05-private.pem.key' THING_NAME = 'Switch_Thing' CLIENT_ID = 'Switch_Thing' TARGET_THING_NAME = 'RobotArm_Thing' GROUP_CA_PATH = './groupCA/' def __init__(self): self.discoveryInfoProvider = DiscoveryInfoProvider() self.discoveryInfoProvider.configureEndpoint(self.ENDPOINT) self.discoveryInfoProvider.configureCredentials(self.ROOT_CA_PATH, self.CERTIFICATE_PATH, self.PRIVATE_KEY_PATH) self.discoveryInfoProvider.configureTimeout(10) logger = logging.getLogger('AWSIoTPythonSDK.core') logger.setLevel(logging.INFO) streamHandler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) def get_ggc_info(self): discoveryInfo = self.discoveryInfoProvider.discover(self.THING_NAME) caList = discoveryInfo.getAllCas() coreList = discoveryInfo.getAllCores() groupId, ca = caList[0] coreInfo = coreList[0] return (groupId, ca, coreInfo) def write_ca_file(self, groupId, ca): groupCAPath = self.GROUP_CA_PATH + groupId + '_CA_' + str(uuid.uuid4()) + '.crt' groupCAFile = open(groupCAPath, 'w') groupCAFile.write(ca) groupCAFile.close() return groupCAPath def connect_to_shadow_service(self, groupCAPath, coreInfo): shadowClient = AWSIoTMQTTShadowClient(self.CLIENT_ID) shadowClient.configureCredentials(groupCAPath, self.PRIVATE_KEY_PATH, self.CERTIFICATE_PATH) connectivityInfo = coreInfo.connectivityInfoList[0] ggcHost = connectivityInfo.host ggcPort = connectivityInfo.port shadowClient.configureEndpoint(ggcHost, ggcPort) shadowClient.connect() return shadowClient def get_mqtt_client(self, shadowClient): return shadowClient.getMQTTConnection() def update_target_device_shadow(self, mqttClient, state): update_topic = '$aws/things/%s/shadow/update' % self.TARGET_THING_NAME desiredState = { 'state': { 'desired': { 'myState': state } } } print('Sending State -------\n%s' % desiredState) mqttClient.publish(update_topic, json.dumps(desiredState), 0) def execute(self): groupId, ca, coreInfo = self.get_ggc_info() groupCAPath = self.write_ca_file(groupId, ca) shadowClient = self.connect_to_shadow_service(groupCAPath, coreInfo) mqttClient = self.get_mqtt_client(shadowClient) while True: sys.stdout.write('Please enter 1 (turn on) or 0 (turn off) to control the robot arm, q to quit: ') user_input = raw_input('') if user_input == 'q': break if user_input == '1': state = 'on' elif user_input == '0': state = 'off' else: print('Invalid input.') continue self.update_target_device_shadow(mqttClient, state)
status = payloadDict["state"]["status"] print(status + " the door") JSONPayload = '{"state":{"reported":{"status":' + '"' + status + '"}}}' print(JSONPayload) deviceShadowHandler.shadowUpdate(JSONPayload, customShadowCallback_Update, 5) if not os.path.isfile(gg_group_ca): discoveryInfoProvider = DiscoveryInfoProvider() discoveryInfoProvider.configureEndpoint(iot_endpoint) discoveryInfoProvider.configureCredentials(root_ca, cert, private_key) discoveryInfoProvider.configureTimeout(10) discoveryInfo = discoveryInfoProvider.discover(client_id) caList = discoveryInfo.getAllCas() coreList = discoveryInfo.getAllCores() ca = caList[0][1] groupCAFile = open(gg_group_ca, "w") groupCAFile.write(ca) groupCAFile.close() print("Successed to discover greengrasss core!") else: print("Greengrass core has already been discovered.") myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(client_id) myAWSIoTMQTTShadowClient.configureEndpoint(gg_core_addr, 8883) myAWSIoTMQTTShadowClient.configureCredentials(gg_group_ca, private_key, cert) myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
def _discover_core(self, client_id, device_certificate_path, device_private_key_path): """Performing the discovery of the core belonging to the same group of the given client identifier. Args: client_id (str): Name of a client, as it is on the cloud, belonging to the same group of the core. device_certificate_path (str): Relative path of a device's certificate stored on the core device, belonging to the same group of the core. device_private_key_path (str): Relative path of a device's private key stored on the core device, belonging to the same group of the core. """ # Progressive back off core backOffCore = ProgressiveBackOffCore() # Discover GGCs discoveryInfoProvider = DiscoveryInfoProvider() discoveryInfoProvider.configureEndpoint(self._endpoint) discoveryInfoProvider.configureCredentials(self._root_ca_path, device_certificate_path, device_private_key_path) discoveryInfoProvider.configureTimeout(10) # 10 sec retryCount = self.MAX_DISCOVERY_ATTEMPTS discovered = False while retryCount != 0: try: discoveryInfo = discoveryInfoProvider.discover(client_id) caList = discoveryInfo.getAllCas() coreList = discoveryInfo.getAllCores() # We only pick the first ca and core info groupId, ca = caList[0] self._core_info = coreList[0] print("Discovered GGC: %s from Group: %s" % (self._core_info.coreThingArn, groupId)) print( "Now we persist the connectivity/identity information...") self._group_ca_path = self._GROUP_CA_PATH + groupId + "_CA_" + str( uuid.uuid4()) + ".crt" if not os.path.exists(self._GROUP_CA_PATH): os.makedirs(self._GROUP_CA_PATH) group_ca_path_file = open(self._group_ca_path, "w") group_ca_path_file.write(ca) group_ca_path_file.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, self.MAX_DISCOVERY_ATTEMPTS)) print("Backing off...\n") backOffCore.backOff() if not discovered: print("Discovery failed after %d retries. Exiting...\n" % (self.MAX_DISCOVERY_ATTEMPTS)) sys.exit(-1) self._configure_logging() AWSGreengrass._discovery_completed = True
discoveryEndpoint = "a100y3wur4j1gq-ats.iot.eu-west-1.amazonaws.com" rootCAPath = "../root-CA.crt" privateKeyPath = "PrivateKey.pem" certificatePath = "certificate.pem.crt" discoveryInfoProvider = DiscoveryInfoProvider() discoveryInfoProvider.configureEndpoint(discoveryEndpoint) discoveryInfoProvider.configureCredentials(rootCAPath, certificatePath, privateKeyPath) groupCA = None coreInfo = None try: discoveryInfo = discoveryInfoProvider.discover(roboName) caList = discoveryInfo.getAllCas() coreList = discoveryInfo.getAllCores() # We only pick the first ca and core info groupId, ca = caList[0] coreInfo = coreList[0] groupCA = GROUP_CA_PATH + groupId + "_CA_" + str(uuid.uuid4()) + ".crt" print("GROUP_CA -->" + groupCA) if not os.path.exists(GROUP_CA_PATH): os.makedirs(GROUP_CA_PATH) groupCAFile = open(groupCA, "w") groupCAFile.write(ca) groupCAFile.close() except DiscoveryInvalidRequestException as e:
def _discover_core(self, client_id, device_certificate_path, device_private_key_path): """Performing the discovery of the core belonging to the same group of the given client name. :param client_id: Name of a client, as it is on the cloud, belonging to the same group of the core. :type client_id: str :param device_certificate_path: Relative path of a device's certificate stored on the core device, belonging to the same group of the core. :type device_certificate_path: str :param device_private_key_path: Relative path of a device's private key stored on the core device, belonging to the same group of the core. :type device_private_key_path: str :returns: The name of the core. :rtype: str :raises EdgeSTInvalidOperationException: is raised if the discovery of the core fails. :raises EdgeSTInvalidDataException: is raised a wrong configuration data is provided. """ # Checking configuration parameters. if not os.access(self._root_ca_path, os.R_OK): msg = '\nRoot Certification Authority certificate path "%s" is not ' \ 'accessible.\r\n' \ 'Please run the application with \"sudo\".' \ % (self._root_ca_path) raise EdgeSTInvalidDataException(msg) if not os.path.exists(device_certificate_path): msg = '\nInvalid device certificate path: "%s"' \ % (device_certificate_path) raise EdgeSTInvalidDataException(msg) if not os.path.exists(device_private_key_path): msg = '\nInvalid device private key path: "%s"' \ % (device_private_key_path) raise EdgeSTInvalidDataException(msg) # Updating service. self._update_status(AWSGreengrassStatus.DISCOVERING_CORE) # Progressive back off core. backOffCore = ProgressiveBackOffCore() # Discover GGCs. discoveryInfoProvider = DiscoveryInfoProvider() discoveryInfoProvider.configureEndpoint(self._endpoint) discoveryInfoProvider.configureCredentials(self._root_ca_path, device_certificate_path, device_private_key_path) discoveryInfoProvider.configureTimeout(self._TIMEOUT_s) attempts = AWSGreengrass.MAX_DISCOVERY_ATTEMPTS while attempts != 0: try: # Discovering information. discoveryInfo = discoveryInfoProvider.discover(client_id) caList = discoveryInfo.getAllCas() coreList = discoveryInfo.getAllCores() # Picking only the first ca and core info. group_id, ca = caList[0] self._core_info = coreList[0] # Persisting connectivity/identity information. self._group_ca_path = self._GROUP_CA_PATH + group_id + \ '_CA_' + str(uuid.uuid4()) + '.crt' if not os.path.exists(self._GROUP_CA_PATH): os.makedirs(self._GROUP_CA_PATH) group_ca_path_file = open(self._group_ca_path, 'w') group_ca_path_file.write(ca) group_ca_path_file.close() break except DiscoveryInvalidRequestException as e: raise EdgeSTInvalidOperationException( 'Invalid discovery request detected: %s' % (e.message)) except BaseException as e: attempts -= 1 backOffCore.backOff() if attempts == 0: raise EdgeSTInvalidOperationException( 'Discovery of the core related to the client "%s", with ' \ 'certificate "%s" and key "%s", failed after %d retries.' % \ (client_id, device_certificate_path, device_private_key_path, AWSGreengrass.MAX_DISCOVERY_ATTEMPTS)) self._configure_logging() AWSGreengrass._discovery_completed = True # Updating service. self._update_status(AWSGreengrassStatus.CORE_DISCOVERED) return self._core_info.coreThingArn
backOffCore = ProgressiveBackOffCore() ### # Discover GGCs ---THIS IS ALLWAYS NEEDED--- discoveryInfoProvider = DiscoveryInfoProvider() discoveryInfoProvider.configureEndpoint(host) discoveryInfoProvider.configureCredentials(rootCAPath, certificatePath, privateKeyPath) discoveryInfoProvider.configureTimeout(10) # 10 sec retryCount = MAX_DISCOVERY_RETRIES #JUST TO TRY CONNECTING A DETERMINED NUMBER OF TIMES discovered = False #INITIAL VALUE OF DISCOVERY groupCA = None #INITIAL VALUE OF THE GROUP coreInfo = None #INITIAL VALUE OF THE CORE while retryCount != 0: try: discoveryInfo = discoveryInfoProvider.discover( thingName) #THE NAME OF THE DEVICE (keep as variable) caList = discoveryInfo.getAllCas() #FIND ALL THE POSSIBLE CAS coreList = discoveryInfo.getAllCores( ) #FIND ALL THE POSSIBLE CORES (just have one core defined) # 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")
def discover_ggc(self): backOffCore = ProgressiveBackOffCore() discoveryInfoProvider = DiscoveryInfoProvider() discoveryInfoProvider.configureEndpoint(self.iot_endpoint) discoveryInfoProvider.configureCredentials(self.iot_ca_path, self.cert_path, self.private_key_path) print('Endpoint: {}'.format(self.iot_endpoint)) print('iot_ca_path: {}'.format(self.iot_ca_path)) print('cert_path: {}'.format(self.cert_path)) print('private_key_path: {}'.format(self.private_key_path)) print('device_name: {}'.format(self.device_name)) discoveryInfoProvider.configureTimeout(10) # 10 sec retryCount = self.max_discovery_retries discovered = False groupCA = None coreInfo = None while retryCount != 0: try: discoveryInfo = discoveryInfoProvider.discover( self.device_name) # noqa: E501 caList = discoveryInfo.getAllCas() coreList = discoveryInfo.getAllCores() groupId, ca = caList[0] coreInfo = coreList[0] print('Discovered GGC: ' + coreInfo.coreThingArn + ' from Group: ' + groupId) host_addr = '' for addr in coreInfo.connectivityInfoList: host_addr = addr.host if self.isIpAddress(host_addr): break print('Discovered GGC Host Address: ' + host_addr) self.ggc_host_addr = host_addr print('Now we persist the connectivity/identity information') groupCA = os.path.join(self.device_path, self.ca_name) ggcHostPath = os.path.join(self.device_path, self.ggc_addr_name) # noqa: E501 groupCAFile = open(groupCA, 'w') groupCAFile.write(ca) groupCAFile.close() groupHostFile = open(ggcHostPath, 'w') groupHostFile.write(host_addr) groupHostFile.close() discovered = True print('Now proceed to the connecting flow...') break except DiscoveryInvalidRequestException as e: print('Invalid discovery request detected!') print('Type: ' + str(type(e))) print('Error message: ' + e.message) print('Stopping...') break except BaseException as e: print('Error in discovery!') print('Type: ' + str(type(e))) print('Error message: ' + e.message) retryCount -= 1 raise print('\n' + str(retryCount) + '/' + str(self.max_discovery_retries) + ' retries left\n') print('Backing off...\n') backOffCore.backOff() if not discovered: print('Discovery failed after ' + str(self.max_discovery_retries) + ' retries. Exiting...\n') sys.exit(-1)
def discoverGGC(host, iotCAPath, certificatePath, privateKeyPath, clientId): # Progressive back off core backOffCore = ProgressiveBackOffCore() # Discover GGCs discoveryInfoProvider = DiscoveryInfoProvider() discoveryInfoProvider.configureEndpoint(host) discoveryInfoProvider.configureCredentials(iotCAPath, certificatePath, privateKeyPath) discoveryInfoProvider.configureTimeout(10) # 10 sec print("Iot end point: " + host) print("Iot CA Path: " + iotCAPath) print("GGAD cert path: " + certificatePath) print("GGAD private key path: " + privateKeyPath) print("GGAD thing name : " + clientId) retryCount = MAX_DISCOVERY_RETRIES discovered = False groupCA = None coreInfo = None while retryCount != 0: try: discoveryInfo = discoveryInfoProvider.discover(clientId) caList = discoveryInfo.getAllCas() coreList = discoveryInfo.getAllCores() # In this example we only have one core # So we pick the first ca and core info groupId, ca = caList[0] coreInfo = coreList[0] print("Discovered GGC: " + coreInfo.coreThingArn + " from Group: " + groupId) hostAddr = "" # In this example Ip detector lambda is turned on which reports # the GGC hostAddr to the CIS (Connectivity Information Service) that stores the # connectivity information for the AWS Greengrass core associated with your group. # This is the information used by discovery and the list of host addresses # could be outdated or wrong and you would normally want to # validate it in a better way. # For simplicity, we will assume the first host address that looks like an ip # is the right one to connect to GGC. # Note: this can also be set manually via the update-connectivity-info CLI for addr in coreInfo.connectivityInfoList: hostAddr = addr.host if isIpAddress(hostAddr): break print("Discovered GGC Host Address: " + hostAddr) print("Now we persist the connectivity/identity information...") groupCA = GROUP_PATH + CA_NAME ggcHostPath = GROUP_PATH + GGC_ADDR_NAME if not os.path.exists(GROUP_PATH): os.makedirs(GROUP_PATH) groupCAFile = open(groupCA, "w") groupCAFile.write(ca) groupCAFile.close() groupHostFile = open(ggcHostPath, "w") groupHostFile.write(hostAddr) groupHostFile.close() discovered = True print("Now proceed to the connecting flow...") break except DiscoveryInvalidRequestException as e: print("Invalid discovery request detected!") print("Type: " + str(type(e))) print("Error message: " + e.message) print("Stopping...") break except BaseException as e: print("Error in discovery!") print("Type: " + str(type(e))) print("Error message: " + e.message) retryCount -= 1 print("\n" + str(retryCount) + "/" + str(MAX_DISCOVERY_RETRIES) + " retries left\n") print("Backing off...\n") backOffCore.backOff() if not discovered: print("Discovery failed after " + str(MAX_DISCOVERY_RETRIES) + " retries. Exiting...\n") sys.exit(-1)
BUTTON = 8 LED = 3 # Initialize the hardware and variables pinMode(LED, "OUTPUT") pinMode(BUTTON, "INPUT") BUTTONSTATE = 0 BUTTONPRESSEDCOUNT = 0 LIGHTSHADOW = 0 # Discover the Core diProvider = DiscoveryInfoProvider() diProvider.configureEndpoint(iot_endpoint) diProvider.configureCredentials(ca, crt, key) diProvider.configureTimeout(10) discoveryInfo = diProvider.discover('Greengrass_Core') infoObj = discoveryInfo.toObjectAtGroupLevel() groupId = list(infoObj.keys())[0] group = infoObj[groupId] core = group.getCoreConnectivityInfo(core_arn) #for addr in core.connectivityInfoList: # print addr.host connectivityInfo = core.connectivityInfoList[0] #Get groupCA caList = discoveryInfo.getAllCas() _, ca_crt = caList[0] group_ca_path = '%s%s_CA_%s.crt' % (HOME_PATH, groupId, str(uuid.uuid4())) with open(group_ca_path, 'w') as group_ca_file: group_ca_file.write(ca_crt)
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)
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)
class RobotArm: ENDPOINT = 'greengrass.iot.ap-northeast-1.amazonaws.com' ROOT_CA_PATH = 'certs/robotArm/root-ca.pem' CERTIFICATE_PATH = 'certs/robotArm/c5e6d39f7b-certificate.pem.crt' PRIVATE_KEY_PATH = 'certs/robotArm/c5e6d39f7b-private.pem.key' THING_NAME = 'RobotArm_Thing' CLIENT_ID = 'RobotArm_Thing' GROUP_CA_PATH = './groupCA/' METERING_TOPIC = '/topic/state' def __init__(self): self.discoveryInfoProvider = DiscoveryInfoProvider() self.discoveryInfoProvider.configureEndpoint(self.ENDPOINT) self.discoveryInfoProvider.configureCredentials( self.ROOT_CA_PATH, self.CERTIFICATE_PATH, self.PRIVATE_KEY_PATH) self.discoveryInfoProvider.configureTimeout(10) 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 get_ggc_info(self): discoveryInfo = self.discoveryInfoProvider.discover(self.THING_NAME) caList = discoveryInfo.getAllCas() coreList = discoveryInfo.getAllCores() groupId, ca = caList[0] coreInfo = coreList[0] return (groupId, ca, coreInfo) def write_ca_file(self, groupId, ca): groupCAPath = self.GROUP_CA_PATH + groupId + '_CA_' + str( uuid.uuid4()) + '.crt' groupCAFile = open(groupCAPath, 'w') groupCAFile.write(ca) groupCAFile.close() return groupCAPath def connect_to_shadow_service(self, groupCAPath, coreInfo): shadowClient = AWSIoTMQTTShadowClient(self.CLIENT_ID) shadowClient.configureCredentials(groupCAPath, self.PRIVATE_KEY_PATH, self.CERTIFICATE_PATH) connectivityInfo = coreInfo.connectivityInfoList[0] ggcHost = connectivityInfo.host ggcPort = connectivityInfo.port shadowClient.configureEndpoint(ggcHost, ggcPort) shadowClient.connect() return shadowClient def get_mqtt_client(self, shadowClient): return shadowClient.getMQTTConnection() def get_device_shadow(self, shadowClient): return shadowClient.createShadowHandlerWithName(self.CLIENT_ID, True) def shadow_update_callback(self, payload, responseStatus, token): reportedState = json.loads(payload)['state']['reported']['myState'] self.publish_mqtt_async(self.mqttClient, reportedState) def shadow_delta_callback(self, payload, responseStatus, token): desiredState = json.loads(payload)['state']['myState'] self.publish_shadow_state(self.deviceShadow, desiredState) def publish_shadow_state(self, deviceShadow, state): reportedState = {'state': {'reported': {'myState': state}}} print('Sending State -------\n%s' % reportedState) deviceShadow.shadowUpdate(json.dumps(reportedState), self.shadow_update_callback, 5) def publish_mqtt_async(self, mqttClient, state): payload = {'state': state} mqttClient.publish(self.METERING_TOPIC, json.dumps(payload), 0) def wait_for_update_shadow(self, deviceShadow): deviceShadow.shadowRegisterDeltaCallback(self.shadow_delta_callback) def execute(self): groupId, ca, coreInfo = self.get_ggc_info() groupCAPath = self.write_ca_file(groupId, ca) shadowClient = self.connect_to_shadow_service(groupCAPath, coreInfo) self.deviceShadow = self.get_device_shadow(shadowClient) self.mqttClient = self.get_mqtt_client(shadowClient) self.publish_shadow_state(self.deviceShadow, 'off') self.wait_for_update_shadow(self.deviceShadow) print('Waiting for an update!') while True: time.sleep(1)