コード例 #1
0
    def process_hour_value(self, hour):
        day = DayModel.find_by_id(hour.day_id)
        after_datetime = (datetime.fromtimestamp(day.date_timestamp) + timedelta(hours=hour.hour))
        before_datetime = (datetime.fromtimestamp(day.date_timestamp) + timedelta(hours=hour.hour + 1))
        events = EventModel.filter(data_type=DataTypeEnum.WATER_USAGE.value,
                                   after_timestamp=after_datetime.timestamp(),
                                   before_timestamp=before_datetime.timestamp(),
                                   graph_id=2)
        total_water_usage = None
        if len(events) != 0 or datetime.now() > before_datetime:
            total_water_usage = 0
        for event in events:
            usage = UsageModel.find_by_id(event.usage_id)
            if usage.consumption_type.is_water_per_hour():
                if event.data == 'True':
                    # @todo: This now ignores the fact that a usage can be spread out over multiple hours and
                    # just adds it to the hour at wich the usage was initiated
                    start = event.timestamp
                    end = EventModel.find_next_false(event).timestamp

                    duration_in_seconds = end - start
                    duration_in_hours = duration_in_seconds / (60 * 60)
                    total_water_usage += duration_in_hours * int(usage.consumption_amount)

            elif usage.consumption_type.is_water_per_usage():
                total_water_usage += int(usage.consumption_amount)

        # is_final_value = before_datetime.timestamp() < datetime.now().timestamp()
        is_final_value = False
        if total_water_usage is not None:
            hour.update(total_water_usage, is_final_value)
コード例 #2
0
    def post(self):
        errors = []
        if 'usage_id' in request.form.keys():
            usage_id = request.form['usage_id']
            data_type = request.form['data_type']
            data = request.form['data']
        else:
            request_data = json.loads(request.data)
            usage_id = request_data['usage_id']
            data_type = request_data['data_type']
            data = request_data['data']

        usage = UsageModel.find_by_id(usage_id)
        if usage is None:
            errors.append(
                Error(
                    "Cannot find usage with id: {}".format(usage_id),
                    "UsageModel.find_by_id({}) returns None".format(usage_id),
                    404, "https://en.wikipedia.org/wiki/HTTP_404"))
        if UnitEnum.has_value(data_type):
            data_type = UnitEnum(data_type)
        else:
            errors.append(
                Error(
                    '"{}" is not a valid unit type.'.format(data_type),
                    "UnitEnum.has_value({}) returned False".format(data_type),
                    400, "https://en.wikipedia.org/wiki/HTTP_400"))

        if len(errors) > 0:
            all_errors_in_json = [error.to_json() for error in errors]
            return {"errors": all_errors_in_json}, 422

        if usage.unit != data_type:
            error = Error(
                'The unit type of the usage with id "{}" does not match the given "{}".'
                .format(usage_id,
                        data_type), "usage.unit does not equal data_type.",
                422, "https://en.wikipedia.org/wiki/HTTP_422")
            return {"errors": error.to_json()}, 422

        event = EventModel(usage_id, data, round(datetime.now().timestamp()))
        event.save_to_db()
        return event.to_json(), 201
コード例 #3
0
    def fill_status(self):
        last_event = None
        for usage in self.usages:
            event = EventModel.find_latest_by_usage_id(usage.id)
            if event is None:
                pass
            elif last_event is None:
                last_event = event
            elif last_event.timestamp > event:
                last_event = event

        if last_event is not None:
            usage = UsageModel.find_by_id(last_event.usage_id)
            self.last_use = {
                'last_use_timestamp': last_event.timestamp,
                'data_type': usage.unit.value,
                'data': float(last_event.data),
                'usage_id': last_event.usage_id
            }
コード例 #4
0
    def process_hour_value(self, hour):
        day = DayModel.find_by_id(hour.day_id)
        after_datetime = (datetime.fromtimestamp(day.date_timestamp) +
                          timedelta(hours=hour.hour))
        before_datetime = (datetime.fromtimestamp(day.date_timestamp) +
                           timedelta(hours=hour.hour + 1))
        events = EventModel.filter(
            data_type=DataTypeEnum.TEMPERATURE.value,
            after_timestamp=after_datetime.timestamp(),
            before_timestamp=before_datetime.timestamp(),
            graph_id=1)
        temperature_sum = 0
        for event in events:
            temperature_sum += float(event.data)
        if temperature_sum == 0:
            value = None
        else:
            value = temperature_sum / len(events)

        is_final_value = before_datetime.timestamp() < datetime.now(
        ).timestamp()
        hour.update(value, is_final_value)
コード例 #5
0
def seed():
    print('Seeding...')
    db.init_app(app)
    if not ItemModel.find_by_id(1):
        items = []

        # START CREATING ITEMS
        print('Creating items...')
        items.append(ItemModel('Heating', 'comment'))
        items.append(
            UsageModel(1, 1, UsageTypeEnum.KILOWATT, 5,
                       '127.0.0.1:5000/item/1', 'PERCENTAGE', 0, 1))

        items.append(ItemModel('staande_lamp_1', 'staande lamp = beste lamp'))
        items.append(
            UsageModel(2, 2, UsageTypeEnum.KILOWATT, 1,
                       '127.0.0.1:5000/item/5', 'TOGGLE', 0, 1))

        items.append(ItemModel('staande_lamp_2', 'staande lamp = beste lamp'))
        items.append(
            UsageModel(3, 3, UsageTypeEnum.KILOWATT, 1,
                       '127.0.0.1:5000/item/3', 'TOGGLE', 0, 1))

        items.append(
            ItemModel('slaapkamer_verlichting',
                      'verlichting in de slaapkamer'))
        items.append(
            UsageModel(4, 4, UsageTypeEnum.KILOWATT, 1,
                       '127.0.0.1:5000/item/4', 'TOGGLE', 0, 1))

        items.append(ItemModel('lamp_nachtkastje', 'lamp op nachtkastje'))
        items.append(
            UsageModel(5, 5, UsageTypeEnum.KILOWATT, 1,
                       '127.0.0.1:5000/item/5', 'TOGGLE', 0, 1))

        items.append(ItemModel('toilet', 'toilet in badkamer'))
        items.append(
            UsageModel(6, 6, UsageTypeEnum.WATER_PER_USAGE, 9,
                       '127.0.0.1:5000/item/6', 'TOGGLE', 0, 1))

        items.append(ItemModel('douche', 'douche'))
        items.append(
            UsageModel(7, 7, UsageTypeEnum.WATER_PER_HOUR, 9,
                       '127.0.0.1:5000/item/7', 'TOGGLE', 0, 1))

        items.append(ItemModel('vaatwasser', ''))
        items.append(
            UsageModel(8, 8, UsageTypeEnum.WATER_PER_USAGE, 10,
                       '127.0.0.1:5000/item/8', 'TOGGLE', 0, 1))

        items.append(ItemModel('wasmachine', ''))
        items.append(
            UsageModel(9, 9, UsageTypeEnum.WATER_PER_USAGE, 13,
                       '127.0.0.1:5000/item/9', 'TOGGLE', 0, 1))

        items.append(ItemModel('droger', ''))
        items.append(
            UsageModel(10, 10, UsageTypeEnum.KILOWATT, 9,
                       '127.0.0.1:5000/item/10', 'TOGGLE', 0, 1))

        items.append(ItemModel('badkamer verlichting', ''))
        items.append(
            UsageModel(11, 11, UsageTypeEnum.KILOWATT, 1,
                       '127.0.0.1:5000/item/11', 'TOGGLE', 0, 1))

        # START CREATING GROUPS
        print('Creating groups...')
        items.append(GroupModel('Huiskamer', True))
        items.append(GroupModel('Slaapkamer', True))
        items.append(GroupModel('Badkamer', True))
        items.append(GroupModel('Verlichting', False))

        # START ADDING ITEMS TO GROUPS
        print('Assigning items to groups...')
        items.append(ItemGroupModel(2, 1))
        items.append(ItemGroupModel(3, 1))
        items.append(ItemGroupModel(8, 1))
        items.append(ItemGroupModel(4, 2))
        items.append(ItemGroupModel(5, 2))
        items.append(ItemGroupModel(6, 3))
        items.append(ItemGroupModel(7, 3))
        items.append(ItemGroupModel(9, 3))
        items.append(ItemGroupModel(10, 3))
        items.append(ItemGroupModel(11, 3))
        items.append(ItemGroupModel(2, 4))
        items.append(ItemGroupModel(3, 4))
        items.append(ItemGroupModel(4, 4))
        items.append(ItemGroupModel(5, 4))
        items.append(ItemGroupModel(11, 4))

        # START CREATING GRAPHS
        items.append(
            GraphModel('AVERAGE_TEMPERATURE', DataTypeEnum.TEMPERATURE))
        items.append(
            GraphModel('AVERAGE_WATER_USAGE', DataTypeEnum.WATER_USAGE))

        # START CREATING EVENTS
        print('Creating events')
        till_date = datetime.now().timestamp()
        about_one_month = (60 * 60 * 24 * 30)
        from_date = till_date - about_one_month

        # make sure the timestamps are never in the future
        limit_time = lambda timestamp: timestamp if timestamp < till_date else till_date

        keep_going = True
        while keep_going:
            for i in range(0, random.randint(1, 4)):
                toilet_break_timestamp = (
                    datetime.fromtimestamp(from_date) +
                    timedelta(hours=random.randint(5, 12),
                              minutes=random.randint(0, 60),
                              seconds=random.randint(0, 60))).timestamp()
                items.append(
                    EventModel(6, 'True', limit_time(toilet_break_timestamp),
                               2))

            for i in range(0, 4):
                daily_shower_start_timestamp = (
                    datetime.fromtimestamp(from_date) +
                    timedelta(hours=random.randint(5, 12),
                              minutes=random.randint(0, 60),
                              seconds=random.randint(0, 60))).timestamp()
                items.append(
                    EventModel(7, 'True',
                               limit_time(daily_shower_start_timestamp), 2))
                daily_shower_end_timestamp = (
                    datetime.fromtimestamp(daily_shower_start_timestamp) +
                    timedelta(minutes=random.randint(5, 15),
                              seconds=random.randint(0, 60))).timestamp()
                items.append(
                    EventModel(7, 'False',
                               limit_time(daily_shower_end_timestamp), 2))
            for i in range(0, 24):
                if not keep_going:
                    break

                for y in range(0, 10):
                    if from_date > till_date:
                        keep_going = False
                        break
                    temp = 0
                    if i in [1, 2, 3, 4, 5, 15]:
                        temp = 15
                    elif i in [0, 14]:
                        temp = 16
                    elif i in [6, 12, 24, 13]:
                        temp = 18
                    elif i in [7, 8, 9, 17, 18, 19, 20, 21, 22]:
                        temp = 21
                    elif i in [10, 23]:
                        temp = 20
                    elif i in [11, 16]:
                        temp = 19

                    items.append(
                        EventModel(1, temp * random.uniform(0.9, 1.1),
                                   from_date, 1))
                    from_date += 6 * 60

        print('inserting data into db, this may take a while...')
        current = 1
        total = len(items)

        # one last flush of the toilet at the current timestamp
        items.append(EventModel(6, 'True', till_date, 2))
        for item in items:
            print('{} out of {}'.format(current, total))
            item.save_to_db()
            current += 1
コード例 #6
0
def update_seed():
    db.init_app(app)
    items = []
    till_date = datetime.now().timestamp()

    # make sure the timestamps are never in the future
    limit_time = lambda timestamp: timestamp if timestamp < till_date else till_date

    # getting highest timestamp value in Event's table. Add 6 minutes to that and use that as the first timestamp.
    from_date = (db.session.query(db.func.max(EventModel.timestamp)).first()[0]
                 )  #md + (6 * 60)

    keep_going = True
    first_time = True
    while keep_going:
        for i in range(0, random.randint(1, 4)):
            toilet_break_timestamp = (
                datetime.fromtimestamp(from_date) +
                timedelta(hours=random.randint(5, 12),
                          minutes=random.randint(0, 60),
                          seconds=random.randint(0, 60))).timestamp()
            items.append(
                EventModel(6, 'True', limit_time(toilet_break_timestamp), 2))

        for i in range(0, 4):
            daily_shower_start_timestamp = (
                datetime.fromtimestamp(from_date) +
                timedelta(hours=random.randint(5, 12),
                          minutes=random.randint(0, 60),
                          seconds=random.randint(0, 60))).timestamp()
            items.append(
                EventModel(7, 'True', limit_time(daily_shower_start_timestamp),
                           2))
            daily_shower_end_timestamp = (
                datetime.fromtimestamp(daily_shower_start_timestamp) +
                timedelta(minutes=random.randint(5, 15),
                          seconds=random.randint(0, 60))).timestamp()
            items.append(
                EventModel(7, 'False', limit_time(daily_shower_end_timestamp),
                           2))
        # 24 hours per day
        for i in range(0, 24):
            y = 0
            if first_time:
                i = datetime.fromtimestamp(from_date).hour
                print(i)
                y = (datetime.fromtimestamp(from_date).minute / 6) - 1
                first_time = False
            if not keep_going:
                break

            # 10 values per hour
            while y < 10:
                if from_date > till_date:
                    keep_going = False
                    break
                temp = 0
                if i in [1, 2, 3, 4, 5, 15]:
                    temp = 15
                elif i in [0, 14]:
                    temp = 16
                elif i in [6, 12, 24, 13]:
                    temp = 18
                elif i in [7, 8, 9, 17, 18, 19, 20, 21, 22]:
                    temp = 21
                elif i in [10, 23]:
                    temp = 20
                elif i in [11, 16]:
                    temp = 19

                items.append(
                    EventModel(1, temp * random.uniform(0.9, 1.1), from_date,
                               1))
                from_date += 6 * 60
                y += 1

    print('inserting data into db, this may take a while...')
    current = 1
    total = len(items)

    # one last flush of the toilet at the current timestamp
    items.append(EventModel(6, 'True', till_date, 2))
    for item in items:
        print('{} out of {}'.format(current, total))
        item.save_to_db()
        current += 1
コード例 #7
0
 def get(self, event_id):
     event = EventModel.find_by_id(event_id)
     return event.to_json()
コード例 #8
0
 def get(self):
     all_events = EventModel.find_all() or []
     all_in_json = [event.to_json() for event in all_events]
     return {"events": all_in_json}, 200
コード例 #9
0
def test_event_resource():
    print("####################   TESTING EVENT RESOURCE   ####################")

    # GETTING ALL USAGES
    print("TEST_1 --- GETTING ALL EVENTS")
    uri = "events"
    expected_result = {
        "events": []
    }
    expected_status = 200
    test_get(uri, expected_result, expected_status)

    # POST ONE EVENT
    print("TEST_2 --- POSTING ONE EVENT")
    uri = "events"
    usage_1 = send_get('usages/1')
    event_1 = EventModel(usage_1['id'], 'True', round(datetime.now().timestamp()))
    event_1_json = event_1.to_json()
    event_1_json['id'] = 1
    body = {
        "usage_id": usage_1['id'],
        "data_type": UnitEnum.TOGGLE.value,
        "data": 'True'
    }

    expected_result = event_1_json
    expected_status = 201

    test_post(uri, body, expected_result, expected_status)

    # GETTING ONE EVENT
    print("TEST_3 --- GETTING ONE EVENT")
    uri = "events/1"
    expected_status = 200
    test_get(uri, expected_result, expected_status)

    # GETTING ALL EVENTS
    print("TEST_4 --- GETTING ALL EVENTS")
    uri = "events"
    expected_result = {
        "events": [event_1_json]
    }
    expected_status = 200
    test_get(uri, expected_result, expected_status)

    # POST ONE EVENT
    print("TEST_5 --- POSTING ONE EVENT - BAD REQUEST")
    uri = "events"
    body = {
        "usage_id": 17,
        "data_type": UnitEnum.TOGGLE.value,
        "data": 'True'
    }
    error = Error(
                "Cannot find usage with id: {}".format(17),
                "UsageModel.find_by_id({}) returns None".format(17),
                404,
                "https://en.wikipedia.org/wiki/HTTP_404")
    expected_result = {"errors": [error.to_json()]}
    expected_status = 422
    test_post(uri, body, expected_result, expected_status)

    # POST ONE EVENT
    print("TEST_6 --- POSTING ONE EVENT - BAD REQUEST")
    uri = "events"
    body = {
        "usage_id": 1,
        "data_type": "KILO WHAT?",
        "data": 'True'
    }
    error = Error(
                '"{}" is not a valid unit type.'.format("KILO WHAT?"),
                "UnitEnum.has_value({}) returned False".format("KILO WHAT?"), 400,
                "https://en.wikipedia.org/wiki/HTTP_400"
            )
    expected_result = {"errors": [error.to_json()]}
    expected_status = 422
    test_post(uri, body, expected_result, expected_status)