/* DESC: Advanced version of mqtt_simple_status.are using a template * to easily change topics, publish new messages or create several * different connections. * Copyright (C) 2018 NetModule AG, Switzerland */ template mqtt_status{ /* mqtt variables */ HOST = ""; PORT = 1883; USERNAME = ""; PASSWORD = ""; TOPIC=""; MESSAGE=""; QOS = 0; /* 0 = publish at most once (fire & forget) , 1 = publish at least once, 2 = publish exactly once */ RETAIN = 0; /* 1 = the message will be stored and send to a new subscriber of that topic */ /* Constructor to initialize mqtt settings */ /* hostname, port, username, password for mqtt broker connection */ /* also a topic must be set via set_topic() */ void mqtt_status(string h, int p, string u, string up){ this.HOST = h; this.PORT = p; this.USERNAME = u; this.PASSWORD = up; // printf("%s, %i, %s, %s", this.HOST, this.PORT, this.USERNAME, this.PASSWORD); } void set_topic(string t){ this.TOPIC = t; } /* Queries nb_status() with provided sections to return the value of desired field */ string status_query(string section, string status_value){ stat_info = nb_status(section); ret = struct_get(stat_info, sprintf("%s", status_value)); if(is_void(stat_info) || is_void(ret)){ return "Couldn't get status"; }else{ return ret; } } /* The publish function to publish a message */ int publish(string msg){ this.MESSAGE = msg; ret = nb_mqtt_publish(this.HOST, this.PORT, this.USERNAME, this.PASSWORD, this.TOPIC, this.QOS, this.RETAIN, this.MESSAGE); if(ret<0){ return -1; }else{ return 0; } } } /* The actual script --- simple example as in mqtt_simple_status.are */ /* mqtt connection settings for the template */ p = new mqtt_status("192.168.240.1", 1883, "test", "test"); /* Set a topic to publish to */ p.set_topic("mycompany/bus1/"); /* Simple loop publishing status messages 10 times with an interval of 60 secs */ for (cnt=0; cnt<10; cnt++){ /* Use status_query() to get desired system infos */ sys_tmp = p.status_query("system", "TEMPERATURE"); mob1_service = p.status_query("wwan", "MOBILE1_SERVICE_TYPE"); mob1_signal = p.status_query("wwan", "MOBILE1_SIGNAL_LEVEL"); gps_long = p.status_query("gnss", "GNSS1_LONGITUDE"); gps_lat = p.status_query("gnss", "GNSS1_LATITUDE"); /* Compose a status message to be published */ msg = sprintf("Status info: \n temp: %s \n mobile1 service: %s\n mobile 1 signal: %s\n gps long: %s\n gps lat %s\n",sys_tmp, mob1_service, mob1_signal, gps_long, gps_lat); /* Publis the message */ stat = p.publish(msg); if(stat<0){ nb_syslog("Failed to publish mqtt message"); } sleep(60); } /* Change to another topic */ p.set_topic("mycompany/bus1/status/"); /* Publish another Message to the new topic */ p.publish("Status update done"); exit(0);