Coverage for flask/src/rasp_water/weather_sensor.py: 16%
37 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-28 13:51 +0900
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-28 13:51 +0900
1#!/usr/bin/env python3
2"""
3雨量データを取得します。
5Usage:
6 weather_sensor.py [-c CONFIG] [-p HOURS] [-D]
8Options:
9 -c CONFIG : CONFIG を設定ファイルとして読み込んで実行します。[default: config.yaml]
10 -p HOURS : 集計する時間を指定します。[default: 12]
11 -D : デバッグモードで動作します。
12"""
14import datetime
15import logging
17import my_lib.sensor_data
18import my_lib.time
19import rasp_water.scheduler
22def hours_since_last_watering():
23 schedule_data = rasp_water.scheduler.schedule_load()
25 now = my_lib.time.now()
27 last_date = []
28 for schedule in schedule_data:
29 if not schedule["is_active"]:
30 continue
31 time_str = schedule["time"]
32 hour, minute = map(int, time_str.split(":"))
34 for days_ago in range(7):
35 day = now - datetime.timedelta(days=days_ago)
36 wday_index = day.weekday()
37 if schedule["wday"][wday_index]:
38 scheduled_date = day.replace(hour=hour, minute=minute, second=0, microsecond=0)
39 last_date.append(scheduled_date)
40 break
42 if len(last_date) == 0:
43 return 24 * 7
45 minutes = (now - max(last_date)).total_seconds() / 60
47 hours = int(minutes // 60)
48 if minutes % 60 >= 30:
49 hours += 1
51 return hours
54def get_rain_fall_sum(config, hours):
55 return my_lib.sensor_data.get_hour_sum(
56 config["influxdb"],
57 config["weather"]["rain_fall"]["sensor"]["measure"],
58 config["weather"]["rain_fall"]["sensor"]["hostname"],
59 "rain",
60 hours=hours,
61 )
64def get_rain_fall(config):
65 hours = hours_since_last_watering()
66 rain_fall_sum = get_rain_fall_sum(config, hours)
68 logging.info("Rain fall sum since last watering: %.1f (%d hours)", rain_fall_sum, hours)
70 rainfall_judge = rain_fall_sum > config["weather"]["rain_fall"]["sensor"]["threshold"]["sum"]
71 logging.info("Rain fall sensor judge: %s", rainfall_judge)
73 return (rainfall_judge, rain_fall_sum)
76if __name__ == "__main__":
77 # TEST Code
78 import docopt
79 import my_lib.config
80 import my_lib.logger
81 import my_lib.webapp.config
83 args = docopt.docopt(__doc__)
85 config_file = args["-c"]
86 hours = int(args["-p"])
87 debug_mode = args["-D"]
89 my_lib.logger.init("test", level=logging.DEBUG if debug_mode else logging.INFO)
91 config = my_lib.config.load(config_file)
93 my_lib.webapp.config.init(config)
94 rasp_water.scheduler.init()
96 logging.info("Sum of rainfall is %.1f (%d hours)", get_rain_fall_sum(config, hours), hours)
98 logging.info("Finish.")