Network access (requests, MQTT)
With Maker, Python on a simulated Raspberry Pi can reach the internet: call web APIs with requests, and send and receive MQTT messages with paho-mqtt. The Pico is modelled as a plain Pico (not a Pico W), so this is for Pi boards only.
On a free account, the first network call raises RuntimeError: Network access is a Maker feature.
HTTP with requests
import requests
reply = requests.get("https://api.open-meteo.com/v1/forecast", params={"latitude": 53.8, "longitude": -1.55, "current": "temperature_2m"})
reply.raise_for_status()
print(reply.json()["current"]["temperature_2m"])
requests.post("https://example.com/log", json={"temperature": 21.5})
get, post, put, patch, delete and Session take the usual arguments (params, data, json, headers, auth). A response has status_code, ok, headers, text, content, json() and raise_for_status().
MQTT with paho-mqtt
Connect to any public broker, or to "sandbox": PyRasp's own broker. Sandbox topics are private to your account, so every Pi you run can talk to the others and nobody else can listen in.
import time
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, reason_code, properties):
client.subscribe("home/#")
def on_message(client, userdata, message):
print(message.topic, message.payload.decode())
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.on_connect = on_connect
client.on_message = on_message
client.connect("sandbox")
client.loop_start()
while True:
client.publish("home/temperature", 21.5)
time.sleep(5)
Callbacks run in the network loop, as in paho: call loop_start(), loop_forever() or loop(). paho 1's style, mqtt.Client("my-id") with four-argument on_connect, works too. For a broker that needs TLS, call client.tls_set() before connecting.
How it works, and its limits
Your program's requests go through the PyRasp server. While your program waits for a reply, only your program (or that thread) waits: the circuit and the simulation keep running in simulated time.
- Only
httpandhttps, to public internet addresses. Local and private addresses (localhost,192.168.x.x,10.x.x.xand so on) are refused, so your home network isn't reachable from the simulator. - Responses are limited to 1 MB, and a request gives up after 10 seconds.
- Up to 60 HTTP requests a minute, 20 MQTT messages a second (sent and received together; extra received messages are dropped), and 50 MB a day.
- Sandbox messages are never retained.