#include "DFRobot_Iot.h"
#include "DFRobot_BC20.h"

DFRobot_Iot myDevice;
DFRobot_BC20 myBC20;

/*Configure device certificate information*/
String ProductKey = "Your_Product_Key";
String ClientId = "12345";/*Custom id*/
String DeviceName = "Your_Device_Name";
String DeviceSecret = "Your_Device_Secret";

/*Configure the domain name and port number*/
String ALIYUN_SERVER = "iot-as-mqtt.cn-shanghai.aliyuncs.com";
uint16_t PORT = 1883;

/*Product identifier that needs to be operated*/
String Identifier = "Your_Identifier";

/*TOPIC that need to be published and subscribed*/
const char * subTopic = "Your_subTopic";//****set
const char * pubTopic = "Your_pubTopic";//******post

DFRobot_Iot myIot;

void ConnectCloud() {
  while (!myBC20.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (myBC20.connect(myDevice._clientId, myDevice._username, myDevice._password)) {
      Serial.println("Connect Server OK");
    }
    else {
      myBC20.getQMTCONN();
    }
  }
}
void setup(){
  Serial.begin(115200);

  Serial.print("Starting the BC20.Please wait. . . ");
  while(!myBC20.powerOn()){
      delay(1000);
      Serial.print(".");
  }
  Serial.println("BC20 started successfully !");
  Serial.println("check OK");
  while (!myBC20.checkNBCard()) {
    Serial.println("Please insert the NB card !");
    delay(1000);
  }
  Serial.println("Waitting for access ...");
  while (myBC20.getGATT() == 0) {
    Serial.print(".");
    delay(1000);
  }
  if(myBC20.getQGNSSC() == OFF){
      Serial.println("open QGNSSC");
      myBC20.setQGNSSC(ON);
  }

  myDevice.init(ALIYUN_SERVER, ProductKey, ClientId, DeviceName, DeviceSecret);
  myBC20.setServer(myDevice._mqttServer, PORT);
  //myBC20.setCallback(callback);
  ConnectCloud();
}

void loop(){
  ConnectCloud();

  myBC20.getCLK();  // Get CLK from BC20
  myBC20.getQGNSSRD();
  myBC20.loop();
  myBC20.publish(pubTopic, ("{\"id\":"+ClientId+",\"params\":{\""+Identifier+"\":{\"value\":{\"Longitude\":"+String(sGGNS.LongitudeVal,6)+",\"Latitude\":"+String(sGGNS.LatitudeVal,6)+",\"Altitude\":"+String(sGGNS.Altitude,6)+",\"CoordinateSystem\":"+(String)2+"}}},\"method\":\"thing.event.property.post\"  }"));
  Serial.println("Data is published to cloud.");
  delay(10000);
}
