spectrum-barometer 2.2.5__tar.gz → 2.3__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.
Files changed (47) hide show
  1. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/MANIFEST.in +2 -2
  2. {spectrum_barometer-2.2.5/spectrum_barometer.egg-info → spectrum_barometer-2.3}/PKG-INFO +37 -5
  3. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/README.md +17 -2
  4. spectrum_barometer-2.3/barometer/__init__.py +1 -0
  5. spectrum_barometer-2.3/barometer/actions.py +237 -0
  6. spectrum_barometer-2.3/barometer/background.py +225 -0
  7. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/barometer/data.py +20 -8
  8. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/barometer/graphs.py +69 -67
  9. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/barometer_logger.py +106 -109
  10. spectrum_barometer-2.3/man/man1/barometer-archive.1 +15 -0
  11. spectrum_barometer-2.3/man/man1/barometer-config.1 +12 -0
  12. spectrum_barometer-2.3/man/man1/barometer-graph.1 +28 -0
  13. spectrum_barometer-2.3/man/man1/barometer-info.1 +8 -0
  14. spectrum_barometer-2.3/man/man1/barometer-scrape.1 +8 -0
  15. spectrum_barometer-2.3/man/man1/barometer-start.1 +12 -0
  16. spectrum_barometer-2.3/man/man1/barometer-stats.1 +8 -0
  17. spectrum_barometer-2.3/man/man1/barometer-stop.1 +8 -0
  18. spectrum_barometer-2.3/man/man1/barometer-test.1 +8 -0
  19. spectrum_barometer-2.3/man/man1/barometer-version.1 +8 -0
  20. spectrum_barometer-2.3/man/man1/barometer-web.1 +12 -0
  21. spectrum_barometer-2.3/man/man1/barometer.1 +59 -0
  22. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/pyproject.toml +11 -4
  23. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3/spectrum_barometer.egg-info}/PKG-INFO +37 -5
  24. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/spectrum_barometer.egg-info/SOURCES.txt +17 -0
  25. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/spectrum_barometer.egg-info/requires.txt +1 -1
  26. spectrum_barometer-2.3/tests/test_archive.py +149 -0
  27. spectrum_barometer-2.3/tests/test_cli.py +102 -0
  28. spectrum_barometer-2.3/tests/test_graphs.py +170 -0
  29. spectrum_barometer-2.3/tests/test_monitor.py +113 -0
  30. spectrum_barometer-2.3/tests/test_pressure.py +81 -0
  31. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/web/app.py +3 -9
  32. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/web/routes.py +24 -43
  33. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/web/static/refresh.js +1 -1
  34. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/web/templates/dashboard.html +23 -41
  35. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/web/templates/stats.html +1 -1
  36. spectrum_barometer-2.2.5/barometer/actions.py +0 -187
  37. spectrum_barometer-2.2.5/barometer/background.py +0 -246
  38. spectrum_barometer-2.2.5/web/__init__.py +0 -0
  39. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/LICENSE.txt +0 -0
  40. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/barometer/paths.py +0 -0
  41. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/setup.cfg +0 -0
  42. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/spectrum_barometer.egg-info/dependency_links.txt +0 -0
  43. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/spectrum_barometer.egg-info/entry_points.txt +0 -0
  44. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/spectrum_barometer.egg-info/top_level.txt +0 -0
  45. {spectrum_barometer-2.2.5/barometer → spectrum_barometer-2.3/web}/__init__.py +0 -0
  46. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/web/static/stabbypeng.png +0 -0
  47. {spectrum_barometer-2.2.5 → spectrum_barometer-2.3}/web/templates/base.html +0 -0
@@ -1,4 +1,4 @@
1
1
  include README.md
2
- include LICENSE
2
+ include LICENSE.txt
3
3
  recursive-include web/templates *.html
4
- recursive-include web/static *
4
+ recursive-include web/static *
@@ -1,15 +1,32 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spectrum-barometer
3
- Version: 2.2.5
3
+ Version: 2.3
4
4
  Summary: Monitor barometric pressure from Spectrum SAX2V1S routers
5
5
  Author-email: BobaTeagrl <Unsorted2750@proton.me>
6
- License: MIT
6
+ License: MIT No Attribution
7
+
8
+ Copyright 2026, BobaTeagrl
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this
11
+ software and associated documentation files (the "Software"), to deal in the Software
12
+ without restriction, including without limitation the rights to use, copy, modify,
13
+ merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
14
+ permit persons to whom the Software is furnished to do so.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
17
+ INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
18
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+
7
23
  Project-URL: Homepage, https://github.com/BobaTeagrl/spectrum-barometer
8
24
  Project-URL: Repository, https://github.com/BobaTeagrl/spectrum-barometer
9
25
  Project-URL: Issues, https://github.com/BobaTeagrl/spectrum-barometer/issues
10
26
  Keywords: barometer,pressure,monitoring,spectrum,router,measurement,sax2v1s
11
27
  Classifier: Development Status :: 5 - Production/Stable
12
28
  Classifier: Intended Audience :: End Users/Desktop
29
+ Classifier: Operating System :: POSIX
13
30
  Classifier: License :: OSI Approved
14
31
  Classifier: Programming Language :: Python :: 3
15
32
  Classifier: Programming Language :: Python :: 3.8
@@ -21,7 +38,7 @@ Requires-Python: >=3.8
21
38
  Description-Content-Type: text/markdown
22
39
  License-File: LICENSE.txt
23
40
  Requires-Dist: click>=8.0
24
- Requires-Dist: pandas>=1.3
41
+ Requires-Dist: pandas>=2.0
25
42
  Requires-Dist: pyyaml>=5.4
26
43
  Requires-Dist: requests>=2.26
27
44
  Requires-Dist: urllib3>=1.26
@@ -38,8 +55,20 @@ Dynamic: license-file
38
55
 
39
56
  Monitor barometric pressure from Spectrum SAX2V1S routers.
40
57
 
58
+
59
+ # probably broken
60
+
61
+ Spectrum pushed a firmware update that removed all worthwhile info from the table i scraped so unless your router wasnt updated it wont work anymore.
62
+
63
+ While this is annoying and a little disapointing version 2.3 was released to give any users left the best time possible while they can have it.
64
+
65
+ Also, as far as i know this was the only tool that pulled from this table so spectrum, if your reading this, me and the guy who did the hard work of cracking the router two teamed ur mom last night and honestly? she was mid.
66
+
67
+
41
68
  ## Installation
42
69
 
70
+ Requires Python 3.8 or later on a POSIX system, such as Linux or macOS. Windows users can run the CLI in WSL.
71
+
43
72
  ### Quick install (recommended)
44
73
  ```bash
45
74
  pipx install spectrum-barometer
@@ -52,7 +81,7 @@ pip install spectrum-barometer
52
81
 
53
82
 
54
83
 
55
- ### Install with pip and git
84
+ ### Install with pipx and git
56
85
  ```bash
57
86
  pipx install git+https://github.com/BobaTeagrl/spectrum-barometer.git
58
87
  ```
@@ -110,7 +139,10 @@ All data is stored in `~/spectrum-barometer/` regardless of where you run the co
110
139
  barometer scrape
111
140
 
112
141
  # Start continuous monitoring (every 5 minutes by default)
113
- barometer monitor
142
+ barometer start
143
+
144
+ # Stop continuous monitoring
145
+ barometer stop
114
146
 
115
147
  # Generate a graph
116
148
  barometer graph
@@ -2,8 +2,20 @@
2
2
 
3
3
  Monitor barometric pressure from Spectrum SAX2V1S routers.
4
4
 
5
+
6
+ # probably broken
7
+
8
+ Spectrum pushed a firmware update that removed all worthwhile info from the table i scraped so unless your router wasnt updated it wont work anymore.
9
+
10
+ While this is annoying and a little disapointing version 2.3 was released to give any users left the best time possible while they can have it.
11
+
12
+ Also, as far as i know this was the only tool that pulled from this table so spectrum, if your reading this, me and the guy who did the hard work of cracking the router two teamed ur mom last night and honestly? she was mid.
13
+
14
+
5
15
  ## Installation
6
16
 
17
+ Requires Python 3.8 or later on a POSIX system, such as Linux or macOS. Windows users can run the CLI in WSL.
18
+
7
19
  ### Quick install (recommended)
8
20
  ```bash
9
21
  pipx install spectrum-barometer
@@ -16,7 +28,7 @@ pip install spectrum-barometer
16
28
 
17
29
 
18
30
 
19
- ### Install with pip and git
31
+ ### Install with pipx and git
20
32
  ```bash
21
33
  pipx install git+https://github.com/BobaTeagrl/spectrum-barometer.git
22
34
  ```
@@ -74,7 +86,10 @@ All data is stored in `~/spectrum-barometer/` regardless of where you run the co
74
86
  barometer scrape
75
87
 
76
88
  # Start continuous monitoring (every 5 minutes by default)
77
- barometer monitor
89
+ barometer start
90
+
91
+ # Stop continuous monitoring
92
+ barometer stop
78
93
 
79
94
  # Generate a graph
80
95
  barometer graph
@@ -0,0 +1 @@
1
+ __version__ = "2.3"
@@ -0,0 +1,237 @@
1
+ import csv
2
+ from contextlib import contextmanager
3
+ from datetime import datetime, timedelta
4
+ from hashlib import sha256
5
+ import logging
6
+ import os
7
+ from pathlib import Path
8
+ from stat import S_IMODE
9
+ from tempfile import NamedTemporaryFile
10
+ from uuid import uuid4
11
+
12
+ from barometer.paths import get_data_dir, get_archive_dir, get_logs_dir
13
+ from barometer.data import load_data, readings_lock
14
+
15
+
16
+ def _sync_directory(directory):
17
+ fd = os.open(directory, os.O_RDONLY)
18
+ try:
19
+ os.fsync(fd)
20
+ finally:
21
+ os.close(fd)
22
+
23
+
24
+ @contextmanager
25
+ def _staged_csv(directory):
26
+ # A .tmp suffix keeps an unfinished batch out of archive discovery.
27
+ with NamedTemporaryFile(mode='w', dir=directory, suffix='.tmp',
28
+ encoding='utf-8', newline='', delete=False) as stream:
29
+ try:
30
+ yield stream
31
+ finally:
32
+ Path(stream.name).unlink(missing_ok=True)
33
+
34
+
35
+ def _archive_readings(archive_dir, cutoff):
36
+ live = get_data_dir() / 'readings.csv'
37
+ if not live.exists():
38
+ return False
39
+
40
+ with live.open(encoding='utf-8', newline='') as source:
41
+ rows = csv.reader(source, strict=True)
42
+ header = next(rows, None)
43
+ if header is None:
44
+ return False
45
+ timestamp_index = header.index('timestamp')
46
+ with _staged_csv(archive_dir) as batch, _staged_csv(live.parent) as recent:
47
+ archive_writer = csv.writer(batch)
48
+ recent_writer = csv.writer(recent)
49
+ archive_writer.writerow(header)
50
+ recent_writer.writerow(header)
51
+ has_old_rows = False
52
+ for row in rows:
53
+ # Preserve unclassifiable records in the live file for recovery.
54
+ try:
55
+ old = datetime.fromisoformat(row[timestamp_index]) < cutoff
56
+ except (ValueError, IndexError, TypeError):
57
+ old = False
58
+ if old:
59
+ archive_writer.writerow(row)
60
+ has_old_rows = True
61
+ else:
62
+ recent_writer.writerow(row)
63
+
64
+ if not has_old_rows:
65
+ return False
66
+
67
+ os.fchmod(recent.fileno(), S_IMODE(os.fstat(source.fileno()).st_mode))
68
+ for stream in (batch, recent):
69
+ stream.flush()
70
+ os.fsync(stream.fileno())
71
+
72
+ # Identical batches reuse their archive on a retry after interruption.
73
+ digest = sha256()
74
+ with open(batch.name, 'rb') as contents:
75
+ for chunk in iter(lambda: contents.read(1024 * 1024), b''):
76
+ digest.update(chunk)
77
+ archive = archive_dir / f'readings_archive_{digest.hexdigest()}.csv'
78
+ if not archive.exists():
79
+ os.rename(batch.name, archive)
80
+ _sync_directory(archive_dir)
81
+ os.replace(recent.name, live)
82
+ _sync_directory(live.parent)
83
+ return True
84
+
85
+
86
+ def archive_old_data(keep_days=90):
87
+ """Move old readings and logs into this month's archive."""
88
+ archived_items = 0
89
+ archive_dir = None
90
+ try:
91
+ if keep_days < 0:
92
+ raise ValueError('Retention must be zero or more days')
93
+ now = datetime.now()
94
+ cutoff = now - timedelta(days=keep_days)
95
+ archive_dir = get_archive_dir() / now.strftime('%Y-%m')
96
+ with readings_lock():
97
+ archive_dir.mkdir(exist_ok=True)
98
+ # Persist the directory chain before removing anything from live data.
99
+ _sync_directory(archive_dir.parent.parent)
100
+ _sync_directory(archive_dir.parent)
101
+ if _archive_readings(archive_dir, cutoff):
102
+ archived_items += 1
103
+
104
+ log_file = get_logs_dir() / 'barometer.log'
105
+ if log_file.exists() and log_file.stat().st_size > 10 * 1024 * 1024:
106
+ # Open writers can finish on the old inode. WatchedFileHandler
107
+ # reopens the live pathname on the next log message.
108
+ log_file.rename(archive_dir / f'barometer_{uuid4().hex}.log')
109
+ archived_items += 1
110
+ _sync_directory(archive_dir)
111
+ _sync_directory(log_file.parent)
112
+
113
+ return {
114
+ 'success': True,
115
+ 'archived_items': archived_items,
116
+ 'message': (f'Archived {archived_items} item(s)' if archived_items
117
+ else 'No items needed archiving'),
118
+ 'archive_path': archive_dir if archived_items else None,
119
+ }
120
+ except Exception as e:
121
+ logging.error(f"Archive failed: {e}")
122
+ return {
123
+ 'success': False,
124
+ 'archived_items': archived_items,
125
+ 'message': f'Could not complete archive: {e}',
126
+ 'archive_path': archive_dir if archived_items else None,
127
+ }
128
+
129
+
130
+ def get_statistics(include_archives=False):
131
+ """
132
+ Get statistical summary of collected data.
133
+
134
+ Args:
135
+ include_archives: Include archived data in stats
136
+
137
+ Returns:
138
+ dict or None: Statistics dictionary or None if no data
139
+ """
140
+ df = load_data(include_archives=include_archives)
141
+
142
+ if df is None or df.empty:
143
+ return None
144
+
145
+ stats = {
146
+ 'total_readings': len(df),
147
+ 'first_reading': df['timestamp'].min(),
148
+ 'last_reading': df['timestamp'].max(),
149
+ 'duration_days': (df['timestamp'].max() - df['timestamp'].min()).days,
150
+ 'pressure': {
151
+ 'current': float(df['pressure_hpa'].iloc[-1]),
152
+ 'average': float(df['pressure_hpa'].mean()),
153
+ 'minimum': float(df['pressure_hpa'].min()),
154
+ 'maximum': float(df['pressure_hpa'].max()),
155
+ 'range': float(df['pressure_hpa'].max() - df['pressure_hpa'].min()),
156
+ 'std_dev': float(df['pressure_hpa'].std()),
157
+ }
158
+ }
159
+
160
+ # Last 24 hours
161
+ last_24h = df[df['timestamp'] > (datetime.now() - timedelta(hours=24))]
162
+ if not last_24h.empty:
163
+ stats['last_24h'] = {
164
+ 'readings': len(last_24h),
165
+ 'average': float(last_24h['pressure_hpa'].mean()),
166
+ 'change': float(last_24h['pressure_hpa'].iloc[-1] - last_24h['pressure_hpa'].iloc[0]),
167
+ }
168
+
169
+ return stats
170
+
171
+
172
+ def get_latest_reading():
173
+ """
174
+ Get the most recent pressure reading.
175
+
176
+ Returns:
177
+ dict or None: {'pressure': float, 'timestamp': datetime} or None
178
+ """
179
+ df = load_data()
180
+
181
+ if df is None or df.empty:
182
+ return None
183
+
184
+ row = df.iloc[-1]
185
+ return {
186
+ 'pressure': float(row['pressure_hpa']),
187
+ 'timestamp': row['timestamp'],
188
+ }
189
+
190
+ def scrape_single_reading():
191
+ """
192
+ Perform a single scrape and save reading.
193
+
194
+ Returns:
195
+ dict: {
196
+ 'success': bool,
197
+ 'pressure': float or None,
198
+ 'message': str
199
+ }
200
+ """
201
+ from barometer_logger import BarometerScraper
202
+
203
+ try:
204
+ scraper = BarometerScraper()
205
+ response = scraper.login()
206
+
207
+ if not response:
208
+ return {
209
+ 'success': False,
210
+ 'pressure': None,
211
+ 'message': 'Connection failed'
212
+ }
213
+
214
+ pressure = scraper.extract_barometer_value(response.text)
215
+
216
+ if not pressure:
217
+ return {
218
+ 'success': False,
219
+ 'pressure': None,
220
+ 'message': 'Failed to extract pressure value'
221
+ }
222
+
223
+ scraper.save_reading(pressure)
224
+
225
+ return {
226
+ 'success': True,
227
+ 'pressure': pressure / 100, # Convert to hPa
228
+ 'message': f'Reading saved: {pressure / 100:.2f} hPa'
229
+ }
230
+
231
+ except Exception as e:
232
+ logging.error(f"Scrape failed: {e}")
233
+ return {
234
+ 'success': False,
235
+ 'pressure': None,
236
+ 'message': f'Could not collect reading: {e}'
237
+ }
@@ -0,0 +1,225 @@
1
+ """Background monitoring using threading with file-based state"""
2
+ import threading
3
+ import time
4
+ import os
5
+ import logging
6
+ import psutil
7
+ from barometer.paths import get_app_dir
8
+ from contextlib import contextmanager
9
+ import fcntl
10
+ from uuid import uuid4
11
+
12
+
13
+ def get_state_file():
14
+ """Get path to state file"""
15
+ return get_app_dir() / 'monitor.state'
16
+
17
+
18
+ def get_interval_file():
19
+ """Get path to interval file"""
20
+ return get_app_dir() / 'monitor.interval'
21
+
22
+
23
+ def get_pid_file():
24
+ """Get path to PID file"""
25
+ return get_app_dir() / 'monitor.pid'
26
+
27
+
28
+ def get_owner_file():
29
+ """Get the identity of this particular monitoring run"""
30
+ return get_app_dir() / 'monitor.owner'
31
+
32
+
33
+ def _all_state_files():
34
+ return [get_state_file(), get_pid_file(), get_interval_file(), get_owner_file()]
35
+
36
+
37
+ def _cleanup_state_files():
38
+ for f in _all_state_files():
39
+ f.unlink(missing_ok=True)
40
+
41
+
42
+ def _write_pid_record():
43
+ # store pid and create_time together so a reused pid can't be mistaken
44
+ pid = os.getpid()
45
+ try:
46
+ create_time = psutil.Process(pid).create_time()
47
+ except psutil.Error:
48
+ create_time = None
49
+ get_pid_file().write_text(f"{pid}:{create_time}")
50
+ return pid
51
+
52
+
53
+ def _read_pid_record():
54
+ pid_file = get_pid_file()
55
+ if not pid_file.exists():
56
+ return None, None
57
+ try:
58
+ text = pid_file.read_text().strip()
59
+ pid_str, _, ct_str = text.partition(':')
60
+ pid = int(pid_str)
61
+ create_time = float(ct_str) if ct_str and ct_str != 'None' else None
62
+ return pid, create_time
63
+ except (ValueError, OSError):
64
+ return None, None
65
+
66
+
67
+ def _process_still_matches(pid, create_time):
68
+ # pid alone isn't enough it could've been recycled by a totally different process
69
+ if pid is None:
70
+ return False
71
+ try:
72
+ proc = psutil.Process(pid)
73
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
74
+ return False
75
+
76
+ if create_time is None:
77
+ return True
78
+
79
+ try:
80
+ return abs(proc.create_time() - create_time) < 1.0
81
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
82
+ return False
83
+
84
+
85
+ @contextmanager
86
+ def _monitor_lock():
87
+ with (get_app_dir() / '.monitor.lock').open('a') as lock:
88
+ fcntl.flock(lock, fcntl.LOCK_EX)
89
+ yield
90
+
91
+
92
+ def _read_text(path):
93
+ try:
94
+ return path.read_text().strip()
95
+ except FileNotFoundError:
96
+ return ''
97
+
98
+
99
+ def _active_state():
100
+ """Read under _monitor_lock. A stopping worker still owns its slot."""
101
+ state = _read_text(get_state_file())
102
+ if state in ('running', 'stop') and _process_still_matches(*_read_pid_record()):
103
+ return state
104
+ if state or get_pid_file().exists():
105
+ _cleanup_state_files()
106
+ return None
107
+
108
+
109
+ def get_monitor_info():
110
+ with _monitor_lock():
111
+ state = _active_state()
112
+ pid, _ = _read_pid_record() if state else (None, None)
113
+ try:
114
+ interval = int(_read_text(get_interval_file())) if state else None
115
+ except ValueError:
116
+ interval = 300
117
+ return {'running': state == 'running', 'stopping': state == 'stop',
118
+ 'pid': pid, 'interval': interval}
119
+
120
+
121
+ def is_monitoring():
122
+ return get_monitor_info()['running']
123
+
124
+
125
+ def is_owned_by_current_process():
126
+ with _monitor_lock():
127
+ return bool(_active_state()) and _read_pid_record()[0] == os.getpid()
128
+
129
+
130
+ # Only the process that started this run needs a shutdown callback.
131
+ _local_owner = None
132
+
133
+
134
+ def stop_owned_monitor():
135
+ owner = _local_owner
136
+ if owner is not None and owner[0] == os.getpid():
137
+ stop_monitoring(run_id=owner[1])
138
+
139
+
140
+ def _monitor_loop(interval, run_id, finished):
141
+ global _local_owner
142
+ from barometer.actions import scrape_single_reading
143
+
144
+ try:
145
+ next_reading = time.monotonic()
146
+ while True:
147
+ with _monitor_lock():
148
+ if (_read_text(get_owner_file()) != run_id or
149
+ _read_text(get_state_file()) != 'running'):
150
+ break
151
+ remaining = next_reading - time.monotonic()
152
+ if remaining > 0:
153
+ time.sleep(min(remaining, 1))
154
+ continue
155
+ try:
156
+ result = scrape_single_reading()
157
+ if result['success']:
158
+ logging.info(f"Background scrape: {result['pressure']:.2f} hPa")
159
+ else:
160
+ logging.error(f"Background scrape failed: {result['message']}")
161
+ except Exception:
162
+ logging.exception("Monitor error")
163
+ next_reading = time.monotonic() + interval
164
+ finally:
165
+ try:
166
+ with _monitor_lock():
167
+ if _read_text(get_owner_file()) == run_id:
168
+ _cleanup_state_files()
169
+ if _local_owner == (os.getpid(), run_id):
170
+ _local_owner = None
171
+ finally:
172
+ finished.set()
173
+
174
+
175
+ def start_monitoring(interval=300):
176
+ global _local_owner
177
+ if type(interval) is not int or interval < 1:
178
+ return {'success': False, 'message': 'Interval must be a positive integer in seconds', 'pid': None}
179
+
180
+ with _monitor_lock():
181
+ state = _active_state()
182
+ if state:
183
+ message = 'Monitoring is already running' if state == 'running' else 'Monitoring is stopping'
184
+ return {'success': False, 'message': message, 'pid': _read_pid_record()[0]}
185
+
186
+ run_id = uuid4().hex
187
+ finished = threading.Event()
188
+ try:
189
+ pid = _write_pid_record()
190
+ get_interval_file().write_text(str(interval))
191
+ get_owner_file().write_text(run_id)
192
+ # Publish last so older installations can also read the PID.
193
+ get_state_file().write_text('running')
194
+ worker = threading.Thread(target=_monitor_loop, args=(interval, run_id, finished),
195
+ daemon=True, name="BarometerMonitor")
196
+ worker.start()
197
+ _local_owner = (pid, run_id)
198
+ except Exception as exc:
199
+ _cleanup_state_files()
200
+ return {'success': False, 'message': f'Failed to start: {exc}', 'pid': None}
201
+ return {'success': True, 'message': f'Monitoring started (interval: {interval}s)',
202
+ 'pid': pid, 'run_id': run_id, 'finished': finished}
203
+
204
+
205
+ def stop_monitoring(wait_seconds=3, *, run_id=None):
206
+ """Public stop targets the active worker. Owner cleanup can target a specific run."""
207
+ with _monitor_lock():
208
+ had_state = get_state_file().exists()
209
+ state = _active_state()
210
+ owner = _read_text(get_owner_file())
211
+ pid_record = _read_pid_record()
212
+ if run_id is not None and (not state or owner != run_id):
213
+ return {'success': True, 'message': 'Monitoring already stopped'}
214
+ if not state:
215
+ message = 'Cleared stale monitoring state' if had_state else 'Monitoring is not running'
216
+ return {'success': had_state, 'message': message}
217
+ get_state_file().write_text('stop')
218
+
219
+ deadline = time.monotonic() + wait_seconds
220
+ while time.monotonic() < deadline:
221
+ with _monitor_lock():
222
+ if _read_text(get_owner_file()) != owner or _read_pid_record() != pid_record:
223
+ return {'success': True, 'message': 'Monitoring stopped'}
224
+ time.sleep(0.1)
225
+ return {'success': True, 'message': 'Stop signal sent; waiting for the current scrape to finish'}
@@ -1,6 +1,8 @@
1
1
  from barometer.paths import get_data_dir, get_archive_dir
2
2
  import pandas
3
- from datetime import datetime, timedelta
3
+ from contextlib import contextmanager
4
+ import fcntl
5
+ from logging.handlers import WatchedFileHandler
4
6
  import logging
5
7
  from barometer.paths import get_logs_dir
6
8
 
@@ -21,15 +23,25 @@ def _read_and_clean(csv_path):
21
23
  return df
22
24
 
23
25
 
26
+ @contextmanager
27
+ def readings_lock(*, shared=False):
28
+ # The CSV itself is replaced during archiving, so lock a stable sibling.
29
+ with (get_data_dir() / '.readings.lock').open('a') as lock:
30
+ fcntl.flock(lock, fcntl.LOCK_SH if shared else fcntl.LOCK_EX)
31
+ yield
32
+
33
+
24
34
  def load_data(include_archives=False):
25
- data_file = get_data_dir() / 'readings.csv'
35
+ with readings_lock(shared=True):
36
+ return _load_data(include_archives)
26
37
 
27
- if not data_file.exists():
28
- return None
38
+
39
+ def _load_data(include_archives):
40
+ data_file = get_data_dir() / 'readings.csv'
29
41
 
30
42
  dfs = []
31
- df = _read_and_clean(data_file)
32
- dfs.append(df)
43
+ if data_file.exists():
44
+ dfs.append(_read_and_clean(data_file))
33
45
 
34
46
  if include_archives:
35
47
  archive_dir = get_archive_dir()
@@ -56,7 +68,7 @@ def setup_logging(verbose=False):
56
68
  level=level,
57
69
  format='%(asctime)s - %(levelname)s - %(message)s',
58
70
  handlers=[
59
- logging.FileHandler(log_file),
71
+ WatchedFileHandler(log_file),
60
72
  logging.StreamHandler()
61
73
  ]
62
- )
74
+ )