예제 #1
0
def get_statistic_item(
    device_id: str,
    timestamp: float,
    db: Session = Depends(get_db_generator),
):
    """
    Get a specific statistic.

    Arguments:
        device_id {str} -- Device id.
        timestamp {float} -- Timestamp when the device registered the information.
        db {Session} -- Database session.

    Returns:
        Union[StatisticSchema, NoItemFoundException] -- Statistic instance defined by device_id and
        timestamp or an exception in case there's no matching statistic.
    """
    try:
        return get_statistic(
            db_session=db,
            device_id=device_id,
            datetime=convert_timestamp_to_datetime(timestamp),
        )
    except NoResultFound:
        raise NoItemFoundException()
예제 #2
0
def update_statistic_item(
    device_id: str,
    timestamp: float,
    new_statistic_information: Dict = {},
    db: Session = Depends(get_db_generator),
):
    """
    Modify a specific statistic.

    Arguments:
        device_id {str} -- Device id.
        timestamp {float} -- Timestamp when the device registered the information.
        new_statistic_information {Dict} -- New statistic information.
        db {Session} -- Database session.

    Returns:
        Union[StatisticSchema, NoItemFoundException, GenericException] -- Updated statistic
        instance defined by device_id and datetime or an exception in case there's no
        matching statistic.
    """
    try:
        return update_statistic(
            db_session=db,
            device_id=device_id,
            datetime=convert_timestamp_to_datetime(timestamp),
            new_statistic_information=new_statistic_information,
        )

    except NoResultFound:
        raise NoItemFoundException()
    except DataError as e:
        raise GenericException(e)
예제 #3
0
def create_statistic_item(
    device_id: str,
    statistic_information: Dict = {},
    db: Session = Depends(get_db_generator),
):
    """
    Create new statistic entry.

    Arguments:
        device_id {str} -- Device id which sent the statistic.
        statistic_information {Dict} -- New statistic information.
        db {Session} -- Database session.

    Returns:
        Union[StatisticSchema, ItemAlreadyExist] -- Statistic instance that was added
        to the database or an exception in case a statistic already exists.
    """
    try:
        # Format input data
        statistic_information["device_id"] = device_id
        statistic_information["datetime"] = convert_timestamp_to_datetime(
            statistic_information["datetime"]
        )
        statistic_information["statistic_type"] = get_enum_type(
            statistic_information["statistic_type"]
        )

        return create_statistic(
            db_session=db, statistic_information=statistic_information
        )
    except IntegrityError:
        raise ItemAlreadyExist()
예제 #4
0
def get_all_device_statistics_items(
    device_id: str,
    datefrom: Optional[str] = Query(None),
    dateto: Optional[str] = Query(None),
    timestampfrom: Optional[float] = Query(None),
    timestampto: Optional[float] = Query(None),
    db: Session = Depends(get_db_generator),
):
    """
    Get all statistics of a specific device.

    Arguments:
        device_id {str} -- Device id.
        datefrom {Optional[str]} -- Datetime to show information from.
        dateto {Optional[str]} -- Datetime to show information to.
        timestampfrom {Optional[float]} -- Timestamp to show information from.
        timestampto {Optional[float]} -- Timestamp to show information from.
        db {Session} -- Database session.

    Returns:
        List[StatisticSchema] -- Statistic instances defined by device_id and
        datetime range.
    """
    from_datetime = datefrom
    to_datetime = dateto

    if not from_datetime and timestampfrom:
        from_datetime = convert_timestamp_to_datetime(timestampfrom)

    if not to_datetime and timestampto:
        to_datetime = convert_timestamp_to_datetime(timestampto)

    return get_statistics_from_to(
        db_session=db,
        device_id=device_id,
        from_date=from_datetime,
        to_date=to_datetime,
    )
예제 #5
0
def test_get_statistic():
    people_with_mask = 4
    people_without_mask = 7
    # now = datetime(2021, 1, 4, 17, 22, 51, 514455, tzinfo=timezone.utc)
    now = convert_timestamp_to_datetime(1609780971.514455)

    statistic = get_statistic(db_session=database_session,
                              device_id=DEVICE_ID,
                              datetime=now)

    assert statistic.device_id == DEVICE_ID
    assert statistic.datetime == now.replace(tzinfo=None)
    assert statistic.statistic_type == StatisticTypeEnum.ALERT
    assert statistic.people_with_mask == people_with_mask
    assert statistic.people_without_mask == people_without_mask
    assert statistic.people_total == people_with_mask + people_without_mask
예제 #6
0
def test_create_same_statistic():
    people_with_mask = 4
    people_without_mask = 7
    # now = datetime(2021, 1, 4, 17, 22, 51, 514455, tzinfo=timezone.utc)
    now = convert_timestamp_to_datetime(1609780971.514455)

    with pytest.raises(IntegrityError):
        stat_info = {
            "device_id": DEVICE_ID,
            "datetime": now,
            "statistic_type": StatisticTypeEnum.ALERT,
            "people_with_mask": people_with_mask,
            "people_without_mask": people_without_mask,
            "people_total": people_with_mask + people_without_mask,
        }

        create_statistic(db_session=database_session,
                         statistic_information=stat_info)
예제 #7
0
def test_create_another_statistic():
    people_with_mask = 5
    people_without_mask = 8
    # now = datetime(2021, 1, 5, 17, 22, 51, 514455, tzinfo=timezone.utc)
    now = convert_timestamp_to_datetime(1609867371.514455)

    stat_info = {
        "device_id": DEVICE_ID,
        "datetime": now,
        "statistic_type": StatisticTypeEnum.ALERT,
        "people_with_mask": people_with_mask,
        "people_without_mask": people_without_mask,
        "people_total": people_with_mask + people_without_mask,
    }

    statistic = create_statistic(db_session=database_session,
                                 statistic_information=stat_info)

    assert statistic.device_id == DEVICE_ID
    assert statistic.datetime == now.replace(tzinfo=None)
    assert statistic.statistic_type == StatisticTypeEnum.ALERT
    assert statistic.people_with_mask == people_with_mask
    assert statistic.people_without_mask == people_without_mask
    assert statistic.people_total == people_with_mask + people_without_mask
예제 #8
0
def process_message(database_session, msg):
    """
    Process message sent to topic.

    Arguments:
        database_session {Session} -- Database session.
        msg {str} -- Received message.
    """
    message = json.loads(msg.payload.decode())

    topic = msg.topic
    if topic == "hello":
        # Register new Jetson device
        device_id = message["device_id"]

        try:
            device_information = {
                "id": device_id,
                "description": message["description"],
            }
            device = create_device(
                db_session=database_session,
                device_information=device_information,
            )
            print("Added device")
        except IntegrityError:
            print(f"A device with id={device_id} already exists")

    elif topic in ["alerts", "receive-from-jetson"]:
        try:
            # Receive alert or report and save it to the database
            statistic_information = {
                "device_id": message["device_id"],
                "datetime":
                convert_timestamp_to_datetime(message["timestamp"]),
                "statistic_type": get_enum_type(topic),
                "people_with_mask": message["people_with_mask"],
                "people_without_mask": message["people_without_mask"],
                "people_total": message["people_total"],
            }

            statistic = create_statistic(
                db_session=database_session,
                statistic_information=statistic_information,
            )

            print(f"Added statistic")
        except IntegrityError:
            print(f"Error, the statistic already exist")

    elif topic == "video-files":
        try:
            print(f"Adding files for device_id: {message['device_id']}")
            new_information = {"file_server_address": message["file_server"]}
            update_device(db_session=database_session,
                          device_id=message["device_id"],
                          new_device_information=new_information)
            update_files(db_session=database_session,
                         device_id=message["device_id"],
                         file_list=message["file_list"])
        except Exception as e:
            print(f"Exception trying to update files: {e}")

    elif topic == "send-to-jetson":
        # Just monitoring this channel, useful for debugging
        print(f"Detected info sent to device_id: {message['device_id']}")