示例#1
0
        public void WriteLap(ILapSummary lap)
        {
            if (lap == null || lap.ElapsedTime == 0)
            {
                return;
            }

            var lapMsg = new LapMesg();

            lapMsg.SetStartTime(new DateTime(lap.StartTime));
            lapMsg.SetTotalElapsedTime(lap.ElapsedTime);
            lapMsg.SetTotalMovingTime(lap.MovingTime);
            lapMsg.SetTotalDistance(lap.Distance.GetValueAs(DistanceUnit.Meter));
            lapMsg.SetAvgSpeed(FitExtensions.GetValidSpeed(lap.AvgSpeed.GetValueAs(SpeedUnit.MeterPerSecond)));
            lapMsg.SetMaxSpeed(FitExtensions.GetValidSpeed(lap.MaxSpeed.GetValueAs(SpeedUnit.MeterPerSecond)));
            lapMsg.SetAvgHeartRate((byte)lap.AvgHeartRate);
            lapMsg.SetMaxHeartRate((byte)lap.MaxHeartRate);
            lapMsg.SetAvgPower((ushort)lap.AvgPower);
            lapMsg.SetMaxPower((ushort)lap.MaxPower);
            lapMsg.SetAvgCadence((byte)lap.AvgCadence);
            lapMsg.SetMaxCadence((byte)lap.MaxCadence);
            lapMsg.SetTotalAscent(Convert.ToUInt16(lap.Ascent));
            lapMsg.SetTotalDescent(Convert.ToUInt16(lap.Descent));
            _encoder.Write(lapMsg);
        }
        public ICollection <LapMesg> GetLapsBasedOnSegments(WorkoutSamples workoutSamples, Dynastream.Fit.DateTime startTime, Sport sport, SubSport subSport)
        {
            using var tracing = Tracing.Trace($"{nameof(FitConverter)}.{nameof(GetLapsBasedOnSegments)}")
                                .WithTag(TagKey.Format, FileFormat.Fit.ToString());

            var stepsAndLaps = new List <LapMesg>();

            if (workoutSamples is null)
            {
                return(stepsAndLaps);
            }

            ushort stepIndex    = 0;
            var    speedMetrics = GetSpeedSummary(workoutSamples);

            if (workoutSamples.Segment_List.Any())
            {
                var totalElapsedTime = 0;
                foreach (var segment in workoutSamples.Segment_List)
                {
                    var lapStartTime = new Dynastream.Fit.DateTime(startTime);
                    lapStartTime.Add(segment.Start_Time_Offset);

                    totalElapsedTime += segment.Length;

                    var lapMesg = new LapMesg();
                    lapMesg.SetStartTime(lapStartTime);
                    lapMesg.SetMessageIndex(stepIndex);
                    lapMesg.SetEvent(Event.Lap);
                    lapMesg.SetLapTrigger(LapTrigger.Time);
                    lapMesg.SetSport(sport);
                    lapMesg.SetSubSport(subSport);

                    lapMesg.SetTotalElapsedTime(segment.Length);
                    lapMesg.SetTotalTimerTime(segment.Length);

                    var startIndex          = segment.Start_Time_Offset;
                    var endIndex            = segment.Start_Time_Offset + segment.Length;
                    var lapDistanceInMeters = 0f;
                    for (int i = startIndex; i < endIndex; i++)
                    {
                        if (speedMetrics is object && i < speedMetrics.Values.Length)
                        {
                            var currentSpeedInMPS = ConvertToMetersPerSecond(speedMetrics.GetValue(i), workoutSamples);
                            lapDistanceInMeters += 1 * currentSpeedInMPS;
                        }
                    }

                    lapMesg.SetTotalDistance(lapDistanceInMeters);
                    stepsAndLaps.Add(lapMesg);

                    stepIndex++;
                }
            }

            return(stepsAndLaps);
        }
示例#3
0
        /// <summary>
        /// Adds a new lap.
        /// </summary>
        private void HandleLapMessage(object sender, MesgEventArgs e)
        {
            LapMesg msg = (LapMesg)e.mesg;
            FitLap  lap = new FitLap(msg, (Laps.Count > 0) ? Laps[Laps.Count - 1].LastRecord + 1 : 0, Records.Count - 1);

            Laps.Add(lap);
            string     description = (lap.FirstRecord < lap.LastRecord) ? string.Format("{0} - {1}", lap.FirstRecord, lap.LastRecord) : lap.FirstRecord.ToString();
            FitMessage message     = new FitMessage(Resources.Lap, description);

            Messages.Add(message);
        }
示例#4
0
        public static void Start(DateTime?start = null)
        {
            Trace.TraceInformation("Start()");
            var activityFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\BeamNG.drive\\VeloActivities";

            if (!Directory.Exists(activityFolder))
            {
                Directory.CreateDirectory(activityFolder);
            }

            var filepath = activityFolder + "\\" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".fit";

            csvFile = new StreamWriter(filepath + ".csv", true);

            startTime     = start ?? DateTime.UtcNow;
            totalDistance = 0;

            // Create file encode object
            encoder = new Encode(ProtocolVersion.V20);

            fitDest = new FileStream(filepath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
            encoder.Open(fitDest);

            var fileIdMesg = new FileIdMesg(); // Every FIT file MUST contain a 'File ID' message as the first message

            fileIdMesg.SetType(Dynastream.Fit.File.Activity);
            fileIdMesg.SetManufacturer(Manufacturer.Bryton);  // Types defined in the profile are available
            fileIdMesg.SetProduct(1704);
            fileIdMesg.SetSerialNumber(5122);
            fileIdMesg.SetTimeCreated(new Dynastream.Fit.DateTime(startTime));

            // Encode each message, a definition message is automatically generated and output if necessary
            encoder.Write(fileIdMesg);

            Resume(start);

            sessionMesg = new SessionMesg();
            sessionMesg.SetStartTime(new Dynastream.Fit.DateTime(startTime));

            currentLapMesg = new LapMesg();
            currentLapMesg.SetStartTime(new Dynastream.Fit.DateTime(startTime));
        }
示例#5
0
        /// <summary>
        /// Terminates the current lap in the FIT recording.
        /// Use cases : ingame lap (if no workout in progress), start/end of workout, end of activity.
        /// </summary>
        public static void TerminateLap()
        {
            var now = new DateTime(System.DateTime.Now);

            currentLapMesg.SetTimestamp(now);
            currentLapMesg.SetSport(Sport.Cycling);
            currentLapMesg.SetTotalElapsedTime(now.GetTimeStamp() - currentLapMesg.GetStartTime().GetTimeStamp());
            currentLapMesg.SetTotalTimerTime(now.GetTimeStamp() - currentLapMesg.GetStartTime().GetTimeStamp());
            currentLapMesg.SetTotalDistance(State.TripTotalKm * 1000 - alreadyLappedDistance);
            currentLapMesg.SetEvent(Event.Lap);
            currentLapMesg.SetEventType(EventType.Stop);
            currentLapMesg.SetEventGroup(0);

            encoder.Write(currentLapMesg);

            numLaps++;
            currentLapMesg        = new LapMesg();
            alreadyLappedDistance = State.TripTotalKm * 1000;

            currentLapMesg.SetStartTime(now);
        }
示例#6
0
        public static LapSummary ToSumary(this LapMesg msg)
        {
            var summary = new LapSummary
            {
                Distance     = new Distance(msg.GetTotalDistance().GetValueOrDefault(0), DistanceUnit.Meter),
                ElapsedTime  = Convert.ToInt32(msg.GetTotalElapsedTime().GetValueOrDefault(0)),
                MovingTime   = Convert.ToInt32(msg.GetTotalTimerTime().GetValueOrDefault(0)),
                StartTime    = msg.GetStartTime().GetDateTime(),
                AvgHeartRate = msg.GetAvgHeartRate().GetValueOrDefault(0),
                MaxHeartRate = msg.GetMaxHeartRate().GetValueOrDefault(0),
                AvgSpeed     = new Speed(msg.GetAvgSpeed().GetValueOrDefault(0), SpeedUnit.MeterPerSecond),
                MaxSpeed     = new Speed(msg.GetMaxSpeed().GetValueOrDefault(0), SpeedUnit.MeterPerSecond),
                AvgCadence   = msg.GetAvgCadence().GetValueOrDefault(0),
                MaxCadence   = msg.GetMaxCadence().GetValueOrDefault(0),
                AvgPower     = msg.GetAvgPower().GetValueOrDefault(0),
                MaxPower     = msg.GetMaxPower().GetValueOrDefault(0),
                Ascent       = msg.GetTotalAscent().GetValueOrDefault(0),
                Descent      = msg.GetTotalDescent().GetValueOrDefault(0)
            };

            return(summary);
        }
示例#7
0
        /// <summary>
        /// Terminates the current lap in the FIT recording.
        /// Use cases : ingame lap (if no workout in progress), start/end of workout, end of activity.
        /// </summary>
        public static void TerminateLap(DateTime?time = null)
        {
            Trace.TraceInformation("TerminateLap()");
            var now = time ?? DateTime.UtcNow;

            currentLapMesg.SetTimestamp(new Dynastream.Fit.DateTime(now));
            currentLapMesg.SetSport(Sport.Cycling);
            currentLapMesg.SetTotalElapsedTime(new Dynastream.Fit.DateTime(now).GetTimeStamp() - currentLapMesg.GetStartTime().GetTimeStamp());
            currentLapMesg.SetTotalTimerTime((float)(totalTimerTime - alreadyLappedTimertime).TotalSeconds);
            currentLapMesg.SetTotalDistance(totalDistance * 1000 - alreadyLappedDistance);
            currentLapMesg.SetEvent(Event.Lap);
            currentLapMesg.SetEventType(EventType.Stop);
            currentLapMesg.SetEventGroup(0);

            encoder.Write(currentLapMesg);

            numLaps++;
            currentLapMesg         = new LapMesg();
            alreadyLappedDistance  = totalDistance * 1000;
            alreadyLappedTimertime = totalTimerTime;

            currentLapMesg.SetStartTime(new Dynastream.Fit.DateTime(now));
        }
示例#8
0
        static public void Start()
        {
            var assettoFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Assetto Corsa\\SimCyclingActivities";

            if (!Directory.Exists(assettoFolder))
            {
                Directory.CreateDirectory(assettoFolder);
            }

            var filepath = assettoFolder + "\\" + System.DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".fit";

            var now = new DateTime(System.DateTime.Now);

            // Create file encode object
            encoder = new Encode(ProtocolVersion.V20);

            fitDest = new FileStream(filepath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
            encoder.Open(fitDest);

            var fileIdMesg = new FileIdMesg(); // Every FIT file MUST contain a 'File ID' message as the first message

            fileIdMesg.SetType(Dynastream.Fit.File.Activity);
            fileIdMesg.SetManufacturer(Manufacturer.Dynastream);  // Types defined in the profile are available
            fileIdMesg.SetProduct(22);
            fileIdMesg.SetSerialNumber(1234);
            fileIdMesg.SetTimeCreated(now);

            // Encode each message, a definition message is automatically generated and output if necessary
            encoder.Write(fileIdMesg);

            sessionMesg = new SessionMesg();
            sessionMesg.SetStartTime(now);

            currentLapMesg = new LapMesg();
            currentLapMesg.SetStartTime(now);
        }
示例#9
0
        public FitLap(LapMesg msg, int first, int last)
        {
            FirstRecord = first;
            LastRecord  = last;

            AveAltitude                = msg.GetAvgAltitude();
            AveCadence                 = msg.GetAvgCadence();
            AveCadencePosition         = FitFile.GetByteList(msg.GetNumAvgCadencePosition(), msg.GetAvgCadencePosition);
            AveCombinedPedalSmoothness = msg.GetAvgCombinedPedalSmoothness();
            AveFractionalCadence       = msg.GetAvgFractionalCadence();
            AveGrade                      = msg.GetAvgGrade();
            AveHeartRate                  = msg.GetAvgHeartRate();
            AveLeftPco                    = msg.GetAvgLeftPco();
            AveLeftPedalSmoothness        = msg.GetAvgLeftPedalSmoothness();
            AveLeftPowerPhase             = FitFile.GetFloatList(msg.GetNumAvgLeftPowerPhase(), msg.GetAvgLeftPowerPhase);
            AveLeftPowerPhasePeak         = FitFile.GetFloatList(msg.GetNumAvgLeftPowerPhasePeak(), msg.GetAvgLeftPowerPhasePeak);
            AveLeftTorqueEffectiveness    = msg.GetAvgLeftTorqueEffectiveness();
            AveLevMotorPower              = msg.GetAvgLevMotorPower();
            AveNegGrade                   = msg.GetAvgNegGrade();
            AveNegVerticalSpeed           = msg.GetAvgNegVerticalSpeed();
            AvePosGrade                   = msg.GetAvgPosGrade();
            AvePosVerticalSpeed           = msg.GetAvgPosVerticalSpeed();
            AvePower                      = msg.GetAvgPower();
            AvePowerPosition              = FitFile.GetUShortList(msg.GetNumAvgPowerPosition(), msg.GetAvgPowerPosition);
            AveRightPco                   = msg.GetAvgRightPco();
            AveRightPedalSmoothness       = msg.GetAvgRightPedalSmoothness();
            AveRightPowerPhase            = FitFile.GetFloatList(msg.GetNumAvgRightPowerPhase(), msg.GetAvgRightPowerPhase);
            AveRightPowerPhasePeak        = FitFile.GetFloatList(msg.GetNumAvgRightPowerPhasePeak(), msg.GetAvgRightPowerPhasePeak);
            AveRightTorqueEffectiveness   = msg.GetAvgRightTorqueEffectiveness();
            AveRunningCadence             = msg.GetAvgRunningCadence();
            AveSaturatedHemoglobinPercent = FitFile.GetFloatList(msg.GetNumAvgSaturatedHemoglobinPercent(), msg.GetAvgSaturatedHemoglobinPercent);
            AveSpeed                      = FitFile.GetSpeed(msg.GetAvgSpeed());
            AveStanceTime                 = msg.GetAvgStanceTime();
            AveStanceTimeBalance          = msg.GetAvgStanceTimeBalance();
            AveStanceTimePercent          = msg.GetAvgStanceTimePercent();
            AveStepLength                 = msg.GetAvgStepLength();
            AveStrokeDistance             = msg.GetAvgStrokeDistance();
            AveTemperature                = msg.GetAvgTemperature();
            AveTotalHemoglobinConc        = FitFile.GetFloatList(msg.GetNumAvgTotalHemoglobinConc(), msg.GetAvgTotalHemoglobinConc);
            AvgVam = msg.GetAvgVam();
            AvgVerticalOscillation = msg.GetAvgVerticalOscillation();
            AvgVerticalRatio       = msg.GetAvgVerticalRatio();
            EndPositionLat         = FitFile.GetDegrees(msg.GetEndPositionLat());
            EndPositionLong        = FitFile.GetDegrees(msg.GetEndPositionLong());
            EnhancedAvgAltitude    = msg.GetEnhancedAvgAltitude();
            EnhancedAvgSpeed       = FitFile.GetSpeed(msg.GetEnhancedAvgSpeed());
            EnhancedMaxAltitude    = msg.GetEnhancedMaxAltitude();
            EnhancedMaxSpeed       = FitFile.GetSpeed(msg.GetEnhancedMaxSpeed());
            EnhancedMinAltitude    = msg.GetEnhancedMinAltitude();
            Event                         = msg.GetEvent();
            EventGroup                    = msg.GetEventGroup();
            EventType                     = msg.GetEventType();
            FirstLengthIndex              = msg.GetFirstLengthIndex();
            GpsAccuracy                   = msg.GetGpsAccuracy();
            Intensity                     = msg.GetIntensity();
            LapTrigger                    = msg.GetLapTrigger();
            LeftRightBalance              = msg.GetLeftRightBalance();
            LevBatteryConsumption         = msg.GetLevBatteryConsumption();
            MaxAltitude                   = msg.GetMaxAltitude();
            MaxCadence                    = msg.GetMaxCadence();
            MaxCadencePosition            = FitFile.GetByteList(msg.GetNumMaxCadencePosition(), msg.GetMaxCadencePosition);
            MaxFractionalCadence          = msg.GetMaxFractionalCadence();
            MaxHeartRate                  = msg.GetMaxHeartRate();
            MaxLevMotorPower              = msg.GetMaxLevMotorPower();
            MaxNegGrade                   = msg.GetMaxNegGrade();
            MaxNegVerticalSpeed           = msg.GetMaxNegVerticalSpeed();
            MaxPosGrade                   = msg.GetMaxPosGrade();
            MaxPosVerticalSpeed           = msg.GetMaxPosVerticalSpeed();
            MaxPower                      = msg.GetMaxPower();
            MaxPowerPosition              = FitFile.GetUShortList(msg.GetNumMaxPowerPosition(), msg.GetMaxPowerPosition);
            MaxRunningCadence             = msg.GetMaxRunningCadence();
            MaxSaturatedHemoglobinPercent = FitFile.GetFloatList(msg.GetNumMaxSaturatedHemoglobinPercent(), msg.GetMaxSaturatedHemoglobinPercent);
            MaxSpeed                      = FitFile.GetSpeed(msg.GetMaxSpeed());
            MaxTemperature                = msg.GetMaxTemperature();
            MaxTotalHemoglobinConc        = FitFile.GetFloatList(msg.GetNumMaxTotalHemoglobinConc(), msg.GetMaxTotalHemoglobinConc);
            MinAltitude                   = msg.GetMinAltitude();
            MinHeartRate                  = msg.GetMinHeartRate();
            MinSaturatedHemoglobinPercent = FitFile.GetFloatList(msg.GetNumMinSaturatedHemoglobinPercent(), msg.GetMinSaturatedHemoglobinPercent);
            MinTotalHemoglobinConc        = FitFile.GetFloatList(msg.GetNumMinTotalHemoglobinConc(), msg.GetMinTotalHemoglobinConc);
            NormalizedPower               = msg.GetNormalizedPower();
            NumActiveLengths              = msg.GetNumActiveLengths();
            NumLengths                    = msg.GetNumLengths();
            OpponentScore                 = msg.GetOpponentScore();
            PlayerScore                   = msg.GetPlayerScore();
            RepetitionNum                 = msg.GetRepetitionNum();
            Sport                         = msg.GetSport();
            StandCount                    = msg.GetStandCount();
            StartPositionLat              = FitFile.GetDegrees(msg.GetStartPositionLat());
            StartPositionLong             = FitFile.GetDegrees(msg.GetStartPositionLong());
            StartTime                     = FitFile.GetDateTime(msg.GetStartTime());
            StrokeCounts                  = FitFile.GetUShortList(msg.GetNumStrokeCount(), msg.GetStrokeCount);
            SubSport                      = msg.GetSubSport();
            SwimStroke                    = msg.GetSwimStroke();
            TimeInCadenceZone             = FitFile.GetFloatList(msg.GetNumTimeInCadenceZone(), msg.GetTimeInCadenceZone);
            TimeInHrZone                  = FitFile.GetFloatList(msg.GetNumTimeInHrZone(), msg.GetTimeInHrZone);
            TimeInPowerZone               = FitFile.GetFloatList(msg.GetNumTimeInPowerZone(), msg.GetTimeInPowerZone);
            TimeInSpeedZone               = FitFile.GetFloatList(msg.GetNumTimeInSpeedZone(), msg.GetTimeInSpeedZone);
            Timestamp                     = FitFile.GetDateTime(msg.GetTimestamp());
            TimeStanding                  = msg.GetTimeStanding();
            TotalAscent                   = msg.GetTotalAscent();
            TotalCalories                 = msg.GetTotalCalories();
            TotalCycles                   = msg.GetTotalCycles();
            TotalDescent                  = msg.GetTotalDescent();
            TotalDistance                 = FitFile.GetDistance(msg.GetTotalDistance());
            TotalElapsedTime              = FitFile.GetTimeSpan(msg.GetTotalElapsedTime());
            TotalFatCalories              = msg.GetTotalFatCalories();
            TotalFractionalCycles         = msg.GetTotalFractionalCycles();
            TotalMovingTime               = FitFile.GetTimeSpan(msg.GetTotalMovingTime());
            TotalStrides                  = msg.GetTotalStrides();
            TotalTimerTime                = FitFile.GetTimeSpan(msg.GetTotalTimerTime());
            TotalWork                     = FitFile.GetWork(msg.GetTotalWork());
            WktStepIndex                  = msg.GetWktStepIndex();
            ZoneCounts                    = FitFile.GetUShortList(msg.GetNumZoneCount(), msg.GetZoneCount);
        }
示例#10
0
文件: FitGen.cs 项目: Landixus/garfit
        /// <summary>
        /// Encode to a fit file
        /// </summary>
        /// <param name="db"></param>
        /// <param name="outputFileName"></param>
        public static void EncodeActivityFile(TrainingCenterDatabase_t db, string outputFileName)
        {
            /*
             *          string assemblyFilePath = Assembly.GetExecutingAssembly().GetName().CodeBase;
             *          string assemblyPath = assemblyFilePath.Replace(SysPath.GetFileName(assemblyFilePath), "");
             */

            if (string.IsNullOrEmpty(outputFileName))
            {
                outputFileName = "out";
            }

            //outputFileName = assemblyPath + outputFileName;

            //  write FIT file
            Encode        encoder = new Encode(ProtocolVersion.V20);
            SysFileStream fitDest = new SysFileStream(outputFileName + ".fit",
                                                      SysFileMode.Create,
                                                      SysFileAccess.ReadWrite,
                                                      SysFileShare.Read);

            // Write our header
            encoder.Open(fitDest);

            // FIT file_id message
            FileIdMesg fileIdMesg = new FileIdMesg();

            fileIdMesg.SetType(File.Activity);  // Activity File = 4
            fileIdMesg.SetManufacturer(Manufacturer.Garmin);
            fileIdMesg.SetProduct(GarminProduct.Fr935);
            fileIdMesg.SetSerialNumber(3949668594);
            fileIdMesg.SetTimeCreated(new DateTime(db.Activities.Activity[0].Id));    // set from input file

            // Encode each message, a definition message is automatically generated and output if necessary
            encoder.OnMesgDefinition(new MesgDefinition(fileIdMesg));
            encoder.OnMesg(fileIdMesg);
            Utils.LogMessage(LogType.Information, "Wrote FileID");

            // FIT FileCreator
            FileCreatorMesg fileCreatorMesg = new FileCreatorMesg();

            fileCreatorMesg.SetSoftwareVersion(600);    // Garmin Connect
            encoder.OnMesgDefinition(new MesgDefinition(fileCreatorMesg));
            encoder.OnMesg(fileCreatorMesg);
            Utils.LogMessage(LogType.Information, "Wrote FileCreatorMesg");

            // FIT event message : not found in TCX
            EventMesg eventMesg = new EventMesg();

            eventMesg.SetTimestamp(new DateTime(db.Activities.Activity[0].Id));
            eventMesg.SetData(0);
            eventMesg.SetEvent(Event.Timer);
            eventMesg.SetEventType(EventType.Start);
            eventMesg.SetEventGroup(0);
            encoder.OnMesgDefinition(new MesgDefinition(eventMesg));
            encoder.OnMesg(eventMesg);
            Utils.LogMessage(LogType.Information, "Wrote EventMesg");

            // FIT deviceInfo message: not found in TCX
            DeviceInfoMesg devInfoMesg = new DeviceInfoMesg();

            devInfoMesg.SetTimestamp(new DateTime(db.Activities.Activity[0].Id));
            devInfoMesg.SetSerialNumber(3949668594);
            devInfoMesg.SetManufacturer(Manufacturer.Garmin);
            devInfoMesg.SetProduct(GarminProduct.Fr935);
            devInfoMesg.SetSoftwareVersion(6);
            devInfoMesg.SetDeviceIndex(0);
            devInfoMesg.SetSourceType(SourceType.Local);
            for (int i = 0; i < 4; i++)
            {
                encoder.OnMesgDefinition(new MesgDefinition(devInfoMesg));
                encoder.OnMesg(devInfoMesg);
                Utils.LogMessage(LogType.Information, "Wrote DeviceInfoMesg");
            }

            // FIT deviceSettings message: not found in TCX
            DeviceSettingsMesg devSettingsMesg = new DeviceSettingsMesg();

            devSettingsMesg.SetUtcOffset(0);
            devSettingsMesg.SetTimeOffset(7, 0);
            devSettingsMesg.SetAutoActivityDetect(0);
            devSettingsMesg.SetAutosyncMinSteps(2000);
            devSettingsMesg.SetAutosyncMinTime(240);
            devSettingsMesg.SetActiveTimeZone(0);
            devSettingsMesg.SetActivityTrackerEnabled(Bool.True);
            devSettingsMesg.SetMountingSide(Side.Left);
            devSettingsMesg.SetTimeMode(1, TimeMode.Utc);
            encoder.OnMesgDefinition(new MesgDefinition(devSettingsMesg));
            encoder.OnMesg(devSettingsMesg);
            Utils.LogMessage(LogType.Information, "Wrote DeviceSettingsMesg");

            // FIT UserProfile message: : not found in TCX
            UserProfileMesg userProfileMesg = new UserProfileMesg();

            userProfileMesg.SetActivityClass(ActivityClass.Level);
            encoder.OnMesgDefinition(new MesgDefinition(userProfileMesg));
            encoder.OnMesg(userProfileMesg);
            Utils.LogMessage(LogType.Information, "Wrote UserProfileMesg");

            // FIT Sport:
            SportMesg sportMesg = new SportMesg();

            sportMesg.SetSport(Sport.Running);
            sportMesg.SetSubSport(SubSport.Road);

            // Encode each message, a definition message is automatically generated and output if necessary
            encoder.OnMesgDefinition(new MesgDefinition(sportMesg));
            encoder.OnMesg(sportMesg);
            Utils.LogMessage(LogType.Information, "Wrote SportMesg");

            // create FIT record and lap message
            double totalTime = 0;

            foreach (Activity_t act in db.Activities.Activity)
            {
                foreach (ActivityLap_t lap in act.Lap)
                {
                    List <RecordMesg> records = new List <RecordMesg>();

                    // FIT Record message:
                    foreach (Trackpoint_t trackPoint in lap.Track)
                    {
                        RecordMesg recMesg = new RecordMesg();

                        recMesg.SetTimestamp(new DateTime(trackPoint.Time));
                        recMesg.SetPositionLat(Utils.ConvertTcxLatLongToFit(trackPoint.Position.LatitudeDegrees));
                        recMesg.SetPositionLong(Utils.ConvertTcxLatLongToFit(trackPoint.Position.LongitudeDegrees));
                        recMesg.SetDistance((float)trackPoint.DistanceMeters);
                        recMesg.SetAltitude((float)trackPoint.AltitudeMeters);
                        //recMesg.SetSpeed((float)trackPoint.Extensions.Any["Speed"]);
                        if (trackPoint.HeartRateBpm != null)
                        {
                            recMesg.SetHeartRate((byte)trackPoint.HeartRateBpm.Value);
                        }

                        // Extension
                        if (trackPoint.Extensions.Any[0].GetElementsByTagName("ns3:RunCadence") != null)
                        {
                            if (trackPoint.Extensions.Any[0].GetElementsByTagName("ns3:RunCadence").Count == 1)
                            {
                                int cadence = 0;
                                int.TryParse((trackPoint.Extensions.Any[0].GetElementsByTagName("ns3:RunCadence")[0].InnerText), out cadence);
                                recMesg.SetCadence((byte)cadence);
                            }
                        }

                        if (trackPoint.Extensions.Any[0].GetElementsByTagName("ns3:Speed") != null)
                        {
                            if (trackPoint.Extensions.Any[0].GetElementsByTagName("ns3:Speed").Count == 1)
                            {
                                double speed = 0;
                                double.TryParse((trackPoint.Extensions.Any[0].GetElementsByTagName("ns3:Speed")[0].InnerText), out speed);
                                recMesg.SetSpeed((float)speed);
                            }
                        }

                        encoder.OnMesgDefinition(new MesgDefinition(recMesg));
                        encoder.OnMesg(recMesg);
                        Utils.LogMessage(LogType.Information, string.Format("Wrote RecMesg: {0}", recMesg.GetTimestamp().ToString()));
                    }

                    LapMesg lapMesg = new LapMesg();
                    lapMesg.SetTimestamp(new DateTime(lap.StartTime));
                    lapMesg.SetStartTime(new DateTime(lap.StartTime));
                    lapMesg.SetTotalMovingTime((float)lap.TotalTimeSeconds);
                    lapMesg.SetStartPositionLat(Utils.ConvertTcxLatLongToFit(lap.Track[0].Position.LatitudeDegrees));
                    lapMesg.SetStartPositionLong(Utils.ConvertTcxLatLongToFit(lap.Track[0].Position.LongitudeDegrees));
                    lapMesg.SetSport(Sport.Running);
                    lapMesg.SetSubSport(SubSport.Road);
                    // TODO: EndPosition
                    lapMesg.SetTotalElapsedTime((float)lap.TotalTimeSeconds);
                    totalTime += lap.TotalTimeSeconds;
                    // TODO: The rest

                    encoder.OnMesgDefinition(new MesgDefinition(lapMesg));
                    encoder.OnMesg(lapMesg);
                    Utils.LogMessage(LogType.Information, "Wrote LapMesg");
                }
            }

            // FIT Session: not found in tcx
            // FIT Activity
            ActivityMesg activityMesg = new ActivityMesg();

            activityMesg.SetTimestamp(new DateTime(db.Activities.Activity[0].Id));
            activityMesg.SetTotalTimerTime((float)totalTime);
            activityMesg.SetLocalTimestamp(new DateTime(db.Activities.Activity[0].Id).GetTimeStamp() + (uint)totalTime);
            activityMesg.SetNumSessions(1);
            activityMesg.SetType(Activity.Manual);
            activityMesg.SetEvent(Event.Activity);
            activityMesg.SetEventType(EventType.Stop);
            //activityMesg.SetTotalTimerTime(db.Activities.Activity[0].Training.);

            encoder.OnMesgDefinition(new MesgDefinition(activityMesg));
            encoder.OnMesg(activityMesg);
            Utils.LogMessage(LogType.Information, "Wrote ActivityMesg");

            // Update header datasize and file CRC
            encoder.Close();
            fitDest.Close();

            Console.WriteLine("Encoded FIT file " + outputFileName + ".fit");
        }
示例#11
0
        static public void CreateTimeBasedActivity()
        {
            const double TwoPI = Math.PI * 2.0;
            const double SemicirclesPerMeter = 107.173;
            const string FileName            = "ActivityEncodeRecipe.fit";

            var messages = new List <Mesg>();

            // The starting timestamp for the activity
            var startTime = new Dynastream.Fit.DateTime(System.DateTime.UtcNow);

            // Timer Events are a BEST PRACTICE for FIT ACTIVITY files
            var eventMesgStart = new EventMesg();

            eventMesgStart.SetTimestamp(startTime);
            eventMesgStart.SetEvent(Event.Timer);
            eventMesgStart.SetEventType(EventType.Start);
            messages.Add(eventMesgStart);

            // Create the Developer Id message for the developer data fields.
            var developerIdMesg = new DeveloperDataIdMesg();

            // It is a BEST PRACTICE to reuse the same Guid for all FIT files created by your platform
            byte[] appId = new Guid("00010203-0405-0607-0809-0A0B0C0D0E0F").ToByteArray();
            for (int i = 0; i < appId.Length; i++)
            {
                developerIdMesg.SetApplicationId(i, appId[i]);
            }
            developerIdMesg.SetDeveloperDataIndex(0);
            developerIdMesg.SetApplicationVersion(110);
            messages.Add(developerIdMesg);

            // Create the Developer Data Field Descriptions
            var doughnutsFieldDescMesg = new FieldDescriptionMesg();

            doughnutsFieldDescMesg.SetDeveloperDataIndex(0);
            doughnutsFieldDescMesg.SetFieldDefinitionNumber(0);
            doughnutsFieldDescMesg.SetFitBaseTypeId(FitBaseType.Float32);
            doughnutsFieldDescMesg.SetFieldName(0, "Doughnuts Earned");
            doughnutsFieldDescMesg.SetUnits(0, "doughnuts");
            doughnutsFieldDescMesg.SetNativeMesgNum(MesgNum.Session);
            messages.Add(doughnutsFieldDescMesg);

            FieldDescriptionMesg hrFieldDescMesg = new FieldDescriptionMesg();

            hrFieldDescMesg.SetDeveloperDataIndex(0);
            hrFieldDescMesg.SetFieldDefinitionNumber(1);
            hrFieldDescMesg.SetFitBaseTypeId(FitBaseType.Uint8);
            hrFieldDescMesg.SetFieldName(0, "Heart Rate");
            hrFieldDescMesg.SetUnits(0, "bpm");
            hrFieldDescMesg.SetNativeFieldNum(RecordMesg.FieldDefNum.HeartRate);
            hrFieldDescMesg.SetNativeMesgNum(MesgNum.Record);
            messages.Add(hrFieldDescMesg);

            // Every FIT ACTIVITY file MUST contain Record messages
            var timestamp = new Dynastream.Fit.DateTime(startTime);

            // Create one hour (3600 seconds) of Record data
            for (uint i = 0; i <= 3600; i++)
            {
                // Create a new Record message and set the timestamp
                var recordMesg = new RecordMesg();
                recordMesg.SetTimestamp(timestamp);

                // Fake Record Data of Various Signal Patterns
                recordMesg.SetDistance(i);                                                          // Ramp
                recordMesg.SetSpeed(1);                                                             // Flatline
                recordMesg.SetHeartRate((byte)((Math.Sin(TwoPI * (0.01 * i + 10)) + 1.0) * 127.0)); // Sine
                recordMesg.SetCadence((byte)(i % 255));                                             // Sawtooth
                recordMesg.SetPower((ushort)((i % 255) < 127 ? 150 : 250));                         // Square
                recordMesg.SetAltitude((float)Math.Abs(((double)i % 255.0) - 127.0));               // Triangle
                recordMesg.SetPositionLat(0);
                recordMesg.SetPositionLong((int)Math.Round(i * SemicirclesPerMeter));

                // Add a Developer Field to the Record Message
                var hrDevField = new DeveloperField(hrFieldDescMesg, developerIdMesg);
                recordMesg.SetDeveloperField(hrDevField);
                hrDevField.SetValue((byte)((Math.Sin(TwoPI * (0.01 * i + 10)) + 1.0) * 127.0)); // Sine

                // Write the Rercord message to the output stream
                messages.Add(recordMesg);

                // Increment the timestamp by one second
                timestamp.Add(1);
            }

            // Timer Events are a BEST PRACTICE for FIT ACTIVITY files
            var eventMesgStop = new EventMesg();

            eventMesgStop.SetTimestamp(timestamp);
            eventMesgStop.SetEvent(Event.Timer);
            eventMesgStop.SetEventType(EventType.StopAll);
            messages.Add(eventMesgStop);

            // Every FIT ACTIVITY file MUST contain at least one Lap message
            var lapMesg = new LapMesg();

            lapMesg.SetMessageIndex(0);
            lapMesg.SetTimestamp(timestamp);
            lapMesg.SetStartTime(startTime);
            lapMesg.SetTotalElapsedTime(timestamp.GetTimeStamp() - startTime.GetTimeStamp());
            lapMesg.SetTotalTimerTime(timestamp.GetTimeStamp() - startTime.GetTimeStamp());
            messages.Add(lapMesg);

            // Every FIT ACTIVITY file MUST contain at least one Session message
            var sessionMesg = new SessionMesg();

            sessionMesg.SetMessageIndex(0);
            sessionMesg.SetTimestamp(timestamp);
            sessionMesg.SetStartTime(startTime);
            sessionMesg.SetTotalElapsedTime(timestamp.GetTimeStamp() - startTime.GetTimeStamp());
            sessionMesg.SetTotalTimerTime(timestamp.GetTimeStamp() - startTime.GetTimeStamp());
            sessionMesg.SetSport(Sport.StandUpPaddleboarding);
            sessionMesg.SetSubSport(SubSport.Generic);
            sessionMesg.SetFirstLapIndex(0);
            sessionMesg.SetNumLaps(1);

            // Add a Developer Field to the Session message
            var doughnutsEarnedDevField = new DeveloperField(doughnutsFieldDescMesg, developerIdMesg);

            doughnutsEarnedDevField.SetValue(sessionMesg.GetTotalElapsedTime() / 1200.0f);
            sessionMesg.SetDeveloperField(doughnutsEarnedDevField);
            messages.Add(sessionMesg);

            // Every FIT ACTIVITY file MUST contain EXACTLY one Activity message
            var activityMesg = new ActivityMesg();

            activityMesg.SetTimestamp(timestamp);
            activityMesg.SetNumSessions(1);
            var timezoneOffset = (int)TimeZoneInfo.Local.BaseUtcOffset.TotalSeconds;

            activityMesg.SetLocalTimestamp((uint)((int)timestamp.GetTimeStamp() + timezoneOffset));
            activityMesg.SetTotalTimerTime(timestamp.GetTimeStamp() - startTime.GetTimeStamp());
            messages.Add(activityMesg);

            CreateActivityFile(messages, FileName, startTime);
        }
示例#12
0
        static public void CreateLapSwimActivity()
        {
            // Example Swim Data representing a 500 yard pool swim using different strokes and drills.
            var swimData = new List <Dictionary <string, object> >()
            {
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 20U }, { "stroke", "Freestyle" }, { "strokes", 30U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 25U }, { "stroke", "Freestyle" }, { "strokes", 20U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 30U }, { "stroke", "Freestyle" }, { "strokes", 10U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 35U }, { "stroke", "Freestyle" }, { "strokes", 20U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Lap" }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Idle" }, { "duration", 60U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Lap" }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 20U }, { "stroke", "Backstroke" }, { "strokes", 30U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 25U }, { "stroke", "Backstroke" }, { "strokes", 20U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 30U }, { "stroke", "Backstroke" }, { "strokes", 10U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 35U }, { "stroke", "Backstroke" }, { "strokes", 20U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Lap" }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Idle" }, { "duration", 60U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Lap" }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 20U }, { "stroke", "Breaststroke" }, { "strokes", 30U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 25U }, { "stroke", "Breaststroke" }, { "strokes", 20U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 30U }, { "stroke", "Breaststroke" }, { "strokes", 10U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 35U }, { "stroke", "Breaststroke" }, { "strokes", 20U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Lap" }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Idle" }, { "duration", 60U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Lap" }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 20U }, { "stroke", "Butterfly" }, { "strokes", 30U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 25U }, { "stroke", "Butterfly" }, { "strokes", 20U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 30U }, { "stroke", "Butterfly" }, { "strokes", 10U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 35U }, { "stroke", "Butterfly" }, { "strokes", 20U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Lap" }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Idle" }, { "duration", 60U }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Lap" }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 40U }, { "stroke", "Drill" }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 40U }, { "stroke", "Drill" }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 40U }, { "stroke", "Drill" }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Active" }, { "duration", 40U }, { "stroke", "Drill" }
                },
                new Dictionary <string, object>()
                {
                    { "type", "Lap" }
                },
            };

            const string FileName = "ActivityEncodeRecipeLapSwim.fit";
            var          messages = new List <Mesg>();

            // The starting timestamp for the activity
            var startTime = new Dynastream.Fit.DateTime(System.DateTime.UtcNow);


            // Timer Events are a BEST PRACTICE for FIT ACTIVITY files
            var eventMesgStart = new EventMesg();

            eventMesgStart.SetTimestamp(startTime);
            eventMesgStart.SetEvent(Event.Timer);
            eventMesgStart.SetEventType(EventType.Start);
            messages.Add(eventMesgStart);

            //
            // Create a Length or Lap message for each item in the sample swim data. Calculate
            // distance, duration, and stroke count for each lap and the overall session.
            //

            // Session Accumulators
            uint   sessionTotalElapsedTime = 0;
            float  sessionDistance         = 0;
            ushort sessionNumLengths       = 0;
            ushort sessionNumActiveLengths = 0;
            ushort sessionTotalStrokes     = 0;
            ushort sessionNumLaps          = 0;

            // Lap accumulators
            uint   lapTotalElapsedTime = 0;
            float  lapDistance         = 0;
            ushort lapNumActiveLengths = 0;
            ushort lapNumLengths       = 0;
            ushort lapFirstLengthIndex = 0;
            ushort lapTotalStrokes     = 0;
            var    lapStartTime        = new Dynastream.Fit.DateTime(startTime);

            var    poolLength     = 22.86f;
            var    poolLengthUnit = DisplayMeasure.Statute;
            var    timestamp      = new Dynastream.Fit.DateTime(startTime);
            ushort messageIndex   = 0;

            foreach (var swimLength in swimData)
            {
                string type = (string)swimLength["type"];

                if (type.Equals("Lap"))
                {
                    // Create a Lap message, set its fields, and write it to the file
                    var lapMesg = new LapMesg();
                    lapMesg.SetMessageIndex(sessionNumLaps);
                    lapMesg.SetTimestamp(timestamp);
                    lapMesg.SetStartTime(lapStartTime);
                    lapMesg.SetTotalElapsedTime(lapTotalElapsedTime);
                    lapMesg.SetTotalTimerTime(lapTotalElapsedTime);
                    lapMesg.SetTotalDistance(lapDistance);
                    lapMesg.SetFirstLengthIndex(lapFirstLengthIndex);
                    lapMesg.SetNumActiveLengths(lapNumActiveLengths);
                    lapMesg.SetNumLengths(lapNumLengths);
                    lapMesg.SetTotalStrokes(lapTotalStrokes);
                    lapMesg.SetAvgStrokeDistance(lapDistance / lapTotalStrokes);
                    lapMesg.SetSport(Sport.Swimming);
                    lapMesg.SetSubSport(SubSport.LapSwimming);
                    messages.Add(lapMesg);

                    sessionNumLaps++;

                    // Reset the Lap accumulators
                    lapFirstLengthIndex = messageIndex;
                    lapNumActiveLengths = 0;
                    lapNumLengths       = 0;
                    lapTotalElapsedTime = 0;
                    lapDistance         = 0;
                    lapTotalStrokes     = 0;
                    lapStartTime        = new Dynastream.Fit.DateTime(timestamp);
                }
                else
                {
                    uint duration   = (uint)swimLength["duration"];
                    var  lengthType = (LengthType)Enum.Parse(typeof(LengthType), type);

                    // Create a Length message and its fields
                    var lengthMesg = new LengthMesg();
                    lengthMesg.SetMessageIndex(messageIndex++);
                    lengthMesg.SetStartTime(timestamp);
                    lengthMesg.SetTotalElapsedTime(duration);
                    lengthMesg.SetTotalTimerTime(duration);
                    lengthMesg.SetLengthType(lengthType);

                    timestamp.Add(duration);
                    lengthMesg.SetTimestamp(timestamp);

                    // Create the Record message that pairs with the Length Message
                    var recordMesg = new RecordMesg();
                    recordMesg.SetTimestamp(timestamp);
                    recordMesg.SetDistance(sessionDistance + poolLength);

                    // Is this an Active Length?
                    if (lengthType == LengthType.Active)
                    {
                        // Get the Active data from the model
                        string     stroke     = swimLength.ContainsKey("stroke") ? (String)swimLength["stroke"] : "Freestyle";
                        uint       strokes    = swimLength.ContainsKey("strokes") ? (uint)swimLength["strokes"] : 0;
                        SwimStroke swimStroke = (SwimStroke)Enum.Parse(typeof(SwimStroke), stroke);

                        // Set the Active data on the Length Message
                        lengthMesg.SetAvgSpeed(poolLength / (float)duration);
                        lengthMesg.SetSwimStroke(swimStroke);

                        if (strokes > 0)
                        {
                            lengthMesg.SetTotalStrokes((ushort)strokes);
                            lengthMesg.SetAvgSwimmingCadence((byte)(strokes * 60U / duration));
                        }

                        // Set the Active data on the Record Message
                        recordMesg.SetSpeed(poolLength / (float)duration);
                        if (strokes > 0)
                        {
                            recordMesg.SetCadence((byte)((strokes * 60U) / duration));
                        }

                        // Increment the "Active" accumulators
                        sessionNumActiveLengths++;
                        lapNumActiveLengths++;
                        sessionDistance     += poolLength;
                        lapDistance         += poolLength;
                        sessionTotalStrokes += (ushort)strokes;
                        lapTotalStrokes     += (ushort)strokes;
                    }

                    // Write the messages to the file
                    messages.Add(recordMesg);
                    messages.Add(lengthMesg);

                    // Increment the "Total" accumulators
                    sessionTotalElapsedTime += duration;
                    lapTotalElapsedTime     += duration;
                    sessionNumLengths++;
                    lapNumLengths++;
                }
            }

            // Timer Events are a BEST PRACTICE for FIT ACTIVITY files
            var eventMesgStop = new EventMesg();

            eventMesgStop.SetTimestamp(timestamp);
            eventMesgStop.SetEvent(Event.Timer);
            eventMesgStop.SetEventType(EventType.StopAll);
            messages.Add(eventMesgStop);

            // Every FIT ACTIVITY file MUST contain at least one Session message
            var sessionMesg = new SessionMesg();

            sessionMesg.SetMessageIndex(0);
            sessionMesg.SetTimestamp(timestamp);
            sessionMesg.SetStartTime(startTime);
            sessionMesg.SetTotalElapsedTime(sessionTotalElapsedTime);
            sessionMesg.SetTotalTimerTime(sessionTotalElapsedTime);
            sessionMesg.SetTotalDistance(sessionDistance);
            sessionMesg.SetSport(Sport.Swimming);
            sessionMesg.SetSubSport(SubSport.LapSwimming);
            sessionMesg.SetFirstLapIndex(0);
            sessionMesg.SetNumLaps(sessionNumLaps);
            sessionMesg.SetPoolLength(poolLength);
            sessionMesg.SetPoolLengthUnit(poolLengthUnit);
            sessionMesg.SetNumLengths(sessionNumLengths);
            sessionMesg.SetNumActiveLengths(sessionNumActiveLengths);
            sessionMesg.SetTotalStrokes(sessionTotalStrokes);
            sessionMesg.SetAvgStrokeDistance(sessionDistance / sessionTotalStrokes);
            messages.Add(sessionMesg);

            // Every FIT ACTIVITY file MUST contain EXACTLY one Activity message
            var activityMesg = new ActivityMesg();

            activityMesg.SetTimestamp(timestamp);
            activityMesg.SetNumSessions(1);
            var timezoneOffset = (int)TimeZoneInfo.Local.BaseUtcOffset.TotalSeconds;

            activityMesg.SetLocalTimestamp((uint)((int)timestamp.GetTimeStamp() + timezoneOffset));
            activityMesg.SetTotalTimerTime(sessionTotalElapsedTime);
            messages.Add(activityMesg);

            CreateActivityFile(messages, FileName, startTime);
        }
示例#13
0
        private Dictionary <int, Tuple <WorkoutStepMesg, LapMesg> > GetWorkoutStepsAndLaps(WorkoutSamples workoutSamples, Dynastream.Fit.DateTime startTime, Sport sport, SubSport subSport)
        {
            var stepsAndLaps = new Dictionary <int, Tuple <WorkoutStepMesg, LapMesg> >();

            if (workoutSamples is null)
            {
                return(stepsAndLaps);
            }

            var cadenceTargets = workoutSamples.Target_Performance_Metrics?.Target_Graph_Metrics?.FirstOrDefault(w => w.Type == "cadence")?.Graph_Data;

            if (cadenceTargets is null)
            {
                return(stepsAndLaps);
            }

            uint            previousCadenceLower = 0;
            uint            previousCadenceUpper = 0;
            ushort          stepIndex            = 0;
            var             duration             = 0;
            float           lapDistanceInMeters  = 0;
            WorkoutStepMesg workoutStep          = null;
            LapMesg         lapMesg      = null;
            var             speedMetrics = GetSpeedSummary(workoutSamples);

            foreach (var secondSinceStart in workoutSamples.Seconds_Since_Pedaling_Start)
            {
                var index = secondSinceStart <= 0 ? 0 : secondSinceStart - 1;
                duration++;

                if (speedMetrics is object && index < speedMetrics.Values.Length)
                {
                    var currentSpeedInMPS = ConvertToMetersPerSecond(speedMetrics.GetValue(index), workoutSamples);
                    lapDistanceInMeters += 1 * currentSpeedInMPS;
                }

                var currentCadenceLower = index < cadenceTargets.Lower.Length ? (uint)cadenceTargets.Lower[index] : 0;
                var currentCadenceUpper = index < cadenceTargets.Upper.Length ? (uint)cadenceTargets.Upper[index] : 0;

                if (currentCadenceLower != previousCadenceLower ||
                    currentCadenceUpper != previousCadenceUpper)
                {
                    if (workoutStep != null && lapMesg != null)
                    {
                        workoutStep.SetDurationValue((uint)duration * 1000);                         // milliseconds

                        var lapEndTime = new Dynastream.Fit.DateTime(startTime);
                        lapEndTime.Add(secondSinceStart);
                        lapMesg.SetTotalElapsedTime(duration);
                        lapMesg.SetTotalTimerTime(duration);
                        lapMesg.SetTimestamp(lapEndTime);
                        lapMesg.SetEventType(EventType.Stop);
                        lapMesg.SetTotalDistance(lapDistanceInMeters);

                        stepsAndLaps.Add(stepIndex, new Tuple <WorkoutStepMesg, LapMesg>(workoutStep, lapMesg));
                        stepIndex++;
                        duration            = 0;
                        lapDistanceInMeters = 0;
                    }

                    workoutStep = new WorkoutStepMesg();
                    workoutStep.SetDurationType(WktStepDuration.Time);
                    workoutStep.SetMessageIndex(stepIndex);
                    workoutStep.SetTargetType(WktStepTarget.Cadence);
                    workoutStep.SetCustomTargetValueHigh(currentCadenceUpper);
                    workoutStep.SetCustomTargetValueLow(currentCadenceLower);
                    workoutStep.SetIntensity(currentCadenceUpper > 60 ? Intensity.Active : Intensity.Rest);

                    lapMesg = new LapMesg();
                    var lapStartTime = new Dynastream.Fit.DateTime(startTime);
                    lapStartTime.Add(secondSinceStart);
                    lapMesg.SetStartTime(lapStartTime);
                    lapMesg.SetWktStepIndex(stepIndex);
                    lapMesg.SetMessageIndex(stepIndex);
                    lapMesg.SetEvent(Event.Lap);
                    lapMesg.SetLapTrigger(LapTrigger.Time);
                    lapMesg.SetSport(sport);
                    lapMesg.SetSubSport(subSport);

                    previousCadenceLower = currentCadenceLower;
                    previousCadenceUpper = currentCadenceUpper;
                }
            }

            return(stepsAndLaps);
        }
示例#14
0
        public void OnMesg(object sender, MesgEventArgs e)
        {
            // Notify any subscribers of either our general mesg event or specific profile mesg event
            if (MesgEvent != null)
            {
                MesgEvent(sender, e);
            }

            switch (e.mesg.Num)
            {
            case (ushort)MesgNum.FileId:
                if (FileIdMesgEvent != null)
                {
                    FileIdMesg    fileIdMesg    = new FileIdMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = fileIdMesg;
                    FileIdMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.FileCreator:
                if (FileCreatorMesgEvent != null)
                {
                    FileCreatorMesg fileCreatorMesg = new FileCreatorMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = fileCreatorMesg;
                    FileCreatorMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Software:
                if (SoftwareMesgEvent != null)
                {
                    SoftwareMesg  softwareMesg  = new SoftwareMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = softwareMesg;
                    SoftwareMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.SlaveDevice:
                if (SlaveDeviceMesgEvent != null)
                {
                    SlaveDeviceMesg slaveDeviceMesg = new SlaveDeviceMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = slaveDeviceMesg;
                    SlaveDeviceMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Capabilities:
                if (CapabilitiesMesgEvent != null)
                {
                    CapabilitiesMesg capabilitiesMesg = new CapabilitiesMesg(e.mesg);
                    MesgEventArgs    mesgEventArgs    = new MesgEventArgs();
                    mesgEventArgs.mesg = capabilitiesMesg;
                    CapabilitiesMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.FileCapabilities:
                if (FileCapabilitiesMesgEvent != null)
                {
                    FileCapabilitiesMesg fileCapabilitiesMesg = new FileCapabilitiesMesg(e.mesg);
                    MesgEventArgs        mesgEventArgs        = new MesgEventArgs();
                    mesgEventArgs.mesg = fileCapabilitiesMesg;
                    FileCapabilitiesMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.MesgCapabilities:
                if (MesgCapabilitiesMesgEvent != null)
                {
                    MesgCapabilitiesMesg mesgCapabilitiesMesg = new MesgCapabilitiesMesg(e.mesg);
                    MesgEventArgs        mesgEventArgs        = new MesgEventArgs();
                    mesgEventArgs.mesg = mesgCapabilitiesMesg;
                    MesgCapabilitiesMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.FieldCapabilities:
                if (FieldCapabilitiesMesgEvent != null)
                {
                    FieldCapabilitiesMesg fieldCapabilitiesMesg = new FieldCapabilitiesMesg(e.mesg);
                    MesgEventArgs         mesgEventArgs         = new MesgEventArgs();
                    mesgEventArgs.mesg = fieldCapabilitiesMesg;
                    FieldCapabilitiesMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.DeviceSettings:
                if (DeviceSettingsMesgEvent != null)
                {
                    DeviceSettingsMesg deviceSettingsMesg = new DeviceSettingsMesg(e.mesg);
                    MesgEventArgs      mesgEventArgs      = new MesgEventArgs();
                    mesgEventArgs.mesg = deviceSettingsMesg;
                    DeviceSettingsMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.UserProfile:
                if (UserProfileMesgEvent != null)
                {
                    UserProfileMesg userProfileMesg = new UserProfileMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = userProfileMesg;
                    UserProfileMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.HrmProfile:
                if (HrmProfileMesgEvent != null)
                {
                    HrmProfileMesg hrmProfileMesg = new HrmProfileMesg(e.mesg);
                    MesgEventArgs  mesgEventArgs  = new MesgEventArgs();
                    mesgEventArgs.mesg = hrmProfileMesg;
                    HrmProfileMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.SdmProfile:
                if (SdmProfileMesgEvent != null)
                {
                    SdmProfileMesg sdmProfileMesg = new SdmProfileMesg(e.mesg);
                    MesgEventArgs  mesgEventArgs  = new MesgEventArgs();
                    mesgEventArgs.mesg = sdmProfileMesg;
                    SdmProfileMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.BikeProfile:
                if (BikeProfileMesgEvent != null)
                {
                    BikeProfileMesg bikeProfileMesg = new BikeProfileMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = bikeProfileMesg;
                    BikeProfileMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.ZonesTarget:
                if (ZonesTargetMesgEvent != null)
                {
                    ZonesTargetMesg zonesTargetMesg = new ZonesTargetMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = zonesTargetMesg;
                    ZonesTargetMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Sport:
                if (SportMesgEvent != null)
                {
                    SportMesg     sportMesg     = new SportMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = sportMesg;
                    SportMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.HrZone:
                if (HrZoneMesgEvent != null)
                {
                    HrZoneMesg    hrZoneMesg    = new HrZoneMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = hrZoneMesg;
                    HrZoneMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.SpeedZone:
                if (SpeedZoneMesgEvent != null)
                {
                    SpeedZoneMesg speedZoneMesg = new SpeedZoneMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = speedZoneMesg;
                    SpeedZoneMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.CadenceZone:
                if (CadenceZoneMesgEvent != null)
                {
                    CadenceZoneMesg cadenceZoneMesg = new CadenceZoneMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = cadenceZoneMesg;
                    CadenceZoneMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.PowerZone:
                if (PowerZoneMesgEvent != null)
                {
                    PowerZoneMesg powerZoneMesg = new PowerZoneMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = powerZoneMesg;
                    PowerZoneMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.MetZone:
                if (MetZoneMesgEvent != null)
                {
                    MetZoneMesg   metZoneMesg   = new MetZoneMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = metZoneMesg;
                    MetZoneMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Goal:
                if (GoalMesgEvent != null)
                {
                    GoalMesg      goalMesg      = new GoalMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = goalMesg;
                    GoalMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Activity:
                if (ActivityMesgEvent != null)
                {
                    ActivityMesg  activityMesg  = new ActivityMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = activityMesg;
                    ActivityMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Session:
                if (SessionMesgEvent != null)
                {
                    SessionMesg   sessionMesg   = new SessionMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = sessionMesg;
                    SessionMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Lap:
                if (LapMesgEvent != null)
                {
                    LapMesg       lapMesg       = new LapMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = lapMesg;
                    LapMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Length:
                if (LengthMesgEvent != null)
                {
                    LengthMesg    lengthMesg    = new LengthMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = lengthMesg;
                    LengthMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Record:
                if (RecordMesgEvent != null)
                {
                    RecordMesg    recordMesg    = new RecordMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = recordMesg;
                    RecordMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Event:
                if (EventMesgEvent != null)
                {
                    EventMesg     eventMesg     = new EventMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = eventMesg;
                    EventMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.DeviceInfo:
                if (DeviceInfoMesgEvent != null)
                {
                    DeviceInfoMesg deviceInfoMesg = new DeviceInfoMesg(e.mesg);
                    MesgEventArgs  mesgEventArgs  = new MesgEventArgs();
                    mesgEventArgs.mesg = deviceInfoMesg;
                    DeviceInfoMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.TrainingFile:
                if (TrainingFileMesgEvent != null)
                {
                    TrainingFileMesg trainingFileMesg = new TrainingFileMesg(e.mesg);
                    MesgEventArgs    mesgEventArgs    = new MesgEventArgs();
                    mesgEventArgs.mesg = trainingFileMesg;
                    TrainingFileMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Hrv:
                if (HrvMesgEvent != null)
                {
                    HrvMesg       hrvMesg       = new HrvMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = hrvMesg;
                    HrvMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Course:
                if (CourseMesgEvent != null)
                {
                    CourseMesg    courseMesg    = new CourseMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = courseMesg;
                    CourseMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.CoursePoint:
                if (CoursePointMesgEvent != null)
                {
                    CoursePointMesg coursePointMesg = new CoursePointMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = coursePointMesg;
                    CoursePointMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Workout:
                if (WorkoutMesgEvent != null)
                {
                    WorkoutMesg   workoutMesg   = new WorkoutMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = workoutMesg;
                    WorkoutMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.WorkoutStep:
                if (WorkoutStepMesgEvent != null)
                {
                    WorkoutStepMesg workoutStepMesg = new WorkoutStepMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = workoutStepMesg;
                    WorkoutStepMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Schedule:
                if (ScheduleMesgEvent != null)
                {
                    ScheduleMesg  scheduleMesg  = new ScheduleMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = scheduleMesg;
                    ScheduleMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Totals:
                if (TotalsMesgEvent != null)
                {
                    TotalsMesg    totalsMesg    = new TotalsMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = totalsMesg;
                    TotalsMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.WeightScale:
                if (WeightScaleMesgEvent != null)
                {
                    WeightScaleMesg weightScaleMesg = new WeightScaleMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = weightScaleMesg;
                    WeightScaleMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.BloodPressure:
                if (BloodPressureMesgEvent != null)
                {
                    BloodPressureMesg bloodPressureMesg = new BloodPressureMesg(e.mesg);
                    MesgEventArgs     mesgEventArgs     = new MesgEventArgs();
                    mesgEventArgs.mesg = bloodPressureMesg;
                    BloodPressureMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.MonitoringInfo:
                if (MonitoringInfoMesgEvent != null)
                {
                    MonitoringInfoMesg monitoringInfoMesg = new MonitoringInfoMesg(e.mesg);
                    MesgEventArgs      mesgEventArgs      = new MesgEventArgs();
                    mesgEventArgs.mesg = monitoringInfoMesg;
                    MonitoringInfoMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Monitoring:
                if (MonitoringMesgEvent != null)
                {
                    MonitoringMesg monitoringMesg = new MonitoringMesg(e.mesg);
                    MesgEventArgs  mesgEventArgs  = new MesgEventArgs();
                    mesgEventArgs.mesg = monitoringMesg;
                    MonitoringMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.MemoGlob:
                if (MemoGlobMesgEvent != null)
                {
                    MemoGlobMesg  memoGlobMesg  = new MemoGlobMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = memoGlobMesg;
                    MemoGlobMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Pad:
                if (PadMesgEvent != null)
                {
                    PadMesg       padMesg       = new PadMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = padMesg;
                    PadMesgEvent(sender, mesgEventArgs);
                }
                break;
            }
        }
        public void OnMesg(object sender, MesgEventArgs e)
        {
            // Notify any subscribers of either our general mesg event or specific profile mesg event
            if (MesgEvent != null)
            {
                MesgEvent(sender, e);
            }

            switch (e.mesg.Num)
            {
            case (ushort)MesgNum.FileId:
                if (FileIdMesgEvent != null)
                {
                    FileIdMesg    fileIdMesg    = new FileIdMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = fileIdMesg;
                    FileIdMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.FileCreator:
                if (FileCreatorMesgEvent != null)
                {
                    FileCreatorMesg fileCreatorMesg = new FileCreatorMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = fileCreatorMesg;
                    FileCreatorMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.TimestampCorrelation:
                if (TimestampCorrelationMesgEvent != null)
                {
                    TimestampCorrelationMesg timestampCorrelationMesg = new TimestampCorrelationMesg(e.mesg);
                    MesgEventArgs            mesgEventArgs            = new MesgEventArgs();
                    mesgEventArgs.mesg = timestampCorrelationMesg;
                    TimestampCorrelationMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Software:
                if (SoftwareMesgEvent != null)
                {
                    SoftwareMesg  softwareMesg  = new SoftwareMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = softwareMesg;
                    SoftwareMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.SlaveDevice:
                if (SlaveDeviceMesgEvent != null)
                {
                    SlaveDeviceMesg slaveDeviceMesg = new SlaveDeviceMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = slaveDeviceMesg;
                    SlaveDeviceMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Capabilities:
                if (CapabilitiesMesgEvent != null)
                {
                    CapabilitiesMesg capabilitiesMesg = new CapabilitiesMesg(e.mesg);
                    MesgEventArgs    mesgEventArgs    = new MesgEventArgs();
                    mesgEventArgs.mesg = capabilitiesMesg;
                    CapabilitiesMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.FileCapabilities:
                if (FileCapabilitiesMesgEvent != null)
                {
                    FileCapabilitiesMesg fileCapabilitiesMesg = new FileCapabilitiesMesg(e.mesg);
                    MesgEventArgs        mesgEventArgs        = new MesgEventArgs();
                    mesgEventArgs.mesg = fileCapabilitiesMesg;
                    FileCapabilitiesMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.MesgCapabilities:
                if (MesgCapabilitiesMesgEvent != null)
                {
                    MesgCapabilitiesMesg mesgCapabilitiesMesg = new MesgCapabilitiesMesg(e.mesg);
                    MesgEventArgs        mesgEventArgs        = new MesgEventArgs();
                    mesgEventArgs.mesg = mesgCapabilitiesMesg;
                    MesgCapabilitiesMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.FieldCapabilities:
                if (FieldCapabilitiesMesgEvent != null)
                {
                    FieldCapabilitiesMesg fieldCapabilitiesMesg = new FieldCapabilitiesMesg(e.mesg);
                    MesgEventArgs         mesgEventArgs         = new MesgEventArgs();
                    mesgEventArgs.mesg = fieldCapabilitiesMesg;
                    FieldCapabilitiesMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.DeviceSettings:
                if (DeviceSettingsMesgEvent != null)
                {
                    DeviceSettingsMesg deviceSettingsMesg = new DeviceSettingsMesg(e.mesg);
                    MesgEventArgs      mesgEventArgs      = new MesgEventArgs();
                    mesgEventArgs.mesg = deviceSettingsMesg;
                    DeviceSettingsMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.UserProfile:
                if (UserProfileMesgEvent != null)
                {
                    UserProfileMesg userProfileMesg = new UserProfileMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = userProfileMesg;
                    UserProfileMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.HrmProfile:
                if (HrmProfileMesgEvent != null)
                {
                    HrmProfileMesg hrmProfileMesg = new HrmProfileMesg(e.mesg);
                    MesgEventArgs  mesgEventArgs  = new MesgEventArgs();
                    mesgEventArgs.mesg = hrmProfileMesg;
                    HrmProfileMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.SdmProfile:
                if (SdmProfileMesgEvent != null)
                {
                    SdmProfileMesg sdmProfileMesg = new SdmProfileMesg(e.mesg);
                    MesgEventArgs  mesgEventArgs  = new MesgEventArgs();
                    mesgEventArgs.mesg = sdmProfileMesg;
                    SdmProfileMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.BikeProfile:
                if (BikeProfileMesgEvent != null)
                {
                    BikeProfileMesg bikeProfileMesg = new BikeProfileMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = bikeProfileMesg;
                    BikeProfileMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.ZonesTarget:
                if (ZonesTargetMesgEvent != null)
                {
                    ZonesTargetMesg zonesTargetMesg = new ZonesTargetMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = zonesTargetMesg;
                    ZonesTargetMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Sport:
                if (SportMesgEvent != null)
                {
                    SportMesg     sportMesg     = new SportMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = sportMesg;
                    SportMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.HrZone:
                if (HrZoneMesgEvent != null)
                {
                    HrZoneMesg    hrZoneMesg    = new HrZoneMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = hrZoneMesg;
                    HrZoneMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.SpeedZone:
                if (SpeedZoneMesgEvent != null)
                {
                    SpeedZoneMesg speedZoneMesg = new SpeedZoneMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = speedZoneMesg;
                    SpeedZoneMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.CadenceZone:
                if (CadenceZoneMesgEvent != null)
                {
                    CadenceZoneMesg cadenceZoneMesg = new CadenceZoneMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = cadenceZoneMesg;
                    CadenceZoneMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.PowerZone:
                if (PowerZoneMesgEvent != null)
                {
                    PowerZoneMesg powerZoneMesg = new PowerZoneMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = powerZoneMesg;
                    PowerZoneMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.MetZone:
                if (MetZoneMesgEvent != null)
                {
                    MetZoneMesg   metZoneMesg   = new MetZoneMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = metZoneMesg;
                    MetZoneMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Goal:
                if (GoalMesgEvent != null)
                {
                    GoalMesg      goalMesg      = new GoalMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = goalMesg;
                    GoalMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Activity:
                if (ActivityMesgEvent != null)
                {
                    ActivityMesg  activityMesg  = new ActivityMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = activityMesg;
                    ActivityMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Session:
                if (SessionMesgEvent != null)
                {
                    SessionMesg   sessionMesg   = new SessionMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = sessionMesg;
                    SessionMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Lap:
                if (LapMesgEvent != null)
                {
                    LapMesg       lapMesg       = new LapMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = lapMesg;
                    LapMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Length:
                if (LengthMesgEvent != null)
                {
                    LengthMesg    lengthMesg    = new LengthMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = lengthMesg;
                    LengthMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Record:
                if (RecordMesgEvent != null)
                {
                    RecordMesg    recordMesg    = new RecordMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = recordMesg;
                    RecordMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Event:
                if (EventMesgEvent != null)
                {
                    EventMesg     eventMesg     = new EventMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = eventMesg;
                    EventMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.DeviceInfo:
                if (DeviceInfoMesgEvent != null)
                {
                    DeviceInfoMesg deviceInfoMesg = new DeviceInfoMesg(e.mesg);
                    MesgEventArgs  mesgEventArgs  = new MesgEventArgs();
                    mesgEventArgs.mesg = deviceInfoMesg;
                    DeviceInfoMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.TrainingFile:
                if (TrainingFileMesgEvent != null)
                {
                    TrainingFileMesg trainingFileMesg = new TrainingFileMesg(e.mesg);
                    MesgEventArgs    mesgEventArgs    = new MesgEventArgs();
                    mesgEventArgs.mesg = trainingFileMesg;
                    TrainingFileMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Hrv:
                if (HrvMesgEvent != null)
                {
                    HrvMesg       hrvMesg       = new HrvMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = hrvMesg;
                    HrvMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.CameraEvent:
                if (CameraEventMesgEvent != null)
                {
                    CameraEventMesg cameraEventMesg = new CameraEventMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = cameraEventMesg;
                    CameraEventMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.GyroscopeData:
                if (GyroscopeDataMesgEvent != null)
                {
                    GyroscopeDataMesg gyroscopeDataMesg = new GyroscopeDataMesg(e.mesg);
                    MesgEventArgs     mesgEventArgs     = new MesgEventArgs();
                    mesgEventArgs.mesg = gyroscopeDataMesg;
                    GyroscopeDataMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.AccelerometerData:
                if (AccelerometerDataMesgEvent != null)
                {
                    AccelerometerDataMesg accelerometerDataMesg = new AccelerometerDataMesg(e.mesg);
                    MesgEventArgs         mesgEventArgs         = new MesgEventArgs();
                    mesgEventArgs.mesg = accelerometerDataMesg;
                    AccelerometerDataMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.ThreeDSensorCalibration:
                if (ThreeDSensorCalibrationMesgEvent != null)
                {
                    ThreeDSensorCalibrationMesg threeDSensorCalibrationMesg = new ThreeDSensorCalibrationMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = threeDSensorCalibrationMesg;
                    ThreeDSensorCalibrationMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.VideoFrame:
                if (VideoFrameMesgEvent != null)
                {
                    VideoFrameMesg videoFrameMesg = new VideoFrameMesg(e.mesg);
                    MesgEventArgs  mesgEventArgs  = new MesgEventArgs();
                    mesgEventArgs.mesg = videoFrameMesg;
                    VideoFrameMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.ObdiiData:
                if (ObdiiDataMesgEvent != null)
                {
                    ObdiiDataMesg obdiiDataMesg = new ObdiiDataMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = obdiiDataMesg;
                    ObdiiDataMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.NmeaSentence:
                if (NmeaSentenceMesgEvent != null)
                {
                    NmeaSentenceMesg nmeaSentenceMesg = new NmeaSentenceMesg(e.mesg);
                    MesgEventArgs    mesgEventArgs    = new MesgEventArgs();
                    mesgEventArgs.mesg = nmeaSentenceMesg;
                    NmeaSentenceMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.AviationAttitude:
                if (AviationAttitudeMesgEvent != null)
                {
                    AviationAttitudeMesg aviationAttitudeMesg = new AviationAttitudeMesg(e.mesg);
                    MesgEventArgs        mesgEventArgs        = new MesgEventArgs();
                    mesgEventArgs.mesg = aviationAttitudeMesg;
                    AviationAttitudeMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Video:
                if (VideoMesgEvent != null)
                {
                    VideoMesg     videoMesg     = new VideoMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = videoMesg;
                    VideoMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.VideoTitle:
                if (VideoTitleMesgEvent != null)
                {
                    VideoTitleMesg videoTitleMesg = new VideoTitleMesg(e.mesg);
                    MesgEventArgs  mesgEventArgs  = new MesgEventArgs();
                    mesgEventArgs.mesg = videoTitleMesg;
                    VideoTitleMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.VideoDescription:
                if (VideoDescriptionMesgEvent != null)
                {
                    VideoDescriptionMesg videoDescriptionMesg = new VideoDescriptionMesg(e.mesg);
                    MesgEventArgs        mesgEventArgs        = new MesgEventArgs();
                    mesgEventArgs.mesg = videoDescriptionMesg;
                    VideoDescriptionMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.VideoClip:
                if (VideoClipMesgEvent != null)
                {
                    VideoClipMesg videoClipMesg = new VideoClipMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = videoClipMesg;
                    VideoClipMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Course:
                if (CourseMesgEvent != null)
                {
                    CourseMesg    courseMesg    = new CourseMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = courseMesg;
                    CourseMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.CoursePoint:
                if (CoursePointMesgEvent != null)
                {
                    CoursePointMesg coursePointMesg = new CoursePointMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = coursePointMesg;
                    CoursePointMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.SegmentId:
                if (SegmentIdMesgEvent != null)
                {
                    SegmentIdMesg segmentIdMesg = new SegmentIdMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = segmentIdMesg;
                    SegmentIdMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.SegmentLeaderboardEntry:
                if (SegmentLeaderboardEntryMesgEvent != null)
                {
                    SegmentLeaderboardEntryMesg segmentLeaderboardEntryMesg = new SegmentLeaderboardEntryMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = segmentLeaderboardEntryMesg;
                    SegmentLeaderboardEntryMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.SegmentPoint:
                if (SegmentPointMesgEvent != null)
                {
                    SegmentPointMesg segmentPointMesg = new SegmentPointMesg(e.mesg);
                    MesgEventArgs    mesgEventArgs    = new MesgEventArgs();
                    mesgEventArgs.mesg = segmentPointMesg;
                    SegmentPointMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.SegmentLap:
                if (SegmentLapMesgEvent != null)
                {
                    SegmentLapMesg segmentLapMesg = new SegmentLapMesg(e.mesg);
                    MesgEventArgs  mesgEventArgs  = new MesgEventArgs();
                    mesgEventArgs.mesg = segmentLapMesg;
                    SegmentLapMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.SegmentFile:
                if (SegmentFileMesgEvent != null)
                {
                    SegmentFileMesg segmentFileMesg = new SegmentFileMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = segmentFileMesg;
                    SegmentFileMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Workout:
                if (WorkoutMesgEvent != null)
                {
                    WorkoutMesg   workoutMesg   = new WorkoutMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = workoutMesg;
                    WorkoutMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.WorkoutStep:
                if (WorkoutStepMesgEvent != null)
                {
                    WorkoutStepMesg workoutStepMesg = new WorkoutStepMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = workoutStepMesg;
                    WorkoutStepMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Schedule:
                if (ScheduleMesgEvent != null)
                {
                    ScheduleMesg  scheduleMesg  = new ScheduleMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = scheduleMesg;
                    ScheduleMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Totals:
                if (TotalsMesgEvent != null)
                {
                    TotalsMesg    totalsMesg    = new TotalsMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = totalsMesg;
                    TotalsMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.WeightScale:
                if (WeightScaleMesgEvent != null)
                {
                    WeightScaleMesg weightScaleMesg = new WeightScaleMesg(e.mesg);
                    MesgEventArgs   mesgEventArgs   = new MesgEventArgs();
                    mesgEventArgs.mesg = weightScaleMesg;
                    WeightScaleMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.BloodPressure:
                if (BloodPressureMesgEvent != null)
                {
                    BloodPressureMesg bloodPressureMesg = new BloodPressureMesg(e.mesg);
                    MesgEventArgs     mesgEventArgs     = new MesgEventArgs();
                    mesgEventArgs.mesg = bloodPressureMesg;
                    BloodPressureMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.MonitoringInfo:
                if (MonitoringInfoMesgEvent != null)
                {
                    MonitoringInfoMesg monitoringInfoMesg = new MonitoringInfoMesg(e.mesg);
                    MesgEventArgs      mesgEventArgs      = new MesgEventArgs();
                    mesgEventArgs.mesg = monitoringInfoMesg;
                    MonitoringInfoMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Monitoring:
                if (MonitoringMesgEvent != null)
                {
                    MonitoringMesg monitoringMesg = new MonitoringMesg(e.mesg);
                    MesgEventArgs  mesgEventArgs  = new MesgEventArgs();
                    mesgEventArgs.mesg = monitoringMesg;
                    MonitoringMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.MemoGlob:
                if (MemoGlobMesgEvent != null)
                {
                    MemoGlobMesg  memoGlobMesg  = new MemoGlobMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = memoGlobMesg;
                    MemoGlobMesgEvent(sender, mesgEventArgs);
                }
                break;

            case (ushort)MesgNum.Pad:
                if (PadMesgEvent != null)
                {
                    PadMesg       padMesg       = new PadMesg(e.mesg);
                    MesgEventArgs mesgEventArgs = new MesgEventArgs();
                    mesgEventArgs.mesg = padMesg;
                    PadMesgEvent(sender, mesgEventArgs);
                }
                break;
            }
        }
示例#16
0
        public static void EncodeCourse()
        {
            const string filename = "CourseEncodeRecipe.fit";

            // Example Record Data Defining a Course
            var courseData = new List <Dictionary <string, object> >()
            {
                new Dictionary <string, object>()
                {
                    { "timestamp", 961262849U }, { "position_lat", 463583114 }, { "position_long", -1131028903 }, { "altitude", 329f }, { "distance", 0f }, { "speed", 0f }
                },
                new Dictionary <string, object>()
                {
                    { "timestamp", 961262855U }, { "position_lat", 463583127 }, { "position_long", -1131031938 }, { "altitude", 328.6f }, { "distance", 22.03f }, { "speed", 3.0f }
                },
                new Dictionary <string, object>()
                {
                    { "timestamp", 961262869U }, { "position_lat", 463583152 }, { "position_long", -1131038159 }, { "altitude", 327.6f }, { "distance", 67.29f }, { "speed", 3.0f }
                },
                new Dictionary <string, object>()
                {
                    { "timestamp", 961262876U }, { "position_lat", 463583164 }, { "position_long", -1131041346 }, { "altitude", 327f }, { "distance", 90.52f }, { "speed", 3.0f }
                },
                new Dictionary <string, object>()
                {
                    { "timestamp", 961262876U }, { "position_lat", 463583164 }, { "position_long", -1131041319 }, { "altitude", 327f }, { "distance", 90.72f }, { "speed", 3.0f }
                },
                new Dictionary <string, object>()
                {
                    { "timestamp", 961262891U }, { "position_lat", 463588537 }, { "position_long", -1131041383 }, { "altitude", 327f }, { "distance", 140.72f }, { "speed", 3.0f }
                },
                new Dictionary <string, object>()
                {
                    { "timestamp", 961262891U }, { "position_lat", 463588549 }, { "position_long", -1131041383 }, { "altitude", 327f }, { "distance", 140.82f }, { "speed", 3.0f }
                },
                new Dictionary <string, object>()
                {
                    { "timestamp", 961262897U }, { "position_lat", 463588537 }, { "position_long", -1131038293 }, { "altitude", 327.6f }, { "distance", 163.26f }, { "speed", 3.0f }
                },
                new Dictionary <string, object>()
                {
                    { "timestamp", 961262911U }, { "position_lat", 463588512 }, { "position_long", -1131032041 }, { "altitude", 328.4f }, { "distance", 208.75f }, { "speed", 3.0f }
                },
                new Dictionary <string, object>()
                {
                    { "timestamp", 961262918U }, { "position_lat", 463588499 }, { "position_long", -1131028879 }, { "altitude", 329f }, { "distance", 231.8f }, { "speed", 3.0f }
                },
                new Dictionary <string, object>()
                {
                    { "timestamp", 961262918U }, { "position_lat", 463588499 }, { "position_long", -1131028903 }, { "altitude", 329f }, { "distance", 231.97f }, { "speed", 3.0f }
                },
                new Dictionary <string, object>()
                {
                    { "timestamp", 961262933U }, { "position_lat", 463583127 }, { "position_long", -1131028903 }, { "altitude", 329f }, { "distance", 281.96f }, { "speed", 3.0f }
                },
            };

            // Create the output stream, this can be any type of stream, including a file or memory stream. Must have read/write access.
            FileStream fitDest = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);

            // Create a FIT Encode object
            Encode encoder = new Encode(ProtocolVersion.V10);

            // Write the FIT header to the output stream
            encoder.Open(fitDest);

            // Reference points for the course
            var firstRecord    = courseData[0];
            var lastRecord     = courseData[courseData.Count - 1];
            var halfwayRecord  = courseData[courseData.Count / 2];
            var startTimestamp = (uint)firstRecord["timestamp"];
            var endTimestamp   = (uint)lastRecord["timestamp"];
            var startDateTime  = new Dynastream.Fit.DateTime(startTimestamp);
            var endDateTime    = new Dynastream.Fit.DateTime(endTimestamp);

            // Every FIT file MUST contain a File ID message
            var fileIdMesg = new FileIdMesg();

            fileIdMesg.SetType(Dynastream.Fit.File.Course);
            fileIdMesg.SetManufacturer(Manufacturer.Development);
            fileIdMesg.SetProduct(ProductId);
            fileIdMesg.SetTimeCreated(startDateTime);
            fileIdMesg.SetSerialNumber(startDateTime.GetTimeStamp());
            encoder.Write(fileIdMesg);

            // Every FIT file MUST contain a Course message
            var courseMesg = new CourseMesg();

            courseMesg.SetName("Garmin Field Day");
            courseMesg.SetSport(Sport.Cycling);
            encoder.Write(courseMesg);

            // Every FIT COURSE file MUST contain a Lap message
            var lapMesg = new LapMesg();

            lapMesg.SetStartTime(startDateTime);
            lapMesg.SetTimestamp(startDateTime);
            lapMesg.SetTotalElapsedTime(endTimestamp - startTimestamp);
            lapMesg.SetTotalTimerTime(endTimestamp - startTimestamp);
            lapMesg.SetStartPositionLat((int)firstRecord["position_lat"]);
            lapMesg.SetStartPositionLong((int)firstRecord["position_long"]);
            lapMesg.SetEndPositionLat((int)lastRecord["position_lat"]);
            lapMesg.SetEndPositionLong((int)lastRecord["position_long"]);
            lapMesg.SetTotalDistance((float)lastRecord["distance"]);
            encoder.Write(lapMesg);

            // Timer Events are REQUIRED for FIT COURSE files
            var eventMesgStart = new EventMesg();

            eventMesgStart.SetTimestamp(startDateTime);
            eventMesgStart.SetEvent(Event.Timer);
            eventMesgStart.SetEventType(EventType.Start);
            encoder.Write(eventMesgStart);

            // Every FIT COURSE file MUST contain Record messages
            foreach (var record in courseData)
            {
                var timestamp = (uint)record["timestamp"];
                var latitude  = (int)record["position_lat"];
                var longitude = (int)record["position_long"];
                var distance  = (float)record["distance"];
                var speed     = (float)record["speed"];
                var altitude  = (float)record["altitude"];

                var recordMesg = new RecordMesg();
                recordMesg.SetTimestamp(new Dynastream.Fit.DateTime(timestamp));
                recordMesg.SetPositionLat(latitude);
                recordMesg.SetPositionLong(longitude);
                recordMesg.SetDistance(distance);
                recordMesg.SetSpeed(speed);
                recordMesg.SetAltitude(altitude);
                encoder.Write(recordMesg);

                // Add a Course Point at the halfway point of the route
                if (record == halfwayRecord)
                {
                    var coursePointMesg = new CoursePointMesg();
                    coursePointMesg.SetTimestamp(new Dynastream.Fit.DateTime(timestamp));
                    coursePointMesg.SetName("Halfway");
                    coursePointMesg.SetType(CoursePoint.Generic);
                    coursePointMesg.SetPositionLat(latitude);
                    coursePointMesg.SetPositionLong(longitude);
                    coursePointMesg.SetDistance(distance);
                    encoder.Write(coursePointMesg);
                }
            }

            // Timer Events are REQUIRED for FIT COURSE files
            var eventMesgStop = new EventMesg();

            eventMesgStop.SetTimestamp(endDateTime);
            eventMesgStop.SetEvent(Event.Timer);
            eventMesgStop.SetEventType(EventType.StopAll);
            encoder.Write(eventMesgStop);

            // Update the data size in the header and calculate the CRC
            encoder.Close();

            // Close the output stream
            fitDest.Close();

            Console.WriteLine($"Encoded FIT file {fitDest.Name}");
        }
示例#17
0
        /// <summary>
        /// Writes the data to a FIT file.
        /// </summary>
        /// <param name="fileName">Name of the FIT file to write to.</param>
        /// <param name="start">Start date/time of the activity.</param>
        /// <param name="laps">Lap and record data to be written.</param>
        /// <param name="calories">Calories used for the activity.</param>
        /// <param name="work">Work done for the activity.</param>
        static void WriteFitFile(string fileName, System.DateTime start, LapsList laps, int calories, uint work)
        {
            // open the encoder and stream
            Encode     encoder   = new Encode(ProtocolVersion.V20);
            FileStream fitStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);

            encoder.Open(fitStream);

            // write the file ID message
            FileIdMesg fileIdMsg = new FileIdMesg();

            fileIdMsg.SetType(Dynastream.Fit.File.Activity);
            fileIdMsg.SetManufacturer(Manufacturer.StagesCycling);
            fileIdMsg.SetProduct(3);
            fileIdMsg.SetSerialNumber(1);
            fileIdMsg.SetTimeCreated(new Dynastream.Fit.DateTime(start));
            encoder.Write(fileIdMsg);

            // write the record and lap messages
            foreach (Lap lap in laps)
            {
                // write the record messages
                foreach (Record record in lap.Records)
                {
                    RecordMesg recordMsg = new RecordMesg();
                    recordMsg.SetTimestamp(new Dynastream.Fit.DateTime(record.Time.ToUniversalTime()));
                    recordMsg.SetHeartRate((byte)record.HeartRate);
                    recordMsg.SetCadence((byte)record.Cadence);
                    recordMsg.SetDistance((float)record.Distance * 1000);
                    recordMsg.SetSpeed((float)(record.Speed / 3.6));
                    recordMsg.SetPower((ushort)record.Power);
                    encoder.Write(recordMsg);
                }

                // write the lap message
                Record   first  = lap.Records[0];
                Record   last   = lap.Records[lap.Records.Count - 1];
                TimeSpan time   = last.Time - first.Time;
                LapMesg  lapMsg = new LapMesg();
                lapMsg.SetTimestamp(new Dynastream.Fit.DateTime(last.Time.ToUniversalTime()));
                lapMsg.SetStartTime(new Dynastream.Fit.DateTime(first.Time.ToUniversalTime()));
                lapMsg.SetTotalElapsedTime((int)time.TotalSeconds);
                lapMsg.SetTotalTimerTime((int)time.TotalSeconds);
                lapMsg.SetTotalDistance((float)(last.Distance - first.Distance) * 1000);
                lapMsg.SetTotalCalories((ushort)lap.Calories);
                lapMsg.SetTotalWork(lap.Work * 1000);
                lapMsg.SetEvent(Event.Lap);
                lapMsg.SetEventType(EventType.Stop);
                lapMsg.SetIntensity(Intensity.Active);
                lapMsg.SetLapTrigger(LapTrigger.Manual);
                lapMsg.SetSport(Sport.Cycling);
                Summary lapSummary = GetLapSummary(lap);
                lapMsg.SetAvgCadence((byte)lapSummary.AveCadence);
                lapMsg.SetMaxCadence((byte)lapSummary.MaxCadence);
                lapMsg.SetAvgHeartRate((byte)lapSummary.AveHeartRate);
                lapMsg.SetMaxHeartRate((byte)lapSummary.MaxHeartRate);
                lapMsg.SetAvgPower((ushort)lapSummary.AvePower);
                lapMsg.SetMaxPower((ushort)lapSummary.MaxPower);
                lapMsg.SetAvgSpeed((float)lapSummary.AveSpeed / 3.6f);
                lapMsg.SetMaxSpeed((float)lapSummary.MaxSpeed / 3.6f);
                encoder.Write(lapMsg);
            }

            // get the first and last records
            Record   firstRecord = laps[0].Records[0];
            Lap      lastLap     = laps[laps.Count - 1];
            Record   lastRecord  = lastLap.Records[lastLap.Records.Count - 1];
            TimeSpan totalTime   = lastRecord.Time - firstRecord.Time;

            // write the session message
            SessionMesg sessionMsg = new SessionMesg();

            sessionMsg.SetTimestamp(new Dynastream.Fit.DateTime(lastRecord.Time.ToUniversalTime()));
            sessionMsg.SetStartTime(new Dynastream.Fit.DateTime(firstRecord.Time.ToUniversalTime()));
            sessionMsg.SetTotalElapsedTime((int)totalTime.TotalSeconds);
            sessionMsg.SetTotalTimerTime((int)totalTime.TotalSeconds);
            sessionMsg.SetTotalDistance((float)(lastRecord.Distance - firstRecord.Distance) * 1000);
            sessionMsg.SetTotalCalories((ushort)calories);
            sessionMsg.SetTotalWork(work * 1000);
            sessionMsg.SetFirstLapIndex(0);
            sessionMsg.SetNumLaps((ushort)laps.Count);
            sessionMsg.SetEvent(Event.Session);
            sessionMsg.SetEventType(EventType.Stop);
            sessionMsg.SetSport(Sport.Cycling);
            sessionMsg.SetSubSport(SubSport.Spin);
            Summary sessionSummary = GetSessionSummary(laps);

            sessionMsg.SetAvgCadence((byte)sessionSummary.AveCadence);
            sessionMsg.SetMaxCadence((byte)sessionSummary.MaxCadence);
            sessionMsg.SetAvgHeartRate((byte)sessionSummary.AveHeartRate);
            sessionMsg.SetMaxHeartRate((byte)sessionSummary.MaxHeartRate);
            sessionMsg.SetAvgPower((ushort)sessionSummary.AvePower);
            sessionMsg.SetMaxPower((ushort)sessionSummary.MaxPower);
            sessionMsg.SetAvgSpeed((float)sessionSummary.AveSpeed / 3.6f);
            sessionMsg.SetMaxSpeed((float)sessionSummary.MaxSpeed / 3.6f);
            encoder.Write(sessionMsg);

            // write the activity message
            ActivityMesg activityMsg = new ActivityMesg();

            activityMsg.SetTimestamp(new Dynastream.Fit.DateTime(lastRecord.Time.ToUniversalTime()));
            activityMsg.SetTotalTimerTime((int)totalTime.TotalSeconds);
            activityMsg.SetNumSessions(1);
            activityMsg.SetType(Activity.Manual);
            activityMsg.SetEvent(Event.Activity);
            activityMsg.SetEventType(EventType.Stop);
            encoder.Write(activityMsg);

            // close the encoder and stream
            encoder.Close();
            fitStream.Close();
        }
示例#18
0
        static void Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            // Generate some FIT messages
            FileIdMesg fileIdMesg = new FileIdMesg();

            fileIdMesg.SetManufacturer(Manufacturer.Dynastream);  // Types defined in the profile are available
            fileIdMesg.SetProduct(1000);
            fileIdMesg.SetSerialNumber(12345);

            //UserProfileMesg myUserProfile = new UserProfileMesg();
            //myUserProfile.SetGender(Gender.Female);
            //float myWeight = 63.1F;
            //myUserProfile.SetWeight(myWeight);
            //myUserProfile.SetAge(99);
            //myUserProfile.SetFriendlyName(Encoding.UTF8.GetBytes("TestUser"));

            var route = GpxClass.FromFile("route.gpx");

            CourseMesg course = new CourseMesg();

            course.SetName(Encoding.UTF8.GetBytes("route from gpx"));
            course.SetSport(Sport.Cycling);

            var baseDate = route.metadata.timeSpecified ? route.metadata.time : System.DateTime.Now.AddDays(-1);

            FileStream fitDest = new FileStream("Test.fit", FileMode.Create, FileAccess.ReadWrite, FileShare.Read);

            // Create file encode object
            Encode encodeDemo = new Encode();

            // Write our header
            encodeDemo.Open(fitDest);
            // Encode each message, a definition message is automatically generated and output if necessary
            encodeDemo.Write(fileIdMesg);
            //encodeDemo.Write(myUserProfile);

            encodeDemo.Write(course);

            var lap = new LapMesg();

            encodeDemo.Write(lap);


            var firstTrk = route.trk.First();

            var firstTrkSeg = firstTrk.trkseg.First();

            var firstPoint = firstTrkSeg.trkpt.First();

            lap.SetTimestamp(new fit.DateTime(firstPoint.time));
            lap.SetStartPositionLat(firstPoint.lat.RawInt());
            lap.SetStartPositionLong(firstPoint.lon.RawInt());

            var lastPoint = firstTrkSeg.trkpt.Last();

            lap.SetEndPositionLat(lastPoint.lat.RawInt());
            lap.SetEndPositionLong(lastPoint.lon.RawInt());

            var e = new EventMesg();

            e.SetTimestamp(new fit.DateTime(firstPoint.time));
            e.SetEventType(EventType.Start);
            e.SetEventGroup(0);
            e.SetEvent(Event.Timer);
            e.SetData(null);
            encodeDemo.Write(e);

            foreach (var point in firstTrkSeg.trkpt)
            {
                var p = new RecordMesg();
                p.SetPositionLat(point.lat.RawInt());
                p.SetPositionLong(point.lon.RawInt());
                //p.SetDistance(point. 10665.65f);
                p.SetAltitude(Convert.ToSingle(point.ele));
                p.SetTimestamp(new fit.DateTime(baseDate));

                encodeDemo.Write(p);
            }

            var eventStop = new EventMesg();

            eventStop.SetData(null);
            eventStop.SetTimestamp(new fit.DateTime(lastPoint.time));
            eventStop.SetEvent(Event.Timer);
            eventStop.SetEventType(EventType.StopDisableAll);
            encodeDemo.Write(eventStop);

            // Update header datasize and file CRC
            encodeDemo.Close();

            fitDest.Close();

            Console.WriteLine("Encoded FIT file test.fit");
            stopwatch.Stop();
            Console.WriteLine("Time elapsed: {0:0.#}s", stopwatch.Elapsed.TotalSeconds);

            Console.ReadKey();
        }
        public ICollection <LapMesg> GetLapsBasedOnDistance(WorkoutSamples workoutSamples, Dynastream.Fit.DateTime startTime, Sport sport, SubSport subSport)
        {
            using var tracing = Tracing.Trace($"{nameof(FitConverter)}.{nameof(GetLapsBasedOnDistance)}")
                                .WithTag(TagKey.Format, FileFormat.Fit.ToString());

            var stepsAndLaps = new List <LapMesg>();

            if (workoutSamples is null)
            {
                return(stepsAndLaps);
            }

            var speedMetrics = GetSpeedSummary(workoutSamples);

            if (speedMetrics is null)
            {
                return(stepsAndLaps);
            }

            var speedUnit = GetDistanceUnit(speedMetrics?.Display_Unit);
            var lapMeters = 0;

            switch (speedUnit)
            {
            case DistanceUnit.Kilometers: lapMeters = 1000; break;

            default: lapMeters = 1600; break;
            }

            LapMesg lap                 = null;
            ushort  stepIndex           = 0;
            var     lapDistanceInMeters = 0f;
            float   lapLengthSeconds    = 0;

            for (var secondsSinceStart = 0; secondsSinceStart < speedMetrics.Values.Length; secondsSinceStart++)
            {
                if (lap is null || lap.GetTotalElapsedTime() is not null)
                {
                    // Start new Lap
                    var lapStartTime = new Dynastream.Fit.DateTime(startTime);
                    lapStartTime.Add(secondsSinceStart);

                    lap = new LapMesg();
                    lap.SetStartTime(lapStartTime);
                    lap.SetMessageIndex(stepIndex);
                    lap.SetEvent(Event.Lap);
                    lap.SetLapTrigger(LapTrigger.Time);
                    lap.SetSport(sport);
                    lap.SetSubSport(subSport);

                    lapLengthSeconds    = 0;
                    lapDistanceInMeters = 0f;
                }

                var currentSpeedInMPS = ConvertToMetersPerSecond(speedMetrics.GetValue(secondsSinceStart), workoutSamples);
                lapDistanceInMeters += 1 * currentSpeedInMPS;
                lapLengthSeconds++;

                if (lapDistanceInMeters >= lapMeters || secondsSinceStart == speedMetrics.Values.Length - 1)
                {
                    lap.SetTotalElapsedTime(lapLengthSeconds);
                    lap.SetTotalTimerTime(lapLengthSeconds);
                    lap.SetTotalDistance(lapDistanceInMeters);
                    stepsAndLaps.Add(lap);
                    stepIndex++;
                }
            }

            return(stepsAndLaps);
        }