Example #1
0
class Note(uorm.Model):

    __db__ = db
    __table__ = "note"
    __schema__ = OrderedDict([
        ("id", ("INT", uorm.id)),
        ("timestamp", ("TIMESTAMP", uorm.now)),
        ("archived", ("INT", 0)),
        ("content", ("TEXT", "")),
    ])

    @classmethod
    def public(cls):
        print("public")
        for v in cls.__db__.db.values(None, None, btree.DESC):
            res = ujson.loads(v)
            row = cls.Row(*res)
            if row.archived:
                continue
            yield row

    @classmethod
    def get_keys(cls):
        keys = []
        for key in cls.__db__.db:
            keys.append(key)
        return keys

    @classmethod
    def del_key(cls, key):
        del cls.__db__.db[key]
        cls.__db__.db.flush()
        return 0
Example #2
0
    def __init__(self, bus, reset_pin=None, default_address=True, declination=(0, 0)):
        self.i2c = pyb.I2C(bus, pyb.I2C.MASTER)
        if reset_pin is not None:
            self.reset_pin = pyb.Pin(reset_pin, pyb.Pin.OUT_PP)
        else:
            self.reset_pin = reset_pin

        if default_address:
            self.address = 0x28
        else:
            self.address = 0x29

        self.declination = (declination[0] + declination[1] / 60) * math.pi / 180

        self.quat_scale = 1.0 / (1 << 14)
        self.sample_delay = 100

        self.default_mode = self.modes["NDOF"]

        self.offsets = OrderedDict(
            accel_offset_x=0,
            accel_offset_y=0,
            accel_offset_z=0,
            mag_offset_x=0,
            mag_offset_y=0,
            mag_offset_z=0,
            gyro_offset_x=0,
            gyro_offset_y=0,
            gyro_offset_z=0,
            accel_radius=0,
            mag_radius=0,
        )
        self.init_sensor()
Example #3
0
File: db.py Project: sassod/uPyEasy
class ruleTable(uorm.Model):

    # Create script table
    __db__ = _dbc
    __table__ = "rule"
    __schema__ = OrderedDict([
        ("timestamp", uorm.now),
        ("id",  1),
        ("enable", "off"),
        ("name", ""),
        ("filename", ""),
        ("delay",  60),
    ])

    @classmethod
    def mapkeys(cls, obj):
        return [obj.get(k) for k in cls.__schema__.keys()]

    @classmethod
    def public(cls):
        res = [x for x in cls.get()]
        return res

    @classmethod
    def getrow(cls):
        res = next(cls.get())
        return res

    @classmethod
    def list(cls):
        res = [x for x in cls.scan()]
        return res.values
                
Example #4
0
File: db.py Project: sassod/uPyEasy
class serviceTable(uorm.Model):

    # Create service table
    __db__ = _dbc
    __table__ = "service"
    __schema__ = OrderedDict([
        ("timestamp", uorm.now),
        ("id",  1),
        ("name", ""),
        ("server", ""),
        ("port", ""),
        ("template", ""),        
    ])

    @classmethod
    def mapkeys(cls, obj):
        return [obj.get(k) for k in cls.__schema__.keys()]

    @classmethod
    def public(cls):
        res = [x for x in cls.get()]
        return res
        
    @classmethod
    def getrow(cls):
        res = next(cls.get())
        return res

    @classmethod
    def list(cls):
        res = [x for x in cls.scan()]
        return res
Example #5
0
File: db.py Project: sassod/uPyEasy
class pluginstoreTable(uorm.Model):

    # Create plugin table
    __db__ = _dbc
    __table__ = "pluginstore"
    __schema__ = OrderedDict([
        ("timestamp", uorm.now),
        ("name", ""),
        ("data", ""),        
    ])

    @classmethod
    def mapkeys(cls, obj):
        return [obj.get(k) for k in cls.__schema__.keys()]

    @classmethod
    def public(cls):
        res = [x for x in cls.get()]
        return res
        
    @classmethod
    def getrow(cls):
        res = next(cls.get())
        return res

    @classmethod
    def list(cls):
        res = [x for x in cls.scan()]
        return res.values
Example #6
0
File: db.py Project: sassod/uPyEasy
class notificationTable(uorm.Model):

    # Create notification table
    __db__ = _dbc
    __table__ = "notification"
    __schema__ = OrderedDict([
        ("timestamp", uorm.now),
        ("id",  1),
        ("serviceid",  1),
        ("enable", ""),
    ])

    @classmethod
    def mapkeys(cls, obj):
        return [obj.get(k) for k in cls.__schema__.keys()]

    @classmethod
    def public(cls):
        res = [x for x in cls.get()]
        return res
        
    @classmethod
    def getrow(cls):
        res = next(cls.get())
        return res

    @classmethod
    def list(cls):
        res = [x for x in cls.scan()]
        return res
Example #7
0
def init_db(umod):

    tb_name = "board_cfg"
    tb_schema = OrderedDict([("name", ""), ("board", ""), ("uid", ""),
                             ("client", ""), ("init", 0)])

    umod.mod_add(tb_name, tb_schema)

    tb_name = "board_mod"
    tb_schema = OrderedDict([
        ("name", ""),
        ("active", ""),
        ("status", ""),
    ])

    umod.mod_add(tb_name, tb_schema)
Example #8
0
class LoginData(uorm.Model):

    __db__ = db
    __table__ = "login"
    __schema__ = OrderedDict([
        ("timestamp", ("TIMESTAMP", uorm.now)),
        ("archived", ("INT", 0)),
        ("username", ("TEXT", "")),
        ("password", ("TEXT", "")),
        ("email", ("TEXT", "")),
        ("street", ("TEXT", "")),
        ("city", ("TEXT", "")),
        ("postcode", ("TEXT", "")),
        ("country", ("TEXT", "")),
        ("mobile", ("TEXT", "")),
        ("content", ("TEXT", "")),
    ])

    @classmethod
    def mapkeys(cls, obj):
        return [obj.get(k) for k in cls.__schema__.keys()]

    @classmethod
    def public(cls):
        res = [x for x in cls.scan() if x.archived == 0]
        res.sort(key=lambda x: x.timestamp, reverse=True)
        return res
Example #9
0
 def save(self, ordered=False):
     # dump updated setting into json
     print("Writing new config item to file %s" % self.file)
     with open(self.file, 'w') as f:
         if ordered:
             ujson.dump(self.config, f)
         else:
             ujson.dump(OrderedDict(self.config), f)
Example #10
0
class dxmapTable(uorm.Model):

    # Create dxpin table
    __db__ = _dbc
    __table__ = "dxmap"
    __schema__ = OrderedDict([
        ("timestamp", uorm.now),
        ("count", 0),
        ("d0", ""),
        ("d1", ""),
        ("d2", ""),
        ("d3", ""),
        ("d4", ""),
        ("d5", ""),
        ("d6", ""),
        ("d7", ""),
        ("d8", ""),
        ("d9", ""),
        ("d10", ""),
        ("d11", ""),
        ("d12", ""),
        ("d13", ""),
        ("d14", ""),
        ("d15", ""),
        ("d16", ""),
        ("d17", ""),
        ("d18", ""),
        ("d19", ""),
        ("d20", ""),
        ("d21", ""),
        ("d22", ""),
        ("d23", ""),
        ("d24", ""),
        ("d25", ""),
        ("d26", ""),
        ("d27", ""),
        ("d28", ""),
        ("d29", ""),
        ("d30", ""),
        ("d31", ""),
        ("d32", ""),
        ("d33", ""),
        ("d34", ""),
        ("d35", ""),
        ("d36", ""),
        ("d37", ""),
        ("d38", ""),
        ("d39", ""),
        ("d40", ""),
    ])

    @classmethod
    def getrow(cls):
        try:
            res = next(cls.get())
        except StopIteration:
            return None
        return res
Example #11
0
def init_db(umod):

    tb_name = "cfg_telnet"
    tb_schema = OrderedDict([
        ("name", ""),
        ("port", ""),
        ("pswd", ""),
    ])

    umod.mod_add(tb_name, tb_schema, active="1", up="ap")
Example #12
0
def init_db(umod):

    tb_name = "board_pin"
    tb_schema = OrderedDict([
        ("name", ""),
        ("npin", ""),
        ("bpin", "")
    ])

    umod.mod_add(tb_name, tb_schema, active="1", up="main")
Example #13
0
    def mod_get(self, m_name):
        self.tbl_add()
        if self._tbl == m_name:
            return True

        s_mod = self.mod_sel(m_name)
        if len(s_mod):
            self.tbl_add(s_mod[0]["name"], OrderedDict(s_mod[0]["sch"]))
            return True
        return False
    def __init__(self, store_path="u_config"):

        _sch_name = "_schema"
        _sch_conf = OrderedDict([
            ("name", ("str", "")),
            ("sch", ("dict", ())),
        ])

        self.store = uorm.Store(store_schema=_sch_name, store_path=store_path, store_config=_sch_conf)
        self.lock = asyncio.Lock()
Example #15
0
def init_db(umod):

    tb_name = "cfg_mqtt"
    tb_schema = OrderedDict([
        ("name", ""),
        ("type", ""),
        ("ip", ""),
        ("port", ""),
    ])

    umod.mod_add(tb_name, tb_schema, active="1", up="sta")
Example #16
0
    def mod_get(self, m_name):
        self.tbl_add()
        if self._tbl == m_name:
            return self._sch

        s_mod = self.mod_sel(m_name)
        if len(s_mod):
            sch = OrderedDict(s_mod[0]["sch"])
            self.tbl_add(s_mod[0]["name"], sch)
            return sch
        return False
Example #17
0
def UNION(fields):
    res = OrderedDict()
    off = 0
    for k, t in fields.items():
        if isinstance(t, tuple):
            assert t[0] == 0
            res[k] = (off, t[1])
        else:
            res[k] = off | t
        off = uctypes.PREV_OFFSET
    return res
Example #18
0
    def __init__(self, db="u_db"):

        self.db = uorm.DB(db)
        self.model = uorm.Model
        self.model.__db__ = self.db

        self._tbl = "modules"
        self._sch = OrderedDict([
            ("name", ""),
            ("sch", ""),
            ("active", ""),
            ("up", ""),
        ])
Example #19
0
def init_db(umod):


    tb_name= "cfg_wifi_sta"
    tb_schema = OrderedDict([
        ("name", ""),
        ("ssid", ""),
        ("passwd", ""),
    ])

    umod.mod_add(tb_name, tb_schema)

    tb_name= "cfg_wifi_ap"
    tb_schema = OrderedDict([
        ("name", ""),
        ("essid", ""),
        ("channel", ""),
        ("password", ""),
        ("authmode", ""),
    ])

    umod.mod_add(tb_name, tb_schema)
Example #20
0
class advancedTable(uorm.Model):

    # Create advanced table
    __db__ = _dbc
    __table__ = "advanced"
    __schema__ = OrderedDict([
        ("timestamp", uorm.now),
        ("scripts", "off"),
        ("rules", "off"),
        ("notifications", "off"),
        ("mqttretain", ""),
        ("messagedelay", 0),
        ("ntphostname", "pool.ntp.org"),
        ("ntptimezone", 60),
        ("ntpdst", ""),
        ("sysloghostname", ""),
        ("sysloglevel", 0),
        ("serialloglevel", 1),
        ("webloglevel", 0),
        ("webloglines", 10),
        ("enablesdlog", ""),
        ("sdloglevel", 0),
        ("enableserial", ""),
        ("serialbaudrate", 115200),
        ("enablesync", ""),
        ("syncport", 8888),
        ("fixedipoctet", 0),
        ("wdi2caddress", 0),
        ("usessdp", ""),
        ("connectfailure", 0),
        ("i2cstretchlimit", 0),
    ])

    @classmethod
    def mapkeys(cls, obj):
        return [obj.get(k) for k in cls.__schema__.keys()]

    @classmethod
    def public(cls):
        res = [x for x in cls.get()]
        return res

    @classmethod
    def getrow(cls):
        res = next(cls.get())
        return res

    @classmethod
    def list(cls):
        res = [x for x in cls.scan()]
        return res
Example #21
0
def adc_gen(pin, delay=None):
    sample = 0
    adc = pyb.ADC(pin)
    ms_time = utime.ticks_ms()
    while True:
        if (delay is None) or (utime.ticks_diff(utime.ticks_ms(), ms_time) >
                               delay):
            ms_time = utime.ticks_ms()
            value = adc.read()
            hist = OrderedDict()
            hist['#'] = sample
            hist['adc'] = value
            yield (sample, value, hist)
            sample += 1
Example #22
0
def init_db(umod):

    tb_name = "cfg_push"
    tb_schema = OrderedDict([
        ("name", ""),
        ("b_pin", ""),
        ("p_on", ""),
        ("p_mode", ""),
        ("p_pull", ""),
        ("ps_mode", ""),
        ("ps_pin", ""),
        ("value", ""),
    ])

    umod.mod_add(tb_name, tb_schema, active="1", up="main")
Example #23
0
    def __init__(self,
                 bus,
                 reset_pin=None,
                 default_address=True,
                 declination=(0, 0)):
        self.i2c = pyb.I2C(bus, pyb.I2C.MASTER)
        if reset_pin is not None:
            self.reset_pin = pyb.Pin(reset_pin, pyb.Pin.OUT_PP)
        else:
            self.reset_pin = reset_pin

        if default_address:
            self.address = 0x28
        else:
            self.address = 0x29

        self.declination = \
            (declination[0] + declination[1] / 60) * math.pi / 180

        self.quat_scale = 1.0 / (1 << 14)
        self.sample_delay = 100

        self.default_mode = self.modes['NDOF']

        self.offsets = OrderedDict(accel_offset_x=0,
                                   accel_offset_y=0,
                                   accel_offset_z=0,
                                   mag_offset_x=0,
                                   mag_offset_y=0,
                                   mag_offset_z=0,
                                   gyro_offset_x=0,
                                   gyro_offset_y=0,
                                   gyro_offset_z=0,
                                   accel_radius=0,
                                   mag_radius=0)
        self.init_sensor()
 def generator(self, delay=None):
     """Return a generator 
     """
     sample = 0
     ms_time = utime.ticks_ms()
     while True:
         if (delay is None) or (utime.ticks_diff(utime.ticks_ms(), ms_time)
                                > delay):
             ms_time = utime.ticks_ms()
             value = self.range
             hist = OrderedDict()
             hist['#'] = sample
             hist['mm'] = value
             yield (sample, value, hist)
             sample += 1
Example #25
0
class controllerTable(uorm.Model):

    # Create controller table
    __db__ = _dbc
    __table__ = "controller"
    __schema__ = OrderedDict([
        ("timestamp", uorm.now),
        ("id", 1),
        ("usedns", ""),
        ("hostname", ""),
        ("port", 1883),
        ("user", ""),
        ("password", ""),
        ("subscribe", ""),
        ("publish", ""),
        ("enable", ""),
        ("protocol", ""),
    ])

    @classmethod
    def public(cls):
        # if cached: return cached table
        if hasattr(cls, '_controller'): return cls._controller
        # no cache: fetch it!
        try:
            cls._controller = [x for x in cls.get()]
        except StopIteration:
            return None
        return cls._controller

    @classmethod
    def getrow(cls):
        try:
            res = next(cls.get())
        except StopIteration:
            return None
        return res

    @classmethod
    def delete(cls, timestamp):
        # delete the table record
        try:
            os.remove(cls.fname(timestamp))
            # if cached: delete cached table
            if hasattr(cls, '_controller'): del cls._controller
        except KeyError:
            return False
        return True
Example #26
0
class pluginTable(uorm.Model):

    # Create plugin table
    __db__ = _dbc
    __table__ = "plugin"
    __schema__ = OrderedDict([
        ("timestamp", uorm.now),
        ("id", 1),
        ("name", ""),
        ("dtype", ""),
        ("stype", ""),
        ("pincnt", 1),
        ("valuecnt", 1),
        ("senddata", ""),
        ("formula", ""),
        ("sync", ""),
        ("timer", ""),
        ("pullup", ""),
        ("inverse", ""),
        ("port", ""),
        ("module", ""),
        ("template", ""),
    ])

    @classmethod
    def public(cls):
        try:
            res = [x for x in cls.get()]
        except StopIteration:
            return None
        return res

    @classmethod
    def getrow(cls):
        try:
            res = next(cls.get())
        except StopIteration:
            return None
        return res

    @classmethod
    def delete(cls, timestamp):
        # delete the table record
        try:
            os.remove(cls.fname(timestamp))
        except KeyError:
            return False
        return True
def adc_gen_burst(pin, delay=None):
    buf = bytearray(500)  # create a buffer of 100 bytes
    sample = 0
    start = utime.ticks_ms()
    tim = pyb.Timer(4, freq=100)
    adc = pyb.ADC(pin)
    while True:
        adc.read_timed(buf, tim)
        for val in buf:  # loop over all values
            value = adc.read()
            hist = OrderedDict()
            hist['#'] = sample
            hist['adc'] = value
            hist['ms'] = utime.ticks_diff(utime.ticks_ms(), start)
            yield (sample, value, hist)
            sample += 1
Example #28
0
class WifiAPModel(BaseModel):
    __table__ = "wifiap"
    __schema__ = OrderedDict([
        ("created_at", str(int(utime.time()))),
        ("channel", 11),
        ("hidden", False),
        ("authmode", 4),
        ("essid", "geekgarden"),
        ("password", "mysupersecretpass"),
        ("hostname", "geekgarden"),
        ("ip", "192.168.10.1"),
        ("mask", "255.255.255.0"),
        ("gateway", "192.168.10.1"),
        ("dns", "8.8.8.8"),
    ])
    __fields__ = list(__schema__.keys())
Example #29
0
def cdf_cal(time_list):
    """ Calculates the cdf for the time delay
    :param list: the list of times
    """
    results_sum = OrderedDict()
    for time in time_list:
        print("time:{}".format(time))
        round_time = round(time, 3)
        print("round_time:{}".format(round_time))
        if round_time in results_sum:
            results_sum[round_time] += 1
        else:
            results_sum[round_time] = 1
        #print("results_sum -> {}".format(results_sum))

    for time_delay in results_sum:
        results_sum[time_delay] = results_sum[time_delay] / len(time_list)
Example #30
0
 def generator(self, delay=50):
     """Return a generator
     """
     sample = 0
     ms_time = utime.ticks_ms()
     while True:
         if (delay is None) or (utime.ticks_diff(utime.ticks_ms(), ms_time)
                                > delay):
             ms_time = utime.ticks_ms()
             value = self.range  # preserve the value of the measurement
             hist = OrderedDict()  # create a simple dictionary
             hist['#'] = sample  # the number of each sample
             hist[
                 'mm'] = value  # write the value of the measurement into the dictionary
             hist['time'] = ms_time
             yield (sample, value, hist)  # create a generator
             sample += 1
Example #31
0
class scriptTable(uorm.Model):

    # Create script table
    __db__ = _dbc
    __table__ = "script"
    __schema__ = OrderedDict([
        ("timestamp", uorm.now),
        ("id", 1),
        ("enable", "off"),
        ("pluginid", 0),
        ("name", ""),
        ("filename", ""),
        ("delay", 60),
    ])

    @classmethod
    def public(cls):
        # if cached: return cached table
        if hasattr(cls, '_script'): return cls._script
        # no cache: fetch it!
        try:
            cls._script = [x for x in cls.get()]
        except StopIteration:
            return None
        return cls._script

    @classmethod
    def getrow(cls):
        try:
            res = next(cls.get())
        except StopIteration:
            return None
        return res

    @classmethod
    def delete(cls, timestamp):
        # delete the table record
        try:
            os.remove(cls.fname(timestamp))
            # if cached: delete cached table
            if hasattr(cls, '_script'): del cls._script
        except KeyError:
            return False
        return True
Example #32
0
class BNO055:
    reg = dict(
        VECTOR_ACCELEROMETER=0x08,
        VECTOR_MAGNETOMETER=0x0e,
        VECTOR_GYROSCOPE=0x14,
        VECTOR_EULER=0x1a,
        VECTOR_LINEARACCEL=0x28,
        VECTOR_GRAVITY=0x2e,
        QUATERNION_DATA=0x20,
        TEMPERATURE=0x34,

        CHIP_ID=0x00,
        SYS_TRIGGER=0x3f,
        OPR_MODE=0x3d,
        PAGE_ID=0x07,
        PWR_MODE=0x3e,

        ACCEL_OFFSET_X_LSB_ADDR=0x55,
        CALIB_STAT_ADDR=0x35,

    )

    modes = dict(
        CONFIG=0x00,
        NDOF=0x0c,
    )

    power_modes = dict(
        NORMAL=0x00,
        LOW=0x01,
        SUSPEND=0x02
    )

    BNO055_ID = 0xa0
    NUM_BNO055_OFFSET_REGISTERS = 22

    def __init__(self, bus, reset_pin=None, default_address=True, declination=(0, 0)):
        print(bus)
        self.i2c = pyb.I2C(bus, pyb.I2C.MASTER)
        if reset_pin is not None:
            self.reset_pin = pyb.Pin(reset_pin, pyb.Pin.OUT_PP)
        else:
            self.reset_pin = reset_pin

        if default_address:
            self.address = 0x28
        else:
            self.address = 0x29

        self.declination = \
            (declination[0] + declination[1] / 60) * math.pi / 180

        self.quat_scale = 1.0 / (1 << 14)
        self.sample_delay = 100

        self.default_mode = self.modes['NDOF']

        self.offsets = OrderedDict(
            accel_offset_x=0,
            accel_offset_y=0,
            accel_offset_z=0,

            mag_offset_x=0,
            mag_offset_y=0,
            mag_offset_z=0,

            gyro_offset_x=0,
            gyro_offset_y=0,
            gyro_offset_z=0,

            accel_radius=0,
            mag_radius=0
        )
        self.init_sensor()

    def init_sensor(self):
        pyb.delay(1000)

        addresses = self.i2c.scan()
        if self.address not in addresses:
            raise Exception("Address %s not found during scan: %s" % (
                self.address, addresses))

        if not self.i2c.is_ready(self.address):
            raise Exception("Device not ready")

        pyb.delay(50)
        chip_id = self.read_8(self.reg['CHIP_ID'])
        if ord(chip_id) != self.BNO055_ID:
            pyb.delay(1000)  # wait for boot
            chip_id = self.read_8(self.reg['CHIP_ID'])
            if ord(chip_id) != self.BNO055_ID:
                raise Exception("Chip ID invalid:", chip_id)

        self.set_mode(self.modes['CONFIG'])

        self.write_8(self.reg['SYS_TRIGGER'], 0x20)  # reset
        pyb.delay(1000)
        # while ord(self.read_8(self.reg['CHIP_ID'])) != self.BNO055_ID:
        #     pyb.delay(10)
        self.write_8(self.reg['PWR_MODE'], self.power_modes['NORMAL'])
        pyb.delay(10)

        self.write_8(self.reg['PAGE_ID'], 0)

        self.write_8(self.reg['SYS_TRIGGER'], 0x0)
        pyb.delay(10)

        self.set_mode(self.default_mode)
        pyb.delay(20)

        pyb.delay(100)

        self.set_ext_crystal_use()

        pyb.delay(100)

    def reset(self):
        if self.reset_pin is not None:
            self.reset_pin.low()
            pyb.delay(1)
            self.reset_pin.high()
            self.init_sensor()
        else:
            print("No reset pin defined. BNO055 not reset")

    def set_mode(self, mode):
        self.write_8(self.reg['OPR_MODE'], mode)
        pyb.delay(30)

    def set_ext_crystal_use(self):
        self.set_mode(self.modes['CONFIG'])
        pyb.delay(25)

        self.write_8(self.reg['PAGE_ID'], 0)
        self.write_8(self.reg['SYS_TRIGGER'], 0x80)
        pyb.delay(10)

        self.set_mode(self.default_mode)
        pyb.delay(20)

    def get_lin_accel(self):  # acceleration in m/s^2 (excluding gravity)
        x, y, z = self.get_vector('VECTOR_LINEARACCEL')
        return x / 100.0, y / 100.0, z / 100.0

    def get_gyro(self):  # angular velocity in rotations per second
        x, y, z = self.get_vector('VECTOR_GYROSCOPE')
        return x / 900.0, y / 900.0, z / 900.0

    def get_quat(self):
        # quaternion vector (see: https://en.wikipedia.org/wiki/Quaternion)

        buf = self.read_len(self.reg['QUATERNION_DATA'], 8)
        w = (buf[1] << 8) | buf[0]
        x = (buf[3] << 8) | buf[2]
        y = (buf[5] << 8) | buf[4]
        z = (buf[7] << 8) | buf[6]
        return (w * self.quat_scale,
                x * self.quat_scale,
                y * self.quat_scale,
                z * self.quat_scale)

    def get_euler(self):  # yaw, pitch, roll in degrees
        z, y, x = self.get_vector('VECTOR_EULER')
        return z / 16.0, y / 16.0, x / 16.0

    def get_temp(self):  # get temperature in degrees celsius
        return ord(self.read_8(self.reg['TEMPERATURE']))

    def get_accel(self):  # acceleration in m/s^2 (including gravity)
        x, y, z = self.get_vector('VECTOR_ACCELEROMETER')
        return x / 100.0, y / 100.0, z / 100.0

    def get_grav(self):  # gravity vector in m/s^2
        x, y, z = self.get_vector('VECTOR_GRAVITY')
        return x / 100.0, y / 100.0, z / 100.0

    def get_mag(self):  # magnetic field strength in micro-Teslas
        x, y, z = self.get_vector('VECTOR_MAGNETOMETER')
        return x / 16.0, y / 16.0, z / 16.0

    def get_vector(self, vector_type):  # get an x, y, z data array from I2C
        buf = self.read_len(self.reg[vector_type], 6)
        data = []
        for index in range(0, len(buf), 2):
            datum = (buf[index + 1] << 8) | buf[index]
            if datum > 0x7fff:
                datum -= 0x10000
            data.append(datum)
        return data

    def get_calibration(self):
        calib_status = ord(self.read_8(self.reg['CALIB_STAT_ADDR']))
        system = (calib_status >> 6) & 0x03
        gyro = (calib_status >> 4) & 0x03
        accel = (calib_status >> 2) & 0x03
        mag = calib_status & 0x03

        return system, gyro, accel, mag

    def is_fully_calibrated(self):
        for status in self.get_calibration()[1:]:
            if status < 3:
                return False
        return True

    def update_offsets(self):
        if self.is_fully_calibrated():
            self.set_mode(self.modes['CONFIG'])

            calib_data = self.read_len(self.reg['ACCEL_OFFSET_X_LSB_ADDR'],
                                       self.NUM_BNO055_OFFSET_REGISTERS)

            self.set_mode(self.default_mode)

            index = 0
            for offset in self.offsets.keys():
                self.offsets[offset] = (calib_data[index + 1] << 8) | calib_data[index]
                index += 2
#            print(self.offsets)
            return True
        else:
            return False

    def get_heading(self):
        # compass heading in radians (be sure to get the correct declination)

        x, y, z = self.get_mag()
        heading = math.atan2(y, x)
        heading += self.declination
        # Correct for reversed heading
        if heading < 0:
            heading += 2 * math.pi
        # Check for wrap and compensate
        elif heading > 2 * math.pi:
            heading -= 2 * math.pi
        return heading

    def write_8(self, register, data):
        return self.i2c.mem_write(data, self.address, register)

    def read_8(self, register):
        return self.i2c.mem_read(1, self.address, register)

    def read_len(self, register, length):
        #        try:
        return self.i2c.mem_read(length, self.address, register)