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@650: import __builtin__ 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"): laurent@650: __builtin__.__dict__["BMZ_DBG"] = True edouard@571: else : laurent@650: __builtin__.__dict__["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: laurent@442: if __name__ == '__main__': laurent@442: __builtin__.__dict__['_'] = wx.GetTranslation#unicode_translation laurent@442: laurent@442: from Beremiz import * Edouard@717: from ConfigTree import ConfigTreeRoot, ConfigTreeNode, opjimg, connectors laurent@442: from plcopen.structures import LOCATIONDATATYPES Edouard@717: from PLCControler import LOCATION_CONFNODE, LOCATION_MODULE, LOCATION_GROUP,\ laurent@442: LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY laurent@500: from PLCOpenEditor import IDEFrame, ProjectDialog laurent@442: smarteh-dev@691: havecanfestival = False smarteh-dev@691: try: Edouard@717: from confnodes.canfestival import RootClass as CanOpenRootClass Edouard@718: from confnodes.canfestival.canfestival import _SlaveCTN, _NodeListCTN, NodeManager smarteh-dev@691: havecanfestival = True smarteh-dev@691: except: smarteh-dev@691: havecanfestival = False smarteh-dev@691: smarteh-dev@691: laurent@442: #------------------------------------------------------------------------------- Edouard@717: # CANFESTIVAL CONFNODE HACK edouard@512: #------------------------------------------------------------------------------- Edouard@717: # from confnodes.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: Edouard@717: BUS_TEXT = """/* Code generated by LPCBus confnode */ Edouard@717: Edouard@717: /* LPCBus confnode 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: Edouard@717: /* LPCBus confnode user variables definition */ laurent@442: %(var_decl)s laurent@442: Edouard@717: /* LPCBus confnode 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: Edouard@718: def CTNEnabled(self): smarteh-dev@682: return None smarteh-dev@682: 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): Edouard@718: return self.GetCTRoot().GetBaseTypes() laurent@442: laurent@442: def GetSizeOfType(self, type): Edouard@718: return LOCATION_SIZES[self.GetCTRoot().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@659: "var_name": infos["name"], 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(), Edouard@717: "type": LOCATION_CONFNODE, 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: Edouard@718: def CTNTestModified(self): laurent@442: return False laurent@442: Edouard@718: def CTNMakeDir(self): laurent@442: pass laurent@442: Edouard@718: def CTNRequestSave(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: Edouard@718: def CTNGenerate_C(self, buildpath, locations): laurent@442: """ laurent@442: Generate C code Edouard@717: @param current_location: Tupple containing confnode 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 Edouard@718: base_types = self.GetCTRoot().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: Edouard@718: matiec_flags = '"-I%s"'%os.path.abspath(self.GetCTRoot().GetIECLibPath()) laurent@442: return [(Gen_Module_path, matiec_flags)],"",True laurent@442: laurent@442: #------------------------------------------------------------------------------- Edouard@717: # LPC CanFestival ConfNode Class smarteh-dev@682: #------------------------------------------------------------------------------- smarteh-dev@682: smarteh-dev@691: if havecanfestival: smarteh-dev@691: smarteh-dev@691: DEFAULT_SETTINGS = { smarteh-dev@691: "CAN_Baudrate": "125K", smarteh-dev@691: "Slave_NodeId": 2, smarteh-dev@691: "Master_NodeId": 1, smarteh-dev@691: } smarteh-dev@691: Edouard@718: class LPCCanOpenSlave(_SlaveCTN): smarteh-dev@691: XSD = """ smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: """ % DEFAULT_SETTINGS smarteh-dev@691: smarteh-dev@691: def __init__(self): smarteh-dev@691: # TODO change netname when name change smarteh-dev@691: NodeManager.__init__(self) smarteh-dev@691: odfilepath = self.GetSlaveODPath() smarteh-dev@691: if(os.path.isfile(odfilepath)): smarteh-dev@691: self.OpenFileInCurrent(odfilepath) smarteh-dev@691: else: smarteh-dev@691: self.CreateNewNode("SlaveNode", # Name - will be changed at build time smarteh-dev@691: 0x00, # NodeID - will be changed at build time smarteh-dev@691: "slave", # Type smarteh-dev@691: "", # description smarteh-dev@691: "None", # profile smarteh-dev@691: "", # prfile filepath smarteh-dev@691: "heartbeat", # NMT smarteh-dev@691: []) # options Edouard@718: self.OnCTNSave() smarteh-dev@691: smarteh-dev@691: def GetCanDevice(self): smarteh-dev@691: return str(self.BaseParams.getIEC_Channel()) smarteh-dev@691: Edouard@718: class LPCCanOpenMaster(_NodeListCTN): smarteh-dev@691: XSD = """ smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: smarteh-dev@691: """ % DEFAULT_SETTINGS smarteh-dev@691: smarteh-dev@691: def GetCanDevice(self): smarteh-dev@691: return str(self.BaseParams.getIEC_Channel()) smarteh-dev@691: smarteh-dev@691: class LPCCanOpen(CanOpenRootClass): smarteh-dev@691: XSD = None Edouard@718: CTNChildrenTypes = [("CanOpenNode",LPCCanOpenMaster, "CanOpen Master"), smarteh-dev@691: ("CanOpenSlave",LPCCanOpenSlave, "CanOpen Slave")] smarteh-dev@691: smarteh-dev@691: def GetCanDriver(self): smarteh-dev@691: return "" smarteh-dev@691: Edouard@718: def LoadChildren(self): Edouard@718: ConfigTreeNode.LoadChildren(self) smarteh-dev@691: smarteh-dev@691: if self.GetChildByName("Master") is None: Edouard@718: master = self.CTNAddChild("Master", "CanOpenNode", 0) smarteh-dev@691: master.BaseParams.setEnabled(False) smarteh-dev@691: smarteh-dev@691: if self.GetChildByName("Slave") is None: Edouard@718: slave = self.CTNAddChild("Slave", "CanOpenSlave", 1) smarteh-dev@691: slave.BaseParams.setEnabled(False) smarteh-dev@682: smarteh-dev@682: smarteh-dev@682: #------------------------------------------------------------------------------- Edouard@717: # LPCConfigTreeRoot 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@652: if not i.startswith('.') and i != "pous.xml": 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: Edouard@717: class LPCConfigTreeRoot(ConfigTreeRoot): Edouard@717: Edouard@717: ConfNodeMethods = [ 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@652: def __init__(self, frame, logger, buildpath): laurent@652: self.OrigBuildPath = buildpath laurent@652: Edouard@717: ConfigTreeRoot.__init__(self, frame, logger) laurent@487: smarteh-dev@691: if havecanfestival: Edouard@718: self.CTNChildrenTypes += [("LPCBus", LPCBus, "LPC bus"), ("CanOpen", LPCCanOpen, "CanOpen bus")] smarteh-dev@691: else: Edouard@718: self.CTNChildrenTypes += [("LPCBus", LPCBus, "LPC bus")] Edouard@718: self.CTNType = "LPC" laurent@652: 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@652: Edouard@717: def ConfNodeLibraryFilePath(self): laurent@652: if self.OrigBuildPath is not None: laurent@652: return os.path.join(self.OrigBuildPath, "pous.xml") laurent@652: else: Edouard@717: return ConfigTreeRoot.ConfNodeLibraryFilePath(self) laurent@652: 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: Edouard@717: return ConfigTreeRoot.GetDefaultTargetName(self) laurent@492: else: laurent@510: return "LPC" laurent@510: laurent@510: def GetTarget(self): Edouard@717: target = ConfigTreeRoot.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: Edouard@717: return ConfigTreeRoot._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@717: ConfigTreeRoot._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() Edouard@718: self.Children = {} laurent@500: Edouard@717: # Keep track of the root confnode (i.e. project path) laurent@442: self.ProjectPath = ProjectPath laurent@500: laurent@478: self.BuildPath = self._getBuildPath() laurent@652: if self.OrigBuildPath is not None: laurent@652: mycopytree(self.OrigBuildPath, self.BuildPath) laurent@442: laurent@478: # If dir have already be made, and file exist Edouard@718: if os.path.isdir(self.CTNPath()) and os.path.isfile(self.ConfNodeXmlFilePath()): Edouard@717: #Load the confnode.xml file into parameters members laurent@478: result = self.LoadXMLParams() laurent@478: if result: laurent@478: return result Edouard@718: #Load and init all the children Edouard@718: self.LoadChildren() laurent@500: smarteh-dev@691: if havecanfestival and self.GetChildByName("CanOpen") is None: Edouard@718: canopen = self.CTNAddChild("CanOpen", "CanOpen", 0) smarteh-dev@682: canopen.BaseParams.setEnabled(False) Edouard@718: canopen.LoadChildren() Edouard@718: Edouard@718: if self.CTNTestModified(): laurent@500: self.SaveProject() laurent@500: laurent@539: if wx.GetApp() is None: Edouard@717: self.RefreshConfNodesBlockLists() laurent@539: else: Edouard@717: wx.CallAfter(self.RefreshConfNodesBlockLists) 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@708: def Generate_lpc_retain_array_sim(self): laurent@708: """ laurent@708: Support for retain array in Simulation laurent@708: """ laurent@708: return """/* Support for retain array */ laurent@708: #define USER_RETAIN_ARRAY_SIZE 2000 laurent@708: #define NUM_OF_COLS 3 laurent@708: unsigned char readOK = 0; laurent@708: unsigned int foundIndex = USER_RETAIN_ARRAY_SIZE; laurent@708: unsigned int retainArray[USER_RETAIN_ARRAY_SIZE][NUM_OF_COLS]; laurent@708: laurent@708: unsigned int __GetRetainData(unsigned char READ, unsigned int INDEX, unsigned int COLUMN) laurent@708: { laurent@708: if(READ == 1) laurent@708: { laurent@708: if((0<=INDEX) && (INDEX return index that is out of array bounds */ laurent@708: return 0; laurent@708: } laurent@708: laurent@708: /* Since Beremiz debugger doesn't like pointer-by-reference stuff or global varibles, separate function is a must */ laurent@708: unsigned char __GetReadStatus(unsigned char dummy) laurent@708: { laurent@708: return readOK; laurent@708: } laurent@708: laurent@708: unsigned int __GetFoundIndex(unsigned char dummy) laurent@708: { laurent@708: return foundIndex; laurent@708: } laurent@708: """ laurent@708: 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: Edouard@718: gen_result = self.CTNGenerate_C(buildpath, self.PLCGeneratedLocatedVars) Edouard@718: CTNCFilesAndCFLAGS, CTNLDFLAGS, DoCalls = gen_result[:3] laurent@492: # if some files have been generated put them in the list with their location Edouard@718: if CTNCFilesAndCFLAGS: Edouard@718: self.LocationCFilesAndCFLAGS = [(self.GetCurrentLocation(), CTNCFilesAndCFLAGS, DoCalls)] laurent@492: else: laurent@492: self.LocationCFilesAndCFLAGS = [] laurent@492: Edouard@717: # confnode asks for some LDFLAGS Edouard@718: if CTNLDFLAGS: laurent@492: # LDFLAGS can be either string Edouard@718: if type(CTNLDFLAGS)==type(str()): Edouard@718: self.LDFLAGS=[CTNLDFLAGS] laurent@492: #or list of strings Edouard@718: elif type(CTNLDFLAGS)==type(list()): Edouard@718: self.LDFLAGS=CTNLDFLAGS[:] laurent@492: else: laurent@492: self.LDFLAGS=[] laurent@492: laurent@492: # Template based part of C code generation Edouard@717: # files are stacked at the beginning, as files of confnode 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@708: (self.Generate_plc_declare_locations,"plc_declare_locations.c","Declare Locations"), laurent@708: # declare located variables for simulate in a black box laurent@708: (self.Generate_lpc_retain_array_sim,"lpc_retain_array_sim.c","Retain Array for Simulation")]: 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) Edouard@717: # Insert this file as first file to be compiled at root confnode 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: self.UnsubscribeAllDebugIECVariable() laurent@492: self.ProgramTransferred() laurent@697: if self.AppFrame is not None: laurent@697: self.AppFrame.RefreshInstancesTree() laurent@697: self.AppFrame.CloseObsoleteDebugTabs() 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): Edouard@717: ConfigTreeRoot._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: laurent@677: def ResetBuildMD5(self): laurent@677: builder=self.GetBuilder() laurent@677: if builder is not None: smarteh-dev@691: builder.ResetBinaryCodeMD5(self.OnlineMode) laurent@677: 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@717: if ConfigTreeRoot._Build(self): laurent@677: laurent@677: ID_ABORTTRANSFERTIMER = wx.NewId() laurent@677: self.AbortTransferTimer = wx.Timer(self.AppFrame, ID_ABORTTRANSFERTIMER) laurent@677: self.AppFrame.Bind(wx.EVT_TIMER, self.AbortTransfer, self.AbortTransferTimer) laurent@677: laurent@677: if self.OnlineMode == "BOOTLOADER": laurent@677: self.BeginTransfer() laurent@677: laurent@677: else: laurent@677: self.logger.write(_("Resetting PLC\n")) laurent@677: #self.StatusTimer.Stop() laurent@677: self.LPCConnector.ResetPLC() laurent@677: self.AbortTransferTimer.Start(milliseconds=5000, oneShot=True) smarteh-dev@691: smarteh-dev@691: else: smarteh-dev@691: self.CurrentMode = None laurent@539: laurent@539: def BeginTransfer(self): laurent@539: self.logger.write(_("Start PLC transfer\n")) laurent@539: laurent@539: self.AbortTransferTimer.Stop() Edouard@717: ConfigTreeRoot._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@708: self.AddToMenuToolBar([(wx.ID_SAVE, "save.png", _(u'Save'), None), laurent@708: (wx.ID_PRINT, "print.png", _(u'Print'), None)]) laurent@706: 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: Edouard@717: self.CTR.ResetAppFrame(lpcberemiz_cmd.Log) Edouard@717: if self.CTR.OnlineMode == 0: Edouard@717: self.CTR._connector = None Edouard@717: Edouard@717: self.CTR.KillDebugThread() laurent@596: self.KillLocalRuntime() laurent@596: laurent@715: self.SaveLastState() 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@706: self._Refresh(TITLE, EDITORTOOLBAR, FILEMENU, EDITMENU, DISPLAYMENU, laurent@500: TYPESTREE, INSTANCESTREE, SCALING) laurent@500: dialog.Destroy() laurent@500: laurent@442: def RefreshFileMenu(self): laurent@708: MenuToolBar = self.Panes["MenuToolBar"] Edouard@717: if self.CTR 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@706: MenuToolBar.EnableTool(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@706: MenuToolBar.EnableTool(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@706: MenuToolBar.EnableTool(wx.ID_PRINT, False) laurent@442: self.FileMenu.Enable(wx.ID_PAGE_SETUP, True) Edouard@717: project_modified = self.CTR.ProjectTestModified() laurent@706: self.FileMenu.Enable(wx.ID_SAVE, project_modified) laurent@706: MenuToolBar.EnableTool(wx.ID_SAVE, project_modified) 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@706: MenuToolBar.EnableTool(wx.ID_PRINT, False) laurent@442: self.FileMenu.Enable(wx.ID_SAVE, False) laurent@706: MenuToolBar.EnableTool(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: Edouard@717: if self.CTR is not None: laurent@442: plcwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) Edouard@718: if self.CTR.CTNTestModified(): laurent@442: bkgdclr = CHANGED_TITLE_COLOUR laurent@442: else: laurent@442: bkgdclr = TITLE_COLOUR laurent@442: Edouard@717: if self.CTR not in self.ConfNodeInfos: Edouard@717: self.ConfNodeInfos[self.CTR] = {"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"])) Edouard@717: st.SetLabel(self.CTR.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: Edouard@717: msizer = self.GenerateMethodButtonSizer(self.CTR, plcwindow, not self.ConfNodeInfos[self.CTR]["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: Edouard@717: def GenerateTreeBranch(self, confnode): laurent@442: leftwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) Edouard@718: if confnode.CTNTestModified(): laurent@442: bkgdclr=CHANGED_WINDOW_COLOUR laurent@442: else: laurent@442: bkgdclr=WINDOW_COLOUR laurent@442: laurent@442: leftwindow.SetBackgroundColour(bkgdclr) laurent@442: Edouard@717: if confnode not in self.ConfNodeInfos: Edouard@717: self.ConfNodeInfos[confnode] = {"expanded" : False, "left_visible" : False, "right_visible" : False} Edouard@717: Edouard@718: self.ConfNodeInfos[confnode]["children"] = confnode.IECSortedChildren() Edouard@717: confnode_infos = confnode.GetVariableLocationTree() Edouard@717: confnode_locations = [] Edouard@717: if len(self.ConfNodeInfos[confnode]["children"]) == 0: Edouard@717: confnode_locations = confnode_infos["children"] Edouard@717: if not self.ConfNodeInfos[confnode].has_key("locations_infos"): Edouard@717: self.ConfNodeInfos[confnode]["locations_infos"] = {"root": {"expanded" : False}} Edouard@717: Edouard@717: self.ConfNodeInfos[confnode]["locations_infos"]["root"]["left"] = None Edouard@717: self.ConfNodeInfos[confnode]["locations_infos"]["root"]["right"] = None Edouard@717: self.ConfNodeInfos[confnode]["locations_infos"]["root"]["children"] = [] Edouard@717: Edouard@717: self.ConfNodeTreeSizer.AddWindow(leftwindow, 0, border=0, flag=wx.GROW) laurent@442: smarteh-dev@682: leftwindowvsizer = wx.BoxSizer(wx.VERTICAL) smarteh-dev@682: leftwindow.SetSizer(leftwindowvsizer) smarteh-dev@682: laurent@442: leftwindowsizer = wx.BoxSizer(wx.HORIZONTAL) smarteh-dev@682: leftwindowvsizer.AddSizer(leftwindowsizer, 0, border=0, flag=0) smarteh-dev@682: Edouard@717: self.GenerateEnableButton(leftwindow, leftwindowsizer, confnode) smarteh-dev@680: laurent@442: st = wx.StaticText(leftwindow, -1) laurent@442: st.SetFont(wx.Font(faces["size"], wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"])) Edouard@717: st.SetLabel(confnode.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: Edouard@717: if len(self.ConfNodeInfos[confnode]["children"]) > 0: Edouard@717: expandbutton.SetToggle(self.ConfNodeInfos[confnode]["expanded"]) laurent@442: def togglebutton(event): laurent@442: if expandbutton.GetToggle(): Edouard@717: self.ExpandConfNode(confnode) laurent@442: else: Edouard@717: self.CollapseConfNode(confnode) Edouard@717: self.ConfNodeInfos[confnode]["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) Edouard@717: elif len(confnode_locations) > 0: Edouard@717: locations_infos = self.ConfNodeInfos[confnode]["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") Edouard@717: self.ConfNodeInfos[confnode]["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) Edouard@717: icon = confnode_infos.get("icon", None) laurent@442: if icon is None: Edouard@717: icon_bitmap = self.LocationImageList.GetBitmap(self.LocationImageDict[confnode_infos["type"]]) laurent@650: else: laurent@650: icon_bitmap = wx.Bitmap(icon) laurent@650: sb.SetBitmap(icon_bitmap) 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"])) Edouard@717: st.SetLabel(confnode.MandatoryParams[1].getName()) laurent@442: leftwindowsizer.AddWindow(st, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) laurent@442: Edouard@717: rightwindow = self.GenerateParamsPanel(confnode, bkgdclr) Edouard@717: self.ConfNodeTreeSizer.AddWindow(rightwindow, 0, border=0, flag=wx.GROW) Edouard@717: Edouard@717: self.ConfNodeInfos[confnode]["left"] = leftwindow Edouard@717: self.ConfNodeInfos[confnode]["right"] = rightwindow Edouard@717: for child in self.ConfNodeInfos[confnode]["children"]: laurent@442: self.GenerateTreeBranch(child) Edouard@717: if not self.ConfNodeInfos[child]["expanded"]: Edouard@717: self.CollapseConfNode(child) Edouard@717: Edouard@717: if len(confnode_locations) > 0: Edouard@717: locations_infos = self.ConfNodeInfos[confnode]["locations_infos"] laurent@650: treectrl = wx.TreeCtrl(self.PLCConfig, -1, size=wx.DefaultSize, laurent@650: style=wx.TR_HAS_BUTTONS|wx.TR_SINGLE|wx.NO_BORDER|wx.TR_HIDE_ROOT|wx.TR_NO_LINES|wx.TR_LINES_AT_ROOT) laurent@650: treectrl.SetImageList(self.LocationImageList) laurent@650: treectrl.Bind(wx.EVT_TREE_BEGIN_DRAG, self.GenerateLocationBeginDragFunction(locations_infos)) laurent@650: treectrl.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.GenerateLocationExpandCollapseFunction(locations_infos, True)) laurent@650: treectrl.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.GenerateLocationExpandCollapseFunction(locations_infos, False)) laurent@650: laurent@650: treectrl.AddRoot("") Edouard@717: self.ConfNodeTreeSizer.AddWindow(treectrl, 0, border=0, flag=0) laurent@650: laurent@650: rightwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) laurent@650: rightwindow.SetBackgroundColour(wx.WHITE) Edouard@717: self.ConfNodeTreeSizer.AddWindow(rightwindow, 0, border=0, flag=wx.GROW) laurent@650: laurent@650: locations_infos["root"]["left"] = treectrl laurent@650: locations_infos["root"]["right"] = rightwindow Edouard@717: for location in confnode_locations: laurent@442: locations_infos["root"]["children"].append("root.%s" % location["name"]) laurent@650: self.GenerateLocationTreeBranch(treectrl, treectrl.GetRootItem(), locations_infos, "root", location) laurent@650: if locations_infos["root"]["expanded"]: laurent@650: self.ExpandLocation(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: Edouard@717: def __init__(self, CTR, Log): laurent@551: cmd.Cmd.__init__(self, stdin=Log, stdout=Log) laurent@551: self.use_rawinput = False Lolitech@547: self.Log = Log Edouard@717: self.CTR = CTR 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: Edouard@717: self.CTR.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: Edouard@717: self.CTR.ResetAppFrame(self.Log) laurent@442: if frame is not None: Lolitech@547: frame.Hide() laurent@442: laurent@442: def Compile(self): Edouard@717: self.CTR._Build() laurent@442: laurent@500: def SetProjectProperties(self, projectname, productname, productversion, companyname): Edouard@717: properties = self.CTR.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: Edouard@717: self.CTR.SetProjectProperties(properties=new_properties, buffer=False) laurent@597: self.RestartTimer() laurent@442: laurent@487: def SetOnlineMode(self, mode, path=None): Edouard@717: self.CTR.SetOnlineMode(mode, path) laurent@487: self.RestartTimer() laurent@487: laurent@442: def AddBus(self, iec_channel, name, icon=None): Edouard@718: for child in self.CTR.IterChildren(): 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 Edouard@718: bus = self.CTR.CTNAddChild(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): Edouard@717: bus = self.CTR.GetChildByIECLocation((iec_channel,)) laurent@442: if bus is None: laurent@551: return "Error: No bus found\n" Edouard@718: for child in self.CTR.IterChildren(): 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): Edouard@717: bus = self.CTR.GetChildByIECLocation((old_iec_channel,)) laurent@442: if bus is None: laurent@551: return "Error: No bus found\n" Edouard@718: for child in self.CTR.IterChildren(): 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: Edouard@717: self.CTR.UpdateProjectVariableLocation(str(old_iec_channel), laurent@539: str(new_iec_channel)) laurent@539: else: Edouard@717: self.CTR.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): Edouard@717: bus = self.CTR.GetChildByIECLocation((iec_channel,)) laurent@442: if bus is None: laurent@551: return "Error: No bus found\n" Edouard@717: self.CTR.RemoveProjectVariableByFilter(str(iec_channel)) Edouard@718: self.CTR.Children["LPCBus"].remove(bus) laurent@442: self.RestartTimer() laurent@442: laurent@553: def AddModule(self, parent, iec_channel, name, icode, icon=None): Edouard@717: module = self.CTR.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): Edouard@717: module = self.CTR.GetChildByIECLocation(iec_location) laurent@442: if module is None: laurent@551: return "Error: No module found\n" Edouard@717: parent = self.CTR.GetChildByIECLocation(iec_location[:-1]) Edouard@717: if parent is self.CTR: 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): Edouard@717: module = self.CTR.GetChildByIECLocation(old_iec_location) laurent@442: if module is None: laurent@551: return "Error: No module found\n" Edouard@717: parent = self.CTR.GetChildByIECLocation(old_iec_location[:-1]) Edouard@717: if parent is self.CTR: 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 Edouard@717: self.CTR.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): Edouard@717: module = self.CTR.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): Edouard@717: module = self.CTR.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" Edouard@717: self.CTR.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): Edouard@717: module = self.CTR.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=""): Edouard@717: module = self.CTR.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): Edouard@717: module = self.CTR.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: Edouard@717: self.CTR.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): Edouard@717: module = self.CTR.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" Edouard@717: size = LOCATION_SIZES[self.CTR.GetBaseType(child["IEC_type"])] laurent@444: address = "%" + LOCATION_DIRS[child["type"]] + size + ".".join(map(str, parent + location)) Edouard@717: self.CTR.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: Edouard@717: def CmdThreadProc(CTR, 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)) Edouard@717: lpcberemiz_cmd = LPCBeremiz_Cmd(CTR, Log) Lolitech@547: lpcberemiz_cmd.cmdloop() Lolitech@547: laurent@551: Log = StdoutPseudoFile(port) Lolitech@547: Edouard@717: CTR = LPCConfigTreeRoot(None, Log, buildpath) Lolitech@547: if projectOpen is not None and os.path.isdir(projectOpen): Edouard@717: result = CTR.LoadProject(projectOpen) 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: Edouard@717: cmd_thread=Thread(target=CmdThreadProc, args=[CTR, 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: Edouard@717: frame = LPCBeremiz(None, ctr=CTR, debug=True) Lolitech@547: Lolitech@547: app.MainLoop() Lolitech@547: