MySQL for the Internet of Things

(Steven Felgate) #1

Chapter 4 ■ Data transformation


void loop() {
String row[3];
int i;


i = 0;
//attempt to read a packet
xbee.readPacket();
if (xbee.getResponse().isAvailable()) {
// XBee module is communicating, check for IO packet
if (xbee.getResponse().getApiId() == ZB_IO_SAMPLE_RESPONSE) {
// Get the packet
xbee.getResponse().getZBRxIoSampleResponse(ioSample);
row[i] = get_data(&ioSample);
i++;
}
else {
Serial.print("Expected I/O Sample, but got ");
Serial.print(xbee.getResponse().getApiId(), HEX);
}
} else if (xbee.getResponse().isError()) {
Serial.print("Error reading packet. Error code: ");
Serial.println(xbee.getResponse().getErrorCode());
}
// Store the data once 3 entries are retrieved.
if (i == 3) {
i = 0;
String strINSERT = String("INSERT INTO test.room_temperatures VALUES ");
strINSERT += row[0];
strINSERT += ",";
strINSERT += row[1];
strINSERT += ",";
strINSERT += row[2];
Serial.println(strINSERT);
// Create an instance of the cursor passing in the connection
MySQL_Cursor *cur = new MySQL_Cursor(&conn);
cur->execute(strINSERT.c_str());
delete cur;
}
}


Wow, that’s a lot of code, and it’s only an excerpt! I have made three sections of the code bold to bring
focus to the concept I am demonstrating. Notice the get_data() method. Here we see code to read the data
from the communication packet and produce a string in the form of (N,F,F,F), where N is an integer and F
is a floating-point number. We use this string later in the code. The second section is the call to get_data()
where we save the string created in an array. The previous section is where we detect that three data
collectors have sent data and we save the information to the database with an INSERT statement.

Free download pdf