or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

composite-devices.mdindex.mdinput-devices.mdoutput-devices.mdpin-factories.mdspi-devices.mdsystem-monitoring.mdtone-system.mdtools.md

system-monitoring.mddocs/

0

# System Monitoring Devices

1

2

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.

3

4

## Base Classes

5

6

### InternalDevice

7

8

Base class for devices that monitor internal system state.

9

10

```python { .api }

11

class InternalDevice(Device):

12

def __init__(self, *, pin_factory=None):

13

"""

14

Base class for internal system monitoring devices.

15

16

Parameters:

17

- pin_factory: Factory or None - Pin factory for advanced usage

18

"""

19

20

@property

21

def value(self) -> float:

22

"""Current normalized value (0.0-1.0)."""

23

24

@property

25

def is_active(self) -> bool:

26

"""Returns True if value exceeds threshold."""

27

28

def close(self):

29

"""Close the device and stop monitoring."""

30

```

31

32

### PolledInternalDevice

33

34

Base class for internal devices that require periodic polling.

35

36

```python { .api }

37

class PolledInternalDevice(InternalDevice):

38

def __init__(self, *, poll_interval=1.0, pin_factory=None):

39

"""

40

Base class for polled internal devices.

41

42

Parameters:

43

- poll_interval: float - Polling interval in seconds

44

- pin_factory: Factory or None - Pin factory for advanced usage

45

"""

46

47

@property

48

def poll_interval(self) -> float:

49

"""Polling interval in seconds."""

50

51

@poll_interval.setter

52

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

53

```

54

55

## System Monitoring Devices

56

57

### CPUTemperature

58

59

CPU core temperature monitoring.

60

61

```python { .api }

62

class CPUTemperature(InternalDevice):

63

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):

64

"""

65

CPU temperature monitoring device.

66

67

Parameters:

68

- sensor_file: str - Path to temperature sensor file

69

- min_temp: float - Minimum temperature for scaling (°C)

70

- max_temp: float - Maximum temperature for scaling (°C)

71

- threshold: float - Temperature threshold for is_active (°C)

72

- pin_factory: Factory or None - Pin factory for advanced usage

73

"""

74

75

@property

76

def temperature(self) -> float:

77

"""Current CPU temperature in Celsius."""

78

79

@property

80

def min_temp(self) -> float:

81

"""Minimum temperature for scaling."""

82

83

@property

84

def max_temp(self) -> float:

85

"""Maximum temperature for scaling."""

86

87

@property

88

def threshold(self) -> float:

89

"""Temperature threshold for is_active."""

90

91

@threshold.setter

92

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

93

94

@property

95

def is_active(self) -> bool:

96

"""Returns True if temperature exceeds threshold."""

97

```

98

99

### LoadAverage

100

101

System load average monitoring.

102

103

```python { .api }

104

class LoadAverage(PolledInternalDevice):

105

def __init__(self, *, min_load_average=0.0, max_load_average=1.0, threshold=0.8, minutes=1, pin_factory=None):

106

"""

107

System load average monitoring device.

108

109

Parameters:

110

- min_load_average: float - Minimum load for scaling

111

- max_load_average: float - Maximum load for scaling

112

- threshold: float - Load threshold for is_active

113

- minutes: int - Load average period (1, 5, or 15 minutes)

114

- pin_factory: Factory or None - Pin factory for advanced usage

115

"""

116

117

@property

118

def load_average(self) -> float:

119

"""Current load average."""

120

121

@property

122

def min_load_average(self) -> float:

123

"""Minimum load average for scaling."""

124

125

@property

126

def max_load_average(self) -> float:

127

"""Maximum load average for scaling."""

128

129

@property

130

def threshold(self) -> float:

131

"""Load average threshold for is_active."""

132

133

@threshold.setter

134

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

135

136

@property

137

def minutes(self) -> int:

138

"""Load average period in minutes."""

139

140

@property

141

def is_active(self) -> bool:

142

"""Returns True if load average exceeds threshold."""

143

```

144

145

### DiskUsage

146

147

Disk space usage monitoring.

148

149

```python { .api }

150

class DiskUsage(PolledInternalDevice):

151

def __init__(self, *, filesystem='/', threshold=0.8, pin_factory=None):

152

"""

153

Disk usage monitoring device.

154

155

Parameters:

156

- filesystem: str - Filesystem path to monitor

157

- threshold: float - Usage threshold for is_active (0.0-1.0)

158

- pin_factory: Factory or None - Pin factory for advanced usage

159

"""

160

161

@property

162

def usage(self) -> float:

163

"""Current disk usage as fraction (0.0-1.0)."""

164

165

@property

166

def percent(self) -> float:

167

"""Current disk usage as percentage (0.0-100.0)."""

168

169

@property

170

def used(self) -> int:

171

"""Used disk space in bytes."""

172

173

@property

174

def free(self) -> int:

175

"""Free disk space in bytes."""

176

177

@property

178

def total(self) -> int:

179

"""Total disk space in bytes."""

180

181

@property

182

def filesystem(self) -> str:

183

"""Filesystem path being monitored."""

184

185

@property

186

def threshold(self) -> float:

187

"""Usage threshold for is_active."""

188

189

@threshold.setter

190

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

191

192

@property

193

def is_active(self) -> bool:

194

"""Returns True if usage exceeds threshold."""

195

```

196

197

### TimeOfDay

198

199

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

200

201

```python { .api }

202

class TimeOfDay(InternalDevice):

203

def __init__(self, start_time=(6, 0), end_time=(18, 0), *, utc=False, pin_factory=None):

204

"""

205

Time of day device for scheduling.

206

207

Parameters:

208

- start_time: tuple - Start time as (hour, minute)

209

- end_time: tuple - End time as (hour, minute)

210

- utc: bool - True for UTC time, False for local time

211

- pin_factory: Factory or None - Pin factory for advanced usage

212

"""

213

214

@property

215

def time(self) -> tuple:

216

"""Current time as (hour, minute, second) tuple."""

217

218

@property

219

def start_time(self) -> tuple:

220

"""Start time as (hour, minute) tuple."""

221

222

@start_time.setter

223

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

224

225

@property

226

def end_time(self) -> tuple:

227

"""End time as (hour, minute) tuple."""

228

229

@end_time.setter

230

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

231

232

@property

233

def utc(self) -> bool:

234

"""True if using UTC time."""

235

236

@property

237

def is_active(self) -> bool:

238

"""Returns True if current time is between start_time and end_time."""

239

240

@property

241

def value(self) -> float:

242

"""Time within active period as fraction (0.0-1.0)."""

243

```

244

245

### PingServer

246

247

Network connectivity monitoring via ping.

248

249

```python { .api }

250

class PingServer(PolledInternalDevice):

251

def __init__(self, host='8.8.8.8', *, pin_factory=None):

252

"""

253

Network connectivity monitoring via ping.

254

255

Parameters:

256

- host: str - Host to ping for connectivity check

257

- pin_factory: Factory or None - Pin factory for advanced usage

258

"""

259

260

@property

261

def host(self) -> str:

262

"""Host being pinged."""

263

264

@property

265

def is_active(self) -> bool:

266

"""Returns True if host is reachable."""

267

268

@property

269

def value(self) -> float:

270

"""1.0 if host is reachable, 0.0 otherwise."""

271

```

272

273

## Usage Examples

274

275

### CPU Temperature Monitoring

276

277

```python

278

from gpiozero import CPUTemperature, LED

279

from signal import pause

280

281

cpu = CPUTemperature(threshold=70.0)

282

warning_led = LED(17)

283

284

def cpu_hot():

285

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

286

warning_led.on()

287

288

def cpu_normal():

289

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

290

warning_led.off()

291

292

cpu.when_activated = cpu_hot

293

cpu.when_deactivated = cpu_normal

294

295

# Check temperature

296

print(f"Current CPU temperature: {cpu.temperature:.1f}°C")

297

print(f"Normalized value: {cpu.value:.2f}")

298

299

pause()

300

```

301

302

### System Load Monitoring

303

304

```python

305

from gpiozero import LoadAverage, RGBLED

306

from signal import pause

307

308

load = LoadAverage(minutes=1, threshold=0.8)

309

status_led = RGBLED(red=2, green=3, blue=4)

310

311

def update_status():

312

load_value = load.load_average

313

if load_value > 2.0:

314

status_led.color = (1, 0, 0) # Red - high load

315

elif load_value > 1.0:

316

status_led.color = (1, 1, 0) # Yellow - medium load

317

else:

318

status_led.color = (0, 1, 0) # Green - low load

319

320

# Update status every 5 seconds

321

load.when_activated = update_status

322

load.when_deactivated = update_status

323

324

pause()

325

```

326

327

### Disk Usage Alert

328

329

```python

330

from gpiozero import DiskUsage, Buzzer

331

from time import sleep

332

333

disk = DiskUsage(filesystem='/', threshold=0.9)

334

alarm = Buzzer(17)

335

336

while True:

337

usage = disk.usage * 100

338

print(f"Disk usage: {usage:.1f}%")

339

print(f"Free space: {disk.free / (1024**3):.1f} GB")

340

341

if disk.is_active:

342

print("WARNING: Disk usage is high!")

343

alarm.beep(on_time=0.1, off_time=0.1, n=3)

344

345

sleep(60) # Check every minute

346

```

347

348

### Time-Based Control

349

350

```python

351

from gpiozero import TimeOfDay, LED

352

from signal import pause

353

354

# Garden lights on from sunset to sunrise (approximate)

355

daylight = TimeOfDay(start_time=(6, 0), end_time=(20, 0))

356

garden_lights = LED(17)

357

358

def lights_on():

359

print("It's dark - turning on garden lights")

360

garden_lights.on()

361

362

def lights_off():

363

print("It's daylight - turning off garden lights")

364

garden_lights.off()

365

366

# Lights are on when NOT in daylight hours

367

daylight.when_deactivated = lights_on

368

daylight.when_activated = lights_off

369

370

# Set initial state

371

if daylight.is_active:

372

lights_off()

373

else:

374

lights_on()

375

376

pause()

377

```

378

379

### Network Connectivity Monitor

380

381

```python

382

from gpiozero import PingServer, LED

383

from signal import pause

384

385

internet = PingServer(host='8.8.8.8')

386

connection_led = LED(17)

387

388

def connected():

389

print("Internet connection is up")

390

connection_led.on()

391

392

def disconnected():

393

print("Internet connection is down")

394

connection_led.blink()

395

396

internet.when_activated = connected

397

internet.when_deactivated = disconnected

398

399

# Set initial state

400

if internet.is_active:

401

connected()

402

else:

403

disconnected()

404

405

pause()

406

```

407

408

### Composite System Monitor

409

410

```python

411

from gpiozero import CPUTemperature, LoadAverage, DiskUsage, LEDBoard

412

from time import sleep

413

414

# System monitoring dashboard

415

temp = CPUTemperature(threshold=70.0)

416

load = LoadAverage(threshold=1.0)

417

disk = DiskUsage(threshold=0.8)

418

419

# Status LEDs

420

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

421

422

def update_status():

423

# Temperature status

424

status_leds.temp.value = temp.value

425

426

# Load status

427

status_leds.load.value = load.value

428

429

# Disk status

430

status_leds.disk.value = disk.value

431

432

# Overall system status

433

if temp.is_active or load.is_active or disk.is_active:

434

status_leds.system.blink()

435

else:

436

status_leds.system.on()

437

438

# Update dashboard every 10 seconds

439

while True:

440

update_status()

441

442

print(f"CPU: {temp.temperature:.1f}°C, "

443

f"Load: {load.load_average:.2f}, "

444

f"Disk: {disk.percent:.1f}%")

445

446

sleep(10)

447

```

448

449

### Event-Based System Response

450

451

```python

452

from gpiozero import CPUTemperature, LoadAverage, Motor

453

from signal import pause

454

455

cpu = CPUTemperature(threshold=75.0)

456

load = LoadAverage(threshold=2.0)

457

cooling_fan = Motor(forward=2, backward=3)

458

459

def start_cooling():

460

print("System overheating - starting cooling fan")

461

cooling_fan.forward(0.8)

462

463

def stop_cooling():

464

if not load.is_active: # Only stop if load is also normal

465

print("Temperature normal - stopping cooling fan")

466

cooling_fan.stop()

467

468

def high_load():

469

print("High system load detected")

470

if not cpu.is_active: # Start fan if not already running

471

cooling_fan.forward(0.5)

472

473

def normal_load():

474

if not cpu.is_active: # Only stop if temperature is also normal

475

print("Load normal - reducing fan speed")

476

cooling_fan.stop()

477

478

# Connect events

479

cpu.when_activated = start_cooling

480

cpu.when_deactivated = stop_cooling

481

load.when_activated = high_load

482

load.when_deactivated = normal_load

483

484

pause()

485

```

486

487

### Data Logging System

488

489

```python

490

from gpiozero import CPUTemperature, LoadAverage, DiskUsage

491

import csv

492

import time

493

from datetime import datetime

494

495

# System monitors

496

cpu = CPUTemperature()

497

load = LoadAverage()

498

disk = DiskUsage()

499

500

# Data logging

501

with open('system_metrics.csv', 'w', newline='') as csvfile:

502

writer = csv.writer(csvfile)

503

writer.writerow(['timestamp', 'cpu_temp', 'load_avg', 'disk_usage'])

504

505

try:

506

while True:

507

timestamp = datetime.now().isoformat()

508

metrics = [

509

timestamp,

510

cpu.temperature,

511

load.load_average,

512

disk.percent

513

]

514

515

writer.writerow(metrics)

516

print(f"Logged: CPU={cpu.temperature:.1f}°C, "

517

f"Load={load.load_average:.2f}, "

518

f"Disk={disk.percent:.1f}%")

519

520

time.sleep(60) # Log every minute

521

522

except KeyboardInterrupt:

523

print("\nLogging stopped")

524

```