LPCBeremiz.py
changeset 717 1c23952dbde1
parent 715 135566ab0807
child 718 5d4dc150b956
equal deleted inserted replaced
716:180e4a7d945c 717:1c23952dbde1
    57 
    57 
    58 if __name__ == '__main__':
    58 if __name__ == '__main__':
    59     __builtin__.__dict__['_'] = wx.GetTranslation#unicode_translation
    59     __builtin__.__dict__['_'] = wx.GetTranslation#unicode_translation
    60 
    60 
    61 from Beremiz import *
    61 from Beremiz import *
    62 from plugger import PluginsRoot, PlugTemplate, opjimg, connectors
    62 from ConfigTree import ConfigTreeRoot, ConfigTreeNode, opjimg, connectors
    63 from plcopen.structures import LOCATIONDATATYPES
    63 from plcopen.structures import LOCATIONDATATYPES
    64 from PLCControler import LOCATION_PLUGIN, LOCATION_MODULE, LOCATION_GROUP,\
    64 from PLCControler import LOCATION_CONFNODE, LOCATION_MODULE, LOCATION_GROUP,\
    65                          LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY
    65                          LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY
    66 from PLCOpenEditor import IDEFrame, ProjectDialog
    66 from PLCOpenEditor import IDEFrame, ProjectDialog
    67 
    67 
    68 havecanfestival = False
    68 havecanfestival = False
    69 try:
    69 try:
    70     from plugins.canfestival import RootClass as CanOpenRootClass
    70     from confnodes.canfestival import RootClass as CanOpenRootClass
    71     from plugins.canfestival.canfestival import _SlavePlug, _NodeListPlug, NodeManager
    71     from confnodes.canfestival.canfestival import _SlavePlug, _NodeListPlug, NodeManager
    72     havecanfestival = True
    72     havecanfestival = True
    73 except:
    73 except:
    74     havecanfestival = False
    74     havecanfestival = False
    75     
    75     
    76 
    76 
    77 #-------------------------------------------------------------------------------
    77 #-------------------------------------------------------------------------------
    78 #                          CANFESTIVAL PLUGIN HACK
    78 #                          CANFESTIVAL CONFNODE HACK
    79 #-------------------------------------------------------------------------------
    79 #-------------------------------------------------------------------------------
    80 # from plugins.canfestival import canfestival
    80 # from confnodes.canfestival import canfestival
    81 # class LPC_canfestival_config:
    81 # class LPC_canfestival_config:
    82 #     def getCFLAGS(self, *args):
    82 #     def getCFLAGS(self, *args):
    83 #         return ""
    83 #         return ""
    84 # 
    84 # 
    85 #     def getLDFLAGS(self, *args):
    85 #     def getLDFLAGS(self, *args):
   146     else:
   146     else:
   147         for group in module["children"]:
   147         for group in module["children"]:
   148             if group["type"] == LOCATION_GROUP and child in group["children"]:
   148             if group["type"] == LOCATION_GROUP and child in group["children"]:
   149                 group["children"].remove(child)
   149                 group["children"].remove(child)
   150 
   150 
   151 BUS_TEXT = """/* Code generated by LPCBus plugin */
   151 BUS_TEXT = """/* Code generated by LPCBus confnode */
   152 
   152 
   153 /* LPCBus plugin includes */
   153 /* LPCBus confnode includes */
   154 #include "app_glue.h"
   154 #include "app_glue.h"
   155 #ifdef _WINDOWS_H
   155 #ifdef _WINDOWS_H
   156   #include "iec_types.h"
   156   #include "iec_types.h"
   157 #else
   157 #else
   158   #include "iec_std_lib.h"
   158   #include "iec_std_lib.h"
   159 #endif
   159 #endif
   160 
   160 
   161 %(declare_code)s
   161 %(declare_code)s
   162 
   162 
   163 /* LPCBus plugin user variables definition */
   163 /* LPCBus confnode user variables definition */
   164 %(var_decl)s
   164 %(var_decl)s
   165 
   165 
   166 /* LPCBus plugin functions */
   166 /* LPCBus confnode functions */
   167 int __init_%(location_str)s(int argc,char **argv)
   167 int __init_%(location_str)s(int argc,char **argv)
   168 {
   168 {
   169 %(init_code)s
   169 %(init_code)s
   170   return 0;
   170   return 0;
   171 }
   171 }
   238                     "description": infos["description"],
   238                     "description": infos["description"],
   239                     "children": []}
   239                     "children": []}
   240     
   240     
   241     def GetVariableLocationTree(self):
   241     def GetVariableLocationTree(self):
   242         return {"name": self.BaseParams.getName(),
   242         return {"name": self.BaseParams.getName(),
   243                 "type": LOCATION_PLUGIN,
   243                 "type": LOCATION_CONFNODE,
   244                 "location": self.GetFullIEC_Channel(),
   244                 "location": self.GetFullIEC_Channel(),
   245                 "icon": self.Icon, 
   245                 "icon": self.Icon, 
   246                 "children": [self._GetVariableLocationTree(self.GetCurrentLocation(), child) 
   246                 "children": [self._GetVariableLocationTree(self.GetCurrentLocation(), child) 
   247                              for child in self.VariableLocationTree]}
   247                              for child in self.VariableLocationTree]}
   248     
   248     
   289         return False
   289         return False
   290 
   290 
   291     def PlugGenerate_C(self, buildpath, locations):
   291     def PlugGenerate_C(self, buildpath, locations):
   292         """
   292         """
   293         Generate C code
   293         Generate C code
   294         @param current_location: Tupple containing plugin IEC location : %I0.0.4.5 => (0,0,4,5)
   294         @param current_location: Tupple containing confnode IEC location : %I0.0.4.5 => (0,0,4,5)
   295         @param locations: List of complete variables locations \
   295         @param locations: List of complete variables locations \
   296             [{"IEC_TYPE" : the IEC type (i.e. "INT", "STRING", ...)
   296             [{"IEC_TYPE" : the IEC type (i.e. "INT", "STRING", ...)
   297             "NAME" : name of the variable (generally "__IW0_1_2" style)
   297             "NAME" : name of the variable (generally "__IW0_1_2" style)
   298             "DIR" : direction "Q","I" or "M"
   298             "DIR" : direction "Q","I" or "M"
   299             "SIZE" : size "X", "B", "W", "D", "L"
   299             "SIZE" : size "X", "B", "W", "D", "L"
   365         
   365         
   366         matiec_flags = '"-I%s"'%os.path.abspath(self.GetPlugRoot().GetIECLibPath())
   366         matiec_flags = '"-I%s"'%os.path.abspath(self.GetPlugRoot().GetIECLibPath())
   367         return [(Gen_Module_path, matiec_flags)],"",True
   367         return [(Gen_Module_path, matiec_flags)],"",True
   368 
   368 
   369 #-------------------------------------------------------------------------------
   369 #-------------------------------------------------------------------------------
   370 #                          LPC CanFestival Plugin Class
   370 #                          LPC CanFestival ConfNode Class
   371 #-------------------------------------------------------------------------------
   371 #-------------------------------------------------------------------------------
   372 
   372 
   373 if havecanfestival:
   373 if havecanfestival:
   374 
   374 
   375     DEFAULT_SETTINGS = {
   375     DEFAULT_SETTINGS = {
   442         
   442         
   443         def GetCanDriver(self):
   443         def GetCanDriver(self):
   444             return ""
   444             return ""
   445         
   445         
   446         def LoadChilds(self):
   446         def LoadChilds(self):
   447             PlugTemplate.LoadChilds(self)
   447             ConfigTreeNode.LoadChilds(self)
   448             
   448             
   449             if self.GetChildByName("Master") is None:
   449             if self.GetChildByName("Master") is None:
   450                 master = self.PlugAddChild("Master", "CanOpenNode", 0)
   450                 master = self.PlugAddChild("Master", "CanOpenNode", 0)
   451                 master.BaseParams.setEnabled(False)
   451                 master.BaseParams.setEnabled(False)
   452             
   452             
   454                 slave = self.PlugAddChild("Slave", "CanOpenSlave", 1)
   454                 slave = self.PlugAddChild("Slave", "CanOpenSlave", 1)
   455                 slave.BaseParams.setEnabled(False)
   455                 slave.BaseParams.setEnabled(False)
   456     
   456     
   457 
   457 
   458 #-------------------------------------------------------------------------------
   458 #-------------------------------------------------------------------------------
   459 #                              LPCPluginsRoot Class
   459 #                              LPCConfigTreeRoot Class
   460 #-------------------------------------------------------------------------------
   460 #-------------------------------------------------------------------------------
   461 
   461 
   462 def mycopytree(src, dst):
   462 def mycopytree(src, dst):
   463     """
   463     """
   464     Copy content of a directory to an other, omit hidden files
   464     Copy content of a directory to an other, omit hidden files
   477             elif os.path.isfile(srcpath):
   477             elif os.path.isfile(srcpath):
   478                 shutil.copy2(srcpath, dstpath)
   478                 shutil.copy2(srcpath, dstpath)
   479 
   479 
   480 [SIMULATION_MODE, TRANSFER_MODE] = range(2)
   480 [SIMULATION_MODE, TRANSFER_MODE] = range(2)
   481 
   481 
   482 class LPCPluginsRoot(PluginsRoot):
   482 class LPCConfigTreeRoot(ConfigTreeRoot):
   483 
   483 
   484     PluginMethods = [
   484     ConfNodeMethods = [
   485         {"bitmap" : opjimg("Debug"),
   485         {"bitmap" : opjimg("Debug"),
   486          "name" : _("Simulate"),
   486          "name" : _("Simulate"),
   487          "tooltip" : _("Simulate PLC"),
   487          "tooltip" : _("Simulate PLC"),
   488          "method" : "_Simulate"},
   488          "method" : "_Simulate"},
   489         {"bitmap" : opjimg("Run"),
   489         {"bitmap" : opjimg("Run"),
   508     ]
   508     ]
   509 
   509 
   510     def __init__(self, frame, logger, buildpath):
   510     def __init__(self, frame, logger, buildpath):
   511         self.OrigBuildPath = buildpath
   511         self.OrigBuildPath = buildpath
   512         
   512         
   513         PluginsRoot.__init__(self, frame, logger)
   513         ConfigTreeRoot.__init__(self, frame, logger)
   514         
   514         
   515         if havecanfestival:
   515         if havecanfestival:
   516             self.PlugChildsTypes += [("LPCBus", LPCBus, "LPC bus"), ("CanOpen", LPCCanOpen, "CanOpen bus")]
   516             self.PlugChildsTypes += [("LPCBus", LPCBus, "LPC bus"), ("CanOpen", LPCCanOpen, "CanOpen bus")]
   517         else:
   517         else:
   518             self.PlugChildsTypes += [("LPCBus", LPCBus, "LPC bus")]
   518             self.PlugChildsTypes += [("LPCBus", LPCBus, "LPC bus")]
   526         
   526         
   527         self.SimulationBuildPath = None
   527         self.SimulationBuildPath = None
   528         
   528         
   529         self.AbortTransferTimer = None
   529         self.AbortTransferTimer = None
   530     
   530     
   531     def PluginLibraryFilePath(self):
   531     def ConfNodeLibraryFilePath(self):
   532         if self.OrigBuildPath is not None:
   532         if self.OrigBuildPath is not None:
   533             return os.path.join(self.OrigBuildPath, "pous.xml")
   533             return os.path.join(self.OrigBuildPath, "pous.xml")
   534         else:
   534         else:
   535             return PluginsRoot.PluginLibraryFilePath(self)
   535             return ConfigTreeRoot.ConfNodeLibraryFilePath(self)
   536     
   536     
   537     def GetProjectName(self):
   537     def GetProjectName(self):
   538         return self.Project.getname()
   538         return self.Project.getname()
   539 
   539 
   540     def GetDefaultTargetName(self):
   540     def GetDefaultTargetName(self):
   541         if self.CurrentMode == SIMULATION_MODE:
   541         if self.CurrentMode == SIMULATION_MODE:
   542             return PluginsRoot.GetDefaultTargetName(self)
   542             return ConfigTreeRoot.GetDefaultTargetName(self)
   543         else:
   543         else:
   544             return "LPC"
   544             return "LPC"
   545 
   545 
   546     def GetTarget(self):
   546     def GetTarget(self):
   547         target = PluginsRoot.GetTarget(self)
   547         target = ConfigTreeRoot.GetTarget(self)
   548         if self.CurrentMode != SIMULATION_MODE:
   548         if self.CurrentMode != SIMULATION_MODE:
   549             target.getcontent()["value"].setBuildPath(self.BuildPath)
   549             target.getcontent()["value"].setBuildPath(self.BuildPath)
   550         return target
   550         return target
   551     
   551     
   552     def _getBuildPath(self):
   552     def _getBuildPath(self):
   553         if self.CurrentMode == SIMULATION_MODE:
   553         if self.CurrentMode == SIMULATION_MODE:
   554             if self.SimulationBuildPath is None:
   554             if self.SimulationBuildPath is None:
   555                 self.SimulationBuildPath = os.path.join(tempfile.mkdtemp(), os.path.basename(self.ProjectPath), "build")
   555                 self.SimulationBuildPath = os.path.join(tempfile.mkdtemp(), os.path.basename(self.ProjectPath), "build")
   556             return self.SimulationBuildPath
   556             return self.SimulationBuildPath
   557         else:
   557         else:
   558             return PluginsRoot._getBuildPath(self)
   558             return ConfigTreeRoot._getBuildPath(self)
   559 
   559 
   560     def _Build(self):
   560     def _Build(self):
   561         save = self.ProjectTestModified()
   561         save = self.ProjectTestModified()
   562         if save:
   562         if save:
   563             self.SaveProject()
   563             self.SaveProject()
   564             self.AppFrame._Refresh(TITLE, FILEMENU)
   564             self.AppFrame._Refresh(TITLE, FILEMENU)
   565         if self.BuildPath is not None:
   565         if self.BuildPath is not None:
   566             mycopytree(self.OrigBuildPath, self.BuildPath)
   566             mycopytree(self.OrigBuildPath, self.BuildPath)
   567         PluginsRoot._Build(self)
   567         ConfigTreeRoot._Build(self)
   568         if save:
   568         if save:
   569             wx.CallAfter(self.AppFrame.RefreshAll)
   569             wx.CallAfter(self.AppFrame.RefreshAll)
   570     
   570     
   571     def SetProjectName(self, name):
   571     def SetProjectName(self, name):
   572         return self.Project.setname(name)
   572         return self.Project.setname(name)
   676         
   676         
   677         # Change XSD into class members
   677         # Change XSD into class members
   678         self._AddParamsMembers()
   678         self._AddParamsMembers()
   679         self.PluggedChilds = {}
   679         self.PluggedChilds = {}
   680         
   680         
   681         # Keep track of the root plugin (i.e. project path)
   681         # Keep track of the root confnode (i.e. project path)
   682         self.ProjectPath = ProjectPath
   682         self.ProjectPath = ProjectPath
   683         
   683         
   684         self.BuildPath = self._getBuildPath()
   684         self.BuildPath = self._getBuildPath()
   685         if self.OrigBuildPath is not None:
   685         if self.OrigBuildPath is not None:
   686             mycopytree(self.OrigBuildPath, self.BuildPath)
   686             mycopytree(self.OrigBuildPath, self.BuildPath)
   687         
   687         
   688         # If dir have already be made, and file exist
   688         # If dir have already be made, and file exist
   689         if os.path.isdir(self.PlugPath()) and os.path.isfile(self.PluginXmlFilePath()):
   689         if os.path.isdir(self.PlugPath()) and os.path.isfile(self.ConfNodeXmlFilePath()):
   690             #Load the plugin.xml file into parameters members
   690             #Load the confnode.xml file into parameters members
   691             result = self.LoadXMLParams()
   691             result = self.LoadXMLParams()
   692             if result:
   692             if result:
   693                 return result
   693                 return result
   694             #Load and init all the childs
   694             #Load and init all the childs
   695             self.LoadChilds()
   695             self.LoadChilds()
   701         
   701         
   702         if self.PlugTestModified():
   702         if self.PlugTestModified():
   703             self.SaveProject()
   703             self.SaveProject()
   704         
   704         
   705         if wx.GetApp() is None:
   705         if wx.GetApp() is None:
   706             self.RefreshPluginsBlockLists()
   706             self.RefreshConfNodesBlockLists()
   707         else:
   707         else:
   708             wx.CallAfter(self.RefreshPluginsBlockLists)
   708             wx.CallAfter(self.RefreshConfNodesBlockLists)
   709 
   709 
   710         return None
   710         return None
   711 
   711 
   712     ############# Real PLC object access #############
   712     ############# Real PLC object access #############
   713     def UpdateMethodsFromPLCStatus(self):
   713     def UpdateMethodsFromPLCStatus(self):
   887         if PlugCFilesAndCFLAGS:
   887         if PlugCFilesAndCFLAGS:
   888             self.LocationCFilesAndCFLAGS = [(self.GetCurrentLocation(), PlugCFilesAndCFLAGS, DoCalls)]
   888             self.LocationCFilesAndCFLAGS = [(self.GetCurrentLocation(), PlugCFilesAndCFLAGS, DoCalls)]
   889         else:
   889         else:
   890             self.LocationCFilesAndCFLAGS = []
   890             self.LocationCFilesAndCFLAGS = []
   891 
   891 
   892         # plugin asks for some LDFLAGS
   892         # confnode asks for some LDFLAGS
   893         if PlugLDFLAGS:
   893         if PlugLDFLAGS:
   894             # LDFLAGS can be either string
   894             # LDFLAGS can be either string
   895             if type(PlugLDFLAGS)==type(str()):
   895             if type(PlugLDFLAGS)==type(str()):
   896                 self.LDFLAGS=[PlugLDFLAGS]
   896                 self.LDFLAGS=[PlugLDFLAGS]
   897             #or list of strings
   897             #or list of strings
   899                 self.LDFLAGS=PlugLDFLAGS[:]
   899                 self.LDFLAGS=PlugLDFLAGS[:]
   900         else:
   900         else:
   901             self.LDFLAGS=[]
   901             self.LDFLAGS=[]
   902         
   902         
   903         # Template based part of C code generation
   903         # Template based part of C code generation
   904         # files are stacked at the beginning, as files of plugin tree root
   904         # files are stacked at the beginning, as files of confnode tree root
   905         for generator, filename, name in [
   905         for generator, filename, name in [
   906            # debugger code
   906            # debugger code
   907            (self.Generate_plc_debugger, "plc_debugger.c", "Debugger"),
   907            (self.Generate_plc_debugger, "plc_debugger.c", "Debugger"),
   908            # init/cleanup/retrieve/publish, run and align code
   908            # init/cleanup/retrieve/publish, run and align code
   909            (self.Generate_plc_common_main,"plc_common_main.c","Common runtime"),
   909            (self.Generate_plc_common_main,"plc_common_main.c","Common runtime"),
   916                 code = generator()
   916                 code = generator()
   917                 if code is None:
   917                 if code is None:
   918                      raise
   918                      raise
   919                 code_path = os.path.join(buildpath,filename)
   919                 code_path = os.path.join(buildpath,filename)
   920                 open(code_path, "w").write(code)
   920                 open(code_path, "w").write(code)
   921                 # Insert this file as first file to be compiled at root plugin
   921                 # Insert this file as first file to be compiled at root confnode
   922                 self.LocationCFilesAndCFLAGS[0][1].insert(0,(code_path, self.plcCFLAGS))
   922                 self.LocationCFilesAndCFLAGS[0][1].insert(0,(code_path, self.plcCFLAGS))
   923             except Exception, exc:
   923             except Exception, exc:
   924                 self.logger.write_error(name+_(" generation failed !\n"))
   924                 self.logger.write_error(name+_(" generation failed !\n"))
   925                 self.logger.write_error(traceback.format_exc())
   925                 self.logger.write_error(traceback.format_exc())
   926                 self.StopSimulation()
   926                 self.StopSimulation()
   968     def StopSimulation(self):
   968     def StopSimulation(self):
   969         self.CurrentMode = None
   969         self.CurrentMode = None
   970         self.ApplyOnlineMode()
   970         self.ApplyOnlineMode()
   971     
   971     
   972     def _Stop(self):
   972     def _Stop(self):
   973         PluginsRoot._Stop(self)
   973         ConfigTreeRoot._Stop(self)
   974         
   974         
   975         if self.CurrentMode == SIMULATION_MODE:
   975         if self.CurrentMode == SIMULATION_MODE:
   976             self.StopSimulation()
   976             self.StopSimulation()
   977 
   977 
   978     def CompareLocalAndRemotePLC(self):
   978     def CompareLocalAndRemotePLC(self):
   999 
   999 
  1000     def _Transfer(self):
  1000     def _Transfer(self):
  1001         if self.CurrentMode is None and self.OnlineMode != "OFF":
  1001         if self.CurrentMode is None and self.OnlineMode != "OFF":
  1002             self.CurrentMode = TRANSFER_MODE
  1002             self.CurrentMode = TRANSFER_MODE
  1003             
  1003             
  1004             if PluginsRoot._Build(self):
  1004             if ConfigTreeRoot._Build(self):
  1005             
  1005             
  1006                 ID_ABORTTRANSFERTIMER = wx.NewId()
  1006                 ID_ABORTTRANSFERTIMER = wx.NewId()
  1007                 self.AbortTransferTimer = wx.Timer(self.AppFrame, ID_ABORTTRANSFERTIMER)
  1007                 self.AbortTransferTimer = wx.Timer(self.AppFrame, ID_ABORTTRANSFERTIMER)
  1008                 self.AppFrame.Bind(wx.EVT_TIMER, self.AbortTransfer, self.AbortTransferTimer)  
  1008                 self.AppFrame.Bind(wx.EVT_TIMER, self.AbortTransfer, self.AbortTransferTimer)  
  1009                 
  1009                 
  1021     
  1021     
  1022     def BeginTransfer(self):
  1022     def BeginTransfer(self):
  1023         self.logger.write(_("Start PLC transfer\n"))
  1023         self.logger.write(_("Start PLC transfer\n"))
  1024         
  1024         
  1025         self.AbortTransferTimer.Stop()
  1025         self.AbortTransferTimer.Stop()
  1026         PluginsRoot._Transfer(self)
  1026         ConfigTreeRoot._Transfer(self)
  1027         self.AbortTransferTimer.Start(milliseconds=5000, oneShot=True)
  1027         self.AbortTransferTimer.Start(milliseconds=5000, oneShot=True)
  1028     
  1028     
  1029     def AbortTransfer(self, event):
  1029     def AbortTransfer(self, event):
  1030         self.logger.write_warning(_("Timeout waiting PLC to recover\n"))
  1030         self.logger.write_warning(_("Timeout waiting PLC to recover\n"))
  1031         
  1031         
  1111         
  1111         
  1112         if self.CheckSaveBeforeClosing(_("Close Application")):
  1112         if self.CheckSaveBeforeClosing(_("Close Application")):
  1113             
  1113             
  1114             frame.Hide()
  1114             frame.Hide()
  1115             
  1115             
  1116             self.PluginRoot.ResetAppFrame(lpcberemiz_cmd.Log)
  1116             self.CTR.ResetAppFrame(lpcberemiz_cmd.Log)
  1117             if self.PluginRoot.OnlineMode == 0:
  1117             if self.CTR.OnlineMode == 0:
  1118                 self.PluginRoot._connector = None
  1118                 self.CTR._connector = None
  1119             
  1119             
  1120             self.PluginRoot.KillDebugThread()
  1120             self.CTR.KillDebugThread()
  1121             self.KillLocalRuntime()
  1121             self.KillLocalRuntime()
  1122             
  1122             
  1123             self.SaveLastState()
  1123             self.SaveLastState()
  1124             
  1124             
  1125             lpcberemiz_cmd.Log.write("Closed\n")
  1125             lpcberemiz_cmd.Log.write("Closed\n")
  1139                               TYPESTREE, INSTANCESTREE, SCALING)
  1139                               TYPESTREE, INSTANCESTREE, SCALING)
  1140         dialog.Destroy()
  1140         dialog.Destroy()
  1141 
  1141 
  1142     def RefreshFileMenu(self):
  1142     def RefreshFileMenu(self):
  1143         MenuToolBar = self.Panes["MenuToolBar"]
  1143         MenuToolBar = self.Panes["MenuToolBar"]
  1144         if self.PluginRoot is not None:
  1144         if self.CTR is not None:
  1145             selected = self.TabsOpened.GetSelection()
  1145             selected = self.TabsOpened.GetSelection()
  1146             if selected >= 0:
  1146             if selected >= 0:
  1147                 graphic_viewer = isinstance(self.TabsOpened.GetPage(selected), Viewer)
  1147                 graphic_viewer = isinstance(self.TabsOpened.GetPage(selected), Viewer)
  1148             else:
  1148             else:
  1149                 graphic_viewer = False
  1149                 graphic_viewer = False
  1161                 self.FileMenu.Enable(wx.ID_CLOSE, False)
  1161                 self.FileMenu.Enable(wx.ID_CLOSE, False)
  1162                 self.FileMenu.Enable(wx.ID_PREVIEW, False)
  1162                 self.FileMenu.Enable(wx.ID_PREVIEW, False)
  1163                 self.FileMenu.Enable(wx.ID_PRINT, False)
  1163                 self.FileMenu.Enable(wx.ID_PRINT, False)
  1164                 MenuToolBar.EnableTool(wx.ID_PRINT, False)
  1164                 MenuToolBar.EnableTool(wx.ID_PRINT, False)
  1165             self.FileMenu.Enable(wx.ID_PAGE_SETUP, True)
  1165             self.FileMenu.Enable(wx.ID_PAGE_SETUP, True)
  1166             project_modified = self.PluginRoot.ProjectTestModified()
  1166             project_modified = self.CTR.ProjectTestModified()
  1167             self.FileMenu.Enable(wx.ID_SAVE, project_modified)
  1167             self.FileMenu.Enable(wx.ID_SAVE, project_modified)
  1168             MenuToolBar.EnableTool(wx.ID_SAVE, project_modified)
  1168             MenuToolBar.EnableTool(wx.ID_SAVE, project_modified)
  1169             self.FileMenu.Enable(wx.ID_PROPERTIES, True)
  1169             self.FileMenu.Enable(wx.ID_PROPERTIES, True)
  1170         else:
  1170         else:
  1171             self.FileMenu.Enable(wx.ID_CLOSE, False)
  1171             self.FileMenu.Enable(wx.ID_CLOSE, False)
  1179         
  1179         
  1180     def RefreshPLCParams(self):
  1180     def RefreshPLCParams(self):
  1181         self.Freeze()
  1181         self.Freeze()
  1182         self.ClearSizer(self.PLCParamsSizer)
  1182         self.ClearSizer(self.PLCParamsSizer)
  1183         
  1183         
  1184         if self.PluginRoot is not None:    
  1184         if self.CTR is not None:    
  1185             plcwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1))
  1185             plcwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1))
  1186             if self.PluginRoot.PlugTestModified():
  1186             if self.CTR.PlugTestModified():
  1187                 bkgdclr = CHANGED_TITLE_COLOUR
  1187                 bkgdclr = CHANGED_TITLE_COLOUR
  1188             else:
  1188             else:
  1189                 bkgdclr = TITLE_COLOUR
  1189                 bkgdclr = TITLE_COLOUR
  1190                 
  1190                 
  1191             if self.PluginRoot not in self.PluginInfos:
  1191             if self.CTR not in self.ConfNodeInfos:
  1192                 self.PluginInfos[self.PluginRoot] = {"right_visible" : False}
  1192                 self.ConfNodeInfos[self.CTR] = {"right_visible" : False}
  1193             
  1193             
  1194             plcwindow.SetBackgroundColour(TITLE_COLOUR)
  1194             plcwindow.SetBackgroundColour(TITLE_COLOUR)
  1195             plcwindow.Bind(wx.EVT_LEFT_DOWN, self.OnPanelLeftDown)
  1195             plcwindow.Bind(wx.EVT_LEFT_DOWN, self.OnPanelLeftDown)
  1196             self.PLCParamsSizer.AddWindow(plcwindow, 0, border=0, flag=wx.GROW)
  1196             self.PLCParamsSizer.AddWindow(plcwindow, 0, border=0, flag=wx.GROW)
  1197             
  1197             
  1198             plcwindowsizer = wx.BoxSizer(wx.HORIZONTAL)
  1198             plcwindowsizer = wx.BoxSizer(wx.HORIZONTAL)
  1199             plcwindow.SetSizer(plcwindowsizer)
  1199             plcwindow.SetSizer(plcwindowsizer)
  1200             
  1200             
  1201             st = wx.StaticText(plcwindow, -1)
  1201             st = wx.StaticText(plcwindow, -1)
  1202             st.SetFont(wx.Font(faces["size"], wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"]))
  1202             st.SetFont(wx.Font(faces["size"], wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"]))
  1203             st.SetLabel(self.PluginRoot.GetProjectName())
  1203             st.SetLabel(self.CTR.GetProjectName())
  1204             plcwindowsizer.AddWindow(st, 0, border=5, flag=wx.ALL|wx.ALIGN_CENTER)
  1204             plcwindowsizer.AddWindow(st, 0, border=5, flag=wx.ALL|wx.ALIGN_CENTER)
  1205             
  1205             
  1206             plcwindowmainsizer = wx.BoxSizer(wx.VERTICAL)
  1206             plcwindowmainsizer = wx.BoxSizer(wx.VERTICAL)
  1207             plcwindowsizer.AddSizer(plcwindowmainsizer, 0, border=5, flag=wx.ALL)
  1207             plcwindowsizer.AddSizer(plcwindowmainsizer, 0, border=5, flag=wx.ALL)
  1208             
  1208             
  1209             plcwindowbuttonsizer = wx.BoxSizer(wx.HORIZONTAL)
  1209             plcwindowbuttonsizer = wx.BoxSizer(wx.HORIZONTAL)
  1210             plcwindowmainsizer.AddSizer(plcwindowbuttonsizer, 0, border=0, flag=wx.ALIGN_CENTER)
  1210             plcwindowmainsizer.AddSizer(plcwindowbuttonsizer, 0, border=0, flag=wx.ALIGN_CENTER)
  1211             
  1211             
  1212             msizer = self.GenerateMethodButtonSizer(self.PluginRoot, plcwindow, not self.PluginInfos[self.PluginRoot]["right_visible"])
  1212             msizer = self.GenerateMethodButtonSizer(self.CTR, plcwindow, not self.ConfNodeInfos[self.CTR]["right_visible"])
  1213             plcwindowbuttonsizer.AddSizer(msizer, 0, border=0, flag=wx.GROW)
  1213             plcwindowbuttonsizer.AddSizer(msizer, 0, border=0, flag=wx.GROW)
  1214             
  1214             
  1215         self.PLCConfigMainSizer.Layout()
  1215         self.PLCConfigMainSizer.Layout()
  1216         self.RefreshScrollBars()
  1216         self.RefreshScrollBars()
  1217         self.Thaw()
  1217         self.Thaw()
  1218 
  1218 
  1219     def GenerateTreeBranch(self, plugin):
  1219     def GenerateTreeBranch(self, confnode):
  1220         leftwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1))
  1220         leftwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1))
  1221         if plugin.PlugTestModified():
  1221         if confnode.PlugTestModified():
  1222             bkgdclr=CHANGED_WINDOW_COLOUR
  1222             bkgdclr=CHANGED_WINDOW_COLOUR
  1223         else:
  1223         else:
  1224             bkgdclr=WINDOW_COLOUR
  1224             bkgdclr=WINDOW_COLOUR
  1225 
  1225 
  1226         leftwindow.SetBackgroundColour(bkgdclr)
  1226         leftwindow.SetBackgroundColour(bkgdclr)
  1227         
  1227         
  1228         if plugin not in self.PluginInfos:
  1228         if confnode not in self.ConfNodeInfos:
  1229             self.PluginInfos[plugin] = {"expanded" : False, "left_visible" : False, "right_visible" : False}
  1229             self.ConfNodeInfos[confnode] = {"expanded" : False, "left_visible" : False, "right_visible" : False}
  1230             
  1230             
  1231         self.PluginInfos[plugin]["children"] = plugin.IECSortedChilds()
  1231         self.ConfNodeInfos[confnode]["children"] = confnode.IECSortedChilds()
  1232         plugin_infos = plugin.GetVariableLocationTree()
  1232         confnode_infos = confnode.GetVariableLocationTree()
  1233         plugin_locations = []
  1233         confnode_locations = []
  1234         if len(self.PluginInfos[plugin]["children"]) == 0:
  1234         if len(self.ConfNodeInfos[confnode]["children"]) == 0:
  1235             plugin_locations = plugin_infos["children"]
  1235             confnode_locations = confnode_infos["children"]
  1236             if not self.PluginInfos[plugin].has_key("locations_infos"):
  1236             if not self.ConfNodeInfos[confnode].has_key("locations_infos"):
  1237                 self.PluginInfos[plugin]["locations_infos"] = {"root": {"expanded" : False}}
  1237                 self.ConfNodeInfos[confnode]["locations_infos"] = {"root": {"expanded" : False}}
  1238             
  1238             
  1239             self.PluginInfos[plugin]["locations_infos"]["root"]["left"] = None
  1239             self.ConfNodeInfos[confnode]["locations_infos"]["root"]["left"] = None
  1240             self.PluginInfos[plugin]["locations_infos"]["root"]["right"] = None
  1240             self.ConfNodeInfos[confnode]["locations_infos"]["root"]["right"] = None
  1241             self.PluginInfos[plugin]["locations_infos"]["root"]["children"] = []
  1241             self.ConfNodeInfos[confnode]["locations_infos"]["root"]["children"] = []
  1242         
  1242         
  1243         self.PluginTreeSizer.AddWindow(leftwindow, 0, border=0, flag=wx.GROW)
  1243         self.ConfNodeTreeSizer.AddWindow(leftwindow, 0, border=0, flag=wx.GROW)
  1244         
  1244         
  1245         leftwindowvsizer = wx.BoxSizer(wx.VERTICAL)
  1245         leftwindowvsizer = wx.BoxSizer(wx.VERTICAL)
  1246         leftwindow.SetSizer(leftwindowvsizer)
  1246         leftwindow.SetSizer(leftwindowvsizer)
  1247         
  1247         
  1248         leftwindowsizer = wx.BoxSizer(wx.HORIZONTAL)
  1248         leftwindowsizer = wx.BoxSizer(wx.HORIZONTAL)
  1249         leftwindowvsizer.AddSizer(leftwindowsizer, 0, border=0, flag=0)
  1249         leftwindowvsizer.AddSizer(leftwindowsizer, 0, border=0, flag=0)
  1250         
  1250         
  1251         self.GenerateEnableButton(leftwindow, leftwindowsizer, plugin)
  1251         self.GenerateEnableButton(leftwindow, leftwindowsizer, confnode)
  1252         
  1252         
  1253         st = wx.StaticText(leftwindow, -1)
  1253         st = wx.StaticText(leftwindow, -1)
  1254         st.SetFont(wx.Font(faces["size"], wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"]))
  1254         st.SetFont(wx.Font(faces["size"], wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"]))
  1255         st.SetLabel(plugin.GetFullIEC_Channel())
  1255         st.SetLabel(confnode.GetFullIEC_Channel())
  1256         leftwindowsizer.AddWindow(st, 0, border=5, flag=wx.RIGHT)
  1256         leftwindowsizer.AddWindow(st, 0, border=5, flag=wx.RIGHT)
  1257         
  1257         
  1258         expandbutton_id = wx.NewId()
  1258         expandbutton_id = wx.NewId()
  1259         expandbutton = wx.lib.buttons.GenBitmapToggleButton(id=expandbutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'plus.png')),
  1259         expandbutton = wx.lib.buttons.GenBitmapToggleButton(id=expandbutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'plus.png')),
  1260               name='ExpandButton', parent=leftwindow, pos=wx.Point(0, 0),
  1260               name='ExpandButton', parent=leftwindow, pos=wx.Point(0, 0),
  1262         expandbutton.labelDelta = 0
  1262         expandbutton.labelDelta = 0
  1263         expandbutton.SetBezelWidth(0)
  1263         expandbutton.SetBezelWidth(0)
  1264         expandbutton.SetUseFocusIndicator(False)
  1264         expandbutton.SetUseFocusIndicator(False)
  1265         expandbutton.SetBitmapSelected(wx.Bitmap(Bpath( 'images', 'minus.png')))
  1265         expandbutton.SetBitmapSelected(wx.Bitmap(Bpath( 'images', 'minus.png')))
  1266             
  1266             
  1267         if len(self.PluginInfos[plugin]["children"]) > 0:
  1267         if len(self.ConfNodeInfos[confnode]["children"]) > 0:
  1268             expandbutton.SetToggle(self.PluginInfos[plugin]["expanded"])
  1268             expandbutton.SetToggle(self.ConfNodeInfos[confnode]["expanded"])
  1269             def togglebutton(event):
  1269             def togglebutton(event):
  1270                 if expandbutton.GetToggle():
  1270                 if expandbutton.GetToggle():
  1271                     self.ExpandPlugin(plugin)
  1271                     self.ExpandConfNode(confnode)
  1272                 else:
  1272                 else:
  1273                     self.CollapsePlugin(plugin)
  1273                     self.CollapseConfNode(confnode)
  1274                 self.PluginInfos[plugin]["expanded"] = expandbutton.GetToggle()
  1274                 self.ConfNodeInfos[confnode]["expanded"] = expandbutton.GetToggle()
  1275                 self.PLCConfigMainSizer.Layout()
  1275                 self.PLCConfigMainSizer.Layout()
  1276                 self.RefreshScrollBars()
  1276                 self.RefreshScrollBars()
  1277                 event.Skip()
  1277                 event.Skip()
  1278             expandbutton.Bind(wx.EVT_BUTTON, togglebutton, id=expandbutton_id)
  1278             expandbutton.Bind(wx.EVT_BUTTON, togglebutton, id=expandbutton_id)
  1279         elif len(plugin_locations) > 0:
  1279         elif len(confnode_locations) > 0:
  1280             locations_infos = self.PluginInfos[plugin]["locations_infos"]
  1280             locations_infos = self.ConfNodeInfos[confnode]["locations_infos"]
  1281             expandbutton.SetToggle(locations_infos["root"]["expanded"])
  1281             expandbutton.SetToggle(locations_infos["root"]["expanded"])
  1282             def togglebutton(event):
  1282             def togglebutton(event):
  1283                 if expandbutton.GetToggle():
  1283                 if expandbutton.GetToggle():
  1284                     self.ExpandLocation(locations_infos, "root")
  1284                     self.ExpandLocation(locations_infos, "root")
  1285                 else:
  1285                 else:
  1286                     self.CollapseLocation(locations_infos, "root")
  1286                     self.CollapseLocation(locations_infos, "root")
  1287                 self.PluginInfos[plugin]["expanded"] = expandbutton.GetToggle()
  1287                 self.ConfNodeInfos[confnode]["expanded"] = expandbutton.GetToggle()
  1288                 locations_infos["root"]["expanded"] = expandbutton.GetToggle()
  1288                 locations_infos["root"]["expanded"] = expandbutton.GetToggle()
  1289                 self.PLCConfigMainSizer.Layout()
  1289                 self.PLCConfigMainSizer.Layout()
  1290                 self.RefreshScrollBars()
  1290                 self.RefreshScrollBars()
  1291                 event.Skip()
  1291                 event.Skip()
  1292             expandbutton.Bind(wx.EVT_BUTTON, togglebutton, id=expandbutton_id)
  1292             expandbutton.Bind(wx.EVT_BUTTON, togglebutton, id=expandbutton_id)
  1293         else:
  1293         else:
  1294             expandbutton.Enable(False)
  1294             expandbutton.Enable(False)
  1295         leftwindowsizer.AddWindow(expandbutton, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL)
  1295         leftwindowsizer.AddWindow(expandbutton, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL)
  1296         
  1296         
  1297         sb = wx.StaticBitmap(leftwindow, -1)
  1297         sb = wx.StaticBitmap(leftwindow, -1)
  1298         icon = plugin_infos.get("icon", None)
  1298         icon = confnode_infos.get("icon", None)
  1299         if icon is None:
  1299         if icon is None:
  1300             icon_bitmap = self.LocationImageList.GetBitmap(self.LocationImageDict[plugin_infos["type"]])
  1300             icon_bitmap = self.LocationImageList.GetBitmap(self.LocationImageDict[confnode_infos["type"]])
  1301         else: 
  1301         else: 
  1302             icon_bitmap = wx.Bitmap(icon)
  1302             icon_bitmap = wx.Bitmap(icon)
  1303         sb.SetBitmap(icon_bitmap)
  1303         sb.SetBitmap(icon_bitmap)
  1304         leftwindowsizer.AddWindow(sb, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL)
  1304         leftwindowsizer.AddWindow(sb, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL)
  1305         
  1305         
  1306         st_id = wx.NewId()
  1306         st_id = wx.NewId()
  1307         st = wx.StaticText(leftwindow, st_id, size=wx.DefaultSize, style=wx.NO_BORDER)
  1307         st = wx.StaticText(leftwindow, st_id, size=wx.DefaultSize, style=wx.NO_BORDER)
  1308         st.SetFont(wx.Font(faces["size"] * 0.75, wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"]))
  1308         st.SetFont(wx.Font(faces["size"] * 0.75, wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"]))
  1309         st.SetLabel(plugin.MandatoryParams[1].getName())
  1309         st.SetLabel(confnode.MandatoryParams[1].getName())
  1310         leftwindowsizer.AddWindow(st, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL)
  1310         leftwindowsizer.AddWindow(st, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL)
  1311         
  1311         
  1312         rightwindow = self.GenerateParamsPanel(plugin, bkgdclr)
  1312         rightwindow = self.GenerateParamsPanel(confnode, bkgdclr)
  1313         self.PluginTreeSizer.AddWindow(rightwindow, 0, border=0, flag=wx.GROW)
  1313         self.ConfNodeTreeSizer.AddWindow(rightwindow, 0, border=0, flag=wx.GROW)
  1314 
  1314 
  1315         self.PluginInfos[plugin]["left"] = leftwindow
  1315         self.ConfNodeInfos[confnode]["left"] = leftwindow
  1316         self.PluginInfos[plugin]["right"] = rightwindow
  1316         self.ConfNodeInfos[confnode]["right"] = rightwindow
  1317         for child in self.PluginInfos[plugin]["children"]:
  1317         for child in self.ConfNodeInfos[confnode]["children"]:
  1318             self.GenerateTreeBranch(child)
  1318             self.GenerateTreeBranch(child)
  1319             if not self.PluginInfos[child]["expanded"]:
  1319             if not self.ConfNodeInfos[child]["expanded"]:
  1320                 self.CollapsePlugin(child)
  1320                 self.CollapseConfNode(child)
  1321         
  1321         
  1322         if len(plugin_locations) > 0:
  1322         if len(confnode_locations) > 0:
  1323             locations_infos = self.PluginInfos[plugin]["locations_infos"]
  1323             locations_infos = self.ConfNodeInfos[confnode]["locations_infos"]
  1324             treectrl = wx.TreeCtrl(self.PLCConfig, -1, size=wx.DefaultSize, 
  1324             treectrl = wx.TreeCtrl(self.PLCConfig, -1, size=wx.DefaultSize, 
  1325                                    style=wx.TR_HAS_BUTTONS|wx.TR_SINGLE|wx.NO_BORDER|wx.TR_HIDE_ROOT|wx.TR_NO_LINES|wx.TR_LINES_AT_ROOT)
  1325                                    style=wx.TR_HAS_BUTTONS|wx.TR_SINGLE|wx.NO_BORDER|wx.TR_HIDE_ROOT|wx.TR_NO_LINES|wx.TR_LINES_AT_ROOT)
  1326             treectrl.SetImageList(self.LocationImageList)
  1326             treectrl.SetImageList(self.LocationImageList)
  1327             treectrl.Bind(wx.EVT_TREE_BEGIN_DRAG, self.GenerateLocationBeginDragFunction(locations_infos))
  1327             treectrl.Bind(wx.EVT_TREE_BEGIN_DRAG, self.GenerateLocationBeginDragFunction(locations_infos))
  1328             treectrl.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.GenerateLocationExpandCollapseFunction(locations_infos, True))
  1328             treectrl.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.GenerateLocationExpandCollapseFunction(locations_infos, True))
  1329             treectrl.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.GenerateLocationExpandCollapseFunction(locations_infos, False))
  1329             treectrl.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.GenerateLocationExpandCollapseFunction(locations_infos, False))
  1330             
  1330             
  1331             treectrl.AddRoot("")
  1331             treectrl.AddRoot("")
  1332             self.PluginTreeSizer.AddWindow(treectrl, 0, border=0, flag=0)
  1332             self.ConfNodeTreeSizer.AddWindow(treectrl, 0, border=0, flag=0)
  1333             
  1333             
  1334             rightwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1))
  1334             rightwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1))
  1335             rightwindow.SetBackgroundColour(wx.WHITE)
  1335             rightwindow.SetBackgroundColour(wx.WHITE)
  1336             self.PluginTreeSizer.AddWindow(rightwindow, 0, border=0, flag=wx.GROW)
  1336             self.ConfNodeTreeSizer.AddWindow(rightwindow, 0, border=0, flag=wx.GROW)
  1337             
  1337             
  1338             locations_infos["root"]["left"] = treectrl
  1338             locations_infos["root"]["left"] = treectrl
  1339             locations_infos["root"]["right"] = rightwindow
  1339             locations_infos["root"]["right"] = rightwindow
  1340             for location in plugin_locations:
  1340             for location in confnode_locations:
  1341                 locations_infos["root"]["children"].append("root.%s" % location["name"])
  1341                 locations_infos["root"]["children"].append("root.%s" % location["name"])
  1342                 self.GenerateLocationTreeBranch(treectrl, treectrl.GetRootItem(), locations_infos, "root", location)
  1342                 self.GenerateLocationTreeBranch(treectrl, treectrl.GetRootItem(), locations_infos, "root", location)
  1343             if locations_infos["root"]["expanded"]:
  1343             if locations_infos["root"]["expanded"]:
  1344                 self.ExpandLocation(locations_infos, "root")
  1344                 self.ExpandLocation(locations_infos, "root")
  1345 
  1345 
  1414     class LPCBeremiz_Cmd(cmd.Cmd):
  1414     class LPCBeremiz_Cmd(cmd.Cmd):
  1415         
  1415         
  1416         prompt = ""
  1416         prompt = ""
  1417         RefreshTimer = None
  1417         RefreshTimer = None
  1418         
  1418         
  1419         def __init__(self, PluginRoot, Log):
  1419         def __init__(self, CTR, Log):
  1420             cmd.Cmd.__init__(self, stdin=Log, stdout=Log)
  1420             cmd.Cmd.__init__(self, stdin=Log, stdout=Log)
  1421             self.use_rawinput = False
  1421             self.use_rawinput = False
  1422             self.Log = Log
  1422             self.Log = Log
  1423             self.PluginRoot = PluginRoot
  1423             self.CTR = CTR
  1424             
  1424             
  1425         def RestartTimer(self):
  1425         def RestartTimer(self):
  1426             if self.RefreshTimer is not None:
  1426             if self.RefreshTimer is not None:
  1427                 self.RefreshTimer.cancel()
  1427                 self.RefreshTimer.cancel()
  1428             self.RefreshTimer = Timer(0.1, wx.CallAfter, args = [self.Refresh])
  1428             self.RefreshTimer = Timer(0.1, wx.CallAfter, args = [self.Refresh])
  1438             return self.Exit()
  1438             return self.Exit()
  1439         
  1439         
  1440         def Show(self):
  1440         def Show(self):
  1441             global frame
  1441             global frame
  1442             if frame is not None:
  1442             if frame is not None:
  1443                 self.PluginRoot.SetAppFrame(frame, frame.Log)
  1443                 self.CTR.SetAppFrame(frame, frame.Log)
  1444                 frame.Show()
  1444                 frame.Show()
  1445                 frame.Raise()
  1445                 frame.Raise()
  1446         
  1446         
  1447         def Refresh(self):
  1447         def Refresh(self):
  1448             global frame
  1448             global frame
  1452                 frame.RefreshAll()
  1452                 frame.RefreshAll()
  1453         
  1453         
  1454         def Close(self):
  1454         def Close(self):
  1455             global frame
  1455             global frame
  1456             
  1456             
  1457             self.PluginRoot.ResetAppFrame(self.Log)
  1457             self.CTR.ResetAppFrame(self.Log)
  1458             if frame is not None:
  1458             if frame is not None:
  1459                 frame.Hide()
  1459                 frame.Hide()
  1460         
  1460         
  1461         def Compile(self):
  1461         def Compile(self):
  1462             self.PluginRoot._Build()
  1462             self.CTR._Build()
  1463         
  1463         
  1464         def SetProjectProperties(self, projectname, productname, productversion, companyname):
  1464         def SetProjectProperties(self, projectname, productname, productversion, companyname):
  1465             properties = self.PluginRoot.GetProjectProperties()
  1465             properties = self.CTR.GetProjectProperties()
  1466             new_properties = properties.copy()
  1466             new_properties = properties.copy()
  1467             new_properties["projectName"] = projectname
  1467             new_properties["projectName"] = projectname
  1468             new_properties["productName"] = productname
  1468             new_properties["productName"] = productname
  1469             new_properties["productVersion"] = productversion
  1469             new_properties["productVersion"] = productversion
  1470             new_properties["companyName"] = companyname
  1470             new_properties["companyName"] = companyname
  1471             if new_properties != properties:
  1471             if new_properties != properties:
  1472                 self.PluginRoot.SetProjectProperties(properties=new_properties, buffer=False)
  1472                 self.CTR.SetProjectProperties(properties=new_properties, buffer=False)
  1473                 self.RestartTimer()
  1473                 self.RestartTimer()
  1474         
  1474         
  1475         def SetOnlineMode(self, mode, path=None):
  1475         def SetOnlineMode(self, mode, path=None):
  1476             self.PluginRoot.SetOnlineMode(mode, path)
  1476             self.CTR.SetOnlineMode(mode, path)
  1477             self.RestartTimer()
  1477             self.RestartTimer()
  1478         
  1478         
  1479         def AddBus(self, iec_channel, name, icon=None):
  1479         def AddBus(self, iec_channel, name, icon=None):
  1480             for child in self.PluginRoot.IterChilds():
  1480             for child in self.CTR.IterChilds():
  1481                 if child.BaseParams.getName() == name:
  1481                 if child.BaseParams.getName() == name:
  1482                     return "Error: A bus named %s already exists\n" % name
  1482                     return "Error: A bus named %s already exists\n" % name
  1483                 elif child.BaseParams.getIEC_Channel() == iec_channel:
  1483                 elif child.BaseParams.getIEC_Channel() == iec_channel:
  1484                     return "Error: A bus with IEC_channel %d already exists\n" % iec_channel
  1484                     return "Error: A bus with IEC_channel %d already exists\n" % iec_channel
  1485             bus = self.PluginRoot.PlugAddChild(name, "LPCBus", iec_channel)
  1485             bus = self.CTR.PlugAddChild(name, "LPCBus", iec_channel)
  1486             if bus is None:
  1486             if bus is None:
  1487                 return "Error: Unable to create bus\n"
  1487                 return "Error: Unable to create bus\n"
  1488             bus.SetIcon(icon)
  1488             bus.SetIcon(icon)
  1489             self.RestartTimer()
  1489             self.RestartTimer()
  1490         
  1490         
  1491         def RenameBus(self, iec_channel, name):
  1491         def RenameBus(self, iec_channel, name):
  1492             bus = self.PluginRoot.GetChildByIECLocation((iec_channel,))
  1492             bus = self.CTR.GetChildByIECLocation((iec_channel,))
  1493             if bus is None:
  1493             if bus is None:
  1494                 return "Error: No bus found\n"
  1494                 return "Error: No bus found\n"
  1495             for child in self.PluginRoot.IterChilds():
  1495             for child in self.CTR.IterChilds():
  1496                 if child != bus and child.BaseParams.getName() == name:
  1496                 if child != bus and child.BaseParams.getName() == name:
  1497                     return "Error: A bus named %s already exists\n" % name
  1497                     return "Error: A bus named %s already exists\n" % name
  1498             bus.BaseParams.setName(name)
  1498             bus.BaseParams.setName(name)
  1499             self.RestartTimer()
  1499             self.RestartTimer()
  1500         
  1500         
  1501         def ChangeBusIECChannel(self, old_iec_channel, new_iec_channel):
  1501         def ChangeBusIECChannel(self, old_iec_channel, new_iec_channel):
  1502             bus = self.PluginRoot.GetChildByIECLocation((old_iec_channel,))
  1502             bus = self.CTR.GetChildByIECLocation((old_iec_channel,))
  1503             if bus is None:
  1503             if bus is None:
  1504                 return "Error: No bus found\n"
  1504                 return "Error: No bus found\n"
  1505             for child in self.PluginRoot.IterChilds():
  1505             for child in self.CTR.IterChilds():
  1506                 if child != bus and child.BaseParams.getIEC_Channel() == new_iec_channel:
  1506                 if child != bus and child.BaseParams.getIEC_Channel() == new_iec_channel:
  1507                     return "Error: A bus with IEC_channel %d already exists\n" % new_iec_channel
  1507                     return "Error: A bus with IEC_channel %d already exists\n" % new_iec_channel
  1508             if wx.GetApp() is None:
  1508             if wx.GetApp() is None:
  1509                 self.PluginRoot.UpdateProjectVariableLocation(str(old_iec_channel), 
  1509                 self.CTR.UpdateProjectVariableLocation(str(old_iec_channel), 
  1510                                                               str(new_iec_channel))
  1510                                                               str(new_iec_channel))
  1511             else:
  1511             else:
  1512                 self.PluginRoot.UpdateProjectVariableLocation(
  1512                 self.CTR.UpdateProjectVariableLocation(
  1513                              str(old_iec_channel), 
  1513                              str(old_iec_channel), 
  1514                              str(new_iec_channel))
  1514                              str(new_iec_channel))
  1515             bus.BaseParams.setIEC_Channel(new_iec_channel)
  1515             bus.BaseParams.setIEC_Channel(new_iec_channel)
  1516             self.RestartTimer()
  1516             self.RestartTimer()
  1517         
  1517         
  1518         def RemoveBus(self, iec_channel):
  1518         def RemoveBus(self, iec_channel):
  1519             bus = self.PluginRoot.GetChildByIECLocation((iec_channel,))
  1519             bus = self.CTR.GetChildByIECLocation((iec_channel,))
  1520             if bus is None:
  1520             if bus is None:
  1521                 return "Error: No bus found\n"
  1521                 return "Error: No bus found\n"
  1522             self.PluginRoot.RemoveProjectVariableByFilter(str(iec_channel))
  1522             self.CTR.RemoveProjectVariableByFilter(str(iec_channel))
  1523             self.PluginRoot.PluggedChilds["LPCBus"].remove(bus)
  1523             self.CTR.PluggedChilds["LPCBus"].remove(bus)
  1524             self.RestartTimer()
  1524             self.RestartTimer()
  1525     
  1525     
  1526         def AddModule(self, parent, iec_channel, name, icode, icon=None):
  1526         def AddModule(self, parent, iec_channel, name, icode, icon=None):
  1527             module = self.PluginRoot.GetChildByIECLocation(parent)
  1527             module = self.CTR.GetChildByIECLocation(parent)
  1528             if module is None:
  1528             if module is None:
  1529                 return "Error: No parent found\n"
  1529                 return "Error: No parent found\n"
  1530             for child in _GetModuleChildren(module):
  1530             for child in _GetModuleChildren(module):
  1531                 if child["name"] == name:
  1531                 if child["name"] == name:
  1532                     return "Error: A module named %s already exists\n" % name
  1532                     return "Error: A module named %s already exists\n" % name
  1539                                                 "init": icode, 
  1539                                                 "init": icode, 
  1540                                                 "children": []})
  1540                                                 "children": []})
  1541             self.RestartTimer()
  1541             self.RestartTimer()
  1542     
  1542     
  1543         def RenameModule(self, iec_location, name):
  1543         def RenameModule(self, iec_location, name):
  1544             module = self.PluginRoot.GetChildByIECLocation(iec_location)
  1544             module = self.CTR.GetChildByIECLocation(iec_location)
  1545             if module is None:
  1545             if module is None:
  1546                 return "Error: No module found\n"
  1546                 return "Error: No module found\n"
  1547             parent = self.PluginRoot.GetChildByIECLocation(iec_location[:-1])
  1547             parent = self.CTR.GetChildByIECLocation(iec_location[:-1])
  1548             if parent is self.PluginRoot:
  1548             if parent is self.CTR:
  1549                 return "Error: No module found\n"
  1549                 return "Error: No module found\n"
  1550             if module["name"] != name:
  1550             if module["name"] != name:
  1551                 for child in _GetModuleChildren(parent):
  1551                 for child in _GetModuleChildren(parent):
  1552                     if child["name"] == name:
  1552                     if child["name"] == name:
  1553                         return "Error: A module named %s already exists\n" % name
  1553                         return "Error: A module named %s already exists\n" % name
  1554                 module["name"] = name
  1554                 module["name"] = name
  1555             self.RestartTimer()
  1555             self.RestartTimer()
  1556     
  1556     
  1557         def ChangeModuleIECChannel(self, old_iec_location, new_iec_channel):
  1557         def ChangeModuleIECChannel(self, old_iec_location, new_iec_channel):
  1558             module = self.PluginRoot.GetChildByIECLocation(old_iec_location)
  1558             module = self.CTR.GetChildByIECLocation(old_iec_location)
  1559             if module is None:
  1559             if module is None:
  1560                 return "Error: No module found\n"
  1560                 return "Error: No module found\n"
  1561             parent = self.PluginRoot.GetChildByIECLocation(old_iec_location[:-1])
  1561             parent = self.CTR.GetChildByIECLocation(old_iec_location[:-1])
  1562             if parent is self.PluginRoot:
  1562             if parent is self.CTR:
  1563                 return "Error: No module found\n"
  1563                 return "Error: No module found\n"
  1564             if module["IEC_Channel"] != new_iec_channel:
  1564             if module["IEC_Channel"] != new_iec_channel:
  1565                 for child in _GetModuleChildren(parent):
  1565                 for child in _GetModuleChildren(parent):
  1566                     if child["IEC_Channel"] == new_iec_channel:
  1566                     if child["IEC_Channel"] == new_iec_channel:
  1567                         return "Error: A module with IEC_channel %d already exists\n" % new_iec_channel
  1567                         return "Error: A module with IEC_channel %d already exists\n" % new_iec_channel
  1568             self.PluginRoot.UpdateProjectVariableLocation(".".join(map(str, old_iec_location)), ".".join(map(str, old_iec_location[:1] + (new_iec_channel,))))
  1568             self.CTR.UpdateProjectVariableLocation(".".join(map(str, old_iec_location)), ".".join(map(str, old_iec_location[:1] + (new_iec_channel,))))
  1569             module["IEC_Channel"] = new_iec_channel
  1569             module["IEC_Channel"] = new_iec_channel
  1570             self.RestartTimer()
  1570             self.RestartTimer()
  1571         
  1571         
  1572         def ChangeModuleInitCode(self, iec_location, icode):
  1572         def ChangeModuleInitCode(self, iec_location, icode):
  1573             module = self.PluginRoot.GetChildByIECLocation(iec_location)
  1573             module = self.CTR.GetChildByIECLocation(iec_location)
  1574             if module is None:
  1574             if module is None:
  1575                 return "Error: No module found\n"
  1575                 return "Error: No module found\n"
  1576             module["init"] = icode
  1576             module["init"] = icode
  1577         
  1577         
  1578         def RemoveModule(self, parent, iec_channel):
  1578         def RemoveModule(self, parent, iec_channel):
  1579             module = self.PluginRoot.GetChildByIECLocation(parent)
  1579             module = self.CTR.GetChildByIECLocation(parent)
  1580             if module is None:
  1580             if module is None:
  1581                 return "Error: No parent found\n"
  1581                 return "Error: No parent found\n"
  1582             child = _GetModuleBySomething(module, "IEC_Channel", (iec_channel,))
  1582             child = _GetModuleBySomething(module, "IEC_Channel", (iec_channel,))
  1583             if child is None:
  1583             if child is None:
  1584                 return "Error: No module found\n"
  1584                 return "Error: No module found\n"
  1585             self.PluginRoot.RemoveProjectVariableByFilter(".".join(map(str, parent + (iec_channel,))))
  1585             self.CTR.RemoveProjectVariableByFilter(".".join(map(str, parent + (iec_channel,))))
  1586             _RemoveModuleChild(module, child)
  1586             _RemoveModuleChild(module, child)
  1587             self.RestartTimer()
  1587             self.RestartTimer()
  1588         
  1588         
  1589         def StartGroup(self, parent, name, icon=None):
  1589         def StartGroup(self, parent, name, icon=None):
  1590             module = self.PluginRoot.GetChildByIECLocation(parent)
  1590             module = self.CTR.GetChildByIECLocation(parent)
  1591             if module is None:
  1591             if module is None:
  1592                 return "Error: No parent found\n"
  1592                 return "Error: No parent found\n"
  1593             for child in module["children"]:
  1593             for child in module["children"]:
  1594                 if child["type"] == LOCATION_GROUP and child["name"] == name:
  1594                 if child["type"] == LOCATION_GROUP and child["name"] == name:
  1595                     return "Error: A group named %s already exists\n" % name
  1595                     return "Error: A group named %s already exists\n" % name
  1598                                       "icon": icon, 
  1598                                       "icon": icon, 
  1599                                       "children": []})
  1599                                       "children": []})
  1600             self.RestartTimer()
  1600             self.RestartTimer()
  1601     
  1601     
  1602         def AddVariable(self, parent, location, name, direction, type, rcode, pcode, description=""):
  1602         def AddVariable(self, parent, location, name, direction, type, rcode, pcode, description=""):
  1603             module = self.PluginRoot.GetChildByIECLocation(parent)
  1603             module = self.CTR.GetChildByIECLocation(parent)
  1604             if module is None:
  1604             if module is None:
  1605                 return "Error: No parent found\n"
  1605                 return "Error: No parent found\n"
  1606             for child in _GetModuleChildren(module):
  1606             for child in _GetModuleChildren(module):
  1607                 if child["name"] == name:
  1607                 if child["name"] == name:
  1608                     return "Error: A variable named %s already exists\n" % name
  1608                     return "Error: A variable named %s already exists\n" % name
  1616                                                 "retrieve": rcode, 
  1616                                                 "retrieve": rcode, 
  1617                                                 "publish": pcode})
  1617                                                 "publish": pcode})
  1618             self.RestartTimer()
  1618             self.RestartTimer()
  1619 
  1619 
  1620         def ChangeVariableParams(self, parent, location, new_name, new_direction, new_type, new_rcode, new_pcode, new_description=None):
  1620         def ChangeVariableParams(self, parent, location, new_name, new_direction, new_type, new_rcode, new_pcode, new_description=None):
  1621             module = self.PluginRoot.GetChildByIECLocation(parent)
  1621             module = self.CTR.GetChildByIECLocation(parent)
  1622             if module is None:
  1622             if module is None:
  1623                 return "Error: No parent found\n"
  1623                 return "Error: No parent found\n"
  1624             variable = None
  1624             variable = None
  1625             for child in _GetModuleChildren(module):
  1625             for child in _GetModuleChildren(module):
  1626                 if child["location"] == location and child["type"] == LOCATION_TYPES[new_direction]:
  1626                 if child["location"] == location and child["type"] == LOCATION_TYPES[new_direction]:
  1628                 elif child["name"] == new_name:
  1628                 elif child["name"] == new_name:
  1629                     return "Error: A variable named %s already exists\n" % new_name
  1629                     return "Error: A variable named %s already exists\n" % new_name
  1630             if variable is None:
  1630             if variable is None:
  1631                 return "Error: No variable found\n"
  1631                 return "Error: No variable found\n"
  1632             if variable["name"] != new_name:
  1632             if variable["name"] != new_name:
  1633                 self.PluginRoot.UpdateProjectVariableName(variable["name"], new_name)
  1633                 self.CTR.UpdateProjectVariableName(variable["name"], new_name)
  1634                 variable["name"] = new_name
  1634                 variable["name"] = new_name
  1635             variable["type"] = LOCATION_TYPES[new_direction]
  1635             variable["type"] = LOCATION_TYPES[new_direction]
  1636             variable["IEC_type"] = new_type
  1636             variable["IEC_type"] = new_type
  1637             variable["retrieve"] = new_rcode
  1637             variable["retrieve"] = new_rcode
  1638             variable["publish"] = new_pcode
  1638             variable["publish"] = new_pcode
  1639             if new_description is not None:
  1639             if new_description is not None:
  1640                 variable["description"] = new_description
  1640                 variable["description"] = new_description
  1641             self.RestartTimer()
  1641             self.RestartTimer()
  1642     
  1642     
  1643         def RemoveVariable(self, parent, location, direction):
  1643         def RemoveVariable(self, parent, location, direction):
  1644             module = self.PluginRoot.GetChildByIECLocation(parent)
  1644             module = self.CTR.GetChildByIECLocation(parent)
  1645             if module is None:
  1645             if module is None:
  1646                 return "Error: No parent found\n"
  1646                 return "Error: No parent found\n"
  1647             child = _GetModuleVariable(module, location, direction)
  1647             child = _GetModuleVariable(module, location, direction)
  1648             if child is None:
  1648             if child is None:
  1649                 return "Error: No variable found\n"
  1649                 return "Error: No variable found\n"
  1650             size = LOCATION_SIZES[self.PluginRoot.GetBaseType(child["IEC_type"])]
  1650             size = LOCATION_SIZES[self.CTR.GetBaseType(child["IEC_type"])]
  1651             address = "%" + LOCATION_DIRS[child["type"]] + size + ".".join(map(str, parent + location))
  1651             address = "%" + LOCATION_DIRS[child["type"]] + size + ".".join(map(str, parent + location))
  1652             self.PluginRoot.RemoveProjectVariableByAddress(address)
  1652             self.CTR.RemoveProjectVariableByAddress(address)
  1653             _RemoveModuleChild(module, child)
  1653             _RemoveModuleChild(module, child)
  1654             self.RestartTimer()
  1654             self.RestartTimer()
  1655         
  1655         
  1656     def location(loc):
  1656     def location(loc):
  1657         return tuple(map(int, loc.split(".")))
  1657         return tuple(map(int, loc.split(".")))
  1712                 return False
  1712                 return False
  1713             else:
  1713             else:
  1714                 return res
  1714                 return res
  1715         return CmdFunction
  1715         return CmdFunction
  1716 
  1716 
  1717     def CmdThreadProc(PluginRoot, Log):
  1717     def CmdThreadProc(CTR, Log):
  1718         global lpcberemiz_cmd
  1718         global lpcberemiz_cmd
  1719         for function, (arg_types, opt) in {"Exit": ([], 0),
  1719         for function, (arg_types, opt) in {"Exit": ([], 0),
  1720                                            "Show": ([], 0),
  1720                                            "Show": ([], 0),
  1721                                            "Refresh": ([], 0),
  1721                                            "Refresh": ([], 0),
  1722                                            "Close": ([], 0),
  1722                                            "Close": ([], 0),
  1736                                            "AddVariable": ([location, location, str, str, str, str, str, str], 1),
  1736                                            "AddVariable": ([location, location, str, str, str, str, str, str], 1),
  1737                                            "ChangeVariableParams": ([location, location, str, str, str, str, str, str], 1),
  1737                                            "ChangeVariableParams": ([location, location, str, str, str, str, str, str], 1),
  1738                                            "RemoveVariable": ([location, location], 0)}.iteritems():
  1738                                            "RemoveVariable": ([location, location], 0)}.iteritems():
  1739             
  1739             
  1740             setattr(LPCBeremiz_Cmd, "do_%s" % function, GetCmdFunction(function, arg_types, opt))
  1740             setattr(LPCBeremiz_Cmd, "do_%s" % function, GetCmdFunction(function, arg_types, opt))
  1741         lpcberemiz_cmd = LPCBeremiz_Cmd(PluginRoot, Log)
  1741         lpcberemiz_cmd = LPCBeremiz_Cmd(CTR, Log)
  1742         lpcberemiz_cmd.cmdloop()
  1742         lpcberemiz_cmd.cmdloop()
  1743 
  1743 
  1744     Log = StdoutPseudoFile(port)
  1744     Log = StdoutPseudoFile(port)
  1745 
  1745 
  1746     PluginRoot = LPCPluginsRoot(None, Log, buildpath)
  1746     CTR = LPCConfigTreeRoot(None, Log, buildpath)
  1747     if projectOpen is not None and os.path.isdir(projectOpen):
  1747     if projectOpen is not None and os.path.isdir(projectOpen):
  1748         result = PluginRoot.LoadProject(projectOpen)
  1748         result = CTR.LoadProject(projectOpen)
  1749         if result:
  1749         if result:
  1750             Log.write("Error: Invalid project directory", result)
  1750             Log.write("Error: Invalid project directory", result)
  1751     else:
  1751     else:
  1752         Log.write("Error: No such file or directory")
  1752         Log.write("Error: No such file or directory")
  1753     
  1753     
  1754     cmd_thread=Thread(target=CmdThreadProc, args=[PluginRoot, Log])
  1754     cmd_thread=Thread(target=CmdThreadProc, args=[CTR, Log])
  1755     cmd_thread.start()
  1755     cmd_thread.start()
  1756 
  1756 
  1757     # Install a exception handle for bug reports
  1757     # Install a exception handle for bug reports
  1758     AddExceptHook(os.getcwd(),__version__)
  1758     AddExceptHook(os.getcwd(),__version__)
  1759     
  1759     
  1760     frame = LPCBeremiz(None, plugin_root=PluginRoot, debug=True)
  1760     frame = LPCBeremiz(None, ctr=CTR, debug=True)
  1761     
  1761     
  1762     app.MainLoop()
  1762     app.MainLoop()
  1763     
  1763