Example - copy and change it

Weather station

Easy Verified

Its dashboard
Source:
examples/weather_station.py
Widgets:
Gauge, Chart
You'll need:
Just a computer to start; a sensor to make it real
What we've checked:
Tested with a fake connection, and seen on a real dashboard in real Chrome, registered against a real server.

The first example showed a value that never changed. Real sensors change, and most programs are a loop: read, publish, wait, repeat. This one is that loop.

You'll need

  • A Raspberry Pi or any computer with Python 3.10 or newer
  • No sensor to start: the readings are random numbers in a believable range

No Pi yet?

Nothing here needs a Pi: follow the steps below on your computer. Add a real sensor whenever you like.

Build it

This project assumes you've registered the device (see Getting Started).

  1. On your Pi, or on your computer, install the SDK: pip install thepihub.
  2. Press View full code above and copy it into a file called weather_station.py, or press to copy a command that creates it.

Running it

Run it:

python weather_station.py

Then open your dashboard. Three gauges and a chart appear, and they change every couple of seconds. Press Ctrl+C to stop it.

Try changing this

  • Change how often it reads. Find interval (2 seconds) and try 1, or 10. Watch the chart.
  • Change the range of the random numbers and see the chart's scales follow.
  • Add a fourth reading, wind speed say: copy how temperature is declared and set.
  • Later, swap the random numbers for a real sensor. Only one function, _read_conditions(), has to change.

The educational bit

  • The numbers here are random. How would you know if a real weather station was telling the truth? What could you check it against?
  • Open the page after it has been running for a while. Why does the chart start empty and fill in?

Safety notes

The Pi and its power adapter are not waterproof: keep them indoors, or in a proper weatherproof box. Only a sensor made for the outdoors should go outside, and only on a cable that suits it. Switch the Pi off while you connect a sensor, and check the sensor's instructions first: the Pi's pins take 3.3 V.

What next

  • Add a real sensor: a BME280 reads temperature, humidity and pressure.
  • Send a warning when it gets too hot, the way the Greenhouse does.
  • Add a camera: stream it live with Live camera, or record a time-lapse video (that part uses the Pi's own camera tools, outside ThePiHub).

Under the hood

The rest of this page is for when you want to know how it works.

One value, or several

temperature.set(readings["temperature"])
humidity.set(readings["humidity"])
pressure.set(readings["pressure"])

conditions.set_values(readings)

There are two ways to publish. .set(value) sends a single number, which is what a gauge wants. .set_values({...}) sends several named values in one update, which is what a chart wants: the whole set of readings arrives together, so the chart never shows a moment that did not exist.

What the chart shows

The chart draws one small panel for each value, not one crowded plot: temperature is around 20, humidity around 60 and pressure around 1,000, so on a single scale two of them would be flat lines. Each panel has its own scale, all three share the time axis, and hovering (or the arrow keys) draws a line through all of them with the readings at that moment. The table icon shows the same numbers as a table.

The platform only keeps the latest value, so the chart shows what your browser has seen since you opened the page: it starts empty and fills in as readings arrive.

The loop

while cycles is None or done < cycles:
    readings = _read_conditions()
    ...
    time.sleep(interval)

The program reads, publishes and sleeps two seconds, until you press Ctrl+C. (The cycles argument is there so a test can stop it after a few rounds; you can ignore it.)

About those numbers

The readings are random values in a plausible range: _read_conditions() stands in for real hardware, and that one function is the only thing you replace. Wire up a BME280 or any other sensor, return its readings in the same shape, and the gauges and the chart follow.

← Back to Projects

Weather station

"""Weather Station - Gauges and a Chart, updated every few seconds.

Copy this file anywhere and run it:

    python weather_station.py

If this is the first time you have connected from this device, it prints a link and a code: open the link
while logged in to ThePiHub and approve it, then answer y when the terminal asks you to confirm the account.
The device is yours and gets its id. Every run after that connects straight away. Ctrl+C stops it.

The readings are random numbers standing in for a sensor: replace `_read_conditions()`.
"""

from __future__ import annotations

import random
import time
from typing import Dict, Optional

from pihub import Device, Program
from pihub.device import Transport


def _read_conditions() -> Dict[str, float]:
    """Random readings, standing in for real sensor hardware."""
    return {
        "temperature": round(random.uniform(15.0, 30.0), 1),
        "humidity": round(random.uniform(30.0, 90.0), 1),
        "pressure": round(random.uniform(980.0, 1050.0), 1),
    }


def main(transport: Optional[Transport] = None, cycles: Optional[int] = None, interval: float = 2.0) -> Device:
    """`transport` and `cycles` are for the tests: left out, it connects to the real server and runs until Ctrl+C."""
    device = Device(transport=transport)

    weather = Program(id="weather", name="Weather Station")

    temperature = weather.output(id="temperature", type="Gauge")
    humidity = weather.output(id="humidity", type="Gauge")
    pressure = weather.output(id="pressure", type="Gauge")
    conditions = weather.output(id="conditions", type="Chart")

    device.add_program(weather)
    device.start()

    done = 0
    try:
        while cycles is None or done < cycles:
            readings = _read_conditions()

            # One value per Gauge.
            temperature.set(readings["temperature"])
            humidity.set(readings["humidity"])
            pressure.set(readings["pressure"])

            # Several values at once, for the Chart.
            conditions.set_values(readings)

            done += 1
            if interval:
                time.sleep(interval)
    except KeyboardInterrupt:  # pragma: no cover
        pass
    finally:
        device.stop()

    return device


if __name__ == "__main__":
    main()  # pragma: no cover

Create weather_station.py from a terminal

Paste this into a terminal on your Pi (over SSH is fine). It writes the whole program to weather_station.py in the folder you are in.

cat > weather_station.py << 'EOF'
"""Weather Station - Gauges and a Chart, updated every few seconds.

Copy this file anywhere and run it:

    python weather_station.py

If this is the first time you have connected from this device, it prints a link and a code: open the link
while logged in to ThePiHub and approve it, then answer y when the terminal asks you to confirm the account.
The device is yours and gets its id. Every run after that connects straight away. Ctrl+C stops it.

The readings are random numbers standing in for a sensor: replace `_read_conditions()`.
"""

from __future__ import annotations

import random
import time
from typing import Dict, Optional

from pihub import Device, Program
from pihub.device import Transport


def _read_conditions() -> Dict[str, float]:
    """Random readings, standing in for real sensor hardware."""
    return {
        "temperature": round(random.uniform(15.0, 30.0), 1),
        "humidity": round(random.uniform(30.0, 90.0), 1),
        "pressure": round(random.uniform(980.0, 1050.0), 1),
    }


def main(transport: Optional[Transport] = None, cycles: Optional[int] = None, interval: float = 2.0) -> Device:
    """`transport` and `cycles` are for the tests: left out, it connects to the real server and runs until Ctrl+C."""
    device = Device(transport=transport)

    weather = Program(id="weather", name="Weather Station")

    temperature = weather.output(id="temperature", type="Gauge")
    humidity = weather.output(id="humidity", type="Gauge")
    pressure = weather.output(id="pressure", type="Gauge")
    conditions = weather.output(id="conditions", type="Chart")

    device.add_program(weather)
    device.start()

    done = 0
    try:
        while cycles is None or done < cycles:
            readings = _read_conditions()

            # One value per Gauge.
            temperature.set(readings["temperature"])
            humidity.set(readings["humidity"])
            pressure.set(readings["pressure"])

            # Several values at once, for the Chart.
            conditions.set_values(readings)

            done += 1
            if interval:
                time.sleep(interval)
    except KeyboardInterrupt:  # pragma: no cover
        pass
    finally:
        device.stop()

    return device


if __name__ == "__main__":
    main()  # pragma: no cover
EOF