Initial commit, LPC files taken out of beremiz revision 915be999f3f0
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/LPCManager.py Sun May 20 11:29:35 2012 +0200
@@ -0,0 +1,1780 @@
+__version__ = "$Revision$" +import os, sys, getopt, wx, tempfile +from types import TupleType, StringType, UnicodeType +CWD = os.path.split(os.path.realpath(__file__))[0] + return os.path.join(CWD,*args) +if __name__ == '__main__': + print "\nUsage of LPCBeremiz.py :" + print "\n %s Projectpath Buildpath port\n"%sys.argv[0] + opts, args = getopt.getopt(sys.argv[1:], "h", ["help"]) + except getopt.GetoptError: + # print help information and exit: + if o in ("-h", "--help"): + if os.path.exists("LPC_DEBUG"): + __builtin__.__dict__["BMZ_DBG"] = True + __builtin__.__dict__["BMZ_DBG"] = False +app = wx.PySimpleApp(redirect=BMZ_DBG) +app.SetAppName('beremiz') +wx.InitAllImageHandlers() +# Import module for internationalization +if __name__ == '__main__': + __builtin__.__dict__['_'] = wx.GetTranslation#unicode_translation +_base_folder = os.path.split(sys.path[0])[0] +sys.path.append(os.path.join(base_folder, "beremiz")) +_base_path = path.split(__file__)[0] +from ProjectController import ProjectController +from ConfigTreeNode import ConfigTreeNode +from LPCconnector import LPC_connector_factory +connectors.connectors["LPC"]=lambda:LPC_connector_factory +from LPCtarget import LPC_target +targets.targets["LPC"]={"xsd": path.join(_base_path, "LPCtarget", "XSD"), + "code": path.join(_base_path,"LPCtarget","plc_LPC_main.c")} +from plcopen.structures import LOCATIONDATATYPES +from PLCControler import LOCATION_CONFNODE, LOCATION_MODULE, LOCATION_GROUP,\ + LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY +from PLCOpenEditor import IDEFrame, ProjectDialog + from canfestival import RootClass as CanOpenRootClass + from canfestival.canfestival import _SlaveCTN, _NodeListCTN, NodeManager + havecanfestival = False +#------------------------------------------------------------------------------- +# CANFESTIVAL CONFNODE HACK +#------------------------------------------------------------------------------- +# from canfestival import canfestival +# class LPC_canfestival_config: +# def getCFLAGS(self, *args): +# def getLDFLAGS(self, *args): +# canfestival.local_canfestival_config = LPC_canfestival_config() +#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------- +LOCATION_TYPES = {"I": LOCATION_VAR_INPUT, + "Q": LOCATION_VAR_OUTPUT, + "M": LOCATION_VAR_MEMORY} +LOCATION_DIRS = dict([(dir, size) for size, dir in LOCATION_TYPES.iteritems()]) +for size, types in LOCATIONDATATYPES.iteritems(): + LOCATION_SIZES[type] = size +def _GetModuleChildren(module): + for child in module["children"]: + if child["type"] == LOCATION_GROUP: + children.extend(child["children"]) +def _GetVariables(module): + for child in module["children"]: + if child["type"] in [LOCATION_GROUP, LOCATION_MODULE]: + variables.extend(_GetVariables(child)) + variables.append(child) +def _GetLastModuleGroup(module): + for child in module["children"]: + if child["type"] == LOCATION_GROUP: + return group["children"] +def _GetModuleBySomething(module, something, toks): + for child in _GetModuleChildren(module): + if child.get(something) == toks[0]: + return _GetModuleBySomething(child, something, toks[1:]) +def _GetModuleVariable(module, location, direction): + for child in _GetModuleChildren(module): + if child["location"] == location and child["type"] == LOCATION_TYPES[direction]: +def _RemoveModuleChild(module, child): + if child in module["children"]: + module["children"].remove(child) + for group in module["children"]: + if group["type"] == LOCATION_GROUP and child in group["children"]: + group["children"].remove(child) +BUS_TEXT = """/* Code generated by LPCBus confnode */ +/* LPCBus confnode includes */ + #include "iec_std_lib.h" +/* LPCBus confnode user variables definition */ +/* LPCBus confnode functions */ +int __init_%(location_str)s(int argc,char **argv) +void __cleanup_%(location_str)s(void) +void __retrieve_%(location_str)s(void) +void __publish_%(location_str)s(void) + self.VariableLocationTree = [] + self.ResetUsedLocations() + def __getitem__(self, key): + return self.VariableLocationTree + raise KeyError, "Only 'children' key is available" + def SetIcon(self, icon): + def _GetChildBySomething(self, something, toks): + return _GetModuleBySomething({"children" : self.VariableLocationTree}, something, toks) + def GetBaseTypes(self): + return self.GetCTRoot().GetBaseTypes() + def GetSizeOfType(self, type): + return LOCATION_SIZES[self.GetCTRoot().GetBaseType(type)] + def _GetVariableLocationTree(self, current_location, infos): + if infos["type"] == LOCATION_MODULE: + location = current_location + (infos["IEC_Channel"],) + return {"name": infos["name"], + "location": ".".join(map(str, location + ("x",))), + "children": [self._GetVariableLocationTree(location, child) for child in infos["children"]]} + elif infos["type"] == LOCATION_GROUP: + return {"name": infos["name"], + "children": [self._GetVariableLocationTree(current_location, child) for child in infos["children"]]} + size = self.GetSizeOfType(infos["IEC_type"]) + location = "%" + LOCATION_DIRS[infos["type"]] + size + ".".join(map(str, current_location + infos["location"])) + return {"name": infos["name"], + "IEC_type": infos["IEC_type"], + "var_name": infos["name"], + "description": infos["description"], + def GetVariableLocationTree(self): + return {"name": self.BaseParams.getName(), + "type": LOCATION_CONFNODE, + "location": self.GetFullIEC_Channel(), + "children": [self._GetVariableLocationTree(self.GetCurrentLocation(), child) + for child in self.VariableLocationTree]} + def CTNTestModified(self): + def CTNRequestSave(self): + def ResetUsedLocations(self): + self.UsedLocations = {} + def _AddUsedLocation(self, parent, location): + if not parent.has_key(num): + parent[num] = {"used": False, "children": {}} + self._AddUsedLocation(parent[num]["children"], location) + parent[num]["used"] = True + def AddUsedLocation(self, location): + self._AddUsedLocation(self.UsedLocations, list(location)) + def _CheckLocationConflicts(self, parent, location): + if not parent.has_key(num): + if parent[num]["used"]: + return self._CheckLocationConflicts(parent[num]["children"], location) + elif len(parent[num]["children"]) > 0: + def CheckLocationConflicts(self, location): + return self._CheckLocationConflicts(self.UsedLocations, list(location)) + def CTNGenerate_C(self, buildpath, locations): + @param current_location: Tupple containing confnode IEC location : %I0.0.4.5 => (0,0,4,5) + @param locations: List of complete variables locations \ + [{"IEC_TYPE" : the IEC type (i.e. "INT", "STRING", ...) + "NAME" : name of the variable (generally "__IW0_1_2" style) + "DIR" : direction "Q","I" or "M" + "SIZE" : size "X", "B", "W", "D", "L" + "LOC" : tuple of interger for IEC location (0,1,2,...) + @return: [(C_file_name, CFLAGS),...] , LDFLAGS_TO_APPEND + current_location = self.GetCurrentLocation() + # define a unique name for the generated C file + location_str = "_".join(map(str, current_location)) + code_str = {"location_str": location_str, + for module in _GetModuleChildren(self): + if module["init"] != "": + code_str["init_code"] += " %s\n" % module["init"] + self.ResetUsedLocations() + for location in locations: + loc = location["LOC"][len(current_location):] + while next is not None and i < len(loc): + next = self._GetChildBySomething("IEC_Channel", loc[:i + 1]) + for variable in _GetModuleChildren(group): + if variable["location"] == var_loc and location["DIR"] == LOCATION_DIRS[variable["type"]]: +# if location["DIR"] != LOCATION_DIRS[variable["type"]]: +# raise Exception, "Direction conflict in variable definition" +# if location["IEC_TYPE"] != variable["IEC_type"]: +# raise Exception, "Type conflict in variable definition" + if location["DIR"] == "Q": + if self.CheckLocationConflicts(location["LOC"]): + raise Exception, "BYTE and BIT from the same BYTE can't be used together" + self.AddUsedLocation(location["LOC"]) + vars.append({"location": location["NAME"], + "Type": variable["IEC_type"], + "Retrieve": variable["retrieve"], + "Publish": variable["publish"], + base_types = self.GetCTRoot().GetBaseTypes() + if var["Type"] in base_types: + code_str["var_decl"] += "%s%s beremiz%s;\n"%(prefix, var["Type"], var["location"]) + code_str["var_decl"] += "%s%s *%s = &beremiz%s;\n"%(prefix, var["Type"], var["location"], var["location"]) + if var["Retrieve"] != "": + code_str["retrieve_code"] += " " + var["Retrieve"] % ("*" + var["location"]) + "\n" + if var["Publish"] != "": + code_str["publish_code"] += " " + var["Publish"] % ("*" + var["location"]) + "\n" + Gen_Module_path = os.path.join(buildpath, "Bus_%s.c"%location_str) + module = open(Gen_Module_path,'w') + module.write(BUS_TEXT % code_str) + matiec_flags = '"-I%s"'%os.path.abspath(self.GetCTRoot().GetIECLibPath()) + return [(Gen_Module_path, matiec_flags)],"",True +#------------------------------------------------------------------------------- +# LPC CanFestival ConfNode Class +#------------------------------------------------------------------------------- + "CAN_Baudrate": "125K", + class LPCCanOpenSlave(_SlaveCTN): + XSD = """<?xml version="1.0" encoding="ISO-8859-1" ?> + <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + <xsd:element name="CanFestivalSlaveNode"> + <xsd:attribute name="CAN_Baudrate" type="xsd:string" use="optional" default="%(CAN_Baudrate)s"/> + <xsd:attribute name="NodeId" type="xsd:string" use="optional" default="%(Slave_NodeId)d"/> + <xsd:attribute name="Sync_Align" type="xsd:integer" use="optional" default="0"/> + <xsd:attribute name="Sync_Align_Ratio" use="optional" default="50"> + <xsd:restriction base="xsd:integer"> + <xsd:minInclusive value="1"/> + <xsd:maxInclusive value="99"/> + # TODO change netname when name change + NodeManager.__init__(self) + odfilepath = self.GetSlaveODPath() + if(os.path.isfile(odfilepath)): + self.OpenFileInCurrent(odfilepath) + self.CreateNewNode("SlaveNode", # Name - will be changed at build time + 0x00, # NodeID - will be changed at build time + def GetCanDevice(self): + return str(self.BaseParams.getIEC_Channel()) + class LPCCanOpenMaster(_NodeListCTN): + XSD = """<?xml version="1.0" encoding="ISO-8859-1" ?> + <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + <xsd:element name="CanFestivalNode"> + <xsd:attribute name="CAN_Baudrate" type="xsd:string" use="optional" default="%(CAN_Baudrate)s"/> + <xsd:attribute name="NodeId" type="xsd:string" use="optional" default="%(Master_NodeId)d"/> + <xsd:attribute name="Sync_TPDOs" type="xsd:boolean" use="optional" default="true"/> + def GetCanDevice(self): + return str(self.BaseParams.getIEC_Channel()) + class LPCCanOpen(CanOpenRootClass): + CTNChildrenTypes = [("CanOpenNode",LPCCanOpenMaster, "CanOpen Master"), + ("CanOpenSlave",LPCCanOpenSlave, "CanOpen Slave")] + def GetCanDriver(self): + def LoadChildren(self): + ConfigTreeNode.LoadChildren(self) + if self.GetChildByName("Master") is None: + master = self.CTNAddChild("Master", "CanOpenNode", 0) + master.BaseParams.setEnabled(False) + if self.GetChildByName("Slave") is None: + slave = self.CTNAddChild("Slave", "CanOpenSlave", 1) + slave.BaseParams.setEnabled(False) +#------------------------------------------------------------------------------- +# LPCProjectController Class +#------------------------------------------------------------------------------- +def mycopytree(src, dst): + Copy content of a directory to an other, omit hidden files + @param src: source directory + @param dst: destination directory + for i in os.listdir(src): + if not i.startswith('.') and i != "pous.xml": + srcpath = os.path.join(src,i) + dstpath = os.path.join(dst,i) + if os.path.isdir(srcpath): + if os.path.exists(dstpath): + mycopytree(srcpath, dstpath) + elif os.path.isfile(srcpath): + shutil.copy2(srcpath, dstpath) +[SIMULATION_MODE, TRANSFER_MODE] = range(2) +class LPCProjectController(ProjectController): + {"bitmap" : opjimg("Debug"), + "name" : _("Simulate"), + "tooltip" : _("Simulate PLC"), + "method" : "_Simulate"}, + {"bitmap" : opjimg("Run"), + "tooltip" : _("Start PLC"), + {"bitmap" : opjimg("Stop"), + "tooltip" : _("Stop Running PLC"), + {"bitmap" : opjimg("Build"), + "tooltip" : _("Build project into build folder"), + {"bitmap" : opjimg("Transfer"), + "name" : _("Transfer"), + "tooltip" : _("Transfer PLC"), + "method" : "_Transfer"}, + def __init__(self, frame, logger, buildpath): + self.OrigBuildPath = buildpath + ProjectController.__init__(self, frame, logger) + self.CTNChildrenTypes += [("LPCBus", LPCBus, "LPC bus"), ("CanOpen", LPCCanOpen, "CanOpen bus")] + self.CTNChildrenTypes += [("LPCBus", LPCBus, "LPC bus")] + self.OnlineMode = "OFF" + self.LPCConnector = None + self.CurrentMode = None + self.previous_mode = None + self.SimulationBuildPath = None + self.AbortTransferTimer = None + def ConfNodeLibraryFilePath(self): + if self.OrigBuildPath is not None: + return os.path.join(self.OrigBuildPath, "pous.xml") + return ProjectController.ConfNodeLibraryFilePath(self) + def GetProjectName(self): + return self.Project.getname() + def GetDefaultTargetName(self): + if self.CurrentMode == SIMULATION_MODE: + return ProjectController.GetDefaultTargetName(self) + target = ProjectController.GetTarget(self) + if self.CurrentMode != SIMULATION_MODE: + target.getcontent()["value"].setBuildPath(self.BuildPath) + def _getBuildPath(self): + if self.CurrentMode == SIMULATION_MODE: + if self.SimulationBuildPath is None: + self.SimulationBuildPath = os.path.join(tempfile.mkdtemp(), os.path.basename(self.ProjectPath), "build") + return self.SimulationBuildPath + return ProjectController._getBuildPath(self) + save = self.ProjectTestModified() + self.AppFrame._Refresh(TITLE, FILEMENU) + if self.BuildPath is not None: + mycopytree(self.OrigBuildPath, self.BuildPath) + ProjectController._Build(self) + wx.CallAfter(self.AppFrame.RefreshAll) + def SetProjectName(self, name): + return self.Project.setname(name) + def SetOnlineMode(self, mode, path=None): + if self.OnlineMode != mode.upper(): + self.OnlineMode = mode.upper() + if self.OnlineMode != "OFF": + uri = "LPC://%s/%s" % (self.OnlineMode,path) + self.LPCConnector = connectors.ConnectorFactory(uri, self) + self.logger.write_error(_("Exception while connecting %s!\n")%uri) + self.logger.write_error(traceback.format_exc()) + # Did connection success ? + if self.LPCConnector is None: + self.logger.write_error(_("Connection failed to %s!\n")%uri) + self.LPCConnector = None + def ApplyOnlineMode(self): + if self.CurrentMode != SIMULATION_MODE: + self._connector = self.LPCConnector + # Init with actual PLC status and print it + self.UpdateMethodsFromPLCStatus() + if self.LPCConnector is not None and self.OnlineMode == "APPLICATION": + self.CompareLocalAndRemotePLC() + if self.previous_plcstate is not None: + status = _(self.previous_plcstate) + self.logger.write(_("PLC is %s\n")%status) + #if self.StatusTimer and not self.StatusTimer.IsRunning(): + # # Start the status Timer + # self.StatusTimer.Start(milliseconds=2000, oneShot=False) + if self.previous_plcstate=="Started": + if self.DebugAvailable() and self.GetIECProgramsAndVariables(): + self.logger.write(_("Debug connect matching running PLC\n")) + self.logger.write_warning(_("Debug do not match PLC - stop/transfert/start to re-enable\n")) + elif self.StatusTimer and self.StatusTimer.IsRunning(): + self.StatusTimer.Stop() + if self.CurrentMode == TRANSFER_MODE: + if self.OnlineMode == "BOOTLOADER": + elif self.OnlineMode == "APPLICATION": + self.CurrentMode = None + self.AbortTransferTimer.Stop() + self.AbortTransferTimer = None + self.logger.write(_("PLC transferred successfully\n")) + # Update a PLCOpenEditor Pou variable name + def UpdateProjectVariableName(self, old_name, new_name): + self.Project.updateElementName(old_name, new_name) + def RemoveProjectVariableByAddress(self, address): + self.Project.removeVariableByAddress(address) + def RemoveProjectVariableByFilter(self, leading): + self.Project.removeVariableByFilter(leading) + def LoadProject(self, ProjectPath, BuildPath=None): + Load a project contained in a folder + @param ProjectPath: path of the project folder + if os.path.basename(ProjectPath) == "": + ProjectPath = os.path.dirname(ProjectPath) + # Verify that project contains a PLCOpen program + plc_file = os.path.join(ProjectPath, "plc.xml") + if os.path.isfile(plc_file): + result = self.OpenXMLFile(plc_file) + self.CreateNewProject({"companyName": "", + # Change XSD into class members + self._AddParamsMembers() + # Keep track of the root confnode (i.e. project path) + self.ProjectPath = ProjectPath + self.BuildPath = self._getBuildPath() + if self.OrigBuildPath is not None: + mycopytree(self.OrigBuildPath, self.BuildPath) + # If dir have already be made, and file exist + if os.path.isdir(self.CTNPath()) and os.path.isfile(self.ConfNodeXmlFilePath()): + #Load the confnode.xml file into parameters members + result = self.LoadXMLParams() + #Load and init all the children + if havecanfestival and self.GetChildByName("CanOpen") is None: + canopen = self.CTNAddChild("CanOpen", "CanOpen", 0) + canopen.BaseParams.setEnabled(False) + if self.CTNTestModified(): + if wx.GetApp() is None: + self.RefreshConfNodesBlockLists() + wx.CallAfter(self.RefreshConfNodesBlockLists) + ############# Real PLC object access ############# + def UpdateMethodsFromPLCStatus(self): + # Get PLC state : Running or Stopped + # TODO : use explicit status instead of boolean + if self.OnlineMode == "OFF": + status = "Disconnected" + elif self.OnlineMode == "BOOTLOADER": + if self._connector is not None: + status = self._connector.GetPLCstatus() + status = "Disconnected" + if self.previous_plcstate != status or self.previous_mode != self.CurrentMode: + simulating = self.CurrentMode == SIMULATION_MODE + "Started" : [("_Simulate", False), + "Stopped" : [("_Simulate", False), + "Connected" : [("_Simulate", not simulating), + "Disconnected" :[("_Simulate", not simulating), + self.previous_plcstate = status + self.previous_mode = self.CurrentMode + def Generate_plc_declare_locations(self): + Declare used locations in order to simulatePLC in a black box + return """#include "iec_types_all.h" +#define __LOCATED_VAR(type, name, ...) \ +type *name = &beremiz_##name; +#include "LOCATED_VARIABLES.h" + def Generate_lpc_retain_array_sim(self): + Support for retain array in Simulation + return """/* Support for retain array */ +#define USER_RETAIN_ARRAY_SIZE 2000 +unsigned char readOK = 0; +unsigned int foundIndex = USER_RETAIN_ARRAY_SIZE; +unsigned int retainArray[USER_RETAIN_ARRAY_SIZE][NUM_OF_COLS]; +unsigned int __GetRetainData(unsigned char READ, unsigned int INDEX, unsigned int COLUMN) + if((0<=INDEX) && (INDEX<USER_RETAIN_ARRAY_SIZE) && (0<=COLUMN) && (COLUMN<NUM_OF_COLS)) + return retainArray[INDEX][COLUMN]; +unsigned char __SetRetainData(unsigned char WRITE, unsigned int INDEX, unsigned int WORD1, unsigned int WORD2, unsigned int WORD3) + if((0<=INDEX) && (INDEX<USER_RETAIN_ARRAY_SIZE)) + retainArray[INDEX][0] = WORD1; + retainArray[INDEX][1] = WORD2; + retainArray[INDEX][2] = WORD3; +unsigned char __FindRetainData(unsigned char SEARCH, unsigned int START_IDX, unsigned int END_IDX, unsigned int WORD1, unsigned int WORD2, unsigned int WORD3) + if((SEARCH==1) && (0<=START_IDX) && (START_IDX<USER_RETAIN_ARRAY_SIZE) && (START_IDX<=END_IDX) && (END_IDX<USER_RETAIN_ARRAY_SIZE)) + for(i=START_IDX;i<=END_IDX;i++) + if((retainArray[i][0] == WORD1) && (retainArray[i][1] == WORD2) && (retainArray[i][2] == WORD3)) + foundIndex = USER_RETAIN_ARRAY_SIZE; /* Data not found => return index that is out of array bounds */ +/* Since Beremiz debugger doesn't like pointer-by-reference stuff or global varibles, separate function is a must */ +unsigned char __GetReadStatus(unsigned char dummy) +unsigned int __GetFoundIndex(unsigned char dummy) + Method called by user to Simulate PLC + self.CurrentMode = SIMULATION_MODE + self._connector = connectors.ConnectorFactory(uri, self) + self.logger.write_error(_("Exception while connecting %s!\n")%uri) + self.logger.write_error(traceback.format_exc()) + # Did connection success ? + if self._connector is None: + self.logger.write_error(_("Connection failed to %s!\n")%uri) + buildpath = self._getBuildPath() + # Eventually create build dir + if not os.path.exists(buildpath): + # Generate SoftPLC IEC code + IECGenRes = self._Generate_SoftPLC() + # If IEC code gen fail, bail out. + self.logger.write_error(_("IEC-61131-3 code generation failed !\n")) + # Reset variable and program list that are parsed from + # CSV file generated by IEC2C compiler. + self.ResetIECProgramsAndVariables() + gen_result = self.CTNGenerate_C(buildpath, self.PLCGeneratedLocatedVars) + CTNCFilesAndCFLAGS, CTNLDFLAGS, DoCalls = gen_result[:3] + # if some files have been generated put them in the list with their location + self.LocationCFilesAndCFLAGS = [(self.GetCurrentLocation(), CTNCFilesAndCFLAGS, DoCalls)] + self.LocationCFilesAndCFLAGS = [] + # confnode asks for some LDFLAGS + # LDFLAGS can be either string + if type(CTNLDFLAGS)==type(str()): + self.LDFLAGS=[CTNLDFLAGS] + elif type(CTNLDFLAGS)==type(list()): + self.LDFLAGS=CTNLDFLAGS[:] + # Template based part of C code generation + # files are stacked at the beginning, as files of confnode tree root + for generator, filename, name in [ + (self.Generate_plc_debugger, "plc_debugger.c", "Debugger"), + # init/cleanup/retrieve/publish, run and align code + (self.Generate_plc_common_main,"plc_common_main.c","Common runtime"), + # declare located variables for simulate in a black box + (self.Generate_plc_declare_locations,"plc_declare_locations.c","Declare Locations"), + # declare located variables for simulate in a black box + (self.Generate_lpc_retain_array_sim,"lpc_retain_array_sim.c","Retain Array for Simulation")]: + code_path = os.path.join(buildpath,filename) + open(code_path, "w").write(code) + # Insert this file as first file to be compiled at root confnode + self.LocationCFilesAndCFLAGS[0][1].insert(0,(code_path, self.plcCFLAGS)) + self.logger.write_error(name+_(" generation failed !\n")) + self.logger.write_error(traceback.format_exc()) + # Get simulation builder + builder = self.GetBuilder() + self.logger.write_error(_("Fatal : cannot get builder.\n")) + if not builder.build() : + self.logger.write_error(_("C Build failed.\n")) + self.logger.write_error(_("C Build crashed !\n")) + self.logger.write_error(traceback.format_exc()) + data = builder.GetBinaryCode() + if self._connector.NewPLC(builder.GetBinaryCodeMD5(), data, []): + self.UnsubscribeAllDebugIECVariable() + self.ProgramTransferred() + if self.AppFrame is not None: + self.AppFrame.CloseObsoleteDebugTabs() + self.logger.write(_("Transfer completed successfully.\n")) + self.logger.write_error(_("Transfer failed\n")) + if not self.StatusTimer.IsRunning(): + # Start the status Timer + self.StatusTimer.Start(milliseconds=500, oneShot=False) + def StopSimulation(self): + self.CurrentMode = None + ProjectController._Stop(self) + if self.CurrentMode == SIMULATION_MODE: + def CompareLocalAndRemotePLC(self): + if self.LPCConnector is None: + # We are now connected. Update button status + MD5 = self.GetLastBuildMD5() + # Check remote target PLC correspondance to that md5 + if MD5 is not None and self.LPCConnector.MatchMD5(MD5): + # warns controller that program match + self.ProgramTransferred() + def ResetBuildMD5(self): + builder=self.GetBuilder() + if builder is not None: + builder.ResetBinaryCodeMD5(self.OnlineMode) + def GetLastBuildMD5(self): + builder=self.GetBuilder() + if builder is not None: + return builder.GetBinaryCodeMD5(self.OnlineMode) + if self.CurrentMode is None and self.OnlineMode != "OFF": + self.CurrentMode = TRANSFER_MODE + if ProjectController._Build(self): + ID_ABORTTRANSFERTIMER = wx.NewId() + self.AbortTransferTimer = wx.Timer(self.AppFrame, ID_ABORTTRANSFERTIMER) + self.AppFrame.Bind(wx.EVT_TIMER, self.AbortTransfer, self.AbortTransferTimer) + if self.OnlineMode == "BOOTLOADER": + self.logger.write(_("Resetting PLC\n")) + #self.StatusTimer.Stop() + self.LPCConnector.ResetPLC() + self.AbortTransferTimer.Start(milliseconds=5000, oneShot=True) + self.CurrentMode = None + def BeginTransfer(self): + self.logger.write(_("Start PLC transfer\n")) + self.AbortTransferTimer.Stop() + ProjectController._Transfer(self) + self.AbortTransferTimer.Start(milliseconds=5000, oneShot=True) + def AbortTransfer(self, event): + self.logger.write_warning(_("Timeout waiting PLC to recover\n")) + self.CurrentMode = None + self.AbortTransferTimer.Stop() + self.AbortTransferTimer = None + if self.GetIECProgramsAndVariables(): + self._connector.StartPLC() + self.logger.write(_("Starting PLC\n")) + self.logger.write_error(_("Couldn't start PLC !\n")) + self.UpdateMethodsFromPLCStatus() +#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------- +class LPCBeremiz(Beremiz): + def _init_coll_FileMenu_Items(self, parent): + AppendMenu(parent, help='', id=wx.ID_SAVE, + kind=wx.ITEM_NORMAL, text=_(u'Save\tCTRL+S')) + AppendMenu(parent, help='', id=wx.ID_CLOSE, + kind=wx.ITEM_NORMAL, text=_(u'Close Tab\tCTRL+W')) + parent.AppendSeparator() + AppendMenu(parent, help='', id=wx.ID_PAGE_SETUP, + kind=wx.ITEM_NORMAL, text=_(u'Page Setup')) + AppendMenu(parent, help='', id=wx.ID_PREVIEW, + kind=wx.ITEM_NORMAL, text=_(u'Preview')) + AppendMenu(parent, help='', id=wx.ID_PRINT, + kind=wx.ITEM_NORMAL, text=_(u'Print')) + parent.AppendSeparator() + AppendMenu(parent, help='', id=wx.ID_PROPERTIES, + kind=wx.ITEM_NORMAL, text=_(u'Properties')) + parent.AppendSeparator() + AppendMenu(parent, help='', id=wx.ID_EXIT, + kind=wx.ITEM_NORMAL, text=_(u'Quit\tCTRL+Q')) + self.Bind(wx.EVT_MENU, self.OnSaveProjectMenu, id=wx.ID_SAVE) + self.Bind(wx.EVT_MENU, self.OnCloseTabMenu, id=wx.ID_CLOSE) + self.Bind(wx.EVT_MENU, self.OnPageSetupMenu, id=wx.ID_PAGE_SETUP) + self.Bind(wx.EVT_MENU, self.OnPreviewMenu, id=wx.ID_PREVIEW) + self.Bind(wx.EVT_MENU, self.OnPrintMenu, id=wx.ID_PRINT) + self.Bind(wx.EVT_MENU, self.OnPropertiesMenu, id=wx.ID_PROPERTIES) + self.Bind(wx.EVT_MENU, self.OnQuitMenu, id=wx.ID_EXIT) + self.AddToMenuToolBar([(wx.ID_SAVE, "save.png", _(u'Save'), None), + (wx.ID_PRINT, "print.png", _(u'Print'), None)]) + def _init_ctrls(self, prnt): + IDEFrame._init_ctrls(self, prnt) + self.Bind(wx.EVT_MENU, self.OnOpenWidgetInspector, id=ID_BEREMIZINSPECTOR) + accel = wx.AcceleratorTable([wx.AcceleratorEntry(wx.ACCEL_CTRL|wx.ACCEL_ALT, ord('I'), ID_BEREMIZINSPECTOR)]) + self.SetAcceleratorTable(accel) + self.PLCConfig = wx.ScrolledWindow(id=ID_BEREMIZPLCCONFIG, + name='PLCConfig', parent=self.LeftNoteBook, pos=wx.Point(0, 0), + size=wx.Size(-1, -1), style=wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER|wx.HSCROLL|wx.VSCROLL) + self.PLCConfig.SetBackgroundColour(wx.WHITE) + self.PLCConfig.Bind(wx.EVT_LEFT_DOWN, self.OnPanelLeftDown) + self.PLCConfig.Bind(wx.EVT_SIZE, self.OnMoveWindow) + self.LeftNoteBook.InsertPage(0, self.PLCConfig, _("Topology"), True) + self.LogConsole = wx.TextCtrl(id=ID_BEREMIZLOGCONSOLE, value='', + name='LogConsole', parent=self.BottomNoteBook, pos=wx.Point(0, 0), + size=wx.Size(0, 0), style=wx.TE_MULTILINE|wx.TE_RICH2) + self.LogConsole.Bind(wx.EVT_LEFT_DCLICK, self.OnLogConsoleDClick) + self.BottomNoteBook.AddPage(self.LogConsole, _("Log Console")) + self._init_beremiz_sizers() + def OnCloseFrame(self, event): + if self.CheckSaveBeforeClosing(_("Close Application")): + self.CTR.ResetAppFrame(lpcberemiz_cmd.Log) + if self.CTR.OnlineMode == 0: + self.CTR._connector = None + self.CTR.KillDebugThread() + self.KillLocalRuntime() + lpcberemiz_cmd.Log.write("Closed\n") + def ShowProperties(self): + old_values = self.Controler.GetProjectProperties() + dialog = ProjectDialog(self ,False) + dialog.SetValues(old_values) + if dialog.ShowModal() == wx.ID_OK: + new_values = dialog.GetValues() + new_values["creationDateTime"] = old_values["creationDateTime"] + if new_values != old_values: + self.Controler.SetProjectProperties(None, new_values) + self._Refresh(TITLE, EDITORTOOLBAR, FILEMENU, EDITMENU, DISPLAYMENU, + PROJECTTREE, POUINSTANCEVARIABLESPANEL, SCALING) + def RefreshFileMenu(self): + MenuToolBar = self.Panes["MenuToolBar"] + if self.CTR is not None: + selected = self.TabsOpened.GetSelection() + graphic_viewer = isinstance(self.TabsOpened.GetPage(selected), Viewer) + if self.TabsOpened.GetPageCount() > 0: + self.FileMenu.Enable(wx.ID_CLOSE, True) + self.FileMenu.Enable(wx.ID_PREVIEW, True) + self.FileMenu.Enable(wx.ID_PRINT, True) + MenuToolBar.EnableTool(wx.ID_PRINT, True) + self.FileMenu.Enable(wx.ID_PREVIEW, False) + self.FileMenu.Enable(wx.ID_PRINT, False) + MenuToolBar.EnableTool(wx.ID_PRINT, False) + self.FileMenu.Enable(wx.ID_CLOSE, False) + self.FileMenu.Enable(wx.ID_PREVIEW, False) + self.FileMenu.Enable(wx.ID_PRINT, False) + MenuToolBar.EnableTool(wx.ID_PRINT, False) + self.FileMenu.Enable(wx.ID_PAGE_SETUP, True) + project_modified = self.CTR.ProjectTestModified() + self.FileMenu.Enable(wx.ID_SAVE, project_modified) + MenuToolBar.EnableTool(wx.ID_SAVE, project_modified) + self.FileMenu.Enable(wx.ID_PROPERTIES, True) + self.FileMenu.Enable(wx.ID_CLOSE, False) + self.FileMenu.Enable(wx.ID_PAGE_SETUP, False) + self.FileMenu.Enable(wx.ID_PREVIEW, False) + self.FileMenu.Enable(wx.ID_PRINT, False) + MenuToolBar.EnableTool(wx.ID_PRINT, False) + self.FileMenu.Enable(wx.ID_SAVE, False) + MenuToolBar.EnableTool(wx.ID_SAVE, False) + self.FileMenu.Enable(wx.ID_PROPERTIES, False) + def RefreshPLCParams(self): + self.ClearSizer(self.PLCParamsSizer) + if self.CTR is not None: + plcwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) + if self.CTR.CTNTestModified(): + bkgdclr = CHANGED_TITLE_COLOUR + if self.CTR not in self.ConfNodeInfos: + self.ConfNodeInfos[self.CTR] = {"right_visible" : False} + plcwindow.SetBackgroundColour(TITLE_COLOUR) + plcwindow.Bind(wx.EVT_LEFT_DOWN, self.OnPanelLeftDown) + self.PLCParamsSizer.AddWindow(plcwindow, 0, border=0, flag=wx.GROW) + plcwindowsizer = wx.BoxSizer(wx.HORIZONTAL) + plcwindow.SetSizer(plcwindowsizer) + st = wx.StaticText(plcwindow, -1) + st.SetFont(wx.Font(faces["size"], wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"])) + st.SetLabel(self.CTR.GetProjectName()) + plcwindowsizer.AddWindow(st, 0, border=5, flag=wx.ALL|wx.ALIGN_CENTER) + plcwindowmainsizer = wx.BoxSizer(wx.VERTICAL) + plcwindowsizer.AddSizer(plcwindowmainsizer, 0, border=5, flag=wx.ALL) + plcwindowbuttonsizer = wx.BoxSizer(wx.HORIZONTAL) + plcwindowmainsizer.AddSizer(plcwindowbuttonsizer, 0, border=0, flag=wx.ALIGN_CENTER) + msizer = self.GenerateMethodButtonSizer(self.CTR, plcwindow, not self.ConfNodeInfos[self.CTR]["right_visible"]) + plcwindowbuttonsizer.AddSizer(msizer, 0, border=0, flag=wx.GROW) + self.PLCConfigMainSizer.Layout() + self.RefreshScrollBars() + def GenerateTreeBranch(self, confnode): + leftwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) + if confnode.CTNTestModified(): + bkgdclr=CHANGED_WINDOW_COLOUR + leftwindow.SetBackgroundColour(bkgdclr) + if confnode not in self.ConfNodeInfos: + self.ConfNodeInfos[confnode] = {"expanded" : False, "left_visible" : False, "right_visible" : False} + self.ConfNodeInfos[confnode]["children"] = confnode.IECSortedChildren() + confnode_infos = confnode.GetVariableLocationTree() + confnode_locations = [] + if len(self.ConfNodeInfos[confnode]["children"]) == 0: + confnode_locations = confnode_infos["children"] + if not self.ConfNodeInfos[confnode].has_key("locations_infos"): + self.ConfNodeInfos[confnode]["locations_infos"] = {"root": {"expanded" : False}} + self.ConfNodeInfos[confnode]["locations_infos"]["root"]["left"] = None + self.ConfNodeInfos[confnode]["locations_infos"]["root"]["right"] = None + self.ConfNodeInfos[confnode]["locations_infos"]["root"]["children"] = [] + self.ConfNodeTreeSizer.AddWindow(leftwindow, 0, border=0, flag=wx.GROW) + leftwindowvsizer = wx.BoxSizer(wx.VERTICAL) + leftwindow.SetSizer(leftwindowvsizer) + leftwindowsizer = wx.BoxSizer(wx.HORIZONTAL) + leftwindowvsizer.AddSizer(leftwindowsizer, 0, border=0, flag=0) + self.GenerateEnableButton(leftwindow, leftwindowsizer, confnode) + st = wx.StaticText(leftwindow, -1) + st.SetFont(wx.Font(faces["size"], wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"])) + st.SetLabel(confnode.GetFullIEC_Channel()) + leftwindowsizer.AddWindow(st, 0, border=5, flag=wx.RIGHT) + expandbutton_id = wx.NewId() + expandbutton = wx.lib.buttons.GenBitmapToggleButton(id=expandbutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'plus.png')), + name='ExpandButton', parent=leftwindow, pos=wx.Point(0, 0), + size=wx.Size(13, 13), style=wx.NO_BORDER) + expandbutton.labelDelta = 0 + expandbutton.SetBezelWidth(0) + expandbutton.SetUseFocusIndicator(False) + expandbutton.SetBitmapSelected(wx.Bitmap(Bpath( 'images', 'minus.png'))) + if len(self.ConfNodeInfos[confnode]["children"]) > 0: + expandbutton.SetToggle(self.ConfNodeInfos[confnode]["expanded"]) + def togglebutton(event): + if expandbutton.GetToggle(): + self.ExpandConfNode(confnode) + self.CollapseConfNode(confnode) + self.ConfNodeInfos[confnode]["expanded"] = expandbutton.GetToggle() + self.PLCConfigMainSizer.Layout() + self.RefreshScrollBars() + expandbutton.Bind(wx.EVT_BUTTON, togglebutton, id=expandbutton_id) + elif len(confnode_locations) > 0: + locations_infos = self.ConfNodeInfos[confnode]["locations_infos"] + expandbutton.SetToggle(locations_infos["root"]["expanded"]) + def togglebutton(event): + if expandbutton.GetToggle(): + self.ExpandLocation(locations_infos, "root") + self.CollapseLocation(locations_infos, "root") + self.ConfNodeInfos[confnode]["expanded"] = expandbutton.GetToggle() + locations_infos["root"]["expanded"] = expandbutton.GetToggle() + self.PLCConfigMainSizer.Layout() + self.RefreshScrollBars() + expandbutton.Bind(wx.EVT_BUTTON, togglebutton, id=expandbutton_id) + expandbutton.Enable(False) + leftwindowsizer.AddWindow(expandbutton, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) + sb = wx.StaticBitmap(leftwindow, -1) + icon = confnode_infos.get("icon", None) + icon_bitmap = self.LocationImageList.GetBitmap(self.LocationImageDict[confnode_infos["type"]]) + icon_bitmap = wx.Bitmap(icon) + sb.SetBitmap(icon_bitmap) + leftwindowsizer.AddWindow(sb, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) + st = wx.StaticText(leftwindow, st_id, size=wx.DefaultSize, style=wx.NO_BORDER) + st.SetFont(wx.Font(faces["size"] * 0.75, wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"])) + st.SetLabel(confnode.MandatoryParams[1].getName()) + leftwindowsizer.AddWindow(st, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) + rightwindow = self.GenerateParamsPanel(confnode, bkgdclr) + self.ConfNodeTreeSizer.AddWindow(rightwindow, 0, border=0, flag=wx.GROW) + self.ConfNodeInfos[confnode]["left"] = leftwindow + self.ConfNodeInfos[confnode]["right"] = rightwindow + for child in self.ConfNodeInfos[confnode]["children"]: + self.GenerateTreeBranch(child) + if not self.ConfNodeInfos[child]["expanded"]: + self.CollapseConfNode(child) + if len(confnode_locations) > 0: + locations_infos = self.ConfNodeInfos[confnode]["locations_infos"] + treectrl = wx.TreeCtrl(self.PLCConfig, -1, size=wx.DefaultSize, + style=wx.TR_HAS_BUTTONS|wx.TR_SINGLE|wx.NO_BORDER|wx.TR_HIDE_ROOT|wx.TR_NO_LINES|wx.TR_LINES_AT_ROOT) + treectrl.SetImageList(self.LocationImageList) + treectrl.Bind(wx.EVT_TREE_BEGIN_DRAG, self.GenerateLocationBeginDragFunction(locations_infos)) + treectrl.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.GenerateLocationExpandCollapseFunction(locations_infos, True)) + treectrl.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.GenerateLocationExpandCollapseFunction(locations_infos, False)) + self.ConfNodeTreeSizer.AddWindow(treectrl, 0, border=0, flag=0) + rightwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) + rightwindow.SetBackgroundColour(wx.WHITE) + self.ConfNodeTreeSizer.AddWindow(rightwindow, 0, border=0, flag=wx.GROW) + locations_infos["root"]["left"] = treectrl + locations_infos["root"]["right"] = rightwindow + for location in confnode_locations: + locations_infos["root"]["children"].append("root.%s" % location["name"]) + self.GenerateLocationTreeBranch(treectrl, treectrl.GetRootItem(), locations_infos, "root", location) + if locations_infos["root"]["expanded"]: + self.ExpandLocation(locations_infos, "root") + def __init__(self, port): + self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.socket.connect(('localhost', port)) + idx = self.Buffer.find("\n") + self.Buffer += self.socket.recv(2048) + idx = self.Buffer.find("\n") + line = self.Buffer[:idx+1] + self.Buffer = self.Buffer[idx+1:] + """ Base class for file like objects to facilitate StdOut for the Shell.""" + def write(self, s, style = None): + self.socket.send(s.encode('utf8')) + def writeyield(self, s): + def write_warning(self, s): + def write_error(self, s): +if __name__ == '__main__': + from threading import Thread, Timer, Semaphore + wx_eval_lock = Semaphore(0) + def wx_evaluator(callable, *args, **kwargs): + eval_res=callable(*args,**kwargs) + def evaluator(callable, *args, **kwargs): + wx.CallAfter(wx_evaluator,callable,*args,**kwargs) + # Command log for debug, for viewing from wxInspector + __builtins__.cmdlog = [] + class LPCBeremiz_Cmd(cmd.Cmd): + def __init__(self, CTR, Log): + cmd.Cmd.__init__(self, stdin=Log, stdout=Log) + self.use_rawinput = False + def RestartTimer(self): + if self.RefreshTimer is not None: + self.RefreshTimer.cancel() + self.RefreshTimer = Timer(0.1, wx.CallAfter, args = [self.Refresh]) + self.RefreshTimer.start() + def do_EOF(self, line): + self.CTR.SetAppFrame(frame, frame.Log) + frame._Refresh(TITLE, POUINSTANCEVARIABLESPANEL, FILEMENU, EDITMENU) + self.CTR.ResetAppFrame(self.Log) + def SetProjectProperties(self, projectname, productname, productversion, companyname): + properties = self.CTR.GetProjectProperties() + new_properties = properties.copy() + new_properties["projectName"] = projectname + new_properties["productName"] = productname + new_properties["productVersion"] = productversion + new_properties["companyName"] = companyname + if new_properties != properties: + self.CTR.SetProjectProperties(properties=new_properties, buffer=False) + def SetOnlineMode(self, mode, path=None): + self.CTR.SetOnlineMode(mode, path) + def AddBus(self, iec_channel, name, icon=None): + for child in self.CTR.IterChildren(): + if child.BaseParams.getName() == name: + return "Error: A bus named %s already exists\n" % name + elif child.BaseParams.getIEC_Channel() == iec_channel: + return "Error: A bus with IEC_channel %d already exists\n" % iec_channel + bus = self.CTR.CTNAddChild(name, "LPCBus", iec_channel) + return "Error: Unable to create bus\n" + def RenameBus(self, iec_channel, name): + bus = self.CTR.GetChildByIECLocation((iec_channel,)) + return "Error: No bus found\n" + for child in self.CTR.IterChildren(): + if child != bus and child.BaseParams.getName() == name: + return "Error: A bus named %s already exists\n" % name + bus.BaseParams.setName(name) + def ChangeBusIECChannel(self, old_iec_channel, new_iec_channel): + bus = self.CTR.GetChildByIECLocation((old_iec_channel,)) + return "Error: No bus found\n" + for child in self.CTR.IterChildren(): + if child != bus and child.BaseParams.getIEC_Channel() == new_iec_channel: + return "Error: A bus with IEC_channel %d already exists\n" % new_iec_channel + if wx.GetApp() is None: + self.CTR.UpdateProjectVariableLocation(str(old_iec_channel), + self.CTR.UpdateProjectVariableLocation( + bus.BaseParams.setIEC_Channel(new_iec_channel) + def RemoveBus(self, iec_channel): + bus = self.CTR.GetChildByIECLocation((iec_channel,)) + return "Error: No bus found\n" + self.CTR.RemoveProjectVariableByFilter(str(iec_channel)) + self.CTR.Children["LPCBus"].remove(bus) + def AddModule(self, parent, iec_channel, name, icode, icon=None): + module = self.CTR.GetChildByIECLocation(parent) + return "Error: No parent found\n" + for child in _GetModuleChildren(module): + if child["name"] == name: + return "Error: A module named %s already exists\n" % name + elif child["IEC_Channel"] == iec_channel: + return "Error: A module with IEC_channel %d already exists\n" % iec_channel + _GetLastModuleGroup(module).append({"name": name, + "type": LOCATION_MODULE, + "IEC_Channel": iec_channel, + def RenameModule(self, iec_location, name): + module = self.CTR.GetChildByIECLocation(iec_location) + return "Error: No module found\n" + parent = self.CTR.GetChildByIECLocation(iec_location[:-1]) + return "Error: No module found\n" + if module["name"] != name: + for child in _GetModuleChildren(parent): + if child["name"] == name: + return "Error: A module named %s already exists\n" % name + def ChangeModuleIECChannel(self, old_iec_location, new_iec_channel): + module = self.CTR.GetChildByIECLocation(old_iec_location) + return "Error: No module found\n" + parent = self.CTR.GetChildByIECLocation(old_iec_location[:-1]) + return "Error: No module found\n" + if module["IEC_Channel"] != new_iec_channel: + for child in _GetModuleChildren(parent): + if child["IEC_Channel"] == new_iec_channel: + return "Error: A module with IEC_channel %d already exists\n" % new_iec_channel + self.CTR.UpdateProjectVariableLocation(".".join(map(str, old_iec_location)), ".".join(map(str, old_iec_location[:1] + (new_iec_channel,)))) + module["IEC_Channel"] = new_iec_channel + def ChangeModuleInitCode(self, iec_location, icode): + module = self.CTR.GetChildByIECLocation(iec_location) + return "Error: No module found\n" + def RemoveModule(self, parent, iec_channel): + module = self.CTR.GetChildByIECLocation(parent) + return "Error: No parent found\n" + child = _GetModuleBySomething(module, "IEC_Channel", (iec_channel,)) + return "Error: No module found\n" + self.CTR.RemoveProjectVariableByFilter(".".join(map(str, parent + (iec_channel,)))) + _RemoveModuleChild(module, child) + def StartGroup(self, parent, name, icon=None): + module = self.CTR.GetChildByIECLocation(parent) + return "Error: No parent found\n" + for child in module["children"]: + if child["type"] == LOCATION_GROUP and child["name"] == name: + return "Error: A group named %s already exists\n" % name + module["children"].append({"name": name, + "type": LOCATION_GROUP, + def AddVariable(self, parent, location, name, direction, type, rcode, pcode, description=""): + module = self.CTR.GetChildByIECLocation(parent) + return "Error: No parent found\n" + for child in _GetModuleChildren(module): + if child["name"] == name: + return "Error: A variable named %s already exists\n" % name + if child["location"] == location and child["type"] == LOCATION_TYPES[direction]: + return "Error: A variable with location %s already exists\n" % ".".join(map(str, location)) + _GetLastModuleGroup(module).append({"name": name, + "type": LOCATION_TYPES[direction], + "description": description, + def ChangeVariableParams(self, parent, location, new_name, new_direction, new_type, new_rcode, new_pcode, new_description=None): + module = self.CTR.GetChildByIECLocation(parent) + return "Error: No parent found\n" + for child in _GetModuleChildren(module): + if child["location"] == location and child["type"] == LOCATION_TYPES[new_direction]: + elif child["name"] == new_name: + return "Error: A variable named %s already exists\n" % new_name + return "Error: No variable found\n" + if variable["name"] != new_name: + self.CTR.UpdateProjectVariableName(variable["name"], new_name) + variable["name"] = new_name + variable["type"] = LOCATION_TYPES[new_direction] + variable["IEC_type"] = new_type + variable["retrieve"] = new_rcode + variable["publish"] = new_pcode + if new_description is not None: + variable["description"] = new_description + def RemoveVariable(self, parent, location, direction): + module = self.CTR.GetChildByIECLocation(parent) + return "Error: No parent found\n" + child = _GetModuleVariable(module, location, direction) + return "Error: No variable found\n" + size = LOCATION_SIZES[self.CTR.GetBaseType(child["IEC_type"])] + address = "%" + LOCATION_DIRS[child["type"]] + size + ".".join(map(str, parent + location)) + self.CTR.RemoveProjectVariableByAddress(address) + _RemoveModuleChild(module, child) + return tuple(map(int, loc.split("."))) + def GetCmdFunction(function, arg_types, opt=0): + arg_number = len(arg_types) + def CmdFunction(self, line): + args_toks = line.split('"') + if len(args_toks) % 2 == 0: + self.Log.write("Error: Invalid command\n") + for num, arg in enumerate(args_toks): + args.extend(stripped.split(" ")) + if opt == 0 and len(args) != arg_number: + elif len(args) > arg_number: + elif len(args) < arg_number - opt: + number = arg_number - opt + self.Log.write("Error: No argument%s expected\n" % extra) + self.Log.write("Error: 1 argument%s expected\n" % extra) + self.Log.write("Error: %d arguments%s expected\n" % (number, extra)) + for num, arg in enumerate(args): + args[num] = arg_types[num](arg) + self.Log.write("Error: Invalid value for argument %d\n" % (num + 1)) + func = getattr(self, function) + res = evaluator(func,*args) + cmdlog.append((function,line,res)) + if len(cmdlog) > 100: #prevent debug log to grow too much + if isinstance(res, (StringType, UnicodeType)): + def CmdThreadProc(CTR, Log): + for function, (arg_types, opt) in {"Exit": ([], 0), + "SetProjectProperties": ([str, str, str, str], 0), + "SetOnlineMode": ([str, str], 1), + "AddBus": ([int, str, str], 1), + "RenameBus": ([int, str], 0), + "ChangeBusIECChannel": ([int, int], 0), + "RemoveBus": ([int], 0), + "AddModule": ([location, int, str, str, str], 1), + "RenameModule": ([location, str], 0), + "ChangeModuleIECChannel": ([location, int], 0), + "ChangeModuleInitCode": ([location, str], 0), + "RemoveModule": ([location, int], 0), + "StartGroup": ([location, str, str], 1), + "AddVariable": ([location, location, str, str, str, str, str, str], 1), + "ChangeVariableParams": ([location, location, str, str, str, str, str, str], 1), + "RemoveVariable": ([location, location], 0)}.iteritems(): + setattr(LPCBeremiz_Cmd, "do_%s" % function, GetCmdFunction(function, arg_types, opt)) + lpcberemiz_cmd = LPCBeremiz_Cmd(CTR, Log) + lpcberemiz_cmd.cmdloop() + Log = StdoutPseudoFile(port) + CTR = LPCProjectController(None, Log, buildpath) + if projectOpen is not None and os.path.isdir(projectOpen): + result = CTR.LoadProject(projectOpen) + Log.write("Error: Invalid project directory", result) + Log.write("Error: No such file or directory") + cmd_thread=Thread(target=CmdThreadProc, args=[CTR, Log]) + # Install a exception handle for bug reports + AddExceptHook(os.getcwd(),__version__) + frame = LPCBeremiz(None, ctr=CTR, debug=True) --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/LPCconnector/LPCAppObject.py Sun May 20 11:29:35 2012 +0200
@@ -0,0 +1,120 @@
+#This file is part of Beremiz, a Integrated Development Environment for +#programming IEC 61131-3 automates supporting plcopen standard and CanFestival. +#Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD +#See COPYING file for copyrights details. +#This library is free software; you can redistribute it and/or +#modify it under the terms of the GNU General Public +#License as published by the Free Software Foundation; either +#version 2.1 of the License, or (at your option) any later version. +#This library is distributed in the hope that it will be useful, +#but WITHOUT ANY WARRANTY; without even the implied warranty of +#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +#General Public License for more details. +#You should have received a copy of the GNU General Public +#License along with this library; if not, write to the Free Software +#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +from LPCAppProto import * +from targets.typemapping import SameEndianessTypeTranslator as TypeTranslator +class LPCAppObject(LPCObject): + def connect(self,comport): + self.SerialConnection = LPCAppProto(comport,#number + def StartPLC(self, debug=False): + self.HandleSerialTransaction(STARTTransaction()) + self.HandleSerialTransaction(STOPTransaction()) + self.HandleSerialTransaction(RESETTransaction()) + def GetPLCstatus(self): + self.HandleSerialTransaction(GET_PLCIDTransaction()) + def MatchMD5(self, MD5): + data = self.HandleSerialTransaction(GET_PLCIDTransaction()) + return data[:32] == MD5[:32] + def SetTraceVariablesList(self, idxs): + Call ctype imported function to append + these indexes to registred variables in PLC debugger + # keep a copy of requested idx + for idx,iectype,force in idxs: + idxstr = ctypes.string_at( + ctypes.c_uint32(idx)),4) + c_type,unpack_func, pack_func = TypeTranslator.get(iectype, (None,None,None)) + forced_type_size = ctypes.sizeof(c_type) + forced_type_size_str = chr(forced_type_size) + forcestr = ctypes.string_at( + pack_func(c_type,force)), + buff += idxstr + forced_type_size_str + forcestr + buff += idxstr + chr(0) + self.HandleSerialTransaction(SET_TRACE_VARIABLETransaction(buff)) + def GetTraceVariables(self): + Return a list of variables, corresponding to the list of required idx + strbuf = self.HandleSerialTransaction( + GET_TRACE_VARIABLETransaction()) + if strbuf is not None and len(strbuf) > 4 and self.PLCStatus == "Started": + ctypes.c_char_p(strbuf[:4]), + ctypes.POINTER(ctypes.c_int)).contents + ctypes.c_char_p(strbuf[4:]), + for idx, iectype, forced in self._Idxs: + cursor = ctypes.c_void_p(buff.value + offset) + c_type,unpack_func, pack_func = TypeTranslator.get(iectype, (None,None,None)) + if c_type is not None and offset < size: + res.append(unpack_func(ctypes.cast(cursor, + ctypes.POINTER(c_type)).contents)) + offset += ctypes.sizeof(c_type) + #PLCprint("Debug error - " + iectype + " not supported !") + #PLCprint("Debug error - buffer too small !") + if offset and offset == size: + return self.PLCStatus, tick.value, res + #PLCprint("Debug error - wrong buffer unpack !") + return self.PLCStatus, None, [] --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/LPCconnector/LPCAppProto.py Sun May 20 11:29:35 2012 +0200
@@ -0,0 +1,121 @@
+LPC_STATUS={0xaa : "Started", +class LPCAppProto(LPCProto): + def HandleTransaction(self, transaction): + self.TransactionLock.acquire() + transaction.SetPseudoFile(self.serialPort) + # send command, wait ack (timeout) + transaction.SendCommand() + current_plc_status = transaction.GetCommandAck() + if current_plc_status is not None: + res = transaction.ExchangeData() + raise LPCProtoError("controller did not answer as expected") + raise LPCProtoError("application mode transaction error : "+str(e)) + self.TransactionLock.release() + return LPC_STATUS.get(current_plc_status,"Broken"), res +class LPCAppTransaction: + def __init__(self, command, optdata = ""): + def SetPseudoFile(self, pseudofile): + self.pseudofile = pseudofile + self.pseudofile.write(chr(self.Command)) + def GetCommandAck(self): + res = self.pseudofile.read(2) + comm_status, current_plc_status = map(ord, res) + raise LPCProtoError("LPC transaction error - controller did not ack order") + # LPC returns command itself as an ack for command + if(comm_status == self.Command): + return current_plc_status + length = len(self.OptData) + # transform length into a byte string + # we presuppose endianess of LPC same as PC + lengthstr = ctypes.string_at(ctypes.pointer(ctypes.c_int(length)),4) + buffer = lengthstr + self.OptData + return self.pseudofile.write(buffer) + lengthstr = self.pseudofile.read(4) + # transform a byte string into length + length = ctypes.cast(ctypes.c_char_p(lengthstr), ctypes.POINTER(ctypes.c_int)).contents.value + return self.pseudofile.read(length) + def ExchangeData(self): +class IDLETransaction(LPCAppTransaction): + LPCAppTransaction.__init__(self, 0x07) + ExchangeData = LPCAppTransaction.GetData +class STARTTransaction(LPCAppTransaction): + LPCAppTransaction.__init__(self, 0x01) +class STOPTransaction(LPCAppTransaction): + LPCAppTransaction.__init__(self, 0x02) +class RESETTransaction(LPCAppTransaction): + LPCAppTransaction.__init__(self, 0x03) +class SET_TRACE_VARIABLETransaction(LPCAppTransaction): + def __init__(self, data): + LPCAppTransaction.__init__(self, 0x04, data) + ExchangeData = LPCAppTransaction.SendData +class GET_TRACE_VARIABLETransaction(LPCAppTransaction): + LPCAppTransaction.__init__(self, 0x05) + ExchangeData = LPCAppTransaction.GetData +class GET_PLCIDTransaction(LPCAppTransaction): + LPCAppTransaction.__init__(self, 0x07) + ExchangeData = LPCAppTransaction.GetData +if __name__ == "__main__": + __builtins__.BMZ_DBG = True + TestConnection = LPCAppProto(6,115200,2) +# TestConnection.HandleTransaction(GET_PLCIDTransaction()) + TestConnection.HandleTransaction(STARTTransaction()) +# TestConnection.HandleTransaction(SET_TRACE_VARIABLETransaction( +# "\x03\x00\x00\x00"*200)) +# TestConnection.HandleTransaction(STARTTransaction()) + TestConnection.HandleTransaction(SET_TRACE_VARIABLETransaction( + #status,res = TestConnection.HandleTransaction(GET_TRACE_VARIABLETransaction()) + #print "GOT : ", map(hex, map(ord, res)) + #TestConnection.HandleTransaction(STOPTransaction()) --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/LPCconnector/LPCBootObject.py Sun May 20 11:29:35 2012 +0200
@@ -0,0 +1,59 @@
+#This file is part of Beremiz, a Integrated Development Environment for +#programming IEC 61131-3 automates supporting plcopen standard and CanFestival. +#Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD +#See COPYING file for copyrights details. +#This library is free software; you can redistribute it and/or +#modify it under the terms of the GNU General Public +#License as published by the Free Software Foundation; either +#version 2.1 of the License, or (at your option) any later version. +#This library is distributed in the hope that it will be useful, +#but WITHOUT ANY WARRANTY; without even the implied warranty of +#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +#General Public License for more details. +#You should have received a copy of the GNU General Public +#License along with this library; if not, write to the Free Software +#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +from LPCBootProto import * +class LPCBootObject(LPCObject): + def __init__(self, confnodesroot, comportstr): + LPCObject.__init__(self, confnodesroot, comportstr) + self.successfully_transfered = False + def connect(self,comport): + self.SerialConnection = LPCBootProto(comport,#number + self.HandleSerialTransaction(KEEPBOOTINGTransaction()) + self.PLCStatus = "Stopped" + def StartPLC(self, debug=False): + self.HandleSerialTransaction(STARTTransaction()) + def NewPLC(self, md5sum, data, extrafiles): + self.successfully_transfered = self.HandleSerialTransaction(LOADTransaction(data, self.PLCprint)) + return self.successfully_transfered + def MatchMD5(self, MD5): + res = self.HandleSerialTransaction(CHECKMD5Transaction(MD5)) + return "".join(res).find('FAILED') == -1 + def SetTraceVariablesList(self, idxs): + def GetTraceVariables(self): + return self.PLCStatus, None, None --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/LPCconnector/LPCBootProto.py Sun May 20 11:29:35 2012 +0200
@@ -0,0 +1,69 @@
+class LPCBootProto(LPCProto): + def HandleTransaction(self, transaction): + self.TransactionLock.acquire() + transaction.SetPseudoFile(self.serialPort) + res = transaction.ExchangeData() + self.TransactionLock.release() +class LPCBootTransaction: + def __init__(self, optdata = ""): + def SetPseudoFile(self, pseudofile): + self.pseudofile = pseudofile + def ExchangeData(self): + self.pseudofile.write(self.OptData) + return map(lambda x:self.pseudofile.readline(), xrange(self.expectedlines)) +class KEEPBOOTINGTransaction(LPCBootTransaction): + LPCBootTransaction.__init__(self, "md5\n") +class STARTTransaction(LPCBootTransaction): + LPCBootTransaction.__init__(self, "go\n") +class CHECKMD5Transaction(LPCBootTransaction): + def __init__(self, md5ref): + LPCBootTransaction.__init__(self, md5ref+"md5\n") +class LOADTransaction(LPCBootTransaction): + def __init__(self, data, PLCprint): + self.PLCprint = PLCprint + LPCBootTransaction.__init__(self, data) + def ExchangeData(self): + #file("fw.bin","w").write(self.OptData) + loptdata = len(self.OptData) + #self.PLCprint("%dkB:" % (loptdata/1024)) + res = self.pseudofile.write(data[:loptdata/100]) + self.PLCprint("%d%%" % count) +if __name__ == "__main__": + __builtins__.BMZ_DBG = True + TestConnection = LPCBootProto(2,115200,1200) + mystr=file("fw.bin").read() + TestConnection.HandleTransaction(LOADTransaction(mystr, mylog)) --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/LPCconnector/LPCObject.py Sun May 20 11:29:35 2012 +0200
@@ -0,0 +1,78 @@
+#This file is part of Beremiz, a Integrated Development Environment for +#programming IEC 61131-3 automates supporting plcopen standard and CanFestival. +#Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD +#See COPYING file for copyrights details. +#This library is free software; you can redistribute it and/or +#modify it under the terms of the GNU General Public +#License as published by the Free Software Foundation; either +#version 2.1 of the License, or (at your option) any later version. +#This library is distributed in the hope that it will be useful, +#but WITHOUT ANY WARRANTY; without even the implied warranty of +#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +#General Public License for more details. +#You should have received a copy of the GNU General Public +#License along with this library; if not, write to the Free Software +#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + def __init__(self, confnodesroot, comportstr): + self.PLCStatus = "Disconnected" + self.confnodesroot = confnodesroot + self.PLCprint = confnodesroot.logger.writeyield + comport = int(comportstr[3:]) - 1 + self.connect(comportstr) + self.confnodesroot.logger.write_error(str(e)+"\n") + self.SerialConnection = None + self.PLCStatus = "Disconnected" + def HandleSerialTransaction(self, transaction): + if self.SerialConnection is not None: + self.PLCStatus, res = self.SerialConnection.HandleTransaction(transaction) + except LPCProtoError,e: + self.confnodesroot.logger.write(_("PLC disconnected\n")) + if self.SerialConnection is not None: + self.SerialConnection.close() + self.SerialConnection = None + self.PLCStatus = "Disconnected" + self.confnodesroot.logger.write_warning(str(e)+"\n") + def StartPLC(self, debug=False): + raise LPCProtoError("Not implemented") + raise LPCProtoError("Not implemented") + def GetPLCstatus(self): + raise LPCProtoError("Not implemented") + def NewPLC(self, md5sum, data, extrafiles): + raise LPCProtoError("Not implemented") + def MatchMD5(self, MD5): + raise LPCProtoError("Not implemented") + def SetTraceVariablesList(self, idxs): + raise LPCProtoError("Not implemented") + def GetTraceVariables(self): + raise LPCProtoError("Not implemented") --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/LPCconnector/LPCProto.py Sun May 20 11:29:35 2012 +0200
@@ -0,0 +1,65 @@
+from threading import Lock +class LPCProtoError(exceptions.Exception): + def __init__(self, msg): + return "Exception in PLC protocol : " + str(self.msg) + def __init__(self, port, rate, timeout): + # serialize access lock + self.TransactionLock = Lock() + # Debugging serial stuff + self._serialPort = serial.Serial( port, rate, timeout = timeout, writeTimeout = timeout ) + res = self._serialPort.readline() + print 'Recv :"', res, '"' + res = self._serialPort.read(cnt) + print "Recv :", map(hex,map(ord,res[:16])), "[...]" + print "Recv :", map(hex,map(ord,res)) + def write(self_, string): + print "Send :", map(hex,map(ord,string[:16])), "[...]" + print "Send :", map(hex,map(ord,string)) + return self._serialPort.write(string) + # i = self._serialPort.write(string[:4096]) + return self._serialPort.flush() + self._serialPort.close() + self.serialPort = myser() + self.serialPort = serial.Serial( port, rate, timeout = timeout ) + # start with empty buffer + self.serialPort.flush() + self.serialPort.close() + self.serialPort.close() --- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/LPCconnector/__init__.py Sun May 20 11:29:35 2012 +0200
@@ -0,0 +1,35 @@
+#Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD +#See COPYING file for copyrights details. +#This library is free software; you can redistribute it and/or +#modify it under the terms of the GNU General Public +#License as published by the Free Software Foundation; either +#version 2.1 of the License, or (at your option) any later version. +#This library is distributed in the hope that it will be useful, +#but WITHOUT ANY WARRANTY; without even the implied warranty of +#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +#General Public License for more details. +#You should have received a copy of the GNU General Public +#License along with this library; if not, write to the Free Software +#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +def LPC_connector_factory(uri, confnodesroot): + This returns the connector to LPC style PLCobject + servicetype, location = uri.split("://") + mode,comportstr = location.split('/') + if mode=="APPLICATION": + from LPCAppObject import LPCAppObject + return LPCAppObject(confnodesroot,comportstr) + elif mode=="BOOTLOADER": + from LPCBootObject import LPCBootObject + return LPCBootObject(confnodesroot,comportstr) Binary file LPCconnector/__init__.pyc has changed
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/LPCtarget/XSD Sun May 20 11:29:35 2012 +0200
@@ -0,0 +1,6 @@
+ <xsd:element name="LPC"> \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/LPCtarget/__init__.py Sun May 20 11:29:35 2012 +0200
@@ -0,0 +1,74 @@
+from subprocess import Popen,PIPE +from targets.toolchain_makefile import toolchain_makefile +class LPC_target(toolchain_makefile): + def __init__(self, CTRInstance): + toolchain_makefile.__init__(self, CTRInstance) + def _GetBinMD5FileName(self): + return os.path.join(self.buildpath, "lastbuildPLCbin.md5") + def _get_md5_header(self): + """Returns signature header""" + ['arm-elf-size','-B',os.path.join(self.buildpath,"ArmPLC_rom.elf")], + stdout=PIPE).communicate()[0].splitlines()[1].split()[0]) + res = "&" + hashlib.md5(open(os.path.join(self.buildpath, "ArmPLC_rom.bin"), "rb").read(size)).hexdigest() + '\n' +\ + def GetBinaryCode(self): + """Returns ready to send signed + sized intel formated hex program""" + res = self._get_md5_header() +\ + open(os.path.join(self.buildpath, "ArmPLC_rom.hex"), "r").read() + def _get_cached_md5_header(self): + if self.binmd5key is not None: + return open(self._GetBinMD5FileName(), "r").read() + def ResetBinaryCodeMD5(self, mode): + if mode == "BOOTLOADER": + os.remove(self._GetBinMD5FileName()) + return toolchain_makefile.ResetBinaryCodeMD5(self) + def GetBinaryCodeMD5(self, mode): + if mode == "BOOTLOADER": + return self._get_cached_md5_header() + return toolchain_makefile.GetBinaryCodeMD5(self) + res = toolchain_makefile.build(self) + self.binmd5key = self._get_md5_header() + f = open(self._GetBinMD5FileName(), "w") + f.write(self.binmd5key) + self.CTRInstance.logger.write( + _("Binary is %s bytes long\n")% + os.path.join(self.buildpath, "ArmPLC_rom.bin")))) Binary file LPCtarget/__init__.pyc has changed
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/LPCtarget/plc_LPC_main.c Sun May 20 11:29:35 2012 +0200
@@ -0,0 +1,145 @@
+ * Yagarto specific code +/* provided by POUS.C */ +extern unsigned long long common_ticktime__; +extern unsigned long __tick; +extern unsigned long idLen; +extern unsigned char *idBuf; +static unsigned char RetainedIdBuf[128] __attribute__((section (".nvolatile"))); +static unsigned char retain_buffer[RETAIN_BUFFER_SIZE] __attribute__((section (".nvolatile"))); +static int debug_locked = 0; +static int _DebugDataAvailable = 0; +static unsigned long __debug_tick; +void LPC_GetTime(IEC_TIME*); +void LPC_SetTimer(unsigned long long next, unsigned long long period); +long AtomicCompareExchange(long* atomicvar,long compared, long exchange) + /* No need for real atomic op on LPC, + * no possible preemption between debug and PLC */ +void PLC_GetTime(IEC_TIME *CURRENT_TIME) + /* Call target GetTime function */ + LPC_GetTime(CURRENT_TIME); +void PLC_SetTimer(unsigned long long next, unsigned long long period) + LPC_SetTimer(next, period); +int startPLC(int argc,char **argv) + if(__init(argc,argv) == 0){ + /* sign retain buffer */ + PLC_SetTimer(0, common_ticktime__); +int TryEnterDebugSection(void) + if(!debug_locked && __DEBUG){ +void LeaveDebugSection(void) +/* from plc_debugger.c */ +int WaitDebugData(unsigned long *tick) + /* no blocking call on LPC */ + if(_DebugDataAvailable && !debug_locked){ + /* returns 0 on success */ + _DebugDataAvailable = 0; +/* Called by PLC thread when debug_publish finished + * This is supposed to unlock debugger thread in WaitDebugData*/ +void InitiateDebugTransfer(void) + _DebugDataAvailable = 1; +void suspendDebug(int disable) + /* Prevent PLC to enter debug code */ + debug_locked = !disable; + /* Let PLC enter debug code */ +void ValidateRetainBuffer(void) + memcpy(RetainedIdBuf, idBuf, idLen); +void InValidateRetainBuffer(void) + /* invalidate that buffer */ +int CheckRetainBuffer(void) + /* compare RETAIN ID buffer with MD5 */ + /* return true if identical */ + int res = memcmp(RetainedIdBuf, idBuf, idLen) == 0; +void Retain(unsigned int offset, unsigned int count, void *p) + if(offset + count < RETAIN_BUFFER_SIZE) + /* write in RETAIN buffer at offset*/ + memcpy(&retain_buffer[offset], p, count); +void Remind(unsigned int offset, unsigned int count, void *p) + if(offset + count < RETAIN_BUFFER_SIZE) + /* read at offset in RETAIN buffer */ + memcpy(p, &retain_buffer[offset], count);