/**
         * Ricevi i pacchetti inviati dalle boards, e sincronizza tutte le boards sul timestamp corrente
         */
        public List <Pacchetto> receivePackets()
        {
            List <Pacchetto> packet_list = new List <Pacchetto>();

            byte[] buffer = new byte[1024];
            writeDebugLine_("In attesa di ricevere dati");

            // ricevo #pacchetti
            receiveBytes(buffer, 4);
            int packet_number = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(buffer, 0));

            writeDebugLine_("Numero di pacchetti da ricevere: " + packet_number);

            // ricevo i pacchetti
            for (int i = 0; i < packet_number; i++)
            {
                Pacchetto packet = Pacchetto.RiceviPacchetto(this);
                packet_list.Add(packet);
            }
            writeDebugLine_("Pacchetti ricevuti");

            // mi sincronizzo con le altre boards
            waitForTimeSync_();

            // invio timestamp
            int epoch         = EspServer.getUnixEpoch();
            int network_epoch = IPAddress.HostToNetworkOrder(epoch);

            socket_.Send(BitConverter.GetBytes(network_epoch), 4, SocketFlags.None);

            writeDebugLine_("Timestamp inviato: " + epoch);
            return(packet_list);
        }
Example #2
0
        public int CountLast5MinutesPhones(int nBoards, int threshold = 0)
        {
            if (nBoards < 2)
            {
                return(-1);
            }
            int    time  = EspServer.getUnixEpoch() - 300;
            string query = " SELECT COUNT(DISTINCT P1.MAC)" + VarQuery(nBoards, time, threshold);

            using (MySqlConnection connessione = new MySqlConnection("Database=" + Database + ";" + "Server=" + Server + ";" + "Port=3306;" + "UID=" + Uid + ";" + "Password="******";"))
                using (MySqlCommand cmd = connessione.CreateCommand())
                {
                    try
                    {
                        connessione.Open();
                        cmd.CommandText = query;
                        using (var dataReader = cmd.ExecuteReader())
                        {
                            Connesso = true;
                            if (dataReader.Read())
                            {
                                return(dataReader.GetInt32(0));
                            }
                            else
                            {
                                return(-1);
                            }
                        }
                    }
                    catch (MySqlException e)
                    {
                        System.Diagnostics.Debug.WriteLine("MySqlException catched." + e.ToString());
                        Connesso = false;
                        return(-100);
                    }
                }
        }
Example #3
0
        public List <string> CountHiddenPhones(DatiDispositivo p, double threshold)
        {
            int           time = EspServer.getUnixEpoch() - 60;
            List <string> list = new List <string>();

            string query = "SELECT MAC " +
                           "FROM posizioni WHERE global = 1 AND timestamp > " + time +
                           " AND ABS(x - " + p.Posizione.Ascissa.ToString(CultureInfo.InvariantCulture) + ") < " + threshold.ToString(CultureInfo.InvariantCulture) +
                           " AND ABS(y - " + p.Posizione.Ordinata.ToString(CultureInfo.InvariantCulture) + ") < " + threshold.ToString(CultureInfo.InvariantCulture) +
                           " AND MAC <> '" + p.MAC_Address + "'";

            using (MySqlConnection connessione = new MySqlConnection("Database=" + Database + ";" + "Server=" + Server + ";" + "Port=3306;" + "UID=" + Uid + ";" + "Password="******";"))
                using (MySqlCommand cmd = connessione.CreateCommand())
                {
                    try
                    {
                        connessione.Open();
                        cmd.CommandText = query;
                        using (var dataReader = cmd.ExecuteReader())
                        {
                            while (dataReader.Read())
                            {
                                list.Add(dataReader.GetString(0));
                            }
                            Connesso = true;
                            return(list);
                        }
                    }
                    catch (MySqlException e)
                    {
                        System.Diagnostics.Debug.WriteLine("MySqlException catched." + e.ToString());
                        Connesso = false;
                        return(null);
                    }
                }
        }
        /** Initializza la board
         * Client: <HI BoardID>
         * Server: <HI>
         * Client: aspetta di ricevere il timestamp
         * Server: aspetta che tutte le boards si connettano
         * Server: <GO  timestamp>
         */
        public bool initialize()
        {
            const int PROTOCOL_MESSAGE_LENGTH = 2;

            if (socket_ == null) // || !socket_.Connected)
            {
                return(false);
            }

            byte[] buffer = new byte[512 * 1024];

            // ricevo HI
            receiveBytes(buffer, PROTOCOL_MESSAGE_LENGTH);
            writeDebugLine_("Aspetto HI");
            String msg = Encoding.ASCII.GetString(buffer, 0, PROTOCOL_MESSAGE_LENGTH);

            if (msg != "HI")
            {
                writeDebugLine_("ERRORE, messaggio inaspettato: " + msg);
                socket_.Close();
                return(false);
            }

            // ricevo BoardID 4 bytes
            receiveBytes(buffer, 4);
            board_id_ = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(buffer, 0));
            writeDebugLine_("ID board ottenuto");

            // segnalo board in inizializzazione
            try
            {
                setBoardStatus_("Waiting", board_id_);
            }
            // verifica che l'IDBoard sia valido
            catch (IndexOutOfRangeException ex)
            {
                writeDebugLine_("ERRORE, IDBoard non corretto: " + board_id_);
                socket_.Close();
                return(false);
            }

            // ricevo MAC 6 bytes
            receiveBytes(buffer, 6);

            Byte[] mac_address = new Byte[6];
            Array.Copy(buffer, 0, mac_address, 0, 6);
            py_address_ = new PhysicalAddress(mac_address);
            writeDebugLine_("MAC ottenuto " + py_address_);

            // rispondo HI
            msg = "HI";
            Encoding.ASCII.GetBytes(msg, 0, PROTOCOL_MESSAGE_LENGTH, buffer, 0);
            writeDebugLine_("Invio HI");
            socket_.Send(buffer, PROTOCOL_MESSAGE_LENGTH, SocketFlags.None);

            // mi sincronizzo con tutte le altre boards
            waitForTimeSync_();

            // invia GO timestamp
            msg = "GO";
            Encoding.ASCII.GetBytes(msg, 0, PROTOCOL_MESSAGE_LENGTH, buffer, 0);
            writeDebugLine_("Invio GO");
            socket_.Send(buffer, PROTOCOL_MESSAGE_LENGTH, SocketFlags.None);
            int network_epoch = IPAddress.HostToNetworkOrder((int)EspServer.getUnixEpoch());

            socket_.Send(BitConverter.GetBytes(network_epoch), 4, SocketFlags.None);

            return(true);
        }
Example #5
0
        /// <summary>
        /// se abbiamo almeno 2 schede, ricerca nel database la tupla(Distinct) MAC,timestamp,global,hash, ID scheda i,RSSI scheda i
        /// all'interno di pacchetti in cui prendendo in considerazione dati di schede diverse riguardanti lo stesso MAC (i-esimo)
        /// la cui differenza di timestamp (tra dati diversi) sia entro una certa soglia (si riferisca alla stessa lettura) e il cui
        /// timestamp sia entro il minuto di ricerca , prese queste tuple calcola i punti di intersezione tramite i metodi dei cerchi
        /// ed infine li aggiunge ad una lista
        /// </summary>
        /// <param name="nBoards">numero di schede presenti</param>
        /// <param name="threshold">soglia del timestamp tra dati diversi</param>
        /// <returns>lista di punti di intersezione</returns>
        public List <DatiDispositivo> GetLastMinuteData(int nBoards, int threshold = 0)
        {
            try
            {
                if (nBoards < 2)
                {
                    return(null);
                }

                int time = EspServer.getUnixEpoch() - 60;

                //Create a list to store the result
                List <DatiDispositivo> list = new List <DatiDispositivo>();

                using (MySqlConnection connessione = new MySqlConnection("Database=" + Database + ";" + "Server=" + Server + ";" + "Port=3306;" + "UID=" + Uid + ";" + "Password="******";"))
                    using (MySqlCommand cmd = connessione.CreateCommand())
                    {
                        connessione.Open();
                        //Create Query
                        StringBuilder builder = new StringBuilder();
                        builder.Append("SELECT DISTINCT P1.MAC, P1.timestamp, P1.global, P1.hash");

                        for (int i = 0; i < nBoards; i++)
                        {
                            builder.Append(", P").Append(i + 1).Append(".ID_scheda, P").Append(i + 1).Append(".RSSI");
                        }

                        builder.Append(VarQuery(nBoards, time, threshold));

                        //Create Command
                        cmd.CommandText = builder.ToString();
                        cmd.ExecuteNonQuery();
                        using (MySqlDataReader dataReader = cmd.ExecuteReader())
                        {
                            while (dataReader.Read())
                            {
                                string mac       = dataReader.GetString(0);
                                int    timestamp = dataReader.GetInt32(1);
                                bool   global    = dataReader.GetBoolean(2);

                                List <Cerchio> cerchi = new List <Cerchio>();
                                for (int i = 0; i < nBoards; i++)
                                {
                                    int id   = dataReader.GetInt32(4 + i * 2);
                                    int rssi = dataReader.GetInt32(5 + i * 2);

                                    cerchi.Add(new Cerchio(GetScheda(id).Punto, rssi));
                                }
                                Punto point = Cerchio.Intersezione(cerchi);
                                if (!(Double.IsNaN(point.Ascissa) || Double.IsNaN(point.Ordinata)))
                                {
                                    if (point.isInside(schede))
                                    {
                                        DatiDispositivo p = new DatiDispositivo(mac, timestamp, point, global);
                                        list.Add(p);
                                    }
                                    else
                                    {
                                        System.Diagnostics.Debug.WriteLine("Geofence discarded: (" + point.Ascissa + "; " + point.Ordinata + ")");
                                    }
                                }
                            }
                        }

                        InserisciPosizioni(list, connessione);
                    }
                Connesso = true;
                return(list);
            }
            catch (KeyNotFoundException e)
            {
                System.Diagnostics.Debug.WriteLine("idBoard not found..." + e.ToString());
                throw e;
            }
            catch (MySqlException e)
            {
                System.Diagnostics.Debug.WriteLine("MySqlException catched." + e.ToString());
                Connesso = false;
                return(null);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Caught exception: " + e.ToString());
                return(null);
            }
        }