@@ -29,6 +29,17 @@ class Agent {
29
29
this . creds = Object . assign ( this . creds , { reconnectPeriod : 0 } )
30
30
// console.log(this.creds)
31
31
32
+ if ( this . creds . ssl ) {
33
+ switch ( this . creds . protocol ) {
34
+ case 'mqtt:' :
35
+ this . creds . protocol = 'mqtts:'
36
+ break
37
+ case 'ws:' :
38
+ this . creds . protocol = 'wss:'
39
+ break
40
+ }
41
+ }
42
+
32
43
const options = {
33
44
protocol : this . creds . protocol ,
34
45
host : this . creds . host ,
@@ -39,13 +50,17 @@ class Agent {
39
50
password : this . creds . credentials . password
40
51
}
41
52
53
+ if ( ! this . creds . verifySSL ) {
54
+ options . rejectUnauthorized = false
55
+ }
56
+
42
57
// console.log(options)
43
58
44
59
// this.client = mqtt.connect(`${this.creds.protocol}//${this.creds.hostname}:${this.creds.port}`, this.creds)
45
60
this . client = mqtt . connect ( options )
46
61
this . client . on ( 'connect' , function ( ) {
47
62
agent . connected = true
48
- // console.log(' connected' )
63
+ console . log ( ` connected to ${ options . host } : ${ options . port } as ${ options . clientId } ` )
49
64
agent . error = null
50
65
agent . client . subscribe ( '#' )
51
66
} )
@@ -73,8 +88,8 @@ class Agent {
73
88
// console.log(packet)
74
89
} )
75
90
this . client . on ( 'error' , function ( error ) {
76
- // console.log('error', error.code)
77
- // console.log(error)
91
+ console . log ( 'error' , error . code )
92
+ console . log ( error )
78
93
switch ( error . code ) {
79
94
case 'ECONNREFUSED' : // connection refused
80
95
case 'ENOTFOUND' : // DNS lookup failed
@@ -102,9 +117,34 @@ class Agent {
102
117
}
103
118
// console.log(`agent.error set to: ${agent.error}`)
104
119
} )
105
- this . client . on ( 'message' , function ( topic ) {
120
+ this . client . on ( 'message' , function ( topic , payload ) {
106
121
// console.log(topic)
107
- agent . topics [ topic ] = Date . now ( )
122
+ let type = 'unknown'
123
+ try {
124
+ const stringPayload = payload . toString ( 'utf8' )
125
+ type = 'string'
126
+ switch ( stringPayload . charAt ( 0 ) ) {
127
+ case '<' :
128
+ // probably XML
129
+ type = 'xml'
130
+ break
131
+ case '{' :
132
+ case '[' :
133
+ // probably JSON
134
+ try {
135
+ JSON . parse ( stringPayload )
136
+ } catch ( err ) {
137
+
138
+ }
139
+ type = 'json'
140
+ }
141
+ } catch ( err ) {
142
+
143
+ }
144
+ agent . topics [ topic ] = {
145
+ timestamp : Date . now ( ) ,
146
+ type
147
+ }
108
148
} )
109
149
} catch ( err ) {
110
150
console . log ( err )
0 commit comments