|
| 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 uint8) error { |
| 27 | + _, err, isErr := c.conn.Publish(topic, mqtt.Payload(cm.ToList(payload)), toQos(qos)).Result() |
| 28 | + if isErr { |
| 29 | + return toError(&err) |
| 30 | + } |
| 31 | + |
| 32 | + return nil |
| 33 | +} |
| 34 | + |
| 35 | +func toQos(q uint8) mqtt.Qos { |
| 36 | + switch q { |
| 37 | + case 0: |
| 38 | + return mqtt.QosAtMostOnce |
| 39 | + case 1: |
| 40 | + return mqtt.QosAtLeastOnce |
| 41 | + case 2: |
| 42 | + return mqtt.QosExactlyOnce |
| 43 | + default: |
| 44 | + panic("invalid QoS") |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +func toError(err *mqtt.Error) error { |
| 49 | + if err == nil { |
| 50 | + return nil |
| 51 | + } |
| 52 | + |
| 53 | + if err.String() == "connection-failed" { |
| 54 | + return fmt.Errorf("connection-failed: %s", *err.ConnectionFailed()) |
| 55 | + } |
| 56 | + |
| 57 | + if err.String() == "other" { |
| 58 | + return fmt.Errorf("other: %s", *err.Other()) |
| 59 | + } |
| 60 | + |
| 61 | + return errors.New(err.String()) |
| 62 | +} |
0 commit comments