Files
OpenPLC_v3/webserver/openplc.py

165 lines
5.3 KiB
Python
Raw Normal View History

2018-06-14 10:43:51 -07:00
#Use this for OpenPLC console: http://eyalarubas.com/python-subproc-nonblock.html
import subprocess
import socket
import errno
import time
from threading import Thread
from queue import Queue, Empty
import io
2018-06-14 10:43:51 -07:00
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 = io.TextIOWrapper(stream, encoding='utf-8')
2018-06-14 10:43:51 -07:00
self._q = Queue()
def _populateQueue(stream, queue):
'''
2018-08-17 10:34:52 -05:00
Collect lines from 'stream' and put them in 'queue'.
2018-06-14 10:43:51 -07:00
'''
2018-08-17 10:34:52 -05:00
#while True:
while (self.end_of_stream == False):
2018-06-14 10:43:51 -07:00
line = stream.readline()
if line:
queue.put(line)
if "Compilation finished with errors!" in line or "Compilation finished successfully!" in line:
2018-08-17 10:34:52 -05:00
self.end_of_stream = True
2018-06-14 10:43:51 -07:00
else:
self.end_of_stream = True
2018-08-17 10:34:52 -05:00
raise UnexpectedEndOfStream
2018-06-14 10:43:51 -07:00
2018-08-17 10:34:52 -05:00
self._t = Thread(target = _populateQueue, args = (self._s, self._q))
2018-06-14 10:43:51 -07:00
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"):
self.theprocess = subprocess.Popen(['./core/openplc']) # XXX: iPAS
2018-06-14 10:43:51 -07:00
self.runtime_status = "Running"
def _rpc(self, msg, timeout=1000):
if not self.runtime_status == "Running":
return ""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 43628))
s.send(f'{msg}\n'.encode('utf-8'))
data = s.recv(timeout).decode('utf-8')
s.close()
self.runtime_status = "Running"
except socket.error as serr:
print(f'Socket error during {msg}, is the runtime active?')
self.runtime_status = "Stopped"
return data
2018-06-14 10:43:51 -07:00
def stop_runtime(self):
if (self.status() == "Running"):
self._rpc(f'quit()')
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/
2018-06-14 10:43:51 -07:00
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 = ""
a = subprocess.Popen(['./scripts/compile_program.sh', str(st_file)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
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
2018-06-14 10:43:51 -07:00
def status(self):
if ('compilation_object' in globals()):
if (compilation_object.end_of_stream == False):
return "Compiling"
if not self._rpc('exec_time()', 10000):
self.runtime_status = "Stopped"
2018-06-14 10:43:51 -07:00
return self.runtime_status
2018-06-14 10:43:51 -07:00
def start_modbus(self, port_num):
return self._rpc(f'start_modbus({port_num})')
2018-06-14 10:43:51 -07:00
def stop_modbus(self):
return self._rpc(f'stop_modbus()')
2018-06-14 10:43:51 -07:00
def start_dnp3(self, port_num):
return self._rpc(f'start_dnp3({port_num})')
2018-06-14 10:43:51 -07:00
def stop_dnp3(self):
return self._rpc(f'stop_dnp3()')
2019-06-17 11:59:48 -05:00
def start_enip(self, port_num):
return self._rpc(f'start_enip({port_num})')
2019-06-17 11:59:48 -05:00
def stop_enip(self):
return self._rpc(f'stop_enip()')
2018-06-14 10:43:51 -07:00
def start_pstorage(self, poll_rate):
return self._rpc(f'start_pstorage({poll_rate})')
def stop_pstorage(self):
return self._rpc(f'stop_pstorage()')
2018-06-14 10:43:51 -07:00
def logs(self):
return self._rpc(f'runtime_logs()',1000000)
2018-06-14 10:43:51 -07:00
def exec_time(self):
return self._rpc(f'exec_time()',10000) or "N/A"