Страница 1 из 1

Поиск литературы

Добавлено: Пт авг 05, 2016 12:03 pm
PavloP
Доброго времени суток
Недавно увидел проект Majordomo в ютубе и весьма заинтересовался. Установил его на BananaPi(улучшенный клон Raspberry Pi B+), благо инструкции весьма подробные.
Интересно самому создавать датчики, но пока не сильно понимаю протоколы соединения с Majordomo. Не могли бы вы посоветовать где почитать про MQTT или другие подходящие протоколы? В частности интересует реализация этих протоколов в Arduino IDE, так как удобнее всего датчики цеплять на ESP8266, а я слишком ленивый, чтобы учить Lua, и подключение датчиков непосредственно к плате на которой установлен Majordomo(ну или реализация на PHP, если прямое подключение невозможно)

Re: Поиск литературы

Добавлено: Пт авг 05, 2016 2:45 pm
sergejey
Если вы хотите отправлять данные с устройства в систему, то подойдёт обычный HTTP-запрос.

Ниже скетч прошивки для ESP8266, реализующий отправку в систему IR-кода с приёмника на устройстве. По аналогии можно сделать периодическую отправку данных температуры и прочее.
СпойлерПоказать

Код: Выделить всё

/*
 * IRremoteESP8266: IRrecvDumpV2 - dump details of IR codes with IRrecv
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * Version 0.1 Sept, 2015
 * Based on Ken Shirriff's IrsendDemo Version 0.1 July, 2009, Copyright 2009 Ken Shirriff, http://arcfn.com
 */

#include <IRremoteESP8266.h>
#include <ESP8266WiFi.h>

int RECV_PIN = D2; //an IR detector/demodulator is connected to GPIO pin D2

const char* ssid     = "wifisid";
const char* password = "wifipassword";

const char* host = "192.168.0.17"; // server address

IRrecv irrecv(RECV_PIN);


void WIFI_Connect() {
  digitalWrite(LED_BUILTIN, LOW);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.disconnect(); 
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    digitalWrite(LED_BUILTIN, LOW);
    delay(500);
    Serial.print(".");
    digitalWrite(LED_BUILTIN, HIGH);
  }

  Serial.println("");
  Serial.println("WiFi connected");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  digitalWrite(LED_BUILTIN, HIGH);  
}

void  setup ( )
{
  pinMode(LED_BUILTIN, OUTPUT);  
  Serial.begin(9600);   // Status message will be sent to PC at 9600 baud
  irrecv.enableIRIn();  // Start the receiver

  WIFI_Connect();
    
}

//+=============================================================================
// Display IR code
//
String ircode (decode_results *results)
{
  // Panasonic has an Address
  if (results->decode_type == PANASONIC) {
    Serial.print(results->panasonicAddress, HEX);
    Serial.print(":");
  }

  // Print Code
  char ss[40];
  sprintf(ss,"%x",results->value);
  return ss;
}

//+=============================================================================
// Display encoding type
//
String encoding (decode_results *results)
{
  switch (results->decode_type) {
    default:
    case UNKNOWN:      return("UNKNOWN");       break ;
    case NEC:          return("NEC");           break ;
    case SONY:         return("SONY");          break ;
    case RC5:          return("RC5");           break ;
    case RC6:          return("RC6");           break ;
    case DISH:         return("DISH");          break ;
    case SHARP:        return("SHARP");         break ;
    case JVC:          return("JVC");           break ;
    case SANYO:        return("SANYO");         break ;
    case MITSUBISHI:   return("MITSUBISHI");    break ;
    case SAMSUNG:      return("SAMSUNG");       break ;
    case LG:           return("LG");            break ;
    case WHYNTER:      return("WHYNTER");       break ;
    case AIWA_RC_T501: return("AIWA_RC_T501");  break ;
    case PANASONIC:    return("PANASONIC");     break ;
  }
}

//+=============================================================================
// Dump out the decode_results structure.
//
void  dumpInfo (decode_results *results)
{
  // Show Encoding standard
  Serial.print("Encoding  : ");
  encoding(results);
  Serial.println("");

  // Show Code & length
  Serial.print("Code      : ");
  ircode(results);
  Serial.print(" (");
  Serial.print(results->bits, DEC);
  Serial.println(" bits)");

  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

// We now create a URI for the request
  String url = "/objects/?script=irreceived&code=";
  url +=  encoding(results);  
  url +=  ircode(results);
  
  Serial.print("Requesting URL: ");
  Serial.println(url);

// This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" + 
               "Connection: close\r\n\r\n");
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }
  
  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }
  
  Serial.println();
  Serial.println("closing connection");    
  
}

//+=============================================================================
// Dump out the decode_results structure.
//
void  dumpRaw (decode_results *results)
{
  // Print Raw data
  Serial.print("Timing[");
  Serial.print(results->rawlen-1, DEC);
  Serial.println("]: ");

  for (int i = 1;  i < results->rawlen;  i++) {
    unsigned long  x = results->rawbuf[i] * USECPERTICK;
    if (!(i & 1)) {  // even
      Serial.print("-");
      if (x < 1000)  Serial.print(" ") ;
      if (x < 100)   Serial.print(" ") ;
      Serial.print(x, DEC);
    } else {  // odd
      Serial.print("     ");
      Serial.print("+");
      if (x < 1000)  Serial.print(" ") ;
      if (x < 100)   Serial.print(" ") ;
      Serial.print(x, DEC);
      if (i < results->rawlen-1) Serial.print(", "); //',' not needed for last one
    }
    if (!(i % 8))  Serial.println("");
  }
  Serial.println("");                    // Newline
}

//+=============================================================================
// Dump out the decode_results structure.
//
void  dumpCode (decode_results *results)
{
  // Start declaration
  Serial.print("unsigned int  ");          // variable type
  Serial.print("rawData[");                // array name
  Serial.print(results->rawlen - 1, DEC);  // array size
  Serial.print("] = {");                   // Start declaration

  // Dump data
  for (int i = 1;  i < results->rawlen;  i++) {
    Serial.print(results->rawbuf[i] * USECPERTICK, DEC);
    if ( i < results->rawlen-1 ) Serial.print(","); // ',' not needed on last one
    if (!(i & 1))  Serial.print(" ");
  }

  // End declaration
  Serial.print("};");  // 

  // Comment
  Serial.print("  // ");
  encoding(results);
  Serial.print(" ");
  ircode(results);

  // Newline
  Serial.println("");

  // Now dump "known" codes
  if (results->decode_type != UNKNOWN) {

    // Some protocols have an address
    if (results->decode_type == PANASONIC) {
      Serial.print("unsigned int  addr = 0x");
      Serial.print(results->panasonicAddress, HEX);
      Serial.println(";");
    }

    // All protocols have data
    Serial.print("unsigned int  data = 0x");
    Serial.print(results->value, HEX);
    Serial.println(";");
  }
}

//+=============================================================================
// The repeating section of the code
//
void  loop ( )
{
  decode_results  results;        // Somewhere to store the results

  if (irrecv.decode(&results)) {  // Grab an IR code
    dumpInfo(&results);           // Output the results
    //dumpRaw(&results);            // Output the results in RAW format
    //dumpCode(&results);           // Output the results as source code
    Serial.println("");           // Blank line between entries
    irrecv.resume();              // Prepare for the next value
  }

    if (WiFi.status() != WL_CONNECTED)
    {
      WIFI_Connect();
    }
}