Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

R&D: JSON serialization #5

Open
asimfarooq5 opened this issue Sep 24, 2024 · 2 comments
Open

R&D: JSON serialization #5

asimfarooq5 opened this issue Sep 24, 2024 · 2 comments

Comments

@asimfarooq5
Copy link
Collaborator

asimfarooq5 commented Sep 24, 2024

Need to check JSON serialization

@asimfarooq5
Copy link
Collaborator Author

JSON serializer

This project demonstrates how to serialize and deserialize WAMP messages on an ESP32 using the ArduinoJson library. It provides simple methods to convert WAMP messages into JSON format

Open Arduino IDE.

Go to Sketch -> Include Library -> Manage Libraries...
Search for "ArduinoJson by Benoit" and install the latest version.
Create new Sketch and copy the code.

#include <ArduinoJson.h>

// Define a basic WAMP Message structure for demonstration.
struct WAMPMessage {
    int type;
    const char* message;

    void marshal(JsonDocument& doc) const {
        doc["type"] = type;
        doc["message"] = message;
    }

    void unmarshal(const JsonDocument& doc) {
        type = doc["type"];
        message = doc["message"];
    }
};

// Function to serialize a WAMP message
String serializeWAMPMessage(const WAMPMessage& wampMessage) {
    StaticJsonDocument<200> doc;
    wampMessage.marshal(doc);

    String output;
    serializeJson(doc, output);
    return output;
}

// Function to deserialize a WAMP message from JSON
WAMPMessage deserializeWAMPMessage(const String& data) {
    StaticJsonDocument<200> doc;
    deserializeJson(doc, data);

    WAMPMessage wampMessage;
    wampMessage.unmarshal(doc);
    return wampMessage;
}

void setup() {
    Serial.begin(115200);
}

void loop() {
    // Main loop logic here
        // Example WAMP message
    WAMPMessage messageToSend;
    messageToSend.type = 1;
    messageToSend.message = "Hello, WAMP!";

    // Serialize the message
    String serialized = serializeWAMPMessage(messageToSend);
    Serial.println("Serialized message: ");
    Serial.println(serialized);

    // Deserialize the message
    WAMPMessage receivedMessage = deserializeWAMPMessage(serialized);
    Serial.println("Deserialized message: ");
    Serial.printf("Type: %d, Message: %s\n", receivedMessage.type, receivedMessage.message);
}

Connect your ESP32, upload the code and you’ll see the serialized and deserialized WAMP message printed to the serial monitor.

@muzzammilshahid
Copy link
Member

works as expected

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants