CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-gpiozero

A simple interface to GPIO devices with Raspberry Pi

Pending
Overview
Eval results
Files

system-monitoring.mddocs/

System Monitoring Devices

Internal system monitoring devices for CPU temperature, disk usage, network connectivity, and system load monitoring. These devices provide access to Raspberry Pi system metrics and can be used as sources for other devices or in event-driven applications.

Base Classes

InternalDevice

Base class for devices that monitor internal system state.

class InternalDevice(Device):
    def __init__(self, *, pin_factory=None):
        """
        Base class for internal system monitoring devices.
        
        Parameters:
        - pin_factory: Factory or None - Pin factory for advanced usage
        """

    @property
    def value(self) -> float:
        """Current normalized value (0.0-1.0)."""

    @property
    def is_active(self) -> bool:
        """Returns True if value exceeds threshold."""

    def close(self):
        """Close the device and stop monitoring."""

PolledInternalDevice

Base class for internal devices that require periodic polling.

class PolledInternalDevice(InternalDevice):
    def __init__(self, *, poll_interval=1.0, pin_factory=None):
        """
        Base class for polled internal devices.
        
        Parameters:
        - poll_interval: float - Polling interval in seconds
        - pin_factory: Factory or None - Pin factory for advanced usage
        """

    @property  
    def poll_interval(self) -> float:
        """Polling interval in seconds."""

    @poll_interval.setter
    def poll_interval(self, value: float): ...

System Monitoring Devices

CPUTemperature

CPU core temperature monitoring.

class CPUTemperature(InternalDevice):
    def __init__(self, *, sensor_file='/sys/class/thermal/thermal_zone0/temp', min_temp=0.0, max_temp=100.0, threshold=80.0, pin_factory=None):
        """
        CPU temperature monitoring device.
        
        Parameters:
        - sensor_file: str - Path to temperature sensor file
        - min_temp: float - Minimum temperature for scaling (°C)
        - max_temp: float - Maximum temperature for scaling (°C)
        - threshold: float - Temperature threshold for is_active (°C)
        - pin_factory: Factory or None - Pin factory for advanced usage
        """

    @property
    def temperature(self) -> float:
        """Current CPU temperature in Celsius."""

    @property
    def min_temp(self) -> float:
        """Minimum temperature for scaling."""

    @property
    def max_temp(self) -> float:
        """Maximum temperature for scaling."""

    @property
    def threshold(self) -> float:
        """Temperature threshold for is_active."""

    @threshold.setter
    def threshold(self, value: float): ...

    @property
    def is_active(self) -> bool:
        """Returns True if temperature exceeds threshold."""

LoadAverage

System load average monitoring.

class LoadAverage(PolledInternalDevice):
    def __init__(self, *, min_load_average=0.0, max_load_average=1.0, threshold=0.8, minutes=1, pin_factory=None):
        """
        System load average monitoring device.
        
        Parameters:
        - min_load_average: float - Minimum load for scaling
        - max_load_average: float - Maximum load for scaling
        - threshold: float - Load threshold for is_active
        - minutes: int - Load average period (1, 5, or 15 minutes)
        - pin_factory: Factory or None - Pin factory for advanced usage
        """

    @property
    def load_average(self) -> float:
        """Current load average."""

    @property 
    def min_load_average(self) -> float:
        """Minimum load average for scaling."""

    @property
    def max_load_average(self) -> float:
        """Maximum load average for scaling."""

    @property
    def threshold(self) -> float:
        """Load average threshold for is_active."""

    @threshold.setter
    def threshold(self, value: float): ...

    @property
    def minutes(self) -> int:
        """Load average period in minutes."""

    @property
    def is_active(self) -> bool:
        """Returns True if load average exceeds threshold."""

DiskUsage

Disk space usage monitoring.

class DiskUsage(PolledInternalDevice):
    def __init__(self, *, filesystem='/', threshold=0.8, pin_factory=None):
        """
        Disk usage monitoring device.
        
        Parameters:
        - filesystem: str - Filesystem path to monitor
        - threshold: float - Usage threshold for is_active (0.0-1.0)
        - pin_factory: Factory or None - Pin factory for advanced usage
        """

    @property
    def usage(self) -> float:
        """Current disk usage as fraction (0.0-1.0)."""

    @property
    def percent(self) -> float:
        """Current disk usage as percentage (0.0-100.0)."""

    @property
    def used(self) -> int:
        """Used disk space in bytes."""

    @property
    def free(self) -> int:
        """Free disk space in bytes."""

    @property
    def total(self) -> int:
        """Total disk space in bytes."""

    @property
    def filesystem(self) -> str:
        """Filesystem path being monitored."""

    @property
    def threshold(self) -> float:
        """Usage threshold for is_active."""

    @threshold.setter
    def threshold(self, value: float): ...

    @property
    def is_active(self) -> bool:
        """Returns True if usage exceeds threshold."""

TimeOfDay

Time-based device for scheduling and time-dependent control.

class TimeOfDay(InternalDevice):
    def __init__(self, start_time=(6, 0), end_time=(18, 0), *, utc=False, pin_factory=None):
        """
        Time of day device for scheduling.
        
        Parameters:
        - start_time: tuple - Start time as (hour, minute)
        - end_time: tuple - End time as (hour, minute)
        - utc: bool - True for UTC time, False for local time
        - pin_factory: Factory or None - Pin factory for advanced usage
        """

    @property
    def time(self) -> tuple:
        """Current time as (hour, minute, second) tuple."""

    @property
    def start_time(self) -> tuple:
        """Start time as (hour, minute) tuple."""

    @start_time.setter
    def start_time(self, value: tuple): ...

    @property
    def end_time(self) -> tuple:
        """End time as (hour, minute) tuple."""

    @end_time.setter
    def end_time(self, value: tuple): ...

    @property
    def utc(self) -> bool:
        """True if using UTC time."""

    @property
    def is_active(self) -> bool:
        """Returns True if current time is between start_time and end_time."""

    @property
    def value(self) -> float:
        """Time within active period as fraction (0.0-1.0)."""

PingServer

Network connectivity monitoring via ping.

class PingServer(PolledInternalDevice):
    def __init__(self, host='8.8.8.8', *, pin_factory=None):
        """
        Network connectivity monitoring via ping.
        
        Parameters:
        - host: str - Host to ping for connectivity check
        - pin_factory: Factory or None - Pin factory for advanced usage
        """

    @property
    def host(self) -> str:
        """Host being pinged."""

    @property
    def is_active(self) -> bool:
        """Returns True if host is reachable."""

    @property
    def value(self) -> float:
        """1.0 if host is reachable, 0.0 otherwise."""

Usage Examples

CPU Temperature Monitoring

from gpiozero import CPUTemperature, LED
from signal import pause

cpu = CPUTemperature(threshold=70.0)
warning_led = LED(17)

def cpu_hot():
    print(f"CPU temperature is high: {cpu.temperature:.1f}°C")
    warning_led.on()

def cpu_normal():
    print(f"CPU temperature is normal: {cpu.temperature:.1f}°C")
    warning_led.off()

cpu.when_activated = cpu_hot
cpu.when_deactivated = cpu_normal

# Check temperature
print(f"Current CPU temperature: {cpu.temperature:.1f}°C")
print(f"Normalized value: {cpu.value:.2f}")

pause()

System Load Monitoring

from gpiozero import LoadAverage, RGBLED
from signal import pause

load = LoadAverage(minutes=1, threshold=0.8)
status_led = RGBLED(red=2, green=3, blue=4)

def update_status():
    load_value = load.load_average
    if load_value > 2.0:
        status_led.color = (1, 0, 0)  # Red - high load
    elif load_value > 1.0:
        status_led.color = (1, 1, 0)  # Yellow - medium load
    else:
        status_led.color = (0, 1, 0)  # Green - low load

# Update status every 5 seconds
load.when_activated = update_status
load.when_deactivated = update_status

pause()

Disk Usage Alert

from gpiozero import DiskUsage, Buzzer
from time import sleep

disk = DiskUsage(filesystem='/', threshold=0.9)
alarm = Buzzer(17)

while True:
    usage = disk.usage * 100
    print(f"Disk usage: {usage:.1f}%")
    print(f"Free space: {disk.free / (1024**3):.1f} GB")
    
    if disk.is_active:
        print("WARNING: Disk usage is high!")
        alarm.beep(on_time=0.1, off_time=0.1, n=3)
    
    sleep(60)  # Check every minute

Time-Based Control

from gpiozero import TimeOfDay, LED
from signal import pause

# Garden lights on from sunset to sunrise (approximate)
daylight = TimeOfDay(start_time=(6, 0), end_time=(20, 0))
garden_lights = LED(17)

def lights_on():
    print("It's dark - turning on garden lights")
    garden_lights.on()

def lights_off():
    print("It's daylight - turning off garden lights")
    garden_lights.off()

# Lights are on when NOT in daylight hours
daylight.when_deactivated = lights_on
daylight.when_activated = lights_off

# Set initial state
if daylight.is_active:
    lights_off()
else:
    lights_on()

pause()

Network Connectivity Monitor

from gpiozero import PingServer, LED
from signal import pause

internet = PingServer(host='8.8.8.8')
connection_led = LED(17)

def connected():
    print("Internet connection is up")
    connection_led.on()

def disconnected():
    print("Internet connection is down")
    connection_led.blink()

internet.when_activated = connected
internet.when_deactivated = disconnected

# Set initial state
if internet.is_active:
    connected()
else:
    disconnected()

pause()

Composite System Monitor

from gpiozero import CPUTemperature, LoadAverage, DiskUsage, LEDBoard
from time import sleep

# System monitoring dashboard
temp = CPUTemperature(threshold=70.0)
load = LoadAverage(threshold=1.0)
disk = DiskUsage(threshold=0.8)

# Status LEDs
status_leds = LEDBoard(temp=17, load=18, disk=19, system=20)

def update_status():
    # Temperature status
    status_leds.temp.value = temp.value
    
    # Load status  
    status_leds.load.value = load.value
    
    # Disk status
    status_leds.disk.value = disk.value
    
    # Overall system status
    if temp.is_active or load.is_active or disk.is_active:
        status_leds.system.blink()
    else:
        status_leds.system.on()

# Update dashboard every 10 seconds
while True:
    update_status()
    
    print(f"CPU: {temp.temperature:.1f}°C, "
          f"Load: {load.load_average:.2f}, "
          f"Disk: {disk.percent:.1f}%")
    
    sleep(10)

Event-Based System Response

from gpiozero import CPUTemperature, LoadAverage, Motor
from signal import pause

cpu = CPUTemperature(threshold=75.0)
load = LoadAverage(threshold=2.0)
cooling_fan = Motor(forward=2, backward=3)

def start_cooling():
    print("System overheating - starting cooling fan")
    cooling_fan.forward(0.8)

def stop_cooling():
    if not load.is_active:  # Only stop if load is also normal
        print("Temperature normal - stopping cooling fan")
        cooling_fan.stop()

def high_load():
    print("High system load detected")
    if not cpu.is_active:  # Start fan if not already running
        cooling_fan.forward(0.5)

def normal_load():
    if not cpu.is_active:  # Only stop if temperature is also normal
        print("Load normal - reducing fan speed")
        cooling_fan.stop()

# Connect events
cpu.when_activated = start_cooling
cpu.when_deactivated = stop_cooling
load.when_activated = high_load
load.when_deactivated = normal_load

pause()

Data Logging System

from gpiozero import CPUTemperature, LoadAverage, DiskUsage
import csv
import time
from datetime import datetime

# System monitors
cpu = CPUTemperature()
load = LoadAverage()
disk = DiskUsage()

# Data logging
with open('system_metrics.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['timestamp', 'cpu_temp', 'load_avg', 'disk_usage'])
    
    try:
        while True:
            timestamp = datetime.now().isoformat()
            metrics = [
                timestamp,
                cpu.temperature,
                load.load_average,
                disk.percent
            ]
            
            writer.writerow(metrics)
            print(f"Logged: CPU={cpu.temperature:.1f}°C, "
                  f"Load={load.load_average:.2f}, "
                  f"Disk={disk.percent:.1f}%")
            
            time.sleep(60)  # Log every minute
            
    except KeyboardInterrupt:
        print("\nLogging stopped")

Install with Tessl CLI

npx tessl i tessl/pypi-gpiozero

docs

composite-devices.md

index.md

input-devices.md

output-devices.md

pin-factories.md

spi-devices.md

system-monitoring.md

tone-system.md

tools.md

tile.json