Program ESP8266 with MicroPython Scripts

当ESP8266启动时, 会执行boot.pymain.py.

方案一: 通过WebREPL传输文件

方案二: 通过webrepl_cli传输文件

$ wget https://github.com/micropython/webrepl/raw/master/webrepl_cli.py \
       https://github.com/micropython/webrepl/raw/master/websocket_helper.py
$ chmod +x webrepl_cli.py
$ ./webrepl_cli.py mqtt.py 192.168.31.172:
put 192.168.31.172 8266  
mqtt.py -> /mqtt.py  
Password:  
Remote WebREPL version: (1, 8, 4)  
Sent 841 of 841 bytes  

boot.py

# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
import gc  
import webrepl  
webrepl.start()  
gc.collect()  

main.py

print('hello world')  

mqtt.py

import dht  
import json  
import time  
from machine import Pin, unique_id  
from ubinascii import hexlify  
from umqtt.simple import MQTTClient

SERVER = "iot.eclipse.org"  
TOPIC = "easypi/dht11"  
CLIENT_ID = hexlify(unique_id())

dht11 = dht.DHT11(Pin(0))  
led = Pin(2, Pin.OUT)

def read_dht11():  
  dht11.measure()
  tem = dht11.temperature()
  hum = dht11.humidity()
  return {
    "temperature": int(tem),
    "humidity": int(hum)
  }

def mqtt_pub(topic, message):  
  try:
    c = MQTTClient(CLIENT_ID, SERVER)
    c.connect()
    c.publish(topic, message)
    time.sleep_ms(200)
    c.disconnect()
  except Exception as e:
    print(e)

def run():  
  led.low()
  # FIXME: freezed
  #mqtt_pub(TOPIC, json.dumps(read_dht11()))
  led.high()
  Timer(-1).init(period=INTERVAL, mode=Timer.ONE_SHOT, callback=lambda t: run())

def run2():  
  while True:
    led.low()
    mqtt_pub(TOPIC, json.dumps(read_dht11()))
    led.high()

Shell

$ minicom -b 115200 -o -D /dev/serial0

WebREPL daemon started on ws://192.168.4.1:8266  
WebREPL daemon started on ws://0.0.0.0:8266  
Started webrepl in normal mode

MicroPython v1.8.4-10-gbc28ac8 on 2016-09-09; ESP module with ESP8266  
Type "help()" for more information.

>>> import os
>>> os.listdir()
['boot.py', 'port_config.py', 'main.py', 'mqtt.py']

>>> import mqtt
>>> mqtt.run2()
>>> # TYPE <Ctrl-C> TO INTERRUPT

>>> import machine
>>> machine.reset()
>>> # TYPE <Ctrl-A> <Shift-X> TO QUIT

WebREPL

http://micropython.org/webrepl/

Welcome to MicroPython!  
Password: ******  
WebREPL connected  
>>> import mqtt
>>> mqtt.run2()

Wiring

Dashboard