Smart house — Smart Home (Python, three files)
This example is written twice, once for each firmware. Pick the tab that matches the firmware of your Smart Home: the tab you pick is remembered on the other examples.
Firmware 3.0 renamed the Python names a program writes, and kept none of the old ones: a Smart Home on 2.x does not know the 3.0 names, and a Smart Home on 3.0 does not know the 2.x ones. The name map lists every change. If you open the example from inside MoBot, it picks the version for the firmware of your Smart Home. If you download a file from this page, use the one in the tab for your firmware.
The big one. A program in three files that puts the house’s web page on your Wi-Fi, tells you where to find it, and then watches what the house is feeling, every two seconds. While it runs, the MoBot app and the Smart Home dashboard in MoBot can talk to the house, and the house’s five little minds — gas alarm, burglar alarm, door, weather and lighting — can look after it.
| file | what lives in it |
|---|---|
main.py |
starts the web page on your Wi-Fi, then keeps watch |
netcheck.py |
is the board on the Wi-Fi, what is its address and its name |
report.py |
what the house is feeling right now |
This is the version for a house on firmware 3.0, where the house is called
home. For a house that still runs firmware 2.x, MoBot opens the 2.x version of
this example instead.
Project for firmware 3.0: 05-smart-house-api.firmware-3.mobot. Open it in MoBot.
What you need
Section titled “What you need”- A MoBot Smart Home board with as much fitted as you have: screen, RGB light, buzzer, fan, servo, number display, gas, light, motion, temperature sensor and the RFID reader.
- The board must already know your Wi-Fi. If it does not, hold the button on the board for five seconds and set it up in the MoBot app first.
- A phone or computer on the same Wi-Fi.
How to run it — read this bit
Section titled “How to run it — read this bit”MoBot saves one file at a time: the tab you are looking at. So:
- Open 05-smart-house-api.firmware-3.mobot. There are three tabs.
- Click
netcheck.py→ Save. - Click
report.py→ Save. - Click
main.py→ Save. MoBot restarts the board, and it runsmain.py.
Miss one and the board stops immediately with
ImportError: no module named 'report', which tells you exactly which tab you
forgot.
What you should see and hear
Section titled “What you should see and hear”On the board’s screen: Looking for the wifi..., then House online, the
address, and the house’s name, MoBot-IOT- and four characters.
In the serial monitor: the addresses to try, and then, every two seconds, a line like:
temp=23 humid=44 gas=780 light=3120 knob=2048 motion=FalseCover the light sensor and light drops. Turn the knob and knob
changes. Wave in front of the board and motion becomes True.
In a browser on the same Wi-Fi:
| address | what it is |
|---|---|
http://<the address>/ |
the Smart Home dashboard, served by the house (the computer needs internet for the dashboard itself) |
http://<the address>/sensors |
every reading at once, as JSON |
http://<the address>/api/monitors |
the five minds, the outputs they hold, and the sensors |
http://<the address>/api/events |
what has happened lately |
The five minds
Section titled “The five minds”The house has five built-in minds that can run it on their own: gas, security, door (the RFID reader), weather and lighting. They start switched off. Switch one on in the MoBot app, and from then on:
| switched on | the house |
|---|---|
| lighting | switches its lamp on when it gets dark |
| weather | starts the fan when it gets hot |
| gas | buzzes an alarm and runs the fan when the gas sensor smells something |
| door | opens the door for a card it knows, then closes it again |
| security | sounds the alarm when something moves while it is armed |
None of that is in your program — and that is why this program only reads. A mind that is on takes over the screen, the fan, the servo and the buzzer, and two programs fighting over one buzzer is a horrible noise.
The line that matters
Section titled “The line that matters”home.dashboard.start() # no argumentsWith no arguments, the house uses the Wi-Fi it has already been set up on:
it has been serving its page there since it switched on, and start() simply
says yes. With two arguments it builds its own little network instead,
which nothing else on your Wi-Fi can reach — that is 04-web-dashboard.
Your own files ask for the house
Section titled “Your own files ask for the house”main.py is given home for free. netcheck.py and report.py are not, so
each asks for it once, at the top:
from smart_home import homeIf it says “no wifi yet”
Section titled “If it says “no wifi yet””Hold the button on the board down for five seconds, then set the house up in the MoBot app. The board remembers the network afterwards, even when it is switched off. Then reset and try again.
The program
Section titled “The program”This project has 3 files. Each one is a tab in MoBot. The code below is a reading copy of each: editing it changes nothing, so open the project and edit it there.
# main.py — Smart house (Python, three files) (iot)## A reading copy of one file inside 05-smart-house-api.firmware-3.mobot.# Editing this copy changes nothing: open the project and edit it there.# This is the entry point — the board runs it as main.py.# Written for firmware 3.0; the 2.x version is 05-smart-house-api.main.py.
"""Smart house - MoBot Smart Home: the whole house, on YOUR wifi.
This is the big one. Three files:
main.py puts the house's web page on your wifi, then keeps watch netcheck.py is the board on the wifi, and what is its address report.py what the house is feeling right now
A house that knows your wifi network joins it when it switches on, and servesits web page there straight away - the page the MoBot app and the Smart Homedashboard in MoBot talk to. This program joins in with one line:
home.dashboard.start() <- NO arguments
With no arguments the house does not build a little network of its own: ituses the page it is already serving on the wifi somebody set it up on - theschool's, or the one at home.
IMPORTANT: save ALL THREE files to the board. MoBot saves the tab you arelooking at, one at a time."""
import time
import netcheckimport report
display = home.displayweb = home.dashboard
# ------------------------------------------------------------------ 1 -------# Is the house on the wifi? If not, there is nothing we can do here.
display.clear()display.show_text("Looking for", 0, 0)display.show_text("the wifi...", 0, 16)
print("Waiting for wifi...")if not netcheck.wait(20): netcheck.explain() display.clear() display.show_text("No wifi yet", 0, 8) display.show_text("Hold button 5s", 0, 24) raise SystemExit
ip = netcheck.address()print("On the wifi. This house is", netcheck.name(), "at", ip)
# ------------------------------------------------------------------ 2 -------# The web page on THAT connection. No name, no password - the house is already# on a network, so it does not need to invent one.
if not web.start(): print("The web page would not start.") raise SystemExit
print("Web page running:", web.is_running())
print("")print("Try these from a phone or computer on the same wifi:")print(" http://" + str(ip) + "/ the Smart Home dashboard (that computer needs internet)")print(" http://" + str(ip) + "/sensors every reading at once")print(" http://" + str(ip) + "/api/monitors the house's five minds: gas, security, door, weather, lighting")print(" http://" + str(ip) + "/api/events what has happened lately")print("")print("The five minds start switched off. Switch them on in the MoBot app,")print("and the house looks after itself while this program keeps watch.")print("")
display.clear()display.show_text("House online", 0, 0)display.show_text(str(ip), 0, 16)display.show_text(netcheck.name(), 0, 32)
# ------------------------------------------------------------------ 3 -------# From here on all this loop does is watch.## It deliberately does NOT touch the screen, the fan, the servo or the buzzer:# once a mind is switched on it takes those over, and two programs fighting# over one buzzer is a horrible noise.
print("Watching. Every two seconds, what the house is feeling:")
while True: print(report.line()) time.sleep(2)# netcheck.py — Smart house (Python, three files) (iot)## A reading copy of one file inside 05-smart-house-api.firmware-3.mobot.# Editing this copy changes nothing: open the project and edit it there.# main.py imports this file; save it to the board too.
"""netcheck.py - is this house on the wifi yet, and what is its address?
Remember the rule from the robotics line-follower: main.py is given the housefor free, your own files are not. So this file asks for it by name, once, atthe top. It is not a copy of the house; it is the very same one main.py uses."""
import time
from smart_home import home
def connected(): """True if the board has joined a wifi network someone told it about.""" return home.wifi.is_connected()
def address(): """The address other people on the network can use, or None.""" return home.wifi.ip()
def name(): """The house's own name, the one the MoBot app shows: MoBot-IOT- and four characters.""" return "MoBot-IOT-" + home.wifi.house_id()
def wait(seconds=20): """Give the board a chance to join. Returns True if it managed it.""" end = time.ticks_add(time.ticks_ms(), int(seconds * 1000)) while time.ticks_diff(end, time.ticks_ms()) > 0: if connected(): return True time.sleep(0.5) return connected()
def explain(): """What to do when there is no wifi. Printed, in plain words.""" print("") print("This house does not know a wifi network yet.") print("") print(" 1. Hold the button on the board down for 5 seconds.") print(" 2. Open the MoBot app and let it set the house up.") print(" 3. The house remembers the network, even after it is switched off.") print("") print("Until then this program cannot start, because it serves the house") print("over YOUR wifi rather than making a little network of its own.")# report.py — Smart house (Python, three files) (iot)## A reading copy of one file inside 05-smart-house-api.firmware-3.mobot.# Editing this copy changes nothing: open the project and edit it there.# main.py imports this file; save it to the board too.
"""report.py - one tidy line about what the house is feeling right now.
Same rule as netcheck.py: this file asks for the house by name.
Every number here is read from the house's own sensors, at the moment you ask:
home.temperature_sensor.temperature() degrees Celsius (None at first) home.temperature_sensor.humidity() percent (None at first) home.gas_sensor.level() 0..4095, bigger = more gas or smoke home.light_sensor.level() 0..4095, bigger = brighter home.knob.position() 0..4095, how far the knob is turned home.motion_sensor.motion_detected() True while something moves"""
from smart_home import home
# The readings worth showing, in the order they are printed.LABELS = ("temp", "humid", "gas", "light", "knob", "motion")
def readings(): """Everything worth showing, as a dictionary of label -> value.""" return { "temp": home.temperature_sensor.temperature(), "humid": home.temperature_sensor.humidity(), "gas": home.gas_sensor.level(), "light": home.light_sensor.level(), "knob": home.knob.position(), "motion": home.motion_sensor.motion_detected(), }
def line(): """One short line, for the serial monitor.""" data = readings() parts = [] for label in LABELS: parts.append(label + "=" + str(data[label])) return " ".join(parts)Try changing it
Section titled “Try changing it”- Show
report.readings()instead ofreport.line()and see the dictionary behind the line. - Switch the lighting mind on in the app, then cover the light sensor: the lamp comes on, and this program never asked for it.
- Add a fourth file that prints a warning when
tempgoes over 30 — but read the warning above about the buzzer before you make it beep.
The big one. This is the program that turns the board from “a box with sensors on it” into a house that runs itself: five little minds wake up and take over the gas alarm, the burglar alarm, the door, the weather and the lighting, while your program just watches.
It is also the only thing anywhere in MoBot that switches those five minds on.
| file | what lives in it |
|---|---|
main.py |
switches everything on, in the right order |
netcheck.py |
is the board on the Wi-Fi, and what is its address |
report.py |
what the house is feeling right now |
Project for firmware 2.x: 05-smart-house-api.mobot. Open it in MoBot.
What you need
Section titled “What you need”- A MoBot Smart Home board with as much fitted as you have: screen, RGB light, buzzer, fan, servo, 7-segment, gas, light, motion, DHT11 and the RFID reader.
- The board must already know your Wi-Fi. If it does not, hold the button on the board for five seconds and set it up in the MoBot app first.
- A phone or computer on the same Wi-Fi.
How to run it — read this bit
Section titled “How to run it — read this bit”MoBot saves one file at a time: the tab you are looking at. So:
- Open 05-smart-house-api.mobot. There are three tabs.
- Click
netcheck.py→ Save. - Click
report.py→ Save. - Click
main.py→ Save. MoBot restarts the board, and it runsmain.py.
Miss one and the board stops immediately with
ImportError: no module named 'report', which tells you exactly which tab you
forgot.
What you should see and hear
Section titled “What you should see and hear”On the board’s screen: Looking for the wifi..., then House awake, the
address, and 5 minds on.
In the serial monitor: the full list of web addresses the house now answers
on — including about a dozen starting with /api/ — and then, every two
seconds, a line like:
temp=23 humid=44 gas=780 light=3120 knob=2048 motion=FalseWatch those numbers move without your program doing anything. The loop at
the bottom of main.py only prints them; the house is collecting them itself.
In a browser on the same Wi-Fi, http://<the address>/api/monitors should
answer with a big block of JSON listing five monitors, six outputs and the
sensors. On any board that has not run this program, that address is a 404.
And then the house starts behaving on its own:
| do this | the house should |
|---|---|
| turn the lights off / cover the light sensor | switch its lamp on — that is the lighting mind |
| breathe on the temperature sensor until it goes over 30 | start the fan — the weather mind |
| hold a smelly marker pen near the gas sensor | buzz an alarm and run the fan — the gas mind |
| hold an RFID card on the reader | the door servo opens, the light goes green, Welcome appears — then it closes itself after four seconds |
| wave in front of the motion sensor after arming security in the app | the alarm goes off |
None of that is in your program. That is the point.
The two lines that matter
Section titled “The two lines that matter”mobotIOT.server.start_web_server() # no argumentsWith no arguments, the board serves the house over the Wi-Fi it has already been set up on. With two arguments it builds its own little network instead, which nothing else on your Wi-Fi can reach. The block Start Web Server on the saved WiFi writes the first one, and the block Start Web Server writes the second.
monitors.enable()This wakes the five minds and adds the whole /api/... half of the house. There
is no block for it, and no other program in MoBot calls it.
If it says “no wifi yet”
Section titled “If it says “no wifi yet””Hold the button on the board down for five seconds, then set the house up in the MoBot app. The board remembers the network afterwards, even when it is switched off. Then reset and try again.
The program
Section titled “The program”This project has 3 files. Each one is a tab in MoBot. The code below is a reading copy of each: editing it changes nothing, so open the project and edit it there.
# main.py — Smart house (Python, three files) (iot)## A reading copy of one file inside 05-smart-house-api.mobot.# Editing this copy changes nothing: open the project and edit it there.# This is the entry point — the board runs it as main.py.
"""Smart house - MoBot Smart Home: the whole house, on YOUR wifi.
This is the big one. Three files:
main.py switches everything on, in the right order netcheck.py is the board on the wifi, and what is its address report.py what the house is feeling right now
Two lines in here are the heart of it.
mobotIOT.server.start_web_server() <- NO arguments
With no arguments the board serves the house over the wifi network somebody already set it up on - the school's, or the one at home. The "Start Web Server on the saved WiFi" block writes this same line. The "Start Web Server" block makes the board build its OWN little network instead, which nothing else can reach.
monitors.enable()
This is what turns the house into a HOUSE. Five little minds wake up and start running it on their own: gas, security, door, weather and lighting. They watch the sensors and work the fan, the servo, the buzzer, the colour light, the screen and the digits, all without your program telling them anything. No block can switch them on, and NOTHING else in MoBot ever calls this - so until you run this file, half of what this board can do has never been switched on at all.
IMPORTANT: save ALL THREE files to the board. MoBot saves the tab you arelooking at, one at a time."""
import time
import monitors
import netcheckimport report
oled = mobotIOT.oledsrv = mobotIOT.server
# ------------------------------------------------------------------ 1 -------# Is the house on the wifi? If not, there is nothing we can do here.
oled.clear_screen()oled.display_text("Looking for", 0, 0)oled.display_text("the wifi...", 0, 16)
print("Waiting for wifi...")if not netcheck.wait(20): netcheck.explain() oled.clear_screen() oled.display_text("No wifi yet", 0, 8) oled.display_text("Hold button 5s", 0, 24) raise SystemExit
ip = netcheck.address()print("On the wifi. This house is at", ip)
# ------------------------------------------------------------------ 2 -------# Start the web server on THAT connection. No name, no password - it is# already on a network, so it does not need to invent one.
if not srv.start_web_server(): print("The web server would not start.") raise SystemExit
print("Web server running:", srv.is_server_running())
# ------------------------------------------------------------------ 3 -------# Wake the five minds up.
monitors.enable()print("The house is now running itself.")print("(monitors.get() hands you the five minds back;")print(" monitors.disable() sends them to sleep again.)")
print("")print("Addresses this house answers on:")for route in report.routes(): print(" ", route)
print("")print("Try these from a phone or computer on the same wifi:")print(" http://" + str(ip) + "/api/monitors everything, all five minds")print(" http://" + str(ip) + "/api/events what has happened lately")print(" http://" + str(ip) + "/api/act what every switch is doing")print(" http://" + str(ip) + "/sensors the simple old list")print("")
oled.clear_screen()oled.display_text("House awake", 0, 0)oled.display_text(str(ip), 0, 16)oled.display_text("5 minds on", 0, 32)
# ------------------------------------------------------------------ 4 -------# From here on the house looks after itself. All this loop does is watch.## It deliberately does NOT touch the screen, the fan, the servo or the buzzer:# the five minds have taken those over, and two programs fighting over one# buzzer is a horrible noise.
print("Watching. The numbers below are being collected by the house itself,")print("not by this loop - this loop only reads them out.")
while True: print(report.line()) time.sleep(2)# netcheck.py — Smart house (Python, three files) (iot)## A reading copy of one file inside 05-smart-house-api.mobot.# Editing this copy changes nothing: open the project and edit it there.# main.py imports this file; save it to the board too.
"""netcheck.py - is this house on the wifi yet, and what is its address?
Remember the rule from the robotics line-follower: main.py is given the boardfor free, your own files are not. This file does not touch mobotIOT at all - itonly talks to wifi_setup, which it imports for itself, so there is nothing toask for."""
import time
import wifi_setup
def connected(): """True if the board has joined a wifi network someone told it about.""" try: return wifi_setup.is_sta_connected() except Exception: return False
def address(): """The address other people on the network can use, or None.""" try: return wifi_setup.sta_ip() except Exception: return None
def wait(seconds=20): """Give the board a chance to join. Returns True if it managed it.""" end = time.ticks_add(time.ticks_ms(), int(seconds * 1000)) while time.ticks_diff(end, time.ticks_ms()) > 0: if connected(): return True time.sleep(0.5) return connected()
def explain(): """What to do when there is no wifi. Printed, in plain words.""" print("") print("This house does not know a wifi network yet.") print("") print(" 1. Hold the button on the board down for 5 seconds.") print(" 2. Open the MoBot app and let it set the house up.") print(" 3. The house remembers the network, even after it is switched off.") print("") print("Until then this program cannot start, because it serves the house") print("over YOUR wifi rather than making a little network of its own.")# report.py — Smart house (Python, three files) (iot)## A reading copy of one file inside 05-smart-house-api.mobot.# Editing this copy changes nothing: open the project and edit it there.# main.py imports this file; save it to the board too.
"""report.py - one tidy line about what the house is feeling right now.
There are two things called "server" here and it is worth getting them straight:
server the MODULE - the box of instructions server.server the OBJECT - the actual running web server, or None
The sensor readings live on the object, in a plain dictionary calledsensor_data. Once the monitors are switched on, the house fills that dictionaryin by itself, every fraction of a second, without your program asking - whichis exactly what this file is here to show you."""
import server
# The names worth showing, and how to label them.WATCH = ( ("temperature", "temp"), ("humidity", "humid"), ("gas", "gas"), ("ldr", "light"), ("pot", "knob"), ("pir", "motion"),)
def sensors(): """A copy of everything the house currently believes.""" if server.server is None: return {} return dict(server.server.sensor_data)
def line(): """One short line, for the serial monitor.""" data = sensors() if not data: return "no server running" parts = [] for key, label in WATCH: if key in data: parts.append(label + "=" + str(data[key])) return " ".join(parts)
def routes(): """Every web address this house answers on, sorted.""" if server.server is None: return [] return sorted(server.server.routes.keys())Try changing it
Section titled “Try changing it”- Print
report.sensors()instead ofreport.line()and see everything the house believes, including the things the five minds are doing. - Add a fourth file that plays a tune when the temperature crosses 30 — but read the warning below about the buzzer first.
- Call
monitors.disable()after a minute and watch the house go quiet again.