forked from thiagoralves/OpenPLC_v3
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathopenplc.py
283 lines (243 loc) · 10.6 KB
/
openplc.py
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
281
282
283
# -----------------------------------------------------------------------------
# Copyright 2015 Thiago Alves
# This file is part of the OpenPLC Software Stack.
# OpenPLC is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# OpenPLC is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with OpenPLC. If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------
#Use this for OpenPLC console: http://eyalarubas.com/python-subproc-nonblock.html
import subprocess
import socket
import errno
import time
import os
from threading import Thread
from queue import Queue, Empty
self_path = os.path.dirname(__file__)
intervals = (
('weeks', 604800), # 60 * 60 * 24 * 7
('days', 86400), # 60 * 60 * 24
('hours', 3600), # 60 * 60
('minutes', 60),
('seconds', 1),
)
def display_time(seconds, granularity=2):
result = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
result.append("{} {}".format(value, name))
return ', '.join(result[:granularity])
class NonBlockingStreamReader:
end_of_stream = False
def __init__(self, stream):
'''
stream: the stream to read from.
Usually a process' stdout or stderr.
'''
self._s = stream
self._q = Queue()
def _populateQueue(stream, queue):
'''
Collect lines from 'stream' and put them in 'queue'.
'''
#while True:
while (self.end_of_stream == False):
line = stream.readline()
if line:
queue.put(line)
if (line.find("Compilation finished with errors!") >= 0 or line.find("Compilation finished successfully!") >= 0):
self.end_of_stream = True
else:
self.end_of_stream = True
raise UnexpectedEndOfStream
self._t = Thread(target = _populateQueue, args = (self._s, self._q))
self._t.daemon = True
self._t.start() #start collecting lines from the stream
def readline(self, timeout = None):
try:
return self._q.get(block = timeout is not None,
timeout = timeout)
except Empty:
return None
class UnexpectedEndOfStream(Exception): pass
class runtime:
project_file = ""
project_name = ""
project_description = ""
runtime_status = "Stopped"
def start_runtime(self):
if (self.status() == "Stopped"):
openplc_path = os.path.abspath(os.path.join(self_path, '..', 'bin', 'openplc'))
self.theprocess = subprocess.Popen([openplc_path]) # XXX: iPAS
self.runtime_status = "Running"
def stop_runtime(self):
if (self.status() == "Running"):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 43628))
s.send(b'quit()\n')
data = s.recv(1000)
s.close()
self.runtime_status = "Stopped"
while self.theprocess.poll() is None: # XXX: iPAS, to prevent the defunct killed process.
time.sleep(1) # https://www.reddit.com/r/learnpython/comments/776r96/defunct_python_process_when_using_subprocesspopen/
except socket.error as serr:
print(("Failed to stop the runtime. Error: " + str(serr)))
def compile_program(self, st_file):
if (self.status() == "Running"):
self.stop_runtime()
self.is_compiling = True
global compilation_status_str
global compilation_object
compilation_status_str = ""
compile_program_path = os.path.abspath(os.path.join(self_path, '..', 'scripts', 'compile_program.sh'))
a = subprocess.Popen([compile_program_path, str(st_file)],
cwd=self_path,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding='UTF-8')
compilation_object = NonBlockingStreamReader(a.stdout)
def compilation_status(self):
global compilation_status_str
global compilation_object
while True:
line = compilation_object.readline()
if not line: break
compilation_status_str += line
return compilation_status_str
def status(self):
if ('compilation_object' in globals()):
if (compilation_object.end_of_stream == False):
return "Compiling"
#If it is running, make sure that it really is running
if (self.runtime_status == "Running"):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 43628))
s.send(b'exec_time()\n')
data = s.recv(10000)
s.close()
self.runtime_status = "Running"
except socket.error as serr:
print(("OpenPLC Runtime is not running. Error: " + str(serr)))
self.runtime_status = "Stopped"
return self.runtime_status
def start_modbus(self, port_num):
if (self.status() == "Running"):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 43628))
s.send(b'start_modbusslave(' + (b'%d' % port_num) + b')\n')
data = s.recv(1000)
s.close()
except ConnectionRefusedError:
print("Error connecting to OpenPLC runtime")
def stop_modbus(self):
if (self.status() == "Running"):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 43628))
s.send(b'stop_modbusslave()\n')
data = s.recv(1000)
s.close()
except ConnectionRefusedError:
print("Error connecting to OpenPLC runtime")
def start_dnp3(self, port_num):
if (self.status() == "Running"):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 43628))
s.send(b'start_dnp3s(' + (b'%d' % port_num) + b')\n')
data = s.recv(1000)
s.close()
except ConnectionRefusedError:
print("Error connecting to OpenPLC runtime")
def stop_dnp3(self):
if (self.status() == "Running"):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 43628))
s.send(b'stop_dnp3s()\n')
data = s.recv(1000)
s.close()
except ConnectionRefusedError:
print("Error connecting to OpenPLC runtime")
def start_enip(self, port_num):
if (self.status() == "Running"):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 43628))
s.send(b'start_enip(' + (b'%d' % port_num) + b')\n')
data = s.recv(1000)
s.close()
except ConnectionRefusedError:
print("Error connecting to OpenPLC runtime")
def stop_enip(self):
if (self.status() == "Running"):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 43628))
s.send(b'stop_enip()\n')
data = s.recv(1000)
s.close()
except ConnectionRefusedError:
print("Error connecting to OpenPLC runtime")
def start_pstorage(self, poll_rate):
if (self.status() == "Running"):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 43628))
s.send(b'start_pstorage(' + (b'%d' % poll_rate) + b')\n')
data = s.recv(1000)
s.close()
except ConnectionRefusedError:
print("Error connecting to OpenPLC runtime")
def stop_pstorage(self):
if (self.status() == "Running"):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 43628))
s.send(b'stop_pstorage()\n')
data = s.recv(1000)
s.close()
except ConnectionRefusedError:
print("Error connecting to OpenPLC runtime")
def logs(self):
if (self.status() == "Running"):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 43628))
s.send(b'runtime_logs()\n')
data = s.recv(1000000)
s.close()
return data
except ConnectionRefusedError:
print("Error connecting to OpenPLC runtime")
return "Error connecting to OpenPLC runtime"
else:
return "OpenPLC Runtime is not running"
def exec_time(self):
if (self.status() == "Running"):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 43628))
s.send(b'exec_time()\n')
data = s.recv(10000)
s.close()
return display_time(int(data), 4)
except ConnectionRefusedError:
print("Error connecting to OpenPLC runtime")
return "Error connecting to OpenPLC runtime"
else:
return "N/A"