Я работаю над проектом, использующим RasPberry Pi3 для создания удаленного выключателя питания, доступного от клиентов.Я хочу, чтобы клиент (ы) мог читать и устанавливать состояние коммутатора.Я собрал немного кода Python (2.7).Я близок, но случайным образом получаю ошибку 32: ошибки прерванного канала, и я считаю, что неправильно делю переменные между потоками, или из-за неправильной синхронизации происходит разрыв соединений.Любая помощь будет оценена.
Сервер
import socket
import threading
from threading import Thread
from SocketServer import ThreadingMixIn
import time
import RPi.GPIO as GPIO
POWER = 5 # GPIO for SS Relay
LOCKOUT = "lcoff"
state = "PowerOff"
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(POWER, GPIO.OUT)
# Multithreaded Python server : TCP Server Socket Thread Pool
class ClientThread(Thread):
Thread.LOCKOUT = 'lcoff'
Thread.state = 'PowerOff'
def __init__(self,ip,port):
Thread.__init__(self)
self.ip = ip
self.port = port
print ("[+] New server socket thread started for " + ip + ":" + str(port))
def run(self):
while True :
cmd = conn.recv(40)
print ("Server received data:"), cmd
if GPIO.input(5) == 0:
Thread.state = "PowerOff"
else:
Thread.state = "PowerOn"
if cmd == "query":
print("query")
if cmd == "lcoff":
Thread.lockout="lcoff"
Thread.state="LockoutOff"
if cmd == "lcon":
Thread.lockout="lcon"
Thread.state="LockoutOn"
if cmd == "setoff" and LOCKOUT == "lcoff":
Thread.state="PowerOff"
GPIO.output(5,False)
print(Thread.state)
if cmd == "seton" and LOCKOUT == "lcoff":
Thread.state="PowerOn"
GPIO.output(5,True)
print(Thread.state)
if cmd == 'exit':
break
print ("MT-Python Server - Reporting current state:", Thread.state)
conn.send(Thread.state) # echo
# Multithreaded Python server : TCP Server Socket Program Stub
setup()
TCP_IP = '192.168.0.40'
TCP_PORT = 59115
BUFFER_SIZE = 40 # Usually 1024, but we need quick response
tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpServer.bind((TCP_IP, TCP_PORT))
threads = []
while True:
tcpServer.listen(4)
print ("MT-Python server: Waiting for connections from TCP clients...")
(conn, (ip,port)) = tcpServer.accept()
newthread = ClientThread(ip,port)
newthread.start()
threads.append(newthread)
for t in threads:
t.join()
Клиент
# Python TCP Client A
import socket
import RPi.GPIO as GPIO
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #GPIO for local Switch
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #GPIO for local Switch
host = '192.168.0.40'
port = 59115
BUFFER_SIZE = 40
cmd = "OK"
setup()
tcpClientA = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpClientA.connect((host, port))
cmd = raw_input("tcpClientA: Enter message/ Enter exit:")
while cmd != 'exit':
if GPIO.input(23) == 1:
cmd = "setoff"
tcpClientA.send(cmd)
data = tcpClientA.recv(BUFFER_SIZE)
print " Client2 received data:", data
if GPIO.input(24) == 1:
cmd = "seton"
tcpClientA.send(cmd)
data = tcpClientA.recv(BUFFER_SIZE)
print " Client2 received data:", data
#cmd = raw_input("tcpClientA: Enter message to continue/ Enter exit:")
tcpClientA.close()