【feat】完成tcp,http的设备上报,及模拟设备测试

This commit is contained in:
XM-GO
2023-09-27 15:15:15 +08:00
parent 950e8d8814
commit 9eff841b81
16 changed files with 778 additions and 168 deletions

View File

@@ -3,28 +3,22 @@ package tcpserver
import (
"context"
"encoding/hex"
"github.com/emicklei/go-restful/v3"
"log"
"fmt"
"net"
"pandax/iothub/hook_message_work"
"pandax/iothub/netbase"
"pandax/pkg/global"
"pandax/pkg/rule_engine/message"
"strings"
"pandax/pkg/tool"
"time"
)
type HookTcpService struct {
HookService *hook_message_work.HookService
keepAlive int64
conn *net.TCPConn
}
func InitTcpHook(addr string, hs *hook_message_work.HookService) {
hhs := &HookTcpService{
HookService: hs,
keepAlive: 20,
}
server := NewTcpServer(addr)
err := server.Start(context.TODO())
if err != nil {
@@ -40,43 +34,58 @@ func InitTcpHook(addr string, hs *hook_message_work.HookService) {
global.Log.Error("Error accepting connection:", err)
continue
}
conn.SetReadDeadline(time.Now().Add(20 * time.Second))
hhs.conn = conn
conn.SetReadDeadline(time.Now().Add(2 * time.Minute))
hhs := &HookTcpService{
HookService: hs,
conn: conn,
}
go hhs.hook()
}
}()
}
// 获取token进行认证
func basicAuthenticate(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
path := req.Request.URL.Path
log.Println(path)
split := strings.Split(path, "/")
log.Println(split)
chain.ProcessFilter(req, resp)
}
func (hhs *HookTcpService) hook() {
isAuth := false
etoken := &tool.DeviceAuth{}
for {
buf := make([]byte, 128)
n := 0
n, err := hhs.conn.Read(buf)
if err != nil {
// 断开连接 掉线
log.Println("断开连接")
_ = hhs.conn.Close()
//设置断开连接
if isAuth {
data := netbase.CreateConnectionInfo(message.DisConnectMes, "tcp", hhs.conn.RemoteAddr().String(), hhs.conn.RemoteAddr().String(), etoken)
hhs.HookService.MessageCh <- data
}
isAuth = false
return
}
if !isAuth {
token := string(buf[:n])
log.Println(token)
isAuth = true
etoken.GetDeviceToken(token)
auth := netbase.Auth(token)
// 认证成功,创建连接记录
if auth {
data := netbase.CreateConnectionInfo(message.ConnectMes, "tcp", hhs.conn.RemoteAddr().String(), hhs.conn.RemoteAddr().String(), etoken)
hhs.HookService.MessageCh <- data
isAuth = true
hhs.Send("success")
} else {
hhs.Send("fail")
}
} else {
hexData := hex.EncodeToString(buf[:n])
log.Println(hexData)
ts := time.Now().Format("2006-01-02 15:04:05.000")
data := &netbase.DeviceEventInfo{
DeviceId: etoken.DeviceId,
DeviceAuth: etoken,
Type: message.RowMes,
}
data.Datas = fmt.Sprintf(`{"ts": "%s","rowdata": "%s"}`, ts, hexData)
// etoken中添加设备标识
hhs.HookService.MessageCh <- data
}
}