rpi-vsts-ci-led/main.go

104 lines
1.8 KiB
Go
Raw Normal View History

2020-04-16 09:05:10 +00:00
package main
import (
2020-04-17 09:14:04 +00:00
"context"
2020-04-16 09:05:10 +00:00
"fmt"
2020-04-17 08:41:48 +00:00
"log"
2020-04-17 09:14:04 +00:00
"net/http"
2020-04-16 09:05:10 +00:00
"os"
"os/signal"
2020-04-17 08:41:48 +00:00
"rpi-ci-led/pkg/config"
"rpi-ci-led/pkg/database"
"rpi-ci-led/pkg/led"
"rpi-ci-led/pkg/websocket"
2020-04-16 09:05:10 +00:00
"rpi-ci-led/pkg/ws2812b"
2020-04-17 09:14:04 +00:00
"rpi-ci-led/route/routes"
2020-04-16 09:05:10 +00:00
"syscall"
2020-04-17 09:14:04 +00:00
"time"
2020-04-16 09:05:10 +00:00
2020-04-17 08:41:48 +00:00
"git.trj.tw/golang/argparse"
2020-04-16 09:05:10 +00:00
"github.com/joho/godotenv"
)
func main() {
fmt.Println("GO ci hook")
godotenv.Load()
2020-04-17 08:41:48 +00:00
var configFile string
var dbPath string
// argument parser
argParser := argparse.New()
argParser.Help("h", "help")
argParser.StringVar(&configFile, "", "f", "config", "config yaml file path", nil)
argParser.StringVar(&dbPath, "", "d", "db", "database file path", nil)
if err := argParser.Parse(os.Args); err != nil {
log.Fatal(err)
}
if err := config.Load(configFile); err != nil {
log.Fatal(err)
}
if err := database.New(dbPath); err != nil {
log.Fatal(err)
}
conf := config.Get()
socket, err := websocket.NewClient(conf.Remote.WSLoc)
if err != nil {
log.Fatal(err)
}
ledsvc, err := led.Init(conf.LED.Pin, conf.LED.Count)
if err != nil {
log.Fatal(err)
}
2020-04-16 09:05:10 +00:00
2020-04-17 09:14:04 +00:00
router := routes.New()
routes.SetRoutes(router)
svc := new(http.Server)
svc.Addr = fmt.Sprintf(":%d", conf.Server.Port)
svc.Handler = router
2020-04-16 09:05:10 +00:00
lock := make(chan os.Signal)
signal.Notify(lock, syscall.SIGINT, syscall.SIGTERM)
// main
2020-04-17 09:14:04 +00:00
go func() {
if err := svc.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
}()
2020-04-17 08:41:48 +00:00
go func() {
if err := socket.Listen(); err != nil {
log.Fatal(err)
}
lock <- syscall.SIGQUIT
}()
go func() { ledsvc.Run() }()
// start ws client connect to server
2020-04-16 09:05:10 +00:00
<-lock
2020-04-17 08:41:48 +00:00
fmt.Printf("Before process exit, close all connection\n")
2020-04-17 09:14:04 +00:00
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
defer cancel()
if err := svc.Shutdown(ctx); err != nil {
log.Fatal(err)
}
2020-04-17 08:41:48 +00:00
socket.Close()
2020-04-17 09:14:04 +00:00
ledsvc.Stop()
2020-04-16 09:05:10 +00:00
ws2812b.Close()
}