FONA + Ubidots IOT Platform Integration

Breakout boards, sensors, other Adafruit kits, etc.

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
User avatar
solardude
 
Posts: 145
Joined: Fri Oct 18, 2013 12:47 am

FONA + Ubidots IOT Platform Integration

Post by solardude »

Hey everybody I'm trying to get FONA up and sending data to http://www.Ubidots.com which can log sensor data sent from Fona and then send SMS and Emails based on predefined Triggers. Fona would be perfect for this platform, I was unimpressed with Xivley and other services in the past.

So Ubidots has provided code that works with the SIM900 so it should work easily with the SIM800 in the FONA since they have the same AT commands.

I'm super busy at the moment but can the Adafruit team or users give this a try and see if they can get it up and running with the FONA?

Here is the code that Ubidots provided that they had working with the SIM900 module. I'll have a Ubidot rep check in here also to offer advice also since they would like to see it up and working also. They will create a tutorial or help Adafruit do it I'm sure.

Tony Dicola take a look if you have time and let us know what you think.
Last edited by solardude on Mon Aug 25, 2014 2:17 pm, edited 1 time in total.

User avatar
agus1985
 
Posts: 5
Joined: Thu Aug 14, 2014 8:05 pm

Re: FONA + Ubidots IOT Platform Integration

Post by agus1985 »

Hi all,

It really looks like a great, tiny device; we're definitively interested in building a tutorial/use case about it.

We'll go ahead and order some units to start playing with, and will get back to you after some testing.

Thanks!

User avatar
solardude
 
Posts: 145
Joined: Fri Oct 18, 2013 12:47 am

Re: FONA + Ubidots IOT Platform Integration

Post by solardude »

Ok here is the current updated code for using the FONA + Ubidots.com IOT software platform to log and graph sensor data sent wirelessly from the FONA.

Ubidots has received a FONA board and are going to build a Step By Step example showing exactly how to use the FONA with Ubidots.com , and they plan on starting the FONA testing and custom code creation the first week of September.

For now here is code that should work that did work for the SIM900 from Simcom which is really similar and runs on the same AT commands.

For now you can try this code and give their free version of their service a try.

Here is how I'm using Ubidots.com to send temp and humidity data to Ubidots using a Spark Core, I also have a event trigger setup so it sends me a email once the temp hits 87 degrees F and it works perfectly everyt time.
Ubi.png
Ubi.png (69.57 KiB) Viewed 4820 times
event.png
event.png (55.23 KiB) Viewed 4820 times
temp email.png
temp email.png (19.42 KiB) Viewed 4820 times
Here is the latest FONA code for sending data to Ubidots.com

Code: Select all

#include <SoftwareSerial.h>
#include <String.h>
 
SoftwareSerial mySerial(7, 8);                                                // Your pins to the GPRS shield
 
 
int value; 

String token = "tShIxUgpfmyWpsz0ZKtFdLDxiPmubDqBuGcI8NzlAuN5GK8ynfd0XDpRZH0R";// Your Ubidots token
String idvariable = "53baaf3c76254244e1c8e408";                               // Your variable_ID
void setup()
{
  
  mySerial.begin(19200);               
  Serial.begin(19200);   
  delay(10000);
}
 
void loop()
{
  
  
 int value = analogRead(A0);
 save_value();      
 if (mySerial.available())
   Serial.write(mySerial.read());
}
 

// This function will send the A0 sensor data to Ubidots, you can see the new value after executing this function

void save_value()
{
  int num;
  String le;
  String var;
  var="{\"value\":"+ String(value) + "}";
  num=var.length();
  le=String(num);
  
  
  mySerial.println("AT+CGATT?");
  delay(2000);
 
  ShowSerialData();
  mySerial.println("AT+CGATT?");
  delay(2000);
 
  ShowSerialData();
  mySerial.println("AT+CGATT?");
  delay(2000);
 
  ShowSerialData();
  mySerial.println("AT+CGATT?");
  delay(2000);
 
  ShowSerialData();
  mySerial.println("AT+CGATT?");
  delay(2000);
 
  ShowSerialData();
  mySerial.println("AT+CGATT?");
  delay(2000);
 
  ShowSerialData();
 
  mySerial.println("AT+CSTT=\"web.vmc.net.co\"");      // Replace with your APN
  delay(1000);
 
  ShowSerialData();
 
  mySerial.println("AT+CIICR");                        // Bring up the wireless connection
  delay(3000);
 
  ShowSerialData();
 
  mySerial.println("AT+CIFSR");                        // Get IP adress
  delay(2000);
 
  ShowSerialData();
 
  mySerial.println("AT+CIPSPRT=0");
  delay(3000);
 
  ShowSerialData();
 
  mySerial.println("AT+CIPSTART=\"tcp\",\"things.ubidots.com\",\"80\"");    // Start the connection to Ubidots
  delay(3000);
 
  ShowSerialData();
 
  mySerial.println("AT+CIPSEND");                      // Start to send data to remote server
  delay(3000);
  ShowSerialData();
  mySerial.print("POST /api/v1.6/variables/"+idvariable);
  delay(100);
  ShowSerialData();
  mySerial.println("/values HTTP/1.1");
  delay(100);
  ShowSerialData();
  mySerial.println("Content-Type: application/json");
  delay(100);
  ShowSerialData();
  mySerial.println("Content-Length: "+le);
  delay(100);
  ShowSerialData();
  mySerial.print("X-Auth-Token: ");
  delay(100);
  ShowSerialData();
  mySerial.println(token);
  delay(100);
  ShowSerialData();
  mySerial.println("Host: things.ubidots.com");
  delay(100);
  ShowSerialData();
  mySerial.println();
  delay(100);
  ShowSerialData();
  mySerial.println(var);
  delay(100);
  ShowSerialData();
  mySerial.println();
  delay(100);
  ShowSerialData();
  mySerial.println((char)26);                            // Sending the HTTP request
  delay(7000);                                           // Waiting for a reply. Important! tweak this time depending on the latency of your mobile Internet connection
  mySerial.println();
 
  ShowSerialData();
 
  mySerial.println("AT+CIPCLOSE");                      // Close the connection
  delay(1000);
  ShowSerialData();
}

// This function is to show the response in your serial terminal

void ShowSerialData()
{
  while(mySerial.available()!=0)
  
    Serial.write(mySerial.read());
    
}

User avatar
adafruit_support_mike
 
Posts: 67454
Joined: Thu Feb 11, 2010 2:51 pm

Re: FONA + Ubidots IOT Platform Integration

Post by adafruit_support_mike »

Thanks for posting the update. It will be interesting to see how things turn out when you Ubidots starts working with the hardware.

User avatar
agus1985
 
Posts: 5
Joined: Thu Aug 14, 2014 8:05 pm

Re: FONA + Ubidots IOT Platform Integration

Post by agus1985 »

Hello,

We got our FONA and it's now sending data to Ubidots. We used an example code provided by the community, and modified it to send data to Ubidots:

Code: Select all

/* Chip McClelland - Cellular Data Logger
   BSD license, Please keep my name and the required Adafruit text in any redistribution

This sketch will connect to Ubidots and periodically upload the current temperature and humidity as well as the number
of times the PIR sensor had detected a person. The counts are then reset and you can access the data on your Ubidots account.

You can use the site - www.ubidots.com - for free with a development account.  Production use will cost money. 
The API for Ubidots is defined here: https://ubidots.com/docs/

 IDE: Arduino 1.0 or later
 I had to add the following line to the Adafruit_FONA.cpp file: typedef char PROGMEM prog_char;
 Otherwise this code would not compile

 Hardware - Adafruit Fona GSM Board
 Temperature Sensor - Dummy Code for now
 Person Counter - Dummy Code for now

 I made use of the Adafruit Fona library and parts of the example code
 /*************************************************** 
  This is an example for our Adafruit FONA Cellular Module

  Designed specifically to work with the Adafruit FONA 
  ----> http://www.adafruit.com/products/1946
  ----> http://www.adafruit.com/products/1963

  These displays use TTL Serial to communicate, 2 pins are required to 
  interface
  Adafruit invests time and resources providing this open source code, 
  please support Adafruit and open-source hardware by purchasing 
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.  
  BSD license, all text above must be included in any redistribution
 ****************************************************/

#include <HardwareSerial.h>
#include "Adafruit_FONA.h"
 
#define FONA_RX 1
#define FONA_TX 0
#define FONA_RST 4
#define FONA_KEY 6
#define FONA_PS 7
 
#define HWSERIAL Serial1

// this is a large buffer for replies
char replybuffer[255];

HardwareSerial fonaSS = Serial1;
Adafruit_FONA fona = Adafruit_FONA(&fonaSS, FONA_RST);
 
uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);


int Interval = 10000;             // Time between measurements in seconds
int KeyTime = 2000;               // Time needed to turn on the Fona
unsigned long Reporting = 30000;  // Time between uploads to Xively
unsigned long TimeOut = 30000;    // How long we will give an AT command to comeplete
unsigned long LastReading = 0;    // When did we last read the sensors - they are slow so will read between sends
unsigned long LastReporting = 0;  // When did we last send data to Xively
uint8_t n=0; 
int f = 0;
int PersonCount = 0;

void setup() {
  delay(3000);
  HWSERIAL.begin(4800);
  Serial.begin(9600);

  Serial.println("Started setup");

  pinMode(FONA_KEY,OUTPUT);                                     // This is the pin used to turn on and off the Fona
  TurnOnFona();
  Serial.println(F("FONA basic test"));
  Serial.println(F("Initializing....(May take 3 seconds)"));   // See if the FONA is responding
  if (! fona.begin(4800)) {                                    // make it slow so its easy to read!
    Serial.println(F("Couldn't find FONA"));
    while (1);
  }
  GetConnected();
  Serial.println(F("FONA is OK"));
  TurnOffFona();  
 
}


void loop() {
  Serial.println("in Loop");
  delay(2000);
  
  if (LastReporting + Reporting <= millis()) {   // This checks to see if it is time to send to Xively
    TurnOnFona();                                // Turn on the module
    GetConnected();                              // Connect to network and start GPRS
    Send2Xively();                               // Send data to Xively
    GetDisconnected();                           // Disconnect from GPRS
    TurnOffFona();                               // Turn off the modeule
    LastReporting = millis();
  }
   
  if (LastReading + Interval <= millis()) {     // This checks to see if it is time to take a sensor reading
    f ++;                 //Do some math to convert the Celsius to Fahrenheit
    PersonCount ++;
    Serial.print(F("The current Temperature is: "));
    Serial.print(f);                             //Send the temperature in degrees F to the serial monitor
    Serial.print(F("F "));    
    LastReading = millis();                     // Record the time of the last sensor readings
  }
  
  
}

// This function is to send the sensor data to Ubidots - each step is commented in the serial terminal
void Send2ubidots()
{
  int num;
  String le;
  String var;
  var = "{\"value\":"+ value + "}";                     //value is the sensor value
  num = var.length();
  le = String(num);                                     //this is to calcule the length of var

  Serial.print(F("Start the connection to Ubidots: "));
  if (SendATCommand("AT+CIPSTART=\"tcp\",\"things.ubidots.com",\"80\"",'C','T')) {
    Serial.println("Connected");
  }
  Serial.print(F("Begin to send data to the remote server: "));
  if (SendATCommand("AT+CIPSEND",'\n','>')) {
    Serial.println("Sending");
  }
 fona.println("POST /api/v1.6/variables/BANNED/values HTTP/1.1");           // Replace with your variable ID
 fona.println("Content-Type: application/json");                                      
 fona.println("Content-Length: "+le");                                                        
 fona.println("X-Auth-Token: BANNED");                                    // here you should replace your Token               
 fona.println("Host: things.ubidots.com");
 fona.println();
 fona.println(var);
 fona.println();
 fona.println((char)26);                                       //This ends the JSON SEND with a carriage return
 Serial.print(F("Send JSON Package: "));
 if (SendATCommand("",'2','0')) {                              // The 200 code from Ubidots means it was successfully uploaded
    Serial.println("Sent");
     PersonCount = 0;
  }
  else {
    Serial.println("Send Timed out, will retry at next interval");
  }
 // delay(2000);
 Serial.print(F("Close connection to Ubidots: "));              // Close the connection
 if (SendATCommand("AT+CIPCLOSE",'G','M')) {
    Serial.println("Closed");
  }
}

boolean SendATCommand(char Command[], char Value1, char Value2) {
 unsigned char buffer[64];                                  // buffer array for data recieve over serial port
 int count = 0;
 int complete = 0;
 unsigned long commandClock = millis();                      // Start the timeout clock
 fona.println(Command);
 while(!complete && commandClock <= millis()+TimeOut)         // Need to give the modem time to complete command 
 {
   while(!fona.available() && commandClock <= millis()+TimeOut);
   while(fona.available()) {                                 // reading data into char array 
     buffer[count++]=fona.read();                            // writing data into array
     if(count == 64) break;
   }
   Serial.write(buffer,count);                           // Uncomment if needed to debug
   for (int i=0; i <= count; i++) {
     if(buffer[i]==Value1 && buffer[i+1]==Value2) complete = 1; 
   }
 }
 if (complete ==1) return 1;                              // Returns "True"  - "False" sticks in the loop for now
 else return 0;
}

void TurnOnFona()
{
  Serial.print("Turning on Fona: ");
  while(digitalRead(FONA_PS)) 
  {
    digitalWrite(FONA_KEY,LOW);
    unsigned long KeyPress = millis();
    while(KeyPress + KeyTime >= millis()) {}
    digitalWrite(FONA_KEY,HIGH);
  }
  fona.begin(4800);
  Serial.println("success!");
}

void GetConnected() 
{
  do 
  {
    n = fona.getNetworkStatus();  // Read the Network / Cellular Status
    Serial.print(F("Network status ")); 
    Serial.print(n);
    Serial.print(F(": "));
      if (n == 0) Serial.println(F("Not registered"));
      if (n == 1) Serial.println(F("Registered (home)"));
      if (n == 2) Serial.println(F("Not registered (searching)"));
      if (n == 3) Serial.println(F("Denied"));
      if (n == 4) Serial.println(F("Unknown"));
      if (n == 5) Serial.println(F("Registered roaming"));
  } while (n != 1);
}

void GetDisconnected()
{
  fona.enableGPRS(false);
  Serial.println(F("GPRS Serivces Started"));
}

void TurnOffFona()
{
  Serial.print("Turning off Fona: ");
  while(digitalRead(FONA_PS))
  {
    digitalWrite(FONA_KEY,LOW);
    unsigned long KeyPress = millis();
    while(KeyPress + KeyTime >= millis()) {}
    digitalWrite(FONA_KEY,HIGH);
  }
  Serial.println("success!");
}

User avatar
agus1985
 
Posts: 5
Joined: Thu Aug 14, 2014 8:05 pm

Re: FONA + Ubidots IOT Platform Integration

Post by agus1985 »

Hi all! Here's the full FONA + Ubidots Tutorial: http://ubidots.com/docs/devices/FONA.html

User avatar
adafruit_support_mike
 
Posts: 67454
Joined: Thu Feb 11, 2010 2:51 pm

Re: FONA + Ubidots IOT Platform Integration

Post by adafruit_support_mike »

Nice! Thanks for posting. ;-)

User avatar
snoller
 
Posts: 34
Joined: Sun Mar 23, 2014 4:59 pm

Re: FONA + Ubidots IOT Platform Integration

Post by snoller »

Hey agus1985 - i really appreciate if you guys are posting code-examples here or on the ubidots website. Unfortunately this code is full of errors and does simply not work at all. In the latest update you posted here you even used a version that tries to post data to Xively and not to ubidots. Aren't you trying this out before uploading? Can someone post a version that really works with Fona and ubidots? I spent quite some time with the different versions of non-working code...
Unfortunately the Adafruit Fona Examples do not cover complex header insertions - would it be possible to provide that for instance?
Thanks in advance.
PS: also tried solardudes example which seems to be tailored to the gprs-shield and not to the fona - at least i did not get it to work with my board.

User avatar
snoller
 
Posts: 34
Joined: Sun Mar 23, 2014 4:59 pm

Re: FONA + Ubidots IOT Platform Integration

Post by snoller »

ok guys - i finally got it to work. Below you can find my code, besides some bugfixes in the code provided by agus1985 i had - after careful testing with AT commands through the console* - to input a few more AT commands so that the module did not respond with an error to the AT+CIPSEND command which opens the connection to the server. It's not beautiful and some stuff is still work in progress (especially the turning on/off thing), but in general it compiles and works.
BTW: it is important to make the handy SendCheckReply() function in the Adafruit library (in the .h file) public, otherwise it won't compile.
*i used this AT-Reference for the SIM-Module as a reference: http://mt-system.ru/sites/default/files ... _v1.03.pdf

Code: Select all

#include <SoftwareSerial.h>
#include "Adafruit_FONA.h"

#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
#define FONA_KEY 6
#define FONA_PS 7

char replybuffer[255];

SoftwareSerial myfona = SoftwareSerial(FONA_TX, FONA_RX);
Adafruit_FONA fona = Adafruit_FONA(&myfona, FONA_RST);

uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);

int Interval = 100;             // Time between measurements in seconds
int KeyTime = 2000;               // Time needed to turn on the Fona
unsigned long Reporting = 20000;  // Time between uploads to Ubidots
unsigned long TimeOut = 30000;    // How long we will give an AT command to comeplete
unsigned long LastReading = 0;    // When did we last read the sensors - they are slow so will read between sends
unsigned long LastReporting = 0;  // When did we last send data to Ubidots
uint8_t n = 0;
int f = 0;
int PersonCount = 0;

void setup() {
  //delay(3000);
  myfona.begin(4800);
  Serial.begin(9600);
  //fona.setGPRSNetworkSettings(F("web.vodafone.de"), F("vf"), F("vf"));   //we define the apn below
  pinMode(FONA_KEY, OUTPUT);                                   // This is the pin used to turn on and off the Fona
  Serial.println(F("Initializing...."));                       // See if the FONA is responding
  if (! fona.begin(4800)) {                                    // make it slow so its easy to read!
    Serial.println(F("Couldn't find FONA"));
    while (1);
  }
  Serial.println(F("FONA is OK"));
  fona.enableGPRS(false);
  //TurnOffFona();
}


void loop() {
  
  
  Serial.println("in Loop");
  delay(2000);
  int value = analogRead(A0);
  if (LastReporting + Reporting <= millis()) {   // This checks to see if it is time to send to Ubidots
    TurnOnFona();
    fona.enableGPRS(true);
    Serial.println(F("GPRS Serivces Started"));
    GetConnected();                              // Connect to network and start GPRS
    Send2ubidots(String(value));                 // Send data to Ubidots
    GetDisconnected();                           // Disconnect from GPRS
    TurnOffFona();                               // Turn off the module
    LastReporting = millis();
  }

  if (LastReading + Interval <= millis()) {     // This checks to see if it is time to take a sensor reading
    f ++;                 //Do some math to convert the Celsius to Fahrenheit
    PersonCount ++;
    Serial.print(F("The current Temperature is: "));
    Serial.print(f);                             //Send the temperature in degrees F to the serial monitor
    Serial.print(F("F "));
    LastReading = millis();                     // Record the time of the last sensor readings
  }


}

// This function is to send the sensor data to Ubidots - each step is commented in the serial terminal
void Send2ubidots(String value)
{

  int num;
  String le;
  String var;
  var = "{\"value\":" + value + "}";          //value is the sensor value
  num = var.length();
  le = String(num);                           //this is to calcule the length of var
 
  fona.sendCheckReply(F("AT+SAPBR=1,1"), F("OK"));
  delay(3000);
  fona.sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"));
  delay(3000);
  fona.sendCheckReply(F("AT+CIPMUX=0"), F("OK"));
  delay(3000);
  fona.sendCheckReply(F("at+cipcsgp=1,\"eseye.com\",\"user\",\"pass\""), F("OK"));  //your APN goes here
  delay(3000); 

  Serial.print(F("Start the connection to Ubidots: "));
  if (SendATCommand("AT+CIPSTART=\"tcp\",\"things.ubidots.com\",\"80\"", 'C', 'T')) {
    Serial.println("Connected");
  }
  Serial.print(F("Begin to send data to the remote server: "));
  if (SendATCommand("AT+CIPSEND", '\n', '>')) {
    Serial.println("Sending");
  }
  fona.println("POST /api/v1.6/variables/BANNED/values HTTP/1.1");           // Replace "xxx..." with your variable ID
  fona.println("Content-Type: application/json");
  fona.println("Content-Length: " + le);
  fona.println("X-Auth-Token: BANNED");                                    // here you should replace "xxx..." with your Ubidots Token
  fona.println("Host: things.ubidots.com");
  fona.println();
  fona.println(var);
  fona.println();
  fona.println((char)26);                                       //This ends the JSON SEND with a carriage return
  Serial.print(F("Send JSON Package: "));
  if (SendATCommand("", '2', '0')) {                            // The 200 code from Ubidots means it was successfully uploaded
    Serial.println("Sent");
    PersonCount = 0;
  }
  else {
    Serial.println("Send Timed out, will retry at next interval");
  }
  // delay(2000);
  Serial.print(F("Close connection to Ubidots: "));              // Close the connection
  if (SendATCommand("AT+CIPCLOSE", 'G', 'M')) {
    Serial.println("Closed");
  }
}

boolean SendATCommand(char Command[], char Value1, char Value2) {
  unsigned char buffer[64];                                  // buffer array for data recieve over serial port
  int count = 0;
  int complete = 0;
  unsigned long commandClock = millis();                      // Start the timeout clock
  fona.println(Command);
  while (!complete && commandClock <= millis() + TimeOut)      // Need to give the modem time to complete command
  {
    while (!fona.available() && commandClock <= millis() + TimeOut);
    while (fona.available()) {                                // reading data into char array
      buffer[count++] = fona.read();                          // writing data into array
      if (count == 64) break;
    }
    //Serial.write(buffer, count);                          // Uncomment if needed to debug
    for (int i = 0; i <= count; i++) {
      if (buffer[i] == Value1 && buffer[i + 1] == Value2) complete = 1;
    }
  }
  if (complete == 1) return 1;                             // Returns "True"  - "False" sticks in the loop for now
  else return 0;
}

void TurnOnFona()
{
  Serial.print("Turning on Fona: ");
  while (digitalRead(FONA_PS))
  {
    digitalWrite(FONA_KEY, LOW);
    unsigned long KeyPress = millis();
    while (KeyPress + KeyTime >= millis()) {}
    digitalWrite(FONA_KEY, HIGH);
  }
  fona.begin(4800);
  Serial.println("success!");
}

void GetConnected()
{
  do
  {
    n = fona.getNetworkStatus();  // Read the Network / Cellular Status
    Serial.print(F("Network status "));
    Serial.print(n);
    Serial.print(F(": "));
    if (n == 0) Serial.println(F("Not registered"));
    if (n == 1) Serial.println(F("Registered (home)"));
    if (n == 2) Serial.println(F("Not registered (searching)"));
    if (n == 3) Serial.println(F("Denied"));
    if (n == 4) Serial.println(F("Unknown"));
    if (n == 5) Serial.println(F("Registered roaming"));
  } while (n != 5);
}

void GetDisconnected()
{
  fona.enableGPRS(false);
  Serial.println(F("GPRS Serivces Stopped"));
}

void TurnOffFona()
{
  Serial.print("Turning off Fona: ");
  while (digitalRead(FONA_PS))
  {
    digitalWrite(FONA_KEY, LOW);
    unsigned long KeyPress = millis();
    while (KeyPress + KeyTime >= millis()) {}
    digitalWrite(FONA_KEY, HIGH);
  }
  Serial.println("success!");
}


User avatar
Allari
 
Posts: 2
Joined: Sat Oct 25, 2014 7:33 am

Re: FONA + Ubidots IOT Platform Integration

Post by Allari »

Hello,

I also try to integrate Ubidots platform using the code from here. But I have an issue with compiling the code. I just cannot get any further. I use the last library. Something wrong with the path to the library? Below you can see my code and the error list. Can anyone give a hint what I am doing wrong? THX

Code: Select all

#include <SoftwareSerial.h>
#include "Adafruit_FONA.h"

#define FONA_RX 10
#define FONA_TX 9
#define FONA_RST 4
#define FONA_KEY 6
#define FONA_PS 7

char replybuffer[255];

SoftwareSerial myfona = SoftwareSerial(FONA_TX, FONA_RX);
Adafruit_FONA fona = Adafruit_FONA(&myfona, FONA_RST);

uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);

int Interval = 100;             // Time between measurements in seconds
int KeyTime = 2000;               // Time needed to turn on the Fona
unsigned long Reporting = 20000;  // Time between uploads to Ubidots
unsigned long TimeOut = 30000;    // How long we will give an AT command to comeplete
unsigned long LastReading = 0;    // When did we last read the sensors - they are slow so will read between sends
unsigned long LastReporting = 0;  // When did we last send data to Ubidots
uint8_t n = 0;
int f = 0;
int PersonCount = 0;

void setup() {
  //delay(3000);
  myfona.begin(4800);
  Serial.begin(9600);
  fona.setGPRSNetworkSettings(F("uk.lebara.mobi"), F("wap"), F("wap"));   //we define the apn below
  pinMode(FONA_KEY, OUTPUT);                                   // This is the pin used to turn on and off the Fona
  Serial.println(F("Initializing...."));                       // See if the FONA is responding
  if (! fona.begin(4800)) {                                    // make it slow so its easy to read!
    Serial.println(F("Couldn't find FONA"));
    while (1);
  }
  Serial.println(F("FONA is OK"));
  fona.enableGPRS(false);
  //TurnOffFona();
}


void loop() {
  
  
  Serial.println("in Loop");
  delay(2000);
  int value = analogRead(A0);
  if (LastReporting + Reporting <= millis()) {   // This checks to see if it is time to send to Ubidots
    TurnOnFona();
    fona.enableGPRS(true);
    Serial.println(F("GPRS Serivces Started"));
    GetConnected();                              // Connect to network and start GPRS
    Send2ubidots(String(value));                 // Send data to Ubidots
    GetDisconnected();                           // Disconnect from GPRS
    TurnOffFona();                               // Turn off the module
    LastReporting = millis();
  }

  if (LastReading + Interval <= millis()) {     // This checks to see if it is time to take a sensor reading
    f ++;                 //Do some math to convert the Celsius to Fahrenheit
    PersonCount ++;
    Serial.print(F("The current Temperature is: "));
    Serial.print(f);                             //Send the temperature in degrees F to the serial monitor
    Serial.print(F("F "));
    LastReading = millis();                     // Record the time of the last sensor readings
  }


}

// This function is to send the sensor data to Ubidots - each step is commented in the serial terminal
void Send2ubidots(String value)
{

  int num;
  String le;
  String var;
  var = "{\"value\":" + value + "}";          //value is the sensor value
  num = var.length();
  le = String(num);                           //this is to calcule the length of var
 
  fona.sendCheckReply(F("AT+SAPBR=1,1"), F("OK"));
  delay(3000);
  fona.sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"));
  delay(3000);
  fona.sendCheckReply(F("AT+CIPMUX=0"), F("OK"));
  delay(3000);
  fona.sendCheckReply(F("at+cipcsgp=1,\"eseye.com\",\"user\",\"pass\""), F("OK"));  //your APN goes here
  delay(3000); 

  Serial.print(F("Start the connection to Ubidots: "));
  if (SendATCommand("AT+CIPSTART=\"tcp\",\"things.ubidots.com\",\"80\"", 'C', 'T')) {
    Serial.println("Connected");
  }
  Serial.print(F("Begin to send data to the remote server: "));
  if (SendATCommand("AT+CIPSEND", '\n', '>')) {
    Serial.println("Sending");
  }
  fona.println("POST /api/v1.6/variables/54cd09b47625422e148f7e89xxxxx/values HTTP/1.1");           // Replace "xxx..." with your variable ID
  fona.println("Content-Type: application/json");
  fona.println("Content-Length: " + le);
  fona.println("X-Auth-Token: BANNED");                                    // here you should replace "xxx..." with your Ubidots Token
  fona.println("Host: things.ubidots.com");
  fona.println();
  fona.println(var);
  fona.println();
  fona.println((char)26);                                       //This ends the JSON SEND with a carriage return
  Serial.print(F("Send JSON Package: "));
  if (SendATCommand("", '2', '0')) {                            // The 200 code from Ubidots means it was successfully uploaded
    Serial.println("Sent");
    PersonCount = 0;
  }
  else {
    Serial.println("Send Timed out, will retry at next interval");
  }
  // delay(2000);
  Serial.print(F("Close connection to Ubidots: "));              // Close the connection
  if (SendATCommand("AT+CIPCLOSE", 'G', 'M')) {
    Serial.println("Closed");
  }
}

boolean SendATCommand(char Command[], char Value1, char Value2) {
  unsigned char buffer[64];                                  // buffer array for data recieve over serial port
  int count = 0;
  int complete = 0;
  unsigned long commandClock = millis();                      // Start the timeout clock
  fona.println(Command);
  while (!complete && commandClock <= millis() + TimeOut)      // Need to give the modem time to complete command
  {
    while (!fona.available() && commandClock <= millis() + TimeOut);
    while (fona.available()) {                                // reading data into char array
      buffer[count++] = fona.read();                          // writing data into array
      if (count == 64) break;
    }
    //Serial.write(buffer, count);                          // Uncomment if needed to debug
    for (int i = 0; i <= count; i++) {
      if (buffer[i] == Value1 && buffer[i + 1] == Value2) complete = 1;
    }
  }
  if (complete == 1) return 1;                             // Returns "True"  - "False" sticks in the loop for now
  else return 0;
}

void TurnOnFona()
{
  Serial.print("Turning on Fona: ");
  while (digitalRead(FONA_PS))
  {
    digitalWrite(FONA_KEY, LOW);
    unsigned long KeyPress = millis();
    while (KeyPress + KeyTime >= millis()) {}
    digitalWrite(FONA_KEY, HIGH);
  }
  fona.begin(4800);
  Serial.println("success!");
}

void GetConnected()
{
  do
  {
    n = fona.getNetworkStatus();  // Read the Network / Cellular Status
    Serial.print(F("Network status "));
    Serial.print(n);
    Serial.print(F(": "));
    if (n == 0) Serial.println(F("Not registered"));
    if (n == 1) Serial.println(F("Registered (home)"));
    if (n == 2) Serial.println(F("Not registered (searching)"));
    if (n == 3) Serial.println(F("Denied"));
    if (n == 4) Serial.println(F("Unknown"));
    if (n == 5) Serial.println(F("Registered roaming"));
  } while (n != 5);
}

void GetDisconnected()
{
  fona.enableGPRS(false);
  Serial.println(F("GPRS Serivces Stopped"));
}

void TurnOffFona()
{
  Serial.print("Turning off Fona: ");
  while (digitalRead(FONA_PS))
  {
    digitalWrite(FONA_KEY, LOW);
    unsigned long KeyPress = millis();
    while (KeyPress + KeyTime >= millis()) {}
    digitalWrite(FONA_KEY, HIGH);
  }
  Serial.println("success!");
}

Code: Select all

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.
Arduino: 1.0.6 + Td: 1.20 (Windows 7), Board: "Teensy 3.1"
fona_data:13: error: no matching function for call to 'Adafruit_FONA::Adafruit_FONA(SoftwareSerial&, int)'
fona_data.ino:13:52: note: candidates are:
In file included from fona_data.ino:2:0:
C:\Program Files\Arduino\libraries\Adafruit_FONA/Adafruit_FONA.h:49:3: note: Adafruit_FONA::Adafruit_FONA(int8_t)
C:\Program Files\Arduino\libraries\Adafruit_FONA/Adafruit_FONA.h:49:3: note:   candidate expects 1 argument, 2 provided
C:\Program Files\Arduino\libraries\Adafruit_FONA/Adafruit_FONA.h:47:7: note: constexpr Adafruit_FONA::Adafruit_FONA(const Adafruit_FONA&)
C:\Program Files\Arduino\libraries\Adafruit_FONA/Adafruit_FONA.h:47:7: note:   candidate expects 1 argument, 2 provided
C:\Program Files\Arduino\libraries\Adafruit_FONA/Adafruit_FONA.h:47:7: note: constexpr Adafruit_FONA::Adafruit_FONA(Adafruit_FONA&&)
C:\Program Files\Arduino\libraries\Adafruit_FONA/Adafruit_FONA.h:47:7: note:   candidate expects 1 argument, 2 provided
fona_data.ino: In function 'void setup()':
fona_data:34: error: no matching function for call to 'Adafruit_FONA::begin(int)'
fona_data.ino:34:24: note: candidate is:
In file included from fona_data.ino:2:0:
C:\Program Files\Arduino\libraries\Adafruit_FONA/Adafruit_FONA.h:50:11: note: boolean Adafruit_FONA::begin(Stream&)
C:\Program Files\Arduino\libraries\Adafruit_FONA/Adafruit_FONA.h:50:11: note:   no known conversion for argument 1 from 'int' to 'Stream&'
fona_data.ino: In function 'void TurnOnFona()':
fona_data:157: error: no matching function for call to 'Adafruit_FONA::begin(int)'
fona_data.ino:157:18: note: candidate is:
In file included from fona_data.ino:2:0:
C:\Program Files\Arduino\libraries\Adafruit_FONA/Adafruit_FONA.h:50:11: note: boolean Adafruit_FONA::begin(Stream&)
C:\Program Files\Arduino\libraries\Adafruit_FONA/Adafruit_FONA.h:50:11: note:   no known conversion for argument 1 from 'int' to 'Stream&'

User avatar
snoller
 
Posts: 34
Joined: Sun Mar 23, 2014 4:59 pm

Re: FONA + Ubidots IOT Platform Integration

Post by snoller »

please edit the Fona library and make all functions public by moving down the 'private:' statement in the Fona.h file.

User avatar
Allari
 
Posts: 2
Joined: Sat Oct 25, 2014 7:33 am

Re: FONA + Ubidots IOT Platform Integration

Post by Allari »

I've already done it. Some errors were gone, but these are still here. FonaTest works, but this code doesn't work.

User avatar
kbnetguy
 
Posts: 15
Joined: Wed Apr 08, 2015 9:03 pm

Re: FONA + Ubidots IOT Platform Integration

Post by kbnetguy »

OK Im not sure what I am doing wrong however I have tried implementing the code on the Ubidpts website http://ubidots.com/docs/devices/FONA.html#devices-fona however its not sending data to the variable in the code. As a simple test I am hard coding one variable to send to ubidots. I've included Token and Variable ID and I get a response that indicated failed. Would love to see if anyone can take a look at the code.

Code: Select all

Results from Serial Monitor

Turning off Fona 
Turning on Fona: 
	---> AT
	<--- AT
	---> AT
	<--- AT
	---> AT
	<--- AT
	---> ATE0
	<--- ATE0
	---> ATE0
	<--- OK
	---> AT+CVHU=0
	<--- OK
	---> ATI
	<--- SIM800 R13.08

OK

FONA is OK
	---> AT+CIPSHUT
	<--- SHUT OK
	---> AT+CGATT=1
	<--- OK
	---> AT+SAPBR=3,1,"CONTYPE","GPRS"
	<--- OK
	---> AT+SAPBR=3,1,"APN","epc.tmobile.com"
	<--- OK
	---> AT+SAPBR=3,1,"USER",""
	<--- OK
	---> AT+SAPBR=3,1,"PWD",""
	<--- OK
	---> AT+SAPBR=1,1
	<--- OK
Turn on
http://things.ubidots.com/api/v1.6/variables/56910c787625423044885ab2/values?token=twG9BwrMyj23KL455VXxRQGdZ89Q06
{"value":78}
****
	---> AT+HTTPTERM
	<--- ERROR
	---> AT+HTTPINIT
	<--- OK
	---> AT+HTTPPARA="CID"
	<--- OK
	---> AT+HTTPPARA="UA"
	<--- OK
	---> AT+HTTPPARA="URL"
	<--- OK
	---> AT+HTTPPARA="CONTENT"
	<--- OK
	---> AT+HTTPDATA=12,10000
	<--- DOWNLOAD
	<--- OK
	---> AT+HTTPACTION=1
	<--- OK
Status: 302
Len: 0
	---> AT+HTTPREAD
	<--- OK
Failed!

****
	---> AT+HTTPTERM
	<--- OK
	---> AT+CIPSHUT
	<--- SHUT OK
	---> AT+SAPBR=0,1
	<--- OK
	---> AT+CGATT=0
	<--- OK
Turn off
Turning off Fona 






ACTUAL CODE-------



#include <SoftwareSerial.h>
#include "Adafruit_FONA.h"
#include <stdlib.h>

// Pin connections:
#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
#define FONA_KEY 7
#define FONA_PS 8

// Ubidots token and variables
char token[] = "twG9BwrMyj23KL455VXxRQGdZ89Q06";
char id1[] = "56910c787625423044885ab2";
//char id2[] = "";
//char id3[] = "";
//char id4[] = "";

// this is a large buffer for replies
char replybuffer[255];

// or comment this out & use a hardware serial port like Serial1 (see below)
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);

uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);
int get_int_len(int);
void sendDataUbidots(void);

int value1, value2, value3, value4;
char buffer [33];

void setup() {
  //For FONA MODULE
  Serial.begin(115200);
  fonaSS.begin(4800);
  pinMode(FONA_KEY, OUTPUT);
  pinMode(FONA_PS, INPUT);
  analogReference(INTERNAL);
  delay(2000);
  TurnOffFona();

}

void loop() {
  flushSerial();
  TurnOnFona();
  checkFona();
  gprsOnFona();
  senseValues();

  while (fona.available()) {
    Serial.write(fona.read());
  }

  gprsOffFona();
  TurnOffFona();
  delay(600000);

}

void senseValues(){
  value1 = 78;
  //value1 = analogRead(A6);
  //value2 = analogRead(A7);
  //value3 = analogRead(A0);
  //value4 = analogRead(A1);

  ////////////////////////////////////////////

  sendDataUbidots(value1, id1);
  //sendDataUbidots(value2, id2);
  //sendDataUbidots(value3, id3);
  //sendDataUbidots(value4, id4);

  /////////////////////////////////////////////

}

void sendDataUbidots(int value, char* myid){

  uint16_t statuscode;
  int16_t length;

  char url1[] = "things.ubidots.com/api/v1.6/variables/";
  char* url2 = myid;
  char url3[] = "/values?token=";
  char* url4 = token;
  int lurl = strlen(url1) + strlen(url2) + strlen(url3) + strlen(url4);

  char url[lurl];
  sprintf(url,"%s%s%s%s",url1,url2,url3,url4);
//  Serial.println(url);

  char data1[] = "{\"value\":";
  char data2[get_int_len(value)+1];
  char data3[] = "}";
  itoa(value,data2,10);
  int ldata = strlen(data1) + strlen(data2) + strlen(data3);

  char data[ldata];
  sprintf(data,"%s%s%s",data1,data2,data3);
  //Serial.println(data);

  Serial.print(F("http://"));
  Serial.println(url);
  Serial.println(data);

   Serial.println(F("****"));
   if (!fona.HTTP_POST_start(url, F("application/json"), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) {
     Serial.println("Failed!");
   }
   while (length > 0) {
     while (fona.available()) {
       char c = fona.read();

  #if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
       loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */
       UDR0 = c;
  #else
       Serial.write(c);
  #endif

       length--;
       if (! length) break;
     }
   }
   Serial.println(F("\n****"));
   fona.HTTP_POST_end();

  // flush input
  flushSerial();
}

void flushSerial() {
    while (Serial.available())
    Serial.read();
}

char readBlocking() {
  while (!Serial.available());
  return Serial.read();
}

uint16_t readnumber() {
  uint16_t x = 0;
  char c;
  while (! isdigit(c = readBlocking())) {
    //Serial.print(c);
  }
  Serial.print(c);
  x = c - '0';
  while (isdigit(c = readBlocking())) {
    Serial.print(c);
    x *= 10;
    x += c - '0';
  }
  return x;
}

uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout) {
  uint16_t buffidx = 0;
  boolean timeoutvalid = true;
  if (timeout == 0) timeoutvalid = false;

  while (true) {
    if (buffidx > maxbuff) {
      //Serial.println(F("SPACE"));
      break;
    }

    while(Serial.available()) {
      char c =  Serial.read();

      //Serial.print(c, HEX); Serial.print("#"); Serial.println(c);

      if (c == '\r') continue;
      if (c == 0xA) {
        if (buffidx == 0)   // the first 0x0A is ignored
          continue;

        timeout = 0;         // the second 0x0A is the end of the line
        timeoutvalid = true;
        break;
      }
      buff[buffidx] = c;
      buffidx++;
    }

    if (timeoutvalid && timeout == 0) {
      //Serial.println(F("TIMEOUT"));
      break;
    }
    delay(1);
  }
  buff[buffidx] = 0;  // null term
  return buffidx;
}

int get_int_len (int value){
  int l=1;
  while(value>9){ l++; value/=10; }
  return l;
}

void checkFona(){
  // See if the FONA is responding
  if (! fona.begin(fonaSS)) {           // can also try fona.begin(Serial1)
    Serial.println(F("Couldn't find FONA"));
    while (1);
  }
  Serial.println(F("FONA is OK"));

  //configure a GPRS APN
  fona.setGPRSNetworkSettings(F("epc.tmobile.com"), F(""), F(""));
  //fona.setGPRSNetworkSettings(F("fast.t-mobile.com"), F(""), F(""));
}

void TurnOnFona(){
  Serial.println("Turning on Fona: ");
  while(digitalRead(FONA_PS)==LOW)
    {
    digitalWrite(FONA_KEY, LOW);
    }
    digitalWrite(FONA_KEY, HIGH);
    delay(4000);
}

void TurnOffFona(){
  Serial.println("Turning off Fona ");
  while(digitalRead(FONA_PS)==HIGH)
  {
    digitalWrite(FONA_KEY, LOW);
    }
    digitalWrite(FONA_KEY, HIGH);
    delay(4000);
}

void gprsOnFona(){
  while(!fona.enableGPRS(true));
  Serial.println(F("Turn on"));
}

void gprsOffFona(){
  while (!fona.enableGPRS(false));
  Serial.println(F("Turn off"));
}



User avatar
Oli_D
 
Posts: 1
Joined: Sat Feb 27, 2016 4:14 am

Re: FONA + Ubidots IOT Platform Integration

Post by Oli_D »

HI guys,

As a choister, I have a difficult choice now. I need some advice... Which IoT you are using now?. I know Xively, but I can't find any button to sign up. And IFTTT is good, but I am not sure whether SIM800 supports MQTT protocol, or only HTTP/GET service. Ubidots looks OK. it will be a option.

Could you share more service?

User avatar
kbnetguy
 
Posts: 15
Joined: Wed Apr 08, 2015 9:03 pm

Re: FONA + Ubidots IOT Platform Integration

Post by kbnetguy »

I really like you Ubidots and its ability to create dashboards etc. The support rocks. They are actually hosting a cron script on their server which sends wunderground data via json to my variables on my ubidots page. Great folks!!!

Locked
Please be positive and constructive with your questions and comments.

Return to “Other Products from Adafruit”