Skip to content

Created occupancy and noise sensor scripts #19

Merged
merged 1 commit into from
Mar 11, 2026
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions noise_sensor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import random
import time
from sensor_base import SensorBase


class NoiseSensor(SensorBase):
"""
Noise sensor that simulates gradual drift in noise levels.
Values range from 30 dB (quiet) to 100 dB (loud environment).
"""

def __init__(self, room_id):
super().__init__("noise", room_id)

# Start at a realistic quiet-to-moderate level
self.current_value = random.uniform(40, 60)

def read_value(self):
"""
Simulate gradual noise drift instead of sudden jumps.
"""

# Small drift step
drift = random.uniform(-5, 5)

self.current_value += drift

# Clamp value within realistic range
self.current_value = max(30, min(100, self.current_value))

return round(self.current_value, 2)

def generate_noise_reading(self):
"""
Generate a formatted JSON noise reading.
"""
value = self.read_value()
return self.generate_reading(value, "dB")


# ------------------------
# Manual Test
# ------------------------

if __name__ == "__main__":

sensor = NoiseSensor("Room101")

print("Testing noise drift:\n")

for _ in range(5):
print(sensor.generate_noise_reading())
time.sleep(1)
56 changes: 56 additions & 0 deletions occupancy_sensor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import random
import time
from sensor_base import SensorBase


class OccupancySensor(SensorBase):
"""
Occupancy sensor that simulates people entering and leaving a room.
Values range from 0 to the room's maximum capacity.
"""

def __init__(self, room_id, capacity):
super().__init__("occupancy", room_id)

self.capacity = capacity

# Start with a realistic initial occupancy
self.current_value = random.randint(0, capacity // 2)

def read_value(self):
"""
Simulate gradual occupancy changes.
People arrive or leave in small groups.
"""

# Small change in occupancy
change = random.randint(-3, 3)

self.current_value += change

# Ensure occupancy stays within valid limits
self.current_value = max(0, min(self.capacity, self.current_value))

return self.current_value

def generate_occupancy_reading(self):
"""
Generate a formatted JSON occupancy reading.
"""
value = self.read_value()
return self.generate_reading(value, "people")


# ------------------------
# Manual Test
# ------------------------

if __name__ == "__main__":

sensor = OccupancySensor("Room101", 40)

print("Testing occupancy drift:\n")

for _ in range(5):
print(sensor.generate_occupancy_reading())
time.sleep(1)