Esempio n. 1
0
def plugin_poll(handle):
    """ Poll readings from the modbus device and returns it in a JSON document as a Python dict.

    Available for poll mode only.

    Args:
        handle: handle returned by the plugin initialisation call
    Returns:
        returns a reading in a JSON document, as a Python dict, if it is available
        None - If no reading is available
    Raises:
        DataRetrievalError
    """

    try:

        readings = get_readings(handle)

        wrapper = {
            'asset': handle['assetName']['value'],
            'timestamp': utils.local_timestamp(),
            'key': str(uuid.uuid4()),
            'readings': readings
        }

    except Exception as ex:
        raise exceptions.DataRetrievalError(ex)
    else:
        return wrapper
Esempio n. 2
0
def plugin_poll(handle):
    _LOGGER.debug("coral-enviro plugin_poll")
    global _enviro
    try:
        time_stamp = utils.local_timestamp()
        readings = {}
        if handle['temperatureSensor']['value'] == 'true':
            readings['temperature'] = _enviro.temperature

        if handle['pressureSensor']['value'] == 'true':
            readings['pressure'] = _enviro.pressure

        if handle['humiditySensor']['value'] == 'true':
            readings['humidity'] = _enviro.humidity

        if handle['ambientLightSensor']['value'] == 'true':
            readings['ambient_light'] = _enviro.ambient_light

        if handle['groveAnalogSensor']['value'] == 'true':
            readings['grove_analog'] = _enviro.grove_analog

        wrapper = {
            'asset': handle['assetName']['value'],
            'timestamp': time_stamp,
            'readings': readings
        }
        return wrapper
    except Exception as ex:
        _LOGGER.exception("coral-enviro exception: {}".format(str(ex)))
        raise exceptions.DataRetrievalError(ex)
Esempio n. 3
0
def get_readings(handle):
    """ Get readings from DNP3 master and process needed registers to return readings as a Python dict.

    Available for poll mode only.

    Args:
        handle: handle returned by the plugin initialisation call
    Returns:
        returns readings as a Python dict
        None - If no reading is available
    Raises:
        DataRetrievalError
    """

    # The DNP3 master will stay open receiving unsolicited updates continuously after the plugin initializes
    global master

    # If the DNP3 master has not been initialized, open it with the configured parameters
    if master is None:
        master = open_dnp3_master(handle)
        time.sleep(10)

    # DNP3 register offsets for the variables we are concerned with for this plugin
    AMBIENT_TEMP_OFFSET = 76
    LTC_TANK_TEMP_OFFSET = 120
    TOP_OIL_TEMP_OFFSET = 150

    try:
        all_dnp3_readings = master.values

        # Assemble the readings using the registers that we are concerned about. Apply scaling factor.
        readings = {
            'ambient_temp':
            all_dnp3_readings['analog'][AMBIENT_TEMP_OFFSET] / 1000,
            'top_oil_temp':
            all_dnp3_readings['analog'][TOP_OIL_TEMP_OFFSET] / 1000,
            'ltc_ttank_temp':
            all_dnp3_readings['analog'][LTC_TANK_TEMP_OFFSET] / 1000
        }

    except Exception as ex:
        raise exceptions.DataRetrievalError(ex)

    return readings
Esempio n. 4
0
async def _start_aiotest(handle):
    # This plugin adds 6 data points 2 within same min, 2 within same hour and 2 within same day
    # this data is useful when testing asset browsing based on timestamps
    ts_lst = list()
    ts_lst.append(str(datetime.now(timezone.utc).astimezone()))
    ts_lst.append(
        str(datetime.now(timezone.utc).astimezone() - timedelta(seconds=3)))
    ts_lst.append(
        str(datetime.now(timezone.utc).astimezone() - timedelta(minutes=5)))
    ts_lst.append(
        str(datetime.now(timezone.utc).astimezone() - timedelta(minutes=6)))
    ts_lst.append(
        str(datetime.now(timezone.utc).astimezone() - timedelta(hours=3)))
    ts_lst.append(
        str(datetime.now(timezone.utc).astimezone() - timedelta(hours=5)))

    i = 1
    for user_ts in ts_lst:
        try:
            data = list()
            data.append({
                'asset':
                '{}{}'.format(handle['assetPrefix']['value'],
                              handle['loudnessAssetName']['value']),
                'timestamp':
                user_ts,
                'key':
                str(uuid.uuid4()),
                'readings': {
                    "loudness": i
                }
            })
            async_ingest.ingest_callback(c_callback, c_ingest_ref, data)
            await asyncio.sleep(0.1)

        except (Exception, RuntimeError) as ex:
            _LOGGER.exception("TEST exception: {}".format(str(ex)))
            raise exceptions.DataRetrievalError(ex)
        else:
            i += 1
def plugin_poll(handle):
    """ Extracts data from the sensor and returns it in a JSON document as a Python dict.
    Available for poll mode only.
    Args:
        handle: handle returned by the plugin initialisation call
    Returns:
        returns a sensor reading in a JSON document, as a Python dict, if it is available
        None - If no reading is available
    Raises:
        TimeoutError
    """
    # air quality is voltage reading between 0 and 5.1
    # we scale is to a value between 0 and 1023
    try:
        time_stamp = utils.local_timestamp()
        data = list()
        if handle['tempHumEnable']['value'] == 'true' and handle[
                'tempHumCount'] == 0:
            data.append({
                'asset':
                '{}{}'.format(handle['assetPrefix']['value'],
                              handle['tempHumAssetName']['value']),
                'timestamp':
                time_stamp,
                'readings': {
                    "temperature": handle['temperature'].getTemperature(),
                    "humidity": handle['humidity'].getHumidity()
                }
            })

        if handle['currentEnable']['value'] == 'true' and handle[
                'currentCount'] == 0:
            data.append({
                'asset':
                '{}{}'.format(handle['assetPrefix']['value'],
                              handle['currentAssetName']['value']),
                'timestamp':
                time_stamp,
                'readings': {
                    "current": handle['current'].getCurrent()
                }
            })

        if handle['encoderEnable']['value'] == 'true' and handle[
                'encoderCount'] == 0:
            value = handle['encoder'].getPosition()
            # convert time_stamp to be usable
            if ":" == time_stamp[-3:-2]:
                timestamp_new = datetime.datetime.strptime(
                    time_stamp[:-3] + time_stamp[-2:],
                    '%Y-%m-%d %H:%M:%S.%f%z')
            else:
                timestamp_new = datetime.datetime.strptime(
                    time_stamp, '%Y-%m-%d %H:%M:%S.%f%z')

            if handle['encoderPreviousValue'] > 0:  # omit first one
                # calculate elapse time in milliseconds
                elapse_time = timestamp_new - handle['encoderPreviousTime']
                elapse_time = elapse_time.total_seconds()
                data.append({
                    'asset':
                    '{}{}'.format(handle['assetPrefix']['value'],
                                  handle['encoderAssetName']['value']),
                    'timestamp':
                    time_stamp,
                    'readings': {
                        # (current_total_iterations - previous_total_iterations) / (elapsed time in seconds)
                        "rotation-per-second":
                        ((value - handle['encoderPreviousValue']) / 1200) /
                        elapse_time
                    }
                })
            # update old values
            handle['encoderPreviousValue'] = value
            handle['encoderPreviousTime'] = timestamp_new

        if handle['accelerometerEnable']['value'] == 'true' and handle[
                'accelerometerCount'] == 0:
            x, y, z = handle['accelerometer'].getAcceleration()
            data.append({
                'asset':
                '{}{}'.format(handle['assetPrefix']['value'],
                              handle['accelerometerAssetName']['value']),
                'timestamp':
                time_stamp,
                'readings': {
                    "accelerometer-x": x,
                    "accelerometer-y": y,
                    "accelerometer-z": z
                }
            })

        if handle['gyroscopeEnable']['value'] == 'true' and handle[
                'gyroscopeCount'] == 0:
            x, y, z = handle['gyroscope'].getAngularRate()
            data.append({
                'asset':
                '{}{}'.format(handle['assetPrefix']['value'],
                              handle['gyroscopeAssetName']['value']),
                'timestamp':
                time_stamp,
                'readings': {
                    "gyroscope-x": x,
                    "gyroscope-y": y,
                    "gyroscope-z": z
                }
            })

        if handle['magnetometerEnable']['value'] == 'true' and handle[
                'magnetometerCount'] == 0:
            x, y, z = handle['magnetometer'].getMagneticField()
            data.append({
                'asset':
                '{}{}'.format(handle['assetPrefix']['value'],
                              handle['magnetometerAssetName']['value']),
                'timestamp':
                time_stamp,
                'readings': {
                    "magnetometer-x": x,
                    "magnetometer-y": y,
                    "magnetometer-z": z
                }
            })

        handle['tempHumCount'] = (handle['tempHumCount'] + 1) % int(
            handle['tempHumPoll']['value'])
        handle['currentCount'] = (handle['currentCount'] + 1) % int(
            handle['currentPoll']['value'])
        handle['encoderCount'] = (handle['encoderCount'] + 1) % int(
            handle['encoderPoll']['value'])
        handle['accelerometerCount'] = (
            handle['accelerometerCount'] + 1) % int(
                handle['accelerometerPoll']['value'])
        handle['gyroscopeCount'] = (handle['gyroscopeCount'] + 1) % int(
            handle['gyroscopePoll']['value'])
        handle['magnetometerCount'] = (handle['magnetometerCount'] + 1) % int(
            handle['magnetometerPoll']['value'])

    except (Exception, RuntimeError) as ex:
        _LOGGER.exception("wind_turbine exception: {}".format(str(ex)))
        raise exceptions.DataRetrievalError(ex)
    else:
        return data
Esempio n. 6
0
def plugin_poll(handle):
    """ Extracts data from the sensor and returns it in a JSON document as a Python dict.

    Available for poll mode only.

    Args:
        handle: handle returned by the plugin initialisation call
    Returns:
        returns a sensor reading in a JSON document, as a Python dict, if it is available
        None - If no reading is available
    Raises:
        DataRetrievalError
    """
    try:
        bus = handle["bus"]
        i2c_address = handle['i2cAddress']['value']

        sensor_add = hex(int(i2c_address, 16))
        start_add = 0x00
        function_code = 0x03
        register_number = 0x04
        response_bytes = 8
        attempt_threshold = 50
        asset_name = '{}'.format(handle['assetName']['value']).replace('%M', i2c_address)

        try:
            # wake up call
            bus.write_i2c_block_data(sensor_add, function_code, [start_add, register_number])
        except Exception as e:
            # expected exception as sensor is sleeping
            pass
        # request data
        bus.write_i2c_block_data(sensor_add, function_code, [start_add, register_number])
        # read data 
        sensor_response = bytearray(bus.read_i2c_block_data(sensor_add, function_code, response_bytes))
        # temperature
        temperature= (sensor_response[4] * 256 + sensor_response[5])/10
        # humidity
        humidity= (sensor_response[2] * 256 + sensor_response[3])/10
        # crc
        crc = sensor_response[7] * 256 + sensor_response[6]
        # calc crc to verify
        calc_crc = 0xFFFF
        for byte in sensor_response[0:6]:
            calc_crc = calc_crc ^ byte
            for i in range(1,9):
                if(calc_crc & 0x01):
                    calc_crc = calc_crc >> 1
                    calc_crc = calc_crc ^ 0xA001
                else:
                    calc_crc = calc_crc >> 1
        if calc_crc != crc:
            pass
        time_stamp = utils.local_timestamp()
        data = {
            'asset': asset_name,
            'timestamp': time_stamp,
            'readings': {
                "temperature": temperature,
                "humidity": humidity
            }
        }
    except (Exception, RuntimeError) as ex:
        _LOGGER.exception("AM2315 exception: {}".format(str(ex)))
        raise exceptions.DataRetrievalError(ex)

    return data