|
| 1 | +package mqtt |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + |
| 7 | + "github.com/spinframework/spin-go-sdk/v3/internal/fermyon/spin/v2.0.0/mqtt" |
| 8 | + "go.bytecodealliance.org/cm" |
| 9 | +) |
| 10 | + |
| 11 | +type Connection struct { |
| 12 | + conn mqtt.Connection |
| 13 | +} |
| 14 | + |
| 15 | +// OpenConnection initializes an MQTT connection |
| 16 | +func OpenConnection(address, username, password string, keepAliveIntervalInSecs uint64) (Connection, error) { |
| 17 | + conn, err, isErr := mqtt.ConnectionOpen(address, username, password, keepAliveIntervalInSecs).Result() |
| 18 | + if isErr { |
| 19 | + return Connection{}, toError(&err) |
| 20 | + } |
| 21 | + |
| 22 | + return Connection{conn: conn}, nil |
| 23 | +} |
| 24 | + |
| 25 | +// Publish publishes an MQTT message |
| 26 | +func (c *Connection) Publish(topic string, payload []byte, qos QoS) error { |
| 27 | + _, err, isErr := c.conn.Publish(topic, mqtt.Payload(cm.ToList(payload)), mqtt.Qos(qos)).Result() |
| 28 | + if isErr { |
| 29 | + return toError(&err) |
| 30 | + } |
| 31 | + |
| 32 | + return nil |
| 33 | +} |
| 34 | + |
| 35 | +// QoS for publishing Mqtt messages |
| 36 | +type QoS = mqtt.Qos |
| 37 | + |
| 38 | +const ( |
| 39 | + QosAtMostOnce = mqtt.QosAtMostOnce |
| 40 | + QosAtLeastOnce = mqtt.QosAtLeastOnce |
| 41 | + QosExactlyOnce = mqtt.QosExactlyOnce |
| 42 | +) |
| 43 | + |
| 44 | +func toError(err *mqtt.Error) error { |
| 45 | + if err == nil { |
| 46 | + return nil |
| 47 | + } |
| 48 | + |
| 49 | + if err.String() == "connection-failed" { |
| 50 | + return fmt.Errorf("connection-failed: %s", *err.ConnectionFailed()) |
| 51 | + } |
| 52 | + |
| 53 | + if err.String() == "other" { |
| 54 | + return fmt.Errorf(*err.Other()) |
| 55 | + } |
| 56 | + |
| 57 | + return errors.New(err.String()) |
| 58 | +} |
0 commit comments