Main

Код прошивки исполнительного контроллера

Назад к описанию

В приведённом ниже коде используются выходы 2-9 для управления реле.

// Universal Arduino controller for MajorDoMo (http://smartliving.ru)
// v 0.2

#include <BSeries.h>
#include <S20Series.h>
#include <StratBase.h>
#include <Ethernet.h>
#include <SPI.h>
//#include <stdio.h>
#include "WString.h"

#define MAX_COMMAND_LEN             (10)
#define MAX_PARAMETER_LEN           (10)
#define COMMAND_TABLE_SIZE          (8)
#define TO_UPPER(x) (((x >= 'a') && (x <= 'z')) ? ((x) - ('a' - 'A')) : (x))

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0xDE, 0x6D, 0xBE, 0xDF, 0xCE, 0xED };
byte ip[] = { 192,168,0,73 };

String url = String(25);
int maxLength=25;

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
Server server(80);
Client webClient  = server.available();

int ledPin = 13;
int webRequest = false; // is command requested by HTTP?
int startPin=2;
int endPin=9;

char gCommandBuffer[MAX_COMMAND_LEN + 1];
char gParamBuffer[MAX_PARAMETER_LEN + 1];
long gParamValue;

typedef struct {
  char const    *name;
  void          (*function)(void);
} command_t;

command_t const gCommandTable[COMMAND_TABLE_SIZE] = {
  {"HELP",    commandsHelp,},
  {"LED",     commandsLed, },
  {"ON",     commandsOn, },  
  {"OFF",     commandsOff, },    
  {"STATE",     commandsState, },      
  {"CLICK",     commandsClick, },        
  {"LCLICK",     commandsLClick, },          
  {NULL,      NULL }
};


 /**********************************************************************
 *
 * Function:    printLine
 *
 * Description: Prints out single line
 *
 * Notes:       
 *
 * Returns:     None.
 *
 **********************************************************************/
 void printLine(const char line[]) {
 if (webRequest) {
  if (webClient) {
   if (webClient.connected()) {
    webClient.println(line);
    webClient.println("<br/>");
   }
  }
} else {
   Serial.println(line);
}

 }


/**********************************************************************
 *
 * Function:    cliBuildCommand
 *
 * Description: Put received characters into the command buffer or the
 *              parameter buffer. Once a complete command is received
 *              return true.
 *
 * Notes:       
 *
 * Returns:     true if a command is complete, otherwise false.
 *
 **********************************************************************/
int cliBuildCommand(char nextChar) {
  static uint8_t idx = 0; //index for command buffer
  static uint8_t idx2 = 0; //index for parameter buffer
  enum { COMMAND, PARAM };
  static uint8_t state = COMMAND;
  /* Don't store any new line characters or spaces. */
  if ((nextChar == '\n') || (nextChar == ' ') || (nextChar == '\t') || (nextChar == '\r'))
    return false;

  /* The completed command has been received. Replace the final carriage
   * return character with a NULL character to help with processing the
   * command. */
  //if (nextChar == '\r') {
  if (nextChar == ';') {
    gCommandBuffer[idx] = '\0';
    gParamBuffer[idx2] = '\0';
    idx = 0;
    idx2 = 0;
    state = COMMAND;
    return true;
  }

  if (nextChar == ',') {
    state = PARAM;
    return false;
  }

  if (state == COMMAND) {
    /* Convert the incoming character to upper case. This matches the case
     * of commands in the command table. Then store the received character
     * in the command buffer. */
    gCommandBuffer[idx] = TO_UPPER(nextChar);
    idx++;

    /* If the command is too long, reset the index and process
     * the current command buffer. */
    if (idx > MAX_COMMAND_LEN) {
      idx = 0;
       return true;
    }
  }

  if (state == PARAM) {
    /* Store the received character in the parameter buffer. */
    gParamBuffer[idx2] = nextChar;
    idx2++;

    /* If the command is too long, reset the index and process
     * the current parameter buffer. */
    if (idx > MAX_PARAMETER_LEN) {
      idx2 = 0;
      return true;
    }
  }

  return false;
}

/**********************************************************************
 *
 * Function:    cliProcessCommand
 *
 * Description: Look up the command in the command table. If the
 *              command is found, call the command's function. If the
 *              command is not found, output an error message.
 *
 * Notes:       
 *
 * Returns:     None.
 *
 **********************************************************************/
void cliProcessCommand(void)
{
  int bCommandFound = false;
  int idx;

  /* Convert the parameter to an integer value. 
   * If the parameter is empty, gParamValue becomes 0. */
  gParamValue = strtol(gParamBuffer, NULL, 0);

  /* Search for the command in the command table until it is found or
   * the end of the table is reached. If the command is found, break
   * out of the loop. */
  for (idx = 0; gCommandTable[idx].name != NULL; idx++) {
    if (strcmp(gCommandTable[idx].name, gCommandBuffer) == 0) {
      bCommandFound = true;
      break;
    }
  }

  /* If the command was found, call the command function. Otherwise,
   * output an error message. */
  if (bCommandFound == true) {
    if (!webRequest) {
     printLine("");
    }
    (*gCommandTable[idx].function)();
  }
  else {
    if (!webRequest) {
     printLine("");
    }
    printLine("Command not found.");
  }
}

/**********************************************************************
 *
 * Function:    commandsLed
 *
 * Description: Change the brightness of the LED.
 *              If this command is called with no parameter,
 *              the LED turns off.
 *
 * Notes:       
 *
 * Returns:     None.
 *
 **********************************************************************/
void commandsLed(void) {
  printLine("LED command received.");

  if (gParamValue >=0 && gParamValue <= 255) {
    analogWrite(ledPin, gParamValue);
  }
  else {
    printLine("wrong parameter value");
  }
}

void commandsOn(void) {
  printLine("ON command received.");
  if (gParamValue>=startPin && gParamValue<=endPin) {
     printLine("Turning ON");
     digitalWrite(gParamValue,HIGH);
  } else {
    printLine("Incorrect PIN");
  }
}

void commandsOff(void) {
  printLine("OFF command received.");
  if (gParamValue>=startPin && gParamValue<=endPin) {
     printLine("Turning OFF");
     digitalWrite(gParamValue,LOW);
  } else {
    printLine("Incorrect PIN");
  } 
}

void commandsClick(void) {
  printLine("CLICK command received.");
  if (gParamValue>=startPin && gParamValue<=endPin) {
     printLine("Clicking");
     digitalWrite(gParamValue,HIGH);     
     delay(1000);
     digitalWrite(gParamValue,LOW);

  } else {
    printLine("Incorrect PIN");
  } 
}

void commandsLClick(void) {
  printLine("LCLICK command received.");
  if (gParamValue>=startPin && gParamValue<=endPin) {
     printLine("Clicking");
     digitalWrite(gParamValue,HIGH);     
     delay(3000);
     digitalWrite(gParamValue,LOW);

  } else {
    printLine("Incorrect PIN");
  } 
}

void commandsState(void) {
  for(int i=startPin;i<=endPin;i++) {
    int st=digitalRead(i);
    char my_st[5];
    itoa(st,my_st,10);
//    printLine("PIN"+i);
    printLine(my_st);
  }
}




void commandsHelp(void) {
  int idx;

  /* Loop through each command in the table and send out the command
   * name to the serial port. */
  for (idx = 0; gCommandTable[idx].name != NULL; idx++) {
    printLine(gCommandTable[idx].name);   
  }

}

void setup() {

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();

  Serial.begin(115200);
  pinMode(ledPin, OUTPUT);   // sets the pin as output
  for (int thisPin = startPin; thisPin <=endPin; thisPin++)  {
    pinMode(thisPin, OUTPUT);      
  }
  Serial.println("Arduino command processing example");
  Serial.print('>');

}

void loop() {
  char rcvChar;
  int  bCommandReady = false;


  if (Serial.available() > 0) {
    rcvChar = Serial.read();
    Serial.print(rcvChar);
    bCommandReady = cliBuildCommand(rcvChar);
  }

  if (bCommandReady == true) {
    webRequest = false;
    bCommandReady = false;
    cliProcessCommand();
    Serial.print('>');
  }


  // web server
  // listen for incoming clients
  Client client = server.available();
  webClient = client;
  //webClient = server.available();
  if (client) {

    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {

      if (client.available()) {
        char c = client.read();

                  if (url.length() < maxLength) {
                    url+=(c);
                  }        

        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {

          //Serial.println("Web request:");
          //Serial.println(url.toCharArray());

          if (url.indexOf("?")>=0) {
            String commandReceived;
            String parametersReceived;
            int PosB=url.indexOf("?")+1;
            int PosE=url.indexOf("HTTP");
            if (url.indexOf(",")>=0) {
              // command has parameters              
              int PosP=url.indexOf(",");
              commandReceived=url.substring(PosB,PosP);              
              parametersReceived=url.substring(PosP+1,PosE-1);              
            } else {
              // command does not have parameters
              commandReceived=url.substring(PosB,PosE-1);              
              parametersReceived="";
            }

            commandReceived=commandReceived.toUpperCase();
            parametersReceived=parametersReceived.toUpperCase();

//            Serial.println("Web command received:");            
//            Serial.println(commandReceived.toCharArray());
            strcpy (gCommandBuffer, commandReceived.toCharArray());

            if (parametersReceived.length()>0) {              
//             Serial.println("Parameters received:");            
//             Serial.println(parametersReceived.toCharArray());
             strcpy (gParamBuffer, parametersReceived.toCharArray());
            }

          } else {
           //no command defined, showing help string
           strcpy (gCommandBuffer, "HELP\0");
          }

          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();

          client.println("<html><head><title>Arduino</title></head><body>");
          webRequest = true;
          bCommandReady = false;

          cliProcessCommand();
          client.println("</body><html>");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    url = "";
    client.stop();
  }  

}

MajorDomo

Project

Partners

edit SideBar

 

Blix theme adapted by David Gilbert, powered by PmWiki