Raspberry Pi - Threaded Socket Server with Python

From myWiki


import socket
import threading
import RPi.GPIO as GPIO
import datetime
import json

# idle disconnect time
client_timeout = 60
# Listen on the following port number
port_num = 8888 

# setting a current mode
GPIO.setmode(GPIO.BCM)
#removing the warings
GPIO.setwarnings(False)

GPIO.setup([18,17,15,14], GPIO.OUT)

class Module(object):
    def __init__(self, name, mtype):
        self.name = name
        self.mtype = "relay_module"
        self.state = { "1" : 0 , "2" : 0 , "3" : 0 , "4" : 0 }
        self.pins = {"1": 18, "2": 17, "3": 15, "4": 14}

    # we are using the N.O. pins on the relay so 0 turns on the relay

    def on(self, port):
        self.state[port] = 1
        GPIO.output(self.pins[port], GPIO.LOW)

    def off(self, port):
        self.state[port] = 0
        GPIO.output(self.pins[port], GPIO.HIGH)

    def status(self, port):
        self.state[port]

relay_module = Module('')

class ThreadedServer(object):
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind((self.host, self.port))

    def listen(self):
        self.sock.listen(5)
        while True:
            client, address = self.sock.accept()
            client.settimeout(client_timeout)
            threading.Thread(target=self.listenToClient, args=(client, address)).start()

    # do message processing here
    def doIt(self,data):
        d = json.loads(data.decode("utf-8"))
        if d["set"] == '0':
            relay_module.off(d[0])
        elif d["set"] == '1':
            relay_module.on(d[0])
        else:
            print("invalid function "+d["set"])
        retVal = {
            'response': 'ok',
            'id': 'house',
            'site_id': 'main',
            'version': '1.0.0'
        }
        return retVal

    def listenToClient(self, client, address):
        size = 1024
        while True:
            try:
                data = client.recv(size) #messages are of type bytes
                print(data.decode("utf-8"))
                if data:
                    # Set the response to echo back the recieved data
                    response = self.doIt(data) # respond with a bytes type
                    client.send(response)
                else:
                    raise Exception('Client disconnected')
            except:
                # Client timed out
                client.close()
                return False


if __name__ == "__main__":
    ThreadedServer('', port_num).listen()

#cleanup all GPIO I/O pins
GPIO.cleanup()