Manufactura industrial
Internet industrial de las cosas | Materiales industriales | Mantenimiento y reparación de equipos | Programación industrial |
home  MfgRobots >> Manufactura industrial >  >> Manufacturing Technology >> Proceso de manufactura

Hogar Hogar inteligente

Componentes y suministros

Raspberry Pi 2 Modelo B
Orange PI también serviría
× 1
Xbee
× 1
Arduino UNO
× 1

Aplicaciones y servicios en línea

Microsoft Azure

Acerca de este proyecto

Introducción

Veamos qué necesitamos para configurar un sistema doméstico inteligente usando MediaTek Linkit. Dado que hay muchos expertos aquí para guiarlo en la conexión del hardware para leer los datos del sensor, me concentraré en crear apis y configurar un servidor local de $ 15 de costo ultra bajo para capturar todos los datos del sensor. Opcionalmente, registro los datos en azul.

Configuración

Los sensores transmiten sus datos a través de señales de radio usando xbee o cualquier transceptor de bajo costo al MediaTek LinkIt. El enlace MediaTek Recibe todos los datos del sensor sin procesar, los empaqueta en un objeto json utilizando la biblioteca adruinojson y realiza una solicitud POST al servidor local. El servidor local aloja la aplicación web nodejs y recibe todos los datos del sensor como objetos json.

El servidor local se utiliza como preprocesador y agrega la hora y la firma de utc. Aquí se puede procesar cualquier validación, conversión y filtración de datos. El servidor local registra todos los datos en el servicio en la nube en nuestro caso, los servicios de almacenamiento azul. Alternativamente, MediaTek linkIt puede publicar directamente los objetos json en los servicios de almacenamiento azure. Configuré un servidor local solo para demostrar que una computadora de $ 15 puede ser lo suficientemente poderosa para manejar nuestros datos. podemos registrar nuestros datos en cualquier base de datos sin sql incluso en nuestro servidor local eliminando por completo la necesidad de almacenamiento externo en la nube. Les dejo todo esto a ustedes.

Demostración

   

Requisito previo

Supongo que sabe cómo leer los datos de los sensores usando sensores y microcontroladores como arduino o mediaTek. Para limitar el alcance de este proyecto, voy a asumir que los datos del sensor están disponibles para MediaTek Link It. Puede usar un transceptor de radio de baja emisión o Xbee para transmitir y recibir las señales de radio de los sensores conectados al microcontrolador como MediaTek. Los principiantes pueden usar el kit de inicio MediaTek linkIt groove para leer los datos del entorno externo como temperatura, humedad, luz, etc.

Json Json Json

Json se ha convertido en el estándar de facto para iot y ha sido ampliamente adoptado. Habiendo dicho sobre el requisito previo, comencemos por modelar los datos de nuestros sensores. El objetivo principal es capturar la mayor cantidad de datos posible y pasarlos al servidor. El servidor puede realizar todos los trabajos de elevación pesados, como análisis, conversión de datos, aprendizaje automático, etc.

El 'deseado' json será el estado deseado de los datos del sensor. Por ejemplo, cuando registramos la temperatura, el valor deseado de 24 significa que debemos sincronizar el valor con la nube con el valor de 24. Nuestros clientes, como la aplicación web o la aplicación móvil, se actualizarán a este valor.

Cuando queremos encender una luz decimos, el estado deseado como encendido. Significa que la luz está encendida o se encenderá. Todas nuestras aplicaciones cliente utilizarán este estado para reflejar los cambios al usuario. Quiero decir, el ícono en nuestra aplicación web se encenderá o apagará.

Este no es un estándar internacional, simplemente se me ocurrió esto. Por lo tanto, no dude en utilizar su propio formato conveniente.

Temperatura

  {"deviceid":"iot / myhome / livingroom / thermostat" "deseado":{"temperatura":"24", "humedad":"80"}, "timeutc":"2015-11 -23T00:41:48.824Z "," singedBy ":" localserver "}  

Micrófono

  {"deviceid":"iot / myhome / livingroom / mic" "deseado":{"duration":"66"}, "timeutc":"2015-11-23T00:41:48.824Z" , "singedBy":"localserver"}  

Distancia

  {"deviceid":"iot / myhome / livingroom / obstacle" "deseado":{"proximidad":"150"}, "timeutc":"2015-01-01", "singedBy":"servidor local"}  

PIR

  {"deviceid":"iot / myhome / livingroom / pir" "deseado":{"inicio de movimiento":"2500", "fin de movimiento":"5345"}, "timeutc":"2015 -11-23T00:41:48.824Z "," singedBy ":" localserver "}  

GPS

  {"deviceid":"iot / mydevice / location" "deseado":{"lat":"25.5", "long":"32.2"}, "timeutc":"2015-11-23T00 :41:48.824Z "," singedBy ":" localserver "}  

Humedad

  {"deviceid":"/ iot / myhome / garden /idity" "deseado":{"idity ":" 20 "}," timeutc ":" 2015-11-23T00:41:48.824Z "," singedBy ":" localserver "}  

Gas

  {"deviceid":"/ iot / myhome / kitchen / gas" "deseado":{"fuga":"No"}, "timeutc":"2015-11-23T00:41:48.824Z "," singedBy ":" localserver "}  

Ligero

  {"deviceid":"/ iot / myhome / livingroom / light" "deseado":{"duration":"60"}, "timeutc":"2015-11-23T00:41:48.824Z "," singedBy ":" localserver "}  

O usa esto,

Sala de estar

  {"deviceid":"/ iot / myhome / livingroom" "deseado":{"temperatura":"25", "humedad":"80", "ventana":"abrir", "puerta ":" cerrado "," ligero ":" 80 "," ruido ":" bajo "}}  

Dormitorio

  {"deviceid":"/ iot / myhome / bedroom" "deseado":{"temperatura":"24", "humedad":"70", "ventana":"cerrada", "puerta ":" cerrado "," ligero ":" 80 "," ac ":" en "" ruido ":" bajo "}}  

MediaTek - Receptor

Consulte el archivo ino adjunto a la sección de software para registrar los datos en el servidor local. Los datos del sensor se simulan, puede pasar la lectura real al objeto json respectivo

Servidor local

El servidor local agrega una sobrecarga, pero será útil de muchas maneras. Podemos hacer uso del servidor local como preprocesador para nuestros datos de iot. Los datos se pueden filtrar, sellar con la hora y firmar

Una pequeña PC y nodejs es una excelente opción para el servidor local. Podemos elegir cualquier computadora pequeña como raspberry pi, odriod, banana pi, beagle bone, etc. Elegí orange pi ($ 15) para este proyecto.

Configuración

Raspberry pi 2 o Orange Pi con cualquier tipo de sistema operativo linux que admita nodejs 5. He elegido orange pi con arch linux para arm7. Nodejs y npm instalados. Descargue mi iotapp de github y navegue a / your / local / path / iotapp y ejecute npm install. La aplicación básica expressjs comienza a escuchar en su puerto 3000.

Vaya a your-local-ip:3000 para comprobar si se muestra la vista predeterminada de expressjs. He creado estas apis para publicar los datos del sensor

/ iot / myhome / livingroom / thermostat - Temperature api

/ iot / myhome / livingroom / mic - Api de sonido

/ iot / myhome / livingroom / pir - API de sensor de presencia

/ iot / myhome / livingroom / distance - Api del sensor de distancia

/ iot / myhome / mydevice / location - gps tracker api

/ iot / myhome / jardín / humedad - api del sensor de humedad del suelo

/ iot / myhome / kitchen / gas - api del sensor de fugas de gas

/ iot / myhome / livingroom / light - api del sensor de luz

/ iot / myhome / livingroom - otra api para sala de estar

/ iot / myhome / bedroom - otra api para dormitorio


Para configurar el servidor local. Clona el código fuente iotapp de mi github. Modifique index.js para poner su dirección IP en la nube o nombre de dominio donde la aplicación aspnet5 está alojada en azure

Servidor remoto

La publicación de datos en la nube se ha vuelto popular hoy en día. Podemos comprar la suscripción de los datos de iot proporcionados como amazon, azure, spark fun, pubnub, estado inicial y muchos otros. He elegido azure para esta demostración. Se pueden desarrollar algoritmos de análisis de datos, minería de datos y aprendizaje automático para procesar nuestros datos.

Descarga iotwebapp desde mi github. Lo creé usando Visual Studio 2015 dirigido a asp.net5. Estas apis se configuraron para publicar los datos de iot. La API registra el iot en las tablas de almacenamiento de Azure

El parámetro deviceid se puede configurar para identificar la ubicación del sensor.

Estas api se han configurado

api / iot / myhome / thermostat - asp.net5 web api para registrar todos los datos del termostato

api / iot / myhome / micro- asp.net5 web api para registrar todos los datos del micrófono

api / iot / myhome / pir - asp.net5 web api para registrar todos los datos pir

api / iot / myhome / distance - asp.net5 web api para registrar todos los datos del sensor de distancia

api / iot / myhome / device / location - asp.net5 web api para registrar los datos del gps

api / iot / myhome /idity - asp.net5 web api para registrar los datos del sensor de humedad

api / iot / myhome / gas - asp.net5 web api para registrar los datos del sensor de gas

api / iot / myhome / light - asp.net5 web api para registrar todos los datos del sensor de luz

api / iot / myhome / livingroom - asp.net5 web api para registrar todos los atributos / datos de sensores de la sala de estar. podemos usar esta api para impulsar todos los valores del sensor.

api / iot / myhome / bedroom - igual que arriba, he creado uno para registrar los detalles de mi habitación

Para configurar el servidor remoto. Clona el código fuente iotwebapp de mi github. Crea una mesa de almacenamiento azul. Modifique IoTController.cs y coloque el nombre y la clave de la cuenta de la tabla de almacenamiento azul. Utilice este nombre de dominio o IP en el servidor local

Conclusión

Hay muchas áreas para refactorizar en el código. Siéntete libre de modificar y avísame si te golpean.

Código

  • MediaTekRx
  • nodejs - servidor local
  • ThermoStatController.cs
  • PIRController.cs
  • MoistureController.cs
  • LivingRoomController.cs
  • LightController.cs
  • GPSController.cs
  • GasController.cs
  • DistanceController.cs
  • BedRoomController.cs
MediaTekRx C / C ++
Media Tek como receptor. Boceto a datos locales al servidor local
 / * Cliente web Este boceto se conecta a un sitio web usando la funcionalidad Wi-Fi en la plataforma MediaTek LinkIt. Cambie la macro WIFI_AP, WIFI_PASSWORD, WIFI_AUTH y SITE_URL en consecuencia. creado el 13 de julio de 2010 por dlf (Metodo2 srl) modificado el 31 de mayo de 2012 por Tom Igoe modificado el 20 de agosto de 2014 por MediaTek Inc. * / # include  #include  #include  #include  #define WIFI_AP "your ap" #define WIFI_PASSWORD "your password" #define WIFI_AUTH LWIFI_WPA // choose from LWIFI_OPEN, LWIFI_WPA, or LWIFI_WEP. # Define SITE_URL "your ip" // your ip address or azure nombre de dominioLWiFiClient c; configuración vacía () {LWiFi.begin (); Serial.begin (115200); // sigue intentando hasta que te conectes a AP Serial.println ("Conectando a AP"); while (0 ==LWiFi.connect (WIFI_AP, LWiFiLoginInfo (WIFI_AUTH, WIFI_PASSWORD))) {retraso (1000); } // sigue intentándolo hasta que te conectes al sitio web Serial.println ("Conectando al sitio web"); while (0 ==c.connect (SITE_URL, 3000)) {Serial.println ("Reconexión al sitio web"); retraso (1000); }} boolean disabledMsg =false; void loop () {// Asegúrate de que estamos conectados y descarga el contenido de la respuesta en Serial while (! c) {Serial.println ("Servidor desconectado .."); // sigue intentándolo hasta que te conectes al sitio web Serial.println ("Conectando al sitio web"); while (0 ==c.connect (SITE_URL, 3000)) {Serial.println ("Reconexión al sitio web"); retraso (1000); }} Serial.println ("Temperatura de lectura ..."); updateTemperature (); retraso (3000); Serial.println ("Detectando sonido ..."); updateSound (); retraso (3000); Serial.println ("Detectando movimiento de personas ..."); updatePIR (); retraso (3000); Serial.println ("Detectando obstáculo ..."); updateDistance (); retraso (3000); Serial.println ("Actualizando la ubicación del dispositivo ..."); updateGPSTracker (); retraso (3000); Serial.println ("Calculando la humedad del suelo ..."); updateMoisture (); retraso (3000); Serial.println ("Detectando fugas de gas ..."); updateGasLeak (); retraso (3000); Serial.println ("Grabando intensidad de luz ..."); updateLightIntensity (); retraso (3000); updateLivingroomAttributes (); retraso (3000); updateBedroomAttributes (); delay (3000);} void writeToConsole () {// Asegúrate de que estamos conectados y descarga el contenido de la respuesta en Serial while (c) {int v =c.read (); if (v! =-1) {Serial.print ((char) v); }} Serial.println (); Serial.println ("Servidor desconectado ..."); // sigue intentándolo hasta que te conectes al sitio web Serial.println ("Conectando al sitio web"); while (0 ==c.connect (SITE_URL, 3000)) {Serial.println ("Reconexión al sitio web"); retraso (1000); }} void updatePIR () {int s largos sin firmar; DynamicJsonBuffer jsonBuffer; JsonObject &root =jsonBuffer.createObject (); JsonObject &deseado =root.createNestedObject ("deseado"); root ["deviceid"] ="/ iot / myhome / livingroom / pir"; // asumir la unidad predeterminada ms deseada ["motionstart"] =String (random (0,1000)); deseado ["motionend"] =Cadena (aleatorio (1000,10000)); String len =String (root.measureLength ()); c.println ("POST / iot / myhome / livingroom / pir HTTP / 1.1"); c.println ("Host:" SITE_URL); c.println ("Tipo de contenido:aplicación / json"); c.println ("Cache-Control:no-cache"); c.print ("Contenido-Longitud:"); c.println (len); c.println ("Conexión:cerrar"); c.println (); root.printTo (c); root.printTo (Serial); // lógica para detectar la respuesta lenta del servidor y publicar la solicitud nuevamente sin esperar una respuesta muerta s =millis (); // esperando la respuesta del servidor Serial.println ("esperando respuesta HTTP:"); while (! c. disponible ()) {retraso (100); if ((millis () - s> 3000)) {Serial.println (); Serial.println ("El servidor no responde ..."); descanso; }} Serial.println ("Llamando a escribir en la consola ..."); writeToConsole (); } void updateDistance () {int largo sin firmar; DynamicJsonBuffer jsonBuffer; JsonObject &root =jsonBuffer.createObject (); JsonObject &deseado =root.createNestedObject ("deseado"); root ["deviceid"] ="/ iot / myhome / livingroom / distanceensor"; // asumir la unidad predeterminada cm deseada ["obstáculo"] =Cadena (aleatorio (50,450)); String len =String (root.measureLength ()); c.println ("POST / iot / myhome / livingroom / distancia HTTP / 1.1"); c.println ("Host:" SITE_URL); c.println ("Tipo de contenido:aplicación / json"); c.println ("Cache-Control:no-cache"); c.print ("Contenido-Longitud:"); c.println (len); c.println ("Conexión:cerrar"); c.println (); root.printTo (c); root.printTo (Serial); s =milis (); // esperando la respuesta del servidor Serial.println ("esperando respuesta HTTP:"); while (! c. disponible ()) {retraso (100); if ((millis () - s> 3000)) {Serial.println (); Serial.println ("El servidor no responde ..."); descanso; }} Serial.println ("Llamando a escribir en la consola ..."); writeToConsole (); } void updateGPSTracker () {int s largos sin firmar; DynamicJsonBuffer jsonBuffer; JsonObject &root =jsonBuffer.createObject (); JsonObject &deseado =root.createNestedObject ("deseado"); root ["deviceid"] ="/ iot / mydevice"; deseado ["lat"] =Cadena (aleatorio (20,25)); deseado ["largo"] =Cadena (aleatorio (22,27)); String len =String (root.measureLength ()); c.println ("POST / iot / mydevice / location HTTP / 1.1"); c.println ("Host:" SITE_URL); c.println ("Tipo de contenido:aplicación / json"); c.println ("Cache-Control:no-cache"); c.print ("Contenido-Longitud:"); c.println (len); c.println ("Conexión:cerrar"); c.println (); root.printTo (c); root.printTo (Serial); s =milis (); // esperando la respuesta del servidor Serial.println ("esperando respuesta HTTP:"); while (! c. disponible ()) {retraso (100); if ((millis () - s> 3000)) {Serial.println (); Serial.println ("El servidor no responde ..."); descanso; }} Serial.println ("Llamando a escribir en la consola ..."); writeToConsole ();} void updateMoisture () {int long unsigned int; DynamicJsonBuffer jsonBuffer; JsonObject &root =jsonBuffer.createObject (); JsonObject &deseado =root.createNestedObject ("deseado"); root ["deviceid"] ="/ iot / mi casa / jardín / humedad"; // asume la unidad deseada por defecto ["humedad"] =String (random (40,60)); String len =String (root.measureLength ()); c.println ("POST / iot / myhome / jardín / humedad HTTP / 1.1"); c.println ("Host:" SITE_URL); c.println ("Tipo de contenido:aplicación / json"); c.println ("Cache-Control:no-cache"); c.print ("Contenido-Longitud:"); c.println (len); c.println ("Conexión:cerrar"); c.println (); root.printTo (c); root.printTo (Serial); s =milis (); // esperando la respuesta del servidor Serial.println ("esperando respuesta HTTP:"); while (! c. disponible ()) {retraso (100); if ((millis () - s> 3000)) {Serial.println (); Serial.println ("El servidor no responde ..."); descanso; }} Serial.println ("Llamando a escribir en la consola ..."); writeToConsole (); } void updateGasLeak () {DynamicJsonBuffer jsonBuffer; JsonObject &root =jsonBuffer.createObject (); JsonObject &deseado =root.createNestedObject ("deseado"); deseado ["fuga"] ="no"; root ["deviceid"] ="/ iot / myhome / kitchen / gas"; int s largos sin firmar; String len =String (root.measureLength ()); c.println ("POST / iot / myhome / cocina / gas HTTP / 1.1"); c.println ("Host:" SITE_URL); c.println ("Tipo de contenido:aplicación / json"); c.println ("Cache-Control:no-cache"); c.print ("Contenido-Longitud:"); c.println (len); c.println ("Conexión:cerrar"); c.println (); root.printTo (c); root.printTo (Serial); s =milis (); // esperando la respuesta del servidor Serial.println ("esperando respuesta HTTP:"); while (! c. disponible ()) {retraso (100); if ((millis () - s> 3000)) {Serial.println (); Serial.println ("El servidor no responde ..."); descanso; }} Serial.println ("Llamando a escribir en la consola ..."); writeToConsole (); } void updateLightIntensity () {DynamicJsonBuffer jsonBuffer; JsonObject &root =jsonBuffer.createObject (); JsonObject &deseado =root.createNestedObject ("deseado"); deseado ["intensidad"] ="80"; root ["deviceid"] ="/ iot / myhome / livingroom / light"; int s largos sin firmar; String len =String (root.measureLength ()); c.println ("POST / iot / myhome / livingroom / light HTTP / 1.1"); c.println ("Host:" SITE_URL); c.println ("Tipo de contenido:aplicación / json"); c.println ("Cache-Control:no-cache"); c.print ("Contenido-Longitud:"); c.println (len); c.println ("Conexión:cerrar"); c.println (); root.printTo (c); root.printTo (Serial); s =milis (); // esperando la respuesta del servidor Serial.println ("esperando respuesta HTTP:"); while (! c. disponible ()) {retraso (100); if ((millis () - s> 3000)) {Serial.println (); Serial.println ("El servidor no responde ..."); descanso; }} Serial.println ("Llamando a escribir en la consola ..."); writeToConsole (); } void updateLivingroomAttributes () {DynamicJsonBuffer jsonBuffer; JsonObject &root =jsonBuffer.createObject (); root ["deviceid"] ="/ iot / myhome / livingroom"; JsonObject &deseado =root.createNestedObject ("deseado"); // API alternativa para los atributos de la sala de estar de loggin todos a la vez deseado ["window"] ="open"; deseado ["puerta"] ="cerrado"; deseado ["ac"] ="apagado"; deseado ["temperatura"] =Cadena (aleatorio (24,28)); deseado ["humedad"] =Cadena (aleatorio (60,65)); int s largos sin firmar; String len =String (root.measureLength ()); c.println ("POST / iot / myhome / livingroom HTTP / 1.1"); c.println ("Host:" SITE_URL); c.println ("Tipo de contenido:aplicación / json"); c.println ("Cache-Control:no-cache"); c.print ("Contenido-Longitud:"); c.println (len); c.println ("Conexión:cerrar"); c.println (); root.printTo (c); root.printTo (Serial); s =milis (); // esperando la respuesta del servidor Serial.println ("esperando respuesta HTTP:"); while (! c. disponible ()) {retraso (100); if ((millis () - s> 3000)) {Serial.println (); Serial.println ("El servidor no responde ..."); descanso; }} Serial.println ("Llamando a escribir en la consola ..."); writeToConsole (); } void updateBedroomAttributes () {DynamicJsonBuffer jsonBuffer; JsonObject &root =jsonBuffer.createObject (); root ["deviceid"] ="/ iot / myhome / bedroom"; JsonObject &deseado =root.createNestedObject ("deseado"); // API alternativa para los atributos de la sala de estar de loggin todos a la vez deseado ["window"] ="open"; deseado ["puerta"] ="cerrado"; deseado ["ac"] ="apagado"; deseado ["temperatura"] =Cadena (aleatorio (22,23)); deseado ["humedad"] =Cadena (aleatorio (75,80)); int s largos sin firmar; String len =String (root.measureLength ()); c.println ("POST / iot / myhome / bedroom HTTP / 1.1"); c.println ("Host:" SITE_URL); c.println ("Tipo de contenido:aplicación / json"); c.println ("Cache-Control:no-cache"); c.print ("Contenido-Longitud:"); c.println (len); c.println ("Conexión:cerrar"); c.println (); root.printTo (c); root.printTo (Serial); s =milis (); // esperando la respuesta del servidor Serial.println ("esperando respuesta HTTP:"); while (! c. disponible ()) {retraso (100); if ((millis () - s> 3000)) {Serial.println (); Serial.println ("El servidor no responde ..."); descanso; }} Serial.println ("Llamando a escribir en la consola ..."); writeToConsole (); } void updateSound () {int s largos sin firmar; long unsigned int e; DynamicJsonBuffer jsonBuffer; JsonObject &root =jsonBuffer.createObject (); JsonObject &deseado =root.createNestedObject ("deseado"); deseado ["intensidad"] =Cadena (aleatorio (40,80)); root ["deviceid"] ="/ iot / myhome / livingroom / mic"; root ["timeutc"] =""; root ["firmado por"] =""; String len =String (root.measureLength ()); c.println ("POST / iot / myhome / livingroom / mic HTTP / 1.1"); c.println ("Host:" SITE_URL); c.println ("Tipo de contenido:aplicación / json"); c.println ("Cache-Control:no-cache"); c.print ("Contenido-Longitud:"); c.println (len); c.println ("Conexión:cerrar"); c.println (); root.printTo (c); root.printTo (Serial); s =milis (); // esperando la respuesta del servidor Serial.println ("esperando respuesta HTTP:"); while (! c. disponible ()) {retraso (100); if ((millis () - s> 3000)) {Serial.println (); Serial.println ("El servidor no responde ..."); descanso; }} Serial.println ("Llamando a escribir en la consola ..."); writeToConsole ();} void updateTemperature () {long unsigned int s; long unsigned int e; DynamicJsonBuffer jsonBuffer; JsonObject &root =jsonBuffer.createObject (); JsonObject &deseado =root.createNestedObject ("deseado"); deseado ["temperatura"] =Cadena (aleatorio (20,40)); deseado ["humedad"] =Cadena (aleatorio (60,80)); root ["deviceid"] ="/ iot / myhome / livingroom / thermostat"; root ["timeutc"] =""; root ["firmado por"] =""; String len =String (root.measureLength ()); c.println ("POST / iot / myhome / livingroom / thermostat HTTP / 1.1"); c.println ("Host:" SITE_URL); c.println ("Tipo de contenido:aplicación / json"); c.println ("Cache-Control:no-cache"); c.print ("Contenido-Longitud:"); c.println (len); c.println ("Conexión:cerrar"); c.println (); root.printTo (c); root.printTo (Serial); s =milis (); // esperando la respuesta del servidor Serial.println ("esperando respuesta HTTP:"); while (! c. disponible ()) {retraso (100); if ((millis () - s> 3000)) {Serial.println (); Serial.println ("El servidor no responde ..."); descanso; }} Serial.println ("Llamando a escribir en la consola ..."); writeToConsole (); } 
nodejs - servidor local JavaScript
El index.js que tiene las rutas para recibir los datos de Media Tek
 var express =require ('express'); var router =express.Router (); var buf =require ('buffer'); var request =require ("request"); // reemplace su-ip-o-nombre-de-dominio con su dirección IP real o nombre de dominio // ejemplo iot.azurewebsites.com//example yourdomainname.com//example 47.12.67.16// accept Solicitud POST en homepagerouter.post ('/ iot / myhome / livingroom / thermostat', function (req, res) {var state =req.body; state.timeutc =new Date (); state.signedby ="orangepi"; console.log (estado); var options ={method:'POST', url:'http:// your-ip-or-domain-name / api / iot / myhome / livingroom / thermostat', headers:{'cache -control ':' no-cache ',' content-type ':' application / json '}, body:state, json:true}; request (options, function (error, response, body) {if (error) throw new Error (error); console.log (body);}); res.send ('Se registró la temperatura de la sala de estar');}); // acepta la solicitud POST microuter.post ('/ iot / myhome / livingroom / mic' , divertida ction (req, res) {var state =req.body; state.timeutc =nueva fecha (); state.signedby ="orangepi"; console.log (estado); var options ={método:'POST', url:'http:// su-ip-o-nombre-de-dominio / api / iot / myhome / livingroom / micrófono', encabezados:{'cache-control':'no- cache ',' content-type ':' application / json '}, body:state, json:true}; request (opciones, función (error, respuesta, cuerpo) {si (error) arrojar nuevo Error (error); console.log (cuerpo);}); res.send ('Grabación de la intensidad del sonido de la sala de estar');}); // acepta la solicitud POST pirrouter.post ('/ iot / myhome / livingroom / pir', function (req, res) {var state =req.body; state.timeutc =new Date (); state.signedby ="orangepi"; console.log (estado); var options ={método:'POST', url:'http:// tu-ip-o-nombre-de-dominio / api / iot / myhome / livingroom / pir ', encabezados:{' cache-control ':' no-cache ',' content-type ':' application / json '}, body:state, json:true}; solicitud (opciones, función (error, respuesta, cuerpo) {if (error) throw new Error (error); console.log (body);}); res.send ('Se registró el movimiento pir de la sala de estar');}); / / accept POST request distancerouter.post ('/ iot / myhome / livingroom / distance', function (req, res) {var state =req.body; state.timeutc =new Date (); state.signedby ="orangepi"; console.log (estado); var options ={method:'POST', url:'http:// your-ip-or-domain-name / api / iot / myhome / livingroom / distance', headers:{'cache -control ':' no-cache ',' content-type ':' application / json '}, body:state, js on:true}; request (opciones, función (error, respuesta, cuerpo) {si (error) arrojar nuevo Error (error); console.log (cuerpo);}); res.send ('Obstáculo de la sala registrado');}); // acepta la solicitud POST gpsrouter.post ('/ iot / mydevice / location', function (req, res) {var state =req.body; state.timeutc =new Date (); state.signedby ="orangepi"; console.log (state); var options ={method:'POST', url:'http:// your-ip-or-domain-name / api / iot / mydevice / location / gps ', headers:{' cache-control ':' no-cache ',' content-type ':' application / json '}, body:state, json:true}; request (options, function (error, response, body) {if (error) throw new Error (error); console.log (body);}); res.send ('ubicación del dispositivo registrada');}); // acepta la solicitud POST enrutador de humedad .post ('/ iot / myhome / garden / humedad', function (req, res) {var state =req.body; state.timeutc =new Date (); state.signedby ="orangepi"; console.log (state ); var options ={método:'POST', url:'http:// tu-ip-o-nombre-de-dominio / api / iot / myhome / jardín / humedad', encabezados:{'cache-control':' no-cache', 'content-type':'application/json' }, body:state, json:true }; request(options, function (error, response, body) { if (error) throw new Error(error); console.log(body); }); res.send('Garden moisture level recorded');});// accept POST request gasrouter.post('/iot/myhome/kitchen/gas', function (req, res) { var state =req.body; state.timeutc =new Date(); state.signedby ="orangepi"; console.log(state); var options ={ method:'POST', url:'http://your-ip-or-domain-name/api/iot/myhome/kitchen/gas', headers:{ 'cache-control':'no-cache', 'content-type':'application/json' }, body:state, json:true }; request(options, function (error, response, body) { if (error) throw new Error(error); console.log(body); }); res.send('Gas leak information recorded');});// accept POST request lightrouter.post('/iot/myhome/livingroom/light', function (req, res) { var state =req.body; state.timeutc =new Date(); state.signedby ="orangepi"; console.log(state); var options ={ method:'POST', url:'http://your-ip-or-domain-name/api/iot/myhome/livingroom/light', headers:{ 'cache-control':'no-cache', 'content-type':'application/json' }, body:state, json:true }; request(optio ns, function (error, response, body) { if (error) throw new Error(error); console.log(body); }); res.send('Light intensity recorded');});// accept POST request livingroomrouter.post('/iot/myhome/livingroom', function (req, res) { var state =req.body; state.timeutc =new Date(); state.signedby ="orangepi"; console.log(state); var options ={ method:'POST', url:'http://your-ip-or-domain-name/api/iot/myhome/room/livingroom', headers:{ 'cache-control':'no-cache', 'content-type':'application/json' }, body:state, json:true }; request(options, function (error, response, body) { if (error) throw new Error(error); console.log(body); }); res.send('Livingroom attributes recorded');});// accept POST request bedroomrouter.post('/iot/myhome/bedroom', function (req, res) { var state =req.body; state.timeutc =new Date(); state.signedby ="orangepi"; console.log(state); var options ={ method:'POST', url:'http://your-ip-or-domain-name/api/iot/myhome/room/bedroom', headers:{ 'cache-control':'no-cache', 'content-type':'application/json' }, body:state, json:true }; request(options, fu nction (error, response, body) { if (error) throw new Error(error); console.log(body); }); res.send('Bedroom attributes recorded');});// accept PUT request at /userrouter.put('/user', function (req, res) { res.send('Got a PUT request at /user');});// accept DELETE request at /user//router.delete('/user', function (req, res) {// res.send('Got a DELETE request at /user');//});/* GET home page. */router.get('/', function(req, res, next) { res.render('index', { title:'Express' });});module.exports =router;
ThermoStatController.csC#
api to log temperature data to the cloud
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNet.Mvc;using Newtonsoft.Json;using Microsoft.WindowsAzure.Storage;using Microsoft.WindowsAzure.Storage.Auth;using Microsoft.WindowsAzure.Storage.Table;// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860namespace iotwebapp.Controllers{ [Route("api/iot/myhome/livingroom/[Controller]")] public class ThermoStatController :IoTController { // GET:// public IActionResult Index() { return View(); } [HttpPost] public IActionResult Post([FromBody]IotTemperature iotTemperature) { // Create the table client. CloudTableClient tableClient =storageAccount.CreateCloudTableClient(); // Create the CloudTable object that represents the "people" table. CloudTable table =tableClient.GetTableReference("iot"); iotTemperature.PartitionKey ="thermostat"; iotTemperature.RowKey =Guid.NewGuid().ToString(); // Create the TableOperation object that inserts the customer entity. TableOperation insertOperation =TableOperation.Insert(iotTemperature); // Execute the insert operation. table.Execute(insertOperation); return Ok("Temperature data logged to azure cloud.."); } } public class IotTemperature :TableEntity { public string deviceid { get; colocar; } public string timeutc { get; colocar; } public string signedby { get; colocar; } public string state { get { return JsonConvert.SerializeObject(this.desired); } set {; } } public Desired desired { get; colocar; } public class Desired { public string temperature { get; colocar; } public string humidity { get; colocar; }}}} 
PIRController.csC#
api to log presence sensor data to azure
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNet.Mvc;using Microsoft.WindowsAzure.Storage.Table;using Newtonsoft.Json;// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860namespace iotwebapp.Controllers{ [Route("api/iot/myhome/livingroom/[Controller]")] public class PIRController :IoTController { [HttpPost] public IActionResult Post([FromBody]IotPIR iotPIR) { // Create the table client. CloudTableClient tableClient =storageAccount.CreateCloudTableClient(); // Create the CloudTable object that represents the "people" table. CloudTable table =tableClient.GetTableReference("iot"); iotPIR.PartitionKey ="pir"; iotPIR.RowKey =Guid.NewGuid().ToString(); // Create the TableOperation object that inserts the customer entity. TableOperation insertOperation =TableOperation.Insert(iotPIR); // Execute the insert operation. table.Execute(insertOperation); return Ok("PIR data logged to azure cloud.."); } } public class IotPIR :TableEntity { public string deviceid { get; colocar; } public string timeutc { get; colocar; } public string signedby { get; colocar; } public string state { get { return JsonConvert.SerializeObject(this.desired); } set {; } } public Desired desired { get; colocar; } public class Desired { public string motionstart { get; colocar; } public string motionend { get; colocar; }}}} 
MoistureController.csC#
api to log soil moisture data to azure
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNet.Mvc;using Microsoft.WindowsAzure.Storage.Table;using Newtonsoft.Json;// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860namespace iotwebapp.Controllers{ [Route("api/iot/myhome/garden/[Controller]")] public class MoistureController :IoTController { [HttpPost] public IActionResult Post([FromBody]IotMoisture iotMoisture) { // Create the table client. CloudTableClient tableClient =storageAccount.CreateCloudTableClient(); // Create the CloudTable object that represents the "people" table. CloudTable table =tableClient.GetTableReference("iot"); iotMoisture.PartitionKey ="moisture"; iotMoisture.RowKey =Guid.NewGuid().ToString(); // Create the TableOperation object that inserts the customer entity. TableOperation insertOperation =TableOperation.Insert(iotMoisture); // Execute the insert operation. table.Execute(insertOperation); return Ok("Moisture data logged to azure cloud.."); } } public class IotMoisture :TableEntity { public string deviceid { get; colocar; } public string timeutc { get; colocar; } public string signedby { get; colocar; } public string state { get { return JsonConvert.SerializeObject(this.desired); } set {; } } public Desired desired { get; colocar; } public class Desired { public string moisture { get; colocar; } } }}
LivingRoomController.csC#
api to log all living room sensor data to azure
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNet.Mvc;using Microsoft.WindowsAzure.Storage.Table;using Newtonsoft.Json;// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860namespace iotwebapp.Controllers{ [Route("api/iot/myhome/room/[controller]")] public class LivingRoomController :IoTController { [HttpPost] public IActionResult Post([FromBody]IotLivingRoom iotLivingRoom) { // Create the table client. CloudTableClient tableClient =storageAccount.CreateCloudTableClient(); // Create the CloudTable object that represents the "people" table. CloudTable table =tableClient.GetTableReference("iot"); iotLivingRoom.PartitionKey ="livingroom"; iotLivingRoom.RowKey =Guid.NewGuid().ToString(); // Create the TableOperation object that inserts the customer entity. TableOperation insertOperation =TableOperation.Insert(iotLivingRoom); // Execute the insert operation. table.Execute(insertOperation); return Ok("Living room attributes logged to azure cloud.."); } } public class IotLivingRoom :TableEntity { public string deviceid { get; colocar; } public string timeutc { get; colocar; } public string signedby { get; colocar; } public string state { get { return JsonConvert.SerializeObject(this.desired); } set {; } } public Desired desired { get; colocar; } public class Desired { public string window { get; colocar; } public string door { get; colocar; } public string ac { get; colocar; } public string temperature { get; colocar; } public string humidity { get; colocar; }}}} 
LightController.csC#
api to log light sensor data to azure
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNet.Mvc;using Microsoft.WindowsAzure.Storage.Table;using Newtonsoft.Json;// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860namespace iotwebapp.Controllers{ [Route("api/iot/myhome/livingroom/[Controller]")] public class LightController :IoTController { [HttpPost] public IActionResult Post([FromBody]IotLight iotLight) { // Create the table client. CloudTableClient tableClient =storageAccount.CreateCloudTableClient(); // Create the CloudTable object that represents the "people" table. CloudTable table =tableClient.GetTableReference("iot"); iotLight.PartitionKey ="light"; iotLight.RowKey =Guid.NewGuid().ToString(); // Create the TableOperation object that inserts the customer entity. TableOperation insertOperation =TableOperation.Insert(iotLight); // Execute the insert operation. table.Execute(insertOperation); return Ok("Light intensity logged to azure cloud.."); } } public class IotLight :TableEntity { public string deviceid { get; colocar; } public string timeutc { get; colocar; } public string signedby { get; colocar; } public string state { get { return JsonConvert.SerializeObject(this.desired); } set {; } } public Desired desired { get; colocar; } public class Desired { public string intensity { get; colocar; } } }}
GPSController.csC#
api to log gps data to azure
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNet.Mvc;using Microsoft.WindowsAzure.Storage.Table;using Newtonsoft.Json;// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860namespace iotwebapp.Controllers{ [Route("api/iot/mydevice/location/[Controller]")] public class GPSController :IoTController { [HttpPost] public IActionResult Post([FromBody]IotGPS iotGPS) { // Create the table client. CloudTableClient tableClient =storageAccount.CreateCloudTableClient(); // Create the CloudTable object that represents the "people" table. CloudTable table =tableClient.GetTableReference("iot"); iotGPS.PartitionKey ="gps"; iotGPS.RowKey =Guid.NewGuid().ToString(); // Create the TableOperation object that inserts the customer entity. TableOperation insertOperation =TableOperation.Insert(iotGPS); // Execute the insert operation. table.Execute(insertOperation); return Ok("GPS data logged to azure cloud.."); } } public class IotGPS :TableEntity { public string deviceid { get; colocar; } public string timeutc { get; colocar; } public string signedby { get; colocar; } public string state { get { return JsonConvert.SerializeObject(this.desired); } set {; } } public Desired desired { get; colocar; } public class Desired { public string lat { get; colocar; } [JsonProperty("long")] public string longitude { get; colocar; }}}} 
GasController.csC#
api to log gas leakage data to azure
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNet.Mvc;using Microsoft.WindowsAzure.Storage.Table;using Newtonsoft.Json;// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860namespace iotwebapp.Controllers{ [Route("api/iot/myhome/kitchen/[Controller]")] public class GasController :IoTController { [HttpPost] public IActionResult Post([FromBody]IotGas iotGas) { // Create the table client. CloudTableClient tableClient =storageAccount.CreateCloudTableClient(); // Create the CloudTable object that represents the "people" table. CloudTable table =tableClient.GetTableReference("iot"); iotGas.PartitionKey ="gas"; iotGas.RowKey =Guid.NewGuid().ToString(); // Create the TableOperation object that inserts the customer entity. TableOperation insertOperation =TableOperation.Insert(iotGas); // Execute the insert operation. table.Execute(insertOperation); return Ok("Gas leak information logged to azure cloud.."); } } public class IotGas :TableEntity { public string deviceid { get; colocar; } public string timeutc { get; colocar; } public string signedby { get; colocar; } public string state { get { return JsonConvert.SerializeObject(this.desired); } set {; } } public Desired desired { get; colocar; } public class Desired { public string leak { get; colocar; } } }}
DistanceController.csC#
api to log ultrasonic distance sensor data to azure
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNet.Mvc;using Microsoft.WindowsAzure.Storage.Table;using Newtonsoft.Json;// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860namespace iotwebapp.Controllers{ [Route("api/iot/myhome/livingroom/[Controller]")] public class DistanceController :IoTController { [HttpPost] public IActionResult Post([FromBody]IotDistance iotDistance) { // Create the table client. CloudTableClient tableClient =storageAccount.CreateCloudTableClient(); // Create the CloudTable object that represents the "people" table. CloudTable table =tableClient.GetTableReference("iot"); iotDistance.PartitionKey ="distance"; iotDistance.RowKey =Guid.NewGuid().ToString(); // Create the TableOperation object that inserts the customer entity. TableOperation insertOperation =TableOperation.Insert(iotDistance); // Execute the insert operation. table.Execute(insertOperation); return Ok("Obstacle data logged to azure cloud.."); } } public class IotDistance :TableEntity { public string deviceid { get; colocar; } public string timeutc { get; colocar; } public string signedby { get; colocar; } public string state { get { return JsonConvert.SerializeObject(this.desired); } set {; } } public Desired desired { get; colocar; } public class Desired { public string obstacle { get; colocar; }}}} 
BedRoomController.csC#
api to log all bedroom sensor data to azure
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNet.Mvc;using Microsoft.WindowsAzure.Storage.Table;using Newtonsoft.Json;// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860namespace iotwebapp.Controllers{ [Route("api/iot/myhome/room/[controller]")] public class BedRoomController :IoTController { [HttpPost] public IActionResult Post([FromBody]IotBedRoom iotBedRoom) { // Create the table client. CloudTableClient tableClient =storageAccount.CreateCloudTableClient(); // Create the CloudTable object that represents the "people" table. CloudTable table =tableClient.GetTableReference("iot"); iotBedRoom.PartitionKey ="bedroom"; iotBedRoom.RowKey =Guid.NewGuid().ToString(); // Create the TableOperation object that inserts the customer entity. TableOperation insertOperation =TableOperation.Insert(iotBedRoom); // Execute the insert operation. table.Execute(insertOperation); return Ok("Bed room attributes logged to azure cloud.."); } } public class IotBedRoom :TableEntity { public string deviceid { get; colocar; } public string timeutc { get; colocar; } public string signedby { get; colocar; } public string state { get { return JsonConvert.SerializeObject(this.desired); } set {; } } public Desired desired { get; colocar; } public class Desired { public string window { get; colocar; } public string door { get; colocar; } public string ac { get; colocar; } public string temperature { get; colocar; } public string humidity { get; colocar; }}}} 
Media Tek Smart home - Source code for data logging
source code for nodejsapp, aspnet5 and mediatek receiver inohttps://github.com/syediddi/iot-mediatek-linkIt

Esquemas

Transmit radio signal from arduino Transmit radio signal via Xbee from arduino without shield Transmit radio signals from arduino

Proceso de manufactura

  1. Datos inteligentes:la próxima frontera en IoT
  2. 433MHz Smart Home Controller con Sensorflare y RaspberryPi
  3. RASPBERRY PI HOME AUTOMATION
  4. Smart Bartender
  5. Los hospitales inteligentes del mañana necesitan un software más inteligente
  6. La brecha de habilidades para el hogar inteligente
  7. Los beneficios de la interconectividad en el lugar de trabajo
  8. Sea inteligente:el futuro de su hogar
  9. El sueño de la fábrica inteligente
  10. Conectividad doméstica inteligente:3 pasos para superar los principales obstáculos
  11. Actualizaciones de hogares inteligentes para la vida moderna