使raspberryPi接收来自tcp客户端和gpio引脚的请求

时间:2018-08-07 02:21:39

标签: python raspberry-pi

我正在使用raspberryPi 3,并且上面有一个python脚本,可以作为tcp服务器接收连接请求。我需要它继续侦听引脚,以防万一我收到来自它们的任何信号。代码,但它并没有按我想要的方式工作。也许您可以帮我一个主意。这是我的代码

import socket
import time
from time import sleep
import RPi.GPIO as GPIO

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_address = ('10.1.39.117', 5040)
print('starting up on %s port %s' % server_address)
sock.bind(server_address)

Msg = "IamHere"
d = ""

sock.listen(1)

GPIO.setmode(GPIO.BOARD)
GatePin       = 11 #pin11 to open gate
closeGatePin  = 23 #pin23 to close gate
LoopsensorPin = 16 #pin16 for loop sensor
TngPin        = 22 #pin22 for tng signal
RFIDPin       = 32 #pin32 for RFID signal
Count         = 1

Status = "closed"

GPIO.setwarnings(False)

def OpenGate():
    print ("Opening Gate.. led on....")
    GPIO.output(GatePin, GPIO.HIGH)  # led on
    time.sleep(0.5)


def CloseGate():
    print ("Closing Gate..led off...")
    GPIO.output(GatePin, GPIO.LOW)  # led off
    time.sleep(0.5)

def setup():
    GPIO.setup(GatePin, GPIO.OUT)  # Set GatePin's mode is output
    GPIO.output(GatePin, GPIO.LOW)  # Set GatePin high to off led
    GPIO.setup(closeGatePin, GPIO.OUT)
    GPIO.output(closeGatePin, GPIO.LOW)

GPIO.setup(LoopsensorPin,GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.setup(TngPin,GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.setup(RFIDPin,GPIO.IN,pull_up_down=GPIO.PUD_UP)


setup()

print("Start..")

while(True):

    if GPIO.input(LoopsensorPin)==0:
        print("Signal received from main loop sensor ")
        CloseGate()
        Count = 0
        Status = "closed"
        print("Gate status is: "+Status)


    #Listen for incoming connections

    #Wait for a connection
    print('waiting for a connection')
    connection, client_address = sock.accept()

    try:
        print('connection from', client_address)

        #while True:
        data = connection.recv(16)
        d = data.decode('utf-8')
        print('received from agent: %s' % d)
        if d == 'Open':
            print('sending response back to the agent')
            #connection.sendall(data)
            connection.send(str(Msg).encode())
            #open gate
            OpenGate()
            Status = "opened"
            print("Gate status is: "+Status)
            print("Waiting for loop sensor signal..")
            GPIO.input(LoopsensorPin)
            while(1):
                if GPIO.input(LoopsensorPin)==0:
                    print("Signal received from loop sensor..")
                    print("loop sensor pressed")
                    sleep(.5)
                    CloseGate()
                    break

    finally:
        # Clean up the connection
        connection.close()


GPIO.cleanup()

我认为我需要在While循环中进行一些更改才能使其正常工作,但是我不确定如何。

将所有tcp代码放入线程后,这是我的新While循环:

print("Application Start..")

if __name__ == "__main__":    
    myTCPThread = TCPThread(shared_variable)
    myTCPThread.start()

while(True):

    if GPIO.input(LoopsensorPin)==0:
        print("Signal received from main loop sensor ")
        CloseGate()
        Count = 0
        Status = "closed"
        print("Gate status is: "+Status)


    if shared_variable == 'Open':
        print('sending response back to the agent')
        connection.send(str(Msg).encode())
        #open gate
        OpenGate()
        Status = "opened"
        print("Gate status is: "+Status)
        print("Waiting for loop sensor signal..")
        GPIO.input(LoopsensorPin)
        while(1):
            if GPIO.input(LoopsensorPin)==0:
                print("Signal received from loop sensor..")
                print("loop sensor pressed")
                sleep(.5)
                CloseGate()
                break           

myTCPThread.close()
myTCPThread.join()      
GPIO.cleanup()  

1 个答案:

答案 0 :(得分:1)

可能无法正常运行,因为我无法对其进行测试。但是问题是socket.accept()是一个阻塞调用,因此阻塞了while循环。解决方案是将所有TCP代码放在这样的单独线程中

from threading import Thread


class TCPThread(Thread):
    def __init__(self, shared_variable):  # run TCP code in a seperate thread
        super().__init__()
        self.shared_variable = shared_variable  # share a variable from main thread to this thread

        server_address = ('10.1.39.117', 5040)  # from your code
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # ...
        self.sock.bind(server_address)  # ...
        sock.listen(1)  # ...

    def run(self):
        while True:  # this loop constantly updates the shared_variable, your while loop (commented below) can just check if it is "Open" or not
            connection, client_address = self.sock.accept()
            data = connection.recv(16)
            self.shared_variable[0] = data.decode('utf-8') 

shared_variable = [None]

if __name__ == "__main__":    
    myTCPThread = TCPThread(shared_variable)
    myTCPThread.start()

    # your while loop
    # ...
    # if shared_variable[0] == "Open":
    # ...