New sensors: SHT4x, BMP390

This commit is contained in:
Ádám Kovács
2023-11-12 10:30:29 +01:00
parent bae126dfad
commit c540ffffe1
7 changed files with 815 additions and 15 deletions

View File

@@ -0,0 +1,57 @@
# micropython
# MIT license
# Copyright (c) 2022 Roman Shevchik goctaprog@gmail.com
import micropython
import ustruct
from sensor_pack import bus_service
class BaseSensor:
"""Base sensor class"""
def __init__(self, adapter: bus_service.BusAdapter, address: int, big_byte_order: bool):
"""Базовый класс Датчик.
Если big_byte_order равен True -> порядок байтов в регистрах датчика «big»
(Порядок от старшего к младшему), в противном случае порядок байтов в регистрах "little"
(Порядок от младшего к старшему)
address - адрес датчика на шине.
Base sensor class. if big_byte_order is True -> register values byteorder is 'big'
else register values byteorder is 'little'
address - address of the sensor on the bus."""
self.adapter = adapter
self.address = address
self.big_byte_order = big_byte_order
def _get_byteorder_as_str(self) -> tuple:
"""Return byteorder as string"""
if self.is_big_byteorder():
return 'big', '>'
else:
return 'little', '<'
def unpack(self, fmt_char: str, source: bytes) -> tuple:
"""распаковка массива, считанного из датчика.
fmt_char: c, b, B, h, H, i, I, l, L, q, Q. pls see: https://docs.python.org/3/library/struct.html"""
if len(fmt_char) != 1:
raise ValueError(f"Invalid length fmt_char parameter: {len(fmt_char)}")
bo = self._get_byteorder_as_str()[1]
return ustruct.unpack(bo + fmt_char, source)
@micropython.native
def is_big_byteorder(self) -> bool:
return self.big_byte_order
def get_id(self):
raise NotImplementedError
def soft_reset(self):
raise NotImplementedError
class Iterator:
def __iter__(self):
return self
def __next__(self):
raise NotImplementedError

View File

@@ -0,0 +1,66 @@
# micropython
# MIT license
# Copyright (c) 2022 Roman Shevchik goctaprog@gmail.com
"""service class for I/O bus operation"""
from machine import I2C
try:
from typing import Literal
except:
pass
class BusAdapter:
"""Proxy between I/O bus and device I/O class"""
def __init__(self, bus):
self.bus = bus
def read_register(self, device_addr: int, reg_addr: int, bytes_count: int) -> bytes:
"""считывает из регистра датчика значение.
device_addr - адрес датчика на шине.
reg_addr - адрес регистра в адресном пространстве датчика.
bytes_count - размер значения в байтах.
reads value from sensor register.
device_addr - address of the sensor on the bus.
reg_addr - register address in the address space of the sensor"""
raise NotImplementedError
def write_register(self, device_addr: int, reg_addr: int, value: int,
bytes_count: int, byte_order: str):
"""записывает данные value в датчик, по адресу reg_addr.
bytes_count - кол-во записываемых байт из value.
byte_order - порядок расположения байт в записываемом значении.
writes value data to the sensor, at reg_addr.
bytes_count - number of bytes written from value.
byte_order - the order of bytes in the value being written.
"""
raise NotImplementedError
def read(self, device_addr, n_bytes: int) -> bytes:
raise NotImplementedError
def write(self, device_addr, buf: bytes):
raise NotImplementedError
class I2cAdapter(BusAdapter):
def __init__(self, bus: I2C):
super().__init__(bus)
def write_register(self, device_addr: int, reg_addr: int, value: int,
bytes_count: int, byte_order: Literal["little", "big"]):
"""записывает данные value в датчик, по адресу reg_addr.
bytes_count - кол-во записываемых данных"""
buf = value.to_bytes(bytes_count, byte_order)
return self.bus.writeto_mem(device_addr, reg_addr, buf)
def read_register(self, device_addr: int, reg_addr: int, bytes_count: int) -> bytes:
"""считывает из регистра датчика значение.
bytes_count - размер значения в байтах"""
return self.bus.readfrom_mem(device_addr, reg_addr, bytes_count)
def read(self, device_addr, n_bytes: int) -> bytes:
return self.bus.readfrom(device_addr, n_bytes)
def write(self, device_addr, buf: bytes):
return self.bus.writeto(device_addr, buf)