PLC.py 2.04 KB
import socket
from enum import Enum
import os
import sys

PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))

from device.Device import Device

class PLC(Device):

    def __init__(self):
        super().__init__("PLC")

    def loop(self):
        while True:
            try:
                conn, addr = self.sock.accept()
            except socket.error as e:
                print("There was a socket error: " + repr(e))
                break

            data = conn.recv(128).decode()

            # print("Received: " + data)

            ''' Pour le moment, on ne reçoit que le message 'STATUS', et on renvoie un JSON qui contient la totlaité des infos '''

            answer = ""
            cut_data = data.split(" ")

            if len(cut_data) < 2:
                print("Invalid message: " + data)
            else:
                cmd_type = cut_data[0]
                cmd = cut_data[1]
                args = cut_data[2:]
                if cmd_type == "SET":
                    pass
                elif cmd_type == "GET":
                    if cmd == "STATUS":
                        answer = self.create_status()
                    else:
                        answer = "Invalid cmd for GET: " + cmd
                        print(answer)
                elif cmd_type == "DO":
                    pass
                else:
                    print("Invalid message: " + data)

            if len(answer) > 0:
                conn.send(bytes(answer, "UTF-8"))
                # print("send: " + answer)
            conn.close()

    def create_status(self):
        status = ""

        ''' Il faudra un petit algo avec un timer pour donner le statut. En attendant, on renvoie tj la même chose '''

        status = ''' {
            presence : No,
            pressure : 1013.25,
            wind_dir : N
        } '''

        return status

if (__name__ == "__main__"):
    plc = PLC()
    plc.loop()