laurent@442: #!/usr/bin/env python laurent@442: # -*- coding: utf-8 -*- edouard@503: import shutil laurent@551: import socket laurent@442: laurent@442: __version__ = "$Revision$" laurent@442: laurent@442: import os, sys, getopt, wx, tempfile laurent@442: from types import TupleType, StringType, UnicodeType laurent@442: laurent@442: CWD = os.path.split(os.path.realpath(__file__))[0] laurent@442: laurent@442: def Bpath(*args): laurent@442: return os.path.join(CWD,*args) laurent@442: laurent@442: if __name__ == '__main__': laurent@442: def usage(): laurent@442: print "\nUsage of LPCBeremiz.py :" laurent@551: print "\n %s Projectpath Buildpath port\n"%sys.argv[0] laurent@442: laurent@442: try: laurent@442: opts, args = getopt.getopt(sys.argv[1:], "h", ["help"]) laurent@442: except getopt.GetoptError: laurent@442: # print help information and exit: laurent@442: usage() laurent@442: sys.exit(2) laurent@442: laurent@442: for o, a in opts: laurent@442: if o in ("-h", "--help"): laurent@442: usage() laurent@442: sys.exit() laurent@442: laurent@551: if len(args) != 3: laurent@442: usage() laurent@442: sys.exit() laurent@551: else: laurent@442: projectOpen = args[0] laurent@442: buildpath = args[1] laurent@551: try: laurent@551: port = int(args[2]) laurent@551: except: laurent@551: usage() laurent@551: sys.exit() Lolitech@547: edouard@571: if os.path.exists("LPC_DEBUG"): edouard@571: __builtins__.BMZ_DBG = True edouard@571: else : edouard@571: __builtins__.BMZ_DBG = False edouard@571: edouard@571: app = wx.PySimpleApp(redirect=BMZ_DBG) Lolitech@547: app.SetAppName('beremiz') Lolitech@547: wx.InitAllImageHandlers() laurent@442: laurent@442: # Import module for internationalization laurent@442: import gettext laurent@442: import __builtin__ laurent@442: laurent@442: if __name__ == '__main__': laurent@442: __builtin__.__dict__['_'] = wx.GetTranslation#unicode_translation laurent@442: laurent@442: from Beremiz import * laurent@492: from plugger import PluginsRoot, PlugTemplate, opjimg, connectors laurent@442: from plcopen.structures import LOCATIONDATATYPES laurent@442: from PLCControler import LOCATION_PLUGIN, LOCATION_MODULE, LOCATION_GROUP,\ laurent@442: LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY laurent@500: from PLCOpenEditor import IDEFrame, ProjectDialog laurent@442: laurent@442: #------------------------------------------------------------------------------- edouard@512: # CANFESTIVAL PLUGIN HACK edouard@512: #------------------------------------------------------------------------------- Edouard@629: # from plugins.canfestival import canfestival Edouard@629: # class LPC_canfestival_config: Edouard@629: # def getCFLAGS(self, *args): Edouard@629: # return "" Edouard@629: # Edouard@629: # def getLDFLAGS(self, *args): Edouard@629: # return "" Edouard@629: # Edouard@629: # canfestival.local_canfestival_config = LPC_canfestival_config() edouard@512: #------------------------------------------------------------------------------- laurent@442: # LPCModule Class laurent@442: #------------------------------------------------------------------------------- laurent@442: laurent@472: LOCATION_TYPES = {"I": LOCATION_VAR_INPUT, laurent@472: "Q": LOCATION_VAR_OUTPUT, laurent@472: "M": LOCATION_VAR_MEMORY} laurent@472: laurent@472: LOCATION_DIRS = dict([(dir, size) for size, dir in LOCATION_TYPES.iteritems()]) laurent@472: laurent@472: LOCATION_SIZES = {} laurent@472: for size, types in LOCATIONDATATYPES.iteritems(): laurent@472: for type in types: laurent@472: LOCATION_SIZES[type] = size laurent@472: laurent@442: def _GetModuleChildren(module): laurent@442: children = [] laurent@442: for child in module["children"]: laurent@442: if child["type"] == LOCATION_GROUP: laurent@442: children.extend(child["children"]) laurent@442: else: laurent@442: children.append(child) laurent@442: return children laurent@442: laurent@550: def _GetVariables(module): laurent@550: variables = [] laurent@550: for child in module["children"]: laurent@550: if child["type"] in [LOCATION_GROUP, LOCATION_MODULE]: laurent@550: variables.extend(_GetVariables(child)) laurent@550: else: laurent@550: variables.append(child) laurent@550: return variables laurent@550: laurent@442: def _GetLastModuleGroup(module): laurent@442: group = module laurent@442: for child in module["children"]: laurent@442: if child["type"] == LOCATION_GROUP: laurent@442: group = child laurent@442: return group["children"] laurent@442: laurent@442: def _GetModuleBySomething(module, something, toks): laurent@442: for child in _GetModuleChildren(module): laurent@442: if child.get(something) == toks[0]: laurent@442: if len(toks) > 1: laurent@442: return _GetModuleBySomething(child, something, toks[1:]) laurent@442: return child laurent@442: return None laurent@442: laurent@472: def _GetModuleVariable(module, location, direction): laurent@442: for child in _GetModuleChildren(module): laurent@472: if child["location"] == location and child["type"] == LOCATION_TYPES[direction]: laurent@442: return child laurent@442: return None laurent@442: laurent@442: def _RemoveModuleChild(module, child): laurent@442: if child in module["children"]: laurent@442: module["children"].remove(child) laurent@442: else: laurent@442: for group in module["children"]: laurent@442: if group["type"] == LOCATION_GROUP and child in group["children"]: laurent@442: group["children"].remove(child) laurent@442: laurent@442: BUS_TEXT = """/* Code generated by LPCBus plugin */ laurent@442: laurent@442: /* LPCBus plugin includes */ laurent@442: #include "app_glue.h" laurent@442: #ifdef _WINDOWS_H laurent@442: #include "iec_types.h" laurent@442: #else laurent@442: #include "iec_std_lib.h" laurent@442: #endif laurent@442: laurent@553: %(declare_code)s laurent@553: laurent@442: /* LPCBus plugin user variables definition */ laurent@442: %(var_decl)s laurent@442: laurent@442: /* LPCBus plugin functions */ laurent@442: int __init_%(location_str)s(int argc,char **argv) laurent@442: { laurent@553: %(init_code)s laurent@442: return 0; laurent@442: } laurent@442: laurent@442: void __cleanup_%(location_str)s(void) laurent@442: { laurent@442: } laurent@442: laurent@442: void __retrieve_%(location_str)s(void) laurent@442: { laurent@550: %(retrieve_code)s laurent@442: } laurent@442: laurent@442: void __publish_%(location_str)s(void) laurent@442: { laurent@550: %(publish_code)s laurent@442: } laurent@442: """ laurent@442: laurent@442: class LPCBus(object): laurent@442: laurent@442: def __init__(self): laurent@442: self.VariableLocationTree = [] laurent@442: self.ResetUsedLocations() laurent@442: self.Icon = None laurent@442: laurent@442: def __getitem__(self, key): laurent@442: if key == "children": laurent@442: return self.VariableLocationTree laurent@442: raise KeyError, "Only 'children' key is available" laurent@442: laurent@442: def SetIcon(self, icon): laurent@442: self.Icon = icon laurent@442: laurent@442: def _GetChildBySomething(self, something, toks): laurent@442: return _GetModuleBySomething({"children" : self.VariableLocationTree}, something, toks) laurent@442: laurent@442: def GetBaseTypes(self): laurent@442: return self.GetPlugRoot().GetBaseTypes() laurent@442: laurent@442: def GetSizeOfType(self, type): laurent@442: return LOCATION_SIZES[self.GetPlugRoot().GetBaseType(type)] laurent@442: laurent@442: def _GetVariableLocationTree(self, current_location, infos): laurent@442: if infos["type"] == LOCATION_MODULE: laurent@442: location = current_location + (infos["IEC_Channel"],) laurent@442: return {"name": infos["name"], laurent@442: "type": infos["type"], laurent@442: "location": ".".join(map(str, location + ("x",))), laurent@442: "icon": infos["icon"], laurent@442: "children": [self._GetVariableLocationTree(location, child) for child in infos["children"]]} laurent@442: elif infos["type"] == LOCATION_GROUP: laurent@442: return {"name": infos["name"], laurent@442: "type": infos["type"], laurent@442: "location": "", laurent@442: "icon": infos["icon"], laurent@442: "children": [self._GetVariableLocationTree(current_location, child) for child in infos["children"]]} laurent@442: else: laurent@442: size = self.GetSizeOfType(infos["IEC_type"]) laurent@442: location = "%" + LOCATION_DIRS[infos["type"]] + size + ".".join(map(str, current_location + infos["location"])) laurent@442: return {"name": infos["name"], laurent@442: "type": infos["type"], laurent@442: "size": size, laurent@442: "IEC_type": infos["IEC_type"], laurent@442: "location": location, laurent@442: "description": infos["description"], laurent@442: "children": []} laurent@442: laurent@442: def GetVariableLocationTree(self): laurent@442: return {"name": self.BaseParams.getName(), laurent@442: "type": LOCATION_PLUGIN, laurent@442: "location": self.GetFullIEC_Channel(), laurent@442: "icon": self.Icon, laurent@442: "children": [self._GetVariableLocationTree(self.GetCurrentLocation(), child) laurent@442: for child in self.VariableLocationTree]} laurent@442: laurent@442: def PlugTestModified(self): laurent@442: return False laurent@442: laurent@442: def PlugMakeDir(self): laurent@442: pass laurent@442: laurent@442: def PlugRequestSave(self): laurent@442: return None laurent@442: laurent@442: def ResetUsedLocations(self): laurent@442: self.UsedLocations = {} laurent@442: laurent@442: def _AddUsedLocation(self, parent, location): laurent@442: num = location.pop(0) laurent@442: if not parent.has_key(num): laurent@442: parent[num] = {"used": False, "children": {}} laurent@442: if len(location) > 0: laurent@442: self._AddUsedLocation(parent[num]["children"], location) laurent@442: else: laurent@442: parent[num]["used"] = True laurent@442: laurent@442: def AddUsedLocation(self, location): laurent@442: if len(location) > 0: laurent@442: self._AddUsedLocation(self.UsedLocations, list(location)) laurent@442: laurent@442: def _CheckLocationConflicts(self, parent, location): laurent@442: num = location.pop(0) laurent@442: if not parent.has_key(num): laurent@442: return False laurent@442: if len(location) > 0: laurent@442: if parent[num]["used"]: laurent@442: return True laurent@442: return self._CheckLocationConflicts(parent[num]["children"], location) laurent@442: elif len(parent[num]["children"]) > 0: laurent@442: return True laurent@442: return False laurent@442: laurent@442: def CheckLocationConflicts(self, location): laurent@442: if len(location) > 0: laurent@442: return self._CheckLocationConflicts(self.UsedLocations, list(location)) laurent@442: return False laurent@442: laurent@442: def PlugGenerate_C(self, buildpath, locations): laurent@442: """ laurent@442: Generate C code laurent@442: @param current_location: Tupple containing plugin IEC location : %I0.0.4.5 => (0,0,4,5) laurent@442: @param locations: List of complete variables locations \ laurent@442: [{"IEC_TYPE" : the IEC type (i.e. "INT", "STRING", ...) laurent@442: "NAME" : name of the variable (generally "__IW0_1_2" style) laurent@442: "DIR" : direction "Q","I" or "M" laurent@442: "SIZE" : size "X", "B", "W", "D", "L" laurent@442: "LOC" : tuple of interger for IEC location (0,1,2,...) laurent@442: }, ...] laurent@442: @return: [(C_file_name, CFLAGS),...] , LDFLAGS_TO_APPEND laurent@442: """ laurent@442: current_location = self.GetCurrentLocation() laurent@442: # define a unique name for the generated C file laurent@442: location_str = "_".join(map(str, current_location)) laurent@442: laurent@442: code_str = {"location_str": location_str, laurent@442: "var_decl": "", laurent@442: "declare_code": "", laurent@553: "init_code": "", laurent@442: "retrieve_code": "", laurent@442: "publish_code": "", laurent@442: } laurent@442: laurent@553: for module in _GetModuleChildren(self): laurent@553: if module["init"] != "": laurent@553: code_str["init_code"] += " %s\n" % module["init"] laurent@550: laurent@442: # Adding variables laurent@442: vars = [] laurent@442: self.ResetUsedLocations() laurent@442: for location in locations: laurent@442: loc = location["LOC"][len(current_location):] laurent@442: group = next = self laurent@442: i = 0 laurent@442: while next is not None and i < len(loc): laurent@442: next = self._GetChildBySomething("IEC_Channel", loc[:i + 1]) laurent@442: if next is not None: laurent@442: i += 1 laurent@442: group = next laurent@442: var_loc = loc[i:] laurent@530: for variable in _GetModuleChildren(group): laurent@566: if variable["location"] == var_loc and location["DIR"] == LOCATION_DIRS[variable["type"]]: Lolitech@543: # if location["DIR"] != LOCATION_DIRS[variable["type"]]: Lolitech@543: # raise Exception, "Direction conflict in variable definition" Lolitech@543: # if location["IEC_TYPE"] != variable["IEC_type"]: Lolitech@543: # raise Exception, "Type conflict in variable definition" laurent@442: if location["DIR"] == "Q": laurent@442: if self.CheckLocationConflicts(location["LOC"]): laurent@442: raise Exception, "BYTE and BIT from the same BYTE can't be used together" laurent@442: self.AddUsedLocation(location["LOC"]) laurent@442: vars.append({"location": location["NAME"], laurent@442: "Type": variable["IEC_type"], laurent@442: "Retrieve": variable["retrieve"], laurent@442: "Publish": variable["publish"], laurent@442: }) laurent@442: break laurent@442: base_types = self.GetPlugRoot().GetBaseTypes() laurent@442: for var in vars: laurent@442: prefix = "" laurent@442: if var["Type"] in base_types: laurent@442: prefix = "IEC_" laurent@442: code_str["var_decl"] += "%s%s beremiz%s;\n"%(prefix, var["Type"], var["location"]) laurent@442: code_str["var_decl"] += "%s%s *%s = &beremiz%s;\n"%(prefix, var["Type"], var["location"], var["location"]) laurent@442: if var["Retrieve"] != "": laurent@550: code_str["retrieve_code"] += " " + var["Retrieve"] % ("*" + var["location"]) + "\n" laurent@442: if var["Publish"] != "": laurent@550: code_str["publish_code"] += " " + var["Publish"] % ("*" + var["location"]) + "\n" laurent@442: laurent@553: Gen_Module_path = os.path.join(buildpath, "Bus_%s.c"%location_str) laurent@442: module = open(Gen_Module_path,'w') laurent@442: module.write(BUS_TEXT % code_str) laurent@442: module.close() laurent@442: laurent@442: matiec_flags = '"-I%s"'%os.path.abspath(self.GetPlugRoot().GetIECLibPath()) laurent@442: return [(Gen_Module_path, matiec_flags)],"",True laurent@442: laurent@442: #------------------------------------------------------------------------------- laurent@442: # LPCPluginsRoot Class laurent@442: #------------------------------------------------------------------------------- laurent@442: laurent@442: def mycopytree(src, dst): laurent@442: """ laurent@442: Copy content of a directory to an other, omit hidden files laurent@442: @param src: source directory laurent@442: @param dst: destination directory laurent@442: """ laurent@442: for i in os.listdir(src): laurent@442: if not i.startswith('.'): laurent@442: srcpath = os.path.join(src,i) laurent@442: dstpath = os.path.join(dst,i) laurent@442: if os.path.isdir(srcpath): edouard@503: if os.path.exists(dstpath): edouard@503: shutil.rmtree(dstpath) edouard@503: os.makedirs(dstpath) laurent@442: mycopytree(srcpath, dstpath) laurent@442: elif os.path.isfile(srcpath): laurent@442: shutil.copy2(srcpath, dstpath) laurent@442: edouard@572: [SIMULATION_MODE, TRANSFER_MODE] = range(2) laurent@539: laurent@442: class LPCPluginsRoot(PluginsRoot): laurent@442: laurent@442: PluginMethods = [ laurent@492: {"bitmap" : opjimg("Debug"), laurent@492: "name" : _("Simulate"), laurent@492: "tooltip" : _("Simulate PLC"), laurent@492: "method" : "_Simulate"}, laurent@487: {"bitmap" : opjimg("Run"), laurent@487: "name" : _("Run"), laurent@487: "shown" : False, laurent@487: "tooltip" : _("Start PLC"), laurent@487: "method" : "_Run"}, laurent@487: {"bitmap" : opjimg("Stop"), laurent@487: "name" : _("Stop"), laurent@487: "shown" : False, laurent@487: "tooltip" : _("Stop Running PLC"), laurent@487: "method" : "_Stop"}, laurent@541: {"bitmap" : opjimg("Build"), laurent@541: "name" : _("Build"), laurent@541: "tooltip" : _("Build project into build folder"), Edouard@625: "method" : "_Build"}, laurent@487: {"bitmap" : opjimg("Transfer"), laurent@487: "name" : _("Transfer"), laurent@487: "shown" : False, laurent@487: "tooltip" : _("Transfer PLC"), laurent@487: "method" : "_Transfer"}, laurent@442: ] laurent@442: laurent@478: def __init__(self, frame, logger): laurent@478: PluginsRoot.__init__(self, frame, logger) laurent@487: laurent@478: self.PlugChildsTypes += [("LPCBus", LPCBus, "LPC bus")] laurent@478: laurent@539: self.OnlineMode = "OFF" laurent@561: self.LPCConnector = None laurent@539: laurent@539: self.CurrentMode = None laurent@539: self.previous_mode = None laurent@539: laurent@492: self.SimulationBuildPath = None laurent@539: laurent@539: self.AbortTransferTimer = None laurent@539: laurent@442: def GetProjectName(self): laurent@442: return self.Project.getname() laurent@442: laurent@510: def GetDefaultTargetName(self): laurent@539: if self.CurrentMode == SIMULATION_MODE: laurent@510: return PluginsRoot.GetDefaultTargetName(self) laurent@492: else: laurent@510: return "LPC" laurent@510: laurent@510: def GetTarget(self): laurent@510: target = PluginsRoot.GetTarget(self) laurent@539: if self.CurrentMode != SIMULATION_MODE: laurent@510: target.getcontent()["value"].setBuildPath(self.BuildPath) laurent@442: return target laurent@492: laurent@492: def _getBuildPath(self): laurent@539: if self.CurrentMode == SIMULATION_MODE: laurent@492: if self.SimulationBuildPath is None: laurent@492: self.SimulationBuildPath = os.path.join(tempfile.mkdtemp(), os.path.basename(self.ProjectPath), "build") laurent@492: return self.SimulationBuildPath laurent@492: else: laurent@494: return PluginsRoot._getBuildPath(self) edouard@503: Edouard@625: def _Build(self): laurent@599: save = self.ProjectTestModified() laurent@599: if save: laurent@599: self.SaveProject() laurent@599: self.AppFrame._Refresh(TITLE, FILEMENU) edouard@503: if self.BuildPath is not None: edouard@503: mycopytree(self.OrigBuildPath, self.BuildPath) Edouard@625: PluginsRoot._Build(self) laurent@599: if save: laurent@599: wx.CallAfter(self.AppFrame.RefreshAll) laurent@492: laurent@442: def SetProjectName(self, name): laurent@442: return self.Project.setname(name) laurent@442: laurent@487: def SetOnlineMode(self, mode, path=None): laurent@539: if self.OnlineMode != mode.upper(): laurent@539: self.OnlineMode = mode.upper() laurent@539: laurent@539: if self.OnlineMode != "OFF": Lolitech@543: uri = "LPC://%s/%s" % (self.OnlineMode,path) laurent@539: try: laurent@539: self.LPCConnector = connectors.ConnectorFactory(uri, self) laurent@539: except Exception, msg: laurent@539: self.logger.write_error(_("Exception while connecting %s!\n")%uri) laurent@539: self.logger.write_error(traceback.format_exc()) laurent@539: laurent@539: # Did connection success ? laurent@539: if self.LPCConnector is None: laurent@539: # Oups. laurent@539: self.logger.write_error(_("Connection failed to %s!\n")%uri) laurent@492: laurent@492: else: laurent@539: self.LPCConnector = None laurent@539: laurent@539: self.ApplyOnlineMode() laurent@539: laurent@539: def ApplyOnlineMode(self): laurent@539: if self.CurrentMode != SIMULATION_MODE: laurent@539: self.KillDebugThread() laurent@539: laurent@539: self._connector = self.LPCConnector laurent@539: laurent@539: # Init with actual PLC status and print it laurent@539: self.UpdateMethodsFromPLCStatus() laurent@539: laurent@539: if self.LPCConnector is not None and self.OnlineMode == "APPLICATION": laurent@539: laurent@539: self.CompareLocalAndRemotePLC() laurent@539: laurent@539: if self.previous_plcstate is not None: laurent@539: status = _(self.previous_plcstate) laurent@539: else: laurent@539: status = "" laurent@539: self.logger.write(_("PLC is %s\n")%status) laurent@539: edouard@575: #if self.StatusTimer and not self.StatusTimer.IsRunning(): edouard@575: # # Start the status Timer edouard@575: # self.StatusTimer.Start(milliseconds=2000, oneShot=False) laurent@539: laurent@539: if self.previous_plcstate=="Started": laurent@539: if self.DebugAvailable() and self.GetIECProgramsAndVariables(): laurent@539: self.logger.write(_("Debug connect matching running PLC\n")) edouard@576: self._connect_debug() laurent@539: else: laurent@539: self.logger.write_warning(_("Debug do not match PLC - stop/transfert/start to re-enable\n")) laurent@539: Lolitech@543: elif self.StatusTimer and self.StatusTimer.IsRunning(): laurent@492: self.StatusTimer.Stop() laurent@539: edouard@572: if self.CurrentMode == TRANSFER_MODE: laurent@492: laurent@539: if self.OnlineMode == "BOOTLOADER": laurent@539: self.BeginTransfer() laurent@539: laurent@539: elif self.OnlineMode == "APPLICATION": laurent@539: self.CurrentMode = None laurent@539: self.AbortTransferTimer.Stop() laurent@539: self.AbortTransferTimer = None laurent@539: laurent@539: self.logger.write(_("PLC transferred successfully\n")) laurent@539: laurent@444: # Update a PLCOpenEditor Pou variable name laurent@444: def UpdateProjectVariableName(self, old_name, new_name): laurent@444: self.Project.updateElementName(old_name, new_name) laurent@444: self.BufferProject() laurent@444: laurent@444: def RemoveProjectVariableByAddress(self, address): laurent@444: self.Project.removeVariableByAddress(address) laurent@444: self.BufferProject() laurent@444: laurent@444: def RemoveProjectVariableByFilter(self, leading): laurent@444: self.Project.removeVariableByFilter(leading) laurent@444: self.BufferProject() laurent@444: laurent@442: def LoadProject(self, ProjectPath, BuildPath=None): laurent@442: """ laurent@478: Load a project contained in a folder laurent@478: @param ProjectPath: path of the project folder laurent@442: """ laurent@478: if os.path.basename(ProjectPath) == "": laurent@478: ProjectPath = os.path.dirname(ProjectPath) laurent@500: laurent@478: # Verify that project contains a PLCOpen program laurent@478: plc_file = os.path.join(ProjectPath, "plc.xml") laurent@500: if os.path.isfile(plc_file): laurent@500: # Load PLCOpen file laurent@500: result = self.OpenXMLFile(plc_file) laurent@500: if result: laurent@500: return result laurent@500: else: laurent@500: self.CreateNewProject({"companyName": "", laurent@500: "productName": "", laurent@500: "productVersion": "", laurent@500: "projectName": "", laurent@500: "pageSize": (0, 0), laurent@500: "scaling": {}}) laurent@500: laurent@442: # Change XSD into class members laurent@442: self._AddParamsMembers() laurent@442: self.PluggedChilds = {} laurent@500: laurent@442: # Keep track of the root plugin (i.e. project path) laurent@442: self.ProjectPath = ProjectPath laurent@500: laurent@478: self.BuildPath = self._getBuildPath() edouard@503: self.OrigBuildPath = BuildPath laurent@442: if BuildPath is not None: laurent@442: mycopytree(BuildPath, self.BuildPath) laurent@442: laurent@478: # If dir have already be made, and file exist laurent@478: if os.path.isdir(self.PlugPath()) and os.path.isfile(self.PluginXmlFilePath()): laurent@478: #Load the plugin.xml file into parameters members laurent@478: result = self.LoadXMLParams() laurent@478: if result: laurent@478: return result laurent@478: #Load and init all the childs laurent@478: self.LoadChilds() laurent@500: laurent@500: if self.PlugTestModified(): laurent@500: self.SaveProject() laurent@500: laurent@539: if wx.GetApp() is None: laurent@539: self.RefreshPluginsBlockLists() laurent@539: else: laurent@539: wx.CallAfter(self.RefreshPluginsBlockLists) laurent@478: laurent@478: return None laurent@442: laurent@487: ############# Real PLC object access ############# laurent@487: def UpdateMethodsFromPLCStatus(self): laurent@487: # Get PLC state : Running or Stopped laurent@487: # TODO : use explicit status instead of boolean laurent@539: if self.OnlineMode == "OFF": laurent@487: status = "Disconnected" laurent@539: elif self.OnlineMode == "BOOTLOADER": laurent@487: status = "Connected" laurent@487: else: laurent@492: if self._connector is not None: laurent@492: status = self._connector.GetPLCstatus() laurent@492: else: laurent@492: status = "Disconnected" laurent@539: if self.previous_plcstate != status or self.previous_mode != self.CurrentMode: laurent@539: simulating = self.CurrentMode == SIMULATION_MODE laurent@487: for args in { laurent@492: "Started" : [("_Simulate", False), laurent@487: ("_Run", False), laurent@487: ("_Stop", True), Edouard@625: ("_Build", True), laurent@559: ("_Transfer", True)], laurent@559: "Stopped" : [("_Simulate", False), laurent@487: ("_Run", True), laurent@487: ("_Stop", False), Edouard@625: ("_Build", True), laurent@559: ("_Transfer", True)], laurent@492: "Connected" : [("_Simulate", not simulating), edouard@571: ("_Run", True), laurent@492: ("_Stop", simulating), Edouard@625: ("_Build", True), laurent@487: ("_Transfer", True)], laurent@492: "Disconnected" :[("_Simulate", not simulating), laurent@487: ("_Run", False), laurent@492: ("_Stop", simulating), Edouard@625: ("_Build", True), laurent@487: ("_Transfer", False)], laurent@487: }.get(status,[]): laurent@487: self.ShowMethod(*args) laurent@487: self.previous_plcstate = status laurent@539: self.previous_mode = self.CurrentMode laurent@487: return True laurent@487: return False laurent@487: laurent@492: def Generate_plc_declare_locations(self): laurent@492: """ laurent@492: Declare used locations in order to simulatePLC in a black box laurent@492: """ laurent@492: return """#include "iec_types_all.h" laurent@492: laurent@492: #define __LOCATED_VAR(type, name, ...) \ laurent@492: type beremiz_##name;\ laurent@492: type *name = &beremiz_##name; laurent@492: laurent@492: #include "LOCATED_VARIABLES.h" laurent@492: laurent@492: #undef __LOCATED_VAR laurent@492: laurent@492: """ laurent@492: laurent@492: def _Simulate(self): laurent@492: """ laurent@492: Method called by user to Simulate PLC laurent@492: """ laurent@539: self.CurrentMode = SIMULATION_MODE laurent@539: laurent@492: uri = "LOCAL://" laurent@492: try: laurent@492: self._connector = connectors.ConnectorFactory(uri, self) laurent@492: except Exception, msg: laurent@492: self.logger.write_error(_("Exception while connecting %s!\n")%uri) laurent@492: self.logger.write_error(traceback.format_exc()) laurent@492: laurent@492: # Did connection success ? laurent@492: if self._connector is None: laurent@492: # Oups. laurent@492: self.logger.write_error(_("Connection failed to %s!\n")%uri) laurent@539: self.StopSimulation() laurent@492: return False laurent@492: laurent@492: buildpath = self._getBuildPath() laurent@492: laurent@492: # Eventually create build dir laurent@492: if not os.path.exists(buildpath): laurent@492: os.makedirs(buildpath) laurent@492: laurent@492: # Generate SoftPLC IEC code laurent@492: IECGenRes = self._Generate_SoftPLC() laurent@492: laurent@492: # If IEC code gen fail, bail out. laurent@492: if not IECGenRes: laurent@492: self.logger.write_error(_("IEC-61131-3 code generation failed !\n")) laurent@539: self.StopSimulation() laurent@492: return False laurent@492: laurent@492: # Reset variable and program list that are parsed from laurent@492: # CSV file generated by IEC2C compiler. laurent@492: self.ResetIECProgramsAndVariables() laurent@492: laurent@492: gen_result = self.PlugGenerate_C(buildpath, self.PLCGeneratedLocatedVars) laurent@492: PlugCFilesAndCFLAGS, PlugLDFLAGS, DoCalls = gen_result[:3] laurent@492: # if some files have been generated put them in the list with their location laurent@492: if PlugCFilesAndCFLAGS: laurent@492: self.LocationCFilesAndCFLAGS = [(self.GetCurrentLocation(), PlugCFilesAndCFLAGS, DoCalls)] laurent@492: else: laurent@492: self.LocationCFilesAndCFLAGS = [] laurent@492: laurent@492: # plugin asks for some LDFLAGS laurent@492: if PlugLDFLAGS: laurent@492: # LDFLAGS can be either string laurent@492: if type(PlugLDFLAGS)==type(str()): laurent@492: self.LDFLAGS=[PlugLDFLAGS] laurent@492: #or list of strings laurent@492: elif type(PlugLDFLAGS)==type(list()): laurent@492: self.LDFLAGS=PlugLDFLAGS[:] laurent@492: else: laurent@492: self.LDFLAGS=[] laurent@492: laurent@492: # Template based part of C code generation laurent@492: # files are stacked at the beginning, as files of plugin tree root laurent@492: for generator, filename, name in [ laurent@492: # debugger code laurent@492: (self.Generate_plc_debugger, "plc_debugger.c", "Debugger"), laurent@492: # init/cleanup/retrieve/publish, run and align code laurent@492: (self.Generate_plc_common_main,"plc_common_main.c","Common runtime"), laurent@492: # declare located variables for simulate in a black box laurent@492: (self.Generate_plc_declare_locations,"plc_declare_locations.c","Declare Locations")]: laurent@492: try: laurent@492: # Do generate laurent@492: code = generator() laurent@492: if code is None: laurent@492: raise laurent@492: code_path = os.path.join(buildpath,filename) laurent@492: open(code_path, "w").write(code) laurent@492: # Insert this file as first file to be compiled at root plugin laurent@492: self.LocationCFilesAndCFLAGS[0][1].insert(0,(code_path, self.plcCFLAGS)) laurent@492: except Exception, exc: laurent@492: self.logger.write_error(name+_(" generation failed !\n")) laurent@492: self.logger.write_error(traceback.format_exc()) laurent@539: self.StopSimulation() laurent@492: return False laurent@492: laurent@492: # Get simulation builder laurent@492: builder = self.GetBuilder() laurent@492: if builder is None: laurent@492: self.logger.write_error(_("Fatal : cannot get builder.\n")) laurent@539: self.StopSimulation() laurent@492: return False laurent@492: laurent@492: # Build laurent@492: try: laurent@492: if not builder.build() : laurent@492: self.logger.write_error(_("C Build failed.\n")) laurent@539: self.StopSimulation() laurent@492: return False laurent@492: except Exception, exc: laurent@492: self.logger.write_error(_("C Build crashed !\n")) laurent@492: self.logger.write_error(traceback.format_exc()) laurent@539: self.StopSimulation() laurent@492: return False laurent@492: laurent@492: data = builder.GetBinaryCode() laurent@492: if data is not None : laurent@492: if self._connector.NewPLC(builder.GetBinaryCodeMD5(), data, []): laurent@492: if self.AppFrame is not None: laurent@492: self.AppFrame.CloseDebugTabs() laurent@492: self.AppFrame.RefreshInstancesTree() laurent@492: self.UnsubscribeAllDebugIECVariable() laurent@492: self.ProgramTransferred() laurent@492: self.logger.write(_("Transfer completed successfully.\n")) laurent@492: else: laurent@492: self.logger.write_error(_("Transfer failed\n")) laurent@539: self.StopSimulation() laurent@492: return False laurent@492: laurent@492: self._Run() laurent@492: laurent@539: if not self.StatusTimer.IsRunning(): laurent@539: # Start the status Timer laurent@539: self.StatusTimer.Start(milliseconds=500, oneShot=False) laurent@539: laurent@539: def StopSimulation(self): laurent@539: self.CurrentMode = None laurent@539: self.ApplyOnlineMode() laurent@539: laurent@539: def _Stop(self): laurent@539: PluginsRoot._Stop(self) laurent@539: laurent@539: if self.CurrentMode == SIMULATION_MODE: laurent@539: self.StopSimulation() laurent@539: laurent@560: def CompareLocalAndRemotePLC(self): laurent@560: if self.LPCConnector is None: laurent@560: return laurent@560: # We are now connected. Update button status laurent@560: MD5 = self.GetLastBuildMD5() laurent@560: # Check remote target PLC correspondance to that md5 laurent@560: if MD5 is not None and self.LPCConnector.MatchMD5(MD5): laurent@560: # warns controller that program match laurent@560: self.ProgramTransferred() laurent@560: edouard@571: def GetLastBuildMD5(self): edouard@571: builder=self.GetBuilder() edouard@571: if builder is not None: edouard@571: return builder.GetBinaryCodeMD5(self.OnlineMode) edouard@571: else: edouard@571: return None edouard@571: laurent@539: def _Transfer(self): laurent@539: if self.CurrentMode is None and self.OnlineMode != "OFF": edouard@572: self.CurrentMode = TRANSFER_MODE laurent@539: Edouard@625: PluginsRoot._Build(self) laurent@539: laurent@539: ID_ABORTTRANSFERTIMER = wx.NewId() laurent@539: self.AbortTransferTimer = wx.Timer(self.AppFrame, ID_ABORTTRANSFERTIMER) laurent@539: self.AppFrame.Bind(wx.EVT_TIMER, self.AbortTransfer, self.AbortTransferTimer) laurent@539: laurent@539: if self.OnlineMode == "BOOTLOADER": laurent@539: self.BeginTransfer() laurent@539: laurent@539: else: laurent@539: self.logger.write(_("Resetting PLC\n")) edouard@575: #self.StatusTimer.Stop() laurent@539: self.LPCConnector.ResetPLC() laurent@539: self.AbortTransferTimer.Start(milliseconds=5000, oneShot=True) laurent@539: laurent@539: def BeginTransfer(self): laurent@539: self.logger.write(_("Start PLC transfer\n")) laurent@539: laurent@539: self.AbortTransferTimer.Stop() laurent@539: PluginsRoot._Transfer(self) laurent@539: self.AbortTransferTimer.Start(milliseconds=5000, oneShot=True) laurent@539: laurent@539: def AbortTransfer(self, event): Lolitech@543: self.logger.write_warning(_("Timeout waiting PLC to recover\n")) laurent@539: laurent@539: self.CurrentMode = None laurent@539: self.AbortTransferTimer.Stop() laurent@539: self.AbortTransferTimer = None laurent@539: event.Skip() laurent@539: edouard@571: def _Run(self): edouard@571: """ edouard@571: Start PLC edouard@571: """ edouard@571: if self.GetIECProgramsAndVariables(): edouard@571: self._connector.StartPLC() edouard@571: self.logger.write(_("Starting PLC\n")) edouard@576: self._connect_debug() edouard@571: else: edouard@571: self.logger.write_error(_("Couldn't start PLC !\n")) edouard@571: self.UpdateMethodsFromPLCStatus() edouard@571: laurent@442: #------------------------------------------------------------------------------- laurent@442: # LPCBeremiz Class laurent@442: #------------------------------------------------------------------------------- Lolitech@549: lpcberemiz_cmd=None laurent@442: laurent@442: class LPCBeremiz(Beremiz): laurent@442: laurent@442: def _init_coll_FileMenu_Items(self, parent): laurent@442: AppendMenu(parent, help='', id=wx.ID_SAVE, laurent@442: kind=wx.ITEM_NORMAL, text=_(u'Save\tCTRL+S')) laurent@442: AppendMenu(parent, help='', id=wx.ID_CLOSE, laurent@442: kind=wx.ITEM_NORMAL, text=_(u'Close Tab\tCTRL+W')) laurent@442: parent.AppendSeparator() laurent@442: AppendMenu(parent, help='', id=wx.ID_PAGE_SETUP, laurent@442: kind=wx.ITEM_NORMAL, text=_(u'Page Setup')) laurent@442: AppendMenu(parent, help='', id=wx.ID_PREVIEW, laurent@442: kind=wx.ITEM_NORMAL, text=_(u'Preview')) laurent@442: AppendMenu(parent, help='', id=wx.ID_PRINT, laurent@442: kind=wx.ITEM_NORMAL, text=_(u'Print')) laurent@442: parent.AppendSeparator() laurent@442: AppendMenu(parent, help='', id=wx.ID_PROPERTIES, laurent@442: kind=wx.ITEM_NORMAL, text=_(u'Properties')) laurent@442: parent.AppendSeparator() laurent@442: AppendMenu(parent, help='', id=wx.ID_EXIT, laurent@442: kind=wx.ITEM_NORMAL, text=_(u'Quit\tCTRL+Q')) laurent@442: laurent@442: self.Bind(wx.EVT_MENU, self.OnSaveProjectMenu, id=wx.ID_SAVE) laurent@442: self.Bind(wx.EVT_MENU, self.OnCloseTabMenu, id=wx.ID_CLOSE) laurent@442: self.Bind(wx.EVT_MENU, self.OnPageSetupMenu, id=wx.ID_PAGE_SETUP) laurent@442: self.Bind(wx.EVT_MENU, self.OnPreviewMenu, id=wx.ID_PREVIEW) laurent@442: self.Bind(wx.EVT_MENU, self.OnPrintMenu, id=wx.ID_PRINT) laurent@442: self.Bind(wx.EVT_MENU, self.OnPropertiesMenu, id=wx.ID_PROPERTIES) laurent@442: self.Bind(wx.EVT_MENU, self.OnQuitMenu, id=wx.ID_EXIT) laurent@442: laurent@442: def _init_ctrls(self, prnt): laurent@442: IDEFrame._init_ctrls(self, prnt) laurent@442: laurent@442: self.Bind(wx.EVT_MENU, self.OnOpenWidgetInspector, id=ID_BEREMIZINSPECTOR) laurent@442: accel = wx.AcceleratorTable([wx.AcceleratorEntry(wx.ACCEL_CTRL|wx.ACCEL_ALT, ord('I'), ID_BEREMIZINSPECTOR)]) laurent@442: self.SetAcceleratorTable(accel) laurent@442: laurent@442: self.PLCConfig = wx.ScrolledWindow(id=ID_BEREMIZPLCCONFIG, laurent@442: name='PLCConfig', parent=self.LeftNoteBook, pos=wx.Point(0, 0), laurent@442: size=wx.Size(-1, -1), style=wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER|wx.HSCROLL|wx.VSCROLL) laurent@442: self.PLCConfig.SetBackgroundColour(wx.WHITE) laurent@442: self.PLCConfig.Bind(wx.EVT_LEFT_DOWN, self.OnPanelLeftDown) laurent@442: self.PLCConfig.Bind(wx.EVT_SIZE, self.OnMoveWindow) laurent@442: self.LeftNoteBook.InsertPage(0, self.PLCConfig, _("Topology"), True) laurent@442: laurent@442: self.LogConsole = wx.TextCtrl(id=ID_BEREMIZLOGCONSOLE, value='', laurent@442: name='LogConsole', parent=self.BottomNoteBook, pos=wx.Point(0, 0), laurent@442: size=wx.Size(0, 0), style=wx.TE_MULTILINE|wx.TE_RICH2) laurent@442: self.LogConsole.Bind(wx.EVT_LEFT_DCLICK, self.OnLogConsoleDClick) laurent@442: self.BottomNoteBook.AddPage(self.LogConsole, _("Log Console")) laurent@442: laurent@442: self._init_beremiz_sizers() laurent@442: laurent@442: def OnCloseFrame(self, event): laurent@519: global frame laurent@539: laurent@596: if self.CheckSaveBeforeClosing(_("Close Application")): laurent@596: laurent@596: frame.Hide() laurent@596: laurent@596: self.PluginRoot.ResetAppFrame(lpcberemiz_cmd.Log) laurent@596: if self.PluginRoot.OnlineMode == 0: laurent@596: self.PluginRoot._connector = None laurent@596: laurent@596: self.PluginRoot.KillDebugThread() laurent@596: self.KillLocalRuntime() laurent@596: laurent@598: self.SaveFrameSize() laurent@598: laurent@596: lpcberemiz_cmd.Log.write("Closed\n") laurent@596: laurent@539: event.Veto() laurent@442: laurent@500: def ShowProperties(self): laurent@500: old_values = self.Controler.GetProjectProperties() laurent@500: dialog = ProjectDialog(self ,False) laurent@500: dialog.SetValues(old_values) laurent@500: if dialog.ShowModal() == wx.ID_OK: laurent@500: new_values = dialog.GetValues() laurent@500: new_values["creationDateTime"] = old_values["creationDateTime"] laurent@500: if new_values != old_values: laurent@500: self.Controler.SetProjectProperties(None, new_values) laurent@500: self._Refresh(TITLE, TOOLBAR, FILEMENU, EDITMENU, DISPLAYMENU, laurent@500: TYPESTREE, INSTANCESTREE, SCALING) laurent@500: dialog.Destroy() laurent@500: laurent@442: def RefreshFileMenu(self): laurent@442: if self.PluginRoot is not None: laurent@442: selected = self.TabsOpened.GetSelection() laurent@442: if selected >= 0: laurent@442: graphic_viewer = isinstance(self.TabsOpened.GetPage(selected), Viewer) laurent@442: else: laurent@442: graphic_viewer = False laurent@442: if self.TabsOpened.GetPageCount() > 0: laurent@442: self.FileMenu.Enable(wx.ID_CLOSE, True) laurent@442: if graphic_viewer: laurent@442: self.FileMenu.Enable(wx.ID_PREVIEW, True) laurent@442: self.FileMenu.Enable(wx.ID_PRINT, True) laurent@442: else: laurent@442: self.FileMenu.Enable(wx.ID_PREVIEW, False) laurent@442: self.FileMenu.Enable(wx.ID_PRINT, False) laurent@442: else: laurent@442: self.FileMenu.Enable(wx.ID_CLOSE, False) laurent@442: self.FileMenu.Enable(wx.ID_PREVIEW, False) laurent@442: self.FileMenu.Enable(wx.ID_PRINT, False) laurent@442: self.FileMenu.Enable(wx.ID_PAGE_SETUP, True) laurent@500: self.FileMenu.Enable(wx.ID_SAVE, self.PluginRoot.PlugTestModified()) laurent@442: self.FileMenu.Enable(wx.ID_PROPERTIES, True) laurent@442: else: laurent@442: self.FileMenu.Enable(wx.ID_CLOSE, False) laurent@442: self.FileMenu.Enable(wx.ID_PAGE_SETUP, False) laurent@442: self.FileMenu.Enable(wx.ID_PREVIEW, False) laurent@442: self.FileMenu.Enable(wx.ID_PRINT, False) laurent@442: self.FileMenu.Enable(wx.ID_SAVE, False) laurent@442: self.FileMenu.Enable(wx.ID_PROPERTIES, False) laurent@442: laurent@442: def RefreshPLCParams(self): laurent@442: self.Freeze() laurent@442: self.ClearSizer(self.PLCParamsSizer) laurent@442: laurent@442: if self.PluginRoot is not None: laurent@442: plcwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) laurent@442: if self.PluginRoot.PlugTestModified(): laurent@442: bkgdclr = CHANGED_TITLE_COLOUR laurent@442: else: laurent@442: bkgdclr = TITLE_COLOUR laurent@442: laurent@442: if self.PluginRoot not in self.PluginInfos: laurent@442: self.PluginInfos[self.PluginRoot] = {"right_visible" : False} laurent@442: laurent@442: plcwindow.SetBackgroundColour(TITLE_COLOUR) laurent@442: plcwindow.Bind(wx.EVT_LEFT_DOWN, self.OnPanelLeftDown) laurent@442: self.PLCParamsSizer.AddWindow(plcwindow, 0, border=0, flag=wx.GROW) laurent@442: laurent@442: plcwindowsizer = wx.BoxSizer(wx.HORIZONTAL) laurent@442: plcwindow.SetSizer(plcwindowsizer) laurent@442: laurent@442: st = wx.StaticText(plcwindow, -1) laurent@442: st.SetFont(wx.Font(faces["size"], wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"])) laurent@442: st.SetLabel(self.PluginRoot.GetProjectName()) laurent@442: plcwindowsizer.AddWindow(st, 0, border=5, flag=wx.ALL|wx.ALIGN_CENTER) laurent@442: laurent@442: plcwindowmainsizer = wx.BoxSizer(wx.VERTICAL) laurent@442: plcwindowsizer.AddSizer(plcwindowmainsizer, 0, border=5, flag=wx.ALL) laurent@442: laurent@442: plcwindowbuttonsizer = wx.BoxSizer(wx.HORIZONTAL) laurent@442: plcwindowmainsizer.AddSizer(plcwindowbuttonsizer, 0, border=0, flag=wx.ALIGN_CENTER) laurent@442: laurent@442: msizer = self.GenerateMethodButtonSizer(self.PluginRoot, plcwindow, not self.PluginInfos[self.PluginRoot]["right_visible"]) laurent@442: plcwindowbuttonsizer.AddSizer(msizer, 0, border=0, flag=wx.GROW) laurent@442: laurent@442: self.PLCConfigMainSizer.Layout() laurent@442: self.RefreshScrollBars() laurent@442: self.Thaw() laurent@442: laurent@442: def GenerateTreeBranch(self, plugin): laurent@442: leftwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) laurent@442: if plugin.PlugTestModified(): laurent@442: bkgdclr=CHANGED_WINDOW_COLOUR laurent@442: else: laurent@442: bkgdclr=WINDOW_COLOUR laurent@442: laurent@442: leftwindow.SetBackgroundColour(bkgdclr) laurent@442: laurent@442: if plugin not in self.PluginInfos: laurent@442: self.PluginInfos[plugin] = {"expanded" : False, "left_visible" : False, "right_visible" : False} laurent@442: laurent@442: self.PluginInfos[plugin]["children"] = plugin.IECSortedChilds() laurent@442: plugin_infos = plugin.GetVariableLocationTree() laurent@442: plugin_locations = [] laurent@442: if len(self.PluginInfos[plugin]["children"]) == 0: laurent@442: plugin_locations = plugin_infos["children"] laurent@442: if not self.PluginInfos[plugin].has_key("locations_infos"): laurent@442: self.PluginInfos[plugin]["locations_infos"] = {"root": {"expanded" : False}} laurent@442: laurent@442: self.PluginInfos[plugin]["locations_infos"]["root"]["children"] = [] laurent@442: laurent@442: self.PluginTreeSizer.AddWindow(leftwindow, 0, border=0, flag=wx.GROW) laurent@442: laurent@442: leftwindowsizer = wx.BoxSizer(wx.HORIZONTAL) laurent@442: leftwindow.SetSizer(leftwindowsizer) laurent@442: laurent@442: st = wx.StaticText(leftwindow, -1) laurent@442: st.SetFont(wx.Font(faces["size"], wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"])) laurent@442: st.SetLabel(plugin.GetFullIEC_Channel()) laurent@442: leftwindowsizer.AddWindow(st, 0, border=5, flag=wx.RIGHT) laurent@442: laurent@442: expandbutton_id = wx.NewId() laurent@442: expandbutton = wx.lib.buttons.GenBitmapToggleButton(id=expandbutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'plus.png')), laurent@442: name='ExpandButton', parent=leftwindow, pos=wx.Point(0, 0), laurent@442: size=wx.Size(13, 13), style=wx.NO_BORDER) laurent@442: expandbutton.labelDelta = 0 laurent@442: expandbutton.SetBezelWidth(0) laurent@442: expandbutton.SetUseFocusIndicator(False) laurent@442: expandbutton.SetBitmapSelected(wx.Bitmap(Bpath( 'images', 'minus.png'))) laurent@442: laurent@442: if len(self.PluginInfos[plugin]["children"]) > 0: laurent@442: expandbutton.SetToggle(self.PluginInfos[plugin]["expanded"]) laurent@442: def togglebutton(event): laurent@442: if expandbutton.GetToggle(): laurent@442: self.ExpandPlugin(plugin) laurent@442: else: laurent@442: self.CollapsePlugin(plugin) laurent@442: self.PluginInfos[plugin]["expanded"] = expandbutton.GetToggle() laurent@442: self.PLCConfigMainSizer.Layout() laurent@442: self.RefreshScrollBars() laurent@442: event.Skip() laurent@442: expandbutton.Bind(wx.EVT_BUTTON, togglebutton, id=expandbutton_id) laurent@442: elif len(plugin_locations) > 0: laurent@442: locations_infos = self.PluginInfos[plugin]["locations_infos"] laurent@442: expandbutton.SetToggle(locations_infos["root"]["expanded"]) laurent@442: def togglebutton(event): laurent@442: if expandbutton.GetToggle(): laurent@442: self.ExpandLocation(locations_infos, "root") laurent@442: else: laurent@442: self.CollapseLocation(locations_infos, "root") laurent@442: self.PluginInfos[plugin]["expanded"] = expandbutton.GetToggle() laurent@442: locations_infos["root"]["expanded"] = expandbutton.GetToggle() laurent@442: self.PLCConfigMainSizer.Layout() laurent@442: self.RefreshScrollBars() laurent@442: event.Skip() laurent@442: expandbutton.Bind(wx.EVT_BUTTON, togglebutton, id=expandbutton_id) laurent@442: else: laurent@442: expandbutton.Enable(False) laurent@442: leftwindowsizer.AddWindow(expandbutton, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) laurent@442: laurent@442: sb = wx.StaticBitmap(leftwindow, -1) laurent@442: icon = plugin_infos.get("icon", None) laurent@442: if icon is None: laurent@442: icon = os.path.join(base_folder, "plcopeneditor", 'Images', '%s.png' % self.LOCATION_BITMAP[plugin_infos["type"]]) laurent@442: sb.SetBitmap(wx.Bitmap(icon)) laurent@442: leftwindowsizer.AddWindow(sb, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) laurent@442: laurent@442: st_id = wx.NewId() laurent@442: st = wx.StaticText(leftwindow, st_id, size=wx.DefaultSize, style=wx.NO_BORDER) laurent@442: st.SetFont(wx.Font(faces["size"] * 0.75, wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"])) laurent@442: st.SetLabel(plugin.MandatoryParams[1].getName()) laurent@442: leftwindowsizer.AddWindow(st, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) laurent@442: laurent@442: rightwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) laurent@442: rightwindow.SetBackgroundColour(bkgdclr) laurent@442: laurent@442: self.PluginTreeSizer.AddWindow(rightwindow, 0, border=0, flag=wx.GROW) laurent@442: laurent@442: self.PluginInfos[plugin]["left"] = leftwindow laurent@442: self.PluginInfos[plugin]["right"] = rightwindow laurent@442: for child in self.PluginInfos[plugin]["children"]: laurent@442: self.GenerateTreeBranch(child) laurent@442: if not self.PluginInfos[child]["expanded"]: laurent@442: self.CollapsePlugin(child) laurent@442: if len(plugin_locations) > 0: laurent@442: locations_infos = self.PluginInfos[plugin]["locations_infos"] laurent@442: for location in plugin_locations: laurent@442: locations_infos["root"]["children"].append("root.%s" % location["name"]) laurent@442: self.GenerateLocationTreeBranch(locations_infos, "root", location) laurent@442: if not locations_infos["root"]["expanded"]: laurent@442: self.CollapseLocation(locations_infos, "root") laurent@442: laurent@442: class StdoutPseudoFile: laurent@551: laurent@551: def __init__(self, port): laurent@551: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) laurent@551: self.socket.connect(('localhost', port)) laurent@552: self.Buffer = "" laurent@551: laurent@551: def __del__(self): laurent@551: self.socket.close() laurent@551: laurent@551: def readline(self): laurent@552: idx = self.Buffer.find("\n") laurent@552: if idx == -1: laurent@552: self.Buffer += self.socket.recv(2048) laurent@552: idx = self.Buffer.find("\n") laurent@552: if idx != -1: laurent@552: line = self.Buffer[:idx+1] laurent@552: self.Buffer = self.Buffer[idx+1:] edouard@571: if BMZ_DBG: edouard@571: print "command >"+line laurent@552: return line laurent@552: return "" laurent@551: laurent@442: """ Base class for file like objects to facilitate StdOut for the Shell.""" laurent@442: def write(self, s, style = None): laurent@442: if s != '': edouard@578: self.socket.send(s.encode('utf8')) edouard@578: edouard@578: def writeyield(self, s): edouard@578: self.write(s) edouard@578: laurent@442: def write_warning(self, s): laurent@442: self.write(s) laurent@442: laurent@442: def write_error(self, s): laurent@442: self.write(s) laurent@442: laurent@442: def flush(self): laurent@442: pass laurent@442: laurent@442: def isatty(self): laurent@551: return False laurent@442: laurent@442: if __name__ == '__main__': laurent@442: Lolitech@547: from threading import Thread, Timer, Semaphore laurent@442: import cmd laurent@442: Lolitech@547: wx_eval_lock = Semaphore(0) Lolitech@547: eval_res = None Lolitech@547: def wx_evaluator(callable, *args, **kwargs): Lolitech@547: global eval_res Lolitech@547: eval_res = None Lolitech@547: try: Lolitech@547: eval_res=callable(*args,**kwargs) Lolitech@547: finally: Lolitech@547: wx_eval_lock.release() Lolitech@547: Lolitech@547: def evaluator(callable, *args, **kwargs): Lolitech@547: global eval_res Lolitech@547: wx.CallAfter(wx_evaluator,callable,*args,**kwargs) Lolitech@547: wx_eval_lock.acquire() Lolitech@547: return eval_res Lolitech@547: Lolitech@547: # Command log for debug, for viewing from wxInspector edouard@571: if BMZ_DBG: edouard@571: __builtins__.cmdlog = [] Lolitech@547: laurent@442: class LPCBeremiz_Cmd(cmd.Cmd): laurent@442: laurent@442: prompt = "" laurent@442: RefreshTimer = None laurent@442: Lolitech@547: def __init__(self, PluginRoot, Log): laurent@551: cmd.Cmd.__init__(self, stdin=Log, stdout=Log) laurent@551: self.use_rawinput = False Lolitech@547: self.Log = Log Lolitech@547: self.PluginRoot = PluginRoot laurent@442: laurent@442: def RestartTimer(self): laurent@442: if self.RefreshTimer is not None: laurent@442: self.RefreshTimer.cancel() Lolitech@547: self.RefreshTimer = Timer(0.1, wx.CallAfter, args = [self.Refresh]) laurent@442: self.RefreshTimer.start() laurent@442: laurent@442: def Exit(self): laurent@539: global frame, app laurent@442: self.Close() laurent@539: app.ExitMainLoop() laurent@442: return True laurent@442: laurent@442: def do_EOF(self, line): laurent@442: return self.Exit() laurent@442: laurent@442: def Show(self): berem@445: global frame laurent@539: if frame is not None: laurent@539: self.PluginRoot.SetAppFrame(frame, frame.Log) Lolitech@547: frame.Show() Lolitech@547: frame.Raise() laurent@442: laurent@442: def Refresh(self): laurent@442: global frame laurent@442: if frame is not None: Lolitech@547: frame._Refresh(TITLE, INSTANCESTREE, FILEMENU, EDITMENU) Lolitech@547: frame.RefreshEditor() Lolitech@547: frame.RefreshAll() laurent@442: laurent@442: def Close(self): laurent@442: global frame laurent@442: laurent@442: self.PluginRoot.ResetAppFrame(self.Log) laurent@442: if frame is not None: Lolitech@547: frame.Hide() laurent@442: laurent@442: def Compile(self): Edouard@625: self.PluginRoot._Build() laurent@442: laurent@500: def SetProjectProperties(self, projectname, productname, productversion, companyname): laurent@500: properties = self.PluginRoot.GetProjectProperties() laurent@597: new_properties = properties.copy() laurent@597: new_properties["projectName"] = projectname laurent@597: new_properties["productName"] = productname laurent@597: new_properties["productVersion"] = productversion laurent@597: new_properties["companyName"] = companyname laurent@597: if new_properties != properties: laurent@597: self.PluginRoot.SetProjectProperties(properties=new_properties) laurent@597: self.RestartTimer() laurent@442: laurent@487: def SetOnlineMode(self, mode, path=None): Lolitech@547: self.PluginRoot.SetOnlineMode(mode, path) laurent@487: self.RestartTimer() laurent@487: laurent@442: def AddBus(self, iec_channel, name, icon=None): laurent@442: for child in self.PluginRoot.IterChilds(): laurent@442: if child.BaseParams.getName() == name: laurent@551: return "Error: A bus named %s already exists\n" % name laurent@442: elif child.BaseParams.getIEC_Channel() == iec_channel: laurent@551: return "Error: A bus with IEC_channel %d already exists\n" % iec_channel laurent@442: bus = self.PluginRoot.PlugAddChild(name, "LPCBus", iec_channel) laurent@442: if bus is None: laurent@551: return "Error: Unable to create bus\n" laurent@442: bus.SetIcon(icon) laurent@442: self.RestartTimer() laurent@442: laurent@442: def RenameBus(self, iec_channel, name): laurent@442: bus = self.PluginRoot.GetChildByIECLocation((iec_channel,)) laurent@442: if bus is None: laurent@551: return "Error: No bus found\n" laurent@442: for child in self.PluginRoot.IterChilds(): laurent@442: if child != bus and child.BaseParams.getName() == name: laurent@551: return "Error: A bus named %s already exists\n" % name laurent@442: bus.BaseParams.setName(name) laurent@442: self.RestartTimer() laurent@442: laurent@442: def ChangeBusIECChannel(self, old_iec_channel, new_iec_channel): laurent@442: bus = self.PluginRoot.GetChildByIECLocation((old_iec_channel,)) laurent@442: if bus is None: laurent@551: return "Error: No bus found\n" laurent@442: for child in self.PluginRoot.IterChilds(): laurent@442: if child != bus and child.BaseParams.getIEC_Channel() == new_iec_channel: laurent@551: return "Error: A bus with IEC_channel %d already exists\n" % new_iec_channel laurent@539: if wx.GetApp() is None: laurent@539: self.PluginRoot.UpdateProjectVariableLocation(str(old_iec_channel), laurent@539: str(new_iec_channel)) laurent@539: else: Lolitech@547: self.PluginRoot.UpdateProjectVariableLocation( laurent@539: str(old_iec_channel), laurent@539: str(new_iec_channel)) laurent@442: bus.BaseParams.setIEC_Channel(new_iec_channel) laurent@442: self.RestartTimer() laurent@442: laurent@442: def RemoveBus(self, iec_channel): laurent@442: bus = self.PluginRoot.GetChildByIECLocation((iec_channel,)) laurent@442: if bus is None: laurent@551: return "Error: No bus found\n" laurent@444: self.PluginRoot.RemoveProjectVariableByFilter(str(iec_channel)) laurent@442: self.PluginRoot.PluggedChilds["LPCBus"].remove(bus) laurent@442: self.RestartTimer() laurent@442: laurent@553: def AddModule(self, parent, iec_channel, name, icode, icon=None): laurent@442: module = self.PluginRoot.GetChildByIECLocation(parent) laurent@442: if module is None: laurent@551: return "Error: No parent found\n" laurent@442: for child in _GetModuleChildren(module): laurent@442: if child["name"] == name: laurent@551: return "Error: A module named %s already exists\n" % name laurent@442: elif child["IEC_Channel"] == iec_channel: laurent@551: return "Error: A module with IEC_channel %d already exists\n" % iec_channel laurent@442: _GetLastModuleGroup(module).append({"name": name, laurent@442: "type": LOCATION_MODULE, laurent@442: "IEC_Channel": iec_channel, laurent@442: "icon": icon, laurent@553: "init": icode, laurent@442: "children": []}) laurent@442: self.RestartTimer() laurent@442: laurent@442: def RenameModule(self, iec_location, name): laurent@442: module = self.PluginRoot.GetChildByIECLocation(iec_location) laurent@442: if module is None: laurent@551: return "Error: No module found\n" laurent@442: parent = self.PluginRoot.GetChildByIECLocation(iec_location[:-1]) laurent@442: if parent is self.PluginRoot: laurent@551: return "Error: No module found\n" laurent@442: if module["name"] != name: laurent@442: for child in _GetModuleChildren(parent): laurent@442: if child["name"] == name: laurent@551: return "Error: A module named %s already exists\n" % name laurent@442: module["name"] = name laurent@442: self.RestartTimer() laurent@442: laurent@442: def ChangeModuleIECChannel(self, old_iec_location, new_iec_channel): laurent@442: module = self.PluginRoot.GetChildByIECLocation(old_iec_location) laurent@442: if module is None: laurent@551: return "Error: No module found\n" laurent@442: parent = self.PluginRoot.GetChildByIECLocation(old_iec_location[:-1]) laurent@442: if parent is self.PluginRoot: laurent@551: return "Error: No module found\n" laurent@442: if module["IEC_Channel"] != new_iec_channel: laurent@442: for child in _GetModuleChildren(parent): laurent@442: if child["IEC_Channel"] == new_iec_channel: laurent@551: return "Error: A module with IEC_channel %d already exists\n" % new_iec_channel laurent@444: self.PluginRoot.UpdateProjectVariableLocation(".".join(map(str, old_iec_location)), ".".join(map(str, old_iec_location[:1] + (new_iec_channel,)))) laurent@442: module["IEC_Channel"] = new_iec_channel laurent@442: self.RestartTimer() laurent@553: laurent@553: def ChangeModuleInitCode(self, iec_location, icode): laurent@553: module = self.PluginRoot.GetChildByIECLocation(iec_location) laurent@553: if module is None: laurent@553: return "Error: No module found\n" laurent@553: module["init"] = icode laurent@553: laurent@442: def RemoveModule(self, parent, iec_channel): laurent@442: module = self.PluginRoot.GetChildByIECLocation(parent) laurent@442: if module is None: laurent@551: return "Error: No parent found\n" laurent@442: child = _GetModuleBySomething(module, "IEC_Channel", (iec_channel,)) laurent@442: if child is None: laurent@551: return "Error: No module found\n" laurent@444: self.PluginRoot.RemoveProjectVariableByFilter(".".join(map(str, parent + (iec_channel,)))) laurent@442: _RemoveModuleChild(module, child) laurent@442: self.RestartTimer() laurent@442: laurent@442: def StartGroup(self, parent, name, icon=None): laurent@442: module = self.PluginRoot.GetChildByIECLocation(parent) laurent@442: if module is None: laurent@551: return "Error: No parent found\n" laurent@442: for child in module["children"]: laurent@442: if child["type"] == LOCATION_GROUP and child["name"] == name: laurent@551: return "Error: A group named %s already exists\n" % name laurent@442: module["children"].append({"name": name, laurent@442: "type": LOCATION_GROUP, laurent@442: "icon": icon, laurent@442: "children": []}) laurent@442: self.RestartTimer() laurent@442: laurent@553: def AddVariable(self, parent, location, name, direction, type, rcode, pcode, description=""): laurent@442: module = self.PluginRoot.GetChildByIECLocation(parent) laurent@442: if module is None: laurent@551: return "Error: No parent found\n" laurent@442: for child in _GetModuleChildren(module): laurent@442: if child["name"] == name: laurent@551: return "Error: A variable named %s already exists\n" % name laurent@472: if child["location"] == location and child["type"] == LOCATION_TYPES[direction]: laurent@551: return "Error: A variable with location %s already exists\n" % ".".join(map(str, location)) laurent@442: _GetLastModuleGroup(module).append({"name": name, laurent@442: "location": location, laurent@442: "type": LOCATION_TYPES[direction], laurent@442: "IEC_type": type, laurent@442: "description": description, laurent@442: "retrieve": rcode, laurent@442: "publish": pcode}) laurent@442: self.RestartTimer() laurent@442: laurent@553: def ChangeVariableParams(self, parent, location, new_name, new_direction, new_type, new_rcode, new_pcode, new_description=None): laurent@442: module = self.PluginRoot.GetChildByIECLocation(parent) laurent@442: if module is None: laurent@551: return "Error: No parent found\n" laurent@442: variable = None laurent@442: for child in _GetModuleChildren(module): laurent@472: if child["location"] == location and child["type"] == LOCATION_TYPES[new_direction]: laurent@442: variable = child laurent@442: elif child["name"] == new_name: laurent@551: return "Error: A variable named %s already exists\n" % new_name laurent@442: if variable is None: laurent@551: return "Error: No variable found\n" laurent@444: if variable["name"] != new_name: laurent@444: self.PluginRoot.UpdateProjectVariableName(variable["name"], new_name) laurent@444: variable["name"] = new_name laurent@442: variable["type"] = LOCATION_TYPES[new_direction] laurent@442: variable["IEC_type"] = new_type laurent@442: variable["retrieve"] = new_rcode laurent@442: variable["publish"] = new_pcode laurent@442: if new_description is not None: laurent@442: variable["description"] = new_description laurent@442: self.RestartTimer() laurent@442: laurent@472: def RemoveVariable(self, parent, location, direction): laurent@442: module = self.PluginRoot.GetChildByIECLocation(parent) laurent@442: if module is None: laurent@551: return "Error: No parent found\n" laurent@472: child = _GetModuleVariable(module, location, direction) laurent@442: if child is None: laurent@551: return "Error: No variable found\n" laurent@444: size = LOCATION_SIZES[self.PluginRoot.GetBaseType(child["IEC_type"])] laurent@444: address = "%" + LOCATION_DIRS[child["type"]] + size + ".".join(map(str, parent + location)) laurent@444: self.PluginRoot.RemoveProjectVariableByAddress(address) laurent@442: _RemoveModuleChild(module, child) laurent@442: self.RestartTimer() laurent@442: laurent@442: def location(loc): laurent@442: return tuple(map(int, loc.split("."))) laurent@442: laurent@442: def GetCmdFunction(function, arg_types, opt=0): laurent@442: arg_number = len(arg_types) laurent@442: def CmdFunction(self, line): laurent@442: args_toks = line.split('"') laurent@442: if len(args_toks) % 2 == 0: laurent@551: self.Log.write("Error: Invalid command\n") tkragelj@526: sys.stdout.flush() laurent@442: return laurent@442: args = [] laurent@442: for num, arg in enumerate(args_toks): laurent@442: if num % 2 == 0: laurent@442: stripped = arg.strip() laurent@442: if stripped: laurent@442: args.extend(stripped.split(" ")) laurent@442: else: laurent@442: args.append(arg) laurent@442: number = None laurent@442: extra = "" laurent@442: if opt == 0 and len(args) != arg_number: laurent@442: number = arg_number laurent@442: elif len(args) > arg_number: laurent@442: number = arg_number laurent@442: extra = " at most" laurent@442: elif len(args) < arg_number - opt: laurent@442: number = arg_number - opt laurent@442: extra = " at least" laurent@442: if number is not None: laurent@442: if number == 0: laurent@551: self.Log.write("Error: No argument%s expected\n" % extra) laurent@442: elif number == 1: laurent@551: self.Log.write("Error: 1 argument%s expected\n" % extra) laurent@442: else: laurent@551: self.Log.write("Error: %d arguments%s expected\n" % (number, extra)) tkragelj@526: sys.stdout.flush() laurent@442: return laurent@442: for num, arg in enumerate(args): laurent@442: try: laurent@442: args[num] = arg_types[num](arg) laurent@442: except: laurent@551: self.Log.write("Error: Invalid value for argument %d\n" % (num + 1)) tkragelj@526: sys.stdout.flush() laurent@442: return Lolitech@547: Lolitech@547: func = getattr(self, function) Lolitech@547: res = evaluator(func,*args) Lolitech@547: edouard@571: if BMZ_DBG: edouard@571: cmdlog.append((function,line,res)) edouard@571: if len(cmdlog) > 100: #prevent debug log to grow too much edouard@571: cmdlog.pop(0) Lolitech@547: laurent@442: if isinstance(res, (StringType, UnicodeType)): laurent@551: self.Log.write(res) laurent@442: return False laurent@442: else: laurent@442: return res laurent@442: return CmdFunction Lolitech@547: Lolitech@547: def CmdThreadProc(PluginRoot, Log): Lolitech@549: global lpcberemiz_cmd Lolitech@547: for function, (arg_types, opt) in {"Exit": ([], 0), Lolitech@547: "Show": ([], 0), Lolitech@547: "Refresh": ([], 0), Lolitech@547: "Close": ([], 0), Lolitech@547: "Compile": ([], 0), Lolitech@547: "SetProjectProperties": ([str, str, str, str], 0), Lolitech@547: "SetOnlineMode": ([str, str], 1), Lolitech@547: "AddBus": ([int, str, str], 1), Lolitech@547: "RenameBus": ([int, str], 0), Lolitech@547: "ChangeBusIECChannel": ([int, int], 0), Lolitech@547: "RemoveBus": ([int], 0), laurent@553: "AddModule": ([location, int, str, str, str], 1), Lolitech@547: "RenameModule": ([location, str], 0), Lolitech@547: "ChangeModuleIECChannel": ([location, int], 0), laurent@553: "ChangeModuleInitCode": ([location, str], 0), Lolitech@547: "RemoveModule": ([location, int], 0), Lolitech@547: "StartGroup": ([location, str, str], 1), laurent@553: "AddVariable": ([location, location, str, str, str, str, str, str], 1), laurent@553: "ChangeVariableParams": ([location, location, str, str, str, str, str, str], 1), Lolitech@547: "RemoveVariable": ([location, location], 0)}.iteritems(): Lolitech@547: Lolitech@547: setattr(LPCBeremiz_Cmd, "do_%s" % function, GetCmdFunction(function, arg_types, opt)) Lolitech@547: lpcberemiz_cmd = LPCBeremiz_Cmd(PluginRoot, Log) Lolitech@547: lpcberemiz_cmd.cmdloop() Lolitech@547: laurent@551: Log = StdoutPseudoFile(port) Lolitech@547: Lolitech@547: PluginRoot = LPCPluginsRoot(None, Log) Lolitech@547: if projectOpen is not None and os.path.isdir(projectOpen): Lolitech@547: result = PluginRoot.LoadProject(projectOpen, buildpath) Lolitech@547: if result: laurent@551: Log.write("Error: Invalid project directory", result) Lolitech@547: else: laurent@551: Log.write("Error: No such file or directory") Lolitech@547: Lolitech@547: cmd_thread=Thread(target=CmdThreadProc, args=[PluginRoot, Log]) Lolitech@547: cmd_thread.start() Lolitech@547: Lolitech@547: # Install a exception handle for bug reports Lolitech@547: AddExceptHook(os.getcwd(),__version__) Lolitech@547: Lolitech@547: frame = LPCBeremiz(None, plugin_root=PluginRoot, debug=True) Lolitech@547: Lolitech@547: app.MainLoop() Lolitech@547: