aboutsummaryrefslogtreecommitdiff
path: root/datalog.h
blob: da715e8e9545f6f7fcb9f3c38c6571c97dc2635a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#pragma once
 
#include <mySD.h>
 
#include "data.h"
 
const int mySD_CS=13;
const int mySD_SCLK=14;
const int mySD_MISO=2;
const int mySD_MOSI=15;
 
//                      12345, 12345, 12345, 12345, 123456, 123456, 123456, 123456, 12345\n 
const char csvHeader[]=" secs,   co2,  temp, humid,    pm1,  pm2.5,    pm4,   pm10,  batt\n";
const char csvFormat[]="% 5lu% 5u% 5.1f% 5.1f% 6.1f% 6.1f% 6.1f% 6.1f% 5.2f\n";
const size_t lineLength=66;
 
class DataLog {
private:
  File logfile;
  char line[100];
  uint8_t linesSinceLastFlush;
  uint8_t flushThreshold;
public:
  DataLog(uint8_t ft=4) : flushThreshold(ft) {}
 
  void start() {
    bool sdok=SD.begin(mySD_CS, mySD_MOSI, mySD_MISO, mySD_SCLK);
    Serial.print("sdok: ");Serial.println(sdok);
    logfile = SD.open("quality.csv",FILE_WRITE);
    Serial.print("file: ");Serial.println(logfile.name());
    uint32_t fileSize = logfile.size();
    logfile.seek(fileSize);
    if (fileSize == 0{
      logfile.write((uint8_t*)csvHeader, lineLength);
    }                    
    linesSinceLastFlush=1;
  }
 
  void show(const SensorData *data) {
    snprintf(
             line, lineLength+1// zero terminator! 
             csvFormat,
             millis()/1000,
 
             data->co2,
             data->temperature,
             data->humidity,
 
             data->pm.mc_1p0,
             max(0.0f,data->pm.mc_2p5 - data->pm.mc_1p0),
             max(0.0f,data->pm.mc_4p0 - data->pm.mc_2p5),
             max(0.0f,data->pm.mc_10p0 - data->pm.mc_4p0),
 
             data->batteryVoltage
             );
    size_t written=logfile.write((uint8_t *)line,lineLength);
    Serial.write(line);
    Serial.print("written: ");Serial.println(written);
    if (++linesSinceLastFlush > flushThreshold) {
      logfile.flush();
      linesSinceLastFlush=0;
 
      Serial.println("flushed");
    }
  }
};