--- a/BeremizIDE.py Tue Aug 15 12:17:51 2017 +0300
+++ b/BeremizIDE.py Tue Aug 15 15:50:30 2017 +0300
@@ -39,7 +39,7 @@
- return os.path.join(beremiz_dir,*args)
+ return os.path.join(beremiz_dir, *args) @@ -85,7 +85,7 @@
-from threading import Lock,Timer,currentThread
+from threading import Lock, Timer, currentThread MainThread = currentThread().ident
from time import time as gettime
@@ -111,7 +111,7 @@
def write(self, s, style = None):
- self.stack.append((s,style))
+ self.stack.append((s, style)) self.TimerAccessLock.acquire()
@@ -180,10 +180,10 @@
self.rising_timer = newtime
def write_warning(self, s):
- self.write(s,self.red_white)
+ self.write(s, self.red_white) def write_error(self, s):
- self.write(s,self.red_yellow)
+ self.write(s, self.red_yellow) @@ -319,20 +319,20 @@
self.Bind(wx.EVT_MENU, self.SwitchFullScrMode, id=keyID)
accels += [wx.AcceleratorEntry(wx.ACCEL_NORMAL, wx.WXK_F12, keyID)]
- for method,shortcut in [("Stop", wx.WXK_F4),
- ("Transfer", wx.WXK_F6),
- ("Connect", wx.WXK_F7),
- ("Build", wx.WXK_F11)]:
- def OnMethodGen(obj,meth):
+ for method, shortcut in [("Stop", wx.WXK_F4), + ("Transfer", wx.WXK_F6), + ("Connect", wx.WXK_F7), + ("Build", wx.WXK_F11)]: + def OnMethodGen(obj, meth): obj.CTR.CallMethod('_'+meth)
wx.CallAfter(self.RefreshStatusToolBar)
- self.Bind(wx.EVT_MENU, OnMethodGen(self,method), id=newid)
- accels += [wx.AcceleratorEntry(wx.ACCEL_NORMAL, shortcut,newid)]
+ self.Bind(wx.EVT_MENU, OnMethodGen(self, method), id=newid) + accels += [wx.AcceleratorEntry(wx.ACCEL_NORMAL, shortcut, newid)] self.SetAcceleratorTable(wx.AcceleratorTable(accels))
@@ -405,7 +405,7 @@
self.__init_execute_path()
IDEFrame.__init__(self, parent, debug)
- self.Log = LogPseudoFile(self.LogConsole,self.SelectTab)
+ self.Log = LogPseudoFile(self.LogConsole, self.SelectTab) self.local_runtime = None
@@ -487,7 +487,7 @@
Bpath("Beremiz_service.py"),
- {False: "-x 0", True:"-x 1"}[taskbaricon],
+ {False: "-x 0", True: "-x 1"}[taskbaricon], self.local_runtime_tmpdir),
timeout=500, keyword = self.local_runtime_tmpdir,
@@ -729,7 +729,7 @@
for confnode_method in self.CTR.StatusMethods:
- if "method" in confnode_method and confnode_method.get("shown",True):
+ if "method" in confnode_method and confnode_method.get("shown", True): StatusToolBar.AddSimpleTool(id,
GetBitmap(confnode_method.get("bitmap", "Unknown")),
@@ -1093,7 +1093,7 @@
def Display_Exception_Dialog(e_type, e_value, e_tb, bug_report_path):
- for i,line in enumerate(traceback.extract_tb(e_tb)):
+ for i, line in enumerate(traceback.extract_tb(e_tb)): trcbck = " " + str(i+1) + ". "
if line[0].find(os.getcwd()) == -1:
trcbck += "file : " + str(line[0]) + ", "
@@ -1145,7 +1145,7 @@
def AddExceptHook(path, app_version='[No version]'): #, ignored_exceptions=[]):
- def save_bug_report(e_type, e_value, e_traceback, bug_report_path,date):
+ def save_bug_report(e_type, e_value, e_traceback, bug_report_path, date): 'app-title': wx.GetApp().GetAppName(), # app_title
'app-version': app_version,
--- a/Beremiz_service.py Tue Aug 15 12:17:51 2017 +0300
+++ b/Beremiz_service.py Tue Aug 15 15:50:30 2017 +0300
@@ -119,7 +119,7 @@
- return os.path.join(beremiz_dir,*args)
+ return os.path.join(beremiz_dir, *args) @@ -127,7 +127,7 @@
# Get folder containing translation files
- localedir = os.path.join(beremiz_dir,"locale")
+ localedir = os.path.join(beremiz_dir, "locale") # Get the default language
langid = wx.LANGUAGE_DEFAULT
# Define translation domain (name of translation files)
@@ -343,7 +343,7 @@
def _LiveShellLocals(self):
if self.pyroserver.plcobj is not None:
- return {"locals":self.pyroserver.plcobj.python_runtime_vars}
+ return {"locals": self.pyroserver.plcobj.python_runtime_vars} @@ -385,7 +385,7 @@
def default_evaluator(tocall, *args, **kwargs):
- res=(tocall(*args,**kwargs), None)
+ res=(tocall(*args, **kwargs), None) res=(None, sys.exc_info())
@@ -430,7 +430,7 @@
self.plcobj = PLCObject(self.workdir, self.daemon, self.argv,
self.statuschange, self.evaluator,
- uri = self.daemon.connect(self.plcobj,"PLCObject")
+ uri = self.daemon.connect(self.plcobj, "PLCObject") print _("Pyro port :"), self.port
print _("Pyro object's uri :"), uri
@@ -499,12 +499,12 @@
main_thread = currentThread()
def statuschangeTskBar(status):
- wx.CallAfter(taskbar_instance.UpdateIcon,status)
+ wx.CallAfter(taskbar_instance.UpdateIcon, status) statuschange.append(statuschangeTskBar)
def wx_evaluator(obj, *args, **kwargs):
- tocall,args,kwargs = obj.call
+ tocall, args, kwargs = obj.call obj.res = default_evaluator(tocall, *args, **kwargs)
@@ -514,8 +514,8 @@
# avoid dead lock if called from the wx mainloop
return default_evaluator(tocall, *args, **kwargs)
- o=type('',(object,),dict(call=(tocall, args, kwargs), res=None))
- wx.CallAfter(wx_evaluator,o)
+ o=type('', (object,), dict(call=(tocall, args, kwargs), res=None)) + wx.CallAfter(wx_evaluator, o) @@ -537,7 +537,7 @@
if pyroserver.plcobj is not None:
- pyroserver.plcobj.LogMessage(0,'\n'.join(traceback.format_exception(*exp)))
+ pyroserver.plcobj.LogMessage(0, '\n'.join(traceback.format_exception(*exp))) traceback.print_exception(*exp)
@@ -611,7 +611,7 @@
- except KeyboardInterrupt,e:
+ except KeyboardInterrupt, e: --- a/PLCControler.py Tue Aug 15 12:17:51 2017 +0300
+++ b/PLCControler.py Tue Aug 15 15:50:30 2017 +0300
@@ -96,7 +96,7 @@
def GetUneditableNames():
return [_("User-defined POUs"), _("Functions"), _("Function Blocks"),
_("Programs"), _("Data Types"), _("Transitions"), _("Actions"),
_("Configurations"), _("Resources"), _("Properties")]
@@ -695,13 +695,27 @@
project = self.GetProject(debug)
infos = {"name": project.getname(), "type": ITEM_PROJECT}
- datatypes = {"name": DATA_TYPES, "type": ITEM_DATATYPES, "values":[]}
+ datatypes = {"name": DATA_TYPES, "type": ITEM_DATATYPES, "values": []} for datatype in project.getdataTypes():
datatypes["values"].append({"name": datatype.getname(), "type": ITEM_DATATYPE,
"tagname": self.ComputeDataTypeName(datatype.getname()), "values": []})
- pou_types = {"function": {"name": FUNCTIONS, "type": ITEM_FUNCTION, "values":[]},
- "functionBlock": {"name": FUNCTION_BLOCKS, "type": ITEM_FUNCTIONBLOCK, "values":[]},
- "program": {"name": PROGRAMS, "type": ITEM_PROGRAM, "values":[]}}
+ "name": FUNCTION_BLOCKS, + "type": ITEM_FUNCTIONBLOCK, for pou in project.getpous():
pou_type = pou.getpouType()
pou_infos = {"name": pou.getname(), "type": ITEM_POU,
@@ -1544,7 +1558,7 @@
self.TotalTypes.extend(addedcat)
- BlkLst = self.TotalTypesDict.setdefault(desc["name"],[])
+ BlkLst = self.TotalTypesDict.setdefault(desc["name"], []) BlkLst.append((section["name"], desc))
# Function that clear the confnode list
@@ -1596,7 +1610,7 @@
# Function that returns the block definition associated to the block type given
def GetBlockType(self, typename, inputs = None, debug = False):
- for sectioname, blocktype in self.TotalTypesDict.get(typename,[]):
+ for sectioname, blocktype in self.TotalTypesDict.get(typename, []): if inputs is not None and inputs != "undefined":
block_inputs = tuple([var_type for name, var_type, modifier in blocktype["inputs"]])
if reduce(lambda x, y: x and y, map(lambda x: x[0] == "ANY" or self.IsOfType(*x), zip(inputs, block_inputs)), True):
@@ -1634,7 +1648,7 @@
project = self.GetProject(debug)
- if words[0] in ["P","T","A"]:
+ if words[0] in ["P", "T", "A"]: pou_type = self.GetPouType(name, debug)
@@ -1658,11 +1672,11 @@
project = self.GetProject(debug)
words = tagname.split("::")
- if project is not None and words[0] in ["P","T","A"]:
+ if project is not None and words[0] in ["P", "T", "A"]: for blocks in self.TotalTypesDict.itervalues():
- for sectioname,block in blocks:
+ for sectioname, block in blocks: if block["type"] == "functionBlock":
blocktypes.append(block["name"])
@@ -1773,7 +1787,7 @@
TypeHierarchy_list has a rough order to it (e.g. SINT, INT, DINT, ...),
which makes it easy for a user to find a type in a menu.
- return [x for x,y in TypeHierarchy_list if not x.startswith("ANY")]
+ return [x for x, y in TypeHierarchy_list if not x.startswith("ANY")] def IsOfType(self, typename, reference, debug = False):
if reference is None or typename == reference:
@@ -2174,7 +2188,7 @@
# Return edited element name
def GetEditedElementName(self, tagname):
words = tagname.split("::")
- if words[0] in ["P","C","D"]:
+ if words[0] in ["P", "C", "D"]: @@ -2183,7 +2197,7 @@
# Return edited element name and type
def GetEditedElementType(self, tagname, debug = False):
words = tagname.split("::")
- if words[0] in ["P","T","A"]:
+ if words[0] in ["P", "T", "A"]: return words[1], self.GetPouType(words[1], debug)
@@ -2201,7 +2215,7 @@
# Return the edited element variables
def GetEditedElementInterfaceVars(self, tagname, tree=False, debug = False):
words = tagname.split("::")
- if words[0] in ["P","T","A"]:
+ if words[0] in ["P", "T", "A"]: project = self.GetProject(debug)
pou = project.getpou(words[1])
@@ -2259,7 +2273,7 @@
# Return the names of the pou elements
def GetEditedElementVariables(self, tagname, debug = False):
words = tagname.split("::")
- if words[0] in ["P","T","A"]:
+ if words[0] in ["P", "T", "A"]: return self.GetProjectPouVariableNames(words[1], debug)
elif words[0] in ["C", "R"]:
names = self.GetConfigurationVariableNames(words[1], debug)
@@ -2302,7 +2316,7 @@
names.update(dict([(varname.upper(), True)
for varname in self.GetEditedElementVariables(tagname, debug)]))
words = tagname.split("::")
- if words[0] in ["P","T","A"]:
+ if words[0] in ["P", "T", "A"]: element = self.GetEditedElement(tagname, debug)
if element is not None and element.getbodyType() not in ["ST", "IL"]:
for instance in element.getinstances():
@@ -2494,7 +2508,7 @@
var_type_obj.setcontent(derived_type)
- def AddEditedElementPouVar(self, tagname, var_type, name,**args):
+ def AddEditedElementPouVar(self, tagname, var_type, name, **args): if self.Project is not None:
words = tagname.split("::")
if words[0] in ['P', 'T', 'A']:
--- a/ProjectController.py Tue Aug 15 12:17:51 2017 +0300
+++ b/ProjectController.py Tue Aug 15 15:50:30 2017 +0300
@@ -70,7 +70,7 @@
def ExtractChildrenTypesFromCatalog(catalog):
- for n,d,h,c in catalog:
+ for n, d, h, c in catalog: if isinstance(c, ListType):
children_types.extend(ExtractChildrenTypesFromCatalog(c))
@@ -80,7 +80,7 @@
def ExtractMenuItemsFromCatalog(catalog):
- for n,d,h,c in catalog:
+ for n, d, h, c in catalog: if isinstance(c, ListType):
children = ExtractMenuItemsFromCatalog(c)
@@ -113,7 +113,7 @@
os.path.join(base_folder, "matiec")
- path = self.findObject(paths, lambda p:os.path.isfile(os.path.join(p, cmd)))
+ path = self.findObject(paths, lambda p: os.path.isfile(os.path.join(p, cmd))) # otherwise use iec2c from PATH
@@ -126,7 +126,7 @@
os.path.join(base_folder, "matiec", "lib"),
- path = self.findObject(paths, lambda p:os.path.isfile(os.path.join(p, "ieclib.txt")))
+ path = self.findObject(paths, lambda p: os.path.isfile(os.path.join(p, "ieclib.txt"))) @@ -134,7 +134,7 @@
os.path.join(self.ieclib_path, "C"),
- path = self.findObject(paths, lambda p:os.path.isfile(os.path.join(p, "iec_types.h")))
+ path = self.findObject(paths, lambda p: os.path.isfile(os.path.join(p, "iec_types.h"))) def findSupportedOptions(self):
@@ -146,7 +146,7 @@
# Invoke compiler. Output files are listed to stdout, errors to stderr
status, result, err_result = ProcessLogger(None, buildcmd,
no_stdout=True, no_stderr=True).spin()
@@ -207,7 +207,7 @@
"""+"\n".join(['<xsd:attribute name='+
'"Enable_'+ libname + '_Library" '+
'type="xsd:boolean" use="optional" default="true"/>'
- for libname,lib in features.libraries])+"""
+ for libname, lib in features.libraries])+""" </xsd:element>""") if len(features.libraries)>0 else '') + """
@@ -262,7 +262,7 @@
- for libname,clsname in features.libraries:
+ for libname, clsname in features.libraries: if self.BeremizRoot.Libraries is None or getattr(self.BeremizRoot.Libraries, "Enable_"+libname+"_Library"):
Lib = GetClassImporter(clsname)()(self, libname, TypeStack)
TypeStack.append(Lib.GetTypes())
@@ -569,17 +569,17 @@
def GetLibrariesCCode(self, buildpath):
if len(self.Libraries)==0:
self.GetIECProgramsAndVariables()
LibIECCflags = '"-I%s" -Wno-unused-function' % os.path.abspath(self.GetIECLibPath())
for lib in self.Libraries:
- res=lib.Generate_C(buildpath,self._VariablesList,LibIECCflags)
+ res=lib.Generate_C(buildpath, self._VariablesList, LibIECCflags) LocatedCCodeAndFlags.append(res[:2])
- return map(list,zip(*LocatedCCodeAndFlags))+[tuple(Extras)]
+ return map(list, zip(*LocatedCCodeAndFlags))+[tuple(Extras)] # Update PLCOpenEditor ConfNode Block types from loaded confnodes
def RefreshConfNodesBlockLists(self):
@@ -668,10 +668,10 @@
- filepath = os.path.join(self._getBuildPath(),"LOCATED_VARIABLES.h")
+ filepath = os.path.join(self._getBuildPath(), "LOCATED_VARIABLES.h") if os.path.isfile(filepath):
# IEC2C compiler generate a list of located variables : LOCATED_VARIABLES.h
- location_file = open(os.path.join(self._getBuildPath(),"LOCATED_VARIABLES.h"))
+ location_file = open(os.path.join(self._getBuildPath(), "LOCATED_VARIABLES.h")) # each line of LOCATED_VARIABLES.h declares a located variable
lines = [line.strip() for line in location_file.readlines()]
# This regular expression parses the lines genereated by IEC2C
@@ -683,7 +683,7 @@
resdict = result.groupdict()
# rewrite string for variadic location as a tuple of integers
- resdict['LOC'] = tuple(map(int,resdict['LOC'].split(',')))
+ resdict['LOC'] = tuple(map(int, resdict['LOC'].split(','))) # set located size to 'X' if not given
@@ -752,7 +752,7 @@
# Invoke compiler. Output files are listed to stdout, errors to stderr
status, result, err_result = ProcessLogger(self.logger, buildcmd,
no_stdout=True, no_stderr=True).spin()
self.logger.write_error(buildcmd + "\n")
self.logger.write_error(repr(e) + "\n")
@@ -797,12 +797,12 @@
self.logger.write_error(_("Error : At least one configuration and one resource must be declared in PLC !\n"))
# transform those base names to full names with path
- C_files = map(lambda filename:os.path.join(buildpath, filename), C_files)
+ C_files = map(lambda filename: os.path.join(buildpath, filename), C_files) # prepend beremiz include to configuration header
H_files = [ fname for fname in result.splitlines() if fname[-2:]==".h" or fname[-2:]==".H" ]
H_files.remove("LOCATED_VARIABLES.h")
- H_files = map(lambda filename:os.path.join(buildpath, filename), H_files)
+ H_files = map(lambda filename: os.path.join(buildpath, filename), H_files) with file(H_file, 'r') as original: data = original.read()
with file(H_file, 'w') as modified: modified.write('#include "beremiz.h"\n' + data)
@@ -825,7 +825,7 @@
targetclass = targets.GetBuilder(targetname)
- if self._builder is None or not isinstance(self._builder,targetclass):
+ if self._builder is None or not isinstance(self._builder, targetclass): self._builder = targetclass(self)
@@ -883,7 +883,7 @@
if self._ProgramList is None or self._VariablesList is None:
- csvfile = os.path.join(self._getBuildPath(),"VARIABLES.csv")
+ csvfile = os.path.join(self._getBuildPath(), "VARIABLES.csv") ProgramsListAttributeName = ["num", "C_path", "type"]
VariablesListAttributeName = ["num", "vartype", "IEC_path", "C_path", "type"]
@@ -894,7 +894,7 @@
- for line in open(csvfile,'r').xreadlines():
+ for line in open(csvfile, 'r').xreadlines(): strippedline = line.strip()
if strippedline.startswith("//"):
@@ -906,9 +906,9 @@
# first section contains programs
for line in ListGroup[0]:
# Split and Maps each field to dictionnary entries
- attrs = dict(zip(ProgramsListAttributeName,line.strip().split(';')))
+ attrs = dict(zip(ProgramsListAttributeName, line.strip().split(';'))) # Truncate "C_path" to remove conf an resources names
- attrs["C_path"] = '__'.join(attrs["C_path"].split(".",2)[1:])
+ attrs["C_path"] = '__'.join(attrs["C_path"].split(".", 2)[1:]) # Push this dictionnary into result.
self._ProgramList.append(attrs)
@@ -917,9 +917,9 @@
for line in ListGroup[1]:
# Split and Maps each field to dictionnary entries
- attrs = dict(zip(VariablesListAttributeName,line.strip().split(';')))
+ attrs = dict(zip(VariablesListAttributeName, line.strip().split(';'))) # Truncate "C_path" to remove conf an resources names
- parts = attrs["C_path"].split(".",2)
+ parts = attrs["C_path"].split(".", 2) config_FB = config_FBs.get(tuple(parts[:2]))
@@ -947,7 +947,7 @@
self._Ticktime = int(ListGroup[2][0])
self.logger.write_error(_("Cannot open/parse VARIABLES.csv!\n"))
self.logger.write_error(traceback.format_exc())
self.ResetIECProgramsAndVariables()
@@ -968,24 +968,28 @@
sz = DebugTypesSize.get(v["type"], 0)
- {"EXT":"%(type)s_P_ENUM",
- "IN":"%(type)s_P_ENUM",
- "MEM":"%(type)s_O_ENUM",
- "OUT":"%(type)s_O_ENUM",
- "VAR":"%(type)s_ENUM"}[v["vartype"]] % v +
+ "EXT": "%(type)s_P_ENUM", + "IN": "%(type)s_P_ENUM", + "MEM": "%(type)s_O_ENUM", + "OUT": "%(type)s_O_ENUM", debug_code = targets.GetCode("plc_debug.c") % {
"\n".join(["extern %(type)s %(C_path)s;" % p for p in self._ProgramList]),
- "extern_variables_declarations":"\n".join([
- {"EXT":"extern __IEC_%(type)s_p %(C_path)s;",
- "IN":"extern __IEC_%(type)s_p %(C_path)s;",
- "MEM":"extern __IEC_%(type)s_p %(C_path)s;",
- "OUT":"extern __IEC_%(type)s_p %(C_path)s;",
- "VAR":"extern __IEC_%(type)s_t %(C_path)s;",
- "FB":"extern %(type)s %(C_path)s;"}[v["vartype"]] % v
+ "extern_variables_declarations": "\n".join([ + "EXT": "extern __IEC_%(type)s_p %(C_path)s;", + "IN": "extern __IEC_%(type)s_p %(C_path)s;", + "MEM": "extern __IEC_%(type)s_p %(C_path)s;", + "OUT": "extern __IEC_%(type)s_p %(C_path)s;", + "VAR": "extern __IEC_%(type)s_t %(C_path)s;", + "FB": "extern %(type)s %(C_path)s;" for v in self._VariablesList if v["C_path"].find('.')<0]),
"variable_decl_array": ",\n".join(variable_decl_array)
@@ -999,38 +1003,38 @@
# filter location that are related to code that will be called
# in retreive, publish, init, cleanup
- locstrs = map(lambda x:"_".join(map(str,x)),
- [loc for loc,Cfiles,DoCalls in self.LocationCFilesAndCFLAGS if loc and DoCalls])
+ locstrs = map(lambda x: "_".join(map(str, x)), + [loc for loc, Cfiles, DoCalls in self.LocationCFilesAndCFLAGS if loc and DoCalls]) # Generate main, based on template
if not self.BeremizRoot.getDisable_Extensions():
plc_main_code = targets.GetCode("plc_main_head.c") % {
- "calls_prototypes":"\n".join([(
+ "calls_prototypes": "\n".join([( "int __init_%(s)s(int argc,char **argv);\n"+
"void __cleanup_%(s)s(void);\n"+
"void __retrieve_%(s)s(void);\n"+
- "void __publish_%(s)s(void);") % {'s':locstr} for locstr in locstrs]),
- "retrieve_calls":"\n ".join([
+ "void __publish_%(s)s(void);") % {'s': locstr} for locstr in locstrs]), + "retrieve_calls": "\n ".join([ "__retrieve_%s();" % locstr for locstr in locstrs]),
- "publish_calls":"\n ".join([ #Call publish in reverse order
+ "publish_calls": "\n ".join([ # Call publish in reverse order "__publish_%s();" % locstrs[i-1] for i in xrange(len(locstrs), 0, -1)]),
- "init_calls":"\n ".join([
+ "init_calls": "\n ".join([ "init_level=%d; " % (i+1)+
"if((res = __init_%s(argc,argv))){" % locstr +
#"printf(\"%s\"); "%locstr + #for debug
- "return res;}" for i,locstr in enumerate(locstrs)]),
- "cleanup_calls":"\n ".join([
+ "return res;}" for i, locstr in enumerate(locstrs)]), + "cleanup_calls": "\n ".join([ "if(init_level >= %d) " % i+
"__cleanup_%s();" % locstrs[i-1] for i in xrange(len(locstrs), 0, -1)])
plc_main_code = targets.GetCode("plc_main_head.c") % {
- "calls_prototypes":"\n",
+ "calls_prototypes": "\n", + "retrieve_calls": "\n", plc_main_code += targets.GetTargetCode(self.GetTarget().getcontent().getLocalTag())
plc_main_code += targets.GetCode("plc_main_tail.c")
@@ -1130,14 +1134,14 @@
- for fname,fobject in ExtraFiles:
- fpath = os.path.join(extrafilespath,fname)
+ for fname, fobject in ExtraFiles: + fpath = os.path.join(extrafilespath, fname) open(fpath, "wb").write(fobject.read())
# Now we can forget ExtraFiles (will close files object)
# Header file for extensions
- open(os.path.join(buildpath,"beremiz.h"), "w").write(targets.GetHeader())
+ open(os.path.join(buildpath, "beremiz.h"), "w").write(targets.GetHeader()) # Template based part of C code generation
# files are stacked at the beginning, as files of confnode tree root
@@ -1145,16 +1149,16 @@
(self.Generate_plc_debugger, "plc_debugger.c", "Debugger"),
# init/cleanup/retrieve/publish, run and align code
- (self.Generate_plc_main,"plc_main.c","Common runtime")]:
+ (self.Generate_plc_main, "plc_main.c", "Common runtime")]: - code_path = os.path.join(buildpath,filename)
+ code_path = os.path.join(buildpath, filename) open(code_path, "w").write(code)
# Insert this file as first file to be compiled at root confnode
- self.LocationCFilesAndCFLAGS[0][1].insert(0,(code_path, self.plcCFLAGS))
+ self.LocationCFilesAndCFLAGS[0][1].insert(0, (code_path, self.plcCFLAGS)) self.logger.write_error(name+_(" generation failed !\n"))
self.logger.write_error(traceback.format_exc())
@@ -1336,19 +1340,19 @@
if(self.previous_plcstate != status):
- "Started": [("_Run", False),
+ "Started": [("_Run", False), - "Stopped": [("_Run", True),
+ "Stopped": [("_Run", True), - "Empty": [("_Run", False),
+ "Empty": [("_Run", False),
- "Disconnected":[("_Run", False),
+ "Disconnected": [("_Run", False),
self.previous_plcstate = status
if self.AppFrame is not None:
@@ -1402,7 +1406,7 @@
if self._connector is not None:
self.IECdebug_lock.acquire()
- for IECPath,data_tuple in self.IECdebug_datas.iteritems():
+ for IECPath, data_tuple in self.IECdebug_datas.iteritems(): WeakCallableDict, data_log, status, fvalue, buffer_list = data_tuple
if len(WeakCallableDict) == 0:
# Callable Dict is empty.
@@ -1410,7 +1414,7 @@
IECPathsToPop.append(IECPath)
elif IECPath != "__tick__":
- Idx, IEC_Type = self._IECPathToIdx.get(IECPath,(None,None))
+ Idx, IEC_Type = self._IECPathToIdx.get(IECPath, (None, None)) if IEC_Type in DebugTypesSize:
Idxs.append((Idx, IEC_Type, fvalue, IECPath))
@@ -1446,12 +1450,12 @@
# Timer to prevent rapid-fire when registering many variables
# use wx.CallAfter use keep using same thread. TODO : use wx.Timer instead
- self.DebugTimer=Timer(0.5,wx.CallAfter,args = [self.RegisterDebugVarToConnector])
+ self.DebugTimer=Timer(0.5, wx.CallAfter, args = [self.RegisterDebugVarToConnector]) # Rearm anti-rapid-fire timer
def GetDebugIECVariableType(self, IECPath):
- Idx, IEC_Type = self._IECPathToIdx.get(IECPath,(None,None))
+ Idx, IEC_Type = self._IECPathToIdx.get(IECPath, (None, None)) def SubscribeDebugIECVariable(self, IECPath, callableobj, buffer_list=False):
@@ -1489,7 +1493,7 @@
self.IECdebug_lock.acquire()
IECdebug_data = self.IECdebug_datas.get(IECPath, None)
if IECdebug_data is not None:
- IECdebug_data[0].pop(callableobj,None)
+ IECdebug_data[0].pop(callableobj, None) if len(IECdebug_data[0]) == 0:
self.IECdebug_datas.pop(IECPath)
@@ -1543,7 +1547,7 @@
if data_tuple is not None:
WeakCallableDict, data_log, status, fvalue, buffer_list = data_tuple
#data_log.append((debug_tick, value))
- for weakcallable,buffer_list in WeakCallableDict.iteritems():
+ for weakcallable, buffer_list in WeakCallableDict.iteritems(): function = getattr(weakcallable, function_name, None)
@@ -1756,7 +1760,7 @@
#self.logger.write(_("PLC is %s\n")%status)
- if self.previous_plcstate in ["Started","Stopped"]:
+ if self.previous_plcstate in ["Started", "Stopped"]: if self.DebugAvailable() and self.GetIECProgramsAndVariables():
self.logger.write(_("Debugger ready\n"))
--- a/canfestival/canfestival.py Tue Aug 15 12:17:51 2017 +0300
+++ b/canfestival/canfestival.py Tue Aug 15 15:50:30 2017 +0300
@@ -235,7 +235,7 @@
res = eds_utils.GenerateEDSFile(os.path.join(buildpath, "Slave_%s.eds" % prefix), slave)
- return [(Gen_OD_path,local_canfestival_config.getCFLAGS(CanFestivalPath))],"",False
+ return [(Gen_OD_path, local_canfestival_config.getCFLAGS(CanFestivalPath))], "", False self.LoadCurrentPrevious()
@@ -445,7 +445,7 @@
Gen_OD_path = os.path.join(buildpath, "OD_%s.c" % prefix )
# Create a new copy of the model with DCF loaded with PDO mappings for desired location
- master, pointers = config_utils.GenerateConciseDCF(locations, current_location, self, self.CanFestivalNode.getSync_TPDOs(),"OD_%s" % prefix)
+ master, pointers = config_utils.GenerateConciseDCF(locations, current_location, self, self.CanFestivalNode.getSync_TPDOs(), "OD_%s" % prefix) except config_utils.PDOmappingException, e:
raise Exception, e.message
@@ -457,7 +457,7 @@
- return [(Gen_OD_path,local_canfestival_config.getCFLAGS(CanFestivalPath))],"",False
+ return [(Gen_OD_path, local_canfestival_config.getCFLAGS(CanFestivalPath))], "", False self.Manager.LoadCurrentPrevious()
@@ -480,8 +480,8 @@
- CTNChildrenTypes = [("CanOpenNode",_NodeListCTN, "CanOpen Master"),
- ("CanOpenSlave",_SlaveCTN, "CanOpen Slave")]
+ CTNChildrenTypes = [("CanOpenNode", _NodeListCTN, "CanOpen Master"), + ("CanOpenSlave", _SlaveCTN, "CanOpen Slave" )] def GetParamsAttributes(self, path = None):
infos = ConfigTreeNode.GetParamsAttributes(self, path = path)
@@ -510,7 +510,7 @@
- format_dict = {"locstr": "_".join(map(str,self.GetCurrentLocation())),
+ format_dict = {"locstr": "_".join(map(str, self.GetCurrentLocation())), "candriver": can_driver_name,
@@ -528,7 +528,7 @@
for child in self.IECSortedChildren():
- childlocstr = "_".join(map(str,child.GetCurrentLocation()))
+ childlocstr = "_".join(map(str, child.GetCurrentLocation())) nodename = "OD_%s" % childlocstr
@@ -557,13 +557,13 @@
# register previously declared func as post_SlaveBootup callback for that node
format_dict["slavebootup_register"] += (
- "%s_Data.post_SlaveBootup = %s_post_SlaveBootup;\n" % (nodename,nodename))
+ "%s_Data.post_SlaveBootup = %s_post_SlaveBootup;\n" % (nodename, nodename)) format_dict["pre_op"] += (
"static void %s_preOperational(CO_Data* d){\n " % (nodename)+
"".join([" masterSendNMTstateChange(d, %d, NMT_Reset_Comunication);\n" % NdId for NdId in SlaveIDs])+
format_dict["pre_op_register"] += (
- "%s_Data.preOperational = %s_preOperational;\n" % (nodename,nodename))
+ "%s_Data.preOperational = %s_preOperational;\n" % (nodename, nodename)) align = child_data.getSync_Align()
@@ -580,7 +580,7 @@
format_dict["post_sync_register"] += (
- "%s_Data.post_sync = %s_post_sync;\n" % (nodename,nodename))
+ "%s_Data.post_sync = %s_post_sync;\n" % (nodename, nodename)) format_dict["nodes_init"] += 'NODE_SLAVE_INIT(%s, %s)\n ' % (
@@ -596,18 +596,18 @@
format_dict["nodes_close"] += 'NODE_CLOSE(%s)\n ' % (nodename)
format_dict["nodes_stop"] += 'NODE_STOP(%s)\n ' % (nodename)
- filename = paths.AbsNeighbourFile(__file__,"cf_runtime.c")
+ filename = paths.AbsNeighbourFile(__file__, "cf_runtime.c") cf_main = open(filename).read() % format_dict
cf_main_path = os.path.join(buildpath, "CF_%(locstr)s.c" % format_dict)
- f = open(cf_main_path,'w')
+ f = open(cf_main_path, 'w') - res = [(cf_main_path, local_canfestival_config.getCFLAGS(CanFestivalPath))],local_canfestival_config.getLDFLAGS(CanFestivalPath), True
+ res = [(cf_main_path, local_canfestival_config.getCFLAGS(CanFestivalPath))], local_canfestival_config.getLDFLAGS(CanFestivalPath), True if can_driver is not None:
- can_driver_path = os.path.join(CanFestivalPath,"drivers",can_driver,can_driver_name)
+ can_driver_path = os.path.join(CanFestivalPath, "drivers", can_driver, can_driver_name) if os.path.exists(can_driver_path):
- res += ((can_driver_name, file(can_driver_path,"rb")),)
+ res += ((can_driver_name, file(can_driver_path, "rb")),) --- a/canfestival/config_utils.py Tue Aug 15 12:17:51 2017 +0300
+++ b/canfestival/config_utils.py Tue Aug 15 15:50:30 2017 +0300
@@ -25,10 +25,25 @@
# Translation between IEC types and Can Open types
-IECToCOType = {"BOOL":0x01, "SINT":0x02, "INT":0x03,"DINT":0x04,"LINT":0x10,
- "USINT":0x05,"UINT":0x06,"UDINT":0x07,"ULINT":0x1B,"REAL":0x08,
- "LREAL":0x11,"STRING":0x09,"BYTE":0x05,"WORD":0x06,"DWORD":0x07,
- "LWORD":0x1B,"WSTRING":0x0B}
# Constants for PDO types
@@ -42,7 +57,7 @@
VariableIncrement = 0x100
VariableStartIndex = {TPDO: 0x2000, RPDO: 0x4000}
VariableDirText = {TPDO: "__I", RPDO: "__Q"}
-VariableTypeOffset = dict(zip(["","X","B","W","D","L"], range(6)))
+VariableTypeOffset = dict(zip(["", "X", "B", "W", "D", "L"], range(6))) TrashVariables = [(1, 0x01), (8, 0x05), (16, 0x06), (32, 0x07), (64, 0x1B)]
@@ -222,10 +237,10 @@
RPDOnumber, TPDOnumber = self.RemoveUsedNodeCobId(node)
# Get Slave's default SDO server parameters
- RSDO_cobid = node.GetEntry(0x1200,0x01)
+ RSDO_cobid = node.GetEntry(0x1200, 0x01) RSDO_cobid = 0x600 + nodeid
- TSDO_cobid = node.GetEntry(0x1200,0x02)
+ TSDO_cobid = node.GetEntry(0x1200, 0x02) TSDO_cobid = 0x580 + nodeid
@@ -384,9 +399,16 @@
format(a1 = location["IEC_TYPE"], a2 = COlocationtype, a3 = subentry_infos["type"], a4 = name)
typeinfos = node.GetEntryInfos(COlocationtype)
- self.IECLocations[name] = {"type":COlocationtype, "pdotype":SlavePDOType[direction],
- "nodeid": nodeid, "index": index,"subindex": subindex,
- "bit": numbit, "size": typeinfos["size"], "sizelocation": sizelocation}
+ self.IECLocations[name] = { + "type": COlocationtype, + "pdotype": SlavePDOType[direction], + "size": typeinfos["size"], + "sizelocation": sizelocation raise PDOmappingException, _("Not PDO mappable variable : '{a1}' (ID:{a2},Idx:{a3},sIdx:{a4}))").\
format(a1 = name, a2 = nodeid, a3 = "%x" % index, a4 = "%x" % subindex)
@@ -550,7 +572,7 @@
indexname = "%s%s%s_%d" % (VariableDirText[variable_infos["pdotype"]],
variable_infos["sizelocation"],
- '_'.join(map(str,current_location)),
+ '_'.join(map(str, current_location)), variable_infos["nodeid"])
# Search for an entry that has an empty subindex
@@ -611,10 +633,10 @@
dcfgenerator = ConciseDCFGenerator(nodelist, nodename)
dcfgenerator.GenerateDCF(locations, current_location, sync_TPDOs)
- masternode,pointers = dcfgenerator.GetMasterNode(), dcfgenerator.GetPointedVariables()
+ masternode, pointers = dcfgenerator.GetMasterNode(), dcfgenerator.GetPointedVariables() # allow access to local OD from Master PLC
pointers.update(LocalODPointers(locations, current_location, masternode))
- return masternode,pointers
+ return masternode, pointers def LocalODPointers(locations, current_location, slave):
@@ -679,7 +701,7 @@
# Extract command options
- opts, args = getopt.getopt(sys.argv[1:], "hr", ["help","reset"])
+ opts, args = getopt.getopt(sys.argv[1:], "hr", ["help", "reset"]) except getopt.GetoptError:
# print help information and exit:
@@ -709,16 +731,18 @@
result = nodelist.LoadProject("test_config")
# List of locations, we try to map for test
- locations = [{"IEC_TYPE":"BYTE","NAME":"__IB0_1_64_24576_1","DIR":"I","SIZE":"B","LOC":(0,1,64,24576,1)},
- {"IEC_TYPE":"INT","NAME":"__IW0_1_64_25601_2","DIR":"I","SIZE":"W","LOC":(0,1,64,25601,2)},
- {"IEC_TYPE":"INT","NAME":"__IW0_1_64_25601_3","DIR":"I","SIZE":"W","LOC":(0,1,64,25601,3)},
- {"IEC_TYPE":"INT","NAME":"__QW0_1_64_25617_2","DIR":"Q","SIZE":"W","LOC":(0,1,64,25617,1)},
- {"IEC_TYPE":"BYTE","NAME":"__IB0_1_64_24578_1","DIR":"I","SIZE":"B","LOC":(0,1,64,24578,1)},
- {"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_1","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,1)},
- {"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_2","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,2)},
- {"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_3","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,3)},
- {"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_4","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,4)},
- {"IEC_TYPE":"UDINT","NAME":"__ID0_1_4096_0","DIR":"I","SIZE":"D","LOC":(0,1,4096,0)}]
+ {"IEC_TYPE": "BYTE", "NAME": "__IB0_1_64_24576_1", "DIR": "I", "SIZE": "B", "LOC": (0, 1, 64, 24576, 1)}, + {"IEC_TYPE": "INT", "NAME": "__IW0_1_64_25601_2", "DIR": "I", "SIZE": "W", "LOC": (0, 1, 64, 25601, 2)}, + {"IEC_TYPE": "INT", "NAME": "__IW0_1_64_25601_3", "DIR": "I", "SIZE": "W", "LOC": (0, 1, 64, 25601, 3)}, + {"IEC_TYPE": "INT", "NAME": "__QW0_1_64_25617_2", "DIR": "Q", "SIZE": "W", "LOC": (0, 1, 64, 25617, 1)}, + {"IEC_TYPE": "BYTE", "NAME": "__IB0_1_64_24578_1", "DIR": "I", "SIZE": "B", "LOC": (0, 1, 64, 24578, 1)}, + {"IEC_TYPE": "UDINT", "NAME": "__ID0_1_64_25638_1", "DIR": "I", "SIZE": "D", "LOC": (0, 1, 64, 25638, 1)}, + {"IEC_TYPE": "UDINT", "NAME": "__ID0_1_64_25638_2", "DIR": "I", "SIZE": "D", "LOC": (0, 1, 64, 25638, 2)}, + {"IEC_TYPE": "UDINT", "NAME": "__ID0_1_64_25638_3", "DIR": "I", "SIZE": "D", "LOC": (0, 1, 64, 25638, 3)}, + {"IEC_TYPE": "UDINT", "NAME": "__ID0_1_64_25638_4", "DIR": "I", "SIZE": "D", "LOC": (0, 1, 64, 25638, 4)}, + {"IEC_TYPE": "UDINT", "NAME": "__ID0_1_4096_0", "DIR": "I", "SIZE": "D", "LOC": (0, 1, 4096, 0)} # Generate MasterNode configuration
--- a/controls/VariablePanel.py Tue Aug 15 12:17:51 2017 +0300
+++ b/controls/VariablePanel.py Tue Aug 15 15:50:30 2017 +0300
@@ -211,7 +211,7 @@
editor = wx.grid.GridCellChoiceEditor()
if self.Parent.IsFunctionBlockType(var_type):
- excluded.extend(["Local","Temp"])
+ excluded.extend(["Local", "Temp"]) editor.SetParameters(",".join([_(choice) for choice in self.Parent.ClassList if choice not in excluded]))
elif colname != "Documentation":
grid.SetReadOnly(row, col, True)
@@ -323,7 +323,7 @@
elif (element_type not in ["config", "resource", "function"] and values[1] == "Global" and
self.ParentWindow.Filter in ["All", "Interface", "External"] or
element_type != "function" and values[1] in ["location", "NamedConstant"]):
- if values[1] in ["location","NamedConstant"]:
+ if values[1] in ["location", "NamedConstant"]: @@ -386,7 +386,7 @@
var_infos.Class = "Global"
var_infos.Location = location
elif values[1] == "NamedConstant":
- if element_type in ["functionBlock","program"]:
+ if element_type in ["functionBlock", "program"]: var_infos.Class = "Local"
var_infos.InitialValue = values[0]
@@ -511,10 +511,10 @@
- # Num Name Class Type Loc Init Option Doc
- self.ColSizes = [40, 80, 100, 80, 110, 120, 100, 160]
- self.ColAlignements = [c, l, l, l, l, l, l, l]
- self.ColFixedSizeFlag=[True,False, True, False, True, True, True, False]
+ # Num Name Class Type Loc Init Option Doc + self.ColSizes = [40, 80, 100, 80, 110, 120, 100, 160] + self.ColAlignements = [c, l, l, l, l, l, l, l] + self.ColFixedSizeFlag=[True, False, True, False, True, True, True, False] # this is an element that cannot have located variables
@@ -533,10 +533,10 @@
- # Num Name Class Type Init Option Doc
- self.ColSizes = [40, 80, 100, 80, 120, 100, 160]
- self.ColAlignements = [c, l, l, l, l, l, l]
- self.ColFixedSizeFlag=[True,False, True, False, True, True, False]
+ # Num Name Class Type Init Option Doc + self.ColSizes = [40, 80, 100, 80, 120, 100, 160] + self.ColAlignements = [c, l, l, l, l, l, l] + self.ColFixedSizeFlag=[True, False, True, False, True, True, False] self.PanelWidthMin = sum(self.ColSizes)
@@ -753,11 +753,11 @@
def RefreshTypeList(self):
- self.ClassList = [self.FilterChoiceTransfer[choice] for choice in self.FilterChoices if self.FilterChoiceTransfer[choice] not in ["All","Interface","Variables"]]
+ self.ClassList = [self.FilterChoiceTransfer[choice] for choice in self.FilterChoices if self.FilterChoiceTransfer[choice] not in ["All", "Interface", "Variables"]] elif self.Filter == "Interface":
- self.ClassList = ["Input","Output","InOut","External"]
+ self.ClassList = ["Input", "Output", "InOut", "External"] elif self.Filter == "Variables":
- self.ClassList = ["Local","Temp"]
+ self.ClassList = ["Local", "Temp"] self.ClassList = [self.Filter]
@@ -811,7 +811,7 @@
- def BuildStdIECTypesMenu(self,type_menu):
+ def BuildStdIECTypesMenu(self, type_menu): # build a submenu containing standard IEC types
base_menu = wx.Menu(title='')
for base_type in self.Controler.GetBaseTypes():
@@ -821,7 +821,7 @@
type_menu.AppendMenu(wx.NewId(), _("Base Types"), base_menu)
- def BuildUserTypesMenu(self,type_menu):
+ def BuildUserTypesMenu(self, type_menu): # build a submenu containing user-defined types
datatype_menu = wx.Menu(title='')
datatypes = self.Controler.GetDataTypes(basetypes = False, confnodetypes = False)
@@ -879,7 +879,7 @@
self.BuildLibsTypesMenu(type_menu)
- self.BuildProjectTypesMenu(type_menu,classtype)
+ self.BuildProjectTypesMenu(type_menu, classtype) self.BuildArrayTypesMenu(type_menu)
--- a/editors/LDViewer.py Tue Aug 15 12:17:51 2017 +0300
+++ b/editors/LDViewer.py Tue Aug 15 15:50:30 2017 +0300
@@ -60,11 +60,11 @@
if element not in element_tree:
- element_tree[element] = {"parents":["start"], "children":[], "weight":None}
+ element_tree[element] = {"parents": ["start"], "children": [], "weight": None} GenerateTree(element, element_tree, stop_list)
elif element_tree[element]:
element_tree[element]["parents"].append("start")
- remove_stops = {"start":[], "stop":[]}
+ remove_stops = {"start": [], "stop": []} for element, values in element_tree.items():
if "stop" in values["children"]:
@@ -129,7 +129,7 @@
element_tree[next]["parents"].append(element)
- element_tree[next] = {"parents":[element], "children":[], "weight":None}
+ element_tree[next] = {"parents": [element], "children": [], "weight": None} GenerateTree(next, element_tree, stop_list)
@@ -494,7 +494,7 @@
varlist.append(self.Controler.GetEditedElementName(self.TagName))
dialog.SetVariables(varlist)
- dialog.SetValues({"name":"","type":COIL_NORMAL})
+ dialog.SetValues({"name": "", "type": COIL_NORMAL}) if dialog.ShowModal() == wx.ID_OK:
values = dialog.GetValues()
startx, starty = LD_OFFSET[0], 0
@@ -577,7 +577,7 @@
left_element = self.SelectedElement.EndConnected
if not isinstance(left_element.GetParentBlock(), LD_Coil):
wires.append(self.SelectedElement)
- elif self.SelectedElement and isinstance(self.SelectedElement,Graphic_Group):
+ elif self.SelectedElement and isinstance(self.SelectedElement, Graphic_Group): if False not in [self.IsWire(element) for element in self.SelectedElement.GetElements()]:
for element in self.SelectedElement.GetElements():
@@ -591,7 +591,7 @@
if var.Class != "Output" and var.Type == "BOOL":
dialog.SetVariables(varlist)
- dialog.SetValues({"name":"","type":CONTACT_NORMAL})
+ dialog.SetValues({"name": "", "type": CONTACT_NORMAL}) if dialog.ShowModal() == wx.ID_OK:
values = dialog.GetValues()
points = wires[0].GetSelectedSegmentPoints()
@@ -686,7 +686,7 @@
connectors = block.GetConnectors()
- block_infos = {"lefts":[],"rights":[]}
+ block_infos = {"lefts": [], "rights": []} block_infos.update(connectors)
for connector in block_infos["inputs"]:
for wire, handle in connector.GetWires():
@@ -808,7 +808,7 @@
varlist.append(self.Controler.GetEditedElementName(self.TagName))
dialog.SetVariables(varlist)
- dialog.SetValues({"name":"","type":COIL_NORMAL})
+ dialog.SetValues({"name": "", "type": COIL_NORMAL}) if dialog.ShowModal() == wx.ID_OK:
values = dialog.GetValues()
powerrail = right_elements[0].GetParentBlock()
--- a/editors/Viewer.py Tue Aug 15 12:17:51 2017 +0300
+++ b/editors/Viewer.py Tue Aug 15 15:50:30 2017 +0300
@@ -689,7 +689,7 @@
# Adding a rubberband to Viewer
self.rubberBand = RubberBand(viewer=self)
- self.Editor.SetBackgroundColour(wx.Colour(255,255,255))
+ self.Editor.SetBackgroundColour(wx.Colour(255, 255, 255)) self.Editor.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
self.LastClientSize = None
@@ -2647,7 +2647,7 @@
comment = Comment(self, value, id)
comment.SetPosition(bbox.x, bbox.y)
min_width, min_height = comment.GetMinSize()
- comment.SetSize(*self.GetScaledSize(max(min_width,bbox.width),max(min_height,bbox.height)))
+ comment.SetSize(*self.GetScaledSize(max(min_width, bbox.width), max(min_height, bbox.height))) self.Controler.AddEditedElementComment(self.TagName, id)
self.RefreshCommentModel(comment)
@@ -2703,11 +2703,11 @@
def AddNewStep(self, bbox, initial=False, wire=None):
- "name": self.Controler.GenerateNewName(
- self.TagName, None, "Step%d", 0),
+ "name": self.Controler.GenerateNewName(self.TagName, None, "Step%d", 0),
dialog = SFCStepDialog(self.ParentWindow, self.Controler, self.TagName, initial)
dialog.SetPreviewFont(self.GetFont())
@@ -3010,11 +3010,15 @@
dialog = SFCTransitionDialog(self.ParentWindow, self.Controler, self.TagName, self.GetDrawingMode() == FREEDRAWING_MODE)
dialog.SetPreviewFont(self.GetFont())
dialog.SetMinElementSize(transition.GetSize())
- dialog.SetValues({"type":transition.GetType(),"value":transition.GetCondition(), "priority":transition.GetPriority()})
+ "type": transition.GetType(), + "value": transition.GetCondition(), + "priority": transition.GetPriority() if dialog.ShowModal() == wx.ID_OK:
values = dialog.GetValues()
rect = transition.GetRedrawRect(1, 1)
- transition.SetType(values["type"],values["value"])
+ transition.SetType(values["type"], values["value"]) transition.SetPriority(values["priority"])
rect = rect.Union(transition.GetRedrawRect())
self.RefreshTransitionModel(transition)
--- a/i18n/mki18n.py Tue Aug 15 12:17:51 2017 +0300
+++ b/i18n/mki18n.py Tue Aug 15 15:50:30 2017 +0300
@@ -166,14 +166,14 @@
if applicationDomain is None:
- applicationName = fileBaseOf(applicationDirectoryPath,withPath=0)
+ applicationName = fileBaseOf(applicationDirectoryPath, withPath=0) applicationName = applicationDomain
os.chdir(applicationDirectoryPath)
if not os.path.exists(filelist):
- raise IOError(2,'No module file: ' % filelist)
+ raise IOError(2, 'No module file: ' % filelist) @@ -217,7 +217,7 @@
if applicationDomain is None:
- applicationName = fileBaseOf(applicationDirectoryPath,withPath=0)
+ applicationName = fileBaseOf(applicationDirectoryPath, withPath=0) applicationName = applicationDomain
@@ -233,21 +233,21 @@
if os.path.exists(langPOfileName):
for fileName in listOf_extraPo:
- fileList += ("%s_%s.po " % (fileName,langCode))
+ fileList += ("%s_%s.po " % (fileName, langCode)) cmd = "msgcat -s --no-wrap %s %s > %s.cat" % (langPOfileName, fileList, langPOfileName)
- mo_targetDir = "%s/%s/LC_MESSAGES" % (targetDir,langCode)
- cmd = "msgfmt --output-file=%s/%s.mo %s_%s.po.cat" % (mo_targetDir,applicationName,applicationName,langCode)
+ mo_targetDir = "%s/%s/LC_MESSAGES" % (targetDir, langCode) + cmd = "msgfmt --output-file=%s/%s.mo %s_%s.po.cat" % (mo_targetDir, applicationName, applicationName, langCode) -def makeMO(applicationDirectoryPath,targetDir='./locale',applicationDomain=None, verbose=0, forceEnglish=0):
+def makeMO(applicationDirectoryPath, targetDir='./locale', applicationDomain=None, verbose=0, forceEnglish=0): """Compile the Portable Object files into the Machine Object stored in the right location.
makeMO converts all translated language-specific PO files located inside
@@ -270,7 +270,7 @@
print "Target directory for .mo files is: %s" % targetDir
if applicationDomain is None:
- applicationName = fileBaseOf(applicationDirectoryPath,withPath=0)
+ applicationName = fileBaseOf(applicationDirectoryPath, withPath=0) applicationName = applicationDomain
@@ -284,10 +284,10 @@
langPOfileName = "%s_%s.po" % (applicationName, langCode)
if os.path.exists(langPOfileName):
- mo_targetDir = "%s/%s/LC_MESSAGES" % (targetDir,langCode)
+ mo_targetDir = "%s/%s/LC_MESSAGES" % (targetDir, langCode) if not os.path.exists(mo_targetDir):
- cmd = 'msgfmt --output-file="%s/%s.mo" "%s_%s.po"' % (mo_targetDir,applicationName,applicationName,langCode)
+ cmd = 'msgfmt --output-file="%s/%s.mo" "%s_%s.po"' % (mo_targetDir, applicationName, applicationName, langCode) @@ -330,7 +330,7 @@
print "\n ERROR: %s" % errorMsg
-def fileBaseOf(filename,withPath=0):
+def fileBaseOf(filename, withPath=0): """fileBaseOf(filename,withPath) ---> string
Return base name of filename. The returned string never includes the extension.
@@ -422,7 +422,7 @@
- return thePath.replace(os.sep,'/')
+ return thePath.replace(os.sep, '/') # -----------------------------------------------------------------------------
@@ -446,11 +446,11 @@
option['moTarget'] = None
- optionList,pargs = getopt.getopt(sys.argv[1:],validOptions,validLongOptions)
+ optionList, pargs = getopt.getopt(sys.argv[1:], validOptions, validLongOptions) except getopt.GetoptError, e:
- for (opt,val) in optionList:
+ for (opt, val) in optionList: @@ -476,11 +476,11 @@
print "Application domain used is: '%s'" % option['domain']
- makePO(appDirPath,option['domain'],option['verbose'])
+ makePO(appDirPath, option['domain'], option['verbose']) printUsage(e[1] + '\n You must write a file app.fil that contains the list of all files to parse.')
- makeMO(appDirPath,option['moTarget'],option['domain'],option['verbose'],option['forceEnglish'])
+ makeMO(appDirPath, option['moTarget'], option['domain'], option['verbose'], option['forceEnglish']) --- a/plcopen/definitions.py Tue Aug 15 12:17:51 2017 +0300
+++ b/plcopen/definitions.py Tue Aug 15 15:50:30 2017 +0300
@@ -31,9 +31,9 @@
# Override gettext _ in this module
# since we just want string to be added to dictionnary
# but translation should happen here
-LANGUAGES = ["IL","ST","FBD","LD","SFC"]
+LANGUAGES = ["IL", "ST", "FBD", "LD", "SFC"] LOCATIONDATATYPES = {"X": ["BOOL"],
"B": ["SINT", "USINT", "BYTE", "STRING"],
@@ -45,10 +45,10 @@
# Function Block Types definitions
#-------------------------------------------------------------------------------
-StdTC6Libs = [(_("Standard function blocks"), join(sd, "Standard_Function_Blocks.xml")),
- (_("Additional function blocks"),join(sd, "Additional_Function_Blocks.xml"))]
+StdTC6Libs = [(_("Standard function blocks"), join(sd, "Standard_Function_Blocks.xml")), + (_("Additional function blocks"), join(sd, "Additional_Function_Blocks.xml"))] -StdFuncsCSV = join(sd,"iec_std.csv")
+StdFuncsCSV = join(sd, "iec_std.csv") @@ -109,39 +109,39 @@
- ("SINT", (-2**7, 2**7 - 1)),
- ("INT", (-2**15, 2**15 - 1)),
- ("DINT", (-2**31, 2**31 - 1)),
- ("LINT", (-2**31, 2**31 - 1)),
- ("USINT", (0, 2**8 - 1)),
- ("UINT", (0, 2**16 - 1)),
- ("UDINT", (0, 2**31 - 1)),
- ("ULINT", (0, 2**31 - 1))
+ ("SINT", (-2**7, 2**7 - 1)), + ("INT", (-2**15, 2**15 - 1)), + ("DINT", (-2**31, 2**31 - 1)), + ("LINT", (-2**31, 2**31 - 1)), + ("USINT", (0, 2**8 - 1)), + ("UINT", (0, 2**16 - 1)), + ("UDINT", (0, 2**31 - 1)), + ("ULINT", (0, 2**31 - 1))
# simple type conv are let as C cast
- (("ANY_INT","ANY_BIT"),("ANY_NUM","ANY_BIT")),
- (("ANY_REAL",),("ANY_REAL",)),
+ (("ANY_INT", "ANY_BIT"), ("ANY_NUM", "ANY_BIT")), + (("ANY_REAL",), ("ANY_REAL",)), - (("ANY_REAL",),("ANY_SINT",)),
- (("ANY_REAL",),("ANY_UINT",)),
- (("ANY_REAL",),("ANY_BIT",)),
+ (("ANY_REAL",), ("ANY_SINT",)), + (("ANY_REAL",), ("ANY_UINT",)), + (("ANY_REAL",), ("ANY_BIT",)), - (("ANY_INT","ANY_BIT"),("ANY_DATE","TIME")),
- (("ANY_REAL",),("ANY_DATE","TIME")),
- (("ANY_STRING",), ("ANY_DATE","TIME")),
+ (("ANY_INT", "ANY_BIT"), ("ANY_DATE", "TIME")), + (("ANY_REAL",), ("ANY_DATE", "TIME")), + (("ANY_STRING",), ("ANY_DATE", "TIME")), - (("ANY_DATE","TIME"), ("ANY_REAL",)),
- (("ANY_DATE","TIME"), ("ANY_INT","ANY_NBIT")),
+ (("ANY_DATE", "TIME"), ("ANY_REAL",)), + (("ANY_DATE", "TIME"), ("ANY_INT", "ANY_NBIT")), (("TIME",), ("ANY_STRING",)),
(("DATE",), ("ANY_STRING",)),
- (("TOD",), ("ANY_STRING",)),
- (("DT",), ("ANY_STRING",)),
+ (("TOD",), ("ANY_STRING",)), + (("DT",), ("ANY_STRING",)), - (("BOOL",), ("ANY_STRING",)),
- (("ANY_BIT",), ("ANY_STRING",)),
+ (("BOOL",), ("ANY_STRING",)), + (("ANY_BIT",), ("ANY_STRING",)), (("ANY_REAL",), ("ANY_STRING",)),
(("ANY_SINT",), ("ANY_STRING",)),
(("ANY_UINT",), ("ANY_STRING",)),
@@ -150,17 +150,20 @@
(("ANY_STRING",), ("ANY_BIT",)),
(("ANY_STRING",), ("ANY_SINT",)),
(("ANY_STRING",), ("ANY_UINT",)),
- (("ANY_STRING",), ("ANY_REAL",))],
- (("BYTE",),("USINT",)),
- (("DWORD",),("UDINT",)),
- (("LWORD",),("ULINT",))],
- (("USINT",),("BYTE",)),
- (("UDINT",),("DWORD",)),
- (("ULINT",),("LWORD",))]
+ (("ANY_STRING",), ("ANY_REAL",)) + (("BYTE",), ("USINT",)), + (("WORD",), ("UINT",)), + (("DWORD",), ("UDINT",)), + (("LWORD",), ("ULINT",)) + (("USINT",), ("BYTE",)), + (("UINT",), ("WORD",)), + (("UDINT",), ("DWORD",)), + (("ULINT",), ("LWORD",)) # remove gettext override
--- a/plcopen/plcopen.py Tue Aug 15 12:17:51 2017 +0300
+++ b/plcopen/plcopen.py Tue Aug 15 15:50:30 2017 +0300
@@ -54,7 +54,7 @@
Define in which order var types must be displayed
-VarOrder = ["Local","Temp","Input","Output","InOut","External","Global","Access"]
+VarOrder = ["Local", "Temp", "Input", "Output", "InOut", "External", "Global", "Access"] Define which action qualifier must be associated with a duration
@@ -1692,14 +1692,14 @@
setattr(cls, "setelementExecutionOrder", setelementExecutionOrder)
def appendcontentInstance(self, instance):
- if self.content.getLocalTag() in ["LD","FBD","SFC"]:
+ if self.content.getLocalTag() in ["LD", "FBD", "SFC"]: self.content.appendcontent(instance)
raise TypeError, _("%s body don't have instances!") % self.content.getLocalTag()
setattr(cls, "appendcontentInstance", appendcontentInstance)
def getcontentInstances(self):
- if self.content.getLocalTag() in ["LD","FBD","SFC"]:
+ if self.content.getLocalTag() in ["LD", "FBD", "SFC"]: return self.content.getcontent()
raise TypeError, _("%s body don't have instances!") % self.content.getLocalTag()
@@ -1708,7 +1708,7 @@
instance_by_id_xpath = PLCOpen_XPath("*[@localId=$localId]")
instance_by_name_xpath = PLCOpen_XPath("ppx:block[@instanceName=$name]")
def getcontentInstance(self, local_id):
- if self.content.getLocalTag() in ["LD","FBD","SFC"]:
+ if self.content.getLocalTag() in ["LD", "FBD", "SFC"]: instance = instance_by_id_xpath(self.content, localId=local_id)
@@ -1718,7 +1718,7 @@
setattr(cls, "getcontentInstance", getcontentInstance)
def getcontentInstancesIds(self):
- if self.content.getLocalTag() in ["LD","FBD","SFC"]:
+ if self.content.getLocalTag() in ["LD", "FBD", "SFC"]: return OrderedDict([(instance.getlocalId(), True)
for instance in self.content])
@@ -1726,7 +1726,7 @@
setattr(cls, "getcontentInstancesIds", getcontentInstancesIds)
def getcontentInstanceByName(self, name):
- if self.content.getLocalTag() in ["LD","FBD","SFC"]:
+ if self.content.getLocalTag() in ["LD", "FBD", "SFC"]: instance = instance_by_name_xpath(self.content)
@@ -1736,7 +1736,7 @@
setattr(cls, "getcontentInstanceByName", getcontentInstanceByName)
def removecontentInstance(self, local_id):
- if self.content.getLocalTag() in ["LD","FBD","SFC"]:
+ if self.content.getLocalTag() in ["LD", "FBD", "SFC"]: instance = instance_by_id_xpath(self.content, localId=local_id)
self.content.remove(instance[0])
@@ -1747,21 +1747,21 @@
setattr(cls, "removecontentInstance", removecontentInstance)
- if self.content.getLocalTag() in ["IL","ST"]:
+ if self.content.getLocalTag() in ["IL", "ST"]: self.content.setanyText(text)
raise TypeError, _("%s body don't have text!") % self.content.getLocalTag()
setattr(cls, "settext", settext)
- if self.content.getLocalTag() in ["IL","ST"]:
+ if self.content.getLocalTag() in ["IL", "ST"]: return self.content.getanyText()
raise TypeError, _("%s body don't have text!") % self.content.getLocalTag()
setattr(cls, "gettext", gettext)
def hasblock(self, block_type):
- if self.content.getLocalTag() in ["IL","ST"]:
+ if self.content.getLocalTag() in ["IL", "ST"]: return self.content.hasblock(block_type)
raise TypeError, _("%s body don't have text!") % self.content.getLocalTag()
@@ -2365,7 +2365,7 @@
for position in self.position:
- points.append((position.getx(),position.gety()))
+ points.append((position.getx(), position.gety())) setattr(cls, "getpoints", getpoints)
--- a/plcopen/structures.py Tue Aug 15 12:17:51 2017 +0300
+++ b/plcopen/structures.py Tue Aug 15 15:50:30 2017 +0300
@@ -100,7 +100,7 @@
take a .csv file and translate it it a "csv_table"
- return [ map(string.strip,line.split(';')) for line in file.xreadlines()]
+ return [ map(string.strip, line.split(';')) for line in file.xreadlines()] def find_section(section_name, table):
@@ -121,7 +121,7 @@
variables = find_section("Standard_functions_variables_types", table)
standard_funtions_input_variables = {}
variable_from_csv = dict([(champ, val) for champ, val in zip(variables, fields[1:]) if champ!=''])
@@ -135,7 +135,7 @@
in : "(ANY_NUM, ANY_NUM)" and { ParameterName: Type, ...}
return [("IN1","ANY_NUM","none"),("IN2","ANY_NUM","none")]
- decl = str_decl.replace('(','').replace(')','').replace(' ','').split(',')
+ decl = str_decl.replace('(', '').replace(')', '').replace(' ', '').split(',') len_of_not_predifined_variable = len([True for param_type in decl if param_type not in variables])
@@ -170,15 +170,15 @@
variables = get_standard_funtions_input_variables(table)
- fonctions = find_section("Standard_functions_type",table)
+ fonctions = find_section("Standard_functions_type", table) Standard_Functions_Decl = []
- "extensible": lambda x: {"yes":True, "no":False}[x],
- "inputs": lambda x:csv_input_translate(x,variables,baseinputnumber),
- "outputs":lambda x:[("OUT",x,"none")]}
+ "extensible": lambda x: {"yes": True, "no": False}[x], + "inputs": lambda x: csv_input_translate(x, variables, baseinputnumber), + "outputs": lambda x: [("OUT", x, "none")]} @@ -194,7 +194,7 @@
Function_decl = dict([(champ, val) for champ, val in zip(fonctions, fields[1:]) if champ])
- baseinputnumber = int(Function_decl.get("baseinputnumber",1))
+ baseinputnumber = int(Function_decl.get("baseinputnumber", 1)) Function_decl["baseinputnumber"] = baseinputnumber
for param, value in Function_decl.iteritems():
@@ -242,12 +242,12 @@
# apply filter given in "filter" column
filter_name = Function_decl["filter"]
- for (InTypes, OutTypes) in ANY_TO_ANY_FILTERS.get(filter_name,[]):
- outs = reduce(lambda a,b: a or b,
+ for (InTypes, OutTypes) in ANY_TO_ANY_FILTERS.get(filter_name, []): + outs = reduce(lambda a, b: a or b, map(lambda testtype: IsOfType(
Function_decl["outputs"][0][1],
- inps = reduce(lambda a,b: a or b,
+ inps = reduce(lambda a, b: a or b, map(lambda testtype: IsOfType(
Function_decl["inputs"][0][1],
@@ -280,7 +280,7 @@
for input in desc["inputs"]]),
", ".join(["%s:%s" % (output[1], output[0])
for output in desc["outputs"]])))
- BlkLst = StdBlckDct.setdefault(desc["name"],[])
+ BlkLst = StdBlckDct.setdefault(desc["name"], []) BlkLst.append((section["name"], desc))
#-------------------------------------------------------------------------------
--- a/runtime/PLCObject.py Tue Aug 15 12:17:51 2017 +0300
+++ b/runtime/PLCObject.py Tue Aug 15 15:50:30 2017 +0300
@@ -47,8 +47,8 @@
@@ -128,16 +128,16 @@
self._log_read_buffer[sz] = '\x00'
- return self._log_read_buffer.value,tick.value,tv_sec.value,tv_nsec.value
+ return self._log_read_buffer.value, tick.value, tv_sec.value, tv_nsec.value elif self._loading_error is not None and level==0:
- return self._loading_error,0,0,0
+ return self._loading_error, 0, 0, 0 def _GetMD5FileName(self):
return os.path.join(self.workingdir, "lasttransferedPLC.md5")
def _GetLibFileName(self):
- return os.path.join(self.workingdir,self.CurrentPLCFilename)
+ return os.path.join(self.workingdir, self.CurrentPLCFilename) @@ -241,22 +241,22 @@
self.PLClibraryLock.acquire()
# Forget all refs to library
- self._startPLC = lambda x,y:None
- self._stopPLC = lambda:None
- self._ResetDebugVariables = lambda:None
- self._RegisterDebugVariable = lambda x, y:None
- self._IterDebugData = lambda x,y:None
- self._FreeDebugData = lambda:None
- self._GetDebugData = lambda:-1
- self._suspendDebug = lambda x:-1
- self._resumeDebug = lambda:None
- self._PythonIterator = lambda:""
+ self._startPLC = lambda x, y: None + self._stopPLC = lambda: None + self._ResetDebugVariables = lambda: None + self._RegisterDebugVariable = lambda x, y: None + self._IterDebugData = lambda x, y: None + self._FreeDebugData = lambda: None + self._GetDebugData = lambda: -1 + self._suspendDebug = lambda x: -1 + self._resumeDebug = lambda: None + self._PythonIterator = lambda: "" - self._LogMessage = lambda l,m,s:PLCprint("OFF LOG :"+m)
+ self._LogMessage = lambda l, m, s: PLCprint("OFF LOG :"+m) self._GetLogMessage = None
self.PLClibraryHandle = None
# Unload library explicitely
- if getattr(self,"_PLClibraryHandle",None) is not None:
+ if getattr(self, "_PLClibraryHandle", None) is not None: dlclose(self._PLClibraryHandle)
self._PLClibraryHandle = None
@@ -269,9 +269,9 @@
runtime python files, loaded when new PLC uploaded
for method in self.python_runtime_vars.get("_runtime_%s" % methodname, []):
- res,exp = self.evaluator(method)
+ res, exp = self.evaluator(method) - self.LogMessage(0,'\n'.join(traceback.format_exception(*exp)))
+ self.LogMessage(0, '\n'.join(traceback.format_exception(*exp))) def PythonRuntimeInit(self):
MethodNames = ["init", "start", "stop", "cleanup"]
@@ -292,7 +292,7 @@
t = self.python_runtime_vars["_"+name+"_ctype"]
raise KeyError("Try to set unknown shared global variable : %s" % name)
- v = self.python_runtime_vars["_"+name+"_pack"](t,value)
+ v = self.python_runtime_vars["_"+name+"_pack"](t, value) self.python_runtime_vars["_PySafeSetPLCGlob_"+name](ctypes.byref(v))
self.python_runtime_vars.update({
@@ -317,7 +317,7 @@
self.python_runtime_vars["_runtime_%s" % methodname].append(method)
- self.LogMessage(0,traceback.format_exc())
+ self.LogMessage(0, traceback.format_exc()) self.PythonRuntimeCall("init")
@@ -332,38 +332,38 @@
def PythonThreadProc(self):
- res,cmd,blkid = "None","None",ctypes.c_void_p()
+ res, cmd, blkid = "None", "None", ctypes.c_void_p() # print "_PythonIterator(", res, ")",
- cmd = self._PythonIterator(res,blkid)
+ cmd = self._PythonIterator(res, blkid) # print " -> ", cmd, blkid
self.python_runtime_vars["FBID"]=FBID
- ccmd,AST =compile_cache.get(FBID, (None,None))
+ ccmd, AST =compile_cache.get(FBID, (None, None)) if ccmd is None or ccmd!=cmd:
AST = compile(cmd, '<plc>', 'eval')
- compile_cache[FBID]=(cmd,AST)
- result,exp = self.evaluator(eval,AST,self.python_runtime_vars)
+ compile_cache[FBID]=(cmd, AST) + result, exp = self.evaluator(eval, AST, self.python_runtime_vars) res = "#EXCEPTION : "+str(exp[1])
- self.LogMessage(1,('PyEval@0x%x(Code="%s") Exception "%s"') % (FBID,cmd,
+ self.LogMessage(1, ('PyEval@0x%x(Code="%s") Exception "%s"') % (FBID, cmd, '\n'.join(traceback.format_exception(*exp))))
self.python_runtime_vars["FBID"]=None
res = "#EXCEPTION : "+str(e)
- self.LogMessage(1,('PyEval@0x%x(Code="%s") Exception "%s"') % (FBID,cmd,str(e)))
+ self.LogMessage(1, ('PyEval@0x%x(Code="%s") Exception "%s"') % (FBID, cmd, str(e))) if self.CurrentPLCFilename is not None and self.PLCStatus == "Stopped":
c_argv = ctypes.c_char_p * len(self.argv)
- res = self._startPLC(len(self.argv),c_argv(*self.argv))
+ res = self._startPLC(len(self.argv), c_argv(*self.argv)) self.PLCStatus = "Started"
@@ -374,7 +374,7 @@
self.LogMessage("PLC started")
- self.LogMessage(0,_("Problem starting PLC : error %d" % res))
+ self.LogMessage(0, _("Problem starting PLC : error %d" % res)) self.PLCStatus = "Broken"
@@ -396,22 +396,22 @@
self.daemon.shutdown(True)
- os.execv(sys.executable,[sys.executable]+sys.argv[:])
+ os.execv(sys.executable, [sys.executable]+sys.argv[:]) # respawn python interpreter
- Timer(0.1,self._Reload).start()
+ Timer(0.1, self._Reload).start() - return self.PLCStatus, map(self.GetLogCount,xrange(LogLevelsCount))
+ return self.PLCStatus, map(self.GetLogCount, xrange(LogLevelsCount)) def NewPLC(self, md5sum, data, extrafiles):
if self.PLCStatus in ["Stopped", "Empty", "Broken"]:
NewFileName = md5sum + lib_ext
- extra_files_log = os.path.join(self.workingdir,"extra_files.txt")
+ extra_files_log = os.path.join(self.workingdir, "extra_files.txt") @@ -431,7 +431,7 @@
- open(os.path.join(self.workingdir,NewFileName),
+ open(os.path.join(self.workingdir, NewFileName), # Store new PLC filename based on md5 key
@@ -439,8 +439,8 @@
log = file(extra_files_log, "w")
- for fname,fdata in extrafiles:
- fpath = os.path.join(self.workingdir,fname)
+ for fname, fdata in extrafiles: + fpath = os.path.join(self.workingdir, fname) open(fpath, "wb").write(fdata)
@@ -480,12 +480,12 @@
if self._suspendDebug(False) == 0:
# keep a copy of requested idx
self._ResetDebugVariables()
- for idx,iectype,force in idxs:
+ for idx, iectype, force in idxs: - c_type,unpack_func, pack_func = \
+ c_type, unpack_func, pack_func = \ TypeTranslator.get(iectype,
- force = ctypes.byref(pack_func(c_type,force))
+ force = ctypes.byref(pack_func(c_type, force)) self._RegisterDebugVariable(idx, force)
--- a/xmlclass/xsdschema.py Tue Aug 15 12:17:51 2017 +0300
+++ b/xmlclass/xsdschema.py Tue Aug 15 15:50:30 2017 +0300
@@ -509,7 +509,7 @@
basetypeinfos = factory.FindSchemaElement(base)
if not isinstance(basetypeinfos, (UnicodeType, StringType)) and basetypeinfos["type"] == COMPLEXTYPE:
- attrnames = dict(map(lambda x:(x["name"], True), basetypeinfos["attributes"]))
+ attrnames = dict(map(lambda x: (x["name"], True), basetypeinfos["attributes"])) if element["type"] == ATTRIBUTE:
@@ -2210,7 +2210,7 @@
- "extract": GenerateIntegerExtraction(minInclusive=-2**63,maxExclusive=2**63),
+ "extract": GenerateIntegerExtraction(minInclusive=-2**63, maxExclusive=2**63), "facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
@@ -2220,7 +2220,7 @@
"basename": "unsignedLong",
- "extract": GenerateIntegerExtraction(minInclusive=0,maxExclusive=2**64),
+ "extract": GenerateIntegerExtraction(minInclusive=0, maxExclusive=2**64), "facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
@@ -2230,7 +2230,7 @@
- "extract": GenerateIntegerExtraction(minInclusive=-2**31,maxExclusive=2**31),
+ "extract": GenerateIntegerExtraction(minInclusive=-2**31, maxExclusive=2**31), "facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
@@ -2240,7 +2240,7 @@
"basename": "unsignedInt",
- "extract": GenerateIntegerExtraction(minInclusive=0,maxExclusive=2**32),
+ "extract": GenerateIntegerExtraction(minInclusive=0, maxExclusive=2**32), "facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
@@ -2250,7 +2250,7 @@
- "extract": GenerateIntegerExtraction(minInclusive=-2**15,maxExclusive=2**15),
+ "extract": GenerateIntegerExtraction(minInclusive=-2**15, maxExclusive=2**15), "facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
@@ -2260,7 +2260,7 @@
"basename": "unsignedShort",
- "extract": GenerateIntegerExtraction(minInclusive=0,maxExclusive=2**16),
+ "extract": GenerateIntegerExtraction(minInclusive=0, maxExclusive=2**16), "facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
@@ -2270,7 +2270,7 @@
- "extract": GenerateIntegerExtraction(minInclusive=-2**7,maxExclusive=2**7),
+ "extract": GenerateIntegerExtraction(minInclusive=-2**7, maxExclusive=2**7), "facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
@@ -2280,7 +2280,7 @@
"basename": "unsignedByte",
- "extract": GenerateIntegerExtraction(minInclusive=0,maxExclusive=2**8),
+ "extract": GenerateIntegerExtraction(minInclusive=0, maxExclusive=2**8), "facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
@@ -2322,7 +2322,7 @@
"facets": GenerateDictFacets(["pattern", "whiteSpace"]),
- "generate": GenerateSimpleTypeXMLText(lambda x:{True: "true", False: "false"}[x]),
+ "generate": GenerateSimpleTypeXMLText(lambda x: {True: "true", False: "false"}[x]), "initial": lambda: False,
"check": lambda x: isinstance(x, BooleanType)
@@ -2343,7 +2343,7 @@
"generate": GenerateSimpleTypeXMLText(datetime.datetime.isoformat),
- "initial": lambda: datetime.datetime(1,1,1,0,0,0,0),
+ "initial": lambda: datetime.datetime(1, 1, 1, 0, 0, 0, 0), "check": lambda x: isinstance(x, datetime.datetime)
@@ -2353,7 +2353,7 @@
"generate": GenerateSimpleTypeXMLText(datetime.date.isoformat),
- "initial": lambda: datetime.date(1,1,1),
+ "initial": lambda: datetime.date(1, 1, 1), "check": lambda x: isinstance(x, datetime.date)
@@ -2363,7 +2363,7 @@
"generate": GenerateSimpleTypeXMLText(datetime.time.isoformat),
- "initial": lambda: datetime.time(0,0,0,0),
+ "initial": lambda: datetime.time(0, 0, 0, 0), "check": lambda x: isinstance(x, datetime.time)
@@ -2548,5 +2548,5 @@
- "anyType": {"type": COMPLEXTYPE, "extract": lambda x:None},
+ "anyType": {"type": COMPLEXTYPE, "extract": lambda x: None},