/// <summary> /// Starts the server. /// </summary> private void StartServer() { // Initialize Socket class socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Request and bind to an IP from DHCP server socket.Bind(new IPEndPoint(IPAddress.Any, 80)); // Debug print our IP address Debug.Print("Listening on " + Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress + ":80"); // Start listen for web requests socket.Listen(10); while (true) { using (Socket clientSocket = socket.Accept()) { // Get clients IP IPEndPoint clientIP = clientSocket.RemoteEndPoint as IPEndPoint; Debug.Print("Received request from " + clientIP.ToString()); EndPoint clientEndPoint = clientSocket.RemoteEndPoint; if (clientSocket.Poll(-1, SelectMode.SelectRead)) { // Create buffer and receive raw bytes. byte[] bytes = new byte[clientSocket.Available]; int count = clientSocket.Receive(bytes); // Convert to string, will include HTTP headers. string rawData = new string(Encoding.UTF8.GetChars(bytes)); WebCommand command = InterpretRequest(rawData); if (command != null) { WebCommandEventArgs args = new WebCommandEventArgs(command); if (CommandReceived != null) { CommandReceived(this, args); byte[] returnBytes = Encoding.UTF8.GetBytes(args.ReturnString); clientSocket.Send(returnBytes, 0, returnBytes.Length, SocketFlags.None); } } } } Thread.Sleep(10); } }
/// <summary> /// Maneja los eventos recibidos a raves del navegador. Realiza acciones con los argumentos que le pasemos par aposteriormente comunicarse con 'Program'. /// </summary> private static void server_CommandReceived(object source, WebCommandEventArgs e) { Debug.Print("Command received: " + e.Command.CommandString); switch (e.Command.CommandString) { #region INDEX case "index": { string message = msgAux; if (!msgAux.Equals("")) { msgAux = ""; } e.ReturnString = writeHTML(message); break; } #endregion #region SETROUND case "setround": { if (ready) { msgAux = "No se pueden cambiar los parámetros en competición ni una vez preparado el sistema."; e.ReturnString = redirect("index"); break; } // Si el tiempo global introducido es diferente al que ya teniamos previamente guardado, lo cambiamos. if ((int.Parse(e.Command.Arguments[3].ToString())) != Datos.timeLeft) { Datos.timeLeft = int.Parse(e.Command.Arguments[3].ToString()); } if (double.Parse(e.Command.Arguments[0].ToString()) > 30 || double.Parse(e.Command.Arguments[1].ToString()) < 12) { msgAux = "El rango de temperatura máximo es entre 30 y 12 grados C."; e.ReturnString = redirect("index"); break; } // Validate the data if (e.Command.Arguments[0].ToString().Length == 0 || e.Command.Arguments[1].ToString().Length == 0 || e.Command.Arguments[2].ToString().Length == 0) { msgAux = "Debe especificar todos los parámetros que se piden."; e.ReturnString = redirect("index"); break; } else { // concatenamos los datos para guardarlos en la variable 'Datos.roundQueue' = xx-xx-xxxx/ for (int a = 0; a < 3; a++) { Datos.roundQueue += e.Command.Arguments[a].ToString(); if (a == 2) { Datos.roundQueue += '/'; } else { Datos.roundQueue += '-'; } } } msgAux = "Se ha introducido una nueva ronda. Click 'set ronda' para una nueva ronda o 'Guardar' si ya estas preparado"; e.ReturnString = redirect("index"); break; } #endregion #region SETPARAMS case "setparams": { if (!e.Command.Arguments[0].Equals(pass)) { msgAux = "La constraseña es incorrecta."; e.ReturnString = redirect("index"); break; } // conrol de contaseña if (!e.Command.Arguments[0].Equals(pass)) { msgAux = "La constraseña es incorrecta."; e.ReturnString = redirect("index"); break; } // Nos aseguramos que no estamos en competicion if (ready) { msgAux = "No se pueden cambiar los parámetros en competición ni una vez preparado el sistema."; e.ReturnString = redirect("index"); break; } // Validate the data if (e.Command.Arguments[1].ToString().Length == 0 || e.Command.Arguments[2].ToString().Length == 0 || e.Command.Arguments[3].ToString().Length == 0) { msgAux = "Debe especificar todos los parámetros que se piden."; e.ReturnString = redirect("index"); break; } // Guardamos los diferentes rangos en un array de strings separandolos por el '/' String[] rangos = Datos.roundQueue.Split('/'); // Instanciamos lo nuevo objetos TemperatureRange con el numero de arrays obtenidos anteriormente en 'rangos' Datos.rangos = new TemperatureRange[rangos.Length]; for (int i = 0; i < (rangos.Length - 1); i++) { // realizamos un nuevo trim pero con '-' separando asi, TempMax, TempMin y roundTime String[] parametros = rangos[i].Split('-'); Datos.rangos[i] = new TemperatureRange(double.Parse(parametros[1]), double.Parse(parametros[0]), int.Parse(parametros[2])); } TemperatureRange temporalTem; /// <summary> /// EN ESTE BUCLE REALIZAMOS UN ALGORITMO DE INSERCION ORDENADA. EN NUESTRO CASO LO HACEMOS DESDE LOS RANGOS QUE /// SE ENCUENTREN EN UNA TENPERATURA MENOR HACIA LAS MAYORES SIEMPRE FIJANDONOS EN LA TEMPERATURA MINIMA. DENESTA MANERA APROVECHAMOS UN /// INCREMENTTO LINEAL DE LA TEMPERATURA EN VEZ DE SALTOS IRREGULARES. SIEMPRE RESPETANDO LOS RANGOS INDICADOS POR EL PROFESOR. /// </summary> for (int i = 0; i < rangos.Length - 1; i++) { for (int j = 0; j <= (rangos.Length - 2); j++) { if ((j + 1) <= (rangos.Length - 2)) { if (Datos.rangos[j].MinTemp > Datos.rangos[j + 1].MinTemp) { temporalTem = Datos.rangos[j]; Datos.rangos[j] = Datos.rangos[j + 1]; Datos.rangos[j + 1] = temporalTem; } } } } Datos.displayRefresh = int.Parse(e.Command.Arguments[1].ToString()); Datos.refresh = int.Parse(e.Command.Arguments[2].ToString()); Datos.timeLeft = int.Parse(e.Command.Arguments[3].ToString()); Datos.tempMax = Datos.rangos[0].MaxTemp; Datos.tempMin = Datos.rangos[0].MinTemp; Datos.roundTime = Datos.rangos[0].RangeTimeInMilliseconds; Datos.roundTimeAux = Datos.roundTime; ready = true; msgAux = "Los parámetros se han cambiado satisfactoriamente. Todo preparado."; e.ReturnString = redirect("index"); break; } #endregion #region START case "start": { // Control de contraseña if (!e.Command.Arguments[0].Equals(pass)) { msgAux = "La constraseña es incorrecta."; e.ReturnString = redirect("index"); break; } // Control de que no estamos en competicion if (Datos.competi) { msgAux = "Ya estamos en competición."; e.ReturnString = redirect("index"); break; } int rounds = 0; Datos.timeInRangeTemp = 0; Thread nuevaRonda = new Thread(Program.startRound); // Lanzamos el hilo para arranzar la ronda nuevaRonda.Start(); Datos.competi = true; while (Datos.competi) { // Comprobamos que hems conseguido el tiempo de la ronda para empezar la nueva. if (Datos.roundTimeAux == 0 && Datos.rangos[rounds + 1] != null && rounds < (Datos.rangos.Length - 1)) { Debug.Print("--------------------------------------INSERTANDO NUEVOS DATOS DE RONDA------------------------------"); rounds++; Datos.tempMax = Datos.rangos[rounds].MaxTemp; Datos.tempMin = Datos.rangos[rounds].MinTemp; Datos.roundTime = Datos.rangos[rounds].RangeTimeInMilliseconds; Datos.roundTimeAux = Datos.roundTime; } Thread.Sleep(Datos.refresh); } // Return feedback to web user. if (Datos.error) { Datos.error = false; msgAux = "Se ha detenido la competición porque se detectó una temperatura superior a 40C."; e.ReturnString = redirect("index"); break; } if (!Datos.competi) { Datos.roundQueue = ""; Datos.timeLeft = 0; msgAux = "Se ha terminado la ronda con " + Datos.timeInRangeTemp + " segundos en el rango indicado" + Datos.roundQueue; ready = false; e.ReturnString = redirect("index"); Program.off(); break; } break; } #endregion #region MODO ENFRIAMIENTO case "coolermode": { // Miramos que la contraseña es correcta if (!e.Command.Arguments[0].Equals(pass)) { msgAux = "La constraseña es incorrecta."; e.ReturnString = redirect("index"); break; } // Comrpbamos que no estamos en competicion if (ready) { msgAux = "No se puede activar este modo en competición ni una vez preparado el sistema."; e.ReturnString = redirect("index"); break; } // Lanzamos el hilo de modo enfriamiento new Thread(Program.coolerMode).Start(); msgAux = "Se ha iniciado el modo enfriamiento satisfactoriamente."; e.ReturnString = redirect("index"); break; } #endregion #region TEMPERATURE CHECK case "temp": { msgAux = "La temperatura del sistema es de " + Datos.tempAct + "C."; e.ReturnString = redirect("index"); break; } #endregion #region TIME CHECK case "time": { msgAux = "El tiempo que se ha mantenido en el rango de temperatura es de " + Datos.timeInRangeTemp + "s."; e.ReturnString = redirect("index"); break; } #endregion } }