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)
Beispiel #2
0
    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)
def core_connect(device_name, config_file, root_ca, certificate, private_key,
                 group_ca_path):
    # read the config file
    cfg = GroupConfigFile(config_file)

    # determine heartbeat device's thing name and orient MQTT client to GG Core
    heartbeat_name = cfg['devices'][device_name]['thing_name']
    iot_endpoint = cfg['misc']['iot_endpoint']
    local_core = None

    # Discover Greengrass Core
    dip = DiscoveryInfoProvider()
    dip.configureEndpoint(iot_endpoint)
    dip.configureCredentials(caPath=root_ca,
                             certPath=certificate,
                             keyPath=private_key)
    dip.configureTimeout(10)  # 10 sec
    log.info("[hb] Discovery using CA: {0} cert: {1} prv_key: {2}".format(
        root_ca, certificate, private_key))
    # Now discover the groups in which this device is a member.
    # The heartbeat should only be in one group
    discovered, discovery_info = utils.ggc_discovery(heartbeat_name,
                                                     dip,
                                                     retry_count=10,
                                                     max_groups=1)

    ca_list = discovery_info.getAllCas()
    group_id, ca = ca_list[0]
    group_ca_file = utils.save_group_ca(ca, group_ca_path, group_id)

    if discovered is False:
        log.error("[hb] Discovery failed for: {0} when connecting to "
                  "service endpoint: {1}".format(heartbeat_name, iot_endpoint))
        return
    log.info("[hb] Discovery success")

    mqttc = AWSIoTMQTTClient(heartbeat_name)

    # find this device Group's core
    for group in discovery_info.getAllGroups():
        utils.dump_core_info_list(group.coreConnectivityInfoList)
        local_core = group.getCoreConnectivityInfo(cfg['core']['thing_arn'])
        if local_core:
            log.info('[hb] Found the local core and Group CA.')
            break

    if not local_core:
        raise EnvironmentError("[hb] Couldn't find the local Core")

    # local Greengrass Core discovered, now connect to Core from this Device
    log.info("[hb] gca_file:{0} cert:{1}".format(group_ca_file, certificate))
    mqttc.configureCredentials(group_ca_file, private_key, certificate)
    mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)

    if not utils.mqtt_connect(mqtt_client=mqttc, core_info=local_core):
        raise EnvironmentError("[hb] Connection to GG Core MQTT failed.")

    return mqttc, heartbeat_name
Beispiel #5
0
    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
Beispiel #6
0
def initGGDiscoveryProvider(host, rootCAPath, certificatePath, privateKeyPath,
                            timeout):

    discoveryInfoProvider = DiscoveryInfoProvider()
    discoveryInfoProvider.configureEndpoint(host)
    discoveryInfoProvider.configureCredentials(rootCAPath, certificatePath,
                                               privateKeyPath)
    discoveryInfoProvider.configureTimeout(timeout)

    return discoveryInfoProvider
def core_connect(device_name, config_file, root_ca, certificate, private_key,
                 group_ca_path):
    global ggd_name, mqttc
    cfg = GroupConfigFile(config_file)
    ggd_name = cfg['devices'][device_name]['thing_name']
    iot_endpoint = cfg['misc']['iot_endpoint']

    dip = DiscoveryInfoProvider()
    dip.configureEndpoint(iot_endpoint)
    dip.configureCredentials(
        caPath=root_ca, certPath=certificate, keyPath=private_key
    )
    dip.configureTimeout(10)  # 10 sec
    logging.info("[button] Discovery using CA:{0} cert:{1} prv_key:{2}".format(
        root_ca, certificate, private_key
    ))

    gg_core, discovery_info = utils.discover_configured_core(
        device_name=device_name, dip=dip, config_file=config_file,
    )
    if not gg_core:
        raise EnvironmentError("[button] Couldn't find the Core")

    ca_list = discovery_info.getAllCas()
    group_id, ca = ca_list[0]
    group_ca_file = utils.save_group_ca(ca, group_ca_path, group_id)

    mqttc = AWSIoTMQTTClient(ggd_name)
    # local Greengrass Core discovered, now connect to Core from this Device
    log.info("[button] gca_file:{0} cert:{1}".format(
        group_ca_file, certificate))
    mqttc.configureCredentials(group_ca_file, private_key, certificate)
    mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)

    return mqttc, gg_core
    def __init__(self, endpoint, root_ca_path, certificate_path, private_key_path, thing_name):
        self.__certificate_path = certificate_path
        self.__private_key_path = private_key_path
        self.__thing_name = thing_name

        # Discover GGCs
        discoveryInfoProvider = DiscoveryInfoProvider()
        discoveryInfoProvider.configureEndpoint(endpoint)
        discoveryInfoProvider.configureCredentials(
            root_ca_path, certificate_path, private_key_path)
        discoveryInfoProvider.configureTimeout(10)  # 10 sec
        self.__discoveryInfoProvider = discoveryInfoProvider
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)
Beispiel #10
0
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 local_shadow_connect(device_name, config_file, root_ca, certificate,
                         private_key, group_ca_dir):
    cfg = GroupConfigFile(config_file)
    ggd_name = cfg['devices'][device_name]['thing_name']
    iot_endpoint = cfg['misc']['iot_endpoint']

    dip = DiscoveryInfoProvider()
    dip.configureEndpoint(iot_endpoint)
    dip.configureCredentials(caPath=root_ca,
                             certPath=certificate,
                             keyPath=private_key)
    dip.configureTimeout(10)  # 10 sec
    logging.info(
        "[shadow_connect] Discovery using CA:{0} cert:{1} prv_key:{2}".format(
            root_ca, certificate, private_key))
    gg_core, discovery_info = discover_configured_core(
        config_file=config_file,
        dip=dip,
        device_name=ggd_name,
    )
    if not gg_core:
        raise EnvironmentError("[core_connect] Couldn't find the Core")

    ca_list = discovery_info.getAllCas()
    core_list = discovery_info.getAllCores()
    group_id, ca = ca_list[0]
    core_info = core_list[0]
    logging.info("Discovered Greengrass Core:{0} from Group:{1}".format(
        core_info.coreThingArn, group_id))
    group_ca_file = save_group_ca(ca, group_ca_dir, group_id)

    # local Greengrass Core discovered
    # get a shadow client to receive commands
    mqttsc = AWSIoTMQTTShadowClient(ggd_name)

    # now connect to Core from this Device
    logging.info("[core_connect] gca_file:{0} cert:{1}".format(
        group_ca_file, certificate))
    mqttsc.configureCredentials(group_ca_file, private_key, certificate)

    mqttc = mqttsc.getMQTTConnection()
    mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)
    if not mqtt_connect(mqttsc, gg_core):
        raise EnvironmentError("connection to Master Shadow failed.")

    # create and register the shadow handler on delta topics for commands
    # with a persistent connection to the Master shadow
    master_shadow = mqttsc.createShadowHandlerWithName(
        cfg['misc']['master_shadow_name'], True)

    return mqttc, mqttsc, master_shadow, ggd_name
Beispiel #12
0
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
def local_shadow_connect(device_name, config_file, root_ca, certificate,
                         private_key, group_ca_dir):
    cfg = GroupConfigFile(config_file)
    ggd_name = cfg['devices'][device_name]['thing_name']
    iot_endpoint = cfg['misc']['iot_endpoint']

    dip = DiscoveryInfoProvider()
    dip.configureEndpoint(iot_endpoint)
    dip.configureCredentials(
        caPath=root_ca, certPath=certificate, keyPath=private_key
    )
    dip.configureTimeout(10)  # 10 sec
    logging.info(
        "[shadow_connect] Discovery using CA:{0} cert:{1} prv_key:{2}".format(
            root_ca, certificate, private_key
    ))
    gg_core, discovery_info = discover_configured_core(
        config_file=config_file, dip=dip, device_name=ggd_name,
    )
    if not gg_core:
        raise EnvironmentError("[core_connect] Couldn't find the Core")

    ca_list = discovery_info.getAllCas()
    core_list = discovery_info.getAllCores()
    group_id, ca = ca_list[0]
    core_info = core_list[0]
    logging.info("Discovered Greengrass Core:{0} from Group:{1}".format(
        core_info.coreThingArn, group_id)
    )
    group_ca_file = save_group_ca(ca, group_ca_dir, group_id)

    # local Greengrass Core discovered
    # get a shadow client to receive commands
    mqttsc = AWSIoTMQTTShadowClient(ggd_name)

    # now connect to Core from this Device
    logging.info("[core_connect] gca_file:{0} cert:{1}".format(
        group_ca_file, certificate))
    mqttsc.configureCredentials(group_ca_file, private_key, certificate)

    mqttc = mqttsc.getMQTTConnection()
    mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)
    if not mqtt_connect(mqttsc, gg_core):
        raise EnvironmentError("connection to Master Shadow failed.")

    # create and register the shadow handler on delta topics for commands
    # with a persistent connection to the Master shadow
    master_shadow = mqttsc.createShadowHandlerWithName(
        cfg['misc']['master_shadow_name'], True)

    return mqttc, mqttsc, master_shadow, ggd_name
Beispiel #14
0
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)
Beispiel #15
0
def core_connect(device_name, config_file, root_ca, certificate, private_key,
                 group_ca_path):
    global ggd_name, mqttc
    cfg = GroupConfigFile(config_file)
    ggd_name = cfg['devices'][device_name]['thing_name']
    iot_endpoint = cfg['misc']['iot_endpoint']

    dip = DiscoveryInfoProvider()
    dip.configureEndpoint(iot_endpoint)
    dip.configureCredentials(caPath=root_ca,
                             certPath=certificate,
                             keyPath=private_key)
    dip.configureTimeout(10)  # 10 sec
    logging.info(
        "[heartrate] Discovery using CA:{0} cert:{1} prv_key:{2}".format(
            root_ca, certificate, private_key))

    gg_core, discovery_info = utils.discover_configured_core(
        device_name=device_name,
        dip=dip,
        config_file=config_file,
    )
    if not gg_core:
        raise EnvironmentError("[heartrate] Couldn't find the Core")

    ca_list = discovery_info.getAllCas()
    group_id, ca = ca_list[0]
    group_ca_file = utils.save_group_ca(ca, group_ca_path, group_id)

    mqttc = AWSIoTMQTTClient(ggd_name)
    # local Greengrass Core discovered, now connect to Core from this Device
    log.info("[heartrate] gca_file:{0} cert:{1}".format(
        group_ca_file, certificate))
    mqttc.configureCredentials(group_ca_file, private_key, certificate)
    mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)

    return mqttc, gg_core
Beispiel #16
0
def initialize(device_name, config_file, root_ca, certificate, private_key,
               group_ca_path):
    global ggd_name

    cfg = GroupConfigFile(config_file)
    local = dict()
    remote = dict()

    # determine heartbeat device's thing name and endpoint for MQTT clients
    ggd_name = cfg['devices'][device_name]['thing_name']
    iot_endpoint = cfg['misc']['iot_endpoint']

    # Discover Greengrass Core
    dip = DiscoveryInfoProvider()
    dip.configureEndpoint(iot_endpoint)
    dip.configureCredentials(
        caPath=root_ca, certPath=certificate, keyPath=private_key
    )
    dip.configureTimeout(10)  # 10 sec
    log.info("Discovery using CA: {0} certificate: {1} prv_key: {2}".format(
        root_ca, certificate, private_key
    ))
    # Now discover the groups in which this device is a member.
    # The arm should only be in two groups. The local and master groups.
    discovered, discovery_info = utils.ggc_discovery(
        ggd_name, dip, retry_count=10, max_groups=2
    )

    # Each group returned has a groupId which can compare to the configured
    # groupId in the config file. If the IDs match, the 'local' Group has been
    # found and therefore local core.
    # If the groupId's do not match, the 'remote' or 'master' group has been
    # found.
    group_list = discovery_info.getAllGroups()
    for g in group_list:
        logging.info("[initialize] group_id:{0}".format(g.groupId))
        if g.groupId == cfg['group']['id']:
            local_cores = g.coreConnectivityInfoList
            local['core'] = local_cores[0]  # just grab first core as local
            local['ca'] = g.caList
        else:
            remote_cores = g.coreConnectivityInfoList
            remote['core'] = remote_cores[0]  # just grab first core as remote
            remote['ca'] = g.caList

    if len(local) > 1 and len(remote) > 1:
        logging.info("[initialize] local_core:{0} remote_core:{1}".format(
            local, remote
        ))
    else:
        raise EnvironmentError("Couldn't find the arm's Cores.")

    # just save one of the group's CAs to use as a CA file later
    local_core_ca_file = utils.save_group_ca(
        local['ca'][0], group_ca_path, local['core'].groupId
    )
    remote_core_ca_file = utils.save_group_ca(
        remote['ca'][0], group_ca_path, remote['core'].groupId
    )

    # Greengrass Cores discovered, now connect to Cores from this Device
    # get a client to send telemetry
    local_mqttc = AWSIoTMQTTClient(ggd_name)
    log.info("[initialize] local gca_file:{0} cert:{1}".format(
        local_core_ca_file, certificate))
    local_mqttc.configureCredentials(
        local_core_ca_file, private_key, certificate
    )
    local_mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)

    if not utils.mqtt_connect(mqtt_client=local_mqttc, core_info=local['core']):
        raise EnvironmentError("Connection to GG Core MQTT failed.")

    # get a shadow client to receive commands
    master_shadow_client = AWSIoTMQTTShadowClient(ggd_name)
    log.info("[initialize] remote ca_file:{0} cert:{1}".format(
        local_core_ca_file, certificate))
    remote_mqttc = master_shadow_client.getMQTTConnection()
    remote_mqttc.configureCredentials(
        remote_core_ca_file, private_key, certificate
    )

    if not utils.mqtt_connect(mqtt_client=master_shadow_client,
                              core_info=remote['core']):
        raise EnvironmentError("Connection to Master Shadow failed.")

    # create and register the shadow handler on delta topics for commands
    # with a persistent connection to the Master shadow
    master_shadow = master_shadow_client.createShadowHandlerWithName(
        cfg['misc']['master_shadow_name'], True)
    log.info("[initialize] created handler for shadow name: {0}".format(
        cfg['misc']['master_shadow_name']
    ))
    token = master_shadow.shadowGet(shadow_mgr, 5)
    log.info("[initialize] shadowGet() tk:{0}".format(token))

    return local_mqttc, remote_mqttc, master_shadow
    parser.error("No private key found at {}".format(privateKeyPath))
    exit(3)

# 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
def initialize(device_name, config_file, root_ca, certificate, private_key,
               group_ca_path):
    # read the config file
    cfg = GroupConfigFile(config_file)

    ggd_name = cfg['devices'][device_name]['thing_name']
    iot_endpoint = cfg['misc']['iot_endpoint']
    # prep for discovery
    dip = DiscoveryInfoProvider()
    dip.configureEndpoint(iot_endpoint)
    dip.configureCredentials(caPath=pa.root_ca,
                             certPath=pa.certificate,
                             keyPath=pa.private_key)
    dip.configureTimeout(10)  # 10 sec
    logging.info("Discovery using CA:{0} cert:{1} prv_key:{2}".format(
        pa.root_ca, pa.certificate, pa.private_key))
    discovered, discovery_info = utils.ggc_discovery(
        thing_name=ggd_name, discovery_info_provider=dip, max_groups=3)

    local, remote = _find_cores(cfg, discovery_info, iot_endpoint)
    # Save each group's CAs to use as a CA file later
    local_core_ca_file = utils.save_group_ca(local['ca'][0], group_ca_path,
                                             local['core'].groupId)
    for r in remote:
        remote[r]['ca_file'] = utils.save_group_ca(remote[r]['ca'][0],
                                                   group_ca_path,
                                                   remote[r]['core'].groupId)

    # create and connect MQTT client pointed toward the Master Greengrass Core
    mqttc_m = AWSIoTMQTTClient(ggd_name)
    log.info("[initialize] local gca_file:{0} cert:{1}".format(
        local_core_ca_file, certificate))
    mqttc_m.configureCredentials(local_core_ca_file, private_key, certificate)
    mqttc_m.configureOfflinePublishQueueing(10, DROP_OLDEST)

    log.info("[initialize] Starting connection to Master Core")
    if utils.mqtt_connect(mqtt_client=mqttc_m, core_info=local['core']):
        log.info("[initialize] Connected to Master Core")
    else:
        log.error("[initialize] could not connect to Master Core")

    # create and connect MQTT clients pointed toward the remote Greengrass Cores
    mqttc_list = list()
    for r in remote:
        remote_mqttc = AWSIoTMQTTClient(ggd_name)
        log.info("[initialize] local gca_file:{0} cert:{1}".format(
            r, certificate))
        remote_mqttc.configureCredentials(remote[r]['ca_file'], private_key,
                                          certificate)
        remote_mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)
        log.info("[initialize] Starting connection to Remote Core")
        if utils.mqtt_connect(mqtt_client=remote_mqttc,
                              core_info=remote[r]['core']):
            log.info("[initialize] Connected to Remote Core:{0}".format(
                remote[r]['core'].coreThingArn))
            mqttc_list.append(remote_mqttc)
        else:
            log.error(
                "[initialize] could not connect to Remote Core:{0}".format(
                    remote[r]['core'].coreThingArn))

    return mqttc_m, mqttc_list
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)
Beispiel #20
0
    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)
GROUP_CA_PATH = "./groupCA/"

# 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()

# Start Discovering GGCs
discoveryInfoProvider = DiscoveryInfoProvider()
discoveryInfoProvider.configureEndpoint(awsiotEndpoint)
discoveryInfoProvider.configureCredentials(rootCAPath, certificatePath,
                                           privateKeyPath)
discoveryInfoProvider.configureTimeout(
    10)  # time out in seconds for discovery request sending/response waiting
retryCount = MAX_DISCOVERY_RETRIES
discovered = False
groupCA = None
coreInfo = None
while retryCount != 0:
    try:
        discoveryInfo = discoveryInfoProvider.discover(thingName=thingName)
        caList = discoveryInfo.getAllCas(
        )  #returns GGCore group id and its Root CA cert
        coreList = discoveryInfo.getAllCores(
    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
#--------------------------------------------------------------------------------------------------

# Configure logging   ---THIS IS ALLWAYS NEEDED---
logger = logging.getLogger("AWSIoTPythonSDK.core")  #always this text
logger.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler()
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')  #always this text
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)

# Progressive back off core
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(
Beispiel #24
0
    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
Beispiel #25
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)
        LIGHTSHADOW) + " to resolve the delta"


# Connect the Grove LED to digital port D3
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]
Beispiel #27
0
isBusy = 'false'
ID = 10000
headLight = "Off"
print("RoboName--> " + roboName)

GROUP_CA_PATH = "./groupCA/"

#discoveryEndpoint ="https://greengrass-ats.iot.eu-west-1.amazonaws.com:8443/greengrass/discover/thing/"+roboName

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]
Beispiel #28
0
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)
Beispiel #29
0
    print(payloadDict)
    print("status: " + str(payloadDict["state"]["status"]))
    print("version: " + str(payloadDict["version"]))
    print("+++++++++++++++++++++++\n\n")

    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)
def core_connect(device_name, config_file, root_ca, certificate, private_key,
                 group_ca_path):
    # read the config file
    cfg = GroupConfigFile(config_file)

    # determine heartbeat device's thing name and orient MQTT client to GG Core
    heartbeat_name = cfg['devices'][device_name]['thing_name']
    iot_endpoint = cfg['misc']['iot_endpoint']
    local_core = None

    # Discover Greengrass Core
    dip = DiscoveryInfoProvider()
    dip.configureEndpoint(iot_endpoint)
    dip.configureCredentials(
        caPath=root_ca, certPath=certificate, keyPath=private_key
    )
    dip.configureTimeout(10)  # 10 sec
    log.info("[hb] Discovery using CA: {0} cert: {1} prv_key: {2}".format(
        root_ca, certificate, private_key
    ))
    # Now discover the groups in which this device is a member.
    # The heartbeat should only be in one group
    discovered, discovery_info = utils.ggc_discovery(
        heartbeat_name, dip, retry_count=10, max_groups=1
    )

    ca_list = discovery_info.getAllCas()
    group_id, ca = ca_list[0]
    group_ca_file = utils.save_group_ca(ca, group_ca_path, group_id)

    if discovered is False:
        log.error(
            "[hb] Discovery failed for: {0} when connecting to "
            "service endpoint: {1}".format(
                heartbeat_name, iot_endpoint
            ))
        return
    log.info("[hb] Discovery success")

    mqttc = AWSIoTMQTTClient(heartbeat_name)

    # find this device Group's core
    for group in discovery_info.getAllGroups():
        utils.dump_core_info_list(group.coreConnectivityInfoList)
        local_core = group.getCoreConnectivityInfo(cfg['core']['thing_arn'])
        if local_core:
            log.info('[hb] Found the local core and Group CA.')
            break

    if not local_core:
        raise EnvironmentError("[hb] Couldn't find the local Core")

    # local Greengrass Core discovered, now connect to Core from this Device
    log.info("[hb] gca_file:{0} cert:{1}".format(group_ca_file, certificate))
    mqttc.configureCredentials(group_ca_file, private_key, certificate)
    mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)

    if not utils.mqtt_connect(mqtt_client=mqttc, core_info=local_core):
        raise EnvironmentError("[hb] Connection to GG Core MQTT failed.")

    return mqttc, heartbeat_name
def initialize(device_name, config_file, root_ca, certificate, private_key,
               group_ca_path):
    # read the config file
    cfg = GroupConfigFile(config_file)

    ggd_name = cfg['devices'][device_name]['thing_name']
    iot_endpoint = cfg['misc']['iot_endpoint']
    # prep for discovery
    dip = DiscoveryInfoProvider()
    dip.configureEndpoint(iot_endpoint)
    dip.configureCredentials(
        caPath=pa.root_ca, certPath=pa.certificate, keyPath=pa.private_key
    )
    dip.configureTimeout(10)  # 10 sec
    logging.info("Discovery using CA:{0} cert:{1} prv_key:{2}".format(
        pa.root_ca, pa.certificate, pa.private_key
    ))
    discovered, discovery_info = utils.ggc_discovery(
        thing_name=ggd_name, discovery_info_provider=dip, max_groups=3
    )

    local, remote = _find_cores(cfg, discovery_info, iot_endpoint)
    # Save each group's CAs to use as a CA file later
    local_core_ca_file = utils.save_group_ca(
        local['ca'][0], group_ca_path, local['core'].groupId
    )
    for r in remote:
        remote[r]['ca_file'] = utils.save_group_ca(
            remote[r]['ca'][0], group_ca_path, remote[r]['core'].groupId
        )

    # create and connect MQTT client pointed toward the Master Greengrass Core
    mqttc_m = AWSIoTMQTTClient(ggd_name)
    log.info("[initialize] local gca_file:{0} cert:{1}".format(
        local_core_ca_file, certificate))
    mqttc_m.configureCredentials(
        local_core_ca_file, private_key, certificate
    )
    mqttc_m.configureOfflinePublishQueueing(10, DROP_OLDEST)

    log.info("[initialize] Starting connection to Master Core")
    if utils.mqtt_connect(mqtt_client=mqttc_m, core_info=local['core']):
        log.info("[initialize] Connected to Master Core")
    else:
        log.error("[initialize] could not connect to Master Core")

    # create and connect MQTT clients pointed toward the remote Greengrass Cores
    mqttc_list = list()
    for r in remote:
        remote_mqttc = AWSIoTMQTTClient(ggd_name)
        log.info("[initialize] local gca_file:{0} cert:{1}".format(
            r, certificate))
        remote_mqttc.configureCredentials(
            remote[r]['ca_file'], private_key, certificate)
        remote_mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)
        log.info("[initialize] Starting connection to Remote Core")
        if utils.mqtt_connect(mqtt_client=remote_mqttc,
                              core_info=remote[r]['core']):
            log.info("[initialize] Connected to Remote Core:{0}".format(
                remote[r]['core'].coreThingArn
            ))
            mqttc_list.append(remote_mqttc)
        else:
            log.error(
                "[initialize] could not connect to Remote Core:{0}".format(
                    remote[r]['core'].coreThingArn
            ))

    return mqttc_m, mqttc_list
    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()
Beispiel #33
0
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)