Skip to content

Search the documentation

Kit
Firmware

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.

  • 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.

MoBot saves one file at a time: the tab you are looking at. So:

  1. Open 05-smart-house-api.firmware-3.mobot. There are three tabs.
  2. Click netcheck.py → Save.
  3. Click report.py → Save.
  4. Click main.py → Save. MoBot restarts the board, and it runs main.py.

Miss one and the board stops immediately with ImportError: no module named 'report', which tells you exactly which tab you forgot.

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=False

Cover 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 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.

home.dashboard.start() # no arguments

With 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.

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 home

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.

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
# 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 serves
its web page there straight away - the page the MoBot app and the Smart Home
dashboard 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: it
uses the page it is already serving on the wifi somebody set it up on - the
school's, or the one at home.
IMPORTANT: save ALL THREE files to the board. MoBot saves the tab you are
looking at, one at a time.
"""
import time
import netcheck
import report
display = home.display
web = 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
# 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 house
for free, your own files are not. So this file asks for it by name, once, at
the 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
# 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)
  • Show report.readings() instead of report.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 temp goes over 30 — but read the warning above about the buzzer before you make it beep.