/*
void readRequest() {
uint8_t fioAddress; // variables locales
if (xbee.readPacket(10)){
if (xbee.getResponse().isAvailable()) {
if (xbee.getResponse().getApiId() == RX_16_RESPONSE) { // se trata de un paquete RX
xbee.getResponse().getRx16Response(rx16); // almacena el paquete recibido en el objeto rx16
switch (rx16.getData(PACKET_TYPE)) {
case INFO: // TRAMA INFO
digitalWrite(8, HIGH);
fioAddress = rx16.getRemoteAddress16();
for ( int k = 0; k < 4; k++ )
uid[k] = rx16.getData(UID_FIELD + k);
generateJson( fioAddress, rx16.getData(TEMPERATURE_FIELD), rx16.getData(HUMIDITY_FIELD), rx16.getData(SLEEPCYCLE_FIELD), rx16.getData(ASYNCHRONUS_FIELD), uid ); // Renueva los datos de la fio en concreto
checkNewAddress(fioAddress);
digitalWrite(8, LOW);
break;
} // switch
} // getApiId
} // available
} // readPacket
} // readRequest
void checkNewAddress ( uint8_t address) { // fioNumber, fioList variables globales
for (int i = 0; i <= fioNumber; i++) {
if (fioNumber == 0) { // TODAVIA NO HAY ELEMENTOS UNIDOS AL COORDINADOR
fioList[i] = address;
fioNumber = 1;
i = fioNumber +1;
}
else{ // La lista no está vacía, chequea elemento a elemento
if ( fioList[i] == address)
i = fioNumber +1;
else {
if (i == fioNumber) { // Luego de chequear toda la lista, si no coincide es un elemento nuevo
fioList[i] = address;
fioNumber++;
i = fioNumber +1;
}
} // end else2
} // end else1
} // end for
} // end checkNewAddress
boolean sendRequest(uint8_t data[], uint8_t length, uint8_t frameId) {
uint8_t ack, option = 0, i = 0;
Tx16Request tx = Tx16Request(0xFFF, option, data, length, frameId);
do {
xbee.send(tx);
// Tx16Request (uint16_t addr16, uint8_t option, uint8_t *payload, uint8_t payloadLength, uint8_t frameId) (OBLIGATORIO PONERLOS TODOS!!)
// Tx16Request (uint16_t addr16, uint8_t *payload, uint8_t payloadLength) Creates a Unicast Tx16Request with the ACK option and DEFAULT_FRAME_ID.
if (xbee.readPacket(1000)) { // got a response!
if (xbee.getResponse().getApiId() == TX_STATUS_RESPONSE) { // should be a znet tx status
xbee.getResponse().getZBTxStatusResponse(txStatus);
ack = txStatus.getStatus(); // get the delivery status, the fifth byte
} // STATUS: 0 = success, 1 = when all retries are expered and no ACK is received
}
i += 1;
}while( (i < 3) && (ack != SUCCESS) );
if (ack == SUCCESS)
return true;
else
return false;
}
*/
void listenForClient() {
EthernetClient client = server.available(); // espera a que haya datos disponilbles
boolean currentLineIsBlank = true, flag = true;
bufferSize = 0;
if ( client ) {
while (client.connected()) {
while (client.available()) {
char c = client.read(); Serial.write(c);
if (c == '\n' && currentLineIsBlank) {
while(client.available()) { // Datos si es un POST
c = client.read();
bufferData[bufferSize++] = c;
}
bufferData[bufferSize] = 0; //Serial.println(bufferData);
// flag = true;
client.println("HTTP/1.1 200 OK");
client.println();
createRequest(bufferData);
client.flush();
client.stop();
}
else if (c == '\n') { // NEW LINE
if (flag) {
buffer[bufferSize] = 0; // no me pinta salto de linea si bufferSize+1
bufferSize = 0; Serial.println(buffer);
if ( strstr(buffer, "GET / HTTP/1.1") ) {
filePrint("SRV.txt", client);
client.flush();
client.stop();
}
else
if ( strstr(buffer, "GET /fioList HTTP/1.1") ){
sendGetResponse(client);
client.flush();
client.stop();
}
else
if ( !strstr(buffer, "POST /changes HTTP/1.1") ) {
client.flush();
client.stop();
}
flag = false;
}
currentLineIsBlank = true;
}
else if (c != '\r') { // caracter de la misma linea
currentLineIsBlank = false;
if ( (bufferSize < bufferMax) && flag )
buffer[bufferSize++] = c;
}
} // client.available
} // client.connected
} // end if
} // endListenForClient
// Petición recibida del tipo: "GET /192.168.112.31/fio HTTP/1.1"
void sendGetResponse(EthernetClient client) {
client.println("HTTP/1.1 200 OK\nContent-Type: application/json\nConnection: close");
client.println();
client.print("{\"fioList\":[\"asynchronus\":\"");
client.print(asynchronusCoord);
client.print("\",\"sleepCycle\":\"");
client.print(sleepCycleCoord);
client.print("\"},");
for (int k = 0; k < fioNumber; k++) {
char filename[9];
sprintf (filename, "F%d.JS", fioList[k]); // si Fx.js guardado en la microSd como Fx.JS
filePrint(filename, client);
if ( (k+1) != fioNumber)
client.println(",");
}
client.println("]}");
}
// fuente: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1295739118
void filePrint (char filename[10], EthernetClient client){
if ((myFile = SD.open(filename, FILE_READ))) {
while ( myFile.available() )
client.print( (char) myFile.read() );
myFile.close(); // CERRAR FICHERO
}
}
void generateJson (uint8_t address, uint8_t temperature, uint8_t humidity, uint8_t sleepCycle, uint8_t asynchronus, uint8_t uid[]) {
char filename[9];
sprintf (filename, "F%d.JS", address); // String jsonString; Usando string no lo escribe correctamente
if ( SD.exists(filename) ) // Si ya existía lo borra
SD.remove(filename);
// CREACION FICHERO
if ((myFile = SD.open(filename, FILE_WRITE))) { // si esta abierto ...
myFile.print("{\"name\":\"fio");
myFile.print( address, DEC);
myFile.print("\",\"address\":\"");
myFile.print(address, DEC);
myFile.print("\",\"temperature\":\"");
myFile.print(temperature, DEC);
myFile.print("\",\"humidity\":\"");
myFile.print(humidity, DEC);
myFile.print("\",\"asynchronus\":\"");
myFile.print(asynchronus, DEC);
myFile.print("\",\"sleepCycle\":\"");
myFile.print(sleepCycle, DEC);
myFile.print("\",\"uid\":\"");
for ( int k = 0; k < 4; k++ )
myFile.print(uid[k], HEX);
myFile.print("\"}");
myFile.close(); // CERRAR FICHERO
}
}
void createRequest(char buffer[]) {
uint8_t frameId = millis()*0x00FF;
char *param, *equal, sleepCycle[3], asynchronus[2];
sleepCycle[0] = 0;
asynchronus[0] = 0;
//sleepCycle=20&asynchronus=0
equal = strstr(buffer, "=") + 1;
param = strstr(equal, "&");
strncat(sleepCycle, equal, param-equal); //sleepCycle
equal = strstr(param, "=") + 1;
strncat(asynchronus, equal, 1); //asynchronus
//Serial.print(atoi(sleepCycle)); Serial.print(atoi(asynchronus));
uint8_t data[] = {CONFIGURATION, 2, atoi(sleepCycle), atoi(asynchronus)}; // Configuration request: [0,2,SLEEP_CYCLE,ASYNCHRONUS]
uint8_t length = sizeof(data);
/*
if ( sendRequest( data, length, frameId) == false ) {
saveRequest(data, length, frameId);
flag2 = true; // al no ser enviada se levanta la bandera de pendientes
}
else { // se consiguió enviar
sleepCycleCoord = atoi(sleepCycle);
asynchronusCoord = atoi(asynchronus);
if (flag1 == true){ // solo vale true la primera vez que se envía el cambio de ciclo.
flag1 == false;
time1 = millis(); // time 1 toma su primer valor
}
}*/
}
void saveRequest(uint8_t data[], uint8_t length, uint8_t frameId) {
uint8_t k = 0;
char filename[9];
sprintf (filename, "%d.txt", 1);
SD.remove(filename); // borrar la anterior
// CREACION FICHERO
if ((myFile = SD.open(filename, FILE_WRITE))) { // si esta abierto ...
myFile.print(frameId, HEX);
while (k < length) {
myFile.println(data[k], HEX);
k++;
}
myFile.close(); // CERRAR FICHERO
}
}
void sendPendingRequest() {
uint8_t frameId, address, k = 0, data[] = {};
char filename[9];
sprintf (filename, "%d.txt", 1);
if ( SD.exists(filename) ) {
if ((myFile = SD.open(filename))) { // ABRIR FICHERO
frameId = myFile.read();
while ( myFile.available() ){
data[k] = myFile.read();
k++;
}
myFile.close(); // CERRAR FICHERO
/* if ( sendRequest( data, sizeof(data), frameId ) == true ){
flag2 = false; // baja la bandera de pendientes
SD.remove(filename);
}*/
} // myFile
} // SD.exists(filename)
} // sendPendingRequest