/// <summary>
        /// Receive a Balloon Message, need to transmit the data in a new TrackerMessage
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task <bool> Receive(BalloonMessage balloonMessage, IModuleClient moduleClient)
        {
            Logger.LogInfo($"Received Balloon Message.");
            UpdatePacketReceiveHistory(true);
            packetReceiptTimer.Change(packetReceiptInterval, packetReceiptInterval);

            this.FlightId = balloonMessage.FlightId;

            var trackerMessage = new TrackerMessage()
            {
                Location   = this.Location,
                DeviceName = this.DeviceName,
                FlightId   = balloonMessage.FlightId,
                PacketReceivedPercentage = CalculatePacketReceivedPercentage()
            };

            try
            {
                Message balloonMessageRaw = new Message(balloonMessage.ToRawBytes());
                await moduleClient.SendEventAsync(TrackerOutputName, balloonMessageRaw);

                Message trackerMessageRaw = new Message(trackerMessage.ToRawBytes());
                await moduleClient.SendEventAsync(TrackerOutputName, trackerMessageRaw);

                Logger.LogInfo($"transmitted message: {JsonConvert.SerializeObject(trackerMessage)}.");
            }
            catch (Exception ex)
            {
                // Todo - wire in with application insights
                Logger.LogWarning($"Error Transmitter tracker message: {ex.Message}");
                return(false);
            }

            return(true);
        }
Exemplo n.º 2
0
    public void Interrupt(int eventType, string tag)
    {
        if (eventModules == null)
        {
            return;
        }
        if (eventType != (int)egEvent.Type.All)
        {
            Interrupt((int)egEvent.Type.All, tag);
        }

        /*
         *  Track all the modules that require to be tracked on every type of event by a certain object
         */
        foreach (OnEventModule eventModule in eventModules[eventType])
        {
            foreach (string moduleTag in eventModule.tags)
            {
                if (moduleTag == tag)
                {
                    TrackerMessage msg = eventModule.module.GetMessage();
                    //Debug.Log ("Tracker message=" + msg);
                    SessionCreator.Instance.CurrentSession.AddMessage(msg);
                }
            }
        }
    }
        private void ReceiptTimerCallback(object state)
        {
            Logger.LogWarning("Timer fired - did not receive expected balloon message");
            UpdatePacketReceiveHistory(false);

            var trackerMessage = new TrackerMessage()
            {
                Location   = this.Location,
                DeviceName = this.DeviceName,
                FlightId   = this.FlightId,
                PacketReceivedPercentage = CalculatePacketReceivedPercentage()
            };

            try
            {
                var     moduleClient      = WrappedModuleClient.Create().Result;
                Message trackerMessageRaw = new Message(trackerMessage.ToRawBytes());
                moduleClient.SendEventAsync(TrackerOutputName, trackerMessageRaw).Wait();
            }
            catch (Exception ex)
            {
                // Todo - wire in with application insights
                Logger.LogWarning($"Error Transmitter tracker message: {ex.Message}");
            }
        }
Exemplo n.º 4
0
    public static TrackerMessage FromJSON(string json)
    {
        fsData         data = fsJsonParser.Parse(json);
        TrackerMessage ret  = null;

        _serializer.TryDeserialize <TrackerMessage>(data, ref ret);
        return(ret);
    }
        /// <summary>
        /// Executes the UDP request.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="message">The message.</param>
        /// <returns>
        /// The tracker response message.
        /// </returns>
        private TrackerMessage ExecuteUdpRequest(Uri uri, TrackerMessage message)
        {
            uri.CannotBeNull();
            message.CannotBeNull();

            byte[]       data = null;
            IAsyncResult asyncResult;
            IPEndPoint   any = new IPEndPoint(IPAddress.Any, this.ListeningPort);

            try
            {
                using (UdpClient udp = new UdpClient())
                {
                    udp.Client.SendTimeout    = (int)TimeSpan.FromSeconds(5).TotalMilliseconds;
                    udp.Client.ReceiveTimeout = (int)TimeSpan.FromSeconds(15).TotalMilliseconds;

                    if (this.TrackerUri.Port > 0)
                    {
                        udp.Send(message.Encode(), message.Length, this.TrackerUri.Host, this.TrackerUri.Port);
                    }
                    else
                    {
                        return(null);
                    }

                    asyncResult = udp.BeginReceive(null, null);

                    if (asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5)))
                    {
                        data = udp.EndReceive(asyncResult, ref any);
                    }
                    else
                    {
                        // timeout
                    }
                }
            }
            catch (SocketException ex)
            {
                Debug.WriteLine($"could not send message to UDP tracker {this.TrackerUri} for torrent {this.TorrentInfoHash}: {ex.Message}");

                return(null);
            }

            if (TrackerMessage.TryDecode(data, 0, MessageType.Response, out message))
            {
                if (message is ErrorMessage)
                {
                    Debug.WriteLine($"error message received from UDP tracker {this.TrackerUri}: \"{message.As<ErrorMessage>().ErrorText}\"");
                }

                return(message);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 6
0
        public void HandleTrackingInfoReceived(TrackerMessage message)
        {
            if (KmlFile == "")
            {
                log.Error("Cannot log to KML file when no KML file has been specified.");
            }

            var point = new Point
            {
                Coordinate = new Vector(message.Lat, message.Long)
            };



            var placemark = new Placemark
            {
                Name = message.DeviceID,
                Time = new Timestamp
                {
                    When = message.Timestamp
                },
                Description = new Description
                {
                    Text = string.Format("Speed: {0}, Direction: {1}", message.Speed, message.Direction)
                },
                Geometry = point
            };

            var serializer = new Serializer();

            if (!File.Exists(KmlFile))
            {
                log.InfoFormat("Creating new KML file '{0}'.", KmlFile);
                var newKml = new Kml();
                newKml.Feature = new Folder
                {
                    Id   = "f0",
                    Name = "gpstrackerd events"
                };
                serializer.Serialize(newKml);
                File.WriteAllText(KmlFile, serializer.Xml);
            }

            Parser parser = new Parser();

            parser.ParseString(File.ReadAllText(KmlFile), false);

            var kml    = (Kml)parser.Root;
            var folder = (Folder)kml.Feature;

            folder.AddFeature(placemark);

            serializer.Serialize(kml);
            File.WriteAllText(KmlFile, serializer.Xml);
            log.InfoFormat("KmlBackend appended record to file '{0}'.", KmlFile);
        }
Exemplo n.º 7
0
    void HandleOnReplayTransition(ReplayEventData data)
    {
        TrackerMessage bodyMessage = SessionAnalyzer.LookupMessage(data.To.messages, "Player Skeleton");

        if (bodyMessage != null)
        {
            EnableBody body = bodyMessage.Value as EnableBody;
            SetFromBody(body, data);
        }
    }
Exemplo n.º 8
0
 public void AddMessage(TrackerMessage message)
 {
     if (!streamAlive)
     {
         return;
     }
     messages.Add(message);
     fs.WriteLine(message.SerializedValue);
     fs.Flush();
 }
Exemplo n.º 9
0
    public static List <TrackerMessage> Lookup(this Session sess, string key)
    {
        List <TrackerMessage> values = new List <TrackerMessage>();

        for (int i = 0; i < sess.Messages.Count; i++)
        {
            TrackerMessage m = sess.Messages[i];
            if (m.Key == key)
            {
                values.Add(m);
            }
        }
        return(values);
    }
Exemplo n.º 10
0
 private void SendMessageToBackend(TrackerMessage message)
 {
     // store up our list of messages to send to backend
     if (message.Key.Equals("Hand Game Position") ||
         message.Key.Equals("Avatar Skeleton") ||
         message.Key.Equals("Footer"))
     {
         sendToBackend.Add(message);
     }
     if (sendToBackend.Count >= numToSend)
     {
         FlushMessagesToBackend();
     }
 }
Exemplo n.º 11
0
    public static List <TrackerMessage> Lookup(this Session sess, DateTime timeStamp)
    {
        List <TrackerMessage> values = new List <TrackerMessage>();

        for (int i = 0; i < sess.Messages.Count; i++)
        {
            TrackerMessage m = sess.Messages[i];
            if (m.TimeStamp.CompareTo(timeStamp) == 0)
            {
                values.Add(m);
            }
        }
        return(values);
    }
Exemplo n.º 12
0
 public void HandleTrackingInfoReceived(TrackerMessage message)
 {
     if (message != null)
     {
         string logLine = string.Format("[{0}] ({1})  {2},{3} - direction: {4} speed: {5}", DateTime.Now, message.DeviceID, message.Lat, message.Long, message.Direction, message.Speed);
         if (OutputFilename != "")
         {
             using (StreamWriter sw = File.AppendText(OutputFilename))
             {
                 sw.WriteLine(logLine);
             }
         }
     }
 }
Exemplo n.º 13
0
        public static TrackerDocument Create(TrackerMessage message)
        {
            return new TrackerDocument() 
            {
                Altitude = (message.Location != null) ? message.Location.alt : 0,
                DeviceName = message.DeviceName,
                FlightId = message.FlightId,
                TimestampUTC = message.Timestamp,
                partitionid = message.partitionid,
                Latitude =  (message.Location != null) ? message.Location.lat : 0,
                Longitude =  (message.Location != null) ? message.Location.@long : 0,
                Geopoint =  (message.Location != null) ? new Point(message.Location.@long,message.Location.lat) : null

                // DistanceToBalloon  - todo
            };
        }
Exemplo n.º 14
0
        private async Task SendDataToSplunk(TrackerMessage message)
        {
            log.DebugFormat("Sending tracker event from tracker {0} to endpoint {1}", message.DeviceID, Endpoint);
            string splunkObject = JsonConvert.SerializeObject(message);
            string postUrl      = string.Format("{0}/services/collector/raw", Endpoint);

            try
            {
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Splunk", AuthenticationToken);
                await client.PostAsync(postUrl, new StringContent(splunkObject, Encoding.UTF8, "application/json"));
            } catch (Exception e)
            {
                log.ErrorFormat("Failed to send data to splunk: {0}", e.Message);
            }
        }
Exemplo n.º 15
0
 public void AddMessage(TrackerMessage message, bool closeJson)
 {
     if (!streamAlive)
     {
         return;
     }
     //Debug.Log("Session Message Added");
     messages.Add(message);
     fs.WriteLine(message.SerializedValue + (closeJson ? "]}" : ","));
     fs.Flush();
     if (!closeJson)
     {
         SendMessageToBackend(message);
     }
     else
     {
         FlushMessagesToBackend();
     }
 }
Exemplo n.º 16
0
        public void HandleTrackingInfoReceived(TrackerMessage message)
        {
            var csb = new MySqlConnectionStringBuilder(this.ConnectionString);

            csb.UserID   = this.Username;
            csb.Password = this.Password;
            using (var conn = new MySqlConnection(csb.ToString()))
            {
                try
                {
                    conn.Open();
                } catch (Exception e)
                {
                    log.ErrorFormat("Error while connecting to MySQL instance: {0}", e.Message);
                    return;
                }

                log.InfoFormat("Inserting tracker record into MySQL {0} server.", conn.ServerVersion);

                var insertionCommand = conn.CreateCommand();
                insertionCommand.CommandText = "INSERT INTO tracker_events (device_id, direction, latitude, longitude, speed) VALUES (@device_id, @direction, @latitude, @longitude, @speed)";
                insertionCommand.Parameters.Add(new MySqlParameter("device_id", message.DeviceID));
                insertionCommand.Parameters.Add(new MySqlParameter("direction", message.Direction));
                insertionCommand.Parameters.Add(new MySqlParameter("latitude", message.Lat));
                insertionCommand.Parameters.Add(new MySqlParameter("longitude", message.Long));
                insertionCommand.Parameters.Add(new MySqlParameter("speed", message.Speed));

                try
                {
                    insertionCommand.ExecuteNonQuery();
                }catch (Exception e)
                {
                    log.ErrorFormat("Failed to insert record into MySQL database: {0}", e.Message);
                }
            }
        }
Exemplo n.º 17
0
 public void AddMessage(TrackerMessage message)
 {
     AddMessage(message, false);
 }
Exemplo n.º 18
0
 public void HandleTrackingInfoReceived(TrackerMessage message)
 {
     SendDataToSplunk(message).Wait();
 }
Exemplo n.º 19
0
    // runs a series of tests for the api
    private IEnumerator TestAPI()
    {
        Authenticate("*****@*****.**", "test", "Kollect");
        yield return(new WaitForSeconds(2f));

        //TestEndpoint();
        //yield return new WaitForSeconds(2f);
        CreateNewSession(EnableAPI.Instance.Game, EnableAPI.Instance.Version);
        yield return(new WaitForSeconds(2f));

        EnableString   handString1 = new EnableString("(2.5, 2.5, 5.0) (2.0, 2.0, 5.0)");
        TrackerMessage handData1   = new TrackerMessage("Hand Game Position", handString1);

        PushSessionData(handData1.SerializedValue);

        EnableString   handString2 = new EnableString("(1.5, 3.5, -5.0) (3.0, 3.0, 5.0)");
        TrackerMessage handData2   = new TrackerMessage("Hand Game Position", handString2);

        PushSessionData(handData2.SerializedValue);

        /*
         *      // create test session data json
         *      Dictionary<string, object> postData = new Dictionary<string, object>();
         *      Dictionary<string, object> handData = new Dictionary<string, object>();
         *      Dictionary<string, object> skeletonData = new Dictionary<string, object>();
         *      Dictionary<string, object> jointDictionary = new Dictionary<string, object>();
         *      Dictionary<string, object> spinebaseData = new Dictionary<string, object>();
         *      Dictionary<string, object> spinemidData = new Dictionary<string, object>();
         *      Dictionary<string, object> position1 = new Dictionary<string, object>();
         *      Dictionary<string, object> orientation1 = new Dictionary<string, object>();
         *      Dictionary<string, object> position2 = new Dictionary<string, object>();
         *      Dictionary<string, object> orientation2 = new Dictionary<string, object>();
         *
         *      Action ClearDBs = () => {
         *              postData.Clear();
         *              handData.Clear();
         *              skeletonData.Clear();
         *              jointDictionary.Clear();
         *              spinebaseData.Clear();
         *              spinemidData.Clear();
         *              position1.Clear();
         *              orientation1.Clear();
         *              position2.Clear();
         *              orientation2.Clear();
         *      };
         *
         *      ClearDBs();
         *      handData.Add("Value", "(2.5, 2.5, 5.0) (2.0, 2.0, 5.0)");
         *      handData.Add("$type", "EnableString");
         *      postData.Add("timestamp", GetTimestamp());
         *      postData.Add("key", "Hand Game Position");
         *      postData.Add("value", handData);
         *      PushSessionData(postData);
         *      yield return new WaitForSeconds(.3f);
         *
         *      ClearDBs();
         *      handData.Add("Value", "(1.5, 3.5, -5.0) (3.0, 3.0, 5.0)");
         *      handData.Add("$type", "EnableString");
         *      postData.Add("timestamp", GetTimestamp());
         *      postData.Add("key", "Hand Game Position");
         *      postData.Add("value", handData);
         *      PushSessionData(postData);
         *      yield return new WaitForSeconds(.3f);
         *
         *      ClearDBs();
         *      position1.Add("x", 1.1);
         *      position1.Add("y", 2.2);
         *      position1.Add("z", 3.3);
         *      orientation1.Add("x", 0.1);
         *      orientation1.Add("y", 0.2);
         *      orientation1.Add("z", 0.3);
         *      orientation1.Add("w", 0.4);
         *      spinebaseData.Add("position", position1);
         *      spinebaseData.Add("orientation", orientation1);
         *      position2.Add("x", 6.6);
         *      position2.Add("y", 7.7);
         *      position2.Add("z", 8.8);
         *      orientation2.Add("x", 0.6);
         *      orientation2.Add("y", 0.7);
         *      orientation2.Add("z", 0.8);
         *      orientation2.Add("w", 0.9);
         *      spinemidData.Add("position", position2);
         *      spinemidData.Add("orientation", orientation2);
         *      skeletonData.Add("SpineBase", spinebaseData);
         *      skeletonData.Add("SpineMid", spinemidData);
         *      jointDictionary.Add("jointDictionary", skeletonData);
         *      postData.Add("timestamp", GetTimestamp());
         *      postData.Add("key", "Player Skeleton");
         *      postData.Add("value", jointDictionary);
         *      PushSessionData(postData);
         */
    }
Exemplo n.º 20
0
 public void AddMessage(TrackerMessage message)
 {
     if (!streamAlive) {
         return;
     }
     messages.Add(message);
     fs.WriteLine(message.SerializedValue);
     fs.Flush();
 }
Exemplo n.º 21
0
        public void HandleGPSTracker(Object obj)
        {
            TcpClient client   = (TcpClient)obj;
            var       stream   = client.GetStream();
            string    deviceID = "";


            try
            {
                string command = "";
                byte   receivedChar;
                while (true)
                {
                    try
                    {
                        int receivedData = stream.ReadByte();
                        if (receivedData == -1)
                        {
                            continue;
                        }
                        receivedChar = (byte)receivedData;
                        if (receivedChar == '*')
                        {
                            command = "";
                        }
                        else if (receivedChar == '#')
                        {
                            // process full message
                            log.Debug(command);
                            string[] segments = command.Split(',');
                            // 0  1          2  3      4 5         6 7          8 9      10
                            // HQ,6028189208,V1,154919,A,5103.6043,N,00343.9613,E,000.40,344,130221,FFFFFBFF,206,20,1501,51814,05,27
                            if (segments.Length == 19)
                            {
                                if (segments[1] != deviceID)
                                {
                                    log.DebugFormat("Client sent deviceID: {0}", segments[1]);
                                    if (deviceID != "")
                                    {
                                        log.WarnFormat("Device ID changed in-flight! old: {0} new: {1}", deviceID, segments[1]);
                                    }
                                    deviceID = segments[1];
                                }
                                if (segments[2] != "V1")
                                {
                                    continue;
                                }

                                // check if receiver has lock on GPS
                                if (segments[4] != "A")
                                {
                                    continue;
                                }

                                var trackerMessage = new TrackerMessage(deviceID);
                                trackerMessage.SetLatLong(segments[5], segments[6], segments[7], segments[8]);
                                trackerMessage.Speed     = Convert.ToDouble(segments[9]);
                                trackerMessage.Direction = Convert.ToInt32(segments[10]);
                                log.InfoFormat("Received tracker message: {0}", trackerMessage.ToString());
                                if (TrackingInfoReceived != null)
                                {
                                    TrackingInfoReceived(trackerMessage);
                                }
                            }
                        }
                        else
                        {
                            command += ASCIIEncoding.ASCII.GetString(new byte[] { receivedChar });
                        }
                    }
                    catch (Exception e)
                    {
                        log.Debug(e);
                    }
                }
            }
            catch (SocketException e)
            {
                log.ErrorFormat("SocketException: {0}", e);
            }
        }
Exemplo n.º 22
0
 /// <summary>
 /// Make a game message with a specified tracker message object
 /// </summary>
 /// <param name="message">Used to specify a specific key and message</param>
 public void Message(TrackerMessage message)
 {
     SessionCreator.Instance.CurrentSession.AddMessage(message);
 }
Exemplo n.º 23
0
 /// <summary>
 /// Make a game message with a specified tracker message object
 /// </summary>
 /// <param name="message">Used to specify a specific key and message</param>
 public void Message(TrackerMessage message)
 {
     SessionCreator.Instance.CurrentSession.AddMessage(message);
 }