Skip to content

Commit

Permalink
Serious rework to normalize methods.
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisgilldc committed Mar 29, 2023
1 parent ef1f8a4 commit fd389f7
Show file tree
Hide file tree
Showing 28 changed files with 1,348 additions and 512 deletions.
32 changes: 32 additions & 0 deletions CobraBay/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
####
# Cobra Bay init
####

from .bay import CBBay
from .display import CBDisplay
from .core import CBCore
from .config import CBConfig
from .network import CBNetwork
from .systemhw import CBPiStatus
from .version import __version__

import CobraBay.detectors
import CobraBay.sensors
import CobraBay.triggers

# def read_version():
# print(__file__)
# """Read a text file and return the content as a string."""
# with io.open("/CobraBay/CobraBay/version.py") as f:
# return f.read()

__repo__ = "https://github.com/chrisgilldc/cobrabay.git"
all = [
'CBBay',
'CBDisplay',
'CBCore',
'CBConfig',
'CBNetwork',
'CBPiStatus',
'__version__'
]
78 changes: 59 additions & 19 deletions lib/bay.py → CobraBay/bay.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
import time
from pint import UnitRegistry, Quantity
from time import monotonic
from .detector import CB_VL53L1X
from .detectors import CB_VL53L1X
import logging
from pprint import pformat
from functools import wraps

import sys
from .exceptions import SensorValueException

# Scan the detectors if we're asked for a property that needs a fresh can and we haven't scanned recently enough.
def scan_if_stale(func):
Expand All @@ -33,18 +34,53 @@ def wrapper(self, *args, **kwargs):
return wrapper


class Bay:
def __init__(self, bay_id, config, detectors):
# Get our settings.
self._settings = config.bay(bay_id)
class CBBay:
def __init__(self, bay_id,
bay_name,
bay_depth,
stop_point,
park_time,
output_unit,
detectors,
detector_settings,
log_level="DEBUG"):
"""
:param bay_id: ID for the bay. Cannot have spaces.
:type bay_id: str
:param bay_name: Long "friendly" name for the Bay, used in MQTT messages
:type bay_name: str
:param bay_depth: Absolute distance of the bay, from the range sensor to the end. Must be a linear Quantity.
:type bay_depth: Quantity
:param stop_point: Distance from the sensor where the vehicle should stop
:type stop_point: Quantity
:param park_time: int
:param output_unit: Unit to output measurements in. Should be a distance unit understood by Pint (ie: 'in', 'cm', etc)
:type output_unit: str
:param detectors: Dictionary of detectors to use.
:type detectors: dict
:param detector_settings: Dictionary of detector configuration settings.
:type detector_settings: dict
:param log_level: Log level for the bay, must be a Logging level.
:type log_level: str
"""
# Save parameters
self._bay_id = bay_id
self._bay_name = bay_name
self._bay_depth = bay_depth
self._stop_point = stop_point
self._park_time = park_time
self._output_unit = output_unit
self._detectors = detectors
self._detector_settings = detector_settings
# Create a logger.
self._logger = logging.getLogger("CobraBay").getChild(self.bay_id)
self._logger.setLevel(config.get_loglevel(bay_id))
self._logger.setLevel(log_level)
self._logger.info("Initializing bay: {}".format(bay_id))
self._logger.debug("Bay received detectors: {}".format(detectors))

# Initialize variables.
self._position = {}
self._quality = {}
self._detectors = {}
self._trigger_registry = {}
self._previous_scan_ts = 0
self._state = None
Expand All @@ -53,7 +89,6 @@ def __init__(self, bay_id, config, detectors):
# Log our initialization.
self._logger.info("Bay '{}' initializing...".format(self.bay_id))
self._logger.info("Bay has settings:")
self._logger.info(pformat(self._settings))
# Create a unit registry.
self._ureg = UnitRegistry

Expand Down Expand Up @@ -170,7 +205,12 @@ def _scan_detectors(self, filter_lateral=True):
quality = {}
# Check all the detectors.
for detector_name in self._detectors:
position[detector_name] = self._detectors[detector_name].value
try:
position[detector_name] = self._detectors[detector_name].value
except SensorValueException:
# For now, pass. Need to add logic here to actually set the overall bay status.
pass

quality[detector_name] = self._detectors[detector_name].quality
self._logger.debug("Read of detector {} returned value '{}' and quality '{}'".
format(self._detectors[detector_name].name, position[detector_name],
Expand Down Expand Up @@ -459,28 +499,28 @@ def _detector_state(self, mode):

@property
def bay_id(self):
return self._settings['bay_id']
return self._bay_id

@bay_id.setter
def bay_id(self, input):
self._settings['bay_id'] = input
self._bay_id = input

@property
def bay_name(self):
return self._settings['bay_name']
return self._bay_name

@bay_name.setter
def bay_name(self, input):
self._settings['bay_name'] = input
self._bay_name = input

# Apply specific config options to the detectors.
def _setup_detectors(self):
# For each detector we use, apply its properties.
self._logger.debug("Detectors: {}".format(self._detectors.keys()))
for dc in self._settings['detectors']['settings'].keys():
for dc in self._detector_settings.keys():
self._logger.debug("Configuring detector {}".format(dc))
self._logger.debug("Settings: {}".format(self._settings['detectors']['settings'][dc]))
for item in self._settings['detectors']['settings'][dc]:
self._logger.debug("Settings: {}".format(self._detector_settings[dc]))
for item in self._detector_settings[dc]:
self._logger.debug(
"Setting property {} to {}".format(item, self._settings['detectors']['settings'][dc][item]))
setattr(self._detectors[dc], item, self._settings['detectors']['settings'][dc][item])
"Setting property {} to {}".format(item, self._detector_settings[dc][item]))
setattr(self._detectors[dc], item, self._detector_settings[dc][item])
Empty file added CobraBay/cli/__init__.py
Empty file.
52 changes: 52 additions & 0 deletions CobraBay/cli/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
####
# Cobra Bay - Main Executor
####

import argparse
import pathlib
import sys
import CobraBay
import logging
from logging.handlers import WatchedFileHandler

from pid import PidFile

def main():
# Parse command line options.
parser = argparse.ArgumentParser(
description="CobraBay Parking System"
)
parser.add_argument("-c", "--config", help="Config file location.")
parser.add_argument("-r", "--run-dir", help="Run directory, for the PID file.")
args = parser.parse_args()

try:
arg_config = pathlib.Path(args.config)
except TypeError:
arg_config = None

# Create the Master logger.
master_logger = logging.getLogger("CobraBay")
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
master_logger.addHandler(console_handler)

# Create a CobraBay config object.
try:
cbconfig = CobraBay.CBConfig(config_file=arg_config, reset_sensors=True)
except ValueError as e:
print(e)
sys.exit(1)

# Initialize the object.
cb = CobraBay.CBCore(config_obj=cbconfig)

# Start the main operating loop.
with PidFile('CobraBay', piddir='/tmp') as p:
print("Pid file name: {}".format(p.pidname))
print("Pid directory: {}".format(p.piddir))
cb.run()


if __name__ == "__main__":
sys.exit(main())
100 changes: 100 additions & 0 deletions CobraBay/cli/sensor_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
####
# Cobra Bay - Sensor Testing Tool
####

import argparse
import pathlib
import sys
import CobraBay
import logging

from pid import PidFile, PidFileAlreadyRunningError, PidFileAlreadyLockedError

def main():
# Parse command line options.
parser = argparse.ArgumentParser(
description="CobraBay Sensor Tester"
)
parser.add_argument("-c", "--config", help="Config file location.")
parser.add_argument("-r", "--run-dir", help="Run directory, for the PID file.")
parser.add_argument("-n", default=1, help="Number of test readings to take.")
parser.add_argument("-s", default="all", help="Sensors to test.")
args = parser.parse_args()

# Check for an active CobraBay instance.
if args.run_dir:
pid_lock = PidFile('CobraBay', piddir=args.run_dir)
else:
# Default the pid file to /tmp
pid_lock = PidFile('CobraBay', piddir="/tmp")

try:
pid_lock.check()
except PidFileAlreadyRunningError:
print("Cannot run sensor test while CobraBay is active. CobraBay running as PID {}".format(pid_lock.pid))
sys.exit(1)
except PidFileAlreadyLockedError:
print("CobraBay lock exists but appears not to be running. May be stale. "
"Check directory '{}', clear and retry.".format(pid_lock.piddir))

try:
arg_config = pathlib.Path(args.config)
except TypeError:
arg_config = None

# Create the Master logger.
master_logger = logging.getLogger("CobraBay")
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
master_logger.addHandler(console_handler)

# Create a CobraBay config object.
try:
cbconfig = CobraBay.CBConfig(config_file=arg_config, reset_sensors=True)
except ValueError as e:
print(e)
sys.exit(1)

# Start the main operating loop.
with PidFile('CobraBay', piddir='/tmp') as p:
# Load the various sensors.
sensors = load_sensors(cbconfig)
print("Loaded sensors: {}".format(list(sensors.keys())))
if args.s == 'all':
test_sensors = sensors.keys()
else:
if args.s not in sensors.keys():
print("Requested test sensors '{}' not in configured sensors.")
sys.exit(1)
else:
test_sensors = [ args.s ]

for sensor in sensors:
sensors[sensor].start_ranging()

i = 1
while i <= int(args.n):
print("Test cycle: {}".format(i))
for sensor in test_sensors:
print("{} - {}".format(sensor, sensors[sensor].range))
i += 1


# Method to load just the sensors out of a given CobraBay Config.
def load_sensors(cbconfig):
sensors = {}
for detector_id in cbconfig.detector_list:
detector_config = cbconfig.detector(detector_id)
if detector_config['sensor']['type'] == 'VL53L1X':
# Create the sensor object using provided settings.
sensor_obj = CobraBay.sensors.CB_VL53L1X(detector_config['sensor'])
elif detector_config['sensor']['type'] == 'TFMini':
sensor_obj = CobraBay.sensors.TFMini(detector_config['sensor'])
else:
continue
sensors[detector_id] = sensor_obj
return sensors


if __name__ == "__main__":
sys.exit(main())
Loading

0 comments on commit fd389f7

Please sign in to comment.