示例#1
0
PATH_TO_AMAZON_ROOT_CA_1 = "cert/xxx"
MESSAGE = "Hello World"
TOPIC = ""
RANGE = 2

# 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=ENDPOINT,
    cert_filepath=PATH_TO_CERTIFICATE,
    pri_key_filepath=PATH_TO_PRIVATE_KEY,
    client_bootstrap=client_bootstrap,
    ca_filepath=PATH_TO_AMAZON_ROOT_CA_1,
    client_id=CLIENT_ID,
    clean_session=False,
    keep_alive_secs=6,
    # if use proxy, comment out.
    # http_proxy_options=awscrt.http.HttpProxyOptions(
    #     host_name='proxygate51.nic.nec.co.jp',
    #     port=8080)
)
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
result = connect_future.result()
print(result)
print("Connected!")
# Publish message to server desired number of times.
print('Begin Publish')
示例#2
0
    # signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGQUIT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    # setup AWS connection
    event_loop_group = io.EventLoopGroup(1)
    host_resolver = io.DefaultHostResolver(event_loop_group)
    client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver)

    # need a unique client id
    aws_mqtt = mqtt_connection_builder.mtls_from_path(
        endpoint=args.endpoint,
        cert_filepath="%s/device.crt" % (args.provision_location),
        pri_key_filepath="%s/device.key" % (args.provision_location),
        client_bootstrap=client_bootstrap,
        ca_filepath="%s/AmazonRootCA1.pem" % (args.cert_location),
        on_connection_interrupted=aws_on_connection_interrupted,
        on_connection_resumed=aws_on_connection_resumed,
        client_id=args.thing_name,
        clean_session=False,
        keep_alive_secs=AWS_KEEP_ALIVE_SECS)

    # connect loop
    conn_attempt = 1
    connected = False
    while not connected and conn_attempt <= AWS_CONNECT_ATTEMPTS:
        try:
            print("[aws] [%d] Connecting to %s as %s ..." %
                  (conn_attempt, args.endpoint, args.thing_name))
            connect_future = aws_mqtt.connect()
            connect_future.result()
示例#3
0
endpoint = config['IOT-DEVICE']['endpoint']
client_id = config['IOT-DEVICE']['client_id']
path_to_cert = config['IOT-DEVICE']['path_to_cert']
path_to_key = config['IOT-DEVICE']['path_to_key']
path_to_root = config['IOT-DEVICE']['path_to_root']
my_topic = config['IOT-DEVICE']['topic']

# 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=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)
# Make the connect() call
connect_future = mqtt_connection.connect()
# Future.result() waits until a result is available
connect_future.result()

lock = threading.Lock()
engine = DetectionEngine(model)
labels = dataset_utils.read_label_file(labels)

ct1 = CentroidTracker(maxDisappeared=600, maxDistance=900)
ct2 = CentroidTracker(maxDisappeared=600, maxDistance=900)
示例#4
0
        received_all_event.set()


if __name__ == '__main__':
    # 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)
    print(client_bootstrap)

    mqtt_connection = mqtt_connection_builder.mtls_from_path(
        endpoint=my_keys["endpoint"],
        cert_filepath=my_keys["cert_filepath"],
        pri_key_filepath=my_keys["pri_key_filepath"],
        client_bootstrap=client_bootstrap,
        ca_filepath=my_keys["ca_filepath"],
        on_connection_interrupted=on_connection_interrupted,
        on_connection_resumed=on_connection_resumed,
        client_id=my_keys['client_id'],
        clean_session=False,
        keep_alive_secs=6)

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

    connect_future = mqtt_connection.connect()

    # Future.result() waits until a result is available
    connect_future.result()
    print("Connected!")
示例#5
0
            endpoint=args.endpoint,
            client_bootstrap=client_bootstrap,
            region=args.signing_region,
            credentials_provider=credentials_provider,
            websocket_proxy_options=proxy_options,
            ca_filepath=args.root_ca,
            client_id=args.client_id,
            clean_session=False,
            keep_alive_secs=6)

    else:
        mqtt_connection = mqtt_connection_builder.mtls_from_path(
            endpoint=args.endpoint,
            cert_filepath=args.cert,
            pri_key_filepath=args.key,
            client_bootstrap=client_bootstrap,
            ca_filepath=args.root_ca,
            client_id=args.client_id,
            clean_session=False,
            keep_alive_secs=6)

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

    connected_future = mqtt_connection.connect()

    shadow_client = iotshadow.IotShadowClient(mqtt_connection)

    # Wait for connection to be fully established.
    # Note that it's not necessary to wait, commands issued to the
    # mqtt_connection before its fully connected will simply be queued.
示例#6
0
import os
import threading


def on_message_received(topic, payload, dup, qos, retain, **kwargs):
    print("Received message from topic '{}': {}".format(topic, payload))


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=os.getenv('IOT_ENDPOINT'),
    cert_filepath="cert.pem.crt",
    pri_key_filepath="private.pem.key",
    client_bootstrap=client_bootstrap,
    ca_filepath="AmazonRootCA1.pem",
    client_id="simplethinglistener")

mqtt_connection.connect().result()

subscribe_future, packet_id = mqtt_connection.subscribe(
    topic="test/testing",
    qos=mqtt.QoS.AT_LEAST_ONCE,
    callback=on_message_received)

subscribe_result = subscribe_future.result()

threading.Event().wait()
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)
示例#8
0
        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))
connect_future = mqtt_connection.connect()

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

with open('weather_data.csv', mode='r') as file:
    reader = csv.DictReader(file)
    for row in reader:
示例#9
0
ADAFRUIT_IO_KEY = os.getenv('ADAFRUIT_IO_KEY')
PM_2_5_TOPIC = 'air-quality.home-pm-2-5'
PM_10_TOPIC = 'air-quality.home-pm-10'
AQI_2_5_TOPIC = 'air-quality.home-aqi-2-5'
AQI_10_TOPIC = 'air-quality.home-aqi-10'

SENSOR = SDS011("/dev/SDS011", use_query_mode=True)
AIO = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

event_loop_group = io.EventLoopGroup(1)
host_resolver = io.DefaultHostResolver(event_loop_group)
client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver)
MQTT = mqtt_connection_builder.mtls_from_path(
    endpoint=IOT_ENDPOINT,
    cert_filepath=os.path.join(DIR_PATH, IOT_CERT_FOLDER, 'certificate.pem'),
    pri_key_filepath=os.path.join(DIR_PATH, IOT_CERT_FOLDER, 'private.key'),
    ca_filepath=os.path.join(DIR_PATH, IOT_CERT_FOLDER, 'ca.pem'),
    client_id='air-quality-pi',
    client_bootstrap=client_bootstrap)
MQTT.connect()


def get_pm_data(n=10):
    pmt_2_5 = 0
    pmt_10 = 0

    # turn on fan
    SENSOR.sleep(sleep=False)

    # sleep for a bit while it stabilizes
    # get average air quality levels over a period of 6 seconds by default
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()
示例#11
0
                        default='samples-client-id',
                        help="Client ID for MQTT connection.")
    parser.add_argument('--topic',
                        default="samples/test",
                        help="Topic to subscribe to, and publish messages to.")
    parser.add_argument('--location', default="Default Location")
    parser.add_argument('--event', default="Sign In")
    args = parser.parse_args()

    # Establish an mqtt connection to publish and subscribe to topics on
    mqtt_connection = mqtt_connection_builder.mtls_from_path(
        endpoint=args.endpoint,
        cert_filepath=args.cert,
        pri_key_filepath=args.key,
        client_bootstrap=
        client_bootstrap,  # Don't know what this is; don't touch it
        ca_filepath=args.root_ca,
        #on_connection_interrupted=on_connection_interrupted, # Don't know what this is; don't touch it
        #on_connection_resumed=on_connection_resumed, # Don't know what this is; don't touch it
        client_id=args.client_id,
        clean_session=False,  # Don't know what this is; don't touch it
        keep_alive_secs=6)  # Don't know what this is; don't touch it

    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!")
        time.sleep(1)
        publish_count += 1


if __name__ == '__main__':
    # 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="a3lk6rh9gr0knb-ats.iot.cn-northwest-1.amazonaws.com.cn",
        cert_filepath="../iot/glue-demo-iot.cert.pem",
        pri_key_filepath="../iot/glue-demo-iot.private.key",
        client_bootstrap=client_bootstrap,
        ca_filepath="../iot/AmazonRootCA1.pem",
        on_connection_interrupted=on_connection_interrupted,
        on_connection_resumed=on_connection_resumed,
        client_id=client_id,
        clean_session=False,
        keep_alive_secs=6)

    connect_future = mqtt_connection.connect()

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

    # Subscribe
    print("Subscribing to topic '{}'...".format(topic))
    subscribe_future, packet_id = mqtt_connection.subscribe(
示例#13
0
with open('./config.json', 'r') as config_file:
    data = config_file.read()
config = json.loads(data)

def interrupted_handler(connection, error, **kwargs):
    print("Connection interrupted: " + error.name + ": " + error.message)

def resumed_handler(connection, return_code, session_present, **kwargs):
    print("Connection resumed: " + return_code)

iot = mqtt_connection_builder.mtls_from_path(
        endpoint="ayecs2a13r9pv-ats.iot.us-west-2.amazonaws.com",
        cert_filepath="/home/" + getpass.getuser() + "/workspace/" + config["name"] + "-certificate.pem.crt",
        pri_key_filepath="/home/" + getpass.getuser() + "/workspace/" + config["name"] + "-private.pem.key",
        ca_filepath="/home/" + getpass.getuser() + "/workspace/AmazonRootCA1.pem",
        client_id=config["name"],
        client_bootstrap=client_bootstrap,
        clean_session=False,
        ping_timeout_ms=3000,
        keep_alive_secs=1200,
        on_connection_interrupted=interrupted_handler,
        on_connection_resumed=resumed_handler)

scheduler = sched.scheduler(time.time, time.sleep)
sentinel = threading.Event()

island = Island(config, iot, scheduler, sentinel, virtual=args.virtual)

modules = [
    Weather(island),
    WeatherStation(island),
    Printer(island),
示例#14
0
        imageReader(name)
    except Exception as e:
        exit(e)


if __name__ == '__main__':
    # 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=ENDPOINT,
        cert_filepath=CERTIFICATE,
        pri_key_filepath=PRIVATE_KEY,
        client_bootstrap=client_bootstrap,
        ca_filepath=ROOT_CA,
        on_connection_interrupted=on_connection_interrupted,
        on_connection_resumed=on_connection_resumed,
        client_id=CLIENT_ID,
        clean_session=False,
        keep_alive_secs=6)
    print("Connecting to {} with client ID '{}'...".format(
        ENDPOINT, CLIENT_ID))
    connect_future = mqtt_connection.connect()
    # Future.result() waits until a result is available
    connect_future.result()
    print("Connected!")
    try:
        # Subscribe
        print("Subscribing to topic '{}'...".format(TOPIC))
        subscribe_future, packet_id = mqtt_connection.subscribe(
示例#15
0
    if command == "on" or command == "off":
        power(command)
    else:
        print("ERROR: Insufficient command")


if __name__ == "__main__":
    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=conf.get('mqtt', 'endpoint'),
        cert_filepath=conf.get('mqtt', 'cert'),
        pri_key_filepath=conf.get('mqtt', 'key'),
        client_bootstrap=client_bootstrap,
        ca_filepath=conf.get('mqtt', 'root-ca'),
        on_connection_interrupted=on_connection_interrupted,
        on_connection_resumed=on_connection_resumed,
        client_id=conf.get('mqtt', 'client-id'),
        clean_session=False,
        keep_alive_secs=6)

    print("Connecting to {} with client ID '{}'...".format(
        conf.get('mqtt', 'endpoint'), conf.get('mqtt', 'client-id')))

    connect_future = mqtt_connection.connect()

    # Future.result() waits until a result is available
    connect_future.result()
    print("Connected!")
#original line: io.init_logging(getattr(io.LogLevel, args.verbosity), 'stderr')
io.init_logging(getattr(io.LogLevel, io.LogLevel.NoLogs.name), 'stderr')

##connect to AWS
##connection variables
event_loop_group = io.EventLoopGroup(1)
host_resolver = io.DefaultHostResolver(event_loop_group)
client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver)

##Replace the below with necessary value for thing M1 or M2
mqtt_connection = mqtt_connection_builder.mtls_from_path(
    endpoint='a3f97mcy639kgs-ats.iot.us-east-2.amazonaws.com',
    cert_filepath="/home/pi/certs/certificate.pem.crt",
    pri_key_filepath='/home/pi/certs/private.pem.key',
    client_bootstrap=client_bootstrap,
    ca_filepath='/home/pi/certs/AmazonRootCA1.pem',
    on_connection_interrupted=on_connection_interrupted,
    on_connection_resumed=on_connection_resumed,
    client_id="SD_M1-" + str(uuid4()),
    clean_session=False,
    keep_alive_secs=6)

##Redefined endpoint and client as local variables##This is not strictly needed except for print statement.    
endpoint='a3f97mcy639kgs-ats.iot.us-east-2.amazonaws.com'
client_id="SD_M1-" + str(uuid4())

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

connect_future = mqtt_connection.connect()

# Future.result() waits until a result is available
示例#17
0
def connectToAWS(cardID):
    """Connects our device to AWS IoT in order to send information to AWS.

    We use AWS IoT to send messages from the device containing information
    like the card ID, time of scanning, location, etc. To get some of this
    external information like location, we pass them in with command-line
    arguments.
    """

    ############################################################################################
    #                                                                                          #
    #        BELOW IS CODE TO CONNECT TO THE IOT TOPIC AND SEND A MESSAGE TO THE TOPIC         #
    #                                                                                          #
    ############################################################################################
    
    print("Setting up AWS Connections...")

    # Establish an mqtt connection to publish and subscribe to topics on.
    mqtt_connection = mqtt_connection_builder.mtls_from_path(
        endpoint=args.endpoint,
        cert_filepath=args.cert,
        pri_key_filepath=args.key,
        client_bootstrap=client_bootstrap, # Don't know what this is; don't touch it
        ca_filepath=args.root_ca,
        #on_connection_interrupted=on_connection_interrupted, # Don't know what this is; don't touch it
        #on_connection_resumed=on_connection_resumed, # Don't know what this is; don't touch it
        client_id=args.client_id,
        clean_session=False, # Don't know what this is; don't touch it
        keep_alive_secs=6) # Don't know what this is; don't touch it

    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 to the topic passed in from the arguments.
    print("> Subscribing to topic '{}'".format(args.topic))
    subscribe_future, packet_id = mqtt_connection.subscribe(
        topic=args.topic,
        qos=mqtt.QoS.AT_LEAST_ONCE)

    subscribe_result = subscribe_future.result()
    print("> Subscribed with {}".format(str(subscribe_result['qos'])))
    
    ############################################################################################
    #                                                                                          #
    #        BELOW IS WHAT SHOULD BE EDITED TO CHANGE WHAT MESSAGE IS SENT TO THE TOPIC        #
    #                                                                                          #
    ############################################################################################

    # Message JSON <<THIS IS WHAT GETS SENT TO THE TOPIC>>
    msg = {
    "ID": cardID,
    "Location": args.location,
    "Event": args.event,
    "DateTime": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }

    message = json.dumps(msg)
    print("> Publishing message to topic '{}': {}".format(args.topic, message))
    mqtt_connection.publish(
        topic=args.topic,
        payload=message,
        qos=mqtt.QoS.AT_LEAST_ONCE)
    time.sleep(1)

    # Disconnect the connection after our message has been sent.
    disconnect_future = mqtt_connection.disconnect()
    print("Disconnecting from AWS...")
    disconnect_future.result()
示例#18
0
            http_proxy_options=proxy_options,
            ca_filepath=args.root_ca,
            on_connection_interrupted=on_connection_interrupted,
            on_connection_resumed=on_connection_resumed,
            client_id=args.client_id,
            clean_session=False,
            keep_alive_secs=30)

    else:
        mqtt_connection = mqtt_connection_builder.mtls_from_path(
            endpoint=args.endpoint,
            port=args.port,
            cert_filepath=args.cert,
            pri_key_filepath=args.key,
            client_bootstrap=client_bootstrap,
            ca_filepath=args.root_ca,
            on_connection_interrupted=on_connection_interrupted,
            on_connection_resumed=on_connection_resumed,
            client_id=args.client_id,
            clean_session=False,
            keep_alive_secs=30,
            http_proxy_options=proxy_options)

    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!")
示例#19
0
def changeScreens(cardID):
    """Changes the screen shown on the Raspberry Pi Hat.

    Checks to see if the card is in the database and displays
    the corresponding screen.

    We are using the inkywHAT Red/Black/White:
    https://shop.pimoroni.com/products/inky-what?variant=13590497624147 

    Documentation:
    https://github.com/pimoroni/inky 

    TODO: Change the screen back to "please scan card" after a set amount of time has passed. 
    Needs some multithreading or something to accomplish that I think.
    """
    
    ######## Pi Hat Setup ########
    print("Changing screens...")

    inkywhat = InkyWHAT('black')
    
    # Establish a new connection for checking if the card is in the DB.
    # Not sure if this is required, but this is the easiest way I could find to do it.
    # Copy-pasted from the earlier mqtt_connection variable.
    pi_hat_connection = mqtt_connection_builder.mtls_from_path(
        endpoint=args.endpoint,
        cert_filepath=args.cert,
        pri_key_filepath=args.key,
        client_bootstrap=client_bootstrap,
        ca_filepath=args.root_ca,
        client_id=args.client_id,
        clean_session=False, 
        keep_alive_secs=6)

    # Query the DB to see if that card is in it.
    # Use the config defined at the top of the file to hide connection information.
    cardInDBResult = False
    try:
        mysqlConn = mysql.connector.connect(host=config['database']['dbHostname'],
                                            database=config['database']['dbName'],
                                            user=config['database']['dbUsername'],
                                            password=config['database']['dbPassword'])
        if mysqlConn.is_connected():
            print("Connected to database...")
            cursor = mysqlConn.cursor()
            cursor.execute("select database();")
            record = cursor.fetchone()
            lookForCardQuery = "SELECT * FROM Student_ID WHERE SID = " + str(cardID)
            cursor.execute(lookForCardQuery)
            records = cursor.fetchall()
            if(cursor.rowcount > 0):
                cardInDBResult = True
    except Error as e:
        print("Error while connecting to MySQL Database", e)
    finally:
        if (mysqlConn.is_connected()):
            cursor.close()
            mysqlConn.close()
            print("Disconnected from database...")

    # If the card is in the database, set the screen to be shown to the "Welcome" screen
    if (cardInDBResult):
        print("ID Found - Displaying Welcome...")
        imgURL = "../../../qrcode/displayScreens/welcome_bw.png"
        im = Image.open(imgURL)

        # Resizing the image so it fits to the screen
        # This is specific to the inkywhat, otherwise it claims that there is a size-mismatch.
        size = (400,300)
        out = im.resize(size)
        out.save('../../../qrcode/resize-output.png')
        img = Image.open('../../../qrcode/resize-output.png')
        pal_img = Image.new("P", (1, 1))
        pal_img.putpalette((255, 255, 255, 0, 0, 0, 255, 0, 0) + (0, 0, 0) * 252)
        img = img.convert("RGB").quantize(palette=pal_img)
        
    # If the card is not in the database, make a QR code and show the "QR Code" screen
    elif (not cardInDBResult):
        print("ID Not Found - Displaying Registration...")
        imgURL = "../../../qrcode/displayScreens/qrscan_bw.png"
        displayURL = "../../../qrcode/qrCodeScreenMerged.png"

        # Generate a QR Code Object
        qr = qrcode.QRCode(
            version=None,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=3,
            border=2,
        )

        # Generate the URL the code points to and add it to the QR Code
        wURL = config['aws_endpoints']['registrationSite'] + str(cardID)
        qr.add_data(wURL)
        qr.make(fit=True)
        img = qr.make_image(fill_color="black", back_color="white")

        # Save the generated QR Code to the proper folder
        img.save('../../../qrcode/qr_image.png')
        im = Image.open(imgURL)

        # Resizing the image so it fits to the screen
        size = (400,300)
        out = im.resize(size)
        out.save('../../../qrcode/resize-output.png')

        # We are using ImageMagick installed on the Raspberry Pi to 
        # composite our generated QR Code onto the premade image
        # with this subprocess call. This could be changed to a 
        # bash script called in the same way.
        s = pyshorteners.Shortener(Shorteners.TINYURL)
        shortLink = s.short(wURL)
        composeQRCodeOntoImageCommand = 'composite -blend 100 -gravity center ../../../qrcode/qr_image.png ../../../qrcode/resize-output.png ../../../qrcode/qrCodeScreenMerged.png'
        composeURLOntoImageCommand = 'convert ../../../qrcode/qrCodeScreenMerged.png -gravity North -pointsize 24 -annotate +0+215 \'' + shortLink + '\' ../../../qrcode/qrCodeScreenMerged.png'
        subprocess.call(composeQRCodeOntoImageCommand, shell=True)
        subprocess.call(composeURLOntoImageCommand, shell=True)

        img = Image.open(displayURL)

        # Continue resizing, inkywhat complains otherwise.
        pal_img = Image.new("P", (1, 1))
        pal_img.putpalette((255, 255, 255, 0, 0, 0, 255, 0, 0) + (0, 0, 0) * 252) 
        img = img.convert("RGB").quantize(palette=pal_img)

    # Update the image on the screen and show it.
    inkywhat.set_image(img)
    inkywhat.set_border('white')
    inkywhat.show()
    print("Finished changing screens...")
示例#20
0
PATH_TO_CERT = "certificates/548fda031d-certificate.pem.crt"
PATH_TO_KEY = "certificates/548fda031d-private.pem.key"
PATH_TO_ROOT = "certificates/root.pem"
MESSAGE = "hello hyunsu"
TOPIC = "test/testing"
RANGE = 5

# 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=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!")
# Publish message to server desired number of times.
print('Begin Publish')
# for i in range (RANGE):
#     data = "{} [{}]".format(MESSAGE, i+1)
#     message = {"message" : data}
示例#21
0
    print("starting")

    # start AWS IOT logging to stderr
    # options are NoLogs, Fatal, Error, Warn, Info, Debug, Trace
    io.init_logging(io.LogLevel.Error, 'stderr')

    # 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=endpoint,
        cert_filepath=cert,
        pri_key_filepath=key,
        client_bootstrap=client_bootstrap,
        ca_filepath=root_ca,
        client_id=client_id,
        clean_session=True,
        keep_alive_secs=6,
        http_proxy_options=None)

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

    connected_future = mqtt_connection.connect()

    shadow_client = iotshadow.IotShadowClient(mqtt_connection)

    # Wait for connection to be fully established.
    connected_future.result()
    pStdErr("Connected to {}!".format(endpoint))