Moving smart lights into smart_home to prepare for adding
[python_utils.git] / site_config.py
1 #!/usr/bin/env python3
2
3 from dataclasses import dataclass
4 import logging
5 import platform
6 from typing import Callable, Optional
7
8 import config
9 import presence
10
11 logger = logging.getLogger(__name__)
12 args = config.add_commandline_args(
13     f'({__file__})',
14     'Args related to __file__'
15 )
16 args.add_argument(
17     '--site_config_override_location',
18     default='NONE',
19     const='NONE',
20     nargs='?',
21     choices=('HOUSE', 'CABIN', 'NONE'),
22     help='Where are we, HOUSE, CABIN?',
23 )
24
25
26 @dataclass
27 class SiteConfig(object):
28     location: str
29     network: str
30     network_netmask: str
31     network_router_ip: str
32     presence_location: presence.Location
33     is_anyone_present: Callable[None, bool]
34
35
36 def get_location():
37     """
38     Where are we?
39
40     >>> location = get_location()
41     >>> location == 'HOUSE' or location == 'CABIN'
42     True
43
44     """
45     return get_config().location
46
47
48 def is_anyone_present_wrapper(location: presence.Location):
49     p = presence.PresenceDetection()
50     return p.is_anyone_in_location_now(location)
51
52
53 def get_config():
54     """
55     Get a configuration dataclass with information that is
56     site-specific including the current running location.
57
58     >>> cfg = get_config()
59     >>> cfg.location == 'HOUSE' or cfg.location == 'CABIN'
60     True
61
62     """
63     hostname = platform.node()
64     try:
65         location_override = config.config['site_config_override_location']
66     except KeyError:
67         location_override = 'NONE'
68     if location_override == 'NONE':
69         if '.house' in hostname:
70             location = 'HOUSE'
71         elif '.cabin' in hostname:
72             location = 'CABIN'
73     if location == 'HOUSE':
74         return SiteConfig(
75             location = 'HOUSE',
76             network = '10.0.0.0/24',
77             network_netmask = '255.255.255.0',
78             network_router_ip = '10.0.0.1',
79             presence_location = presence.Location.HOUSE,
80             is_anyone_present = lambda x=presence.Location.HOUSE: is_anyone_present_wrapper(x),
81         )
82     elif location == 'CABIN':
83         return SiteConfig(
84             location = 'CABIN',
85             network = '192.168.0.0/24',
86             network_netmask = '255.255.255.0',
87             network_router_ip = '192.168.0.1',
88             presence_location = presence.Location.CABIN,
89             is_anyone_present = lambda x=presence.Location.CABIN: is_anyone_present_wrapper(x),
90         )
91     else:
92         raise Exception(f'Unknown site location: {location}')
93
94
95 if __name__ == '__main__':
96     import doctest
97     doctest.testmod()