Passes the data to the handler.
        :param deviceId: the device the data comes from.
        :param measurementId: the measurement id.
        :param data: the data.
        :return: true if the data was handled.
516982
def recordData(self, measurementId, deviceId, data):
        
        am, handler = self.getDataHandler(measurementId, deviceId)
        if handler is not None:
            am.stillRecording(deviceId, len(data))
            handler.handle(data)
            return True
        else:
            logger.error('Received data for unknown handler ' + deviceId + '/' + measurementId)
            return False
1097376
void measure(Registry registry, JmxData data, List<Measurement> ms) {
    Map<String, String> tags = tagMappings.entrySet().stream().collect(Collectors.toMap(
        Map.Entry::getKey,
        e -> MappingExpr.substitute(e.getValue(), data.getStringAttrs())
    ));
    Id id = registry
        .createId(MappingExpr.substitute(nameMapping, data.getStringAttrs()))
        .withTags(tags);

    Map<String, Number> numberAttrs = new HashMap<>(data.getNumberAttrs());
    JmxData previous = previousData.put(data.getName(), data);
    if (previous != null) {
      previous.getNumberAttrs().forEach((key, value) -> numberAttrs.put("previous:" + key, value));
    }

    Double v = MappingExpr.eval(valueMapping, numberAttrs);

    if (v != null && !v.isNaN()) {
      if (counter) {
        updateCounter(registry, id, v.longValue());
      } else {
        ms.add(new Measurement(id, registry.clock().wallTime(), v));
      }
    }
  }
995063
def _on_connected(self, device):
        
        self._logger.debug("Device connected event: {}".format(device))

        self.connected = True
        self._connection_handle = device['connection_handle']
        self.device.connected = True
        self._audit('ClientConnected')
216866
def search_device_by_id(self, deviceID) -> Device:
        
        for d in self.devices:
            if d.id == deviceID:
                return d
        return None
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')
501943
def device(self, device_id, *args, **kwargs):
        
        return Device(device_id, self.corsair_sdk, self._corsair_sdk_path, *args, **kwargs)
739805
def handle_data(self, data):
        
        self.log.debug( u'Encountered some data  : {0}'.format(data) )
        if not self.level:
            self.data.append(data)
353602
def data_received(self, data):
        
        if self.state == STATE_STARTING:
            self.state = STATE_RUNNING
            _LOGGER.debug('Websocket handshake: %s', data.decode())
            return
        _LOGGER.debug('Websocket data: %s', data)

        while len(data) > 0:
            payload, extra_data = self.get_payload(data)
            self._data = payload ###
            self.async_session_handler_callback('data')###
            #self.async_callback(payload)
            data = extra_data
863885
def put(self, deviceId, measurementId):
        
        record = self.measurements.get(deviceId)
        if record is not None:
            measurement = record.get(measurementId)
            if measurement is not None:
                if len([x.name for x in measurement.statuses if x.name is 'COMPLETE' or x.name is 'FAILED']) > 0:
                    logger.info('Overwriting existing completed measurement ' + x.name)
                    measurement = None
            if measurement is None:
                logger.info('Initiating measurement ' + measurementId)
                measurement = ScheduledMeasurement(measurementId, self.recordingDevices.get(deviceId))
                body = request.get_json()
                duration_ = body['duration']
                def _cleanup():
                    logger.info('Removing ' + measurementId + ' from ' + deviceId)
                    record.pop(measurementId)
                measurement.schedule(duration_, at=body.get('at'), delay=body.get('delay'), callback=_cleanup)
                # a quick hack to enable the measurement to be cleaned up by the ScheduledMeasurement
                record[measurementId] = measurement
                return measurement, 200
            else:
                return measurement, 400
        else:
            return 'unknown device ' + deviceId, 400
144677
public boolean notifyMeasurementEnding(Iterable<Measurement> measurements) throws IOException {
    println(controlLogMessageRenderer.render(new StopMeasurementLogMessage(measurements)));
    for (Measurement measurement : measurements) {
      println(String.format("I got a result! %s: %f%s%n", measurement.description(),
          measurement.value().magnitude() / measurement.weight(), measurement.value().unit()));
    }
    writer.flush();
    return shouldKeepMeasuring();
  }
727247
def failMeasurement(self, measurementId, deviceName, failureReason=None):
        
        am, handler = self.getDataHandler(measurementId, deviceName)
        if handler is not None:
            am.updateDeviceStatus(deviceName, RecordStatus.FAILED, reason=failureReason)
            handler.stop(measurementId)
            return True
        else:
            return False
1079817
def accept(self, deviceId, device):
        
        storedDevice = self.devices.get(deviceId)
        if storedDevice is None:
            logger.info('Initialising device ' + deviceId)
            storedDevice = Device(self.maxAgeSeconds)
            storedDevice.deviceId = deviceId
            # this uses an async handler to decouple the recorder put (of the data) from the analyser handling that data
            # thus the recorder will become free as soon as it has handed off the data. This means delivery is only
            # guaranteed as long as the analyser stays up but this is not a system that sits on top of a bulletproof
            # message bus so unlucky :P
            storedDevice.dataHandler = AsyncHandler('analyser', CSVLogger('analyser', deviceId, self.dataDir))
        else:
            logger.debug('Pinged by device ' + deviceId)
        storedDevice.payload = device
        storedDevice.lastUpdateTime = datetime.datetime.utcnow()
        # TODO if device has FAILED, do something?
        self.devices.update({deviceId: storedDevice})
        self.targetStateController.updateDeviceState(storedDevice.payload)
601057
async def delete(self, device, remove=True):
        
        device = self._find_device(device)
        if not self.is_handleable(device) or not device.is_loop:
            self._log.warn(_('not deleting {0}: unhandled device', device))
            return False
        if remove:
            await self.auto_remove(device, force=True)
        self._log.debug(_('deleting {0}', device))
        await device.delete()
        self._log.info(_('deleted {0}', device))
        return True
1122263
def editMeasurement(self, measurementId, data):
        
        oldMeasurement = self.getMeasurement(measurementId, measurementStatus=MeasurementStatus.COMPLETE)
        if oldMeasurement:
            import copy
            newMeasurement = copy.deepcopy(oldMeasurement)
            deleteOld = False
            createdFilteredCopy = False
            newName = data.get('name', None)
            newDesc = data.get('description', None)
            newStart = float(data.get('start', 0))
            newEnd = float(data.get('end', oldMeasurement.duration))
            newDuration = newEnd - newStart
            newDevices = data.get('devices', None)
            if newName:
                logger.info('Updating name from ' + oldMeasurement.name + ' to ' + newName)
                newMeasurement.updateName(newName)
                createdFilteredCopy = True
                deleteOld = True
            if newDesc:
                logger.info('Updating description from ' + str(oldMeasurement.description) + ' to ' + str(newDesc))
                newMeasurement.description = newDesc
            if newDuration != oldMeasurement.duration:
                logger.info('Copying measurement to allow support new duration ' + str(newDuration))
                if oldMeasurement.name == newMeasurement.name:
                    newMeasurement.updateName(newMeasurement.name + '-' + str(int(time.time())))
                newMeasurement.duration = newDuration
                createdFilteredCopy = True
            if createdFilteredCopy:
                logger.info('Copying measurement data from ' + oldMeasurement.idAsPath + ' to ' + newMeasurement.idAsPath)
                newMeasurementPath = self._getPathToMeasurementMetaDir(newMeasurement.idAsPath)
                dataSearchPattern = self._getPathToMeasurementMetaDir(oldMeasurement.idAsPath) + '/**/data.out'
                newDataCountsByDevice = [self._filterCopy(dataFile, newStart, newEnd, newMeasurementPath)
                                         for dataFile in glob.glob(dataSearchPattern)]
                for device, count in newDataCountsByDevice:
                    newMeasurement.recordingDevices.get(device)['count'] = count
            self.store(newMeasurement)
            if newDevices:
                for renames in newDevices:
                    logger.info('Updating device name from ' + str(renames[0]) + ' to ' + str(renames[1]))
                    deviceState = newMeasurement.recordingDevices.get(renames[0])
                    newMeasurement.recordingDevices[renames[1]] = deviceState
                    del newMeasurement.recordingDevices[renames[0]]
                    os.rename(os.path.join(self._getPathToMeasurementMetaDir(newMeasurement.idAsPath), renames[0]),
                              os.path.join(self._getPathToMeasurementMetaDir(newMeasurement.idAsPath), renames[1]))
                self.store(newMeasurement)
            if deleteOld or createdFilteredCopy or newDevices:
                self.completeMeasurements.append(newMeasurement)
            if deleteOld:
                self.delete(oldMeasurement.id)
            return True
        else:
            return False
498310
public void setDeviceId(byte[] deviceId) {
    if (deviceId == null) {
      throw new RuntimeException("Device ID cannot be null.");
    }
    if (deviceId.length != DEVICE_ID_SIZE) {
      throw new RuntimeException(String.format(
          "Device ID must be %d bytes long.", Integer.valueOf(DEVICE_ID_SIZE)));
    }
    this.deviceId = deviceId;
  }
1037837
def put(self, measurementId, deviceId):
        
        data = request.get_json()
        if data is not None:
            parsedData = json.loads(data)
            logger.debug('Received payload ' + measurementId + '/' + deviceId + ': ' +
                         str(len(parsedData)) + ' records')
            if self._measurementController.recordData(measurementId, deviceId, parsedData):
                return None, 200
            else:
                logger.warning('Unable to record payload ' + measurementId + '/' + deviceId)
                return None, 404
        else:
            logger.error('Invalid data payload received ' + measurementId + '/' + deviceId)
            return None, 400
265385
def handle(self, data):
        
        if self.handler:
            state = self.handler(data)
            if state is None:
                return self.next_state
            return state
        return self.next_state