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: Laurent@18: _base_folder = os.path.split(sys.path[0])[0] Laurent@18: sys.path.append(os.path.join(_base_folder, "beremiz")) Laurent@18: Laurent@18: from util.TranslationCatalogs import AddCatalog, locale Laurent@18: AddCatalog(os.path.join(CWD, "locale")) Edouard@0: Edouard@0: if __name__ == '__main__': Laurent@18: # Import module for internationalization Laurent@18: import gettext Laurent@18: Laurent@18: __builtin__.__dict__['loc'] = locale Laurent@18: __builtin__.__dict__['_'] = wx.GetTranslation Edouard@0: Laurent@2: _base_path = os.path.split(__file__)[0] Edouard@3: import features Edouard@7: from POULibrary import POULibrary Edouard@7: Edouard@7: class PLCLibrary(POULibrary): Edouard@7: def GetLibraryPath(self): Edouard@7: return os.path.join(_base_path, "pous.xml") Edouard@7: Edouard@7: features.libraries=[('LPC', lambda: PLCLibrary)] Edouard@7: Laurent@2: Laurent@2: import connectors Laurent@2: from LPCconnector import LPC_connector_factory Laurent@2: connectors.connectors["LPC"]=lambda:LPC_connector_factory Laurent@2: Laurent@2: import targets Laurent@2: from LPCtarget import LPC_target Laurent@2: targets.targets["LPC"] = {"xsd": os.path.join(_base_path, "LPCtarget", "XSD"), Laurent@4: "class": lambda: LPC_target, Laurent@2: "code": os.path.join(_base_path,"LPCtarget","plc_LPC_main.c")} Laurent@2: targets.toolchains["makefile"] = os.path.join(_base_path, "LPCtarget", "XSD_toolchain_makefile") Laurent@2: Edouard@0: from Beremiz import * Edouard@0: from ProjectController import ProjectController Edouard@0: from ConfigTreeNode import ConfigTreeNode Laurent@17: from editors.ProjectNodeEditor import ProjectNodeEditor Laurent@2: Edouard@0: from plcopen.structures import LOCATIONDATATYPES Laurent@2: from PLCControler import PLCControler, LOCATION_CONFNODE, LOCATION_MODULE, LOCATION_GROUP,\ Edouard@0: LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY Laurent@17: from IDEFrame import IDEFrame Laurent@17: from dialogs import ProjectDialog Laurent@20: from controls import TextCtrlAutoComplete 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 Laurent@2: from canfestival.NetworkEditor import NetworkEditor Laurent@2: from canfestival.SlaveEditor import SlaveEditor Edouard@0: havecanfestival = True Edouard@0: except: Edouard@0: havecanfestival = False Edouard@0: Laurent@2: SCROLLBAR_UNIT = 10 Laurent@2: WINDOW_COLOUR = wx.Colour(240,240,240) Laurent@2: TITLE_COLOUR = wx.Colour(200,200,220) Laurent@2: CHANGED_TITLE_COLOUR = wx.Colour(220,200,220) Laurent@2: CHANGED_WINDOW_COLOUR = wx.Colour(255,240,240) Laurent@2: Laurent@2: if wx.Platform == '__WXMSW__': Laurent@2: faces = { 'times': 'Times New Roman', Laurent@2: 'mono' : 'Courier New', Laurent@2: 'helv' : 'Arial', Laurent@2: 'other': 'Comic Sans MS', Laurent@2: 'size' : 16, Laurent@2: } Laurent@2: else: Laurent@2: faces = { 'times': 'Times', Laurent@2: 'mono' : 'Courier', Laurent@2: 'helv' : 'Helvetica', Laurent@2: 'other': 'new century schoolbook', Laurent@2: 'size' : 18, Laurent@2: } Laurent@2: Laurent@2: # Some helpers to tweak GenBitmapTextButtons Laurent@2: # TODO: declare customized classes instead. Laurent@2: gen_mini_GetBackgroundBrush = lambda obj:lambda dc: wx.Brush(obj.GetParent().GetBackgroundColour(), wx.SOLID) Laurent@2: gen_textbutton_GetLabelSize = lambda obj:lambda:(wx.lib.buttons.GenButton._GetLabelSize(obj)[:-1] + (False,)) Laurent@2: Laurent@2: def make_genbitmaptogglebutton_flat(button): Laurent@2: button.GetBackgroundBrush = gen_mini_GetBackgroundBrush(button) Laurent@2: button.labelDelta = 0 Laurent@2: button.SetBezelWidth(0) Laurent@2: button.SetUseFocusIndicator(False) Laurent@2: Laurent@2: # Patch wx.lib.imageutils so that gray is supported on alpha images Laurent@2: import wx.lib.imageutils Laurent@2: from wx.lib.imageutils import grayOut as old_grayOut Laurent@2: def grayOut(anImage): Laurent@2: if anImage.HasAlpha(): Laurent@2: AlphaData = anImage.GetAlphaData() Laurent@2: else : Laurent@2: AlphaData = None Laurent@2: Laurent@2: old_grayOut(anImage) Laurent@2: Laurent@2: if AlphaData is not None: Laurent@2: anImage.SetAlphaData(AlphaData) Laurent@2: Laurent@2: wx.lib.imageutils.grayOut = grayOut Laurent@2: Laurent@2: class GenBitmapTextButton(wx.lib.buttons.GenBitmapTextButton): Laurent@2: def _GetLabelSize(self): Laurent@2: """ used internally """ Laurent@2: w, h = self.GetTextExtent(self.GetLabel()) Laurent@2: if not self.bmpLabel: Laurent@2: return w, h, False # if there isn't a bitmap use the size of the text Laurent@2: Laurent@2: w_bmp = self.bmpLabel.GetWidth()+2 Laurent@2: h_bmp = self.bmpLabel.GetHeight()+2 Laurent@2: height = h + h_bmp Laurent@2: if w_bmp > w: Laurent@2: width = w_bmp Laurent@2: else: Laurent@2: width = w Laurent@2: return width, height, False Laurent@2: Laurent@2: def DrawLabel(self, dc, width, height, dw=0, dy=0): Laurent@2: bmp = self.bmpLabel Laurent@2: if bmp != None: # if the bitmap is used Laurent@2: if self.bmpDisabled and not self.IsEnabled(): Laurent@2: bmp = self.bmpDisabled Laurent@2: if self.bmpFocus and self.hasFocus: Laurent@2: bmp = self.bmpFocus Laurent@2: if self.bmpSelected and not self.up: Laurent@2: bmp = self.bmpSelected Laurent@2: bw,bh = bmp.GetWidth(), bmp.GetHeight() Laurent@2: if not self.up: Laurent@2: dw = dy = self.labelDelta Laurent@2: hasMask = bmp.GetMask() != None Laurent@2: else: Laurent@2: bw = bh = 0 # no bitmap -> size is zero Laurent@2: Laurent@2: dc.SetFont(self.GetFont()) Laurent@2: if self.IsEnabled(): Laurent@2: dc.SetTextForeground(self.GetForegroundColour()) Laurent@2: else: Laurent@2: dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)) Laurent@2: Laurent@2: label = self.GetLabel() Laurent@2: tw, th = dc.GetTextExtent(label) # size of text Laurent@2: if not self.up: Laurent@2: dw = dy = self.labelDelta Laurent@2: Laurent@2: pos_x = (width-bw)/2+dw # adjust for bitmap and text to centre Laurent@2: pos_y = (height-bh-th)/2+dy Laurent@2: if bmp !=None: Laurent@2: dc.DrawBitmap(bmp, pos_x, pos_y, hasMask) # draw bitmap if available Laurent@2: pos_x = (width-tw)/2+dw # adjust for bitmap and text to centre Laurent@2: pos_y += bh + 2 Laurent@2: Laurent@2: dc.DrawText(label, pos_x, pos_y) # draw the text Laurent@2: 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: Laurent@2: class LPCSlaveEditor(SlaveEditor): Laurent@11: SHOW_BASE_PARAMS = False Laurent@2: Edouard@0: class LPCCanOpenSlave(_SlaveCTN): Edouard@0: XSD = """ Edouard@0: Edouard@0: Edouard@0: Edouard@0: Laurent@20: 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: Laurent@2: EditorType = LPCSlaveEditor Laurent@2: 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()) Laurent@2: Laurent@14: ConfNodeMethods = [ Laurent@14: {"bitmap" : "NetworkEdit", Laurent@14: "name" : _("Edit slave"), Laurent@14: "tooltip" : _("Edit CanOpen slave with ObjdictEdit"), Laurent@14: "method" : "_OpenView"}, Laurent@14: ] + _SlaveCTN.ConfNodeMethods Laurent@14: Laurent@2: class LPCNetworkEditor(NetworkEditor): Laurent@11: SHOW_BASE_PARAMS = False Edouard@0: Edouard@0: class LPCCanOpenMaster(_NodeListCTN): Edouard@0: XSD = """ Edouard@0: Edouard@0: Edouard@0: Edouard@0: Laurent@20: Edouard@0: Edouard@0: Edouard@0: Edouard@0: Edouard@0: """ % DEFAULT_SETTINGS Laurent@2: Laurent@2: EditorType = LPCNetworkEditor Laurent@2: Edouard@0: def GetCanDevice(self): Edouard@0: return str(self.BaseParams.getIEC_Channel()) Edouard@0: Laurent@14: ConfNodeMethods = [ Laurent@14: {"bitmap" : "NetworkEdit", Laurent@14: "name" : _("Edit network"), Laurent@14: "tooltip" : _("Edit CanOpen Network with NetworkEdit"), Laurent@14: "method" : "_OpenView"}, Laurent@14: ] + _NodeListCTN.ConfNodeMethods Laurent@14: Edouard@0: class LPCCanOpen(CanOpenRootClass): Edouard@0: XSD = None Laurent@11: CTNChildrenTypes = [("CanOpenNode", LPCCanOpenMaster, "CanOpen Master"), Laurent@11: ("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) Laurent@4: #master.BaseParams.setEnabled(False) Laurent@2: master.CTNRequestSave() Edouard@0: Edouard@0: if self.GetChildByName("Slave") is None: Edouard@0: slave = self.CTNAddChild("Slave", "CanOpenSlave", 1) Laurent@4: #slave.BaseParams.setEnabled(False) Laurent@2: slave.CTNRequestSave() 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): Laurent@4: if not i.startswith('.'): 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: Laurent@2: class LPCProjectNodeEditor(ProjectNodeEditor): Laurent@2: SHOW_PARAMS = False Laurent@2: ENABLE_REQUIRED = False Laurent@2: Edouard@0: class LPCProjectController(ProjectController): Edouard@0: Laurent@2: StatusMethods = [ Laurent@2: {"bitmap" : "Debug", Edouard@0: "name" : _("Simulate"), Edouard@0: "tooltip" : _("Simulate PLC"), Edouard@0: "method" : "_Simulate"}, Laurent@2: {"bitmap" : "Run", Edouard@0: "name" : _("Run"), Edouard@0: "shown" : False, Edouard@0: "tooltip" : _("Start PLC"), Edouard@0: "method" : "_Run"}, Laurent@2: {"bitmap" : "Stop", Edouard@0: "name" : _("Stop"), Edouard@0: "shown" : False, Edouard@0: "tooltip" : _("Stop Running PLC"), Edouard@0: "method" : "_Stop"}, Laurent@2: {"bitmap" : "Build", Edouard@0: "name" : _("Build"), Edouard@0: "tooltip" : _("Build project into build folder"), Edouard@0: "method" : "_Build"}, Laurent@2: {"bitmap" : "Transfer", Edouard@0: "name" : _("Transfer"), Edouard@0: "shown" : False, Edouard@0: "tooltip" : _("Transfer PLC"), Edouard@0: "method" : "_Transfer"}, Edouard@0: ] Laurent@2: Laurent@2: ConfNodeMethods = [] Laurent@2: Laurent@2: EditorType = LPCProjectNodeEditor Laurent@2: 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: Laurent@2: def GetProjectInfos(self): Laurent@2: infos = PLCControler.GetProjectInfos(self) Laurent@2: configurations = infos["values"].pop(-1) Laurent@2: resources = None Laurent@2: for config_infos in configurations["values"]: Laurent@2: if resources is None: Laurent@2: resources = config_infos["values"][0] Laurent@2: else: Laurent@2: resources["values"].extend(config_infos["values"][0]["values"]) Laurent@2: if resources is not None: Laurent@2: infos["values"].append(resources) Laurent@2: return infos Laurent@2: 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: Laurent@21: # Update a PLCOpenEditor Pou variable location Laurent@21: def UpdateProjectVariableLocation(self, old_leading, new_leading): Laurent@21: self.Project.updateElementAddress(old_leading, new_leading) Laurent@21: self.BufferProject() Laurent@21: 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: Laurent@19: def AddProjectDefaultConfiguration(self, config_name="config", res_name="resource1"): Laurent@19: ProjectController.AddProjectDefaultConfiguration(self, config_name, res_name) Laurent@19: Laurent@19: self.SetEditedResourceInfos( Laurent@19: self.ComputeConfigurationResourceName(config_name, res_name), Laurent@19: [{"Name": "main_task", Laurent@19: "Triggering": "Cyclic", Laurent@19: "Interval": "T#50ms", Laurent@19: "Priority": 0}], Laurent@19: []) Laurent@19: 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": {}}) Laurent@19: if len(self.GetProjectConfigNames()) == 0: Laurent@19: self.AddProjectDefaultConfiguration() 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) Laurent@4: #canopen.BaseParams.setEnabled(False) Edouard@0: canopen.LoadChildren() Laurent@2: canopen.CTNRequestSave() 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() Laurent@21: self.AppFrame.RefreshPouInstanceVariablesPanel() 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_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.OnQuitMenu, id=wx.ID_EXIT) Edouard@0: Laurent@16: self.AddToMenuToolBar([(wx.ID_SAVE, "save", _(u'Save'), None), Laurent@16: (wx.ID_PRINT, "print", _(u'Print'), None)]) Edouard@0: Laurent@2: def _init_coll_AddMenu_Items(self, parent): Laurent@2: IDEFrame._init_coll_AddMenu_Items(self, parent, False) Laurent@2: new_id = wx.NewId() Laurent@2: AppendMenu(parent, help='', id=new_id, Laurent@2: kind=wx.ITEM_NORMAL, text=_(u'&Resource')) Laurent@2: self.Bind(wx.EVT_MENU, self.AddResourceMenu, id=new_id) Laurent@2: Edouard@0: def _init_ctrls(self, prnt): Laurent@2: Beremiz._init_ctrls(self, prnt) 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) Laurent@2: self.MainTabs["PLCConfig"] = (self.PLCConfig, _("Topology")) Edouard@0: self.LeftNoteBook.InsertPage(0, self.PLCConfig, _("Topology"), True) Edouard@0: Laurent@2: self.PLCConfigMainSizer = wx.FlexGridSizer(cols=1, hgap=2, rows=2, vgap=2) Laurent@2: self.PLCParamsSizer = wx.BoxSizer(wx.VERTICAL) Laurent@2: self.ConfNodeTreeSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=0, vgap=2) Laurent@2: self.ConfNodeTreeSizer.AddGrowableCol(0) Laurent@2: self.ConfNodeTreeSizer.AddGrowableCol(1) Laurent@2: Laurent@2: self.PLCConfigMainSizer.AddSizer(self.PLCParamsSizer, 0, border=10, flag=wx.GROW|wx.TOP|wx.LEFT|wx.RIGHT) Laurent@2: self.PLCConfigMainSizer.AddSizer(self.ConfNodeTreeSizer, 0, border=10, flag=wx.BOTTOM|wx.LEFT|wx.RIGHT) Laurent@2: self.PLCConfigMainSizer.AddGrowableCol(0) Laurent@2: self.PLCConfigMainSizer.AddGrowableRow(1) Laurent@2: Laurent@2: self.PLCConfig.SetSizer(self.PLCConfigMainSizer) Laurent@2: Laurent@2: self.AUIManager.Update() Laurent@2: Laurent@2: def __init__(self, parent, projectOpen=None, buildpath=None, ctr=None, debug=True): Laurent@2: self.ConfNodeInfos = {} Laurent@2: Laurent@2: Beremiz.__init__(self, parent, projectOpen, buildpath, ctr, debug) Laurent@21: Laurent@21: def Show(self): Laurent@21: wx.Frame.Show(self) Laurent@21: 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: Laurent@2: def OnMoveWindow(self, event): Laurent@2: self.GetBestSize() Laurent@2: self.RefreshScrollBars() Laurent@2: event.Skip() Laurent@2: Laurent@2: def OnPanelLeftDown(self, event): Laurent@2: focused = self.FindFocus() Laurent@2: if isinstance(focused, TextCtrlAutoComplete): Laurent@2: focused.DismissListBox() Laurent@2: event.Skip() 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: 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) Laurent@2: Laurent@2: def RefreshScrollBars(self): Laurent@2: xstart, ystart = self.PLCConfig.GetViewStart() Laurent@2: window_size = self.PLCConfig.GetClientSize() Laurent@2: sizer = self.PLCConfig.GetSizer() Laurent@2: if sizer: Laurent@2: maxx, maxy = sizer.GetMinSize() Laurent@2: posx = max(0, min(xstart, (maxx - window_size[0]) / SCROLLBAR_UNIT)) Laurent@2: posy = max(0, min(ystart, (maxy - window_size[1]) / SCROLLBAR_UNIT)) Laurent@2: self.PLCConfig.Scroll(posx, posy) Laurent@2: self.PLCConfig.SetScrollbars(SCROLLBAR_UNIT, SCROLLBAR_UNIT, Laurent@2: maxx / SCROLLBAR_UNIT, maxy / SCROLLBAR_UNIT, posx, posy) Laurent@2: 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: Laurent@2: def GenerateMethodButtonSizer(self, confnode, parent, horizontal = True): Laurent@2: normal_bt_font=wx.Font(faces["size"] / 3, wx.DEFAULT, wx.NORMAL, wx.NORMAL, faceName = faces["helv"]) Laurent@2: mouseover_bt_font=wx.Font(faces["size"] / 3, wx.DEFAULT, wx.NORMAL, wx.NORMAL, underline=True, faceName = faces["helv"]) Laurent@2: if horizontal: Laurent@2: msizer = wx.FlexGridSizer(cols=len(confnode.ConfNodeMethods)) Laurent@2: else: Laurent@2: msizer = wx.FlexGridSizer(cols=1) Laurent@2: for confnode_method in confnode.ConfNodeMethods: Laurent@2: if "method" in confnode_method and confnode_method.get("shown",True): Laurent@2: id = wx.NewId() Laurent@2: label = confnode_method["name"] Laurent@2: button = GenBitmapTextButton(id=id, parent=parent, Laurent@2: bitmap=wx.Bitmap(Bpath("images", "%s.png"%confnode_method.get("bitmap", "Unknown"))), label=label, Laurent@2: name=label, pos=wx.DefaultPosition, style=wx.NO_BORDER) Laurent@2: button.SetFont(normal_bt_font) Laurent@2: button.SetToolTipString(confnode_method["tooltip"]) Laurent@2: button.Bind(wx.EVT_BUTTON, self.GetButtonCallBackFunction(confnode, confnode_method["method"]), id=id) Laurent@2: # a fancy underline on mouseover Laurent@2: def setFontStyle(b, s): Laurent@2: def fn(event): Laurent@2: b.SetFont(s) Laurent@2: b.Refresh() Laurent@2: event.Skip() Laurent@2: return fn Laurent@2: button.Bind(wx.EVT_ENTER_WINDOW, setFontStyle(button, mouseover_bt_font)) Laurent@2: button.Bind(wx.EVT_LEAVE_WINDOW, setFontStyle(button, normal_bt_font)) Laurent@2: #hack to force size to mini Laurent@2: if not confnode_method.get("enabled",True): Laurent@2: button.Disable() Laurent@2: msizer.AddWindow(button, 0, border=0, flag=wx.ALIGN_CENTER) Laurent@2: return msizer Laurent@2: Laurent@2: def GenerateEnableButton(self, parent, sizer, confnode): Laurent@2: enabled = confnode.CTNEnabled() Laurent@2: if enabled is not None: Laurent@2: enablebutton_id = wx.NewId() Laurent@2: enablebutton = wx.lib.buttons.GenBitmapToggleButton(id=enablebutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'Disabled.png')), Laurent@2: name='EnableButton', parent=parent, size=wx.Size(16, 16), pos=wx.Point(0, 0), style=0)#wx.NO_BORDER) Laurent@2: enablebutton.SetToolTipString(_("Enable/Disable this confnode")) Laurent@2: make_genbitmaptogglebutton_flat(enablebutton) Laurent@2: enablebutton.SetBitmapSelected(wx.Bitmap(Bpath( 'images', 'Enabled.png'))) Laurent@2: enablebutton.SetToggle(enabled) Laurent@2: def toggleenablebutton(event): Laurent@2: res = self.SetConfNodeParamsAttribute(confnode, "BaseParams.Enabled", enablebutton.GetToggle()) Laurent@2: enablebutton.SetToggle(res) Laurent@2: event.Skip() Laurent@2: enablebutton.Bind(wx.EVT_BUTTON, toggleenablebutton, id=enablebutton_id) Laurent@2: sizer.AddWindow(enablebutton, 0, border=0, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) Laurent@2: else: Laurent@2: sizer.AddSpacer(wx.Size(16, 16)) Laurent@2: Laurent@2: def RefreshConfNodeTree(self): Laurent@2: self.Freeze() Laurent@2: self.ClearSizer(self.ConfNodeTreeSizer) Laurent@2: if self.CTR is not None: Laurent@2: for child in self.CTR.IECSortedChildren(): Laurent@2: self.GenerateTreeBranch(child) Laurent@2: if not self.ConfNodeInfos[child]["expanded"]: Laurent@2: self.CollapseConfNode(child) Laurent@2: self.PLCConfigMainSizer.Layout() Laurent@2: self.RefreshScrollBars() Laurent@2: self.Thaw() Laurent@2: 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: Laurent@4: #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()) Laurent@4: leftwindowsizer.AddWindow(st, 0, border=5, flag=wx.LEFT|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: Laurent@2: rightwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) Laurent@2: rightwindow.SetBackgroundColour(bkgdclr) Laurent@2: rightwindowsizer = self.GenerateMethodButtonSizer(confnode, rightwindow, not self.ConfNodeInfos[confnode]["right_visible"]) Laurent@2: rightwindow.SetSizer(rightwindowsizer) 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: Laurent@2: def ExpandConfNode(self, confnode, force = False): Laurent@2: for child in self.ConfNodeInfos[confnode]["children"]: Laurent@2: self.ConfNodeInfos[child]["left"].Show() Laurent@2: self.ConfNodeInfos[child]["right"].Show() Laurent@2: if force or self.ConfNodeInfos[child]["expanded"]: Laurent@2: self.ExpandConfNode(child, force) Laurent@2: if force: Laurent@2: self.ConfNodeInfos[child]["expanded"] = True Laurent@2: locations_infos = self.ConfNodeInfos[confnode].get("locations_infos", None) Laurent@2: if locations_infos is not None: Laurent@2: if force or locations_infos["root"]["expanded"]: Laurent@2: self.ExpandLocation(locations_infos, "root", force) Laurent@2: if force: Laurent@2: locations_infos["root"]["expanded"] = True Laurent@2: Laurent@2: def CollapseConfNode(self, confnode, force = False): Laurent@2: for child in self.ConfNodeInfos[confnode]["children"]: Laurent@2: self.ConfNodeInfos[child]["left"].Hide() Laurent@2: self.ConfNodeInfos[child]["right"].Hide() Laurent@2: self.CollapseConfNode(child, force) Laurent@2: if force: Laurent@2: self.ConfNodeInfos[child]["expanded"] = False Laurent@2: locations_infos = self.ConfNodeInfos[confnode].get("locations_infos", None) Laurent@2: if locations_infos is not None: Laurent@2: self.CollapseLocation(locations_infos, "root", force) Laurent@2: if force: Laurent@2: locations_infos["root"]["expanded"] = False Laurent@2: Laurent@2: def ExpandLocation(self, locations_infos, group, force = False, refresh_size=True): Laurent@2: locations_infos[group]["expanded"] = True Laurent@2: if group == "root": Laurent@2: if locations_infos[group]["left"] is not None: Laurent@2: locations_infos[group]["left"].Show() Laurent@2: if locations_infos[group]["right"] is not None: Laurent@2: locations_infos[group]["right"].Show() Laurent@2: elif locations_infos["root"]["left"] is not None: Laurent@2: locations_infos["root"]["left"].Expand(locations_infos[group]["item"]) Laurent@2: if force: Laurent@2: for child in locations_infos[group]["children"]: Laurent@2: self.ExpandLocation(locations_infos, child, force, False) Laurent@2: if locations_infos["root"]["left"] is not None and refresh_size: Laurent@2: self.RefreshTreeCtrlSize(locations_infos["root"]["left"]) Laurent@2: Laurent@2: def CollapseLocation(self, locations_infos, group, force = False, refresh_size=True): Laurent@2: locations_infos[group]["expanded"] = False Laurent@2: if group == "root": Laurent@2: if locations_infos[group]["left"] is not None: Laurent@2: locations_infos[group]["left"].Hide() Laurent@2: if locations_infos[group]["right"] is not None: Laurent@2: locations_infos[group]["right"].Hide() Laurent@2: elif locations_infos["root"]["left"] is not None: Laurent@2: locations_infos["root"]["left"].Collapse(locations_infos[group]["item"]) Laurent@2: if force: Laurent@2: for child in locations_infos[group]["children"]: Laurent@2: self.CollapseLocation(locations_infos, child, force, False) Laurent@2: if locations_infos["root"]["left"] is not None and refresh_size: Laurent@2: self.RefreshTreeCtrlSize(locations_infos["root"]["left"]) Laurent@2: Laurent@2: def GenerateLocationTreeBranch(self, treectrl, root, locations_infos, parent, location): Laurent@2: location_name = "%s.%s" % (parent, location["name"]) Laurent@2: if not locations_infos.has_key(location_name): Laurent@2: locations_infos[location_name] = {"expanded" : False} Laurent@2: Laurent@2: if location["type"] in [LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY]: Laurent@2: label = "%(name)s (%(location)s)" % location Laurent@2: elif location["location"] != "": Laurent@2: label = "%(location)s: %(name)s" % location Laurent@2: else: Laurent@2: label = location["name"] Laurent@2: item = treectrl.AppendItem(root, label) Laurent@2: treectrl.SetPyData(item, location_name) Laurent@2: treectrl.SetItemImage(item, self.LocationImageDict[location["type"]]) Laurent@2: Laurent@2: locations_infos[location_name]["item"] = item Laurent@2: locations_infos[location_name]["children"] = [] Laurent@2: infos = location.copy() Laurent@2: infos.pop("children") Laurent@2: locations_infos[location_name]["infos"] = infos Laurent@2: for child in location["children"]: Laurent@2: child_name = "%s.%s" % (location_name, child["name"]) Laurent@2: locations_infos[location_name]["children"].append(child_name) Laurent@2: self.GenerateLocationTreeBranch(treectrl, item, locations_infos, location_name, child) Laurent@2: if locations_infos[location_name]["expanded"]: Laurent@2: self.ExpandLocation(locations_infos, location_name) Laurent@2: Laurent@2: def GenerateLocationBeginDragFunction(self, locations_infos): Laurent@2: def OnLocationBeginDragFunction(event): Laurent@2: item = event.GetItem() Laurent@2: location_name = locations_infos["root"]["left"].GetPyData(item) Laurent@2: if location_name is not None: Laurent@2: infos = locations_infos[location_name]["infos"] Laurent@2: if infos["type"] in [LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY]: Laurent@2: data = wx.TextDataObject(str((infos["location"], "location", infos["IEC_type"], infos["var_name"], infos["description"]))) Laurent@2: dragSource = wx.DropSource(self) Laurent@2: dragSource.SetData(data) Laurent@2: dragSource.DoDragDrop() Laurent@2: return OnLocationBeginDragFunction Laurent@2: Laurent@2: def RefreshTreeCtrlSize(self, treectrl): Laurent@2: rect = self.GetTreeCtrlItemRect(treectrl, treectrl.GetRootItem()) Laurent@2: treectrl.SetMinSize(wx.Size(max(rect.width, rect.x + rect.width) + 20, max(rect.height, rect.y + rect.height))) Laurent@2: self.PLCConfigMainSizer.Layout() Laurent@2: self.PLCConfig.Refresh() Laurent@2: wx.CallAfter(self.RefreshScrollBars) Laurent@2: Laurent@2: def GetTreeCtrlItemRect(self, treectrl, item): Laurent@2: item_rect = treectrl.GetBoundingRect(item, True) Laurent@2: if item_rect is not None: Laurent@2: minx, miny = item_rect.x, item_rect.y Laurent@2: maxx, maxy = item_rect.x + item_rect.width, item_rect.y + item_rect.height Laurent@2: else: Laurent@2: minx = miny = maxx = maxy = 0 Laurent@2: Laurent@2: if treectrl.ItemHasChildren(item) and (item == treectrl.GetRootItem() or treectrl.IsExpanded(item)): Laurent@2: if wx.VERSION >= (2, 6, 0): Laurent@2: child, item_cookie = treectrl.GetFirstChild(item) Laurent@2: else: Laurent@2: child, item_cookie = treectrl.GetFirstChild(item, 0) Laurent@2: while child.IsOk(): Laurent@2: child_rect = self.GetTreeCtrlItemRect(treectrl, child) Laurent@2: minx = min(minx, child_rect.x) Laurent@2: miny = min(miny, child_rect.y) Laurent@2: maxx = max(maxx, child_rect.x + child_rect.width) Laurent@2: maxy = max(maxy, child_rect.y + child_rect.height) Laurent@2: child, item_cookie = treectrl.GetNextChild(item, item_cookie) Laurent@2: Laurent@2: return wx.Rect(minx, miny, maxx - minx, maxy - miny) Laurent@2: Laurent@2: def GenerateLocationExpandCollapseFunction(self, locations_infos, expand): Laurent@2: def OnLocationExpandedFunction(event): Laurent@2: item = event.GetItem() Laurent@2: location_name = locations_infos["root"]["left"].GetPyData(item) Laurent@2: if location_name is not None: Laurent@2: locations_infos[location_name]["expanded"] = expand Laurent@2: self.RefreshTreeCtrlSize(locations_infos["root"]["left"]) Laurent@2: event.Skip() Laurent@2: return OnLocationExpandedFunction Laurent@2: Laurent@2: def GetButtonCallBackFunction(self, confnode, method): Laurent@2: """ Generate the callbackfunc for a given confnode method""" Laurent@2: def OnButtonClick(event): Laurent@2: # Disable button to prevent re-entrant call Laurent@2: event.GetEventObject().Disable() Laurent@2: # Call Laurent@2: getattr(confnode,method)() Laurent@2: # Re-enable button Laurent@2: event.GetEventObject().Enable() Laurent@2: # Trigger refresh on Idle Laurent@2: wx.CallAfter(self.RefreshAll) Laurent@2: event.Skip() Laurent@2: return OnButtonClick Laurent@2: Laurent@2: def ClearSizer(self, sizer): Laurent@2: staticboxes = [] Laurent@2: for item in sizer.GetChildren(): Laurent@2: if item.IsSizer(): Laurent@2: item_sizer = item.GetSizer() Laurent@2: self.ClearSizer(item_sizer) Laurent@2: if isinstance(item_sizer, wx.StaticBoxSizer): Laurent@2: staticboxes.append(item_sizer.GetStaticBox()) Laurent@2: sizer.Clear(True) Laurent@2: for staticbox in staticboxes: Laurent@2: staticbox.Destroy() Laurent@2: Laurent@2: def RefreshAll(self): Laurent@2: Beremiz.RefreshAll(self) Laurent@2: self.RefreshPLCParams() Laurent@2: self.RefreshConfNodeTree() Laurent@2: 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 Laurent@21: self.restore_last_state = 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() Laurent@21: self.restore_last_state = True Laurent@21: self.RestartTimer() Edouard@0: Edouard@0: def Refresh(self): Edouard@0: global frame Edouard@0: if frame is not None: Laurent@21: if self.restore_last_state: Laurent@21: self.restore_last_state = False Laurent@21: frame.RestoreLastState() Laurent@21: else: Laurent@21: frame.RefreshEditor() Laurent@19: frame._Refresh(TITLE, PROJECTTREE, POUINSTANCEVARIABLESPANEL, FILEMENU, EDITMENU) 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): Laurent@6: new_properties = { Laurent@6: "projectName": projectname, Laurent@6: "productName": productname, Laurent@6: "productVersion": productversion, Laurent@6: "companyName": companyname} Laurent@6: self.CTR.SetProjectProperties(properties=new_properties, buffer=False) Laurent@6: 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: