Example #1
0
 public void ProcessData(EmitData data)
 {
     factory.StartNew<bool>(() =>
         {
             try
             {
                 String url = String.Format(baseUrl + "?card={0}&time={1:HH:mm:ss.fff}&location={2}", data.Id, data.Time, data.BoxId);
                 WebClient webClient = new WebClient();
                 Stream stream = webClient.OpenRead(url);
                 StreamReader reader = new StreamReader(stream);
                 String request = reader.ReadToEnd();
                 Console.WriteLine("Success: " + url);
             }
             catch (WebException ex)
             {
                 return false;
             }
             return true;
         }).ContinueWith((t) => {
             if (!t.Result)
             {
                 // failed to upload for some reason - put back in queue
                 Console.WriteLine("Failed - retry");
                 ProcessData(data);
             }
         });
 }
Example #2
0
        public void Start()
        {
            MySqlConnection conn = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString);
            MySqlCommand cmd = new MySqlCommand("SELECT * FROM LocationPasses WHERE year = " + Year + " ORDER BY time", conn);

            Task.Factory.StartNew(() =>
            {
                try
                {
                    conn.Open();
                    MySqlDataReader data = cmd.ExecuteReader();

                    DateTime nextSleep = DateTime.Now;
                    Boolean init = false;

                    while (data.Read())
                    {
                        EmitData d = new EmitData()
                        {
                            Id = data.GetInt16("card"),
                            BoxId = data.GetInt16("location"),
                            Time = data.GetDateTime("time"),
                            Force = false
                        };

                            EventHandler<EmitDataRecievedEventArgs> handler = DataReceived;

                            if (handler != null)
                                handler(this, new EmitDataRecievedEventArgs(d));

                        System.Threading.Thread.Sleep(30);
                    }
                    data.Close();
                    conn.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to read database:" + ex.Message);
                }
                finally
                {
                    conn.Close();
                }
            });
        }
Example #3
0
        public void Start()
        {
            Task.Factory.StartNew(() =>
            {
                try
                {
                    Dictionary<int, DateTime> timers = new Dictionary<int, DateTime>();
                    Random rnd = new Random();

                    // init start
                    foreach(int test in Testers)
                        timers.Add(test, new DateTime(2016,4,16,13,14,00));

                    foreach (int box in Stations) {
                        foreach(int test in Testers) {
                            // Leap forward 10-20 min
                            timers[test] = timers[test].AddSeconds(rnd.Next(600, 1200));

                            EmitData d = new EmitData()
                                {
                                    Id = test,
                                    BoxId = box,
                                    Time = timers[test],
                                    Force = false
                                };

                                EventHandler<EmitDataRecievedEventArgs> handler = DataReceived;

                                if (handler != null)
                                    handler(this, new EmitDataRecievedEventArgs(d));

                            System.Threading.Thread.Sleep(1000);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            });
        }
Example #4
0
        public void ProcessData(EmitData data)
        {
            lock (lockObj)
            {
                ToSend.Enqueue(data);
            }

            if (sending)
            {
                return;
            }

            lock (lockObj) {
                sending = true;
            }

            while (ToSend.Count > 0)
            {
                EmitData dataToSend = ToSend.Peek();
                try
                {
                    myHub.Invoke("SendPassering", new object[] { dataToSend });
                    lock (lockObj)
                        ToSend.Dequeue();
                    Console.WriteLine("Successfully " + dataToSend.Id.ToString());
                }
                catch (Exception ex) {
                    Console.WriteLine("Error - sleeping 3 sec before retry");
                    System.Threading.Thread.Sleep(3000);
                }
            }
            lock (lockObj)
            {
                sending = false;
            }
        }
Example #5
0
        protected void ProcessDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            String data = sp.ReadExisting();

            buffer.Append(data);

            // Only check if newline in data
            if (data.IndexOf('\n') < 0)
                return;

            Console.WriteLine(DateTime.Now.ToLongTimeString() + ": COM checking");
            String checkString = buffer.ToString();

            while (checkString.IndexOf('\n') > 0)
            {
                String indata = checkString.Substring(0, checkString.IndexOf('\n'));
                checkString = checkString.Substring(checkString.IndexOf('\n') + 1);
                buffer.Clear().Append(checkString);

                if (indata.IndexOf("M") >= 0 || indata.IndexOf("emiTag") >= 0)
                {
                    EmitData d = new EmitData();
                    foreach (String s in indata.Split('\t'))
                    {
                        if (s.Length > 0)
                        {
                            switch (s.Substring(0, 1))
                            {
                                case "N":
                                    d.Id = int.Parse(s.Substring(1));
                                    break;
                                case "W":
                                case "E":
                                    d.Time = DateTime.ParseExact(s.Substring(1), "HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture);
                                    break;
                                case "V":
                                    d.Voltage = double.Parse(s.Substring(1, 3));
                                    break;
                                case "C":
                                    d.BoxId = GetBoxId(s.Substring(1));
                                    break;
                                case "S":
                                    d.Chip = int.Parse(s.Substring(1));
                                    break;
                            }
                        }
                    }
                    EventHandler<EmitDataRecievedEventArgs> handler = DataReceived;

                    if (handler != null && d.Id > 0)
                        handler(this, new EmitDataRecievedEventArgs(d));
                }
            }
        }
Example #6
0
        public static Race LoadYear(int year, String jsonFile)
        {
            if (!System.IO.File.Exists(jsonFile))
                throw new IndexOutOfRangeException("Unsupported year");

            var json = System.IO.File.ReadAllText(jsonFile);

            var race = JsonConvert.DeserializeObject<Race>(json);

            switch (year)
            {
                case 2013:
                    (new EmitReaderLib.Builders.MySqlRaceBuilder2014("kjeringi.2013", "2013")).BuildRace(race);
                    break;
                case 2014:
                    (new EmitReaderLib.Builders.MySqlRaceBuilder2014("kjeringi.2013", "2014")).BuildRace(race);
                    break;
                case 2015:
                    (new EmitReaderLib.Builders.MySqlRaceBuilder2015("kjeringi", new List<int>(), "2015")).BuildRace(race);
                    break;
                case 2016:
                    (new EmitReaderLib.Builders.MySqlRaceBuilder2015("kjeringi.2016", Enumerable.Range(5001, 29).ToList<int>(), "2016")).BuildRace(race);
                    break;
            }

            MySqlConnection conn = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Kjeringi.Writer"].ConnectionString);
            MySqlCommand cmd = new MySqlCommand("SELECT card, location, concat(curdate(), \" \", time(time)) as time FROM LocationPasses WHERE year = " + year.ToString() + " ORDER BY time", conn);

            conn.Open();
            var data = cmd.ExecuteReader();

            while (data.Read())
            {
                EmitData d = new EmitData()
                {
                    Id = data.GetInt16("card"),
                    BoxId = data.GetInt16("location"),
                    Time = data.GetDateTime("time"),
                    Force = false
                };
                race.AddPass(d);
            }
            data.Close();
            conn.Close();

            return race;
        }
Example #7
0
        public Participant AddPass(EmitData emitdata)
        {
            if (!ParticipantByEmit.ContainsKey(emitdata.Id))
                return null;

            var participant = ParticipantByEmit[emitdata.Id];
            var timestation = TimeStations.Find(x => x.Id.Equals(emitdata.BoxId));

            //// going back in time?
            //if (participant.Passes.Count > 0 && participant.Passes.Last().Value.Time > emitdata.Time)
            //    return null;

            lock (syncRoot)
            {
                if (!participant.Passes.ContainsKey(timestation.Id))
                    participant.Passes.Add(timestation.Id, emitdata);

                DateTime startTime = participant.Passes.First().Value.Time;
                TimeSpan totalTime = (emitdata.Time - startTime);

                if (!participant.Finished && !timestation.Start)
                {
                    participant.TotalTime = totalTime.ToString(@"hh\:mm\:ss");

                    if (timestation.Progress.HasValue)
                    {
                        double ticksSoFar = (double) totalTime.Ticks;
                        double estimate = (ticksSoFar * 100.0) / timestation.Progress.Value;

                        participant.EstimatedArrival = startTime + TimeSpan.FromTicks((long)estimate);
                    }
                }

                if (timestation.Official)
                {
                    List<Result> res = new List<Result>();

                    foreach (ParticipantClass c in participant.Classes)
                    {
                        res.AddRange(
                            participant.Passes
                                .Where(p => this.TimeStations.Find(ts => ts.Id.Equals(p.Key)).Official)
                                .OrderBy(p => this.TimeStations.Find(ts => ts.Id.Equals(p.Key)).Sequence)
                                .SelectWithPrevious((prev, cur) =>
                                    new Result()
                                    {
                                        Class = c.Name,
                                        EmitId = participant.EmitID,
                                        Sequence = this.TimeStations.Find(ts => ts.Id.Equals(cur.Key)).Sequence,
                                        Location = cur.Key,
                                        IsSuper = participant.IsSuper,
                                        Startnumber = participant.Startnumber,
                                        Leg = this.TimeStations.Find(ts => ts.Id.Equals(cur.Key)).Name,
                                        ClassId = c.Id,
                                        Name = participant.IsSuper ? participant.Name : participant.TeamMembers[this.TimeStations.Find(ts => ts.Id.Equals(cur.Key)).Leg - 1],
                                        Team = participant.IsSuper ? "" : participant.Name,
                                        Time = (cur.Value.Time - prev.Value.Time).ToString(@"hh\:mm\:ss"),
                                        Ticks = (cur.Value.Time - prev.Value.Time).Ticks,
                                        Total = participant.TotalTime,
                                        Position = this.ParticipantListByClass[c.Id]
                                            .Where(p => p.Passes.ContainsKey(cur.Key))
                                            .OrderBy(p => p.Passes[cur.Key].Time)
                                            .ToList<Participant>()
                                            .IndexOf(participant) + 1

                                    }
                                        ).ToList<Result>());
                    }

                    participant._splits = res;
                }

                if (timestation.Finish)
                {
                    participant.Finished = true;
                    participant.RealArrival = emitdata.Time;
                }

                return participant;
            }
        }
Example #8
0
 public EmitDataRecievedEventArgs(EmitData data)
 {
     this.Data = data;
 }
Example #9
0
        public void Start()
        {
            MySqlConnection conn = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString);
            MySqlCommand cmd = new MySqlCommand("SELECT * FROM timers_raw WHERE year = " + Year + " AND location in (" + String.Join(",", Locations) + ") and card between " + CardStart + " AND " + CardEnd + " ORDER BY id", conn);

            Task.Factory.StartNew(() =>
            {
                try
                {
                    conn.Open();
                    MySqlDataReader data = cmd.ExecuteReader();

                    DateTime nextSleep = DateTime.Now;
                    Boolean init = false;

                    while (data.Read())
                    {
                        DateTime time;
                        if (DateTime.TryParseExact(data["time"].ToString(), "HH:mm:ss.FFF", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out time))
                        {
                            EmitData d = new EmitData()
                                {
                                    Id = int.Parse(data["card"].ToString()),
                                    BoxId = int.Parse(data["location"].ToString()),
                                    Time = time,
                                    Force = false
                                };

                            EventHandler<EmitDataRecievedEventArgs> handler = DataReceived;

                            if (handler != null)
                                handler(this, new EmitDataRecievedEventArgs(d));
                        }
                        else
                            Console.WriteLine("Unable to parse: " + data["time"].ToString());

                        System.Threading.Thread.Sleep(300);
                    }
                    data.Close();
                    conn.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to read database:" + ex.Message);
                }
                finally
                {
                    conn.Close();
                }
            });
        }
Example #10
0
        public void SendPassering(EmitData data)
        {
            (new EmitReaderLib.Writers.MySqlWriter("kjeringi.writer", TheRace.Instance.Name)).PersistPass(data);
            //try
            //{
                // Tester?
                data.Test = TheRace.Instance.Testers.Contains(data.Id);

                // Add new Passering to race
                Participant resultat = TheRace.Instance.AddPass(data);
                var timestation = TheRace.Instance.TimeStations.First(ts => ts.Id.Equals(data.BoxId));

                if (resultat != null)
                {
                    Clients.All.addLogMessage(resultat.Splits().Count > 0 ? resultat.Splits().Last().Time : "", resultat.EmitID, resultat.Startnumber, resultat.Name, resultat.EstimatedArrival.ToLongTimeString());
                    Clients.Group(timestation.Id.ToString()).newPass(resultat);
                }
                else
                {
                    Clients.All.addLogMessage("No result generated", data.Id, data.BoxId, data.Time, "");
                }
            //}
            //catch (Exception ex) {
            //    // Duplicate
            //}
        }