前回の記事でRaspberryPi4で立てた無線LANを使ってホスト側のRaspberryPi4からPicoWへ適当なコマンドを送ってPicoWから適当な返事を返すコードを書いた
UECSを使いたかったんだけど素人にはCのサンプルコードをPythonで書き直すスキルがなかったのでできる範囲で適当に作った。
PicoWで実行するコード
import network,socket,machine,time
from picozero import pico_temp_sensor,pico_led
ssid = 'NameOfNetwork'
password = 'AardvarkBadgerHedgehog'
def connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid,password)
while wlan.isconnected()==False:
print("Waiting for connection")
time.sleep(5)
ip = wlan.ifconfig()[0]
print(f'Connected on {ip}')
return ip
def open_socket(ip):
address = (ip,8080)
connection = socket.socket()
connection.bind(address)
connection.listen(1)
return connection
def serve(connection):
pico_led.on()
while True:
client = connection.accept()[0]
request = client.recv(1024)
try:
request = request.decode()
if request=="Hello!":
response = "Hello world!"
elif request=="temp?":
temp = pico_temp_sensor.temp
response = "Current temperture is "+str(round(temp,2))+"°C"
elif request=="time?":
response = "Current time is "+str(time.time())
else:
response = "pardon?"
except:
response = "Failed recieving a message"
print(request)
client.send(response.encode('utf-8'))
client.close()
try:
ip = connect()
connection = open_socket(ip)
serve(connection)
except KeyboardInterrupt:
machine.reset()
RaspberryPi4側で実行するコード
import socket,time,datetime,os
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
def send_message(ip,port,mes):
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
s.connect((ip,port))
s.sendall(mes.encode('utf-8'))
buf = s.recv(1024)
return buf
try:
ip = '192.168.4.20'
port = 8080
while True:
try:
buf = send_message(path,ip,port,"Hello!")
buf = buf.decode().strip("()")
print(buf)
time.sleep(1)
buf = main(path,ip,port,"temp?")
buf = buf.decode().strip("()")
print(buf)
time.sleep(1)
buf = main(path,ip,port,"time?")
buf = buf.decode().strip("()")
print(buf)
time.sleep(1)
buf = main(path,ip,port,"WTF!!!")
buf = buf.decode().strip("()")
print(buf)
time.sleep(1)
except:
dt_now = datetime.datetime.now()
dt_now = dt_now.strftime("%Y-%m-%d_%H:%M:%S")
print(dt_now,"error, try again.")
time.sleep(1)
pass
except KeyboardInterrupt:
pass
通信プロトコル的なものが無法地帯となっているけど独立したネットワークなので気にしない…。登録済のMACしか接続できないようにしているのでよほどのことがなければ事故もおこらないはず。多分。
受信したコマンドに応じて実行する関数を変えれば測定ノードから環境情報を取得して制御ノードでモーターの制御みたいなこともできる。