Give a Raspberry Pi eyes: a camera, a question and a relay
A small board, a camera module and forty lines of Python: take a picture, ask the API a question, act on the answer. With the key, retry and cost choices that keep it safe unattended.
A small board with a camera can take a picture. What it could not do, until recently, is understand one. Telling a closed fridge door from an open one, a failed 3D print from a good one, or a wilting seedling from a healthy one used to mean collecting hundreds of pictures and training a model for that one job.
With an API that answers questions about pictures, the board does not need to understand anything. It takes the picture, asks, and acts on a yes or a no. This post builds that loop on a Raspberry Pi, with the choices that matter once the board is left alone on a shelf.1
The example
A shop has a row of glass-door fridges. A door left open for an hour spoils stock. A Pi with a camera module looks at the row, asks every five minutes “Is a fridge door open?”, and switches on a light at the counter when the answer is yes twice in a row.
There is no server in this design, no monitor and no webhook. The board calls the API itself and decides by itself.
Before the code: three choices
Save the question as an agent. Put the configuration in a saved agent from the console, and only its id on the board. You can then rewrite the question without touching the Pi, and each change is a new version, so a board in the field keeps its behaviour until you move it.
Use a Run only key. The key lives on the board’s SD card, and anyone who picks up the board can read it. A Run only key can run checks and nothing else: it cannot read or change your agents, and you revoke it from the console if a board goes missing.
Start with a test key. It is free and gives the same answer for the same picture, which is what you want while debugging the wiring rather than the question.
The loop
import os, subprocess, time
import requests
from gpiozero import OutputDevice
KEY = os.environ['CAMLY_API_KEY'] # a Run only key; a test key while you build
AGENT = 'agt_...' # the saved agent this board runs
DEVICE = 'fridge-row-1' # names this board in the Idempotency-Key
EVERY = 300 # seconds between pictures
light = OutputDevice(17) # the relay, on GPIO 17
def take_picture(path='/tmp/frame.jpg'):
subprocess.run(['rpicam-still', '-n', '-t', '1000',
'--width', '1280', '--height', '960', '-o', path], check=True)
return path
def check(path, n):
"""Returns True or False, or None when no answer could be had."""
for attempt in range(3):
try:
with open(path, 'rb') as f:
r = requests.post('https://api.camly.ai/v1/runs', timeout=60,
headers={'Authorization': f'Bearer {KEY}',
'Idempotency-Key': f'{DEVICE}-{n}'},
data={'agent': AGENT}, files={'image': f})
except requests.RequestException:
time.sleep(2 ** attempt); continue
if r.status_code == 200:
return r.json()['result']['flagged']
if r.status_code == 429:
time.sleep(int(r.headers.get('Retry-After', 10))); continue
if r.status_code >= 500:
time.sleep(2 ** attempt); continue
raise SystemExit(f'Camly answered {r.status_code}: fix the key, the balance or the agent.')
return None
n, yes_in_a_row = int(time.time()), 0
while True:
n += 1
flagged = check(take_picture(), n)
if flagged is not None:
yes_in_a_row = yes_in_a_row + 1 if flagged else 0
light.on() if yes_in_a_row >= 2 else light.off()
time.sleep(EVERY)
Treat it as a starting point: the capture line depends on your camera module and your system image, and the relay on your wiring.
What each part is for
The picture is 1280 pixels wide. The API scales larger pictures down to 1280 on their longest side, so a bigger one only costs upload time.
The Idempotency-Key is the board’s name and a picture number. If the connection drops after the picture was sent but before the answer came back, the retry carries the same key: the API returns the first answer and charges once. Without it, a flaky Wi-Fi link is paid for twice.
The retries are sorted by cause. A 429 means too many checks this minute: wait the number of seconds in Retry-After. A 502 or a lost connection was not charged: retry with a growing pause. A 401, 402, 403, 404 or 422 will not get better by itself: the key, the balance or the agent needs fixing, so the program stops instead of repeating the refusal all night.1
“No answer” is not “no”. When all three attempts fail, check returns None, and the loop leaves the light as it was. A board that cannot reach the API must not conclude that all is well.
Two yeses in a row. One flagged picture can be a customer holding the door while choosing. Two in a row, five minutes apart, is a door left open. This is the same idea as the confirm rule of a monitor, written in two lines because the board keeps its own state. The server-side version is described in from checks to incidents.
What it costs
Every picture is one check, €0.005 at the time of writing.1
| Every | Checks a day | Per day | Per 30 days |
|---|---|---|---|
| Hour | 24 | €0.12 | €3.60 |
| 15 minutes | 96 | €0.48 | €14.40 |
| 5 minutes | 288 | €1.44 | €43.20 |
The pace should follow the thing watched. Seedlings do not wilt in five minutes; a fridge door matters within fifteen. Limit the hours too: a shop that closes at eight has no customers to leave a door open at midnight, though a door left open at closing time is exactly what you want to catch, so keep a last check after the doors are locked.
Then set a budget on the key in the console. A bug that turns EVERY = 300 into a tight loop is the classic way a small project gets an unpleasant invoice; a hard budget on the key refuses checks past the amount you chose.
When to move the logic off the board
This design is right for one board doing one job. It starts to strain when there are twenty boards, when someone wants a history of incidents, or when the alert must reach a phone rather than a light. At that point, make each board a push camera and let a monitor on the server keep the state and send a webhook: the board then only takes pictures and sends them, with a key that can do nothing else. The ways of sending are compared in five ways to get a picture to the API.
A smaller board, such as a microcontroller with a camera, can make the same call without Linux; the documentation has a complete example in C++.1
Sources
- Camly API, all guides as plain text: Send from a device, Saved agents, Retries, Keys, Limits and prices. platform.camly.ai
- Camly API contract (OpenAPI). api.camly.ai