やりたいこと
以下の通り。なお、Wi-Fiアクセスポイントは、iPhoneによるテザリングを想定している。
- Raspberry Pi pico Wが移動していると仮定する。
- Raspberry Pi pico Wが、登録しておいたWi-Fiアクセスポイントに近づいたら、自動で接続する。
- Wi-Fiアクセスポイントに接続できたら、SLACKに通知する。
- 通知をみら、指定されたURLにアクセスすると、ブラウザにON/OFFボタンが表示される。
- ボタンをクリックすると、出力端子が作動する。
コード
import machine
import network
import uasyncio
import urequests
from microdot import Microdot, Response
SSID = "YOUR_WI-FI_SSID"
PW = "WI-FI_PASSWORD"
SLACK_URL = "https://hooks.slack.com/services/***********/***********/************************"
async def run_web_server():
app = Microdot()
Response.default_content_type = 'text/html'
htmldoc_home = "<html><head><style type="text/css"><!-- table {width: 100%; height: 100%;} td {text-align: center;} button {width: 90%; height: 80%; font-size: 64px;} --></style><title>Wireless controller</title></head><body><table><tr><td><button onclick="location.href='./relay/on'">On</button></td><td><button onclick="location.href='./relay/off'">Off</button></td></tr></table></body></html>"
htmldoc_on = "<html><head><title>Wireless controller</title></head><body>Turned on.</br><a href="../../">Return</a></body></html>"
htmldoc_off = "<html><head><title>Wireless controller</title></head><body>Turned off.</br><a href="../../">Return</a></body></html>"
relay1 = machine.Pin(21, machine.Pin.OUT)
relay2 = machine.Pin(22, machine.Pin.OUT)
relay1.off()
relay2.off()
@app.get('/')
async def _index(request):
return htmldoc_home
@app.get('/relay/<status>')
async def _relay(request, status):
if status == 'on':
relay1.on()
relay2.on()
return htmldoc_on
elif status == 'off':
relay1.off()
relay2.off()
return htmldoc_off
return 'Invalid status.'
print('Web server is running.')
app.run(port = 80)
async def loop():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
led = machine.Pin('LED', machine.Pin.OUT)
while True:
if wlan.isconnected() == False:
print("Connecting to the Wi-Fi router.", end="")
count = 0
while wlan.isconnected() == False:
if count == 0:
wlan.disconnect()
wlan.connect(SSID, PW)
led.value(1)
print(".", end="")
await uasyncio.sleep(0.25)
led.value(0)
await uasyncio.sleep(0.25)
count += 1
if count > 10:
count = 0
print(" Connected.")
led.value(1)
wlan_status = wlan.ifconfig()
print(f'- IP Address: {wlan_status[0]}')
print(f'- Netmask: {wlan_status[1]}')
print(f'- Default Gateway: {wlan_status[2]}')
print(f'- Name Server: {wlan_status[3]}')
print()
print('Please access: http://{}/'.format(wlan.ifconfig()[0]))
print()
print('I will nortify to the Slack.')
data = {"text" : "Hello! Please access: http://" + wlan_status[0] +"/", "username" : "Raspberry Pi"}
response = urequests.post(SLACK_URL, json=data)
print(f'{response.status_code} {response.text}')
response.close()
await uasyncio.sleep(1)
async def main():
uasyncio.create_task(loop())
await run_web_server()
if __name__ == '__main__':
uasyncio.run(main())