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 heartbeat(config_file, topic, frequency=3):
    # 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']['GGD_heartbeat']['thing_name']
    mqttc = AWSIoTMQTTClient(heartbeat_name)
    mqttc.configureEndpoint(ggd_config.inv_arm_ip, ggd_config.inv_arm_port)
    mqttc.configureCredentials(
        CAFilePath=dir_path + "/" + ggd_ca_file_path,
        KeyPath=dir_path + "/certs/GGD_heartbeat.private.key",
        CertificatePath=dir_path + "/certs/GGD_heartbeat.certificate.pem.crt"
    )

    mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)

    if mqtt_connect(mqttc):
        # MQTT client has connected to GG Core, start heartbeat messages
        try:
            start = datetime.datetime.now()
            while True:
                hostname = socket.gethostname()

                now = datetime.datetime.now()
                msg = {
                    "version": "2017-07-05",  # YYYY-MM-DD
                    "ggd_id": heartbeat_name,
                    "hostname": hostname,
                    "data": [
                        {
                            "sensor_id": "heartbeat",
                            "ts": now.isoformat(),
                            "duration": str(now - start)
                        }
                    ]
                }
                print("[hb] publishing heartbeat msg: {0}".format(msg))
                mqttc.publish(topic, json.dumps(msg), 0)
                time.sleep(random.random() * 10)

        except KeyboardInterrupt:
            log.info(
                "[__main__] KeyboardInterrupt ... exiting heartbeat")
        mqttc.disconnect()
        time.sleep(2)
    else:
        print("[hb] could not connect successfully via mqtt.")
Пример #3
0
def heartbeat(config_file, topic, frequency=3):
    # 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']['GGD_heartbeat']['thing_name']
    mqttc = AWSIoTMQTTClient(heartbeat_name)
    mqttc.configureEndpoint(ggd_config.inv_arm_ip, ggd_config.inv_arm_port)
    mqttc.configureCredentials(
        CAFilePath=dir_path + "/" + ggd_ca_file_path,
        KeyPath=dir_path + "/certs/GGD_heartbeat.private.key",
        CertificatePath=dir_path + "/certs/GGD_heartbeat.certificate.pem.crt")

    mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)

    if mqtt_connect(mqttc):
        # MQTT client has connected to GG Core, start heartbeat messages
        try:
            start = datetime.datetime.now()
            while True:
                hostname = socket.gethostname()

                now = datetime.datetime.now()
                msg = {
                    "version":
                    "2017-07-05",  # YYYY-MM-DD
                    "ggd_id":
                    heartbeat_name,
                    "hostname":
                    hostname,
                    "data": [{
                        "sensor_id": "heartbeat",
                        "ts": now.isoformat(),
                        "duration": str(now - start)
                    }]
                }
                print("[hb] publishing heartbeat msg: {0}".format(msg))
                mqttc.publish(topic, json.dumps(msg), 0)
                time.sleep(random.random() * 10)

        except KeyboardInterrupt:
            log.info("[__main__] KeyboardInterrupt ... exiting heartbeat")
        mqttc.disconnect()
        time.sleep(2)
    else:
        print("[hb] could not connect successfully via mqtt.")
Пример #4
0
  {"2": [{"n":1,"r":-41},{"n":255,"r":0},{"n":3,"r":-26}]},
  {"1": [{"n":255,"r":0},{"n":2,"r":-41},{"n":2,"r":0}]},
  {"1": [{"n":255,"r":0},{"n":2,"r":-50},{"n":2,"r":0}]},
  {"2": [{"n":1,"r":-42},{"n":255,"r":0},{"n":3,"r":-15}]},
  {"1": [{"n":255,"r":0},{"n":2,"r":-41},{"n":2,"r":0}]},
  {"1": [{"n":255,"r":0},{"n":2,"r":-41},{"n":0,"r":0}]},
  {"2": [{"n":0,"r":0},{"n":255,"r":0},{"n":3,"r":-26}]},
  {"1": [{"n":255,"r":0},{"n":2,"r":-43},{"n":0,"r":0}]},
  {"2": [{"n":1,"r":-54},{"n":255,"r":0},{"n":3,"r":-26}]},
  {"1": [{"n":255,"r":0},{"n":2,"r":-42},{"n":2,"r":0}]},
  {"1": [{"n":255,"r":0},{"n":2,"r":-43},{"n":2,"r":0}]},
  {"1": [{"n":255,"r":0},{"n":2,"r":-43},{"n":0,"r":0}]},
  {"1": [{"n":255,"r":0},{"n":2,"r":-54},{"n":0,"r":0}]},
  {"1": [{"n":255,"r":0},{"n":2,"r":-54},{"n":0,"r":0}]},
  {"2": [{"n":1,"r":-41},{"n":255,"r":0},{"n":0,"r":0}]},
  {"3": [{"n":2,"r":0},{"n":2,"r":-24},{"n":255,"r":0}]},
  {"1": [{"n":255,"r":0},{"n":2,"r":-41},{"n":0,"r":0}]},
  {"1": [{"n":255,"r":0},{"n":2,"r":-52},{"n":2,"r":0}]},
  {"3": [{"n":2,"r":0},{"n":2,"r":-24},{"n":255,"r":0}]},
  {"4": [{"n":1,"r":-43},{"n":1,"r":-12},{"n":3,"r":-26},{"n":255, "r":0}]}
]

cli = mqtt_connect()
for data in test_data:
    #client.publish("mesh_gateway/data", json.dumps(data))
    mqtt_send(cli, data)
    print('send', data)
    time.sleep(1)
print("Publishing message to topic","mesh_gateway/data")
mqtt_disconnect(cli)
    red_parser.add_argument('--off', dest='toggle', action='store_false',
                            help="Virtual toggle OFF")
    red_parser.add_argument('--light', action='store_true')
    red_parser.set_defaults(func=button_red, toggle=True)

    white_parser = subparsers.add_parser(
        'white',
        description='Virtual WHITE button toggled')
    white_parser.add_argument('--on', dest='toggle', action='store_true',
                              help="Virtual toggle ON")
    white_parser.add_argument('--off', dest='toggle', action='store_false',
                              help="Virtual toggle OFF")
    white_parser.add_argument('--light', action='store_true')
    white_parser.set_defaults(func=button_white, toggle=True)

    pa = parser.parse_args()

    client, core = core_connect(
        device_name=pa.device_name,
        config_file=pa.config_file, root_ca=pa.root_ca,
        certificate=pa.certificate, private_key=pa.private_key,
        group_ca_path=pa.group_ca_path
    )

    if utils.mqtt_connect(mqtt_client=client, core_info=core):
        pa.func(pa)

    time.sleep(0.5)
    mqttc.disconnect()
    time.sleep(1)
Пример #6
0
    mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)

    return mqttc, gg_core


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Tracker GGD and CLI heart rate',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('device_name',
                        help="The GGD device_name in the config file.")
    parser.add_argument('config_file', help="The config file.")
    parser.add_argument('root_ca',
                        help="Root CA File Path of Cloud Server Certificate.")
    parser.add_argument('certificate', help="File Path of GGD Certificate.")
    parser.add_argument('private_key', help="File Path of GGD Private Key.")
    parser.add_argument(
        'group_ca_path',
        help="The directory path where the discovered Group CA will be saved.")

    pa = parser.parse_args()

    client, core = core_connect(device_name=pa.device_name,
                                config_file=pa.config_file,
                                root_ca=pa.root_ca,
                                certificate=pa.certificate,
                                private_key=pa.private_key,
                                group_ca_path=pa.group_ca_path)

    if utils.mqtt_connect(mqtt_client=client, core_info=core):
        heartrate('user1')
Пример #7
0
def main_loop():
    in_ = ''

    loop_flag = True
    
    global __STM
    global __FIF
    global CONF_READ_TIMEOUT
    global CONF_METER_TO_READ
    global CONF_WATCHDOG_RESET
    global CONF_METERF
    
    start_read = time.time()
    start_wdg = time.time()
    
    try:
        while loop_flag:
            if time.time() - start_wdg > CONF_WATCHDOG_RESET:
                __STM.reset_wdg()
                start_wdg = time.time()
                
            elif time.time() - start_read > CONF_READ_TIMEOUT:
                
                #STM_GO = stm32.STM32()
                #FIF_GO = fif.FIF(STM_GO, usb_log=True)
                __STM.set_led_toggle('YELLOW',1000,1,1)
                
                utils.mqtt_connect(log=True)
                time.sleep(15)
                
                for m in CONF_METER_TO_READ:
                    res = __FIF.read_LE_0xM(int(m), int(CONF_METERF[int(m)-1])) # CONF_METERF indicates phase number
                    
                    if res[0] != 0:
                        utils.mqtt_send('le_0xm_{}'.format(m), res[9])
                        USB0.send('Meter with {} address read out correctly\r\n'.format(m))
                    else:
                        USB0.send('Meter with {} address is not responding\r\n'.format(m))
                    time.sleep(15)
                
                time.sleep(30)
                utils.mqtt_disconnect(log=True)
                
                __STM.set_led('YELLOW','OFF',0)
                start_read = time.time()
                __STM.reset_wdg()
                start_wdg = time.time()
                continue
                
            elif (in_.find('AT++') == -1):
                in_ = in_ + USB0.read()
            else:
                if (in_.find('AT++') != -1):
            
                    if (in_.find('AT++CONFIG?') != -1):
                        # returns whole configuration
                        CONFIG.dump()
                        USB0.send('++CONFIG OK\r\n')
                        in_ = ''
                        start_read = time.time()
                        continue
                    
                    if (in_.find('AT++METACH=') != -1):
                        # command changes meter addr to new one
                        
                        x = in_.find('=')
                        y = ''
                        for ch in in_[x+1:]:
                            if ch != ',':
                                y += ch
                            else:
                                break
                        addr = y
                        
                        x = in_.find(',')
                        y = ''
                        for ch in in_[x+1:]:
                            if ch != '\r':
                                y += ch
                            else:
                                break
                        new_addr = y
                        try:
                            res = __FIF.change_addr_LE_0xM(int(addr), int(new_addr))
                            USB0.send('METER ADDR CHANGED: {}\r\n'.format(res))
                        except Exception as e:
                            USB0.send('FATAL ERROR ++METACH: {}\r\n'.format(e))
                            
                        USB0.send('++METACH OK\r\n')
                        in_ = ''
                        start_read = time.time()
                        __STM.reset_wdg()
                        start_wdg = time.time()
                        continue
                    
                    
                    if (in_.find('AT++METTR=') != -1):
                        # command sets meters to read out
                        
                        x = in_.find('=')
                        y = in_.find('\r')
                        z = ''
                        for ch in in_[x+1:y]:
                            z += ch
                        
                        CONFIG.set('METER_TO_READ',z)
                        CONFIG.write()
                        CONF_METER_TO_READ = CONFIG.get('METER_TO_READ').split(',')
                        USB0.send('METER_TO_READ -> {}\r\n'.format(CONF_METER_TO_READ))                   
                        USB0.send('++METTR OK\r\n')
                        in_ = ''
                        start_read = time.time()
                        __STM.reset_wdg()
                        start_wdg = time.time()
                        continue
                    
                    if (in_.find('AT++METERF=') != -1):
                        # command sets meters to read out
                        
                        x = in_.find('=')
                        y = in_.find('\r')
                        z = ''
                        for ch in in_[x+1:y]:
                            z += ch
                        
                        CONFIG.set('METERF',z)
                        CONFIG.write()
                        CONF_METERF = CONFIG.get('METERF').split(',')
                        USB0.send('METERF -> {}\r\n'.format(CONF_METERF))                   
                        USB0.send('++METERF OK\r\n')
                        in_ = ''
                        start_read = time.time()
                        __STM.reset_wdg()
                        start_wdg = time.time()
                        continue
                    
                    if (in_.find('AT++METTEST=') != -1):
                        # command tests the meter read out
                        
                        x = in_.find('=')
                        y = in_.find('\r')
                        addr = int(in_[x+1:y])
                        
                        res = __FIF.read_LE_0xM(int(addr), int(CONF_METERF[addr-1]))
                    
                        if res[0] != 0:
                            USB0.send('Meter with {} address read out correctly\r\n'.format(res))
                        else:
                            USB0.send('Meter with {} address is not responding\r\n'.format(res))
                        
                        USB0.send('++METTEST OK\r\n')
                        in_ = ''
                        start_read = time.time()
                        __STM.reset_wdg()
                        start_wdg = time.time()
                        continue
                    
                    if (in_.find('AT++READTM=') != -1):
                        # command sets meters to read out
                        
                        x = in_.find('=')
                        y = in_.find('\r')
                        z = int(in_[x+1:y])
                        
                        CONFIG.set('READ_TIMEOUT',str(z))
                        CONFIG.write()
                        CONF_READ_TIMEOUT = int(CONFIG.get('READ_TIMEOUT'))
                        USB0.send('READ_TIMEOUT -> {}\r\n'.format(CONF_READ_TIMEOUT))                   
                        USB0.send('++READTM OK\r\n')
                        in_ = ''
                        start_read = time.time()
                        __STM.reset_wdg()
                        start_wdg = time.time()
                        continue
            
            
                    if (in_.find('AT++STM?') != -1):
                        USB0.send('++STM OK\r\n')
                        in_ = ''
                        start_read = time.time()
                        __STM.reset_wdg()
                        start_wdg = time.time()
                        continue
            
                    if (in_.find('AT++MQTT=CONNECT') != -1):
                        utils.mqtt_connect(log=True)
                        USB0.send('++STM OK\r\n') # TODO to change for ++MQTT OK
                        in_ = ''
                        start_read = time.time()
                        __STM.reset_wdg()
                        start_wdg = time.time()
                        continue
            
                    if (in_.find('AT++MQTT=DISCONNECT') != -1):
                        utils.mqtt_disconnect(log=True)
                        USB0.send('++STM OK\r\n')
                        in_ = ''
                        start_read = time.time()
                        __STM.reset_wdg()
                        start_wdg = time.time()
                        continue
            
                    if (in_.find('AT++DWCONN') != -1):
                        res = utils.get_DWCONN()
                        USB0.send('{}\r\n'.format(res[0]))
                        USB0.send('++DWCONN OK\r\n')
                        in_ = ''
                        start_read = time.time()
                        __STM.reset_wdg()
                        start_wdg = time.time()
                        continue
          
                    if (in_.find('AT++STM=') != -1):
                
                        cmd_idx = in_.find('=')+1
                        cmd = in_[cmd_idx:]
                
                        SER.send(cmd, 1)
                        res = utils.SER_receive(2)
                        USB0.send('(++STM OK):' + res)
                        in_ = ''
                        start_read = time.time()
                        __STM.reset_wdg()
                        start_wdg = time.time()
                        continue
  
                    if (in_.find('AT++MODEM=') != -1):
                
                        cmd_idx = in_.find('=')+1
                        cmd = in_[cmd_idx:]
                
                        MDM.send(cmd, 1)
                        res = utils.MDM_receive(2)
                        USB0.send('(++MODEM OK):' + res)
                        in_ = ''
                        start_read = time.time()
                        __STM.reset_wdg()
                        start_wdg = time.time()
                        continue
            
                    if (in_.find('AT++QUIT') != -1):
                        __STM.set_led('RED','OFF',0)
                        USB0.send('++QUIT OK\r\n')
                        in_ = ''
                        loop_flag = False
            
                    else:
                        USB0.send('++OK\r\n')
                        in_ = ''
                        start_read = time.time()
                        __STM.reset_wdg()
                        start_wdg = time.time()
                        continue
        else: 
            USB0.send('MODBUS program has been closed...\r\n')
    except Exception as e:
        USB0.send('FATAL ERROR: main loop {}\r\n'.format(e))
        log('FATAL ERROR: main loop {}\r\n'.format(e))
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
Пример #10
0
def connect(port):
    """
        Establish a connection to the serial port and start to collect readings
        from the serial port
    """
    mqtt_cli = mqtt_connect()
    list = []
    reading = {}
    readings = []

    #print("Collecting readings from " + port)
    logger.info('Collection readings from ' + port)

    input = serial.Serial(port=port, baudrate=SPEED, timeout=0.5)

    while input.isOpen():
        try:
            data_lines = input.readlines()
            if not data_lines:
                print([])
            else:

                for line in data_lines:
                    data = line.decode('utf-8').split()
                    # print(data)
                    rssi = int(data[0])
                    #print('rssi:', rssi)
                    hexarray = []
                    for x in data[1:]:

                        if len(x) == 2:
                            hexarray.append('0x' + x)
                        elif len(x) == 1:
                            hexarray.append("0x0" + x)
                        else:
                            raise Exception(x, "lenght is not 1 or 2")
                    #print(hexarray, len(hexarray))
                    data = [int(x, 16) for x in hexarray]
                    #print(len(data), " bytes")
                    #print(data)
                    try:
                        msg_type = Msg_Type(data[4])
                    except:
                        traceback.print_exc()
                        msg_type = Msg_Type.MESH_TYPE_UNKNOWN

                    if msg_type == Msg_Type.MESH_TYPE_RT_REPORT:

                        # logger.info(str(time.ctime(int(time.time())))
                        #            + " # of Entries = " + str(data[1])
                        #             + "\n"
                        #            )
                        table = PrettyTable()

                        #table.field_names = ["isNeighbor", "# of Hops", "Next Hop", "State", "Remaining Timeout", "RSSI"]
                        table.field_names = [
                            "isNeighbor", "# of Hops", "Next Hop", "State",
                            "RSSI"
                        ]
                        length = 5
                        owner = data[0]
                        rt = {owner: []}
                        for i in range(1, int(data[1]) + 1):
                            state = ['Invalid', 'Valid'
                                     ][int(data[9 + (i - 1) * length + 3])]
                            rssi = sign_extend(
                                (data[9 + (i - 1) * length + 4] << 8
                                 | data[9 + (i - 1) * length + 5]))
                            table.add_row([
                                data[9 + (i - 1) * length + 1],
                                data[9 + (i - 1) * length + 2], i, state, rssi
                            ])
                            if state == 'Valid' and data[9 + (i - 1) * length +
                                                         1] == 1:
                                rt[owner].append({'n': i, 'r': rssi})
                            else:
                                rt[owner].append({'n': 255, 'rssi': 0})
                        #print("RT report from node", data[0])
                        #print(table)


#              print(rt)
                        mqtt_send(mqtt_cli, rt)
        except KeyboardInterrupt:
            exit()
        except:
            traceback.print_exc()

    input.close()
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
Пример #12
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