// Author: Xiaohai Li (xhli@citytech.cuny.edu)
// Robotics Research Lab, NYC College of Technology of CUNY
// License: GPL V2.0
// 04/16/2018

// To send binary number 0 and 1 recursively from Photon to IBM Watson IoT Platform Quickstart,
// then you can use the Quickstart to visualization the data.

// This #include statement was automatically added by the Particle IDE.
#include <MQTT.h>

#define HOST_PORT  1883
#define MQTT_QoS   0

// To connect and use IBM Watson IoT Platform Quickstart service, need to set
// Organization ID: quickstart
// authentication:  not required.
char *IOT_HOST = "quickstart.messaging.internetofthings.ibmcloud.com"; 
char *IOT_CLIENT = "d:quickstart:your_DeviceType_here: your_DeviceID_here";
// "d:orgnizationID:DeviceType:DeviceID";
char *IOT_USERNAME = NULL;  // 
char *IOT_PASSWORD = NULL;  //
char *IOT_TOPIC = "iot-2/evt/testdata/fmt/json";

MQTT client( IOT_HOST, HOST_PORT, callback );

bool flag = 1;
int IndicatorLed = D7;
char payload[80];

void setup() {
  pinMode(IndicatorLed, OUTPUT);
  Serial.begin( 9600 );
  Serial.println( "Connecting Photon to IBM Watson IoT Platform ...... " );

  while( !Serial.available() ) {
    Particle.process();
  }  

  client.connect( IOT_CLIENT, IOT_USERNAME, IOT_PASSWORD  );

  if( client.isConnected() ) {
    Serial.println( "Now connected!" );
    // client.subscribe( IOT_SUBSCRIBE );
  }
}

void loop() {
  sprintf(payload, "{ \"binary\": \"%d\" }", flag);
 
  client.publish(IOT_TOPIC, const_cast<char*> (payload) ); 
 
  digitalWrite(IndicatorLed, HIGH);
  delay(100);
  digitalWrite(IndicatorLed, LOW);
  delay(100);
   
  client.loop();

  Serial.print( "Data being sent to Cloud: " );
  Serial.println( flag );
  delay( 3000 );
 
  flag = (!flag);
}

void callback( char* topic, byte* payload, unsigned int length ) {
  char p[length + 1];
   
  memcpy( p, payload, length );
  p[length] = NULL;
   
  String message( p );
}