Blame view

src/devices/Device.py 9.7 KB
e8e6f017   Jeremy   Reworked devices ...
1
from django.conf import settings
ac26ad2b   haribo   Date: 22/07/2016
2
import socket
bb0fbab1   haribo   Fini de mettre la...
3
import configparser
e8e6f017   Jeremy   Reworked devices ...
4
5
import abc
import select
bca9a283   Jeremy   Reworked the sche...
6
import utils.Logger as L
bb0fbab1   haribo   Fini de mettre la...
7

e8e6f017   Jeremy   Reworked devices ...
8
9
10
'''
    Generic object for the communication with all the devices (need inheritance)
'''
9774228b   haribo   Date: 22/06/2016
11

c53a13e0   Jeremy   Updating a lot of...
12
13
DEBUG_FILE = False

65149de7   Jeremy   Update
14

ddf59dd4   haribo   Remaniement :
15
class DeviceController():
e8e6f017   Jeremy   Reworked devices ...
16
17
18
19
20
21
22
23
24
    __metaclass__ = abc.ABCMeta
    logger = L.setupLogger("DeviceLogger", "Devices")
    name = ""
    config_file = "../config/socket_config.ini"
    config = None
    connected = False
    sock = None
    ip = None
    port = None
9b5bad52   haribo   Commented all the...
25

bb0fbab1   haribo   Fini de mettre la...
26
    def __init__(self, device_name):
e8e6f017   Jeremy   Reworked devices ...
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
        self.name = device_name
        self.getConfig()
        self.getConnection(device_name)
        self.connect()

    @abc.abstractmethod
    def set(self, command: str, *args):
        return

    @abc.abstractmethod
    def do(self, command: str, *args):
        return

    @abc.abstractmethod
    def get(self, command: str, *args):
        return

ce470283   Jeremy   Plc simulator fin...
44
45
46
47
    @abc.abstractmethod
    def getStatus(self):
        return

f7dd3df1   Jeremy   Update simulators...
48
49
50
51
52
53
54
55
56
57
58
59
    # def isConnectionEnded(self) -> bool:
    #     try:
    #         readable, writable, exceptional = select.select([], [], [self.sock], 0)
    #         if (not readable or exceptional):
    #             return False
    #         self.sock.rea
    #     except Exception as e:
    #         if (settings.DEBUG):
    #             self.log("Error in isConnectionEnded for device " + self.name)
    #         return False
    #     return False

e8e6f017   Jeremy   Reworked devices ...
60
61
62
63
    def sendMessage(self, message: str) -> int:
        if (not self.isConnected()):
            return (1)
        try:
f7dd3df1   Jeremy   Update simulators...
64
            readable, writable, exceptional = select.select([], [self.sock], [self.sock], 0)
e8e6f017   Jeremy   Reworked devices ...
65
66
67
            if not (writable or exceptional):
                raise (Exception("Socket not writable"))
            self.sock.send(bytes(message, "UTF-8"))
605b65e5   Jeremy   Update simulators
68
        except Exception as e:
e8e6f017   Jeremy   Reworked devices ...
69
            if (settings.DEBUG):
605b65e5   Jeremy   Update simulators
70
                self.log(self.name, "Could not send message on socket : " + message + " -> " + str(e))
e8e6f017   Jeremy   Reworked devices ...
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
            return (1)
        return (0)

    def isError(self, message: str):
        if (message == "FAILED" or message == "NOT_SET" or message == "DISCONNECTED"):
            return (True)
        return (False)

    def isConnected(self):
        if (not self.sock or not self.connected):
            if (self.connect()):
                return (False)
            self.connected = True
        return (True)

    def readBytes(self, size) -> str:
        if (not self.isConnected()):
            return ("NOT_SET")
65149de7   Jeremy   Update
89
        try:
f7dd3df1   Jeremy   Update simulators...
90
            readable, writable, exceptional = select.select([self.sock], [], [self.sock], 0)
e8e6f017   Jeremy   Reworked devices ...
91
92
93
94
95
96
97
98
            if not (readable or exceptional):
                raise (Exception("Socket not readable"))
            ret = self.sock.recv(size).decode()
            if (not ret):
                if (settings.DEBUG):
                    self.log(self.name, "Connection has been killed")
                self.connected = False
                return ("DISCONNECTED")
605b65e5   Jeremy   Update simulators
99
        except Exception as e:
e8e6f017   Jeremy   Reworked devices ...
100
            if (settings.DEBUG):
605b65e5   Jeremy   Update simulators
101
                self.log(self.name, "Socket not readable : " + str(e))
e8e6f017   Jeremy   Reworked devices ...
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
            return ("FAILED")
        return (ret)

    def blockAndReadBytes(self, size) -> str:
        self.sock.setblocking(1)
        return (self.readBytes(size))

    def blockAndReadMessage(self) -> str:
        return (self.blockAndReadBytes(1024))

    def setBlocking(self, flag):
        if (not self.sock):
            return (1)
        self.sock.setblocking(flag)
        return (0)

    # TODO maybe read more than 1024 bytes ?????
    def readMessage(self) -> str:
        return self.readBytes(1024)

    def getConnection(self, device_name):
        self.ip = self.config.get(device_name, "ip")
        self.port = int(self.config.get(device_name, "port"))
        return (0)

    def getConfig(self):
        self.config = configparser.ConfigParser()
        self.config.read(self.config_file)
        return (0)

    def log(self, device_name: str, message: str):
c53a13e0   Jeremy   Updating a lot of...
133
134
        if DEBUG_FILE and settings.DEBUG:
            self.logger.info("From device : " + device_name + " -> " + message)
e8e6f017   Jeremy   Reworked devices ...
135
136
137
138
139
140
141
142
        return (0)

    def connect(self):
        if (self.ip is None or self.port is None):
            self.log(self.name, "Ip or Port not initialized")
            return (1)
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
65149de7   Jeremy   Update
143
            self.sock.connect((self.ip, self.port))
e8e6f017   Jeremy   Reworked devices ...
144
145
146
            self.sock.setblocking(0) # Default : socket non blocking
        except Exception as e:
            if (settings.DEBUG):
605b65e5   Jeremy   Update simulators
147
                self.log(self.name, "Failed to connect to " + str(self.ip) + ":" + str(self.port) + " -> " + str(e))
65149de7   Jeremy   Update
148
            return (1)
e8e6f017   Jeremy   Reworked devices ...
149
        self.connected = True
65149de7   Jeremy   Update
150
        return (0)
ac26ad2b   haribo   Date: 22/07/2016
151

e8e6f017   Jeremy   Reworked devices ...
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280

                # def __init__(self, device_name):
    #     with open(GRAMMAR_FILE) as grammar_file:
    #         grammar = json.load(grammar_file)
    #
    #     enums = grammar["Enums"]
    #
    #     for enum in enums:
    #         self.enums[enum] = enums[enum]
    #
    #     if device_name[:6] == "Camera":
    #         device = grammar["Camera"]
    #
    #         for item in device["set"]:
    #             param_type = item["param_type"]
    #             if len(param_type) < 4 or param_type[:4] != "Enum":
    #                 ''' This transforms 'int' string to <int> type '''
    #                 param_type = locate(param_type)
    #             self.set_msgs.append((item["name"], item["nb_param"], param_type))
    #         for item in device["get"]:
    #             self.get_msgs.append(item)
    #         for item in device["do"]:
    #             param_type = item["param_type"]
    #             if len(param_type) < 4 or param_type[:4] != "Enum":
    #                 param_type = locate(param_type)
    #             self.do_msgs.append((item["name"], item["nb_param"], param_type))
    #
    #     device = grammar[device_name]
    #
    #     for item in device["set"]:
    #         param_type = item["param_type"]
    #         if len(param_type) < 4 or param_type[:4] != "Enum":
    #             param_type = locate(param_type)
    #         self.set_msgs.append((item["name"], item["nb_param"], param_type))
    #     for item in device["get"]:
    #         self.get_msgs.append(item)
    #     for item in device["do"]:
    #         param_type = item["param_type"]
    #         if len(param_type) < 4 or param_type[:4] != "Enum":
    #             param_type = locate(param_type)
    #         self.do_msgs.append((item["name"], item["nb_param"], param_type))
    #
    # def init_socket(self):
    #     if self.ip is None or self.port is None:
    #         raise ValueError("IP and/or PORT not initialized")
    #     # TODO: gérer un fail de connexion
    #     self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #     try:
    #         self.sock.connect((self.ip, self.port))
    #     except ConnectionError:
    #         print("Connection failed to ip : " + str(self.ip) + " Port : " + str(self.port), file=sys.stderr)
    #         return (1)
    #     return (0)
    #
    # def set(self, cmd, *args):
    #     '''
    #         Send a SET message to the device
    #     '''
    #     msg = [msg for msg in self.set_msgs if msg[0] == cmd]
    #     if len(msg) == 0:
    #         raise ValueError("Invalid message argument %s" % (cmd,))
    #     msg = msg[0]
    #     if len(args) not in msg[1]:
    #         raise ValueError("Bad number of arguments")
    #
    #     if type(msg[2]) is str:
    #         if msg[2] not in self.enums.keys():
    #             raise TypeError("Enum %s doesn't exist. Please check the grammar.json file." % (msg[2],))
    #         enum = self.enums[msg[2]]
    #         for arg in args:
    #             if arg not in enum:
    #                 raise TypeError("Bad value '%s' for enum '%s'" % (arg, msg[2]))
    #     else:
    #         for arg in args:
    #             if type(arg) != msg[2]:
    #                 raise TypeError("Bad type of argument: expected %s" % (msg[2],))
    #
    #
    #     # if self.init_socket() == 1:
    #     #     self._message_queue
    #     message = "SET " + cmd + " " + " ".join([str(arg) for arg in args])
    #     self.sock.send(bytes(message, "UTF-8"))
    #     # print("set ", cmd)
    #
    #
    # def get(self, cmd):
    #     '''
    #         Send a GET message to the device
    #     '''
    #     if cmd not in self.get_msgs:
    #         raise ValueError("Invalid message argument %s" % (cmd,))
    #
    #     self.init_socket()
    #     message = "GET " + cmd
    #     self.sock.send(bytes(message, "UTF-8"))
    #     # print("get ", cmd)
    #     # TODO: gérer le timeout
    #     ret = self.sock.recv(1024).decode()
    #     # print("return : ", ret)
    #     return ret
    #
    #
    # def do(self, cmd, *args):
    #     '''
    #         Send a DO message to the device
    #     '''
    #     msg = [msg for msg in self.do_msgs if msg[0] == cmd]
    #     if len(msg) == 0:
    #         raise ValueError("Invalid message argument %s" % (cmd,))
    #     msg = msg[0]
    #     if len(args) not in msg[1]:
    #         raise ValueError("Bad number of arguments")
    #
    #     if type(msg[2]) is str:
    #         if msg[2] not in self.enums.keys():
    #             raise TypeError("Enum %s doesn't exist. Please check the grammar.json file." % (msg[2],))
    #         enum = self.enums[msg[2]]
    #         for arg in args:
    #             if arg not in enum:
    #                 raise TypeError("Bad value '%s' for enum '%s'" % (arg, msg[2]))
    #     else:
    #         for arg in args:
    #             if type(arg) != msg[2]:
    #                 raise TypeError("Bad type of argument: expected %s" % (msg[2],))
    #
    #     self.init_socket()
    #     message = "DO " + cmd + " " + " ".join([str(arg) for arg in args])
    #     self.sock.send(bytes(message, "UTF-8"))
    #     # print("do ", cmd)