--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/LPCBeremiz.py Mon Nov 30 10:13:36 2009 +0100
@@ -0,0 +1,989 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+__version__ = "$Revision$"
+
+import os, sys, getopt, wx, tempfile
+from types import TupleType, StringType, UnicodeType
+
+CWD = os.path.split(os.path.realpath(__file__))[0]
+
+def Bpath(*args):
+ return os.path.join(CWD,*args)
+
+if __name__ == '__main__':
+ def usage():
+ print "\nUsage of LPCBeremiz.py :"
+ print "\n %s [Projectpath] [Buildpath]\n"%sys.argv[0]
+
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], "h", ["help"])
+ except getopt.GetoptError:
+ # print help information and exit:
+ usage()
+ sys.exit(2)
+
+ for o, a in opts:
+ if o in ("-h", "--help"):
+ usage()
+ sys.exit()
+
+ if len(args) > 2:
+ usage()
+ sys.exit()
+ elif len(args) == 1:
+ projectOpen = args[0]
+ buildpath = None
+ elif len(args) == 2:
+ projectOpen = args[0]
+ buildpath = args[1]
+ else:
+ projectOpen = None
+ buildpath = None
+
+class PseudoLocale:
+ LocaleDirs = []
+ Domains = []
+
+ def AddCatalogLookupPathPrefix(self, localedir):
+ self.LocaleDirs.append(localedir)
+
+ def AddCatalog(self, domain):
+ self.Domains.append(domain)
+
+# Import module for internationalization
+import gettext
+import __builtin__
+
+# Define locale for wx
+__builtin__.__dict__['loc'] = PseudoLocale()
+
+if __name__ == '__main__':
+ __builtin__.__dict__['_'] = wx.GetTranslation#unicode_translation
+
+from Beremiz import *
+from plugger import PluginsRoot, PlugTemplate, opjimg
+from plcopen.structures import LOCATIONDATATYPES
+from PLCControler import LOCATION_PLUGIN, LOCATION_MODULE, LOCATION_GROUP,\
+ LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY
+from PLCOpenEditor import IDEFrame
+
+#-------------------------------------------------------------------------------
+# LPCModule Class
+#-------------------------------------------------------------------------------
+
+def _GetModuleChildren(module):
+ children = []
+ for child in module["children"]:
+ if child["type"] == LOCATION_GROUP:
+ children.extend(child["children"])
+ else:
+ children.append(child)
+ return children
+
+def _GetLastModuleGroup(module):
+ group = module
+ for child in module["children"]:
+ if child["type"] == LOCATION_GROUP:
+ group = child
+ return group["children"]
+
+def _GetModuleBySomething(module, something, toks):
+ for child in _GetModuleChildren(module):
+ if child.get(something) == toks[0]:
+ if len(toks) > 1:
+ return _GetModuleBySomething(child, something, toks[1:])
+ return child
+ return None
+
+def _GetModuleVariable(module, location):
+ for child in _GetModuleChildren(module):
+ if child["location"] == location:
+ return child
+ return None
+
+def _RemoveModuleChild(module, child):
+ if child in module["children"]:
+ module["children"].remove(child)
+ else:
+ for group in module["children"]:
+ if group["type"] == LOCATION_GROUP and child in group["children"]:
+ group["children"].remove(child)
+
+LOCATION_TYPES = {"I": LOCATION_VAR_INPUT,
+ "Q": LOCATION_VAR_OUTPUT,
+ "M": LOCATION_VAR_MEMORY}
+
+LOCATION_DIRS = dict([(dir, size) for size, dir in LOCATION_TYPES.iteritems()])
+
+LOCATION_SIZES = {}
+for size, types in LOCATIONDATATYPES.iteritems():
+ for type in types:
+ LOCATION_SIZES[type] = size
+
+BUS_TEXT = """/* Code generated by LPCBus plugin */
+
+/* LPCBus plugin includes */
+#include "app_glue.h"
+#ifdef _WINDOWS_H
+ #include "iec_types.h"
+#else
+ #include "iec_std_lib.h"
+#endif
+
+%(declare_code)s
+
+/* LPCBus plugin user variables definition */
+%(var_decl)s
+
+/* LPCBus plugin functions */
+int __init_%(location_str)s(int argc,char **argv)
+{
+ return 0;
+}
+
+void __cleanup_%(location_str)s(void)
+{
+}
+
+void __retrieve_%(location_str)s(void)
+{
+ %(retrieve_code)s
+}
+
+void __publish_%(location_str)s(void)
+{
+ %(publish_code)s
+}
+"""
+
+class LPCBus(object):
+
+ def __init__(self):
+ self.VariableLocationTree = []
+ self.ResetUsedLocations()
+ self.Icon = None
+
+ def __getitem__(self, key):
+ if key == "children":
+ return self.VariableLocationTree
+ raise KeyError, "Only 'children' key is available"
+
+ def SetIcon(self, icon):
+ self.Icon = icon
+
+ def _GetChildBySomething(self, something, toks):
+ return _GetModuleBySomething({"children" : self.VariableLocationTree}, something, toks)
+
+ def GetBaseTypes(self):
+ return self.GetPlugRoot().GetBaseTypes()
+
+ def GetSizeOfType(self, type):
+ return LOCATION_SIZES[self.GetPlugRoot().GetBaseType(type)]
+
+ def _GetVariableLocationTree(self, current_location, infos):
+ if infos["type"] == LOCATION_MODULE:
+ location = current_location + (infos["IEC_Channel"],)
+ return {"name": infos["name"],
+ "type": infos["type"],
+ "location": ".".join(map(str, location + ("x",))),
+ "icon": infos["icon"],
+ "children": [self._GetVariableLocationTree(location, child) for child in infos["children"]]}
+ elif infos["type"] == LOCATION_GROUP:
+ return {"name": infos["name"],
+ "type": infos["type"],
+ "location": "",
+ "icon": infos["icon"],
+ "children": [self._GetVariableLocationTree(current_location, child) for child in infos["children"]]}
+ else:
+ size = self.GetSizeOfType(infos["IEC_type"])
+ location = "%" + LOCATION_DIRS[infos["type"]] + size + ".".join(map(str, current_location + infos["location"]))
+ return {"name": infos["name"],
+ "type": infos["type"],
+ "size": size,
+ "IEC_type": infos["IEC_type"],
+ "location": location,
+ "description": infos["description"],
+ "children": []}
+
+ def GetVariableLocationTree(self):
+ return {"name": self.BaseParams.getName(),
+ "type": LOCATION_PLUGIN,
+ "location": self.GetFullIEC_Channel(),
+ "icon": self.Icon,
+ "children": [self._GetVariableLocationTree(self.GetCurrentLocation(), child)
+ for child in self.VariableLocationTree]}
+
+ def PlugTestModified(self):
+ return False
+
+ def PlugMakeDir(self):
+ pass
+
+ def PlugRequestSave(self):
+ return None
+
+ def ResetUsedLocations(self):
+ self.UsedLocations = {}
+
+ def _AddUsedLocation(self, parent, location):
+ num = location.pop(0)
+ if not parent.has_key(num):
+ parent[num] = {"used": False, "children": {}}
+ if len(location) > 0:
+ self._AddUsedLocation(parent[num]["children"], location)
+ else:
+ parent[num]["used"] = True
+
+ def AddUsedLocation(self, location):
+ if len(location) > 0:
+ self._AddUsedLocation(self.UsedLocations, list(location))
+
+ def _CheckLocationConflicts(self, parent, location):
+ num = location.pop(0)
+ if not parent.has_key(num):
+ return False
+ if len(location) > 0:
+ if parent[num]["used"]:
+ return True
+ return self._CheckLocationConflicts(parent[num]["children"], location)
+ elif len(parent[num]["children"]) > 0:
+ return True
+ return False
+
+ def CheckLocationConflicts(self, location):
+ if len(location) > 0:
+ return self._CheckLocationConflicts(self.UsedLocations, list(location))
+ return False
+
+ def PlugGenerate_C(self, buildpath, locations):
+ """
+ Generate C code
+ @param current_location: Tupple containing plugin IEC location : %I0.0.4.5 => (0,0,4,5)
+ @param locations: List of complete variables locations \
+ [{"IEC_TYPE" : the IEC type (i.e. "INT", "STRING", ...)
+ "NAME" : name of the variable (generally "__IW0_1_2" style)
+ "DIR" : direction "Q","I" or "M"
+ "SIZE" : size "X", "B", "W", "D", "L"
+ "LOC" : tuple of interger for IEC location (0,1,2,...)
+ }, ...]
+ @return: [(C_file_name, CFLAGS),...] , LDFLAGS_TO_APPEND
+ """
+ current_location = self.GetCurrentLocation()
+ # define a unique name for the generated C file
+ location_str = "_".join(map(str, current_location))
+
+ code_str = {"location_str": location_str,
+ "var_decl": "",
+ "declare_code": "",
+ "retrieve_code": "",
+ "publish_code": "",
+ }
+
+ # Adding variables
+ vars = []
+ self.ResetUsedLocations()
+ for location in locations:
+ loc = location["LOC"][len(current_location):]
+ group = next = self
+ i = 0
+ while next is not None and i < len(loc):
+ next = self._GetChildBySomething("IEC_Channel", loc[:i + 1])
+ if next is not None:
+ i += 1
+ group = next
+ var_loc = loc[i:]
+ for variable in group["children"]:
+ if variable["location"] == var_loc:
+ if location["DIR"] != LOCATION_DIRS[variable["type"]]:
+ raise Exception, "Direction conflict in variable definition"
+ if location["IEC_TYPE"] != variable["IEC_type"]:
+ raise Exception, "Type conflict in variable definition"
+ if location["DIR"] == "Q":
+ if self.CheckLocationConflicts(location["LOC"]):
+ raise Exception, "BYTE and BIT from the same BYTE can't be used together"
+ self.AddUsedLocation(location["LOC"])
+ vars.append({"location": location["NAME"],
+ "Type": variable["IEC_type"],
+ "Declare": variable["declare"],
+ "Retrieve": variable["retrieve"],
+ "Publish": variable["publish"],
+ })
+ break
+ base_types = self.GetPlugRoot().GetBaseTypes()
+ for var in vars:
+ prefix = ""
+ if var["Type"] in base_types:
+ prefix = "IEC_"
+ code_str["var_decl"] += "%s%s beremiz%s;\n"%(prefix, var["Type"], var["location"])
+ code_str["var_decl"] += "%s%s *%s = &beremiz%s;\n"%(prefix, var["Type"], var["location"], var["location"])
+ if var["Declare"] != "":
+ code_str["declare_code"] += var["Declare"] + "\n"
+ if var["Retrieve"] != "":
+ code_str["retrieve_code"] += var["Retrieve"] % ("*" + var["location"]) + "\n"
+ if var["Publish"] != "":
+ code_str["publish_code"] += var["Publish"] % ("*" + var["location"]) + "\n"
+
+ Gen_Module_path = os.path.join(buildpath, "Module_%s.c"%location_str)
+ module = open(Gen_Module_path,'w')
+ module.write(BUS_TEXT % code_str)
+ module.close()
+
+ matiec_flags = '"-I%s"'%os.path.abspath(self.GetPlugRoot().GetIECLibPath())
+ return [(Gen_Module_path, matiec_flags)],"",True
+
+#-------------------------------------------------------------------------------
+# LPCPluginsRoot Class
+#-------------------------------------------------------------------------------
+
+def mycopytree(src, dst):
+ """
+ Copy content of a directory to an other, omit hidden files
+ @param src: source directory
+ @param dst: destination directory
+ """
+ for i in os.listdir(src):
+ if not i.startswith('.'):
+ srcpath = os.path.join(src,i)
+ dstpath = os.path.join(dst,i)
+ if os.path.isdir(srcpath):
+ os.makedirs(dstpath)
+ mycopytree(srcpath, dstpath)
+ elif os.path.isfile(srcpath):
+ shutil.copy2(srcpath, dstpath)
+
+class LPCPluginsRoot(PluginsRoot):
+
+ PlugChildsTypes = [("LPCBus", LPCBus, "LPC bus")]
+
+ PluginMethods = [
+ {"bitmap" : opjimg("Build"),
+ "name" : _("Build"),
+ "tooltip" : _("Build project into build folder"),
+ "method" : "_build"},
+ {"bitmap" : opjimg("Clean"),
+ "name" : _("Clean"),
+ "enabled" : False,
+ "tooltip" : _("Clean project build folder"),
+ "method" : "_Clean"},
+ ]
+
+ def GetProjectName(self):
+ return self.Project.getname()
+
+ def GetDefaultTarget(self):
+ target = self.Classes["BeremizRoot_TargetType"]()
+ target_value = self.Classes["TargetType_Makefile"]()
+ target_value.setBuildPath(self.BuildPath)
+ target.setcontent({"name": "Makefile", "value": target_value})
+ return target
+
+ def SetProjectName(self, name):
+ return self.Project.setname(name)
+
+ def LoadProject(self, ProjectPath, BuildPath=None):
+ """
+ Load a project XML file
+ @param ProjectPath: path of the project xml file
+ """
+ # Load PLCOpen file
+ result = self.OpenXMLFile(ProjectPath)
+ if result:
+ return result
+ # Change XSD into class members
+ self._AddParamsMembers()
+ self.PluggedChilds = {}
+ # Keep track of the root plugin (i.e. project path)
+ self.ProjectPath = ProjectPath
+
+ self.BuildPath = tempfile.mkdtemp()
+ if BuildPath is not None:
+ mycopytree(BuildPath, self.BuildPath)
+
+ self.RefreshPluginsBlockLists()
+
+ if os.path.exists(self._getBuildPath()):
+ self.EnableMethod("_Clean", True)
+
+ def SaveProject(self):
+ self.SaveXMLFile(self.ProjectPath)
+
+#-------------------------------------------------------------------------------
+# LPCBeremiz Class
+#-------------------------------------------------------------------------------
+
+class LPCBeremiz(Beremiz):
+
+ def _init_coll_FileMenu_Items(self, parent):
+ AppendMenu(parent, help='', id=wx.ID_SAVE,
+ kind=wx.ITEM_NORMAL, text=_(u'Save\tCTRL+S'))
+ AppendMenu(parent, help='', id=wx.ID_CLOSE,
+ kind=wx.ITEM_NORMAL, text=_(u'Close Tab\tCTRL+W'))
+ parent.AppendSeparator()
+ AppendMenu(parent, help='', id=wx.ID_PAGE_SETUP,
+ kind=wx.ITEM_NORMAL, text=_(u'Page Setup'))
+ AppendMenu(parent, help='', id=wx.ID_PREVIEW,
+ kind=wx.ITEM_NORMAL, text=_(u'Preview'))
+ AppendMenu(parent, help='', id=wx.ID_PRINT,
+ kind=wx.ITEM_NORMAL, text=_(u'Print'))
+ parent.AppendSeparator()
+ AppendMenu(parent, help='', id=wx.ID_PROPERTIES,
+ kind=wx.ITEM_NORMAL, text=_(u'Properties'))
+ parent.AppendSeparator()
+ AppendMenu(parent, help='', id=wx.ID_EXIT,
+ kind=wx.ITEM_NORMAL, text=_(u'Quit\tCTRL+Q'))
+
+ self.Bind(wx.EVT_MENU, self.OnSaveProjectMenu, id=wx.ID_SAVE)
+ self.Bind(wx.EVT_MENU, self.OnCloseTabMenu, id=wx.ID_CLOSE)
+ self.Bind(wx.EVT_MENU, self.OnPageSetupMenu, id=wx.ID_PAGE_SETUP)
+ self.Bind(wx.EVT_MENU, self.OnPreviewMenu, id=wx.ID_PREVIEW)
+ self.Bind(wx.EVT_MENU, self.OnPrintMenu, id=wx.ID_PRINT)
+ self.Bind(wx.EVT_MENU, self.OnPropertiesMenu, id=wx.ID_PROPERTIES)
+ self.Bind(wx.EVT_MENU, self.OnQuitMenu, id=wx.ID_EXIT)
+
+ def _init_ctrls(self, prnt):
+ IDEFrame._init_ctrls(self, prnt)
+
+ self.Bind(wx.EVT_MENU, self.OnOpenWidgetInspector, id=ID_BEREMIZINSPECTOR)
+ accel = wx.AcceleratorTable([wx.AcceleratorEntry(wx.ACCEL_CTRL|wx.ACCEL_ALT, ord('I'), ID_BEREMIZINSPECTOR)])
+ self.SetAcceleratorTable(accel)
+
+ self.PLCConfig = wx.ScrolledWindow(id=ID_BEREMIZPLCCONFIG,
+ name='PLCConfig', parent=self.LeftNoteBook, pos=wx.Point(0, 0),
+ size=wx.Size(-1, -1), style=wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER|wx.HSCROLL|wx.VSCROLL)
+ self.PLCConfig.SetBackgroundColour(wx.WHITE)
+ self.PLCConfig.Bind(wx.EVT_LEFT_DOWN, self.OnPanelLeftDown)
+ self.PLCConfig.Bind(wx.EVT_SIZE, self.OnMoveWindow)
+ self.LeftNoteBook.InsertPage(0, self.PLCConfig, _("Topology"), True)
+
+ self.LogConsole = wx.TextCtrl(id=ID_BEREMIZLOGCONSOLE, value='',
+ name='LogConsole', parent=self.BottomNoteBook, pos=wx.Point(0, 0),
+ size=wx.Size(0, 0), style=wx.TE_MULTILINE|wx.TE_RICH2)
+ self.LogConsole.Bind(wx.EVT_LEFT_DCLICK, self.OnLogConsoleDClick)
+ self.BottomNoteBook.AddPage(self.LogConsole, _("Log Console"))
+
+ self._init_beremiz_sizers()
+
+ def OnCloseFrame(self, event):
+ global frame, lpcberemiz_cmd
+ frame = None
+ self.PluginRoot.ResetAppFrame(lpcberemiz_cmd.Log)
+
+ self.KillLocalRuntime()
+
+ event.Skip()
+
+ def RefreshFileMenu(self):
+ if self.PluginRoot is not None:
+ selected = self.TabsOpened.GetSelection()
+ if selected >= 0:
+ graphic_viewer = isinstance(self.TabsOpened.GetPage(selected), Viewer)
+ else:
+ graphic_viewer = False
+ if self.TabsOpened.GetPageCount() > 0:
+ self.FileMenu.Enable(wx.ID_CLOSE, True)
+ if graphic_viewer:
+ self.FileMenu.Enable(wx.ID_PREVIEW, True)
+ self.FileMenu.Enable(wx.ID_PRINT, True)
+ else:
+ self.FileMenu.Enable(wx.ID_PREVIEW, False)
+ self.FileMenu.Enable(wx.ID_PRINT, False)
+ else:
+ self.FileMenu.Enable(wx.ID_CLOSE, False)
+ self.FileMenu.Enable(wx.ID_PREVIEW, False)
+ self.FileMenu.Enable(wx.ID_PRINT, False)
+ self.FileMenu.Enable(wx.ID_PAGE_SETUP, True)
+ self.FileMenu.Enable(wx.ID_SAVE, True)
+ self.FileMenu.Enable(wx.ID_PROPERTIES, True)
+ else:
+ self.FileMenu.Enable(wx.ID_CLOSE, False)
+ self.FileMenu.Enable(wx.ID_PAGE_SETUP, False)
+ self.FileMenu.Enable(wx.ID_PREVIEW, False)
+ self.FileMenu.Enable(wx.ID_PRINT, False)
+ self.FileMenu.Enable(wx.ID_SAVE, False)
+ self.FileMenu.Enable(wx.ID_PROPERTIES, False)
+
+ def RefreshPLCParams(self):
+ self.Freeze()
+ self.ClearSizer(self.PLCParamsSizer)
+
+ if self.PluginRoot is not None:
+ plcwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1))
+ if self.PluginRoot.PlugTestModified():
+ bkgdclr = CHANGED_TITLE_COLOUR
+ else:
+ bkgdclr = TITLE_COLOUR
+
+ if self.PluginRoot not in self.PluginInfos:
+ self.PluginInfos[self.PluginRoot] = {"right_visible" : False}
+
+ plcwindow.SetBackgroundColour(TITLE_COLOUR)
+ plcwindow.Bind(wx.EVT_LEFT_DOWN, self.OnPanelLeftDown)
+ self.PLCParamsSizer.AddWindow(plcwindow, 0, border=0, flag=wx.GROW)
+
+ plcwindowsizer = wx.BoxSizer(wx.HORIZONTAL)
+ plcwindow.SetSizer(plcwindowsizer)
+
+ st = wx.StaticText(plcwindow, -1)
+ st.SetFont(wx.Font(faces["size"], wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"]))
+ st.SetLabel(self.PluginRoot.GetProjectName())
+ plcwindowsizer.AddWindow(st, 0, border=5, flag=wx.ALL|wx.ALIGN_CENTER)
+
+ plcwindowmainsizer = wx.BoxSizer(wx.VERTICAL)
+ plcwindowsizer.AddSizer(plcwindowmainsizer, 0, border=5, flag=wx.ALL)
+
+ plcwindowbuttonsizer = wx.BoxSizer(wx.HORIZONTAL)
+ plcwindowmainsizer.AddSizer(plcwindowbuttonsizer, 0, border=0, flag=wx.ALIGN_CENTER)
+
+ msizer = self.GenerateMethodButtonSizer(self.PluginRoot, plcwindow, not self.PluginInfos[self.PluginRoot]["right_visible"])
+ plcwindowbuttonsizer.AddSizer(msizer, 0, border=0, flag=wx.GROW)
+
+ self.PLCConfigMainSizer.Layout()
+ self.RefreshScrollBars()
+ self.Thaw()
+
+ def GenerateTreeBranch(self, plugin):
+ leftwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1))
+ if plugin.PlugTestModified():
+ bkgdclr=CHANGED_WINDOW_COLOUR
+ else:
+ bkgdclr=WINDOW_COLOUR
+
+ leftwindow.SetBackgroundColour(bkgdclr)
+
+ if plugin not in self.PluginInfos:
+ self.PluginInfos[plugin] = {"expanded" : False, "left_visible" : False, "right_visible" : False}
+
+ self.PluginInfos[plugin]["children"] = plugin.IECSortedChilds()
+ plugin_infos = plugin.GetVariableLocationTree()
+ plugin_locations = []
+ if len(self.PluginInfos[plugin]["children"]) == 0:
+ plugin_locations = plugin_infos["children"]
+ if not self.PluginInfos[plugin].has_key("locations_infos"):
+ self.PluginInfos[plugin]["locations_infos"] = {"root": {"expanded" : False}}
+
+ self.PluginInfos[plugin]["locations_infos"]["root"]["children"] = []
+
+ self.PluginTreeSizer.AddWindow(leftwindow, 0, border=0, flag=wx.GROW)
+
+ leftwindowsizer = wx.BoxSizer(wx.HORIZONTAL)
+ leftwindow.SetSizer(leftwindowsizer)
+
+ st = wx.StaticText(leftwindow, -1)
+ st.SetFont(wx.Font(faces["size"], wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"]))
+ st.SetLabel(plugin.GetFullIEC_Channel())
+ leftwindowsizer.AddWindow(st, 0, border=5, flag=wx.RIGHT)
+
+ expandbutton_id = wx.NewId()
+ expandbutton = wx.lib.buttons.GenBitmapToggleButton(id=expandbutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'plus.png')),
+ name='ExpandButton', parent=leftwindow, pos=wx.Point(0, 0),
+ size=wx.Size(13, 13), style=wx.NO_BORDER)
+ expandbutton.labelDelta = 0
+ expandbutton.SetBezelWidth(0)
+ expandbutton.SetUseFocusIndicator(False)
+ expandbutton.SetBitmapSelected(wx.Bitmap(Bpath( 'images', 'minus.png')))
+
+ if len(self.PluginInfos[plugin]["children"]) > 0:
+ expandbutton.SetToggle(self.PluginInfos[plugin]["expanded"])
+ def togglebutton(event):
+ if expandbutton.GetToggle():
+ self.ExpandPlugin(plugin)
+ else:
+ self.CollapsePlugin(plugin)
+ self.PluginInfos[plugin]["expanded"] = expandbutton.GetToggle()
+ self.PLCConfigMainSizer.Layout()
+ self.RefreshScrollBars()
+ event.Skip()
+ expandbutton.Bind(wx.EVT_BUTTON, togglebutton, id=expandbutton_id)
+ elif len(plugin_locations) > 0:
+ locations_infos = self.PluginInfos[plugin]["locations_infos"]
+ expandbutton.SetToggle(locations_infos["root"]["expanded"])
+ def togglebutton(event):
+ if expandbutton.GetToggle():
+ self.ExpandLocation(locations_infos, "root")
+ else:
+ self.CollapseLocation(locations_infos, "root")
+ self.PluginInfos[plugin]["expanded"] = expandbutton.GetToggle()
+ locations_infos["root"]["expanded"] = expandbutton.GetToggle()
+ self.PLCConfigMainSizer.Layout()
+ self.RefreshScrollBars()
+ event.Skip()
+ expandbutton.Bind(wx.EVT_BUTTON, togglebutton, id=expandbutton_id)
+ else:
+ expandbutton.Enable(False)
+ leftwindowsizer.AddWindow(expandbutton, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL)
+
+ sb = wx.StaticBitmap(leftwindow, -1)
+ icon = plugin_infos.get("icon", None)
+ if icon is None:
+ icon = os.path.join(base_folder, "plcopeneditor", 'Images', '%s.png' % self.LOCATION_BITMAP[plugin_infos["type"]])
+ sb.SetBitmap(wx.Bitmap(icon))
+ leftwindowsizer.AddWindow(sb, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL)
+
+ st_id = wx.NewId()
+ st = wx.StaticText(leftwindow, st_id, size=wx.DefaultSize, style=wx.NO_BORDER)
+ st.SetFont(wx.Font(faces["size"] * 0.75, wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"]))
+ st.SetLabel(plugin.MandatoryParams[1].getName())
+ leftwindowsizer.AddWindow(st, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL)
+
+ rightwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1))
+ rightwindow.SetBackgroundColour(bkgdclr)
+
+ self.PluginTreeSizer.AddWindow(rightwindow, 0, border=0, flag=wx.GROW)
+
+ self.PluginInfos[plugin]["left"] = leftwindow
+ self.PluginInfos[plugin]["right"] = rightwindow
+ for child in self.PluginInfos[plugin]["children"]:
+ self.GenerateTreeBranch(child)
+ if not self.PluginInfos[child]["expanded"]:
+ self.CollapsePlugin(child)
+ if len(plugin_locations) > 0:
+ locations_infos = self.PluginInfos[plugin]["locations_infos"]
+ for location in plugin_locations:
+ locations_infos["root"]["children"].append("root.%s" % location["name"])
+ self.GenerateLocationTreeBranch(locations_infos, "root", location)
+ if not locations_infos["root"]["expanded"]:
+ self.CollapseLocation(locations_infos, "root")
+
+frame = None
+
+def BeremizStartProc(plugin_root):
+ global frame
+
+ app = wx.PySimpleApp()
+ app.SetAppName('beremiz')
+ wx.InitAllImageHandlers()
+
+ # Get the english language
+ langid = wx.LANGUAGE_ENGLISH
+ # Import module for internationalization
+ import gettext
+ import __builtin__
+
+ # Define locale for wx
+ loc = wx.Locale(langid)
+ for localedir in PseudoLocale.LocaleDirs:
+ loc.AddCatalogLookupPathPrefix(localedir)
+ for domain in PseudoLocale.Domains:
+ loc.AddCatalog(domain)
+
+ __builtin__.__dict__['_'] = wx.GetTranslation#unicode_translation
+
+ # Install a exception handle for bug reports
+ AddExceptHook(os.getcwd(),__version__)
+
+ frame = LPCBeremiz(None, plugin_root=plugin_root, debug=False)
+ plugin_root.SetAppFrame(frame, frame.Log)
+ frame.Show()
+
+ app.MainLoop()
+
+class StdoutPseudoFile:
+ """ Base class for file like objects to facilitate StdOut for the Shell."""
+ def write(self, s, style = None):
+ if s != '':
+ print s
+
+ def write_warning(self, s):
+ self.write(s)
+
+ def write_error(self, s):
+ self.write(s)
+
+ def flush(self):
+ pass
+
+ def isatty(self):
+ return false
+
+if __name__ == '__main__':
+
+ from threading import Thread, Timer
+ import cmd
+
+ class LPCBeremiz_Cmd(cmd.Cmd):
+
+ prompt = ""
+ Log = StdoutPseudoFile()
+ RefreshTimer = None
+
+ def __init__(self, projectOpen, buildpath):
+ cmd.Cmd.__init__(self)
+ self.PluginRoot = LPCPluginsRoot(None, self.Log)
+ if projectOpen is not None and os.path.isfile(projectOpen):
+ result = self.PluginRoot.LoadProject(projectOpen, buildpath)
+ if result:
+ print "Error: Invalid project directory", result
+ else:
+ print "Error: No such file or directory"
+
+ def RestartTimer(self):
+ if self.RefreshTimer is not None:
+ self.RefreshTimer.cancel()
+ self.RefreshTimer = Timer(0.1, self.Refresh)
+ self.RefreshTimer.start()
+
+ def Exit(self):
+ self.Close()
+ return True
+
+ def do_EOF(self, line):
+ return self.Exit()
+
+ def Show(self):
+ beremiz_thread=Thread(target=BeremizStartProc, args=[self.PluginRoot])
+ beremiz_thread.start()
+
+ def Refresh(self):
+ global frame
+ if frame is not None:
+ wx.CallAfter(frame.RefreshAll)
+
+ def Close(self):
+ global frame
+
+ self.PluginRoot.ResetAppFrame(self.Log)
+ if frame is not None:
+ wx.CallAfter(frame.Close)
+
+ def Compile(self):
+ if wx.GetApp() is None:
+ self.PluginRoot._build()
+ else:
+ wx.CallAfter(self.PluginRoot._build)
+
+ def SetProjectName(self, name):
+ self.PluginRoot.SetProjectName(name)
+ self.RestartTimer()
+
+ def AddBus(self, iec_channel, name, icon=None):
+ for child in self.PluginRoot.IterChilds():
+ if child.BaseParams.getName() == name:
+ return "Error: A bus named %s already exists" % name
+ elif child.BaseParams.getIEC_Channel() == iec_channel:
+ return "Error: A bus with IEC_channel %d already exists" % iec_channel
+ bus = self.PluginRoot.PlugAddChild(name, "LPCBus", iec_channel)
+ if bus is None:
+ return "Error: Unable to create bus"
+ bus.SetIcon(icon)
+ self.RestartTimer()
+
+ def RenameBus(self, iec_channel, name):
+ bus = self.PluginRoot.GetChildByIECLocation((iec_channel,))
+ if bus is None:
+ return "Error: No bus found"
+ for child in self.PluginRoot.IterChilds():
+ if child != bus and child.BaseParams.getName() == name:
+ return "Error: A bus named %s already exists" % name
+ bus.BaseParams.setName(name)
+ self.RestartTimer()
+
+ def ChangeBusIECChannel(self, old_iec_channel, new_iec_channel):
+ bus = self.PluginRoot.GetChildByIECLocation((old_iec_channel,))
+ if bus is None:
+ return "Error: No bus found"
+ for child in self.PluginRoot.IterChilds():
+ if child != bus and child.BaseParams.getIEC_Channel() == new_iec_channel:
+ return "Error: A bus with IEC_channel %d already exists" % new_iec_channel
+ bus.BaseParams.setIEC_Channel(new_iec_channel)
+ self.RestartTimer()
+
+ def RemoveBus(self, iec_channel):
+ bus = self.PluginRoot.GetChildByIECLocation((iec_channel,))
+ if bus is None:
+ return "Error: No bus found"
+ self.PluginRoot.PluggedChilds["LPCBus"].remove(bus)
+ self.RestartTimer()
+
+ def AddModule(self, parent, iec_channel, name, icon=None):
+ module = self.PluginRoot.GetChildByIECLocation(parent)
+ if module is None:
+ return "Error: No parent found"
+ for child in _GetModuleChildren(module):
+ if child["name"] == name:
+ return "Error: A module named %s already exists" % name
+ elif child["IEC_Channel"] == iec_channel:
+ return "Error: A module with IEC_channel %d already exists" % iec_channel
+ _GetLastModuleGroup(module).append({"name": name,
+ "type": LOCATION_MODULE,
+ "IEC_Channel": iec_channel,
+ "icon": icon,
+ "children": []})
+ self.RestartTimer()
+
+ def RenameModule(self, iec_location, name):
+ module = self.PluginRoot.GetChildByIECLocation(iec_location)
+ if module is None:
+ return "Error: No module found"
+ parent = self.PluginRoot.GetChildByIECLocation(iec_location[:-1])
+ if parent is self.PluginRoot:
+ return "Error: No module found"
+ if module["name"] != name:
+ for child in _GetModuleChildren(parent):
+ if child["name"] == name:
+ return "Error: A module named %s already exists" % name
+ module["name"] = name
+ self.RestartTimer()
+
+ def ChangeModuleIECChannel(self, old_iec_location, new_iec_channel):
+ module = self.PluginRoot.GetChildByIECLocation(old_iec_location)
+ if module is None:
+ return "Error: No module found"
+ parent = self.PluginRoot.GetChildByIECLocation(old_iec_location[:-1])
+ if parent is self.PluginRoot:
+ return "Error: No module found"
+ if module["IEC_Channel"] != new_iec_channel:
+ for child in _GetModuleChildren(parent):
+ if child["IEC_Channel"] == new_iec_channel:
+ return "Error: A module with IEC_channel %d already exists" % new_iec_channel
+ module["IEC_Channel"] = new_iec_channel
+ self.RestartTimer()
+
+ def RemoveModule(self, parent, iec_channel):
+ module = self.PluginRoot.GetChildByIECLocation(parent)
+ if module is None:
+ return "Error: No parent found"
+ child = _GetModuleBySomething(module, "IEC_Channel", (iec_channel,))
+ if child is None:
+ return "Error: No module found"
+ _RemoveModuleChild(module, child)
+ self.RestartTimer()
+
+ def StartGroup(self, parent, name, icon=None):
+ module = self.PluginRoot.GetChildByIECLocation(parent)
+ if module is None:
+ return "Error: No parent found"
+ for child in module["children"]:
+ if child["type"] == LOCATION_GROUP and child["name"] == name:
+ return "Error: A group named %s already exists" % name
+ module["children"].append({"name": name,
+ "type": LOCATION_GROUP,
+ "icon": icon,
+ "children": []})
+ self.RestartTimer()
+
+ def AddVariable(self, parent, location, name, direction, type, dcode, rcode, pcode, description=""):
+ module = self.PluginRoot.GetChildByIECLocation(parent)
+ if module is None:
+ return "Error: No parent found"
+ for child in _GetModuleChildren(module):
+ if child["name"] == name:
+ return "Error: A variable named %s already exists" % name
+ if child["location"] == location:
+ return "Error: A variable with location %s already exists" % ".".join(map(str, location))
+ _GetLastModuleGroup(module).append({"name": name,
+ "location": location,
+ "type": LOCATION_TYPES[direction],
+ "IEC_type": type,
+ "description": description,
+ "declare": dcode,
+ "retrieve": rcode,
+ "publish": pcode})
+ self.RestartTimer()
+
+ def ChangeVariableParams(self, parent, location, new_name, new_direction, new_type, new_dcode, new_rcode, new_pcode, new_description=None):
+ module = self.PluginRoot.GetChildByIECLocation(parent)
+ if module is None:
+ return "Error: No parent found"
+ variable = None
+ for child in _GetModuleChildren(module):
+ if child["location"] == location:
+ variable = child
+ elif child["name"] == new_name:
+ return "Error: A variable named %s already exists" % new_name
+ if variable is None:
+ return "Error: No variable found"
+ variable["name"] = new_name
+ variable["type"] = LOCATION_TYPES[new_direction]
+ variable["IEC_type"] = new_type
+ variable["declare"] = new_dcode
+ variable["retrieve"] = new_rcode
+ variable["publish"] = new_pcode
+ if new_description is not None:
+ variable["description"] = new_description
+ self.RestartTimer()
+
+ def RemoveVariable(self, parent, location):
+ module = self.PluginRoot.GetChildByIECLocation(parent)
+ if module is None:
+ return "Error: No parent found"
+ child = _GetModuleVariable(module, location)
+ if child is None:
+ return "Error: No variable found"
+ _RemoveModuleChild(module, child)
+ self.RestartTimer()
+
+ def location(loc):
+ return tuple(map(int, loc.split(".")))
+
+ def GetCmdFunction(function, arg_types, opt=0):
+ arg_number = len(arg_types)
+ def CmdFunction(self, line):
+ args_toks = line.split('"')
+ if len(args_toks) % 2 == 0:
+ print "Error: Invalid command"
+ return
+ args = []
+ for num, arg in enumerate(args_toks):
+ if num % 2 == 0:
+ stripped = arg.strip()
+ if stripped:
+ args.extend(stripped.split(" "))
+ else:
+ args.append(arg)
+ number = None
+ extra = ""
+ if opt == 0 and len(args) != arg_number:
+ number = arg_number
+ elif len(args) > arg_number:
+ number = arg_number
+ extra = " at most"
+ elif len(args) < arg_number - opt:
+ number = arg_number - opt
+ extra = " at least"
+ if number is not None:
+ if number == 0:
+ print "Error: No argument%s expected" % extra
+ elif number == 1:
+ print "Error: 1 argument%s expected" % extra
+ else:
+ print "Error: %d arguments%s expected" % (number, extra)
+ return
+ for num, arg in enumerate(args):
+ try:
+ args[num] = arg_types[num](arg)
+ except:
+ print "Error: Invalid value for argument %d" % (num + 1)
+ return
+ res = getattr(self, function)(*args)
+ if isinstance(res, (StringType, UnicodeType)):
+ print res
+ return False
+ else:
+ return res
+ return CmdFunction
+
+ for function, (arg_types, opt) in {"Exit": ([], 0),
+ "Show": ([], 0),
+ "Refresh": ([], 0),
+ "Close": ([], 0),
+ "Compile": ([], 0),
+ "SetProjectName": ([str], 0),
+ "AddBus": ([int, str, str], 1),
+ "RenameBus": ([int, str], 0),
+ "ChangeBusIECChannel": ([int, int], 0),
+ "RemoveBus": ([int], 0),
+ "AddModule": ([location, int, str, str], 1),
+ "RenameModule": ([location, str], 0),
+ "ChangeModuleIECChannel": ([location, int], 0),
+ "RemoveModule": ([location, int], 0),
+ "StartGroup": ([location, str, str], 1),
+ "AddVariable": ([location, location, str, str, str, str, str, str], 1),
+ "ChangeVariableParams": ([location, location, str, str, str, str, str, str, str, str], 1),
+ "RemoveVariable": ([location, location], 0)}.iteritems():
+
+ setattr(LPCBeremiz_Cmd, "do_%s" % function, GetCmdFunction(function, arg_types, opt))
+
+ lpcberemiz_cmd = LPCBeremiz_Cmd(projectOpen, buildpath)
+ lpcberemiz_cmd.cmdloop()
+