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
Exemple #2
0
        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
Exemple #3
0
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
Exemple #4
0
        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
Exemple #5
0
        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
Exemple #6
0
 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
Exemple #7
0
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)
Exemple #8
0
    def PedalStrokeAnalysis(self, info, Cadence):
        self.Cadence    = Cadence
        self.StartTime  = info[0][0]            # First element = at pedelecho
        data            = []
        logfile.Write('PedalStrokeAnalysis - Cadence=%3s info=%3s StartTime=%s' % \
                        (self.Cadence, len(info), self.StartTime))
        for i in info:
            Angle = self.Angle(i[0])
            if Angle == -1: break

            Power = i[1]

            d = (Angle, Power)
            logfile.Write('Angle=%3s power=%5s Time=%s' % (Angle, Power, i[0]))
            data.append(d)
        self.ShowRadarGraph(data)
Exemple #9
0
 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 g(name, fn, t, f, conn):
    debug.activate(debug.All)
    logfile.Open(fn, name)
    logfile.Write(fn)

    for i in range(0, 100):
        logfile.Write(name, i)

        # Communicate "results" to parent_conn
        # Then receive whether to proceed or to stop
        if i % f == 0:
            conn.send([i, None, 'hello', name])
            if conn.recv(): break

        # Wait, so we cycle once per second
        time.sleep(t)
Exemple #11
0
 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
Exemple #12
0
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)
Exemple #13
0
 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
Exemple #14
0
 def print(self):
     try:
         if self.args.autostart: logfile.Write("-a")
         if self.args.bicycle:
             logfile.Write("-b %s,%s/%s,%s/%s" %
                           (self.tyre, self.fL, self.fS, self.rS, self.rL))
         if self.args.debug:
             logfile.Write("-d %s (%s)" % (self.debug, bin(self.debug)))
         if self.args.ftp: logfile.Write("-f %s" % self.ftp)
         if self.args.gui: logfile.Write("-g")
         if self.args.manual: logfile.Write("-m")
         if not self.args.calibrate: logfile.Write("-n")
         if self.args.factor: logfile.Write("-p %s" % self.PowerFactor)
         if self.args.resistance:
             logfile.Write("-r %s/%s" %
                           (self.ResistanceH, self.ResistanceL))
         if self.args.simulate: logfile.Write("-s")
     except:
         pass  # May occur when incorrect command line parameters, error already given before
Exemple #15
0
 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
Exemple #16
0
 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
Exemple #17
0
 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
Exemple #18
0
        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
Exemple #19
0
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.Write("-a")
         if self.SimulateTrainer: logfile.Write("-s")
         if v or self.args.debug:
             logfile.Write("-d %s (%s)" % (self.debug, bin(self.debug)))
         if v or self.args.dongle:
             logfile.Write("-D %s (%s)" % (self.dongle, hex(self.dongle)))
         if v or self.args.hrm:
             logfile.Write("-H %s (%s)" % (self.hrm, hex(self.hrm)))
         if v or self.args.fe:
             logfile.Write("-F %s (%s)" % (self.fe, hex(self.fe)))
         if v or self.args.scs:
             logfile.Write("-S %s (%s)" % (self.scs, hex(self.scs)))
         if v or self.args.vtx:
             logfile.Write("-V %s (%s)" % (self.vtx, hex(self.vtx)))
     except:
         pass  # May occur when incorrect command line parameters, error already given before
Exemple #21
0
    def OnPaint(self, event):
        # ----------------------------------------------------------------------
        # Draw background
        # ----------------------------------------------------------------------
        dc = wx.PaintDC(self)
        dc.DrawBitmap(self.BackgroundBitmap, 0, 0)  # LeftTop in pixels

        # ----------------------------------------------------------------------
        # Draw HeartRate
        #       Image functions done once, instead of every OnPaint()
        # ----------------------------------------------------------------------
        if self.HeartRateImage and self.HeartRate > 40:
            #           img = self.HeartRateImage.Scale(self.HeartRateWH, self.HeartRateWH, wx.IMAGE_QUALITY_HIGH)
            #           bmp = wx.Bitmap(img)
            if self.HeartRateWH == 36:
                dc.DrawBitmap(self.bmp36x36, self.HeartRateX, self.HeartRateY)
            elif self.HeartRateWH == 40:
                dc.DrawBitmap(self.bmp40x40, self.HeartRateX, self.HeartRateY)
            else:
                logfile.Write("Unsupported image size")
        else:
            pass
    def __init__(self):
        #-----------------------------------------------------------------------
        # Define and process command line
        #-----------------------------------------------------------------------
        parser = argparse.ArgumentParser(
            description=
            'Program to broadcast data from USB Tacx Fortius trainer, and to receive resistance data for the trainer'
        )
        parser.add_argument('-a',
                            '--autostart',
                            help='Automatically start',
                            required=False,
                            action='store_true')
        s = '%s,%s/%s,%s/%s' % (self.__tyre__, self.__fL__, self.__fS__,
                                self.__rS__, self.__rL__)
        parser.add_argument('-b',
                            '--bicycle',
                            help='Bicycle definition, default=' + s,
                            required=False,
                            default=False)
        parser.add_argument('-d',
                            '--debug',
                            help='Show debugging data',
                            required=False,
                            default=False)
        parser.add_argument('-f',
                            '--ftp',
                            help='FTP of the rider, default=%s' % self.__ftp__,
                            required=False,
                            default=False)
        parser.add_argument('-g',
                            '--gui',
                            help='Run with graphical user interface',
                            required=False,
                            action='store_true')
        parser.add_argument(
            '-H',
            '--hrm',
            help='Use this Heart Rate Monitor (0: default, -1: none)',
            required=False,
            default=False)
        parser.add_argument(
            '-m',
            '--manual',
            help='Run manual power (ignore target from antDongle)',
            required=False,
            action='store_true')
        parser.add_argument(
            '-M',
            '--manualGrade',
            help='Run manual grade (ignore target from antDongle)',
            required=False,
            action='store_true')
        parser.add_argument('-n',
                            '--calibrate',
                            help='Do not calibrate before start',
                            required=False,
                            action='store_false')
        parser.add_argument(
            '-p',
            '--factor',
            help='Adjust target Power by multiplying by this factor',
            required=False,
            default=False)
        parser.add_argument(
            '-r',
            '--resistance',
            help='FTP percentages for resistance mode, default=150/100',
            required=False,
            default=False)
        parser.add_argument('-s',
                            '--simulate',
                            help='Simulated trainer to test ANT+ connectivity',
                            required=False,
                            action='store_true')
        #scs    parser.add_argument('-S','--scs',       help='Use this Speed Cadence Sensor (0: default device)',   required=False, default=False)
        args = parser.parse_args()
        self.args = args

        #-----------------------------------------------------------------------
        # Booleans; either True or False
        #-----------------------------------------------------------------------
        self.autostart = args.autostart
        self.gui = args.gui
        self.manual = args.manual
        self.manualGrade = args.manualGrade
        self.calibrate = args.calibrate
        self.SimulateTrainer = args.simulate

        if self.manual and self.manualGrade:
            logfile.Write(
                "-m and -M are mutually exclusive; manual power selected")
            self.manualGrade = False  # Mutually exclusive

        if (self.manual or self.manualGrade) and self.SimulateTrainer:
            logfile.Write(
                "-m/-M and -s both specified, most likely for program test purpose"
            )

        #-----------------------------------------------------------------------
        # Bicycle definition to be parsed; three parameters
        # format=tyre,chainring,cassette, e.g. "2.096,50/34,15/25"
        #-----------------------------------------------------------------------
        if args.bicycle:
            b = args.bicycle.split(",")
            #-------------------------------------------------------------------
            # parameter1: Tyre defined?
            #-------------------------------------------------------------------
            if len(b) >= 1:
                try:
                    self.tyre = float(b[0])
                    if self.tyre < 1: self.tyre = self.__tyre__
                except:
                    logfile.Write('Command line error; -b incorrect tyre=%s' %
                                  b[0])
                    self.tyre = self.__tyre__

            #-------------------------------------------------------------------
            # parameter2: Chainring, large/small separated by /
            # format=large/small, e.g. 50/34
            # If one value is specified, e.g. "50" 50/50 is assumed
            #-------------------------------------------------------------------
            if len(b) >= 2:
                s = b[1].split('/')
                if len(s) >= 0:
                    try:
                        self.fL = int(s[0])
                    except:
                        logfile.Write(
                            'Command line error; -b incorrect large chainring=%s'
                            % s[0])

                self.fS = self.fL  # Default is single chainring
                if len(s) >= 1:
                    try:
                        self.fS = int(s[1])
                    except:
                        logfile.Write(
                            'Command line error; -b incorrect small chainring=%s'
                            % s[1])

            #-------------------------------------------------------------------
            # parameter3: Cassette, small/large separated by /
            # If one value is specified, e.g. "15" 15/15 is assumed
            #-------------------------------------------------------------------
            if len(b) >= 3:
                s = b[2].split('/')
                if len(s) >= 0:
                    try:
                        self.rS = int(s[0])
                    except:
                        logfile.Write(
                            'Command line error; -b incorrect small cassette=%s'
                            % s[0])

                self.rL = self.rS  # Default is single speed cassette
                if len(s) >= 1:
                    try:
                        self.rL = int(s[1])
                    except:
                        logfile.Write(
                            'Command line error; -b incorrect large cassette=%s'
                            % s[1])

        #-----------------------------------------------------------------------
        # Get debug-flags, used in debug module
        #-----------------------------------------------------------------------
        if args.debug:
            try:
                self.debug = int(args.debug)
            except:
                logfile.Write(
                    'Command line error; -d incorrect debugging flags=%s' %
                    args.debug)

        #-----------------------------------------------------------------------
        # Get riders FTP
        #-----------------------------------------------------------------------
        if args.ftp:
            try:
                self.ftp = int(args.ftp)
                if self.ftp < 50: self.ftp = self.__ftp__
            except:
                logfile.Write('Command line error; -f incorrect ftp=%s' %
                              args.ftp)

        #-----------------------------------------------------------------------
        # Get HRM
        # - None: read HRM from Tacx Fortius and broadcast as HRM master device
        # - -1  : no master and no slave device
        # - 0   : pair with the first ANT+ HRM that is found
        # - next: pair with the defined ANT+ HRM monitor
        #             the number can be found with ExplorANT
        #-----------------------------------------------------------------------
        if args.hrm:
            try:
                self.hrm = int(args.hrm)
            except:
                logfile.Write('Command line error; -H incorrect HRM=%s' %
                              args.hrm)

        #-----------------------------------------------------------------------
        # Get SCS
        # - None: No Speed Cadence Sensor
        # - 0   : pair with the first ANT+ SCS that is found
        # - next: pair with the defined ANT+ SCS
        #             the number can be found with ExplorANT
        #-----------------------------------------------------------------------
#scs    if args.scs:
#scs        try:
#scs            self.scs = int(args.scs)
#scs        except:
#scs            logfile.Write('Command line error; -S incorrect SCS=%s' % args.scs)

#-----------------------------------------------------------------------
# Get powerfactor
#-----------------------------------------------------------------------
        if args.factor:
            try:
                self.PowerFactor = float(args.factor)
            except:
                logfile.Write(
                    'Command line error; -f incorrect power factor=%s' %
                    args.factor)

        #-----------------------------------------------------------------------
        # Parse Resistance
        #-----------------------------------------------------------------------
        if args.resistance:
            s = args.resistance.split('/')
            if len(s) >= 0:
                try:
                    self.ResistanceH = int(s[0])
                except:
                    logfile.Write(
                        'Command line error; -r incorrect high resistance=%s' %
                        s[0])

            if len(s) >= 1:
                try:
                    self.ResistanceL = int(s[1])
                except:
                    logfile.Write(
                        'Command line error; -r incorrect low resistance=%s' %
                        s[1])
Exemple #23
0
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()
Exemple #24
0
 def SetLeds(self, ANT=None, BLE=None, Cadence=None, Shutdown=None, Tacx=None):
     if debug.on(debug.MultiProcessing): logfile.Write ("mp-MainDataToGUI(%s, (%s, %s, %s, %d, %s))" % (cmd_SetLeds, Tacx, Shutdown, Cadence, BLE, ANT))
     self.app_conn.send((cmd_SetLeds, (ANT, BLE, Cadence, Shutdown, Tacx)))  # x. Main sends messages to GUI; no response expected
Exemple #25
0
 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
    def print(self):
        try:
            v = debug.on(
                debug.Any
            )  # Verbose: print all command-line variables with values
            if self.autostart: logfile.Write("-a")
            if v or self.args.bicycle:
                logfile.Write("-b %s,%s/%s,%s/%s" %
                              (self.tyre, self.fL, self.fS, self.rS, self.rL))
            if v or self.args.debug:
                logfile.Write("-d %s (%s)" % (self.debug, bin(self.debug)))
            if v or self.args.ftp: logfile.Write("-f %s" % self.ftp)
            if self.gui: logfile.Write("-g")
            if v or self.args.hrm: logfile.Write("-H %s" % self.hrm)
            if self.manual: logfile.Write("-m")
            if self.manualGrade: logfile.Write("-M")
            if not self.args.calibrate: logfile.Write("-n")
            if v or self.args.factor: logfile.Write("-p %s" % self.PowerFactor)
            if v or self.args.resistance:
                logfile.Write("-r %s/%s" %
                              (self.ResistanceH, self.ResistanceL))
            if self.args.simulate: logfile.Write("-s")
#scs        if      self.args.scs:           logfile.Write ("-S %s" % self.scs )
        except:
            pass  # May occur when incorrect command line parameters, error already given before
Exemple #27
0
                    else:
                        DeviceType = '?'

                    #-----------------------------------------------------------
                    # Store in device table, so we print at the end of loop
                    #-----------------------------------------------------------
                    deviceID = clsDeviceID(Channel, DeviceType, DeviceNumber,
                                           DeviceTypeID, TransmissionType)
                    # print (Channel, end=' ')
                    if DeviceNumber == 0:  # No device paired, request again
                        AntDongle.Write([ant.msg4D_RequestMessage(Channel, ant.msgID_ChannelID)], \
                                        False, False)
                        pass
                    else:
                        d = deviceID
                        logfile.Write ("ExplorANT: %3s discovered on channel=%s, number=%5s typeID=%3s TrType=%3s" % \
                            (d.DeviceType, d.Channel, d.DeviceNumber, d.DeviceTypeID, d.TransmissionType) )
                        if not deviceID in deviceIDs:
                            print('%s=%s' % (d.Channel, DeviceType), end=' ')
                            logfile.Write('ExplorANT: added to list')

                            deviceIDs.append(deviceID)

                            #---------------------------------------------------
                            # Ask the found device for more info; page 70
                            #---------------------------------------------------
                            info = ant.msgPage70_RequestDataPage(
                                Channel, ant.DeviceNumber_EA, 255, 255, 1, 70,
                                0)
                            d = ant.ComposeMessage(ant.msgID_AcknowledgedData,
                                                   info)
                            AntDongle.Write([d], False)
Exemple #28
0
# Description:  Show all dongles available
#               Open defined dongle
#               Start listening what's going on in the air
#
# Output:       Console/logfile
#
# Returns:      None
# ------------------------------------------------------------------------------

debug.deactivate()
clv = cmd.Create()
debug.activate(clv.debug)

if True or debug.on(debug.Any):
    logfile.Open('ExplorANT')
    logfile.Write("ExplorANT started")
    clv.print()
    logfile.Write("--------------------")

# ------------------------------------------------------------------------------
# First enumerate all dongles
# ------------------------------------------------------------------------------
ant.EnumerateAll()

# ------------------------------------------------------------------------------
# Open dongle; either the defined one or default
#
# Note, it does not matter which dongle you open.
# The dongle itself means a connection to the ANT+ network
# Each application starting can use any ANT+ dongle
# ------------------------------------------------------------------------------
Exemple #29
0
    debug.deactivate()
    clv = cmd.CommandLineVariables()
    debug.activate(clv.debug)
    FortiusAntBody.Initialize(clv)

    if debug.on(debug.Any):
        logfile.Open()
        logfile.Console("FortiusANT started")
        clv.print()
        logfile.Console("------------------")

    #-------------------------------------------------------------------------------
    # Component info
    #-------------------------------------------------------------------------------
    if debug.on(debug.Any):
        logfile.Write('Version info for the components')
        s = " %20s = %s"
        logfile.Write(s % ('FortiusAnt', __version__))
        logfile.Write(s % ('antDongle', ant.__version__))
        logfile.Write(s % ('antHRM', hrm.__version__))
        logfile.Write(s % ('antFE', fe.__version__))
        logfile.Write(s % ('debug', debug.__version__))
        logfile.Write(s % ('FortiusAntBody', FortiusAntBody.__version__))
        logfile.Write(s % ('FortiusAntCommand', cmd.__version__))
        logfile.Write(s % ('FortiusAntGui', gui.__version__))
        logfile.Write(s % ('logfile', logfile.__version__))
        logfile.Write(s % ('structConstants', sc.__version__))
        logfile.Write(s % ('usbTrainer', usbTrainer.__version__))

        logfile.Write(s % ('argparse', argparse.__version__))
        #   logfile.Write(s % ('binascii',             binascii.__version__ ))
Exemple #30
0
 def MainCommandFromGui(self):  # Step 2. Main receives command from GUI
     command = self.app_conn.recv()
     if debug.on(debug.MultiProcessing) and not (command == cmd_Idle):
         logfile.Write("mp-MainCommandFromGui() returns %s" % (command))
     return command