diff --git a/src/bh1750/bh1750.cxx b/src/bh1750/bh1750.cxx index 1adc1d5d..fec0454f 100644 --- a/src/bh1750/bh1750.cxx +++ b/src/bh1750/bh1750.cxx @@ -25,6 +25,7 @@ #include #include +#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 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); diff --git a/src/bh1750/bh1750.hpp b/src/bh1750/bh1750.hpp index 4c7bee87..5490b512 100644 --- a/src/bh1750/bh1750.hpp +++ b/src/bh1750/bh1750.hpp @@ -32,6 +32,7 @@ #include #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.