예제 #1
0
        resubscribe_future.add_done_callback(on_resubscribe_complete)


def on_resubscribe_complete(resubscribe_future):
    resubscribe_results = resubscribe_future.result()
    print("Resubscribe results: {}".format(resubscribe_results))

    for topic, qos in resubscribe_results['topics']:
        if qos is None:
            sys.exit("Server rejected resubscribe to topic: {}".format(topic))


endPt = "a37g54y6ddcht7-ats.iot.us-east-1.amazonaws.com"
clientId = "samples-client-id"

event_loop_group = io.EventLoopGroup(1)
host_resolver = io.DefaultHostResolver(event_loop_group)
client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver)

mqtt_connection = mqtt_connection_builder.mtls_from_path(
    endpoint=endPt,
    cert_filepath="Certificates/cdc357b6af-certificate.pem.crt",
    pri_key_filepath="Certificates/cdc357b6af-private.pem.key",
    client_bootstrap=client_bootstrap,
    on_connection_interrupted=on_connection_interrupted,
    on_connection_resumed=on_connection_resumed,
    client_id=clientId,
    clean_session=False,
    keep_alive_secs=6)

print("Connecting to {} with client ID '{}'...".format(endPt, clientId))
def main():
    #AWS CONNECTION
    event_loop_group = io.EventLoopGroup(1)
    host_resolver = io.DefaultHostResolver(event_loop_group)
    client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver)
    mqtt_connection = mqtt_connection_builder.mtls_from_path(
                endpoint=ENDPOINT,
                cert_filepath=PATH_TO_CERT,
                pri_key_filepath=PATH_TO_KEY,
                client_bootstrap=client_bootstrap,
                ca_filepath=PATH_TO_ROOT,
                client_id=CLIENT_ID,
                clean_session=False,
                keep_alive_secs=6
                )
    print("Connecting to {} with client ID '{}'...".format(
            ENDPOINT, CLIENT_ID))
    # Make the connect() call
    connect_future = mqtt_connection.connect()
    # Future.result() waits until a result is available
    connect_future.result()
    print("Connected!")

    """
    Tasks API
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    service = build('tasks', 'v1', credentials=creds)

    # Call the Tasks API
    results = service.tasklists().list(maxResults=10).execute()
    items = results.get('items', [])

    previous_task_count = 0
    current_task_count = 0

    while True:

        previous_task_count = current_task_count
        current_task_count = 0
        tasks = []
        if not items:
            print('No task lists found.')
        else:
            print('Task lists:')
            for item in items:
                lists = service.tasks().list(tasklist=item['id'], showCompleted=False).execute().get('items')

                if lists is not None:
                    current_task_count += len(lists)
                    tasks.append(lists)
                #print(u'{0} ({1})'.format(item['title'], item['id']))
        print('total tasks' , current_task_count)
        
        #if current task count has decreased
        if(current_task_count < previous_task_count):
            print('Begin Publish')
            for i in range(5):
                message = {"h" : 200, "s": 255, 'v': 255, "client": 'ec2'}
                mqtt_connection.publish(topic=TOPIC, payload=json.dumps(message), qos=mqtt.QoS.AT_LEAST_ONCE)
                print("Published: '" + json.dumps(message) + "' to the topic: " + "'lamp/state'")
        
        time.sleep(1)


    print('Ending')
    disconnect_future = mqtt_connection.disconnect()
    disconnect_future.result()
예제 #3
0
def device_main():
    """
    main loop for dummy device
    """
    global device_name, mqtt_connection, shadow_client

    sensor = SenseHat()

    init_info = arg_check()
    device_name = init_info['device_name']
    iot_endpoint = init_info['endpoint']
    rootca_file = init_info['certs'][0]
    private_key_file = init_info['certs'][1]
    certificate_file = init_info['certs'][2]

    logger.info("device_name: %s", device_name)
    logger.info("endpoint: %s", iot_endpoint)
    logger.info("rootca cert: %s", rootca_file)
    logger.info("private key: %s", private_key_file)
    logger.info("certificate: %s", certificate_file)

    # Spin up resources
    event_loop_group = io.EventLoopGroup(1)
    host_resolver = io.DefaultHostResolver(event_loop_group)
    client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver)

    mqtt_connection = mqtt_connection_builder.mtls_from_path(
        endpoint=iot_endpoint,
        cert_filepath=certificate_file,
        pri_key_filepath=private_key_file,
        client_bootstrap=client_bootstrap,
        ca_filepath=rootca_file,
        client_id=device_name,
        clean_session=False,
        keep_alive_secs=KEEP_ALIVE)

    connected_future = mqtt_connection.connect()
    shadow_client = iotshadow.IotShadowClient(mqtt_connection)
    connected_future.result()

    print("Check latest Shadow status")
    get_accepted_subscribed_future, _ = shadow_client.subscribe_to_get_shadow_accepted(
        request=iotshadow.GetShadowSubscriptionRequest(device_name),
        qos=mqtt.QoS.AT_LEAST_ONCE,
        callback=on_get_shadow_accepted)

    get_rejected_subscribed_future, _ = shadow_client.subscribe_to_get_shadow_rejected(
        request=iotshadow.GetShadowSubscriptionRequest(device_name),
        qos=mqtt.QoS.AT_LEAST_ONCE,
        callback=on_get_shadow_rejected)

    # Wait for subscriptions to succeed
    get_accepted_subscribed_future.result()
    get_rejected_subscribed_future.result()

    publish_get_future = shadow_client.publish_get_shadow(
        request=iotshadow.GetShadowRequest(device_name),
        qos=mqtt.QoS.AT_LEAST_ONCE)

    # Ensure that publish succeeds
    publish_get_future.result()

    logger.info("Subscribing to Shadow Delta events...")
    delta_subscribed_future, _ = shadow_client.subscribe_to_shadow_delta_updated_events(
        request=iotshadow.ShadowDeltaUpdatedSubscriptionRequest(device_name),
        qos=mqtt.QoS.AT_LEAST_ONCE,
        callback=on_shadow_delta_updated)

    # Wait for subscription to succeed
    delta_subscribed_future.result()

    logger.info("Subscribing to Shadow Update responses...")
    update_accepted_subscribed_future, _ = shadow_client.subscribe_to_update_shadow_accepted(
        request=iotshadow.UpdateShadowSubscriptionRequest(device_name),
        qos=mqtt.QoS.AT_LEAST_ONCE,
        callback=on_update_shadow_accepted)

    update_rejected_subscribed_future, _ = shadow_client.subscribe_to_update_shadow_rejected(
        request=iotshadow.UpdateShadowSubscriptionRequest(device_name),
        qos=mqtt.QoS.AT_LEAST_ONCE,
        callback=on_update_shadow_rejected)

    # Wait for subscriptions to succeed
    update_accepted_subscribed_future.result()
    update_rejected_subscribed_future.result()

    # Start sending dummy data
    topic = BASE_TOPIC + device_name
    logging.info("topic: %s", topic)
    while True:
        now = datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
        humi = sensor.temperature
        temp = sensor.humidity
        payload = {
            "DEVICE_NAME": device_name,
            "TIMESTAMP": now,
            "TEMPERATURE": int(temp),
            "HUMIDITY": int(humi)
        }
        logger.debug("  payload: %s", payload)

        mqtt_connection.publish(topic=topic,
                                payload=json.dumps(payload),
                                qos=mqtt.QoS.AT_LEAST_ONCE)

        time.sleep(wait_time)
예제 #4
0
def main():
    # Parse command line arguments
    parser, args = parse_args()

    global count
    count = args.count

    # set log level
    io.init_logging(getattr(io.LogLevel, args.verbosity), 'stderr')

    # Print MAC address
    print(gma())

    # Initialize and Calibrate Gas Sensor 1x
    mq = MQ()

    # Initial the dht device, with data pin connected to:
    dht_device = adafruit_dht.DHT22(PIN_DHT)

    # Initialize Light Sensor
    ls = LightSensor(PIN_LIGHT)

    # Initialize PIR Sensor
    pir = MotionSensor(PIN_PIR)
    led = LED(PIN_PIR_LED)

    # Spin up resources
    event_loop_group = io.EventLoopGroup(1)
    host_resolver = io.DefaultHostResolver(event_loop_group)
    client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver)

    # Set MQTT connection
    mqtt_connection = set_mqtt_connection(args, client_bootstrap)

    print("Connecting to {} with client ID '{}'...".format(
        args.endpoint, args.client_id))

    connect_future = mqtt_connection.connect()

    # Future.result() waits until a result is available
    connect_future.result()
    print("Connected!")

    # # Subscribe (this will pull in messages down from other devices)
    # print("Subscribing to topic '{}'...".format(args.topic))
    # subscribe_future, packet_id = mqtt_connection.subscribe(
    #     topic=args.topic,
    #     qos=mqtt.QoS.AT_LEAST_ONCE,
    #     callback=on_message_received)
    #
    # subscribe_result = subscribe_future.result()
    # print("Subscribed with {}".format(str(subscribe_result['qos'])))

    while True:
        led.off()

        # Create message payload
        payload_dht = get_sensor_data_dht(dht_device)
        payload_gas = get_sensor_data_gas(mq)
        payload_light = get_sensor_data_light(ls)
        payload_motion = get_sensor_data_motion(pir, led)

        payload = {
            "device_id": gma(),
            "ts": time.time(),
            "data": {
                "temp": payload_dht["temp"],
                "humidity": payload_dht["humidity"],
                "lpg": payload_gas["lpg"],
                "co": payload_gas["co"],
                "smoke": payload_gas["smoke"],
                "light": payload_light["light"],
                "motion": payload_motion["motion"]
            }
        }

        # Don't send bad messages!
        if payload["data"]["temp"] is not None \
                and payload["data"]["humidity"] is not None \
                and payload["data"]["co"] is not None:
            # Publish Message
            message_json = json.dumps(payload,
                                      sort_keys=True,
                                      indent=None,
                                      separators=(',', ':'))

            try:
                mqtt_connection.publish(topic=args.topic,
                                        payload=message_json,
                                        qos=mqtt.QoS.AT_LEAST_ONCE)
            except mqtt.SubscribeError as err:
                print(".SubscribeError: {}".format(err))
            except exceptions.AwsCrtError as err:
                print("AwsCrtError: {}".format(err))
            else:
                time.sleep(args.frequency)
        else:
            print("sensor failure...retrying...")