def FortiusAntChild(clv, conn): # -------------------------------------------------------------------------- # Initialize the child process, create our own logfile # -------------------------------------------------------------------------- debug.activate(clv.debug) if debug.on(debug.Any): logfile.Open('FortiusAntGUI') logfile.Console('FortiusAnt GUI started in child-process') FortiusAntBody.Initialize(clv) # -------------------------------------------------------------------------- # Start the user-interface # -------------------------------------------------------------------------- app = wx.App(0) frame = frmFortiusAntChild(None, conn, clv) app.SetTopWindow(frame) frame.Show() if clv.autostart: frame.Autostart() app.MainLoop() # -------------------------------------------------------------------------- # Signal parent that we're done # -------------------------------------------------------------------------- frame.GuiMessageToMain(cmd_EndExecution, False) if debug.on(debug.Any): logfile.Console('FortiusAnt GUI ended')
def LocateHW(self): global devTrainer, devAntDongle if debug.on(debug.Application): logfile.Write("Scan for hardware") #--------------------------------------------------------------------------- # Get ANT dongle #--------------------------------------------------------------------------- if not devAntDongle: devAntDongle, msg = ant.GetDongle() SetDongleMsg(self, msg) #--------------------------------------------------------------------------- # Get Trainer and find trainer model for Windows and Linux #--------------------------------------------------------------------------- if debug.on(debug.Application): logfile.Write("Get USB trainer") if not devTrainer: if clv.SimulateTrainer: SetTacxMsg(self, "Simulated Trainer") else: devTrainer = usbTrainer.GetTrainer() if not devTrainer: SetTacxMsg(self, "Trainer not detected") else: SetTacxMsg(self, "Trainer detected") usbTrainer.InitialiseTrainer(devTrainer) #initialise trainer #--------------------------------------------------------------------------- # Done #--------------------------------------------------------------------------- if debug.on(debug.Application): logfile.Write("Scan for hardware - end") if devAntDongle and (clv.SimulateTrainer or devTrainer): return True else: return False
def githubWindowTitle(): rtn = WindowTitle url = 'https://raw.githubusercontent.com/WouterJD/FortiusANT/master/pythoncode/FortiusAntTitle.py' try: file = urllib.request.urlopen(url) except: if debug.on(debug.Function): logfile.Write ('No access to FortiusAntTitle.py on github') pass else: if debug.on(debug.Function): logfile.Write ('Check FortiusAntTitle.py on github') for line in file: DecodedLine = line.decode('utf-8') if DecodedLine[:len('WindowTitle')] == 'WindowTitle': #--------------------------------------------------------------- # We read ourselves, so second token must be WindowTitle #--------------------------------------------------------------- githubWindowTitle = DecodedLine.split('"')[1] #--------------------------------------------------------------- # Check if equal; unequal is considered newer #--------------------------------------------------------------- if debug.on(debug.Any): logfile.Write ('Version='+ WindowTitle + ', on github=' + githubWindowTitle + '.') if githubWindowTitle == WindowTitle: pass else: rtn = rtn + ' [version on github=' + githubWindowTitle + ']' break file = None return rtn
def Read(self): if debug.on(debug.Ble): logfile.Write("BleInterface.Read() ...") rtn = False self.jsondata = None if self.interface: #----------------------------------------------------------- # Read from bluetooth interface #----------------------------------------------------------- try: r = requests.get(f'http://{self.host}:{self.port}/ant') except Exception as e: logfile.Console("... requests.get() error " + str(e)) else: #------------------------------------------------------- # Now we have a response object r # Which should contain a JSON object #------------------------------------------------------- if r.ok and r.text != "": try: self.jsondata = json.loads(r.text) except Exception as e: logfile.Console("... json.loads() error " + str(e)) else: rtn = True if debug.on(debug.Ble): logfile.Write("... returns: %s (%s)" % (rtn, self.jsondata)) return rtn
def GuiMessageToMain(self, command, wait=True, p1=None, p2=None): # ---------------------------------------------------------------------- # Step 1. GUI sends a command to main # ---------------------------------------------------------------------- if debug.on(debug.MultiProcessing) and not (command == cmd_Idle): logfile.Write("mp-GuiMessageToMain(conn, %s, %s, %s, %s)" % (command, wait, p1, p2)) self.gui_conn.send((command, p1, p2)) rtn = True while wait: # ------------------------------------------------------------------ # Check if requested command is ended # OR that information is received from Main # ------------------------------------------------------------------ # Will be more efficient than self.gui_conn.poll() / sleep loop... # ------------------------------------------------------------------ # Step 4. GUI receives the response (command, rtn) # ------------------------------------------------------------------ msg = self.gui_conn.recv() cmd = msg[0] rtn = msg[1] if debug.on(debug.MultiProcessing) and not (command == cmd_Idle and rtn == 0): logfile.Write( "mp-GuiAnswerFromMain(conn) returns (%s, %s)" % (cmd, rtn)) # ------------------------------------------------------------------ # We wait for the response on the command # and in the meantime receive data to displayed # # cmd_StopButton is treated differently, since that command is sent # while we are waiting for the response on cmd_Runoff or cmd_Tacx2Dongle # we ignore the response here and cmd_StopButton does not start wait-loop # to avoid some sort of nesting or so. # ------------------------------------------------------------------ if cmd == command: break # command is ready elif cmd == cmd_StopButton: pass elif cmd == cmd_SetValues: self.SetValues(rtn[0], rtn[1], rtn[2], rtn[3], rtn[4], rtn[5], rtn[6], rtn[7], rtn[8], rtn[9], rtn[10]) # rtn is tuple elif cmd == cmd_SetMessages: self.SetMessages( rtn[0], rtn[1], rtn[2]) # rtn is (Tacx, Dongle, HRM) tuple elif cmd == cmd_PedalStrokeAnalysis: self.PedalStrokeAnalysis( rtn[0], rtn[1]) # rtn is (info, Cadence) tuple pass else: logfile.Console( '%s active but unknown response received (%s, %s); the message is ignored.' % (command, cmd, rtn)) break return rtn
def Close(): try: if debug.on(): fLogfile.close if debug.on(debug.LogfileJson): LogfileJson.Close() except: pass
def Open(prefix='FortiusANT', suffix=''): global fLogfile, LogfileJson if debug.on(): if len(suffix) > 0 and suffix[0] != '.': suffix = '.' + suffix filename = prefix + '.' + datetime.now().strftime('%Y-%m-%d %H-%M-%S') + suffix + ".log" fLogfile = open(filename,"w+") if debug.on(debug.LogfileJson) and prefix == 'FortiusANT': LogfileJson = clsLogfileJson(filename.replace('.log', '.json'))
def Close(self): if self.interface: if debug.on(debug.Ble): logfile.Write("BleInterface.Close() ...") self.interface.terminate() self.interface.wait() self.interface = None self.Message = ", Bluetooth interface closed" self.OK = False if debug.on(debug.Ble): logfile.Write("... completed") else: pass
def Write (logText): logText = datetime.utcnow().strftime('%H:%M:%S,%f')[0:12] + ": " + logText print (logText) if debug.on(): try: test = fLogfile except: Open() # if module not initiated, open implicitly try: if debug.on(): fLogfile.write(logText + "\n") # \r\n except: print ("logfile.Write (" + logText + ") called, but logfile is not opened.")
def SetValues(self, fSpeed, iRevs, iPower, iTargetMode, iTargetPower, fTargetGrade, iTacx, iHeartRate): # -------------------------------------------------------------------------- # Calculate delta time since previous call # -------------------------------------------------------------------------- delta = time.time() - staticVariables.LastTime # Delta time since previous # -------------------------------------------------------------------------- # Update current readings # -------------------------------------------------------------------------- if clv.gui: self.SetValues(fSpeed, iRevs, iPower, iTargetMode, iTargetPower, fTargetGrade, iTacx, iHeartRate) if delta >= 1 and (not clv.gui or debug.on(debug.Any)): staticVariables.LastTime = time.time() # Time in seconds if iTargetMode == gui.mode_Power: sTarget = "%3.0fW" % iTargetPower elif iTargetMode == gui.mode_Grade: sTarget = "%3.1f%%" % fTargetGrade else: sTarget = "None" msg = "Target=%s Speed=%4.1fkmh hr=%3.0f Current=%3.0fW Cad=%3.0f r=%4.0f %3.0f%%" % \ (sTarget, fSpeed, iHeartRate, iPower, iRevs, iTacx, int(clv.PowerFactor * 100) ) logfile.Write(msg)
def SetValues(self, fSpeed, iRevs, iPower, iTargetMode, iTargetPower, fTargetGrade, iTacx, iHeartRate, iTeeth, extra=None): # ---------------------------------------------------------------------- # Console: Update current readings, once per second # ---------------------------------------------------------------------- delta = time.time() - self.LastTime # Delta time since previous if delta >= 1 and (not clv.gui or debug.on(debug.Application)): self.LastTime = time.time() # Time in seconds if iTargetMode == gui.mode_Power: sTarget = "%3.0fW" % iTargetPower elif iTargetMode == gui.mode_Grade: sTarget = "%3.1f%%" % fTargetGrade if iTargetPower > 0: # 2020-01-22 sTarget += "(%iW)" % iTargetPower # Target power added for reference else: sTarget = "None" msg = "Target=%s Speed=%4.1fkmh hr=%3.0f Current=%3.0fW Cad=%3.0f r=%4.0f T=%3.0f" % \ ( sTarget, fSpeed, iHeartRate, iPower, iRevs, iTacx, int(iTeeth) ) logfile.Console(msg)
def Open(): global fLogfile if debug.on(): filename = "FortiusANT." + datetime.utcnow().strftime( '%Y-%m-%d %H-%M-%S') + ".log" fLogfile = open(filename, "w+")
def SetValues(self, fSpeed, iRevs, iPower, iTargetMode, iTargetPower, fTargetGrade, iTacx, iHeartRate, iCrancksetIndex, iCassetteIndex, fReduction): delta = time.time() - self.LastTime # Delta time since previous call if delta >= 1: # Do not send faster than once per second self.LastTime = time.time() # Time in seconds if debug.on(debug.MultiProcessing): logfile.Write ("mp-MainDataToGUI(%s, (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s))" % \ (cmd_SetValues, fSpeed, iRevs, iPower, iTargetMode, iTargetPower, fTargetGrade, iTacx, iHeartRate, iCrancksetIndex, iCassetteIndex, fReduction)) self.app_conn.send((cmd_SetValues, (fSpeed, iRevs, iPower, iTargetMode, iTargetPower, fTargetGrade, iTacx, iHeartRate, iCrancksetIndex, iCassetteIndex, fReduction)))
def print(self): try: v = debug.on(debug.Any) # Verbose: print all command-line variables with values if self.autostart: logfile.Console("-a") if self.PedalStrokeAnalysis:logfile.Console("-A") if v or self.args.CalibrateRR: logfile.Console("-c %s" % self.CalibrateRR ) if v or self.args.debug: logfile.Console("-d %s (%s)" % (self.debug, bin(self.debug) ) ) if v or self.args.antDeviceID: logfile.Console("-D %s" % self.antDeviceID ) if v or self.args.GradeAdjust: if self.GradeAdjust == 1: logfile.Console("-G defines Grade = antGrade * %s" \ % (self.GradeFactor ) ) if self.GradeAdjust == 2: logfile.Console("-G defines Grade = antGrade * %s [* %s (downhill)]" \ % (self.GradeFactor, self.GradeFactorDH) ) if self.GradeAdjust == 3: logfile.Console("-G defines Grade = (antGrade - %s) * %s [* %s (downhill)]" \ % (self.GradeShift, self.GradeFactor, self.GradeFactorDH) ) if self.gui: logfile.Console("-g") if v or self.args.hrm: logfile.Console("-H %s" % self.hrm ) if self.manual: logfile.Console("-m") if self.manualGrade: logfile.Console("-M") if not self.args.calibrate: logfile.Console("-n") if v or self.args.factor: logfile.Console("-p %s" % self.PowerFactor ) if self.args.PowerMode: logfile.Console("-P") if self.args.Resistance: logfile.Console("-r") if self.args.simulate: logfile.Console("-s") #scs if v or self.args.scs: logfile.Console("-S %s" % self.scs ) if v or self.args.TacxType: logfile.Console("-t %s" % self.TacxType) if self.exportTCX: logfile.Console("-x") except: pass # May occur when incorrect command line parameters, error already given before
def print(self): try: v = debug.on( debug.Any ) # Verbose: print all command-line variables with values if self.autostart: logfile.Console("-a") if self.PedalStrokeAnalysis: logfile.Console("-A") if v or self.args.debug: logfile.Console("-d %s (%s)" % (self.debug, bin(self.debug))) if self.gui: logfile.Console("-g") if v or self.args.hrm: logfile.Console("-H %s" % self.hrm) if self.manual: logfile.Console("-m") if self.manualGrade: logfile.Console("-M") if not self.args.calibrate: logfile.Console("-n") if v or self.args.factor: logfile.Console("-p %s" % self.PowerFactor) if self.args.PowerMode: logfile.Console("-P") if self.args.simulate: logfile.Console("-s") #scs if self.args.scs: logfile.Console("-S %s" % self.scs ) if self.args.TacxType: logfile.Console("-t %s" % self.TacxType) if self.uphill: logfile.Console("-u") #------------------------------------------------------------------- # Deprecated #------------------------------------------------------------------- # if v or self.args.bicycle: logfile.Console("-b %s,%s/%s,%s/%s" % (self.tyre, self.fL, self.fS, self.rS, self.rL)) # if v or self.args.ftp: logfile.Console("-f %s" % self.ftp ) # if v or self.args.resistance: logfile.Console("-r %s/%s" % (self.ResistanceH, self.ResistanceL)) except: pass # May occur when incorrect command line parameters, error already given before
def Write(logText, console=False): logText = datetime.utcnow().strftime('%H:%M:%S,%f')[0:12] + ": " + logText if console: print(logText) sys.stdout.flush() if debug.on(): try: test = fLogfile except: Open() # if module not initiated, open implicitly try: if debug.on(): fLogfile.write(logText + "\n") # \r\n except: # print ("logfile.Write (" + logText + ") called, but logfile is not opened.") pass
def Open(prefix='FortiusANT', suffix=''): global fLogfile if debug.on(): if len(suffix) > 0 and suffix[0] != '.': suffix = '.' + suffix filename = prefix + '.' + datetime.utcnow().strftime('%Y-%m-%d %H-%M-%S') + suffix + ".log" fLogfile = open(filename,"w+")
def MainCommandFromGui(self): # Step 2. Main receives command from GUI msg = self.app_conn.recv() command = msg[0] p1 = msg[1] p2 = msg[2] if debug.on(debug.MultiProcessing) and not (command == cmd_Idle): logfile.Write ("mp-MainCommandFromGui() returns (%s, %s, %s)" % (command, p1, p2)) return command, p1, p2
def PedalStrokeAnalysis(self, info, Cadence): if debug.on(debug.MultiProcessing): logfile.Write("mp-MainDataToGUI(%s, (info, %s))" % (cmd_PedalStrokeAnalysis, Cadence)) self.app_conn.send( (cmd_PedalStrokeAnalysis, (info, Cadence))) # x. Main sends messages to GUI; no response expected pass
def InitialiseTrainer(dev): # will not read cadence until initialisation byte is sent data = struct.pack(sc.unsigned_int, 0x00000002) if debug.on(debug.Data2): logfile.Write("InitialiseTrainer data=%s (len=%s)" % (logfile.HexSpace(data), len(data))) dev.write(0x02, data)
def SetMessages(self, Tacx=None, Dongle=None, HRM=None): newMessages = (Tacx, Dongle, HRM) if newMessages != self.PreviousMessages: # Send immediatly if changed self.PreviousMessages = newMessages if debug.on(debug.MultiProcessing): logfile.Write("mp-MainDataToGUI(%s, (%s, %s, %s))" % (cmd_SetMessages, Tacx, Dongle, HRM)) self.app_conn.send( (cmd_SetMessages, (Tacx, Dongle, HRM))) # x. Main sends messages to GUI; no response expected
def Write(self, data): rtn = False if debug.on(debug.Ble): logfile.Write('BleInterface.Write(%s)' % data) if self.interface: url = f'http://{self.host}:{self.port}/ant' try: r = requests.post(url, data=data) except Exception as e: logfile.Console("... requests.post() error " + str(e)) else: rtn = r.ok return rtn
def SetValues(self, fSpeed, iRevs, iPower, iTargetMode, iTargetPower, \ fTargetGrade, iTacx, iHeartRate, iCrancksetIndex, iCassetteIndex, fReduction): global clv # ---------------------------------------------------------------------- # Console: Update current readings, once per second # ---------------------------------------------------------------------- delta = time.time() - self.LastTime # Delta time since previous if delta >= 1 and (not clv.gui or debug.on(debug.Application)): self.LastTime = time.time() # Time in seconds if clv.imperial: s1 = fSpeed / mile s2 = "mph" else: s1 = fSpeed s2 = "km/h" if iTargetMode == mode_Power: sTarget = "%3.0fW" % iTargetPower elif iTargetMode == mode_Grade: sTarget = "%3.1f%%" % fTargetGrade if iTargetPower > 0: # 2020-01-22 sTarget += "(%iW)" % iTargetPower # Target power added for reference else: sTarget = "None" if clv.hrm == -1: h = "" else: h = "hr=%3.0f " % iHeartRate all = False self.leds = "" if all or True: # Led 1 = Tacx trainer; USB, ANT or Simulated self.leds += "t" if self.StatusLeds[0] else "-" if all or OnRaspberry: # Led 2 = on raspberry only self.leds += "s" if self.StatusLeds[1] else "-" if all or clv.Tacx_Cadence: # Led 3 = Cadence sensor (black because backgroup is white) self.leds += "c" if self.StatusLeds[2] else "-" if all or clv.ble: # Led 4 = Bluetooth CTP self.leds += "b" if self.StatusLeds[3] else "-" if all or clv.antDeviceID != -1: # Led 5 = ANT CTP self.leds += "a" if self.StatusLeds[4] else "-" msg = "Target=%s %4.1f%s %sCurrent=%3.0fW Cad=%3.0f r=%4.0f %3s%% %s" % \ (sTarget, s1,s2, h, iPower, iRevs, iTacx, int(fReduction*100), self.leds) logfile.Console (msg)
def Open(self): self.OK = False self.Message = ", Bluetooth interface cannot be opened" if debug.on(debug.Ble): logfile.Write("BleInterface.Open() ...") if self.interface: if debug.on(debug.Ble): logfile.Write('... already open') else: #----------------------------------------------------------- # path to find ./node (in the parent of the directory where # 'we' are located) assuming directory structure: # ./node # ./pythoncode # ./WindowsExecutable #----------------------------------------------------------- if getattr(sys, 'frozen', False): dirname = os.path.realpath( sys.argv[0]) # the started executable else: dirname = str(lib_programname.get_path_executed_script() ) # type: pathlib.Path dirname = os.path.dirname( dirname) # Remove /filename.py or /filename.exe dirname = dirname.replace('\\', '/') # Unify separator = / dirname = dirname[0:dirname.rfind('/')] # Remove last level #----------------------------------------------------------- # Create interface as sub-process #----------------------------------------------------------- command = ["node", "server.js"] directory = dirname + "/node" if debug.on(debug.Ble): logfile.Write("... Popen(%s,%s)" % (directory, command)) try: if debug.on(debug.Any): self.interface = subprocess.Popen( command, cwd=directory, stdout=logfile.fLogfile, stderr=logfile.fLogfile) else: self.interface = subprocess.Popen(command, cwd=directory) except Exception as e: self.Message += "; " + str(e) if debug.on(debug.Ble): logfile.Write("... " + str(e)) else: if debug.on(debug.Ble): logfile.Write('... completed') self.Message = ", Bluetooth interface open" self.OK = True if self.OK: logfile.Console( "FortiusANT exchanges data with a bluetooth Cycling Training Program" ) return self.OK
def Settings(self, pRestartApplication, pclv): global RestartApplication, clv RestartApplication = pRestartApplication clv = pclv if debug.on(debug.Function): logfile.Write ("FortiusAnt.Settings(%s, %s)" % (pRestartApplication, pclv.debug)) if testMode: print('') logfile.Console ('Transfer settings') time.sleep(1) logfile.Console ('Done') rtn = True else: rtn = FortiusAntBody.Settings(self, pRestartApplication, pclv) return rtn
def print(self): try: v = debug.on( debug.Any ) # Verbose: print all command-line variables with values if self.autostart: logfile.Console("-a") if self.SimulateTrainer: logfile.Console("-s") if v or self.args.debug: logfile.Console("-d %s (%s)" % (self.debug, bin(self.debug))) if v or self.args.dongle: logfile.Console("-D %s (%s)" % (self.dongle, hex(self.dongle))) if v or self.args.hrm: logfile.Console("-H %s (%s)" % (self.hrm, hex(self.hrm))) if v or self.args.fe: logfile.Console("-F %s (%s)" % (self.fe, hex(self.fe))) if v or self.args.scs: logfile.Console("-S %s (%s)" % (self.scs, hex(self.scs))) if v or self.args.vtx: logfile.Console("-V %s (%s)" % (self.vtx, hex(self.vtx))) except: pass # May occur when incorrect command line parameters, error already given before
def Write(self, data): rtn = False retry = 10 if debug.on(debug.Ble): logfile.Write('BleInterface.Write(%s)' % data) while retry and not rtn and self.interface: url = f'http://{self.host}:{self.port}/ant' try: r = requests.post(url, data=data) except Exception as e: msg = "... requests.post() error " + str(e) if retry and '[Errno 111]' in msg: retry -= 1 time.sleep(0.250) logfile.Write(msg) else: retry = 0 logfile.Console(msg) else: rtn = r.ok return rtn
def Open(self): self.OK = False self.Message = ", Bluetooth interface cannot be opened" if debug.on(debug.Ble): logfile.Write("BleInterface.Open() ...") if self.interface: if debug.on(debug.Ble): logfile.Write('... already open') else: #----------------------------------------------------------- # Create interface as sub-process #----------------------------------------------------------- command = ["node", "server.js"] directory = Path.cwd().parent / "node" if debug.on(debug.Ble): logfile.Write("... Popen(%s,%s)" % (directory, command)) try: if debug.on(debug.Any): self.interface = subprocess.Popen( command, cwd=directory, stdout=logfile.fLogfile, stderr=logfile.fLogfile) else: self.interface = subprocess.Popen(command, cwd=directory) except Exception as e: self.Message += "; " + str(e) if debug.on(debug.Ble): logfile.Write("... " + str(e)) else: if debug.on(debug.Ble): logfile.Write('... completed') self.Message = ", Bluetooth interface opened to CTP" self.OK = True if self.OK: logfile.Console( "FortiusANT exchanges data with a bluetooth Cycling Training Program" ) return self.OK
def mainProgram(): global RestartApplication, clv # -------------------------------------------------------------------------- # Initialize # -------------------------------------------------------------------------- debug.deactivate() if not RestartApplication: clv = cmd.CommandLineVariables() debug.activate(clv.debug) FortiusAntBody.Initialize(clv) if debug.on(debug.Any): logfile.Open() logfile.Console("FortiusANT started") logfile.Write (' Restart=%s debug=%s' % (RestartApplication, clv.debug)) clv.print() logfile.Console("------------------") RestartApplication = False #------------------------------------------------------------------------------- # Component info #------------------------------------------------------------------------------- if debug.on(debug.Any): # ---------------------------------------------------------------------- if getattr(sys, 'frozen', False): logfile.Write('Windows executable started') else: logfile.Write('Python version started') # ---------------------------------------------------------------------- logfile.Write('Version info for the components' ) logfile.Write(githubWindowTitle()) s = " %20s = %s" logfile.Write(s % ('FortiusAnt', __version__ )) logfile.Write(s % ('antDongle', ant.__version__ )) logfile.Write(s % ('antFE', fe.__version__ )) logfile.Write(s % ('antHRM', hrm.__version__ )) logfile.Write(s % ('antPWR', pwr.__version__ )) logfile.Write(s % ('antSCS', scs.__version__ )) logfile.Write(s % ('bleDongle', bleDongle.__version__ )) logfile.Write(s % ('constants', constants.__version__ )) logfile.Write(s % ('debug', debug.__version__ )) logfile.Write(s % ('FortiusAntBody', FortiusAntBody.__version__ )) logfile.Write(s % ('FortiusAntCommand', cmd.__version__ )) if UseGui: logfile.Write(s % ('FortiusAntGui', gui.__version__ )) logfile.Write(s % ('logfile', logfile.__version__ )) if UseGui: logfile.Write(s % ('RadarGraph', RadarGraph.__version__ )) logfile.Write(s % ('settings', settings.__version__ )) logfile.Write(s % ('structConstants', sc.__version__ )) logfile.Write(s % ('TCXexport', TCXexport.__version__ )) logfile.Write(s % ('usbTrainer', usbTrainer.__version__ )) logfile.Write(s % ('argparse', argparse.__version__ )) # logfile.Write(s % ('binascii', binascii.__version__ )) # logfile.Write(s % ('math', math.__version__ )) logfile.Write(s % ('numpy', numpy.__version__ )) logfile.Write(s % ('os', os.name )) if os.name == 'nt': v = sys.getwindowsversion() logfile.Write((s + '.%s') % ('windows', v.major, v.minor)) logfile.Write(s % ('pickle', pickle.format_version )) logfile.Write(s % ('platform', platform.__version__ )) # logfile.Write(s % ('glob', glob.__version__ )) # logfile.Write(s % ('random', random.__version__ )) logfile.Write(s % ('sys (python)', sys.version )) # logfile.Write(s % ('struct', struct.__version__ )) # logfile.Write(s % ('threading', threading.__version__ )) # logfile.Write(s % ('time', time.__version__ )) logfile.Write(s % ('usb', usb.__version__ )) if UseGui: logfile.Write(s % ('wx', wx.__version__ )) logfile.Write('FortiusANT code flags') logfile.Write(s % ('UseMultiProcessing', UseMultiProcessing)) logfile.Write(s % ('UseGui', UseGui)) logfile.Write(s % ('UseBluetooth', UseBluetooth)) logfile.Write("------------------") if not clv.gui: # -------------------------------------------------------------------------- # Console only, no multiprocessing required to separate GUI # -------------------------------------------------------------------------- Console = clsFortiusAntConsole() Console.Autostart() elif not UseMultiProcessing: # -------------------------------------------------------------------------- # No multiprocessing wanted, start GUI immediatly # -------------------------------------------------------------------------- clv.PedalStrokeAnalysis = False app = wx.App(0) frame = frmFortiusAnt(None, clv) app.SetTopWindow(frame) frame.Show() if clv.autostart: frame.Autostart() app.MainLoop() else: # -------------------------------------------------------------------------- # Multiprocessing wanted, start GUI in it's own process # -------------------------------------------------------------------------- # https://docs.python.org/3/library/multiprocessing.html # Create queue and sub-process # -------------------------------------------------------------------------- app_conn, gui_conn = multiprocessing.Pipe(True) pChild = multiprocessing.Process(target=FortiusAntChild, args=(clv, gui_conn) ) pChild.start() # -------------------------------------------------------------------------- # Poll child-process untill done # -------------------------------------------------------------------------- parent = clsFortiusAntParent(app_conn) # The child process has the GUI parent.ListenToChild() # -------------------------------------------------------------------------- # Wait for child-process to complete # -------------------------------------------------------------------------- pChild.join() # ------------------------------------------------------------------------------ # We're done # ------------------------------------------------------------------------------ if debug.on(debug.Any): logfile.Console('FortiusAnt ended') logfile.Close()
def MainRespondToGUI(self, command, rtn): if debug.on(debug.MultiProcessing) and not (command == cmd_Idle and rtn == 0): logfile.Write ("mp-MainRespondToGUI(%s, %s)" % (command, rtn)) self.app_conn.send((command, rtn)) # Step 3. Main sends the response to GUI