-
Notifications
You must be signed in to change notification settings - Fork 0
/
comfo.go
107 lines (85 loc) · 2.54 KB
/
comfo.go
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
package main
import (
"fmt"
"io"
"log/slog"
"net"
"net/http"
"os"
"time"
"github.com/ti-mo/comfo/comfoserver"
"github.com/spf13/viper"
"github.com/tarm/serial"
)
var (
// Compile-time injected variables
// Version is the Comfo API version
Version string
// GitRev is the git revision the binary was built with
GitRev string
// BuildTime is the binary build timestamp
BuildTime string
// GoVersion is the go compiler version the binary was built with
GoVersion string
)
func main() {
fmt.Printf("Comfo API %v - home automation endpoint for ComfoAir-based ventilation units\n\n", Version)
fmt.Printf("Git Revision: %v\nBuild time: %v, with %v\n\n", GitRev, BuildTime, GoVersion)
// Configure Viper
viper.SetEnvPrefix("comfo")
viper.AutomaticEnv()
// Configure logging.
level := slog.LevelInfo
if viper.GetBool(configDebug) {
level = slog.LevelDebug
}
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: level}))
slog.SetDefault(logger)
slog.Debug("Debug logging enabled")
// Open connection to unit
c, err := ConnectUnit(viper.GetString(configMode), viper.GetString(configTarget))
if err != nil {
slog.Error("Error connecting to unit", "error", err)
os.Exit(1)
}
defer c.Close()
// Initialize and start cache timers
comfoserver.StartCaches(c)
// Initialize router and listen for connections
router := NewRouter()
srv := &http.Server{
Handler: router,
Addr: viper.GetString(configListen),
WriteTimeout: 5 * time.Second,
ReadTimeout: 5 * time.Second,
}
slog.Info("API listening", "address", viper.GetString(configListen))
if err := srv.ListenAndServe(); err != nil {
slog.Error("ListenAndServe", "error", err)
os.Exit(1)
}
}
// ConnectUnit sets up a connection to the unit over TCP or Serial.
func ConnectUnit(mode string, unit string) (conn io.ReadWriteCloser, err error) {
switch mode {
case "tcp":
// Establish TCP connection
slog.Info("Connecting to the unit over tcp", "address", unit)
conn, err = net.Dial("tcp", unit)
if err != nil {
return nil, fmt.Errorf("unable to dial the unit at %s: %w", unit, err)
}
slog.Info("Connection established!", "address", unit)
case "serial":
// Establish serial connection
slog.Info("Opening serial device", "device", unit)
conn, err = serial.OpenPort(&serial.Config{Name: unit, Baud: 9600})
if err != nil {
return nil, fmt.Errorf("unable to open serial device at %s: %w", unit, err)
}
slog.Info("Opened device", "device", unit)
default:
return nil, fmt.Errorf("unsupported unit mode %s", mode)
}
return
}