1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| import socket import time import sys import RPi.GPIO as GPIO import threading #Please modify your Key!! key = '' host = '' port = #Please modify your Key!! class MainClass(): def init(self): print ('Start a socket:TCP...') self.socket_tcp = socket.socket(socket.AF_INET,socket.SOCK_STREAM) print ('TCP listen in port %s:%d'%(host,port)) self.host_addr = (host,port) self.socket_tcp.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) self.socket_tcp.bind(self.host_addr) self.socket_tcp.listen(50) GPIO.setmode(GPIO.BOARD) GPIO.setup(11,GPIO.OUT) GPIO.setup(12,GPIO.OUT) try: while True: print ('Try to receiving...') self.socket_con,self.addr = self.socket_tcp.accept() client_ip,port = self.addr print 'Client:',client_ip,'Port:',port self.StartThreads() time.sleep(0.1) except KeyboardInterrupt: self.socket_tcp.close() time.sleep(2) sys.exit() def StartThreads(self): thread = WorkThread(self.socket_con,self.addr) thread.start() def Error(self): self.socket_tcp.close() class WorkThread(threading.Thread): def __init__(self,fork_sock_con,addr): threading.Thread.__init__(self) self.connect = fork_sock_con self.ip,self.port = addr time.sleep(0.1) self.connect.send('Welcome To Raspberry Control Panel!\n') self.event = threading.Event() self.event.clear() self.delay = 30 self.ifdo = True def stop(self): self.ifdo = False def run(self): try: data = self.connect.recv(1024) if not data: self.ifdo = False elif data == key: time.sleep(0.1) #self.connect.send('{\"M\":\"checkinok\",\"ID\":\"D0001\"}') while self.ifdo: self.event.wait(0.2) data = self.connect.recv(1024) if not data: break elif data == '1': GPIO.output(12,True) GPIO.output(11,True) self.connect.send('The LED is On!\n') elif data == '0': GPIO.output(12,False) GPIO.output(11,False) self.connect.send('The LED is Off!\n') elif data == 'checkout': self.connect.send('Goodbye!') break else: self.connect.send('Invilid Package!\n') self.connect.close() time.sleep(0.5) print 'Disconnect with:%s'%(self.ip) self.connect.close() except socket.timeout: print 'timeout!' self.connect.close() a = MainClass() a.init()
|