All files / node-coap/lib helpers.js

100% Statements 124/124
98% Branches 49/50
100% Functions 17/17
100% Lines 124/124

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 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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274                    1x 1x 1x           1x 1x   1x 132x                   1x               1492x 1492x   1492x 2x     1490x 840x     1490x 1450x   1490x 1510x           1490x     1x 2x 2x 2x     1x 797x 796x   1x 1x 1x   1x   1x 1x   1x   1x     1x     920x   920x 920x 920x   920x 920x 920x 920x 920x   920x 753x   753x 37x     753x 19x     753x   753x 267x     920x 110x   920x 920x 920x 12x       1x 2x 2x 1x 1x                 1x 2936x 3293x 1225x 1711x                 1x 2x 2x 1x 1x     1x     1x 2x 2x 2x 2x 2x 1x 1x 1x   2x 2x                 1x   1226x   240x 240x   984x 984x   1x 1x     1x     1225x   2x   1223x                       1x   802x 802x 802x     802x 802x 802x 802x       802x 144x   658x 656x   2x 1x 1x       1x   801x           1x 7x           1x 9x 7x       1x 2x     1x 310x    
'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 toBinary   = require('./option_converter').toBinary
  , fromBinary = require('./option_converter').fromBinary
  , codes      = {
        '0.01': 'GET'
      , '0.02': 'POST'
      , '0.03': 'PUT'
      , '0.04': 'DELETE'
    }
  , capitalize = require('capitalize')
  , isIgnored  = require('./option_converter').isIgnored
 
module.exports.genAck = function(request) {
  return {
      messageId: request.messageId
    , code: '0.00'
    , options: []
    , confirmable: false
    , ack: true
    , reset: false
  }
}
 
var optionAliases = {
  'Content-Type': 'Content-Format',
  'Etag': 'ETag'
}
 
function setOption(name, values) {
  var i
 
  name = capitalize.words(name)
  name = optionAliases[name] || name
 
  if (isIgnored(name)) {
    return this
  }
 
  this._packet.options = this._packet.options.filter(function(option) {
    return option.name !== name
  })
 
  if (!Array.isArray(values))
    values = [values]
 
  for (i = 0; i < values.length; i++) {
    this._packet.options.push({
        name: name
      , value: toBinary(name, values[i])
    })
  }
 
  return this
}
 
module.exports.addSetOption = function(klass) {
  var proto = klass.prototype
  proto.setOption = setOption
  proto.setHeader = setOption
}
 
module.exports.toCode = function toCode(code) {
  if (typeof code === 'string')
    return code
 
  var first  = Math.floor(code / 100)
    , second = code - first * 100
    , result = ''
 
  result += first + '.'
 
  Eif (second < 10)
    result += '0'
 
  result += second
 
  return result
}
 
module.exports.packetToMessage = function packetToMessage(dest, packet) {
 
  var i
    , options = packet.options
    , option
    , paths   = []
    , queries = []
    , query   = ''
 
  dest.payload = packet.payload
  dest.options = packet.options
  dest.code    = packet.code
  dest.method  = codes[packet.code]
  dest.headers = {}
 
  for (i=0; i < options.length; i++) {
    option = options[i]
 
    if (option.name === 'Uri-Path') {
      paths.push(option.value)
    }
 
    if (option.name === 'Uri-Query') {
      queries.push(option.value)
    }
 
    option.value = fromBinary(option.name, option.value)
 
    if (option.value != null && !Buffer.isBuffer(option.value))
      dest.headers[option.name] = option.value
  }
 
  if (dest.headers['Content-Format'])
    dest.headers['Content-Type'] = dest.headers['Content-Format']
 
  query = queries.join('&')
  dest.url = '/' + paths.join('/')
  if (query) {
    dest.url += '?' + query
  }
}
 
module.exports.hasOption = function hasOption(options, name) {
  for (var i in options)
    if (options[i].name == name)
      return true
  return null
}
 
/*
get an option value from options
  options     array of object, in form {name: , value}
  name        name of the object wanted to retrive
  return      value, or null
*/
module.exports.getOption = function getOption(options, name) {
  for (var i in options)
    if (options[i].name == name)
      return options[i].value
  return null
}
 
/*
get an option value from options
  options     array of object, in form {name: , value}
  name        name of the object wanted to retrive
  return      value, or null
*/
module.exports.removeOption = function removeOption(options, name) {
  for (var i in options) {
    if (options[i].name == name) {
      delete options[i]
      return true
    }
  }
  return false
}
 
module.exports.simplifyPacketForPrint = function simplifyPacketForPrint(packetIn) {
  var packet = Object.assign({}, packetIn)
  packet.token = packet.token.toString("hex")
  packet.payload = "Buff: " + packet.payload.length
  var newOptions = {}
  for(var j in packet.options) {
      var name = packet.options[j].name
      var hex = packet.options[j].value.toString("hex")
      newOptions[name] = hex
  }
  packet.options = newOptions
  return packet
}
/*
parse block2
  value       block2 value buffer
  return      object describes block2, {moreBlock2: , num: , size: }
 
with invalid block2 value, the function return null
*/
module.exports.parseBlock2 = function parseBlock2(block2Value) {
  var num
  switch (block2Value.length) {
    case 1:
    num = block2Value[0] >> 4
    break
    case 2:
    num = (block2Value[0]*256 + block2Value[1]) >> 4
    break
    case 3:
    num = (block2Value[0]*256*256 + block2Value[1]*256 + block2Value[2]) >>4
    break
    default:
    // Block2 is more than 3 bytes
    return null
  }
  // limit value of size is 1024 (2**(6+4))
  if (block2Value.slice(-1)[0] == 7) {
    // Block size is bigger than 1024
    return null
  }
  return {
    moreBlock2: (block2Value.slice(-1)[0] & (0x01<<3))? true:false,
    num: num,
    size: Math.pow(2, (block2Value.slice(-1)[0] & 0x07)+4)
  }
}
 
/*
create buffer for block2 option
  requestedBlock      object contain block2 infor, e.g. {moreBlock2: true, num: 100, size: 32}
  return              Buffer carrying block2 value
*/
module.exports.createBlock2 = function createBlock2(requestedBlock) {
  var byte
  var szx = Math.log(requestedBlock.size)/Math.log(2) - 4
  var m = ((requestedBlock.moreBlock2==true)?1:0)
  var num = requestedBlock.num
  var extraNum
 
  byte = 0
  byte |= szx
  byte |= m << 3
  byte |= (num&0xf) <<4
 
  // total num occupy up to 5 octets
  // num share the higher octet of first byte, and (may) take more 2 bytes for the rest 4 octets
  if (num <= 0xf) {
    extraNum = null
  }
  else if (num <=0xfff) {
    extraNum = Buffer.of(num/16)
  }
  else if (num <=0xfffff) {
    extraNum = Buffer.alloc(2)
    extraNum.writeUInt16BE(num>>4,0)
  }
  else {
    // too big block2 number
    return null
  }
  return (extraNum)? Buffer.concat([extraNum, Buffer.of(byte)]):Buffer.of(byte)
}
 
/**
 * Provide a or function to use with the reduce() Array method
 */
module.exports.or = function or(previous, current) {
    return previous || current
}
 
/**
 * Provide a function to detect whether an option has a particular name (for its use with filter or map).
 */
module.exports.isOption = function isOption(optionName) {
  return function(option) {
    return option.name === optionName
  }
}
 
module.exports.isNumeric = function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n)
}
 
module.exports.isBoolean = function isBoolean(n) {
  return typeof(n) === 'boolean'
}