Skip to content

Commit 1214d8e

Browse files
author
Ilia Shcheglov
committed
Extracted DB PATH
1 parent a82ce3d commit 1214d8e

File tree

9 files changed

+52
-16
lines changed

9 files changed

+52
-16
lines changed

.env.dist

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
DB_PATH=PATH

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ sensor_data.db
22
co2_readings.csv
33
__pycache__
44
.DS_Store
5+
.env

README.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ graph TD
6262
```bash
6363
git clone https://github.com/isheglov/co2-sensor-script.git
6464
cd co2-sensor-script
65+
cp .env.dist .env
6566
```
6667

6768
2. **Set up your Python environment**:
@@ -74,7 +75,7 @@ source hid_env/bin/activate
7475

7576
3. **Install the required packages**:
7677
```bash
77-
pip install hidapi Flask pandas plotly
78+
pip install -r requirements.txt
7879
```
7980

8081
4. **Create the SQLite Database**:
@@ -151,8 +152,8 @@ sudo systemctl restart myapp.service
151152

152153
### Web Pages:
153154

154-
- index.html: Main dashboard for real-time data visualization.
155-
- current.html: Shows the latest sensor readings.
155+
- **/**: Main dashboard for real-time data visualization.
156+
- **/current**: Shows the latest sensor readings.
156157

157158
## License
158159

automation/monitor.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,16 @@
1313
# pylint: disable=import-error
1414

1515
import time
16+
import os # Standard import should be before third-party
1617
import sqlite3
1718
from RPi import GPIO
19+
from dotenv import load_dotenv
20+
21+
load_dotenv() # Load environment variables from .env file
22+
1823

1924
# Configuration
20-
DB_PATH = '../sensor_data.db' # Path to your SQLite database
25+
DB_PATH = os.getenv('DB_PATH') # Path to your SQLite database
2126
RELAY_PIN = 17 # GPIO pin connected to the relay (use the BCM numbering)
2227
CO2_THRESHOLD_ON = 800 # CO2 ppm level to turn relay on
2328
FAN_DURATION = 300 # Duration to keep the fan on (in seconds)

co2_sensor.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
DEVICE_PATH = b'/dev/hidraw0'
1111

1212
# Path to the SQLite database
13-
DB_PATH = 'sensor_data.db'
13+
DB_PATH = '../sensor_data.db'
1414

1515

1616
class CO2Sensor:
@@ -54,7 +54,6 @@ def save_to_db(self):
5454
INSERT INTO last_day_sensor_data (date, co2, temperature, humidity)
5555
VALUES (?, ?, ?, ?)
5656
""", (current_time, self.current_co2, self.current_temperature, self.current_humidity))
57-
5857
cursor.execute("""
5958
DELETE FROM last_day_sensor_data WHERE date < datetime('now', '-24 hours')
6059
""")
@@ -140,7 +139,7 @@ def run(self):
140139
self.parse_data(data)
141140
else:
142141
print("No data received from the device.")
143-
time.sleep(10)
142+
time.sleep(10)
144143

145144
self.h.close()
146145
except IOError as ex:

create_db.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,12 @@
22
# pylint: disable=import-error
33

44
import sqlite3
5+
import os # Standard import should be before third-party
6+
from dotenv import load_dotenv
57

6-
DB_PATH = '../sensor_data.db'
8+
load_dotenv() # Load environment variables from .env file
9+
10+
DB_PATH = os.getenv('DB_PATH')
711

812
conn = sqlite3.connect(DB_PATH)
913
cursor = conn.cursor()

requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,5 @@ hidapi
22
Flask
33
pandas
44
plotly
5+
werkzeug
6+
python-dotenv
File renamed without changes.

web_service/app.py

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,28 @@
88
import plotly.graph_objs as go
99
from plotly.subplots import make_subplots
1010
from werkzeug.middleware.profiler import ProfilerMiddleware
11+
from dotenv import load_dotenv
12+
13+
load_dotenv() # Load environment variables from .env file
1114

1215
app = Flask(__name__)
1316

1417
# Determine the absolute path to the database file
1518
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
1619
DB_NAME = os.path.join(BASE_DIR, 'sensor_data.db')
20+
DB_PATH = os.getenv('DB_PATH')
1721

1822
def get_latest_data():
23+
"""Fetches the latest sensor data from the database."""
1924
try:
20-
conn = sqlite3.connect(DB_NAME)
25+
conn = sqlite3.connect(DB_PATH)
2126
cursor = conn.cursor()
2227
cursor.execute(
23-
"SELECT date, co2, temperature, humidity FROM last_day_sensor_data ORDER BY id DESC LIMIT 1"
28+
"""
29+
SELECT date, co2, temperature, humidity
30+
FROM last_day_sensor_data
31+
ORDER BY id DESC LIMIT 1
32+
"""
2433
)
2534
row = cursor.fetchone()
2635
if row:
@@ -38,8 +47,9 @@ def get_latest_data():
3847
conn.close()
3948

4049
def fetch_last_day():
50+
"""Fetches the last day's sensor data from the database."""
4151
try:
42-
conn = sqlite3.connect(DB_NAME)
52+
conn = sqlite3.connect(DB_PATH)
4353
query = "SELECT date, co2, temperature, humidity FROM last_day_sensor_data;"
4454
df = pd.read_sql_query(query, conn)
4555
df['date'] = pd.to_datetime(df['date'])
@@ -70,28 +80,41 @@ def resample_data(df, rule='1T'):
7080

7181
@app.route('/')
7282
def index():
83+
"""Renders the index page with sensor data plots."""
7384
df_orig = fetch_last_day()
7485
if df_orig.empty:
7586
return render_template('index.html', graph_html="No data available.")
76-
7787
# Resample data to one-minute intervals to reduce the number of points
7888
df = resample_data(df_orig, rule='1T')
7989

8090
fig = make_subplots(
8191
rows=3,
8292
cols=1,
8393
shared_xaxes=True,
84-
subplot_titles=("CO₂ Levels Over Time", "Temperature Over Time", "Humidity Over Time")
94+
subplot_titles=(
95+
"CO₂ Levels Over Time",
96+
"Temperature Over Time",
97+
"Humidity Over Time",
98+
),
8599
)
86-
fig.add_trace(go.Scatter(x=df['date'], y=df['co2'], mode='lines', name='CO₂ over time'), row=1, col=1)
87-
fig.add_trace(go.Scatter(x=df['date'], y=df['temperature'], mode='lines', name='Temperature (°C)'), row=2, col=1)
88-
fig.add_trace(go.Scatter(x=df['date'], y=df['humidity'], mode='lines', name='Humidity (%)'), row=3, col=1)
100+
fig.add_trace(
101+
go.Scatter(x=df['date'], y=df['co2'], mode='lines', name='CO₂ over time'), row=1, col=1
102+
)
103+
fig.add_trace(
104+
go.Scatter(x=df['date'], y=df['temperature'], mode='lines', name='Temperature (°C)'),
105+
row=2,
106+
col=1
107+
)
108+
fig.add_trace(
109+
go.Scatter(x=df['date'], y=df['humidity'], mode='lines', name='Humidity (%)'), row=3, col=1
110+
)
89111
fig.update_layout(title='Sensor Data Over Time', xaxis_title='Time', height=800)
90112
graph_html = fig.to_html(full_html=False)
91113
return render_template('index.html', graph_html=graph_html)
92114

93115
@app.route('/current')
94116
def current():
117+
"""Renders the current data page."""
95118
current_data = get_latest_data()
96119
return render_template('current.html', current_data=current_data)
97120

0 commit comments

Comments
 (0)