link.go 1.9 KB
Newer Older
J
Jason 已提交
1 2 3 4
package dtu

import (
	"bytes"
J
Jason 已提交
5
	"errors"
J
Jason 已提交
6
	"fmt"
J
Jason 已提交
7
	"log"
J
Jason 已提交
8 9
	"net"
	"regexp"
J
Jason 已提交
10
	"time"
J
Jason 已提交
11 12
)

J
顶替  
Jason 已提交
13 14
type Link struct {
	ID int64
J
 
Jason 已提交
15

J
Jason 已提交
16 17 18
	Error      string
	Serial     string
	RemoteAddr net.Addr
J
 
Jason 已提交
19

J
 
Jason 已提交
20 21
	Rx int
	Tx int
J
Jason 已提交
22

J
Jason 已提交
23 24
	conn interface{}

J
Jason 已提交
25 26
	lastTime time.Time

J
Jason 已提交
27
	channel *Channel
J
Jason 已提交
28

J
Jason 已提交
29 30
}

J
顶替  
Jason 已提交
31
func (l *Link) checkRegister(buf []byte) error {
J
Jason 已提交
32
	n := len(buf)
J
顶替  
Jason 已提交
33
	if n < l.channel.Register.Length {
J
Jason 已提交
34 35 36 37 38
		return fmt.Errorf("register package is too short %d %s", n, string(buf[:n]))
	}
	serial := string(buf[:n])

	// 正则表达式判断合法性
J
顶替  
Jason 已提交
39 40
	if l.channel.Register.Regex != "" {
		reg := regexp.MustCompile(`^` + l.channel.Register.Regex + `$`)
J
Jason 已提交
41 42 43 44 45 46 47
		match := reg.MatchString(serial)
		if !match {
			return fmt.Errorf("register package format error %s", serial)
		}
	}

	//按序号保存索引,供外部使用
J
顶替  
Jason 已提交
48
	connections.Store(serial, l)
J
Jason 已提交
49 50 51 52

	return nil
}

J
顶替  
Jason 已提交
53 54 55
func (l *Link) onData(buf []byte) {
	l.Rx += len(buf)
	l.lastTime = time.Now()
J
Jason 已提交
56

J
Jason 已提交
57
	//检查注册包
J
顶替  
Jason 已提交
58 59
	if l.channel.Register.Enable && l.Serial != "" {
		err := l.checkRegister(buf)
J
Jason 已提交
60
		if err != nil {
J
Jason 已提交
61
			log.Println(err)
J
顶替  
Jason 已提交
62
			_ = l.Close()
J
Jason 已提交
63 64 65 66 67 68 69 70 71
			return
		}

		//TODO 转发剩余内容

		return
	}

	//检查心跳包
J
顶替  
Jason 已提交
72
	if l.channel.HeartBeat.Enable && bytes.Compare(l.channel.HeartBeat.Content, buf) == 0 {
J
Jason 已提交
73
		//TODO 判断上次收发时间,是否已经过去心跳间隔
J
Jason 已提交
74 75 76
		return
	}

J
Jason 已提交
77
	//TODO 内容转发,暂时直接回复
J
顶替  
Jason 已提交
78
	_, _ = l.Send(buf)
J
Jason 已提交
79 80 81

}

J
顶替  
Jason 已提交
82 83 84
func (l *Link) Send(buf []byte) (int, error) {
	l.Tx += len(buf)
	l.lastTime = time.Now()
J
Jason 已提交
85

J
顶替  
Jason 已提交
86
	if conn, ok := l.conn.(net.Conn); ok {
J
Jason 已提交
87
		return conn.Write(buf)
J
Jason 已提交
88
	}
J
顶替  
Jason 已提交
89 90
	if conn, ok := l.conn.(net.PacketConn); ok {
		return conn.WriteTo(buf, l.RemoteAddr)
J
Jason 已提交
91
	}
J
Jason 已提交
92
	return 0, errors.New("错误的链接类型")
J
Jason 已提交
93 94
}

J
顶替  
Jason 已提交
95 96
func (l *Link) Close() error {
	return l.conn.(net.Conn).Close()
J
Jason 已提交
97
}
J
Jason 已提交
98

J
顶替  
Jason 已提交
99 100
func newConnection(conn net.Conn) *Link {
	return &Link{
J
Jason 已提交
101 102
		RemoteAddr: conn.RemoteAddr(),
		conn:       conn,
J
Jason 已提交
103 104 105
	}
}

J
顶替  
Jason 已提交
106 107
func newPacketConnection(conn net.PacketConn, addr net.Addr) *Link {
	return &Link{
J
 
Jason 已提交
108 109
		RemoteAddr: addr,
		conn:       conn,
J
Jason 已提交
110
	}
J
Jason 已提交
111
}