summaryrefslogtreecommitdiff
path: root/mqtt.go
blob: 2e83e8a8b56802e56eb4217b1cd0317f5c6b678c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package main

import (
	"context"
	"errors"
	"fmt"
	"net/url"
	"time"

	"github.com/charmbracelet/log"
	"github.com/eclipse/paho.golang/autopaho"
	"github.com/eclipse/paho.golang/paho"
	"github.com/meshnet-gophers/meshtastic-go"
	pb "github.com/meshnet-gophers/meshtastic-go/meshtastic"
	"github.com/meshnet-gophers/meshtastic-go/radio"
	"google.golang.org/protobuf/proto"
)

// Implements MeshIf
type MqttIf struct {
	Address   string
	Username  string
	Password  string
	ClientID  string
	Root      string
	GatewayID meshtastic.NodeID
	Channels  *pb.ChannelSet

	logger  *log.Logger
	c       *autopaho.ConnectionManager
	ctx     context.Context
	stop    context.CancelFunc
	inputCh chan mqttServiceEnvelope
	chIdMap map[string]uint8
}

type mqttServiceEnvelope struct {
	timestamp time.Time
	se        *pb.ServiceEnvelope
}

func NewMqttIf(address string, username, password, root, clientID string, gatewayID meshtastic.NodeID, channels *pb.ChannelSet) *MqttIf {
	logger := log.WithPrefix("MqttIf")
	inputCh := make(chan mqttServiceEnvelope, 10)
	return &MqttIf{
		Address:   address,
		Username:  username,
		Password:  password,
		ClientID:  clientID,
		Root:      root,
		GatewayID: gatewayID,
		Channels:  channels,

		logger:  logger,
		inputCh: inputCh,
	}
}

func (m *MqttIf) channelPublishTopic(channelId string) string {
	return fmt.Sprintf("%s/2/e/%s/%s", m.Root, channelId, m.GatewayID)
}

func (m *MqttIf) onConnectionUp(cm *autopaho.ConnectionManager, connAck *paho.Connack) {
	topics := []string{fmt.Sprintf("%s/2/e/PKI/#", m.Root)}
	chIdMap := make(map[string]uint8)
	for _, c := range m.Channels.Settings {
		topics = append(topics, fmt.Sprintf("%s/2/e/%s/#", m.Root, c.Name))
		channelHash, err := radio.ChannelHash(c.Name, c.Psk)
		if err != nil {
			m.logger.Errorf("failed to build channel hash: %s", err)
			m.c.Disconnect(m.ctx)
			return
		}
		chIdMap[c.Name] = uint8(channelHash)
	}
	m.chIdMap = chIdMap
	subscriptions := make([]paho.SubscribeOptions, 0, len(topics))
	for _, t := range topics {
		subscriptions = append(subscriptions, paho.SubscribeOptions{Topic: t, QoS: 1})
	}
	if _, err := cm.Subscribe(m.ctx, &paho.Subscribe{Subscriptions: subscriptions}); err != nil {
		m.logger.Errorf("failed to subscribe (%s). This is likely to mean no messages will be received.", err)
		m.c.Disconnect(m.ctx)
		return
	}
	m.logger.Info("Subscribed", "topics", topics)
}

func (m *MqttIf) onConnectionError(err error) {
	m.logger.Warnf("error whilst attempting connection: %s\n", err)
}

func (m *MqttIf) onReceive(pr paho.PublishReceived) (bool, error) {
	if pr.Packet.Duplicate() || pr.AlreadyHandled {
		return false, nil
	}
	se := &pb.ServiceEnvelope{}
	if err := proto.Unmarshal(pr.Packet.Payload, se); err != nil {
		return false, fmt.Errorf("unmarshalling ServicePayload from Mqtt: %w", err)
	}
	if se.Packet.RxTime == 0 {
		se.Packet.RxTime = uint32(time.Now().Unix())
	}
	m.inputCh <- mqttServiceEnvelope{timestamp: time.Now(), se: se}
	return true, nil
}

func (m *MqttIf) onClientError(err error) {
	m.logger.Warnf("client error: %s\n", err)
}

func (m *MqttIf) onServerDisconnect(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)
	}
}

func (m *MqttIf) Open() error {
	m.ctx, m.stop = context.WithCancel(context.Background())
	u, err := url.Parse(m.Address)
	if err != nil {
		return err
	}
	cliCfg := autopaho.ClientConfig{
		ServerUrls:                    []*url.URL{u},
		KeepAlive:                     20, // Keepalive message should be sent every 20 seconds
		CleanStartOnInitialConnection: false,
		SessionExpiryInterval:         60,
		OnConnectionUp:                m.onConnectionUp,
		OnConnectError:                m.onConnectionError,
		ConnectUsername:               m.Username,
		ConnectPassword:               []byte(m.Password),
		ClientConfig: paho.ClientConfig{
			ClientID:           m.ClientID,
			OnPublishReceived:  []func(paho.PublishReceived) (bool, error){m.onReceive},
			OnClientError:      m.onClientError,
			OnServerDisconnect: m.onServerDisconnect,
		},
	}

	m.c, err = autopaho.NewConnection(m.ctx, cliCfg) // starts process; will reconnect until context cancelled
	if err != nil {
		return err
	}
	if err = m.c.AwaitConnection(m.ctx); err != nil {
		return err
	}

	return nil
}

func (m *MqttIf) Close() error {
	m.logger.Info("Closing MQTT connection...")
	m.c.Disconnect(m.ctx)
	m.stop()
	close(m.inputCh)
	<-m.ctx.Done()
	return nil
}

func (m *MqttIf) ReadMeshPacket() (*pb.MeshPacket, uint64, error) {
	if err := m.ctx.Err(); err != nil {
		return nil, 0, err
	}
	p := <-m.inputCh
	if p.se == nil || p.se.Packet == nil {
		return nil, 0, errors.New("no input")
	}
	p.se.Packet.Channel = uint32(m.chIdMap[p.se.ChannelId])
	return p.se.Packet, uint64(p.timestamp.UnixMicro()), nil
}

func (m *MqttIf) WriteMeshPacket(p *pb.MeshPacket) error {
	var channelId string
	if p.PkiEncrypted {
		channelId = "PKI"
		p.Priority = pb.MeshPacket_HIGH
	} else {
		channel := m.Channels.Settings[p.Channel]
		channelId = channel.Name
	}
	if p.RxTime == 0 {
		p.RxTime = uint32(time.Now().Unix())
	}
	p.RelayNode = p.RelayNode & 0xFF
	p.NextHop = p.NextHop & 0xFF
	p.Channel = 0 // Don't expose your channel number
	se := &pb.ServiceEnvelope{
		Packet:    p,
		ChannelId: channelId,
		GatewayId: m.GatewayID.String(),
	}
	payload, err := proto.Marshal(se)
	if err != nil {
		return err
	}
	topic := m.channelPublishTopic(channelId)
	m.c.Publish(m.ctx, &paho.Publish{
		Topic:   topic,
		Payload: payload,
	})
	return nil
}