Example #1
0
    def __init__(self, state: State) -> None:
        """Initializes recipe manager."""

        # Initialize parent class
        super().__init__()

        # Initialize logger
        self.logger = Logger("Recipe", "recipe")

        # Initialize state
        self.state = state

        # Initialize state machine transitions
        self.transitions = {
            modes.INIT: [modes.NORECIPE, modes.ERROR],
            modes.NORECIPE: [modes.START, modes.ERROR],
            modes.START: [modes.QUEUED, modes.ERROR],
            modes.QUEUED: [modes.NORMAL, modes.STOP, modes.ERROR],
            modes.NORMAL: [modes.PAUSE, modes.STOP, modes.ERROR],
            modes.PAUSE: [modes.START, modes.ERROR],
            modes.STOP: [modes.NORECIPE, modes.ERROR],
            modes.ERROR: [modes.RESET],
            modes.RESET: [modes.INIT],
        }

        # Start state machine from init mode
        self.mode = modes.INIT
Example #2
0
    def __init__(
        self,
        name: str,
        i2c_lock: threading.RLock,
        bus: int,
        address: int,
        mux: Optional[int] = None,
        channel: Optional[int] = None,
        simulate: bool = False,
        mux_simulator: Optional[MuxSimulator] = None,
        Simulator: Optional[PeripheralSimulator] = None,
    ) -> None:
        """ Initializes atlas driver. """

        # Initialize parameters
        self.simulate = simulate

        # Initialize logger
        logname = "Driver({})".format(name)
        self.logger = Logger(logname, "peripherals")

        # Initialize I2C
        try:
            self.i2c = I2C(
                name=name,
                i2c_lock=i2c_lock,
                bus=bus,
                address=address,
                mux=mux,
                channel=channel,
                mux_simulator=mux_simulator,
                PeripheralSimulator=Simulator,
            )
        except I2CError as e:
            raise exceptions.InitError(logger=self.logger)
Example #3
0
    def __init__(
        self,
        name: str,
        i2c_lock: threading.RLock,
    ) -> None:
        """Initializes ArduinoComms"""

        # Initialize logger
        logname = "ArduinoComms({})".format(name)
        self.logger = Logger(logname, __name__)

        self.bus = 2
        self.address = 0x08

        self.name = name

        # Initialize I2C
        try:
            self.i2c = I2C(name="Arduino-{}".format(name),
                           i2c_lock=i2c_lock,
                           bus=self.bus,
                           address=self.address,
                           mux=None)
        except I2CError as e:
            raise exceptions.InitError(logger=self.logger) from e
Example #4
0
    def __init__(
        self,
        name: str,
        bus: int,
        device_addr: int,
        mux_address: Optional[int],
        mux_channel: Optional[int],
        mux_simulator: Optional[MuxSimulator],
    ) -> None:

        # Initialize parameters
        self.name = name
        self.bus = bus
        self.device_addr = device_addr
        self.mux_address = mux_address
        self.mux_channel = mux_channel
        self.mux_simulator = mux_simulator

        # Initialize logger
        logname = "Simulator({})".format(name)
        self.logger = Logger(logname, __name__)
        self.logger.debug("Initializing simulator")

        # Initialize buffer
        self.buffer: bytearray = bytearray([])  # mutable bytes

        # Initialize register
        self.registers: Dict[int, int] = {}
        self.writes: Dict[str, bytes] = {}
    def __init__(
        self,
        name: str,
        i2c_lock: threading.RLock,
        address: int,
        bus: Optional[int] = None,
        mux: Optional[int] = None,
        channel: Optional[int] = None,
        mux_simulator: Optional[MuxSimulator] = None,
        PeripheralSimulator: Optional[PeripheralSimulator] = None,
        verify_device: bool = True,
    ) -> None:

        # Initialize passed in parameters
        self.name = name
        self.i2c_lock = i2c_lock
        self.bus = bus
        self.address = address
        self.mux = mux
        self.channel = channel

        # Initialize logger
        logname = "I2C({})".format(self.name)
        self.logger = Logger(logname, "i2c")
        self.logger.debug("Initializing communication")

        # Verify mux config
        if self.mux != None and self.channel == None:
            raise InitError(
                "Mux requires channel value to be set") from ValueError

        # Initialize io
        if PeripheralSimulator != None:
            self.logger.debug("Using simulated io stream")
            self.io = PeripheralSimulator(  # type: ignore
                name, bus, address, mux, channel, mux_simulator)
        else:
            self.logger.debug("Using device io stream")
            with self.i2c_lock:
                self.io = DeviceIO(name, bus)

        # Verify mux exists
        if self.mux != None:
            self.verify_mux()

        # Verify device exists
        if verify_device:
            self.verify_device()

        # Successfully initialized!
        self.logger.debug("Initialization successful")
 def __init__(self) -> None:
     """Initializes state machine manager."""
     self.logger: Logger = Logger("StateMachineManager", __name__)
     self.thread: threading.Thread = threading.Thread(target=self.run)
     self.event_queue: queue.Queue = queue.Queue()
     self.is_shutdown: bool = False
     self._mode: str = modes.INIT
     self.transitions: Dict[str, List[str]] = {
         modes.INIT: [modes.NORMAL, modes.SHUTDOWN, modes.ERROR],
         modes.NORMAL: [modes.RESET, modes.SHUTDOWN, modes.ERROR],
         modes.RESET: [modes.INIT, modes.SHUTDOWN, modes.ERROR],
         modes.ERROR: [modes.RESET, modes.SHUTDOWN],
     }
     self.logger.debug("Initialized")
Example #7
0
    def __init__(self) -> None:
        """Initializes coordinator."""

        # Initialize parent class
        super().__init__()

        # Initialize logger
        self.logger = Logger("Coordinator", "coordinator")
        self.logger.debug("Initializing coordinator")

        # Initialize state
        self.state = State()

        # Initialize environment state dict, TODO: remove this
        self.state.environment = {
            "sensor": {"desired": {}, "reported": {}},
            "actuator": {"desired": {}, "reported": {}},
            "reported_sensor_stats": {
                "individual": {"instantaneous": {}, "average": {}},
                "group": {"instantaneous": {}, "average": {}},
            },
        }

        # Initialize recipe state dict, TODO: remove this
        self.state.recipe = {
            "recipe_uuid": None,
            "start_timestamp_minutes": None,
            "last_update_minute": None,
        }

        # Initialize managers
        self.recipe = RecipeManager(self.state)
        self.iot = IotManager(self.state, self.recipe)  # type: ignore
        self.resource = ResourceManager(self.state, self.iot)  # type: ignore
        self.network = NetworkManager(self.state)  # type: ignore
        self.upgrade = UpgradeManager(self.state)  # type: ignore

        # Initialize state machine transitions
        self.transitions = {
            modes.INIT: [modes.CONFIG, modes.ERROR, modes.SHUTDOWN],
            modes.CONFIG: [modes.SETUP, modes.ERROR, modes.SHUTDOWN],
            modes.SETUP: [modes.NORMAL, modes.ERROR, modes.SHUTDOWN],
            modes.NORMAL: [modes.LOAD, modes.ERROR, modes.SHUTDOWN],
            modes.LOAD: [modes.CONFIG, modes.ERROR, modes.SHUTDOWN],
            modes.RESET: [modes.INIT, modes.SHUTDOWN],
            modes.ERROR: [modes.RESET, modes.SHUTDOWN],
        }

        # Initialize state machine mode
        self.mode = modes.INIT
    def __init__(self, name: str, bus: int) -> None:

        # Initialize parameters
        self.name = name
        self.bus = bus

        # Initialize logger
        logname = "DeviceIO({})".format(name)
        self.logger = Logger(logname, __name__)

        # Verify io exists
        self.logger.debug("Verifying io stream exists")
        self.open()
        self.close()
    def __init__(
        self,
        name: str,
        panel_configs: List[Dict[str, Any]],
        panel_properties: Dict[str, Any],
        i2c_lock: threading.Lock,
        simulate: bool = False,
        mux_simulator: Optional[MuxSimulator] = None,
    ) -> None:
        """Initializes driver."""

        # Initialize driver parameters
        self.panel_properties = panel_properties
        self.i2c_lock = i2c_lock
        self.simulate = simulate

        # Initialize logger
        self.logger = Logger(name="Driver({})".format(name),
                             dunder_name=__name__)

        # Parse panel properties
        self.channels = self.panel_properties.get("channels")
        self.dac_map = self.panel_properties.get("dac_map")

        # Initialze num expected panels
        self.num_expected_panels = len(panel_configs)

        # Initialize panels
        self.panels: List[LEDDAC5578Panel] = []
        for config in panel_configs:
            panel = LEDDAC5578Panel(name, config, i2c_lock, simulate,
                                    mux_simulator, self.logger)
            panel.initialize()
            self.panels.append(panel)

        # Check at least one panel is still active
        active_panels = [
            panel for panel in self.panels if not panel.is_shutdown
        ]
        self.num_active_panels = len(active_panels)
        if self.num_active_panels < 1:
            raise NoActivePanelsError(logger=self.logger)

        # Successfully initialized
        message = "Successfully initialized with {} ".format(
            self.num_active_panels)
        message2 = "active panels, expected {}".format(
            self.num_expected_panels)
        self.logger.debug(message + message2)
    def __init__(self, name: str) -> None:

        # Initialize parameters
        self.name = name

        # Initialize logger
        logname = "DeviceIO({})".format(name)
        self.logger = Logger(logname, __name__)

        # Verify io exists
        self.logger.debug("Verifying io stream exists")

        UART.setup("UART1")
        self.ser = serial.Serial(port = "/dev/ttyO1", baudrate=9600)

        self.open()
        self.close()
Example #11
0
    def __init__(
        self,
        bus: int = 0,
        address: int = PCA9632_I2C_ADDRESS,
        mux: Optional[int] = None,
        channel: Optional[int] = None,
        simulate: bool = False,
        mux_simulator: Optional[MuxSimulator] = None,
    ) -> None:
        """Initializes Grove RGB LCD."""

        # Initialize logger
        self.logger = Logger('LED', __name__)

        # Check if simulating
        if simulate:
            self.logger.info("Simulating LED")

        # Initialize I2C
        try:
            self.i2c = I2C(
                name="LED",
                i2c_lock=threading.RLock(),
                bus=bus,
                address=address,
                mux=mux,
                channel=channel,
                mux_simulator=mux_simulator,
                PeripheralSimulator=None,
            )
        except I2CError as e:
            raise LEDError(logger=self.logger) from e

        # Initialize the LED
        try:
            self.init_data = [
                0x80, 0x80, 0x21, 0x00, 0x00, 0x00, 0x40, 0x80, 0x02, 0xEA
            ]

            # init and clear any LED values
            self.i2c.write(bytes(self.init_data))

        except I2CError as e:
            raise LEDError(logger=self.logger) from e
Example #12
0
    def __init__(
        self,
        name: str,
        i2c_lock: threading.Lock,
        bus: int,
        address: int,
        mux: Optional[int] = None,
        channel: Optional[int] = None,
        simulate: Optional[bool] = False,
        mux_simulator: Optional[MuxSimulator] = None,
    ) -> None:
        """Initializes t6713 driver."""

        # Initialize parameters
        self.simulate = simulate
        self.i2c_lock = i2c_lock

        # Initialize logger
        self.logger = Logger(name="Driver({})".format(name),
                             dunder_name=__name__)

        # Check if simulating
        if simulate:
            self.logger.info("Simulating driver")
            Simulator = T6713Simulator
        else:
            Simulator = None

        # Initialize I2C
        try:
            self.i2c = I2C(
                name=name,
                i2c_lock=i2c_lock,
                bus=bus,
                address=address,
                mux=mux,
                channel=channel,
                mux_simulator=mux_simulator,
                PeripheralSimulator=Simulator,
            )

        except I2CError as e:
            raise InitError(logger=self.logger) from e
Example #13
0
    def __init__(
        self,
        name: str,
        arduino_lock: threading.RLock,
    ) -> None:

        # Initialize passed in parameters
        self.name = name
        self.arduino_lock = arduino_lock

        # Initialize logger
        logname = "Arduino({})".format(self.name)
        self.logger = Logger(logname, "arduino")
        self.logger.debug("Initializing communication")

        self.io = DeviceIO(name)

        # Successfully initialized!
        self.logger.debug("Initialization successful")
    def __init__(self,
                 name: str,
                 simulate: bool = False,
                 ini_file: str = None,
                 config_file: str = None,
                 debug: bool = False) -> None:
        """Initializes bacpypes."""

        self.logger = Logger(name + ".BACNet", __name__)

        if ini_file is None or config_file is None:
            raise exceptions.InitError(message="Missing file args",
                                       logger=self.logger)

        try:
            self.logger.info("driver init")
            self.bnet = BACNET.Bnet(self.logger, ini_file, config_file, debug)

        except Exception as e:
            raise exceptions.InitError(logger=self.logger) from e
Example #15
0
    def __init__(
        self,
        name: str,
        i2c_lock: threading.Lock,
        bus: int,
        address: int,
        mux: Optional[int] = None,
        channel: Optional[int] = None,
        simulate: Optional[bool] = False,
        mux_simulator: Optional[MuxSimulator] = None,
    ) -> None:
        """Initializes driver."""

        # Initialize logger
        self.logger = Logger(name="Driver({})".format(name), dunder_name=__name__)

        # Check if simulating
        if simulate:
            self.logger.info("Simulating driver")
            Simulator = SHT25Simulator
        else:
            Simulator = None

        # Initialize I2C
        try:
            self.i2c = I2C(
                name=name,
                i2c_lock=i2c_lock,
                bus=bus,
                address=address,
                mux=mux,
                channel=channel,
                mux_simulator=mux_simulator,
                PeripheralSimulator=Simulator,
                verify_device=False,  # need to write before device responds to read
            )
            self.read_user_register(retry=True)

        except I2CError as e:
            raise InitError(logger=self.logger) from e
Example #16
0
    def __init__(
        self,
        name: str,
        i2c_lock: threading.RLock,
        bus: int,
        address: int,
        mux: Optional[int] = None,
        channel: Optional[int] = None,
        simulate: bool = False,
        mux_simulator: Optional[MuxSimulator] = None,
    ) -> None:
        """Initializes DAC5578."""

        # Initialize logger
        logname = "DAC5578-({})".format(name)
        self.logger = Logger(logname, __name__)

        # Check if simulating
        if simulate:
            self.logger.info("Simulating driver")
            Simulator = DAC5578Simulator
        else:
            Simulator = None

        # Initialize I2C
        try:
            self.i2c = I2C(
                name="DAC5578-{}".format(name),
                i2c_lock=i2c_lock,
                bus=bus,
                address=address,
                mux=mux,
                channel=channel,
                mux_simulator=mux_simulator,
                PeripheralSimulator=Simulator,
            )
        except I2CError as e:
            raise exceptions.InitError(logger=self.logger) from e
    def __init__(
        self,
        name: str,
        i2c_lock: threading.RLock,
        bus: int,
        rgb_address: int = RGB_ADDRESS,
        lcd_address: int = LCD_ADDRESS,
        mux: Optional[int] = None,
        channel: Optional[int] = None,
        simulate: bool = False,
        mux_simulator: Optional[MuxSimulator] = None,
    ) -> None:
        """Initializes Grove RGB LCD."""

        # Initialize logger
        logname = "GroveRGBLCD({})".format(name)
        self.logger = Logger(logname, __name__)

        # Check if simulating
        if simulate:
            self.logger.info("Simulating driver")
            Simulator = simulator.GroveRGBLCDSimulator
        else:
            Simulator = None

        # Initialize I2C
        try:
            self.i2c_rgb = I2C(
                name="RGB-{}".format(name),
                i2c_lock=i2c_lock,
                bus=bus,
                address=rgb_address,
                mux=mux,
                channel=channel,
                mux_simulator=mux_simulator,
                PeripheralSimulator=Simulator,
            )
            self.i2c_lcd = I2C(
                name="LCD-{}".format(name),
                i2c_lock=i2c_lock,
                bus=bus,
                address=lcd_address,
                mux=mux,
                channel=channel,
                mux_simulator=mux_simulator,
                PeripheralSimulator=Simulator,
            )
        except I2CError as e:
            raise exceptions.InitError(logger=self.logger) from e

        # Initialize the display
        try:
            # command: clear display
            self.i2c_lcd.write(bytes([self.CMD, self.CLEAR]))
            time.sleep(0.05)  # Wait for lcd to process

            # command: display on, no cursor
            self.i2c_lcd.write(bytes([self.CMD, self.DISPLAY_ON_NO_CURSOR]))

            # command: 2 lines
            self.i2c_lcd.write(bytes([self.CMD, self.TWO_LINES]))
            time.sleep(0.05)  # Wait for lcd to process

        except I2CError as e:
            raise exceptions.DriverError(logger=self.logger) from e
Example #18
0
import subprocess, socket, urllib.request, re

# Import python types
from typing import List, Dict, Union

# Import device utilities
from device.utilities import system
from device.utilities.logger import Logger

# Initialize file paths
GET_WIFIS_SCRIPT_PATH = "scripts/get_wifis.sh"
CONNECT_WIFI_SCRIPT_PATH = "scripts/connect_wifi.sh"
DELETE_WIFIS_SCRIPT_PATH = "scripts/delete_all_wifi_connections.sh"

# Initialize logger
logger = Logger("NetworkUtility", "network")


def is_connected() -> bool:
    """Checks if connected to network."""
    try:
        urllib.request.urlopen("http://google.com")
        return True
    except urllib.error.URLError:  # type: ignore
        return False


def get_ip_address() -> str:
    """Gets ip address of the active network interface."""
    logger.debug("Getting ip address")
Example #19
0
# Import standard python modules
import subprocess, os, re

# Import device utilities
from device.utilities.logger import Logger

from django.conf import settings

# Initialize file paths
# DEVICE_CONFIG_PATH = "data/config/device.txt"
# DATA_PATH = os.getenv("STORAGE_LOCATION", "data")
DEVICE_CONFIG_PATH = settings.DATA_PATH + "/config/device.txt"

# Initialize logger
logger = Logger("SystemUtility", "system")
logger.debug("Initializing utility")


def device_config_name() -> str:
    """Gets device config name from file."""
    logger.debug("Getting device config name")

    # Get device config name
    if os.path.exists(DEVICE_CONFIG_PATH):
        with open(DEVICE_CONFIG_PATH) as f:
            device_config_name = f.readline().strip()
    else:
        device_config_name = "unspecified"

    # Successfully got device config name
    logger.debug("Device config name: {}".format(device_config_name))
Example #20
0
 def __init__(self) -> None:
     self.logger = Logger("NetworkUtility", "network")
Example #21
0
# Import device utilities
from device.utilities.logger import Logger
from device.utilities import network

# Initialize file paths
REGISTRATION_DATA_DIR = "data/registration/"
DEVICE_ID_PATH = REGISTRATION_DATA_DIR + "device_id.bash"
ROOTS_PATH = REGISTRATION_DATA_DIR + "roots.pem"
RSA_CERT_PATH = REGISTRATION_DATA_DIR + "rsa_cert.pem"
RSA_PRIVATE_PATH = REGISTRATION_DATA_DIR + "rsa_private.pem"
VERIFICATION_CODE_PATH = REGISTRATION_DATA_DIR + "verification_code.txt"
REGISTER_SCRIPT_PATH = "scripts/one_time_key_creation_and_iot_device_registration.sh"

# Initialize logger
logger = Logger("IotRegistrationUtility", "iot")


def is_registered() -> bool:
    """Checks if device is registered by checking local files."""
    logger.debug("Checking if device is registered")
    if (os.path.exists(DEVICE_ID_PATH) and os.path.exists(ROOTS_PATH)
            and os.path.exists(RSA_CERT_PATH)
            and os.path.exists(RSA_PRIVATE_PATH)):
        return True
    else:
        return False


def device_id() -> str:
    """Gets device id string from local file. TODO: Handle exeptions."""
Example #22
0
    def __init__(self) -> None:
        """Initializes mux simulator."""

        # Initialize logger
        self.logger = Logger("Simulator(Mux)", __name__)
Example #23
0
# Import standard python modules
import pyudev, glob, subprocess

# Import python types
from typing import List

# Import device utilities
from device.utilities.logger import Logger

# Initialize logger
logger = Logger("USBUtility", "device")


def device_matches(device_path: str,
                   vendor_id: int,
                   product_id: int,
                   friendly: bool = True) -> bool:
    """Checks if a usb device at specified path matches vendor id and product id."""
    logger.debug("Checking if device matches")

    # Convert device path to real path if friendly
    # TODO: Explain friendly path...
    if friendly:
        command = "udevadm info --name={} -q path".format(device_path)
        process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
        output, error = process.communicate()
        device_path = str(output.strip(), encoding="utf-8")

    # Get device info
    context = pyudev.Context()
    device = pyudev.Device.from_path(context, device_path)
# Import device utilities
from device.utilities.logger import Logger

# Import driver elements
from device.peripherals.modules.bacnet import exceptions

# Conditionally import the bacpypes wrapper class, or use the simulator.
# The brain that runs on PFCs doesn't have or need BACnet communications,
# only the LGHC (running on linux) does.
try:
    from device.peripherals.modules.bacnet import bnet_wrapper as BACNET
except Exception as e:
    l = Logger("\n\nBACNet.driver", __name__)
    l.critical(e)
    from device.peripherals.modules.bacnet import bnet_simulator as BACNET


class BacnetDriver:
    """Driver for BACNet communications to HVAC."""

    # --------------------------------------------------------------------------
    def __init__(self,
                 name: str,
                 simulate: bool = False,
                 ini_file: str = None,
                 config_file: str = None,
                 debug: bool = False) -> None:
        """Initializes bacpypes."""

        self.logger = Logger(name + ".BACNet", __name__)
Example #25
0
    def __init__(
        self,
        name: str,
        vendor_id: int,
        product_id: int,
        resolution: str,
        simulate: bool = False,
        usb_mux_comms: Optional[Dict[str, Any]] = None,
        usb_mux_channel: Optional[int] = None,
        i2c_lock: Optional[threading.Lock] = None,
        mux_simulator: Optional[MuxSimulator] = None,
    ) -> None:
        """Initializes USB camera camera."""

        # Initialize parameters
        self.name = name
        self.vendor_id = vendor_id
        self.product_id = product_id
        self.resolution = resolution
        self.simulate = simulate

        # Initialize logger
        self.logger = Logger(name="Driver({})".format(name),
                             dunder_name=__name__)

        # Check if simulating
        if simulate:
            self.logger.info("Simulating driver")
            self.directory = "device/peripherals/modules/usb_camera/tests/images/"
        else:
            self.directory = IMAGE_DIR

        # Check directory exists else create it
        if not os.path.exists(self.directory):
            os.makedirs(self.directory)

        # Check if using usb mux
        if usb_mux_comms == None or usb_mux_channel == None:
            self.dac5578 = None
            return

        # Get optional i2c parameters
        mux = usb_mux_comms.get("mux", None)  # type: ignore
        if mux != None:
            mux = int(mux, 16)

        # Using usb mux, initialize driver
        try:
            self.dac5578 = DAC5578Driver(
                name=name,
                i2c_lock=i2c_lock,  # type: ignore
                bus=usb_mux_comms.get("bus", None),  # type: ignore
                address=int(usb_mux_comms.get("address", None),
                            16),  # type: ignore
                mux=mux,
                channel=usb_mux_comms.get("channel", None),  # type: ignore
                simulate=simulate,
                mux_simulator=mux_simulator,
            )
            self.usb_mux_channel = usb_mux_channel
        except I2CError as e:
            raise InitError(logger=self.logger) from e
Example #26
0
# Import standard python modules
import datetime, jwt

# Import python types
from typing import NamedTuple, Any

# Import device utilities
from device.utilities.logger import Logger

# Initialize logger
logger = Logger("IotTokenUtility", "iot")


class JsonWebToken(NamedTuple):
    """Dataclass for json web token."""

    encoded: Any  # TODO: Get type
    issued_timestamp: float
    expiration_timestamp: float

    @property
    def is_expired(self) -> bool:
        """Checks if token is expired."""
        current_timestamp = datetime.datetime.utcnow().timestamp()
        return current_timestamp > self.expiration_timestamp


def create_json_web_token(
    project_id: str,
    private_key_filepath: str,
    encryption_algorithm: str = "RS256",