public virtual int SendWaypoints(IList <GlobalsatWaypoint> waypoints, IJobMonitor jobMonitor) { int nrSentWaypoints = 0; if (this.Open()) { try { GlobalsatPacket packet = PacketFactory.SendWaypoints(this.FitnessDevice.configInfo.MaxNrWaypoints, waypoints); GlobalsatPacket response = (GlobalsatPacket)this.SendPacket(packet); // km500 no out of memory- waypoint overwritten nrSentWaypoints = response.ResponseSendWaypoints(); if (nrSentWaypoints < waypoints.Count) { jobMonitor.ErrorText = string.Format("Could only send {0} out of {1} waypoints (Capacity {2}).", nrSentWaypoints, waypoints.Count, this.FitnessDevice.configInfo.MaxNrWaypoints); } } catch (Exception e) { jobMonitor.ErrorText = Properties.Resources.Device_SendWaypoints_Error + e; } finally { this.Close(); } } if (!this.DataRecieved) { NoCommunicationError(jobMonitor); nrSentWaypoints = 0; } return(nrSentWaypoints); }
public virtual IList <GlobalsatWaypoint> GetWaypoints(IJobMonitor jobMonitor) { IList <GlobalsatWaypoint> waypoints = null; if (this.Open()) { try { GlobalsatPacket packet = PacketFactory.GetWaypoints(); GlobalsatPacket response = (GlobalsatPacket)this.SendPacket(packet); waypoints = response.ResponseGetWaypoints(); } catch (Exception e) { jobMonitor.ErrorText = Properties.Resources.Device_GetWaypoints_Error + e; } finally { this.Close(); } } if (!this.DataRecieved) { NoCommunicationError(jobMonitor); waypoints = null; } return(waypoints); }
public virtual bool DeleteAllWaypoints(IJobMonitor jobMonitor) { bool result = false; if (this.Open()) { try { GlobalsatPacket packet = PacketFactory.DeleteAllWaypoints(); GlobalsatPacket response = (GlobalsatPacket)this.SendPacket(packet); result = true; } catch (Exception e) { jobMonitor.ErrorText = Properties.Resources.Device_DeleteWaypoints_Error + e; } finally { this.Close(); } } if (!this.DataRecieved) { NoCommunicationError(jobMonitor); } return(result); }
public virtual int SetSystemConfiguration2(GlobalsatDeviceConfiguration devConfig, IJobMonitor jobMonitor) { int result = -1; //No need to check if device is connected if (this.Open()) { try { GlobalsatPacket packet = PacketFactory.SetSystemConfiguration2(devConfig.SystemConfigDataRaw); GlobalsatPacket response = (GlobalsatPacket)this.SendPacket(packet); //No info in the response result = 0; } catch (Exception e) { jobMonitor.ErrorText = Properties.Resources.Device_GetInfo_Error + e; } finally { this.Close(); } } if (!this.DataRecieved) { NoCommunicationError(jobMonitor); } return(result); }
public virtual bool DeleteAllTracks(IJobMonitor jobMonitor) { bool result = false; try { if (this.Open()) { //IList<GlobalsatPacket.TrackFileHeader> headers = ((GlobalsatProtocol2)device).ReadTrackHeaders(jobMonitor); //List<GlobalsatPacket.TrackFileHeader> fetch = new List<GlobalsatPacket.TrackFileHeader>(); GlobalsatPacket getDeleteAllTracks = PacketFactory.GetDeleteAllTracks(); GlobalsatPacket2 response = (GlobalsatPacket2)SendPacket(getDeleteAllTracks); result = true; } } catch (Exception e) { jobMonitor.ErrorText = Properties.Resources.Device_OpenDevice_Error + e; //throw new Exception(Properties.Resources.Device_OpenDevice_Error + e); } finally { this.Close(); } if (!this.DataRecieved) { NoCommunicationError(jobMonitor); } return(result); }
public virtual IList <GlobalsatPacket> SendTrackPackets(GhPacketBase.Train trackFile) { IList <GlobalsatPacket> sendTrackPackets = new List <GlobalsatPacket>(); //Console.WriteLine("------ SendTrackStart()"); GlobalsatPacket startPacket = PacketFactory.SendTrackStart(trackFile); sendTrackPackets.Add(startPacket); //Some protocols send laps in separate header //Use common code instead of overiding this method GlobalsatPacket lapPacket = PacketFactory.SendTrackLaps(trackFile); if (lapPacket != null) { sendTrackPackets.Add(lapPacket); } for (int i = 0; i < trackFile.TrackPoints.Count; i += startPacket.TrackPointsPerSection) { //Console.WriteLine("------ SendTrackSection()"); GlobalsatPacket pointsPacket = PacketFactory.SendTrackSection(trackFile, i, Math.Min(i + startPacket.TrackPointsPerSection - 1, trackFile.TrackPoints.Count - 1)); sendTrackPackets.Add(pointsPacket); } return(sendTrackPackets); }
public GlobalsatSystemConfiguration2 GetGlobalsatSystemConfiguration2() { GlobalsatPacket packet = PacketFactory.GetSystemConfiguration2(); GlobalsatPacket response2 = (GlobalsatPacket)this.SendPacket(packet); GlobalsatSystemConfiguration2 systemInfo = response2.ResponseGetSystemConfiguration2(); return(systemInfo); }
public virtual IList <GlobalsatPacket.TrackFileHeader> ReadTrackHeaders(IJobMonitor monitor) { //monitor.StatusText = CommonResources.Text.Devices.ImportJob_Status_OpeningDevice; GlobalsatPacket getHeadersPacket = PacketFactory.GetTrackFileHeaders(); GlobalsatPacket2 response = (GlobalsatPacket2)SendPacket(getHeadersPacket); return(response.UnpackTrackHeaders()); }
public IList <Gh625Packet.TrackFileHeader625M> ReadTrackHeaders(IJobMonitor monitor) { monitor.PercentComplete = 0; monitor.StatusText = CommonResources.Text.Devices.ImportJob_Status_OpeningDevice; Int16[] tracks = new Int16[2]; GlobalsatPacket getHeadersPacket = PacketFactory.GetTrackFileHeaders(); Gh625Packet response = (Gh625Packet)SendPacket(getHeadersPacket); return(response.UnpackTrackHeaders()); }
protected bool ValidGlobalsatPort(SerialPort port) { GlobalsatPacket packet = PacketFactory.GetWhoAmI(); bool res = false; //If "probe" packet fails, this is not a Globalsat port //If some distinction needed (other device?), set some flag here GhPacketBase response = null; try { response = SendPacket(packet); } catch (Exception) { } if (response != null && response.CommandId == packet.CommandId && response.PacketLength > 1) { string devId = response.ByteArr2String(0, 8); if (!string.IsNullOrEmpty(devId)) { lastDevId = devId; if (this.FitnessDevice.configInfo.AllowedIds == null || this.FitnessDevice.configInfo.AllowedIds.Count == 0) { this.devId = devId; res = true; } else { foreach (string aId in this.FitnessDevice.configInfo.AllowedIds) { if (devId.StartsWith(aId)) { this.devId = devId; res = true; break; } } } } } if (!res) { this.Close(); } return(res); }
public virtual Bitmap GetScreenshot(IJobMonitor jobMonitor) { Bitmap result = null; //Note: No check for connected here if (this.Open()) { try { GlobalsatPacket packet = PacketFactory.GetScreenshot(); GlobalsatPacket response = (GlobalsatPacket)this.SendPacket(packet); System.Drawing.RotateFlipType rotate = RotateFlipType.RotateNoneFlipNone; if (this.FitnessDevice.CanRotateScreen) { //try getting screen orientaion try { packet = PacketFactory.GetSystemConfiguration2(); GlobalsatPacket response2 = (GlobalsatPacket)this.SendPacket(packet); GlobalsatSystemConfiguration2 systemInfo = response2.ResponseGetSystemConfiguration2(); if (systemInfo.ScreenOrientation == 1) { rotate = RotateFlipType.Rotate90FlipNone; } } catch {} } result = response.ResponseGetScreenshot(rotate); } catch (Exception e) { jobMonitor.ErrorText = Properties.Resources.Device_GetInfo_Error + e; //throw new Exception(Properties.Resources.Device_GetInfo_Error + e); } finally { this.Close(); } } if (!this.DataRecieved) { NoCommunicationError(jobMonitor); } return(result); }
public IList <Gh615Packet.TrackFileSection> ReadTracks(IList <Gh615Packet.TrackFileHeader> tracks, IJobMonitor monitor) { if (tracks.Count == 0) { return(new Gh615Packet.TrackFileSection[0]); } float totalPoints = 0; IList <Int16> trackIndexes = new List <Int16>(); foreach (Gh615Packet.TrackFileHeader header in tracks) { totalPoints += header.TrackPointCount; trackIndexes.Add(header.TrackPointIndex); } float pointsRead = 0; IList <Gh615Packet.TrackFileSection> trackSections = new List <Gh615Packet.TrackFileSection>(); GlobalsatPacket getFilesPacket = PacketFactory.GetTrackFileSections(trackIndexes); GlobalsatPacket getNextPacket = PacketFactory.GetNextTrackSection(); Gh615Packet data = (Gh615Packet)SendPacket(getFilesPacket); monitor.PercentComplete = 0; Gh615Packet.TrackFileSection trackSection; do { trackSection = data.UnpackTrackSection(); if (trackSection != null) { pointsRead += trackSection.EndPointIndex - trackSection.StartPointIndex + 1; DateTime time = trackSection.StartTime.ToLocalTime(); string statusProgress = time.ToShortDateString() + " " + time.ToShortTimeString(); monitor.StatusText = String.Format(CommonResources.Text.Devices.ImportJob_Status_Reading, statusProgress); monitor.PercentComplete = pointsRead / totalPoints; trackSections.Add(trackSection); data = (Gh615Packet)SendPacket(getNextPacket); } } while (trackSection != null); monitor.PercentComplete = 1; return(trackSections); }
public override int SendWaypoints(IList <GlobalsatWaypoint> waypoints, IJobMonitor jobMonitor) { int nrSentWaypoints = 0; if (this.Open()) { try { foreach (GlobalsatWaypoint g in waypoints) { GlobalsatPacket packet = PacketFactory.SendWaypoints(this.FitnessDevice.configInfo.MaxNrWaypoints, new List <GlobalsatWaypoint> { g }); GlobalsatPacket response = (GlobalsatPacket)this.SendPacket(packet); int resp = response.ResponseSendWaypoints(); nrSentWaypoints += resp; if (resp <= 0) { jobMonitor.ErrorText = string.Format("Could only send {0} out of {1} waypoints. (Capacity {2}).", nrSentWaypoints, waypoints.Count, this.FitnessDevice.configInfo.MaxNrWaypoints); break; } } } catch (Exception ex) { jobMonitor.ErrorText = Properties.Resources.Device_SendWaypoints_Error + ex; } finally { this.Close(); } } if (!this.DataRecieved) { //Normal case NoCommunicationError(jobMonitor); } return(nrSentWaypoints); }
//not working, deletes all... public virtual int DeleteTracks(DateTime oldest, IJobMonitor jobMonitor) { int res = -1; try { if (this.Open()) { IList <GlobalsatPacket.TrackFileHeader> headers = this.ReadTrackHeaders(jobMonitor); IList <GlobalsatPacket.TrackFileHeader> fetch = new List <GlobalsatPacket.TrackFileHeader>(); foreach (GlobalsatPacket.TrackFileHeader t in headers) { if (t.StartTime < oldest) { fetch.Add(t); } } if (fetch.Count > 0) { GlobalsatPacket getDeleteTracks = PacketFactory.GetDeleteTracks(fetch); GlobalsatPacket2 response = (GlobalsatPacket2)SendPacket(getDeleteTracks); } res = fetch.Count; } } catch (Exception e) { jobMonitor.ErrorText = Properties.Resources.Device_OpenDevice_Error + e; //throw new Exception(Properties.Resources.Device_OpenDevice_Error + e); } finally { this.Close(); } if (!this.DataRecieved) { NoCommunicationError(jobMonitor); } return(res); }
//Not used as a separate protocol now //public virtual GlobalsatPacket.GlobalsatSystemInformation GetSystemConfiguration(IJobMonitor jobMonitor) //{ // this.Open(); // try // { // GlobalsatPacket packet = PacketFactory.GetSystemConfiguration(); // GlobalsatPacket response = (GlobalsatPacket)this.SendPacket(packet); // GlobalsatPacket.GlobalsatSystemConfiguration systemInfo = response.ResponseGetSystemConfiguration(); // return systemInfo; // } // catch(Exception e) // { // throw new Exception(Properties.Resources.Device_GetInfo_Error+e); // } // finally // { // this.Close(); // } //} public virtual GlobalsatDeviceConfiguration GetSystemConfiguration2(IJobMonitor jobMonitor) { //No need to check if device is connected GlobalsatDeviceConfiguration devConfig = new GlobalsatDeviceConfiguration(); if (this.Open()) { try { GlobalsatPacket packet = PacketFactory.GetSystemConfiguration(); GlobalsatPacket response = (GlobalsatPacket)this.SendPacket(packet); GlobalsatSystemConfiguration systemInfo = response.ResponseGetSystemConfiguration(); devConfig.DeviceName = systemInfo.DeviceName; packet = PacketFactory.GetSystemConfiguration2(); response = (GlobalsatPacket)this.SendPacket(packet); devConfig.SystemConfigDataRaw = response.PacketData; } catch (Exception e) { devConfig = null; jobMonitor.ErrorText = Properties.Resources.Device_GetInfo_Error + e; } finally { this.Close(); } } if (!this.DataRecieved) { NoCommunicationError(jobMonitor); } return(devConfig); }
public IList <Gh625Packet.TrackFileSection625M> ReadTracks(IList <Gh625Packet.TrackFileHeader625M> tracks, IJobMonitor monitor) { if (tracks.Count == 0) { return(new Gh625Packet.TrackFileSection625M[0]); } float totalPoints = 0; IList <Int16> trackIndexes = new List <Int16>(); foreach (Gh625Packet.TrackFileHeader625M header in tracks) { totalPoints += header.TrackPointCount; trackIndexes.Add(header.TrackPointIndex); } float pointsRead = 0; IList <Gh625Packet.TrackFileSection625M> trackSections = new List <Gh625Packet.TrackFileSection625M>(); GlobalsatPacket getFilesPacket = PacketFactory.GetTrackFileSections(trackIndexes); GlobalsatPacket getNextPacket = PacketFactory.GetNextTrackSection(); Gh625Packet response = (Gh625Packet)SendPacket(getFilesPacket); monitor.PercentComplete = 0; Gh625Packet.TrackFileSection625M trackSection; int numInCurrentTrain = 0; int readInCurrentTrain = 0; do { if (numInCurrentTrain == 0) { // The section is a laps section (the first of the section) trackSection = response.UnpackTrackSectionLaps(); if (trackSection != null) { numInCurrentTrain = trackSection.TrackPointCount; readInCurrentTrain = 0; } } else { // The section is a GPS/HRM detail section trackSection = response.UnpackTrackSection(); if (trackSection != null) { int pointsInThisSection = trackSection.EndPointIndex - trackSection.StartPointIndex + 1; readInCurrentTrain += pointsInThisSection; pointsRead += pointsInThisSection; DateTime time = trackSection.StartTime.ToLocalTime(); string statusProgress = time.ToShortDateString() + " " + time.ToShortTimeString(); monitor.StatusText = String.Format(CommonResources.Text.Devices.ImportJob_Status_Reading, statusProgress); monitor.PercentComplete = pointsRead / totalPoints; if (readInCurrentTrain >= numInCurrentTrain) { numInCurrentTrain = 0; } } } if (trackSection != null) { trackSections.Add(trackSection); response = (Gh625Packet)SendPacket(getNextPacket); } } while (trackSection != null); monitor.PercentComplete = 1; return(trackSections); }
//This routine has a lot of try-catch-rethrow to simplify debugging //Globalsat device communication is tricky... public virtual GhPacketBase SendPacket(GlobalsatPacket packet) { //Use packet factory, to make sure the packet matches the device GhPacketBase received = this.PacketFactory; //sending occasionally fails, retry int remainingAttempts = 3; while (remainingAttempts > 0) { try { if (!port.IsOpen) { //Physical port should be closed port.Open(); } if (packet.CommandId == GhPacketBase.CommandWhoAmI) { //Speed-up device detection, keep this as short as possible. //625XT seem to work with 5ms, 505 needs more than 100 port.ReadTimeout = this.FitnessDevice.ReadTimeoutDetect; } else if (packet.CommandId == GhPacketBase.CommandGetScreenshot) { port.ReadTimeout = 5000; } else { port.ReadTimeout = this.FitnessDevice.ReadTimeout; } //Override from device config? if (this.FitnessDevice.configInfo.ReadTimeout > 0 && (packet.CommandId != GhPacketBase.CommandGetScreenshot || this.FitnessDevice.configInfo.ReadTimeout > port.ReadTimeout)) { port.ReadTimeout = this.FitnessDevice.configInfo.ReadTimeout; } byte[] sendPayload = packet.ConstructPayload(this.FitnessDevice.BigEndianPacketLength); try { /* * Console.Write("Write:"); * for(int i = 0; i < sendPayload.Length;i++) * { * Console.Write(" " + sendPayload[i].ToString() ); * } * Console.WriteLine(""); */ port.Write(sendPayload, 0, sendPayload.Length); } catch (Exception e) { string s = string.Format("Error occurred, sending {0} bytes.", sendPayload.Length); ReportError(s, packet.CommandId == GhPacketBase.CommandWhoAmI, e); port.Close(); throw; } try { int data = port.ReadByte(); received.CommandId = (byte)data; if (data < 0 || data > 255) { //Special handling for first byte -1 is stream closed throw new TimeoutException(string.Format("No data received for {0},{1}", packet.CommandId, data)); } if (packet.CommandId == GhPacketBase.CommandWhoAmI) { this.DataRecieved = false; } else { this.DataRecieved = true; } int hiPacketLen = port.ReadByte(); int loPacketLen = port.ReadByte(); //Note: The endian for size (except for 561) from the device always seem to be the same (not so when sending) received.PacketLength = (Int16)((hiPacketLen << 8) + loPacketLen); } catch (Exception e) { string s = string.Format("Error occurred, receiving {0} bytes ({1},{2}).", received.PacketLength, packet.CommandId, received.CommandId); ReportError(s, packet.CommandId == GhPacketBase.CommandWhoAmI, e); port.Close(); throw; } if (packet.CommandId != GhPacketBase.CommandGetScreenshot && received.PacketLength > this.FitnessDevice.configInfo.MaxPacketPayload || received.PacketLength > 0x1000) { string s = string.Format("Error occurred, bad response receiving {0} bytes ({1},{2}).", received.PacketLength, packet.CommandId, received.CommandId); ReportError(s, packet.CommandId == GhPacketBase.CommandWhoAmI); port.Close(); throw new Exception(Properties.Resources.Device_OpenDevice_Error); } received.PacketData = new byte[received.PacketLength]; byte checksum = 0; int receivedBytes = 0; //debug timeouts try { for (Int16 b = 0; b < received.PacketLength; b++) { int data = port.ReadByte(); if (data < 0 || data > 255) { //-1 is stream closed throw new TimeoutException(string.Format("All data not received for {0}({4},{1}) bytes ({2},{3}).", received.PacketLength, receivedBytes, packet.CommandId, received.CommandId, data)); } received.PacketData[b] = (byte)data; receivedBytes++; } checksum = (byte)port.ReadByte(); receivedBytes++; /* * Console.Write("Read: id:" + received.CommandId + " length:" + received.PacketLength); * for(int i = 0; i < received.PacketLength;i++) * { * Console.Write(" " + received.PacketData[i].ToString() ); * } * Console.WriteLine(" checksum:" + checksum); */ } catch (Exception e) { string s = string.Format("Error occurred, receiving {0}({1}) bytes ({2},{3}).", received.PacketLength, receivedBytes, packet.CommandId, received.CommandId); ReportError(s, packet.CommandId == GhPacketBase.CommandWhoAmI, e); port.Close(); throw; //Debug template, if the device is corrupted //Should use resend //Ignore the exception, just to get data from the device //if (!(this is Gh505Device && // (receivedBytes == 2005 && received.PacketLength == 2068 || // receivedBytes == 913 && received.PacketLength == 976))) //{ // throw e; //} //received.PacketLength = (Int16)receivedBytes; //checksum = 0; //overrideException = true; } if (!received.ValidResponseCrc(checksum)) { string s = string.Format("Error occurred, invalid checksum receiving {0}({1}) bytes ({2},{3}).", received.PacketLength, receivedBytes, packet.CommandId, received.CommandId); ReportError(s, packet.CommandId == GhPacketBase.CommandWhoAmI); port.Close(); throw new Exception(Properties.Resources.Device_OpenDevice_Error); } else if (received.CommandId == GhPacketBase.ResponseResendTrackSection && remainingAttempts > 0) { //retry sending remainingAttempts--; } else if (received.CommandId != packet.CommandId && //TODO: Cleanup in allowed sender/response allowed (probably overload) !((received.CommandId == GhPacketBase.CommandGetTrackFileSections || received.CommandId == GhPacketBase.CommandId_FINISH || received.CommandId == GhPacketBase.ResponseSendTrackFinish) && (packet.CommandId == GhPacketBase.CommandGetNextTrackSection || packet.CommandId == GhPacketBase.CommandGetTrackFileSections || packet.CommandId == GhPacketBase.CommandSendTrackSection)) ) { string s = string.Format("Error occurred, invalid response {0}({1}) bytes ({2},{3}).", received.PacketLength, receivedBytes, packet.CommandId, received.CommandId); ReportError(s, packet.CommandId == GhPacketBase.CommandWhoAmI); if (received.CommandId == GhPacketBase.ResponseInsuficientMemory) { throw new InsufficientMemoryException(Properties.Resources.Device_InsuficientMemory_Error); } throw new Exception(Properties.Resources.Device_OpenDevice_Error); } else { //Assume OK response, no more tries remainingAttempts = 0; } } #pragma warning disable CS0168 // Variable is declared but never used catch (Exception e) #pragma warning restore CS0168 // Variable is declared but never used { remainingAttempts--; if (packet.CommandId == GhPacketBase.CommandWhoAmI || remainingAttempts <= 0) { //No need retry this.Close(); throw; } } } return(received); }
public virtual int SendTrack(IList <GhPacketBase.Train> trains, IJobMonitor jobMonitor) { int result = 0; if (jobMonitor.Cancelled) { return(result); } if (this.Open()) { //Something to start the progress... jobMonitor.PercentComplete = 0.01F; try { foreach (GhPacketBase.Train train in trains) { IList <GlobalsatPacket> packets = SendTrackPackets(train); int i = 0; foreach (GlobalsatPacket packet in packets) { GlobalsatPacket response = (GlobalsatPacket)this.SendPacket(packet); if (response != null && response.CommandId != packet.CommandId) { //Generic codes handled in SendPacket if (response.CommandId == GhPacketBase.ResponseSendTrackFinish) { //Done, all sent break; } else if (response.CommandId == GhPacketBase.ResponseResendTrackSection) { //Handled in SendPacket(), retry there or fail //throw new Exception(Properties.Resources.Device_SendTrack_Error); } //Console.WriteLine("------ send error 4"); jobMonitor.ErrorText = Properties.Resources.Device_SendTrack_Error + response.CommandId; break; //throw new Exception(Properties.Resources.Device_SendTrack_Error + response.CommandId); } i++; //Handle open packet as one, for each activity float progress = (result + (1 + 1 + i) / (float)(1 + packets.Count)) / (float)(trains.Count); jobMonitor.PercentComplete = progress; if (jobMonitor.Cancelled) { return(result); } } result++; //Globalsat seem to need waiting in between activities.... if (trains.Count > 1) { System.Threading.Thread.Sleep(1000); } } } catch (Exception ex) { jobMonitor.ErrorText = Properties.Resources.Device_SendTrack_Error + Environment.NewLine + ex.Message; } finally { this.Close(); } } if (!this.DataRecieved) { NoCommunicationError(jobMonitor); result = 0; } return(result); }
public virtual IList <GlobalsatPacket.Train> ReadTracks(IList <GlobalsatPacket.TrackFileHeader> tracks, IJobMonitor monitor) { if (tracks.Count == 0) { return(new GlobalsatPacket.Train[0]); } int totalPoints = 0; IList <Int16> trackIndexes = new List <Int16>(); foreach (GlobalsatPacket.TrackFileHeader header in tracks) { totalPoints += header.TrackPointCount; //track number, less than 100 trackIndexes.Add((Int16)header.TrackPointIndex); } int totalPointsRead = 0; GlobalsatPacket getFilesPacket = PacketFactory.GetTrackFileSections(trackIndexes); GlobalsatPacket2 response = (GlobalsatPacket2)SendPacket(getFilesPacket); monitor.PercentComplete = 0; IList <GlobalsatPacket.Train> trains = new List <GlobalsatPacket.Train>(); ReadMode readMode = ReadMode.Header; int trainLapsToRead = 0; int pointsToRead = 0; while (response.CommandId != GlobalsatPacket2.CommandId_FINISH && !monitor.Cancelled) { //Check that previous mode was finished, especially at corruptions there can be out of sync if (readMode != ReadMode.Header) { byte readMode2 = response.GetTrainContent(); if (readMode2 == GlobalsatPacket.HeaderTypeTrackPoints) { if (readMode != ReadMode.Points) { //TODO: Handle error } readMode = ReadMode.Points; } else if (readMode2 == GlobalsatPacket.HeaderTypeLaps) { if (readMode != ReadMode.Laps) { //TODO: Handle error } readMode = ReadMode.Laps; } else { if (readMode != ReadMode.Header) { //TODO: Handle error if (trains.Count > 0) { trains.RemoveAt(trains.Count - 1); } } readMode = ReadMode.Header; } } if (response.CommandId == GlobalsatPacket2.CommandId_FINISH) { break; } switch (readMode) { case ReadMode.Header: { GlobalsatPacket.Train train = response.UnpackTrainHeader(); if (train != null) { trainLapsToRead = train.LapCount; pointsToRead = train.TrackPointCount; trains.Add(train); } readMode = ReadMode.Laps; break; } case ReadMode.Laps: { GlobalsatPacket.Train currentTrain = trains[trains.Count - 1]; IList <GlobalsatPacket.Lap> laps = response.UnpackLaps(); foreach (GlobalsatPacket.Lap lap in laps) { currentTrain.Laps.Add(lap); } trainLapsToRead -= laps.Count; if (trainLapsToRead <= 0) { readMode = ReadMode.Points; } break; } case ReadMode.Points: { GlobalsatPacket.Train currentTrain = trains[trains.Count - 1]; IList <GlobalsatPacket.TrackPoint> points = response.UnpackTrackPoints(); foreach (GlobalsatPacket.TrackPoint point in points) { currentTrain.TrackPoints.Add(point); } pointsToRead -= points.Count; totalPointsRead += points.Count; DateTime startTime = currentTrain.StartTime.ToLocalTime(); string statusProgress = startTime.ToShortDateString() + " " + startTime.ToShortTimeString(); monitor.StatusText = String.Format(CommonResources.Text.Devices.ImportJob_Status_Reading, statusProgress); monitor.PercentComplete = (float)totalPointsRead / (float)totalPoints; if (pointsToRead <= 0) { readMode = ReadMode.Header; } break; } } //All requests are the same response = (GlobalsatPacket2)SendPacket(PacketFactory.GetNextTrackSection()); } monitor.PercentComplete = 1; monitor.StatusText = CommonResources.Text.Devices.ImportJob_Status_ImportComplete; return(trains); }