|
1 | 1 | package main |
2 | 2 |
|
3 | 3 | import ( |
| 4 | +"encoding/json" |
4 | 5 | "github.com/RoanBrand/SerialToTCPBridgeProtocol/protocol" |
5 | 6 | "log" |
| 7 | +"os" |
| 8 | +"sync" |
6 | 9 | "time" |
7 | 10 | ) |
8 | 11 |
|
9 | | -const ( |
10 | | -COMPortName = "COM4" // Windows |
11 | | -//COMPortName = "/dev/serial0" // Linux |
12 | | -COMBaudRate = 115200 |
13 | | -) |
14 | | - |
15 | 12 | func main() { |
16 | | -com := protocol.NewComGateway(COMPortName, COMBaudRate) |
17 | | -for { |
18 | | -err := com.ServeCOM() |
19 | | -log.Printf("%v: Error: %v\n", COMPortName, err) |
20 | | -log.Println("Retrying in 5s...") |
21 | | -time.Sleep(time.Second * 5) |
| 13 | +c, err := loadConfig() |
| 14 | +if err != nil { |
| 15 | +log.Fatalf(`%v (You must have a valid "config.json" next to the executable)`, err) |
| 16 | +} |
| 17 | +if len(c.Gateways) == 0 { |
| 18 | +log.Fatal("No gateways configured in the config. Exiting.") |
| 19 | +} |
| 20 | + |
| 21 | +w := sync.WaitGroup{} |
| 22 | +for _, v := range c.Gateways { |
| 23 | +w.Add(1) |
| 24 | +go func(v gatewayConfig) { |
| 25 | +com := protocol.NewComGateway(v.COMPortName, v.COMBaudRate) |
| 26 | +for { |
| 27 | +err := com.ServeCOM() |
| 28 | +log.Printf("%v: Error: %v\nRetrying in 5s...\n", v.COMPortName, err) |
| 29 | +time.Sleep(time.Second * 5) |
| 30 | +} |
| 31 | +w.Done() |
| 32 | +}(v) |
| 33 | +} |
| 34 | +w.Wait() |
| 35 | +} |
| 36 | + |
| 37 | +type gatewayConfig struct { |
| 38 | +GatewayName string `json:"gateway name"` |
| 39 | +COMPortName string `json:"comport name"` |
| 40 | +COMBaudRate int `json:"baud rate"` |
| 41 | +} |
| 42 | + |
| 43 | +type config struct { |
| 44 | +Gateways []gatewayConfig `json:"gateways"` |
| 45 | +} |
| 46 | + |
| 47 | +func loadConfig() (*config, error) { |
| 48 | +file, err := os.Open("config.json") |
| 49 | +if err != nil { |
| 50 | +return nil, err |
| 51 | +} |
| 52 | +decoder := json.NewDecoder(file) |
| 53 | +configuration := config{} |
| 54 | +err = decoder.Decode(&configuration) |
| 55 | +if err != nil { |
| 56 | +return nil, err |
22 | 57 | } |
| 58 | +return &configuration, nil |
23 | 59 | } |
0 commit comments