integrading two different WiFi libraries, DNS lookup

Still having issues with my m2x project…

i was using an adafruit NTP example to get the time and then integraded with cattledog’s help for getting that into an iso8601 format… Then i went to integrate with my m2x project which is based off of sparkfun WiFi libraries.

I am using a Mega and writing in ATmel studio.

The problem that i am having is in the section where it wants to grab the IP address of the NTP time server. adafruit uses “getHostByName”, and, as best i can tell reading through the .h and .cpp lib’s, sparkfun uses dnsLoopUp. Secondarily and already fixed, adafruit uses prefix “cc3000”, whereas sparkfun uses “wifi”.

The NTP section is at the bottom of this example sketch in the “gettime()”:

/***************************************************
  This is an example for the Adafruit CC3000 Wifi Breakout & Shield

  Designed specifically to work with the Adafruit WiFi products:
  ----> https://www.adafruit.com/products/1469

  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, Kevin Townsend and Phil Burgess for
  Adafruit Industries.  BSD license, all text above must be included
  in any redistribution
*/
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <Time.h>
uint32_t unixTimestamp = 0;
uint32_t syncProvider()
{
 return unixTimestamp;
}

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
                                         SPI_CLOCK_DIVIDER); // you can change this clock speed but DI

#define WLAN_SSID       "HOME-61B2"        // cannot be longer than 32 characters!
#define WLAN_PASS       "removed"
#define WLAN_SECURITY   WLAN_SEC_WPA2

Adafruit_CC3000_Client client;

const unsigned long
  connectTimeout  = 15L * 1000L, // Max time to wait for server connection
  responseTimeout = 15L * 1000L; // Max time to wait for data from server
int
  countdown       = 0;  // loop() iterations until next time server query
unsigned long
  lastPolledTime  = 0L, // Last value retrieved from time server
  sketchTime      = 0L; // CPU milliseconds since last server query


void setup(void)
{
 setSyncProvider(syncProvider);//sets internal clock
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n")); 

  displayDriverMode();
  
  Serial.println(F("\nInitialising the CC3000 ..."));
  if (!cc3000.begin()) {
    Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
    for(;;);
  }

  uint16_t firmware = checkFirmwareVersion();
  if (firmware < 0x113) {
    Serial.println(F("Wrong firmware version!"));
    for(;;);
  } 
  
  displayMACAddress();
  
  Serial.println(F("\nDeleting old connection profiles"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Failed!"));
    while(1);
  }

  /* Attempt to connect to an access point */
  char *ssid = WLAN_SSID;             /* Max 32 chars */
  Serial.print(F("\nAttempting to connect to ")); Serial.println(ssid);
  
  /* NOTE: Secure connections are not available in 'Tiny' mode! */
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }
   
  Serial.println(F("Connected!"));
  
  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP()) {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  /* Display the IP address DNS, Gateway, etc. */  
  while (!displayConnectionDetails()) {
    delay(1000);
  }
}


// To reduce load on NTP servers, time is polled once per roughly 24 hour period.
// Otherwise use millis() to estimate time since last query.  Plenty accurate.
void loop(void) {

  if(countdown == 0) {            // Time's up?
    unsigned long t  = getTime(); // Query time server
    if(t) {                       // Success?
      lastPolledTime = t;         // Save time
      sketchTime     = millis();  // Save sketch time of last valid time query
      countdown      = 24*60*4-1; // Reset counter: 24 hours * 15-second intervals
    }
  } else {
    countdown--;                  // Don't poll; use math to figure current time
  }

  unsigned long currentTime = lastPolledTime + (millis() - sketchTime) / 1000;

  Serial.print(F("Current UNIX time: "));
  Serial.print(currentTime);
  Serial.println(F(" (seconds since 1/1/1970 UTC)"));
  unixTimestamp=currentTime;
 setSyncProvider(syncProvider);//sets internal clock
  
   delay(15000L); // Pause 15 seconds 
   Serial.println("");

   char buffer[21];
   sprintf(buffer,"%d-%02d-%02dT%02d:%02d:%02dZ\0",year(),month(),day(),hour(),minute(),second());
   Serial.println(buffer);
   String stringTime = (buffer);
   Serial.println(stringTime);
   }

   
   void printDigits(int digits)
   {
   // utility function for digital clock display: prints preceding colon and leading 0
   Serial.print(':');
   if(digits < 10)
   Serial.print('0');
   Serial.print(digits);
   }




/**************************************************************************/
/*!
    @brief  Tries to read the IP address and other connection details
*/
/**************************************************************************/
bool displayConnectionDetails(void)
{
  uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;
  
  if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
  {
    Serial.println(F("Unable to retrieve the IP Address!\r\n"));
    return false;
  }
  else
  {
    Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
    Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
    Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
    Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
    Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
    Serial.println();
    return true;
  }
}

// Minimalist time server query; adapted from Adafruit Gutenbird sketch,
// which in turn has roots in Arduino UdpNTPClient tutorial.
unsigned long getTime(void) {

  uint8_t       buf[48];
  unsigned long ip, startTime, t = 0L;

  Serial.print(F("Locating time server..."));

  // Hostname to IP lookup; use NTP pool (rotates through servers)
  if(cc3000.getHostByName("pool.ntp.org", &ip)) {
    static const char PROGMEM
      timeReqA[] = { 227,  0,  6, 236 },
      timeReqB[] = {  49, 78, 49,  52 };

    Serial.println(F("\r\nAttempting connection..."));
    startTime = millis();
    do {
      client = cc3000.connectUDP(ip, 123);
    } while((!client.connected()) &&
            ((millis() - startTime) < connectTimeout));

    if(client.connected()) {
      Serial.print(F("connected!\r\nIssuing request..."));

      // Assemble and issue request packet
      memset(buf, 0, sizeof(buf));
      memcpy_P( buf    , timeReqA, sizeof(timeReqA));
      memcpy_P(&buf[12], timeReqB, sizeof(timeReqB));
      client.write(buf, sizeof(buf));

      Serial.print(F("\r\nAwaiting response..."));
      memset(buf, 0, sizeof(buf));
      startTime = millis();
      while((!client.available()) &&
            ((millis() - startTime) < responseTimeout));
      if(client.available()) {
        client.read(buf, sizeof(buf));
        t = (((unsigned long)buf[40] << 24) |
             ((unsigned long)buf[41] << 16) |
             ((unsigned long)buf[42] <<  8) |
              (unsigned long)buf[43]) - 2208988800UL;
        Serial.print(F("OK\r\n"));
      }
      client.close();
    }
  }
  if(!t) Serial.println(F("error"));
  return t;
}

My attempt to integrate is the following, at the end again:

/****
M2X_CC3000_Post.ino
Post temperature data to AT&T's M2X
Shawn Hymel @ SparkFun Electronics
August 19, 2014
*/
#include <SPI.h>
#include <SFE_CC3000.h>
#include <SFE_CC3000_Client.h>
#include <jsonlite.h>
#include <M2XStreamClient.h>
#include <Wire.h>
#include <Time.h>
uint32_t unixTimestamp = 0;

uint32_t syncProvider()
{
	return unixTimestamp;
}

//time initialization:
const unsigned long
connectTimeout  = 15L * 1000L, // Max time to wait for server connection
responseTimeout = 15L * 1000L; // Max time to wait for data from server
int
countdown       = 0;  // loop() iterations until next time server query
unsigned long
lastPolledTime  = 0L, // Last value retrieved from time server
sketchTime      = 0L; // CPU milliseconds since last server query


// Parameters
#define POST_DELAY_MS   60000 // Post to stream every 10 seconds

// Pins
#define CC3000_INT      3   // Needs to be an interrupt pin (D2/D3)
#define CC3000_EN       5   // Can be any digital pin
#define CC3000_CS       10  // Preferred is pin 10 on Uno

// Connection info data lengths
#define IP_ADDR_LEN     4   // Length of IP address in bytes

// WiFi Constants
char ap_ssid[] = "HOME-61B2";                  // SSID of network
char ap_password[] = "0C6B7DEB3241400F";          // Password of network
unsigned int ap_security = WLAN_SEC_WPA2; // Security of network
unsigned int timeout = 30000;             // Milliseconds


// M2X Constants***
char buffer[21];
char feedId[] =         "704c6c304c44c7505df9d4dc444b159e";
char m2xKey[]    =     "c26fd5082c394e2c111cb7fe73d47a8f";
const char *streamNames[] = { "distance", "light" };
int counts[] = { 2, 1 };
const char *ats[] = {buffer};
double values[] = { 10.0, 20.0, 7.5 };


// Global Variables
SFE_CC3000 wifi = SFE_CC3000(CC3000_INT, CC3000_EN, CC3000_CS);
SFE_CC3000_Client client = SFE_CC3000_Client(wifi);
M2XStreamClient m2xClient(&client, m2xKey);

const int photoPin=0;
int light;
const int sonicPin=4;
long sensor,distance;

int g_response;

// Setup. Configure HTU21D, WiFi, and M2X.
void setup() {

	g_response = 0;
	
	// Initialize UART for debugging
	Serial.begin(115200);
	Serial.println();
	Serial.println(F("SparkFun CC3000 - M2X Post"));

	//sensor ini
	pinMode(sonicPin,INPUT);

	// Initialize CC3000 (configure SPI communications)
	if ( wifi.init() ) {
		Serial.println(F("CC3000 initialization complete"));
		} else {
		Serial.println(F("Something went wrong during CC3000 init!"));
	}

	// Connect using DHCP
	Serial.print(F("Connecting to SSID: "));
	Serial.println(ap_ssid);
	if(wifi.connect(ap_ssid, ap_security, ap_password, timeout)) {
		Serial.println(F("Connected!"));
		} else {
		Serial.println(F("Error: Could not connect to AP"));
	}	
}

void isoTime()
{
	 if(countdown == 0) {            // Time's up?
		unsigned long t  = getTime(); // Query time server
		 if(t) {                       // Success?
			 lastPolledTime = t;         // Save time
			 sketchTime     = millis();  // Save sketch time of last valid time query
			 countdown      = 24*60*4-1; // Reset counter: 24 hours * 15-second intervals
		 }
		 } else {
		 countdown--;                  // Don't poll; use math to figure current time
	 }
	 unsigned long currentTime = lastPolledTime + (millis() - sketchTime) / 1000;
	 unixTimestamp=currentTime;
	 char buffer[21];
	 sprintf(buffer,"%d-%02d-%02dT%02d:%02d:%02dZ\0",year(),month(),day(),hour(),minute(),second());
	 Serial.println(buffer);
}

// Main loop. Post sensor readings at regular intervals.
void loop() {

	// Read sensor
	sensor=pulseIn(sonicPin,HIGH);
	distance=sensor/147;
	light=analogRead(photoPin);
	isoTime();
	// Print reading to console with degree symbol and 'C'
	Serial.print(F("Inches: "));
	Serial.println(distance);
	Serial.print(F("Lumens"));
	Serial.println(light);
	//Serial.println (ats);
	// Post data to your stream
	g_response = m2xClient.postMultiple(feedId, 2, streamNames, counts, ats,values);

	// If we fail to receive a response, stop running
	Serial.print(F("Post response: "));
	Serial.println(g_response);
	if ( g_response == -1 ) {
		while(1);
	}

	// Wait to post to stream again
	delay(POST_DELAY_MS);
}
unsigned long getTime(void) {

	uint8_t       buf[48];
	unsigned long ip_address, startTime, t = 0L;

	Serial.print(F("Locating time server..."));

	// Hostname to IP lookup; use NTP pool (rotates through servers)
	if(wifi.dnsLookup("pool.ntp.org", &ip_address)) {
		static const char PROGMEM
		timeReqA[] = { 227,  0,  6, 236 },
		timeReqB[] = {  49, 78, 49,  52 };

		Serial.println(F("\r\nAttempting connection..."));
		startTime = millis();
		do {
			client.connectUDP(ip_address, 123);
		} while((!client.connected()) &&
		((millis() - startTime) < connectTimeout));

		if(client.connected()) {
			Serial.print(F("connected!\r\nIssuing request..."));

			// Assemble and issue request packet
			memset(buf, 0, sizeof(buf));
			memcpy_P( buf    , timeReqA, sizeof(timeReqA));
			memcpy_P(&buf[12], timeReqB, sizeof(timeReqB));
			client.write(buf, sizeof(buf));

			Serial.print(F("\r\nAwaiting response..."));
			memset(buf, 0, sizeof(buf));
			startTime = millis();
			while((!client.available()) &&
			((millis() - startTime) < responseTimeout));
			if(client.available()) {
				client.read(buf, sizeof(buf));
				t = (((unsigned long)buf[40] << 24) |
				((unsigned long)buf[41] << 16) |
				((unsigned long)buf[42] <<  8) |
				(unsigned long)buf[43]) - 2208988800UL;
				Serial.print(F("OK\r\n"));
			}
			client.close();
		}
	}
	if(!t) Serial.println(F("error"));
	return t;
}

If i leave the SFE library as default, i get the following compile error:

m2x_s1_2feed.ino:In function 'long unsigned int getTime()'
m2x_s1_2feed.ino:181:47: error: no matching function for call to 'SFE_CC3000::dnsLookup(const char [13], long unsigned int*)'
:if(wifi.dnsLookup("pool.ntp.org", &ip_address)) {
:^
m2x_s1_2feed.ino:candidate is
m2x_s1_2feed.ino:In file included from
SFE_CC3000.h:dnsLookup(char*, IPAddress*)
:bool dnsLookup(char *hostname, IPAddress  *ip_address);

the library section from the .cpp follows:

bool SFE_CC3000::dnsLookup(char *hostname, IPAddress *ip_address)
{
    unsigned long ret_ip_addr = 0;

    /* If CC3000 is not initialized, return false. */
	if (!getInitStatus()) {
        return false;
    }
    
    /* If not connected, return false. */
    if (!getConnectionStatus()) {
        return false;
    }
    
    /* If DHCP has not been assigned, return false. */
    if (!getDHCPStatus()) {
        return false;
    }

    /* Attempt to get IP address by hostname */
    if (!gethostbyname(hostname, strlen(hostname), &ret_ip_addr)) {
        return false;
    }

    *ip_address = IPAddress(
        (uint8_t)(ret_ip_addr >> 24) & 0xFF,
        (uint8_t)(ret_ip_addr >> 16) & 0xFF,
        (uint8_t)(ret_ip_addr >> 8) & 0xFF,
        (uint8_t)ret_ip_addr & 0xFF);

    return true;
}

in contrast, the adafruit .cpp section for the same style function looks like this:

#ifndef CC3000_TINY_DRIVER
uint16_t Adafruit_CC3000::getHostByName(char *hostname, uint32_t *ip) {
  if (!_initialised) return 0;
  if (!cc3000Bitset.test(CC3000BitSet::IsConnected)) return 0;
  if (!cc3000Bitset.test(CC3000BitSet::HasDHCP)) return 0;

  int16_t r = gethostbyname(hostname, strlen(hostname), ip);
  //if (CC3KPrinter != 0) { CC3KPrinter->print("Errno: "); CC3KPrinter->println(r); }
  return r;
}
#endif

or maybe its this section?..

int Adafruit_CC3000_Client::connect(const char *host, uint16_t port){
  
  // if (!_initialised) return 0;
  // if (!ulCC3000Connected) return 0;
  // if (!ulCC3000DHCP) return 0;

  uint32_t ip = 0;

  int16_t r = gethostbyname(host, strlen(host), &ip);

  if (ip!=0 && r!=0)
    return connect(ip, port);
  else 
    return 0;
}