...
 
Commits (56)
......@@ -18,8 +18,12 @@ style:
tests:
stage: tests
before_script:
- conda create --name testenv --channel http://bcu-ci.esrf.fr/stable python=2 --file requirements-conda.txt --file requirements-test-conda.txt
- conda create -q --yes --name testenv --channel http://bcu-ci.esrf.fr/stable python=3 --file requirements-conda.txt --file requirements-test-conda.txt
- source activate testenv
# Get louie from github for python 3 compatibility
- conda install -q --yes git
- pip install git+https://github.com/11craft/louie.git
# Install bliss and its pip-only dependencies
- pip install .
script:
- python setup.py test --addopts "--cov bliss --cov-report html --cov-report term"
......@@ -31,8 +35,8 @@ tests:
build_doc:
stage: build_doc
before_script:
- source activate tango2.7
- conda install --yes --channel http://bcu-ci.esrf.fr/stable --file requirements-conda.txt --file requirements-doc-conda.txt
- conda create -q --yes --name docenv --channel http://bcu-ci.esrf.fr/stable python=3 --file requirements-conda.txt --file requirements-doc-conda.txt
- source activate docenv
- pip install -r requirements-doc.txt
script:
- python setup.py build_sphinx
......@@ -44,7 +48,7 @@ build_doc:
build_user_doc:
stage: build_user_doc
before_script:
- conda install --yes --channel http://bcu-ci.esrf.fr/stable --file requirements-doc-conda.txt
- conda install -q --yes --channel http://bcu-ci.esrf.fr/stable --file requirements-doc-conda.txt
- pip install -r requirements-doc.txt
script:
- cd doc && mkdocs build
......
......@@ -17,17 +17,17 @@ replied_host = set()
try:
with gevent.Timeout(3., "END"):
while True:
msg,address = udp.recvfrom(8192)
host,port = msg.split('|')
replied_host.add((host,port))
msg, address = udp.recvfrom(8192)
host, port = msg.split("|")
replied_host.add((host, port))
except gevent.Timeout:
pass
if replied_host:
max_host_len = max([len(host) for host,port in replied_host])
max_host_len = max([len(host) for host, port in replied_host])
format = "{0: <%d} {1}" % max_host_len
print(format.format("HOST","PORT"))
print((format.format("HOST", "PORT")))
for host, port in sorted(replied_host):
print(format.format(host, port))
print((format.format(host, port)))
else:
print("No response!!!")
......@@ -22,13 +22,12 @@ import bliss
from bliss.shell.web import bliss_webserver
try:
arguments = docopt.docopt(__doc__)
port = int(arguments['--port'])
arguments = docopt.docopt(__doc__)
port = int(arguments["--port"])
except docopt.DocoptExit as e:
print e.message
print(e.message)
else:
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
bliss_webserver.serve_forever(port)
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
bliss_webserver.serve_forever(port)
......@@ -25,102 +25,120 @@ try:
except ImportError:
try:
from PyMca5.PyMcaIO import sps
except ImportError: # last chance
except ImportError: # last chance
from PyMca import sps
from bliss.data.node import DataNodeIterator,_get_or_create_node,is_zerod
from bliss.data.node import DataNodeIterator, _get_or_create_node, is_zerod
ARRAY_NAME = "SCAN_D"
class _MaxPointReach(Exception):
pass
class _MaxCounterReach(Exception):
pass
class _NewCounter(Exception):
pass
def copy_data(zerod,zerod_index,
session_name,max_nb_counter,max_nb_points):
def copy_data(zerod, zerod_index, session_name, max_nb_counter, max_nb_points):
data_channel = zerod
channel_name = zerod.name
previous_cnt_number = len(zerod_index)
channel_info = zerod_index.setdefault(channel_name,
{'from':0, 'index':len(zerod_index)})
channel_info = zerod_index.setdefault(
channel_name, {"from": 0, "index": len(zerod_index)}
)
if len(zerod_index) > max_nb_counter:
raise _MaxCounterReach()
elif previous_cnt_number != len(zerod_index):
raise _NewCounter()
from_index = channel_info.get('from')
data = data_channel.get(from_index,-1)
from_index = channel_info.get("from")
data = data_channel.get(from_index, -1)
nb_points = from_index + len(data)
if nb_points > max_nb_points:
raise _MaxPointReach()
channel_info['from'] = nb_points
channel_info["from"] = nb_points
if len(data):
sps_index = channel_info['index']
sps_data = sps.getdata(session_name,ARRAY_NAME)
sps_data.T[sps_index][from_index:from_index+len(data)] = data
sps.putdata(session_name,ARRAY_NAME,sps_data)
sps_index = channel_info["index"]
sps_data = sps.getdata(session_name, ARRAY_NAME)
sps_data.T[sps_index][from_index : from_index + len(data)] = data
sps.putdata(session_name, ARRAY_NAME, sps_data)
min_index = nb_points
for channel_name,channel_info in zerod_index.iteritems():
point_nb = channel_info.get('from')
for channel_name, channel_info in zerod_index.items():
point_nb = channel_info.get("from")
if point_nb < min_index:
min_index = point_nb
sps.putinfo(session_name,ARRAY_NAME,json.dumps((min_index,"running")))
sps.putinfo(session_name, ARRAY_NAME, json.dumps((min_index, "running")))
def new_scanno(last={"scanno": 0}):
last["scanno"]+=1
last["scanno"] += 1
return last["scanno"]
def watch_data(scan_node,session_name):
npoints = max(scan_node.info.get("npoints"),4096)
def watch_data(scan_node, session_name):
npoints = max(scan_node.info.get("npoints"), 4096)
title = scan_node.info.get("title") or "unknown scan"
nbcounters = 64
while True:
try:
scan_data_iterator = DataNodeIterator(scan_node)
pubsub = scan_data_iterator.children_event_register()
sps.create(session_name,ARRAY_NAME,npoints,nbcounters)
sps.create(session_name, ARRAY_NAME, npoints, nbcounters)
zerod_index = OrderedDict()
for channel in scan_data_iterator.walk(filter='channel',wait=False):
for channel in scan_data_iterator.walk(filter="channel", wait=False):
if is_zerod(channel):
channel_name = channel.name
zerod_index.setdefault(channel_name,{'from':0, 'index':len(zerod_index)})
copy_data(channel,zerod_index,
session_name,nbcounters,npoints)
allcountersdict = dict([(i,"") for i in range(nbcounters)])
allcountersdict.update(dict(((i,name) for i,name in enumerate(zerod_index))))
sps.putmetadata(session_name,ARRAY_NAME,
json.dumps((allcountersdict,
{"npts":npoints,
"allmotorm": "",
"scanno" : new_scanno(),
"datafile" : "bliss",
"spec": session_name,
"columnnames": zerod_index.keys()+[""]*(nbcounters-len(zerod_index.keys())),
"columns": len(zerod_index.keys()),
"selectedcounters" : ';'.join(zerod_index.keys())},
{})))
for event_type, zerod in scan_data_iterator.wait_for_event(pubsub, filter='channel'):
zerod_index.setdefault(
channel_name, {"from": 0, "index": len(zerod_index)}
)
copy_data(channel, zerod_index, session_name, nbcounters, npoints)
allcountersdict = dict([(i, "") for i in range(nbcounters)])
allcountersdict.update(
dict(((i, name) for i, name in enumerate(zerod_index)))
)
sps.putmetadata(
session_name,
ARRAY_NAME,
json.dumps(
(
allcountersdict,
{
"npts": npoints,
"allmotorm": "",
"scanno": new_scanno(),
"datafile": "bliss",
"spec": session_name,
"columnnames": list(zerod_index.keys())
+ [""] * (nbcounters - len(list(zerod_index.keys()))),
"columns": len(list(zerod_index.keys())),
"selectedcounters": ";".join(list(zerod_index.keys())),
},
{},
)
),
)
for event_type, zerod in scan_data_iterator.wait_for_event(
pubsub, filter="channel"
):
if not is_zerod(zerod):
continue
if event_type is scan_data_iterator.NEW_CHILD_EVENT:
copy_data(zerod, zerod_index,
session_name, nbcounters, npoints)
copy_data(zerod, zerod_index, session_name, nbcounters, npoints)
elif event_type is scan_data_iterator.NEW_DATA_IN_CHANNEL_EVENT:
copy_data(zerod, zerod_index,
session_name, nbcounters, npoints)
copy_data(zerod, zerod_index, session_name, nbcounters, npoints)
except _MaxCounterReach:
nbcounters *= 2
except _MaxPointReach:
......@@ -130,39 +148,45 @@ def watch_data(scan_node,session_name):
npoints *= 2
except _NewCounter:
pass
def watch_session(session_name):
session_node = _get_or_create_node(session_name,node_type='session')
session_node = _get_or_create_node(session_name, node_type="session")
if session_node is not None:
data_iterator = DataNodeIterator(session_node)
pubsub = data_iterator.children_event_register()
last_scan_node = None
for last_scan_node in data_iterator.walk(filter='scan',wait=False):
for last_scan_node in data_iterator.walk(filter="scan", wait=False):
pass
watch_data_task = None
if last_scan_node is not None:
watch_data_task = gevent.spawn(watch_data,last_scan_node,session_name)
for event_type,scan_node in data_iterator.wait_for_event(pubsub,filter='scan'):
watch_data_task = gevent.spawn(watch_data, last_scan_node, session_name)
for event_type, scan_node in data_iterator.wait_for_event(
pubsub, filter="scan"
):
if event_type != data_iterator.NEW_CHILD_EVENT:
continue
if watch_data_task:
watch_data_task.kill()
watch_data_task = gevent.spawn(watch_data,scan_node,session_name)
watch_data_task = gevent.spawn(watch_data, scan_node, session_name)
def main():
try:
# Parse arguments, use file docstring as a parameter definition
arguments = docopt.docopt(__doc__)
sessions_name = arguments['<name>']
sessions_name = arguments["<name>"]
except docopt.DocoptExit as e:
print e.message
print(e.message)
else:
tasks = list()
for session in sessions_name:
tasks.append(gevent.spawn(watch_session,session))
tasks.append(gevent.spawn(watch_session, session))
try:
gevent.joinall(tasks)
except KeyboardInterrupt:
pass
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()
......@@ -10,64 +10,69 @@ import argparse
import MySQLdb
from bliss.config import static
def main(host = None,user = None,passwd = None):
def main(host=None, user=None, passwd=None):
config = static.get_config()
conn = MySQLdb.connect(host=host,user=user,passwd=passwd,db='tango')
conn = MySQLdb.connect(host=host, user=user, passwd=passwd, db="tango")
cursor = conn.cursor()
cursor.execute('select name,server,class from device where ior like "ior:%"')
server2nodes = {}
device2nodes = {}
for name,server,klass in cursor:
if name.startswith('dserver'): continue
for name, server, klass in cursor:
if name.startswith("dserver"):
continue
node = server2nodes.get(server)
if node is None:
node = static.Node(config,filename = 'tango/%s.yml' % server.replace('/','_'))
exe_name,personal = server.split('/')
node['server'] = exe_name
node['personal_name'] = personal
node = static.Node(
config, filename="tango/%s.yml" % server.replace("/", "_")
)
exe_name, personal = server.split("/")
node["server"] = exe_name
node["personal_name"] = personal
server2nodes[server] = node
device_node = static.Node(config,parent = node)
device_node['tango_name'] = name
device_node['class'] = klass
device_node = static.Node(config, parent=node)
device_node["tango_name"] = name
device_node["class"] = klass
device2nodes[name] = device_node
device_list = node.get('device')
device_list = node.get("device")
if device_list is None:
node['device'] = [device_node]
node["device"] = [device_node]
else:
device_list.append(device_node)
#properties
# properties
cursor = conn.cursor()
cursor.execute('select device,name,value from property_device order by device,count')
for device,name,value in cursor :
cursor.execute(
"select device,name,value from property_device order by device,count"
)
for device, name, value in cursor:
device_node = device2nodes.get(device)
if device_node is None:
continue
properties = device_node.get('properties')
properties = device_node.get("properties")
if properties is None:
properties = static.Node(config,parent = device_node)
device_node['properties'] = properties
properties = static.Node(config, parent=device_node)
device_node["properties"] = properties
values = properties.get(name)
if values is None:
properties[name] = value
else:
if isinstance(values,list):
if isinstance(values, list):
values.append(value)
else:
properties[name] = [values,value]
for node in server2nodes.values():
properties[name] = [values, value]
for node in list(server2nodes.values()):
node.save()
if __name__ == '__main__':
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--host",dest="host",help="host where mysql is running")
parser.add_argument("--user",dest="user",
help="mysql user")
parser.add_argument("--passwd",dest="passwd",
help="mysql password")
parser.add_argument("--host", dest="host", help="host where mysql is running")
parser.add_argument("--user", dest="user", help="mysql user")
parser.add_argument("--passwd", dest="passwd", help="mysql password")
options = parser.parse_args()
main(host=options.host,user=options.user,passwd=options.passwd)
main(host=options.host, user=options.user, passwd=options.passwd)
......@@ -104,10 +104,10 @@ class Exporter(ExporterClient.ExporterClient):
if "\x1f" in value:
value = self.parseArray(value)
try:
value = map(int, value)
value = list(map(int, value))
except:
try:
value = map(float, value)
value = list(map(float, value))
except:
pass
else:
......@@ -155,7 +155,7 @@ class ExporterChannel:
def update(self, value=None):
if value is None:
value = self.getValue()
if type(value) == types.TupleType:
if type(value) == tuple:
value = list(value)
self.value = value
......
......@@ -7,7 +7,7 @@
Copyright 2009 by European Molecular Biology Laboratory - Grenoble
"""
from StandardClient import *
from .StandardClient import *
CMD_SYNC_CALL = "EXEC"
CMD_ASNC_CALL = "ASNC"
......@@ -32,7 +32,7 @@ class ExporterClient(StandardClient):
try:
evtstr = msg[4:]
tokens = evtstr.split(PARAMETER_SEPARATOR)
self.onEvent(tokens[0], tokens[1], long(tokens[2]))
self.onEvent(tokens[0], tokens[1], int(tokens[2]))
except:
# print "Error processing event: " + str(sys.exc_info()[1])
pass
......@@ -82,7 +82,7 @@ class ExporterClient(StandardClient):
def __processReturn(self, ret):
if ret[:4] == RET_ERR:
raise Exception, ret[4:]
raise Exception(ret[4:])
elif ret == RET_NULL:
return None
elif ret[:4] == RET_OK:
......
This diff is collapsed.
......@@ -9,7 +9,7 @@ import sys
import time
import string
import threading
from ExporterClient import *
from .ExporterClient import *
SERVER_ADDRESS = "localhost"
SERVER_PORT = 9001
......@@ -243,7 +243,7 @@ if __name__ == "__main__":
class Microdiff(MDEvents):
def onReceivedEvent(self, name, value, timestamp):
print " Event: " + name + " = " + str(value)
print(" Event: " + name + " = " + str(value))
md = Microdiff(SERVER_ADDRESS, SERVER_PORT, PROTOCOL.STREAM, TIMEOUT, RETRIES)
md.start()
......@@ -251,6 +251,6 @@ if __name__ == "__main__":
while True:
time.sleep(1.0)
if not md.isConnected():
print "Not Connected"
print("Not Connected")
md.stop()
......@@ -108,15 +108,15 @@ class StandardClient:
try:
self.__sock__.sendto(msg, (self.server_ip, self.server_port))
except:
raise SocketError, "Socket error:" + str(sys.exc_info()[1])
raise SocketError("Socket error:" + str(sys.exc_info()[1]))
received = False
while received == False:
try:
ret = self.__sock__.recv(4096)
except socket.timeout:
raise TimeoutError, "Timeout error:" + str(sys.exc_info()[1])
raise TimeoutError("Timeout error:" + str(sys.exc_info()[1]))
except:
raise SocketError, "Socket error:" + str(sys.exc_info()[1])
raise SocketError("Socket error:" + str(sys.exc_info()[1]))
if ret[0:5] == msg_number:
received = True
ret = ret[5:]
......@@ -230,7 +230,7 @@ class StandardClient:
with gevent.Timeout(self.timeout, TimeoutError):
while self.received_msg is None:
if not self.error is None:
raise SocketError, "Socket error:" + str(self.error)
raise SocketError("Socket error:" + str(self.error))
self.msg_received_event.wait()
return self.received_msg
......@@ -254,7 +254,9 @@ class StandardClient:
@protect_from_kill
def send(self, cmd):
if self.protocol == PROTOCOL.DATAGRAM:
raise ProtocolError, "Protocol error: send command not support in datagram clients"
raise ProtocolError(
"Protocol error: send command not support in datagram clients"
)
else:
return self.__sendStream__(cmd)
......
......@@ -9,4 +9,4 @@
interface specific classes)
"""
from _gpib import *
from ._gpib import *
......@@ -89,7 +89,7 @@ class Enet(EnetSocket):
def __init__(self, cnt, **keys):
EnetSocket.__init__(self, None) # Don't use the socket connection
url = keys.pop("url")
url_parse = re.compile("^(enet://)?([^:/]+):?([0-9]*)$")
url_parse = re.compile(r"^(enet://)?([^:/]+):?([0-9]*)$")
match = url_parse.match(url)
if match is None:
raise EnetError("Enet: url is not valid (%s)" % url)
......@@ -129,7 +129,7 @@ class Prologix:
self._logger = logging.getLogger(str(self))
self._debug = self._logger.debug
url = keys.pop("url")
url_parse = re.compile("^(prologix://)?([^:/]+):?([0-9]*)$")
url_parse = re.compile(r"^(prologix://)?([^:/]+):?([0-9]*)$")
match = url_parse.match(url)
if match is None:
raise PrologixError("Inet: url is not valid (%s)" % url)
......@@ -272,7 +272,7 @@ class LocalGpibError(GpibError):
class LocalGpib(object):
URL_RE = re.compile("^(local://)?([0-9]{1,2})$")
URL_RE = re.compile(r"^(local://)?([0-9]{1,2})$")
def __init__(self, cnt, **keys):
url = keys.pop("url")
......@@ -347,7 +347,7 @@ class Gpib:
interface = Gpib(url="enet://gpibid00a.esrf.fr", pad=15)
"""
ENET, TANGO, TANGO_DEVICE_SERVER, PROLOGIX, LOCAL = range(5)
ENET, TANGO, TANGO_DEVICE_SERVER, PROLOGIX, LOCAL = list(range(5))
READ_BLOCK_SIZE = 64 * 1024
def __init__(self, url=None, pad=0, sad=0, timeout=1., tmo=13, eot=1, eos="\n"):
......
......@@ -45,9 +45,9 @@ def _dbg(f, name=None):
name = f.__name__
def wrap(self, *a, **k):
print "DBG: %s: enter: %s %s" % (name, ` a `, ` k `),
print("DBG: %s: enter: %s %s" % (name, repr(a), repr(k)), end=" ")
r = f(self, *a, **k)
print "exit: %s" % ` r `
print("exit: %s" % repr(r))
return r
wrap._dummy = True
......@@ -59,7 +59,7 @@ def _not_impl(name):
if "ignore_not_impl" in debug:
return None
else:
raise NotImplementedError, "%s not implemented", name
raise NotImplementedError("%s not implemented").with_traceback(name)
return _dbg(wrap, name)
......@@ -99,8 +99,8 @@ class EnetSocket(object):
if "dummy_io" in debug:
_open = lambda self: None
_send = lambda self, s: sys.stderr.write("DBG: > %s" % (` s `))
_recv = lambda self, len: raw_input("DBG: < #%s:" % (len))[:len]
_send = lambda self, s: sys.stderr.write("DBG: > %s" % (repr(s)))
_recv = lambda self, len: input("DBG: < #%s:" % (len))[:len]
_close = lambda self: None
if "io" in debug:
......@@ -395,7 +395,7 @@ class EnetLib(object):
if name[:3] == "dev":
pad = int(name[3:])
else:
raise ValueError, "configuration not yet implemented. use devX"
raise ValueError("configuration not yet implemented. use devX")
return self.ibdev(pad)
def ibdev(self, *a, **ka):
......@@ -430,16 +430,16 @@ if __name__ == "__main__":
nienet_host = "qo-hpf-gpib1.ethz.ch"
l = EnetLib(nienet_host)
ud = l.ibdev(pad=13)
print "ibrsp", l.ibrsp(ud)
print "iblines", l.iblines(ud)
print "ibtrg", l.ibtrg(ud)
print "ibask", l.ibask(ud, 1)
print "ibln 13", l.ibln(ud, 13)
print "ibln 11", l.ibln(ud, 11)
print "ibwrt", l.ibwrt(ud, "ID?;")
print "ibrd", l.ibrd(ud, 10)
print "ibwrt", l.ibwrt(ud, "SET?;")
print "ibrd", ` l.ibrd(ud, 640) `
print "ibwrt", l.ibwrt(ud, "DSTB;")
print "ibrd", ` l.ibrd(ud, 4096) `
print "ibbna", l.ibbna(ud)
print("ibrsp", l.ibrsp(ud))
print("iblines", l.iblines(ud))
print("ibtrg", l.ibtrg(ud))
print("ibask", l.ibask(ud, 1))
print("ibln 13", l.ibln(ud, 13))
print("ibln 11", l.ibln(ud, 11))
print("ibwrt", l.ibwrt(ud, "ID?;"))
print("ibrd", l.ibrd(ud, 10))
print("ibwrt", l.ibwrt(ud, "SET?;"))
print("ibrd", repr(l.ibrd(ud, 640)))
print("ibwrt", l.ibwrt(ud, "DSTB;"))
print("ibrd", repr(l.ibrd(ud, 4096)))
print("ibbna", l.ibbna(ud))
......@@ -530,7 +530,7 @@ class ModbusTcp:
modbus._connected = False
modbus._fd = None
# inform all pending requests that the socket closed
for trans in modbus._transaction.values():
for trans in list(modbus._transaction.values()):
trans.put(socket.error(errno.EPIPE, "Broken pipe"))
except ReferenceError:
pass
......@@ -158,7 +158,7 @@ class _ServerObject(object):
def __dir__(self):
result = ["zerorpc_call__"]
for name, info in self._metadata["members"].items():
for name, info in list(self._metadata["members"].items()):
if "method" in info["type"]:
result.append(name)
return result
......@@ -332,7 +332,7 @@ def Client(address, **kwargs):
stream = metadata.get("stream", False)
members = dict(_client=client)
for name, info in metadata["members"].items():
for name, info in list(metadata["members"].items()):
if name.startswith("__") and name[2:-2] in SPECIAL_METHODS:
continue
name, mtype, doc = info["name"], info["type"], info["doc"]
......
......@@ -33,7 +33,6 @@ Example::
"""
from __future__ import absolute_import
import re
import inspect
......@@ -47,17 +46,17 @@ from .exceptions import CommunicationError, CommunicationTimeout
def decode_IDN(s):
manuf, model, serial, version = map(str.strip, s.split(","))
manuf, model, serial, version = list(map(str.strip, s.split(",")))
return dict(manufacturer=manuf, model=model, serial=serial, version=version)
def __decode_Err(s):
code, desc = map(str.strip, s.split(",", 1))
code, desc = list(map(str.strip, s.split(",", 1)))
return dict(code=int(code), desc=desc[1:-1])
def __decode_ErrArray(s):
msgs = map(str.strip, s.split(","))
msgs = list(map(str.strip, s.split(",")))
result = []
for i in range(0, len(msgs), 2):
code, desc = int(msgs[i]), msgs[i + 1][1:-1]
......@@ -285,7 +284,7 @@ class Commands(object):
try:
return self._command_cache[cmd_name_u]
except KeyError:
for cmd_expr, cmd_info in self.command_expressions.items():
for cmd_expr, cmd_info in list(self.command_expressions.items()):
reg_expr = cmd_info["re"]
if reg_expr.match(cmd_name):
self._command_cache[cmd_name.upper()] = cmd_expr
......@@ -303,7 +302,7 @@ class Commands(object):
self.command_expressions.update(commands.command_expressions)
self._command_cache.update(commands._command_cache)
elif isinstance(commands, dict):
for cmd_expr, cmd in commands.items():
for cmd_expr, cmd in list(commands.items()):
self[cmd_expr] = cmd
else:
for cmd_expr, cmd in commands:
......@@ -779,7 +778,7 @@ def main(argv=None):
)
add(
"--parity",
choices=serial.PARITY_NAMES.keys(),
choices=list(serial.PARITY_NAMES.keys()),
default=serial.PARITY_NONE,
help="parity type",
)
......
......@@ -5,7 +5,6 @@
# Copyright (c) 2016 Beamline Control Unit, ESRF
# Distributed under the GNU LGPLv3. See LICENSE for more info.
from __future__ import absolute_import
__all__ = ["LocalSerial", "RFC2217", "SER2NET", "TangoSerial", "Serial"]
......@@ -28,7 +27,7 @@ except ImportError:
pass
else:
# import all rfc2217 protol keys in this module
key_match = re.compile("^[A-Z_]+$")
key_match = re.compile(r"^[A-Z_]+$")
pro_keys_dict = dict(
[(x, rfc2217.__dict__[x]) for x in dir(rfc2217) if key_match.match(x)]
)
......@@ -75,7 +74,7 @@ class _BaseSerial:
self._cnt = weakref.ref(cnt)
self._port = port
self._data = ""
self._data = b""
self._event = event.Event()
self._rx_filter = None
self._rpipe, self._wpipe = os.pipe()
......@@ -90,7 +89,7 @@ class _BaseSerial:
return gevent.Timeout(timeout, SerialTimeout(timeout_errmsg))
def _close(self):
os.write(self._wpipe, "|")
os.write(self._wpipe, b"|")
if self._raw_read_task:
self._raw_read_task.join()
self._raw_read_task = None
......@@ -173,7 +172,7 @@ class _BaseSerial:
self._data = self._data[maxsize:]
else:
msg = self._data
self._data = ""
self._data = b""
return msg
@staticmethod
......@@ -214,7 +213,7 @@ class LocalSerial(_BaseSerial):
def flushInput(self):
self.__serial.flushInput()
self._data = ""
self._data = b""
def close(self):
self._close()
......@@ -232,19 +231,19 @@ class RFC2217Timeout(SerialTimeout):
class RFC2217(_BaseSerial):
class TelnetCmd:
def __init__(self):
self.data = ""
self.data = b""
def telnetSendOption(self, action, option):
self.data += "".join([IAC, action, option])
self.data += b"".join([IAC, action, option])
class TelnetSubNego:
def __init__(self):
self.data = ""
self.data = b""
self.logger = None
def rfc2217SendSubnegotiation(self, option, value):
value = value.replace(IAC, IAC_DOUBLED)
self.data += "".join(
self.data += b"".join(
[IAC, SB, COM_PORT_OPTION, option] + list(value) + [IAC, SE]
)
......@@ -278,7 +277,7 @@ class RFC2217(_BaseSerial):
# RFC 2217 flow control between server and client
self._remote_suspend_flow = False
port_parse = re.compile("^(rfc2217://)?([^:/]+?):([0-9]+)$")
port_parse = re.compile(r"^(rfc2217://)?([^:/]+?):([0-9]+)$")
match = port_parse.match(port)
if match is None:
raise RFC2217Error("port is not a valid url (%s)" % port)
......@@ -391,8 +390,8 @@ class RFC2217(_BaseSerial):
self.rfc2217_options["control"].set(SET_CONTROL_USE_NO_FLOW_CONTROL)
self._socket.send(telnet_sub_cmd.data)
telnet_sub_cmd.data = ""
items = self.rfc2217_port_settings.values()
telnet_sub_cmd.data = b""
items = list(self.rfc2217_port_settings.values())
while 1:
self._parse_nego(telnet_cmd)
if sum(o.active for o in items) == len(items):
......@@ -418,20 +417,20 @@ class RFC2217(_BaseSerial):
purge = self.rfc2217_options["purge"]
telnet_sub_cmd = purge.connection
purge.set(PURGE_RECEIVE_BUFFER)
self._data = ""
self._data = b""
self._rx_filter = None
self._socket.send(telnet_sub_cmd.data)
telnet_sub_cmd.data = ""
telnet_sub_cmd.data = b""
while not purge.isReady():
self._parse_nego(telnet_cmd)
self._rx_filter = self._rfc2217_filter
self._data = ""
self._data = b""
def _rfc2217_filter(self, data):
if data[-1] == IAC and data[-2] != IAC:
self._pending_data = data
return ""
return b""
if self._pending_data:
data = self._pending_data + data
......@@ -485,7 +484,7 @@ class RFC2217(_BaseSerial):
elif suboption == FLOWCONTROL_RESUME:
self._remote_suspend_flow = False
else:
for item in self.rfc2217_options.values():
for item in list(self.rfc2217_options.values()):
if item.ack_option == suboption:
item.checkAnswer(value)
break
......@@ -495,7 +494,7 @@ class RFC2217(_BaseSerial):
if iac_pos == -1: # no more negotiation rx
if telnet_cmd.data:
self._socket.send(telnet_cmd.data)
telnet_cmd.data = ""
telnet_cmd.data = b""
break
def close(self):
......@@ -510,7 +509,7 @@ class SER2NETError(SerialError):
class SER2NET(RFC2217):
def __init__(self, cnt, **keys):
port = keys.pop("port")
port_parse = re.compile("^(ser2net://)?([^:/]+?):([0-9]+)(.+)$")
port_parse = re.compile(r"^(ser2net://)?([^:/]+?):([0-9]+)(.+)$")
match = port_parse.match(port)
if match is None:
raise SER2NETError("port is not a valid url (%s)" % port)
......@@ -519,7 +518,7 @@ class SER2NET(RFC2217):
rx = comm.write_readline(msg)
msg_pos = rx.find(msg)
rx = rx[msg_pos + len(msg) :]
port_parse = re.compile("^([0-9]+).+?%s" % match.group(4))
port_parse = re.compile(r"^([0-9]+).+?%s" % match.group(4))
rfc2217_port = None
for line in rx.split("\r\n"):
g = port_parse.match(line)
......@@ -603,7 +602,7 @@ class TangoSerial(_BaseSerial):
get_object_proxy(device).set_timeout_millis(int(timeout * 1000))
args = []
kwargs["eol"] = cnt._eol
for arg, (key, encode) in self.PAR_MAP.items():
for arg, (key, encode) in list(self.PAR_MAP.items()):
args.append(arg)
args.append(encode(self, kwargs[key]))
device.DevSerSetParameter(args)
......@@ -620,20 +619,20 @@ class TangoSerial(_BaseSerial):
self._device.DevSerSetNewline(eol_encode(self, eol))
self._last_eol = eol
buff = ""
buff = b""
while True:
line = self._device.DevSerReadLine() or ""
if line == "":
return ""
line = self._device.DevSerReadLine() or b""
if line == b"":
return b""
buff += line
if buff[-lg:] == eol:
return buff[:-lg]
def _raw_read(self, maxsize):
if maxsize:
return self._device.DevSerReadNChar(maxsize) or ""
return self._device.DevSerReadNChar(maxsize) or b""
else:
return self._device.DevSerReadRaw() or ""
return self._device.DevSerReadRaw() or b""
_read = _raw_read
......@@ -645,7 +644,7 @@ class TangoSerial(_BaseSerial):
class Serial:
LOCAL, RFC2217, SER2NET, TANGO = range(4)
LOCAL, RFC2217, SER2NET, TANGO = list(range(4))
def __init__(
self,
......@@ -660,7 +659,7 @@ class Serial:
writeTimeout=None,
dsrdtr=False,
interCharTimeout=None,
eol="\n",
eol=b"\n",
):
self._serial_kwargs = {
......
......@@ -117,7 +117,7 @@ class SpecChannel:
def update(self, channelValue, deleted=False, force=False):
"""Update channel's value and emit the 'valueChanged' signal."""
if isinstance(channelValue, types.DictType) and self.access1 is not None:
if isinstance(channelValue, dict) and self.access1 is not None:
if self.access1 in channelValue:
if deleted:
event.send(self, "valueChanged", (None, self.name))
......@@ -128,7 +128,7 @@ class SpecChannel:
or self.value is None
or self.value != channelValue[self.access1]
):
if isinstance(channelValue[self.access1], types.DictType):
if isinstance(channelValue[self.access1], dict):
self.value = channelValue[self.access1].copy()
else:
self.value = self._coerce(channelValue[self.access1])
......@@ -152,13 +152,11 @@ class SpecChannel:
)
return
if isinstance(self.value, types.DictType) and isinstance(
channelValue, types.DictType
):
if isinstance(self.value, dict) and isinstance(channelValue, dict):
# update dictionary
if deleted:
for key, val in channelValue.iteritems():
if isinstance(val, types.DictType):
for key, val in channelValue.items():
if isinstance(val, dict):
for k in val:
try:
del self.value[key][k]
......@@ -172,8 +170,8 @@ class SpecChannel:
except KeyError:
pass
else:
for k1, v1 in channelValue.iteritems():
if isinstance(v1, types.DictType):
for k1, v1 in channelValue.items():
if isinstance(v1, dict):
try:
self.value[k1].update(v1)
except KeyError:
......@@ -182,9 +180,7 @@ class SpecChannel:
self.value[k1] = {None: self.value[k1]}
self.value[k1].update(v1)
else:
if k1 in self.value and isinstance(
self.value[k1], types.DictType
):
if k1 in self.value and isinstance(self.value[k1], dict):
self.value[k1][None] = v1
else:
self.value[k1] = v1
......
......@@ -36,7 +36,7 @@ class wrap_errors(object):
func = self.func
try:
return func(*args, **kwargs)
except Exception, e:
except Exception as e:
return SpecClientError(e)
def __str__(self):
......@@ -69,7 +69,7 @@ class BaseSpecCommand:
self.setCommand(command)
if connection is not None:
if type(connection) in (types.UnicodeType, types.StringType):
if type(connection) in (str, bytes):
#
# connection is given in the 'host:port' form
#
......@@ -122,7 +122,7 @@ class BaseSpecCommand:
# convert args list to string args list
# it is much more convenient using .call('psvo', 12) than .call('psvo', '12')
# a possible problem will be seen in Spec
args = map(repr, args)
args = list(map(repr, args))
if func:
# macro function
......