PollutionService.h 2.53 KB
#ifndef __BLE_POLLUTION_SERVICE_H__
#define __BLE_POLLUTION_SERVICE_H__

#include "BLEDevice.h"

/* Pollution Service */
class PollutionService {
public:
    const static uint16_t UUID_POLLUTION_SERVICE             = 0xA000;
    const static uint16_t UUID_POLLUTION_LEVEL_CHAR          = 0xA001;
    const static uint16_t UUID_TEMPERATURE_CHAR = 0x2A6E;
    
    typedef int16_t  TemperatureType_t;
    typedef uint8_t  PollutionLevelType_t;
    
    PollutionService(BLEDevice &_ble, PollutionLevelType_t level) :
        ble(_ble),
        pollutionLevel(level),
        pollutionLevelCharacteristic(UUID_POLLUTION_LEVEL_CHAR, &pollutionLevel, sizeof(pollutionLevel), sizeof(pollutionLevel),
                                   GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY),
        temperatureCharacteristic(UUID_TEMPERATURE_CHAR, &temperature, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) {

        static bool serviceAdded = false; /* We should only ever need to add the service once. */
        if (serviceAdded) {
            return;
        }

        GattCharacteristic *charTable[] = {&pollutionLevelCharacteristic,
                                           &temperatureCharacteristic };
        GattService         pollutionService(UUID_POLLUTION_SERVICE, charTable, sizeof(charTable) / sizeof(GattCharacteristic *));

        ble.addService(pollutionService);
        serviceAdded = true;
    }

    /**
     * Update the pollution level with a new value. Valid values range from
     * 0..100. Anything outside this range will be ignored.
     * @param newLevel New level.
     */
    void updatePollutionLevel(uint8_t newLevel) {
        pollutionLevel = newLevel;
        ble.updateCharacteristicValue(pollutionLevelCharacteristic.getValueAttribute().getHandle(), &pollutionLevel, 1);
    }
    
    /**
     * @brief   Update temperature characteristic.
     * @param   newTemperatureVal New temperature measurement.
     */
    void updateTemperature(double newTemperatureVal)
    {
        temperature = (TemperatureType_t) (newTemperatureVal * 100);
        ble.updateCharacteristicValue(temperatureCharacteristic.getValueHandle(), (uint8_t *) &temperature, sizeof(TemperatureType_t));
    }
    

private:
    BLEDevice           &ble;
    
    TemperatureType_t temperature;
    PollutionLevelType_t pollutionLevel;
    
    GattCharacteristic   pollutionLevelCharacteristic;
    ReadOnlyGattCharacteristic<TemperatureType_t> temperatureCharacteristic;
};

#endif /* #ifndef __BLE_POLLUTION_SERVICE_H__*/