package main

import (
	"context"
	"dlt645-server/server"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/os/gproc"
	"os"
	"sparrow-sdk/config"
	gatewayV2 "sparrow-sdk/v2"
)

func main() {
	ctx := context.Background()
	err := glog.SetLevelStr(g.Cfg().GetString("Server.RunMode"))
	if err != nil {
		panic(err)
	}
	gw := gatewayV2.NewGateway(&config.Config{
		SparrowServer: g.Cfg().GetString("Sparrow.Server"),
		ProductKey:    g.Cfg().GetString("Sparrow.ProductKey"),
		Protocol:      "mqtt",
		DeviceCode:    g.Cfg().GetString("Sparrow.DeviceCode"),
		Version:       "1.0.0",
		Debug:         g.Cfg().GetBool("Sparrow.Debug"),
	})
	if _, err = gw.Register(); err != nil {
		panic(err)
	}
	if _, err = gw.Authentication(); err != nil {
		panic(err)
	}
	// 通用指令回调
	gw.SetReportCommandCallback(func(deviceCode, subId string) error {
		return nil
	})
	go gw.Connect()

	srv := server.NewServer(
		ctx,
		g.Cfg().GetString("Server.Addr"),
		g.Cfg().GetInt("Server.Port"),
		gw,
	)
	go func() {
		if err := srv.Start(); err != nil {
			panic(err)
		}
	}()

	gproc.AddSigHandlerShutdown(func(sig os.Signal) {
		gw.Close()
		srv.Stop()
	})
	gproc.Listen()
}
