From e2e386a891f0e1284df8da5b9a1aa63e4a13a602 Mon Sep 17 00:00:00 2001 From: Malte Muench Date: Thu, 9 May 2024 21:37:09 +0200 Subject: [PATCH 1/7] Some typofixing and doc improvements Signed-off-by: Malte Muench --- src/internal/canbushandling.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/internal/canbushandling.go b/src/internal/canbushandling.go index feb3e12..9e51261 100644 --- a/src/internal/canbushandling.go +++ b/src/internal/canbushandling.go @@ -1,4 +1,4 @@ -// Package can2mqtt contains some tools for bridging a CAN-Interface +// Package internal of c3re/can2mqtt contains some tools for bridging a CAN-Interface // and a mqtt-network package internal From 6f2ae182d1bfc85e8384ab8c7db2b1c12a10ccca Mon Sep 17 00:00:00 2001 From: Malte Muench Date: Fri, 10 May 2024 14:45:49 +0200 Subject: [PATCH 2/7] Write help to stderr Signed-off-by: Malte Muench --- src/can2mqtt.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/can2mqtt.go b/src/can2mqtt.go index cb3cc5d..c7709ee 100644 --- a/src/can2mqtt.go +++ b/src/can2mqtt.go @@ -39,10 +39,10 @@ func main() { // help function (obvious...) func printHelp() { - fmt.Printf("welcome to the CAN2MQTT bridge!\n\n") - fmt.Printf("Usage: can2mqtt [-f ] [-c ] [-m ] [-v] [-h] [-d ]\n") - fmt.Printf(": a can2mqtt.csv file\n") - fmt.Printf(": a CAN-Interface e.g. can0\n") - fmt.Printf(": connectstring for MQTT. e.g.: tcp://[user:pass@]localhost:1883\n") - fmt.Printf(": directional Mode 0 = bidirectional, 1 = can2mqtt only, 2 = mqtt2can only\n") + _, _ = fmt.Fprintf(os.Stderr, "welcome to the CAN2MQTT bridge!\n\n") + _, _ = fmt.Fprintf(os.Stderr, "Usage: can2mqtt [-f ] [-c ] [-m ] [-v] [-h] [-d ]\n") + _, _ = fmt.Fprintf(os.Stderr, ": a can2mqtt.csv file\n") + _, _ = fmt.Fprintf(os.Stderr, ": a CAN-Interface e.g. can0\n") + _, _ = fmt.Fprintf(os.Stderr, ": connectstring for MQTT. e.g.: tcp://[user:pass@]localhost:1883\n") + _, _ = fmt.Fprintf(os.Stderr, ": directional Mode 0 = bidirectional, 1 = can2mqtt only, 2 = mqtt2can only\n") } From 7077eaf043e6acaa5a08dc2924187886633861da Mon Sep 17 00:00:00 2001 From: Malte Muench Date: Fri, 10 May 2024 14:47:17 +0200 Subject: [PATCH 3/7] Improve logging, and improve error handling in reading the csv Signed-off-by: Malte Muench --- src/internal/canbushandling.go | 45 +++++++----------- src/internal/main.go | 84 +++++++++++++--------------------- src/internal/mqtthandling.go | 45 ++++++------------ 3 files changed, 63 insertions(+), 111 deletions(-) diff --git a/src/internal/canbushandling.go b/src/internal/canbushandling.go index 9e51261..2002fba 100644 --- a/src/internal/canbushandling.go +++ b/src/internal/canbushandling.go @@ -3,9 +3,9 @@ package internal import ( - "fmt" "github.com/brutella/can" - "log" + "log/slog" + "os" "sync" ) @@ -18,23 +18,21 @@ var bus *can.Bus // CAN-Bus pointer func canStart(canInterface string) { var err error - if dbg { - fmt.Printf("canbushandler: initializing CAN-Bus interface %s\n", canInterface) - } + slog.Debug("canbushandler: initializing CAN-Bus", "interface", canInterface) bus, err = can.NewBusForInterfaceWithName(canInterface) if err != nil { - if dbg { - fmt.Printf("canbushandler: error while activating CAN-Bus interface: %s\n", canInterface) - } - log.Fatal(err) + slog.Error("canbushandler: error while initializing CAN-Bus", "error", err) + os.Exit(1) } + slog.Info("canbushandler: connected to CAN") + slog.Debug("canbushandler: registering handler") bus.SubscribeFunc(handleCANFrame) + slog.Debug("canbushandler: starting receive loop") + // will not return if everything is fine err = bus.ConnectAndPublish() if err != nil { - if dbg { - fmt.Printf("canbushandler: error while activating CAN-Bus interface: %s\n", canInterface) - } - log.Fatal(err) + slog.Error("canbushandler: error while processing CAN-Bus", "error", err) + os.Exit(1) } } @@ -43,18 +41,14 @@ func handleCANFrame(frame can.Frame) { var idSub = false // indicates, whether the id was subscribed or not for _, i := range csi { if i == frame.ID { - if dbg { - fmt.Printf("canbushandler: ID %d is in subscribed list, calling receivehadler.\n", frame.ID) - } + slog.Debug("canbushandler: received subscribed frame", "id", frame.ID) go handleCAN(frame) idSub = true break } } if !idSub { - if dbg { - fmt.Printf("canbushandler: ID:%d was not subscribed. /dev/nulled that frame...\n", frame.ID) - } + slog.Debug("canbushandler: ignored unsubscribed frame", "id", frame.ID) } } @@ -63,16 +57,12 @@ func canSubscribe(id uint32) { csiLock.Lock() csi = append(csi, id) csiLock.Unlock() - if dbg { - fmt.Printf("canbushandler: mutex lock+unlock successful. subscribed to ID:%d\n", id) - } + slog.Debug("canbushandler: successfully subscribed CAN-ID", "id", id) } // expects a CANFrame and sends it func canPublish(frame can.Frame) { - if dbg { - fmt.Println("canbushandler: sending CAN-Frame: ", frame) - } + slog.Debug("canbushandler: sending CAN-Frame", "frame", frame) // Check if ID is using more than 11-Bits: if frame.ID >= 0x800 { // if so, enable extended frame format @@ -80,9 +70,6 @@ func canPublish(frame can.Frame) { } err := bus.Publish(frame) if err != nil { - if dbg { - fmt.Printf("canbushandler: error while transmitting the CAN-Frame.\n") - } - log.Fatal(err) + slog.Error("canbushandler: error while publishing CAN-Frame", "error", err) } } diff --git a/src/internal/main.go b/src/internal/main.go index 74aaf39..0a4f3bf 100644 --- a/src/internal/main.go +++ b/src/internal/main.go @@ -4,12 +4,13 @@ import ( "bufio" // Reader "encoding/csv" // CSV Management "fmt" // print :) + "io" // EOF const + "log" // error management + "os" // open files + "strconv" // parse strings + "log/slog" "github.com/brutella/can" "github.com/c3re/can2mqtt/internal/convertfunctions" - "io" // EOF const - "log" // error management - "os" // open files - "strconv" // parse strings "sync" ) @@ -46,6 +47,7 @@ var wg sync.WaitGroup // just standard information output. Default is false. func SetDbg(v bool) { dbg = v + slog.SetLogLoggerLevel(slog.LevelDebug) } // SetCi sets the CAN-Interface to use for the CAN side @@ -86,28 +88,8 @@ func SetConfDirMode(s string) { // parses the can2mqtt.csv file and from there everything takes // its course... func Start() { - fmt.Println("Starting can2mqtt") - fmt.Println() - fmt.Println("MQTT-Config: ", cs) - fmt.Println("CAN-Config: ", ci) - fmt.Println("can2mqtt.csv: ", c2mf) - fmt.Print("dirMode: ", dirMode, " (") - if dirMode == 0 { - fmt.Println("bidirectional)") - } - if dirMode == 1 { - fmt.Println("can2mqtt only)") - } - if dirMode == 2 { - fmt.Println("mqtt2can only)") - } - fmt.Print("Debug-Mode: ") - if dbg { - fmt.Println("yes") - } else { - fmt.Println("no") - } - fmt.Println() + log.SetFlags(0) + slog.Info("Starting can2mqtt", "mqtt-config", cs, "can-interface", ci, "can2mqtt.csv", c2mf, "dir-mode", dirMode, "debug", dbg) wg.Add(1) go canStart(ci) // epic parallel shit ;-) mqttStart(cs) @@ -121,10 +103,12 @@ func readC2MPFromFile(filename string) { file, err := os.Open(filename) if err != nil { - log.Fatal(err) + slog.Error("main: can2mqtt.csv could not be opened", "filename", filename, "error", err) + os.Exit(1) } r := csv.NewReader(bufio.NewReader(file)) + r.FieldsPerRecord = 3 pairFromID = make(map[uint32]*can2mqtt) pairFromTopic = make(map[string]*can2mqtt) for { @@ -133,16 +117,26 @@ func readC2MPFromFile(filename string) { if err == io.EOF { break } + if err != nil { + slog.Warn("main: skipping line", "filename", filename, "error", err) + continue + } + line, _ := r.FieldPos(0) tmp, err := strconv.ParseUint(record[0], 10, 32) if err != nil { - fmt.Printf("Error while converting can-ID: %s :%s\n", record[0], err.Error()) + slog.Warn("main: skipping line, malformed can-ID", "error", err, "line", line) continue } canID := uint32(tmp) convMode := record[1] topic := record[2] - if isInSlice(canID, topic) { - panic("main: each ID and each topic is only allowed once!") + if isIDInSlice(canID) { + slog.Warn("main: skipping line, duplicate ID", "id", canID, "line", line) + continue + } + if isTopicInSlice(topic) { + slog.Warn("main: skipping line duplicate topic", "topic", topic, "line", line) + continue } switch convMode { case "16bool2ascii": @@ -311,30 +305,18 @@ func readC2MPFromFile(filename string) { mqttSubscribe(topic) // TODO move to append function canSubscribe(canID) // TODO move to append function } - if dbg { - fmt.Printf("main: the following CAN-MQTT pairs have been extracted:\n") - fmt.Printf("main: CAN-ID\t\t conversion mode\t\tMQTT-topic\n") - for _, c2mp := range pairFromID { - fmt.Printf("main: %d\t\t%s\t\t%s\n", c2mp.canId, c2mp.convMethod, c2mp.mqttTopic) - } + + for _, c2mp := range pairFromID { + slog.Debug("main: extracted pair", "id", c2mp.canId, "convertmode", c2mp.convMethod, "topic", c2mp.mqttTopic) } } -// check function to check if a topic or an ID is in the slice -func isInSlice(canId uint32, mqttTopic string) bool { - if pairFromID[canId] != nil { - if dbg { - fmt.Printf("main: The ID %d or the Topic %s is already in the list!\n", canId, mqttTopic) - } - return true - } - if pairFromTopic[mqttTopic] != nil { - if dbg { - fmt.Printf("main: The ID %d or the Topic %s is already in the list!\n", canId, mqttTopic) - } - return true - } - return false +func isIDInSlice(canId uint32) bool { + return pairFromID[canId] != nil +} + +func isTopicInSlice(mqttTopic string) bool { + return pairFromTopic[mqttTopic] != nil } // get the corresponding ID for a given topic diff --git a/src/internal/mqtthandling.go b/src/internal/mqtthandling.go index e9fa04a..83124e2 100644 --- a/src/internal/mqtthandling.go +++ b/src/internal/mqtthandling.go @@ -1,8 +1,9 @@ package internal import ( - "fmt" MQTT "github.com/eclipse/paho.mqtt.golang" + "log/slog" + "os" "strings" ) @@ -17,16 +18,10 @@ func mqttStart(suppliedString string) { // looks like authentication is required for this server userPasswordHost := strings.TrimPrefix(suppliedString, "tcp://") userPassword, host, found := strings.Cut(userPasswordHost, "@") - if !found { - fmt.Println("Whoops, there is an issue with your MQTT-connectString:") - fmt.Println("suppliedString: ", suppliedString) - fmt.Println("userPasswordHost: ", userPasswordHost) - } user, pw, found = strings.Cut(userPassword, ":") if !found { - fmt.Println("Whoops, there is an issue with your MQTT-connectString:") - fmt.Println("suppliedString: ", suppliedString) - fmt.Println("userPasswordHost: ", userPasswordHost) + slog.Error("mqtthandler: missing colon(:) between username and password", "connect string", suppliedString) + os.Exit(1) } connectString = "tcp://" + host } @@ -37,16 +32,12 @@ func mqttStart(suppliedString string) { clientSettings.SetCredentialsProvider(userPwCredProv) } client = MQTT.NewClient(clientSettings) - if dbg { - fmt.Printf("mqtthandler: starting connection to: %s\n", connectString) - } + slog.Debug("mqtthandler: starting connection", "connectString", connectString) if token := client.Connect(); token.Wait() && token.Error() != nil { - fmt.Println("mqttHandler: Oh no an error occurred...") - panic(token.Error()) - } - if dbg { - fmt.Printf("mqttHandler: connection established!\n") + slog.Error("mqtthandler: could not connect to mqtt", "error", token.Error()) + os.Exit(1) } + slog.Info("mqtthandler: connected to mqtt") } // credentialsProvider @@ -57,33 +48,25 @@ func userPwCredProv() (username, password string) { // subscribe to a new topic func mqttSubscribe(topic string) { if token := client.Subscribe(topic, 0, nil); token.Wait() && token.Error() != nil { - fmt.Printf("mqtthandler: error while subscribing: %s\n", topic) - } - if dbg { - fmt.Printf("mqtthandler: successfully subscribed: %s\n", topic) + slog.Error("mqtthandler: error subscribing", "error", token.Error()) } + slog.Debug("mqtthandler: subscribed", "topic", topic) } // unsubscribe a topic func mqttUnsubscribe(topic string) { if token := client.Unsubscribe(topic); token.Wait() && token.Error() != nil { - fmt.Printf("mqtthandler: Error while unsuscribing :%s\n", topic) - } - if dbg { - fmt.Printf("mqtthandler: successfully unsubscribed %s\n", topic) + slog.Error("mqtthandler: error unsubscribing", "error", token.Error()) } + slog.Debug("mqtthandler: unsubscribed", "topic", topic) } // publish a new message func mqttPublish(topic string, payload []byte) { - if dbg { - fmt.Printf("mqtthandler: sending message: \"%s\" to topic: \"%s\"\n", payload, topic) - } mqttUnsubscribe(topic) + slog.Debug("mqtthandler: publishing message", "payload", payload, "topic", topic) token := client.Publish(topic, 0, false, payload) token.Wait() - if dbg { - fmt.Printf("mqtthandler: message was transmitted successfully!.\n") - } + slog.Debug("mqtthandler: published message", "payload", payload, "topic", topic) mqttSubscribe(topic) } From 4b6d139a6d5782be771e798f2d9c0ef4f8edce93 Mon Sep 17 00:00:00 2001 From: Malte Muench Date: Fri, 10 May 2024 15:04:43 +0200 Subject: [PATCH 4/7] Remove unused methods Signed-off-by: Malte Muench --- src/internal/main.go | 27 ++++++--------------------- 1 file changed, 6 insertions(+), 21 deletions(-) diff --git a/src/internal/main.go b/src/internal/main.go index 0a4f3bf..e3514ed 100644 --- a/src/internal/main.go +++ b/src/internal/main.go @@ -4,13 +4,13 @@ import ( "bufio" // Reader "encoding/csv" // CSV Management "fmt" // print :) - "io" // EOF const - "log" // error management - "os" // open files - "strconv" // parse strings - "log/slog" "github.com/brutella/can" "github.com/c3re/can2mqtt/internal/convertfunctions" + "io" // EOF const + "log" // error management + "log/slog" + "os" // open files + "strconv" // parse strings "sync" ) @@ -211,7 +211,7 @@ func readC2MPFromFile(filename string) { toCan: convertfunctions.EightUint82AsciiToCan, toMqtt: convertfunctions.EightUint82AsciiToMqtt, } - // Int methodes come here now + // Int methods come here now case "int82ascii": pairFromID[canID] = &can2mqtt{ canId: canID, @@ -319,21 +319,6 @@ func isTopicInSlice(mqttTopic string) bool { return pairFromTopic[mqttTopic] != nil } -// get the corresponding ID for a given topic -func getIdFromTopic(topic string) uint32 { - return pairFromTopic[topic].canId -} - -// get the conversion mode for a given topic -func getConvModeFromTopic(topic string) string { - return pairFromTopic[topic].convMethod -} - -// get the convertMode for a given ID -func getConvModeFromId(canId uint32) string { - return pairFromID[canId].convMethod -} - // get the corresponding topic for an ID func getTopicFromId(canId uint32) string { return pairFromID[canId].mqttTopic From 708db0fce69d2a1c093b369d5ed516d4d44fcfe8 Mon Sep 17 00:00:00 2001 From: Malte Muench Date: Fri, 10 May 2024 15:33:40 +0200 Subject: [PATCH 5/7] Adds logging for receivehandling.go Signed-off-by: Malte Muench --- src/internal/receivehandling.go | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/src/internal/receivehandling.go b/src/internal/receivehandling.go index 6a9ec87..780295d 100644 --- a/src/internal/receivehandling.go +++ b/src/internal/receivehandling.go @@ -1,9 +1,9 @@ package internal import ( - "fmt" "github.com/brutella/can" MQTT "github.com/eclipse/paho.mqtt.golang" + "log/slog" ) // handleCAN is the standard receive handler for CANFrames @@ -11,22 +11,18 @@ import ( // 1. calling standard convert function: convert2MQTT // 2. sending the message func handleCAN(cf can.Frame) { - if dbg { - fmt.Printf("receivehandler: received CANFrame: ID: %d, len: %d, payload %s\n", cf.ID, cf.Length, cf.Data) - } + slog.Debug("receivehandler: received CANFrame", "id", cf.ID, "len", cf.Length, "data", cf.Data) // Only do conversions when necessary if dirMode != 2 { mqttPayload, err := pairFromID[cf.ID].toMqtt(cf) if err != nil { - fmt.Printf("Error while converting CAN Frame with ID %d and payload %s: %s\n", cf.ID, cf.Data, err.Error()) + slog.Warn("receivehandler: conversion to MQTT message unsuccessful", "convertmode", pairFromID[cf.ID].convMethod, "error", err) return } - if dbg { - fmt.Printf("receivehandler: converted String: %s\n", mqttPayload) - } topic := getTopicFromId(cf.ID) mqttPublish(topic, mqttPayload) - fmt.Printf("ID: %d len: %d data: %X -> topic: \"%s\" message: \"%s\"\n", cf.ID, cf.Length, cf.Data, topic, mqttPayload) + // this is the most common log-message, craft with care... + slog.Info("CAN -> MQTT", "ID", cf.ID, "len", cf.Length, "data", cf.Data, "convertmode", pairFromID[cf.ID].convMethod, "topic", topic, "message", mqttPayload) } } @@ -35,22 +31,16 @@ func handleCAN(cf can.Frame) { // 1. calling the standard convert function: convert2CAN // 2. sending the message func handleMQTT(_ MQTT.Client, msg MQTT.Message) { - if dbg { - fmt.Printf("receivehandler: received message: topic: %s, msg: %s\n", msg.Topic(), msg.Payload()) - } + slog.Debug("receivehandler: received message", "topic", msg.Topic(), "payload", msg.Payload()) if dirMode != 1 { - //cf := convert2CAN(msg.Topic(), string(msg.Payload())) cf, err := pairFromTopic[msg.Topic()].toCan(msg.Payload()) if err != nil { - fmt.Printf("Error while converting MQTT-Message with Topic %s payload %s: %s\n", msg.Topic(), msg.Payload(), err.Error()) + slog.Warn("receivehandler: conversion to CAN-Frame unsuccessful", "convertmode", pairFromTopic[msg.Topic()].convMethod, "error", err) return } - if dbg { - fmt.Printf("receivehandler: converted data: %s\n", cf.Data) - } cf.ID = uint32(pairFromTopic[msg.Topic()].canId) canPublish(cf) - fmt.Printf("ID: %d len: %d data: %X <- topic: \"%s\" message: \"%s\"\n", cf.ID, cf.Length, cf.Data, msg.Topic(), msg.Payload()) + slog.Info("CAN <- MQTT", "ID", cf.ID, "len", cf.Length, "data", cf.Data, "convertmode", pairFromTopic[msg.Topic()].convMethod, "topic", msg.Topic(), "message", msg.Payload()) } } From 133de5d053b3df9e967dd908eb8835010007219f Mon Sep 17 00:00:00 2001 From: Malte Muench Date: Fri, 10 May 2024 15:40:41 +0200 Subject: [PATCH 6/7] Various smaller IDE proposed improvements Signed-off-by: Malte Muench --- README.md | 2 +- src/internal/convertfunctions/bytecolor2colorcode.go | 2 +- src/internal/convertfunctions/int2ascii.go | 2 +- src/internal/convertfunctions/pixelbin2ascii.go | 2 +- src/internal/convertfunctions/uint2ascii.go | 4 ++-- src/internal/receivehandling.go | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 017bc09..1bb2c8d 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ Example: 123,uint322ascii,huette/all/000/airmonitor/sensors/pm10 ``` -Explanation for the 1st Line: For example our Doorstatus is published on the CAN-Bus every second with the CAN-ID 112 (decimal). can2mqtt will take everything thats published there and will push it through to mqtt-topic huette/all/a03/door/sensors/opened. +Explanation for the 1st Line: For example our Doorstatus is published on the CAN-Bus every second with the CAN-ID 112 (decimal). can2mqtt will take everything that is published there and will push it through to mqtt-topic huette/all/a03/door/sensors/opened. ## convert-modes Here they are: diff --git a/src/internal/convertfunctions/bytecolor2colorcode.go b/src/internal/convertfunctions/bytecolor2colorcode.go index 80388d3..14909cf 100644 --- a/src/internal/convertfunctions/bytecolor2colorcode.go +++ b/src/internal/convertfunctions/bytecolor2colorcode.go @@ -17,7 +17,7 @@ func ByteColor2ColorCodeToCan(input []byte) (can.Frame, error) { if err != nil { return can.Frame{}, errors.New(fmt.Sprintf("Error while converting: %s", err.Error())) } - var returner can.Frame = can.Frame{Length: 3} + var returner = can.Frame{Length: 3} copy(res, returner.Data[0:3]) return returner, nil } diff --git a/src/internal/convertfunctions/int2ascii.go b/src/internal/convertfunctions/int2ascii.go index ede2446..332a7d6 100644 --- a/src/internal/convertfunctions/int2ascii.go +++ b/src/internal/convertfunctions/int2ascii.go @@ -79,7 +79,7 @@ func FourInt162AsciiToMqtt(input can.Frame) ([]byte, error) { // numberAmount*numberWidth shall not be larger than 64 // input has to contain the data that shall be converted. The input is split at whitespaces, the amount of fields has // to match numberAmount. -// If the amount of fields matches, each field is converted to a uint of size numberWidth. The results are then added to the CAN-frame. +// If the amount of fields matches, each field is converted to an uint of size numberWidth. The results are then added to the CAN-frame. func NIntM2AsciiToCan(numberAmount, numberWidth uint, input []byte) (can.Frame, error) { if !(numberWidth == 8 || numberWidth == 16 || numberWidth == 32 || numberWidth == 64) { diff --git a/src/internal/convertfunctions/pixelbin2ascii.go b/src/internal/convertfunctions/pixelbin2ascii.go index 852f029..f2b6881 100644 --- a/src/internal/convertfunctions/pixelbin2ascii.go +++ b/src/internal/convertfunctions/pixelbin2ascii.go @@ -26,7 +26,7 @@ func PixelBin2AsciiToCan(input []byte) (can.Frame, error) { if err != nil { return can.Frame{}, errors.New(fmt.Sprintf("Error while converting: %s", err.Error())) } - var returner can.Frame = can.Frame{Length: 4} + var returner = can.Frame{Length: 4} returner.Data[0] = uint8(number) copy(res, returner.Data[1:4]) return returner, nil diff --git a/src/internal/convertfunctions/uint2ascii.go b/src/internal/convertfunctions/uint2ascii.go index c0490e5..82dc8ce 100644 --- a/src/internal/convertfunctions/uint2ascii.go +++ b/src/internal/convertfunctions/uint2ascii.go @@ -79,7 +79,7 @@ func FourUint162AsciiToMqtt(input can.Frame) ([]byte, error) { // numberAmount*numberWidth shall not be larger than 64 // input has to contain the data that shall be converted. The input is split at whitespaces, the amount of fields has // to match numberAmount. -// If the amount of fields matches, each field is converted to a uint of size numberWidth. The results are then added to the CAN-frame. +// If the amount of fields matches, each field is converted to an uint of size numberWidth. The results are then added to the CAN-frame. func NUintM2AsciiToCan(numberAmount, numberWidth uint, input []byte) (can.Frame, error) { if !(numberWidth == 8 || numberWidth == 16 || numberWidth == 32 || numberWidth == 64) { @@ -139,7 +139,7 @@ func NUintM2AsciiToMqtt(numberAmount, numberWidth uint, input can.Frame) ([]byte for i := uint(0); i < numberAmount; i++ { switch numberWidth { case 64: - returnStrings = append(returnStrings, strconv.FormatUint(uint64(binary.LittleEndian.Uint64(input.Data[i*bytePerNumber:(i+1)*bytePerNumber])), 10)) + returnStrings = append(returnStrings, strconv.FormatUint(binary.LittleEndian.Uint64(input.Data[i*bytePerNumber:(i+1)*bytePerNumber]), 10)) case 32: returnStrings = append(returnStrings, strconv.FormatUint(uint64(binary.LittleEndian.Uint32(input.Data[i*bytePerNumber:(i+1)*bytePerNumber])), 10)) case 16: diff --git a/src/internal/receivehandling.go b/src/internal/receivehandling.go index 780295d..91e68a3 100644 --- a/src/internal/receivehandling.go +++ b/src/internal/receivehandling.go @@ -39,7 +39,7 @@ func handleMQTT(_ MQTT.Client, msg MQTT.Message) { slog.Warn("receivehandler: conversion to CAN-Frame unsuccessful", "convertmode", pairFromTopic[msg.Topic()].convMethod, "error", err) return } - cf.ID = uint32(pairFromTopic[msg.Topic()].canId) + cf.ID = pairFromTopic[msg.Topic()].canId canPublish(cf) slog.Info("CAN <- MQTT", "ID", cf.ID, "len", cf.Length, "data", cf.Data, "convertmode", pairFromTopic[msg.Topic()].convMethod, "topic", msg.Topic(), "message", msg.Payload()) } From a749e855d33ef19ffca3e838de82817d93977518 Mon Sep 17 00:00:00 2001 From: Malte Muench Date: Fri, 10 May 2024 15:46:56 +0200 Subject: [PATCH 7/7] renamings, prefer short names Signed-off-by: Malte Muench --- src/internal/{canbushandling.go => canbus.go} | 22 +++++++++---------- src/internal/main.go | 12 +++++----- src/internal/{mqtthandling.go => mqtt.go} | 20 ++++++++--------- .../{receivehandling.go => receiving.go} | 8 +++---- 4 files changed, 31 insertions(+), 31 deletions(-) rename src/internal/{canbushandling.go => canbus.go} (65%) rename src/internal/{mqtthandling.go => mqtt.go} (68%) rename src/internal/{receivehandling.go => receiving.go} (74%) diff --git a/src/internal/canbushandling.go b/src/internal/canbus.go similarity index 65% rename from src/internal/canbushandling.go rename to src/internal/canbus.go index 2002fba..6bc9bb2 100644 --- a/src/internal/canbushandling.go +++ b/src/internal/canbus.go @@ -18,20 +18,20 @@ var bus *can.Bus // CAN-Bus pointer func canStart(canInterface string) { var err error - slog.Debug("canbushandler: initializing CAN-Bus", "interface", canInterface) + slog.Debug("canbus: initializing CAN-Bus", "interface", canInterface) bus, err = can.NewBusForInterfaceWithName(canInterface) if err != nil { - slog.Error("canbushandler: error while initializing CAN-Bus", "error", err) + slog.Error("canbus: error while initializing CAN-Bus", "error", err) os.Exit(1) } - slog.Info("canbushandler: connected to CAN") - slog.Debug("canbushandler: registering handler") + slog.Info("canbus: connected to CAN") + slog.Debug("canbus: registering handler") bus.SubscribeFunc(handleCANFrame) - slog.Debug("canbushandler: starting receive loop") + slog.Debug("canbus: starting receive loop") // will not return if everything is fine err = bus.ConnectAndPublish() if err != nil { - slog.Error("canbushandler: error while processing CAN-Bus", "error", err) + slog.Error("canbus: error while processing CAN-Bus", "error", err) os.Exit(1) } } @@ -41,14 +41,14 @@ func handleCANFrame(frame can.Frame) { var idSub = false // indicates, whether the id was subscribed or not for _, i := range csi { if i == frame.ID { - slog.Debug("canbushandler: received subscribed frame", "id", frame.ID) + slog.Debug("canbus: received subscribed frame", "id", frame.ID) go handleCAN(frame) idSub = true break } } if !idSub { - slog.Debug("canbushandler: ignored unsubscribed frame", "id", frame.ID) + slog.Debug("canbus: ignored unsubscribed frame", "id", frame.ID) } } @@ -57,12 +57,12 @@ func canSubscribe(id uint32) { csiLock.Lock() csi = append(csi, id) csiLock.Unlock() - slog.Debug("canbushandler: successfully subscribed CAN-ID", "id", id) + slog.Debug("canbus: successfully subscribed CAN-ID", "id", id) } // expects a CANFrame and sends it func canPublish(frame can.Frame) { - slog.Debug("canbushandler: sending CAN-Frame", "frame", frame) + slog.Debug("canbus: sending CAN-Frame", "frame", frame) // Check if ID is using more than 11-Bits: if frame.ID >= 0x800 { // if so, enable extended frame format @@ -70,6 +70,6 @@ func canPublish(frame can.Frame) { } err := bus.Publish(frame) if err != nil { - slog.Error("canbushandler: error while publishing CAN-Frame", "error", err) + slog.Error("canbus: error while publishing CAN-Frame", "error", err) } } diff --git a/src/internal/main.go b/src/internal/main.go index e3514ed..7b5a6f3 100644 --- a/src/internal/main.go +++ b/src/internal/main.go @@ -103,7 +103,7 @@ func readC2MPFromFile(filename string) { file, err := os.Open(filename) if err != nil { - slog.Error("main: can2mqtt.csv could not be opened", "filename", filename, "error", err) + slog.Error("can2mqtt.csv could not be opened", "filename", filename, "error", err) os.Exit(1) } @@ -118,24 +118,24 @@ func readC2MPFromFile(filename string) { break } if err != nil { - slog.Warn("main: skipping line", "filename", filename, "error", err) + slog.Warn("skipping line", "filename", filename, "error", err) continue } line, _ := r.FieldPos(0) tmp, err := strconv.ParseUint(record[0], 10, 32) if err != nil { - slog.Warn("main: skipping line, malformed can-ID", "error", err, "line", line) + slog.Warn("skipping line, malformed can-ID", "error", err, "line", line) continue } canID := uint32(tmp) convMode := record[1] topic := record[2] if isIDInSlice(canID) { - slog.Warn("main: skipping line, duplicate ID", "id", canID, "line", line) + slog.Warn("skipping line, duplicate ID", "id", canID, "line", line) continue } if isTopicInSlice(topic) { - slog.Warn("main: skipping line duplicate topic", "topic", topic, "line", line) + slog.Warn("skipping line duplicate topic", "topic", topic, "line", line) continue } switch convMode { @@ -307,7 +307,7 @@ func readC2MPFromFile(filename string) { } for _, c2mp := range pairFromID { - slog.Debug("main: extracted pair", "id", c2mp.canId, "convertmode", c2mp.convMethod, "topic", c2mp.mqttTopic) + slog.Debug("extracted pair", "id", c2mp.canId, "convertmode", c2mp.convMethod, "topic", c2mp.mqttTopic) } } diff --git a/src/internal/mqtthandling.go b/src/internal/mqtt.go similarity index 68% rename from src/internal/mqtthandling.go rename to src/internal/mqtt.go index 83124e2..8cf9341 100644 --- a/src/internal/mqtthandling.go +++ b/src/internal/mqtt.go @@ -20,7 +20,7 @@ func mqttStart(suppliedString string) { userPassword, host, found := strings.Cut(userPasswordHost, "@") user, pw, found = strings.Cut(userPassword, ":") if !found { - slog.Error("mqtthandler: missing colon(:) between username and password", "connect string", suppliedString) + slog.Error("mqtt: missing colon(:) between username and password", "connect string", suppliedString) os.Exit(1) } connectString = "tcp://" + host @@ -32,12 +32,12 @@ func mqttStart(suppliedString string) { clientSettings.SetCredentialsProvider(userPwCredProv) } client = MQTT.NewClient(clientSettings) - slog.Debug("mqtthandler: starting connection", "connectString", connectString) + slog.Debug("mqtt: starting connection", "connectString", connectString) if token := client.Connect(); token.Wait() && token.Error() != nil { - slog.Error("mqtthandler: could not connect to mqtt", "error", token.Error()) + slog.Error("mqtt: could not connect to mqtt", "error", token.Error()) os.Exit(1) } - slog.Info("mqtthandler: connected to mqtt") + slog.Info("mqtt: connected to mqtt") } // credentialsProvider @@ -48,25 +48,25 @@ func userPwCredProv() (username, password string) { // subscribe to a new topic func mqttSubscribe(topic string) { if token := client.Subscribe(topic, 0, nil); token.Wait() && token.Error() != nil { - slog.Error("mqtthandler: error subscribing", "error", token.Error()) + slog.Error("mqtt: error subscribing", "error", token.Error()) } - slog.Debug("mqtthandler: subscribed", "topic", topic) + slog.Debug("mqtt: subscribed", "topic", topic) } // unsubscribe a topic func mqttUnsubscribe(topic string) { if token := client.Unsubscribe(topic); token.Wait() && token.Error() != nil { - slog.Error("mqtthandler: error unsubscribing", "error", token.Error()) + slog.Error("mqtt: error unsubscribing", "error", token.Error()) } - slog.Debug("mqtthandler: unsubscribed", "topic", topic) + slog.Debug("mqtt: unsubscribed", "topic", topic) } // publish a new message func mqttPublish(topic string, payload []byte) { mqttUnsubscribe(topic) - slog.Debug("mqtthandler: publishing message", "payload", payload, "topic", topic) + slog.Debug("mqtt: publishing message", "payload", payload, "topic", topic) token := client.Publish(topic, 0, false, payload) token.Wait() - slog.Debug("mqtthandler: published message", "payload", payload, "topic", topic) + slog.Debug("mqtt: published message", "payload", payload, "topic", topic) mqttSubscribe(topic) } diff --git a/src/internal/receivehandling.go b/src/internal/receiving.go similarity index 74% rename from src/internal/receivehandling.go rename to src/internal/receiving.go index 91e68a3..eee10e9 100644 --- a/src/internal/receivehandling.go +++ b/src/internal/receiving.go @@ -11,12 +11,12 @@ import ( // 1. calling standard convert function: convert2MQTT // 2. sending the message func handleCAN(cf can.Frame) { - slog.Debug("receivehandler: received CANFrame", "id", cf.ID, "len", cf.Length, "data", cf.Data) + slog.Debug("received CANFrame", "id", cf.ID, "len", cf.Length, "data", cf.Data) // Only do conversions when necessary if dirMode != 2 { mqttPayload, err := pairFromID[cf.ID].toMqtt(cf) if err != nil { - slog.Warn("receivehandler: conversion to MQTT message unsuccessful", "convertmode", pairFromID[cf.ID].convMethod, "error", err) + slog.Warn("conversion to MQTT message unsuccessful", "convertmode", pairFromID[cf.ID].convMethod, "error", err) return } topic := getTopicFromId(cf.ID) @@ -31,12 +31,12 @@ func handleCAN(cf can.Frame) { // 1. calling the standard convert function: convert2CAN // 2. sending the message func handleMQTT(_ MQTT.Client, msg MQTT.Message) { - slog.Debug("receivehandler: received message", "topic", msg.Topic(), "payload", msg.Payload()) + slog.Debug("received message", "topic", msg.Topic(), "payload", msg.Payload()) if dirMode != 1 { cf, err := pairFromTopic[msg.Topic()].toCan(msg.Payload()) if err != nil { - slog.Warn("receivehandler: conversion to CAN-Frame unsuccessful", "convertmode", pairFromTopic[msg.Topic()].convMethod, "error", err) + slog.Warn("conversion to CAN-Frame unsuccessful", "convertmode", pairFromTopic[msg.Topic()].convMethod, "error", err) return } cf.ID = pairFromTopic[msg.Topic()].canId