Browse Source

皇爷提交

THINK 2 years ago
commit
a258eb49b1
31 changed files with 4131 additions and 0 deletions
  1. 37 0
      .gitignore
  2. 20 0
      src/zks.com/gotcp/LICENSE
  3. 88 0
      src/zks.com/gotcp/README.md
  4. 320 0
      src/zks.com/gotcp/conn.go
  5. 122 0
      src/zks.com/gotcp/dial_test.go
  6. 108 0
      src/zks.com/gotcp/example/client/client.go
  7. 60 0
      src/zks.com/gotcp/example/ltvProtocol.go
  8. 122 0
      src/zks.com/gotcp/example/server/server.go
  9. 42 0
      src/zks.com/gotcp/protocol.go
  10. 84 0
      src/zks.com/gotcp/server.go
  11. 135 0
      src/zks.com/gotcp/server_test.go
  12. 85 0
      src/zks.com/gotcp/startTag/starttagProtocol.go
  13. 27 0
      src/zks.com/gotcp/util.go
  14. 316 0
      src/zks.com/newbbfrontsocketv2/blackbox/bboxProtocol.go
  15. 601 0
      src/zks.com/newbbfrontsocketv2/blackbox/blackboxcommon.go
  16. 50 0
      src/zks.com/newbbfrontsocketv2/blackbox/conf.go
  17. 586 0
      src/zks.com/newbbfrontsocketv2/blackbox/dataserver.go
  18. 197 0
      src/zks.com/newbbfrontsocketv2/blackbox/socketboltdb_test.go
  19. 22 0
      src/zks.com/newbbfrontsocketv2/blackbox/writedata.go
  20. 18 0
      src/zks.com/newbbfrontsocketv2/business/sensordata/sensordata.go
  21. 16 0
      src/zks.com/newbbfrontsocketv2/business/sensordata/sensordataService.go
  22. 25 0
      src/zks.com/newbbfrontsocketv2/business/versionmanage/versionmanage.go
  23. 16 0
      src/zks.com/newbbfrontsocketv2/business/versionmanage/versionmanageService.go
  24. 15 0
      src/zks.com/newbbfrontsocketv2/conf/app.conf
  25. 1 0
      src/zks.com/newbbfrontsocketv2/conf/port.txt
  26. 80 0
      src/zks.com/newbbfrontsocketv2/main.go
  27. 523 0
      src/zks.com/socketutils/dbgutil/debug.go
  28. 127 0
      src/zks.com/socketutils/log.go
  29. 22 0
      src/zks.com/socketutils/nsqlog.go
  30. 223 0
      src/zks.com/socketutils/stringConv.go
  31. 43 0
      src/zks.com/socketutils/utils.go

+ 37 - 0
.gitignore

@@ -0,0 +1,37 @@
1
+# ---> Go
2
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
3
+*.o
4
+*.a
5
+*.so
6
+
7
+# Folders
8
+_obj
9
+_test
10
+
11
+# Architecture specific extensions/prefixes
12
+*.[568vq]
13
+[568vq].out
14
+
15
+*.cgo1.go
16
+*.cgo2.c
17
+_cgo_defun.c
18
+_cgo_gotypes.go
19
+_cgo_export.*
20
+
21
+_testmain.go
22
+
23
+*.exe
24
+*.test
25
+*.prof
26
+
27
+
28
+.idea
29
+*.exe
30
+*.test
31
+*.prof
32
+*.exe
33
+*.exe~
34
+pkg
35
+swagger
36
+go.mod
37
+

+ 20 - 0
src/zks.com/gotcp/LICENSE

@@ -0,0 +1,20 @@
1
+The MIT License (MIT)
2
+
3
+Copyright (c) 2014 Jie Li
4
+
5
+Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+this software and associated documentation files (the "Software"), to deal in
7
+the Software without restriction, including without limitation the rights to
8
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+the Software, and to permit persons to whom the Software is furnished to do so,
10
+subject to the following conditions:
11
+
12
+The above copyright notice and this permission notice shall be included in all
13
+copies or substantial portions of the Software.
14
+
15
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 88 - 0
src/zks.com/gotcp/README.md

@@ -0,0 +1,88 @@
1
+gotcp is a powerful package for quickly writing tcp applications/services in golang.
2
+
3
+
4
+Install the gotcp package:
5
+~~~
6
+go get github.com/gansidui/gotcp
7
+~~~
8
+
9
+Create server.go file:
10
+
11
+~~~ go
12
+package main
13
+
14
+import (
15
+	"fmt"
16
+	"github.com/gansidui/gotcp"
17
+	"log"
18
+	"net"
19
+	"os"
20
+	"os/signal"
21
+	"runtime"
22
+	"syscall"
23
+	"time"
24
+)
25
+
26
+type ConnDelegate struct{}
27
+
28
+func (this *ConnDelegate) OnConnect(c *gotcp.Conn) bool {
29
+	fmt.Println("OnConnect")
30
+	return true
31
+}
32
+
33
+func (this *ConnDelegate) OnMessage(c *gotcp.Conn, p *gotcp.Packet) bool {
34
+	fmt.Println("OnMessage:", p.GetLen(), p.GetType(), string(p.GetData()))
35
+	return true
36
+}
37
+
38
+func (this *ConnDelegate) OnClose(c *gotcp.Conn) {
39
+	fmt.Println("OnClose")
40
+}
41
+
42
+func (this *ConnDelegate) OnIOError(c *gotcp.Conn, err error) {
43
+	fmt.Println("OnIOError:", err)
44
+}
45
+
46
+func main() {
47
+	runtime.GOMAXPROCS(runtime.NumCPU())
48
+
49
+	tcpAddr, err := net.ResolveTCPAddr("tcp4", "127.0.0.1:8989")
50
+	checkError(err)
51
+	listener, err := net.ListenTCP("tcp", tcpAddr)
52
+	checkError(err)
53
+
54
+	config := &gotcp.Config{
55
+		AcceptTimeout:          5 * time.Second,
56
+		ReadTimeout:            5 * time.Second,
57
+		WriteTimeout:           5 * time.Second,
58
+		MaxPacketLength:        int32(2048),
59
+		SendPacketChanLimit:    int32(10),
60
+		ReceivePacketChanLimit: int32(10),
61
+	}
62
+	delegate := &ConnDelegate{}
63
+
64
+	svr := gotcp.NewServer(config, delegate)
65
+	go svr.Start(listener)
66
+
67
+	ch := make(chan os.Signal)
68
+	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
69
+	log.Printf("Signal: %v\r\n", <-ch)
70
+
71
+	svr.Stop()
72
+}
73
+
74
+func checkError(err error) {
75
+	if err != nil {
76
+		log.Fatal(err)
77
+	}
78
+}
79
+
80
+
81
+~~~
82
+
83
+
84
+Run server:
85
+~~~
86
+go run server.go
87
+~~~
88
+

+ 320 - 0
src/zks.com/gotcp/conn.go

@@ -0,0 +1,320 @@
1
+package gotcp
2
+
3
+import (
4
+	"errors"
5
+	"fmt"
6
+	"log"
7
+	"net"
8
+	"sync"
9
+	"sync/atomic"
10
+	"time"
11
+)
12
+
13
+// Conn exposes a set of callbacks for the
14
+// various events that occur on a connection
15
+type Conn struct {
16
+	conn        *net.TCPConn     // the raw TCPConn
17
+	config      *Config          // configure information
18
+	delegate    ConnDelegate     // callbacks in Conn
19
+	protocol    Protocol         // data protocol
20
+	deliverData *deliverConnData // server delivery deliverConnData to the connection to control
21
+
22
+	extraData interface{} // save the extra data with conn
23
+
24
+	closeOnce sync.Once // close the conn, once, per instance.
25
+	closeFlag int32
26
+	closeChan chan struct{}
27
+
28
+	sendPacketChan    chan *Packet // send packet queue
29
+	receivePacketChan chan *Packet // receive packet queue
30
+}
31
+
32
+// ConnDelegate is an interface of methods
33
+// that are used as callbacks in Conn
34
+type ConnDelegate interface {
35
+	// OnConnect is called when the connection was accepted,
36
+	// If the return value of false is closed
37
+	OnConnect(*Conn) bool
38
+
39
+	// OnMessage is called when the connection receives a packet,
40
+	// If the return value of false is closed
41
+	OnMessage(*Conn, *Packet) bool
42
+
43
+	// OnClose is called when the connection closed
44
+	OnClose(*Conn)
45
+
46
+	// OnIOError is called when the connection experiences
47
+	// a low-level TCP transport error
48
+	OnIOError(*Conn, error)
49
+}
50
+
51
+// The configure of connection
52
+type Config struct {
53
+	AcceptTimeout          time.Duration // connection accepted timeout
54
+	ReadTimeout            time.Duration // connection read timeout
55
+	WriteTimeout           time.Duration // connection write timeout
56
+	MaxPacketLength        uint32        // the maximum length of packet
57
+	SendPacketChanLimit    uint32        // the limit of packet send channel
58
+	ReceivePacketChanLimit uint32        // the limit of packet receive channel
59
+}
60
+
61
+func newConn(conn *net.TCPConn,, config *Config, delegate ConnDelegate, protocol Protocol, deliverData *deliverConnData) *Conn {
62
+	return &Conn{
63
+		conn:              conn,
64
+		config:            config,
65
+		delegate:          delegate,
66
+		protocol:          protocol,
67
+		deliverData:       deliverData,
68
+		closeChan:         make(chan struct{}),
69
+		sendPacketChan:    make(chan *Packet, config.SendPacketChanLimit),
70
+		receivePacketChan: make(chan *Packet, config.ReceivePacketChanLimit),
71
+	}
72
+}
73
+
74
+// Get extra data
75
+func (c *Conn) GetExtraData() interface{} {
76
+	return c.extraData
77
+}
78
+
79
+// Put extra data
80
+func (c *Conn) PutExtraData(data interface{}) {
81
+	c.extraData = data
82
+}
83
+
84
+// Get the raw connection to use more features
85
+func (c *Conn) GetRawConn() *net.TCPConn {
86
+	return c.conn
87
+}
88
+
89
+// Close the Conn
90
+func (c *Conn) Close() {
91
+	c.closeOnce.Do(func() {
92
+		atomic.StoreInt32(&c.closeFlag, 1)
93
+		close(c.closeChan)
94
+		c.conn.Close()
95
+		c.delegate.OnClose(c)
96
+	})
97
+}
98
+
99
+func (c *Conn) SetReadDeadline(timeout time.Duration) {
100
+	c.conn.SetReadDeadline(time.Now().Add(timeout))
101
+}
102
+
103
+func (c *Conn) SetWriteDeadline(timeout time.Duration) {
104
+	c.conn.SetWriteDeadline(time.Now().Add(timeout))
105
+}
106
+
107
+// Indicates whether or not the connection is closed
108
+func (c *Conn) IsClosed() bool {
109
+	return atomic.LoadInt32(&c.closeFlag) == 1
110
+}
111
+
112
+// Sync read a packet, this method will block on IO
113
+func (c *Conn) ReadPacket() (*Packet, error) {
114
+	return c.protocol.ReadPacket(c.conn, c.config.MaxPacketLength)
115
+}
116
+
117
+// Async read a packet, this method will never block
118
+func (c *Conn) AsyncReadPacket(timeout time.Duration) (*Packet, error) {
119
+	if c.IsClosed() {
120
+		return nil, ConnClosedError
121
+	}
122
+
123
+	if timeout == 0 {
124
+		select {
125
+		case p := <-c.receivePacketChan:
126
+			return p, nil
127
+
128
+		case <-c.closeChan:
129
+			return nil, ConnClosedError
130
+
131
+		default:
132
+			return nil, ReadBlockedError
133
+		}
134
+
135
+	} else {
136
+		select {
137
+		case p := <-c.receivePacketChan:
138
+			return p, nil
139
+
140
+		case <-c.closeChan:
141
+			return nil, ConnClosedError
142
+
143
+		case <-time.After(timeout):
144
+			return nil, ReadBlockedError
145
+		}
146
+	}
147
+}
148
+
149
+// Sync write a packet, this method will block on IO
150
+func (c *Conn) WritePacket(p *Packet) error {
151
+	if c.IsClosed() {
152
+		return ConnClosedError
153
+	}
154
+
155
+	if n, err := c.conn.Write(p.Serialize()); err != nil || n != int(p.GetLen()) {
156
+		return errors.New(fmt.Sprintf("Write error: [%v], n[%v], p len[%v]", err, n, p.GetLen()))
157
+	}
158
+
159
+	return nil
160
+}
161
+func (c *Conn) WritePacketN(p *Packet) (int ,error) {
162
+	if c.IsClosed() {
163
+		return 100,ConnClosedError
164
+	}
165
+	n, err := c.conn.Write(p.Serialize());
166
+	if  err != nil || n != int(p.GetLen()) {
167
+		return n,errors.New(fmt.Sprintf("Write error: [%v], n[%v], p len[%v]", err, n, p.GetLen()))
168
+	}
169
+
170
+	return n,nil
171
+}
172
+
173
+// Async write a packet, this method will never block
174
+func (c *Conn) AsyncWritePacket(p *Packet, timeout time.Duration) error {
175
+	if c.IsClosed() {
176
+		return ConnClosedError
177
+	}
178
+
179
+	if timeout == 0 {
180
+		select {
181
+		case c.sendPacketChan <- p:
182
+			return nil
183
+
184
+		case <-c.closeChan:
185
+			return ConnClosedError
186
+
187
+		default:
188
+			return WriteBlockedError
189
+		}
190
+
191
+	} else {
192
+		select {
193
+		case c.sendPacketChan <- p:
194
+			return nil
195
+
196
+		case <-c.closeChan:
197
+			return ConnClosedError
198
+
199
+		case <-time.After(timeout):
200
+			return WriteBlockedError
201
+		}
202
+	}
203
+}
204
+
205
+func (c *Conn) Do() {
206
+	c.deliverData.waitGroup.Add(3)
207
+	go c.handleLoop()
208
+	go c.readLoop()
209
+	go c.writeLoop()
210
+}
211
+
212
+func (c *Conn) readLoop() {
213
+	defer func() {
214
+		if e := recover(); e != nil {
215
+			log.Printf("readLoop panic: %v\r\n", e)
216
+		}
217
+		c.Close()
218
+		c.deliverData.waitGroup.Done()
219
+	}()
220
+
221
+	for {
222
+		select {
223
+		case <-c.deliverData.exitChan:
224
+			return
225
+
226
+		case <-c.closeChan:
227
+			return
228
+
229
+		default:
230
+		}
231
+
232
+		c.conn.SetReadDeadline(time.Now().Add(c.config.ReadTimeout))
233
+
234
+		recPacket, err := c.ReadPacket()
235
+		if err != nil {
236
+			c.delegate.OnIOError(c, err)
237
+			return
238
+		}
239
+
240
+		c.receivePacketChan <- recPacket
241
+	}
242
+}
243
+
244
+func (c *Conn) writeLoop() {
245
+	defer func() {
246
+		if e := recover(); e != nil {
247
+			log.Printf("writeLoop panic: %v\r\n", e)
248
+		}
249
+		c.Close()
250
+		c.deliverData.waitGroup.Done()
251
+	}()
252
+
253
+	for {
254
+		select {
255
+		case <-c.deliverData.exitChan:
256
+			return
257
+
258
+		case <-c.closeChan:
259
+			return
260
+
261
+		case p := <-c.sendPacketChan:
262
+			err := c.WritePacket(p)
263
+			if err != nil {
264
+				c.delegate.OnIOError(c, err)
265
+				return
266
+			}
267
+		}
268
+	}
269
+}
270
+
271
+func (c *Conn) handleLoop() {
272
+	defer func() {
273
+		if e := recover(); e != nil {
274
+			log.Printf("handleLoop panic: %v\r\n", e)
275
+		}
276
+		c.Close()
277
+		c.deliverData.waitGroup.Done()
278
+	}()
279
+
280
+	if !c.delegate.OnConnect(c) {
281
+		return
282
+	}
283
+
284
+	rawConn, err := c.(*net.TCPConn).SyscallConn()
285
+	if err != nil {
286
+		fmt.Println("Error getting raw connection:", err.Error())
287
+		continue
288
+	}
289
+
290
+	rawConn.Control(func(fd uintptr) {
291
+		err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.SOL_SOCKET, syscall.SO_RCVBUF, 1024)
292
+		if err != nil {
293
+			fmt.Println("Error setting receive buffer size:", err.Error())
294
+			return
295
+		}
296
+
297
+		var val int
298
+		val, err = syscall.GetsockoptInt(syscall.Handle(fd), syscall.SOL_SOCKET, syscall.SO_RCVBUF)
299
+		if err != nil {
300
+			fmt.Println("Error getting receive buffer size:", err.Error())
301
+			return
302
+		}
303
+
304
+		fmt.Printf("Receive buffer size: %d\n", val)
305
+	})
306
+	for {
307
+		select {
308
+		case <-c.deliverData.exitChan:
309
+			return
310
+
311
+		case <-c.closeChan:
312
+			return
313
+
314
+		case p := <-c.receivePacketChan:
315
+			if !c.delegate.OnMessage(c, p) {
316
+				return
317
+			}
318
+		}
319
+	}
320
+}

+ 122 - 0
src/zks.com/gotcp/dial_test.go

@@ -0,0 +1,122 @@
1
+package gotcp
2
+
3
+import (
4
+	"fmt"
5
+	"net"
6
+	"testing"
7
+	"time"
8
+)
9
+
10
+// Server delegate
11
+type ServerDelegate struct {
12
+	t *testing.T
13
+}
14
+
15
+func (this *ServerDelegate) OnConnect(c *Conn) bool {
16
+	fmt.Println("Server OnConnect")
17
+	return true
18
+}
19
+
20
+func (this *ServerDelegate) OnMessage(c *Conn, p *Packet) bool {
21
+	fmt.Println("Server OnMessage")
22
+
23
+	if p.GetType() == 777 {
24
+		if string(p.GetData()) != "BYE" {
25
+			this.t.Fatal()
26
+		}
27
+		return false
28
+	}
29
+
30
+	if p.GetType() != 999 || string(p.GetData()) != "hello" {
31
+		this.t.Fatal()
32
+	}
33
+
34
+	c.WritePacket(NewPacket(888, []byte("world")))
35
+
36
+	return true
37
+}
38
+
39
+func (this *ServerDelegate) OnClose(c *Conn) {
40
+	fmt.Println("Server OnClose")
41
+}
42
+
43
+func (this *ServerDelegate) OnIOError(c *Conn, err error) {
44
+	fmt.Println("Server OnIOError")
45
+}
46
+
47
+// Client delegate
48
+type ClientDelegate struct {
49
+	t *testing.T
50
+}
51
+
52
+func (this *ClientDelegate) OnConnect(c *Conn) bool {
53
+	fmt.Println("Client OnConnect")
54
+	return true
55
+}
56
+
57
+func (this *ClientDelegate) OnMessage(c *Conn, p *Packet) bool {
58
+	fmt.Println("Client OnMessage")
59
+
60
+	if p.GetType() != 888 || string(p.GetData()) != "world" {
61
+		this.t.Fatal()
62
+	}
63
+
64
+	c.AsyncWritePacket(NewPacket(777, []byte("BYE")), time.Second)
65
+
66
+	return true
67
+}
68
+
69
+func (this *ClientDelegate) OnClose(c *Conn) {
70
+	fmt.Println("Client OnClose")
71
+}
72
+
73
+func (this *ClientDelegate) OnIOError(c *Conn, err error) {
74
+	fmt.Println("Client OnIOError")
75
+}
76
+
77
+func TestDial(t *testing.T) {
78
+	tcpAddr, _ := net.ResolveTCPAddr("tcp4", "127.0.0.1:8990")
79
+	listener, _ := net.ListenTCP("tcp", tcpAddr)
80
+
81
+	config := &Config{
82
+		AcceptTimeout:          5 * time.Second,
83
+		ReadTimeout:            5 * time.Second,
84
+		WriteTimeout:           5 * time.Second,
85
+		MaxPacketLength:        int32(2048),
86
+		SendPacketChanLimit:    int32(10),
87
+		ReceivePacketChanLimit: int32(10),
88
+	}
89
+	delegate := &ServerDelegate{t: t}
90
+
91
+	svr := NewServer(config, delegate)
92
+	go svr.Start(listener)
93
+
94
+	time.Sleep(time.Second)
95
+
96
+	simulateClientDial(t, svr)
97
+
98
+	svr.Stop()
99
+}
100
+
101
+func simulateClientDial(t *testing.T, svr *Server) {
102
+	config := &Config{
103
+		AcceptTimeout:          5 * time.Second,
104
+		ReadTimeout:            5 * time.Second,
105
+		WriteTimeout:           5 * time.Second,
106
+		MaxPacketLength:        int32(2048),
107
+		SendPacketChanLimit:    int32(10),
108
+		ReceivePacketChanLimit: int32(10),
109
+	}
110
+	delegate := &ClientDelegate{t: t}
111
+
112
+	conn, err := svr.Dial("tcp4", "127.0.0.1:8990", config, delegate)
113
+	if err != nil {
114
+		t.Fatal()
115
+	}
116
+
117
+	go conn.Do()
118
+	time.Sleep(time.Second)
119
+
120
+	conn.WritePacket(NewPacket(999, []byte("hello")))
121
+	time.Sleep(time.Second)
122
+}

+ 108 - 0
src/zks.com/gotcp/example/client/client.go

@@ -0,0 +1,108 @@
1
+package main
2
+
3
+import (
4
+	"errors"
5
+	"fmt"
6
+	"log"
7
+	"net"
8
+	"time"
9
+
10
+	"zks.com/gotcp/example"
11
+)
12
+
13
+const (
14
+	TYPE_LOGIN = iota + 1
15
+	TYPE_LOGOUT
16
+	TYPE_MSG
17
+
18
+	TYPE_REPLY_LOGIN
19
+	TYPE_REPLY_LOGOUT
20
+	TYPE_REPLY_MSG
21
+)
22
+
23
+func main() {
24
+	for j := 0; j < 100000; j++ {
25
+
26
+		go func(j int) {
27
+			conn, err := connect()
28
+			if err != nil {
29
+				log.Fatal(err)
30
+			}
31
+			defer conn.Close()
32
+
33
+			fmt.Println("connect  ====== ", j)
34
+
35
+			if err = sendLogin(conn); err != nil {
36
+				log.Fatal(err)
37
+			}
38
+
39
+			for i := 0; i < 200; i++ {
40
+				time.Sleep(6 * time.Second)
41
+				if err = sendMsg(conn); err != nil {
42
+					log.Fatal(err)
43
+				}
44
+			}
45
+
46
+			if err = sendLogout(conn); err != nil {
47
+				log.Fatal(err)
48
+			}
49
+
50
+			fmt.Println("disconnect  ****** ", j)
51
+
52
+		}(j)
53
+
54
+		time.Sleep(20 * time.Millisecond)
55
+	}
56
+
57
+	time.Sleep(time.Hour)
58
+}
59
+
60
+func connect() (*net.TCPConn, error) {
61
+	tcpAddr, _ := net.ResolveTCPAddr("tcp4", "127.0.0.1:8989")
62
+	return net.DialTCP("tcp", nil, tcpAddr)
63
+}
64
+
65
+func sendLogin(conn *net.TCPConn) error {
66
+	conn.Write(example.NewPacket(TYPE_LOGIN, []byte("LOGIN")).Serialize())
67
+	ltvProtocol := new(example.LtvProtocol)
68
+	p, err := ltvProtocol.ReadPacket(conn, 2048)
69
+	if err != nil {
70
+		return err
71
+	}
72
+
73
+	if p.GetTypeInt() != TYPE_REPLY_LOGIN || string(p.GetData()) != "LOGIN OK" {
74
+		return errors.New("LOGIN FAILED")
75
+	}
76
+
77
+	return nil
78
+}
79
+
80
+func sendLogout(conn *net.TCPConn) error {
81
+	conn.Write(example.NewPacket(TYPE_LOGOUT, []byte("BYE BYE")).Serialize())
82
+	ltvProtocol := new(example.LtvProtocol)
83
+	p, err := ltvProtocol.ReadPacket(conn, 2048)
84
+	if err != nil {
85
+		return err
86
+	}
87
+
88
+	if p.GetTypeInt() != TYPE_REPLY_LOGOUT || string(p.GetData()) != "LOGOUT OK" {
89
+		return errors.New("LOGOUT FAILED")
90
+	}
91
+
92
+	return nil
93
+}
94
+
95
+func sendMsg(conn *net.TCPConn) error {
96
+	conn.Write(example.NewPacket(TYPE_MSG, []byte("hello world")).Serialize())
97
+	ltvProtocol := new(example.LtvProtocol)
98
+	p, err := ltvProtocol.ReadPacket(conn, 2048)
99
+	if err != nil {
100
+		return err
101
+	}
102
+
103
+	if p.GetTypeInt() != TYPE_REPLY_MSG || string(p.GetData()) != "REPLY_hello world" {
104
+		return errors.New("MSG FAILED")
105
+	}
106
+
107
+	return nil
108
+}

+ 60 - 0
src/zks.com/gotcp/example/ltvProtocol.go

@@ -0,0 +1,60 @@
1
+package example
2
+
3
+import (
4
+	"io"
5
+
6
+	"zks.com/gotcp"
7
+)
8
+
9
+// Packet: pacLen + pacType + pacData
10
+// Big endian: int32 + int32 + []byte
11
+type LtvPacketDelegate struct {
12
+	pacLen  uint32
13
+	pacType uint32
14
+	pacData []byte
15
+}
16
+
17
+func (p *LtvPacketDelegate) Serialize() []byte {
18
+	buf := make([]byte, 8+len(p.pacData))
19
+	copy(buf[0:4], gotcp.Uint32ToBytes(p.pacLen))
20
+	copy(buf[4:8], gotcp.Uint32ToBytes(p.pacType))
21
+	copy(buf[8:], p.pacData)
22
+	return buf
23
+}
24
+
25
+func (p *LtvPacketDelegate) GetLen() uint32 {
26
+	return p.pacLen
27
+}
28
+
29
+func (p *LtvPacketDelegate) GetTypeInt() uint32 {
30
+	return p.pacType
31
+}
32
+
33
+func (p *LtvPacketDelegate) GetTypeString() string {
34
+	return ""
35
+}
36
+
37
+func (p *LtvPacketDelegate) GetData() []byte {
38
+	return p.pacData
39
+}
40
+
41
+func NewPacket(pacType uint32, pacData []byte) *gotcp.Packet {
42
+	packet := new(gotcp.Packet)
43
+	packet.Delegate = &LtvPacketDelegate{
44
+		pacLen:  uint32(8) + uint32(len(pacData)),
45
+		pacType: pacType,
46
+		pacData: pacData,
47
+	}
48
+	return packet
49
+}
50
+
51
+type LtvProtocol struct {
52
+}
53
+
54
+func (this *LtvProtocol) ReadPacket(r io.Reader, MaxPacketLength uint32) (*gotcp.Packet, error) {
55
+
56
+	data := make([]byte, MaxPacketLength) // 设定缓存空间
57
+	readLengh, _ := r.Read(data)
58
+
59
+	return NewPacket(1, data[:readLengh]), nil
60
+}

+ 122 - 0
src/zks.com/gotcp/example/server/server.go

@@ -0,0 +1,122 @@
1
+package main
2
+
3
+import (
4
+	"fmt"
5
+	"log"
6
+	"net"
7
+	"os"
8
+	"os/signal"
9
+	"runtime"
10
+	"syscall"
11
+	"time"
12
+
13
+	"zks.com/gotcp"
14
+	"zks.com/gotcp/example"
15
+)
16
+
17
+const (
18
+	TYPE_LOGIN = iota + 1
19
+	TYPE_LOGOUT
20
+	TYPE_MSG
21
+
22
+	TYPE_REPLY_LOGIN
23
+	TYPE_REPLY_LOGOUT
24
+	TYPE_REPLY_MSG
25
+)
26
+
27
+type ConnDelegate struct {
28
+	connectCount int
29
+	closeCount   int
30
+	messageCount int
31
+}
32
+
33
+func (this *ConnDelegate) OnConnect(c *gotcp.Conn) bool {
34
+	p, err := c.AsyncReadPacket(5 * time.Second)
35
+	if err != nil {
36
+		fmt.Printf("OnConnect[Error]:[%v]\n", err)
37
+		return false
38
+	}
39
+
40
+	if p.GetTypeInt() == TYPE_LOGIN && string(p.GetData()) == "LOGIN" {
41
+		c.WritePacket(example.NewPacket(TYPE_REPLY_LOGIN, []byte("LOGIN OK")))
42
+
43
+		this.connectCount++
44
+		c.PutExtraData(this.connectCount)
45
+
46
+		fmt.Printf("OnConnect[LOGIN][***%v***]\n", c.GetExtraData().(int))
47
+		return true
48
+	}
49
+
50
+	return false
51
+}
52
+
53
+func (this *ConnDelegate) OnMessage(c *gotcp.Conn, p *gotcp.Packet) bool {
54
+	if p.GetTypeInt() == TYPE_LOGOUT {
55
+		c.WritePacket(example.NewPacket(TYPE_REPLY_LOGOUT, []byte("LOGOUT OK")))
56
+		fmt.Printf("OnMessage[LOGOUT][***%v***]:[%v]\n", c.GetExtraData().(int), string(p.GetData()))
57
+		return false
58
+	}
59
+
60
+	if p.GetTypeInt() == TYPE_MSG {
61
+		c.AsyncWritePacket(example.NewPacket(TYPE_REPLY_MSG, []byte("REPLY_"+string(p.GetData()))), 5*time.Second)
62
+
63
+		this.messageCount++
64
+
65
+		fmt.Printf("OnMessage[MSG][***%v***]:[%v]\n", c.GetExtraData().(int), string(p.GetData()))
66
+		return true
67
+	}
68
+
69
+	return true
70
+}
71
+
72
+func (this *ConnDelegate) OnClose(c *gotcp.Conn) {
73
+	this.closeCount++
74
+	fmt.Printf("OnClose[***%v***]\n", c.GetExtraData().(int))
75
+}
76
+
77
+func (this *ConnDelegate) OnIOError(c *gotcp.Conn, err error) {
78
+	fmt.Printf("OnIOError[***%v***]:[%v]\n", c.GetExtraData().(int), err)
79
+}
80
+
81
+func main() {
82
+	runtime.GOMAXPROCS(runtime.NumCPU())
83
+
84
+	tcpAddr, err := net.ResolveTCPAddr("tcp4", "127.0.0.1:8989")
85
+	checkError(err)
86
+
87
+	listener, err := net.ListenTCP("tcp", tcpAddr)
88
+	checkError(err)
89
+
90
+	config := &gotcp.Config{
91
+		AcceptTimeout:          10 * time.Second,
92
+		ReadTimeout:            120 * time.Second,
93
+		WriteTimeout:           120 * time.Second,
94
+		MaxPacketLength:        2048,
95
+		SendPacketChanLimit:    10,
96
+		ReceivePacketChanLimit: 10,
97
+	}
98
+	delegate := &ConnDelegate{}
99
+	protocol := &example.LtvProtocol{}
100
+	svr := gotcp.NewServer(config, delegate, protocol)
101
+	go svr.Start(listener)
102
+
103
+	go func() {
104
+		for {
105
+			fmt.Println("===========goroutine==========", runtime.NumGoroutine())
106
+			fmt.Println(delegate.connectCount, delegate.closeCount, delegate.messageCount)
107
+			time.Sleep(2 * time.Second)
108
+		}
109
+	}()
110
+
111
+	ch := make(chan os.Signal)
112
+	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
113
+	log.Printf("Signal: %v\r\n", <-ch)
114
+
115
+	svr.Stop()
116
+}
117
+
118
+func checkError(err error) {
119
+	if err != nil {
120
+		log.Fatal(err)
121
+	}
122
+}

+ 42 - 0
src/zks.com/gotcp/protocol.go

@@ -0,0 +1,42 @@
1
+package gotcp
2
+
3
+import (
4
+	"io"
5
+)
6
+
7
+type PacketDelegate interface {
8
+	Serialize() []byte
9
+	GetLen() uint32
10
+	GetData() []byte
11
+	GetTypeInt() uint32
12
+	GetTypeString() string
13
+}
14
+
15
+type Packet struct {
16
+	length   int32
17
+	Delegate PacketDelegate
18
+}
19
+
20
+func (p *Packet) Serialize() []byte {
21
+	return p.Delegate.Serialize()
22
+}
23
+
24
+func (p *Packet) GetLen() uint32 {
25
+	return p.Delegate.GetLen()
26
+}
27
+
28
+func (p *Packet) GetData() []byte {
29
+	return p.Delegate.GetData()
30
+}
31
+
32
+func (p *Packet) GetTypeInt() uint32 {
33
+	return p.Delegate.GetTypeInt()
34
+}
35
+
36
+func (p *Packet) GetTypeString() string {
37
+	return p.Delegate.GetTypeString()
38
+}
39
+
40
+type Protocol interface {
41
+	ReadPacket(r io.Reader, MaxPacketLength uint32) (*Packet, error)
42
+}

+ 84 - 0
src/zks.com/gotcp/server.go

@@ -0,0 +1,84 @@
1
+package gotcp
2
+
3
+import (
4
+	"log"
5
+	"net"
6
+	"sync"
7
+	"time"
8
+)
9
+
10
+// Server struct
11
+type Server struct {
12
+	config      *Config          // configure infomation
13
+	delegate    ConnDelegate     // conn delegate(message callbacks)
14
+	protocol    Protocol         // data protocol
15
+	deliverData *deliverConnData // deliver to conn
16
+}
17
+
18
+// Server delivery deliverConnData to the connection to control
19
+type deliverConnData struct {
20
+	exitChan  chan struct{}   // server notify all goroutines to shutdown
21
+	waitGroup *sync.WaitGroup // wait for all goroutines
22
+}
23
+
24
+func NewServer(config *Config, delegate ConnDelegate, protocol Protocol) *Server {
25
+	return &Server{
26
+		config:   config,
27
+		delegate: delegate,
28
+		protocol: protocol,
29
+		deliverData: &deliverConnData{
30
+			exitChan:  make(chan struct{}),
31
+			waitGroup: &sync.WaitGroup{},
32
+		},
33
+	}
34
+}
35
+
36
+// Start server
37
+func (s *Server) Start(listener *net.TCPListener) {
38
+	log.Printf("Start listen on %v\r\n", listener.Addr())
39
+	s.deliverData.waitGroup.Add(1)
40
+	defer func() {
41
+		log.Printf("Stop listen on %v\r\n", listener.Addr())
42
+		listener.Close()
43
+		s.deliverData.waitGroup.Done()
44
+	}()
45
+
46
+	for {
47
+		select {
48
+		case <-s.deliverData.exitChan:
49
+			return
50
+
51
+		default:
52
+		}
53
+
54
+		listener.SetDeadline(time.Now().Add(s.config.AcceptTimeout))
55
+
56
+		conn, err := listener.AcceptTCP()
57
+		if err != nil {
58
+			continue
59
+		}
60
+
61
+		go newConn(conn, s.config, s.delegate, s.protocol, s.deliverData).Do()
62
+	}
63
+}
64
+
65
+// Stop server
66
+func (s *Server) Stop() {
67
+	close(s.deliverData.exitChan)
68
+	s.deliverData.waitGroup.Wait()
69
+}
70
+
71
+// Server dial to the other server
72
+func (s *Server) Dial(network, address string, config *Config, delegate ConnDelegate, protocol Protocol) (*Conn, error) {
73
+	tcpAddr, err := net.ResolveTCPAddr(network, address)
74
+	if err != nil {
75
+		return nil, err
76
+	}
77
+
78
+	conn, err := net.DialTCP("tcp", nil, tcpAddr)
79
+	if err != nil {
80
+		return nil, err
81
+	}
82
+
83
+	return newConn(conn, config, delegate, protocol, s.deliverData), nil
84
+}

+ 135 - 0
src/zks.com/gotcp/server_test.go

@@ -0,0 +1,135 @@
1
+package gotcp
2
+
3
+import (
4
+	"fmt"
5
+	"net"
6
+	"testing"
7
+	"time"
8
+)
9
+
10
+// test tips
11
+/******************************************************/
12
+
13
+var OnConnectTip, OnMessageTip, OnCloseTip, OnIOErrorTip string
14
+
15
+/******************************************************/
16
+
17
+// delegate
18
+/******************************************************/
19
+type Delegate struct{}
20
+
21
+func (this *Delegate) OnConnect(c *Conn) bool {
22
+	p, err := c.AsyncReadPacket(5 * time.Second)
23
+	if err != nil {
24
+		return false
25
+	}
26
+
27
+	OnConnectTip = fmt.Sprintf("OnConnect[%v,%v,%v]", p.GetLen(), p.GetType(), string(p.GetData()))
28
+
29
+	fmt.Println(OnConnectTip)
30
+	return true
31
+}
32
+
33
+func (this *Delegate) OnMessage(c *Conn, p *Packet) bool {
34
+	OnMessageTip = fmt.Sprintf("OnMessage[%v,%v,%v]", p.GetLen(), p.GetType(), string(p.GetData()))
35
+	fmt.Println(OnMessageTip)
36
+
37
+	if string(p.GetData()) == "logout" {
38
+		c.WritePacket(NewPacket(888, []byte("ok")))
39
+		return false
40
+	}
41
+
42
+	c.AsyncWritePacket(NewPacket(999, []byte(string(p.GetData())+",ok")), 5*time.Second)
43
+
44
+	return true
45
+}
46
+
47
+func (this *Delegate) OnClose(c *Conn) {
48
+	OnCloseTip = fmt.Sprintf("OnClose[%v]", c.IsClosed())
49
+	fmt.Println(OnCloseTip)
50
+}
51
+
52
+func (this *Delegate) OnIOError(c *Conn, err error) {
53
+	if err != nil {
54
+		OnIOErrorTip = fmt.Sprintf("OnIOError[%v]", err)
55
+	}
56
+	fmt.Println(OnIOErrorTip)
57
+}
58
+
59
+/******************************************************/
60
+
61
+func simulateClient(t *testing.T) {
62
+	tcpAddr, _ := net.ResolveTCPAddr("tcp4", "127.0.0.1:8989")
63
+	conn, _ := net.DialTCP("tcp", nil, tcpAddr)
64
+
65
+	// OnConnect
66
+	conn.Write(NewPacket(777, []byte("login")).Serialize())
67
+	time.Sleep(100 * time.Millisecond)
68
+	if OnConnectTip != "OnConnect[13,777,login]" {
69
+		t.Fatal()
70
+	}
71
+
72
+	// OnMessage
73
+	conn.Write(NewPacket(666, []byte("helloworld")).Serialize())
74
+	time.Sleep(100 * time.Millisecond)
75
+	if OnMessageTip != "OnMessage[18,666,helloworld]" {
76
+		t.Fatal()
77
+	}
78
+
79
+	retPacket, _ := ReadPacket(conn, 2048)
80
+	if retPacket.GetLen() != 21 || retPacket.GetType() != 999 || string(retPacket.GetData()) != "helloworld,ok" {
81
+		t.Fatal()
82
+	}
83
+
84
+	// OnClose
85
+	conn.Write(NewPacket(555, []byte("logout")).Serialize())
86
+	time.Sleep(100 * time.Millisecond)
87
+	if OnMessageTip != "OnMessage[14,555,logout]" {
88
+		t.Fatal()
89
+	}
90
+
91
+	retPacket, _ = ReadPacket(conn, 2048)
92
+	if retPacket.GetLen() != 10 || retPacket.GetType() != 888 || string(retPacket.GetData()) != "ok" {
93
+		t.Fatal()
94
+	}
95
+
96
+	if OnCloseTip != "OnClose[true]" {
97
+		t.Fatal()
98
+	}
99
+
100
+	// OnIOError
101
+	if OnIOErrorTip != fmt.Sprintf("OnIOError[%v]", ReadPacketError) {
102
+		t.Fatal()
103
+	}
104
+}
105
+
106
+func TestServer(t *testing.T) {
107
+	tcpAddr, err := net.ResolveTCPAddr("tcp4", "127.0.0.1:8989")
108
+	if err != nil {
109
+		t.Fatal()
110
+	}
111
+
112
+	listener, err := net.ListenTCP("tcp", tcpAddr)
113
+	if err != nil {
114
+		t.Fatal()
115
+	}
116
+
117
+	config := &Config{
118
+		AcceptTimeout:          5 * time.Second,
119
+		ReadTimeout:            5 * time.Second,
120
+		WriteTimeout:           5 * time.Second,
121
+		MaxPacketLength:        2048,
122
+		SendPacketChanLimit:    10,
123
+		ReceivePacketChanLimit: 10,
124
+	}
125
+	delegate := &Delegate{}
126
+
127
+	svr := NewServer(config, delegate)
128
+	go svr.Start(listener)
129
+
130
+	time.Sleep(time.Second)
131
+
132
+	simulateClient(t)
133
+
134
+	svr.Stop()
135
+}

+ 85 - 0
src/zks.com/gotcp/startTag/starttagProtocol.go

@@ -0,0 +1,85 @@
1
+package example
2
+
3
+import (
4
+	"io"
5
+
6
+	"zks.com/gotcp"
7
+)
8
+
9
+var (
10
+	fullBuf *bytes.Buffer = bytes.NewBuffer([]byte{}) //缓存区
11
+	SOH     []byte        = []byte{0xBE, 0xBE}        //开始标记 start of head
12
+)
13
+
14
+// Packet: SOH + Data
15
+type StartTagPacketDelegate struct {
16
+	pacLen  int32
17
+	pacType int32
18
+	pacData []byte
19
+}
20
+
21
+func (p *StartTagPacketDelegate) Serialize() []byte {
22
+	buf := make([]byte, 8+len(p.pacData))
23
+	copy(buf[0:4], gotcp.Int32ToBytes(p.pacLen))
24
+	copy(buf[4:8], gotcp.Int32ToBytes(p.pacType))
25
+	copy(buf[8:], p.pacData)
26
+	return buf
27
+}
28
+
29
+func (p *StartTagPacketDelegate) GetLen() int32 {
30
+	return p.pacLen
31
+}
32
+
33
+func (p *StartTagPacketDelegate) GetTypeInt() int32 {
34
+	return p.pacType
35
+}
36
+
37
+func (p *StartTagPacketDelegate) GetTypeString() string {
38
+	return ""
39
+}
40
+
41
+func (p *StartTagPacketDelegate) GetData() []byte {
42
+	return p.pacData
43
+}
44
+
45
+func NewPacket(pacType int32, pacData []byte) *gotcp.Packet {
46
+	packet := new(gotcp.Packet)
47
+	packet.Delegate = &LtvPacketDelegate{
48
+		pacLen:  int32(8) + int32(len(pacData)),
49
+		pacType: pacType,
50
+		pacData: pacData,
51
+	}
52
+	return packet
53
+}
54
+
55
+type StartTagProtocol struct {
56
+}
57
+
58
+func (this *StartTagProtocol) ReadPacket(r io.Reader, MaxPacketLength int32) (*gotcp.Packet, error) {
59
+	var (
60
+		pacBLen  []byte = make([]byte, 4)
61
+		pacBType []byte = make([]byte, 4)
62
+		pacLen   int32
63
+	)
64
+
65
+	// read pacLen
66
+	if n, err := io.ReadFull(r, pacBLen); err != nil && n != 4 {
67
+		return nil, gotcp.ReadPacketError
68
+	}
69
+	if pacLen = gotcp.BytesToInt32(pacBLen); pacLen > MaxPacketLength {
70
+		return nil, gotcp.PacketTooLargeError
71
+	}
72
+
73
+	// read pacType
74
+	if n, err := io.ReadFull(r, pacBType); err != nil && n != 4 {
75
+		return nil, gotcp.ReadPacketError
76
+	}
77
+
78
+	// read pacData
79
+	pacData := make([]byte, pacLen-8)
80
+	if n, err := io.ReadFull(r, pacData); err != nil && n != int(pacLen) {
81
+		return nil, gotcp.ReadPacketError
82
+	}
83
+
84
+	return NewPacket(gotcp.BytesToInt32(pacBType), pacData), nil
85
+}

+ 27 - 0
src/zks.com/gotcp/util.go

@@ -0,0 +1,27 @@
1
+package gotcp
2
+
3
+import (
4
+	"encoding/binary"
5
+	"errors"
6
+)
7
+
8
+// Error types
9
+var (
10
+	ConnClosedError     = errors.New("connection was closed")
11
+	WriteBlockedError   = errors.New("write blocking")
12
+	ReadBlockedError    = errors.New("read blocking")
13
+	ReadPacketError     = errors.New("read packet error")
14
+	PacketTooLargeError = errors.New("packet too large")
15
+)
16
+
17
+// BigEndian: uint32 --> []byte
18
+func Uint32ToBytes(v uint32) []byte {
19
+	b := make([]byte, 4)
20
+	binary.BigEndian.PutUint32(b, v)
21
+	return b
22
+}
23
+
24
+// BigEndian: []byte --> uint32
25
+func BytesToUint32(b []byte) uint32 {
26
+	return binary.BigEndian.Uint32(b)
27
+}

+ 316 - 0
src/zks.com/newbbfrontsocketv2/blackbox/bboxProtocol.go

@@ -0,0 +1,316 @@
1
+package blackbox
2
+
3
+import (
4
+	"fmt"
5
+	"io"
6
+
7
+	"bytes"
8
+	"sync"
9
+	"time"
10
+
11
+	"zks.com/gotcp"
12
+	utils "zks.com/socketutils"
13
+	coldcloud "zks.com/zcoldcloud"
14
+)
15
+
16
+//var SockeData = struct {
17
+//	sync.RWMutex
18
+//	m map[string][]byte
19
+//}{m: make(map[string][]byte)}
20
+
21
+type SockeBody struct {
22
+	Time int64
23
+	Body []byte
24
+}
25
+
26
+var SockeData = struct {
27
+	sync.RWMutex
28
+	m map[string]SockeBody
29
+}{m: make(map[string]SockeBody)}
30
+
31
+// Packet
32
+type BBoxPacketDelegate struct {
33
+	pLen  uint32
34
+	pType uint32
35
+	pData []byte
36
+}
37
+type blackboxddata struct {
38
+	Code      string
39
+	Datapoint coldcloud.DatapointColdCloud
40
+}
41
+
42
+func (p *BBoxPacketDelegate) Serialize() []byte {
43
+	return p.pData
44
+}
45
+
46
+func (p *BBoxPacketDelegate) GetLen() uint32 {
47
+	return p.pLen
48
+}
49
+
50
+func (p *BBoxPacketDelegate) GetTypeInt() uint32 {
51
+	return p.pType
52
+}
53
+
54
+func (p *BBoxPacketDelegate) GetTypeString() string {
55
+	return ""
56
+}
57
+
58
+func (p *BBoxPacketDelegate) GetData() []byte {
59
+	return p.pData
60
+}
61
+
62
+func NewPacket(pType uint32, pData []byte) *gotcp.Packet {
63
+	packet := new(gotcp.Packet)
64
+	packet.Delegate = &BBoxPacketDelegate{
65
+		pLen:  uint32(len(pData)),
66
+		pType: pType,
67
+		pData: pData,
68
+	}
69
+	return packet
70
+}
71
+
72
+type BBoxProtocol struct {
73
+}
74
+
75
+//通用
76
+func (this *BBoxProtocol) ReadPacket(r io.Reader, MaxPacketLength uint32) (*gotcp.Packet, error) {
77
+	data := make([]byte, MaxPacketLength) // 设定缓存空间
78
+	readLengh, err := r.Read(data)
79
+	//utils.InformationalWithFormat("request: % X", data[:readLengh])
80
+	if err != nil { //EOF, or worse
81
+		fmt.Println(1, err)
82
+		return nil, err
83
+	}
84
+	if readLengh == 0 { // 连接可能已被客户端关闭
85
+		fmt.Println("数据长度读取为零")
86
+		return nil, gotcp.ReadPacketError
87
+		//return nil, err
88
+	} else {
89
+		//fmt.Println("next execuse NewPacket")
90
+		return NewPacket(1, data[:readLengh]), nil
91
+	}
92
+
93
+}
94
+func (this *BBoxProtocol) ReadPacket_OK(r io.Reader, MaxPacketLength uint32) (*gotcp.Packet, error) {
95
+	var fullBuf *bytes.Buffer = bytes.NewBuffer([]byte{}) //缓存区
96
+	for {
97
+		data := make([]byte, MaxPacketLength) // 设定缓存空间
98
+		readLengh, err := r.Read(data)
99
+		if err != nil { //EOF, or worse
100
+			return nil, err
101
+		}
102
+		if readLengh == 0 { // 连接可能已被客户端关闭
103
+			return nil, gotcp.ReadPacketError
104
+		} else {
105
+			//记录日志
106
+			utils.InformationalWithFormat("% X", data[:readLengh])
107
+			if (data[0] == 0x7E && data[readLengh-1] == 0x7E) || (data[0] == 0x8E && data[readLengh-1] == 0x8E) {
108
+				if len(fullBuf.Bytes()) > 0 {
109
+					fmt.Println("错误日志>黏包", fmt.Sprintf("% X", fullBuf.Bytes()))
110
+				}
111
+				return NewPacket(1, data[:readLengh]), nil
112
+			} else {
113
+				fullBuf.Write(data[:readLengh]) //写入数据到缓冲区
114
+				if (fullBuf.Bytes()[0] == 0x7E && fullBuf.Bytes()[len(fullBuf.Bytes())-1] == 0x7E) || (fullBuf.Bytes()[0] == 0x8E && fullBuf.Bytes()[len(fullBuf.Bytes())-1] == 0x8E) {
115
+					return NewPacket(1, fullBuf.Bytes()), nil
116
+				} else if fullBuf.Bytes()[0] == 0x7E {
117
+					continue
118
+				}
119
+			}
120
+		}
121
+	}
122
+}
123
+
124
+type BBoxConnDelegate struct {
125
+	connectCount int
126
+	closeCount   int
127
+	messageCount int
128
+}
129
+
130
+func (this *BBoxConnDelegate) OnConnect(c *gotcp.Conn) bool {
131
+
132
+	this.connectCount++
133
+	Conns.Lock()
134
+	fmt.Println("连接数:", len(Conns.m))
135
+	Conns.Unlock()
136
+	c.PutExtraData(this.connectCount)
137
+
138
+	return true
139
+}
140
+
141
+// 正式使用
142
+func (this *BBoxConnDelegate) OnMessage_OK(c *gotcp.Conn, p *gotcp.Packet) bool {
143
+	fmt.Println("连接数:", c.GetRawConn().RemoteAddr())
144
+	bs := p.GetData()
145
+	utils.InformationalWithFormat("OnMessage:% X", bs)
146
+	if len(bs) >= 2 {
147
+		if bs[0] == 0x8E {
148
+			go DoWork(c, bs)
149
+		} else {
150
+			data := []byte{}
151
+			for i := 0; i < len(bs); i++ {
152
+				data = append(data, bs[i])
153
+				if i != 0 && bs[i] == 0x7E && len(data) > 2 {
154
+					go DoWork(c, data)
155
+					data = []byte{}
156
+				}
157
+			}
158
+		}
159
+	}
160
+	return true
161
+}
162
+
163
+//记录socket通道存断开数据
164
+func (this *BBoxConnDelegate) OnMessage(c *gotcp.Conn, p *gotcp.Packet) bool {
165
+	bs := p.GetData()
166
+	utils.InformationalWithFormat("OnMessage:% X", bs)
167
+	if len(bs) >= 2 {
168
+		data := []byte{}
169
+		//正常数据有7E开头结束
170
+		if bs[0] == 0x7E && bs[len(bs)-1] == 0x7E {
171
+			SockeData.Lock()
172
+			if len(SockeData.m[utils.ToStr(c.GetRawConn().RemoteAddr())].Body) > 0 { //map中有待发数据
173
+				oldbs := SockeData.m[utils.ToStr(c.GetRawConn().RemoteAddr())].Body
174
+				var newbs []byte
175
+				rightdata := false
176
+				for i := 0; i < len(oldbs); i++ {
177
+					if len(newbs) == 0 && oldbs[i] == 0x7E && len(oldbs)-1 > i && oldbs[i+1] != 0x7E {
178
+						rightdata = true
179
+					}
180
+					if rightdata == true {
181
+						newbs = append(newbs, oldbs[i])
182
+					}
183
+					if len(newbs) > 5 && oldbs[i] == 0x7E { //获取黏包中有效数据
184
+						rightdata = false
185
+						go DoWork(c, newbs)
186
+						newbs = []byte{}
187
+					}
188
+				}
189
+				fmt.Println(c.GetRawConn().RemoteAddr(), "错误日志>黏包", fmt.Sprintf("% X", SockeData.m[utils.ToStr(c.GetRawConn().RemoteAddr())].Body))
190
+				Writedata_v2(fmt.Sprintf("% X", SockeData.m[utils.ToStr(c.GetRawConn().RemoteAddr())].Body))
191
+			}
192
+			delete(SockeData.m, utils.ToStr(c.GetRawConn().RemoteAddr()))
193
+			SockeData.Unlock()
194
+			for i := 0; i < len(bs); i++ {
195
+				data = append(data, bs[i])
196
+				if i != 0 && bs[i] == 0x7E && len(data) > 2 {
197
+					go DoWork(c, data)
198
+					data = []byte{}
199
+				}
200
+			}
201
+		} else if bs[0] == 0x8E && bs[len(bs)-1] == 0x8E { //平台下发命令
202
+			go DoWork(c, bs)
203
+		} else { //异常数据
204
+			SockeData.Lock()
205
+			bodylen := len(SockeData.m[utils.ToStr(c.GetRawConn().RemoteAddr())].Body)
206
+			if bodylen > 0 && SockeData.m[utils.ToStr(c.GetRawConn().RemoteAddr())].Body[0] == 0x7E && bs[len(bs)-1] == 0x7E { //断包处理,map中有7E开头,新来数据有7E结尾
207
+				okbody := append(SockeData.m[utils.ToStr(c.GetRawConn().RemoteAddr())].Body, bs...)
208
+				delete(SockeData.m, utils.ToStr(c.GetRawConn().RemoteAddr()))
209
+				SockeData.Unlock()
210
+				for i := 0; i < len(okbody); i++ {
211
+					data = append(data, okbody[i])
212
+					if i != 0 && okbody[i] == 0x7E && len(data) > 2 {
213
+						go DoWork(c, data)
214
+						data = []byte{}
215
+					}
216
+				}
217
+			} else if bodylen == 0 && bs[0] != 0x7E { //map中没有信息,新来数据没有7E开头(处理脏数据)
218
+				var newbs []byte
219
+				rightdata := false
220
+				for i := 0; i < len(bs); i++ {
221
+					if len(newbs) == 0 && bs[i] == 0x7E && len(bs)-1 > i && bs[i+1] != 0x7E {
222
+						rightdata = true
223
+					}
224
+					if rightdata == true {
225
+						newbs = append(newbs, bs[i])
226
+					}
227
+
228
+					if len(newbs) > 5 && bs[i] == 0x7E { //捕获带有脏数据有7E开头结尾的数据
229
+						rightdata = false
230
+						go DoWork(c, newbs)
231
+						newbs = []byte{}
232
+					}
233
+				}
234
+				//处理带有脏数据的有7E开头没有7E结尾的数据,去掉开头脏数据保留有效数据存入map
235
+				if len(newbs) > 5 {
236
+					SockeData.m[utils.ToStr(c.GetRawConn().RemoteAddr())] = SockeBody{Time: time.Now().Unix(), Body: newbs}
237
+					fmt.Println(c.GetRawConn().RemoteAddr(), "错误日志>无7E开头(黏指令)", fmt.Sprintf("% X", bs))
238
+				} else {
239
+					fmt.Println(c.GetRawConn().RemoteAddr(), "错误日志>无7E开头", fmt.Sprintf("% X", bs))
240
+				}
241
+				SockeData.Unlock()
242
+				Writedata_v2(fmt.Sprintf("% X", bs))
243
+			} else { //断包处理后半段数据,(map中有信息,新来数据没有7E开头)?
244
+				SockeData.m[utils.ToStr(c.GetRawConn().RemoteAddr())] = SockeBody{Time: time.Now().Unix(), Body: append(SockeData.m[utils.ToStr(c.GetRawConn().RemoteAddr())].Body, bs...)}
245
+				SockeData.Unlock()
246
+			}
247
+		}
248
+	}
249
+	return true
250
+}
251
+func (this *BBoxConnDelegate) OnMessage1(c *gotcp.Conn, p *gotcp.Packet) bool {
252
+	fmt.Println("连接数:", c.GetRawConn().RemoteAddr())
253
+	bs := p.GetData()
254
+	utils.InformationalWithFormat("OnMessage:% X", bs)
255
+	if len(bs) >= 2 {
256
+		if bs[0] == 0x8E {
257
+			go DoWork(c, bs)
258
+		} else {
259
+			data := []byte{}
260
+			for i := 0; i < len(bs); i++ {
261
+				data = append(data, bs[i])
262
+				if i != 0 && bs[i] == 0x7E && len(data) > 2 {
263
+					go DoWork(c, data)
264
+					data = []byte{}
265
+				}
266
+			}
267
+		}
268
+	}
269
+	return true
270
+}
271
+func (this *BBoxConnDelegate) OnClose(c *gotcp.Conn) {
272
+	defer func() {
273
+		if r := recover(); r != nil {
274
+			fmt.Println("OnClose Recovered in f", r)
275
+		}
276
+	}()
277
+	this.closeCount++
278
+	Conns.Lock()
279
+	for k, v := range Conns.m {
280
+		if v == c {
281
+			fmt.Println(k + "已断开")
282
+			delete(Conns.m, k)
283
+			fmt.Println("剩余连接数:", len(Conns.m))
284
+		}
285
+	}
286
+	Conns.Unlock()
287
+	SockeData.Lock()
288
+	if len(SockeData.m[utils.ToStr(c.GetRawConn().RemoteAddr())].Body) > 0 {
289
+		oldbs := SockeData.m[utils.ToStr(c.GetRawConn().RemoteAddr())].Body
290
+		var newbs []byte
291
+		rightdata := false
292
+		for i := 0; i < len(oldbs); i++ {
293
+			if len(newbs) == 0 && oldbs[i] == 0x7E && len(oldbs)-1 > i && oldbs[i+1] != 0x7E {
294
+				rightdata = true
295
+			}
296
+			if rightdata == true {
297
+				newbs = append(newbs, oldbs[i])
298
+			}
299
+			if len(newbs) > 5 && oldbs[i] == 0x7E {
300
+				rightdata = false
301
+				go DoWork(c, newbs)
302
+				newbs = []byte{}
303
+			}
304
+		}
305
+		fmt.Println("错误日志>连接断开数据包丢失", fmt.Sprintf("% X", SockeData.m[utils.ToStr(c.GetRawConn().RemoteAddr())].Body))
306
+		Writedata_v2(fmt.Sprintf("% X", SockeData.m[utils.ToStr(c.GetRawConn().RemoteAddr())].Body))
307
+	}
308
+	delete(SockeData.m, utils.ToStr(c.GetRawConn().RemoteAddr()))
309
+	fmt.Println("统计黏包socket", len(SockeData.m))
310
+	SockeData.Unlock()
311
+	fmt.Printf("OnClose[%s][***%v***]\n")
312
+}
313
+
314
+func (this *BBoxConnDelegate) OnIOError(c *gotcp.Conn, err error) {
315
+	fmt.Printf("OnIOError[%s][***%v***]:[%v]\n", c.GetRawConn().RemoteAddr(), c.GetExtraData().(int), err)
316
+}

+ 601 - 0
src/zks.com/newbbfrontsocketv2/blackbox/blackboxcommon.go

@@ -0,0 +1,601 @@
1
+package blackbox
2
+
3
+import (
4
+	"strconv"
5
+	"time"
6
+
7
+	"bytes"
8
+	"encoding/json"
9
+	"fmt"
10
+	"github.com/axgle/mahonia"
11
+	"io/ioutil"
12
+	"net/http"
13
+	"strings"
14
+	"zks.com/gotcp"
15
+	"zks.com/newbbfrontsocketv2/business/versionmanage"
16
+	"zks.com/socketutils"
17
+	utils "zks.com/zUtils"
18
+	coldcloud "zks.com/zcoldcloud"
19
+)
20
+
21
+type GaoDeGpsChange struct {
22
+	Status    string `json:"status"`
23
+	Info      string `json:"info"`
24
+	Locations string `json:"locations"`
25
+}
26
+
27
+func GetChannelValue(c *gotcp.Conn, value, command []byte, msgid, msggatewayid string, msgliusid int64) (dataarray []blackboxddata) {
28
+	defer func() {
29
+		if r := recover(); r != nil {
30
+			fmt.Println("Recovered in f", r)
31
+		}
32
+	}()
33
+	switch msgid {
34
+	case "2004":
35
+		Conns2004.Lock()
36
+		if v, ok := Conns2004.m[msggatewayid]; ok {
37
+			socketutils.InformationalWithFormat("授时:", msggatewayid, "数据:", v)
38
+			if time.Now().Unix()-v.Time < 300 && v.Count+1 > 5 {
39
+				socketutils.InformationalWithFormat("授时主动断开:", msggatewayid)
40
+				c.Close()
41
+				delete(Conns2004.m, msggatewayid)
42
+				Conns2004.Unlock()
43
+				return nil
44
+			}
45
+			if time.Now().Unix()-v.Time > 60*60 {
46
+				Conns2004.m[msggatewayid] = Status2004{time.Now().Unix(), 1}
47
+			} else {
48
+				Conns2004.m[msggatewayid] = Status2004{v.Time, v.Count + 1}
49
+			}
50
+		} else {
51
+			Conns2004.m[msggatewayid] = Status2004{time.Now().Unix(), 1}
52
+		}
53
+		Conns2004.Unlock()
54
+		var uyear, umonth, uday, uhour, uminute, usecond uint64
55
+		t := time.Now().Format("20060102150405")
56
+		uyear, _ = strconv.ParseUint(t[2:4], 16, 0)
57
+		umonth, _ = strconv.ParseUint(t[4:6], 16, 0)
58
+		uday, _ = strconv.ParseUint(t[6:8], 16, 0)
59
+		uhour, _ = strconv.ParseUint(t[8:10], 16, 0)
60
+		uminute, _ = strconv.ParseUint(t[10:12], 16, 0)
61
+		usecond, _ = strconv.ParseUint(t[12:], 16, 0)
62
+		sendms := []byte{0xA0, 0x04, 0x00, 0x06, command[5], command[6], command[7], command[8], command[9], command[10], command[11], command[12], byte(uyear), byte(umonth), byte(uday), byte(uhour), byte(uminute), byte(usecond)}
63
+		sendms = append(sendms, yihuo(sendms))
64
+		send := []byte{0x7E}
65
+		for _, v := range sendms {
66
+			if v == 0x7E {
67
+				send = append(send, 0x7D, 0x02)
68
+			} else if v == 0x7D {
69
+				send = append(send, 0x7D, 0x01)
70
+			} else {
71
+				send = append(send, v)
72
+			}
73
+		}
74
+		send = append(send, 0x7E)
75
+		//err_send := c.WritePacket(NewPacket(3, send))
76
+		n, err_send := c.WritePacketN(NewPacket(3, send))
77
+		socketutils.InformationalWithFormat("守时:", n, "错误信息:", err_send)
78
+	case "2010", "2011":
79
+		temp := value
80
+		if len(temp) < 19 {
81
+			fmt.Println("2010类型数据长度下小于19", len(temp))
82
+			return
83
+		}
84
+		var gdzdcd int64
85
+		switch int(temp[0]) {
86
+		case 3:
87
+			sensors := make(map[string]string)
88
+			temp = temp[10:]
89
+			for {
90
+				sensorid := fmt.Sprintf("%X", temp[1:5])
91
+				fmt.Println("sensorid ", sensorid) //sensorid
92
+				if sensorid != msggatewayid {
93
+					sensors[sensorid] = sensorid
94
+				}
95
+				gdzdcd = 14
96
+				sjnewcom := temp[gdzdcd+1:]
97
+				tempnew := S6ForWriter(sjnewcom)
98
+				temp = tempnew
99
+				fmt.Println("剩余长度", len(temp))
100
+				if len(temp) == 0 {
101
+
102
+					break
103
+				}
104
+			}
105
+			for sensor, _ := range sensors {
106
+				DParamSensorSet(c, sensor, msggatewayid)
107
+			}
108
+		}
109
+		if msgid == "2011" {
110
+			fmt.Println("-------> [反馈分支][2011]")
111
+			// 发送反馈信息
112
+			rawMsg := []byte{0xA0, 0x01, 0x00, 0x05, command[5], command[6], command[7], command[8], command[9], command[10], command[11], command[12]}
113
+			rawMsg = append(rawMsg, Valuebyte2(int(msgliusid))...)
114
+			rawMsg = append(rawMsg, 0x20, 0x11, 0x00)
115
+			rawMsg = append(rawMsg, yihuo(rawMsg))
116
+			message := []byte{0x7E}
117
+			for _, v := range rawMsg {
118
+				if v == 0x7E {
119
+					message = append(message, 0x7D, 0x02)
120
+				} else if v == 0x7D {
121
+					message = append(message, 0x7D, 0x01)
122
+				} else {
123
+					message = append(message, v)
124
+				}
125
+			}
126
+			message = append(message, 0x7E)
127
+			fmt.Println("_ _ _ _ _ _ _ _ _ _ _ _ _ _ [2011][Response] _ _ _ _ _ _ _ _ _ _ _ _ _ _")
128
+			fmt.Println("[Msg]", fmt.Sprintf("%X", message))
129
+			go WritePacketAndLog(c, message, time.Now().Unix())
130
+		}
131
+	case "2024":
132
+		if len(value) < 3 {
133
+			return
134
+		}
135
+		//当前软件版本
136
+		banben := fmt.Sprintf("%X", value[0:2])
137
+		fmt.Println("当前软件版本 ", banben)
138
+		//项目名长度
139
+		namelengthx := fmt.Sprintf("%X", value[2])
140
+		namelength, _ := strconv.ParseInt(namelengthx, 16, 64)
141
+		fmt.Println("项目名长度 ", namelength)
142
+		if len(value) < (3 + int(namelength)) {
143
+			return
144
+		}
145
+		projectname := byteToAscii(value[3 : 3+namelength])
146
+		fmt.Println("项目名 ", projectname)
147
+		var version versionmanage.VersionManage
148
+		strUrl := Config.Send.Waterdrop.Service + "/remoteupgrade/newestversion?projecttag=1&projectname=" + projectname + "&versionnum=" + banben + "&mainserial=" + msggatewayid
149
+		json.Unmarshal(Apiget(strUrl), &version)
150
+		strUrl = Config.Send.Waterdrop.Service + "/remoteupgrade/upgradehistory/device?projecttag=1&projectname=" + projectname + "&currversion=" + banben + "&mainserial=" + msggatewayid + "&upversion=" + utils.ToStr(version.VersionNum)
151
+		json.Unmarshal(Apiget(strUrl), nil)
152
+		if version.Id == 0 {
153
+			fmt.Println("无升级数据包")
154
+			return
155
+		}
156
+		var newbanben = version.VersionName
157
+		//var banbenname ="S6_1139"
158
+		bytestr, err := ioutil.ReadFile("/home/wwwroot/zksiotservice/waterdrop/web" + version.FilePath)
159
+		if err != nil {
160
+			fmt.Println("升级文件读取异常", err)
161
+		}
162
+		one, _ := strconv.ParseUint(newbanben[1:3], 16, 0)
163
+		two, _ := strconv.ParseUint(newbanben[3:5], 16, 0)
164
+		message := []byte{byte(one), byte(two)}
165
+		message = append(message, Valuebyte4(len(bytestr))...)
166
+		sendms := []byte{0xA0, 0x08, 0x00, byte(len(message)), command[5], command[6], command[7], command[8], command[9], command[10], command[11], command[12], byte(one), byte(two)}
167
+		sendms = append(sendms, Valuebyte4(len(bytestr))...)
168
+		sendms = append(sendms, yihuo(sendms))
169
+		send := []byte{0x7E}
170
+		for _, v := range sendms {
171
+			if v == 0x7E {
172
+				send = append(send, 0x7D, 0x02)
173
+			} else if v == 0x7D {
174
+				send = append(send, 0x7D, 0x01)
175
+			} else {
176
+				send = append(send, v)
177
+			}
178
+		}
179
+		send = append(send, 0x7E)
180
+		c.WritePacket(NewPacket(3, send))
181
+		var emtity coldcloud.DUpgrade
182
+		coldcloud.UpdateControlDUpgrade("CTL"+msggatewayid, emtity)
183
+	case "2025":
184
+		if len(value) < 7 {
185
+			return
186
+		}
187
+		//当前软件版本
188
+		banben := fmt.Sprintf("%X", value[0:2])
189
+		fmt.Println("升级软件版本 ", banben)
190
+		//分包序号
191
+		fenbaoxuliehaox := fmt.Sprintf("%X", value[2:4])
192
+		fenbaoxuliehaod, _ := strconv.ParseInt(fenbaoxuliehaox, 16, 64)
193
+		fmt.Println("分包序号 ", fenbaoxuliehaod)
194
+		//分包长度
195
+		fenbaoxchangdux := fmt.Sprintf("%X", value[4:6])
196
+		fenbaoxchangdud, _ := strconv.ParseInt(fenbaoxchangdux, 16, 64)
197
+		fmt.Println("分包长度 ", fenbaoxchangdud)
198
+		//项目名长度
199
+		namelengthx := fmt.Sprintf("%X", value[6])
200
+		namelength, _ := strconv.ParseInt(namelengthx, 16, 64)
201
+		fmt.Println("项目名长度 ", namelength)
202
+		if len(value) < (7 + int(namelength)) {
203
+			return
204
+		}
205
+		//项目名
206
+		projectname := byteToAscii(value[7 : 7+namelength])
207
+		fmt.Println("项目名 ", projectname)
208
+		var version versionmanage.VersionManage
209
+		strUrl := Config.Send.Waterdrop.Service + "/remoteupgrade/versiondetail?projecttag=1&projectname=" + projectname + "&versionnum=" + banben
210
+		json.Unmarshal(Apiget(strUrl), &version)
211
+		if version.Id == 0 {
212
+			fmt.Println("无升级数据包")
213
+			return
214
+		}
215
+		bytestr, err := ioutil.ReadFile("/home/wwwroot/zksiotservice/waterdrop/web" + version.FilePath)
216
+		if err != nil {
217
+			fmt.Println("升级文件读取异常", err)
218
+		}
219
+		databyte := []byte{}
220
+		if (int(fenbaoxuliehaod)+1)*int(fenbaoxchangdud) > len(bytestr) {
221
+			databyte = bytestr[fenbaoxuliehaod*fenbaoxchangdud:]
222
+		} else {
223
+			databyte = bytestr[fenbaoxuliehaod*fenbaoxchangdud : (int(fenbaoxuliehaod)+1)*int(fenbaoxchangdud)]
224
+		}
225
+		fmt.Println(databyte)
226
+		message := []byte{}
227
+		message = append(message, value[0:4]...)
228
+		message = append(message, Valuebyte2(len(databyte))...)
229
+		message = append(message, databyte...)
230
+		sendms := []byte{0xA0, 0x09}
231
+		sendms = append(sendms, Valuebyte2(len(message))...)
232
+		sendms = append(sendms, []byte{command[5], command[6], command[7], command[8], command[9], command[10], command[11], command[12]}...)
233
+		sendms = append(sendms, message...)
234
+		sendms = append(sendms, yihuo(sendms))
235
+		send := []byte{0x7E}
236
+		for _, v := range sendms {
237
+			if v == 0x7E {
238
+				send = append(send, 0x7D, 0x02)
239
+			} else if v == 0x7D {
240
+				send = append(send, 0x7D, 0x01)
241
+			} else {
242
+				send = append(send, v)
243
+			}
244
+		}
245
+		send = append(send, 0x7E)
246
+		c.WritePacket(NewPacket(3, send))
247
+	}
248
+	return
249
+}
250
+
251
+//S6多探头循环写入
252
+func S6ForWriter(sjnewcom []byte) (temp []byte) {
253
+	for {
254
+		//数据项列表长度
255
+		sjlength := len(sjnewcom)
256
+		if sjlength < 2 {
257
+			sjnewcom = []byte{}
258
+			break
259
+		}
260
+		//获取端口编号
261
+		portnumx := fmt.Sprintf("%X", sjnewcom[0])
262
+		portnumint64, _ := strconv.ParseInt(portnumx, 16, 32)
263
+		portnumint := int(portnumint64)
264
+		if portnumint == 255 {
265
+			sjnewcom = sjnewcom[1:]
266
+			break
267
+		}
268
+		//获取数据类型
269
+		datatypestr := fmt.Sprintf("%X", sjnewcom[1])
270
+		datatype, _ := strconv.ParseInt(datatypestr, 16, 32)
271
+		if datatype == 1 {
272
+			if len(sjnewcom[2:]) < 4 {
273
+				sjnewcom = sjnewcom[2:]
274
+				break
275
+			}
276
+			sjnewcom = sjnewcom[6:]
277
+		} else if datatype == 2 {
278
+			if len(sjnewcom[2:]) < 2 {
279
+				sjnewcom = sjnewcom[2:]
280
+				break
281
+			}
282
+			sjnewcom = sjnewcom[4:]
283
+		} else if datatype == 3 {
284
+			if len(sjnewcom[2:]) < 4 {
285
+				sjnewcom = sjnewcom[2:]
286
+				break
287
+			}
288
+			sjnewcom = sjnewcom[6:]
289
+		} else if datatype == 4 {
290
+			if len(sjnewcom[2:]) < 3 {
291
+				sjnewcom = sjnewcom[2:]
292
+				break
293
+			}
294
+			sjnewcom = sjnewcom[5:]
295
+		} else if datatype == 5 { //压力传感器
296
+			if len(sjnewcom[2:]) < 4 {
297
+				sjnewcom = sjnewcom[2:]
298
+				break
299
+			}
300
+			sjnewcom = sjnewcom[6:]
301
+		} else if datatype == 10 {
302
+			if len(sjnewcom[2:]) < 4 {
303
+				sjnewcom = sjnewcom[2:]
304
+				break
305
+			}
306
+			sjnewcom = sjnewcom[6:]
307
+		} else if datatype == 11 {
308
+			if len(sjnewcom[2:]) < 16 {
309
+				sjnewcom = sjnewcom[2:]
310
+				break
311
+			}
312
+			sjnewcom = sjnewcom[18:]
313
+		} else if datatype == 12 {
314
+			if len(sjnewcom[2:]) < 1 {
315
+				sjnewcom = sjnewcom[2:]
316
+				break
317
+			}
318
+			sjnewcom = sjnewcom[3:]
319
+		} else if datatype == 13 {
320
+			if len(sjnewcom[2:]) < 1 {
321
+				sjnewcom = sjnewcom[2:]
322
+				break
323
+			}
324
+			sjnewcom = sjnewcom[2:]
325
+		} else if datatype == 254 {
326
+
327
+			if len(sjnewcom[2:]) < 6 {
328
+				sjnewcom = sjnewcom[2:]
329
+				break
330
+			}
331
+			sjnewcom = sjnewcom[8:]
332
+		} else {
333
+			fmt.Println("不定项的除了STH20和NTC其他类型", datatype)
334
+			sjnewcom = []byte{}
335
+			break
336
+		}
337
+	}
338
+	return sjnewcom
339
+}
340
+
341
+//设置参数
342
+func DParamSensorSet(c *gotcp.Conn, sensor, msggatewayid string) {
343
+	paramset, _ := coldcloud.GetReverseControlDParam("CTL" + sensor)
344
+	if paramset.Id != 0 && len(sensor) >= 8 {
345
+		head := []byte{0xA0, 0x02, 0x00}
346
+		sendms := []byte{}
347
+		sensormac1, _ := strconv.ParseInt(sensor[0:2], 16, 64)
348
+		sensormac2, _ := strconv.ParseInt(sensor[2:4], 16, 64)
349
+		sensormac3, _ := strconv.ParseInt(sensor[4:6], 16, 64)
350
+		sensormac4, _ := strconv.ParseInt(sensor[6:8], 16, 64)
351
+		sendms = append(sendms, 0x00, byte(sensormac1), byte(sensormac2), byte(sensormac3), byte(sensormac4))
352
+		for _, v := range paramset.SetValue {
353
+			if time.Now().Unix()-v.CreateOn.Unix() > (60 * 120) {
354
+				break
355
+			}
356
+			switch v.Dtype {
357
+			case 1:
358
+				zksint, _ := utils.StrTo(v.Value).Int()
359
+				sendms = append(sendms, byte(v.Dtype))
360
+				sendms = append(sendms, Valuebyte4(zksint)...)
361
+			case 2:
362
+				zksint, _ := utils.StrTo(v.Value).Int()
363
+				sendms = append(sendms, byte(v.Dtype))
364
+				fmt.Println(fmt.Sprintf("% X", sendms))
365
+				sendms = append(sendms, Valuebyte4(zksint)...)
366
+			case 3:
367
+				zksfloat, _ := utils.StrTo(v.Value).Float32()
368
+				zksint := int(zksfloat * 100)
369
+				sendms = append(sendms, byte(v.Dtype))
370
+				sendms = append(sendms, byte(v.Port))
371
+				if zksint >= 0 {
372
+					sendms = append(sendms, Valuebyte2(zksint)...)
373
+				} else {
374
+					sendms = append(sendms, Bumatobyte2(zksint)...)
375
+				}
376
+			case 4:
377
+				zksfloat, _ := utils.StrTo(v.Value).Float32()
378
+				zksint := int(zksfloat * 100)
379
+				sendms = append(sendms, byte(v.Dtype))
380
+				sendms = append(sendms, byte(v.Port))
381
+				if zksint >= 0 {
382
+					sendms = append(sendms, Valuebyte2(zksint)...)
383
+				} else {
384
+					sendms = append(sendms, Bumatobyte2(zksint)...)
385
+				}
386
+			case 11:
387
+				name := []byte(CodertoGBK(utils.Substr(v.Value, 0, 10)))
388
+				sendms = append(sendms, byte(v.Dtype))
389
+				sendms = append(sendms, byte(len(name)))
390
+				sendms = append(sendms, name...)
391
+			case 27:
392
+				zksfloat, _ := utils.StrTo(v.Value).Float32()
393
+				zksint := int(zksfloat * 100)
394
+				sendms = append(sendms, byte(v.Dtype))
395
+				sendms = append(sendms, byte(v.Port))
396
+				if zksint >= 0 {
397
+					sendms = append(sendms, Valuebyte2(zksint)...)
398
+				} else {
399
+					sendms = append(sendms, Bumatobyte2(zksint)...)
400
+				}
401
+			case 28: //湿度校正
402
+				zksfloat, _ := utils.StrTo(v.Value).Float32()
403
+				zksint := int(zksfloat * 100)
404
+				sendms = append(sendms, byte(v.Dtype))
405
+				sendms = append(sendms, byte(v.Port))
406
+				if zksint >= 0 {
407
+					sendms = append(sendms, Valuebyte2(zksint)...)
408
+				} else {
409
+					sendms = append(sendms, Bumatobyte2(zksint)...)
410
+				}
411
+			}
412
+		}
413
+		if len(sendms) == 0 {
414
+			//Apipost(Config.Send.Waterdrop.Service+"/dparamset/setv2?mainserial="+sensor+"&num="+utils.ToStr(paramset.ControlNum)+"&state=2", "POST", nil)
415
+			var dparamset coldcloud.DParamSet
416
+			coldcloud.UpdateCTLDParamSet("CTL"+sensor, dparamset)
417
+		} else {
418
+			mac1, _ := strconv.ParseInt(msggatewayid[0:2], 16, 64)
419
+			mac2, _ := strconv.ParseInt(msggatewayid[2:4], 16, 64)
420
+			mac3, _ := strconv.ParseInt(msggatewayid[4:6], 16, 64)
421
+			mac4, _ := strconv.ParseInt(msggatewayid[6:8], 16, 64)
422
+			head = append(head, byte(len(sendms)), byte(mac1), byte(mac2), byte(mac3), byte(mac4), 0x00, 0x00)
423
+			head = append(head, Valuebyte2(paramset.ControlNum)...)
424
+			sendms = append(head, sendms...)
425
+			sendms = append(sendms, yihuo(sendms))
426
+			send := []byte{0x7E}
427
+			for _, v := range sendms {
428
+				if v == 0x7E {
429
+					send = append(send, 0x7D, 0x02)
430
+				} else if v == 0x7D {
431
+					send = append(send, 0x7D, 0x01)
432
+				} else {
433
+					send = append(send, v)
434
+				}
435
+			}
436
+			send = append(send, 0x7E)
437
+			fmt.Println("反向控制命令", fmt.Sprintf("% X", send))
438
+			c.WritePacket(NewPacket(3, send))
439
+		}
440
+	}
441
+}
442
+func byteToAscii(signalList []byte) (str string) {
443
+	for i := 0; i < len(signalList); i++ {
444
+		if signalList[i] != 0x00 {
445
+			str += string(signalList[i])
446
+		}
447
+	}
448
+	return str
449
+}
450
+func yihuo(signalList []byte) byte {
451
+	var xor byte
452
+	xor = signalList[0]
453
+	for i := 1; i < len(signalList); i++ {
454
+		xor ^= signalList[i]
455
+	}
456
+	return xor
457
+}
458
+
459
+//把16进制转换为二进制字符串
460
+func ByteToBinaryString(data byte) (str string) {
461
+	var a byte
462
+	for i := 0; i < 8; i++ {
463
+		a = data
464
+		data <<= 1
465
+		data >>= 1
466
+		switch a {
467
+		case data:
468
+			str += "0"
469
+		default:
470
+			str += "1"
471
+		}
472
+		data <<= 1
473
+	}
474
+	return str
475
+}
476
+
477
+//把一个字节的二进制字符串转换为十进制数字
478
+func btox(b string) string {
479
+	base, _ := strconv.ParseInt(b, 2, 12)
480
+
481
+	return strconv.FormatInt(base, 10)
482
+}
483
+
484
+//把一个字节的二进制字符串转换为十六进制数字
485
+func btox16(b string) string {
486
+	base, _ := strconv.ParseInt(b, 2, 12)
487
+
488
+	return strconv.FormatInt(base, 16)
489
+}
490
+func Substr(str string, start int, length int) string {
491
+	rs := []rune(str)
492
+	rl := len(rs)
493
+	end := 0
494
+
495
+	if start < 0 {
496
+		start = rl - 1 + start
497
+	}
498
+	end = start + length
499
+
500
+	if start > end {
501
+		start, end = end, start
502
+	}
503
+
504
+	if start < 0 {
505
+		start = 0
506
+	}
507
+	if start > rl {
508
+		start = rl
509
+	}
510
+	if end < 0 {
511
+		end = 0
512
+	}
513
+	if end > rl {
514
+		end = rl
515
+	}
516
+
517
+	return string(rs[start:end])
518
+}
519
+
520
+//数值转为2个字节
521
+func Valuebyte2(v int) []byte {
522
+	value := make([]byte, 2)
523
+	value[0] = byte(v >> 8 & 0xff)
524
+	value[1] = byte(v & 0xff)
525
+	return value
526
+}
527
+
528
+//数值转为4个字节
529
+func Valuebyte4(v int) []byte {
530
+	value := make([]byte, 4)
531
+	value[0] = byte(v >> 24 & 0xff)
532
+	value[1] = byte(v >> 16 & 0xff)
533
+	value[2] = byte(v >> 8 & 0xff)
534
+	value[3] = byte(v & 0xff)
535
+	return value
536
+}
537
+
538
+//2个字节的补码
539
+func Bumatobyte2(v int) []byte {
540
+	value := make([]byte, 2)
541
+	if v < 0 {
542
+		v = 65535 + 1 + v
543
+	}
544
+	value[0] = byte(v >> 8 & 0xff)
545
+	value[1] = byte(v & 0xff)
546
+	return value
547
+}
548
+
549
+//4个字节的补码
550
+func Bumabyte4(v int64) []byte {
551
+	value := make([]byte, 4)
552
+	if v < 0 {
553
+		v = 4294967295 + 1 + v
554
+	}
555
+	value[0] = byte(v >> 24 & 0xff)
556
+	value[1] = byte(v >> 16 & 0xff)
557
+	value[2] = byte(v >> 8 & 0xff)
558
+	value[3] = byte(v & 0xff)
559
+	return value
560
+}
561
+func Apipost(strUrl, method string, postDict interface{}) (body []byte) {
562
+	strUrl = strings.Replace(strUrl, " ", "%20", -1)
563
+	httpClient := &http.Client{
564
+		//Transport:nil,
565
+		//CheckRedirect: nil,
566
+	}
567
+
568
+	var httpReq *http.Request
569
+
570
+	b, _ := json.Marshal(postDict)
571
+	postBytesReader := bytes.NewReader(b)
572
+	httpReq, _ = http.NewRequest(method, strUrl, postBytesReader)
573
+	httpReq.Header.Add("Content-Type", "application/json")
574
+	response, _ := httpClient.Do(httpReq)
575
+	body, _ = ioutil.ReadAll(response.Body)
576
+	return
577
+}
578
+func Apiget(str string) (body []byte) {
579
+	str = strings.Replace(str, " ", "%20", -1)
580
+	response, _ := http.Get(str)
581
+	if response != nil {
582
+		defer response.Body.Close()
583
+		body, _ = ioutil.ReadAll(response.Body)
584
+	}
585
+	//json.Unmarshal(body, &devices)
586
+	return
587
+}
588
+func CodertoGBK(str string) string {
589
+	dec := mahonia.NewDecoder("UTF-8")
590
+	enc := mahonia.NewEncoder("GBK")
591
+	return enc.ConvertString(dec.ConvertString(str))
592
+}
593
+
594
+//发送给设备并且打印日志
595
+func WritePacketAndLog(c *gotcp.Conn, message []byte, sendtime int64) {
596
+	responseError := c.WritePacket(NewPacket(3, message))
597
+	fmt.Println("反向控制[UsedTime]", time.Now().Unix()-sendtime, "[Msg]", fmt.Sprintf("%X", message))
598
+	if responseError != nil {
599
+		fmt.Println("[ResponseError]", responseError)
600
+	}
601
+}

+ 50 - 0
src/zks.com/newbbfrontsocketv2/blackbox/conf.go

@@ -0,0 +1,50 @@
1
+package blackbox
2
+
3
+import (
4
+	"io/ioutil"
5
+	"os"
6
+
7
+	"github.com/naoina/toml"
8
+)
9
+
10
+type AppConfig struct {
11
+	Send struct {
12
+		Redis struct {
13
+			Addr    string
14
+			Poolnum int
15
+			Pwd     string
16
+		}
17
+		Nsq struct {
18
+			Nsqdtcpaddr string
19
+			Topic       string
20
+		}
21
+		Nsqrequest struct {
22
+			Nsqdtcpaddr string
23
+			Topic       string
24
+		}
25
+		Waterdrop struct {
26
+			Service string
27
+		}
28
+	}
29
+	Service struct {
30
+		Ipandport string
31
+	}
32
+}
33
+
34
+var Config AppConfig
35
+
36
+func ReadAppConfig(path string) (config AppConfig) {
37
+	f, err := os.Open(path)
38
+	if err != nil {
39
+		panic(err)
40
+	}
41
+	defer f.Close()
42
+	buf, err := ioutil.ReadAll(f)
43
+	if err != nil {
44
+		panic(err)
45
+	}
46
+	if err := toml.Unmarshal(buf, &config); err != nil {
47
+		panic(err)
48
+	}
49
+	return
50
+}

+ 586 - 0
src/zks.com/newbbfrontsocketv2/blackbox/dataserver.go

@@ -0,0 +1,586 @@
1
+/*更新记录
2
+20-5-7-23 zh 增加深低温校准(温度在-195到-190之间时 将温度改为 196)
3
+20-5-9-8 zh 增加深低温校准(温度小于-197时 将温度改为 196 小数点后为随机数)
4
+20-5-10-13 zh 修改校准规则,存储前一条数据到缓存boltdb中
5
+*/
6
+
7
+package blackbox
8
+
9
+import (
10
+	"fmt"
11
+	"strconv"
12
+	"sync"
13
+	"time"
14
+
15
+	"encoding/json"
16
+
17
+	"zks.com/gotcp"
18
+	zksutils "zks.com/zUtils"
19
+	coldcloud "zks.com/zcoldcloud"
20
+)
21
+
22
+var format string = "2006-1-2 15:4:5"
23
+var Conns = struct {
24
+	sync.RWMutex
25
+	m map[string]*gotcp.Conn
26
+}{m: make(map[string]*gotcp.Conn)}
27
+var Conns2004 = struct {
28
+	sync.RWMutex
29
+	m map[string]Status2004
30
+}{m: make(map[string]Status2004)}
31
+
32
+type Status2004 struct {
33
+	Time  int64
34
+	Count int64
35
+}
36
+type Status struct {
37
+	Status  int    `json:"status"`
38
+	Id      string `json:"id"`
39
+	Message string `json:"message"`
40
+}
41
+
42
+func DoWork(c *gotcp.Conn, command []byte) error {
43
+	fmt.Println("DoWork", time.Now(), fmt.Sprintf("%X", command))
44
+	defer func() {
45
+		if r := recover(); r != nil {
46
+			fmt.Println("Recovered in f", r)
47
+		}
48
+	}()
49
+	if 0x7E != command[0] || 0x7E != command[len(command)-1] {
50
+		if 0x8E == command[0] && 0x8E == command[len(command)-1] {
51
+			go ControlDevice(c, command)
52
+		}
53
+	} else {
54
+		//创建新的byte数组
55
+		newcom := make([]byte, 0)
56
+		//循环便利原数组,去掉首尾的0x7E,把数据中的0x7D 0x01转义为0x7D,0x7D 0x02转义为0x7E
57
+		for i := 1; i < len(command)-1; i++ {
58
+
59
+			if command[i] == 0x7D && command[i+1] == 0x01 {
60
+				newcom = append(newcom, 0x7D)
61
+				i++
62
+			} else if command[i] == 0x7D && command[i+1] == 0x02 {
63
+				newcom = append(newcom, 0x7E)
64
+				i++
65
+			} else {
66
+				newcom = append(newcom, command[i])
67
+			}
68
+		}
69
+		if len(newcom) >= 13 {
70
+			bytejh := yihuo(newcom[0 : len(newcom)-1])
71
+			//fmt.Println("校验码: ", bytejh)
72
+			//fmt.Println("原校验码: ", newcom[len(newcom)-1])
73
+			//消息ID
74
+			msgid := fmt.Sprintf("%X", newcom[0:2])
75
+			//fmt.Println("消息ID ", msgid)
76
+			//消息体属性
77
+			msgattr := newcom[2:4]
78
+			str := ByteToBinaryString(msgattr[0])
79
+			str1 := ByteToBinaryString(msgattr[1])
80
+			//消息体长度
81
+			msglength := btox(Substr(str+str1, len(str+str1)-11, 11))
82
+			//fmt.Println("标记消息体长度 ", msglength)
83
+			//实际消息体长度
84
+			msgsjcd := len(newcom[12:]) - 1
85
+			msglengthint, _ := strconv.Atoi(msglength)
86
+			//fmt.Println("实际消息体长度 ", msgsjcd)
87
+			//网关ID
88
+			msggatewayid := fmt.Sprintf("%X", newcom[4:8])
89
+			fmt.Println("网关ID ", msggatewayid)
90
+			coldcloud.UpdateBoxIpAndPort(msggatewayid, coldcloud.IpAndPortStruct{Config.Service.Ipandport, time.Now()})
91
+			//UUID
92
+			//msguuid := fmt.Sprintf("%X", newcom[8:10])
93
+			//fmt.Println("msguuid  ", msguuid) //msguuid
94
+			//消息流水号
95
+			msgliusidx := fmt.Sprintf("%X", newcom[10:12])
96
+			msgliusid, _ := strconv.ParseInt(msgliusidx, 16, 64)
97
+			//fmt.Println("消息流水号 ", msgliusid)
98
+			//消息包总数
99
+			//var msgtotal int64
100
+			//fmt.Println(msgtotal) //msgtotal
101
+			//消息包序号
102
+			//var msgnum int64
103
+			//fmt.Println(msgnum) //msgnum
104
+			if bytejh == newcom[len(newcom)-1] && msglengthint == msgsjcd {
105
+				//A029下发报警给报警器
106
+				if msgid != "A029" {
107
+					Conns.Lock()
108
+					Conns.m[msggatewayid] = c
109
+					Conns.Unlock()
110
+				}
111
+				switch msgid {
112
+				case "2004", "2024", "2025", "2010", "2011":
113
+					var datacom []byte
114
+					datacom = newcom[12 : 12+msgsjcd]
115
+					fmt.Println(fmt.Sprintf("% X", datacom))
116
+					GetChannelValue(c, datacom, command, msgid, msggatewayid, msgliusid)
117
+				case "A029":
118
+					Conns.Lock()
119
+					if v, ok := Conns.m[msggatewayid]; ok {
120
+						fmt.Println("A029发送", fmt.Sprintf("%X", command))
121
+						go v.WritePacket(NewPacket(3, command))
122
+					}
123
+					Conns.Unlock()
124
+				}
125
+				DParamSet(c, msggatewayid)
126
+				ShutdownOrBoot(c, msggatewayid)
127
+			}
128
+		}
129
+		Writedata_v2(fmt.Sprintf("% X", command))
130
+	}
131
+	return nil
132
+}
133
+
134
+//设置参数
135
+func DParamSet(c *gotcp.Conn, msggatewayid string) {
136
+	paramset, _ := coldcloud.GetReverseControlDParam("CTL" + msggatewayid)
137
+	if paramset.Id != 0 && len(msggatewayid) >= 8 {
138
+		head := []byte{0xA0, 0x02, 0x00}
139
+		sendms := []byte{}
140
+		for _, v := range paramset.SetValue {
141
+			if time.Now().Unix()-v.CreateOn.Unix() > (60 * 30) {
142
+				sendms = []byte{}
143
+				break
144
+			}
145
+			switch v.Dtype {
146
+			case 1:
147
+				zksint, _ := zksutils.StrTo(v.Value).Int()
148
+				sendms = append(sendms, byte(v.Dtype))
149
+				sendms = append(sendms, Valuebyte4(zksint)...)
150
+			case 2:
151
+				zksint, _ := zksutils.StrTo(v.Value).Int()
152
+				sendms = append(sendms, byte(v.Dtype))
153
+				fmt.Println(fmt.Sprintf("% X", sendms))
154
+				sendms = append(sendms, Valuebyte4(zksint)...)
155
+			case 3:
156
+				zksfloat, _ := zksutils.StrTo(v.Value).Float32()
157
+				zksint := int(zksfloat * 100)
158
+				sendms = append(sendms, byte(v.Dtype))
159
+				sendms = append(sendms, byte(v.Port))
160
+				if zksint >= 0 {
161
+					sendms = append(sendms, Valuebyte2(zksint)...)
162
+				} else {
163
+					sendms = append(sendms, Bumatobyte2(zksint)...)
164
+				}
165
+			case 4:
166
+				zksfloat, _ := zksutils.StrTo(v.Value).Float32()
167
+				zksint := int(zksfloat * 100)
168
+				sendms = append(sendms, byte(v.Dtype))
169
+				sendms = append(sendms, byte(v.Port))
170
+				if zksint >= 0 {
171
+					sendms = append(sendms, Valuebyte2(zksint)...)
172
+				} else {
173
+					sendms = append(sendms, Bumatobyte2(zksint)...)
174
+				}
175
+			case 11:
176
+				name := []byte(CodertoGBK(zksutils.Substr(v.Value, 0, 10)))
177
+				sendms = append(sendms, byte(v.Dtype))
178
+				sendms = append(sendms, byte(len(name)))
179
+				sendms = append(sendms, name...)
180
+			case 27:
181
+				zksfloat, _ := zksutils.StrTo(v.Value).Float32()
182
+				zksint := int(zksfloat * 100)
183
+				sendms = append(sendms, byte(v.Dtype))
184
+				sendms = append(sendms, byte(v.Port))
185
+				if zksint >= 0 {
186
+					sendms = append(sendms, Valuebyte2(zksint)...)
187
+				} else {
188
+					sendms = append(sendms, Bumatobyte2(zksint)...)
189
+				}
190
+			case 28: //湿度校正
191
+				zksfloat, _ := zksutils.StrTo(v.Value).Float32()
192
+				zksint := int(zksfloat * 100)
193
+				sendms = append(sendms, byte(v.Dtype))
194
+				sendms = append(sendms, byte(v.Port))
195
+				if zksint >= 0 {
196
+					sendms = append(sendms, Valuebyte2(zksint)...)
197
+				} else {
198
+					sendms = append(sendms, Bumatobyte2(zksint)...)
199
+				}
200
+			}
201
+		}
202
+		if len(sendms) == 0 {
203
+			//Apipost(Config.Send.Waterdrop.Service+"/dparamset/setv2?mainserial="+msggatewayid+"&num="+zksutils.ToStr(paramset.ControlNum)+"&state=2", "POST", nil)
204
+			var dparamset coldcloud.DParamSet
205
+			coldcloud.UpdateCTLDParamSet("CTL"+msggatewayid, dparamset)
206
+		} else {
207
+			mac1, _ := strconv.ParseInt(msggatewayid[0:2], 16, 64)
208
+			mac2, _ := strconv.ParseInt(msggatewayid[2:4], 16, 64)
209
+			mac3, _ := strconv.ParseInt(msggatewayid[4:6], 16, 64)
210
+			mac4, _ := strconv.ParseInt(msggatewayid[6:8], 16, 64)
211
+			//		ctlnum, _ := coldcloud.GetReverseControlCtlSNum("CTL" + msggatewayid)
212
+			//		numint, _ := zksutils.StrTo(ctlnum).Int()
213
+			head = append(head, byte(len(sendms)), byte(mac1), byte(mac2), byte(mac3), byte(mac4), 0x00, 0x00)
214
+			head = append(head, Valuebyte2(paramset.ControlNum)...)
215
+			sendms = append(head, sendms...)
216
+			sendms = append(sendms, yihuo(sendms))
217
+			send := []byte{0x7E}
218
+			for _, v := range sendms {
219
+				if v == 0x7E {
220
+					send = append(send, 0x7D, 0x02)
221
+				} else if v == 0x7D {
222
+					send = append(send, 0x7D, 0x01)
223
+				} else {
224
+					send = append(send, v)
225
+				}
226
+			}
227
+			send = append(send, 0x7E)
228
+			fmt.Println("反向控制命令", fmt.Sprintf("% X", send))
229
+			c.WritePacket(NewPacket(3, send))
230
+		}
231
+	}
232
+	//设置飞行模式
233
+	lightset, _ := coldcloud.GetReverseControlSetLight("CTL" + msggatewayid)
234
+	if lightset.SetType == 1 && len(msggatewayid) >= 8 && lightset.RequestState == 0 {
235
+		if time.Now().Unix() > (lightset.OccurTime.Unix() - 120) {
236
+			var status Status
237
+			if time.Now().Unix() < lightset.CloseTime.Unix() || lightset.RemainMin == 0 {
238
+				head := []byte{0xA0, 0x0B, 0x00}
239
+				sendms := []byte{}
240
+				mac1, _ := strconv.ParseInt(msggatewayid[0:2], 16, 64)
241
+				mac2, _ := strconv.ParseInt(msggatewayid[2:4], 16, 64)
242
+				mac3, _ := strconv.ParseInt(msggatewayid[4:6], 16, 64)
243
+				mac4, _ := strconv.ParseInt(msggatewayid[6:8], 16, 64)
244
+				head = append(head, 0x02, byte(mac1), byte(mac2), byte(mac3), byte(mac4), 0x00, 0x00)
245
+				head = append(head, Valuebyte2(lightset.ControlNumber)...)
246
+				sendms = append(sendms, Valuebyte2(lightset.RemainMin)...)
247
+				sendms = append(head, sendms...)
248
+				sendms = append(sendms, yihuo(sendms))
249
+				send := []byte{0x7E}
250
+				for _, v := range sendms {
251
+					if v == 0x7E {
252
+						send = append(send, 0x7D, 0x02)
253
+					} else if v == 0x7D {
254
+						send = append(send, 0x7D, 0x01)
255
+					} else {
256
+						send = append(send, v)
257
+					}
258
+				}
259
+				send = append(send, 0x7E)
260
+				fmt.Println("设置飞行模式", fmt.Sprintf("% X", send))
261
+				c.WritePacket(NewPacket(3, send))
262
+				json.Unmarshal(Apipost(Config.Send.Waterdrop.Service+"/devicestate/state?mainserial="+msggatewayid+"&controlnumber="+zksutils.ToStr(lightset.ControlNumber)+"&settype=1&requeststate=1&requesttime="+time.Now().Format("2006-01-02 15:04:05"), "PUT", nil), &status)
263
+				if status.Status == 1 {
264
+					lightset.RequestState = 1
265
+					lightset.OccurTime = time.Now()
266
+					coldcloud.UpdateCtlSetLight("CTL"+msggatewayid, lightset)
267
+				}
268
+			} else {
269
+				json.Unmarshal(Apipost(Config.Send.Waterdrop.Service+"/devicestate/state?mainserial="+msggatewayid+"&controlnumber="+zksutils.ToStr(lightset.ControlNumber)+"&settype=1&requeststate=4&requesttime="+time.Now().Format("2006-01-02 15:04:05"), "PUT", nil), &status)
270
+				if status.Status == 1 {
271
+					lightset.RequestState = 4
272
+					lightset.OccurTime = time.Now()
273
+					coldcloud.UpdateCtlSetLight("CTL"+msggatewayid, lightset)
274
+				}
275
+			}
276
+
277
+		}
278
+	}
279
+	//远程升级
280
+	dupgrade, err := coldcloud.GetReverseControlDUpgrade("CTL" + msggatewayid)
281
+	if err == nil && len(dupgrade.Data) > 0 {
282
+		if time.Now().Unix()-dupgrade.Time < 1800 {
283
+			mac1, _ := strconv.ParseInt(msggatewayid[0:2], 16, 64)
284
+			mac2, _ := strconv.ParseInt(msggatewayid[2:4], 16, 64)
285
+			mac3, _ := strconv.ParseInt(msggatewayid[4:6], 16, 64)
286
+			mac4, _ := strconv.ParseInt(msggatewayid[6:8], 16, 64)
287
+			sendms := []byte{0xA0, 0x0A, 0x00, 0x00, byte(mac1), byte(mac2), byte(mac3), byte(mac4), 0x00, 0x00, 0x00, 0x00}
288
+			sendms = append(sendms, yihuo(sendms))
289
+			send := []byte{0x7E}
290
+			for _, v := range sendms {
291
+				if v == 0x7E {
292
+					send = append(send, 0x7D, 0x02)
293
+				} else if v == 0x7D {
294
+					send = append(send, 0x7D, 0x01)
295
+				} else {
296
+					send = append(send, v)
297
+				}
298
+			}
299
+			send = append(send, 0x7E)
300
+			err := c.WritePacket(NewPacket(3, send))
301
+			fmt.Println(err, "缓存远程升级", fmt.Sprintf("% X", send))
302
+		}
303
+	}
304
+}
305
+
306
+//平台发送多条同一推送报警信息(暂时不用)
307
+func ServiceToTriggerMsg(c *gotcp.Conn, msggatewayid string) {
308
+	cachevalue, err := coldcloud.GetReverseControlTriggerMac("CTL" + msggatewayid)
309
+	//cachevalue, err := coldcloud.GetTriggerMac("TMac" + msggatewayid)
310
+	if err == nil && len(cachevalue.TriggerMac) > 0 {
311
+		fmt.Println("平台发送报警信息")
312
+		var data []byte
313
+		for _, v := range cachevalue.TriggerMac {
314
+			mac1, _ := strconv.ParseInt(v.MainMac[0:2], 16, 64)
315
+			mac2, _ := strconv.ParseInt(v.MainMac[2:4], 16, 64)
316
+			mac3, _ := strconv.ParseInt(v.MainMac[4:6], 16, 64)
317
+			mac4, _ := strconv.ParseInt(v.MainMac[6:8], 16, 64)
318
+			port, _ := strconv.ParseUint(v.Port, 16, 64)
319
+			lastdata, err1 := coldcloud.GetTriggerHistoryLast("trigger_c" + v.Mac)
320
+			macdata := []byte{}
321
+			if err1 == nil {
322
+				for _, v1 := range lastdata {
323
+					if v1.IsSend == 2 && v1.ActionType == "alertor" && v1.SendTo == msggatewayid {
324
+						if v1.EventFiled == "temperature" {
325
+							macdata = []byte{byte(mac1), byte(mac2), byte(mac3), byte(mac4), byte(port), byte(1)}
326
+							macdata = append(macdata, Bumabyte4(int64(v1.Value*100))...)
327
+						} else if v1.EventFiled == "humidity" {
328
+							macdata = []byte{byte(mac1), byte(mac2), byte(mac3), byte(mac4), byte(port), byte(2)}
329
+							macdata = append(macdata, Bumabyte4(int64(v1.Value*100))...)
330
+						}
331
+					}
332
+				}
333
+			}
334
+			if len(macdata) > 0 {
335
+				data = append(data, macdata...)
336
+			}
337
+		}
338
+		var sendms []byte
339
+		if len(data) > 0 && len(data) < 100 {
340
+			mac1, _ := strconv.ParseInt(msggatewayid[0:2], 16, 64)
341
+			mac2, _ := strconv.ParseInt(msggatewayid[2:4], 16, 64)
342
+			mac3, _ := strconv.ParseInt(msggatewayid[4:6], 16, 64)
343
+			mac4, _ := strconv.ParseInt(msggatewayid[6:8], 16, 64)
344
+			ctlnum, _ := coldcloud.GetReverseControlCtlSNum("CTL" + msggatewayid)
345
+			numint, _ := zksutils.StrTo(ctlnum).Int()
346
+			sendms = []byte{0xA0, 0x03, 0x00, byte(len(data)), byte(mac1), byte(mac2), byte(mac3), byte(mac4), 0x00, 0x00}
347
+			sendms = append(sendms, Valuebyte2(numint)...)
348
+			sendms = append(sendms, data...)
349
+			sendms = append(sendms, yihuo(sendms))
350
+			send := []byte{0x7E}
351
+			for _, v := range sendms {
352
+				if v == 0x7E {
353
+					send = append(send, 0x7D, 0x02)
354
+				} else if v == 0x7D {
355
+					send = append(send, 0x7D, 0x01)
356
+				} else {
357
+					send = append(send, v)
358
+				}
359
+			}
360
+			send = append(send, 0x7E)
361
+			fmt.Println("平台发送报警信息", fmt.Sprintf("% X", send))
362
+			c.WritePacket(NewPacket(3, send))
363
+		}
364
+	}
365
+}
366
+
367
+//平台推送单条报警信息
368
+func ServiceToTriggerSingleMsg(c *gotcp.Conn, msggatewayid string) {
369
+	cachevalue, err := coldcloud.GetReverseControlTriggerMac("CTL" + msggatewayid)
370
+	if err == nil && len(cachevalue.TriggerMac) > 0 {
371
+		fmt.Println("平台发送报警信息", len(cachevalue.TriggerMac))
372
+		for _, v := range cachevalue.TriggerMac {
373
+			if len(v.MainMac) >= 8 && len(msggatewayid) >= 8 {
374
+				mac1, _ := strconv.ParseInt(v.MainMac[0:2], 16, 64)
375
+				mac2, _ := strconv.ParseInt(v.MainMac[2:4], 16, 64)
376
+				mac3, _ := strconv.ParseInt(v.MainMac[4:6], 16, 64)
377
+				mac4, _ := strconv.ParseInt(v.MainMac[6:8], 16, 64)
378
+				port, _ := strconv.ParseUint(v.Port, 16, 64)
379
+				lastdata, err1 := coldcloud.GetTriggerHistoryLast("trigger_c" + v.Mac)
380
+				if err1 == nil {
381
+					for _, v1 := range lastdata {
382
+						if v1.IsSend == 2 && v1.ActionType == "alertor" && v1.SendTo == msggatewayid {
383
+							macdata := []byte{}
384
+							if v1.EventFiled == "temperature" {
385
+								macdata = []byte{byte(mac1), byte(mac2), byte(mac3), byte(mac4), byte(port), byte(1)}
386
+								macdata = append(macdata, Bumabyte4(int64(v1.Value*100))...)
387
+								t := v1.AlarmOn.Format("20060102150405")
388
+								uyear, _ := strconv.ParseUint(t[2:4], 16, 0)
389
+								umonth, _ := strconv.ParseUint(t[4:6], 16, 0)
390
+								uday, _ := strconv.ParseUint(t[6:8], 16, 0)
391
+								uhour, _ := strconv.ParseUint(t[8:10], 16, 0)
392
+								uminute, _ := strconv.ParseUint(t[10:12], 16, 0)
393
+								usecond, _ := strconv.ParseUint(t[12:], 16, 0)
394
+								macdata = append(macdata, byte(uyear), byte(umonth), byte(uday), byte(uhour), byte(uminute), byte(usecond))
395
+								var sendms []byte
396
+								mac1, _ := strconv.ParseInt(msggatewayid[0:2], 16, 64)
397
+								mac2, _ := strconv.ParseInt(msggatewayid[2:4], 16, 64)
398
+								mac3, _ := strconv.ParseInt(msggatewayid[4:6], 16, 64)
399
+								mac4, _ := strconv.ParseInt(msggatewayid[6:8], 16, 64)
400
+								sendms = []byte{0xA0, 0x03, 0x00, byte(len(macdata)), byte(mac1), byte(mac2), byte(mac3), byte(mac4), 0x00, 0x00}
401
+								sendms = append(sendms, Valuebyte2(v1.ControlNum)...)
402
+								sendms = append(sendms, macdata...)
403
+								sendms = append(sendms, yihuo(sendms))
404
+								send := []byte{0x7E}
405
+								for _, v := range sendms {
406
+									if v == 0x7E {
407
+										send = append(send, 0x7D, 0x02)
408
+									} else if v == 0x7D {
409
+										send = append(send, 0x7D, 0x01)
410
+									} else {
411
+										send = append(send, v)
412
+									}
413
+								}
414
+								send = append(send, 0x7E)
415
+								fmt.Println(time.Now(), "流水号", v1.ControlNum, "平台发送报警信息温度 ", fmt.Sprintf("% X", send))
416
+								c.WritePacket(NewPacket(3, send))
417
+							} else if v1.EventFiled == "humidity" {
418
+								macdata = []byte{byte(mac1), byte(mac2), byte(mac3), byte(mac4), byte(port), byte(2)}
419
+								macdata = append(macdata, Bumabyte4(int64(v1.Value*100))...)
420
+								t := v1.AlarmOn.Format("20060102150405")
421
+								uyear, _ := strconv.ParseUint(t[2:4], 16, 0)
422
+								umonth, _ := strconv.ParseUint(t[4:6], 16, 0)
423
+								uday, _ := strconv.ParseUint(t[6:8], 16, 0)
424
+								uhour, _ := strconv.ParseUint(t[8:10], 16, 0)
425
+								uminute, _ := strconv.ParseUint(t[10:12], 16, 0)
426
+								usecond, _ := strconv.ParseUint(t[12:], 16, 0)
427
+								macdata = append(macdata, byte(uyear), byte(umonth), byte(uday), byte(uhour), byte(uminute), byte(usecond))
428
+								var sendms []byte
429
+								mac1, _ := strconv.ParseInt(msggatewayid[0:2], 16, 64)
430
+								mac2, _ := strconv.ParseInt(msggatewayid[2:4], 16, 64)
431
+								mac3, _ := strconv.ParseInt(msggatewayid[4:6], 16, 64)
432
+								mac4, _ := strconv.ParseInt(msggatewayid[6:8], 16, 64)
433
+								ctlnum, _ := coldcloud.GetReverseControlCtlSNum("CTL" + msggatewayid)
434
+								numint, _ := zksutils.StrTo(ctlnum).Int()
435
+								sendms = []byte{0xA0, 0x03, 0x00, byte(len(macdata)), byte(mac1), byte(mac2), byte(mac3), byte(mac4), 0x00, 0x00}
436
+								sendms = append(sendms, Valuebyte2(numint)...)
437
+								sendms = append(sendms, macdata...)
438
+								sendms = append(sendms, yihuo(sendms))
439
+								send := []byte{0x7E}
440
+								for _, v := range sendms {
441
+									if v == 0x7E {
442
+										send = append(send, 0x7D, 0x02)
443
+									} else if v == 0x7D {
444
+										send = append(send, 0x7D, 0x01)
445
+									} else {
446
+										send = append(send, v)
447
+									}
448
+								}
449
+								send = append(send, 0x7E)
450
+								fmt.Println(time.Now(), "流水号", "平台发送报警信息湿度", fmt.Sprintf("% X", send))
451
+								c.WritePacket(NewPacket(3, send))
452
+
453
+							}
454
+						}
455
+					}
456
+				}
457
+			}
458
+
459
+		}
460
+	}
461
+}
462
+
463
+//平台远程控制设备(关机、重启)
464
+func ShutdownOrBoot(c *gotcp.Conn, msggatewayid string) {
465
+	//设置关机、重启
466
+	shutdown, _ := coldcloud.GetReverseControlShutDown("CTL" + msggatewayid)
467
+	if len(msggatewayid) >= 8 && len(shutdown.Serial) >= 8 && shutdown.ControlType != 0 {
468
+		if time.Now().Unix() > (shutdown.CreatTime.Unix() - 120) {
469
+			head := []byte{0xA0, 0x05, 0x00}
470
+			sendms := []byte{}
471
+			mac1, _ := strconv.ParseInt(msggatewayid[0:2], 16, 64)
472
+			mac2, _ := strconv.ParseInt(msggatewayid[2:4], 16, 64)
473
+			mac3, _ := strconv.ParseInt(msggatewayid[4:6], 16, 64)
474
+			mac4, _ := strconv.ParseInt(msggatewayid[6:8], 16, 64)
475
+			head = append(head, 0x05, byte(mac1), byte(mac2), byte(mac3), byte(mac4), 0x00, 0x00)
476
+			head = append(head, Valuebyte2(shutdown.ControlNumber)...)
477
+			mac1, _ = strconv.ParseInt(shutdown.Serial[0:2], 16, 64)
478
+			mac2, _ = strconv.ParseInt(shutdown.Serial[2:4], 16, 64)
479
+			mac3, _ = strconv.ParseInt(shutdown.Serial[4:6], 16, 64)
480
+			mac4, _ = strconv.ParseInt(shutdown.Serial[6:8], 16, 64)
481
+			sendms = append(sendms, byte(mac1), byte(mac2), byte(mac3), byte(mac4))
482
+			sendms = append(sendms, byte(shutdown.ControlType))
483
+			sendms = append(head, sendms...)
484
+			sendms = append(sendms, yihuo(sendms))
485
+			send := []byte{0x7E}
486
+			for _, v := range sendms {
487
+				if v == 0x7E {
488
+					send = append(send, 0x7D, 0x02)
489
+				} else if v == 0x7D {
490
+					send = append(send, 0x7D, 0x01)
491
+				} else {
492
+					send = append(send, v)
493
+				}
494
+			}
495
+			send = append(send, 0x7E)
496
+			fmt.Println("设置关机重启", fmt.Sprintf("% X", send))
497
+			c.WritePacket(NewPacket(3, send))
498
+			Apipost(Config.Send.Waterdrop.Service+"/devicestate/state?mainserial="+msggatewayid+"&controlnumber="+zksutils.ToStr(shutdown.ControlNumber)+"&requeststate=1&requesttime="+time.Now().Format("2006-01-02 15:04:05"), "PUT", nil)
499
+		}
500
+	}
501
+}
502
+
503
+//func ControlDevice(c *gotcp.Conn, command []byte) {
504
+//	fmt.Println("实时发送", len(Conns.m))
505
+//	Conns.Lock()
506
+//	for k, v := range Conns.m {
507
+//		if len(command) > 7 && k == fmt.Sprintf("%X", command[1:5]) {
508
+//			switch fmt.Sprintf("%X", command[5:7]) {
509
+//			case "A002":
510
+//				fmt.Println("设置设备参数进入", k)
511
+//				DParamSet(v, k)
512
+//			case "A003":
513
+//				fmt.Println("报警推送")
514
+//				ServiceToTriggerSingleMsg(v, k)
515
+//			case "A005":
516
+//				fmt.Println("远程控制设备")
517
+//			case "A00A":
518
+//				mac1, _ := strconv.ParseInt(k[0:2], 16, 64)
519
+//				mac2, _ := strconv.ParseInt(k[2:4], 16, 64)
520
+//				mac3, _ := strconv.ParseInt(k[4:6], 16, 64)
521
+//				mac4, _ := strconv.ParseInt(k[6:8], 16, 64)
522
+//				//ctlnum, _ := coldcloud.GetReverseControlCtlSNum("CTL" + k)
523
+//				//numint, _ := zksutils.StrTo(ctlnum).Int()
524
+//				sendms := []byte{0xA0, 0x0A, 0x00, 0x00, byte(mac1), byte(mac2), byte(mac3), byte(mac4), 0x00, 0x00, 0x00, 0x00}
525
+//				//sendms = append(sendms, Valuebyte2(numint)...)
526
+//				sendms = append(sendms, yihuo(sendms))
527
+//				send := []byte{0x7E}
528
+//				for _, v := range sendms {
529
+//					if v == 0x7E {
530
+//						send = append(send, 0X7D, 0X02)
531
+//					} else if v == 0x7D {
532
+//						send = append(send, 0X7D, 0X01)
533
+//					} else {
534
+//						send = append(send, v)
535
+//					}
536
+//				}
537
+//				send = append(send, 0x7E)
538
+//				err := v.WritePacket(NewPacket(3, send))
539
+//				fmt.Println(err, "远程升级", fmt.Sprintf("% X", send))
540
+//			}
541
+//		}
542
+//	}
543
+//	Conns.Unlock()
544
+//}
545
+func ControlDevice(c *gotcp.Conn, command []byte) {
546
+	if len(command) > 7 {
547
+		k := fmt.Sprintf("%X", command[1:5])
548
+		Conns.Lock()
549
+		if v, ok := Conns.m[k]; ok {
550
+			Conns.Unlock()
551
+			switch fmt.Sprintf("%X", command[5:7]) {
552
+			case "A002":
553
+				fmt.Println("设置设备参数进入", k)
554
+				DParamSet(v, k)
555
+			case "A003":
556
+				fmt.Println("报警推送")
557
+				ServiceToTriggerSingleMsg(v, k)
558
+			case "A005":
559
+				fmt.Println("远程控制设备")
560
+			case "A00A":
561
+				mac1, _ := strconv.ParseInt(k[0:2], 16, 64)
562
+				mac2, _ := strconv.ParseInt(k[2:4], 16, 64)
563
+				mac3, _ := strconv.ParseInt(k[4:6], 16, 64)
564
+				mac4, _ := strconv.ParseInt(k[6:8], 16, 64)
565
+				sendms := []byte{0xA0, 0x0A, 0x00, 0x00, byte(mac1), byte(mac2), byte(mac3), byte(mac4), 0x00, 0x00, 0x00, 0x00}
566
+				sendms = append(sendms, yihuo(sendms))
567
+				send := []byte{0x7E}
568
+				for _, v := range sendms {
569
+					if v == 0x7E {
570
+						send = append(send, 0x7D, 0x02)
571
+					} else if v == 0x7D {
572
+						send = append(send, 0x7D, 0x01)
573
+					} else {
574
+						send = append(send, v)
575
+					}
576
+				}
577
+				send = append(send, 0x7E)
578
+				err := v.WritePacket(NewPacket(3, send))
579
+				fmt.Println(err, "远程升级", fmt.Sprintf("% X", send))
580
+			}
581
+		} else {
582
+			Conns.Unlock()
583
+			fmt.Println("Key Not Found")
584
+		}
585
+	}
586
+}

File diff suppressed because it is too large
+ 197 - 0
src/zks.com/newbbfrontsocketv2/blackbox/socketboltdb_test.go


+ 22 - 0
src/zks.com/newbbfrontsocketv2/blackbox/writedata.go

@@ -0,0 +1,22 @@
1
+package blackbox
2
+
3
+import (
4
+	"encoding/json"
5
+	"fmt"
6
+	"github.com/nsqio/go-nsq"
7
+)
8
+
9
+var Producernsq *nsq.Producer
10
+var Producernsqrequest *nsq.Producer
11
+var err error
12
+
13
+func Writedata_v2(data string) error {
14
+	bdata, err := json.Marshal(data)
15
+	Producernsqrequest.Publish(Config.Send.Nsqrequest.Topic, bdata)
16
+	err = Producernsq.Publish(Config.Send.Nsq.Topic, bdata)
17
+	if err != nil {
18
+		fmt.Println("nsq err", err)
19
+		return err
20
+	}
21
+	return nil
22
+}

+ 18 - 0
src/zks.com/newbbfrontsocketv2/business/sensordata/sensordata.go

@@ -0,0 +1,18 @@
1
+package sensordata
2
+
3
+import (
4
+	"time"
5
+)
6
+
7
+type SensorData struct {
8
+	Id            int       `xorm:"not null pk autoincr INT(11)"`
9
+	IType         int       `xorm:"'itype'"`
10
+	TagId         string    `xorm:"'tagId'"`
11
+	Temperature   float64   `xorm:"'temperature'"`
12
+	Humidity      float64   `xorm:"'humidity'"`
13
+	BatteryLevel  float64   `xorm:"'batteryLevel'"`
14
+	RecordTime    time.Time `xorm:"'recordTime'"`
15
+	UploadTime    time.Time `xorm:"'uploadTime'"`
16
+	BatteryStatus int       `xorm:"'batteryStatus'"`
17
+	AlarmStatus   int       `xorm:"'alarmStatus'"`
18
+}

+ 16 - 0
src/zks.com/newbbfrontsocketv2/business/sensordata/sensordataService.go

@@ -0,0 +1,16 @@
1
+package sensordata
2
+
3
+import (
4
+	"github.com/go-xorm/xorm"
5
+	. "zks.com/zUtils/db"
6
+)
7
+
8
+type SensorDataService struct {
9
+	ServiceBase
10
+}
11
+
12
+func GetSensorDataService(xormEngine *xorm.Engine) *SensorDataService {
13
+	s := new(SensorDataService)
14
+	s.DBE = xormEngine
15
+	return s
16
+}

+ 25 - 0
src/zks.com/newbbfrontsocketv2/business/versionmanage/versionmanage.go

@@ -0,0 +1,25 @@
1
+package versionmanage
2
+
3
+import "time"
4
+
5
+type VersionManage struct {
6
+	Id             int       `xorm:"<- not null pk autoincr INT(10)"`
7
+	ProjectTag     int       `xorm:"INT(10)"`
8
+	ProjectName    string    `xorm:"VARCHAR(255)"`
9
+	VersionNum     int       `xorm:"INT(10)"`
10
+	VersionName    string    `xorm:"VARCHAR(255)"`
11
+	FileType       string    `xorm:"VARCHAR(255)"`
12
+	MainSerials    string    `xorm:"VARCHAR(255)"`
13
+	FileName       string    `xorm:"VARCHAR(255)"`
14
+	FilePath       string    `xorm:"VARCHAR(255)"`
15
+	FileLenNum     int       `xorm:"INT(11)"`
16
+	SizeNum        int       `xorm:"INT(11)"`
17
+	VersionDes     string    `xorm:"VARCHAR(255)"`
18
+	CreateOn       time.Time `xorm:"DATETIME created"`
19
+	CreateUserId   int       `xorm:"INT(11)"`
20
+	CreateBy       string    `xorm:"VARCHAR(50)"`
21
+	ModifiedUserId int       `xorm:"INT(11)"`
22
+	ModifiedBy     string    `xorm:"VARCHAR(255)"`
23
+	ModifiedOn     time.Time `xorm:"DATETIME updated"`
24
+	Remark         string    `xorm:"VARCHAR(255)"`
25
+}

+ 16 - 0
src/zks.com/newbbfrontsocketv2/business/versionmanage/versionmanageService.go

@@ -0,0 +1,16 @@
1
+package versionmanage
2
+
3
+import (
4
+	"github.com/go-xorm/xorm"
5
+	. "zks.com/zUtils/db"
6
+)
7
+
8
+type VersionManageService struct {
9
+	ServiceBase
10
+}
11
+
12
+func GetVersionManageService(xormEngine *xorm.Engine) *VersionManageService {
13
+	s := new(VersionManageService)
14
+	s.DBE = xormEngine
15
+	return s
16
+}

+ 15 - 0
src/zks.com/newbbfrontsocketv2/conf/app.conf

@@ -0,0 +1,15 @@
1
+[send]
2
+[send.redis]
3
+addr = "192.168.1.251:26379"
4
+poolnum = 50
5
+pwd = "Zks201812iot"
6
+[send.nsq]
7
+nsqdtcpaddr = "127.0.0.1:9150"
8
+topic = "blackfront"
9
+[send.nsqrequest]
10
+nsqdtcpaddr = "127.0.0.1:9150"
11
+topic = "blackfrontrequest"
12
+[send.waterdrop]
13
+service = "http://114.215.122.32:8089/v1"
14
+[service]
15
+ipandport = ""

+ 1 - 0
src/zks.com/newbbfrontsocketv2/conf/port.txt

@@ -0,0 +1 @@
1
+12200

+ 80 - 0
src/zks.com/newbbfrontsocketv2/main.go

@@ -0,0 +1,80 @@
1
+package main
2
+
3
+import (
4
+	"bufio"
5
+	"net"
6
+	"os"
7
+	"os/signal"
8
+	"runtime"
9
+	"syscall"
10
+	"time"
11
+
12
+	"github.com/nsqio/go-nsq"
13
+	"zks.com/gotcp"
14
+	service "zks.com/newbbfrontsocketv2/blackbox"
15
+	utils "zks.com/socketutils"
16
+	"zks.com/zUtils/redis"
17
+)
18
+
19
+var port string = "11100"
20
+
21
+func main() {
22
+	service.Config = service.ReadAppConfig("conf/app.conf")
23
+	//初始化缓存区
24
+	redis.InitRedisAuth(service.Config.Send.Redis.Poolnum, service.Config.Send.Redis.Addr, service.Config.Send.Redis.Pwd)
25
+	//redis.InitRedis(service.Config.Send.Redis.Poolnum, service.Config.Send.Redis.Addr)
26
+	//nsq
27
+	cfg := nsq.NewConfig()
28
+	service.Producernsq, _ = nsq.NewProducer(service.Config.Send.Nsq.Nsqdtcpaddr, cfg)
29
+	service.Producernsqrequest, _ = nsq.NewProducer(service.Config.Send.Nsqrequest.Nsqdtcpaddr, cfg)
30
+	initport()
31
+	//初始化日志设定
32
+	os.Mkdir("./runlog", os.ModePerm)
33
+	utils.SetLevel(utils.LevelInformational)
34
+	utils.SetLogger("file", `{"filename":"runlog/runlog.log"}`)
35
+	//启动服务
36
+	runtime.GOMAXPROCS(runtime.NumCPU())
37
+	tcpAddr, err := net.ResolveTCPAddr("tcp4", ":"+port)
38
+
39
+	utils.LogError(err)
40
+
41
+	listener, err := net.ListenTCP("tcp", tcpAddr)
42
+	utils.LogError(err)
43
+	utils.Informational("服务启动,端口:", port)
44
+
45
+	config := &gotcp.Config{
46
+		AcceptTimeout:          10 * 60 * time.Second,
47
+		ReadTimeout:            20 * 60 * time.Second,
48
+		WriteTimeout:           120 * time.Second,
49
+		MaxPacketLength:        20240,
50
+		SendPacketChanLimit:    50,
51
+		ReceivePacketChanLimit: 100,
52
+	}
53
+
54
+	//因未获取到此代码引用,故暂时使用其他方法
55
+	//delegate := &mos.MosConnDelegate{}
56
+	//protocol := &mos.MosProtocol{}
57
+	delegate := &service.BBoxConnDelegate{}
58
+	protocol := &service.BBoxProtocol{}
59
+	svr := gotcp.NewServer(config, delegate, protocol)
60
+	go svr.Start(listener)
61
+
62
+	//停止服务
63
+	ch := make(chan os.Signal)
64
+	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
65
+	utils.Informational("Signal:", <-ch)
66
+
67
+	svr.Stop()
68
+}
69
+func initport() {
70
+	f, err := os.OpenFile("conf/port.txt", os.O_RDONLY, 0)
71
+	if err != nil {
72
+		panic(err)
73
+	}
74
+	defer f.Close()
75
+
76
+	br := bufio.NewReader(f)
77
+
78
+	//每次读取一行
79
+	port, _ = br.ReadString('\n')
80
+}

+ 523 - 0
src/zks.com/socketutils/dbgutil/debug.go

@@ -0,0 +1,523 @@
1
+//from github.com/realint/dbgutil
2
+
3
+package dbgutil
4
+
5
+import (
6
+	"bytes"
7
+	"fmt"
8
+	"log"
9
+	"os"
10
+	"reflect"
11
+	"runtime"
12
+)
13
+
14
+var (
15
+	dunno     = []byte("???")
16
+	centerDot = []byte("·")
17
+	dot       = []byte(".")
18
+	lbr       = []byte("{")
19
+	lbrn      = []byte("{\n")
20
+	com       = []byte(",")
21
+	comn      = []byte(",\n")
22
+	rbr       = []byte("}")
23
+	comnrbr   = []byte(",\n}")
24
+)
25
+
26
+//
27
+// 变量打印时不格式化代码,(支持指针关系打印)
28
+//
29
+func Display(data ...interface{}) breaker {
30
+	return display(false, data...)
31
+}
32
+
33
+//
34
+// 变量打印时格式化代码(不支持指针关系打印)
35
+//
36
+func FormatDisplay(data ...interface{}) breaker {
37
+	return display(true, data...)
38
+}
39
+
40
+func display(formated bool, data ...interface{}) breaker {
41
+	var pc, file, line, ok = runtime.Caller(2)
42
+
43
+	if !ok {
44
+		return breaker{}
45
+	}
46
+
47
+	var buf = new(bytes.Buffer)
48
+
49
+	fmt.Fprintf(buf, "[Debug] at %s() [%s:%d]\n", function(pc), file, line)
50
+
51
+	fmt.Fprintf(buf, "\n[Variables]\n")
52
+
53
+	for i := 0; i < len(data); i += 2 {
54
+		var output = Print(len(data[i].(string))+3, !formated, formated, "    ", nil, data[i+1])
55
+
56
+		fmt.Fprintf(buf, "%s = %s", data[i], output)
57
+	}
58
+
59
+	log.Print(buf)
60
+
61
+	return breaker{}
62
+}
63
+
64
+type breaker struct {
65
+}
66
+
67
+//
68
+// 根据条件暂停程序并打印堆栈信息,回车后继续运行
69
+//
70
+func (this breaker) Break(condition bool) {
71
+	if condition {
72
+		fmt.Fprintf(os.Stderr, "\n[Stack]\n%s", Stack(2, ""))
73
+		fmt.Fprint(os.Stderr, "\npress ENTER to continue")
74
+		fmt.Scanln()
75
+	}
76
+}
77
+
78
+//
79
+// 暂停程序并打印堆栈信息,回车后继续运行
80
+//
81
+func Break() {
82
+	var pc, file, line, ok = runtime.Caller(1)
83
+
84
+	if !ok {
85
+		return
86
+	}
87
+
88
+	var buf = new(bytes.Buffer)
89
+
90
+	fmt.Fprintf(buf, "[Debug] at %s() [%s:%d]\n", function(pc), file, line)
91
+
92
+	fmt.Fprintf(buf, "\n[Stack]\n%s", Stack(2, ""))
93
+
94
+	fmt.Fprintf(buf, "\npress ENTER to continue")
95
+
96
+	log.Print(buf)
97
+
98
+	fmt.Scanln()
99
+}
100
+
101
+type pointerInfo struct {
102
+	prev *pointerInfo
103
+	n    int
104
+	addr uintptr
105
+	pos  int
106
+	used []int
107
+}
108
+
109
+//
110
+// 输出变量值
111
+//
112
+func Print(headlen int, printPointers, formatOutput bool, indent string, structFilter func(string, string) bool, data ...interface{}) []byte {
113
+	var buf = new(bytes.Buffer)
114
+
115
+	if len(data) > 1 {
116
+		fmt.Fprint(buf, indent)
117
+
118
+		fmt.Fprint(buf, "[")
119
+
120
+		if formatOutput {
121
+			fmt.Fprintln(buf)
122
+		}
123
+	}
124
+
125
+	for k, v := range data {
126
+		var buf2 = new(bytes.Buffer)
127
+		var pointers *pointerInfo
128
+		var interfaces []reflect.Value = make([]reflect.Value, 0, 10)
129
+
130
+		printKeyValue(buf2, reflect.ValueOf(v), &pointers, &interfaces, structFilter, formatOutput, indent, 1)
131
+
132
+		if k < len(data)-1 {
133
+			fmt.Fprint(buf2, ", ")
134
+		}
135
+
136
+		fmt.Fprintln(buf2)
137
+
138
+		if printPointers && pointers != nil {
139
+			printPointerInfo(buf2, headlen, pointers)
140
+		}
141
+
142
+		buf.Write(buf2.Bytes())
143
+	}
144
+
145
+	if len(data) > 1 {
146
+		if formatOutput {
147
+			fmt.Fprintln(buf)
148
+		}
149
+
150
+		fmt.Fprint(buf, indent)
151
+
152
+		fmt.Fprint(buf, "]")
153
+	}
154
+
155
+	return buf.Bytes()
156
+}
157
+
158
+func isSimpleType(val reflect.Value, kind reflect.Kind, pointers **pointerInfo, interfaces *[]reflect.Value) bool {
159
+	switch kind {
160
+	case reflect.Bool:
161
+		return true
162
+	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
163
+		return true
164
+	case reflect.Uint8, reflect.Uint16, reflect.Uint, reflect.Uint32, reflect.Uint64:
165
+		return true
166
+	case reflect.Float32, reflect.Float64:
167
+		return true
168
+	case reflect.Complex64, reflect.Complex128:
169
+		return true
170
+	case reflect.String:
171
+		return true
172
+	case reflect.Chan:
173
+		return true
174
+	case reflect.Invalid:
175
+		return true
176
+	case reflect.Interface:
177
+		for _, in := range *interfaces {
178
+			if reflect.DeepEqual(in, val) {
179
+				return true
180
+			}
181
+		}
182
+		return false
183
+	case reflect.UnsafePointer:
184
+		if val.IsNil() {
185
+			return true
186
+		}
187
+
188
+		var elem = val.Elem()
189
+
190
+		if isSimpleType(elem, elem.Kind(), pointers, interfaces) {
191
+			return true
192
+		}
193
+
194
+		var addr = val.Elem().UnsafeAddr()
195
+
196
+		for p := *pointers; p != nil; p = p.prev {
197
+			if addr == p.addr {
198
+				return true
199
+			}
200
+		}
201
+
202
+		return false
203
+	}
204
+
205
+	return false
206
+}
207
+
208
+func printKeyValue(buf *bytes.Buffer, val reflect.Value, pointers **pointerInfo, interfaces *[]reflect.Value, structFilter func(string, string) bool, formatOutput bool, indent string, level int) {
209
+	var t = val.Kind()
210
+
211
+	switch t {
212
+	case reflect.Bool:
213
+		fmt.Fprint(buf, val.Bool())
214
+	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
215
+		fmt.Fprint(buf, val.Int())
216
+	case reflect.Uint8, reflect.Uint16, reflect.Uint, reflect.Uint32, reflect.Uint64:
217
+		fmt.Fprint(buf, val.Uint())
218
+	case reflect.Float32, reflect.Float64:
219
+		fmt.Fprint(buf, val.Float())
220
+	case reflect.Complex64, reflect.Complex128:
221
+		fmt.Fprint(buf, val.Complex())
222
+	case reflect.UnsafePointer:
223
+		fmt.Fprintf(buf, "unsafe.Pointer(0x%X)", val.Pointer())
224
+	case reflect.Ptr:
225
+		if val.IsNil() {
226
+			fmt.Fprint(buf, "nil")
227
+			return
228
+		}
229
+
230
+		var addr = val.Elem().UnsafeAddr()
231
+
232
+		for p := *pointers; p != nil; p = p.prev {
233
+			if addr == p.addr {
234
+				p.used = append(p.used, buf.Len())
235
+				fmt.Fprintf(buf, "0x%X", addr)
236
+				return
237
+			}
238
+		}
239
+
240
+		*pointers = &pointerInfo{
241
+			prev: *pointers,
242
+			addr: addr,
243
+			pos:  buf.Len(),
244
+			used: make([]int, 0),
245
+		}
246
+
247
+		fmt.Fprint(buf, "&")
248
+
249
+		printKeyValue(buf, val.Elem(), pointers, interfaces, structFilter, formatOutput, indent, level)
250
+	case reflect.String:
251
+		fmt.Fprint(buf, "\"", val.String(), "\"")
252
+	case reflect.Interface:
253
+		var value = val.Elem()
254
+
255
+		if !value.IsValid() {
256
+			fmt.Fprint(buf, "nil")
257
+		} else {
258
+			for _, in := range *interfaces {
259
+				if reflect.DeepEqual(in, val) {
260
+					fmt.Fprint(buf, "repeat")
261
+					return
262
+				}
263
+			}
264
+
265
+			*interfaces = append(*interfaces, val)
266
+
267
+			printKeyValue(buf, value, pointers, interfaces, structFilter, formatOutput, indent, level+1)
268
+		}
269
+	case reflect.Struct:
270
+		var t = val.Type()
271
+
272
+		fmt.Fprint(buf, t)
273
+		fmt.Fprint(buf, "{")
274
+
275
+		for i := 0; i < val.NumField(); i++ {
276
+			if formatOutput {
277
+				fmt.Fprintln(buf)
278
+			} else {
279
+				fmt.Fprint(buf, " ")
280
+			}
281
+
282
+			var name = t.Field(i).Name
283
+
284
+			if formatOutput {
285
+				for ind := 0; ind < level; ind++ {
286
+					fmt.Fprint(buf, indent)
287
+				}
288
+			}
289
+
290
+			fmt.Fprint(buf, name)
291
+			fmt.Fprint(buf, ": ")
292
+
293
+			if structFilter != nil && structFilter(t.String(), name) {
294
+				fmt.Fprint(buf, "ignore")
295
+			} else {
296
+				printKeyValue(buf, val.Field(i), pointers, interfaces, structFilter, formatOutput, indent, level+1)
297
+			}
298
+
299
+			fmt.Fprint(buf, ",")
300
+		}
301
+
302
+		if formatOutput {
303
+			fmt.Fprintln(buf)
304
+
305
+			for ind := 0; ind < level-1; ind++ {
306
+				fmt.Fprint(buf, indent)
307
+			}
308
+		} else {
309
+			fmt.Fprint(buf, " ")
310
+		}
311
+
312
+		fmt.Fprint(buf, "}")
313
+	case reflect.Array, reflect.Slice:
314
+		fmt.Fprint(buf, val.Type())
315
+		fmt.Fprint(buf, "{")
316
+
317
+		var allSimple = true
318
+
319
+		for i := 0; i < val.Len(); i++ {
320
+			var elem = val.Index(i)
321
+
322
+			var isSimple = isSimpleType(elem, elem.Kind(), pointers, interfaces)
323
+
324
+			if !isSimple {
325
+				allSimple = false
326
+			}
327
+
328
+			if formatOutput && !isSimple {
329
+				fmt.Fprintln(buf)
330
+			} else {
331
+				fmt.Fprint(buf, " ")
332
+			}
333
+
334
+			if formatOutput && !isSimple {
335
+				for ind := 0; ind < level; ind++ {
336
+					fmt.Fprint(buf, indent)
337
+				}
338
+			}
339
+
340
+			printKeyValue(buf, elem, pointers, interfaces, structFilter, formatOutput, indent, level+1)
341
+
342
+			if i != val.Len()-1 || !allSimple {
343
+				fmt.Fprint(buf, ",")
344
+			}
345
+		}
346
+
347
+		if formatOutput && !allSimple {
348
+			fmt.Fprintln(buf)
349
+
350
+			for ind := 0; ind < level-1; ind++ {
351
+				fmt.Fprint(buf, indent)
352
+			}
353
+		} else {
354
+			fmt.Fprint(buf, " ")
355
+		}
356
+
357
+		fmt.Fprint(buf, "}")
358
+	case reflect.Map:
359
+		var t = val.Type()
360
+		var keys = val.MapKeys()
361
+
362
+		fmt.Fprint(buf, t)
363
+		fmt.Fprint(buf, "{")
364
+
365
+		var allSimple = true
366
+
367
+		for i := 0; i < len(keys); i++ {
368
+			var elem = val.MapIndex(keys[i])
369
+
370
+			var isSimple = isSimpleType(elem, elem.Kind(), pointers, interfaces)
371
+
372
+			if !isSimple {
373
+				allSimple = false
374
+			}
375
+
376
+			if formatOutput && !isSimple {
377
+				fmt.Fprintln(buf)
378
+			} else {
379
+				fmt.Fprint(buf, " ")
380
+			}
381
+
382
+			if formatOutput && !isSimple {
383
+				for ind := 0; ind <= level; ind++ {
384
+					fmt.Fprint(buf, indent)
385
+				}
386
+			}
387
+
388
+			printKeyValue(buf, keys[i], pointers, interfaces, structFilter, formatOutput, indent, level+1)
389
+			fmt.Fprint(buf, ": ")
390
+			printKeyValue(buf, elem, pointers, interfaces, structFilter, formatOutput, indent, level+1)
391
+
392
+			if i != val.Len()-1 || !allSimple {
393
+				fmt.Fprint(buf, ",")
394
+			}
395
+		}
396
+
397
+		if formatOutput && !allSimple {
398
+			fmt.Fprintln(buf)
399
+
400
+			for ind := 0; ind < level-1; ind++ {
401
+				fmt.Fprint(buf, indent)
402
+			}
403
+		} else {
404
+			fmt.Fprint(buf, " ")
405
+		}
406
+
407
+		fmt.Fprint(buf, "}")
408
+	case reflect.Chan:
409
+		fmt.Fprint(buf, val.Type())
410
+	case reflect.Invalid:
411
+		fmt.Fprint(buf, "invalid")
412
+	default:
413
+		fmt.Fprint(buf, "unknow")
414
+	}
415
+}
416
+
417
+func printPointerInfo(buf *bytes.Buffer, headlen int, pointers *pointerInfo) {
418
+	var anyused = false
419
+	var pointerNum = 0
420
+
421
+	for p := pointers; p != nil; p = p.prev {
422
+		if len(p.used) > 0 {
423
+			anyused = true
424
+		}
425
+		pointerNum += 1
426
+		p.n = pointerNum
427
+	}
428
+
429
+	if anyused {
430
+		var pointerBufs = make([][]rune, pointerNum+1)
431
+
432
+		for i := 0; i < len(pointerBufs); i++ {
433
+			var pointerBuf = make([]rune, buf.Len()+headlen)
434
+
435
+			for j := 0; j < len(pointerBuf); j++ {
436
+				pointerBuf[j] = ' '
437
+			}
438
+
439
+			pointerBufs[i] = pointerBuf
440
+		}
441
+
442
+		for pn := 0; pn <= pointerNum; pn++ {
443
+			for p := pointers; p != nil; p = p.prev {
444
+				if len(p.used) > 0 && p.n >= pn {
445
+					if pn == p.n {
446
+						pointerBufs[pn][p.pos+headlen] = '└'
447
+
448
+						var maxpos = 0
449
+
450
+						for i, pos := range p.used {
451
+							if i < len(p.used)-1 {
452
+								pointerBufs[pn][pos+headlen] = '┴'
453
+							} else {
454
+								pointerBufs[pn][pos+headlen] = '┘'
455
+							}
456
+
457
+							maxpos = pos
458
+						}
459
+
460
+						for i := 0; i < maxpos-p.pos-1; i++ {
461
+							if pointerBufs[pn][i+p.pos+headlen+1] == ' ' {
462
+								pointerBufs[pn][i+p.pos+headlen+1] = '─'
463
+							}
464
+						}
465
+					} else {
466
+						pointerBufs[pn][p.pos+headlen] = '│'
467
+
468
+						for _, pos := range p.used {
469
+							if pointerBufs[pn][pos+headlen] == ' ' {
470
+								pointerBufs[pn][pos+headlen] = '│'
471
+							} else {
472
+								pointerBufs[pn][pos+headlen] = '┼'
473
+							}
474
+						}
475
+					}
476
+				}
477
+			}
478
+
479
+			buf.WriteString(string(pointerBufs[pn]) + "\n")
480
+		}
481
+	}
482
+}
483
+
484
+//
485
+// 获取堆栈信息(从系统自带的debug模块中提取代码改造的)
486
+//
487
+func Stack(skip int, indent string) []byte {
488
+	var buf = new(bytes.Buffer)
489
+
490
+	for i := skip; ; i++ {
491
+		var pc, file, line, ok = runtime.Caller(i)
492
+
493
+		if !ok {
494
+			break
495
+		}
496
+
497
+		buf.WriteString(indent)
498
+
499
+		fmt.Fprintf(buf, "at %s() [%s:%d]\n", function(pc), file, line)
500
+	}
501
+
502
+	return buf.Bytes()
503
+}
504
+
505
+// function returns, if possible, the name of the function containing the PC.
506
+func function(pc uintptr) []byte {
507
+	fn := runtime.FuncForPC(pc)
508
+	if fn == nil {
509
+		return dunno
510
+	}
511
+	name := []byte(fn.Name())
512
+	// The name includes the path name to the package, which is unnecessary
513
+	// since the file name is already included.  Plus, it has center dots.
514
+	// That is, we see
515
+	//	runtime/debug.*T·ptrmethod
516
+	// and want
517
+	//	*T.ptrmethod
518
+	if period := bytes.Index(name, dot); period >= 0 {
519
+		name = name[period+1:]
520
+	}
521
+	name = bytes.Replace(name, centerDot, dot, -1)
522
+	return name
523
+}

+ 127 - 0
src/zks.com/socketutils/log.go

@@ -0,0 +1,127 @@
1
+// Copyright 2014 beego Author. All Rights Reserved.
2
+//
3
+// Licensed under the Apache License, Version 2.0 (the "License");
4
+// you may not use this file except in compliance with the License.
5
+// You may obtain a copy of the License at
6
+//
7
+//      http://www.apache.org/licenses/LICENSE-2.0
8
+//
9
+// Unless required by applicable law or agreed to in writing, software
10
+// distributed under the License is distributed on an "AS IS" BASIS,
11
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+// See the License for the specific language governing permissions and
13
+// limitations under the License.
14
+
15
+package socketutils
16
+
17
+import (
18
+	"fmt"
19
+	"strings"
20
+
21
+	"github.com/astaxie/beego/logs"
22
+)
23
+
24
+// Log levels to control the logging output.
25
+const (
26
+	LevelEmergency = iota
27
+	LevelAlert
28
+	LevelCritical
29
+	LevelError
30
+	LevelWarning
31
+	LevelNotice
32
+	LevelInformational
33
+	LevelDebug
34
+)
35
+
36
+func init() {
37
+	// init BeeLogger
38
+	BeeLogger = logs.NewLogger(10000)
39
+	err := BeeLogger.SetLogger("console", "")
40
+	if err != nil {
41
+		fmt.Println("init console log error:", err)
42
+	}
43
+}
44
+
45
+// SetLogLevel sets the global log level used by the simple
46
+// logger.
47
+func SetLevel(l int) {
48
+	BeeLogger.SetLevel(l)
49
+}
50
+
51
+func SetLogFuncCall(b bool) {
52
+	BeeLogger.EnableFuncCallDepth(b)
53
+	BeeLogger.SetLogFuncCallDepth(3)
54
+}
55
+
56
+// logger references the used application logger.
57
+var BeeLogger *logs.BeeLogger
58
+
59
+// SetLogger sets a new logger.
60
+func SetLogger(adaptername string, config string) error {
61
+	err := BeeLogger.SetLogger(adaptername, config)
62
+	if err != nil {
63
+		return err
64
+	}
65
+	return nil
66
+}
67
+
68
+func Emergency(v ...interface{}) {
69
+	BeeLogger.Emergency(generateFmtStr(len(v)), v...)
70
+}
71
+
72
+func Alert(v ...interface{}) {
73
+	BeeLogger.Alert(generateFmtStr(len(v)), v...)
74
+}
75
+
76
+// Critical logs a message at critical level.
77
+func Critical(v ...interface{}) {
78
+	BeeLogger.Critical(generateFmtStr(len(v)), v...)
79
+}
80
+
81
+// Error logs a message at error level.
82
+func Error(v ...interface{}) {
83
+	BeeLogger.Error(generateFmtStr(len(v)), v...)
84
+}
85
+
86
+// Warning logs a message at warning level.
87
+func Warning(v ...interface{}) {
88
+	BeeLogger.Warning(generateFmtStr(len(v)), v...)
89
+}
90
+
91
+//// Deprecated: compatibility alias for Warning(), Will be removed in 1.5.0.
92
+//func Warn(v ...interface{}) {
93
+//	Warning(v...)
94
+//}
95
+
96
+func Notice(v ...interface{}) {
97
+	BeeLogger.Notice(generateFmtStr(len(v)), v...)
98
+}
99
+
100
+// Info logs a message at info level.
101
+func Informational(v ...interface{}) {
102
+	BeeLogger.Informational(generateFmtStr(len(v)), v...)
103
+}
104
+
105
+func InformationalWithFormat(format string, v ...interface{}) {
106
+	BeeLogger.Informational(format, v...)
107
+}
108
+
109
+//// Deprecated: compatibility alias for Warning(), Will be removed in 1.5.0.
110
+//func Info(v ...interface{}) {
111
+//	Informational(v...)
112
+//}
113
+
114
+// Debug logs a message at debug level.
115
+func Debug(v ...interface{}) {
116
+	BeeLogger.Debug(generateFmtStr(len(v)), v...)
117
+}
118
+
119
+//// Trace logs a message at trace level.
120
+//// Deprecated: compatibility alias for Warning(), Will be removed in 1.5.0.
121
+//func Trace(v ...interface{}) {
122
+//	BeeLogger.Trace(generateFmtStr(len(v)), v...)
123
+//}
124
+
125
+func generateFmtStr(n int) string {
126
+	return strings.Repeat("%v ", n)
127
+}

+ 22 - 0
src/zks.com/socketutils/nsqlog.go

@@ -0,0 +1,22 @@
1
+package socketutils
2
+
3
+import (
4
+	"os"
5
+)
6
+
7
+type Logger struct {
8
+}
9
+
10
+func NewLogger(filename string) *Logger {
11
+	//初始化日志设定
12
+	os.Mkdir("./log", os.ModePerm)
13
+	SetLevel(LevelInformational)
14
+	SetLogger("file", `{"filename":"log/`+filename+`"}`)
15
+
16
+	return &Logger{}
17
+}
18
+
19
+func (l *Logger) Output(calldepth int, s string) error {
20
+	Informational(calldepth, s)
21
+	return nil
22
+}

+ 223 - 0
src/zks.com/socketutils/stringConv.go

@@ -0,0 +1,223 @@
1
+package socketutils
2
+
3
+import (
4
+	"fmt"
5
+	"reflect"
6
+	"strconv"
7
+	"time"
8
+)
9
+
10
+var DefaultTimeLoc = time.Local
11
+
12
+// 转换字符串到其他类型
13
+
14
+type StrTo string
15
+
16
+func (f *StrTo) Set(v string) {
17
+	if v != "" {
18
+		*f = StrTo(v)
19
+	} else {
20
+		f.Clear()
21
+	}
22
+}
23
+
24
+func (f *StrTo) Clear() {
25
+	*f = StrTo(0x1E)
26
+}
27
+
28
+func (f StrTo) Exist() bool {
29
+	return string(f) != string(0x1E)
30
+}
31
+
32
+func (f StrTo) Bool() (bool, error) {
33
+	return strconv.ParseBool(f.String())
34
+}
35
+
36
+func (f StrTo) Float32() (float32, error) {
37
+	v, err := strconv.ParseFloat(f.String(), 32)
38
+	return float32(v), err
39
+}
40
+
41
+func (f StrTo) Float64() (float64, error) {
42
+	return strconv.ParseFloat(f.String(), 64)
43
+}
44
+
45
+func (f StrTo) Int() (int, error) {
46
+	v, err := strconv.ParseInt(f.String(), 10, 32)
47
+	return int(v), err
48
+}
49
+
50
+func (f StrTo) Int8() (int8, error) {
51
+	v, err := strconv.ParseInt(f.String(), 10, 8)
52
+	return int8(v), err
53
+}
54
+
55
+func (f StrTo) Int16() (int16, error) {
56
+	v, err := strconv.ParseInt(f.String(), 10, 16)
57
+	return int16(v), err
58
+}
59
+
60
+func (f StrTo) Int32() (int32, error) {
61
+	v, err := strconv.ParseInt(f.String(), 10, 32)
62
+	return int32(v), err
63
+}
64
+
65
+func (f StrTo) Int64() (int64, error) {
66
+	v, err := strconv.ParseInt(f.String(), 10, 64)
67
+	return int64(v), err
68
+}
69
+
70
+func (f StrTo) Uint() (uint, error) {
71
+	v, err := strconv.ParseUint(f.String(), 10, 32)
72
+	return uint(v), err
73
+}
74
+
75
+func (f StrTo) Uint8() (uint8, error) {
76
+	v, err := strconv.ParseUint(f.String(), 10, 8)
77
+	return uint8(v), err
78
+}
79
+
80
+func (f StrTo) Uint16() (uint16, error) {
81
+	v, err := strconv.ParseUint(f.String(), 10, 16)
82
+	return uint16(v), err
83
+}
84
+
85
+func (f StrTo) Uint32() (uint32, error) {
86
+	v, err := strconv.ParseUint(f.String(), 10, 32)
87
+	return uint32(v), err
88
+}
89
+
90
+func (f StrTo) Uint64() (uint64, error) {
91
+	v, err := strconv.ParseUint(f.String(), 10, 64)
92
+	return uint64(v), err
93
+}
94
+
95
+func (f StrTo) String() string {
96
+	if f.Exist() {
97
+		return string(f)
98
+	}
99
+	return ""
100
+}
101
+
102
+// 转换其他类型到字符串
103
+func ToStr(value interface{}, args ...int) (s string) {
104
+	switch v := value.(type) {
105
+	case bool:
106
+		s = strconv.FormatBool(v)
107
+	case float32:
108
+		s = strconv.FormatFloat(float64(v), 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 32))
109
+	case float64:
110
+		s = strconv.FormatFloat(v, 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 64))
111
+	case int:
112
+		s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
113
+	case int8:
114
+		s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
115
+	case int16:
116
+		s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
117
+	case int32:
118
+		s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
119
+	case int64:
120
+		s = strconv.FormatInt(v, argInt(args).Get(0, 10))
121
+	case uint:
122
+		s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
123
+	case uint8:
124
+		s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
125
+	case uint16:
126
+		s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
127
+	case uint32:
128
+		s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
129
+	case uint64:
130
+		s = strconv.FormatUint(v, argInt(args).Get(0, 10))
131
+	case string:
132
+		s = v
133
+	case []byte:
134
+		s = string(v)
135
+	default:
136
+		s = fmt.Sprintf("%v", v)
137
+	}
138
+	return s
139
+}
140
+
141
+// convert any numeric value to int64
142
+func ToInt64(value interface{}) (d int64) {
143
+	val := reflect.ValueOf(value)
144
+	switch value.(type) {
145
+	case int, int8, int16, int32, int64:
146
+		d = val.Int()
147
+	case uint, uint8, uint16, uint32, uint64:
148
+		d = int64(val.Uint())
149
+	default:
150
+		panic(fmt.Errorf("ToInt64 need numeric not `%T`", value))
151
+	}
152
+	return
153
+}
154
+
155
+//参数列表取值常用
156
+type argString []string
157
+
158
+func (a argString) Get(i int, args ...string) (r string) {
159
+	if i >= 0 && i < len(a) {
160
+		r = a[i]
161
+	} else if len(args) > 0 {
162
+		r = args[0]
163
+	}
164
+	return
165
+}
166
+
167
+type argInt []int
168
+
169
+func (a argInt) Get(i int, args ...int) (r int) {
170
+	if i >= 0 && i < len(a) {
171
+		r = a[i]
172
+	}
173
+	if len(args) > 0 {
174
+		r = args[0]
175
+	}
176
+	return
177
+}
178
+
179
+type argAny []interface{}
180
+
181
+func (a argAny) Get(i int, args ...interface{}) (r interface{}) {
182
+	if i >= 0 && i < len(a) {
183
+		r = a[i]
184
+	}
185
+	if len(args) > 0 {
186
+		r = args[0]
187
+	}
188
+	return
189
+}
190
+
191
+// 把字符串转换为time.Time对象
192
+func Str2DateTime(timeStr string) (timeObj time.Time, err error) {
193
+	format := "2006-01-02 15:04:05"
194
+	timeObj, err = time.Parse(format, timeStr)
195
+	//Check(err)
196
+	return
197
+}
198
+
199
+func Str2Date(timeStr string) (timeObj time.Time, err error) {
200
+	format := "2006-01-02"
201
+	timeObj, err = time.Parse(format, timeStr)
202
+	//Check(err)
203
+	return
204
+}
205
+
206
+func TimeParse(dateString, format string) (time.Time, error) {
207
+	tp, err := time.ParseInLocation(format, dateString, DefaultTimeLoc)
208
+	return tp, err
209
+}
210
+
211
+func TimeFormat(t time.Time, format string) string {
212
+	return t.Format(format)
213
+}
214
+
215
+func indirectType(v reflect.Type) reflect.Type {
216
+	switch v.Kind() {
217
+	case reflect.Ptr:
218
+		return indirectType(v.Elem())
219
+	default:
220
+		return v
221
+	}
222
+	return v
223
+}

+ 43 - 0
src/zks.com/socketutils/utils.go

@@ -0,0 +1,43 @@
1
+// Copyright 2014 zks
2
+//
3
+
4
+package socketutils
5
+
6
+import (
7
+	"fmt"
8
+	//"strings"
9
+	"os"
10
+
11
+	"github.com/Unknwon/com"
12
+	"github.com/Unknwon/goconfig"
13
+)
14
+
15
+var Cfg *goconfig.ConfigFile
16
+
17
+// LoadConfig loads configuration file.
18
+func LoadConfig(cfgPath string) {
19
+	if !com.IsExist(cfgPath) {
20
+		os.Create(cfgPath)
21
+	}
22
+
23
+	var err error
24
+	Cfg, err = goconfig.LoadConfigFile(cfgPath)
25
+	if err == nil {
26
+		Informational("Initialize app.ini")
27
+	} else {
28
+		fmt.Println(err)
29
+		os.Exit(2)
30
+	}
31
+
32
+}
33
+
34
+// SaveConfig saves configuration file.
35
+func SaveConfig(cfgPath string) error {
36
+	return goconfig.SaveConfigFile(Cfg, cfgPath)
37
+}
38
+
39
+func LogError(err error) {
40
+	if err != nil {
41
+		Critical(err.Error())
42
+	}
43
+}