Netduino-Plus como webserver interactuando con dispositivos


Hay muchas maneras de controlar la puerta del garaje con su Netduino. En este caso se   modificara un mando de apertura de puerta de garaje  por medio de un OPTOISOLATOR   y este a su vez se conectara a nuestro netduino por medio de uan resistencia en serie. Para enviar comandos a la placa de  Netduino se utilizaran simples  comandos HTTP.

Componentes necesarios para el montaje

  • Abrir puertas de garajes
  • OPTOISOLATOR con el controlador de Darlington – 1 canal.
  • Resistencia de 100 ohmios
  • 33 ohmios resistencia
  • Netduino  Plus

El esquema para la conexión del netudiono  con el abridor de la puerta del garaje es bastante sencillo:

  • Conecte el pin OPTOISOLATOR 1 (ánodo) al pin digital plus Netduino 13
  • Conecte el pin OPTOISOLATOR 2 (cátodo) a un pin de tierra en el signo más Netduino con una resistencia de 33 ohmios en línea.
  • Conectar el pasador optoaislador 3 (emisor) a un lado de la puerta de garaje pulsador con una resistencia de 100 ohmios en línea.
  • Conectar el pasador optoaislador 4 (colector) al otro lado de la puerta garge abridor pulsador.

Explicacion del código 

Primero se inicializa el puerto digital 13 para hablar con el abrepuertas de garaje
Desues se analiza la solicitud http y confirme que el usuario solicitado a la puerta se active con el comando «HTTP: /192.XXX.X.XXX/activatedoor»

Se llama al  método para activar el abridor de puerta de garaje.
Se envia respuesta HTTP.
Se envía una respuesta HTTP – comando no reconocido.
Se  active el método de puerta de garaje
Se  encienda el LED de a bordo para que se envíe el comando de confirmación visual al abrepuertas de garaje
Se  envíe voltaje al pin digital 13 para cerrar el botón en el abrepuertas de garaje
Se espera 1 segundo
Se apagua el LED de a bordo
Se detiene el voltaje en el pin 13

 

Codigo completo

 

public class WebServer : IDisposable
{
private Socket socket = null;
//open connection to onbaord led so we can blink it with every request
private OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
private OutputPort Garage2CarOpener = new OutputPort(Pins.GPIO_PIN_D13, false);

public WebServer()
{
//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(Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress);
//Start listen for web requests
socket.Listen(10);
ListenForRequest();
}

public void ListenForRequest()
{
while (true)
{
using (Socket clientSocket = socket.Accept())
{
//Get clients IP
IPEndPoint clientIP = clientSocket.RemoteEndPoint as IPEndPoint;
EndPoint clientEndPoint = clientSocket.RemoteEndPoint;
//int byteCount = cSocket.Available;
int bytesReceived = clientSocket.Available;
if (bytesReceived > 0)
{
//Get request
byte[] buffer = new byte[bytesReceived];
int byteCount = clientSocket.Receive(buffer, bytesReceived, SocketFlags.None);
string request = new string(Encoding.UTF8.GetChars(buffer));
string firstLine = request.Substring(0, request.IndexOf(‘\n’)); //Example «GET /activatedoor HTTP/1.1»
string[] words = firstLine.Split(‘ ‘); //Split line into words
string command = string.Empty;
if( words.Length > 2)
{
string method = words[0]; //First word should be GET
command = words[1].TrimStart(‘/’); //Second word is our command – remove the forward slash
}
switch (command.ToLower())
{
case «activatedoor»:
ActivateGarageDoor();
//Compose a response
string response = «I just opened or closed the garage!»;
string header = «HTTP/1.0 200 OK\r\nContent-Type: text; charset=utf-8\r\nContent-Length: » + response.Length.ToString() + «\r\nConnection: close\r\n\r\n»;
clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);
clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);
break;
default:
//Did not recognize command
response = «Bad command»;
header = «HTTP/1.0 200 OK\r\nContent-Type: text; charset=utf-8\r\nContent-Length: » + response.Length.ToString() + «\r\nConnection: close\r\n\r\n»;
clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);
clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);
break;
}
}
}
}
}
private void ActivateGarageDoor()
{
led.Write(true); //Light on-board LED for visual cue
Garage2CarOpener.Write(true); //»Push» garage door button
Thread.Sleep(1000); //For 1 second
led.Write(false); //Turn off on-board LED
Garage2CarOpener.Write(false); //Turn off garage door button
}
#region IDisposable Members
~WebServer()
{
Dispose();
}
public void Dispose()
{
if (socket != null)
socket.Close();
}
#endregion
}

Anuncio publicitario

Primeros Pasos con Netduino como webserber


 

En estas lineas vamos a mostrar cómo crear un pequeños servidor web, que ejecutaremos en nuestro Netduino (+). El servidor web debe responder ante cada petición HTTP con un «Hola Mundo».

 

Empezamos creando un nuevo proyecto de tipo Netduino Plus en nuestro Visual Studio–> Botón derecho sobre el proyecto y elige «Añadir nuevo elemento». –>Añade una nueva clase llamada WebServer.cs.
Aquí presentamos una versión muy simple de nuestro servidor web  que se mantiene a la escucha, atendiendo las peticiones, y respondiendo «Hola Mundo» mientras hace parpadear el led de nuestro Netduino Plus.
public class WebServer : IDisposable
{
   private Socket socket = null;
   private OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
   public WebServer()
  {
       //Inicializamos el socket
       socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
       //Conectamos el socket
       socket.Bind(new IPEndPoint(IPAddress.Any, 80));
      //Iniciamos la escucha
      socket.Listen(10);
      ListenForRequest();
 }
 public void ListenForRequest()
{
  while (true)
  {
     using (Socket clientSocket = socket.Accept())
     {
       //Aceptamos el cliente
       IPEndPoint clientIP = clientSocket.RemoteEndPoint as IPEndPoint;
       EndPoint clientEndPoint = clientSocket.RemoteEndPoint;
       int bytesReceived = clientSocket.Available;
       if (bytesReceived > 0)
      {
           //Obtenemos la petición
           byte[] buffer = new byte[bytesReceived];
           int byteCount = clientSocket.Receive(buffer, bytesReceived, SocketFlags.None);
           string request = new string(Encoding.UTF8.GetChars(buffer));
           Debug.Print(request);
         //Componemos la respuesta (Nota 1)
           string response = «Hola Mundo»;
           string header = «HTTP/1.0 200 OK\r\nContent-Type: text; charset=utf-8\r\nContent-Length: » + response.Length.ToString() + «\r\nConnection: close\r\n\r\n»;
           clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);
           clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);
           //Parpadeo del led
           led.Write(true);
           Thread.Sleep(150);
           led.Write(false);
      }
    }
  }
}
#region IDisposable Members
~WebServer()
{
      Dispose();
}
public void Dispose()
{
     if (socket != null)
        socket.Close();
}
#endregion
}
El siguiente paso es añadir el siguiente código para iniciar el servidor web.
public static void Main()
{
    Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].EnableDhcp();
    WebServer webServer = new WebServer();
    webServer.ListenForRequest();
}
En el siguiente paso, tenemos que desplegar el código en nuestro Netduino haciendo click en las propiedades del proyecto.
Una vez cambiadas las propiedades del proyecto, seleccionamos la pestaña «.Net Micro Framework» y cambiamos las siguientes propiedades:
Transport: USB
Device: NetduinoPlus_NetduinoPlus
Ahora solo nos queda pulsar F5 para pasar nuestro código a Netduino ,esperar unos inst asegurando que  nuestro Netduino-plus esta conectado a internet   realizamos la siguiente petición mediante nuestro navegador.
http://192.168.1.2/ ( o la ip que le haya asignado nuestro router a nuestro netduino)

 

 

Acceso a twitter con netduino


 

Pasos a aseguir

Las librerias de Microtweet de Codeplex, aquí

Crear una nueva cuenta de twitter.

Regístrese nueva aplicación según las instrucciones. Agregar 4 claves para el código.

Se usara un ssnsor de 1 hilo S1820 (de la parte posterior de Java material Tini en 2000/01. Obsoleta DS1820, pero funciona bien)1

Tambien  se usa un pulsador para realizar elenvio de tweets

Cargue este codigo en su netduino , asegurese que este est coenctado a Internet y  Pulse el botón: esto , leera la temperatura,y  enviara tweets.

 

A continuación el codigo para nuestro Netduino:

using System;
002 using System.Net;
003 using System.Net.Sockets;
004 using System.Threading;
005 using Microsoft.SPOT;
006 using Microsoft.SPOT.Hardware;
007 using SecretLabs.NETMF.Hardware;
008 using SecretLabs.NETMF.Hardware.NetduinoPlus;
009 using Komodex.NETMF.MicroTweet;
010 using Microsoft.SPOT.Net.NetworkInformation;
011 using CW.NETMF.Hardware;
012
013 namespace TweetButtonTest
014 {
015     public class Program
016     {
017         private const string consumerKey = "KeyGoesHere";
018         private const string consumerSecret = "ItsASecret";
019         private const string userToken = "InsertCoin";
020         private const string userSecret = "Shh...DontTellAnyone";
021
022         private const string ntpServer = "time-a.nist.gov";
023
024         private OutputPort led = null;
025         private TwitterClient twitterClient = null;
026         private OneWire oneWire;
027
028         public static void Main()
029         {
030             new Program().Run();
031         }
032
033         public void Run()
034         {
035
036             NTP.UpdateTimeFromNTPServer(ntpServer);
037
038             twitterClient = new TwitterClient(consumerKey, consumerSecret, userToken, userSecret);
039
040             oneWire = new OneWire(Pins.GPIO_PIN_D1);
041             led = new OutputPort(Pins.GPIO_PIN_D13, false);
042
043             Button button = new Button(Pins.GPIO_PIN_D0);
044             button.Released += new NoParamEventHandler(button_Released);
045
046             Thread.Sleep(Timeout.Infinite);
047         }
048
049         void button_Released()
050         {
051             try
052             {
053                 float temperature = GetTemperature();
054                 string msg = "Today I'm tweeting the temperature from an DS1820. It's "+temperature+"C #netdunio";
055                 Debug.Print(msg);
056
057                 bool tweetSent =  twitterClient.SendTweet(msg);
058                 if (tweetSent)
059                 {
060                     FlashLed(1);
061                 }
062                 else
063                 {
064                     FlashLed(2);
065                 }
066             }
067             catch
068             {
069                 FlashLed(3);
070             }
071         }
072
073         private void FlashLed(int flashCount)
074         {
075             while (flashCount-- > 0)
076             {
077                 led.Write(true);
078                 Thread.Sleep(250);
079                 led.Write(false);
080                 Thread.Sleep(250);
081             }
082         }
083
084         private float GetTemperature()
085         {
086             oneWire.Reset();
087             oneWire.WriteByte(OneWire.SkipRom); //All devices
088             oneWire.WriteByte(DS1820.ConvertT); //Do convert
089             Thread.Sleep(750);  //Wait for conversion
090
091             oneWire.Reset();
092             oneWire.WriteByte(OneWire.SkipRom); //All devices
093             oneWire.WriteByte(DS1820.ReadScratchpad); //Read data
094
095             //Read the first two bytes - tempLow and tempHigh
096             byte tempLow = oneWire.ReadByte();
097             byte tempHigh = oneWire.ReadByte();
098             return DS1820.GetTemperature(tempLow, tempHigh);
099
100         }
101     }
102 }

Sincronizar la hora de tu netduino


Este utilidad  para nuestro Netduino    toma el dato fecha-hora(datetime)   de un servidor  NTP
El código se basa  en http://weblogs.asp.net/mschwarz/archive/2008/03/09/wrong-datetime-on-net-micro-framework-devices.aspx
Código para Netduino-Plus:

using
 System;
02 using Microsoft.SPOT;
03 using System.Net.Sockets;
04 using System.Net;
05 using Microsoft.SPOT.Hardware;
06 using SecretLabs.NETMF.Hardware;
07 using SecretLabs.NETMF.Hardware.Netduino;
08 using Microsoft.SPOT.Time;
09
10 namespace NetduinoPlusWebServer
11 {
12     class TimeHandeler
13     {
14  
19         /// <param name="TimeServer">Timeserver</param>
20         /// <returns>Local NTP Time</returns>
21         public static DateTime NTPTime(String TimeServer)
22         {
23             // Find endpoint for timeserver
24             IPEndPoint ep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123);
25
26             // Connect to timeserver
27             Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
28             s.Connect(ep);
29
30             // Make send/receive buffer
31             byte[] ntpData = new byte[48];
32             Array.Clear(ntpData, 0, 48);
33
34             // Set protocol version
35             ntpData[0] = 0x1B;
36
37             // Send Request
38             s.Send(ntpData);
39
40             // Receive Time
41             s.Receive(ntpData);
42
43             byte offsetTransmitTime = 40;
44
45             ulong intpart = 0;
46             ulong fractpart = 0;
47
48             for (int i = 0; i <= 3; i++)
49                 intpart = (intpart <<  8 ) | ntpData[offsetTransmitTime + i];
50
51             for (int i = 4; i <= 7; i++)
52                 fractpart = (fractpart <<  8 ) | ntpData[offsetTransmitTime + i];
53
54             ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L);
55
56             s.Close();
57
58             TimeSpan timeSpan = TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
59             DateTime dateTime = new DateTime(1900, 1, 1);
60             dateTime += timeSpan;
61
62             TimeSpan offsetAmount = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
63             DateTime networkDateTime = (dateTime + offsetAmount);
64
65             return networkDateTime;
66         }
67
68     }
69 }

Netduino-Plus como webserver interactuando con dispositivos


Hay muchas maneras de controlar la puerta del garaje con su Netduino. En este caso se   modificara un mando de apertura de puerta de garaje  por medio de un OPTOISOLATOR   y este a su vez se conectara a nuestro netduino por medio de uan resistencia en serie. Para enviar comandos a la placa de  Netduino se utilizaran simples  comandos HTTP.

Componentes necesarios para el montaje

  • Abrir puertas de garajes
  • OPTOISOLATOR con el controlador de Darlington – 1 canal.
  • Resistencia de 100 ohmios
  • 33 ohmios resistencia
  • Netduino  Plus

El esquema para la conexión del netudiono  con el abridor de la puerta del garaje es bastante sencillo:

  • Conecte el pin OPTOISOLATOR 1 (ánodo) al pin digital plus Netduino 13
  • Conecte el pin OPTOISOLATOR 2 (cátodo) a un pin de tierra en el signo más Netduino con una resistencia de 33 ohmios en línea.
  • Conectar el pasador optoaislador 3 (emisor) a un lado de la puerta de garaje pulsador con una resistencia de 100 ohmios en línea.
  • Conectar el pasador optoaislador 4 (colector) al otro lado de la puerta garge abridor pulsador.

Código

public class WebServer : IDisposable
02     {
03         private Socket socket = null;
04         //open connection to onbaord led so we can blink it with every request
05         private OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
06         private OutputPort Garage2CarOpener = new OutputPort(Pins.GPIO_PIN_D13,false);
07
08         public WebServer()
09         {
10             //Initialize Socket class
11             socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
12             //Request and bind to an IP from DHCP server
13             socket.Bind(new IPEndPoint(IPAddress.Any, 80));
14             //Debug print our IP address
15             Debug.Print(Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress);
16             //Start listen for web requests
17             socket.Listen(10);
18             ListenForRequest();
19         }
20
21         public void ListenForRequest()
22         {
23             while (true)
24             {
25                 using (Socket clientSocket = socket.Accept())
26                 {
27                     //Get clients IP
28                     IPEndPoint clientIP = clientSocket.RemoteEndPoint as IPEndPoint;
29                     EndPoint clientEndPoint = clientSocket.RemoteEndPoint;
30                     //int byteCount = cSocket.Available;
31                     int bytesReceived = clientSocket.Available;
32                     if (bytesReceived > 0)
33                     {
34                         //Get request
35                         byte[] buffer = new byte[bytesReceived];
36                         int byteCount = clientSocket.Receive(buffer, bytesReceived, SocketFlags.None);
37                         string request = new string(Encoding.UTF8.GetChars(buffer));
38                         string firstLine = request.Substring(0, request.IndexOf('\n')); //Example "GET /activatedoor HTTP/1.1"
39                         string[] words = firstLine.Split(' ');  //Split line into words
40                         string command = string.Empty;
41                         if( words.Length > 2)
42                         {
43                             string method = words[0]; //First word should be GET
44                             command = words[1].TrimStart('/'); //Second word is our command - remove the forward slash
45                         }
46                         switch (command.ToLower())
47                         {
48                             case "activatedoor":
49                                 ActivateGarageDoor();
50                                 //Compose a response
51                                 string response = "I just opened or closed the garage!";
52                                 string header = "HTTP/1.0 200 OK\r\nContent-Type: text; charset=utf-8\r\nContent-Length: " + response.Length.ToString() +"\r\nConnection: close\r\n\r\n";
53                                 clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);
54                                 clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);
55                                 break;
56                             default:
57                                 //Did not recognize command
58                                 response = "Bad command";
59                                 header = "HTTP/1.0 200 OK\r\nContent-Type: text; charset=utf-8\r\nContent-Length: " + response.Length.ToString() + "\r\nConnection: close\r\n\r\n";
60                                 clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);
61                                 clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);
62                                 break;
63                         }
64                     }
65                 }
66             }
67         }
68         private void ActivateGarageDoor()
69         {
70             led.Write(true);                //Light on-board LED for visual cue
71             Garage2CarOpener.Write(true);   //"Push" garage door button
72             Thread.Sleep(1000);             //For 1 second
73             led.Write(false);               //Turn off on-board LED
74             Garage2CarOpener.Write(false);  //Turn off garage door button
75         }
76         #region IDisposable Members
77         ~WebServer()
78         {
79             Dispose();
80         }
81         public void Dispose()
82         {
83             if (socket != null)
84                 socket.Close();
85         }
86         #endregion
87     }

Primeros Pasos con Netduino como webserber


En estas lineas vamos a mostrar cómo crear un pequeños servidor web, que ejecutaremos en nuestro Netduino (+). El servidor web debe responder ante cada petición HTTP con un «Hola Mundo».

Empezamos creando un nuevo proyecto de tipo Netduino Plus en nuestro Visual Studio–> Botón derecho sobre el proyecto y elige «Añadir nuevo elemento». –>Añade una nueva clase llamada WebServer.cs.
Aquí presentamos una versión muy simple de nuestro servidor web  que se mantiene a la escucha, atendiendo las peticiones, y respondiendo «Hola Mundo» mientras hace parpadear el led de nuestro Netduino Plus.
public class WebServer : IDisposable
{
   private Socket socket = null;
   private OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
   public WebServer()
  {
       //Inicializamos el socket
       socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
       //Conectamos el socket
       socket.Bind(new IPEndPoint(IPAddress.Any, 80));
      //Iniciamos la escucha
      socket.Listen(10);
      ListenForRequest();
 }
 public void ListenForRequest()
{
  while (true)
  {
     using (Socket clientSocket = socket.Accept())
     {
       //Aceptamos el cliente
       IPEndPoint clientIP = clientSocket.RemoteEndPoint as IPEndPoint;
       EndPoint clientEndPoint = clientSocket.RemoteEndPoint;
       int bytesReceived = clientSocket.Available;
       if (bytesReceived > 0)
      {
           //Obtenemos la petición
           byte[] buffer = new byte[bytesReceived];
           int byteCount = clientSocket.Receive(buffer, bytesReceived, SocketFlags.None);
           string request = new string(Encoding.UTF8.GetChars(buffer));
           Debug.Print(request);
         //Componemos la respuesta (Nota 1)
           string response = «Hola Mundo»;
           string header = «HTTP/1.0 200 OK\r\nContent-Type: text; charset=utf-8\r\nContent-Length: » + response.Length.ToString() + «\r\nConnection: close\r\n\r\n»;
           clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);
           clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);
           //Parpadeo del led
           led.Write(true);
           Thread.Sleep(150);
           led.Write(false);
      }
    }
  }
}
#region IDisposable Members
~WebServer()
{
      Dispose();
}
public void Dispose()
{
     if (socket != null)
        socket.Close();
}
#endregion
}
El siguiente paso es añadir el siguiente código para iniciar el servidor web.
public static void Main()
{
    Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].EnableDhcp();
    WebServer webServer = new WebServer();
    webServer.ListenForRequest();
}
En el siguiente paso, tenemos que desplegar el código en nuestro Netduino haciendo click en las propiedades del proyecto.
Una vez cambiadas las propiedades del proyecto, seleccionamos la pestaña «.Net Micro Framework» y cambiamos las siguientes propiedades:
Transport: USB
Device: NetduinoPlus_NetduinoPlus
Ahora solo nos queda pulsar F5 para pasar nuestro código a Netduino ,esperar unos inst asegurando que  nuestro Netduino-plus esta conectado a internet   realizamos la siguiente petición mediante nuestro navegador.
http://192.168.1.2/ ( o la ip que le haya asignado nuestro router a nuestro netduino)