controller.py 5.25 KB
Newer Older
Carldst's avatar
Carldst committed
1
2
3
4
5
6
7
# controller.py https://www.bogotobogo.com/python/python_network_programming_server_client.php
import socket
import time
from multiprocessing import Process
from APIs import *
import psutil
import os
Carl De Sousa Trias's avatar
Carl De Sousa Trias committed
8

Carldst's avatar
Carldst committed
9
10
import ast
import tkinter as tk
Carl De Sousa Trias's avatar
Carl De Sousa Trias committed
11
from tkinter import filedialog, simpledialog
Carldst's avatar
Carldst committed
12
13
import wget
import config
Carl De Sousa Trias's avatar
Carl De Sousa Trias committed
14
from PIL import Image
Carldst's avatar
Carldst committed
15
16
17
18
19
20
21
22

# create a socket object
serversocket = socket.socket(
	        socket.AF_INET, socket.SOCK_STREAM)

# get local machine name
host = socket.gethostname()

Carl De Sousa Trias's avatar
Carl De Sousa Trias committed
23
port = 12468
Carldst's avatar
Carldst committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

# bind to the port
serversocket.bind((host, port))

# queue up to 5 requests
serversocket.listen(5)
print("Controller Initialized")
CompCostFlag=False
while True:
    # establish a connection
    clientsocket, addr = serversocket.accept()
    # print("Got a connection from %s" % str(addr))
    # currentTime = time.ctime(time.time()) + "\r\n"
    data=clientsocket.recv(1024)
    message=data.decode()
    message = message.split()
    if not data: break
    if "help" in message[0].lower():
        ### to be updated
43
        print(" ----------------------------------------")
Carldst's avatar
Carldst committed
44
45
46
47
48
49
50
51
        print(" this program is the implementation of NNW in the AIF")
        print(" you can run AIM/AIW by sending 'run XX' ")
        print(" you can pause AIM/AIW by sending 'stop XX' ")
        print(" you can resume AIM/AIW by sending 'resume XX' ")
        print(" you can obtain the status of AIM/AIW by sending 'status XX' ")
        print(" you can end the program by typing 'exit'")
        print(" ----------------------------------------")

52
    elif "wget" in message[0].lower():
Carldst's avatar
Carldst committed
53
54
55
56
57
58
        test=wget.download(message[1])
        print(type(test))

    elif "getparse" in message[0].lower():

        #print(type(message[1]),message[1]) #always str
Carl De Sousa Trias's avatar
Carl De Sousa Trias committed
59

Carldst's avatar
Carldst committed
60
61
        root = tk.Tk()
        root.withdraw()
Carl De Sousa Trias's avatar
Carl De Sousa Trias committed
62
        filename = filedialog.askopenfilename(title='Select the zip (json and AIMs)', filetypes=(("Text files",
Carldst's avatar
Carldst committed
63
64
65
66
67
68
69
                                                                                             "*.zip"),
                                                                                            ("all files",
                                                                                             "*.*")))
        json_dict = MPAI_AIFS_GetAndParseArchive(filename)
        time.sleep(.5)
        import AIW.AIMs_files as AIMs_file
        config.AIM_dict = json_dict['SubAIMs']
70
71
        config.Topology = json_dict['Topology'] ### topology

Carldst's avatar
Carldst committed
72
73
        for i in range(len(json_dict['SubAIMs'])):
            config.AIMs[config.AIM_dict[i]["Name"]] = getattr(AIMs_file, config.AIM_dict[i]["Name"])()
74

Carldst's avatar
Carldst committed
75
76
        ### AIMs file should be in the .zip
        # print(AIMs.keys())
77
78
        # print(config.Topology)
        print(".json parsed")
Carl De Sousa Trias's avatar
Carl De Sousa Trias committed
79

Carldst's avatar
Carldst committed
80
81
82
83
84
85
86
87
88
89
90
91
    elif 'write' in message[0].lower():
        ## message[1] AIM_name, message[2] port_name, message[3] what to write
        MPAI_AIFM_Port_Input_Write(message[1],message[2],message[3])
    elif "read" in message[0].lower():
        ## message[1] AIM_name, message[2] port_name
        result=MPAI_AIFM_Port_Output_Read(message[1],message[2])
        print(message[2], "of", message[1], ":", result, type(result))
    elif "reset" in message[0].lower():
        ## message[1] AIM_name, message[2] port_name
        MPAI_AIFM_Port_Reset(message[1],message[2])

    elif 'run' in message[0].lower():
Carl De Sousa Trias's avatar
Carl De Sousa Trias committed
92
93
94
95
96
97
98
99
100
101
        for elements in config.Topology:
            # print(elements)
            if elements["Output"]["AIMName"]=="": ## no outputs means it's an input
                ### TBD better: if conditions link to the port reading
                root = tk.Tk()
                root.withdraw()
                path = filedialog.askopenfilename(title='Select '+str(elements["Input"]["PortName"]))

                MPAI_AIFM_Port_Input_Write(elements["Input"]["AIMName"], elements["Input"]["PortName"],
                                           path)
Carldst's avatar
Carldst committed
102
            else:
Carl De Sousa Trias's avatar
Carl De Sousa Trias committed
103
104
105
106
107
108
109
110
111
                MPAI_AIFM_AIM_Start(elements["Output"]["AIMName"])
                if elements["Input"]["AIMName"]=="": ## no inputs means it's an output
                    print("Output of",elements["Output"]["AIMName"],"- port",elements["Output"]["PortName"] )
                    print()
                    print(MPAI_AIFM_Port_Output_Read(elements["Output"]["AIMName"],elements["Input"]["PortName"]))
                    print()
                else:
                    MPAI_AIFM_Port_Input_Write(elements["Input"]["AIMName"], elements["Input"]["PortName"],
                                           MPAI_AIFM_Port_Output_Read(elements["Output"]["AIMName"],elements["Output"]["PortName"]))
Carldst's avatar
Carldst committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136


    elif 'status' in message[0].lower():
        print(config.dict_process)
        MPAI_AIFM_AIM_GetStatus(message[1])
    elif 'pause' in message[0].lower():
        MPAI_AIFM_AIM_Pause(message[1])
    elif 'resume' in message[0].lower():
        MPAI_AIFM_AIM_Resume(message[1])

    elif 'stop' in message[0].lower():
        if message[1].lower() in config.dict_process:
            config.dict_process[message[1]].terminate()
            print( message[1], "stopped")
        else:
            print(message[1], "isn't running")
    elif "exit" in message[0].lower():
        print("ending session...")

        break
    else:
        print("input not implemented")
    clientsocket.close()
print("session ended")

137
### TO DO https://docs.python.org/3/library/multiprocessing.html