Web dashboard — Smart Home (Python)
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.
Your house, on your phone. The board makes its own little Wi-Fi network. You join it, open a web address, and you are talking to the house: reading the temperature, the light, the gas and the movement sensor, and switching the fan, the colour light and the screen.
This is the version for a house on firmware 3.0, where the web page is
home.dashboard. For a house that still runs firmware 2.x, MoBot opens the 2.x
version of this example instead.
Project for firmware 3.0: 04-web-dashboard.firmware-3.mobot. Open it in MoBot.
What you need
Section titled “What you need”- A MoBot Smart Home board with screen, fan, RGB light and the temperature, gas, light, knob and motion sensors.
- A phone or a laptop with Wi-Fi.
- A USB cable and the serial monitor, at least the first time.
How to run it
Section titled “How to run it”- Open 04-web-dashboard.firmware-3.mobot. Change
SSIDandPASSWORDif you like — use a password of at least 8 characters: that is the usual rule for WPA2 Wi-Fi networks. - Press Save. MoBot restarts the board, and it runs the program.
- The screen shows the network name, the address and the password. Read them off the board.
- On your phone, join the Wi-Fi network MoBotHouse. Your phone will warn you there is no internet on it — that is right, this network is just the house.
- Open
http://192.168.4.1/sensorsin the browser.
What you should see
Section titled “What you should see”- On the board’s screen:
Join MoBotHouse, then the address192.168.4.1, then the password. - In the serial monitor: a list of addresses to try.
- In the browser, at
/sensors, something like:
{"sensors": {"temperature": 23, "humidity": 45, "gas": 812, "pot": 2047, "pir": false, "ldr": 3300, "slider_1": 0.0, "toggle_1": false, "rgb_1": {"r": 0, "g": 0, "b": 0}, "text_1": ""}, "ts": 91234}Reload it with your hand over the light sensor and ldr drops. Wave in front
of the board and pir becomes true. Turn the knob and pot changes.
That is the test: the numbers must move when you touch the house.
Looking is easy; changing needs a send
Section titled “Looking is easy; changing needs a send”A browser address bar can only look at an address. To change something you have to send — which is what the Smart Home dashboard inside MoBot does for you, and what these lines do from a computer joined to the same network:
curl -X POST http://192.168.4.1/fan -d '{"value": 60}'curl -X POST http://192.168.4.1/lamp -d '{"value": true}'curl -X POST http://192.168.4.1/say -d '{"value": "Hello"}'curl -X POST http://192.168.4.1/colour -d '{"value": {"r":0,"g":200,"b":200}}'and then, on the board:
| you send | the house does |
|---|---|
/fan 60 |
the fan spins up to 60 % |
/lamp true |
the colour light turns white |
/lamp false |
the colour light goes dark |
/colour |
the colour light changes colour (red, green and blue, each 0–255) |
/say Hello |
the word appears on the screen and the buzzer beeps once |
/say goodnight |
the house stops the web page, switches everything off and says Goodnight |
/lamp and /colour are two controls for the same light. Each one changes it
when its own value changes: switch the lamp on and the light is white, send a
colour and it takes that colour, switch the lamp off and it goes dark.
Sending goodnight is the only way this program ends. stop() has no block
either — once a blocks program has started the web page there is no way to stop
it again short of resetting the board.
The words this program uses
Section titled “The words this program uses”| you write | what it does |
|---|---|
home.dashboard.start(SSID, PASSWORD) |
makes the house’s own Wi-Fi network and starts the web page; True when it runs |
home.dashboard.ip(), is_running() |
the address to type in, and whether the page is up |
add_slider(path), add_switch(path), add_color(path), add_text(path) |
a new control at that web address; gives back its number |
slider(n), switch(n), color(n), text(n) |
what was last sent to control number n |
update_temperature(v) and the other update_... |
a reading for /sensors |
home.dashboard.stop() |
stops the web page |
The order that matters
Section titled “The order that matters”web.start(SSID, PASSWORD) # FIRSTfan_id = web.add_slider("/fan") # only thenstart() builds a brand new web page. A control added before it was added
to the old page — the one the house serves on its own when it is on your Wi-Fi —
and is thrown away with it, so the phone gets nothing at /fan. With no page
running at all, the add fails with
AttributeError: 'NoneType' object has no attribute 'add_slider'. There is
nothing in the blocks that makes the order obvious, and it is the most common way
this goes wrong.
The program
Section titled “The program”This is a reading copy of the program in the project: editing it changes nothing, so open the project and edit it there.
# main.py — Web dashboard (Python) (iot)## A reading copy of one file inside 04-web-dashboard.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 04-web-dashboard.main.py.
"""Web dashboard - MoBot Smart Home: your house on your phone.
The board makes its OWN little wifi network. You join it with a phone, open aweb address, and you are talking to the house.
Two halves:
* The house TELLS you things. update_temperature(21) and so on put a number where anyone can read it at http://192.168.4.1/sensors .
* You TELL the house things. add_slider("/fan") makes a new address the phone can send to, and slider(...) is how your program finds out what was sent.
The block set can start the web page, add a control and read one. It has noway to stop the web page again, and it cannot wait for a word typed on thephone - both of which are down here.
ORDER MATTERS. dashboard.start() must come FIRST. Starting it throws awayevery control that was added before, because it builds a brand new web page."""
import time
SSID = "MoBotHouse"PASSWORD = "mobot1234" # at least 8 characters (the usual WPA2 rule)
web = home.dashboarddisplay = home.displaylamp = home.rgb_led
# ---------------------------------------------------------------- start -----
display.clear()display.show_text("Starting", 0, 0)display.show_text("wifi...", 0, 16)
print("Making a wifi network called", SSID)ok = web.start(SSID, PASSWORD)
if not ok: print("The web page did not start.") display.clear() display.show_text("WiFi failed", 0, 24) raise SystemExit
ip = web.ip()print("Running:", web.is_running(), " address:", ip)
display.clear()display.show_text("Join " + SSID, 0, 0)display.show_text(str(ip), 0, 16)display.show_text("pw " + PASSWORD, 0, 32)
# ------------------------------------------------------------- controls -----# Each of these makes a new web address: send to it to change it, open it to# read it back. Each one gives back a number your program uses to read it.
fan_id = web.add_slider("/fan") # a numberlamp_id = web.add_switch("/lamp") # on or off - the colour light, white or darkcolour_id = web.add_color("/colour") # three numbers - the block's RGB kindmessage_id = web.add_text("/say") # some words - the block's Text kind
base = "http://" + str(ip)print("")print("Join the wifi network " + SSID + " (password " + PASSWORD + "), then:")print("")print("TO LOOK - type these straight into a browser:")print(" " + base + "/status what this board can do")print(" " + base + "/sensors everything at once")print(" " + base + "/temperature just the temperature")print(" " + base + "/fan what the fan was last told")print("")print("TO CHANGE - a browser address bar can only LOOK. To change something")print("you have to SEND, which the Smart Home dashboard in MoBot does for you.")print("From a computer you can also do it by hand:")print(' curl -X POST ' + base + '/fan -d \'{"value": 60}\'')print(' curl -X POST ' + base + '/lamp -d \'{"value": true}\'')print(' curl -X POST ' + base + '/say -d \'{"value": "Hello"}\'')print(' curl -X POST ' + base + '/colour -d \'{"value": {"r":0,"g":200,"b":200}}\'')print("")
# ----------------------------------------------------------------- loop -----
last_message = ""
# The house has ONE colour light, and two controls for it: /lamp makes it white# or dark, /colour makes it any colour. Each one changes the light only when ITS# OWN value changes. (/colour starts out as red 0, green 0, blue 0; writing it# every time round would turn a white lamp dark again half a second later.)last_lamp = Falselast_colour = None
while True: # ---- tell the world what the house can feel ------------------------- # temperature() and humidity() are None until the sensor's first good # reading, so only send real numbers. temperature = home.temperature_sensor.temperature() humidity = home.temperature_sensor.humidity() if temperature is not None: web.update_temperature(temperature) if humidity is not None: web.update_humidity(humidity)
web.update_gas(home.gas_sensor.level()) # 0..4095 web.update_ldr(home.light_sensor.level()) # 0..4095, bigger = brighter web.update_pot(home.knob.position()) # 0..4095 web.update_pir(home.motion_sensor.motion_detected())
# ---- do what the phone asked --------------------------------------- speed = web.slider(fan_id) if speed is not None: home.fan.set_speed(int(speed))
lamp_on = bool(web.switch(lamp_id)) if lamp_on != last_lamp: last_lamp = lamp_on if lamp_on: lamp.set_color(255, 255, 255) # white: red, green and blue all the way up else: lamp.set_color(0, 0, 0) # dark
colour = web.color(colour_id) if isinstance(colour, dict) and colour != last_colour: last_colour = colour # Red, green, blue, each 0..255 - what the phone picks is what the # lamp shows. lamp.set_color(colour.get("r", 0), colour.get("g", 0), colour.get("b", 0))
message = web.text(message_id) if message and message != last_message: last_message = message display.clear() display.show_text(str(message)[:16], 0, 0) display.show_text(str(ip), 0, 48) home.buzzer.play_note("C5", 120) print("the phone said:", message)
# A password to close the house down again. There is no block for # stopping the web page once it has started. if str(message).strip().lower() == "goodnight": print("Shutting the web page down.") web.stop() home.fan.off() lamp.set_color(0, 0, 0) display.clear() display.show_text("Goodnight", 0, 24) print("Running:", web.is_running()) break
time.sleep(0.5)Try changing it
Section titled “Try changing it”- Add a second slider on
/brightnessand use it to dim the RGB light. - Make the screen show the temperature all the time, and the phone’s message only for five seconds.
- Give the fan a mind of its own: run it automatically when the temperature goes over 28, unless the phone has said otherwise.
Your house, on your phone. The board makes its own little Wi-Fi network. You join it, open a web address, and you are talking to the house: reading the temperature, the light, the gas and the movement sensor, and switching the fan, the colour light and the screen.
Project for firmware 2.x: 04-web-dashboard.mobot. Open it in MoBot.
What you need
Section titled “What you need”- A MoBot Smart Home board with screen, fan, RGB light and the DHT11, gas, light, potentiometer and motion sensors.
- A phone or a laptop with Wi-Fi.
- A USB cable and the serial monitor, at least the first time.
How to run it
Section titled “How to run it”- Open 04-web-dashboard.mobot. Change
SSIDandPASSWORDif you like — use a password of at least 8 characters: that is the usual rule for WPA2 Wi-Fi networks. - Press Save. MoBot restarts the board, and it runs the program.
- The screen shows the network name, the address and the password. Read them off the board.
- On your phone, join the Wi-Fi network MoBotHouse. Your phone will warn you there is no internet on it — that is right, this network is just the house.
- Open
http://192.168.4.1/sensorsin the browser.
What you should see
Section titled “What you should see”- On the board’s screen:
Join MoBotHouse, then the address192.168.4.1, then the password. - In the serial monitor: a list of addresses to try.
- In the browser, at
/sensors, something like:
{"sensors": {"temperature": 23, "humidity": 45, "gas": 812, "pot": 2047, "pir": false, "ldr": 3300, "slider_1": 0.0, "toggle_1": false, "rgb_1": {"r": 0, "g": 0, "b": 0}, "text_1": ""}, "ts": 91234}Reload it with your hand over the light sensor and ldr drops. Wave in front
of the board and pir becomes true. Turn the knob and pot changes.
That is the test: the numbers must move when you touch the house.
Looking is easy; changing needs a send
Section titled “Looking is easy; changing needs a send”A browser address bar can only look at an address. To change something you have to send — which is what the Smart Home dashboard inside MoBot does for you, and what these lines do from a computer joined to the same network:
curl -X POST http://192.168.4.1/fan -d '{"value": 60}'curl -X POST http://192.168.4.1/lamp -d '{"value": true}'curl -X POST http://192.168.4.1/say -d '{"value": "Hello"}'curl -X POST http://192.168.4.1/colour -d '{"value": {"r":0,"g":80,"b":80}}'and then, on the board:
| you send | the house does |
|---|---|
/fan 60 |
the fan spins up to 60 % |
/lamp true |
the colour light turns white |
/lamp false |
the colour light goes dark |
/colour |
the colour light changes colour (each number is a percentage, 0–100) |
/say Hello |
the word appears on the screen and the buzzer beeps once |
/say goodnight |
the house shuts the web server down, switches everything off and says Goodnight |
/lamp and /colour are two controls for the same light. Each one changes it
when its own value changes: switch the lamp on and the light is white, send a
colour and it takes that colour, switch the lamp off and it goes dark.
Sending goodnight is the only way this program ends. stop_web_server() has
no block either — once a blocks program has started a server there is no way to
stop it again short of resetting the board.
The order that matters
Section titled “The order that matters”srv.start_web_server(SSID, PASSWORD) # FIRSTfan_id = srv.register_slider("/fan") # only thenRegister a control before the server exists and you get
AttributeError: 'NoneType' object has no attribute 'register_slider'with no explanation. There is nothing in the blocks that makes the order obvious, and it is the most common way this goes wrong.
The program
Section titled “The program”This is a reading copy of the program in the project: editing it changes nothing, so open the project and edit it there.
# main.py — Web dashboard (Python) (iot)## A reading copy of one file inside 04-web-dashboard.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.
"""Web dashboard - MoBot Smart Home: your house on your phone.
The board makes its OWN little wifi network. You join it with a phone, open aweb address, and you are talking to the house.
Two halves:
* The house TELLS you things. update_temperature(21) and so on put a number where anyone can read it at http://192.168.4.1/sensors .
* You TELL the house things. register_slider("/fan") makes a new address the phone can post to, and get_slider(...) is how your program finds out what was posted.
The block set has one register block and one get block (Toggle, Slider, RGBor Text). It has no way to stop the server again - which is down here.
ORDER MATTERS. start_web_server() must come FIRST. Registering a controlbefore the server exists fails with AttributeError: 'NoneType' object has no attribute 'register_slider'"""
import time
SSID = "MoBotHouse"PASSWORD = "mobot1234" # at least 8 characters (the usual WPA2 rule)
srv = mobotIOT.serveroled = mobotIOT.oledrgb = mobotIOT.rgb_led
# ---------------------------------------------------------------- start -----
oled.clear_screen()oled.display_text("Starting", 0, 0)oled.display_text("wifi...", 0, 16)
print("Making a wifi network called", SSID)ok = srv.start_web_server(SSID, PASSWORD)
if not ok: print("The server did not start.") oled.clear_screen() oled.display_text("WiFi failed", 0, 24) raise SystemExit
ip = srv.get_server_ip()print("Running:", srv.is_server_running(), " address:", ip)
oled.clear_screen()oled.display_text("Join " + SSID, 0, 0)oled.display_text(str(ip), 0, 16)oled.display_text("pw " + PASSWORD, 0, 32)
# ------------------------------------------------------------- controls -----# Each of these makes TWO new web addresses: one to write to, one to read back.
fan_id = srv.register_slider("/fan") # a numberlamp_id = srv.register_toggle("/lamp") # on or off - the colour light, white or darkcolour_id = srv.register_rgb("/colour") # three numbers - the block's RGB kindmessage_id = srv.register_text("/say") # some words - the block's Text kind
base = "http://" + str(ip)print("")print("Join the wifi network " + SSID + " (password " + PASSWORD + "), then:")print("")print("TO LOOK - type these straight into a browser:")print(" " + base + "/status what this board can do")print(" " + base + "/sensors everything at once")print(" " + base + "/temperature just the temperature")print(" " + base + "/fan what the fan was last told")print("")print("TO CHANGE - a browser address bar can only LOOK. To change something")print("you have to SEND, which the Smart Home dashboard in MoBot does for you.")print("From a computer you can also do it by hand:")print(' curl -X POST ' + base + '/fan -d \'{"value": 60}\'')print(' curl -X POST ' + base + '/lamp -d \'{"value": true}\'')print(' curl -X POST ' + base + '/say -d \'{"value": "Hello"}\'')print(' curl -X POST ' + base + '/colour -d \'{"value": {"r":0,"g":80,"b":80}}\'')print("")
# ----------------------------------------------------------------- loop -----
last_message = ""
# The house has ONE colour light, and two controls for it: /lamp makes it white# or dark, /colour makes it any colour. Each one changes the light only when ITS# OWN value changes. (/colour starts out as red 0, green 0, blue 0; writing it# every time round would turn a white lamp dark again half a second later.)last_lamp = Falselast_colour = None
while True: # ---- tell the world what the house can feel ------------------------- try: temperature = mobotIOT.dht11.read(0) humidity = mobotIOT.dht11.read(1) srv.update_temperature(temperature) srv.update_humidity(humidity) except Exception: # The DHT11 is slow and sulky and fails now and then. Keep going. temperature = None
srv.update_gas(mobotIOT.mq135.read()) # 0..4095 srv.update_ldr(mobotIOT.ldr.read()) # 0..4095, bigger = brighter srv.update_pot(mobotIOT.pot.read()) # 0..4095 srv.update_pir(mobotIOT.pir.motion_detected())
# ---- do what the phone asked --------------------------------------- speed = srv.get_slider(fan_id) if speed is not None: mobotIOT.fan.set_speed(int(speed))
lamp_on = bool(srv.get_toggle(lamp_id)) if lamp_on != last_lamp: last_lamp = lamp_on if lamp_on: rgb.write(100, 100, 100) # white: red, green and blue all the way up else: rgb.write(0, 0, 0) # dark
colour = srv.get_rgb(colour_id) if isinstance(colour, dict) and colour != last_colour: last_colour = colour # Red, green, blue: firmware 2.0 names each lamp pin by the colour it # really drives, so what the viewer picks is what the lamp shows. rgb.write(colour.get("r", 0), colour.get("g", 0), colour.get("b", 0))
message = srv.get_text(message_id) if message and message != last_message: last_message = message oled.clear_screen() oled.display_text(str(message)[:16], 0, 0) oled.display_text(str(ip), 0, 48) mobotIOT.buzzer.play_note("C5", 120) print("the phone said:", message)
# A password to close the house down again. There is no block for # stopping a server once it has started. if str(message).strip().lower() == "goodnight": print("Shutting the web server down.") srv.stop_web_server() mobotIOT.fan.off() rgb.write(0, 0, 0) oled.clear_screen() oled.display_text("Goodnight", 0, 24) print("Running:", srv.is_server_running()) break
time.sleep(0.5)Try changing it
Section titled “Try changing it”- Add a second slider on
/brightnessand use it to dim the RGB light. - Make the screen show the temperature all the time, and the phone’s message only for five seconds.
- Give the fan a mind of its own: run it automatically when the temperature goes over 28, unless the phone has said otherwise.