rhs 0.0.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
rhs-0.0.2/LICENSE ADDED
@@ -0,0 +1,25 @@
1
+ BSD 2-Clause License
2
+
3
+ Copyright (c) 2023, UH Robot House / User Projects
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
20
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
rhs-0.0.2/PKG-INFO ADDED
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.4
2
+ Name: rhs
3
+ Version: 0.0.2
4
+ Summary: Sensor poll using REST API
5
+ Author-email: Patrick Holthaus <patrick.holthaus@googlemail.com>
6
+ License-Expression: BSD-2-Clause
7
+ Project-URL: Homepage, https://gitlab.com/robothouse/rh-projects/hospital-at-home/sensors/
8
+ Project-URL: Bug Tracker, https://gitlab.com/robothouse/rh-projects/hospital-at-home/sensors/issues/
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: oyaml
15
+ Requires-Dist: zfl
16
+ Dynamic: license-file
17
+
18
+ This is work in progress.
19
+
20
+ # Installing/downloading the code
21
+
22
+ To get the code ready, you need to create a virtual environment and install these sources:
23
+
24
+ ```bash
25
+ python3 -mvenv /tmp/test
26
+ source /tmp/test/bin/activate
27
+
28
+ git clone git@gitlab.com:robothouse/rh-projects/hospital-at-home/sensors.git
29
+ cd sensors
30
+ git checkout nodb
31
+ pip install -e .
32
+ ```
33
+
34
+ # Running the code
35
+
36
+ To run the code that communicates directly with the homecentre, you need to set password and username for the home centre and then run the example:
37
+
38
+ ```bash
39
+ export HC_USER=<user>
40
+ export HC_PASSWORD=<password>
41
+ export HC_ADDRESS=<IP of the home centre>
42
+ rhs_monitor -c src/rhs/config/sensors.yaml
43
+ ```
rhs-0.0.2/README.md ADDED
@@ -0,0 +1,26 @@
1
+ This is work in progress.
2
+
3
+ # Installing/downloading the code
4
+
5
+ To get the code ready, you need to create a virtual environment and install these sources:
6
+
7
+ ```bash
8
+ python3 -mvenv /tmp/test
9
+ source /tmp/test/bin/activate
10
+
11
+ git clone git@gitlab.com:robothouse/rh-projects/hospital-at-home/sensors.git
12
+ cd sensors
13
+ git checkout nodb
14
+ pip install -e .
15
+ ```
16
+
17
+ # Running the code
18
+
19
+ To run the code that communicates directly with the homecentre, you need to set password and username for the home centre and then run the example:
20
+
21
+ ```bash
22
+ export HC_USER=<user>
23
+ export HC_PASSWORD=<password>
24
+ export HC_ADDRESS=<IP of the home centre>
25
+ rhs_monitor -c src/rhs/config/sensors.yaml
26
+ ```
@@ -0,0 +1,26 @@
1
+ [project]
2
+ name = "rhs"
3
+ version = "0.0.2"
4
+ authors = [
5
+ { name="Patrick Holthaus", email="patrick.holthaus@googlemail.com" },
6
+ ]
7
+ description = "Sensor poll using REST API"
8
+ readme = "README.md"
9
+ license = "BSD-2-Clause"
10
+ license-files = [ "LICENSE" ]
11
+ requires-python = ">=3.10"
12
+ classifiers = [
13
+ "Programming Language :: Python :: 3",
14
+ "Operating System :: OS Independent",
15
+ ]
16
+ dependencies = [
17
+ "oyaml",
18
+ "zfl"
19
+ ]
20
+
21
+ [project.scripts]
22
+ rhs_monitor = "rhs.monitor:main_cli"
23
+
24
+ [project.urls]
25
+ "Homepage" = "https://gitlab.com/robothouse/rh-projects/hospital-at-home/sensors/"
26
+ "Bug Tracker" = "https://gitlab.com/robothouse/rh-projects/hospital-at-home/sensors/issues/"
rhs-0.0.2/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1,14 @@
1
+ import os
2
+ import yaml
3
+
4
+ baseDir = os.path.dirname(os.path.realpath(__file__))
5
+
6
+ server_config = {}
7
+ with open(os.path.join(baseDir, 'database.yaml')) as config:
8
+ server_config.update(yaml.safe_load(config))
9
+
10
+ locations_config = {}
11
+ locationDir = os.path.join(baseDir, 'Locations')
12
+ for fileName in [os.path.join(locationDir, f) for f in os.listdir(locationDir) if f.endswith('.yaml')]:
13
+ with open(fileName) as config:
14
+ locations_config.update(yaml.safe_load(config))
File without changes
@@ -0,0 +1,61 @@
1
+ import base64
2
+ import json
3
+ import os
4
+ import urllib.request
5
+ import argparse
6
+ import pprint
7
+
8
+ class ZWaveHomeActuator:
9
+
10
+ def __init__(self):
11
+ self._base_url = "http://%(ip)s:80/api/callAction" % {
12
+ "ip": os.environ.get(
13
+ "HC_ADDRESS",
14
+ "10.0.1.114"
15
+ )
16
+ }
17
+ self._user = os.environ.get("HC_USER", "admin")
18
+ self._password = os.environ.get("HC_PASSWORD", "admin")
19
+
20
+
21
+ def _request(self, deviceID, action, value):
22
+ try:
23
+ url = "%(base)s"\
24
+ "?deviceID=%(deviceID)s"\
25
+ "&name=%(action)s"\
26
+ "&arg1=%(value)s"\
27
+ % {'base': self._base_url,
28
+ 'deviceID': deviceID,
29
+ 'action': action,
30
+ 'value': value}
31
+ request = urllib.request.Request(url)
32
+ auth_string = base64.b64encode(bytes(f"{self._user}:{self._password}", "ascii"))
33
+ request.add_header("Authorization", "Basic %s" % auth_string.decode("utf-8"))
34
+ response = urllib.request.urlopen(request)
35
+ return json.load(response)
36
+ except Exception as e:
37
+ print(f"Error communicating with HomeCentre: {repr(e)}")
38
+
39
+ def setValue(self, deviceID, action, value):
40
+ data = self._request(deviceID, action, value)
41
+ print(data)
42
+ if not data or data['result']['result'] != 0:
43
+ print(f"WARNING: Unexpected result: {data}")
44
+ return data
45
+
46
+
47
+ if __name__ == "__main__":
48
+
49
+ # example call: python3 homecentre_actuators.py -d 117 -a setValue -v 0
50
+ parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
51
+ parser.add_argument("-d", "--deviceID", type=int,
52
+ help="The device/sensor to actuate.", required=True)
53
+ parser.add_argument("-a", "--action", type=str,
54
+ help="The action to call.", required=True)
55
+ parser.add_argument("-v", "--value", type=str,
56
+ help="The value to set the device to.", required=True)
57
+ args, unknown = parser.parse_known_args()
58
+
59
+ pp = pprint.PrettyPrinter(indent=2)
60
+ act = ZWaveHomeActuator()
61
+ pp.pprint(act.setValue(args.deviceID, args.action, args.value))
@@ -0,0 +1,132 @@
1
+ #!/usr/bin/env python3
2
+
3
+ import datetime
4
+ import yaml
5
+
6
+ from rhs.homecenter.sensor import ZWaveHomeSensor
7
+
8
+ class HomeCenterAdapter:
9
+
10
+ def __init__(self, config):
11
+ with open(config, "r") as f:
12
+ self.config = yaml.safe_load(f)
13
+
14
+ self.sensor = ZWaveHomeSensor()
15
+
16
+ self.previous_status = {}
17
+ self.previous_value = {}
18
+
19
+ self.device_type_lookup = {}
20
+ self.role_lookup = {}
21
+ self.unit_lookup = {}
22
+
23
+ for sensor_type, cfg in self.config.get("sensors", {}).items():
24
+ for device_type in cfg.get("types", []):
25
+ self.device_type_lookup[device_type] = sensor_type
26
+ for role in cfg.get("roles", []):
27
+ self.role_lookup[role] = sensor_type
28
+ for unit in cfg.get("units", []):
29
+ self.unit_lookup[unit] = sensor_type
30
+
31
+ rooms = self.sensor.get_rooms()
32
+ self.room_lookup = {
33
+ room["id"]: room["name"]
34
+ for room in rooms
35
+ if "id" in room and "name" in room
36
+ }
37
+
38
+ def get_semantic_type(self, role, unit, device_type):
39
+ return (
40
+ self.device_type_lookup.get(device_type)
41
+ or self.role_lookup.get(role)
42
+ or self.unit_lookup.get(unit)
43
+ or "UNKNOWN"
44
+ )
45
+
46
+ def evaluate_rule(self, rule, value):
47
+ try:
48
+ return bool(
49
+ eval(
50
+ rule,
51
+ {"__builtins__": {}},
52
+ {"value": value}
53
+ )
54
+ )
55
+ except Exception:
56
+ return False
57
+
58
+ def determine_status(self, value, sensor_type_cfg, device_cfg):
59
+ rule = device_cfg.get("activeRule", sensor_type_cfg.get("activeRule"))
60
+ active_status = device_cfg.get("activeStatus", sensor_type_cfg.get("activeStatus", "Active"))
61
+ inactive_status = device_cfg.get("inactiveStatus", sensor_type_cfg.get("inactiveStatus", "Inactive"))
62
+
63
+ if rule is None:
64
+ return str(value), None
65
+
66
+ if self.evaluate_rule(rule, value):
67
+ return active_status, 1
68
+
69
+ return inactive_status, 0
70
+
71
+ def convert(self, device):
72
+
73
+ props = device.get("properties", {})
74
+ device_id = device["id"]
75
+ room_id = device.get("roomID", 0)
76
+ role = props.get("deviceRole", "Unknown")
77
+ unit = props.get("unit")
78
+ value = props.get("value")
79
+
80
+ semantic_type = self.get_semantic_type(
81
+ role,
82
+ unit,
83
+ device.get("type", "")
84
+ )
85
+
86
+ # room_cfg = self.config.get("rooms", {}).get(room_id, {})
87
+ type_cfg = self.config.get("sensors", {}).get(semantic_type, {})
88
+
89
+ device_cfg = (
90
+ self.config.get("devices", {}).get(device_id)
91
+ or self.config.get("devices", {}).get(str(device_id), {})
92
+ )
93
+
94
+ status, status_binary = self.determine_status(
95
+ value, type_cfg, device_cfg
96
+ )
97
+
98
+ sensor = {
99
+ "sensorId": device_id,
100
+ "name": device_cfg.get("name", device["name"]),
101
+ "locationId": room_id,
102
+ "locationName": self.room_lookup.get(room_id, f"Room-{room_id}"),
103
+ "sensorType": semantic_type,
104
+ "status": status,
105
+ "statusBinary": status_binary,
106
+ "value": value,
107
+ "lastStatus": self.previous_status.get(device_id),
108
+ "lastActiveValue": self.previous_value.get(device_id),
109
+ "lastUpdate": datetime.datetime.now(),
110
+ "roomID": room_id,
111
+ "deviceRole": role,
112
+ "unit": unit,
113
+ "batteryLevel": props.get("batteryLevel"),
114
+ "icon": device_cfg.get(
115
+ "icon",
116
+ type_cfg.get("icon", 0)
117
+ ),
118
+ "iconName": device_cfg.get(
119
+ "iconName",
120
+ type_cfg.get("iconName", "")
121
+ ),
122
+ "xCoord": device_cfg.get("xCoord", 0.0),
123
+ "yCoord": device_cfg.get("yCoord", 0.0),
124
+ "orientation": device_cfg.get("orientation", 0.0)
125
+ }
126
+
127
+ self.previous_status[device_id] = status
128
+ self.previous_value[device_id] = value
129
+ return sensor
130
+
131
+ def get_sensors(self):
132
+ return [self.convert(device) for device in self.sensor.get_devices()]
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env python3
2
+
3
+ import base64
4
+ import json
5
+ import os
6
+ import urllib.request
7
+
8
+ class ZWaveHomeSensor:
9
+
10
+ def __init__(self):
11
+ self._base_url = "http://%(ip)s:80/api/" % {
12
+ "ip": os.environ.get(
13
+ "HC_ADDRESS",
14
+ "10.0.1.114"
15
+ )
16
+ }
17
+ self._user = os.environ.get("HC_USER", "admin")
18
+ self._password = os.environ.get("HC_PASSWORD", "admin")
19
+
20
+ def _request(self, endpoint):
21
+ try:
22
+ url = self._base_url + endpoint
23
+ request = urllib.request.Request(url)
24
+ auth_string = base64.b64encode(bytes(f"{self._user}:{self._password}", "ascii"))
25
+ request.add_header("Authorization", "Basic %s" % auth_string.decode("utf-8"))
26
+ response = urllib.request.urlopen(request)
27
+ return json.load(response)
28
+ except Exception as e:
29
+ print(f"Error communicating with HomeCentre: {repr(e)}")
30
+
31
+ def _request_visible(self, endpoint):
32
+ return [
33
+ item
34
+ for item in self._request(endpoint)
35
+ if item.get("visible", False)
36
+ ]
37
+
38
+ def get_devices(self, visible_only = True):
39
+ if visible_only:
40
+ return self._request_visible("devices")
41
+ else:
42
+ return self._request("devices")
43
+
44
+ def get_rooms(self):
45
+ return self._request_visible("rooms")
46
+
47
+ def get_sections(self):
48
+ return self._request_visible("sections")
49
+
50
+ def get_history(self, from_timestamp):
51
+ return self._request(f"events/history?from={from_timestamp}")
52
+
53
+ def get_device(self, device_id):
54
+ return self._request(f"devices/{device_id}")
55
+
56
+ def get_room(self, room_id):
57
+ return self._request(f"rooms/{room_id}")
58
+
59
+
60
+ if __name__ == "__main__":
61
+ hc = ZWaveHomeSensor()
62
+ devices = hc.get_devices()
63
+ rooms = hc.get_rooms()
64
+ sections = hc.get_sections()
65
+ print(f"Retrieved {len(devices)} visible devices, {len(rooms)} rooms, and {len(sections)} sections.")
@@ -0,0 +1,86 @@
1
+ #!/usr/bin/env python3
2
+
3
+ import argparse
4
+ import pprint
5
+ import time
6
+
7
+ from rhs.homecenter.adapter import HomeCenterAdapter
8
+ from zfl.logging.state import SystemState
9
+
10
+ def main_cli():
11
+
12
+ parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
13
+ parser.add_argument(
14
+ "-c",
15
+ "--config",
16
+ type=str,
17
+ default="config/sensors.yaml",
18
+ help="YAML configuration file"
19
+ )
20
+ parser.add_argument(
21
+ "-p",
22
+ "--polling-interval",
23
+ type=float,
24
+ default=1.0,
25
+ help="Polling interval in seconds"
26
+ )
27
+ parser.add_argument(
28
+ "--verbose",
29
+ action="store_true",
30
+ help="Print complete sensor structure on every change"
31
+ )
32
+
33
+ args = parser.parse_args()
34
+ updater = HomeCenterAdapter(config=args.config)
35
+ state = SystemState()
36
+ pp = pprint.PrettyPrinter(indent=1)
37
+ known_states = {}
38
+ sensors = updater.get_sensors()
39
+
40
+ print(f"Found {len(sensors)} sensors.\nPolling for changes...")
41
+
42
+ while True:
43
+ try:
44
+ sensors = updater.get_sensors()
45
+ for sensor in sensors:
46
+ sensor_id = sensor["sensorId"]
47
+ current_state = (sensor["status"])
48
+
49
+ if sensor_id not in known_states:
50
+ print(f"Sensor {sensor_id} ({sensor['name']}) loaded with status: {sensor['status']}, value: {sensor['value']}")
51
+ known_states[sensor_id] = current_state
52
+ if args.verbose:
53
+ pp.pprint(sensor)
54
+
55
+ elif (known_states[sensor_id] != current_state):
56
+ print(f"Sensor {sensor_id} ({sensor['name']}) changed to status: {sensor['status']}, value: {sensor['value']}")
57
+ state.update_state(
58
+ {
59
+ sensor['sensorId']:
60
+ {"name": sensor['name'],
61
+ "value": sensor['value'],
62
+ "status": sensor['status'],
63
+ "location": sensor['locationName'],
64
+ "type": sensor['sensorType'],
65
+ "battery": sensor['batteryLevel'],
66
+ "type": sensor['sensorType'],
67
+ }
68
+ }, path="/sensors")
69
+
70
+ if args.verbose:
71
+ pp.pprint(sensor)
72
+ known_states[sensor_id] = current_state
73
+
74
+ time.sleep(args.polling_interval)
75
+
76
+ except KeyboardInterrupt:
77
+ print("Stopped by user.")
78
+ break
79
+
80
+ except Exception as e:
81
+ print(f"Polling error: {e}")
82
+ time.sleep(5)
83
+
84
+
85
+ if __name__ == "__main__":
86
+ main_cli()
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.4
2
+ Name: rhs
3
+ Version: 0.0.2
4
+ Summary: Sensor poll using REST API
5
+ Author-email: Patrick Holthaus <patrick.holthaus@googlemail.com>
6
+ License-Expression: BSD-2-Clause
7
+ Project-URL: Homepage, https://gitlab.com/robothouse/rh-projects/hospital-at-home/sensors/
8
+ Project-URL: Bug Tracker, https://gitlab.com/robothouse/rh-projects/hospital-at-home/sensors/issues/
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: oyaml
15
+ Requires-Dist: zfl
16
+ Dynamic: license-file
17
+
18
+ This is work in progress.
19
+
20
+ # Installing/downloading the code
21
+
22
+ To get the code ready, you need to create a virtual environment and install these sources:
23
+
24
+ ```bash
25
+ python3 -mvenv /tmp/test
26
+ source /tmp/test/bin/activate
27
+
28
+ git clone git@gitlab.com:robothouse/rh-projects/hospital-at-home/sensors.git
29
+ cd sensors
30
+ git checkout nodb
31
+ pip install -e .
32
+ ```
33
+
34
+ # Running the code
35
+
36
+ To run the code that communicates directly with the homecentre, you need to set password and username for the home centre and then run the example:
37
+
38
+ ```bash
39
+ export HC_USER=<user>
40
+ export HC_PASSWORD=<password>
41
+ export HC_ADDRESS=<IP of the home centre>
42
+ rhs_monitor -c src/rhs/config/sensors.yaml
43
+ ```
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/rhs/__init__.py
5
+ src/rhs/monitor.py
6
+ src/rhs.egg-info/PKG-INFO
7
+ src/rhs.egg-info/SOURCES.txt
8
+ src/rhs.egg-info/dependency_links.txt
9
+ src/rhs.egg-info/entry_points.txt
10
+ src/rhs.egg-info/requires.txt
11
+ src/rhs.egg-info/top_level.txt
12
+ src/rhs/config/__init__.py
13
+ src/rhs/homecenter/__init__.py
14
+ src/rhs/homecenter/actuator.py
15
+ src/rhs/homecenter/adapter.py
16
+ src/rhs/homecenter/sensor.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ rhs_monitor = rhs.monitor:main_cli
@@ -0,0 +1,2 @@
1
+ oyaml
2
+ zfl
@@ -0,0 +1 @@
1
+ rhs