All files / node-coap/lib observe_write_stream.js

97.62% Statements 41/42
75% Branches 3/4
100% Functions 5/5
97.62% Lines 41/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                    1x 1x 1x     21x   21x                 21x 21x 21x   21x   21x 21x 19x 4x         1x 1x   1x 30x   30x     30x   30x     1x 34x 34x 34x 34x   34x 34x 34x 34x     1x 1x 1x 1x 1x 1x 1x   1x   1x 1x 1x     1x  
'use strict'
 
/*
 * Copyright (c) 2013-2021 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 Writable = require('readable-stream').Writable
  , util     = require('util')
  , helpers  = require('./helpers')
 
function ObserveWriteStream(request, send) {
  Writable.call(this)
 
  this._packet = {
      token: request.token
    , messageId: request.messageId
    , options: []
    , confirmable: false
    , ack: request.confirmable
    , reset: false
  }
 
  this._request = request
  this._send = send
  this.statusCode = ''
 
  this._counter = 0
 
  var that = this
  this.on('finish', function() {
    if (that._counter === 0) { // we have sent no messages
      that._doSend(null)
    }
  })
}
 
util.inherits(ObserveWriteStream, Writable)
helpers.addSetOption(ObserveWriteStream)
 
ObserveWriteStream.prototype._write = function write(data, encoding, done) {
  this.setOption('Observe', ++this._counter)
 
  Iif (this._counter === 16777215)
    this._counter = 1
 
  this._doSend(data)
 
  done()
}
 
ObserveWriteStream.prototype._doSend = function doSend(data) {
  var packet = this._packet
  packet.code = this.statusCode
  packet.payload = data
  this._send(this, packet)
 
  this._packet.confirmable = this._request.confirmable
  this._packet.ack = !this._request.confirmable
  delete this._packet.messageId
  delete this._packet.payload
}
 
ObserveWriteStream.prototype.reset = function reset() {
  var packet = this._packet
  packet.code = '0.00'
  packet.payload = ''
  packet.reset = true
  packet.ack = false
  packet.token = Buffer.alloc(0)
 
  this._send(this, packet)
 
  this._packet.confirmable = this._request.confirmable
  delete this._packet.messageId
  delete this._packet.payload
}
 
module.exports = ObserveWriteStream