/
outgoing_message.js
114 lines (83 loc) · 2.33 KB
/
outgoing_message.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
'use strict';
/*
* Copyright (c) 2013-2015 node-coap contributors.
*
* node-coap is licensed under an MIT +no-false-attribs license.
* All rights not explicitly granted in the MIT license are reserved.
* See the included LICENSE file for more details.
*/
var BufferList = require('bl')
, util = require('util')
, helpers = require('./helpers')
, toCode = helpers.toCode
function OutgoingMessage(request, send) {
BufferList.call(this)
this._packet = {
messageId: request.messageId
, token: request.token
, options: []
, confirmable: false
, ack: false
, reset: false
}
var that = this
if (request.confirmable) {
// replying in piggyback
this._packet.ack = true
this._ackTimer = setTimeout(function() {
send(that, helpers.genAck(request))
// we are no more in piggyback
that._packet.confirmable = true
that._packet.ack = false
// we need a new messageId for the CON
// reply
delete that._packet.messageId
that._ackTimer = null
}, request.piggybackReplyMs)
}
this._send = send
this.statusCode = ''
this.code = ''
}
util.inherits(OutgoingMessage, BufferList)
helpers.addSetOption(OutgoingMessage)
OutgoingMessage.prototype.end = function(a, b) {
BufferList.prototype.end.call(this, a, b)
var packet = this._packet
, that = this
packet.code = toCode(this.code || this.statusCode)
packet.payload = this
if (this._ackTimer)
clearTimeout(this._ackTimer)
this._send(this, packet)
// easy clean up after generating the packet
delete this._packet.payload
return this
}
OutgoingMessage.prototype.reset = function() {
BufferList.prototype.end.call(this)
var packet = this._packet
, that = this
packet.code = '0.00'
packet.payload = ''
packet.reset = true;
packet.ack = false
packet.token = ''
if (this._ackTimer)
clearTimeout(this._ackTimer)
this._send(this, packet)
// easy clean up after generating the packet
delete this._packet.payload
return this
}
OutgoingMessage.prototype.writeHead = function(code, headers) {
var packet = this._packet
var header
packet.code = String(code).replace(/(^\d[^.])/, '$1.')
for (header in headers) {
if (headers.hasOwnProperty(header)) {
this.setOption(header, headers[header])
}
}
}
module.exports = OutgoingMessage