예제 #1
0
def offload_sensor_data(sensor_data):
    logger.info("Saving data to database...")
    count = 0

    # Connect to the database
    ddb = DryadDatabase()
    if ddb.connect(CUSTOM_DATABASE_NAME) == False:
        logger.error("Failed to update device info")
        return False

    for node_data in sensor_data:
        source_id   = node_data['node_id']
        data        = node_data['data']

        for sensor_data in data:
            ts = sensor_data['time']
            read_data = '{ "type" : "%s", "value" : %f }' % ( sensor_data["sensor"], sensor_data["reading"] )
            ddb.add_data(read_data, source=source_id, timestamp=ts)

            if (count % 5) == 0:
                logger.info("Data saved:{0} records".format(count))

            count += 1

    # Disconnect from the database
    ddb.disconnect()

    return True
예제 #2
0
def load_sensor_nodes():
    ddb = DryadDatabase()
    if ddb.connect(CUSTOM_DATABASE_NAME) == False:
        logger.error("Load Sensor Node Info Failed")
        return False

    node_list = ddb.get_nodes('C_TYPE = "UNKNOWN" OR C_TYPE = "SENSOR"')

    ddb.disconnect()
    
    return node_list
예제 #3
0
def save_new_sensor_nodes(node_list):
    ddb = DryadDatabase()
    if ddb.connect(CUSTOM_DATABASE_NAME) == False:
        logger.error("Load Sensor Node Info Failed")
        return False

    for address, name in node_list:
        # If this device already exists, then skip it
        if ddb.get_node_info(address):
            continue

        ddb.add_node_info(address, name, "UNKNOWN")

    ddb.disconnect()

    return True
예제 #4
0
def init():
    # Initialize the logger
    if init_logger() == False:
        logger.error("Initialization Failed")
        return False

    # Setup the database
    ddb = DryadDatabase()
    if ddb.connect(CUSTOM_DATABASE_NAME) == False:
        logger.error("Initialization Failed")
        return False

    if ddb.setup() == False:
        logger.error("Initialization Failed")
        return False

    ddb.disconnect()

    logger.info("Initialization Finished")
    return True
예제 #5
0
def gather_sensor_data(address, name, ntype, nclass):
    # Skip unnamed devices
    if name == "":
        return

    # If the device type is UNKNOWN, then we have to know what kind
    #   of device we're dealing with and remember it for the future
    if ntype == "UNKNOWN":
        nclass = "UNKNOWN"
        device = None

        ddb = DryadDatabase()
        if ddb.connect(CUSTOM_DATABASE_NAME) == False:
            logger.error("Failed to update device info")
            return

        device_type = ble.check_device_type(address, name)
        if device_type == "BLUNO_BEETLE" or device_type == "PARROT_FP":
            nclass = device_type
            if ddb.update_node(address, node_type="SENSOR", node_class=device_type) == False:
                logger.error("Failed to update device info")

        ddb.disconnect()

 
    # Setup the device object based on the node class
    if nclass == "BLUNO_BEETLE":
        # Initialize our Bluno device
        device = bluno_ble.Bluno(address)

    elif nclass == "PARROT_FP":
        # Initialize our Parrot Flower Power device
        device = parrot_ble.Parrot(address)

    else:
        logger.error("Cannot initialize unknown device class")
        return
            
    # Obtain the event handle
    handle_event = device.get_event_hdl()

    # Start the device
    if device.start() == False:
        logger.error("Sensor Node Initialize failed")
        device.stop()
        return

    # Read the device name
    logger.info("Reading device name...")
    logger.info("Name:{0}".format(device.get_name()))

    if nclass == "PARROT_FP":
        if USE_LED:
            device.trigger_led(True)
            logger.info("Triggering Parrot flower LED")

    logger.info("Reading data...")
    counter = MAX_SAMPLE_COUNT
    try:
        stop_time = time.time() + 12.0
        while (counter > 0):
            handle_event.wait(2)
            counter -= 1
            if time.time() > (stop_time):
                logger.info("Time limit reached.")
                break
            handle_event.clear()
    except KeyboardInterrupt:
        logger.exception("Keyboard Interrupt detected")

    if nclass == "PARROT_FP":
        if USE_LED:
            device.trigger_led(False)

    logger.info("Finishing up live measurements...")
    device.stop()

    logger.info("Done.")

    return {"node_id" : name, "data" : device.get_data()}
예제 #6
0
    def handle_req_download(self, link, content):
        limit = None
        start_id = None
        end_id = None
        unsent_only = False

        download_args = content.split(',')

        # Parse our argument list
        if len(download_args) > 0:
            for arg in download_args:
                # TODO This part needs to be cleaned up

                if arg.lower().startswith("limit="):
                    limit = int(arg.split('=')[1])

                elif arg.lower().startswith("start_id="):
                    # TODO Not yet used!
                    start_id = int(arg.split('=')[1])

                elif arg.lower().startswith("end_id="):
                    # TODO Not yet used!
                    end_id = int(arg.split('=')[1])

                elif arg.lower().startswith("unsent_only="):
                    # TODO Not yet used!
                    val = arg.split('=')[1]
                    if val == "True":
                        unsent_only = True
                    else:
                        unsent_only = False

        db = DryadDatabase()
        if db.connect(self.dbname) == False:
            return False

        if limit == None:
            limit = 20

        records = db.get_data(limit=limit)
        while records != None:
            proc_ids = []
            resp_data = []

            # Compose our response content
            for rec in records:
                proc_ids.append(rec[0])
                resp_data.append({
                    "timestamp": rec[2],
                    "source": rec[1],
                    "data": json.loads(rec[3])
                })

            # Send our response
            try:
                resp = '"content" : '
                resp += json.dumps(resp_data)
                if link.send_response(resp) == False:
                    self.logger.error("Failed to send response")
                    db.disconnect()
                    return False
            except:
                self.logger.error(
                    "Failed to send response due to an exception")
                db.disconnect()
                return False

            # Once data is sent successfully, we can mark off the records whose
            #   IDs we took note of earlier in our database
            for rec_id in proc_ids:
                db.set_data_uploaded(rec_id)

            # Get a new batch of unsent records
            records = db.get_data(20)

            if len(records) < 1:
                self.logger.info("No more data to send")
                break

        db.disconnect()

        return True