LiamBindle / MQTT-C

A portable MQTT C client for embedded systems and PCs alike.
https://liambindle.ca/MQTT-C
MIT License
774 stars 275 forks source link

Publish File #84

Closed the-mind closed 4 years ago

the-mind commented 4 years ago

How can I publish a file, like a zip file or a binary using mqtt-c ? Please help.

LiamBindle commented 4 years ago

@the-mind A zip file is just an array of bytes (i.e. a 13.4 KB zip file is simply 13400 bytes that are structured in the zip file format). To send a zip file with MQTT-C I would do something like this:

  1. Open and copy the zip file's bytes into an local array (e.g. open the file, for each byte in the 13400 bytes, copy it into a local void* array that's at least 13400 bytes)
  2. Publish that array as an MQTT message. The void * where you copied the zip file is your application message, and the application message size is 13400.

The documentation of publishing with MQTT-C is here. Note that application_message is a void* (i.e. it's anything...it's just a series of bytes). Note that the application_message is not a character array--it's a series of raw bytes.

Does that help? Let me know if I can clarify anything.

the-mind commented 4 years ago

This is the snippet of my C code as it is. I'm honestly really not that good in C

    FILE *filepointer;
    void *buffer;
    long filelen;

    filepointer = fopen("mqtttest.zip", "rb");  // Open the file in binary mode
    fseek(filepointer, 0, SEEK_END);          // Jump to the end of the file
    filelen = ftell(filepointer);             // Get the current byte offset in the file
    rewind(filepointer);                      // Jump back to the beginning of the file

    buffer = (void *)malloc(filelen * sizeof(void)); // Enough memory for the file
    fread(buffer, filelen, 1, filepointer); // Read in the entire file
    fclose(filepointer);

    mqtt_publish(&client, topic, buffer, filelen + 1, MQTT_PUBLISH_QOS_0);

Where could I be going wrong ? It's not successfully publishing data as it should. Could you also share a snippet that could work? Or help me debug mine?

LiamBindle commented 4 years ago

I took a quick look at your snippet and nothing jumps out at me. Here are a couple suggestions that might help you troubleshoot:

  1. Is the broker receiving your message? If you set up a different client and subscribe to your topic, do you see the same bytes come through?
  2. You could check the MD5 sum of your buffer, and make sure it's the same as the MD5 sim of mqtttest.zip on your disk. It would be useful to also check if your receiving client gets the same checksum.
  3. How big is the file? MQTT can't handle messages larger than 260 MB (iirc).

Good luck!