PollutionDevice.h 1.98 KB
#ifndef __POLLUTION_DEVICE_H__
#define __POLLUTION_DEVICE_H__

#include "mbed.h"

class PollutionDevice {
public:
    const static int length = 31;
    const static int baud = 9600;
    
    PollutionDevice(Serial *uart) : uart(uart), PM01Value(0), PM2_5Value(0), PM10Value(0) {}
    
    /*
     * Permet de savoir si on lit le début de la trame associée au GPS.
     */
    bool canBeRead() {
        return uart->readable() && uart->getc() == 0x42;
    }
    
    /*
     * Permet de lire la trame du capteur de pollution.
     */
    void read() {
        char buf[length];
        
        for(int i = 0; i < length; i++){ 
            buf[i]=uart->getc();
        } // full packet now in buffer.
        
        if(buf[0] == 0x4d){
          if(checkValue(buf, length)){
            PM01Value=((buf[3]<<8) + buf[4]); //count PM1.0 value of the air detector module
            PM2_5Value=((buf[5]<<8) + buf[6]);//count PM2.5 value of the air detector module
            PM10Value=((buf[7]<<8) + buf[8]); //count PM10 value of the air detector module  
          }           
        } 
    }
    
    int getPM01()
    {
      return PM01Value;
    }
    
    int getPM2_5()
    {
      return PM2_5Value;
    }
    
    int getPM10()
    {
      return PM10Value;
    }

private:
    Serial *uart;
    int PM01Value;          //define PM1.0 value of the air detector module
    int PM2_5Value;         //define PM2.5 value of the air detector module
    int PM10Value;         //define PM10 value of the air detector module
    
    bool checkValue(char *buffer, char length)
    {  
      bool flag = false;
      int sum = 0;
    
      for(int i = 0; i < (length - 2); i++){
        sum = sum + buffer[i];
      }
      sum = sum + 0x42; //0x42 : Le premier caractère qui n'est pas dans le buffer
     
      if(sum == ((buffer[length - 2] << 8) + buffer[length - 1]))  //check the serial data 
      {
        sum = 0;
        flag = true;
      }
      return flag;
    }
};

#endif /* #ifndef __POLLUTION_DEVICE_H__*/