ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • MQTT(mosquitto) Visual studio - 2 (Publisher)
    Network 2021. 3. 8. 21:15

    간단하게 Publish 할 수 있는 Client를 제작해 봅니다.

    <Header>

    #include <stdio.h>
    #include <stdlib.h>
    #include <windows.h>
    #include <mosquitto.h>
    
    #define sleep(x) Sleep((x)*1000)
    #define strdup _strdup
    
    #define DEFAULT_MQTT_HOST "127.0.0.1"
    #define DEFAULT_MQTT_PORT 1883
    #define DEFAULT_MQTT_KEEPALIVE 60
    #define DEFAULT_MQTT_TOPIC "EXAMPLE_TOPIC"
    
    #define BUF_LENGTH 65536

     

    <Callback Function>

    void connect_callback(struct mosquitto *mosq, void *obj, int result) {
    	printf("connect callback, rc=%d\n", result);
    }
    
    void message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) {
    	printf("message '%.*s' for topic '%s'\n", msg->payloadlen, (char *)msg->payload, msg->topic);
    }
    

     

    <main>

    int main(int argc, char **argv)
    {
    	int rc;
    	char *mqtt_host = strdup(DEFAULT_MQTT_HOST);
    	char *mqtt_topic = strdup(DEFAULT_MQTT_TOPIC);
    	int mqtt_port = DEFAULT_MQTT_PORT;
    	int mqtt_keepalive = DEFAULT_MQTT_KEEPALIVE;
    
    	int mdelay = 0;
    	bool clean_session = true;
    	
    	struct mosquitto *mosq = NULL;
    
    	mosquitto_lib_init();
    	mosq = mosquitto_new(NULL, clean_session, NULL);
    	if (!mosq) {
    		fprintf(stderr, "Could not create new mosquitto struct\n");
    		exit(1);
    	}
    
    	if (mosquitto_connect(mosq, mqtt_host, mqtt_port, mqtt_keepalive)) {
    		fprintf(stderr, "Unable to connect mosquitto.\n");
    		exit(1);
    	}
    
    	char buf[BUF_LENGTH];
    
    	do {
    		rc = mosquitto_loop(mosq, -1, 1);
    
    		scanf_s("%s", buf, BUF_LENGTH);
    		if (!strcmp(buf, "exit")) break;
    
    		rc = mosquitto_publish(mosq, NULL, mqtt_topic,  strlen(buf), buf, 0, 0);
    		if (rc != MOSQ_ERR_SUCCESS) {
    			fprintf(stderr, "Error publishing: %s\n", mosquitto_strerror(rc));
    		}
    		
    	} while (rc == MOSQ_ERR_SUCCESS);
    
    	mosquitto_destroy(mosq);
    	mosquitto_lib_cleanup();
    	free(mqtt_host);
    	free(mqtt_topic);
    
    	return 0;
    }
    

     

    댓글

Designed by Tistory.