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 address, uint8_t data[], uint8_t length, uint8_t frameId) {
uint16_t fio_address = 0x0000;
uint8_t ack, option = 0, i = 0, timeWait;
if (address == 0xFF) {
fio_address = 0xFFFF;
i=3;
timeWait = 100;
}
else {
fio_address = 0x0000 + address;
timeWait = 1000;
}
Tx16Request tx = Tx16Request(fio_address, 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(timeWait)) { // got a response!
if (xbee.getResponse().getApiId() == TX_STATUS_RESPONSE) { // should be a znet tx status
xbee.getResponse().getZBTxStatusResponse(txStatus);
// get the delivery status, the fifth byte
ack = txStatus.getStatus();
} // STATUS: 0 = success, 1 = when all retries are expered and no ACK is received
}
i += 1;
}while( (i < 3) && (ack != SUCCESS) );
if (ack == SUCCESS) {
mySerial.println("\nack");
return true;
}
else {
return false;
}
}
void listenForClient() {
Client client = server.available(); // espera a que haya datos disponilbles
if ( client )
waitForRequest(client);
}
void waitForRequest(Client client) {
boolean currentLineIsBlank = true, flag = true;
char c;
bufferSize = 0;
while (client.connected()) {
while (client.available()) {
c = client.read(); //mySerial.print(c);
if (c == '\n' && currentLineIsBlank) {
// Here is where the POST data is.
while(client.available()) { // sino hay datos, no entra solo si hay datos
c = client.read();
bufferData[bufferSize++] = c;
}
bufferData[bufferSize] = 0;
//Serial.print("\nDatos del Post: ");
//Serial.print(bufferData);
flag = true;
parseReceivedRequest(client);
}
else if (c == '\n') { // NEW LINE
if (flag) {
//Serial.print('\n');
buffer[bufferSize] = 0; // no me pinta salto de linea si bufferSize+1
//Serial.print(buffer);
bufferSize = 0;
flag = false;
}
currentLineIsBlank = true;
}
else if (c != '\r') { // you've gotten a character on the current line
currentLineIsBlank = false;
if ( bufferSize < bufferMax && flag )
buffer[bufferSize++] = c;
}
} // client.available
} // client.connected
} // end void
void parseReceivedRequest(Client client) { // Petición recibida del tipo: "GET /192.168.112.31/fio HTTP/1.1"
mySerial.println(buffer);
if ( strstr(buffer, "GET / HTTP/1.1") ) { // Serial.print("pinta la web");
webPrint(client);
}
else if ( strstr(buffer, "GET /fioList HTTP/1.1") ) { // Serial.println("respuesta fioList");
sendGetResponse(client);
}
else if ( strstr(buffer, "POST /changes HTTP/1.1") ) { // Serial.println("respuesta a un POST");
client.println("HTTP/1.1 200 OK");
client.println();
//sendPostResponse(client);
createRequest(bufferData);
}
client.flush();
client.stop();
}
/*void sendPostResponse ( Client client) {
client.println("HTTP/1.1 200 OK");
client.println();
}*/
void sendGetResponse(Client client) {
char filename[9];
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: application/json");
client.println("Connection: close");
client.println();
client.print("{\"fioList\":[");
client.print("{\"asynchronus\":\"");
client.print(asynchronusCoord);
client.print("\",\"sleepCycle\":\"");
client.print(sleepCycleCoord);
client.print("\"},");
for (int k = 0; k < fioNumber; k++) {
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("]}");
}
void webPrint (Client client) {
filePrint("SRV_2.txt", client);
}
// fuente: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1295739118
void filePrint (char filename[9], Client client){
if (myFile = SD.open(filename, FILE_READ)) {
while ( myFile.available() ) {
client.print( (char) myFile.read() );
}
myFile.close(); // CERRAR FICHERO
}
else{
mySerial.print("no leido");
}
}
// OFF modo pregunta ( SIEMPRE DESPIERTO )
// PERIODO modo envio de informacion periodica ( CON CICLOS DE SUEÑO )
// ASINCRONO modo solo envio de info si es que hay cambios ( SIEMPRE DESPIERTO )
// ASINCRONO + PERIODO modo envio de info si hay cambio ( CON CICLO DE SUEÑO )
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) ) {
SD.remove(filename);
}
myFile = SD.open(filename, FILE_WRITE); // CREACION FICHERO
if (myFile) { // 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 *asyn, *slpC, *equal;
char sleepCycle[3], asynchronus[2];
sleepCycle[0] = 0;
asynchronus[0] = 0;
equal = strstr(buffer, "=") + 1;
slpC = strstr(equal, "&");
strncat(sleepCycle, equal, slpC-equal);
equal = strstr(slpC, "=") + 1;
asyn = strstr(equal, "&");
strncat(asynchronus, equal, asyn-equal);
//sleepCycle=20&asynchronus=0
int asynchronus2 = atoi(asynchronus);
int sleepCycle2 = atoi(sleepCycle);
uint8_t data[] = {CONFIGURATION,2,sleepCycle2, asynchronus2}; // Configuration request: [0,2,SLEEP_CYCLE,ASYNCHRONUS]
uint8_t length = sizeof(data);
/*
if ( sendRequest( 0xFF, data, length, frameId) == false ) {
Serial.print("envio fallido");
saveRequest(0xFF, data, length, frameId);
flag2 = true; // al no ser enviada se levanta la bandera de pendientes
}
else { // se consiguió enviar
sleepCycleCoord = sleepCycle2;
asynchronusCoord = asynchronus2;
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 address, uint8_t data[], uint8_t length, uint8_t frameId) {
char filename[9];
int k = 0;
sprintf (filename, "%d.txt", 1);
eraseRequest(filename);
myFile = SD.open(filename, FILE_WRITE);
if (myFile) { // si esta abierto ...
myFile.print(address, HEX); myFile.print('\n');
myFile.print(frameId, HEX); myFile.print('\n');
while (k < length) {
myFile.print(data[k], HEX); myFile.print('\n');
k++;
}
myFile.close();
}
}
void sendPendingRequest() {
uint8_t frameId, address, k = 0, data[] = {};
char filename[6];
sprintf (filename, "%d.txt", "1");
if ( SD.exists(filename) ) {
myFile = SD.open(filename);
if (myFile) { // si esta abierto ...
address = myFile.read();
frameId = myFile.read();
while ( myFile.available() ){
data[k] = myFile.read();
k++;
}
myFile.close(); // CERRAR FICHERO
if ( sendRequest( address, data, sizeof(data), frameId ) == true ){
flag2 = false; // baja la bandera de pendientes
eraseRequest(filename);
}
} // myFile
} // SD.exists(filename)
}
void eraseRequest(char filename[9]) {
SD.remove(filename);
}