Copyright © https://mongoose-os.com

Mongoose OS Forum

frame

MQTT unsubscribe from topic

bs_alexbs_alex Barcelona

Hi there,

I am trying to unsubscribe from a MQTT topic using the C function:

mg_mqtt_unsubscribe - (https://github.com/mongoose-os-libs/mongoose/blob/f77042513b04137a2e1955a5b1e609308d168283/include/mongoose.h#L5675)

I am coding using the Web UI and JS, so I am suposed to use a wrapper to call the function (https://github.com/cesanta/mjs/blob/master/README.md#cc-interoperability).
I have been trying to make it with no luck.

Could anyone give me a hand on this?
Thanks in advance.

Comments

  • nliviunliviu Romania
    edited April 7

    Unfortunately, it's not possible to ffi directly because of the argument char **topics which is not supported by mjs (Function arguments should be simple: only int, double, char *, void * are supported).
    You have to wrap it in a simpler C function in main.c:

    #include "mgos_mqtt.h"
    
    void mqttUnsubscribe(char* topic) {
      struct mg_connection* nc = mgos_mqtt_get_global_conn();
      if (nc) {
        // void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,size_t topics_len, uint16_t message_id);
        mg_mqtt_unsubscribe(nc, &topic, 1, mgos_mqtt_get_packet_id());
      }
    }
    

    You can ffi this one:

    let unsubscribe = ffi('void mqttUnsubscribe(char*)');
    
    Thanked by 1bs_alex
  • bs_alexbs_alex Barcelona

    Thanks. Sorry if this is a too basic question, but how can I edit main.c file from the WEB UI, if I am coding a JS app?

  • nliviunliviu Romania

    Did you import an application or created your own in WebUI? What is your OS?
    Assuming you imported a predefined app for js and using Windows.
    First add

    sources:
     - src
    

    in mos.yml and save it.
    Try to create a new file with the name src/main.c and you will see an arror similar to Server Error: {"error":"open C:\\Users\\<user_name>\\.mos\\apps-latest\\demo-js\\src\\main.c: The system cannot find the path specified."}
    This means that the src directory does not exist.
    Open a command prompt and create the src directory mkdir C:\Users\<user_name>\.mos\apps-latest\demo-js\src (your real path will be different).

    Return to the WebUI and create src/main.c, select it from the files combo-box, edit, save it and build.

    PS. If you are not on Windows, the approach is very similar.

  • bs_alexbs_alex Barcelona

    It worked, I owe you a beer.
    Thanks

  • nliviunliviu Romania

    I'm drinking one right now :wink:

Sign In or Register to comment.