aboutsummaryrefslogtreecommitdiffstats
path: root/cmd/subscriber/main.go
blob: f561d606ccc92703aa63ba0455fc1a28626b3af8 (plain) (blame)
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log/slog"
	"net/url"
	"os"
	"os/signal"
	"strings"
	"sync"
	"syscall"
	"time"

	"github.com/eclipse/paho.golang/autopaho"
	"github.com/eclipse/paho.golang/paho"
	"github.com/joho/godotenv"
	"hub/internal/weather"
)

// MessageHandler wraps the function to process incoming messages
type MessageHandler func(*paho.Publish)

func main() {
	// Load environment variables
	_ = godotenv.Load()

	// Load configuration
	cfg := weather.LoadSubscriberConfig()

	// Setup logging
	var logLevel slog.Level
	switch strings.ToLower(cfg.LogLevel) {
	case "debug":
		logLevel = slog.LevelDebug
	case "warn", "warning":
		logLevel = slog.LevelWarn
	case "error":
		logLevel = slog.LevelError
	default:
		logLevel = slog.LevelInfo
	}

	logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		Level: logLevel,
	}))

	// Create context for graceful shutdown
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Handle signals
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		sig := <-sigChan
		logger.Info("Received signal", "signal", sig)
		cancel()
	}()

	// Run the subscriber
	logger.Info("Starting MQTT v5 subscriber for FMI weather data",
		"broker", cfg.MQTTBroker,
		"topics", cfg.Topics,
		"qos", cfg.QoS)

	if err := runSubscriber(ctx, cfg, logger); err != nil {
		logger.Error("Subscriber failed", "error", err)
		os.Exit(1)
	}

	logger.Info("Subscriber stopped gracefully")
}

func runSubscriber(ctx context.Context, cfg *weather.SubscriberConfig, logger *slog.Logger) error {
	// Initialize statistics
	stats := weather.InitTopicStats()
	statsMutex := &sync.RWMutex{}

	// Create MQTT client with custom configuration
	serverURL, err := url.Parse(cfg.MQTTBroker)
	if err != nil {
		return fmt.Errorf("invalid MQTT broker URL: %w", err)
	}

	// Create message handler
	messageHandler := func(pr paho.PublishReceived) (bool, error) {
		go handleMessage(pr.Packet, logger, stats, statsMutex)
		return true, nil
	}

	// Client configuration
	cliCfg := autopaho.ClientConfig{
		ServerUrls: []*url.URL{serverURL},
		KeepAlive:  uint16(cfg.MQTTKeepAlive.Seconds()),
		ClientConfig: paho.ClientConfig{
			ClientID: fmt.Sprintf("%s-%d", cfg.MQTTClientID, os.Getpid()),
			OnPublishReceived: []func(paho.PublishReceived) (bool, error){
				messageHandler,
			},
			OnServerDisconnect: func(d *paho.Disconnect) {
				if d != nil && d.ReasonCode != 0 {
					logger.Warn("MQTT disconnected", "reason", d.ReasonCode)
				} else {
					logger.Info("MQTT disconnected gracefully")
				}
			},
		},
		ConnectUsername: cfg.MQTTUsername,
		ConnectPassword: []byte(cfg.MQTTPassword),
		ConnectTimeout:  30 * time.Second,
	}

	cliCfg.CleanStartOnInitialConnection = false
	cliCfg.SessionExpiryInterval = uint32(cfg.MQTTSessionExp.Seconds())

	// Connection callbacks
	cliCfg.OnConnectionUp = func(cm *autopaho.ConnectionManager, connAck *paho.Connack) {
		logger.Info("MQTT v5 connected",
			"session_present", connAck.SessionPresent,
			"keep_alive", cfg.MQTTKeepAlive)

		// Subscribe to topics after connection is established
		if len(cfg.Topics) > 0 {
			subscriptions := make([]paho.SubscribeOptions, len(cfg.Topics))
			for i, topic := range cfg.Topics {
				subscriptions[i] = paho.SubscribeOptions{
					Topic: topic,
					QoS:   byte(cfg.QoS),
				}
			}

			ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
			defer cancel()

			// FIXED: SubscriptionIdentifier is a pointer
			subID := int(1)
			subProps := &paho.SubscribeProperties{
				SubscriptionIdentifier: &subID,
			}

			if _, err := cm.Subscribe(ctx, &paho.Subscribe{
				Subscriptions: subscriptions,
				Properties:    subProps,
			}); err != nil {
				logger.Error("Failed to subscribe", "error", err)
			} else {
				logger.Info("Subscribed to topics",
					"topics", cfg.Topics,
					"qos", cfg.QoS)
			}
		}
	}

	cliCfg.OnConnectError = func(err error) {
		logger.Error("MQTT connection error", "error", err)
	}

	// Connect to broker
	mqttClient, err := autopaho.NewConnection(ctx, cliCfg)
	if err != nil {
		return fmt.Errorf("failed to create MQTT connection: %w", err)
	}

	// Wait for connection
	err = mqttClient.AwaitConnection(ctx)
	if err != nil {
		return fmt.Errorf("failed to establish MQTT connection: %w", err)
	}

	defer func() {
		discCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()

		if err := mqttClient.Disconnect(discCtx); err != nil {
			logger.Error("Failed to disconnect MQTT", "error", err)
		}
	}()

	logger.Info("Subscriber started and waiting for messages...")

	// Statistics reporting goroutine
	ticker := time.NewTicker(30 * time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-ctx.Done():
			// Print final statistics
			statsMutex.RLock()
			finalStats := stats.MessagesReceived
			statsMutex.RUnlock()

			if len(finalStats) > 0 {
				logger.Info("Final message statistics", "stats", finalStats)
			}
			return nil

		case <-ticker.C:
			if cfg.EnableDebug {
				statsMutex.RLock()
				currentStats := stats.MessagesReceived
				statsMutex.RUnlock()

				if len(currentStats) > 0 {
					logger.Debug("Message statistics", "stats", currentStats)
				}
			}
		}
	}
}

func handleMessage(pkt *paho.Publish, logger *slog.Logger,
	stats *weather.TopicStats, mutex *sync.RWMutex) {

	// Update statistics
	mutex.Lock()
	stats.MessagesReceived[pkt.Topic]++
	stats.LastMessageTime[pkt.Topic] = time.Now()
	mutex.Unlock()

	// Route based on topic pattern
	switch {
	case strings.HasPrefix(pkt.Topic, "weather/obs/"):
		processObservationMessage(pkt, logger)
	case strings.HasPrefix(pkt.Topic, "weather/forecast/"):
		processForecastMessage(pkt, logger)
	default:
		logger.Warn("Unknown topic pattern", "topic", pkt.Topic)
		// Try to decode as generic JSON
		var data map[string]interface{}
		if err := json.Unmarshal(pkt.Payload, &data); err == nil {
			logger.Info("Generic message", "topic", pkt.Topic, "data", data)
		} else {
			logger.Info("Raw message", "topic", pkt.Topic, "payload", string(pkt.Payload))
		}
	}
}

func processObservationMessage(pkt *paho.Publish, logger *slog.Logger) {
	var obs weather.Observation
	if err := json.Unmarshal(pkt.Payload, &obs); err != nil {
		logger.Error("Failed to parse observation",
			"error", err,
			"topic", pkt.Topic)
		return
	}

	// Extract user properties
	userProps := make(map[string]string)
	if pkt.Properties != nil {
		for _, prop := range pkt.Properties.User {
			userProps[prop.Key] = prop.Value
		}
	}

	// Format value for display
	valueStr := "null"
	if obs.Value != nil {
		valueStr = fmt.Sprintf("%.2f", *obs.Value)
	}

	logger.Info("Observation received",
		"topic", pkt.Topic,
		"station", obs.Station,
		"parameter", obs.Parameter,
		"time", obs.Time.Format(time.RFC3339),
		"value", valueStr,
		"user_properties", userProps,
		"retain", pkt.Retain,
		"qos", pkt.QoS)
}

func processForecastMessage(pkt *paho.Publish, logger *slog.Logger) {
	var fc weather.ForecastValue
	if err := json.Unmarshal(pkt.Payload, &fc); err != nil {
		logger.Error("Failed to parse forecast",
			"error", err,
			"topic", pkt.Topic)
		return
	}

	// Extract user properties
	userProps := make(map[string]string)
	if pkt.Properties != nil {
		for _, prop := range pkt.Properties.User {
			userProps[prop.Key] = prop.Value
		}
	}

	// Format value for display
	valueStr := "null"
	if fc.Value != nil {
		valueStr = fmt.Sprintf("%.2f", *fc.Value)
	}

	logger.Info("Forecast received",
		"topic", pkt.Topic,
		"model", fc.Model,
		"parameter", fc.Parameter,
		"run_time", fc.RunTime.Format(time.RFC3339),
		"forecast_time", fc.ForecastTime.Format(time.RFC3339),
		"location", fmt.Sprintf("(%.4f,%.4f)", fc.Location.Lat, fc.Location.Lon),
		"value", valueStr,
		"user_properties", userProps,
		"retain", pkt.Retain,
		"qos", pkt.QoS)
}