Commit 899d172f authored by Pavel Vainerman's avatar Pavel Vainerman

(python): рефкторинг

parent 2de094bf
......@@ -16,7 +16,7 @@
Name: libuniset2
Version: 2.6
Release: alt9
Release: alt10
Summary: UniSet - library for building distributed industrial control systems
License: LGPL
......@@ -505,11 +505,14 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
%exclude %_pkgconfigdir/libUniSet2.pc
# history of current unpublished changes
# add tests for REST API (with RPC)
# python: refactoring UInterface (add UInterfaceModbus and UInterfaceUniSet)
# refactoring TCPCheck (use future)
%changelog
* Mon Jan 09 2017 Pavel Vainerman <pv@altlinux.ru> 2.6-alt10
- add tests for REST API (with RPC)
- python: refactoring UInterface (add UInterfaceModbus and UInterfaceUniSet)
- refactoring TCPCheck (use future)
- minor refactoring and fixes
* Fri Dec 16 2016 Pavel Vainerman <pv@altlinux.ru> 2.6-alt9
- UObject: added attempts to activate the object
......
......@@ -5,8 +5,9 @@ from pyUConnector import *
import time
import sys
def is_id( str_id ):
if isinstance(str_id,int) or isinstance(str_id,long):
def is_id(str_id):
if isinstance(str_id, int) or isinstance(str_id, long):
return True
if str_id.strip().isdigit():
......@@ -14,19 +15,19 @@ def is_id( str_id ):
return False
def to_int(s):
def to_int(s):
if s == None or s == "":
return 0
if isinstance(s,int) or isinstance(s,long):
if isinstance(s, int) or isinstance(s, long):
return s
if isinstance(s,float):
if isinstance(s, float):
return int(s)
if len(s)>2 and s[0] == '0' and s[1] == 'x':
return int(s,16)
if len(s) > 2 and s[0] == '0' and s[1] == 'x':
return int(s, 16)
if s.upper() == "TRUE":
return 1
......@@ -36,40 +37,43 @@ def to_int(s):
return int(s.strip())
def to_str(s_val):
def to_str(s_val):
if s_val == None:
return ""
return str(s_val)
def bool2str( state ):
def bool2str(state):
if state:
return "1"
return "0"
def get_sinfo(raw, sep='@'):
raw = to_str(raw)
v = raw.strip().split(sep)
if len(v) > 1:
return [v[0],v[1]]
return [v[0],""]
return [v[0], v[1]]
return [v[0], ""]
# Функция требует инициализированного UConnector
# (т.е. загруженного configure.xml)
def to_sid(str_id, ui):
if str_id == None or str_id == "":
return [DefaultID,DefaultID,""]
return [DefaultID, DefaultID, ""]
if is_id(str_id):
return [int(str_id),DefaultID,ui.getShortName(int(str_id))]
return [int(str_id), DefaultID, ui.getShortName(int(str_id))]
s = get_sinfo(str_id)
s_id = s[0]
s_node = s[1]
if s_id == "":
return [DefaultID,DefaultID,"?@?"]
return [DefaultID, DefaultID, "?@?"]
s_name = ""
if is_id(s_id):
......@@ -80,7 +84,7 @@ def to_sid(str_id, ui):
s_id = ui.getSensorID(s_id)
if s_node == "":
return [s_id,DefaultID,s_name]
return [s_id, DefaultID, s_name]
n_name = ""
if is_id(s_node):
......@@ -90,11 +94,11 @@ def to_sid(str_id, ui):
n_name = s_node
s_node = ui.getNodeID(s_node)
return [s_id,s_node,str(s_name+"@"+n_name)]
return [s_id, s_node, str(s_name + "@" + n_name)]
# Получение списка пар [id@node,int(val)] из строки "id1@node1=val1,id2=val2,.."
def get_int_list(raw_str,sep='='):
# Получение списка пар [id@node,int(val)] из строки "id1@node1=val1,id2=val2,.."
def get_int_list(raw_str, sep='='):
if raw_str == None or raw_str == "":
return []
......@@ -103,25 +107,26 @@ def get_int_list(raw_str,sep='='):
for s in l:
v = s.split(sep)
if len(v) > 1:
slist.append([v[0],to_int(v[1])])
slist.append([v[0], to_int(v[1])])
else:
print "(get_list:WARNING): (v=x) undefined value for " + str(s)
slist.append([v[0],0])
slist.append([v[0], 0])
return slist
def list_to_str(lst,sep='='):
def list_to_str(lst, sep='='):
res = ""
for v in lst:
if res != "":
res += ",%s=%s"%(v[0],v[1])
res += ",%s=%s" % (v[0], v[1])
else:
res += "%s=%s"%(v[0],v[1])
res += "%s=%s" % (v[0], v[1])
return res
# Получение списка пар [sX,kX] из строки "s1=k1,s2=k2,.."
def get_str_list(raw_str,sep='='):
# Получение списка пар [sX,kX] из строки "s1=k1,s2=k2,.."
def get_str_list(raw_str, sep='='):
if raw_str == None or raw_str == "":
return []
......@@ -130,15 +135,15 @@ def get_str_list(raw_str,sep='='):
for s in l:
v = s.split("=")
if len(v) > 1:
slist.append([v[0],v[1]])
slist.append([v[0], v[1]])
else:
print "(get_str_list:WARNING): (v=x) undefined value for " + str(s)
slist.append([v[0],""])
slist.append([v[0], ""])
return slist
# Получение списка пар [key,val] из строки "key1:val1,key2:val2,.."
def get_replace_list(raw_str):
if raw_str == None or raw_str == "":
return []
slist = []
......@@ -148,34 +153,34 @@ def get_replace_list(raw_str):
if len(v) > 1:
key = to_str(v[0]).strip().strip("\n")
val = to_str(v[1]).strip().strip("\n")
slist.append([key,val])
slist.append([key, val])
else:
print "(get_replace_list:WARNING): (v:x) undefined value for " + str(s)
key = to_str(v[0]).strip().strip("\n")
slist.append([key,0])
slist.append([key, 0])
return slist
# Парсинг строки вида hostname:port
def get_mbslave_param( raw_str, sep=':' ):
# Парсинг строки вида hostname:port
def get_mbslave_param(raw_str, sep=':'):
if to_str(raw_str) == "":
return [None,None]
return [None, None]
l = raw_str.split(sep)
if len(l) > 2:
print "(get_mbslave_param:WARNING): BAD FORMAT! string='%s'. Must be 'hostname:port'"%(raw_str)
return [None,None]
print "(get_mbslave_param:WARNING): BAD FORMAT! string='%s'. Must be 'hostname:port'" % (raw_str)
return [None, None]
if len(l) == 2:
return [ l[0], to_int(l[1]) ]
return [l[0], to_int(l[1])]
#default modbus port = 502
return [ l[1], 502 ]
# default modbus port = 502
return [l[1], 502]
# Парсинг строки вида "mbreg@mbaddr:mbfunc:nbit:vtype"
def get_mbquery_param( raw_str, def_mbfunc="0x04", ret_str=False ):
# Парсинг строки вида "mbreg@mbaddr:mbfunc:nbit:vtype"
def get_mbquery_param(raw_str, def_mbfunc="0x04", ret_str=False):
raw_str = to_str(raw_str)
l = raw_str.split(':')
......@@ -193,9 +198,9 @@ def get_mbquery_param( raw_str, def_mbfunc="0x04", ret_str=False ):
mbfunc = l[1]
if mbfunc.startswith("0x"):
mbfunc = str(int(mbfunc,16))
mbfunc = str(int(mbfunc, 16))
else:
mbfunc = str(int(mbfunc,10))
mbfunc = str(int(mbfunc, 10))
mbreg = None
mbaddr = "0x01"
......@@ -207,44 +212,47 @@ def get_mbquery_param( raw_str, def_mbfunc="0x04", ret_str=False ):
if len(mbaddr) == 0 or len(mbreg) == 0 or len(mbfunc) == 0:
if ret_str == True:
return ["","","","",""]
return ["", "", "", "", ""]
#print "(get_mbquery_param:WARNING): BAD STRING FORMAT! strig='%s'. Must be 'mbreg@mbaddr:mbfunc:nbit:vtype'"%(raw_str)
return [None,None,None,None,None]
# print "(get_mbquery_param:WARNING): BAD STRING FORMAT! strig='%s'. Must be 'mbreg@mbaddr:mbfunc:nbit:vtype'"%(raw_str)
return [None, None, None, None, None]
if ret_str == False:
return [ to_int(mbaddr), to_int(mbreg), to_int(mbfunc), to_int(nbit), vtype ]
return [to_int(mbaddr), to_int(mbreg), to_int(mbfunc), to_int(nbit), vtype]
return [ mbaddr, mbreg, mbfunc, nbit, vtype ]
return [mbaddr, mbreg, mbfunc, nbit, vtype]
def fcalibrate( raw, rawMin, rawMax, calMin, calMax ):
def fcalibrate(raw, rawMin, rawMax, calMin, calMax):
if rawMax == rawMin:
return 0; # деление на 0!!!
return 1.0 * (raw - rawMin) * (calMax - calMin) / ( rawMax - rawMin ) + calMin;
return 1.0 * (raw - rawMin) * (calMax - calMin) / (rawMax - rawMin) + calMin;
def getArgParam(param,defval=""):
def getArgParam(param, defval=""):
for i in range(0, len(sys.argv)):
if sys.argv[i] == param:
if i+1 < len(sys.argv):
return sys.argv[i+1]
if i + 1 < len(sys.argv):
return sys.argv[i + 1]
else:
break;
break
return defval
def getArgInt(param,defval=0):
def getArgInt(param, defval=0):
for i in range(0, len(sys.argv)):
if sys.argv[i] == param:
if i+1 < len(sys.argv):
return to_int(sys.argv[i+1])
if i + 1 < len(sys.argv):
return to_int(sys.argv[i + 1])
else:
break;
break
return defval
def checkArgParam(param,defval=""):
def checkArgParam(param, defval=""):
for i in range(0, len(sys.argv)):
if sys.argv[i] == param:
return True
......
......@@ -4,11 +4,8 @@
import sys
from pyUniSet import *
from pyUConnector import *
from UGlobal import *
from pyUExceptions import *
class UInterface():
def __init__(self):
self.itype = ""
......
......@@ -3,18 +3,18 @@
import sys
from pyUniSet import *
from pyUModbus import *
from UInterface import *
from UGlobal import *
from pyUExceptions import *
from pyUModbus import *
class UInterfaceModbus():
def __init__(self):
class UInterfaceModbus(UInterface):
def __init__(self, ip, port):
UInterface.__init__(self)
self.itype = "modbus"
self.i = UModbus()
self.i.prepare(ip,port)
# return [id,node,name]
def getIDinfo(self, s_id):
......
......@@ -2,9 +2,9 @@
# -*- coding: utf-8 -*-
from UInterface import *
from UGlobal import *
from pyUConnector import *
class UInterfaceUniSet(UInterface):
def __init__(self, xmlfile, params):
UInterface.__init__(self)
......
......@@ -4,6 +4,8 @@
from UGlobal import *
from UniXML import *
from UInterface import *
from UInterfaceUniSet import *
from UInterfaceModbus import *
from pyUniSet import *
from pyUModbus import *
......
......@@ -12,4 +12,4 @@
/* Для генерации классов и констант в Питоне */
%include "UModbus.h"
%include "UExceptions.h"
// %include "UExceptions.h"
......@@ -130,95 +130,6 @@ class UModbus:
UModbus_swigregister = _pyUModbus.UModbus_swigregister
UModbus_swigregister(UModbus)
class UException(Exception):
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, UException, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, UException, name)
__repr__ = _swig_repr
def __init__(self, *args):
this = _pyUModbus.new_UException(*args)
try:
self.this.append(this)
except Exception:
self.this = this
__swig_destroy__ = _pyUModbus.delete_UException
__del__ = lambda self: None
def getError(self):
return _pyUModbus.UException_getError(self)
__swig_setmethods__["err"] = _pyUModbus.UException_err_set
__swig_getmethods__["err"] = _pyUModbus.UException_err_get
UException_swigregister = _pyUModbus.UException_swigregister
UException_swigregister(UException)
class UTimeOut(UException):
__swig_setmethods__ = {}
for _s in [UException]:
__swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {}))
__setattr__ = lambda self, name, value: _swig_setattr(self, UTimeOut, name, value)
__swig_getmethods__ = {}
for _s in [UException]:
__swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {}))
__getattr__ = lambda self, name: _swig_getattr(self, UTimeOut, name)
__repr__ = _swig_repr
def __init__(self, *args):
this = _pyUModbus.new_UTimeOut(*args)
try:
self.this.append(this)
except Exception:
self.this = this
__swig_destroy__ = _pyUModbus.delete_UTimeOut
__del__ = lambda self: None
UTimeOut_swigregister = _pyUModbus.UTimeOut_swigregister
UTimeOut_swigregister(UTimeOut)
class USysError(UException):
__swig_setmethods__ = {}
for _s in [UException]:
__swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {}))
__setattr__ = lambda self, name, value: _swig_setattr(self, USysError, name, value)
__swig_getmethods__ = {}
for _s in [UException]:
__swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {}))
__getattr__ = lambda self, name: _swig_getattr(self, USysError, name)
__repr__ = _swig_repr
def __init__(self, *args):
this = _pyUModbus.new_USysError(*args)
try:
self.this.append(this)
except Exception:
self.this = this
__swig_destroy__ = _pyUModbus.delete_USysError
__del__ = lambda self: None
USysError_swigregister = _pyUModbus.USysError_swigregister
USysError_swigregister(USysError)
class UValidateError(UException):
__swig_setmethods__ = {}
for _s in [UException]:
__swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {}))
__setattr__ = lambda self, name, value: _swig_setattr(self, UValidateError, name, value)
__swig_getmethods__ = {}
for _s in [UException]:
__swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {}))
__getattr__ = lambda self, name: _swig_getattr(self, UValidateError, name)
__repr__ = _swig_repr
def __init__(self, *args):
this = _pyUModbus.new_UValidateError(*args)
try:
self.this.append(this)
except Exception:
self.this = this
__swig_destroy__ = _pyUModbus.delete_UValidateError
__del__ = lambda self: None
UValidateError_swigregister = _pyUModbus.UValidateError_swigregister
UValidateError_swigregister(UValidateError)
# This file is compatible with both classic and new-style classes.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment