/*
 * TEnergyMonitor.h
 *
 *  Created on: 07 apr 2018
 *      Author: Emanuele
 */

#ifndef TENERGYMONITOR_H_
#define TENERGYMONITOR_H_

#define ADC_BITS 	16
#define ADC_COUNTS 	(1<<ADC_BITS)
#define VSUPPLY		3300

#include "mbed.h"
#include "millis.h"

class TEnergyMonitor {

  public:
	TEnergyMonitor(Serial* _pc);

	void voltage(PinName _inPinV, double _VCAL, double _PHASECAL);
	void current(PinName _inPinI, double _ICAL);

	void voltageTX(double _VCAL, double _PHASECAL);
	void currentTX(unsigned int _channel, double _ICAL);

	void calcVI(unsigned int crossings, unsigned int timeout);
	double calcIrms(unsigned int NUMBER_OF_SAMPLES);
	void serialprint();

	long readVcc();
	//Useful value variables
	double realPower,
	   apparentPower,
	   powerFactor,
	   Vrms,
	   Irms;

  private:

	Serial* pc;

	//Set Voltage and current input pins
	PinName inPinV;
	PinName inPinI;
	AnalogIn *adcV;
	AnalogIn *adcI;
	//Calibration coefficients
	//These need to be set in order to obtain accurate results
	double VCAL;
	double ICAL;
	double PHASECAL;

	//--------------------------------------------------------------------------------------
	// Variable declaration for emon_calc procedure
	//--------------------------------------------------------------------------------------
	unsigned int sampleV;  							 //sample_ holds the raw analog read value
	unsigned int sampleI;

	double lastFilteredV,filteredV;          //Filtered_ is the raw analog value minus the DC offset
	double filteredI;
	double offsetV;                          //Low-pass filter output
	double offsetI;                          //Low-pass filter output

	double phaseShiftedV;                             //Holds the calibrated phase shifted voltage.

	double sqV,sumV,sqI,sumI,instP,sumP;              //sq = squared, sum = Sum, inst = instantaneous

	int startV;                                       //Instantaneous voltage at start of sample window.

	bool lastVCross, checkVCross;                  //Used to measure number of times threshold is crossed.


};

#endif /* TENERGYMONITOR_H_ */
