MQTT topic gateway-id/node-id is now mapped to campus/room for influx Assisted-by: Junie:gemini-3-flash Signed-off-by: Klagarge <remi@heredero.ch>
81 lines
2.1 KiB
Go
81 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
)
|
|
|
|
// mappingFile is the structure of the JSON config file.
|
|
// Campus names map to the list of gateway IDs that belong to them.
|
|
// Room names map to the list of node IDs that belong to them.
|
|
type mappingFile struct {
|
|
Campus map[string][]string `json:"campus"`
|
|
Room map[string][]string `json:"room"`
|
|
}
|
|
|
|
// MappingConfig holds the reverse lookup maps built from the config file:
|
|
//
|
|
// gateway_id -> campus name
|
|
// node_id -> room name
|
|
type MappingConfig struct {
|
|
gatewayToCampus map[string]string
|
|
nodeToRoom map[string]string
|
|
}
|
|
|
|
// EmptyMapping returns a MappingConfig with no entries.
|
|
// GetCampus and GetRoom will return their "unknown_*" fallback values.
|
|
func EmptyMapping() *MappingConfig {
|
|
return &MappingConfig{
|
|
gatewayToCampus: make(map[string]string),
|
|
nodeToRoom: make(map[string]string),
|
|
}
|
|
}
|
|
|
|
// LoadMapping reads the mapping configuration from a JSON file and builds
|
|
// the internal reverse-lookup tables.
|
|
func LoadMapping(path string) (*MappingConfig, error) {
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to read mapping file %q: %w", path, err)
|
|
}
|
|
|
|
var raw mappingFile
|
|
if err := json.Unmarshal(data, &raw); err != nil {
|
|
return nil, fmt.Errorf("failed to parse mapping JSON: %w", err)
|
|
}
|
|
|
|
cfg := &MappingConfig{
|
|
gatewayToCampus: make(map[string]string),
|
|
nodeToRoom: make(map[string]string),
|
|
}
|
|
|
|
for campus, gateways := range raw.Campus {
|
|
for _, gwID := range gateways {
|
|
cfg.gatewayToCampus[gwID] = campus
|
|
}
|
|
}
|
|
|
|
for room, nodes := range raw.Room {
|
|
for _, nodeID := range nodes {
|
|
cfg.nodeToRoom[nodeID] = room
|
|
}
|
|
}
|
|
|
|
return cfg, nil
|
|
}
|
|
|
|
// GetCampus returns the campus name for a given gateway ID.
|
|
// The boolean is false if the gateway ID has no mapping.
|
|
func (c *MappingConfig) GetCampus(gatewayID string) (string, bool) {
|
|
campus, ok := c.gatewayToCampus[gatewayID]
|
|
return campus, ok
|
|
}
|
|
|
|
// GetRoom returns the room name for a given node ID.
|
|
// The boolean is false if the node ID has no mapping.
|
|
func (c *MappingConfig) GetRoom(nodeID string) (string, bool) {
|
|
room, ok := c.nodeToRoom[nodeID]
|
|
return room, ok
|
|
}
|