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