黃昕暐
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # ESP8266/ESP32 通用的 MicroPython Web Server ###### tags: `MicroPython` `ESP32` `ESP8266` ### 緣由 如果使用 [Arduino Core](https://arduino-esp8266.readthedocs.io/en/latest/) 撰寫 ESP8266 的程式, 可以使用 [ESP8266WebServer](https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WebServer) 程式庫建立網頁伺服器, 這對於需要提供遠端遙控或是微服務 API 的應用來說非常方便, 可是如果你使用 MicroPython 撰寫 ESP8266 的程式, 就沒有簡單現成的對應模組可用, 網路上可以找到專為 ESP32 撰寫的相似功能模組, 但是卻大到無法挪到 ESP8266 上執行。 為了達到上述目的, 只好自己動手撰寫了一個輕量級的 [ESP8266WebServer](https://github.com/codemee/ESP8266WebServer) 模組來用。設計這個模組時, 有兩個基本原則: 1. 盡量模仿 Arduino Core 版本的 ESP8266WebServer 程式庫, 讓兩者的使用體驗相似。 2. 保持輕量, 原本就是為了自用, 所以這個模組只能處理 HTTP GET, 其餘功能一概不理。 由於這個模組僅使用到 MicroPython 的標準程式庫, 因此可以通用於 ESP8266/ESP32 上。 ### 模組安裝方法 這個模組運作實際上只需要 [ESP8266WebServer.py](https://github.com/codemee/ESP8266WebServer/blob/master/ESP8266WebServer.py), 你可從 github 直接複製整個模組回來: ```bash git clone https://github.com/codemee/ESP8266WebServer.git ``` 然後透過 [ampy](https://pypi.org/project/adafruit-ampy/) 工具或是 thonny IDE 將 ESP8266WebServer.py 上傳到 ESP8266/ESP32 控制板上即可。 ### 模組使用方法 要使用 ESP8266WebServer 模組, 必須依循以下步驟: 1. 匯入 ESP8266WebServer 模組: ```python import ESP8266WebServer ``` 1. 定義處理指定路徑的函式, 舉例來說, 如果我們希望透過以下路徑控制內建的 LED: ```html http://控制板IP/cmd?led=on http://控制板IP/cmd?led=off ``` 那麼所需要處理的路徑就是 "/cmd", "led" 就是這個路徑可附加的參數, 而 "on" 或是 "off" 則是參數內容。首先就是要撰寫一個專門處理 "/cmd" 路徑的函式: ```python def handleCmd(socket, args): if 'led' in args: if args['led'] == 'on': pin.off() elif args['led'] == 'off': pin.on() ESP8266WebServer.ok(socket, "200", args["led"]) else: ESP8266WebServer.err(socket, "400", "Bad Request") ``` 處理路徑的函式必須有 2 個參數, 第 1 個參數是用來傳送資料回用戶端的物件; 第 2 個參數則是隨路徑傳入的參數字典, 這個字典會以參數名稱為索引鍵 (key)、參數內容為元素值, 只要利用字典的操作就可以判斷是否有指定名稱的參數, 並且可以取出參數內容。上例中就以參數 led 的內容為 "on" 或 "off" 來控制 pin 物件控制的腳位電位高低。 這個函式最後必須傳回狀態碼以及內容給用戶端, 若正常處理時可叫用 ESP8266WebServer.ok, 否則叫用 ESP8266WebServer.err。這 2 個方法的第 1 個引數都是路徑處理函式的第 1 個參數;第 2 個引數則是狀態碼, 可自行參考 HTTP 文件;第 3 個引數是要送回給用戶端的內容, 如果需要, 可以加上第 4 個引數, 指定內容的格式, 例如若傳回的是 HTML 內容, 則要指定為 "text/html", 如果沒有指定, 格式預設為 "text/plain" 純文字。 1. 設定特定路徑與對應的處理函式: ```python ESP8266WebServer.onPath("/cmd", handleCmd) ``` 這表示若 HTTP GET 的請求路徑是 "/cmd", 就自動叫用 handleCmd 函式來處理。 1. 啟用網頁伺服器: ```python ESP8266WebServer.begin(8899) ``` 啟用時必須指定埠號, 若指定為 80 號, 在瀏覽器中就可以不標示埠號, 例如: ```html http://控制板IP/cmd?led=on ``` 若像是上面程式指定埠號是 8899, 那麼在瀏覽器中網址就要加上埠號, 例如: ```html http://控制板IP:8899/cmd?led=on ``` 1. 不斷檢查是否接到請求, 並在必要時關閉 ESP8266WebServer: ```python try: while True: # Let server process requests ESP8266WebServer.handleClient() except: ESP8266WebServer.close() ``` ### 簡易範例 瞭解以上流程後, 我們就可以撰寫一個簡易的程式, 可以讓使用者透過 HTTP GET 遙控 ESP8266 上內建的 LED 了: ```python= import ESP8266WebServer import network import machine GPIO_NUM = 2 # Builtin led (D4) # Wi-Fi configuration STA_SSID = "MEE_MI" STA_PSK = "PinkFloyd1969" # Disable AP interface ap_if = network.WLAN(network.AP_IF) if ap_if.active(): ap_if.active(False) # Connect to Wi-Fi if not connected sta_if = network.WLAN(network.STA_IF) if not ap_if.active(): sta_if.active(True) if not sta_if.isconnected(): sta_if.connect(STA_SSID, STA_PSK) # Wait for connecting to Wi-Fi while not sta_if.isconnected(): pass # Show IP address print("Server started @", sta_if.ifconfig()[0]) # Get pin object for controlling builtin LED pin = machine.Pin(GPIO_NUM, machine.Pin.OUT) pin.on() # Turn LED off (it use sinking input) # Handler for path "/cmd?led=[on|off]" def handleCmd(socket, args): if 'led' in args: if args['led'] == 'on': pin.off() elif args['led'] == 'off': pin.on() ESP8266WebServer.ok(socket, "200", args["led"]) else: ESP8266WebServer.err(socket, "400", "Bad Request") # Start the server @ port 8899 ESP8266WebServer.begin(8899) # Register handler for each path ESP8266WebServer.onPath("/cmd", handleCmd) try: while True: # Let server process requests ESP8266WebServer.handleClient() except: ESP8266WebServer.close() ``` 執行後會看到終端機顯示控制板的 IP: ```python Server started @ 192.168.100.214 ``` 接著, 就可以在瀏覽器的網址列鍵入控制 LED 的網址, 例如: ![](https://i.imgur.com/nkmH7M5.png) 就會讓 ESP8266 內建的 LED 亮起來, 瀏覽器內顯示的 "on" 就是從控制板處理 "/cmd" 路徑的 handleCmd 函式送回的, 如果使用 curl 工具可以看的更清楚: ``` curl -i http://192.168.100.214:8899/cmd?led=on HTTP/1.1 200 OK Content-Type: text/plain on ``` ### 結語 ESP8266WebServer 模組除了上述簡易的用法外, 也可以設定文件資料夾, 即可直接傳回 HTML 檔案, 甚至還可以在 HTML 中使用樣板, 以 Python 程式中的資料取代 HTML 文件中特定的字樣, 這些我們留待下一次的文章中說明。

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully