備忘錄_20160105(定位)
修改
回首頁
程式 2023-04-25 17:16:38 1682414198 100
ESP32 S3 + DFPlayer Mini [web music player]
ESP32 S3 + DFPlayer Mini [web music player]
from machine import Pin
import utime
import network
import socket
from dfplayermini import Player
def doBlink():
global oLed
for i in range(3):
oLed.value(1)
utime.sleep(0.1)
oLed.value(0)
utime.sleep(0.1)
def getCommand(strRequest):
iIdxL=strRequest.find('[cmd=')
iIdxR=-1
if iIdxL!=-1:
iIdxR=strRequest[iIdxL:].find(']')
if iIdxL==-1 or iIdxR==-1:
return ['', ''] # 沒有符合格式的指令
strCommandString=strRequest[iIdxL+5:iIdxL+iIdxR]
if len(strCommandString)<1:
return ['', ''] # 格式正確,但無內容
iIdxComma=strCommandString.find(',')
if iIdxComma==-1:
strCmdStr=strCommandString
strCmdVal=''
else:
strCmdStr=strCommandString[:iIdxComma]
strCmdVal=strCommandString[iIdxComma+1:]
return [strCmdStr.strip(), strCmdVal.strip()]
def webSvr_init():
global oWLan
oWLan=network.WLAN(network.STA_IF)
oWLan.ifconfig(('192.168.100.99', '255.255.255.0', '192.168.100.1', '8.8.8.8'))
oWLan.active(True)
try:
if oWLan.isconnected():
oWLan.disconnect()
except Exception as oErr:
print('斷開無線網路發生意外!')
print(str(oErr))
try:
oWLan.connect('ssid','password')
except Exception as oErr:
print('連接無線網路發生意外!')
print(str(oErr))
for i in range(20):
utime.sleep(1)
if oWLan.isconnected():
print('wifi connected')
break
print('wifi not connected')
print(oWLan.ifconfig())
utime.sleep(0.1)
def webSvr_listen():
global oWLan, oMusic
oSocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
oSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
oSocket.setblocking(True)
oSocket.bind((oWLan.ifconfig()[0], 80))
oSocket.listen(10) # 可以有十條連線
booContinue=True
while booContinue:
oConn, oAddr=oSocket.accept()
utime.sleep(0.01)
oRequest=oConn.recv(1024) # buffer 1024 bytes
strRequest=str(oRequest)
[strCmdStr, strCmdVal]=getCommand(strRequest)
print(strCmdStr, strCmdVal)
doBlink()
# http://192.168.100.99/[cmd=goodbye]
# http://192.168.100.99/[cmd=play,1]
# ......
if strCmdStr=='goodbye':
print('goodbye')
oMusic.stop()
booContinue=False
elif strCmdStr=='play':
print('play',strCmdVal)
oMusic.play(int(strCmdVal))
elif strCmdStr=='stop':
print('stop')
oMusic.stop()
elif strCmdStr=='next':
print('next')
oMusic.play('next')
elif strCmdStr=='prev':
print('prev')
oMusic.play('prev')
elif strCmdStr=='volume':
print('volume',strCmdVal)
oMusic.volume(int(strCmdVal))
strHtml='<html><head><title>ESP32 S3</title></head><body>ver=0.6<hr>'+strRequest+'<hr>'+strCmdStr+'<hr>'+strCmdVal+'</body></html>'
oConn.write('HTTP/1.1 200 OK\n')
oConn.write('Content-Type: text/html\n')
oConn.write('Connection: close\n\n')
oConn.write(strHtml)
oConn.close()
if booContinue==False:
break
oSocket.close()
oMusic=Player(pin_TX=10, pin_RX=9)
oLed=Pin(2, Pin.OUT)
oWLan=False
webSvr_init()
webSvr_listen()
print('Really goodbye!')