void InValidFingerPrintShouldFail() { string nodeId = "4816d758dd37833a3a5551001dac8a5fa737a342"; PayloadSigner signer = new PayloadSigner(nodeId, new FileKeyStore("./")); signer.Init(); List <string> telemetryToSend = new List <string>(); telemetryToSend.Add("abc 1"); telemetryToSend.Add("abc 2"); telemetryToSend.Add("abc 3"); TelemetryPacket pkt = new TelemetryPacket { NodeId = nodeId, Payload = telemetryToSend, Signature = signer.SignPayload(string.Join(string.Empty, telemetryToSend)) }; string jsonPayload = JsonConvert.SerializeObject(pkt); FtpManager fm = new FtpManager(_userName, _password, _ftpHost, _ftpPort, "38:32:36:8e:ad:ac:8c:31:57:b4:80:ba:2d:e4:88:9d", "/upload/dropzone/"); string fileName = string.Format("{0}-{1}.json", nodeId, DateTime.UtcNow.ToString("yyyy-MM-dd_HH:mm:ss")); //Assert.True(!fm.transferData(jsonPayload, fileName)); }
private void timer1_Tick(object sender, EventArgs e) { var packet = new TelemetryPacket(); var byteMessage = PacketUtilities.ConvertPacketToByteArray(packet); udpClient.Send(byteMessage, byteMessage.Length); }
public void Returning_to_pits_does_not_set_previous_lap_as_fastest() { // set outlap var manager = new TelemetryLapManager(); foreach (var packet in TelemetryLapHelper.CreateOutLap().Packets) { manager.ProcessIncomingPacket(packet); } // Add nearly all of a lap var firstLap = TelemetryLapHelper.CreatePopulatedLap(lapNumber: 1f, completeLap: true); for (var i = 0; i < firstLap.Packets.Count - 2; i++) { manager.ProcessIncomingPacket(firstLap.Packets[i]); } Assert.IsNull(manager.FastestLap); var garagePacket = new TelemetryPacket { Lap = 0f, Speed = 0f, LapDistance = -0.001f }; Assert.IsTrue(garagePacket.IsSittingInPits); manager.ProcessIncomingPacket(garagePacket); Assert.IsNull(manager.FastestLap); }
public void SpeedInKmPerHour_is_correct() { var packet = new TelemetryPacket { Speed = 100f }; Assert.AreEqual(360, packet.SpeedInKmPerHour); }
public void GetPacketClosestTo_returns_packet_closest_to_supplied_packet() { var tLap = new TelemetryLap(Circuit.NullCircuit, "LapType"); tLap.AddPacket(new TelemetryPacket { LapDistance = 0.529f }); tLap.AddPacket(new TelemetryPacket { LapDistance = 1.875f }); tLap.AddPacket(new TelemetryPacket { LapDistance = 3.221f }); tLap.AddPacket(new TelemetryPacket { LapDistance = 4.567f }); tLap.AddPacket(new TelemetryPacket { LapDistance = 5.931f }); tLap.AddPacket(new TelemetryPacket { LapDistance = 7.262f }); // should be closest to this tLap.AddPacket(new TelemetryPacket { LapDistance = 8.611f }); tLap.AddPacket(new TelemetryPacket { LapDistance = 9.961f }); tLap.AddPacket(new TelemetryPacket { LapDistance = 11.311f }); tLap.AddPacket(new TelemetryPacket { LapDistance = 12.661f }); tLap.AddPacket(new TelemetryPacket { LapDistance = 14.013f }); tLap.AddPacket(new TelemetryPacket { LapDistance = 15.365f }); tLap.AddPacket(new TelemetryPacket { LapDistance = 16.715f }); tLap.AddPacket(new TelemetryPacket { LapDistance = 18.067f }); tLap.AddPacket(new TelemetryPacket { LapDistance = 19.419f }); var tPacketCompare = new TelemetryPacket { LapDistance = 7.811f }; var foundPacket = tLap.GetPacketClosestTo(tPacketCompare); Assert.AreEqual(7.262f, foundPacket.LapDistance); }
public static byte[] ConvertPacketToByteArray(TelemetryPacket packet) { int size = Marshal.SizeOf(packet); byte[] arr = new byte[size]; IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(packet, ptr, true); Marshal.Copy(ptr, arr, 0, size); Marshal.FreeHGlobal(ptr); return arr; }
public TelemetryPacketGenerator(int lowerRange, int upperRange) { _packetNumber = 0; _lowerRange = lowerRange; _upperRange = upperRange; _randomGenerator = new Random(); _current = new TelemetryPacket { Time = ElapsedTime }; }
public TelemetryPacket GetPacket() { // inspect each property and fill with crap var packet = new TelemetryPacket(); ValueType vThis = packet; var fields = packet.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance); for (var i = 0; i < fields.Count(); i++) { fields[i].SetValue(vThis, 10); } return((TelemetryPacket)vThis); }
public void HasStartLinePacket_is_false_when_first_packet_time_is_greater_than_one_sixtieth_of_second() { const float cutoff = (1000 / 60000f) + 0.001f; // Samples are taken every 0.017 seconds, so first sample must be < 0.018 into the lap. // time differs slightly because last sample of last lap might have been nearly 0.017 before end of that lap. var tPacket = new TelemetryPacket() { LapTime = cutoff * 1.1f }; var tLap = new TelemetryLap(Circuit.NullCircuit, "LapType"); tLap.AddPacket(tPacket); Assert.IsFalse(tLap.IsFirstPacketStartLine); }
public void ShouldDeseializeFromJson() { string json = "{ \"nodeid\":\"validator-1\",\"payload\": [ \"payload-line-1\",\"payload-line-2\" ],\"signature\":\"a-signature\"}"; TelemetryPacket tp = JsonConvert.DeserializeObject <TelemetryPacket>(json); tp.NodeId.Should().Be("validator-1"); tp.Signature.Should().Be("a-signature"); tp.Payload.Should() .HaveCount(2) .And .BeEquivalentTo(new[] { "payload-line-1", "payload-line-2" }); }
// This method runs continously in the data collection thread. It // waits to receive UDP packets from the game, converts them and writes // them to the shared struct variable. private void FetchData() { while (true) { // Get the data (this will block until we get a packet) Byte[] receiveBytes = udpSocket.Receive(ref senderIP); // Lock access to the shared struct syncMutex.WaitOne(); TransmissionLabel.BackColor = Color.Green; // Convert the bytes received to the shared struct latestData = PacketUtilities.ConvertToPacket(receiveBytes); manager.ProcessIncomingPacket(latestData); //TransmissionLabel.BackColor = Color.Red; // Release the lock again syncMutex.ReleaseMutex(); } }
protected override void start() { //if(manager == null) // manager = new TelemetryLapManager(); // Set up the socket for collecting game telemetry try { //remoteIP = F1SpeedSettings.AllowConnectionsFromOtherMachines ? new IPEndPoint(IPAddress.Any, PORTNUM) : new IPEndPoint(IPAddress.Parse(IP), PORTNUM); //remoteIP = new IPEndPoint(IPAddress.Parse(IP), PORTNUM); udpSocket = new UdpClient(PORTNUM); //udpSocket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //udpSocket.ExclusiveAddressUse = false; //udpSocket.Client.Bind(remoteIP); NotifyStatusMessage("Connected to F1 Codemaster. " + IP + ":" + PORTNUM.ToString()); while (!CancellationPending) { if (udpSocket.Available > 0) { // Get the data (this will block until we get a packet) Byte[] receiveBytes = udpSocket.Receive(ref senderIP); // Lock access to the shared struct //syncMutex.WaitOne(); // Convert the bytes received to the shared struct latestData = PacketUtilities.ConvertToPacket(receiveBytes); //manager.ProcessIncomingPacket(latestData); // Release the lock again //syncMutex.ReleaseMutex(); /*currentRpm = float.Parse(manager.GetCurrentData("EngineRevs")); * firstRpm = 1.10f * float.Parse(manager.GetCurrentData("IdleRpm")); * lastRpm = 0.90f * float.Parse(manager.GetCurrentData("MaxRpm"));*/ currentRpm = latestData.EngineRevs; firstRpm = 1.10f * latestData.IdleRpm; lastRpm = 0.90f * latestData.MaxRpm; sendRPMShiftMsg(currentRpm, firstRpm, lastRpm, flag); foreach (SerialManager serialManager in sm) { if (serialManager.deviceContains7Segments()) { send7SegmentMsg(); } } lastTimeConnected = Utils.getCurrentTimeMillis(); } else { if (Utils.getCurrentTimeMillis() - lastTimeConnected > 1000) { foreach (SerialManager serialManager in sm) { if (serialManager.deviceContains7Segments()) { serialManager.enqueueCommand(Utils.getDisconnectedMsgCmd(), false); serialManager.enqueueCommand(Utils.getBlackRPMCmd(), false); } } //race session hasn't started or game paused lastTimeConnected = 0; } } Thread.Sleep(TIMERINTERVAL); } } catch (Exception e) { logger.LogMessageToFile(e.ToString(), true); // throw; } }
/// <summary> /// Sends data to Ingress restful end point /// </summary> /// <param name="state">Object state</param> private static void FlushToIngress(object state) { // Flush to ingress if more than 10 telemetry recordings -or- last flush older that 1 minute if (_globalQueue.Count <= 10 && DateTime.UtcNow - _lastFlush <= new TimeSpan(0, 1, 0)) { Console.WriteLine($"Not flushing: {_globalQueue.Count} Queued - {(DateTime.UtcNow - _lastFlush).TotalSeconds} seconds since flush"); return; } List <string> telemetryToSend = new List <string>(); while (telemetryToSend.Count < 50 && _globalQueue.TryDequeue(out string lineFromQueue)) { telemetryToSend.Add(lineFromQueue); } Console.WriteLine($"Flushing {telemetryToSend.Count} to ingress. {_globalQueue.Count} still in queue." + (_flushHighspeed ? " [HighSpeed]" : "")); TelemetryPacket pkt = new TelemetryPacket { NodeId = _configuration.NodeId, Payload = telemetryToSend, Signature = _signer.SignPayload(string.Join(string.Empty, telemetryToSend)) }; string jsonPayload = JsonConvert.SerializeObject(pkt); // Send data TalkToIngress tti = new TalkToIngress(_configuration.IngressHost + "/api/ingress/influx", _configuration.IngressFingerprint); bool sendSuccess = tti.SendRequest(jsonPayload).Result; if (!sendSuccess) { if (DateTime.UtcNow - _lastFlush > TimeSpan.FromMinutes(5)) { // unable to send to ingress for 5 minutes - send by second channel Console.WriteLine("ERROR: Unable to send to ingress for more then 5 minutes. Sending queue on second channel."); string fileName = $"{_configuration.NodeId}-{DateTime.UtcNow:yyyy-MM-dd_HH:mm:ss}.json"; try { if (!_ftpMgr.TransferData(jsonPayload, fileName)) { Console.WriteLine("ERROR: Unable to send data on second channel. Data File {0}", fileName); // second channel also not available - requeue Console.WriteLine("Unable to flush to second channel - re queueing"); telemetryToSend.ForEach(_globalQueue.Enqueue); } } catch (Exception ex) { Console.WriteLine("ERROR: Unable to send data on second channel. Error Details {0}", ex); // second channel also not available - requeue Console.WriteLine("Unable to flush to second channel - re queueing"); telemetryToSend.ForEach(_globalQueue.Enqueue); } } else { // 5min second channel delay not reached -> re-queue Console.WriteLine("Unable to flush. Re-queuing..."); telemetryToSend.ForEach(_globalQueue.Enqueue); } } else { if (_globalQueue.Count > 250 && !_flushHighspeed) { // increase processing speed to 2 seconds Console.WriteLine("Increasing push speed due to queue size"); _flushTimer.Change(2000, 2000); _flushHighspeed = true; } else if (_globalQueue.Count < 250 && _flushHighspeed) // queue is small enough to get processed. back to normal speed { Console.WriteLine("Decreasing push speed due to queue size"); _flushTimer.Change(10000, 10000); _flushHighspeed = false; } _lastFlush = DateTime.UtcNow; } }
private void ReadWorker(object n) { lock (this.Data) { _DataPointer = 0; _ReadStage = 1; for (int i = 0; i < data.Length - 8; i++) { if (data[i] == '$' && data[i + 1] == '#') { ushort PacketID = BitConverter.ToUInt16(data, i + 2); ushort Type = BitConverter.ToUInt16(data, i + 4); ushort InstanceID = BitConverter.ToUInt16(data, i + 6); ushort PacketSize = BitConverter.ToUInt16(data, i + 8); byte[] PacketData = new byte[PacketSize]; ByteMethods.memcpy(PacketData, data, PacketSize, 0, i + 10); TelemetryPacket packet = new TelemetryPacket { Data = PacketData, ID = PacketID, Type = (TelemetryLogPacket)Type, InstanceID = InstanceID, Size = PacketSize }; Packets.Add(packet); _DataPointer = i + PacketSize; i += PacketSize; } } _DataPointer = data.Length; _ReadStage = 2; // parse packets TelemetrySample Sample = new TelemetrySample(); Instances = new Dictionary <int, string>(); Properties = new Dictionary <string, Dictionary <int, string> >(); Types = new Dictionary <string, Dictionary <int, int> >(); string last_type = ""; int last_type_id = 0; bool first_packet = true; double time = -1.0; foreach (TelemetryPacket packet in Packets) { _PacketPointer++; switch (packet.Type) { case TelemetryLogPacket.InstanceName: last_type = ASCIIEncoding.ASCII.GetString(packet.Data).Replace('\0', ' ').Trim(); last_type_id = packet.InstanceID; Instances.Add(last_type_id, last_type); Types.Add(last_type, new Dictionary <int, int>()); Properties.Add(last_type, new Dictionary <int, string>()); break; case TelemetryLogPacket.InstanceMember: int id = BitConverter.ToInt16(packet.Data, 2); if (!Sample.Data.ContainsKey(last_type_id)) { Sample.Data.Add(last_type_id, new Dictionary <int, object>()); } if (Sample.Data[last_type_id].ContainsKey(id) == false) { Sample.Data[last_type_id].Add(id, 0); } int type_id = BitConverter.ToInt16(packet.Data, 0); if (Types[last_type].ContainsKey(id) == false) { Types[last_type].Add(id, type_id); byte[] member_name = new byte[packet.Data.Length - 4]; ByteMethods.memcpy(member_name, packet.Data, packet.Data.Length - 4, 0, 4); string key = ASCIIEncoding.ASCII.GetString(member_name).Replace('\0', ' ').Trim(); Properties[last_type].Add(id, key); } break; case TelemetryLogPacket.Data: int instance_id = BitConverter.ToInt16(packet.Data, 0); int last_typeid = 0; for (int i = 2; i < packet.Data.Length;) { int id_type = BitConverter.ToInt32(packet.Data, i); object v = 0; Dictionary <int, int> TypeArray = Types[Instances[instance_id]]; i += 4; if (TypeArray.ContainsKey(id_type)) { switch (TypeArray[id_type]) { case 0: //double v = BitConverter.ToDouble(packet.Data, i); i += 8; break; case 1: //float v = BitConverter.ToSingle(packet.Data, i); i += 4; break; case 2: // int32 v = BitConverter.ToInt32(packet.Data, i); i += 4; break; case 3: // int16 v = BitConverter.ToInt16(packet.Data, i); i += 2; break; case 4: // int8 v = packet.Data[i]; i += 1; break; case 5: // uint32 v = BitConverter.ToUInt32(packet.Data, i); i += 4; break; case 6: // uint16 v = BitConverter.ToUInt16(packet.Data, i); i += 2; break; case 7: // uint8 v = packet.Data[i]; i += 1; break; case 8: // string int k = i; for (; k < packet.Data.Length; k++) { if (packet.Data[k] == 0) { break; } } v = ASCIIEncoding.ASCII.GetString(packet.Data, i, k - i); i = k + 1; break; case 9: // bool v = ((packet.Data[i] == 1) ? true : false); i += 1; break; default: v = 0; break; } Sample.Data[instance_id][id_type] = (object)v; last_typeid = id_type; } } break; case TelemetryLogPacket.Time: // Store previous samples. if (time != -1.0 && this.Data.ContainsKey(time) == false) { this.Data.Add(time, Sample.Clone()); this.Data[time].Time = time; } time = BitConverter.ToDouble(packet.Data, 0); break; } } // Store last sample. if (time != -1.0 && this.Data.ContainsKey(time) == false) { this.Data.Add(time, Sample.Clone()); this.Data[time].Time = time; } _ReadStage = 3; // Set the telemetry track. if (Telemetry.m.Active_Session) { return; } else if (Telemetry.m.Sims != null) { // TODO: Urgent; add simulator type to log file. Telemetry.m.Track_Load(Telemetry.m.Sims.Get("rfactor"), GetString(time, "Session.CircuitName")); } } }