BH1750: Add string based constructor

Signed-off-by: Adelin Dobre <adelin.dobre@rinftech.com>
Signed-off-by: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
This commit is contained in:
Adelin Dobre 2018-07-13 14:47:42 +03:00 committed by Mihai Tudor Panu
parent 87dc660bd6
commit 742150feea
2 changed files with 73 additions and 0 deletions

View File

@ -25,6 +25,7 @@
#include <iostream>
#include <stdexcept>
#include "upm_string_parser.hpp"
#include "bh1750.hpp"
using namespace upm;
@ -38,6 +39,69 @@ BH1750::BH1750(int bus, int addr, BH1750_OPMODES_T mode) :
": bh1750_init() failed");
}
BH1750::BH1750(std::string initStr) : mraaIo(initStr)
{
mraa_io_descriptor* descs = mraaIo.getMraaDescriptors();
std::vector<std::string> upmTokens;
if(!mraaIo.getLeftoverStr().empty()) {
upmTokens = UpmStringParser::parse(mraaIo.getLeftoverStr());
}
// make sure MRAA is initialized
int mraa_rv;
if ((mraa_rv = mraa_init()) != MRAA_SUCCESS)
{
throw std::runtime_error(std::string(__FUNCTION__) +
": mraa_init() failed");
}
m_bh1750 = (bh1750_context)malloc(sizeof(struct _bh1750_context));
if(!m_bh1750)
throw std::runtime_error(std::string(__FUNCTION__) +
": bh1750_init() failed");
m_bh1750->is_continuous = false;
// init the i2c context
if(!descs->i2cs)
{
throw std::runtime_error(std::string(__FUNCTION__) +
": mraa_i2c_init() failed");
}
else
{
if( !(m_bh1750->i2c = descs->i2cs[0]) )
{
free(m_bh1750);
throw std::runtime_error(std::string(__FUNCTION__) +
": mraa_i2c_init() failed");
}
}
for (std::string tok : upmTokens)
{
if(tok.substr(0, 5) == "mode:") {
BH1750_OPMODES_T mode = (BH1750_OPMODES_T)std::stoi(tok.substr(5),nullptr,0);
if(bh1750_set_opmode(m_bh1750, mode) != UPM_SUCCESS)
{
bh1750_close(m_bh1750);
throw std::runtime_error(std::string(__FUNCTION__) +
": bh1750_init() failed");
}
}
if(tok.substr(0, 8) == "powerUp:") {
powerUp();
}
if(tok.substr(0, 10) == "powerDown:") {
powerDown();
}
if(tok.substr(0, 12) == "sendCommand:") {
uint8_t mode = (uint8_t)std::stoi(tok.substr(12),nullptr,0);
sendCommand(mode);
}
}
}
BH1750::~BH1750()
{
bh1750_close(m_bh1750);

View File

@ -32,6 +32,7 @@
#include <interfaces/iLight.hpp>
#include "bh1750.h"
#include "mraa/initio.hpp"
namespace upm {
/**
@ -73,6 +74,13 @@ namespace upm {
BH1750(int bus=BH1750_DEFAULT_I2C_BUS, int addr=BH1750_DEFAULT_I2C_ADDR,
BH1750_OPMODES_T mode=BH1750_OPMODE_H2_ONCE);
/**
* Instantiates BH1750 Light Sensor object based on a given string.
*
* @param initStr string containing specific information for BH1750 initialization.
*/
BH1750(std::string initStr);
/**
* BH1750 object destructor
*/
@ -120,6 +128,7 @@ namespace upm {
protected:
// bh1750 device context
bh1750_context m_bh1750;
mraa::MraaIo mraaIo;
/**
* Sends a command to the device via I2C.