Coverage for src/unit_cooler/webui/api/cooler_stat.py: 100%

31 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-28 08:08 +0000

1#!/usr/bin/env python3 

2""" 

3冷却システムを作業状況を WebUI に渡します。 

4 

5Usage: 

6 cooler_stat.py [-c CONFIG] [-D] 

7 

8Options: 

9 -c CONFIG : CONFIG を設定ファイルとして読み込んで実行します。 [default: config.yaml] 

10 -D : デバッグモードで動作します。 

11""" 

12 

13import logging 

14import os 

15 

16import flask 

17import my_lib.flask_util 

18import my_lib.sensor_data 

19import my_lib.webapp.config 

20 

21import unit_cooler.controller.engine 

22 

23blueprint = flask.Blueprint("cooler-stat", __name__, url_prefix=my_lib.webapp.config.URL_PREFIX) 

24 

25api_base_url = None 

26 

27 

28def init(api_base_url_): 

29 global api_base_url # noqa: PLW0603 

30 

31 api_base_url = api_base_url_ 

32 

33 

34def watering(config, day_before): 

35 day_offset = 7 if os.environ.get("DUMMY_MODE", "false") == "true" else 0 

36 

37 amount = my_lib.sensor_data.get_day_sum( 

38 config["controller"]["influxdb"], 

39 config["controller"]["watering"]["measure"], 

40 config["controller"]["watering"]["hostname"], 

41 "flow", 

42 1, 

43 day_before, 

44 day_offset, 

45 ) 

46 

47 return { 

48 "amount": amount, 

49 "price": amount * config["controller"]["watering"]["unit_price"] / 1000.0, 

50 } 

51 

52 

53def watering_list(config): 

54 return [watering(config, i) for i in range(10)] 

55 

56 

57def get_last_message(message_queue): 

58 # NOTE: 現在の実際の制御モードを取得する。 

59 while not message_queue.empty(): 

60 get_last_message.last_message = message_queue.get() 

61 return get_last_message.last_message 

62 

63 

64get_last_message.last_message = None 

65 

66 

67def get_stats(config, message_queue): 

68 # NOTE: データを受け渡しのは面倒なので、直接計算してしまう 

69 mode = unit_cooler.controller.engine.judge_cooling_mode(config) 

70 

71 return { 

72 "watering": watering_list(config), 

73 "sensor": mode["sense_data"], 

74 "mode": get_last_message(message_queue), 

75 "cooler_status": mode["cooler_status"], 

76 "outdoor_status": mode["outdoor_status"], 

77 } 

78 

79 

80@blueprint.route("/api/stat", methods=["GET"]) 

81@my_lib.flask_util.support_jsonp 

82def api_get_stats(): 

83 config = flask.current_app.config["CONFIG"] 

84 message_queue = flask.current_app.config["MESSAGE_QUEUE"] 

85 

86 return flask.jsonify(get_stats(config, message_queue)) 

87 

88 

89if __name__ == "__main__": 

90 # TEST Code 

91 import docopt 

92 import my_lib.config 

93 import my_lib.logger 

94 import my_lib.pretty 

95 

96 args = docopt.docopt(__doc__) 

97 

98 config_file = args["-c"] 

99 debug_mode = args["-D"] 

100 

101 my_lib.logger.init("test", level=logging.DEBUG if debug_mode else logging.INFO) 

102 

103 config = my_lib.config.load(config_file) 

104 

105 logging.info(my_lib.pretty.format(watering_list(config)))