a bunch of changes

This commit is contained in:
OMGeeky
2025-05-17 15:22:06 +02:00
parent 8bc58e4056
commit baccbfbfdd
15 changed files with 331 additions and 290 deletions

4
.gitignore vendored
View File

@@ -1,2 +1,6 @@
.idea/workspace.xml
config.json
/deploy/code/
/deploy/upload/
/deploy/last_upload/
/deploy/actual_upload/

3
.idea/esp-sensors.iml generated
View File

@@ -3,6 +3,9 @@
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.venv" />
<excludeFolder url="file://$MODULE_DIR$/deploy/last_upload" />
<excludeFolder url="file://$MODULE_DIR$/deploy/actual_upload" />
<excludeFolder url="file://$MODULE_DIR$/deploy/upload" />
</content>
<orderEntry type="jdk" jdkName="Python 3.12 (esp-sensors)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />

45
deploy/deploy.sh Executable file
View File

@@ -0,0 +1,45 @@
#pip install adafruit-ampy
CODE_DIR="src/"
LIBS_DIR=deploy/upload
UPLOAD_SOURCE_DIR=deploy/upload
CONFIG_FILE=deploy/config.json
ACTUAL_UPLOAD_SOURCE_DIR=deploy/actual_upload
LAST_UPLOAD_DIR=deploy/last_upload
UPLOAD_TARGET_DIR=
echo "preparing for deployment"
mkdir -p "$UPLOAD_SOURCE_DIR"
# move the last upload directory to a backup to be able to compare the changes and only upload the changes
rm -rf "$LAST_UPLOAD_DIR"
mv "$UPLOAD_SOURCE_DIR" "$LAST_UPLOAD_DIR"
mkdir -p "$UPLOAD_SOURCE_DIR"
mkdir -p "$LAST_UPLOAD_DIR"
cp -r "$CODE_DIR"* "$UPLOAD_SOURCE_DIR"
cp "$CONFIG_FILE" "$UPLOAD_SOURCE_DIR"
# check if the flag -libs is set and copy the libraries to the upload directory
if [[ "$1" == "-libs" ]]; then
echo "Copying libraries to upload directory"
mkdir -p "$UPLOAD_SOURCE_DIR/lib"
cp -r "$LIBS_DIR"* "$UPLOAD_SOURCE_DIR/lib"
fi
# check what files have changed and only upload the changed files (use $ACTUAL_UPLOAD_SOURCE_DIR for the changed files)
echo "Checking for changes in the upload directory"
rm -rf "$ACTUAL_UPLOAD_SOURCE_DIR"
mkdir -p "$ACTUAL_UPLOAD_SOURCE_DIR"
#rsync -a --delete --ignore-existing "$UPLOAD_SOURCE_DIR/" "$LAST_UPLOAD_DIR/" "$ACTUAL_UPLOAD_SOURCE_DIR/"
# TODO: use diff or rsync to check for changes and only upload the changed files (and delete the files, that are no longer there)
cp -r "$UPLOAD_SOURCE_DIR"/* "$ACTUAL_UPLOAD_SOURCE_DIR"
if [ -z "$ESP_PORT" ]; then
echo "ESP_PORT is not set. Please set it to the correct port for your ESP32 device."
exit 1
fi
echo "Deploying to ESP32 on port '$ESP_PORT'"
ampy --port "$ESP_PORT" put "$ACTUAL_UPLOAD_SOURCE_DIR"/ "$UPLOAD_TARGET_DIR"/

Binary file not shown.

164
deploy/libs/ssd1306.py Normal file
View File

@@ -0,0 +1,164 @@
# MicroPython SSD1306 OLED driver, I2C and SPI interfaces
from micropython import const
import framebuf
# register definitions
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xA4)
SET_NORM_INV = const(0xA6)
SET_DISP = const(0xAE)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP = const(0xA0)
SET_MUX_RATIO = const(0xA8)
SET_IREF_SELECT = const(0xAD)
SET_COM_OUT_DIR = const(0xC0)
SET_DISP_OFFSET = const(0xD3)
SET_COM_PIN_CFG = const(0xDA)
SET_DISP_CLK_DIV = const(0xD5)
SET_PRECHARGE = const(0xD9)
SET_VCOM_DESEL = const(0xDB)
SET_CHARGE_PUMP = const(0x8D)
# Subclassing FrameBuffer provides support for graphics primitives
# http://docs.micropython.org/en/latest/pyboard/library/framebuf.html
class SSD1306(framebuf.FrameBuffer):
def __init__(self, width, height, external_vcc):
self.width = width
self.height = height
self.external_vcc = external_vcc
self.pages = self.height // 8
self.buffer = bytearray(self.pages * self.width)
super().__init__(self.buffer, self.width, self.height, framebuf.MONO_VLSB)
self.init_display()
def init_display(self):
for cmd in (
SET_DISP, # display off
# address setting
SET_MEM_ADDR,
0x00, # horizontal
# resolution and layout
SET_DISP_START_LINE, # start at line 0
SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0
SET_MUX_RATIO,
self.height - 1,
SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0
SET_DISP_OFFSET,
0x00,
SET_COM_PIN_CFG,
0x02 if self.width > 2 * self.height else 0x12,
# timing and driving scheme
SET_DISP_CLK_DIV,
0x80,
SET_PRECHARGE,
0x22 if self.external_vcc else 0xF1,
SET_VCOM_DESEL,
0x30, # 0.83*Vcc
# display
SET_CONTRAST,
0xFF, # maximum
SET_ENTIRE_ON, # output follows RAM contents
SET_NORM_INV, # not inverted
SET_IREF_SELECT,
0x30, # enable internal IREF during display on
# charge pump
SET_CHARGE_PUMP,
0x10 if self.external_vcc else 0x14,
SET_DISP | 0x01, # display on
): # on
self.write_cmd(cmd)
self.fill(0)
self.show()
def poweroff(self):
self.write_cmd(SET_DISP)
def poweron(self):
self.write_cmd(SET_DISP | 0x01)
def contrast(self, contrast):
self.write_cmd(SET_CONTRAST)
self.write_cmd(contrast)
def invert(self, invert):
self.write_cmd(SET_NORM_INV | (invert & 1))
def rotate(self, rotate):
self.write_cmd(SET_COM_OUT_DIR | ((rotate & 1) << 3))
self.write_cmd(SET_SEG_REMAP | (rotate & 1))
def show(self):
x0 = 0
x1 = self.width - 1
if self.width != 128:
# narrow displays use centred columns
col_offset = (128 - self.width) // 2
x0 += col_offset
x1 += col_offset
self.write_cmd(SET_COL_ADDR)
self.write_cmd(x0)
self.write_cmd(x1)
self.write_cmd(SET_PAGE_ADDR)
self.write_cmd(0)
self.write_cmd(self.pages - 1)
self.write_data(self.buffer)
class SSD1306_I2C(SSD1306):
def __init__(self, width, height, i2c, addr=0x3C, external_vcc=False):
self.i2c = i2c
self.addr = addr
self.temp = bytearray(2)
self.write_list = [b"\x40", None] # Co=0, D/C#=1
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.temp[0] = 0x80 # Co=1, D/C#=0
self.temp[1] = cmd
self.i2c.writeto(self.addr, self.temp)
def write_data(self, buf):
self.write_list[1] = buf
self.i2c.writevto(self.addr, self.write_list)
class SSD1306_SPI(SSD1306):
def __init__(self, width, height, spi, dc, res, cs, external_vcc=False):
self.rate = 10 * 1024 * 1024
dc.init(dc.OUT, value=0)
res.init(res.OUT, value=0)
cs.init(cs.OUT, value=1)
self.spi = spi
self.dc = dc
self.res = res
self.cs = cs
import time
self.res(1)
time.sleep_ms(1)
self.res(0)
time.sleep_ms(10)
self.res(1)
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs(1)
self.dc(0)
self.cs(0)
self.spi.write(bytearray([cmd]))
self.cs(1)
def write_data(self, buf):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs(1)
self.dc(1)
self.cs(0)
self.spi.write(buf)
self.cs(1)

View File

@@ -202,34 +202,6 @@ custom_display_config = {
display = OLEDDisplay(display_config=custom_display_config)
```
## Saving Configuration
You can save a configuration to a file using the `save_config` function:
```python
from src.esp_sensors.config import save_config
# Save configuration to the default path (config.json)
save_config(config)
# Or specify a custom path
save_config(config, "custom_config.json")
```
## Creating Default Configuration
To create a default configuration file:
```python
from src.esp_sensors.config import create_default_config
# Create a default configuration file at the default path (config.json)
create_default_config()
# Or specify a custom path
create_default_config("custom_config.json")
```
## Configuration Parameters
### Common Parameters

View File

@@ -7,8 +7,6 @@ sensor names, and intervals without modifying the code.
"""
import json
import os
from typing import Dict, Any, Optional, Union, List
# Default configuration file path
DEFAULT_CONFIG_PATH = "config.json"
@@ -48,10 +46,14 @@ DEFAULT_CONFIG = {
"ssl": False,
"keepalive": 60,
},
"network": {
"ssid": "<your ssid>",
"password": "<your password>",
}
}
def load_config(config_path: str = DEFAULT_CONFIG_PATH) -> Dict[str, Any]:
def load_config(config_path: str = DEFAULT_CONFIG_PATH) :
"""
Load configuration from a JSON file.
@@ -64,43 +66,18 @@ def load_config(config_path: str = DEFAULT_CONFIG_PATH) -> Dict[str, Any]:
If the file doesn't exist or can't be read, returns the default configuration.
"""
try:
if os.path.exists(config_path):
with open(config_path, "r") as f:
config = json.load(f)
return config
else:
print(
f"Configuration file {config_path} not found. Using default configuration."
)
return DEFAULT_CONFIG
with open(config_path, "r") as f:
print(f"Loading configuration from '{config_path}'")
config = json.load(f)
return config
except Exception as e:
print(f"Error loading configuration: {e}. Using default configuration.")
return DEFAULT_CONFIG
def save_config(config: Dict[str, Any], config_path: str = DEFAULT_CONFIG_PATH) -> bool:
"""
Save configuration to a JSON file.
Args:
config: Configuration dictionary to save
config_path: Path to the configuration file (default: config.json)
Returns:
True if the configuration was saved successfully, False otherwise
"""
try:
with open(config_path, "w") as f:
json.dump(config, f, indent=4)
return True
except Exception as e:
print(f"Error saving configuration: {e}")
return False
def get_sensor_config(
sensor_type: str, config: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
sensor_type: str, config: dict | None = None
) -> dict:
"""
Get configuration for a specific sensor type.
@@ -123,8 +100,8 @@ def get_sensor_config(
def get_display_config(
display_type: str, config: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
display_type: str, config: dict | None = None
) -> dict:
"""
Get configuration for a specific display type.
@@ -147,8 +124,8 @@ def get_display_config(
def get_button_config(
button_name: str = "main_button", config: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
button_name: str = "main_button", config: dict | None = None
) -> dict:
"""
Get configuration for a specific button.
@@ -170,7 +147,7 @@ def get_button_config(
return button_config
def get_mqtt_config(config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
def get_mqtt_config(config: dict | None = None) -> dict:
"""
Get MQTT configuration.
@@ -189,16 +166,3 @@ def get_mqtt_config(config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
mqtt_config = DEFAULT_CONFIG.get("mqtt", {})
return mqtt_config
def create_default_config(config_path: str = DEFAULT_CONFIG_PATH) -> bool:
"""
Create a default configuration file.
Args:
config_path: Path to the configuration file (default: config.json)
Returns:
True if the configuration was created successfully, False otherwise
"""
return save_config(DEFAULT_CONFIG, config_path)

View File

@@ -2,9 +2,6 @@
DHT22 temperature and humidity sensor module for ESP32.
"""
import time
from typing import Dict, Any, Optional
try:
import dht
from machine import Pin
@@ -29,7 +26,7 @@ class DHT22Sensor(TemperatureSensor, HumiditySensor):
pin: int = None,
interval: int = None,
temperature_unit: str = None,
sensor_config: Dict[str, Any] = None,
sensor_config: dict | None = None,
):
"""
Initialize a new DHT22 sensor.
@@ -67,7 +64,10 @@ class DHT22Sensor(TemperatureSensor, HumiditySensor):
# Initialize the sensor if not in simulation mode
if not SIMULATION:
self._sensor = dht.DHT22(Pin(pin))
print("Initializing DHT22 sensor...")
pin1 = Pin(self.pin)
self._sensor = dht.DHT22(pin1)
print(f"DHT22 sensor initialized on pin {pin1}")
def apply_parameters(self, interval, name, pin, sensor_config):
# Get main parameters from config if not provided
@@ -160,7 +160,10 @@ class DHT22Sensor(TemperatureSensor, HumiditySensor):
humidity_metadata = HumiditySensor.get_metadata(self)
# Combine metadata from both parent classes
metadata = {**temp_metadata, **humidity_metadata}
metadata = {}
metadata.update(temp_metadata)
metadata.update(humidity_metadata)
# metadata = {**temp_metadata, **humidity_metadata}
# Ensure the name is the main sensor name, not the humidity sensor name
metadata["name"] = self.name
metadata["type"] = "DHT22"

View File

@@ -3,7 +3,6 @@ Humidity sensor module for ESP-based sensors.
"""
import random
from typing import Dict, Any, Optional
from .sensor import Sensor
from .config import get_sensor_config
@@ -16,7 +15,7 @@ class HumiditySensor(Sensor):
name: str = None,
pin: int = None,
interval: int = None,
sensor_config: Dict[str, Any] = None,
sensor_config: dict | None = None,
**kwargs,
):
"""

View File

@@ -7,7 +7,6 @@ It supports both real hardware and simulation mode.
import time
import json
from typing import Dict, Any, Optional, Union
# Import hardware-specific modules if available (for ESP32/ESP8266)
try:
@@ -56,7 +55,7 @@ except ImportError:
return
def setup_mqtt(mqtt_config: Dict[str, Any]) -> Optional[MQTTClient]:
def setup_mqtt(mqtt_config: dict) -> MQTTClient | None:
"""
Set up and connect to the MQTT broker.
@@ -92,9 +91,9 @@ def setup_mqtt(mqtt_config: Dict[str, Any]) -> Optional[MQTTClient]:
def publish_sensor_data(
client: Optional[MQTTClient],
mqtt_config: Dict[str, Any],
sensor: Any,
client: MQTTClient | None,
mqtt_config: dict,
sensor,
temperature: float,
humidity: float,
) -> bool:

View File

@@ -2,9 +2,6 @@
OLED display module for ESP32 using SSD1306 controller.
"""
import time
from typing import Dict, Any, Optional
try:
from machine import Pin, I2C
import ssd1306
@@ -30,7 +27,7 @@ class OLEDDisplay(Sensor):
address: int | str = None,
interval: int = None,
on_time: int = None,
display_config: Dict[str, Any] = None,
display_config = None,
):
"""
Initialize a new OLED display.

View File

@@ -2,8 +2,6 @@
Base sensor module for ESP-based sensors.
"""
from typing import Dict, Any, Optional
from .config import get_sensor_config
class Sensor:
@@ -14,7 +12,7 @@ class Sensor:
name: str = None,
pin: int = None,
interval: int = None,
sensor_config: Dict[str, Any] = None,
sensor_config = None,
):
"""
Initialize a new sensor.
@@ -37,7 +35,7 @@ class Sensor:
interval if interval is not None else sensor_config.get("interval", 60)
)
self._last_reading: Optional[float] = None
self._last_reading= None
def read(self) -> float:
"""
@@ -51,7 +49,7 @@ class Sensor:
self._last_reading = 0.0
return self._last_reading
def get_metadata(self) -> Dict[str, Any]:
def get_metadata(self) :
"""
Get sensor metadata.

View File

@@ -3,7 +3,6 @@ Temperature sensor module for ESP-based sensors.
"""
import random
from typing import Dict, Any, Optional
from .sensor import Sensor
from .config import get_sensor_config
@@ -17,7 +16,7 @@ class TemperatureSensor(Sensor):
pin: int = None,
interval: int = None,
unit: str = None,
sensor_config: Dict[str, Any] = None,
sensor_config: dict | None = None,
):
"""
Initialize a new temperature sensor.

View File

@@ -10,7 +10,6 @@ This program:
"""
import time
import sys
from esp_sensors.oled_display import OLEDDisplay
from esp_sensors.dht22 import DHT22Sensor
@@ -81,151 +80,92 @@ def main():
"""
Main function to demonstrate button-triggered sensor display with MQTT publishing.
"""
# record start time
last_read_time = time.time() # this is to make sure, the sleep time is correct
# Load configuration
config = load_config()
button_config = get_button_config("main_button", config)
# print('config: ', config)
# button_config = get_button_config("main_button", config)
mqtt_config = get_mqtt_config(config)
dht_config = get_sensor_config("dht22", config)
display_config = get_display_config("oled", config)
network_config = config.get("network", {})
# Initialize a DHT22 sensor using configuration
dht_sensor = DHT22Sensor(
sensor_config=get_sensor_config("dht22", config) # Pass the loaded config
)
dht_sensor = DHT22Sensor(sensor_config=dht_config)
if network_config.get("ssid"):
ssid = network_config.get("ssid")
password = network_config.get("password")
connect_wifi(ssid, password)
# Initialize an OLED display using configuration
display = OLEDDisplay(
display_config=get_display_config("oled", config) # Pass the loaded config
)
display = OLEDDisplay(display_config=display_config)
# Set up MQTT client if enabled
mqtt_client = setup_mqtt(mqtt_config)
mqtt_publish_interval = mqtt_config.get("publish_interval", 60)
last_publish_time = 0
last_read_time = 0 # Track the last time sensors were read
# Set up button using configuration
button_pin = button_config.get("pin", 0)
if not SIMULATION:
pull_up = button_config.get("pull_up", True)
button = Pin(button_pin, Pin.IN, Pin.PULL_UP if pull_up else None)
# Display initialization message
# # Set up button using configuration
# button_pin = button_config.get("pin", 0)
# if not SIMULATION:
# pull_up = button_config.get("pull_up", True)
# button = Pin(button_pin, Pin.IN, Pin.PULL_UP if pull_up else None)
#
# # Display initialization message
display.clear()
display.display_text("Ready - Auto & Button", 0, 0)
print(
f"System initialized. Will run every {mqtt_publish_interval} seconds or on button press..."
)
print(f"System initialized. Will run every {mqtt_publish_interval} seconds or on button press...")
# Main loop - sleep until button press, then read and display sensor data
try:
while True:
# Calculate time until next scheduled reading
current_time = time.time()
time_since_last_read = current_time - last_read_time
time_until_next_read = max(
0, mqtt_publish_interval - int(time_since_last_read)
)
# while True:
print('sleeping for 5 seconds for debugging')
time.sleep(5)
# Wait for button press or until next scheduled reading
if SIMULATION:
# In simulation mode, wait for Enter key with timeout
# Read sensor values
temperature = dht_sensor.read_temperature()
humidity = dht_sensor.read_humidity()
#
# # Format values for display
temp_str = f"Temp: {temperature:.1f} C"
hum_str = f"Humidity: {humidity:.1f}%"
time_str = f"Time: {time.time():.0f}"
name_str = f"Sensor: {dht_sensor.name}"
if not simulate_button_press(timeout=time_until_next_read):
break # Exit if 'q' was pressed or Ctrl+C
# Display values
# TODO: only display values, if the button has been clicked
display.display_values(
[name_str, temp_str, hum_str, time_str, "Press button again"]
)
time.sleep(3)
else:
# In hardware mode, check if button is pressed (active low)
button_pressed_value = 0 if not pull_up else 1 # TODO: check if 1 is correct
if button.value() == button_pressed_value: # Button is pressed
pass
elif time_since_last_read >= mqtt_publish_interval:
# Time for scheduled reading
pass
else:
# Go to light sleep mode to save power
# Wake up on pin change (button press) or timer
print(
f"Entering light sleep mode for {time_until_next_read:.1f} seconds or until button press..."
)
# Print to console
print('='*20)
print(f"Sensor data: {temp_str}, {hum_str}")
print('='*20)
# Set up wake on button press
esp32.wake_on_ext0(
pin=button, level=button_pressed_value
) # Wake on button press (low)
# Publish to MQTT
publish_sensor_data(mqtt_client, mqtt_config, dht_sensor, temperature, humidity)
# Set up wake on timer
if last_read_time > 0: # Skip timer on first run
# Convert seconds to milliseconds for sleep
esp32.wake_on_timer(time_until_next_read * 1000)
if mqtt_client:
try:
mqtt_client.disconnect()
print("MQTT client disconnected")
except Exception as e:
print(f"Error disconnecting MQTT client: {e}")
# Enter light sleep
esp32.light_sleep() # Light sleep preserves RAM but saves power
time_until_next_read = mqtt_publish_interval - (time.time() - last_read_time)
print('sleeping for', time_until_next_read, 'seconds')
if not SIMULATION:
deepsleep(time_until_next_read * 1000)
else:
# Simulate deep sleep
print(f"Simulated deep sleep for {time_until_next_read:.1f} seconds")
time.sleep(time_until_next_read)
# When we get here, either the button was pressed or the timer expired
print(f"Awake from light sleep")
# Determine if this was triggered by a button press or scheduled interval
if SIMULATION:
trigger_source = "user input or scheduled interval"
else:
trigger_source = (
"button press" if button.value() == 0 else "scheduled interval"
)
print(f"Reading sensor data (triggered by {trigger_source})...")
# Read sensor values
temperature = dht_sensor.read_temperature()
humidity = dht_sensor.read_humidity()
# Update last read time
last_read_time = time.time()
# Adjust for actual sleep duration (so if we sleep longer or shorter (because of
# the button) than expected, we don't miss the next scheduled read)
actual_sleep_duration = last_read_time - current_time
last_read_time -= (
(actual_sleep_duration - time_until_next_read)
% mqtt_publish_interval
)
# Format values for display
temp_str = f"Temp: {temperature:.1f} C"
hum_str = f"Humidity: {humidity:.1f}%"
time_str = f"Time: {time.time():.0f}"
name_str = f"Sensor: {dht_sensor.name}"
# Display values
# TODO: only display values, if the button has been clicked
display.display_values(
[name_str, temp_str, hum_str, time_str, "Press button again"]
)
# Print to console
print(f"Updated display with: {temp_str}, {hum_str}")
# Publish to MQTT if enabled
current_time = time.time()
publish_sensor_data(
mqtt_client, mqtt_config, dht_sensor, temperature, humidity
)
if mqtt_client and (
current_time - last_publish_time >= mqtt_publish_interval
):
last_publish_time = current_time
print(f"Next normal MQTT publish in {mqtt_publish_interval} seconds")
# Keep display on for a few seconds before going back to sleep
time.sleep(display.on_time)
# Clear display to save power
display.clear()
display.display_text("Ready - Auto & Button", 0, 0)
print("last_read_time", last_read_time)
if SIMULATION:
print(
f"Display cleared. Will run again in {mqtt_publish_interval - (time.time() - last_read_time):.1f} seconds or on button press."
)
except KeyboardInterrupt:
# Clean up on exit
@@ -245,5 +185,23 @@ def main():
print("Program terminated by user")
def connect_wifi(ssid, password):
import network
print(f'Connecting to WIFI: "{ssid}"')
# Connect to your network
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
connection_start_time = time.time()
while not station.isconnected():
# Check if connection attempt has timed out
if time.time() - connection_start_time > 10:
print("Connection timed out")
return False
pass
print('Connection successful')
print(station.ifconfig())
if __name__ == "__main__":
main()

View File

@@ -8,10 +8,8 @@ import tempfile
import pytest
from src.esp_sensors.config import (
load_config,
save_config,
get_sensor_config,
get_display_config,
create_default_config,
DEFAULT_CONFIG,
)
@@ -27,39 +25,6 @@ def test_load_default_config():
assert "displays" in config
def test_save_and_load_config():
"""Test saving and loading configuration."""
# Create a temporary file
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as temp_file:
temp_path = temp_file.name
try:
# Create a test configuration
test_config = {
"sensors": {
"test_sensor": {"name": "Test Sensor", "pin": 10, "interval": 30}
}
}
# Save the configuration
result = save_config(test_config, temp_path)
assert result is True
# Load the configuration
loaded_config = load_config(temp_path)
# Check that the loaded configuration matches the saved one
assert loaded_config == test_config
assert loaded_config["sensors"]["test_sensor"]["name"] == "Test Sensor"
assert loaded_config["sensors"]["test_sensor"]["pin"] == 10
assert loaded_config["sensors"]["test_sensor"]["interval"] == 30
finally:
# Clean up the temporary file
if os.path.exists(temp_path):
os.unlink(temp_path)
def test_get_sensor_config():
"""Test getting sensor configuration."""
# Create a test configuration
@@ -96,32 +61,3 @@ def test_get_display_config():
# Get configuration for a non-existent display (should return default or empty dict)
non_existent_config = get_display_config("non_existent", test_config)
assert isinstance(non_existent_config, dict)
def test_create_default_config():
"""Test creating a default configuration file."""
# Create a temporary file path
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as temp_file:
temp_path = temp_file.name
try:
# Remove the file (we just want the path)
os.unlink(temp_path)
# Create the default configuration
result = create_default_config(temp_path)
assert result is True
# Check that the file exists
assert os.path.exists(temp_path)
# Load the configuration and check it matches the default
with open(temp_path, "r") as f:
config = json.load(f)
assert config == DEFAULT_CONFIG
finally:
# Clean up the temporary file
if os.path.exists(temp_path):
os.unlink(temp_path)