Skip to content

Commit

Permalink
fix: fix problem with observe responses without observe option (#344)
Browse files Browse the repository at this point in the history
* fix: fix problem with initial observe request

* feat: add observe example using californium server

* test: add observe server response without option

* test: fix eager deregister test
  • Loading branch information
JKRhb committed Apr 24, 2022
1 parent 029033e commit 6ecb2b7
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 5 deletions.
29 changes: 29 additions & 0 deletions examples/observe_eclipse.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const coap = require('../') // or coap

const statusRequest = coap.request({
method: 'GET',
host: 'californium.eclipseprojects.io',
pathname: 'obs',
observe: true,
confirmable: true
})

let responseCounter = 0

statusRequest.on('response', res => {
res.on('error', err => {
console.error('Error by receiving: ' + err)
this.emit('error', 'Error by receiving: ' + err)
res.close()
})

res.on('data', chunk => {
console.log(`Server time: ${chunk.toString()}`)
responseCounter++
if (responseCounter >= 5) {
console.log('Successfully received five responses. Closing the ObserveStream.')
res.close()
}
})
})
statusRequest.end()
12 changes: 8 additions & 4 deletions lib/observe_read_stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,24 @@ export default class ObserveReadStream extends IncomingMessage {
packetToMessage(this, packet)
}

let observe: number

if (typeof this.headers.Observe !== 'number') {
return
observe = 0
} else {
observe = this.headers.Observe
}

// First notification
if (this._lastId === undefined) {
this._lastId = this.headers.Observe - 1
this._lastId = observe - 1
}

const dseq = (this.headers.Observe - this._lastId) & 0xffffff
const dseq = (observe - this._lastId) & 0xffffff
const dtime = Date.now() - this._lastTime

if (this._disableFiltering || (dseq > 0 && dseq < (1 << 23)) || dtime > 128 * 1000) {
this._lastId = this.headers.Observe
this._lastId = observe
this._lastTime = Date.now()
this.push(packet.payload)
}
Expand Down
10 changes: 9 additions & 1 deletion test/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1257,6 +1257,14 @@ describe('request', function () {
return
}

ssend(rsinfo, {
messageId: packet.messageId,
token: packet.token,
payload: Buffer.from('42'),
ack: true,
code: '2.05'
})

ssend(rsinfo, {
messageId: packet.messageId,
token: packet.token,
Expand Down Expand Up @@ -1382,7 +1390,7 @@ describe('request', function () {
return
}

server.on('message', (msg, rsinfo) => {
server.once('message', (msg, rsinfo) => {
const packet = parse(msg)
if (packet.ack && (packet.code === '0.00')) {
return
Expand Down

0 comments on commit 6ecb2b7

Please sign in to comment.