void log_mqtt(std::string payload) { if (!getenv("MQTT_SERVER")) { return; } init_mqtt(); int rc; if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) { std::cout << "Failed to connect to MQTT server, return code:" << rc << std::endl; return; } std::stringstream json; json << "{\"d\": " << payload << " }"; std::string jsonStr = json.str(); pubmsg.payload = &jsonStr; pubmsg.payloadlen = json.str().length(); pubmsg.qos = QOS; pubmsg.retained = 0; MQTTClient_publishMessage(client, getenv("MQTT_TOPIC"), &pubmsg, &token); std::cout << "Publishing to MQTT server on" << getenv("MQTT_TOPIC") << std::endl; std::cout << json.str() << std::endl; rc = MQTTClient_waitForCompletion(client, token, TIMEOUT); std::cout << "MQTT message delivered" << std::endl; MQTTClient_disconnect(client, 10000); }
int main (int ac, char **av){ char l[1024]; /* Creates threads as detached in order to save * some resources when quiting */ assert(!pthread_attr_init (&thread_attr)); assert(!pthread_attr_setdetachstate (&thread_attr, PTHREAD_CREATE_DETACHED)); L = lua_open(); /* opens Lua */ luaL_openlibs(L); /* and it's libraries */ atexit(clean_lua); luaL_openlib(L,"Selene", seleneLib, 0); /* Declare Selene's functions */ init_shared(L); init_SelTimer(L); init_SelCollection(L); init_SelTimedCollection(L); init_SelTimedWindowCollection(L); init_SelFIFO(L); init_log(L); init_SelEvent(L); #ifdef USE_MQTT init_mqtt(L); #endif lua_pushnumber(L, VERSION); /* Expose version to lua side */ lua_setglobal(L, "SELENE_VERSION"); if(ac > 1){ if(ac > 2){ /* Handle script's arguments */ luaL_checkstack(L, ac-1, "too many arguments to script"); /* Place for args (ac-2) + the table itself */ lua_createtable(L, ac-2, 0); for(int i=2; i<ac; i++){ lua_pushstring(L, av[i]); lua_rawseti(L, -2, i-1); } lua_setglobal(L, "arg"); } char *t = strdup( av[1] ); /* Launching script */ assert(t); lua_pushstring(L, dirname(t) ); lua_setglobal(L, "SELENE_SCRIPT_DIR"); strcpy(t, av[1]); lua_pushstring(L, basename(t) ); lua_setglobal(L, "SELENE_SCRIPT_NAME"); int err = luaL_loadfile(L, av[1]) || lua_pcall(L, 0, 0, 0); if(err){ fprintf(stderr, "%s", lua_tostring(L, -1)); lua_pop(L, 1); /* pop error message from the stack */ exit(EXIT_FAILURE); } } else while(fgets(l, sizeof(l), stdin) != NULL){ int err = luaL_loadbuffer(L, l, strlen(l), "line") || lua_pcall(L, 0, 0, 0); if(err){ fprintf(stderr, "%s\n", lua_tostring(L, -1)); lua_pop(L, 1); /* pop error message from the stack */ } } exit(EXIT_SUCCESS); }