etherlab/EtherCATManagementEditor.py
changeset 2643 b98d9e08231f
parent 2437 105c20fdeb19
parent 2641 c9deff128c37
equal deleted inserted replaced
2640:1b4b335e19ea 2643:b98d9e08231f
    69 
    69 
    70         # fill EtherCAT Management Treebook
    70         # fill EtherCAT Management Treebook
    71         panels = [
    71         panels = [
    72             ("Slave State",        SlaveStatePanelClass, []),
    72             ("Slave State",        SlaveStatePanelClass, []),
    73             ("SDO Management",     SDOPanelClass, []),
    73             ("SDO Management",     SDOPanelClass, []),
    74             ("PDO Monitoring",     PDOPanelClass, []),
    74             ("PDO Mapping",     PDOPanelClass, [
       
    75                     ("Rx PDO", RxPDOPanelClass),
       
    76                     ("Tx PDO", TxPDOPanelClass)]),
       
    77             ("MDP Setting",		MDPPanel, []),
    75             ("ESC Management",     EEPROMAccessPanel, [
    78             ("ESC Management",     EEPROMAccessPanel, [
    76                 ("Smart View", SlaveSiiSmartView),
    79                     ("Smart View",  SlaveSiiSmartView),
    77                 ("Hex View", HexView)]),
    80                     ("Hex View",    HexView)]),
    78             ("Register Access",     RegisterAccessPanel, [])
    81             ("Register Access",    RegisterAccessPanel, []),
       
    82             ("DC Configuration",    DCConfigPanel, [])
    79         ]
    83         ]
    80         for pname, pclass, subs in panels:
    84         for pname, pclass, subs in panels:
    81             self.AddPage(pclass(self, self.Controler), pname)
    85             self.AddPage(pclass(self, self.Controler), pname)
    82             for spname, spclass in subs:
    86             for spname, spclass in subs:
    83                 self.AddSubPage(spclass(self, self.Controler), spname)
    87                 self.AddSubPage(spclass(self, self.Controler), spname)
   228     def OnButtonClick(self, event):
   232     def OnButtonClick(self, event):
   229         """
   233         """
   230         Event handler for slave state transition button click (Init, PreOP, SafeOP, OP button)
   234         Event handler for slave state transition button click (Init, PreOP, SafeOP, OP button)
   231         @param event : wx.EVT_BUTTON object
   235         @param event : wx.EVT_BUTTON object
   232         """
   236         """
   233         check_connect_flag = self.Controler.CommonMethod.CheckConnect(False)
   237         # Check whether beremiz connected or not.
       
   238         # If this method is called cyclically, set the cyclic flag true
       
   239         check_connect_flag = self.Controler.CommonMethod.CheckConnect(cyclic_flag = False)
   234         if check_connect_flag:
   240         if check_connect_flag:
   235             state_dic = ["INIT", "PREOP", "SAFEOP", "OP"]
   241             state_dic = ["INIT", "PREOP", "SAFEOP", "OP"]
   236 
   242 
   237             # If target state is one of {INIT, PREOP, SAFEOP}, request slave state transition immediately.
   243             # If target state is one of {INIT, PREOP, SAFEOP}, request slave state transition immediately.
   238             if event.GetId() < 3:
   244             if event.GetId() < 3:
   253     def GetCurrentState(self, event):
   259     def GetCurrentState(self, event):
   254         """
   260         """
   255         Timer event handler for periodic slave state monitoring (Default period: 1 sec = 1000 msec).
   261         Timer event handler for periodic slave state monitoring (Default period: 1 sec = 1000 msec).
   256         @param event : wx.TIMER object
   262         @param event : wx.TIMER object
   257         """
   263         """
   258         check_connect_flag = self.Controler.CommonMethod.CheckConnect(True)
   264         if self.IsShownOnScreen() is False:
       
   265             return
       
   266 
       
   267         # Check whether beremiz connected or not.
       
   268         # If this method is called cyclically, set the cyclic flag true
       
   269         check_connect_flag = self.Controler.CommonMethod.CheckConnect(cyclic_flag = True)
   259         if check_connect_flag:
   270         if check_connect_flag:
   260             returnVal = self.Controler.CommonMethod.GetSlaveStateFromSlave()
   271             returnVal = self.Controler.CommonMethod.GetSlaveStateFromSlave()
   261             line = returnVal.split("\n")
   272             line = returnVal.split("\n")
   262             try:
   273             try:
   263                 self.SetCurrentState(line[self.Controler.GetSlavePos()])
   274                 self.SetCurrentState(line[self.Controler.GetSlavePos()])
   283         """
   294         """
   284         Event handler for "Start State Monitoring" button.
   295         Event handler for "Start State Monitoring" button.
   285           - start slave state monitoring thread
   296           - start slave state monitoring thread
   286         @param event : wx.EVT_BUTTON object
   297         @param event : wx.EVT_BUTTON object
   287         """
   298         """
   288         self.SlaveStateThread = wx.Timer(self)
   299         # Check whether beremiz connected or not.
   289         # set timer period (1000 ms)
   300         # If this method is called cyclically, set the cyclic flag true
   290         self.SlaveStateThread.Start(1000)
   301         check_connect_flag = self.Controler.CommonMethod.CheckConnect(cyclic_flag = False)
       
   302         if check_connect_flag:
       
   303             self.SlaveStateThread = wx.Timer(self)
       
   304             # set timer period (2000 ms)
       
   305             self.SlaveStateThread.Start(2000)
       
   306         else:
       
   307             pass
   291 
   308 
   292     def CurrentStateThreadStop(self, event):
   309     def CurrentStateThreadStop(self, event):
   293         """
   310         """
   294         Event handler for "Stop State Monitoring" button.
   311         Event handler for "Stop State Monitoring" button.
   295           - stop slave state monitoring thread
   312           - stop slave state monitoring thread
   316         self.DatatypeDescription, self.CommunicationObject, self.ManufacturerSpecific, \
   333         self.DatatypeDescription, self.CommunicationObject, self.ManufacturerSpecific, \
   317             self.ProfileSpecific, self.Reserved, self.AllSDOData = range(6)
   334             self.ProfileSpecific, self.Reserved, self.AllSDOData = range(6)
   318 
   335 
   319         self.Controler = controler
   336         self.Controler = controler
   320 
   337 
       
   338         self.SDOMonitorEntries = {}
       
   339         #----------------------------- SDO Monitor -------------------------------#
       
   340         self.RBList = ["ON","OFF"]
       
   341         
       
   342         self.SDOMonitorRB = wx.RadioBox(self, label=_("monitoring"),
       
   343                                         choices=self.RBList, majorDimension=2)
       
   344         
       
   345         self.SDOMonitorRB.SetSelection(1)
       
   346         self.Bind(wx.EVT_RADIOBOX, self.OnRadioBox, self.SDOMonitorRB)
       
   347        
       
   348         self.SDOMonitorGrid = wx.grid.Grid(self,size=wx.Size(850,150),style=wx.EXPAND
       
   349                                                         |wx.ALIGN_CENTER_HORIZONTAL
       
   350                                                         |wx.ALIGN_CENTER_VERTICAL) 
       
   351         self.SDOMonitorGrid.Bind(gridlib.EVT_GRID_CELL_LEFT_DCLICK, 
       
   352                                                     self.onMonitorGridDoubleClick)
       
   353 
       
   354         #----------------------------- SDO Entries ----------------------------#
       
   355         self.SDOUpdateBtn = wx.Button(self, label=_("update"))         
       
   356         self.SDOUpdateBtn.Bind(wx.EVT_BUTTON, self.OnSDOUpdate)
       
   357         
       
   358         self.SDOTraceThread = None
       
   359         self.SDOMonitoringFlag = False
       
   360         self.SDOValuesList = []
       
   361         # Default SDO Page Number
       
   362         self.SDOPageNum = 2
       
   363 
       
   364         #----------------------------- Sizer --------------------------------------#
   321         self.SDOManagementMainSizer = wx.BoxSizer(wx.VERTICAL)
   365         self.SDOManagementMainSizer = wx.BoxSizer(wx.VERTICAL)
   322         self.SDOManagementInnerMainSizer = wx.FlexGridSizer(cols=1, hgap=10, rows=2, vgap=10)
   366         self.SDOInfoBox = wx.StaticBox(self, label=_("SDO Entries"))
   323 
   367         self.SDOMonitorBox = wx.StaticBox(self, label=_("SDO Monitor"))
   324         self.SDOUpdate = wx.Button(self, label=_('update'))
   368 
   325         self.SDOUpdate.Bind(wx.EVT_BUTTON, self.SDOInfoUpdate)
   369         self.SDONoteBook = SDONoteBook(self, controler=self.Controler)
   326 
   370         self.SDOInfoBoxSizer = wx.StaticBoxSizer(self.SDOInfoBox, orient=wx.VERTICAL)
   327         self.CallSDONoteBook = SDONoteBook(self, controler=self.Controler)
   371         self.SDOMonitorBoxSizer = wx.StaticBoxSizer(self.SDOMonitorBox, 
   328         self.SDOManagementInnerMainSizer.Add(self.SDOUpdate)
   372                                                                     orient=wx.VERTICAL)
   329         self.SDOManagementInnerMainSizer.Add(self.CallSDONoteBook, wx.ALL | wx.EXPAND)
   373         self.SDOInfoBoxSizer.Add(self.SDOUpdateBtn)
   330 
   374         
   331         self.SDOManagementMainSizer.Add(self.SDOManagementInnerMainSizer)
   375         self.SDOInfoBoxSizer.Add(self.SDONoteBook, wx.ALL|wx.EXPAND)
   332 
   376         self.SDOMonitorBoxSizer.Add(self.SDOMonitorRB)
       
   377         self.SDOMonitorBoxSizer.Add(self.SDOMonitorGrid)
       
   378         self.SDOManagementMainSizer.AddMany([self.SDOInfoBoxSizer, 
       
   379                                              self.SDOMonitorBoxSizer])
   333         self.SetSizer(self.SDOManagementMainSizer)
   380         self.SetSizer(self.SDOManagementMainSizer)
   334 
   381         
   335     def SDOInfoUpdate(self, event):
   382         #----------------------------- fill the contents --------------------------# 
   336         """
   383         #self.entries = self.Controler.CTNParent.CTNParent.GetEntriesList()
   337         Evenet handler for SDO "update" button.
   384 
   338           - Load SDO data from current slave
   385         slave = self.Controler.CTNParent.GetSlave(self.Controler.GetSlavePos())
   339         @param event : wx.EVT_BUTTON object
   386         type_infos = slave.getType()
   340         """
   387         device, alignment = self.Controler.CTNParent.GetModuleInfos(type_infos)
   341         self.Controler.CommonMethod.SaveSDOData = []
   388         self.entries = device.GetEntriesList()
       
   389 
       
   390         self.Controler.CommonMethod.SDOVariables = []
       
   391         self.Controler.CommonMethod.SDOSubEntryData = []
   342         self.Controler.CommonMethod.ClearSDODataSet()
   392         self.Controler.CommonMethod.ClearSDODataSet()
   343         self.SDOFlag = False
   393         self.SDOParserXML(self.entries)
   344 
   394         self.SDONoteBook.CreateNoteBook()      
   345         # Check whether beremiz connected or not.
   395         self.CreateSDOMonitorGrid()
   346         check_connect_flag = self.Controler.CommonMethod.CheckConnect(False)
   396         self.Refresh()
       
   397 
       
   398     def OnSDOUpdate(self, event):
       
   399         SlavePos = self.Controler.GetSlavePos()
       
   400         num = self.SDOPageNum - 1
       
   401         if num < 0:
       
   402             for i in range(len(self.Controler.CommonMethod.SDOVariables)):
       
   403                 data = self.Controler.GetCTRoot()._connector.GetSDOEntriesData(
       
   404                            self.Controler.CommonMethod.SDOVariables[i], SlavePos)
       
   405                 self.Controler.CommonMethod.SDOVariables[i] = data
       
   406         else :
       
   407             SDOUploadEntries = self.Controler.CommonMethod.SDOVariables[num]        
       
   408             data = self.Controler.GetCTRoot()._connector.GetSDOEntriesData(SDOUploadEntries, SlavePos)
       
   409             self.Controler.CommonMethod.SDOVariables[num] = data
       
   410 
       
   411         self.SDONoteBook.CreateNoteBook()      
       
   412         self.Refresh()
       
   413 
       
   414     def OnRadioBox(self, event):
       
   415         """
       
   416         There are two selections that are on and off.
       
   417         If the on is selected, the monitor thread begins to run.
       
   418         If the off is selected, the monitor thread gets off.
       
   419         @param event: wx.EVT_RADIOBOX object 
       
   420         """
       
   421         on, off = range(2)
       
   422 
       
   423         if event.GetInt() == on:
       
   424             CheckThreadFlag = self.SDOMonitoringThreadOn()
       
   425             if not CheckThreadFlag:
       
   426                 self.SDOMonitorRB.SetSelection(off)
       
   427         elif event.GetInt() == off:
       
   428             self.SDOMonitoringThreadOff()
       
   429 
       
   430     def SDOMonitoringThreadOn(self):
       
   431         check_connect_flag = self.Controler.CommonMethod.CheckConnect(cyclic_flag = False)
   347         if check_connect_flag:
   432         if check_connect_flag:
   348             self.SDOs = self.Controler.CommonMethod.GetSlaveSDOFromSlave()
   433             self.SetSDOTraceValues(self.SDOMonitorEntries)
   349             # SDOFlag is "False", user click "Cancel" button
   434             self.Controler.GetCTRoot()._connector.GetSDOData()
   350             self.SDOFlag = self.SDOParser()
   435             self.SDOTraceThread = Thread(target=self.SDOMonitorThreadProc)
   351 
   436             self.SDOMonitoringFlag = True
   352             if self.SDOFlag:
   437             self.SDOTraceThread.start()
   353                 self.CallSDONoteBook.CreateNoteBook()
   438         return check_connect_flag
   354                 self.Refresh()
   439 
   355 
   440     def SDOMonitoringThreadOff(self):
   356     def SDOParser(self):
   441         check_connect_flag = self.Controler.CommonMethod.CheckConnect(cyclic_flag = False)
   357         """
   442         if check_connect_flag:
   358         Parse SDO data set that obtain "SDOInfoUpdate" Method
   443             self.SDOMonitoringFlag = False
   359         @return True or False
   444             if self.SDOTraceThread is not None:
   360         """
   445                 self.SDOTraceThread.join()
   361 
   446             self.SDOTraceThread = None
   362         slaveSDO_progress = wx.ProgressDialog(_("Slave SDO Monitoring"), _("Now Uploading..."),
   447             self.Controler.GetCTRoot()._connector.StopSDOThread()
   363                                               maximum=len(self.SDOs.splitlines()),
   448 
   364                                               parent=self,
   449     def SetSDOTraceValues(self, SDOMonitorEntries):
   365                                               style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME |
   450         SlavePos = self.Controler.GetSlavePos()
   366                                               wx.PD_ESTIMATED_TIME | wx.PD_REMAINING_TIME |
   451         check_connect_flag = self.Controler.CommonMethod.CheckConnect(cyclic_flag = True)
   367                                               wx.PD_AUTO_HIDE | wx.PD_SMOOTH)
   452         if check_connect_flag:
   368 
   453             self.Controler.GetCTRoot()._connector.SetSDOTraceValues(SDOMonitorEntries, SlavePos)
   369         # If keep_going flag is False, SDOParser method is stop and return "False".
   454 
   370         keep_going = True
   455     def SDOMonitorThreadProc(self):
   371         count = 0
   456         while self.SDOMonitoringFlag and self.Controler.GetCTRoot()._connector.PLCStatus != "Started":
   372 
   457             self.SDOValuesList = self.Controler.GetCTRoot()._connector.GetSDOData()
   373         # SDO data example
   458             LocalData = self.SDOValuesList[0].items()
   374         # SDO 0x1000, "Device type"
   459             LocalData.sort()
   375         # 0x1000:00,r-r-r-,uint32,32 bit,"Device type",0x00020192, 131474
   460             if self.SDOValuesList[1] != self.Controler.GetSlavePos():
   376         for details_line in self.SDOs.splitlines():
   461                 continue
   377             count += 1
   462             row = 0
   378             line_token = details_line.split("\"")
   463             for (idx, subidx), data in LocalData:
   379             # len(line_token[2]) case : SDO 0x1000, "Device type"
   464                 self.SDOMonitorGrid.SetCellValue(row, 6, str(data["value"]))
   380             if len(line_token[2]) == 0:
   465                 row += 1
   381                 title_name = line_token[1]
   466             time.sleep(0.5)
   382             # else case : 0x1000:00,r-r-r-,uint32,32 bit,"Device type",0x00020192, 131474
   467 
   383             else:
   468     def CreateSDOMonitorGrid(self):
   384                 # line_token = ['0x1000:00,r-r-r-,uint32,32 bit,', 'Device type', ',0x00020192, 131474']
   469         """
   385                 token_head, name, token_tail = line_token
   470         It creates SDO Monitor table and specifies cell size and labels.
   386 
   471         """
   387                 # token_head = ['0x1000:00', 'r-r-r-', 'uint32', '32 bit', '']
   472         self.SDOMonitorGrid.CreateGrid(0,7) 
   388                 token_head = token_head.split(",")
   473         SDOCellSize = [(0, 65), (1, 65), (2, 50), (3, 70), 
   389                 ful_idx, access, type, size, _empty = token_head
   474                          (4, 40), (5, 450), (6, 85)]
   390                 # ful_idx.split(":") = ['0x1000', '00']
   475 
   391                 idx, sub_idx = ful_idx.split(":")
   476         for (index, size) in SDOCellSize:
   392 
   477             self.SDOMonitorGrid.SetColSize(index, size)
   393                 # token_tail = ['', '0x00020192', '131474']
   478         
   394                 token_tail = token_tail.split(",")
   479         self.SDOMonitorGrid.SetRowLabelSize(0)
   395                 try:
   480 
   396                     _empty, hex_val, _dec_val = token_tail
   481         SDOTableLabel = [(0, "Index"), (1, "Subindex"), (2, "Access"),
   397 
   482                          (3, "Type"), (4, "Size"), (5, "Name"), (6, "Value")]
   398                 # SDO data is not return "dec value"
   483         
   399                 # line example :
   484         for (index, label) in SDOTableLabel:
   400                 # 0x1702:01,rwr-r-,uint32,32 bit," 1st mapping", ----
   485             self.SDOMonitorGrid.SetColLabelValue(index, label)
   401                 except Exception:
   486             self.SDOMonitorGrid.SetColLabelAlignment(index, wx.ALIGN_CENTER)
   402                     _empty, hex_val = token_tail
   487 
   403 
   488     def onMonitorGridDoubleClick(self, event):
   404                 name_after_check = self.StringTest(name)
   489         """
   405 
   490         Event Handler for double click on the SDO entries table.
   406                 # convert hex type
   491         It adds the entry into the SDO monitor table.
   407                 sub_idx = "0x" + sub_idx
   492         If the entry is already in the SDO monitor table, 
   408 
   493         then it's removed from the SDO monitor table.
   409                 if type == "octet_string":
   494         @pram event: gridlib.EVT_GRID_CELL_LEFT_DCLICK object
   410                     hex_val = ' ---- '
   495         """
   411 
   496         row = event.GetRow()
   412                 # SResult of SlaveSDO data parsing. (data type : dictionary)
   497         idx = self.SDOMonitorGrid.GetCellValue(row, 0)
   413                 self.Data = {'idx': idx.strip(), 'subIdx': sub_idx.strip(), 'access': access.strip(),
   498         subIdx = self.SDOMonitorGrid.GetCellValue(row, 1)
   414                              'type': type.strip(), 'size': size.strip(),  'name': name_after_check.strip("\""),
   499         
   415                              'value': hex_val.strip(), "category": title_name.strip("\"")}
   500         del self.SDOMonitorEntries[(idx, subIdx)]
   416 
   501         self.SDOMonitorGrid.DeleteRows(row, 1)
   417                 category_divide_value = [0x1000, 0x2000, 0x6000, 0xa000, 0xffff]
   502         # add jblee
   418 
   503         self.SetSDOTraceValues(self.SDOMonitorEntries)
   419                 for count in range(len(category_divide_value)):
   504         self.SDOMonitorGrid.Refresh()
   420                     if int(idx, 0) < category_divide_value[count]:
   505 
   421                         self.Controler.CommonMethod.SaveSDOData[count].append(self.Data)
   506     def SDOParserXML(self, entries):
   422                         break
   507         """
   423 
   508         Parse SDO data set that obtain "ESI file"
   424                 self.Controler.CommonMethod.SaveSDOData[self.AllSDOData].append(self.Data)
   509         @param entries: SDO entry list 
   425 
   510         """  
   426             if count >= len(self.SDOs.splitlines()) // 2:
   511         entries_list = entries.items()
   427                 (keep_going, _skip) = slaveSDO_progress.Update(count, "Please waiting a moment!!")
   512         entries_list.sort()
   428             else:
   513         self.ForDefaultValueFlag = False
   429                 (keep_going, _skip) = slaveSDO_progress.Update(count)
   514         self.CompareValue = ""
   430 
   515         self.sub_entry_value_list = []
   431             # If user click "Cancel" loop suspend immediately
   516 
   432             if not keep_going:
   517         for (index, subidx), entry in entries_list:
   433                 break
   518             # exclude entry that isn't in the objects
   434 
   519             check_mapping = entry["PDOMapping"]
   435         slaveSDO_progress.Destroy()
   520             if check_mapping is "T" or check_mapping is "R":
   436         return keep_going
   521                 if "PDO index" not in entry.keys():
   437 
   522                     continue
   438     def StringTest(self, check_string):
   523 
   439         """
   524             idx = "0" + entry["Index"].strip("#")
   440         Test value 'name' is alphanumeric
   525             #subidx = hex(int(entry["SubIndex"], 0))
   441         @param check_string : input data for check
   526             try :        
   442         @return result : output data after check
   527                 subidx = "0x" + entry["SubIndex"]
   443         """
   528             except :
   444         # string.printable is print this result
   529                 subidx = "0x0"
   445         # '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
   530             datatype = entry["Type"]
   446         # !"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c
   531 
   447         allow_range = string.printable
   532             try :
   448         result = check_string
   533                 default_value = entry["DefaultData"]
   449         for i in range(0, len(check_string)):
   534             except :
   450             # string.isalnum() is check whether string is alphanumeric or not
   535                 default_value = " --- "
   451             if check_string[len(check_string)-1-i:len(check_string)-i] in allow_range:
   536             # Result of SlaveSDO data parsing. (data type : dictionary)
   452                 result = check_string[:len(check_string) - i]
   537             self.Data = {'idx':idx, 'subIdx':subidx, 'access':entry["Access"], 
   453                 break
   538                          'type':datatype, 'size': str(entry["BitSize"]), 
   454         return result
   539                          'name':entry["Name"], 'value':default_value}
   455 
   540             category_divide_value = [0x1000, 0x2000, 0x6000, 0xa000, 0xffff]
   456 
   541                 
   457 # -------------------------------------------------------------------------------
   542             for count in range(len(category_divide_value)) :
       
   543                 if int(idx, 0) < category_divide_value[count]:
       
   544                     self.Controler.CommonMethod.SDOVariables[count].append(self.Data)
       
   545                     break
       
   546 
       
   547         self.Controler.CommonMethod.SDOSubEntryData = self.sub_entry_value_list
       
   548     
       
   549 #-------------------------------------------------------------------------------
   458 #                    For SDO Notebook (divide category)
   550 #                    For SDO Notebook (divide category)
   459 # -------------------------------------------------------------------------------
   551 # -------------------------------------------------------------------------------
   460 class SDONoteBook(wx.Notebook):
   552 class SDONoteBook(wx.Notebook):
   461     def __init__(self, parent, controler):
   553     def __init__(self, parent, controler):
   462         """
   554         """
   492         #                        "SDO Index 0xa000 - 0xffff : Reserved",
   584         #                        "SDO Index 0xa000 - 0xffff : Reserved",
   493         #                        "All SDO Object"]
   585         #                        "All SDO Object"]
   494 
   586 
   495         self.DeleteAllPages()
   587         self.DeleteAllPages()
   496 
   588 
       
   589         self.Controler.CommonMethod.SDOVariables[5] = []
       
   590         for i in range(4):
       
   591             self.Controler.CommonMethod.SDOVariables[5] += self.Controler.CommonMethod.SDOVariables[i]
       
   592             
   497         for txt, count in page_texts:
   593         for txt, count in page_texts:
   498             self.Data = self.Controler.CommonMethod.SaveSDOData[count]
   594             self.Data = self.Controler.CommonMethod.SDOVariables[count]
   499             self.Win = SlaveSDOTable(self, self.Data)
   595             self.SubEntryData = self.Controler.CommonMethod.SDOSubEntryData
       
   596             self.Win = SlaveSDOTable(self, self.Data, self.SubEntryData)
   500             self.AddPage(self.Win, txt)
   597             self.AddPage(self.Win, txt)
   501 
   598 
       
   599     # add jblee
       
   600     def OnPageChanged(self, event):
       
   601         old = event.GetOldSelection()
       
   602         new = event.GetSelection()
       
   603         sel = self.GetSelection()
       
   604         self.parent.SDOPageNum = new
       
   605         event.Skip()
       
   606 
       
   607     def OnPageChanging(self, event):
       
   608         old = event.GetOldSelection()
       
   609         new = event.GetSelection()
       
   610         sel = self.GetSelection()
       
   611         event.Skip()
   502 
   612 
   503 # -------------------------------------------------------------------------------
   613 # -------------------------------------------------------------------------------
   504 #                    For SDO Grid (fill index, subindex, etc...)
   614 #                    For SDO Grid (fill index, subindex, etc...)
   505 # -------------------------------------------------------------------------------
   615 # -------------------------------------------------------------------------------
   506 class SlaveSDOTable(wx.grid.Grid):
   616 class SlaveSDOTable(wx.grid.Grid):
   507     def __init__(self, parent, data):
   617     def __init__(self, parent, data, fixed_value):
   508         """
   618         """
   509         Constructor
   619         Constructor
   510         @param parent: Reference to the parent SDOPanelClass class
   620         @param parent: Reference to the parent SDOPanelClass class
   511         @param data: SDO data after parsing "SDOParser" method
   621         @param data: SDO data after parsing "SDOParser" method
   512         """
   622         """
   516         self.Controler = parent.Controler
   626         self.Controler = parent.Controler
   517         self.parent = parent
   627         self.parent = parent
   518         self.SDOFlag = True
   628         self.SDOFlag = True
   519         if data is None:
   629         if data is None:
   520             self.SDOs = []
   630             self.SDOs = []
   521         else:
   631             self.sub_entry_value = []
       
   632         else :
   522             self.SDOs = data
   633             self.SDOs = data
   523 
   634             self.sub_entry_value = fixed_value
   524         self.CreateGrid(len(self.SDOs), 8)
   635         
   525         SDOCellSize = [(0, 65), (1, 65), (2, 50), (3, 55),
   636         self.CreateGrid(len(self.SDOs), 7)
   526                        (4, 40), (5, 200), (6, 250), (7, 85)]
   637         SDOCellSize = [(0, 65), (1, 65), (2, 50), (3, 70), 
   527 
   638                          (4, 40), (5, 400), (6, 135)]
       
   639         
   528         for (index, size) in SDOCellSize:
   640         for (index, size) in SDOCellSize:
   529             self.SetColSize(index, size)
   641             self.SetColSize(index, size)
   530 
   642 
   531         self.SetRowLabelSize(0)
   643         self.SetRowLabelSize(0)
   532 
   644 
   533         SDOTableLabel = [(0, "Index"), (1, "Subindex"), (2, "Access"),
   645         SDOTableLabel = [(0, "Index"), (1, "Subindex"), (2, "Access"),
   534                          (3, "Type"), (4, "Size"), (5, "Category"),
   646                          (3, "Type"), (4, "Size"), (5, "Name"), (6, "Value")]
   535                          (6, "Name"), (7, "Value")]
       
   536 
   647 
   537         for (index, label) in SDOTableLabel:
   648         for (index, label) in SDOTableLabel:
   538             self.SetColLabelValue(index, label)
   649             self.SetColLabelValue(index, label)
   539             self.SetColLabelAlignment(index, wx.ALIGN_CENTRE)
   650             self.SetColLabelAlignment(index, wx.ALIGN_CENTER)
   540 
   651 
   541         attr = wx.grid.GridCellAttr()
   652         attr = wx.grid.GridCellAttr()
   542 
   653 
   543         # for SDO download
   654         # for SDO download and monitoring 
   544         self.Bind(wx.grid.EVT_GRID_CELL_LEFT_DCLICK, self.SDOModifyDialog)
   655         self.Bind(gridlib.EVT_GRID_CELL_LEFT_DCLICK, self.onGridDoubleClick)
   545 
   656 
   546         for i in range(7):
   657         for i in range(7):
   547             self.SetColAttr(i, attr)
   658             self.SetColAttr(i, attr)
   548 
   659 
   549         self.SetColLabelAlignment(wx.ALIGN_CENTER, wx.ALIGN_CENTER)
   660         self.SetColLabelAlignment(wx.ALIGN_CENTER, wx.ALIGN_CENTER)
   552 
   663 
   553     def SetTableValue(self):
   664     def SetTableValue(self):
   554         """
   665         """
   555         Cell is filled by new parsing data
   666         Cell is filled by new parsing data
   556         """
   667         """
   557         sdo_list = ['idx', 'subIdx', 'access', 'type', 'size', 'category', 'name', 'value']
   668         sdo_list = ['idx', 'subIdx', 'access', 'type', 'size', 'name', 'value']
       
   669         count = 0
   558         for row_idx in range(len(self.SDOs)):
   670         for row_idx in range(len(self.SDOs)):
   559             for col_idx in range(len(self.SDOs[row_idx])):
   671             for col_idx in range(len(self.SDOs[row_idx])):
   560                 self.SetCellValue(row_idx, col_idx, self.SDOs[row_idx][sdo_list[col_idx]])
   672                 
       
   673                 # the top entries that have sub index is shaded.
       
   674                 if int(self.SDOs[row_idx]['subIdx'], 16) == 0x00:
       
   675                     try:
       
   676                         if int(self.SDOs[row_idx + 1]['subIdx'], 16) is not 0x00:
       
   677                             self.SetCellBackgroundColour(row_idx, col_idx, \
       
   678                                                                 wx.LIGHT_GREY)
       
   679                     except:
       
   680                         pass
       
   681 
       
   682                 if self.SDOs[row_idx][sdo_list[col_idx]] == "modifying":
       
   683                     if len(self.sub_entry_value) == count:
       
   684                         continue
       
   685                     self.SetCellValue(row_idx, col_idx, self.sub_entry_value[count])
       
   686                     count += 1
       
   687                 else :
       
   688                     self.SetCellValue(row_idx, col_idx, \
       
   689                                   self.SDOs[row_idx][sdo_list[col_idx]])
       
   690 
   561                 self.SetReadOnly(row_idx, col_idx, True)
   691                 self.SetReadOnly(row_idx, col_idx, True)
   562                 if col_idx < 5:
   692                 if col_idx < 5:
   563                     self.SetCellAlignment(row_idx, col_idx, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
   693                     self.SetCellAlignment(row_idx, col_idx, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
   564 
   694 
   565     def CheckSDODataAccess(self, row):
   695     def CheckSDODataAccess(self, row):
   566         """
   696         """
   567         CheckSDODataAccess method is checking that access data has "w"
   697         check that access field has "rw"
   568         Access field consist 6 char, if mean
       
   569            rw      rw     rw
       
   570         (preop) (safeop) (op)
       
   571         Example Access field : rwrwrw, rwrw--
       
   572         @param row : Selected cell by user
   698         @param row : Selected cell by user
   573         @return Write_flag : If data has "w", flag is true
   699         @return Write_flag : If data has "w", flag is true
   574         """
   700         """
   575         write_flag = False
       
   576         check = self.SDOs[row]['access']
   701         check = self.SDOs[row]['access']
   577         if check[1:2] == 'w':
   702         if check == "rw":
   578             self.Controler.CommonMethod.Check_PREOP = True
       
   579             write_flag = True
       
   580         if check[3:4] == 'w':
       
   581             self.Controler.CommonMethod.Check_SAFEOP = True
       
   582             write_flag = True
       
   583         if check[5:] == 'w':
       
   584             self.Controler.CommonMethod.Check_OP = True
       
   585             write_flag = True
       
   586 
       
   587         return write_flag
       
   588 
       
   589     def DecideSDODownload(self, state):
       
   590         """
       
   591         compare current state and "access" field,
       
   592         result notify SDOModifyDialog method
       
   593         @param state : current slave state
       
   594         @return True or False
       
   595         """
       
   596         # Example of 'state' parameter : "0  0:0  PREOP  +  EL9800 (V4.30) (PIC24, SPI, ET1100)"
       
   597         state = state[self.Controler.GetSlavePos()].split("  ")[2]
       
   598         if state == "PREOP" and self.Controler.CommonMethod.Check_PREOP:
       
   599             return True
   703             return True
   600         elif state == "SAFEOP" and self.Controler.CommonMethod.Check_SAFEOP:
   704         else:
   601             return True
   705             return False
   602         elif state == "OP" and self.Controler.CommonMethod.Check_OP:
   706     
   603             return True
       
   604 
       
   605         return False
       
   606 
       
   607     def ClearStateFlag(self):
   707     def ClearStateFlag(self):
   608         """
   708         """
   609         Initialize StateFlag
   709         Initialize StateFlag
   610         StateFlag is notice SDOData access each slave state
   710         StateFlag is notice SDOData access each slave state
   611         """
   711         """
   612         self.Controler.CommonMethod.Check_PREOP = False
   712         self.Controler.CommonMethod.Check_PREOP = False
   613         self.Controler.CommonMethod.Check_SAFEOP = False
   713         self.Controler.CommonMethod.Check_SAFEOP = False
   614         self.Controler.CommonMethod.Check_OP = False
   714         self.Controler.CommonMethod.Check_OP = False
   615 
   715 
   616     def SDOModifyDialog(self, event):
   716     def onGridDoubleClick (self, event):
   617         """
   717         """
   618         Create dialog for SDO value modify
   718         Create dialog for SDO value modify
   619         if user enter data, perform command "ethercat download"
   719         if user enter data, perform command "ethercat download"  
   620         @param event : wx.grid.EVT_GRID_CELL_LEFT_DCLICK object
   720         @param event : gridlib.EVT_GRID_CELL_LEFT_DCLICK object
   621         """
   721         """
   622         self.ClearStateFlag()
   722         self.ClearStateFlag()
   623 
   723         
   624         # CheckSDODataAccess is checking that OD(Object Dictionary) has "w"
   724         # CheckSDODataAccess is checking that OD(Object Dictionary) has "w" 
   625         if event.GetCol() == 7 and self.CheckSDODataAccess(event.GetRow()):
   725         if event.GetCol() == 6 and self.CheckSDODataAccess(event.GetRow()) :    
   626             dlg = wx.TextEntryDialog(
   726             dlg = wx.TextEntryDialog (self, 
   627                 self,
   727                     "Enter hex or dec value (if enter dec value, " \
   628                 _("Enter hex or dec value (if enter dec value, it automatically conversed hex value)"),
   728                   + "it automatically conversed hex value)",
   629                 "SDOModifyDialog",
   729                     "SDOModifyDialog", style = wx.OK | wx.CANCEL)
   630                 style=wx.OK | wx.CANCEL)
   730 
   631 
   731             start_value = self.GetCellValue(event.GetRow(), event.GetCol()) 
   632             start_value = self.GetCellValue(event.GetRow(), event.GetCol())
       
   633             dlg.SetValue(start_value)
   732             dlg.SetValue(start_value)
   634 
   733             
   635             if dlg.ShowModal() == wx.ID_OK:
   734             if dlg.ShowModal() == wx.ID_OK:
   636                 try:
   735                 # Check whether beremiz connected or not.
   637                     int(dlg.GetValue(), 0)
   736                 # If this method is called cyclically, set the cyclic flag true
   638                     # check "Access" field
   737                 check_connect_flag = self.Controler.CommonMethod.CheckConnect(cyclic_flag = False)
   639                     if self.DecideSDODownload(self.Controler.CommonMethod.SlaveState[self.Controler.GetSlavePos()]):
   738                 if check_connect_flag:
       
   739                     try :
       
   740                         input_val = hex(int(dlg.GetValue(), 0))
   640                         # Request "SDODownload"
   741                         # Request "SDODownload"
   641                         self.Controler.CommonMethod.SDODownload(
   742                         return_val = self.Controler.CommonMethod.SDODownload(
   642                             self.SDOs[event.GetRow()]['type'],
   743                                                 self.SDOs[event.GetRow()]["type"], 
   643                             self.SDOs[event.GetRow()]['idx'],
   744                                                 self.SDOs[event.GetRow()]["idx"], 
   644                             self.SDOs[event.GetRow()]['subIdx'],
   745                                                 self.SDOs[event.GetRow()]["subIdx"], 
   645                             dlg.GetValue())
   746                                                 dlg.GetValue())
   646 
   747                         if return_val is "":
   647                         self.SetCellValue(event.GetRow(), event.GetCol(), hex(int(dlg.GetValue(), 0)))
   748                             SDOUploadEntry = {"idx" : self.SDOs[event.GetRow()]["idx"],
   648                     else:
   749                                               "subIdx" : self.SDOs[event.GetRow()]["subIdx"],
   649                         self.Controler.CommonMethod.CreateErrorDialog(_('You cannot SDO download this state'))
   750                                               "size" : self.SDOs[event.GetRow()]["size"]
   650                 # Error occured process of "int(variable)"
   751                                              }
   651                 # User input is not hex, dec value
   752                             data = self.Controler.GetCTRoot()._connector.GetSDOEntryData(
   652                 except ValueError:
   753                                 SDOUploadEntry, self.Controler.GetSlavePos())
   653                     self.Controler.CommonMethod.CreateErrorDialog(_('You can input only hex, dec value'))
   754                             hex_val = hex(data)[:-1]                           
   654 
   755 
   655 
   756                             # download data check
   656 # -------------------------------------------------------------------------------
   757                             if input_val == hex_val:
   657 #                 For PDO Monitoring Panel
   758                                 display_val = "%s(%d)" % (hex_val, data) 
       
   759                                 self.SetCellValue(event.GetRow(), event.GetCol(), 
       
   760                                                   display_val)
       
   761                             else :
       
   762                                 self.Controler.CommonMethod.CreateErrorDialog(\
       
   763                                             'SDO Value not completely download, please try again')    
       
   764                         else:
       
   765                             self.Controler.GetCTRoot().logger.write_error(return_val)
       
   766                             
       
   767                     # Error occured process of "int(variable)"
       
   768                     # User input is not hex, dec value
       
   769                     except ValueError:
       
   770                         self.Controler.CommonMethod.CreateErrorDialog(\
       
   771                                             'You can input only hex, dec value')    
       
   772         else:
       
   773             SDOPanel = self.parent.parent
       
   774             row = event.GetRow() 
       
   775             
       
   776             idx = self.SDOs[row]["idx"]
       
   777             subIdx = self.SDOs[row]["subIdx"]
       
   778             SDOPanel.SDOMonitorEntries[(idx, subIdx)] = {
       
   779                                                 "access": self.SDOs[row]["access"],
       
   780                                                 "type": self.SDOs[row]["type"],
       
   781                                                 "size": self.SDOs[row]["size"],
       
   782                                                 "name": self.SDOs[row]["name"],
       
   783                                                 # add jblee
       
   784                                                 "value": ""}
       
   785             
       
   786             del_rows = SDOPanel.SDOMonitorGrid.GetNumberRows()
       
   787             
       
   788             try: 
       
   789                 SDOPanel.SDOMonitorGrid.DeleteRows(0, del_rows)
       
   790             except:
       
   791                 pass
       
   792 
       
   793             SDOPanel.SDOMonitorGrid.AppendRows(len(SDOPanel.SDOMonitorEntries))
       
   794             SDOPanel.SetSDOTraceValues(SDOPanel.SDOMonitorEntries)
       
   795             
       
   796             SME_list = SDOPanel.SDOMonitorEntries.items()
       
   797             SME_list.sort()
       
   798 
       
   799             gridRow = 0
       
   800             for (idx, subIdx), entry in SME_list:
       
   801                 SDOPanel.SDOMonitorGrid.SetCellValue(gridRow, 0, str(idx))
       
   802                 SDOPanel.SDOMonitorGrid.SetCellValue(gridRow, 1, str(subIdx))
       
   803                 for col, key in [(2, "access"),
       
   804                                  (3, "type"),
       
   805                                  (4, "size"),
       
   806                                  (5, "name")]:
       
   807                     SDOPanel.SDOMonitorGrid.SetCellValue(gridRow, col, entry[key])
       
   808                 for col in range(7):
       
   809                     SDOPanel.SDOMonitorGrid.SetReadOnly(gridRow, col, True)
       
   810                     if col < 5 :
       
   811                         SDOPanel.SDOMonitorGrid.SetCellAlignment(\
       
   812                                         gridRow, col, wx.ALIGN_CENTER, wx.ALIGN_CENTER)
       
   813                 gridRow += 1
       
   814             
       
   815             SDOPanel.SDOMonitorGrid.Refresh()
       
   816 
       
   817 #-------------------------------------------------------------------------------
       
   818 #                 For PDO Mapping Panel
   658 # PDO Class UI  : Panel -> Choicebook (RxPDO, TxPDO) ->
   819 # PDO Class UI  : Panel -> Choicebook (RxPDO, TxPDO) ->
   659 #                 Notebook (PDO Index) -> Grid (PDO entry)
   820 #                 Notebook (PDO Index) -> Grid (PDO entry)
   660 # -------------------------------------------------------------------------------
   821 #-------------------------------------------------------------------------------
   661 class PDOPanelClass(wx.Panel):
   822 class PDOPanelClass(wx.Panel):
   662     def __init__(self, parent, controler):
   823     def __init__(self, parent, controler):
   663         """
   824         """
   664         Constructor
   825         Constructor
   665         @param parent: Reference to the parent EtherCATManagementTreebook class
   826         @param parent: Reference to the parent EtherCATManagementTreebook class
   666         @param controler: _EthercatSlaveCTN class in EthercatSlave.py
   827         @param controler: _EthercatSlaveCTN class in EthercatSlave.py
   667         """
   828         """
   668         wx.Panel.__init__(self, parent, -1)
   829         wx.Panel.__init__(self, parent, -1)
   669         self.Controler = controler
   830         self.Controler = controler
   670 
   831         sizer = wx.FlexGridSizer(cols=1, hgap=20,rows=3, vgap=20)
   671         self.PDOMonitoringEditorMainSizer = wx.BoxSizer(wx.VERTICAL)
   832         line = wx.StaticText(self, -1, "\n In order to control Ethercat device, user must select proper PDO set.\
   672         self.PDOMonitoringEditorInnerMainSizer = wx.FlexGridSizer(cols=1, hgap=10, rows=2, vgap=10)
   833                                         \n Each PDO sets describe operation modes (CSP, CSV, CST) supported by Ethercat devices.\
   673 
   834                                       \n\n PDOs have two types, RxPDO and TxPDO.\
   674         self.CallPDOChoicebook = PDOChoicebook(self, controler=self.Controler)
   835                                         \n  - RxPDO refers to the Receive Process Data Object. It means the control parameters which sent from controller to the EtherCAT Slave device.\
   675         self.PDOMonitoringEditorInnerMainSizer.Add(self.CallPDOChoicebook, wx.ALL)
   836                                         \n    In general, ControlWord (0x6040), Modes of Operations (0x6060), and TargetPosition (0x607A) are regarded as RxPDO.\
   676 
   837                                         \n  - TxPDO refers to the Transmit Process Data Object. It used to report status of EtherCAT Slave device to the controller in order to calibrate their next actuation.\
   677         self.PDOMonitoringEditorMainSizer.Add(self.PDOMonitoringEditorInnerMainSizer)
   838                                         \n    StatusWord (0x6041), Modes of Operation Display (0x6061), and ActualPosition (0x607A) include in TxPDO.\
   678 
   839                                       \n\n PDO Mapping feature provides available RxPDO and TxPDO sets which defined in Ethercat slave description XML.\
   679         self.SetSizer(self.PDOMonitoringEditorMainSizer)
   840                                         \n If there is no selection of PDO set, first set (0x1600, 0x1A00) will be chosen as default configuration.")
       
   841         
       
   842         sizer.Add(line)
       
   843         self.SetSizer(sizer)
       
   844 
       
   845 class RxPDOPanelClass(wx.Panel):
       
   846     def __init__(self, parent, controler):
       
   847         """
       
   848         Constructor
       
   849         @param parent: Reference to the parent EtherCATManagementTreebook class
       
   850         @param controler: _EthercatSlaveCTN class in EthercatSlave.py
       
   851         """
       
   852         wx.Panel.__init__(self, parent, -1)
       
   853         self.Controler = controler
       
   854 
       
   855         # add jblee
       
   856         #self.PDOIndexList = ["RxPDO"]
       
   857         self.PDOIndexList = []
       
   858         self.LoadPDOSelectData()
       
   859 
       
   860         #HSAHN ADD. 2015.7.26 PDO Select Function ADD
       
   861         self.Controler.CommonMethod.RequestPDOInfo()
       
   862         self.PDOcheckBox = []
       
   863         self.rx_pdo_entries = self.Controler.CommonMethod.GetRxPDOCategory()
       
   864         if len(self.rx_pdo_entries):
       
   865             for i in range(len(self.rx_pdo_entries)):
       
   866                 self.PDOcheckBox.append(wx.CheckBox(self, label=str(hex(self.rx_pdo_entries[i]['pdo_index'])), size=(120,15)))
       
   867                 if not self.Controler.SelectedRxPDOIndex and self.rx_pdo_entries[i]['sm'] is not None:
       
   868                     self.PDOcheckBox[-1].SetValue(True)
       
   869                     self.Controler.SelectedRxPDOIndex.append(int(self.PDOcheckBox[-1].GetLabel(), 0))
       
   870                     self.InitSavePDO()
       
   871                 elif self.rx_pdo_entries[i]['pdo_index'] in self.Controler.SelectedRxPDOIndex:
       
   872                     self.PDOIndexList.append(str(hex(self.rx_pdo_entries[i]['pdo_index'])))
       
   873                     self.PDOcheckBox[-1].SetValue(True)
       
   874                     
       
   875             for cb in self.PDOcheckBox:
       
   876                 self.Bind(wx.EVT_CHECKBOX, self.PDOSelectCheck, cb)
       
   877 
       
   878             self.PDOListBox = wx.StaticBox(self, label=_("PDO Mapping Select"))
       
   879             self.PDOListBoxSizer = wx.StaticBoxSizer(self.PDOListBox, orient=wx.HORIZONTAL)
       
   880             self.RxPDOListBox = wx.StaticBox(self, label=_("RxPDO"))
       
   881             self.RxPDOListBoxSizer = wx.StaticBoxSizer(self.RxPDOListBox, orient=wx.VERTICAL)
       
   882             self.RxPDOListBoxInnerSizer = wx.FlexGridSizer(cols=3, hgap=5, rows=10, vgap=5)
       
   883             self.RxPDOListBoxInnerSizer.AddMany(self.PDOcheckBox[0:len(self.rx_pdo_entries)])
       
   884             self.RxPDOListBoxSizer.Add(self.RxPDOListBoxInnerSizer)
       
   885             self.PDOListBoxSizer.Add(self.RxPDOListBoxSizer)
       
   886             self.PDOWarningText = wx.StaticText(self, -1,
       
   887                        "  *Warning*\n\n By default configuration, \n\n first mapping set is selected. \n\n Choose the PDO mapping!",
       
   888                        size=(220, -1))
       
   889             self.PDOListBoxSizer.Add(self.PDOWarningText)
       
   890 
       
   891             self.PDOMonitoringEditorMainSizer = wx.BoxSizer(wx.VERTICAL)
       
   892             self.PDOMonitoringEditorInnerMainSizer = wx.FlexGridSizer(cols=1, hgap=10, rows=2, vgap=10)
       
   893 
       
   894         
       
   895             self.CallPDOChoicebook = PDONoteBook(self, controler=self.Controler, name="Rx")
       
   896             self.PDOMonitoringEditorInnerMainSizer.Add(self.CallPDOChoicebook, wx.ALL)
       
   897 
       
   898             self.PDOInformationBox = wx.StaticBox(self, label=_("RxPDO Mapping List"))
       
   899             self.PDOInformationBoxSizer = wx.StaticBoxSizer(self.PDOInformationBox, orient=wx.VERTICAL)
       
   900             self.PDOInformationBoxSizer.Add(self.PDOMonitoringEditorInnerMainSizer)
       
   901 
       
   902             self.PDOMonitoringEditorMainSizer.Add(self.PDOListBoxSizer)
       
   903             self.PDOMonitoringEditorMainSizer.Add(self.PDOInformationBoxSizer)
       
   904             self.SetSizer(self.PDOMonitoringEditorMainSizer)
       
   905 
       
   906             # add jblee
       
   907             self.PDOExcludeCheck()
       
   908         else:
       
   909             sizer = wx.FlexGridSizer(cols=1, hgap=20,rows=3, vgap=20)
       
   910             line = wx.StaticText(self, -1, "\n  This device does not support RxPDO.")
       
   911         
       
   912             sizer.Add(line)
       
   913             self.SetSizer(sizer)
       
   914 
       
   915     def LoadPDOSelectData(self):
       
   916         RxPDOData = self.Controler.BaseParams.getRxPDO()
       
   917         RxPDOs = []
       
   918         if RxPDOData != "None":
       
   919             RxPDOs = RxPDOData.split()
       
   920         if RxPDOs :
       
   921             for RxPDO in RxPDOs :
       
   922                 self.Controler.SelectedRxPDOIndex.append(int(RxPDO, 0))
       
   923 
       
   924     def PDOSelectCheck(self, event):
       
   925         # add jblee for Save User Select
       
   926         cb = event.GetEventObject()
       
   927                          # prevent duplicated check
       
   928         if cb.GetValue() and int(cb.GetLabel(), 0) not in self.Controler.SelectedRxPDOIndex:
       
   929             self.Controler.SelectedRxPDOIndex.append(int(cb.GetLabel(), 0))
       
   930             self.PDOIndexList.append(cb.GetLabel())
       
   931         else:
       
   932             self.Controler.SelectedRxPDOIndex.remove(int(cb.GetLabel(), 0))
       
   933             self.PDOIndexList.remove(cb.GetLabel())
       
   934 
       
   935         data = ""
       
   936         for PDOIndex in self.PDOIndexList:            
       
   937             data = data + " " + PDOIndex
       
   938 
       
   939         self.Controler.BaseParams.setRxPDO(data)
       
   940         self.Controler.GetCTRoot().CTNRequestSave()
       
   941 
       
   942         self.PDOExcludeCheck()
       
   943 
       
   944     def InitSavePDO(self):
       
   945         for PDOIndex in self.Controler.SelectedRxPDOIndex:
       
   946             self.PDOIndexList.append(str(hex(PDOIndex)))
       
   947 
       
   948         data = ""
       
   949         for PDOIndex in self.PDOIndexList:            
       
   950             data = data + " " + PDOIndex
       
   951 
       
   952         self.Controler.BaseParams.setRxPDO(data)
       
   953 
       
   954     # 2016.06.21
       
   955     # add jblee for check exclude pdo list
       
   956     def PDOExcludeCheck(self):
       
   957         #files = os.listdir(self.Controler.CTNPath())
       
   958         #filepath = os.path.join(self.Controler.CTNPath(), "DataForPDO.txt")
       
   959         CurIndexs = self.Controler.SelectedRxPDOIndex
       
   960         for CB in self.PDOcheckBox:
       
   961             if len(CB.GetLabel().split()) > 1:
       
   962                 CB.Enable()
       
   963                 CB.SetLabel(CB.GetLabel().split()[0])
       
   964 
       
   965         for pdo in self.rx_pdo_entries:
       
   966             for CurIndex in CurIndexs:
       
   967                 if pdo["pdo_index"] == CurIndex:
       
   968                     ex_list = pdo["exclude_list"]
       
   969                     for ex_item in ex_list:
       
   970                         for CB in self.PDOcheckBox:
       
   971                             if CB.GetLabel() == hex(ex_item):
       
   972                                 CB.SetLabel(CB.GetLabel() + " (Excluded)")
       
   973                                 CB.Disable()
       
   974 
       
   975     def RefreshPDOInfo(self):
       
   976         pass
   680 
   977 
   681     def PDOInfoUpdate(self):
   978     def PDOInfoUpdate(self):
   682         """
   979         """
   683         Call RequestPDOInfo method and create Choicebook
   980         Call RequestPDOInfo method and create Choicebook
   684         """
   981         """
   685         self.Controler.CommonMethod.RequestPDOInfo()
   982         self.Controler.CommonMethod.RequestPDOInfo()
   686         self.CallPDOChoicebook.Destroy()
   983         self.CallPDOChoicebook.Destroy()
   687         self.CallPDOChoicebook = PDOChoicebook(self, controler=self.Controler)
   984         self.CallPDOChoicebook = PDOChoicebook(self, controler=self.Controler, name="Rx")
   688         self.Refresh()
   985         self.Refresh()
   689 
   986 
   690 
   987 class TxPDOPanelClass(wx.Panel):
   691 # -------------------------------------------------------------------------------
       
   692 #                    For PDO Choicebook (divide Tx, Rx PDO)
       
   693 # -------------------------------------------------------------------------------
       
   694 class PDOChoicebook(wx.Choicebook):
       
   695     def __init__(self, parent, controler):
   988     def __init__(self, parent, controler):
   696         """
   989         """
   697         Constructor
   990         Constructor
   698         @param parent: Reference to the parent PDOPanelClass class
   991         @param parent: Reference to the parent EtherCATManagementTreebook class
   699         @param controler: _EthercatSlaveCTN class in EthercatSlave.py
   992         @param controler: _EthercatSlaveCTN class in EthercatSlave.py
   700         """
   993         """
   701         wx.Choicebook.__init__(self, parent, id=-1, size=(500, 500), style=wx.CHB_DEFAULT)
   994         wx.Panel.__init__(self, parent, -1)
   702         self.Controler = controler
   995         self.Controler = controler
   703 
   996 
   704         RxWin = PDONoteBook(self, controler=self.Controler, name="Rx")
   997         # add jblee
   705         TxWin = PDONoteBook(self, controler=self.Controler, name="Tx")
   998         self.PDOIndexList = []
   706         self.AddPage(RxWin, "RxPDO")
   999         self.LoadPDOSelectData()
   707         self.AddPage(TxWin, "TxPDO")
  1000 
   708 
  1001         #HSAHN ADD. 2015.7.26 PDO Select Function ADD
       
  1002         self.Controler.CommonMethod.RequestPDOInfo()
       
  1003         self.PDOcheckBox = []
       
  1004         self.tx_pdo_entries = self.Controler.CommonMethod.GetTxPDOCategory()
       
  1005         if len(self.tx_pdo_entries):
       
  1006             for i in range(len(self.tx_pdo_entries)):
       
  1007                 self.PDOcheckBox.append(wx.CheckBox(self, label=str(hex(self.tx_pdo_entries[i]['pdo_index'])), size=(120,15)))
       
  1008                 if not self.Controler.SelectedTxPDOIndex and self.tx_pdo_entries[i]['sm'] is not None:
       
  1009                     self.PDOcheckBox[-1].SetValue(True)
       
  1010                     self.Controler.SelectedTxPDOIndex.append(int(self.PDOcheckBox[-1].GetLabel(), 0))
       
  1011                     self.InitSavePDO()
       
  1012                 elif self.tx_pdo_entries[i]['pdo_index'] in self.Controler.SelectedTxPDOIndex:
       
  1013                     self.PDOIndexList.append(str(hex(self.tx_pdo_entries[i]['pdo_index'])))
       
  1014                     self.PDOcheckBox[-1].SetValue(True)
       
  1015             for cb in self.PDOcheckBox:
       
  1016                 self.Bind(wx.EVT_CHECKBOX, self.PDOSelectCheck, cb)
       
  1017         
       
  1018             self.PDOListBox = wx.StaticBox(self, label=_("PDO Mapping Select"))
       
  1019             self.PDOListBoxSizer = wx.StaticBoxSizer(self.PDOListBox, orient=wx.HORIZONTAL)
       
  1020             self.TxPDOListBox = wx.StaticBox(self, label=_("TxPDO"))
       
  1021             self.TxPDOListBoxSizer = wx.StaticBoxSizer(self.TxPDOListBox, orient=wx.VERTICAL)
       
  1022             self.TxPDOListBoxInnerSizer = wx.FlexGridSizer(cols=3, hgap=5, rows=10, vgap=5)
       
  1023             self.TxPDOListBoxInnerSizer.AddMany(self.PDOcheckBox[0:len(self.tx_pdo_entries)])
       
  1024             self.TxPDOListBoxSizer.Add(self.TxPDOListBoxInnerSizer)
       
  1025             self.PDOListBoxSizer.Add(self.TxPDOListBoxSizer)
       
  1026             self.PDOWarningText = wx.StaticText(self, -1,
       
  1027                        "  *Warning*\n\n By default configuration, \n\n first mapping set is selected. \n\n Choose the PDO mapping!",
       
  1028                        size=(220, -1))
       
  1029             self.PDOListBoxSizer.Add(self.PDOWarningText)
       
  1030 
       
  1031             self.PDOMonitoringEditorMainSizer = wx.BoxSizer(wx.VERTICAL)
       
  1032             self.PDOMonitoringEditorInnerMainSizer = wx.FlexGridSizer(cols=1, hgap=10, rows=2, vgap=10)
       
  1033 
       
  1034             self.CallPDOChoicebook = PDONoteBook(self, controler=self.Controler, name="Tx")
       
  1035             self.PDOMonitoringEditorInnerMainSizer.Add(self.CallPDOChoicebook, wx.ALL)
       
  1036 
       
  1037             self.PDOInformationBox = wx.StaticBox(self, label=_("TxPDO Mapping List"))
       
  1038             self.PDOInformationBoxSizer = wx.StaticBoxSizer(self.PDOInformationBox, orient=wx.VERTICAL)
       
  1039             self.PDOInformationBoxSizer.Add(self.PDOMonitoringEditorInnerMainSizer)
       
  1040 
       
  1041             self.PDOMonitoringEditorMainSizer.Add(self.PDOListBoxSizer)
       
  1042             self.PDOMonitoringEditorMainSizer.Add(self.PDOInformationBoxSizer)
       
  1043             self.SetSizer(self.PDOMonitoringEditorMainSizer)
       
  1044 
       
  1045             # add jblee
       
  1046             self.PDOExcludeCheck()
       
  1047         else:
       
  1048             sizer = wx.FlexGridSizer(cols=1, hgap=20,rows=3, vgap=20)
       
  1049             line = wx.StaticText(self, -1, "\n  This device does not support TxPDO.")
       
  1050         
       
  1051             sizer.Add(line)
       
  1052             self.SetSizer(sizer)
       
  1053 
       
  1054     def LoadPDOSelectData(self):
       
  1055         TxPDOData = self.Controler.BaseParams.getTxPDO()
       
  1056         TxPDOs = []
       
  1057         if TxPDOData != "None":
       
  1058             TxPDOs = TxPDOData.split()
       
  1059         if TxPDOs :
       
  1060             for TxPDO in TxPDOs :
       
  1061                 self.Controler.SelectedTxPDOIndex.append(int(TxPDO, 0))
       
  1062 
       
  1063     def PDOSelectCheck(self, event):
       
  1064         # add jblee for Save User Select
       
  1065         cb = event.GetEventObject()
       
  1066                          # prevent duplicated check
       
  1067         if cb.GetValue() and int(cb.GetLabel(), 0) not in self.Controler.SelectedTxPDOIndex:
       
  1068             self.Controler.SelectedTxPDOIndex.append(int(cb.GetLabel(), 0))
       
  1069             self.PDOIndexList.append(cb.GetLabel())
       
  1070         else:
       
  1071             self.Controler.SelectedTxPDOIndex.remove(int(cb.GetLabel(), 0))
       
  1072             self.PDOIndexList.remove(cb.GetLabel())
       
  1073 
       
  1074         data = ""
       
  1075         for PDOIndex in self.PDOIndexList:            
       
  1076             data = data + " " + PDOIndex
       
  1077 
       
  1078         self.Controler.BaseParams.setTxPDO(data)
       
  1079         self.Controler.GetCTRoot().CTNRequestSave()
       
  1080 
       
  1081         self.PDOExcludeCheck()
       
  1082 
       
  1083     def InitSavePDO(self):
       
  1084         for PDOIndex in self.Controler.SelectedTxPDOIndex:
       
  1085             self.PDOIndexList.append(str(hex(PDOIndex)))
       
  1086 
       
  1087         data = ""
       
  1088         for PDOIndex in self.PDOIndexList:            
       
  1089             data = data + " " + PDOIndex
       
  1090 
       
  1091         self.Controler.BaseParams.setTxPDO(data)
       
  1092 
       
  1093     # 2016.06.21
       
  1094     # add jblee for check exclude pdo list
       
  1095     def PDOExcludeCheck(self):
       
  1096         CurIndexs = self.Controler.SelectedTxPDOIndex
       
  1097         for CB in self.PDOcheckBox:
       
  1098             if len(CB.GetLabel().split()) > 1:
       
  1099                 CB.Enable()
       
  1100                 CB.SetLabel(CB.GetLabel().split()[0])
       
  1101 
       
  1102         for pdo in self.tx_pdo_entries:
       
  1103             for CurIndex in CurIndexs:
       
  1104                 if pdo["pdo_index"] == CurIndex:
       
  1105                     ex_list = pdo["exclude_list"]
       
  1106                     for ex_item in ex_list:
       
  1107                         for CB in self.PDOcheckBox:
       
  1108                             if CB.GetLabel() == hex(ex_item):
       
  1109                                 CB.SetLabel(CB.GetLabel() + " (Excluded)")
       
  1110                                 CB.Disable()
       
  1111 
       
  1112     def PDOInfoUpdate(self):
       
  1113         """
       
  1114         Call RequestPDOInfo method and create Choicebook
       
  1115         """
       
  1116         self.Controler.CommonMethod.RequestPDOInfo()
       
  1117         self.CallPDOChoicebook.Destroy()
       
  1118         self.CallPDOChoicebook = PDOChoicebook(self, controler=self.Controler, name="Tx")
       
  1119         self.Refresh()
   709 
  1120 
   710 # -------------------------------------------------------------------------------
  1121 # -------------------------------------------------------------------------------
   711 #                    For PDO Notebook (divide PDO index)
  1122 #                    For PDO Notebook (divide PDO index)
   712 # -------------------------------------------------------------------------------
  1123 # -------------------------------------------------------------------------------
   713 class PDONoteBook(wx.Notebook):
  1124 class PDONoteBook(wx.Notebook):
   716         Constructor
  1127         Constructor
   717         @param parent: Reference to the parent PDOChoicebook class
  1128         @param parent: Reference to the parent PDOChoicebook class
   718         @param name: identifier whether RxPDO or TxPDO
  1129         @param name: identifier whether RxPDO or TxPDO
   719         @param controler: _EthercatSlaveCTN class in EthercatSlave.py
  1130         @param controler: _EthercatSlaveCTN class in EthercatSlave.py
   720         """
  1131         """
   721         wx.Notebook.__init__(self, parent, id=-1, size=(640, 400))
  1132         wx.Notebook.__init__(self, parent, id=-1, size=(600, 400))
   722         self.Controler = controler
  1133         self.Controler = controler
   723 
  1134 
   724         count = 0
  1135         count = 0
   725         page_texts = []
  1136         page_texts = []
   726 
       
   727         self.Controler.CommonMethod.RequestPDOInfo()
       
   728 
  1137 
   729         if name == "Tx":
  1138         if name == "Tx":
   730             # obtain pdo_info and pdo_entry
  1139             # obtain pdo_info and pdo_entry
   731             # pdo_info include (PDO index, name, number of entry)
  1140             # pdo_info include (PDO index, name, number of entry)
   732             pdo_info = self.Controler.CommonMethod.GetTxPDOCategory()
  1141             pdo_info = self.Controler.CommonMethod.GetTxPDOCategory()
   818                     self.SetCellAlignment(row_idx, col_idx, wx.ALIGN_LEFT, wx.ALIGN_CENTRE)
  1227                     self.SetCellAlignment(row_idx, col_idx, wx.ALIGN_LEFT, wx.ALIGN_CENTRE)
   819                 self.SetReadOnly(row_idx, col_idx, True)
  1228                 self.SetReadOnly(row_idx, col_idx, True)
   820                 self.SetRowSize(row_idx, 25)
  1229                 self.SetRowSize(row_idx, 25)
   821             start_value += 1
  1230             start_value += 1
   822 
  1231 
   823 
  1232 #-------------------------------------------------------------------------------
   824 # -------------------------------------------------------------------------------
  1233 #                    For MDP Main Panel         
   825 #                    For EEPROM Access Main Panel
  1234 #-------------------------------------------------------------------------------  
   826 #                 (This class explain EEPROM Access)
  1235 class MDPPanel(wx.Panel):
   827 # -------------------------------------------------------------------------------
       
   828 class EEPROMAccessPanel(wx.Panel):
       
   829     def __init__(self, parent, controler):
  1236     def __init__(self, parent, controler):
   830         """
  1237         """
   831         Constructor
  1238         Constructor
   832         @param parent: Reference to the parent EtherCATManagementTreebook class
  1239         @param parent: Reference to the parent EtherCATManagementTreebook class
   833         @param controler: _EthercatSlaveCTN class in EthercatSlave.py
  1240         @param controler: _EthercatSlaveCTN class in EthercatSlave.py
   834         """
  1241         """
   835         wx.Panel.__init__(self, parent, -1)
  1242         wx.Panel.__init__(self, parent, -1)
       
  1243         self.parent = parent
       
  1244         self.Controler = controler
       
  1245 
       
  1246         sizer = wx.FlexGridSizer(cols=3, hgap=20, rows=1, vgap=20)
       
  1247 
       
  1248         # Include Module ListBox
       
  1249         leftInnerSizer = wx.FlexGridSizer(cols=1, hgap=10,rows=2, vgap=10)
       
  1250         # Include Add, Delete Button
       
  1251         middleInnerSizer = wx.FlexGridSizer(cols=1, hgap=10,rows=2, vgap=10)
       
  1252         # Include Slot ListBox
       
  1253         rightInnerSizer = wx.FlexGridSizer(cols=1, hgap=10,rows=2, vgap=10)
       
  1254         
       
  1255         # Get Module Name as Array
       
  1256         # MDPArray = {SlaveName, [data0, data1, ...], SlotIndexIncrement, SlotPdoIncrement}
       
  1257         # data = [ModuleName, ModuleInfo, [PDOInfo1, PDOInfo2, ...]]
       
  1258         # PDOInfo = {Index, Name, BitSize, Access, PDOMapping, SubIndex, Type}
       
  1259         slave = self.Controler.CTNParent.GetSlave(self.Controler.GetSlavePos())
       
  1260         type_infos = slave.getType()
       
  1261         MDPArray = self.Controler.CTNParent.CTNParent.GetMDPInfos(type_infos)
       
  1262 
       
  1263         NameSet = []
       
  1264         if MDPArray:
       
  1265             for info in MDPArray[0][1]:
       
  1266                 NameSet.append(info[0])
       
  1267 
       
  1268         # Module ListBox
       
  1269         self.ModuleLabel = wx.StaticText(self, -1, "Module")
       
  1270         self.ModuleListBox = wx.ListBox(self, size = (150, 200), choices = NameSet)
       
  1271         #self.ModuleListBox = wx.ListBox(self, size = (150, 200), choices = [])
       
  1272         self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnModuleListBoxDCClick, self.ModuleListBox)
       
  1273 
       
  1274         # Button
       
  1275         self.AddButton = wx.Button(self, label=_(" Add Module  "))
       
  1276         self.DeleteButton = wx.Button(self, label=_("Delete Module"))
       
  1277 
       
  1278         # Button Event Mapping
       
  1279         self.AddButton.Bind(wx.EVT_BUTTON, self.OnAddButton)
       
  1280         self.DeleteButton.Bind(wx.EVT_BUTTON, self.OnDeleteButton)
       
  1281 
       
  1282         # Slot ListBox
       
  1283         self.SlotLabel = wx.StaticText(self, -1, "Slot")
       
  1284         self.SlotListBox = wx.ListBox(self, size = (150, 200))
       
  1285         self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnSlotListBoxDCClick, self.SlotListBox)
       
  1286         self.SelectModule = []
       
  1287 
       
  1288         # Add Object Each Sizer
       
  1289         leftInnerSizer.AddMany([self.ModuleLabel, self.ModuleListBox])
       
  1290         middleInnerSizer.Add(self.AddButton, 0, wx.TOP, 100)
       
  1291         middleInnerSizer.Add(self.DeleteButton, 0, wx.BOTTOM, 120)
       
  1292         rightInnerSizer.AddMany([self.SlotLabel, self.SlotListBox])
       
  1293         
       
  1294         sizer.AddMany([leftInnerSizer, middleInnerSizer, rightInnerSizer])
       
  1295         
       
  1296         self.SetSizer(sizer)
       
  1297 
       
  1298         self.InitMDPSet()
       
  1299 
       
  1300     def InitMDPSet(self):
       
  1301         files = os.listdir(self.Controler.CTNPath())
       
  1302         filepath = os.path.join(self.Controler.CTNPath(), "DataForMDP.txt")
       
  1303         try:
       
  1304             moduleDataFile = open(filepath, 'r')
       
  1305             lines = moduleDataFile.readlines()
       
  1306 
       
  1307             for line in lines:
       
  1308                 if line == "\n":
       
  1309                     continue
       
  1310                 module_pos = line.split()[-1]
       
  1311                 name_len_limit = len(line) - len(module_pos) - 2
       
  1312                 module_name = line[0:name_len_limit]
       
  1313                 
       
  1314                 self.SelectModule.append((module_name, int(module_pos)))
       
  1315 
       
  1316             localModuleInfo = []        
       
  1317             count = 1
       
  1318             for (item, pos) in self.SelectModule:
       
  1319                 slotString = "Slot %d %s : " % (count, item.split()[1]) + item.split()[0]
       
  1320                 localModuleInfo.append(slotString)
       
  1321                 count += 1
       
  1322             self.SlotListBox.SetItems(localModuleInfo)
       
  1323 
       
  1324         except:
       
  1325             moduleDataFile = open(filepath, 'w')
       
  1326 
       
  1327         moduleDataFile.close()
       
  1328 
       
  1329     def OnAddButton(self, event):
       
  1330         files = os.listdir(self.Controler.CTNPath())
       
  1331         filepath = os.path.join(self.Controler.CTNPath(), "DataForMDP.txt")
       
  1332         moduleDataFile = open(filepath, 'w')
       
  1333 
       
  1334         selectNum = self.ModuleListBox.GetSelection()
       
  1335         if selectNum >= 0:
       
  1336             selectStr = self.ModuleListBox.GetString(selectNum)
       
  1337             self.SelectModule.append((selectStr, selectNum))
       
  1338             localModuleInfo = []
       
  1339             count = 1
       
  1340             for (item, pos) in self.SelectModule:
       
  1341                 slotString = "Slot %d %s : " % (count, item.split()[1]) + item.split()[0]
       
  1342                 localModuleInfo.append(slotString)
       
  1343                 count += 1
       
  1344             self.SlotListBox.SetItems(localModuleInfo)
       
  1345 
       
  1346         moduleDataFile.close()
       
  1347         
       
  1348     def OnDeleteButton(self, event):
       
  1349         files = os.listdir(self.Controler.CTNPath())
       
  1350         filepath = os.path.join(self.Controler.CTNPath(), "DataForMDP.txt")
       
  1351         moduleDataFile = open(filepath, 'w')
       
  1352 
       
  1353         selectNum = self.SlotListBox.GetSelection()
       
  1354         if selectNum >= 0:
       
  1355             selectStr = self.SlotListBox.GetString(selectNum)
       
  1356             self.SelectModule.pop(selectNum)
       
  1357             localModuleInfo = []
       
  1358             count = 1
       
  1359             for (item, pos) in self.SelectModule:
       
  1360                 moduleDataFile.write(item + " " + str(pos) + "\n")
       
  1361                 slotString = "Slot %d %s : " % (count, item.split()[1]) + item.split()[0]
       
  1362                 localModuleInfo.append(slotString)
       
  1363                 count += 1
       
  1364             self.SlotListBox.SetItems(localModuleInfo)
       
  1365 
       
  1366         moduleDataFile.close()
       
  1367 
       
  1368     def OnModuleListBoxDCClick(self, event):
       
  1369         files = os.listdir(self.Controler.CTNPath())
       
  1370         filepath = os.path.join(self.Controler.CTNPath(), "DataForMDP.txt")
       
  1371         moduleDataFile = open(filepath, 'w')
       
  1372 
       
  1373         selectNum = self.ModuleListBox.GetSelection()
       
  1374         if selectNum >= 0:
       
  1375             selectStr = self.ModuleListBox.GetString(selectNum)
       
  1376             self.SelectModule.append((selectStr, selectNum))
       
  1377             localModuleInfo = []
       
  1378             count = 1
       
  1379             for (item, pos) in self.SelectModule:
       
  1380                 moduleDataFile.write(item + " " + str(pos) + "\n")
       
  1381                 slotString = "Slot %d %s : " % (count, item.split()[1]) + item.split()[0]
       
  1382                 localModuleInfo.append(slotString)
       
  1383                 module = self.Controler.CTNParent.CTNParent.GetSelectModule(pos)
       
  1384                 self.Controler.CommonMethod.SavePDOData(module)
       
  1385                 count += 1
       
  1386             self.SlotListBox.SetItems(localModuleInfo)
       
  1387 
       
  1388         moduleDataFile.close()
       
  1389 
       
  1390     def OnSlotListBoxDCClick(self, event):
       
  1391         files = os.listdir(self.Controler.CTNPath())
       
  1392         filepath = os.path.join(self.Controler.CTNPath(), "DataForMDP.txt")
       
  1393         moduleDataFile = open(filepath, 'w')
       
  1394 
       
  1395         selectNum = self.SlotListBox.GetSelection()
       
  1396         if selectNum >= 0:
       
  1397             selectStr = self.SlotListBox.GetString(selectNum)
       
  1398             self.SelectModule.pop(selectNum)
       
  1399             localModuleInfo = []
       
  1400             count = 1
       
  1401             for (item, pos) in self.SelectModule:
       
  1402                 moduleDataFile.write(item + " " + str(pos) + "\n")
       
  1403                 slotString = "Slot %d %s : " % (count, item.split()[1]) + item.split()[0]
       
  1404                 localModuleInfo.append(slotString)
       
  1405                 count += 1
       
  1406             self.SlotListBox.SetItems(localModuleInfo)
       
  1407 
       
  1408         moduleDataFile.close()
       
  1409 
       
  1410 # -------------------------------------------------------------------------------
       
  1411 #                    For EEPROM Access Main Panel
       
  1412 #                 (This class explain EEPROM Access)
       
  1413 # -------------------------------------------------------------------------------
       
  1414 class EEPROMAccessPanel(wx.Panel):
       
  1415     def __init__(self, parent, controler):
       
  1416         """
       
  1417         Constructor
       
  1418         @param parent: Reference to the parent EtherCATManagementTreebook class
       
  1419         @param controler: _EthercatSlaveCTN class in EthercatSlave.py
       
  1420         """
       
  1421         wx.Panel.__init__(self, parent, -1)
   836         sizer = wx.FlexGridSizer(cols=1, hgap=20, rows=3, vgap=20)
  1422         sizer = wx.FlexGridSizer(cols=1, hgap=20, rows=3, vgap=20)
   837 
  1423 
   838         line = wx.StaticText(self, -1, "\n  EEPROM Access is composed to SmartView and HexView. \
  1424         line = wx.StaticText(self, -1, "\n  EEPROM Access is composed to SmartView and HexView. \
   839                                               \n\n   - SmartView shows Config Data, Device Identity, Mailbox settings, etc. \
  1425                                               \n\n   - SmartView shows Config Data, Device Identity, Mailbox settings, etc. \
   840                                               \n\n   - HexView shows EEPROM's contents.")
  1426                                               \n\n   - HexView shows EEPROM's contents.")
   856         """
  1442         """
   857         wx.Panel.__init__(self, parent, -1)
  1443         wx.Panel.__init__(self, parent, -1)
   858         self.parent = parent
  1444         self.parent = parent
   859         self.Controler = controler
  1445         self.Controler = controler
   860 
  1446 
   861         self.PDIType = {
  1447         # PDI Type 1, 13 unknown Type, Fix Future
   862             0: ['none', '00000000'],
  1448         self.PDIType = {0  :['none', '00000000'], 
   863             4: ['Digital I/O', '00000100'],
  1449                         1  :['unknown', '00000000'],
   864             5: ['SPI Slave', '00000101'],
  1450                         4  :['Digital I/O', '00000100'],
   865             7: ['EtherCAT Bridge (port3)', '00000111'],
  1451                         5  :['SPI Slave', '00000101'],
   866             8: ['uC async. 16bit', '00001000'],
  1452                         7  :['EtherCAT Bridge (port3)', '00000111'],
   867             9: ['uC async. 8bit', '00001001'],
  1453                         8  :['uC async. 16bit', '00001000'],
   868             10: ['uC sync. 16bit', '00001010'],
  1454                         9  :['uC async. 8bit', '00001001'],
   869             11: ['uC sync. 8bit', '00001011'],
  1455                         10 :['uC sync. 16bit', '00001010'],
   870             16: ['32 Digtal Input and 0 Digital Output', '00010000'],
  1456                         11 :['uC sync. 8bit', '00001011'],
   871             17: ['24 Digtal Input and 8 Digital Output', '00010001'],
  1457                         13 :['unknown', '00000000'],
   872             18: ['16 Digtal Input and 16 Digital Output', '00010010'],
  1458                         16 :['32 Digtal Input and 0 Digital Output', '00010000'],
   873             19: ['8 Digtal Input and 24 Digital Output', '00010011'],
  1459                         17 :['24 Digtal Input and 8 Digital Output', '00010001'],
   874             20: ['0 Digtal Input and 32 Digital Output', '00010100'],
  1460                         18 :['16 Digtal Input and 16 Digital Output','00010010'],
   875             128: ['On-chip bus', '11111111']
  1461                         19 :['8 Digtal Input and 24 Digital Output', '00010011'],
   876         }
  1462                         20 :['0 Digtal Input and 32 Digital Output', '00010100'],
       
  1463                         128:['On-chip bus', '11111111']
       
  1464                         }
   877 
  1465 
   878         sizer = wx.FlexGridSizer(cols=1, hgap=5, rows=2, vgap=5)
  1466         sizer = wx.FlexGridSizer(cols=1, hgap=5, rows=2, vgap=5)
   879         button_sizer = wx.FlexGridSizer(cols=2, hgap=5, rows=1, vgap=5)
  1467         button_sizer = wx.FlexGridSizer(cols=2, hgap=5, rows=1, vgap=5)
   880 
  1468 
   881         for button, mapping_method in [("Write EEPROM", self.WriteToEEPROM),
  1469         for button, mapping_method in [("Write EEPROM", self.WriteToEEPROM),
   933         """
  1521         """
   934         Refresh displayed data based on slave EEPROM and save binary file through dialog
  1522         Refresh displayed data based on slave EEPROM and save binary file through dialog
   935         @param event : wx.EVT_BUTTON object
  1523         @param event : wx.EVT_BUTTON object
   936         """
  1524         """
   937         # Check whether beremiz connected or not.
  1525         # Check whether beremiz connected or not.
   938         check_connect_flag = self.Controler.CommonMethod.CheckConnect(False)
  1526         # If this method is called cyclically, set the cyclic flag true
       
  1527         check_connect_flag = self.Controler.CommonMethod.CheckConnect(cyclic_flag = False)
   939         if check_connect_flag:
  1528         if check_connect_flag:
   940             self.SiiBinary = self.Controler.CommonMethod.LoadData()
  1529             self.SiiBinary = self.Controler.CommonMethod.LoadData()
   941             self.SetEEPROMData()
  1530             self.SetEEPROMData()
   942             dialog = wx.FileDialog(self, _("Save as..."), os.getcwd(),
  1531             dialog = wx.FileDialog(self, _("Save as..."), os.getcwd(),
   943                                    "slave0.bin",  _("bin files (*.bin)|*.bin|All files|*.*"),
  1532                                    "slave0.bin",  _("bin files (*.bin)|*.bin|All files|*.*"),
  1255         Load EEPROM data from slave and refresh Hex View grid
  1844         Load EEPROM data from slave and refresh Hex View grid
  1256         Binded to 'Sii Upload' button.
  1845         Binded to 'Sii Upload' button.
  1257         @param event : wx.EVT_BUTTON object
  1846         @param event : wx.EVT_BUTTON object
  1258         """
  1847         """
  1259         # Check whether beremiz connected or not.
  1848         # Check whether beremiz connected or not.
  1260         check_connect_flag = self.Controler.CommonMethod.CheckConnect(False)
  1849         # If this method is called cyclically, set the cyclic flag true
       
  1850         check_connect_flag = self.Controler.CommonMethod.CheckConnect(cyclic_flag = False)
  1261         if check_connect_flag:
  1851         if check_connect_flag:
  1262             # load from EEPROM data and parsing
  1852             # load from EEPROM data and parsing
  1263             self.SiiBinary = self.Controler.CommonMethod.LoadData()
  1853             self.SiiBinary = self.Controler.CommonMethod.LoadData()
  1264             self.HexCode, self.HexRow, self.HexCol = self.Controler.CommonMethod.HexRead(self.SiiBinary)
  1854             self.HexCode, self.HexRow, self.HexCol = self.Controler.CommonMethod.HexRead(self.SiiBinary)
  1265             self.UpdateSiiGridTable(self.HexRow, self.HexCol)
  1855             self.UpdateSiiGridTable(self.HexRow, self.HexCol)
  1272         Binded to 'Sii Download' button.
  1862         Binded to 'Sii Download' button.
  1273         @param event : wx.EVT_BUTTON object
  1863         @param event : wx.EVT_BUTTON object
  1274         """
  1864         """
  1275         # Check whether beremiz connected or not,
  1865         # Check whether beremiz connected or not,
  1276         # and whether status is "Started" or not.
  1866         # and whether status is "Started" or not.
  1277         check_connect_flag = self.Controler.CommonMethod.CheckConnect(False)
  1867         # If this method is called cyclically, set the cyclic flag true
       
  1868         check_connect_flag = self.Controler.CommonMethod.CheckConnect(cyclic_flag = False)
  1278         if check_connect_flag:
  1869         if check_connect_flag:
  1279             status, _log_count = self.Controler.GetCTRoot()._connector.GetPLCstatus()
  1870             status, _log_count = self.Controler.GetCTRoot()._connector.GetPLCstatus()
  1280             if status is not PlcStatus.Started:
  1871             if status is not PlcStatus.Started:
  1281                 self.Controler.CommonMethod.SiiWrite(self.SiiBinary)
  1872                 self.Controler.CommonMethod.SiiWrite(self.SiiBinary)
  1282                 self.Controler.CommonMethod.Rescan()
  1873                 self.Controler.CommonMethod.Rescan()
  1437         Declare initial data.
  2028         Declare initial data.
  1438         """
  2029         """
  1439         # flag for compact view
  2030         # flag for compact view
  1440         self.CompactFlag = False
  2031         self.CompactFlag = False
  1441 
  2032 
  1442         # main grid의 rows and cols
  2033         # main grid rows and cols
  1443         self.MainRow = [512, 512, 512, 512]
  2034         self.MainRow = [512, 512, 512, 512]
  1444         self.MainCol = 4
  2035         self.MainCol = 4
  1445 
  2036 
  1446         # main grids' data range
  2037         # main grids' data range
  1447         self.PageRange = []
  2038         self.PageRange = []
  1673         Handle the click event of the 'Reload' button.
  2264         Handle the click event of the 'Reload' button.
  1674         Get the data from registers again, and update the table.
  2265         Get the data from registers again, and update the table.
  1675         @param event: wx.EVT_BUTTON object
  2266         @param event: wx.EVT_BUTTON object
  1676         """
  2267         """
  1677         # Check whether beremiz connected or not.
  2268         # Check whether beremiz connected or not.
  1678         check_connect_flag = self.Controler.CommonMethod.CheckConnect(False)
  2269         # If this method is called cyclically, set the cyclic flag true
       
  2270         check_connect_flag = self.Controler.CommonMethod.CheckConnect(cyclic_flag = False)
  1679         if check_connect_flag:
  2271         if check_connect_flag:
  1680             self.LoadData()
  2272             self.LoadData()
  1681             self.BasicSetData()
  2273             self.BasicSetData()
  1682             self.ParseData()
  2274             self.ParseData()
  1683             # set data into UI
  2275             # set data into UI
  2057         """
  2649         """
  2058         Constructor
  2650         Constructor
  2059         @param parent: wx.ScrollWindow object
  2651         @param parent: wx.ScrollWindow object
  2060         @Param controler: _EthercatSlaveCTN class in EthercatSlave.py
  2652         @Param controler: _EthercatSlaveCTN class in EthercatSlave.py
  2061         """
  2653         """
  2062         wx.Panel.__init__(self, parent, -1, (0, 0),
  2654         wx.Panel.__init__(self, parent)
  2063                           size=wx.DefaultSize, style=wx.SUNKEN_BORDER)
       
  2064         self.Controler = controler
  2655         self.Controler = controler
  2065         self.parent = parent
  2656         self.parent = parent
  2066         self.StaticBox = {}
  2657         self.StaticBox = {}
  2067         self.StaticText = {}
  2658         self.StaticText = {}
  2068         self.TextCtrl = {}
  2659         self.TextCtrl = {}
  2069 
  2660 
  2070         # ----------------------- Main Sizer and Update Button --------------------------------------------
  2661         # ----------------------- Main Sizer and Update Button --------------------------------------------
  2071         self.MasterStateSizer = {"main": wx.BoxSizer(wx.VERTICAL)}
  2662         self.MasterStateSizer = {"main": wx.BoxSizer(wx.VERTICAL)}
  2072         for key, attr in [
  2663         for key, attr in [
  2073                 ("innerMain",           [1, 10, 2, 10]),
  2664             ("innerTop",            [2, 10, 1, 10]),
  2074                 ("innerTopHalf",        [2, 10, 1, 10]),
  2665             ("innerMiddle",         [1, 10, 1, 10]),
  2075                 ("innerBottomHalf",     [2, 10, 1, 10]),
  2666             ("innerBottom",         [1, 10, 1, 10]),
  2076                 ("innerMasterState",    [2, 10, 3, 10]),
  2667             ("innerMasterState",    [2, 10, 3, 10]),
  2077                 ("innerDeviceInfo",     [4, 10, 3, 10]),
  2668             ("innerDeviceInfo",     [4, 10, 3, 10]),
  2078                 ("innerFrameInfo",      [4, 10, 5, 10])]:
  2669             ("innerFrameInfo",      [4, 10, 5, 10]),
       
  2670             ("innerSlaveInfo",     [1, 10, 2, 10])]:
  2079             self.MasterStateSizer[key] = wx.FlexGridSizer(cols=attr[0], hgap=attr[1], rows=attr[2], vgap=attr[3])
  2671             self.MasterStateSizer[key] = wx.FlexGridSizer(cols=attr[0], hgap=attr[1], rows=attr[2], vgap=attr[3])
  2080 
  2672 
  2081         self.UpdateButton = wx.Button(self, label=_('Update'))
  2673         self.MSUpdateButton = wx.Button(self, label=_("Update"))
  2082         self.UpdateButton.Bind(wx.EVT_BUTTON, self.OnButtonClick)
  2674         self.MSUpdateButton.Bind(wx.EVT_BUTTON, self.OnMSUpdateButtonClick)
  2083 
  2675         self.SIUpdateButton = wx.Button(self, label=_("Update"))
  2084         for key, label in [
  2676         self.SIUpdateButton.Bind(wx.EVT_BUTTON, self.OnSIUpdateButtonClick)
  2085                 ('masterState', 'EtherCAT Master State'),
  2677         
  2086                 ('deviceInfo', 'Ethernet Network Card Information'),
  2678         for key, label in [                
  2087                 ('frameInfo', 'Network Frame Information')]:
  2679             ("masterState", "EtherCAT Master State"),
       
  2680             ("deviceInfo", "Ethernet Network Card Information"),
       
  2681             ("frameInfo", "Network Frame Information"),
       
  2682             ("slaveInfo", "Slave Information")]: 
  2088             self.StaticBox[key] = wx.StaticBox(self, label=_(label))
  2683             self.StaticBox[key] = wx.StaticBox(self, label=_(label))
  2089             self.MasterStateSizer[key] = wx.StaticBoxSizer(self.StaticBox[key])
  2684             self.MasterStateSizer[key] = wx.StaticBoxSizer(self.StaticBox[key])
  2090 
  2685 
  2091         # ----------------------- Master State -----------------------------------------------------------
  2686         # ----------------------- Master State -----------------------------------------------------------
  2092         for key, label in [
  2687         for key, label in [
  2112 
  2707 
  2113         self.MasterStateSizer['deviceInfo'].AddSizer(self.MasterStateSizer['innerDeviceInfo'])
  2708         self.MasterStateSizer['deviceInfo'].AddSizer(self.MasterStateSizer['innerDeviceInfo'])
  2114 
  2709 
  2115         # ----------------------- Network Frame Information -----------------------------------------------
  2710         # ----------------------- Network Frame Information -----------------------------------------------
  2116         for key, label in [
  2711         for key, label in [
  2117                 ('Tx frame rate [1/s]', 'Tx Frame Rate [1/s]:'),
  2712             ("Tx frame rate [1/s]", "Tx Frame Rate [1/s]:"), 
  2118                 ('Rx frame rate [1/s]', 'Tx Rate [kByte/s]:'),
  2713             ("Tx rate [KByte/s]", "Tx Rate [KByte/s]:"), 
  2119                 ('Loss rate [1/s]', 'Loss Rate [1/s]:'),
  2714             ("Rx frame rate [1/s]", "Rx Frame Rate [1/s]:"), 
  2120                 ('Frame loss [%]', 'Frame Loss [%]:')]:
  2715             ("Rx rate [KByte/s]", "Rx Rate [KByte/s]:"), 
       
  2716             ("Loss rate [1/s]", "Loss Rate [1/s]:"),
       
  2717             ("Frame loss [%]", "Frame Loss [%]:")]:
  2121             self.StaticText[key] = wx.StaticText(self, label=_(label))
  2718             self.StaticText[key] = wx.StaticText(self, label=_(label))
  2122             self.MasterStateSizer['innerFrameInfo'].Add(self.StaticText[key])
  2719             self.MasterStateSizer['innerFrameInfo'].Add(self.StaticText[key])
  2123             self.TextCtrl[key] = {}
  2720             self.TextCtrl[key] = {}
  2124             for index in ['0', '1', '2']:
  2721             for index in ['0', '1', '2']:
  2125                 self.TextCtrl[key][index] = wx.TextCtrl(self, size=wx.Size(130, 24), style=wx.TE_READONLY)
  2722                 self.TextCtrl[key][index] = wx.TextCtrl(self, size=wx.Size(130, 24), style=wx.TE_READONLY)
  2126                 self.MasterStateSizer['innerFrameInfo'].Add(self.TextCtrl[key][index])
  2723                 self.MasterStateSizer['innerFrameInfo'].Add(self.TextCtrl[key][index])
  2127 
  2724 
  2128         self.MasterStateSizer['frameInfo'].AddSizer(self.MasterStateSizer['innerFrameInfo'])
  2725         self.MasterStateSizer['frameInfo'].AddSizer(self.MasterStateSizer['innerFrameInfo'])
  2129 
  2726 
       
  2727         # ------------------------------- Slave Information  -----------------------------------------------
       
  2728         self.SITreeListCtrl = SITreeListCtrl(self, self.Controler) 
       
  2729         self.MasterStateSizer["innerSlaveInfo"].AddMany([self.SIUpdateButton,
       
  2730                                                                self.SITreeListCtrl])
       
  2731         self.MasterStateSizer["slaveInfo"].AddSizer(
       
  2732                 self.MasterStateSizer["innerSlaveInfo"]) 
       
  2733 
  2130         # --------------------------------- Main Sizer ----------------------------------------------------
  2734         # --------------------------------- Main Sizer ----------------------------------------------------
       
  2735         self.MasterStateSizer["main"].Add(self.MSUpdateButton)
  2131         for key, sub, in [
  2736         for key, sub, in [
  2132                 ('innerTopHalf', ['masterState', 'deviceInfo']),
  2737             ("innerTop", [
  2133                 ('innerBottomHalf', ['frameInfo']),
  2738                     "masterState", "deviceInfo"]),
  2134                 ('innerMain', ['innerTopHalf', 'innerBottomHalf'])
  2739             ("innerMiddle", [
  2135         ]:
  2740                     "frameInfo"]),
       
  2741             ("innerBottom", [
       
  2742                     "slaveInfo"]),
       
  2743             ("main", [
       
  2744                     "innerTop", "innerMiddle", "innerBottom"])]:
  2136             for key2 in sub:
  2745             for key2 in sub:
  2137                 self.MasterStateSizer[key].AddSizer(self.MasterStateSizer[key2])
  2746                 self.MasterStateSizer[key].AddSizer(self.MasterStateSizer[key2])
  2138 
  2747 
  2139         self.MasterStateSizer['main'].AddSizer(self.UpdateButton)
  2748         self.SetSizer(self.MasterStateSizer["main"])
  2140         self.MasterStateSizer['main'].AddSizer(self.MasterStateSizer['innerMain'])
  2749     
  2141 
  2750     def OnMSUpdateButtonClick(self, event):
  2142         self.SetSizer(self.MasterStateSizer['main'])
       
  2143 
       
  2144     def OnButtonClick(self, event):
       
  2145         """
  2751         """
  2146         Handle the event of the 'Update' button.
  2752         Handle the event of the 'Update' button.
  2147         Update the data of the master state.
  2753         Update the data of the master state.
  2148         @param event: wx.EVT_BUTTON object
  2754         @param event: wx.EVT_BUTTON object
  2149         """
  2755         """
  2157                             self.TextCtrl[key][index].SetValue(self.MasterState[key][int(index)])
  2763                             self.TextCtrl[key][index].SetValue(self.MasterState[key][int(index)])
  2158                     else:
  2764                     else:
  2159                         self.TextCtrl[key].SetValue(self.MasterState[key][0])
  2765                         self.TextCtrl[key].SetValue(self.MasterState[key][0])
  2160         else:
  2766         else:
  2161             self.Controler.CommonMethod.CreateErrorDialog(_('PLC not connected!'))
  2767             self.Controler.CommonMethod.CreateErrorDialog(_('PLC not connected!'))
       
  2768 
       
  2769     def OnSIUpdateButtonClick(self, event):
       
  2770         """
       
  2771         Handle the event of the radio box in the slave information 
       
  2772         @param event: wx.EVT_RADIOBOX object
       
  2773         """
       
  2774         if self.Controler.GetCTRoot()._connector is not None:
       
  2775             self.SITreeListCtrl.UpdateSI()
       
  2776         
       
  2777         else :
       
  2778             self.Controler.CommonMethod.CreateErrorDialog('PLC not connected!')
       
  2779     
       
  2780 
       
  2781 #-------------------------------------------------------------------------------
       
  2782 #                    For Slave Information  Panel
       
  2783 #------------------------------------------------------------------------------- 
       
  2784 class SITreeListCtrl(wx.Panel):
       
  2785     
       
  2786     EC_Addrs = ["0x0300", "0x0302", "0x0304", "0x0306", "0x0301", "0x0303", "0x0305", 
       
  2787                 "0x0307", "0x0308", "0x0309", "0x030A", "0x030B", "0x030C", "0x030D",
       
  2788                 "0x0310", "0x0311", "0x0312", "0x0313", "0x0442", "0x0443"]
       
  2789 
       
  2790     def __init__(self, parent, controler):
       
  2791         """
       
  2792         Constructor
       
  2793         @param parent: Reference to the MasterStatePanel class
       
  2794         @param Controler: _EthercatCTN class in EthercatMaster.py
       
  2795         """
       
  2796 
       
  2797         wx.Panel.__init__(self, parent, -1, size=wx.Size(750, 350))
       
  2798 
       
  2799         self.Controler=controler
       
  2800         
       
  2801         self.Tree = wx.gizmos.TreeListCtrl(self, -1, size=wx.Size(750,350), 
       
  2802                                                             style=wx.TR_HAS_BUTTONS
       
  2803                                                             |wx.TR_HIDE_ROOT
       
  2804                                                             |wx.TR_ROW_LINES
       
  2805                                                             |wx.TR_COLUMN_LINES
       
  2806                                                             |wx.TR_FULL_ROW_HIGHLIGHT)
       
  2807         for label, width in [
       
  2808                 ("name",        400),
       
  2809                 ("position",    100),
       
  2810                 ("state",       100),
       
  2811                 ("error",       100)]:
       
  2812             self.Tree.AddColumn(label, width=width)
       
  2813         
       
  2814         self.Tree.SetMainColumn(0)
       
  2815         
       
  2816     def UpdateSI(self):
       
  2817         """
       
  2818         Update the data of the slave information.
       
  2819         """
       
  2820         position, not_used, state, not_used, name = range(5)
       
  2821         
       
  2822         slave_node = []
       
  2823         slave_info_list = []
       
  2824         error_counter= []
       
  2825         
       
  2826         # get slave informations (name, position, state)
       
  2827         slaves_infos = self.Controler.CommonMethod.GetSlaveStateFromSlave()
       
  2828         slave_info_lines = slaves_infos.splitlines()
       
  2829         
       
  2830         for line in slave_info_lines:
       
  2831             slave_info_list.append(line.split(None,4))
       
  2832 
       
  2833         slave_num = len(slave_info_lines)
       
  2834         
       
  2835         reg_info = []
       
  2836         for ec in self.EC_Addrs:
       
  2837             reg_info.append(ec + ",0x001")
       
  2838         
       
  2839         # get error counts of slaves
       
  2840         err_count_list = self.Controler.CommonMethod.MultiRegRead(slave_num, reg_info)
       
  2841                 
       
  2842         self.Tree.DeleteAllItems()
       
  2843         
       
  2844         root = self.Tree.AddRoot("") 
       
  2845         ec_list_idx = 0
       
  2846 
       
  2847         for slave_idx in range(slave_num):
       
  2848             slave_node = self.Tree.AppendItem(root, "")
       
  2849             
       
  2850             # set name, postion, state 
       
  2851             col_num = 0 
       
  2852             for info_idx in [name, position, state]:
       
  2853                 self.Tree.SetItemText(slave_node, 
       
  2854                                       slave_info_list[slave_idx][info_idx], col_num)
       
  2855                 col_num += 1
       
  2856 
       
  2857             error_counter = {}
       
  2858             ec_idx = 0
       
  2859             
       
  2860             # set error counter's name and default value 
       
  2861             for ec, sub_ecs in [("Port Error Counters 0/1/2/3",[
       
  2862                                     "Invaild Frame Counter 0/1/2/3",
       
  2863                                     "RX Error Counter 0/1/2/3"]),
       
  2864                                 ("Forward RX Error Counter 0/1/2/3", []),       
       
  2865                                 ("ECAT Processing Unit Error Counter", []),
       
  2866                                 ("PDI Error Counter", []),
       
  2867                                 ("Lost Link Counter 0/1/2/3", []),
       
  2868                                 ("Watchdog Counter Process Data", []),
       
  2869                                 ("Watchdog Counter PDI", [])]:
       
  2870                 ec_sub_idx = 0
       
  2871                 ec_name = ec
       
  2872                 tree_node = self.Tree.AppendItem(slave_node, "%s" % ec)
       
  2873                 
       
  2874                 if ec_name.find("0/1/2/3") > 0:
       
  2875                     num_ports = 4
       
  2876                     err_count = [0, 0, 0, 0]
       
  2877                 else:
       
  2878                     num_ports = 1
       
  2879                     err_count = [0]
       
  2880 
       
  2881                 error_counter[(ec_idx, ec_sub_idx)] = {
       
  2882                         "name": ec_name,
       
  2883                         "tree_node": tree_node,
       
  2884                         "num_ports": num_ports,
       
  2885                         "err_count": err_count}
       
  2886 
       
  2887                 for sub_ec in sub_ecs:
       
  2888                     ec_sub_idx += 1
       
  2889                     ec_name = sub_ec
       
  2890                     tree_node = self.Tree.AppendItem(\
       
  2891                         error_counter[(ec_idx, 0)]["tree_node"], 
       
  2892                             "%s" % sub_ec)
       
  2893                     
       
  2894                     if ec_name.find("0/1/2/3") > 0:
       
  2895                         num_ports = 4
       
  2896                         err_count = [0, 0, 0, 0]
       
  2897                     else:
       
  2898                         num_ports = 1
       
  2899                         err_count = [0]
       
  2900 
       
  2901                     error_counter[(ec_idx, ec_sub_idx)] = {
       
  2902                             "name": ec_name,
       
  2903                             "tree_node": tree_node, 
       
  2904                             "num_ports": num_ports,
       
  2905                             "err_count": err_count}
       
  2906 
       
  2907                     for port_num in range(num_ports):
       
  2908                         try:
       
  2909                             error_counter[(ec_idx, ec_sub_idx)]["err_count"][port_num] += \
       
  2910                                     int(err_count_list[ec_list_idx].split(",")[2], 16)
       
  2911                         except:
       
  2912                             error_counter[(ec_idx, ec_sub_idx)]["err_count"][port_num] = -1
       
  2913 
       
  2914                         ec_list_idx += 1
       
  2915                 
       
  2916                 if ec_sub_idx > 0:
       
  2917                     for port_num in range(num_ports):
       
  2918                         err_sum = 0
       
  2919                         for sub_idx in range(1, ec_sub_idx+1):
       
  2920                             err_sum += error_counter[(ec_idx, sub_idx)]\
       
  2921                                                 ["err_count"][port_num]
       
  2922                         error_counter[(ec_idx, 0)]["err_count"][port_num] = err_sum
       
  2923                         
       
  2924                 else:
       
  2925                     for port_num in range(num_ports):
       
  2926                         try:
       
  2927                             error_counter[(ec_idx, ec_sub_idx)]["err_count"][port_num] += \
       
  2928                                     int(err_count_list[ec_list_idx].split(",")[2], 16)
       
  2929                         except:
       
  2930                             error_counter[(ec_idx, ec_sub_idx)]["err_count"][port_num] = -1
       
  2931                         ec_list_idx += 1
       
  2932 
       
  2933                 ec_idx += 1
       
  2934             
       
  2935             # set texts in "error" column. 
       
  2936             ec_info_list = error_counter.items()
       
  2937             ec_info_list.sort()
       
  2938             
       
  2939             err_checker = "none"
       
  2940            
       
  2941             for (idx, sub_idx), ec_info in ec_info_list:
       
  2942                 ec_text = ""
       
  2943                 for port_num in range(ec_info["num_ports"]):
       
  2944                     if ec_info["err_count"][port_num] != 0:
       
  2945                         err_checker = "occurred"
       
  2946 
       
  2947                     if ec_info["err_count"][port_num] < 0:
       
  2948                         ec_text = "reg I/O error"
       
  2949                     else:
       
  2950                         ec_text = ec_text + "%d/" % ec_info["err_count"][port_num]
       
  2951 
       
  2952                 ec_text = ec_text.strip("/")
       
  2953                 
       
  2954                 self.Tree.SetItemText(ec_info["tree_node"], ec_text, col_num)
       
  2955             
       
  2956             self.Tree.SetItemText(slave_node, err_checker, col_num)
       
  2957 
       
  2958 class DCConfigPanel(wx.Panel):
       
  2959     def __init__(self, parent, controler):
       
  2960         """
       
  2961         Constructor
       
  2962         @param parent: Reference to the MasterStatePanel class
       
  2963         @param Controler: _EthercatCTN class in EthercatMaster.py
       
  2964         """
       
  2965 
       
  2966         wx.Panel.__init__(self, parent, -1, size=wx.Size(750, 350))
       
  2967 
       
  2968         self.Controler = controler
       
  2969         self.parent = parent
       
  2970 
       
  2971         self.ESI_DC_Data = self.Controler.CommonMethod.LoadESIData()
       
  2972 
       
  2973         # initialize SlaveStatePanel UI dictionaries
       
  2974         self.StaticBoxDic = {}
       
  2975         self.StaticTextDic = {}
       
  2976         self.TextCtrlDic = {}
       
  2977         self.ComboBoxDic = {}
       
  2978         self.CheckBoxDic = {}
       
  2979         self.RadioButtonDic = {}
       
  2980         OperationModeComboList = []
       
  2981         Sync1CycleComboList = []
       
  2982         
       
  2983         for ESI_Data in self.ESI_DC_Data:
       
  2984             OperationModeComboList.append(ESI_Data["desc"])
       
  2985 
       
  2986         UnitComboList = [ "/100", "/ 50", "/ 40", "/ 30", "/ 25", "/ 20", "/16",
       
  2987             "/ 10", "/ 8", "/ 5", "/ 4", "/ 3", "/ 2", "x 1", "x 2", "x 3", "x 4", 
       
  2988             "x 5", "x 8", "x 10", "x 16", "x 20", "x 25", "x 30", "x 40", "x 50", 
       
  2989             "x 100"
       
  2990         ]
       
  2991 
       
  2992         UnitComboListPlus = [ "/100", "/ 50", "/ 40", "/ 30", "/ 25", "/ 20", "/16",
       
  2993             "/ 10", "/ 8", "/ 5", "/ 4", "/ 3", "/ 2", "x 0", "x 1", "x 2", "x 3", 
       
  2994             "x 4", "x 5", "x 8", "x 10", "x 16", "x 20", "x 25", "x 30", "x 40", 
       
  2995             "x 50", "x 100"
       
  2996         ]
       
  2997 
       
  2998         for i in range(1024):
       
  2999             Sync1CycleComboList.append("x " + str(i + 1))
       
  3000         
       
  3001         # iniitalize BoxSizer and FlexGridSizer
       
  3002         self.SizerDic = {
       
  3003             "DCConfig_main_sizer" : wx.BoxSizer(wx.VERTICAL),
       
  3004             "DCConfig_inner_main_sizer" : wx.FlexGridSizer(cols=1, hgap=50, rows=2, vgap=10),
       
  3005             "CyclicMode_InnerSizer" : wx.FlexGridSizer(cols=1, hgap=5, rows=2, vgap=5),
       
  3006             "SyncMode_InnerSizer" : wx.FlexGridSizer(cols=2, hgap=5, rows=1, vgap=5),
       
  3007             "OperationMode_InnerSizer" : wx.FlexGridSizer(cols=2, hgap=100, rows=2, vgap=10),
       
  3008             "CheckEnable_InnerSizer" : wx.FlexGridSizer(cols=2, hgap=10, rows=1, vgap=10),
       
  3009             "Sync0_InnerSizer" : wx.FlexGridSizer(cols=1, hgap=15, rows=3, vgap=10),
       
  3010             "Sync0_CycleTimeSizer" : wx.FlexGridSizer(cols=2, hgap=10, rows=2, vgap=5),
       
  3011             "Sync0_ShiftTimeSizer" : wx.FlexGridSizer(cols=2, hgap=20, rows=2, vgap=5),
       
  3012             "Sync1_InnerSizer" : wx.FlexGridSizer(cols=1, hgap=15, rows=3, vgap=10),
       
  3013             "Sync1_CycleTimeSizer" : wx.FlexGridSizer(cols=2, hgap=10, rows=2, vgap=5),
       
  3014             "Sync1_ShiftTimeSizer" : wx.FlexGridSizer(cols=2, hgap=20, rows=2, vgap=5)
       
  3015         }
       
  3016         
       
  3017         # initialize StaticBox and StaticBoxSizer
       
  3018         for box_name, box_label in [
       
  3019                 ("CyclicModeBox", "Cyclic Mode"),
       
  3020                 ("Sync0Box", "Sync0"),
       
  3021                 ("Sync0CycleTimeBox", "Cycle Time (us):"),
       
  3022                 ("Sync0ShiftTimeBox", "Shift Time (us):"),
       
  3023                 ("Sync1Box", "Sync1"),
       
  3024                 ("Sync1CycleTimeBox", "Cycle Time (us):"),
       
  3025                 ("Sync1ShiftTimeBox", "Shift Time (us):")
       
  3026             ]:
       
  3027             self.StaticBoxDic[box_name] = wx.StaticBox(self, label=_(box_label))
       
  3028             self.SizerDic[box_name] = wx.StaticBoxSizer(self.StaticBoxDic[box_name])  
       
  3029         
       
  3030         for statictext_name, statictext_label in [
       
  3031                 ("MainLabel", "Distributed Clock"),
       
  3032                 ("OperationModeLabel", "Operation Mode:"),
       
  3033                 ("SyncUnitCycleLabel", "Sync Unit Cycle (us)"),
       
  3034                 ("Sync0ShiftTimeUserDefinedLabel", "User Defined"),
       
  3035                 ("Sync1ShiftTimeUserDefinedLabel", "User Defined"),
       
  3036                 ("BlankObject", ""),
       
  3037                 ("BlankObject1", "")
       
  3038             ]:
       
  3039             self.StaticTextDic[statictext_name] = wx.StaticText(self, label=_(statictext_label))
       
  3040 
       
  3041         for textctl_name in [
       
  3042                 ("SyncUnitCycle_Ctl"),
       
  3043                 ("Sync0CycleTimeUserDefined_Ctl"),
       
  3044                 ("Sync0ShiftTimeUserDefined_Ctl"),
       
  3045                 ("Sync1CycleTimeUserDefined_Ctl"),
       
  3046                 ("Sync1ShiftTimeUserDefined_Ctl"),
       
  3047             ]:
       
  3048             self.TextCtrlDic[textctl_name] = wx.TextCtrl(
       
  3049                 self, size=wx.Size(130, 24), style=wx.TE_READONLY)
       
  3050 
       
  3051         for checkbox_name, checkbox_label in [
       
  3052                 ("DCEnable", "Enable"),
       
  3053                 ("Sync0Enable", "Enable Sync0"),
       
  3054                 ("Sync1Enable", "Enable Sync1")
       
  3055             ]:
       
  3056             self.CheckBoxDic[checkbox_name] = wx.CheckBox(self, -1, checkbox_label)
       
  3057 
       
  3058         for combobox_name, combobox_list, size in [
       
  3059                 ("OperationModeChoice", OperationModeComboList, 250),
       
  3060                 ("Sync0UnitCycleChoice", UnitComboList, 130),
       
  3061                 ("Sync1UnitCycleChoice", UnitComboList, 130)
       
  3062             ]:
       
  3063             self.ComboBoxDic[combobox_name] = wx.ComboBox(self, size=wx.Size(size, 24), 
       
  3064                 choices = combobox_list, style = wx.CB_DROPDOWN | wx.CB_READONLY)
       
  3065 
       
  3066         for radiobutton_name, radiobutton_label in [
       
  3067                 ("Sync0CycleTimeUnitRadioButton", "Sync Unit Cycle"),
       
  3068                 ("Sync0CycleTimeUserDefinedRadioButton", "User Defined"),
       
  3069                 ("Sync1CycleTimeUnitRadioButton", "Sync Unit Cycle"),
       
  3070                 ("Sync1CycleTimeUserDefinedRadioButton", "User Defined")
       
  3071             ]:
       
  3072             self.RadioButtonDic[radiobutton_name] = wx.RadioButton(
       
  3073                 self, label = radiobutton_label, style = wx.RB_SINGLE)
       
  3074 
       
  3075 
       
  3076         self.ApplyButton = wx.Button(self, label="Apply")
       
  3077 
       
  3078         # binding event
       
  3079         self.Bind(wx.EVT_CHECKBOX, self.CheckDCEnable, self.CheckBoxDic["DCEnable"])
       
  3080         #self.Bind(wx.EVT_COMBOBOX, self.SelectOperationMode, self.ComboBoxDic["OperationModeChoice"])
       
  3081         #self.Bind(wx.EVT_COMBOBOX, self.SelectUnitCycle, self.ComboBoxDic["Sync0UnitChoice"])
       
  3082         self.Bind(wx.EVT_RADIOBUTTON, self.SelectSync0CycleTime, 
       
  3083             self.RadioButtonDic["Sync0CycleTimeUnitRadioButton"])
       
  3084         self.Bind(wx.EVT_RADIOBUTTON, self.SelectSync0CycleTime, 
       
  3085             self.RadioButtonDic["Sync0CycleTimeUserDefinedRadioButton"])
       
  3086         self.Bind(wx.EVT_RADIOBUTTON, self.SelectSync1CycleTime, 
       
  3087             self.RadioButtonDic["Sync1CycleTimeUnitRadioButton"])
       
  3088         self.Bind(wx.EVT_RADIOBUTTON, self.SelectSync1CycleTime, 
       
  3089             self.RadioButtonDic["Sync1CycleTimeUserDefinedRadioButton"])
       
  3090         self.Bind(wx.EVT_CHECKBOX, self.CheckSync0Enable, self.CheckBoxDic["Sync0Enable"])
       
  3091         self.Bind(wx.EVT_CHECKBOX, self.CheckSync1Enable, self.CheckBoxDic["Sync1Enable"])
       
  3092         self.Bind(wx.EVT_BUTTON, self.OnClickApplyButton, self.ApplyButton)
       
  3093 
       
  3094         # sync1 shifttime box contents
       
  3095         self.SizerDic["Sync1_ShiftTimeSizer"].AddMany([
       
  3096             self.StaticTextDic["Sync1ShiftTimeUserDefinedLabel"],
       
  3097             self.TextCtrlDic["Sync1ShiftTimeUserDefined_Ctl"]
       
  3098         ])
       
  3099 
       
  3100         # sync1 shifttime box
       
  3101         self.SizerDic["Sync1ShiftTimeBox"].Add(self.SizerDic["Sync1_ShiftTimeSizer"])
       
  3102         
       
  3103         # sync1 cycletime box contents
       
  3104         self.SizerDic["Sync1_CycleTimeSizer"].AddMany([
       
  3105             self.RadioButtonDic["Sync1CycleTimeUnitRadioButton"], 
       
  3106             self.ComboBoxDic["Sync1UnitCycleChoice"],
       
  3107             self.RadioButtonDic["Sync1CycleTimeUserDefinedRadioButton"],
       
  3108             self.TextCtrlDic["Sync1CycleTimeUserDefined_Ctl"]
       
  3109         ])
       
  3110 
       
  3111         # sync0 cycletime box
       
  3112         self.SizerDic["Sync1CycleTimeBox"].Add(self.SizerDic["Sync1_CycleTimeSizer"])
       
  3113 
       
  3114         self.SizerDic["Sync1_InnerSizer"].AddMany([
       
  3115             self.CheckBoxDic["Sync1Enable"], self.SizerDic["Sync1CycleTimeBox"], 
       
  3116             self.SizerDic["Sync1ShiftTimeBox"]
       
  3117         ])
       
  3118 
       
  3119         # sync1 box
       
  3120         self.SizerDic["Sync1Box"].Add(self.SizerDic["Sync1_InnerSizer"])
       
  3121 
       
  3122         # sync0 shifttime box contents
       
  3123         self.SizerDic["Sync0_ShiftTimeSizer"].AddMany([
       
  3124             self.StaticTextDic["Sync0ShiftTimeUserDefinedLabel"],
       
  3125             self.TextCtrlDic["Sync0ShiftTimeUserDefined_Ctl"]
       
  3126         ])
       
  3127 
       
  3128         # sync0 shifttime box
       
  3129         self.SizerDic["Sync0ShiftTimeBox"].Add(self.SizerDic["Sync0_ShiftTimeSizer"])
       
  3130         
       
  3131         # sync0 cycletime box contents
       
  3132         self.SizerDic["Sync0_CycleTimeSizer"].AddMany([
       
  3133             self.RadioButtonDic["Sync0CycleTimeUnitRadioButton"], 
       
  3134             self.ComboBoxDic["Sync0UnitCycleChoice"],
       
  3135             self.RadioButtonDic["Sync0CycleTimeUserDefinedRadioButton"],
       
  3136             self.TextCtrlDic["Sync0CycleTimeUserDefined_Ctl"]
       
  3137         ])
       
  3138 
       
  3139         # sync0 cycletime box
       
  3140         self.SizerDic["Sync0CycleTimeBox"].Add(self.SizerDic["Sync0_CycleTimeSizer"])
       
  3141 
       
  3142         self.SizerDic["Sync0_InnerSizer"].AddMany([
       
  3143             self.CheckBoxDic["Sync0Enable"], self.SizerDic["Sync0CycleTimeBox"], 
       
  3144             self.SizerDic["Sync0ShiftTimeBox"]
       
  3145         ])
       
  3146 
       
  3147         # sync0 box
       
  3148         self.SizerDic["Sync0Box"].Add(self.SizerDic["Sync0_InnerSizer"])
       
  3149 
       
  3150         # sync0, sync1 box
       
  3151         self.SizerDic["SyncMode_InnerSizer"].AddMany([
       
  3152             self.SizerDic["Sync0Box"], self.SizerDic["Sync1Box"]
       
  3153         ])
       
  3154 
       
  3155         # CyclicMode Box
       
  3156         self.SizerDic["CheckEnable_InnerSizer"].AddMany([
       
  3157             self.StaticTextDic["SyncUnitCycleLabel"], 
       
  3158             self.TextCtrlDic["SyncUnitCycle_Ctl"]
       
  3159         ])
       
  3160 
       
  3161         self.SizerDic["OperationMode_InnerSizer"].AddMany([
       
  3162             self.StaticTextDic["OperationModeLabel"], 
       
  3163             self.ComboBoxDic["OperationModeChoice"],
       
  3164             self.CheckBoxDic["DCEnable"], self.SizerDic["CheckEnable_InnerSizer"]
       
  3165         ])
       
  3166 
       
  3167         self.SizerDic["CyclicMode_InnerSizer"].AddMany([
       
  3168             self.SizerDic["OperationMode_InnerSizer"], 
       
  3169             self.SizerDic["SyncMode_InnerSizer"]
       
  3170         ])
       
  3171 
       
  3172         self.SizerDic["CyclicModeBox"].Add(self.SizerDic["CyclicMode_InnerSizer"])
       
  3173 
       
  3174         # Main Sizer
       
  3175         self.SizerDic["DCConfig_inner_main_sizer"].AddMany([
       
  3176             self.StaticTextDic["MainLabel"], self.ApplyButton,
       
  3177             self.SizerDic["CyclicModeBox"]
       
  3178         ])
       
  3179         
       
  3180         self.SizerDic["DCConfig_main_sizer"].Add(self.SizerDic["DCConfig_inner_main_sizer"])
       
  3181         
       
  3182         self.SetSizer(self.SizerDic["DCConfig_main_sizer"])
       
  3183         
       
  3184         self.Centre()
       
  3185 
       
  3186         self.UIOnOffSet(False)
       
  3187         self.LoadProjectDCData()
       
  3188 
       
  3189     def UIOnOffSet(self, activate):
       
  3190         if activate :
       
  3191             for object in self.RadioButtonDic:
       
  3192                 self.RadioButtonDic[object].Enable()
       
  3193 
       
  3194             for object in self.ComboBoxDic:
       
  3195                 if object == "OperationModeChoice":
       
  3196                     continue
       
  3197                 self.ComboBoxDic[object].Enable()
       
  3198 
       
  3199             for object in self.TextCtrlDic:
       
  3200                 if object in ["SyncUnitCycle_Ctl", "InputReference_Ctl"]:
       
  3201                     continue
       
  3202                 self.TextCtrlDic[object].Enable()
       
  3203 
       
  3204             for object in self.CheckBoxDic:
       
  3205                 if object == "DCEnable":
       
  3206                     continue
       
  3207                 self.CheckBoxDic[object].Enable()
       
  3208 
       
  3209         # initial set or DC enable uncheck
       
  3210         else :
       
  3211             for object in self.RadioButtonDic:
       
  3212                 self.RadioButtonDic[object].Disable()
       
  3213 
       
  3214             for object in self.ComboBoxDic:
       
  3215                 if object == "OperationModeChoice":
       
  3216                     continue
       
  3217                 self.ComboBoxDic[object].Disable()
       
  3218 
       
  3219             for object in self.TextCtrlDic:
       
  3220                 if object == "SyncUnitCycle_Ctl":
       
  3221                     continue
       
  3222                 self.TextCtrlDic[object].Disable()
       
  3223 
       
  3224             for object in self.CheckBoxDic:
       
  3225                 if object == "DCEnable":
       
  3226                     continue
       
  3227                 self.CheckBoxDic[object].Disable()
       
  3228 
       
  3229             for data in self.ESI_DC_Data:
       
  3230                 index = self.Controler.ExtractHexDecValue(data["assign_activate"])
       
  3231                 if index == 0:
       
  3232                     config_name = data["desc"]
       
  3233                     self.ComboBoxDic["OperationModeChoice"].SetStringSelection(config_name)
       
  3234 
       
  3235     def CheckSync0Enable(self, evt):
       
  3236         if evt.GetInt():
       
  3237             self.ComboBoxDic["Sync0UnitCycleChoice"].Enable()
       
  3238             self.RadioButtonDic["Sync0CycleTimeUnitRadioButton"].Enable()
       
  3239             self.RadioButtonDic["Sync0CycleTimeUserDefinedRadioButton"].Enable()
       
  3240             self.TextCtrlDic["Sync0CycleTimeUserDefined_Ctl"].Enable()
       
  3241             self.TextCtrlDic["Sync0ShiftTimeUserDefined_Ctl"].Enable()
       
  3242         else :
       
  3243             self.ComboBoxDic["Sync0UnitCycleChoice"].Disable()
       
  3244             self.RadioButtonDic["Sync0CycleTimeUnitRadioButton"].Disable()
       
  3245             self.RadioButtonDic["Sync0CycleTimeUserDefinedRadioButton"].Disable()
       
  3246             self.TextCtrlDic["Sync0CycleTimeUserDefined_Ctl"].Disable()
       
  3247             self.TextCtrlDic["Sync0ShiftTimeUserDefined_Ctl"].Disable()
       
  3248             self.RadioButtonDic["Sync0CycleTimeUnitRadioButton"].SetValue(False)
       
  3249             self.RadioButtonDic["Sync0CycleTimeUserDefinedRadioButton"].SetValue(False)
       
  3250             self.TextCtrlDic["Sync0CycleTimeUserDefined_Ctl"].SetValue("")
       
  3251             self.TextCtrlDic["Sync0ShiftTimeUserDefined_Ctl"].SetValue("")
       
  3252 
       
  3253     def CheckSync1Enable(self, evt):
       
  3254         if evt.GetInt():
       
  3255             self.ComboBoxDic["Sync1UnitCycleChoice"].Enable()
       
  3256             self.RadioButtonDic["Sync1CycleTimeUnitRadioButton"].Enable()
       
  3257             self.RadioButtonDic["Sync1CycleTimeUserDefinedRadioButton"].Enable()
       
  3258             self.TextCtrlDic["Sync1CycleTimeUserDefined_Ctl"].Enable()
       
  3259             self.TextCtrlDic["Sync1ShiftTimeUserDefined_Ctl"].Enable()
       
  3260         else :
       
  3261             self.ComboBoxDic["Sync1UnitCycleChoice"].Disable()
       
  3262             self.RadioButtonDic["Sync1CycleTimeUnitRadioButton"].Disable()
       
  3263             self.RadioButtonDic["Sync1CycleTimeUserDefinedRadioButton"].Disable()
       
  3264             self.TextCtrlDic["Sync1CycleTimeUserDefined_Ctl"].Disable()
       
  3265             self.TextCtrlDic["Sync1ShiftTimeUserDefined_Ctl"].Disable()
       
  3266             self.RadioButtonDic["Sync1CycleTimeUnitRadioButton"].SetValue(False)
       
  3267             self.RadioButtonDic["Sync1CycleTimeUserDefinedRadioButton"].SetValue(False)
       
  3268             self.TextCtrlDic["Sync1CycleTimeUserDefined_Ctl"].SetValue("")
       
  3269             self.TextCtrlDic["Sync1ShiftTimeUserDefined_Ctl"].SetValue("")
       
  3270 
       
  3271     def CheckDCEnable(self, evt):
       
  3272         ns_mode = 1
       
  3273         task_cycle_ns = self.GetInterval(ns_mode)
       
  3274         sync0_cycle_factor = None
       
  3275         sync1_cycle_factor = None
       
  3276 
       
  3277         #task_cycle_ns = self.Controler.GetCTRoot()._Ticktime
       
  3278         if (task_cycle_ns > 0):
       
  3279             self.UIOnOffSet(evt.GetInt())
       
  3280 
       
  3281             if evt.GetInt():
       
  3282                 # default select DC enable sync0
       
  3283                 default_list_num = 0
       
  3284                 config_name = self.ESI_DC_Data[default_list_num]["desc"]
       
  3285                 assign_act = self.ESI_DC_Data[default_list_num]["assign_activate"]
       
  3286                 sync0_cycle_time_ns = self.ESI_DC_Data[default_list_num]["cycletime_sync0"]
       
  3287                 if sync0_cycle_time_ns == 0 :
       
  3288                     sync0_cycle_factor = self.ESI_DC_Data[default_list_num]["cycletime_sync0_factor"]
       
  3289                 sync0_shift_time_ns = self.ESI_DC_Data[default_list_num]["shifttime_sync0"]
       
  3290                 sync1_cycle_time_ns = self.ESI_DC_Data[default_list_num]["cycletime_sync1"]
       
  3291                 if sync1_cycle_time_ns == 0 :
       
  3292                     sync1_cycle_factor = self.ESI_DC_Data[default_list_num]["cycletime_sync1_factor"]
       
  3293                 sync1_shift_time_ns = self.ESI_DC_Data[default_list_num]["shifttime_sync1"]
       
  3294 
       
  3295                 cal_assign_act = self.Controler.ExtractHexDecValue(assign_act)
       
  3296                 sync0_cycle_time_us = str(int(sync0_cycle_time_ns) / 1000)
       
  3297                 sync0_shift_time_us = str(int(sync0_shift_time_ns) / 1000)
       
  3298                 sync1_cycle_time_us = str(int(sync1_cycle_time_ns) / 1000)
       
  3299                 sync1_shift_time_us = str(int(sync1_shift_time_ns) / 1000)
       
  3300 
       
  3301                 task_cycle_to_us = str(int(task_cycle_ns) / 1000)
       
  3302 
       
  3303                 # DC sync0 mode
       
  3304                 if cal_assign_act == 768:
       
  3305                     # Disable About Sync1 Objects
       
  3306                     self.CheckBoxDic["Sync1Enable"].SetValue(False)
       
  3307                     self.RadioButtonDic["Sync1CycleTimeUnitRadioButton"].Disable()
       
  3308                     self.ComboBoxDic["Sync1UnitCycleChoice"].Disable()
       
  3309                     self.RadioButtonDic["Sync1CycleTimeUserDefinedRadioButton"].Disable()
       
  3310                     self.TextCtrlDic["Sync1CycleTimeUserDefined_Ctl"].Disable()
       
  3311                     self.TextCtrlDic["Sync1ShiftTimeUserDefined_Ctl"].Disable()
       
  3312 
       
  3313                 else :
       
  3314                     self.CheckBoxDic["Sync1Enable"].SetValue(True)
       
  3315                     if sync1_cycle_factor is not None:
       
  3316                         self.RadioButtonDic["Sync1CycleTimeUnitRadioButton"].SetValue(True)
       
  3317                         self.RadioButtonDic["Sync1CycleTimeUserDefinedRadioButton"].SetValue(False)
       
  3318                         self.TextCtrlDic["Sync1CycleTimeUserDefined_Ctl"].Disable()
       
  3319                         self.SetSyncUnitCycle(sync1_cycle_factor, 
       
  3320                             self.ComboBoxDic["Sync1UnitCycleChoice"])
       
  3321                     else :
       
  3322                         self.RadioButtonDic["Sync1CycleTimeUnitRadioButton"].SetValue(False)
       
  3323                         self.RadioButtonDic["Sync1CycleTimeUserDefinedRadioButton"].SetValue(True)
       
  3324                         self.ComboBoxDic["Sync1UnitCycleChoice"].Disable()
       
  3325                         self.TextCtrlDic["Sync1CycleTimeUserDefined_Ctl"].SetValue(sync1_cycle_time_us)
       
  3326 
       
  3327                     self.TextCtrlDic["Sync1ShiftTimeUserDefined_Ctl"].SetValue(sync1_shift_time_us)
       
  3328 
       
  3329                 # Set Sync0 Objects
       
  3330                 self.CheckBoxDic["Sync0Enable"].SetValue(True)
       
  3331                 if sync0_cycle_factor is not None:
       
  3332                     self.RadioButtonDic["Sync0CycleTimeUnitRadioButton"].SetValue(True)
       
  3333                     self.RadioButtonDic["Sync0CycleTimeUserDefinedRadioButton"].SetValue(False)
       
  3334                     self.TextCtrlDic["Sync0CycleTimeUserDefined_Ctl"].Disable()
       
  3335                     self.SetSyncUnitCycle(sync0_cycle_factor, 
       
  3336                         self.ComboBoxDic["Sync0UnitCycleChoice"])
       
  3337                 else :
       
  3338                     self.RadioButtonDic["Sync0CycleTimeUnitRadioButton"].SetValue(False)
       
  3339                     self.RadioButtonDic["Sync0CycleTimeUserDefinedRadioButton"].SetValue(True)
       
  3340                     self.ComboBoxDic["Sync0UnitCycleChoice"].Disable()
       
  3341                     self.TextCtrlDic["Sync0CycleTimeUserDefined_Ctl"].SetValue(sync0_cycle_time_us)
       
  3342 
       
  3343                 self.TextCtrlDic["Sync0ShiftTimeUserDefined_Ctl"].SetValue(sync0_shift_time_us)
       
  3344 
       
  3345                 self.ComboBoxDic["OperationModeChoice"].SetStringSelection(config_name)
       
  3346                 self.TextCtrlDic["SyncUnitCycle_Ctl"].SetValue(task_cycle_to_us)
       
  3347             else :
       
  3348                 self.CheckBoxDic["Sync0Enable"].SetValue(False)
       
  3349                 self.CheckBoxDic["Sync1Enable"].SetValue(False)
       
  3350                 self.RadioButtonDic["Sync0CycleTimeUnitRadioButton"].SetValue(False)
       
  3351                 self.RadioButtonDic["Sync0CycleTimeUserDefinedRadioButton"].SetValue(False)
       
  3352                 self.RadioButtonDic["Sync1CycleTimeUnitRadioButton"].SetValue(False)
       
  3353                 self.RadioButtonDic["Sync1CycleTimeUserDefinedRadioButton"].SetValue(False)
       
  3354                 self.TextCtrlDic["Sync0CycleTimeUserDefined_Ctl"].SetValue("")
       
  3355                 self.TextCtrlDic["Sync0ShiftTimeUserDefined_Ctl"].SetValue("")
       
  3356                 self.TextCtrlDic["Sync1CycleTimeUserDefined_Ctl"].SetValue("")
       
  3357                 self.TextCtrlDic["Sync1ShiftTimeUserDefined_Ctl"].SetValue("")
       
  3358 
       
  3359         else :
       
  3360             self.UIOnOffSet(False)
       
  3361             #error_str = "DC Enable is not possble, please set task interval"
       
  3362             error_str = "Can't Set DC Enable"
       
  3363             self.Controler.CommonMethod.CreateErrorDialog(error_str)
       
  3364 
       
  3365     def SetSyncUnitCycle(self, factor, object):
       
  3366         # factor > 0 ==> * factor, factor < 0 ==> / factor
       
  3367         factor_to_int = int(factor)
       
  3368         if factor_to_int > 0:
       
  3369             lists = object.GetStrings()
       
  3370 
       
  3371             for token in lists:
       
  3372                 temp = token.split(" ")
       
  3373                 if (temp[0] == "x") and (int(temp[1]) == factor_to_int):
       
  3374                     object.SetStringSelection(token)
       
  3375                     return True
       
  3376 
       
  3377         else : 
       
  3378             lists = object.GetStrings()
       
  3379 
       
  3380             for token in lists:
       
  3381                 temp = token.split(" ")
       
  3382                 if (temp[0] == "/") and (int(temp[1]) == factor_to_int):
       
  3383                     object.SetStringSelection(token)
       
  3384                     return True
       
  3385 
       
  3386         return False
       
  3387 
       
  3388     def GetInterval(self, mode):
       
  3389         project_infos = self.Controler.GetCTRoot().GetProjectInfos()
       
  3390         for project_info_list in project_infos["values"]:
       
  3391             if project_info_list["name"] == "Resources" :
       
  3392                 token = project_info_list["values"][0]["tagname"]
       
  3393        
       
  3394         tasks, instances = self.Controler.GetCTRoot().GetEditedResourceInfos(token)
       
  3395         try:
       
  3396             task_cycle_ns = self.ParseTime(tasks[0]["Interval"])
       
  3397         except :
       
  3398             task_cycle_ns = 0
       
  3399         task_cycle_us = int(task_cycle_ns) / 1000
       
  3400 
       
  3401         # mode == 1 ==> return ns
       
  3402         # mode == 2 ==> return us
       
  3403 
       
  3404         if mode == 1:
       
  3405             return task_cycle_ns
       
  3406         if mode == 2:
       
  3407             return str(task_cycle_us)
       
  3408 
       
  3409     def ParseTime(self, input):
       
  3410         # input example : 't#1ms'
       
  3411         # temp.split('#') -> ['t', '1ms']
       
  3412         temp = input.split('#')
       
  3413          
       
  3414         # temp[1] : '1ms'
       
  3415         # temp[-2:] : 'ms'
       
  3416         # temp[:-2] : '1'
       
  3417         if temp[1][-2:] == "ms":
       
  3418            # convert nanosecond unit
       
  3419            result = int(temp[1][:-2]) * 1000000
       
  3420         elif temp[1][-2:] == "us":
       
  3421            result = int(temp[1][:-2]) * 1000
       
  3422 
       
  3423         return str(result)
       
  3424 
       
  3425     def SelectSync0CycleTime(self, evt):
       
  3426         selected_object = evt.GetEventObject()
       
  3427 
       
  3428         if selected_object.GetLabel() == "User Defined" :
       
  3429             self.RadioButtonDic["Sync0CycleTimeUnitRadioButton"].SetValue(False)
       
  3430             self.TextCtrlDic["Sync0CycleTimeUserDefined_Ctl"].Enable()
       
  3431             self.ComboBoxDic["Sync0UnitCycleChoice"].Disable()
       
  3432         elif selected_object.GetLabel() == "Sync Unit Cycle" :
       
  3433             self.RadioButtonDic["Sync0CycleTimeUserDefinedRadioButton"].SetValue(False)
       
  3434             self.ComboBoxDic["Sync0UnitCycleChoice"].Enable()
       
  3435             self.TextCtrlDic["Sync0CycleTimeUserDefined_Ctl"].Disable()
       
  3436 
       
  3437     def SelectSync1CycleTime(self, evt):
       
  3438         selected_object = evt.GetEventObject()
       
  3439 
       
  3440         if selected_object.GetLabel() == "User Defined" :
       
  3441             self.RadioButtonDic["Sync1CycleTimeUnitRadioButton"].SetValue(False)
       
  3442             self.TextCtrlDic["Sync1CycleTimeUserDefined_Ctl"].Enable()
       
  3443             self.ComboBoxDic["Sync1UnitCycleChoice"].Disable()
       
  3444         elif selected_object.GetLabel() == "Sync Unit Cycle" :
       
  3445             self.RadioButtonDic["Sync1CycleTimeUserDefinedRadioButton"].SetValue(False)
       
  3446             self.ComboBoxDic["Sync1UnitCycleChoice"].Enable()
       
  3447             self.TextCtrlDic["Sync1CycleTimeUserDefined_Ctl"].Disable()
       
  3448 
       
  3449     def GetCycle(self, period, section):
       
  3450         temp = section.split(" ")
       
  3451 
       
  3452         if temp[0] == "x":
       
  3453             result = int(period) * int(temp[1])
       
  3454         elif temp[0] == "/" :
       
  3455             result = int(period) / int(temp[1])
       
  3456         else :
       
  3457             result = ""
       
  3458 
       
  3459         return result
       
  3460 
       
  3461     def OnClickApplyButton(self, evt):
       
  3462         us_mode = 2
       
  3463         dc_enable = self.CheckBoxDic["DCEnable"].GetValue()
       
  3464         dc_desc = self.ComboBoxDic["OperationModeChoice"].GetStringSelection()
       
  3465         dc_assign_activate = self.ESI_DC_Data[0]["assign_activate"]
       
  3466         dc_assign_activate_mod = dc_assign_activate.split('x')[1]
       
  3467 
       
  3468         if self.RadioButtonDic["Sync0CycleTimeUnitRadioButton"].GetValue():
       
  3469             temp = self.ComboBoxDic["Sync0UnitCycleChoice"].GetStringSelection()
       
  3470             dc_sync0_cycle = "1_" + str(self.GetCycle(self.GetInterval(us_mode), temp))
       
  3471         elif  self.RadioButtonDic["Sync0CycleTimeUserDefinedRadioButton"].GetValue():
       
  3472             dc_sync0_cycle = "2_" + self.TextCtrlDic["Sync0CycleTimeUserDefined_Ctl"].GetValue()
       
  3473         else :
       
  3474             dc_sync0_cycle = ""
       
  3475 
       
  3476         if self.RadioButtonDic["Sync1CycleTimeUnitRadioButton"].GetValue():
       
  3477             temp = self.ComboBoxDic["Sync1UnitCycleChoice"].GetStringSelection()
       
  3478             dc_sync1_cycle = "1_" + self.GetCycle(self.GetInterval(us_mode), temp)
       
  3479         elif  self.RadioButtonDic["Sync1CycleTimeUserDefinedRadioButton"].GetValue():
       
  3480             dc_sync1_cycle = "2_" + self.TextCtrlDic["Sync1CycleTimeUserDefined_Ctl"].GetValue()
       
  3481         else :
       
  3482             dc_sync1_cycle = ""
       
  3483 
       
  3484         dc_sync0_shift = self.TextCtrlDic["Sync0ShiftTimeUserDefined_Ctl"].GetValue()
       
  3485         dc_sync1_shift = self.TextCtrlDic["Sync1ShiftTimeUserDefined_Ctl"].GetValue()
       
  3486 
       
  3487         self.Controler.BaseParams.setDC_Enable(dc_enable)
       
  3488         self.Controler.BaseParams.setDC_Desc(dc_desc)
       
  3489         self.Controler.BaseParams.setDC_Assign_Activate(dc_assign_activate_mod)
       
  3490         if dc_sync0_cycle:
       
  3491             self.Controler.BaseParams.setDC_Sync0_Cycle_Time(dc_sync0_cycle)
       
  3492         if dc_sync0_shift:
       
  3493             self.Controler.BaseParams.setDC_Sync0_Shift_Time(dc_sync0_shift)
       
  3494         if dc_sync1_cycle:
       
  3495             self.Controler.BaseParams.setDC_Sync1_Cycle_Time(dc_sync1_cycle)
       
  3496         if dc_sync1_shift:
       
  3497             self.Controler.BaseParams.setDC_Sync1_Shift_Time(dc_sync1_shift)
       
  3498         project_infos = self.Controler.GetCTRoot().CTNRequestSave()
       
  3499 
       
  3500     def GetSymbol(self, period, cycle):
       
  3501         cmp1 = int(period)
       
  3502         cmp2 = int(cycle)
       
  3503 
       
  3504         if cmp1 == cmp2 :
       
  3505             return "x 1"
       
  3506         elif cmp2 > cmp1 :
       
  3507             temp = cmp2 / cmp1
       
  3508             result = "x " + str(temp)
       
  3509         else :
       
  3510             temp = cmp1 / cmp2
       
  3511             result = "/ " + str(temp)
       
  3512 
       
  3513         return result
       
  3514 
       
  3515     def SetSyncCycle(self, period, sync0_cycle, sync1_cycle):
       
  3516         if sync0_cycle != "None":
       
  3517             self.CheckBoxDic["Sync0Enable"].SetValue(True)               
       
  3518             temp = sync0_cycle.split("_")
       
  3519             if temp[0] == "1":
       
  3520                 symbol = self.GetSymbol(period, temp[1])
       
  3521                 self.ComboBoxDic["Sync0UnitCycleChoice"].SetStringSelection(symbol)
       
  3522                 self.TextCtrlDic["Sync0CycleTimeUserDefined_Ctl"].Disable()
       
  3523                 self.RadioButtonDic["Sync0CycleTimeUnitRadioButton"].SetValue(True)
       
  3524             else :
       
  3525                 self.TextCtrlDic["Sync0CycleTimeUserDefined_Ctl"].SetValue(temp[1])
       
  3526                 self.ComboBoxDic["Sync0UnitCycleChoice"].Disable()
       
  3527                 self.RadioButtonDic["Sync0CycleTimeUserDefinedRadioButton"].SetValue(True)
       
  3528 
       
  3529         if sync1_cycle != "None":
       
  3530             self.CheckBoxDic["Sync1Enable"].SetValue(True)
       
  3531             temp = sync1_cycle.split("_")
       
  3532             if temp[0] == "1":
       
  3533                 symbol = self.GetSymbol(period, temp[1])
       
  3534                 self.ComboBoxDic["Sync1UnitChoice"].SetStringSelection(symbol)
       
  3535                 self.TextCtrlDic["Sync1CycleTimeUserDefined_Ctl"].Disable()
       
  3536                 self.RadioButtonDic["Sync1CycleTimeUnitRadioButton"].SetValue(True)
       
  3537             else :
       
  3538                 self.TextCtrlDic["Sync1CycleTimeUserDefined_Ctl"].SetValue(temp[1])
       
  3539                 self.ComboBoxDic["Sync1UnitChoice"].Disable()
       
  3540                 self.RadioButtonDic["Sync1CycleTimeUserDefinedRadioButton"].SetValue(True)
       
  3541 
       
  3542     def LoadProjectDCData(self):
       
  3543         ns_mode = 1
       
  3544         task_cycle_ns = self.GetInterval(ns_mode)
       
  3545         task_cycle_to_us = int(task_cycle_ns) / 1000
       
  3546         dc_enable = self.Controler.BaseParams.getDC_Enable()
       
  3547         dc_desc = self.Controler.BaseParams.getDC_Desc()
       
  3548         dc_assign_activate = self.Controler.BaseParams.getDC_Assign_Activate()
       
  3549         dc_sync0_cycle = self.Controler.BaseParams.getDC_Sync0_Cycle_Time()
       
  3550         dc_sync0_shift = self.Controler.BaseParams.getDC_Sync0_Shift_Time()
       
  3551         dc_sync1_cycle = self.Controler.BaseParams.getDC_Sync1_Cycle_Time()
       
  3552         dc_sync1_shift = self.Controler.BaseParams.getDC_Sync1_Shift_Time()
       
  3553 
       
  3554         self.UIOnOffSet(dc_enable)
       
  3555 
       
  3556         if dc_enable:
       
  3557             self.CheckBoxDic["DCEnable"].SetValue(dc_enable)
       
  3558             self.ComboBoxDic["OperationModeChoice"].SetStringSelection(dc_desc)
       
  3559             self.TextCtrlDic["SyncUnitCycle_Ctl"].SetValue(str(task_cycle_to_us))
       
  3560             self.SetSyncCycle(str(task_cycle_to_us), dc_sync0_cycle, dc_sync1_cycle)
       
  3561             if dc_sync0_shift != "None":
       
  3562                 self.TextCtrlDic["Sync0ShiftTimeUserDefined_Ctl"].SetValue(dc_sync0_shift)
       
  3563             if dc_sync1_shift != "None":
       
  3564                 self.TextCtrlDic["Sync1ShiftTimeUserDefined_Ctl"].SetValue(dc_sync1_shift)
       
  3565 
       
  3566             if dc_assign_activate == "300":
       
  3567                 self.CheckBoxDic["Sync1Enable"].SetValue(False)
       
  3568                 self.RadioButtonDic["Sync1CycleTimeUnitRadioButton"].Disable()
       
  3569                 self.ComboBoxDic["Sync1UnitCycleChoice"].Disable()
       
  3570                 self.RadioButtonDic["Sync1CycleTimeUserDefinedRadioButton"].Disable()
       
  3571                 self.TextCtrlDic["Sync1CycleTimeUserDefined_Ctl"].Disable()
       
  3572                 self.TextCtrlDic["Sync1ShiftTimeUserDefined_Ctl"].Disable()
       
  3573 
       
  3574 
       
  3575 
       
  3576 
       
  3577 
       
  3578 
       
  3579 
       
  3580 
       
  3581 
       
  3582