https://github.com/ruuvi/ruuvi-sensor-protocols
775313
function(manufacturerDataBytes){
  //console.log(manufacturerDataBytes);
  let humidityStart      = 1;
  let humidityEnd        = humidityStart+1;
  let temperatureStart   = humidityEnd;
  let temperatureEnd     = temperatureStart+2;
  let pressureStart      = temperatureEnd;
  let pressureEnd        = pressureStart+2;
  let accelerationXStart = pressureEnd;
  let accelerationXEnd   = accelerationXStart+2;
  let accelerationYStart = accelerationXEnd;
  let accelerationYEnd   = accelerationYStart+2;
  let accelerationZStart = accelerationYEnd;
  let accelerationZEnd   = accelerationZStart+2;
  let batteryStart       = accelerationZEnd;
  let batteryEnd         = batteryStart+2;

  let robject = {};

  let humidity = manufacturerDataBytes[humidityStart];
  humidity/= 2; //scale
  robject.humidity = humidity;

  let temperatureBytes = manufacturerDataBytes.slice(temperatureStart, temperatureEnd);
  let temperature = temperatureBytes[0]  //Full degrees
  temperature += temperatureBytes[1]/100.0; //Decimals
  if(temperature > 128){           // Ruuvi format, sign bit + value
    temperature = temperature-128; 
    temperature = 0 - temperature; 
  }
  robject.temperature = temperature;

  let pressureBytes = manufacturerDataBytes.slice(pressureStart, pressureEnd)  // uint16_t pascals
  let pressure = (pressureBytes[0]<<8) + pressureBytes[1];
  pressure += 50000; //Ruuvi format
  robject.pressure = pressure;

  let accelerationBytes = manufacturerDataBytes.slice(accelerationXStart, accelerationXEnd);  // milli-g
  let accelerationX = (accelerationBytes[0]<<8) + accelerationBytes[1];
  if(accelerationX > 32767){ accelerationX -= 65536;}  //two's complement

  accelerationBytes = manufacturerDataBytes.slice(accelerationYStart, accelerationYEnd);  // milli-g
  let accelerationY = (accelerationBytes[0]<<8) + accelerationBytes[1];
  if(accelerationY > 32767){ accelerationY -= 65536;}  //two's complement

  accelerationBytes = manufacturerDataBytes.slice(accelerationZStart, accelerationZEnd);  // milli-g
  let accelerationZ = (accelerationBytes[0]<<8) + accelerationBytes[1];
  if(accelerationZ > 32767){ accelerationZ -= 65536;}  //two's complement

  robject.accelerationX = accelerationX;
  robject.accelerationY = accelerationY;
  robject.accelerationZ = accelerationZ;
  
  let batteryBytes = manufacturerDataBytes.slice(batteryStart, batteryEnd);  // milli volts
  let battery = (batteryBytes[0]<<8) + batteryBytes[1];
  robject.battery = battery;
  robject.destination_endpoint = 3;

  return robject;
}
315920
function protocol(value) {
  var val = value.slice(-6).toLowerCase()
  return val === mailto || val.slice(-5) === https || val.slice(-4) === http
}
104099
function transmit(sensor)
{
    // lets build up a packet and try loading it (8 bytes max).
    var myPayload = "01234567";
    console.log("Loading a packet of 8 numbers (0-7) into a TX buffer...");
    sensor.loadTXBuffer(sensorObj.MCP2515_TX_BUFFER0,
                        0, false, false, myPayload);

    // now lets try to transmit it
    console.log("Transmitting packet...");
    sensor.transmitBuffer(sensorObj.MCP2515_TX_BUFFER0, true);

    console.log("Transmit successful");
    console.log();
}
1318033
def _decode_sensor_data(properties):
        """"""
        b64_input = ""
        for s in properties.get('payload'):
            # pylint: disable=consider-using-join
            b64_input += s

        decoded = base64.b64decode(b64_input)
        data = zlib.decompress(decoded)
        points = []
        i = 0

        while i < len(data):
            points.append({
                'timestamp': int(1e3 * ArloBaseStation._parse_statistic(
                    data[i:(i + 4)], 0)),
                'temperature': ArloBaseStation._parse_statistic(
                    data[(i + 8):(i + 10)], 1),
                'humidity': ArloBaseStation._parse_statistic(
                    data[(i + 14):(i + 16)], 1),
                'airQuality': ArloBaseStation._parse_statistic(
                    data[(i + 20):(i + 22)], 1)
            })
            i += 22

        return points
217340
def srp(x, promisc=None, iface=None, iface_hint=None, filter=None,
        nofilter=0, type=ETH_P_ALL, *args, **kargs):
    """"""
    if iface is None and iface_hint is not None:
        iface = conf.route.route(iface_hint)[0]
    s = conf.L2socket(promisc=promisc, iface=iface,
                      filter=filter, nofilter=nofilter, type=type)
    result = sndrcv(s, x, *args, **kargs)
    s.close()
    return result
813070
private function _other()
    {
        foreach ($this->_lines as $line) {
            $buffer = preg_split("/\s*\|\s*/", $line);
            if (isset($buffer[1]) && $buffer[1] == "Compact"
               && $buffer[5] !== "Init"
               && $buffer[5] !== "Unknown"
               && $buffer[5] !== "NotAvailable") {
                $dev = new SensorDevice();
                $dev->setName($buffer[4].' ('.$buffer[2].')');

                $buffer5s = preg_split("/\s+/", $buffer5 = $buffer[5]);
                if (isset($buffer5s[1])) {
                    $value = hexdec($buffer5s[0]) & 0xff;
                    if ($buffer5s[1] === 'DiscreteEvt') {
                        $dev->setValue('0x'.dechex($value));
                    } elseif (($buffer5s[1] === 'DiscreteUnit') && ($value > 0)) {
                        $dev->setValue('0x'.dechex($value - 1));
                    } else {
                        $dev->setValue($buffer5);
                    }
                } else {
                    $dev->setValue($buffer5);
                }
                $this->mbinfo->setMbOther($dev);
            }
        }
    }
371614
def chomp_protocol(url):
        
        if '+' in url:
            url = url.split('+', 1)[1]
        scheme, netloc, path, query, frag = urlparse.urlsplit(url)
        rev = None
        if '@' in path:
            path, rev = path.rsplit('@', 1)
        url = urlparse.urlunsplit((scheme, netloc, path, query, ''))
        if url.startswith('ssh://git@github.com/'):
            url = url.replace('ssh://', 'git+ssh://')
        elif '://' not in url:
            assert 'file:' not in url
            url = url.replace('git+', 'git+ssh://')
            url = url.replace('ssh://', '')
        return url
187409
def put_settings(self, sensors=[], actuators=[], auth_token=None,
                     endpoint=None, blink=None, discovery=None,
                     dht_sensors=[], ds18b20_sensors=[]):
        
        url = self.base_url + '/settings'

        payload = {
            "sensors": sensors,
            "actuators": actuators,
            "dht_sensors": dht_sensors,
            "ds18b20_sensors": ds18b20_sensors,
            "token": auth_token,
            "apiUrl": endpoint
        }

        if blink is not None:
            payload['blink'] = blink

        if discovery is not None:
            payload['discovery'] = discovery

        try:
            r = requests.put(url, json=payload, timeout=10)
            return r.ok
        except RequestException as err:
            raise Client.ClientError(err)
596118
def build_args():
    """"""

    parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument(u'sensor_graph', type=str, help=u"The sensor graph file to load and run.")
    parser.add_argument(u'--stop', u'-s', action=u"append", default=[], type=str, help=u"A stop condition for when the simulation should end.")
    parser.add_argument(u'--realtime', u'-r', action=u"store_true", help=u"Do not accelerate the simulation, pin the ticks to wall clock time")
    parser.add_argument(u'--watch', u'-w', action=u"append", default=[], help=u"A stream to watch and print whenever writes are made.")
    parser.add_argument(u'--trace', u'-t', help=u"Trace all writes to output streams to a file")
    parser.add_argument(u'--disable-optimizer', action="store_true", help=u"disable the sensor graph optimizer completely")
    parser.add_argument(u"--mock-rpc", u"-m", action=u"append", type=str, default=[], help=u"mock an rpc, format should be <slot id>:<rpc_id> = value.  For example -m \"slot 1:0x500a = 10\"")
    parser.add_argument(u"--port", u"-p", help=u"The port to use to connect to a device if we are semihosting")
    parser.add_argument(u"--semihost-device", u"-d", type=lambda x: int(x, 0), help=u"The device id of the device we should semihost this sensor graph on.")
    parser.add_argument(u"-c", u"--connected", action="store_true", help=u"Simulate with a user connected to the device (to enable realtime outputs)")
    parser.add_argument(u"-i", u"--stimulus", action=u"append", default=[], help="Push a value to an input stream at the specified time (or before starting).  The syntax is [time: ][system ]input X = Y where X and Y are integers")
    return parser
830155
def check(sensor_class, args):
        
        parser = SensorCmdLine.parsers(sensor_class)
        parsed = parser.parse_args(args)
        return sensor_class.check(json.loads(parsed.data))
1900
async def async_get_sensor_log(self, index: int) -> Optional[SensorLogResponse]:
        

        response = await self._protocol.async_execute(
            GetSensorLogCommand(index))
        if isinstance(response, SensorLogResponse):
            return response
        return None
789387
def _decode_ctrl_packet(self, version, packet):
        """"""

        for i in range(5):
            input_bit = packet[i]
            self._debug(PROP_LOGLEVEL_DEBUG, "Byte " + str(i) + ": " + str((input_bit >> 7) & 1) + str((input_bit >> 6) & 1) + str((input_bit >> 5) & 1) + str((input_bit >> 4) & 1) + str((input_bit >> 3) & 1) + str((input_bit >> 2) & 1) + str((input_bit >> 1) & 1) + str(input_bit & 1))

        for sensor in self._ctrl_sensor:
            if (sensor.sensor_type == PROP_SENSOR_FLAG):
                sensor.value = (packet[sensor.index // 8] >> (sensor.index % 8)) & 1
            elif (sensor.sensor_type == PROP_SENSOR_RAW):
                sensor.value = packet
145657
function decodeURIComponentSafe(uri, mod) {
    var decodedURI = '';
    var i = 0;
    var length, arr, tempDecodedURI;

    mod = !!(mod);
    arr = uri.split(/(%(?:d0|d1)%.{2})/);

    for (length = arr.length; i < length; i += 1) {
        try {
            tempDecodedURI = decodeURIComponent(arr[i]);
        } catch (e) {
            tempDecodedURI = mod ? arr[i].replace(/%(?!\d+)/g, '%25') : arr[i];
        }

        decodedURI += tempDecodedURI;
    }

    return decodedURI;
}
1265011
function Input(server) {
  // Konstruktorin sisältöä ei dokumentoida
  /**#nocode+*/

  var self = this
    , rli = readline.createInterface(process.stdin, process.stdout, function (partial) {
      return [server.commands.suggest(partial), partial];
    });

  process.stdin.resume();
  process.stdin.setEncoding('utf8');

  if (process.platform !== "win32") {
    process.on('SIGINT', function processSIGINT() {
      log.notice('Received ' + 'SIGINT'.red);
      // Lakataan kuuntelemasta stdin-syötettä.
      // Node sulkeutuu jahka kaikki eventit on kutsuttu, eikä uusia ole lisätty event-luuppiin.
      process.stdin.destroy();
      server.close();
    });
  }

  rli.on('close', function rliClose() {
    process.stdin.destroy();
    server.close();
  });

  rli.on('line', function rliLine(input){
    var msg = input.trim();
    if (!msg) { return; }
    // Käsitellään serverikomennot
    server.commands.call(msg.split(' ')[0], splitString(msg).splice(1));
  });

  // Tästä eteenpäin dokumentoidaan taas jos on jotain dokumentoitavaa
  /**#nocode-*/
}
1014971
def queryByPortSensor(portiaConfig, edgeId, port, sensor, last=False, params={ 'from': None, 'to': None, 'order': None, 'precision': 'ms', 'limit': None }):
    """"""

    header = {'Accept': 'text/csv'}

    if last == False:
        endpoint = '/select/device/{0}/port/{1}/sensor/{2}{3}'.format( edgeId, port, sensor, utils.buildGetParams(params) )
    else:
        endpoint = '/select/device/{0}/port/{1}/sensor/{2}/last{3}'.format( edgeId, port, sensor, utils.buildGetParams(params) )

    response = utils.httpGetRequest(portiaConfig, endpoint, header)

    if response.status_code == 200:
        try:

            dimensionSeries = pandas.read_csv( StringIO(response.text), sep=';' )
            if portiaConfig['debug']:
                print( '[portia-debug]: {0} rows'.format( len(dimensionSeries.index) ) )

            return dimensionSeries

        except:
            raise Exception('couldn\'t create pandas data frame')
    else:
        raise Exception('couldn\'t retrieve data')
981886
def api_sensors(self) -> Set[str]:
        """"""
        today = round_time(datetime.now(timezone.utc), by=timedelta(days=1))
        c = requests.get(
            f"https://opensky-network.org/api/sensor/myStats"
            f"?days={int(today.timestamp())}",
            auth=self.auth,
        )
        if c.status_code != 200:
            raise ValueError(c.content.decode())
        return set(c.json()[0]["stats"].keys())
803709
def tdSensor(self):
        
        protocol = create_string_buffer(20)
        model = create_string_buffer(20)
        sid = c_int()
        datatypes = c_int()

        self._lib.tdSensor(protocol, sizeof(protocol), model, sizeof(model),
                           byref(sid), byref(datatypes))
        return {'protocol': self._to_str(protocol),
                'model': self._to_str(model),
                'id': sid.value, 'datatypes': datatypes.value}