sdk-adam4015-mqtt-publish.are
DEV = "SERIAL2";
SLAVEID = 1;
 
HOST = "123.123.123.123"; 
PORT = 1883;
KEEPALIVE = 60;
PROTOCOL = "V31";
USERNAME = "mqtt-username";
PASSWORD = "mqtt-password";
CLIENT_ID = "SDK-GPS";
TOPIC = "mqtt-topic";
QOS = 0;
RETAIN = 0; 
MESSAGE = "";
CLEAN_SESSION = true;
MQTT_HANDLE = 0;
 
/*create new mqtt instance*/
MQTT_HANDLE = nb_mqttlib_new(CLIENT_ID, CLEAN_SESSION);
 
 /* check serial port config */
st = nb_config_get("serial.1.status");
if (st != "2") {
    nb_syslog("Serial port is not enabled for us");
    exit(1);
}
 
/* set attributes */
ret = nb_serial_setattr(DEV, 9600, 8, 1, 0, 0);
if (ret != 0) {
    printf("Could not set serial attributes: %i \n",ret);
    exit(1);
}
 
/* open serial port */
fd = nb_serial_open(DEV);
if (fd < 0) {
    printf("Unable to open %s\n", DEV);
    exit(1);
}
 
/* register fd for modbus functions */
if (nb_modbus_register(fd, MODBUS_TYPE_RTU) < 0) {
    printf("Unable to register to modbus\n");
    exit(1);
}
 
/* set slave id */
if (nb_modbus_set_slave(fd, SLAVEID) < 0) {
    printf("Unable to set slave identifier\n");
    exit(1);
}
 
if (nb_mqttlib_set_protocol_version(MQTT_HANDLE, PROTOCOL)  < 0 ) {
  printf("Unable to set Protocol version\n");
    exit(1);
}
 
if (nb_mqttlib_set_user_pw(MQTT_HANDLE, USERNAME, PASSWORD) < 0 ) {
	printf("Unable to set Username and Passsword\n");
 
	exit(1);
}
 
if (nb_mqttlib_connect(MQTT_HANDLE, HOST, PORT, KEEPALIVE) < 0 ) {
	printf("Unable to connect\n");
	exit(1);
}
 
 
while (1) {
 
/* read 1 registers from address 0*/
data = nb_modbus_read_input_regs(fd, 0, 1);
/*write word from array in variable*/
word=(int) data[0];
/*convert PT100 data to temperature*/
temp=(float) word / 65535 * 100;
 
//printf("%f\n",temp);
 
MESSAGE=sprintf("%f",temp);
 
ret = nb_mqttlib_publish(MQTT_HANDLE, TOPIC, MESSAGE, QOS, RETAIN);
 
if(ret<0){
			nb_syslog("Failed to publish mqtt message");
	}
 
sleep(60);
}
 
exit(0);