eclipse / paho.golang

Go libraries
Other
327 stars 92 forks source link

how to use file-based persistence? #246

Closed Yusoo closed 6 months ago

Yusoo commented 6 months ago

I am using autopaho, but no files are generated, my code like this

import (
    "github.com/eclipse/paho.golang/autopaho"
    "github.com/eclipse/paho.golang/paho"
    "github.com/eclipse/paho.golang/paho/session/state"
    storefile "github.com/eclipse/paho.golang/paho/store/file"
)

    cliState, err := storefile.New("mydir", "cli_", ".pkt")
    if err != nil {
        panic(err)
    }
    srvState, err := storefile.New("mydir", "srv_", ".pkt")
    if err != nil {
        panic(err)
    }

cliCfg := autopaho.ClientConfig{
        ServerUrls: []*url.URL{u},
        KeepAlive:  20, // Keepalive message should be sent every 20 seconds
        // CleanStartOnInitialConnection defaults to false. Setting this to true will clear the session on the first connection.
        CleanStartOnInitialConnection: false,
        // SessionExpiryInterval - Seconds that a session will survive after disconnection.
        // It is important to set this because otherwise, any queued messages will be lost if the connection drops and
        // the server will not queue messages while it is down. The specific setting will depend upon your needs
        // (60 = 1 minute, 3600 = 1 hour, 86400 = one day, 0xFFFFFFFE = 136 years, 0xFFFFFFFF = don't expire)
        SessionExpiryInterval: 60,
        OnConnectionUp: func(cm *autopaho.ConnectionManager, connAck *paho.Connack) {
            fmt.Println("mqtt connection up")
            // Subscribing in the OnConnectionUp callback is recommended (ensures the subscription is reestablished if
            // the connection drops)
            if _, err := cm.Subscribe(context.Background(), &paho.Subscribe{
                Subscriptions: []paho.SubscribeOptions{
                    {Topic: topic, QoS: 1},
                },
            }); err != nil {
                fmt.Printf("failed to subscribe (%s). This is likely to mean no messages will be received.", err)
            }
            fmt.Println("mqtt subscription made")
        },
        OnConnectError: func(err error) { fmt.Printf("error whilst attempting connection: %s\n", err) },
        // eclipse/paho.golang/paho provides base mqtt functionality, the below config will be passed in for each connection
        ClientConfig: paho.ClientConfig{
            // If you are using QOS 1/2, then it's important to specify a client id (which must be unique)
            ClientID: clientID,
                        Session:  state.New(cliState, srvState), 
            // OnPublishReceived is a slice of functions that will be called when a message is received.
            // You can write the function(s) yourself or use the supplied Router
            OnPublishReceived: []func(paho.PublishReceived) (bool, error){
                func(pr paho.PublishReceived) (bool, error) {
                    fmt.Printf("received message on topic %s; body: %s (retain: %t)\n", pr.Packet.Topic, pr.Packet.Payload, pr.Packet.Retain)
                    return true, nil
                }},
            OnClientError: func(err error) { fmt.Printf("client error: %s\n", err) },
            OnServerDisconnect: func(d *paho.Disconnect) {
                if d.Properties != nil {
                    fmt.Printf("server requested disconnect: %s\n", d.Properties.ReasonString)
                } else {
                    fmt.Printf("server requested disconnect; reason code: %d\n", d.ReasonCode)
                }
            },
        },
    }

I'm not sure if something is wrong. Is there have any examples?

MattBrittan commented 6 months ago

Best example is probably the docker one. Files will only exist while messages are in flight (in normal circumstances they will be created/deleted pretty quickly!). Your code looks fine (well your SessionExpiryInterval is pretty low but that might be intentional).

Note that if you want to queue outbound PUBLISH packets whilst the connection is down then see the queue demo.

You need both of the above to match the 3.1.1 clients functionality (but this client is not limited to 65535 queued messages).

Yusoo commented 6 months ago

I am testing on windows, the program sends data to the MQTT server at regular intervals, when I stop the MQTT server, the program reports an error: connection with the MQTT server is currently down, but I can't find any generated files.

MattBrittan commented 6 months ago

Session store files are only created when the message is sent to the server, this only happens when the connection is up.

It will be difficult to create a situation where these files are visible becsuse they are deleted as soon as the message us fully delivered (the test suite does this by using a custom broker that can delay acknowledgements).

Yusoo commented 6 months ago

Changed to use paho.mqtt.golang and it seems to be working correctly :)

MattBrittan commented 6 months ago

OK - closing this off.

Note that things were probably working properly with this repo too, but you were not really clear about what you expected making it difficult to help.