Loading .pylint.rc +2 −2 Original line number Diff line number Diff line Loading @@ -393,8 +393,8 @@ preferred-modules= [EXCEPTIONS] # Exceptions that will emit a warning when caught. overgeneral-exceptions=BaseException, Exception overgeneral-exceptions=builtins.BaseException, builtins.Exception [REFACTORING] Loading misc/test_nsett.py +26 −16 Original line number Diff line number Diff line Loading @@ -3,28 +3,38 @@ import sys import time import pysen.ui.nsett as nsett def wait_callback(dt, done): if not done: print('%.1f waiting...\r' % dt, end='', flush=True) else: print('\n**ready** ', flush=True) from pysen.misc import setup_logger hostname = "localhost" quit = "no" if len(sys.argv)>1: hostname=sys.argv[1] ns = nsett.NseConnection(verbose=True, wait_callback=wait_callback) ns.connect(hostname) if len(sys.argv)>2: quit=sys.argv[2] #ns.send('testmode off') logger = setup_logger() ns.send('q_move 0.10', timeout=300) # takes ~200s on the first take with "real" mode time.sleep(5) ns.send('q_move 0.20', timeout=300) # taked ~10s on the second take def wait_callback(dt, done, cmd=""): if done: print('**ready** ', flush=True) return print('%.3fs waiting...\r' % dt, end='', flush=True) ns = nsett.NseConnection(verbose=True, wait_callback=wait_callback) try: ns.connect(hostname) except OSError as err: sys.exit(-1) ns.send('testmode on') ns.send('tofconf lambda 6.5e-10 detpos 27.3') ns.send('tau 20e-9') ns.send('q_move 0.50' ) ns.send('display physics') ;#print('-->',"\n".join(ns.pop())) ns.send('show physics') ;#print('-->',"\n".join(ns.pop())) ns.send('show tech' ) ;#print('-->',"\n".join(ns.pop())) if quit == "yes": ns.send('quit', timeout=None) print('done') ns.disconnect() pysen/revision.py +2 −2 Original line number Diff line number Diff line Loading @@ -3,8 +3,8 @@ PySEN revision module """ import sys __version__ = "1.3" __release__ = "b3" __date__ = "Mar 16, 2023" __release__ = "b5" __date__ = "Mar 17, 2023" def version(full=False): "get pysen version number" Loading pysen/ui/SimpleEchoSimulator.py +3 −5 Original line number Diff line number Diff line Loading @@ -29,9 +29,7 @@ def sqt(t, coh, tcoh, inc, tinc, beta=1): return coh*f_exp(t,tcoh,beta)-1/3*inc*f_exp(t,tinc,beta) class MainWindow(QMainWindow, Ui_MainWindow): """ Main for viewing and deleting available groups. """ """Main for viewing and deleting available groups.""" def __init__(self, parent=None): """init MainWindow""" super().__init__(parent) Loading Loading @@ -238,8 +236,8 @@ class MainWindow(QMainWindow, Ui_MainWindow): self.lines['dn'].set_data(dj/MICRO,dn) self.lines['ave'].set_data(dj/MICRO,ave) bot = min(np.amin(yecho), min(up,dn))*0.8 top = max(np.amax(yecho), max(up,dn))*1.1 bot = min(np.amin(yecho), up, dn)*0.8 top = max(np.amax(yecho), up, dn)*1.1 ax.set_ylim(bottom=bot, top=top) ysqt = sqt(xt, coh, tcoh, inc, tinc,beta)/norm Loading pysen/ui/nsett.py +58 −62 Original line number Diff line number Diff line Loading @@ -5,10 +5,10 @@ Pythonic equivalent for nsetty C-program """ import os import socket import errno import time import struct import threading import logging from collections import deque from ..iostrings import encode, decode Loading @@ -26,22 +26,23 @@ class NseConnection: "ReceiveNewCmd(): Authorization timeout deactivated.") #SOCKET_FILE = 'stream.tmp' SOCKET_PORT = 1966 LOG_FILE = 'nsett.log' MAX_QUELEN = 16 # remember last 16 responses DEF_TIMEOUT = 30 MAX_QUELEN = 32 # remember last 16 responses DEF_TIMEOUT = 10 """NSE TTY connection""" def __init__(self, logfile=None, wait_callback=None, verbose=False): def __init__(self, wait_callback=None, verbose=False): self._sock = None self._sock_timeout = 3.0 # FIXME: hardcoded socket timeout self._pid = os.getpid() self._pid_s = struct.pack('I', self._pid) #pylint: disable=consider-using-with self._log = open(logfile or NseConnection.LOG_FILE, 'a', encoding="utf8") self.log = logging.getLogger() self._reply = deque(maxlen=NseConnection.MAX_QUELEN) self._connected = False self._busy = False self._hostname = socket.gethostname() self._callback = wait_callback or self._default_callback self._thread = None # receiving thread self._thread_done = threading.Event() # thread event (to stop) self._thread_busy = threading.Event() # thread is busy receving data self._mode = 'b' self._verbose = verbose Loading @@ -50,30 +51,29 @@ class NseConnection: @staticmethod def _default_callback(delta_t, done): if not done: print('%.1fs waiting...\r' % delta_t, end='', flush=True) else: if done: print('**ready** ', flush=True) return print('%.3fs waiting...\n' % delta_t, end='', flush=True) def connect(self, connection=None, timeout=DEF_TIMEOUT): """connect to nse control program connection = "filename" -> AF_UNIX connection = "hostname" -> AF_INET (hostname, SOCKET_PORT) connection = ("hostname", port) """ connection = connection or ('localhost', self.SOCKET_PORT) self._busy = True connection = "hostname:port" """ connection = connection or 'localhost:%d' % self.SOCKET_PORT self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: if os.path.exists(connection): if os.path.exists(str(connection)): self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) else: # if not found assume it is a hostname connection = (connection, self.SOCKET_PORT) except TypeError: pass connection = connection.split(':') try: connection = (connection[0], int(connection[1])) except (ValueError, IndexError): connection = connection[0], self.SOCKET_PORT self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) t0 = time.time() self._sock.settimeout(3.0) self._sock.settimeout(self._sock_timeout) def wait_loop(method, arg): result = None while True: Loading @@ -81,12 +81,12 @@ class NseConnection: try: result = method(arg) break except socket.timeout: continue except socket.error as err: if err.errno != errno.ENOENT: raise err continue except TimeoutError: pass except OSError as err: self.log.error(err) raise finally: if (time.time()-t0)>timeout: raise RuntimeError("timeout in connect()") return result Loading @@ -94,24 +94,26 @@ class NseConnection: result = wait_loop(self._sock.connect, connection) # wait for receving 'ack' from the server result = wait_loop(self._sock.recv , self.CMD_LEN) # append ack result self._reply.append(decode(result, encoding='ascii')) self._sock.settimeout(timeout) # start receiving thread self.start() self._sock.send(encode(self._mode)) time.sleep(1.0) # FIXIT # self.send('say connection from "%s"' % self.id) self._thread = self.start() time.sleep(0.1) # FIXME self.send('say remote connection from "%s"' % self.id) self._connected = True def disconnect(self): "disconnect from the server" if self._sock: if self._thread is not None: self._thread_done.set() self._thread.join() self._sock.close() def start(self): "start receiving thread" t = threading.Thread(target=self._receive_thread) t = threading.Thread(target=self._receive_messages) t.daemon = True t.start() return t Loading @@ -120,7 +122,7 @@ class NseConnection: "send a command" command = " ".join([str(arg) for arg in args]) messg = command+'\n' self._busy = True #self._busy = True if self._verbose: print("---> " + messg, end='') self._sock.send(self._pid_s+encode(messg, encoding='ascii', errors='ignore')) Loading @@ -142,7 +144,7 @@ class NseConnection: dt = time.time() - t0 time.sleep(sleep_time) self._callback(dt, False) if not self._busy: if not self.is_busy: break if dt>timeout: raise RuntimeError("timeout in wait()") Loading @@ -162,7 +164,7 @@ class NseConnection: @property def is_busy(self): "return busy status" return self._busy return self._thread_busy.is_set() @property def wait_callback(self): Loading @@ -174,15 +176,15 @@ class NseConnection: "set wait callback" self._callback = callback def _receive_thread(self): "receive responsed in background" def _receive_messages(self): "receive responses in background" response = [] while True: while not self._thread_done.is_set(): try: msg = self._sock.recv(self.CMD_LEN) self._thread_busy.set() # msg = decode(msg, encoding='ascii', errors='replace') self._busy = True self.log(msg) self.log.info(msg) lines = msg.split('\n') for line in lines: if not line: Loading @@ -190,23 +192,17 @@ class NseConnection: if line.startswith("(%d-0)" % self._pid): response = [line,] elif line in self.READY_MSG: if response: self._reply.append(response) response = [] self._busy = False self._thread_busy.clear() elif response: response.append(line) except socket.error as e: self.log(str(e)) except TimeoutError: pass # ignore timeout error - wait for another one except UnicodeDecodeError as err: self.log.error(err) #'%s' % str(err)) except OSError as err: self.log.error(err) #'%s' % err) self._connected = False break except UnicodeDecodeError as e: self.log(str(e)) self._busy=False def log(self, msg): """log messages""" self._log.write(msg) self._log.flush() self._thread_busy.clear() Loading
.pylint.rc +2 −2 Original line number Diff line number Diff line Loading @@ -393,8 +393,8 @@ preferred-modules= [EXCEPTIONS] # Exceptions that will emit a warning when caught. overgeneral-exceptions=BaseException, Exception overgeneral-exceptions=builtins.BaseException, builtins.Exception [REFACTORING] Loading
misc/test_nsett.py +26 −16 Original line number Diff line number Diff line Loading @@ -3,28 +3,38 @@ import sys import time import pysen.ui.nsett as nsett def wait_callback(dt, done): if not done: print('%.1f waiting...\r' % dt, end='', flush=True) else: print('\n**ready** ', flush=True) from pysen.misc import setup_logger hostname = "localhost" quit = "no" if len(sys.argv)>1: hostname=sys.argv[1] ns = nsett.NseConnection(verbose=True, wait_callback=wait_callback) ns.connect(hostname) if len(sys.argv)>2: quit=sys.argv[2] #ns.send('testmode off') logger = setup_logger() ns.send('q_move 0.10', timeout=300) # takes ~200s on the first take with "real" mode time.sleep(5) ns.send('q_move 0.20', timeout=300) # taked ~10s on the second take def wait_callback(dt, done, cmd=""): if done: print('**ready** ', flush=True) return print('%.3fs waiting...\r' % dt, end='', flush=True) ns = nsett.NseConnection(verbose=True, wait_callback=wait_callback) try: ns.connect(hostname) except OSError as err: sys.exit(-1) ns.send('testmode on') ns.send('tofconf lambda 6.5e-10 detpos 27.3') ns.send('tau 20e-9') ns.send('q_move 0.50' ) ns.send('display physics') ;#print('-->',"\n".join(ns.pop())) ns.send('show physics') ;#print('-->',"\n".join(ns.pop())) ns.send('show tech' ) ;#print('-->',"\n".join(ns.pop())) if quit == "yes": ns.send('quit', timeout=None) print('done') ns.disconnect()
pysen/revision.py +2 −2 Original line number Diff line number Diff line Loading @@ -3,8 +3,8 @@ PySEN revision module """ import sys __version__ = "1.3" __release__ = "b3" __date__ = "Mar 16, 2023" __release__ = "b5" __date__ = "Mar 17, 2023" def version(full=False): "get pysen version number" Loading
pysen/ui/SimpleEchoSimulator.py +3 −5 Original line number Diff line number Diff line Loading @@ -29,9 +29,7 @@ def sqt(t, coh, tcoh, inc, tinc, beta=1): return coh*f_exp(t,tcoh,beta)-1/3*inc*f_exp(t,tinc,beta) class MainWindow(QMainWindow, Ui_MainWindow): """ Main for viewing and deleting available groups. """ """Main for viewing and deleting available groups.""" def __init__(self, parent=None): """init MainWindow""" super().__init__(parent) Loading Loading @@ -238,8 +236,8 @@ class MainWindow(QMainWindow, Ui_MainWindow): self.lines['dn'].set_data(dj/MICRO,dn) self.lines['ave'].set_data(dj/MICRO,ave) bot = min(np.amin(yecho), min(up,dn))*0.8 top = max(np.amax(yecho), max(up,dn))*1.1 bot = min(np.amin(yecho), up, dn)*0.8 top = max(np.amax(yecho), up, dn)*1.1 ax.set_ylim(bottom=bot, top=top) ysqt = sqt(xt, coh, tcoh, inc, tinc,beta)/norm Loading
pysen/ui/nsett.py +58 −62 Original line number Diff line number Diff line Loading @@ -5,10 +5,10 @@ Pythonic equivalent for nsetty C-program """ import os import socket import errno import time import struct import threading import logging from collections import deque from ..iostrings import encode, decode Loading @@ -26,22 +26,23 @@ class NseConnection: "ReceiveNewCmd(): Authorization timeout deactivated.") #SOCKET_FILE = 'stream.tmp' SOCKET_PORT = 1966 LOG_FILE = 'nsett.log' MAX_QUELEN = 16 # remember last 16 responses DEF_TIMEOUT = 30 MAX_QUELEN = 32 # remember last 16 responses DEF_TIMEOUT = 10 """NSE TTY connection""" def __init__(self, logfile=None, wait_callback=None, verbose=False): def __init__(self, wait_callback=None, verbose=False): self._sock = None self._sock_timeout = 3.0 # FIXME: hardcoded socket timeout self._pid = os.getpid() self._pid_s = struct.pack('I', self._pid) #pylint: disable=consider-using-with self._log = open(logfile or NseConnection.LOG_FILE, 'a', encoding="utf8") self.log = logging.getLogger() self._reply = deque(maxlen=NseConnection.MAX_QUELEN) self._connected = False self._busy = False self._hostname = socket.gethostname() self._callback = wait_callback or self._default_callback self._thread = None # receiving thread self._thread_done = threading.Event() # thread event (to stop) self._thread_busy = threading.Event() # thread is busy receving data self._mode = 'b' self._verbose = verbose Loading @@ -50,30 +51,29 @@ class NseConnection: @staticmethod def _default_callback(delta_t, done): if not done: print('%.1fs waiting...\r' % delta_t, end='', flush=True) else: if done: print('**ready** ', flush=True) return print('%.3fs waiting...\n' % delta_t, end='', flush=True) def connect(self, connection=None, timeout=DEF_TIMEOUT): """connect to nse control program connection = "filename" -> AF_UNIX connection = "hostname" -> AF_INET (hostname, SOCKET_PORT) connection = ("hostname", port) """ connection = connection or ('localhost', self.SOCKET_PORT) self._busy = True connection = "hostname:port" """ connection = connection or 'localhost:%d' % self.SOCKET_PORT self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: if os.path.exists(connection): if os.path.exists(str(connection)): self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) else: # if not found assume it is a hostname connection = (connection, self.SOCKET_PORT) except TypeError: pass connection = connection.split(':') try: connection = (connection[0], int(connection[1])) except (ValueError, IndexError): connection = connection[0], self.SOCKET_PORT self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) t0 = time.time() self._sock.settimeout(3.0) self._sock.settimeout(self._sock_timeout) def wait_loop(method, arg): result = None while True: Loading @@ -81,12 +81,12 @@ class NseConnection: try: result = method(arg) break except socket.timeout: continue except socket.error as err: if err.errno != errno.ENOENT: raise err continue except TimeoutError: pass except OSError as err: self.log.error(err) raise finally: if (time.time()-t0)>timeout: raise RuntimeError("timeout in connect()") return result Loading @@ -94,24 +94,26 @@ class NseConnection: result = wait_loop(self._sock.connect, connection) # wait for receving 'ack' from the server result = wait_loop(self._sock.recv , self.CMD_LEN) # append ack result self._reply.append(decode(result, encoding='ascii')) self._sock.settimeout(timeout) # start receiving thread self.start() self._sock.send(encode(self._mode)) time.sleep(1.0) # FIXIT # self.send('say connection from "%s"' % self.id) self._thread = self.start() time.sleep(0.1) # FIXME self.send('say remote connection from "%s"' % self.id) self._connected = True def disconnect(self): "disconnect from the server" if self._sock: if self._thread is not None: self._thread_done.set() self._thread.join() self._sock.close() def start(self): "start receiving thread" t = threading.Thread(target=self._receive_thread) t = threading.Thread(target=self._receive_messages) t.daemon = True t.start() return t Loading @@ -120,7 +122,7 @@ class NseConnection: "send a command" command = " ".join([str(arg) for arg in args]) messg = command+'\n' self._busy = True #self._busy = True if self._verbose: print("---> " + messg, end='') self._sock.send(self._pid_s+encode(messg, encoding='ascii', errors='ignore')) Loading @@ -142,7 +144,7 @@ class NseConnection: dt = time.time() - t0 time.sleep(sleep_time) self._callback(dt, False) if not self._busy: if not self.is_busy: break if dt>timeout: raise RuntimeError("timeout in wait()") Loading @@ -162,7 +164,7 @@ class NseConnection: @property def is_busy(self): "return busy status" return self._busy return self._thread_busy.is_set() @property def wait_callback(self): Loading @@ -174,15 +176,15 @@ class NseConnection: "set wait callback" self._callback = callback def _receive_thread(self): "receive responsed in background" def _receive_messages(self): "receive responses in background" response = [] while True: while not self._thread_done.is_set(): try: msg = self._sock.recv(self.CMD_LEN) self._thread_busy.set() # msg = decode(msg, encoding='ascii', errors='replace') self._busy = True self.log(msg) self.log.info(msg) lines = msg.split('\n') for line in lines: if not line: Loading @@ -190,23 +192,17 @@ class NseConnection: if line.startswith("(%d-0)" % self._pid): response = [line,] elif line in self.READY_MSG: if response: self._reply.append(response) response = [] self._busy = False self._thread_busy.clear() elif response: response.append(line) except socket.error as e: self.log(str(e)) except TimeoutError: pass # ignore timeout error - wait for another one except UnicodeDecodeError as err: self.log.error(err) #'%s' % str(err)) except OSError as err: self.log.error(err) #'%s' % err) self._connected = False break except UnicodeDecodeError as e: self.log(str(e)) self._busy=False def log(self, msg): """log messages""" self._log.write(msg) self._log.flush() self._thread_busy.clear()