Ejemplo n.º 1
0
        /*Fucnión que genera un paquete de agregación para que los demás vehículos firmen si están
         * de acuerto con la información*/
        public void EnviaNuevoPaqueteAgregacion()
        {
            string IP = IPAddress.Broadcast.ToString();
            Cripto criputiles = new Cripto(Formulario);
            //Se obtiene el pseudónim
            BD AccesoBD = new BD(Formulario);
            string pseudonym = AccesoBD.recuperamyPseu();

            Cliente Client = new Cliente(Formulario, "9050");
            string prueba = "I_Traffic Jam_" + NombreVia + "_" + SentidoMarcha + "_" + CoodX.ToString() + "_" + CoordY.ToString() + "_" + CoordZ.ToString() + "_" + HoraGeneracionPaquete.ToString("MM/dd/yyyy HH:mm:ss");
            // Client.respuesta("T1", pseudonym,prueba, IP);
            Formulario.Invoke(Formulario.myDelegate, new Object[] { "Se envía el paquete" });
            Client.respuesta("T1", pseudonym, criputiles.Encrypt(prueba, AccesoBD.recuperamySK()), IP);
        }
Ejemplo n.º 2
0
        /*Función que devuelve el resultado de firmar un mensaje si estamos de acuerdo con la información*/
        public void InformacionAggreacion(string msje, string IP)
        {
            //OBTIENE HORA ACTUAL
            //DateTime myDateTime = DateTime.Now;
            //ACCESO A LA BD
            string hash, viaSentido;
            BD AccesoBD = new BD(Formulario);
            string evento, posibleevento;
            Cripto criputiles = new Cripto(Formulario);
            DetectaIncidente incidente = new DetectaIncidente(Formulario);
            //Se comprueba si ya existe el incidente en las coordenadas X,Y aprox.
            evento = AccesoBD.ExisteEvento("T1", NombreVia, SentidoMarcha, CoodX, CoordY);

            Formulario.Invoke(Formulario.myDelegate, new Object[] { "¿Tengo el evento en BD? " });
            if (evento.Equals(""))
            {

                Formulario.Invoke(Formulario.myDelegate, new Object[] { "El evento no lo tengo en BD" });

                //SE VA A COMPROBAR SI SE PUEDE SER TESTIGO DE ESTE EVENTO

                //1º Obtenemos el la vía y el sentido de circulación de nuestr vehículo
                viaSentido = incidente.ViaSentidoMarcha();
                string via = "";
                string sentido = "";
                if (!viaSentido.Equals(""))
                {
                    string[] viaSentidoAux = viaSentido.Split('|');
                    via = viaSentidoAux[0];
                    sentido = viaSentidoAux[1];
                }

                //2º Si la información está dentro de mi Rango, y circulo por esa vía yo puedo detectar el problema
                if (EnRango(CoodX, CoordY, via, sentido))
                {
                    Formulario.Invoke(Formulario.myDelegate, new Object[] { "La información está dentro de mi rango" });
                    //3º Si estoy dentro del rango compruebo si detecto el problema
                    if (incidente.CompruebaIncidente())
                    {
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Yo también detecto el incidente" });

                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "¿Tengo el posible evento en PosibleEvento? " });
                        posibleevento = AccesoBD.ExistePosibleEvento("T1", NombreVia, SentidoMarcha, CoodX, CoordY);
                        if (posibleevento.Equals(""))
                        {
                            Formulario.Invoke(Formulario.myDelegate, new Object[] { "NO" });
                            Formulario.Invoke(Formulario.myDelegate, new Object[] { "Inserto PosibleEvento en BD " });
                            //Se inserta el incidente en posible Evento BD
                            AccesoBD.insertarPosibleEvento("T1", NombreVia, SentidoMarcha, CoodX, CoordY, CoordZ, HoraGeneracionPaquete, "");
                        }
                        //Firmo el paquete
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "The packet is to be signed because I can detect the incident" });
                        //Firmo la información
                        hash = FirmarMsje(msje, Server.myPseudonimo);
                        //Busco my pseudónimo
                        string myPseudonimo = AccesoBD.recuperamyPseu();
                        //Mando el mensaje  con  la Firma
                        //Nota hay que agregar el hash
                        Cliente Client = new Cliente(Formulario, "9050");
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Send a signed packet" });
                        //Client.respuesta("T1", myPseudonimo, "F_Traffic Jam_" + NombreVia + "_" + SentidoMarcha + "_" + Server.myPseudonimo + "_" + hash + "_" + CoodX + "_" + CoordY + "_" + CoordZ, IP);
                        Client.respuesta("T1", myPseudonimo, criputiles.Encrypt("F_Traffic Jam_" + NombreVia + "_" + SentidoMarcha + "_" + Server.myPseudonimo + "_" + hash + "_" + CoodX + "_" + CoordY + "_" + CoordZ, AccesoBD.recuperamySK()), IP);

                    }//EnIF CompruebaIncidente
                    //se trata de un ataque
                    else
                    {
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Intento de Ataque" });
                    }
                }//EndIF EnRango
                //No estoy en rango por lo que no puedo comprobar la información
                else
                {
                    Formulario.Invoke(Formulario.myDelegate, new Object[] { "La información no está en  mi rango" });
                }
            }//EndIF ExisteEvento
            //Si tengo el evento en la BD o bien yo lo detecté y envié un msje para ser firmado o ya lo firmé y recibí el agregado
            else
            {
                Formulario.Invoke(Formulario.myDelegate, new Object[] { "El evento no es nuevo, ya existe en BD" });
                /*Si estoy esperando firmas que que ya mandé el paquete agregado, */
                if (AggregarFirmas.getEsperoFirmas())
                {
                    Formulario.Invoke(Formulario.myDelegate, new Object[] { "Tambien tengo este evento en mi BD y espero firmas" });
                    // si mi evento es más antiguo que el que me llega noo
                    string[] info = evento.Split('|');
                    //Si el mio es más antiguo me quedo con el mio
                    if (DateTime.Parse(info[2]).CompareTo(HoraGeneracionPaquete) < 0)
                    {
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "La fecha en que yo creé el evento" + info[2] });
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "La fecha del evento en el paquete" + HoraGeneracionPaquete });
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Mi evento se creó antes" });

                    }
                    //Sino, tengo que modificar el mio y quedarme con este
                    else
                    {
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Mi evento es más viejo, lo borro de BD" });
                        //Ya no se queda a la espera de ninguna firma
                        AggregarFirmas.resetEsperoFirmas();
                        //eliminamos el evento existente
                        AccesoBD.EliminaEvento("T1", HoraGeneracionPaquete);
                        //Agregamos el nuevo evento y lo mandamos firmado
                        InformacionAggreacion(msje, IP);

                    }

                }//EndIF esperoFirmas
                //Si no espero firmas es que ya firmé
                else
                {
                    Formulario.Invoke(Formulario.myDelegate, new Object[] { "Incident already dealt" });
                }

            }
        }
Ejemplo n.º 3
0
        private void autenticar(string myString, string clientIPAddress, string[] datosConexion)
        {
            string auxiliar;
            Cliente myCliente = new Cliente(Formulario, "9050");
            Random randomNumber = new Random(DateTime.Now.Second);

            if ((datosConexion[0].Equals(secuencia) && autenticando.Equals(datosConexion[1]) ||
                ((datosConexion[0].Equals("D2") || datosConexion[0].Equals("D1") || datosConexion[0].Equals("01")) && autenticando.Equals("00"))))//  CONTROL DE SECUENCIA(solo funciona si se autentica 1 a la vez)
                switch (datosConexion[0])
                {
                    case "01"://RECIBE BEACON, ENVIA INICIO DE AUTENTICACIÓN
                        // if(){//COMPROBAR QUE TODAVIA NO ME HE AUTENTICADO
                        segundos = DateTime.Now.Second;
                        enviado = "D1";
                        secuencia = "D2";
                        //String IDs = DButiles.recuperaIDs();
                        string HashIDs = Criptutiles.generaHash(DButiles.recuperaIDs());//IDs);
                        myCliente.respuesta("D1", myPseudonimo, HashIDs, clientIPAddress);
                        // comprobarReenvio("D1", myPseudonimo, HashIDs, clientIPAddress);
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "D1: Beacon, Send Authentication" });
                        break;
                    //}
                    case "D1"://PIDE IDs DE ALMACEN(B)
                        enviado = "D2";
                        secuencia = "D3";
                        autenticando = datosConexion[1];
                        hashaComprobar = datosConexion[2];

                        string datos = "-";
                        myCliente.respuesta("D2", myPseudonimo, datos,clientIPAddress);//"-", clientIPAddress);
                        comprobarReenvio("D2", myPseudonimo, datos, clientIPAddress);//"-", clientIPAddress);
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "D2: Send request" });
                        break;

                    case "D2"://ENVIA IDs DE ALMACEN
                        enviado = "D3";
                        secuencia = "D4";

                        autenticando = datosConexion[1];
                        auxiliar = DButiles.recuperaIDs();
                        myCliente.respuesta("D3", myPseudonimo, auxiliar, clientIPAddress);
                        comprobarReenvio("D3", myPseudonimo, auxiliar, clientIPAddress);
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "D3: Send IDs of the Keystore" });
                        break;

                    case "D3"://COMPRUEBA IDs, ENVIA NODO COMÚN(X)
                        enviado = "D4";
                        secuencia = "D5";
                        autenticando = datosConexion[1];
                        //comprobar hash coincide con hash(IDs),
                        string comprueba = Criptutiles.generaHash(datosConexion[2]);
                        if (comprueba.Equals(hashaComprobar))
                        {
                            //X=Comprobar ID comun,
                            string[] idAlmacenA = DButiles.recuperaIDs().Split(';');//adelantado a D1
                            string[] idAlmacenB = datosConexion[2].Split(';');
                            elementoComun = "0";
                            for (int i = 0; i < idAlmacenB.Length; i++)
                            {//Buscamos el elemento comun entre dos almacenes
                                for (int j = 0; j < idAlmacenA.Length; j++)
                                {
                                    if (string.Equals(idAlmacenA[j], idAlmacenB[i]))
                                    {
                                        elementoComun = idAlmacenA[j];
                                        i = idAlmacenB.Length;
                                        j = idAlmacenA.Length;
                                    }
                                }
                            }
                            if (!string.Equals("0", elementoComun))//)(string.Equals(comprueba, hashaComprobar)
                            {
                                myCliente.respuesta("D4", myPseudonimo, elementoComun, clientIPAddress);//X
                                comprobarReenvio("D4", myPseudonimo, elementoComun, clientIPAddress);//
                                Formulario.Invoke(Formulario.myDelegate, new Object[] { "D4: OK, Send IDs common Node(X)" });
                            }
                            else
                            {
                                Formulario.Invoke(Formulario.myDelegate, new Object[] { "D4: Error: Not common X" });
                                autenticando = "00";
                                secuencia = "01";
                            }
                        }
                        else
                        {
                            Formulario.Invoke(Formulario.myDelegate, new Object[] { "D4: Error: Diferent Hash " });
                            autenticando = "00";
                            secuencia = "01";
                        }
                        break;

                    case "D4"://ENVIA (GRAFO + GRAFO_ISOMORFO)
                        enviado = "D5";
                        secuencia = "Z2";
                        elementoComun = datosConexion[2];
                        grafoGenerado = Criptutiles.generaGrafoAleatorio(datosConexion[2], DButiles.recuperaClavePublica(elementoComun));
                        grafoIsomorfoGenerado = Criptutiles.generaGrafoIsomorfo(grafoGenerado);
                        //RECUPERAR CLAVE PUBLICA Y PASAR DE NUMERO A Bits.
                        //string grafo= generaGrafo(recuperaPublicExponente(elementoComun);
                        //string grafoIsomorfo = generaIsomorfo(grafo);
                        auxiliar = grafoGenerado + ";" + grafoIsomorfoGenerado;
                        myCliente.respuesta("D5", myPseudonimo, auxiliar, clientIPAddress);//envio D5 y Z1 en el mismo paquete
                        comprobarReenvio("D5", myPseudonimo, auxiliar, clientIPAddress);
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "D5&Z1: Send Graph of KUx & Isomorphic" });
                        grafoIsomorfoGenerado = Criptutiles.generaGrafoIsomorfo(grafoGenerado);//GENERA NUEVO GRAFO ISOMORFO adelantado de Z2
                        break;

                    case "D5"://&&Z1 ENVIA PREGUNTA ALEATORIA
                        enviado = "Z2";
                        secuencia = "Z3";
                        //recibe grafo y isomorfo ;envia pregunta 1 (equivalencia entre grafo y grafo isomorfo (0) o circuito hamiltoniano del isomorfismo(1))
                        string[] grafos = datosConexion[2].Split(';');
                        grafo = grafos[0];//.ToString();
                        grafoIsomorfo = grafos[1];//.ToString();
                        pregunta = "1";// randomNumber.Next(2).ToString();
                        myCliente.respuesta("Z2", myPseudonimo, pregunta, clientIPAddress); //Pregunta
                        comprobarReenvio("Z2", myPseudonimo, pregunta, clientIPAddress);
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Z2:Send Question 1" });
                        break;

                    //SE PUEDE PONER UN FOR PARA HACER VARIAS ITERACIONES
                    case "Z2"://ENVIA RESPUESTA + NUEVO_GRAFO_ISOMORFO
                        enviado = "Z3";
                        secuencia = "Z4";
                        // Genera Respuesta
                        // grafoIsomorfoGenerado = generaGrafoIsomorfo(grafoGenerado);//GENERA NUEVO GRAFO ISOMORFO
                        string respuesta = "";
                        if (datosConexion[2].Equals("0")) //equivalencia entre grafo y grafo isomorfo (0)(PRECALCULAR RESPUESTAS??)
                        {
                            for (int i = 0; i < listaaleatoria.Length; i++)
                            {
                                if (i == 0)
                                    respuesta = listaaleatoria[i].ToString();
                                else
                                    respuesta = respuesta + ":" + listaaleatoria[i].ToString();
                            }
                            respuesta = respuesta + ";" + grafoIsomorfoGenerado;
                        }
                        else if (datosConexion[2].Equals("1"))//circuito hamiltoniano del isomorfismo(1)
                        {
                            respuesta = Criptutiles.generaCHdeIsomorfo() + ";" + grafoIsomorfoGenerado;
                        }
                        else
                            respuesta = "0";
                        myCliente.respuesta("Z3", myPseudonimo, respuesta, clientIPAddress);//Respuesta1, Grafoisomorfo(X)
                        comprobarReenvio("Z3", myPseudonimo, respuesta, clientIPAddress);
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Z3: Send Answer 1 + Isomorphic2" });

                        //misDatosCifrados1=Criptutiles.Encrypt(DButiles.recuperaMisDatosPublicos());//adelantado para Z4
                        break;

                    case "Z3"://COMPRUEBA RESPUESTA Y RECIBO GRAFO_ISOMORFO PARA SIGUIENTE PREGUNTA
                        enviado = "Z4";
                        secuencia = "E1";
                        bool comprobacion = false;
                        string[] aux = datosConexion[2].Split(';');
                        if (pregunta.Equals("0"))//equivalencia entre grafo y grafo isomorfo (0)
                            // if (datosConexion[1])//permutar el grafo isomorfo y comprobar si es igual al grafo.
                            comprobacion = Criptutiles.compruebaIsomorfismo(aux[0], grafo, grafoIsomorfo);
                        /*if (compruebaIsomorfismo(datosConexion[1], grafo, grafoIsomorfo))
                            comprobacion = true;
                        else
                            comprobacion = false;*/
                        else if (pregunta.Equals("1"))//circuito hamiltoniano del isomorfismo(1)
                            comprobacion = Criptutiles.esCH(aux[0], grafoIsomorfo);//CH del isomorfo

                        grafoIsomorfo = aux[1];//cargo el nuevo grafo isomorfo
                        if (comprobacion)
                        {
                            pregunta = (randomNumber.Next(2) % 1).ToString();  //genero nueva pregunta
                            //Comprueba Respuesta1
                            myCliente.respuesta("Z4", myPseudonimo, pregunta, clientIPAddress);
                            comprobarReenvio("Z4", myPseudonimo, pregunta, clientIPAddress);
                            Formulario.Invoke(Formulario.myDelegate, new Object[] { "Z4: Checked-Send Question 2" });
                        }
                        else
                        {
                            Formulario.Invoke(Formulario.myDelegate, new Object[] { "Z3: Answer is Not correct" });
                            autenticando = "00";
                            secuencia = "01";
                        }
                        //misDatosCifrados2 = Criptutiles.Encrypt(DButiles.recuperaMisDatosPublicos());//adelantado para E1
                        break;

                    case "Z4"://GENERA RESPUESTA SOBRE EL NUEVO GRAFO ISOMORFO,
                        //EN EL ULTIMO ENVIO DE Zs SE ENVIA ID, CLAVE PUBLICA Y SECRETA DE A CIFRADA CON X = Ex(IDa,KUa,Ka)
                        enviado = "E1";
                        secuencia = "E2";
                        // Genera Respuesta
                        if (datosConexion[2].Equals("0"))//(PRECALCULAR RESPUESTAS??)
                        {
                            respuesta = "";
                            for (int i = 0; i < listaaleatoria.Length; i++)
                            {
                                if (i == 0)
                                    respuesta = listaaleatoria[i].ToString();
                                else
                                    respuesta = respuesta + ":" + listaaleatoria[i].ToString();
                            }
                        }
                        else if (datosConexion[2].Equals("1"))
                        {
                            respuesta = Criptutiles.generaCHdeIsomorfo();
                        }
                        else
                            respuesta = "0";

                        //busco en bd personal los datos a enviar
                        //EL ENCRYPT DEBE CAMBIARSE POR NUESTRO ENCRYPT Y DEBE TENER LA CLAVE COMO PARAMETRO (KUx)
                        //CIFRADO CON clavePublicaComun
                        auxiliar = respuesta + ";" + Criptutiles.Encrypt(DButiles.recuperaMisDatosPublicos(), ""+DButiles.recuperaClavePublica(elementoComun));// Encrypt("IDa,KUa,Ka");
                        myCliente.respuesta("E1", myPseudonimo, auxiliar, clientIPAddress);//cifradoSimetrico("IDentificador"));
                        comprobarReenvio("E1", myPseudonimo, auxiliar, clientIPAddress);
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "E1: Send Answer 2, Ex(IDa,KUa,Ka)" });
                        //almacenCifrado1 = Criptutiles.Encrypt(DButiles.recuperaKeyStore());//adelantado de E2
                        break;

                    case "E1"://COMPRUEBA ULTIMA PREGUNTA, DESCIFRA Ex(IDa,KUa,Ka) Y ENVIA CIFRADO CON Ka
                        enviado = "E2";
                        secuencia = "E3";
                        //comprobar respuesta y si es buena enviar datos
                        string[] aux2 = datosConexion[2].Split(';');
                        bool comprobacion2 = false;
                        if (pregunta.Equals("0"))//equivalencia entre grafo y grafo isomorfo (0)
                            comprobacion2 = Criptutiles.compruebaIsomorfismo(aux2[0], grafo, grafoIsomorfo);
                        else if (pregunta.Equals("1"))//circuito hamiltoniano del isomorfismo(1)
                            comprobacion2 = Criptutiles.esCH(aux2[0], grafoIsomorfo);//CH del isomorfo

                        if (comprobacion2)
                        {   //DESCIFRAR DATOS

                            string datosDescifrados = Criptutiles.Decrypt(aux2[1], ""+DButiles.recuperaClavePublica(elementoComun));//DESCIFRAR CON clavePublicaComun
                            //aux=datosDescifrados.Split(',');
                            DButiles.addUser(datosDescifrados);//AÑADE O ACTUALIZA USUARIO EN LA BD
                            auxiliar = Criptutiles.Encrypt(DButiles.recuperaMisDatosPublicos(), ""+DButiles.recuperaClavePublica(elementoComun));//CIFRAR CON Kb
                            myCliente.respuesta("E2", myPseudonimo, auxiliar, clientIPAddress);//misDatosCifrados2);//, "Pas5pr@se", "s@1tValue", "SHA1", 2, "@1B2c3D4e5F6g7H8", 256));
                            comprobarReenvio("E2", myPseudonimo, auxiliar, clientIPAddress);
                            Formulario.Invoke(Formulario.myDelegate, new Object[] { "E2: Send Eka(IDb, Pseub,Modb, KUb,Kb);Decrypt: " + datosDescifrados });//, "Pas5pr@se", "s@1tValue", "SHA1", 2, "@1B2c3D4e5F6g7H8",256) });
                        }
                        else
                        {
                            Formulario.Invoke(Formulario.myDelegate, new Object[] { "E1:It is Not correct" });
                            autenticando = "00";
                            secuencia = "01";
                        }
                        //almacenCifrado2 = Criptutiles.Encrypt(DButiles.recuperaKeyStore());
                        break;

                    case "E2"://DESCIFRO Eka(IDb,KUb,Kb) Y ENVIO CIFRADO EL ALMACEN (Ekb(KeyStoreB))
                        enviado = "E3";
                        secuencia = "E4";

                        string datosDescifrados2 = Criptutiles.Decrypt(datosConexion[2], ""+DButiles.recuperaClavePublica(elementoComun));//DESCIFRAR CON clave secreta de A
                        DButiles.addUser(datosDescifrados2);
                        auxiliar = Criptutiles.Encrypt(DButiles.recuperaKeyStore(), DButiles.recuperamySK());//"KeystoreB");

                        myCliente.respuesta("E3", myPseudonimo, auxiliar, clientIPAddress);// almacenCifrado1);
                        comprobarReenvio("E3", myPseudonimo, auxiliar, clientIPAddress);
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "E3: Send Ekb(KeystoreB),Decrypt: " + datosDescifrados2 });//, "Pas5pr@se", "s@1tValue", "SHA1", 2, "@1B2c3D4e5F6g7H8", 256) });
                        break;

                    case "E3"://ENVIO CIFRADO ALMACEN A, DESCIFRO ALMACEN B Y AÑADO A REPOSITORIO LO QUE INTERESE.

                        string almacenA = Criptutiles.Decrypt(datosConexion[2], DButiles.recuperaSK(autenticando));
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Decrypt Receive: " + almacenA });//,"Pas5pr@se", "s@1tValue", "SHA1", 2, "@1B2c3D4e5F6g7H8", 256) });//"Send Eka(KeystoreA)"
                        //LEER KEYSTORE Y AÑADIR EN REPOSITORIO
                        auxiliar = Criptutiles.Encrypt(DButiles.recuperaKeyStore(), DButiles.recuperamySK());//"KeystoreA");//adelantado en E1
                        myCliente.respuesta("E4", myPseudonimo, auxiliar, clientIPAddress);//almacenCifrado2);
                        comprobarReenvio("E4", myPseudonimo, auxiliar, clientIPAddress);
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "E4: Sending Ea(Keystore)" });
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Updating DB with Max Degree. Add: " + DButiles.actualizaDB(almacenA) });
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { datosConexion[1] + "- Authenticated" });
                        enviado = "E4";
                        secuencia = "E5";

                        break;

                    case "E4"://DESCIFRO ALMACEN A Y AÑADO A REPOSITORIO LO QUE INTERESE.
                        string almacenB = Criptutiles.Decrypt(datosConexion[2],DButiles.recuperaSK(autenticando));
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Decrypt Receive: " + almacenB });//,"Pas5pr@se", "s@1tValue", "SHA1", 2, "@1B2c3D4e5F6g7H8", 256) });//"Send Eka(KeystoreA)"
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Updating DB with Max Degree " });
                        DButiles.marcarAutenticado(datosConexion[1]);
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Added to DB: " + DButiles.actualizaDB(almacenB) });
                        myCliente.respuesta("E5", myPseudonimo, "-", clientIPAddress);
                       // comprobarReenvio("E5", myPseudonimo, "-", clientIPAddress);
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "E5: sending" });

                        if (segundos < DateTime.Now.Second)
                            segundos = DateTime.Now.Second - segundos;
                        else
                            segundos = DateTime.Now.Second + 60 - segundos;
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { datosConexion[1] + "- Authenticated. Seconds: " + segundos });
                        secuencia = "01";
                        enviado = "00";
                        autenticando = "00";

                        enviarEventos(myPseudonimo, clientIPAddress);//enviar eventos actuales

                        break;
                    case "E5"://DESCIFRO ALMACEN A Y AÑADO A REPOSITORIO LO QUE INTERESE.
                        DButiles.marcarAutenticado(datosConexion[1]);

                        enviarEventos(myPseudonimo, clientIPAddress); //Enviar eventos actuales

                        secuencia = "01";
                        enviado = "00";
                        autenticando = "00";
                        break;
                    default:
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Bad FC" });
                        break;
                }
        }
Ejemplo n.º 4
0
        public void posibleparking()
        {
            SError err;
            SGpsPosition gps;
            string hostName = Dns.GetHostName();
            IPHostEntry thisHost = Dns.GetHostEntry(hostName);
            string thisIpAddr = thisHost.AddressList[0].ToString();
            Cliente mycliente = new Cliente(Formulario, "9050");
            DateTime inicio = DateTime.Now.AddSeconds(10.00);//si en menos de X segundos detecta la señal gps avisa de posible aparcamiento
            string auxiliar, via, sentido;
            Cripto criputiles = new Cripto(Formulario);
            BD DButiles = new BD(Formulario);

            while (DateTime.Compare(DateTime.Now, inicio) < 0)
            {
                try
                {
                    if (CApplicationAPI.GetActualGpsPosition(out err, out gps, false, 1000) == 1)
                    {
                        LONGPOSITION position = new LONGPOSITION(gps.Longitude, gps.Latitude);
                        sentido = ObtenerSentidoMarcha(gps.Course);
                        CApplicationAPI.GetLocationInfo(out err, position, out via, 0);

                        int CoorX = gps.Longitude;
                        int CoorY = gps.Latitude;
                        int CoorZ = gps.Altitude;
                        //string viaOnombre = "calle";
                        //string sentido = "sentido";
                        DateTime fechaDato = DateTime.Now;
                        string datoAparcamiento = via + ";" + sentido + ";" + CoorX + ";" + CoorY + ";" + CoorZ + ";" + fechaDato;//Estos datos los coge de un fichero
                        string firma = criputiles.RSAfirma(datoAparcamiento);

                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Possible parking in: " + CoorX + "," + CoorY });
                        auxiliar = criputiles.Encrypt(datoAparcamiento+";"+firma, DButiles.recuperamySK());
                        mycliente.respuesta("P2", Server.myPseudonimo,auxiliar , thisIpAddr);
                        DButiles.insertarEvento("P2", via, sentido, CoorX, CoorY, CoorZ, fechaDato, firma);

                        break;
                    }
                }
                catch { }
                Thread.Sleep(1000);
            }
        }
Ejemplo n.º 5
0
        private void gestionaPaqueteAutenticado(string myString, string clientIPAddress, string[] datosConexion)
        {
            Cliente myCliente = new Cliente(Formulario, "9050");
            string[] coordenadas;
            //string dirimconges;
            //int IDbitmap;
            //SError err;
            BD AccesoBD= new BD(Formulario);

            /*******************************
                Para agregacion
             *******************************/
            string msje, tipo,nombreVia,sentidoMarcha;
            double X = 0.0, Y = 0.0,Z=0.0;
            string[] info;

            switch (datosConexion[0])
            {
                case "D1"://el nodo ha perdido el cambio de beacon
                   string msj = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ",00," + Server.myPseudonimo + ", Ek1(00:TimeStamp:newPseu)";
                   myCliente.respuesta("01", viejoPseu, msj, clientIPAddress);
                    break;
                case "T1"://paquete de tráfico, comprobamos validez
                    datosConexion[2] = Criptutiles.Decrypt(datosConexion[2], DButiles.recuperaSK(datosConexion[1]));
                    coordenadas = datosConexion[2].Split(';');

                    lock (this)
                    {

                        info = datosConexion[2].Split('_');
                        tipo = info[0];

                        //Si es un mensaje de aggregación
                        if (tipo.Equals("I"))
                        {
                            Formulario.Invoke(Formulario.myDelegate, new Object[] { "An information packet arrives" });

                            msje = info[1];
                            nombreVia = info[2];
                            sentidoMarcha = info[3];
                            X = double.Parse(info[4]);
                            Y = double.Parse(info[5]);
                            Z = double.Parse(info[6]);
                            Formulario.Invoke(Formulario.myDelegate, new Object[] { msje + " in " + nombreVia + "direction " + sentidoMarcha + X + ", " + Y });
                            System.Globalization.CultureInfo myCIintl = new System.Globalization.CultureInfo("es-ES", false);
                            agregacion PaqAg = new agregacion(Formulario, nombreVia, sentidoMarcha, X, Y, Z, DateTime.ParseExact(info[7], "MM/dd/yyyy HH:mm:ss", myCIintl));
                            PaqAg.InformacionAggreacion(msje, clientIPAddress);
                        }
                        //Si es una respuesta de aggregación

                        //Formato del paquete|F-Atasco en la M40-ID-hash.ToString|
                        if (tipo.Equals("F"))
                        {
                            Formulario.Invoke(Formulario.myDelegate, new Object[] { "LLega un paquete F" });
                            Formulario.Invoke(Formulario.myDelegate, new Object[] { "Compruebo si estoy a la espera de firmas" });
                            if (AggregarFirmas.getEsperoFirmas())
                            {
                                //Formamos el paquete con la información que nos va llegando de los diferentes vehículos
                                //string IDPaquete=info[1];
                                msje = info[1];
                                nombreVia = info[2];
                                sentidoMarcha = info[3];
                                string IDVehículo = info[4];
                                string firma = info[5];
                                string data = "A signed packet arrives from " + IDVehículo.ToString();
                                Formulario.Invoke(Formulario.myDelegate, new Object[] { data });
                                X = double.Parse(info[6]);
                                Y = double.Parse(info[7]);
                                Z = double.Parse(info[8]);
                                DateTime myDateTime = DateTime.Now;
                                string posiblevento;

                                posiblevento = AccesoBD.ExistePosibleEvento("T1", nombreVia, sentidoMarcha, X, Y);
                                Formulario.Invoke(Formulario.myDelegate, new Object[] { "¿Existe el posible Evento?" });
                                if (!(posiblevento.Equals("") && posiblevento.Equals("error")))
                                {
                                    Formulario.Invoke(Formulario.myDelegate, new Object[] { "SI" });
                                    Formulario.Invoke(Formulario.myDelegate, new Object[] { "LO esperaba" });
                                    if (AggregarFirmas.getnumerofirmas() <= 0)
                                    {
                                        string IP = IPAddress.Broadcast.ToString();
                                        string firmas = AggregarFirmas.getfirmas();
                                        AggregarFirmas.agregafirmas(firmas + firma + "|" + IDVehículo);
                                        AggregarFirmas.incrementarfirmas();
                                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "AgregoFirma con id VEhículo, Lo inserto en BD" });
                                        AccesoBD.insertarEvento("T1", nombreVia, sentidoMarcha, X, Y, Z, myDateTime, firma);
                                        //utiles.anadePoi("Atasco", "Atasco", (int)(X*100000), (int)(Y*100000), 100);
                                        utiles.anadePoi("Atasco", "Atasco", (int)(X), (int)(Y), 100);
                                        Cliente Client = new Cliente(Formulario, "9050");
                                        string prueba = "A_Traffic Jam." + AggregarFirmas.getfirmas() + "_" + nombreVia + "_" + sentidoMarcha + "_" + X.ToString() + "_" + Y.ToString() + "_" + Z.ToString() + "_" + myDateTime.ToString("MM/dd/yyyy HH:mm:ss");
                                        Client.respuesta("T1", myPseudonimo, Criptutiles.Encrypt(prueba, AccesoBD.recuperamySK()), IP);
                                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Send an aggregation Packet" });
                                        AggregarFirmas.resetEsperoFirmas();
                                    }
                                }
                            }
                            else
                            {
                                Formulario.Invoke(Formulario.myDelegate, new Object[] { "No espero paquete F, no hago nada" });
                            }
                        }//end IF F
                        if (tipo.Equals("A"))
                        {
                            Formulario.Invoke(Formulario.myDelegate, new Object[] { "An agregation packet arrives" });

                            msje = info[1];
                            nombreVia = info[2];
                            sentidoMarcha = info[3];
                            X = double.Parse(info[4]);
                            Y = double.Parse(info[5]);
                            Z = double.Parse(info[6]);
                            System.Globalization.CultureInfo myCIintl = new System.Globalization.CultureInfo("es-ES", false);
                            agregacion PaqAg = new agregacion(Formulario, nombreVia, sentidoMarcha, X, Y, Z, DateTime.ParseExact(info[7], "MM/dd/yyyy HH:mm:ss", myCIintl));
                            PaqAg.MensajeAgregado(msje);
                        }//end IF A
                    }//end lock

                    break;

                case "P1"://paquete de publicidad, oomprobamos validez e insertamos en el mapa en caso de ser válido
                    //COMPROBANDO FIRMA CIFRADA (CLAVE PUBLICA)
                    string datosDescifrados=Criptutiles.RSAverifica(datosConexion[1], datosConexion[2], true);
                    if (datosDescifrados.Equals(""))
                   // if (!RSA3.VerifyData(decryptedData, "SHA1", signedData))// (dataToEncrypt, "SHA1", signedData);
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Advertisement Data not Correct" });
                    else
                    {
                        //Formulario.Invoke(Formulario.myDelegate, new Object[] { "Advertisement Data Correct" });
                        //datosConexion[2] = Criptutiles.Decrypt(datosConexion[2], DButiles.recuperaSK(datosConexion[1]));
                        coordenadas = datosDescifrados.Split(';');

                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Advertisement: " + coordenadas[0]+" in "+ coordenadas[2] + "," + coordenadas[3] });
                        DButiles.insertarEvento("P1", coordenadas[0], coordenadas[1], double.Parse(coordenadas[2]), double.Parse(coordenadas[3]), double.Parse(coordenadas[4]), DateTime.Parse(coordenadas[5]), coordenadas[coordenadas.Length-1]);
                        utiles.anadePoi("El Corte Ingles","Comercio", int.Parse(coordenadas[2]), int.Parse(coordenadas[3]), 100);
                       /* try
                        {
                            int res = CApplicationAPI.DeletePoiCategory(out err, coordenadas[0], "ESP", 1000);
                            string dirImagen = @coordenadas[0]+".bmp";
                            res = CApplicationAPI.AddPoiCategory(out err, coordenadas[3],dirImagen, "ESP", 1000);
                            LONGPOSITION position = new LONGPOSITION(int.Parse(coordenadas[2]), int.Parse(coordenadas[3]));//X, Y);
                            SPoi poi = new SPoi(position, "Comercio", coordenadas[0], 1000);
                            res = CApplicationAPI.AddPoi(out err, ref poi, 1000);
                        }
                        catch {}*/
                    }
                    break;

                case "P2"://paquete de aparcamiento
                    //COMPROBANDO FIRMA CIFRADA (CLAVE PUBLICA)
                    string datosDescifrados2=Criptutiles.RSAverifica(datosConexion[1], datosConexion[2],false);
                    if (datosDescifrados2.Equals(""))
                        // if (!RSA3.VerifyData(decryptedData, "SHA1", signedData))// (dataToEncrypt, "SHA1", signedData);
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Possible Parking Data not Correct" });
                    else
                    {
                        // datosConexion[2] = Criptutiles.Decrypt(datosConexion[2], DButiles.recuperaSK(datosConexion[1]));
                        coordenadas = datosDescifrados2.Split(';');
                        Formulario.Invoke(Formulario.myDelegate, new Object[] { "Parking in: " + coordenadas[0] + " sense " + coordenadas[1] + "coordinates " + coordenadas[2] + "," + coordenadas[3] });
                        DButiles.insertarEvento("P2", coordenadas[0], coordenadas[1], double.Parse(coordenadas[2]), double.Parse(coordenadas[3]), double.Parse(coordenadas[4]), DateTime.Parse(coordenadas[5]), coordenadas[coordenadas.Length - 1]);
                        utiles.anadePoi("Posible Plaza", "Posible Plaza", int.Parse(coordenadas[2]), int.Parse(coordenadas[3]),100);
                       /* try
                        {
                            int res = CApplicationAPI.DeletePoiCategory(out err, "Posible Plaza", "ESP", 1000);
                            string dirImagen = @"parkingsinfondo.bmp";
                            res = CApplicationAPI.AddPoiCategory(out err, "Posible Plaza", dirImagen, "ESP", 1000);
                            LONGPOSITION position = new LONGPOSITION(int.Parse(coordenadas[2]), int.Parse(coordenadas[3]));//X, Y);
                            SPoi poi = new SPoi(position, "Posible Plaza", "Posible plaza", 1000);
                            res = CApplicationAPI.AddPoi(out err, ref poi, 1000);
                            //if (CApplicationAPI.AddBitmapToMap(out err, dirimconges, int.Parse(coordenadas[2]), int.Parse(coordenadas[3]), out IDbitmap, 1000) == 1)
                        }
                        catch
                        {}*/
                    }
                    break;

                default:
                    break;
            }
        }
Ejemplo n.º 6
0
 public void reenviarPaquete()
 {
     Cliente myCliente = new Cliente(Formulario, "9050");
     //System.Threading.
     Thread.Sleep(7000);//TIMESTAMP
     int intentos = 0;
     while (enviado.Equals(señal) && (intentos <= 1) && !Formulario.cerrar)
     {
         intentos++;
         Formulario.Invoke(Formulario.myDelegate, new Object[] { "Reenviando" });
         myCliente.respuesta(señal, pseu, paquete, direccion);//, "Pas5pr@se", "s@1tValue", "SHA1", 2, "@1B2c3D4e5F6g7H8", 256));
         System.Threading.Thread.Sleep(5000);//TIMESTAMP
     }
     if (intentos >= 2)
     {
         secuencia = "01";
         enviado = "00";
         autenticando = "00";
     }
 }
Ejemplo n.º 7
0
        //La publicidad debe recoger de un fichero la firma y mandarla a cada usuario con el que se autentique.
        private void publicidad_Click(object sender, EventArgs e)
        {
            BD DButiles = new BD(this);
            int CoorX = -1632721;// 0899; //-1538956;//
            int CoorY = 2848901;// 704;// 924;// 2309;//2786158;//
            int CoorZ = 0;
            SError err;
            SGpsPosition gps;
            try
            {
                if (CApplicationAPI.GetActualGpsPosition(out err, out gps, false, 1000) == 1)
                {
                    CoorX = gps.Longitude;
                    CoorY = gps.Latitude;
                }
            }
            catch { }

            string viaOnombre = "El Corte Ingles";//El Corte Ingles
            string sentido = "sentido";
            DateTime fechaDato = DateTime.Now;
            string datoPublicidad = viaOnombre + ";" + sentido + ";" + CoorX + ";" + CoorY + ";" + CoorZ + ";" + fechaDato;//Estos datos los coge de un fichero
            //GENERAMOS FIRMA (ESTO ES PARA PRUEBAS)En la versión final esta firma la recogerá de un fichero que le pasará la autoridad
            Utiles utiles = new Utiles();
            byte[] dataToSign = utiles.StrToByteArray(datoPublicidad);
            RSAParameters Cprivada = new RSAParameters()
            {
                D = Convert.FromBase64String("7QePOux7La+Y3jWwOwyHXqCDiduvXQv23TrfVX6cvTmr9BH0FtBzf4dbxYumjreztNrmX+wYsWH5W4pycB67S/tWODZrlrR8zuCCjWauC3ZjPWnlyU+Npg0qzLm7XkCLiuveQWpR4E/TWcs6Wr9pVL2zXT/BsWYC9t39qvkhTKE="),
                DP = Convert.FromBase64String("fJnDOGGMlWgVoQ+7MZtUfivpChykRC39W5UyTnnZ8+xxkt67nzlxXs2wl3w8EV1wRGYPXr0KfjFldUXYGd8h2Q=="),
                DQ = Convert.FromBase64String("3Ls7pKVPqzABAUxQ6jTKypsH7Zd+DJDhQfQset2sK15DmDU+cAY2BFufKvsojfYI2UKKtqvoIGKrWzZ+zrwKOQ=="),
                Exponent = Convert.FromBase64String("AQAB"),
                InverseQ = Convert.FromBase64String("rWWEy1hBu44BBcjuZwFNiixwEQobmHCG+ZqFRldjJKT/2RThzKNc9Q6vYwR52WSwGNxLmlwTvRb2p/gM13WaVQ=="),
                Modulus = Convert.FromBase64String("98Ej5BZ/VMG4nxCzdMZoZ8V50//GvnEQc3CX4vyHzDjOfUGB21ZjVF12s+h3ZQmQX/Woq1zZM6sNsTLVG2SiQhzwWIEE7ioyr2vn1OjE17QOlmrVtl8lI4txnZQQh8jaq1mEi1lqI7JMvwBr+AmTWz+Vf5RraWv/a7qonMDovyM="),
                P = Convert.FromBase64String("/SEbB4+LoAyHzUFTxyuA2mOJdZYIMiugNv9hUZQUjRzVbavfGVaxP/Pu5nxkyzmPtgcTn3m9nwbqwQSlLwEDdw=="),
                Q = Convert.FromBase64String("+pBuG5WisL4wg+B5auoXSQ5Q0/v4405ypMdQ5p6mG2notIamTZ4sp3m2+PpQOitlXrOQemlL3oaed2SH2XQUtQ==")
            };
            RSACryptoServiceProvider RSA2 = new RSACryptoServiceProvider();
            RSA2.ImportParameters(Cprivada);
            byte[] signedData = RSA2.SignData(dataToSign, "SHA1");
             string firma=Convert.ToBase64String(signedData).ToString();//

            Cliente clientePubli = new Cliente(this, "9050");
            Cripto criputiles = new Cripto(this);
            Invoke(myDelegate, new Object[] { "Sending Advertisements." });
               //SError err;
               /* int res = CApplicationAPI.DeletePoiCategory(out err, "El Corte Inglés", "ESP", 0);//(Borramos Para las pruebas)
             res = CApplicationAPI.DeletePoiCategory(out err, "28482309", "ESP", 0);//(Borramos Para las pruebas)
             res = CApplicationAPI.DeletePoiCategory(out err, "atasco", "ESP", 0);//(Borramos Para las pruebas)
             res = CApplicationAPI.DeletePoiCategory(out err, "comercio", "ESP", 0);//(Borramos Para las pruebas)
             res = CApplicationAPI.DeletePoiCategory(out err, "el corte ingles", "ESP", 0);//(Borramos Para las pruebas)
             res = CApplicationAPI.DeletePoiCategory(out err, "elcorteingles", "ESP", 0);//(Borramos Para las pruebas)
             res = CApplicationAPI.DeletePoiCategory(out err, "posible plaza", "ESP", 0);//(Borramos Para las pruebas)
             res = CApplicationAPI.DeletePoiCategory(out err, "restaurante", "ESP", 0);//(Borramos Para las pruebas)*/

               DButiles.insertarEvento("P1", viaOnombre, sentido, CoorX, CoorY, CoorZ, fechaDato, firma); //-1538936, 2786108, DateTime.Now);//Arinaga
            clientePubli.respuesta("P1", Server.myPseudonimo, criputiles.Encrypt(datoPublicidad+ ";" + firma, DButiles.recuperamySK()) , IPAddress.Broadcast.ToString());//,
            //utiles.anadePoi("El Corte Ingles", "Comercio", CoorX, CoorY, 100);
            utiles.anadePoi("banesto", "Comercio", CoorX, CoorY, 100);
            /*         //----------------------------------------------------------------------------------------------
            //ENVIAMOS APARCAMIENTO TB (PARA PRUEBA)
            CoorX = CoorX + 200;//-1631287;
            //CoorY = 2850168;
            viaOnombre = "calle1";
            sentido = "sentido1";
            fechaDato = DateTime.Now;
            string datoAparcamiento = viaOnombre + ";" + sentido + ";" + CoorX + ";" + CoorY + ";" + CoorZ + ";" + fechaDato;//Estos datos los coge de un fichero
            firma= criputiles.RSAfirma(datoAparcamiento);

            Invoke(myDelegate, new Object[] { "Sending Possible Parking" });
            DButiles.insertarEvento("P2", viaOnombre, sentido, CoorX, CoorY, CoorZ, fechaDato, firma);
            clientePubli.respuesta("P2", Server.myPseudonimo, criputiles.Encrypt(datoAparcamiento + ";"+firma, DButiles.recuperamySK()), IPAddress.Broadcast.ToString());//,
            utiles.anadePoi("Posible Plaza", "Posible Plaza", CoorX, CoorY, 100);
            //----------------------------------------------------------------------------------------------
            //ENVIAMOS ATASCO TB (PARA PRUEBA)

            CoorX = CoorX + 200;// -1538956;
               // CoorY = 2786158;
            viaOnombre = "calle1";
            sentido = "sentido1";
            fechaDato = DateTime.Now;
            string datoAtasco = viaOnombre + ";" + sentido + ";" + CoorX + ";" + CoorY + ";" + CoorZ + ";" + fechaDato;//Estos datos los coge de un fichero
            firma = criputiles.RSAfirma(datoAtasco);

            Invoke(myDelegate, new Object[] { "Sending Possible Traffic Jam" });
            DButiles.insertarEvento("T1", viaOnombre, sentido, CoorX, CoorY, CoorZ, fechaDato, firma);
            clientePubli.respuesta("T1", Server.myPseudonimo, criputiles.Encrypt(datoAtasco + ";" + firma, DButiles.recuperamySK()), IPAddress.Broadcast.ToString());//,
            utiles.anadePoi("Atasco", "Atasco", CoorX, CoorY, 100);*/
        }
Ejemplo n.º 8
0
        private void enviarEventos(string pseuUsuario, string clientIPAddress)
        {
            Cliente myCliente = new Cliente(Formulario, "9050");
            string[] eventos = DButiles.recuperaEventos();
            //Formulario.Invoke(Formulario.myDelegate, new Object[] { "Sending Events to: "+pseuUsuario });
            string[] evCortados;
            if (eventos != null)
            for (int i = 0; i < eventos.Length; i++)//Hay que distinguir los eventos porque la publicidad se envia con firma
            {
                evCortados = eventos[i].Split(';');
               // if (evCortados[0].Equals("P1"))//paquete de publicidad
                    myCliente.respuesta(evCortados[0], pseuUsuario, Criptutiles.Encrypt(evCortados[1] + ";" + evCortados[2] + ";" + evCortados[3] + ";" + evCortados[4] + ";" + evCortados[5] + ";" + evCortados[6] + ";" + evCortados[7] + ";" + evCortados[8], DButiles.recuperamySK()), clientIPAddress);    //+ ";" + evCortados[4]
               // else
               //     myCliente.respuesta(evCortados[0], pseuUsuario, Criptutiles.Encrypt(evCortados[1] + ";" + evCortados[2] + ";" + evCortados[3] + ";" + evCortados[4] + ";" + evCortados[5] + ";" + evCortados[6] + ";" + evCortados[7] + ";" + evCortados[8], DButiles.recuperamySK()), clientIPAddress);    //+ ";" + evCortados[4]

                Formulario.Invoke(Formulario.myDelegate, new Object[] { "Sending: " + evCortados[0]+":"+ pseuUsuario });
            }
        }
Ejemplo n.º 9
0
        //Iniciamos aplicacion
        private void Play_Click(object sender, EventArgs e)
        {
            progressBar1.Maximum = 7;
            progressBar1.Value = 1;
            cerrar = false;
            Invoke(myDelegate, new Object[] { "Loading... Please Wait." });
            Play.Enabled = false;//DESABILITO PLAY
            Play.Visible = false;

            //Habilitamos hardware
            Hardware detect = new Hardware();
            if (detect.BluetoothOn())//habilita bluetooth
                Invoke(myDelegate, new Object[] { "Enabled Bluetooth successfully." });
            if (detect.WifiOn())// habilita wifi
                Invoke(myDelegate, new Object[] { "Enabled Wifi successfully." });
            if (detect.conectawifi("vaipho"))//conecta a la red vaipho
                Invoke(myDelegate, new Object[] { "VAiPho conected successfully." });
            progressBar1.Value = 2;
            //Si el manos libres del coche se apaga, VAiPho se apagará también (para evitar atascos inexistentes)
            int key = (int)Registry.GetValue(registryKey, "Bluetooth", -1);
            rg = new RegistryState(registryKey, registryValueName);
            rg.Changed += new ChangeEventHandler(bluetooth_Changed);
            progressBar1.Value = 3;

            //LA CREACION DE LA BD NO SE DEBE EJECUTAR EN LA VERSIÓN FINAL
            Invoke(myDelegate, new Object[] { "Generating DB." });
            BD basededatos = new BD(this);
            //if (basededatos.crearBD())
                if (basededatos.crearTablas())
                {
                    progressBar1.Value = 4;
                    Server Servidor = new Server(this);//, 9050);
                    Cliente Cliente1 = new Cliente(this, "9050");

                    progressBar1.Value = 5;
                    string hostName = Dns.GetHostName();
                    IPHostEntry thisHost = Dns.GetHostEntry(hostName);
                    labelIP.Text = thisHost.AddressList[0].ToString();
                    labelPseu.Text = basededatos.recuperamyPseu();
                    Thread hiloCliente = new Thread(new ThreadStart(Cliente1.beacon));
                    hiloCliente.Start();
                    progressBar1.Value = 6;
                    DetectaIncidente VigilaCarretera = new DetectaIncidente(this);//Aquí dentro se lleva a cabo todo lo de detectarIncidentes
                    VigilaCarretera.DetectaIncidenteStart();
                    //VigilaCarretera.posibleparking();//señala un posible aparcamiento(al encenderse el servicio, no en el play)
                    progressBar1.Value = 7;
                    /*Prueba VigilaCarretera = new Prueba(this);
                    VigilaCarretera.DetectaIncidenteStart();*/
                }
                progressBar1.Value = 0;
        }
Ejemplo n.º 10
0
 //Paramos aplicación
 private void pausandoServicios()
 {
     cerrar = true;
     Invoke(myDelegate, new Object[] { "Stop Services." });
     Cliente cierracliente = new Cliente(this, "9050");//,"127.0.0.1","bye");
     cierracliente.respuesta("01", Server.myPseudonimo, "-", "127.0.0.1");//,
        // PlayEnabled(true);
 }
Ejemplo n.º 11
0
        private void Form1_Load(object sender, EventArgs e)
        {
            cerrar = false;
            Play.Visible = false;
            progressBar1.Maximum = 8;
            progressBar1.Value = 1;
            Invoke(myDelegate, new Object[] { "Loading... Please Wait." });
            Play.Enabled = false;//DESABILITO PLAY

            //byte[] m_soundBytes = new byte[Properties.Resources.iniciando1.Length];
            //Properties.Resources.iniciando1.Read(m_soundBytes, 0, (int)Properties.Resources.iniciando1.Length);
              //  new System.Media.SoundPlayer(
            //System.IO.Stream stream = (System.IO.Stream)Properties.Resources.ResourceManager.BaseName. "iniciando1",false,false);
               // System.Media.SoundPlayer player = new System.Media.SoundPlayer(stream);
               //     Properties.Resources.iniciando1.Play();
            //WSounds ws1 = ;

               // string patch = System.AppDomain.CurrentDomain.BaseDirectory.ToString() BaseDirectory;// BaseDirectory;
            string _appFolder = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            string dirSonido = _appFolder + @"\Sounds\iniciando.wav";//\Sounds\\Sonidos"\\Tarjeta de almacenamiento\\FLEET_MOBILE_14d\\MisSonidos\\iniciando.wav";//Properties.Resources.ResourceManager.BaseName+"\\// "..\\Resources\\iniciando.wav";//\\Tarjeta de almacenamiento\\FLEET_MOBILE_14d\\MisSonidos\\iniciando.wav";
            dirSonido = "\\Tarjeta de almacenamiento\\FLEET_MOBILE_14d\\MisSonidos\\iniciando.wav";

            try
            {
                WSounds ws = new WSounds();
                ws.Play(dirSonido, ws.SND_FILENAME | ws.SND_ASYNC);
            }
            catch (Exception ex)
            {
                Invoke(myDelegate, new Object[] { "Error: " + ex.Message });
            }

            Hardware detect = new Hardware();
            if (detect.BluetoothOn())//habilita bluetooth
                Invoke(myDelegate, new Object[] { "Enabled Bluetooth successfully." });
            if (detect.WifiOn())// habilita wifi
                Invoke(myDelegate, new Object[] { "Enabled Wifi successfully." });
            if (detect.conectawifi("vaipho"))//conecta a la red vaipho
                Invoke(myDelegate, new Object[] { "VAiPho connected successfully." });
            progressBar1.Value = 2;

            //Si el manos libres del coche se apaga, VAiPho se apagará también (para evitar atascos inexistentes)
            int key = (int)Registry.GetValue(registryKey, "Bluetooth", -1);
            rg = new RegistryState(registryKey, registryValueName);
            rg.Changed += new ChangeEventHandler(bluetooth_Changed);

            progressBar1.Value = 3;
            //LA CREACION DE LA BD NO SE DEBE EJECUTAR EN LA VERSIÓN FINAL
            Invoke(myDelegate, new Object[] { "Generating DB." });
            BD basededatos = new BD(this);
            progressBar1.Value = 4;
               /* if (basededatos.crearTablas())//comentar inserts en crear tablas.
            {
                basededatos.creaActualizaBD();
            }*/

            //if (basededatos.crearBD())
                if (basededatos.crearTablas())
                {
                    progressBar1.Value = 5;
                    Server Servidor = new Server(this);//, 9050);
                    Cliente Cliente1 = new Cliente(this, "9050");
                    string hostName = Dns.GetHostName();
                    progressBar1.Value = 6;
                    IPHostEntry thisHost = Dns.GetHostEntry(hostName);
                    labelPseu.Text = basededatos.recuperamyPseu();
                    labelIP.Text = thisHost.AddressList[0].ToString();
                    labelPseu.Text = basededatos.recuperamyPseu();
                    Thread hiloCliente = new Thread(new ThreadStart(Cliente1.beacon));
                    hiloCliente.Start();
                    progressBar1.Value = 7;
                    DetectaIncidente VigilaCarretera = new DetectaIncidente(this);
                    VigilaCarretera.DetectaIncidenteStart();
                    VigilaCarretera.posibleparking();
                    progressBar1.Value = 8;
                    /*Prueba VigilaCarretera = new Prueba(this);
                    VigilaCarretera.DetectaIncidenteStart();*/
                }
                progressBar1.Value = 0;
        }
Ejemplo n.º 12
0
        //Cerramos aplicación y GPS
        private void cerrandoAplicacion()
        {
            try
            {
                cerrar = true;
                Cliente cierracliente = new Cliente(this, "9050");//,"127.0.0.1","bye");
                cierracliente.respuesta("01", Server.myPseudonimo, "-", "127.0.0.1");//,
                 string _appFolder = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
                 string dirSonido = _appFolder + @"\Sounds\apagando.wav";
                dirSonido = "\\Tarjeta de almacenamiento\\FLEET_MOBILE_14d\\MisSonidos\\apagando.wav";//parking.wav";

                WSounds ws = new WSounds();
                ws.Play(dirSonido, ws.SND_FILENAME | ws.SND_ASYNC);

                DriveHandler.EndApplication(0);
                DriveHandler.CloseApi();
                Hardware detect = new Hardware();
                detect.WifiOff();

            }
            catch
            {
                //    Formulario.Invoke(Formulario.myDelegate, new Object[] { "Error software GPS: " + e.Message });
            }
        }
Ejemplo n.º 13
0
        private void Atasco_Click(object sender, EventArgs e)
        {
            BD DButiles = new BD(this);
            int CoorX = -1632700;// 0899; //-1538956;//
            int CoorY = 2848779;//2309;//2786158;//
            int CoorZ = 0;
            SError err;
            SGpsPosition gps;
            try
            {
                if (CApplicationAPI.GetActualGpsPosition(out err, out gps, false, 1000) == 1)
                {
                    CoorX = gps.Longitude;
                    CoorY = gps.Latitude;
                }
            }
            catch { }

            string viaOnombre = "Atasco";
            string sentido = "sentido";
            DateTime fechaDato = DateTime.Now;
            string datoPublicidad = viaOnombre + ";" + sentido + ";" + CoorX + ";" + CoorY + ";" + CoorZ + ";" + fechaDato;//Estos datos los coge de un fichero

               // string firma = Convert.ToBase64String(signedData).ToString();//
            Utiles utiles = new Utiles();
            Cliente clientePubli = new Cliente(this, "9050");
            Cripto criputiles = new Cripto(this);
                //----------------------------------------------------------------------------------------------
                //ENVIAMOS ATASCO TB (PARA PRUEBA)
                //CoorX = CoorX + 200;// -1538956;
               // CoorY = 2786158;
                viaOnombre = "calle1";
                sentido = "sentido1";
                fechaDato = DateTime.Now;//.GetDateTimeFormats("MM/dd/yyyy HH:mm:ss");

            agregacion datoagregado=  new agregacion(this, viaOnombre, sentido, CoorX, CoorY, CoorZ, fechaDato);
            string firma = datoagregado.FirmarMsje("Traffic Jam", Server.myPseudonimo);
                string datoAtasco = viaOnombre + "_" + sentido + "_" + CoorX + "_" + CoorY + "_" + CoorZ + "_" + fechaDato.ToString("MM/dd/yyyy HH:mm:ss");//Estos datos los coge de un fichero
               // firma = criputiles.RSAfirma(datoAtasco);
                string mensaje = "A_Traffic Jam." + firma + '|'+Server.myPseudonimo + "_" + datoAtasco;
                Invoke(myDelegate, new Object[] { "Sending Possible Traffic Jam" });
                DButiles.insertarEvento("T1", viaOnombre, sentido, CoorX, CoorY, CoorZ, fechaDato, firma);
                clientePubli.respuesta("T1", Server.myPseudonimo, criputiles.Encrypt(mensaje, DButiles.recuperamySK()), IPAddress.Broadcast.ToString());//,+ ";" + firma
                utiles.anadePoi("Atasco", "Atasco", CoorX, CoorY, 100);
        }