def __init__(self,
              O3BoardNo='ISB',
              SO2BoardNo='ISB',
              NO2BoardNo='ISB',
              COBoardNo='ISB'):
     threading.Thread.__init__(self)
     self.O3boardNo = O3BoardNo
     #this needs to change to reflect proper callibration value
     self.SO2BoardNo = SO2BoardNo
     self.NO2BoardNo = NO2BoardNo
     self.COBoardNo = COBoardNo
     self.ADS1115 = 0x01
     self.adc = ADS1115(address=0x48)
     self.adc2 = ADS1115(address=0x49)
     self.sps = 8
     self.tempAndHumCalibrationData = []
     self.gasOffsetsAndSensitivity = []
     self.NO2 = 0
     self.O3 = 0
     self.CO = 0
     self.SO2 = 0
     self.temperature = 0
     self.gasADCReadings = {
         'SO2': [0, 0],
         'CO': [0, 0],
         'O3': [0, 0],
         'NO2': [0, 0]
     }
Example #2
0
    def __init__(self):

        two_up = os.path.abspath(os.path.join(__file__, ".."))
        rel_path = "controlboard_config.json"
        abs_file_path = os.path.join(two_up, rel_path)
        abs_file_path = os.path.abspath(os.path.realpath(abs_file_path))
        config = open(file=abs_file_path)

        super().__init__(config)
        self.adc = ADC()
        GPIO.setmode(GPIO.BCM)
        """
        Define pin numbers to which units are connected on Pi.
        """
        self.redSwitch = 27
        self.orangeSwitch = 22
        self.greenSwitch = 18
        self.mainSwitch = 23
        self.switches = [
            self.redSwitch,
            self.orangeSwitch,
            self.greenSwitch,
            self.mainSwitch,
        ]

        self.redLight1 = 9
        self.redLight2 = 15
        self.redLight3 = 17
        self.greenLight1 = 10
        self.greenLight2 = 14
        self.greenLight3 = 4

        self.redLEDs = [self.redLight1, self.redLight2, self.redLight3]
        self.greenLEDs = [self.greenLight1, self.greenLight2, self.greenLight3]

        self.a_pin0 = 24
        self.a_pin1 = 25
        self.a_pin2 = 8
        self.b_pin0 = 7
        self.b_pin1 = 1
        self.b_pin2 = 12

        GPIO.setup(self.redSwitch, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(self.orangeSwitch, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(self.greenSwitch, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(self.mainSwitch, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        GPIO.setup(self.redLight1, GPIO.OUT)
        GPIO.setup(self.redLight2, GPIO.OUT)
        GPIO.setup(self.redLight3, GPIO.OUT)
        GPIO.setup(self.greenLight1, GPIO.OUT)
        GPIO.setup(self.greenLight2, GPIO.OUT)
        GPIO.setup(self.greenLight3, GPIO.OUT)

        GPIO.setup(self.a_pin0, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.a_pin1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.a_pin2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.b_pin0, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.b_pin1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.b_pin2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
Example #3
0
def runtest(cfg: Config, args: argparse.Namespace,
            df: Optional[Datafile]) -> bool:
    logger = logging.getLogger()
    # Extract parameters from configuration files
    try:
        adc = ADS1115(address=cfg.get_int('Adc', 'Addr'),
                      busnum=cfg.get_int('Adc', 'Bus'))
        sens = AnalogFlowMeter(adc, cfg.get_int('AnalogFlowSensor', 'Chan'),
                               cfg.get_expr('AnalogFlowSensor', 'Gain'),
                               cfg.get_array('AnalogFlowSensor', 'Coeff'))
    except BadEntry:
        logger.exception("Configuration error")
        return False

    interval = 1. / args.rate
    print("Enter ctrl-c to exit ...", file=sys.stderr)
    sens.reset()
    try:
        for tick in ticker(interval):
            vol, secs = sens.amount()
            rec = OrderedDict(elapsed=round(secs, 3), vol=round(vol, 3))
            writerec(rec)
            if df:
                df.add_record("flow", rec, ts=tick)
    except KeyboardInterrupt:
        print("done", file=sys.stderr)

    return True
Example #4
0
 def __init__(self, logger, mpdService):
     self._logger = logger
     self._mpdService = mpdService
     self._adc = ADS1115()
     self._last_value = None
     self._max_value = 32767 * 3.3 / 4.096
     self._stop = False
     self._queue = SerialQueue("Volume Monitor")
Example #5
0
    def __init__(self):
        self.i2c_bus = busio.I2C(scl=board.SCL, sda=board.SDA)
        self.i2c_mux = TCA9548A(i2c=self.i2c_bus, address=0x70)

        self.adc = ADS1115(i2c=self.i2c_mux[3], address=0x56)
        self.volt_gain = 1
        # Measures for standard lear batteries with nominal 12V
        self.full = 12.65  # V
        self.empty = 11.99  # V
Example #6
0
    def __init__(self, mode_args=None):

        self.args = mode_args
        self.sample_rate = float(self.args.sample_rate)
        self.convert = self.args.convert

        # Create an ADS1115 ADC (16-bit) instance.
        self.adc = ADS1115()

        # show values
        if self.convert:
            print('Converted readings')
        else:
            print("RAW Readings")

        # Choose a gain of 1 for reading voltages from 0 to 4.09V.
        # Or pick a different gain to change the range of voltages that
        #  are read:
        #  - 2/3 = +/-6.144V
        #  -   1 = +/-4.096V
        #  -   2 = +/-2.048V
        #  -   4 = +/-1.024V
        #  -   8 = +/-0.512V
        #  -  16 = +/-0.256V
        # See table 3 in the ADS1015/ADS1115 datasheet for more info on gain.
        self.GAIN = 1
        self.ARR = [0, 1, 2, 3]
        self.POT_CAL = {
            0: {
                'correction': 1.15,
                'offset': 30,
                'low': 9,
                'high': 26344,
                'throw': 297
            },
            1: {
                'correction': 1.15,
                'offset': 30,
                'low': 5,
                'high': 26335,
                'throw': 300
            },
            2: {
                'correction': 1.15,
                'offset': 30,
                'low': 4,
                'high': 26335,
                'throw': 300
            },
            3: {
                'correction': 1.15,
                'offset': 30,
                'low': 4,
                'high': 26335,
                'throw': 300
            }
        }
Example #7
0
    def __init__(self):
        """__init__() - Create an instance of the DyeSensor
        """

        try:
            self.sensor = ADS1115()

        except Exception as e:
            logging.error('Exception in DyeSensor: {0}'.format(e))
            self.sensor = None
Example #8
0
    def __init__(self):
        self.status = "Initializing"
        # Choose a gain of 1 for reading voltages from 0 to 4.09V.
        # Or pick a different gain to change the range of voltages that are read:
        #  - 2/3 = +/-6.144V
        #  -   1 = +/-4.096V
        #  -   2 = +/-2.048V
        #  -   4 = +/-1.024V
        #  -   8 = +/-0.512V
        #  -  16 = +/-0.256V
        # See table 3 in the ADS1015/ADS1115 datasheet for more info on gain.

        # Soil moisture sensor powerd by a GPIO line -> 3.3
        self.gain = 1

        #Set gain to 2/3 to monitor battery while it is charging
        #self.gain = 2/3

        #Resolution is 16 bits so 2^16 = 65536
        #self.resolution = 65536
        #self.resmin =  -32768
        #self.resmax = 32767
        #self.gainV = 6.144

        #Compute resolution in volts according to gain
        self.resolution = self.res_dict[self.gain] / 32768 / 1000
        self.channel = 0

        #frequency. Not used for the moment
        self.data_rate = None  # 250 samples per second <- it was here

        #self.device = 0x01 #16-bit ADC ADS1115
        self.adc = ADS1115()

        #dry run
        self.raw = 0
        self.min = 0
        self.max = 0
        self.volts = 0

        #Configure GPIO mode and channels
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.POWER_PIN, GPIO.OUT, initial=GPIO.LOW)

        self.readCalibration()
        self.readData()

        self.status = "Idle"
def getPressure(drucksensor_num):
    if drucksensor_num == 5:
        addr = 0x49
        drucksensor_num = 1
    else:
        addr = 0x48

    adc = ADS1115(address=addr)
    GAIN = 1
    # adc.start_adc(drucksensor_num, gain=GAIN)
    valueOfADC = adc.read_adc(drucksensor_num - 1,
                              gain=GAIN)  # abs(adc.get_last_result())
    volt = (valueOfADC / 32767) * 4.096
    #bar = round((10 / 3.3) * volt, 2)      # 4-20mA entspricht 0-3.3V
    #bar = round((125/33) * volt - 2.5, 2)   # 0-20mA entspricht 0-3.3V
    bar = round((125 / 24) * volt - 2.5, 2)  # 0-25mA entspricht 0-3V
    return bar
Example #10
0
def main():
    set("delayed", "0")
    set("mode", "servo")
    set("servo_max", "180")
    set("active", "1")

    delay_period = 0.01
    t = 0
    scale = 200

    ########given#######
    # state launch conditions
    R = 287  # J/(kg*K)
    # h_o = 0  # m
    # P_o = 101300  # Pa
    # L = -0.0065  # K/m
    # T_o = 273  # K
    # g = 9.81  # m/s^2
    # state the gain of controller
    kp = 2
    ki = 0
    kd = 1
    # initialize fin position
    phi = 0  # degrees
    setServo(phi)
    # state desired roll
    r = 10  # degrees/s

    while True:  # infinite loop
        # calculate time
        t_old = t
        t = current_milli_time()
        del_t = t - t_old
        # calcualte om_x, om_y, om_z angular velocities
        # read straight from MPU-6050 gyroscope (scaled)
        om_x = read_word_2c(0x43) / 131
        om_y = read_word_2c(0x45) / 131
        om_z = read_word_2c(0x47) / 131
        # calculate roll, pitch, yaw angular positions
        roll = om_x * del_t
        pitch = om_y * del_t
        yaw = om_z * del_t
        # calcualte al_x, al_y, al_z angular accelerations
        al_x = om_x / del_t
        al_y = om_y / del_t
        al_z = om_z / del_t
        # calcualte a_x, a_y, a_z accelerations
        # read straight from ADXL377 high-g accelerometer
        a_x = arduino_map(adc.read_adc(0), 0, 675, -scale, scale)
        a_y = arduino_map(adc.read_adc(1), 0, 675, -scale, scale)
        a_z = arduino_map(adc.read_adc(2), 0, 675, -scale, scale)
        # calculate x, y, z position
        x = a_x / (del_t) ^ 2
        y = a_y / (del_t) ^ 2
        z = a_z / (del_t) ^ 2
        # calculate u, v, w velocities
        u = a_x / del_t
        v = a_y / del_t
        w = a_z / del_t
        # calculate P, T, h, rho
        # read from BMP180 sensor
        P = BMP180.read_pressure()
        P_o = BMP180.read_sealevel_pressure()
        T = BMP180.read_temperature()
        rho = P / (R * T)
        h = BMP180.read_altitude()
        # h = (T/L)*((P_o/P)^(R*L/g)-1)+h_o
        # calculate error
        e = r - roll
        e_int = e * t
        e_der = e / del_t
        # apply the controlled gain to the servo based on the error
        phi = kp * e + ki * e_int + kd * e_der
        setServo(phi)
        time.sleep(delay_period)
        var = [
            t, del_t, roll, pitch, yaw, om_x, om_y, om_z, al_x, al_y, al_z, x,
            y, z, u, v, w, a_x, a_y, a_z, phi, e, P, T, rho, h
        ]
        write_to_csv(var)
        # write out to .csv file
        # delay to protect code from breaking.
        time.sleep(0.010)  # seconds
Example #11
0
 def __init__(self):
     from Adafruit_ADS1x15 import ADS1115
     self._adc = ADS1115(busnum=1)
Example #12
0
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
# LED Pin
#LEDPIN = 18
#GPIO.setup(LEDPIN,GPIO.OUT)
#GPIO.output(LEDPIN,0)
# 1st mirocontroller communication
# assumption: when 1st micrcontroller starts process, it will send a continuous HIGH signal to the 2nd microcontroller.
ReadDigitalPin = 15
GPIO.setup(ReadDigitalPin, GPIO.IN)
# Event parameters
running = False
raw_data = False
# ADS1115 ADC (16-bit) instance
adc = ADS1115()
GAIN = 1
# "samples per second" (ADC's conversion time = 1/sps)
# does not change internal sampling rate [lower sps = more data averaged per sample]
sps = 860
# Data storage
data = []
# Paths
rpi_specific_path = "/home/pi/ADC/data"
print("Setup complete")

# LOOP
while True:
    try:
        # While pin is HIGH...
        while GPIO.input(ReadDigitalPin) == 1:
Example #13
0
def runedna(cfg: Config,
            deployment: Deployment,
            df: Datafile,
            prfilt: Callable[[float], float]) -> bool:
    logger = logging.getLogger()
    logger.info("Starting deployment: %s", deployment.id)

    if cfg.has_section("Metadata"):
        meta = []
        for key in cfg.options("Metadata"):
            meta.append(key)
            meta.append(cfg.get_string("Metadata", key))
        df.add_record("metadata", meta)

    # Extract parameters from configuration files
    try:
        pr = dict()
        adc = ADS1115(address=cfg.get_int('Adc', 'Addr'),
                      busnum=cfg.get_int('Adc', 'Bus'))
        pr["Filter"] = PrSensor(adc,
                                cfg.get_int('Pressure.Filter', 'Chan'),
                                cfg.get_expr('Pressure.Filter', 'Gain'),
                                coeff=cfg.get_array('Pressure.Filter', 'Coeff'))
        pr["Env"] = PrSensor(adc,
                             cfg.get_int('Pressure.Env', 'Chan'),
                             cfg.get_expr('Pressure.Env', 'Gain'),
                             coeff=cfg.get_array('Pressure.Env', 'Coeff'))
        # Discard the first sample
        psi_to_dbar(pr["Env"].read())

        prmax = cfg.get_float('Pressure.Filter', 'Max')

        def checkpr() -> Tuple[float, bool]:
            psi = pr["Filter"].read()
            return psi, psi < prmax

        def checkdepth(limits: Tuple[float, float]) -> Tuple[float, bool]:
            dbar = psi_to_dbar(pr["Env"].read())
            return prfilt(dbar), limits[0] <= dbar <= limits[1]

        pumps = dict()
        for key in ("Sample", "Ethanol"):
            pumps[key] = Pump(cfg.get_int('Motor.'+key, 'Enable'))

        valves = dict()
        for key in ("1", "2", "3", "Ethanol"):
            vkey = "Valve." + key
            valves[key] = Valve(cfg.get_int(vkey, 'Enable'),
                                cfg.get_int(vkey, 'IN1'),
                                cfg.get_int(vkey, 'IN2'),
                                lopen=cfg.get_string(vkey, 'open'),
                                lclose=cfg.get_string(vkey, 'close'))

        fm = AnalogFlowMeter(adc,
                             cfg.get_int('AnalogFlowSensor', 'Chan'),
                             cfg.get_expr('AnalogFlowSensor', 'Gain'),
                             cfg.get_array('AnalogFlowSensor', 'Coeff'))
        sample_rate = cfg.get_float('FlowSensor', 'Rate')
        ledctl = LedCtl(obj=LED(cfg.get_int("LED", "GPIO")),
                        fast=cfg.get_float("LED", "fast"),
                        slow=cfg.get_float("LED", "slow"),
                        fade=cfg.get_float("LED", "fade"))

        limits = dict()
        for key in ("Sample", "Ethanol"):
            limits[key] = FlowLimits(amount=cfg.get_float('Collect.'+key, 'Amount'),
                                     time=cfg.get_float('Collect.'+key, 'Time'))

        deployment.seek_err = cfg.get_float('Deployment', 'SeekErr')
        deployment.depth_err = cfg.get_float('Deployment', 'DepthErr')
        deployment.pr_rate = cfg.get_float('Deployment', 'PrRate')
        deployment.seek_time = cfg.get_int('Deployment', 'SeekTime')
        deployment.downcast = cfg.get_bool('Deployment', 'Downcast')

        # Each entry in depths is a tuple containing the depth and
        # the sample index.
        depths = []
        for i, key in enumerate(['Sample.1', 'Sample.2', 'Sample.3']):
            depths.append((cfg.get_float(key, 'Depth'), i+1))
    except BadEntry:
        logger.exception("Configuration error")
        return False

    try:
        batteries = [Battery(SMBus(0)), Battery(SMBus(1))]
    except Exception:
        logger.exception("Battery monitoring disabled")
        batteries = []

    # Samples are collected in depth order, not index order.
    depths.sort(key=lambda e: e[0], reverse=not deployment.downcast)
    for target, index in depths:
        logger.info("Seeking depth for sample %d; %.2f +/- %.2f",
                    index, target, deployment.seek_err)
        drange = (target-deployment.seek_err, target+deployment.seek_err)
        with blinker(ledctl.obj, ledctl.slow):
            depth, status = seekdepth(df,
                                      partial(checkdepth, drange),
                                      deployment.pr_rate,
                                      deployment.seek_time)
        if not status:
            logger.critical("Depth seek time limit expired. Aborting.")
            return False

        logger.info("Collecting sample %d", index)
        drange = (depth-deployment.depth_err, depth+deployment.depth_err)
        status = collect(df, index,
                         (pumps["Sample"], pumps["Ethanol"]),
                         valves,
                         fm, sample_rate,
                         (limits["Sample"], limits["Ethanol"]),
                         checkpr,
                         partial(checkdepth, drange), batteries)

    return True
Example #14
0
def main():
    parser = argparse.ArgumentParser(description="Prime an eDNA flow path")
    parser.add_argument("cfg",
                        metavar="FILE",
                        help="system configuration file")
    parser.add_argument("valve",
                        metavar="N",
                        type=int,
                        help="valve# to prime, 1-3")
    parser.add_argument("--time",
                        metavar="SECS",
                        type=float,
                        default=30,
                        help="runtime in seconds")
    parser.add_argument("--prmax",
                        metavar="PSI",
                        type=float,
                        default=12,
                        help="maximum filter pressure in psi")
    args = parser.parse_args()

    try:
        cfg = Config(args.cfg)
    except Exception as e:
        print("Error loading config file; " + str(e), file=sys.stderr)
        sys.exit(1)

    if args.valve < 1 or args.valve > 3:
        print("Valve number must be between 1 and 3", file=sys.stderr)
        sys.exit(1)

    logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
                        level=logging.INFO,
                        datefmt='%Y-%m-%d %H:%M:%S',
                        stream=sys.stderr)

    # eDNA uses the Broadcom SOC pin numbering scheme
    GPIO.setmode(GPIO.BCM)
    try:
        adc = ADS1115(address=0x48, busnum=cfg.get_int('Adc', 'Bus'))
        pr_chan = cfg.get_int('Pressure.Filter', 'Chan')
        pr_gain = cfg.get_float('Pressure.Filter', 'Gain')

        motor = cfg.get_int('Motor.Sample', 'Enable')
        GPIO.setup(motor, GPIO.OUT)

        # Config file key for valve
        vkey = "Valve." + str(args.valve)
        sample_valve = Valve(cfg.get_int(vkey, 'Enable'),
                             cfg.get_int(vkey, 'Power'),
                             cfg.get_int(vkey, 'Gnd'))
        eth_valve = Valve(cfg.get_int('Valve.Ethanol', 'Enable'),
                          cfg.get_int('Valve.Ethanol', 'Power'),
                          cfg.get_int('Valve.Ethanol', 'Gnd'))
    except BadEntry as e:
        print(str(e), file=sys.stderr)
        GPIO.cleanup()
        sys.exit(2)

    try:
        prime_cycle(sample_valve, eth_valve, motor,
                    partial(checkpr, adc, pr_chan, pr_gain, args.prmax),
                    args.time)
    finally:
        GPIO.cleanup()
Example #15
0
#!/usr/bin/env python

#must get adc library from https://github.com/adafruit/Adafruit_Python_ADS1x15.git
#check https://learn.adafruit.com/raspberry-pi-analog-to-digital-converters/ads1015-slash-ads1115
#channels 0-3 are conneted to potentiameter, and chip connects to SDA and SCL on pi

import RPi.GPIO as GPIO
import rospy
from Adafruit_ADS1x15 import ADS1115
adc = ADS1115()  #declares adc as an object of the ADS1115 class
r = rospy.Rate(10)  #10 Hz


def reader():
    pot1 = 0  #intialize potentiameters & use them as 4 ch of adc
    pot2 = 1
    pot3 = 2
    pot4 = 3

    while not rospy.is_shutdown():
        val1 = adc.read_adc(pot1, 0)
        val2 = adc.read_adc(pot2, 0)
        val3 = adc.read_adc(pot3, 0)
        val4 = adc.read_adc(pot4, 0)

        rospy.loginfo("Potentiameter 1 reading: " + str(val1))
        rospy.loginfo("Potentiameter 2 reading: " + str(val2))
        rospy.loginfo("Potentiameter 3 reading: " + str(val3))
        rospy.loginfo("Potentiameter 4 reading: " + str(val4))
        r.sleep()
Example #16
0
 def __init__(self):
     self.adc = ADS1115()
     self.logger = logging.getLogger(__name__)
Example #17
0
class ControlBoard(Device):
    def __init__(self):

        two_up = os.path.abspath(os.path.join(__file__, ".."))
        rel_path = "controlboard_config.json"
        abs_file_path = os.path.join(two_up, rel_path)
        abs_file_path = os.path.abspath(os.path.realpath(abs_file_path))
        config = open(file=abs_file_path)

        super().__init__(config)
        self.adc = ADC()
        GPIO.setmode(GPIO.BCM)
        """
        Define pin numbers to which units are connected on Pi.
        """
        self.redSwitch = 27
        self.orangeSwitch = 22
        self.greenSwitch = 18
        self.mainSwitch = 23
        self.switches = [
            self.redSwitch,
            self.orangeSwitch,
            self.greenSwitch,
            self.mainSwitch,
        ]

        self.redLight1 = 9
        self.redLight2 = 15
        self.redLight3 = 17
        self.greenLight1 = 10
        self.greenLight2 = 14
        self.greenLight3 = 4

        self.redLEDs = [self.redLight1, self.redLight2, self.redLight3]
        self.greenLEDs = [self.greenLight1, self.greenLight2, self.greenLight3]

        self.a_pin0 = 24
        self.a_pin1 = 25
        self.a_pin2 = 8
        self.b_pin0 = 7
        self.b_pin1 = 1
        self.b_pin2 = 12

        GPIO.setup(self.redSwitch, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(self.orangeSwitch, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(self.greenSwitch, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(self.mainSwitch, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        GPIO.setup(self.redLight1, GPIO.OUT)
        GPIO.setup(self.redLight2, GPIO.OUT)
        GPIO.setup(self.redLight3, GPIO.OUT)
        GPIO.setup(self.greenLight1, GPIO.OUT)
        GPIO.setup(self.greenLight2, GPIO.OUT)
        GPIO.setup(self.greenLight3, GPIO.OUT)

        GPIO.setup(self.a_pin0, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.a_pin1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.a_pin2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.b_pin0, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.b_pin1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.b_pin2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

    def get_sliders_analog_reading(self):
        positions = [0, 0, 0]
        for channel in range(0, 3):
            positions[channel] = round(100 -
                                       (self.adc.read_adc(channel) / 266))
        return positions

    def status_binair_to_bool(self, binair):
        if binair == 0:
            return False
        else:
            return True

    def status_binair_to_sting(self, binair):
        if binair == 0:
            return "uit"
        else:
            return "aan"

    def get_status(self):
        """
        Return status of switches, LEDs and sliders of device.
        """
        return {
            "redSwitch":
            self.status_binair_to_bool(GPIO.input(self.redSwitch)),
            "orangeSwitch":
            self.status_binair_to_bool(GPIO.input(self.orangeSwitch)),
            "greenSwitch":
            self.status_binair_to_bool(GPIO.input(self.greenSwitch)),
            "mainSwitch":
            self.status_binair_to_bool(GPIO.input(self.mainSwitch)),
            "greenLight1":
            self.status_binair_to_sting(GPIO.input(self.greenLight1)),
            "greenLight2":
            self.status_binair_to_sting(GPIO.input(self.greenLight2)),
            "greenLight3":
            self.status_binair_to_sting(GPIO.input(self.greenLight3)),
            "redLight1":
            self.status_binair_to_sting(GPIO.input(self.redLight1)),
            "redLight2":
            self.status_binair_to_sting(GPIO.input(self.redLight2)),
            "redLight3":
            self.status_binair_to_sting(GPIO.input(self.redLight3)),
            "slider1":
            self.get_sliders_analog_reading()[0],
            "slider2":
            self.get_sliders_analog_reading()[1],
            "slider3":
            self.get_sliders_analog_reading()[2],
        }

    def perform_instruction(self, action):
        """
        Set here the mapping from messages to methods.
        Should return warning when illegal instruction was sent
        or instruction could not be performed.
        """
        instruction = action.get("instruction")
        if instruction == "blink":
            self.blink(action.get("component_id"), action.get("value"))
        elif instruction == "turnOnOff":
            self.turn_on_off(action.get("component_id"), action.get("value"))
        else:
            return False

        return True

    def blink(self, component, args):
        led = getattr(self, component)

        time.sleep(args[1])  # delay
        interval = args[0]
        GPIO.output(led, GPIO.HIGH)
        time.sleep(interval)
        GPIO.output(led, GPIO.LOW)
        time.sleep(interval)
        GPIO.output(led, GPIO.HIGH)
        time.sleep(interval)
        GPIO.output(led, GPIO.LOW)
        time.sleep(interval)

    def turn_on_off(self, component, arg):
        led = getattr(self, component)
        if arg:
            GPIO.output(led, GPIO.HIGH)
        else:
            GPIO.output(led, GPIO.LOW)

    def test(self):
        for j in range(0, 3):
            for i in range(0, 3):
                GPIO.output(self.redLEDs[i], GPIO.HIGH)
                GPIO.output(self.greenLEDs[i], GPIO.HIGH)
                time.sleep(0.2)
            for i in range(0, 3):
                GPIO.output(self.redLEDs[i], GPIO.LOW)
                GPIO.output(self.greenLEDs[i], GPIO.LOW)
                time.sleep(0.2)

    def __status_update(self, channel):
        self.status_changed()

    def setup_events(self):

        GPIO.add_event_detect(
            device.redSwitch,
            GPIO.BOTH,
            callback=self.__status_update,
            bouncetime=100,
        )
        GPIO.add_event_detect(
            device.orangeSwitch,
            GPIO.BOTH,
            callback=self.__status_update,
            bouncetime=100,
        )
        GPIO.add_event_detect(
            device.greenSwitch,
            GPIO.BOTH,
            callback=self.__status_update,
            bouncetime=100,
        )
        GPIO.add_event_detect(
            device.mainSwitch,
            GPIO.BOTH,
            callback=self.__status_update,
            bouncetime=100,
        )
        GPIO.add_event_detect(
            device.a_pin0,
            GPIO.BOTH,
            callback=self.__status_update,
        )
        GPIO.add_event_detect(
            device.a_pin1,
            GPIO.BOTH,
            callback=self.__status_update,
        )
        GPIO.add_event_detect(
            device.a_pin2,
            GPIO.BOTH,
            callback=self.__status_update,
        )
        GPIO.add_event_detect(
            device.b_pin0,
            GPIO.BOTH,
            callback=self.__status_update,
        )
        GPIO.add_event_detect(
            device.b_pin1,
            GPIO.BOTH,
            callback=self.__status_update,
        )
        GPIO.add_event_detect(
            device.b_pin2,
            GPIO.BOTH,
            callback=self.__status_update,
        )

    def loop(self):
        previous = self.get_sliders_analog_reading()
        while True:
            positions = self.get_sliders_analog_reading()
            if previous != positions:
                self.status_changed()
                previous = positions

    def reset(self):
        for i in range(0, 3):
            GPIO.output(self.redLEDs[i], GPIO.LOW)
            GPIO.output(self.greenLEDs[i], GPIO.LOW)

    def main(self):
        self.setup_events()
        self.start(loop=self.loop, stop=GPIO.cleanup)
Example #18
0
def runtest(cfg: Config, args: argparse.Namespace,
            df: Optional[Datafile]) -> bool:
    logger = logging.getLogger()
    # Extract parameters from configuration files
    try:
        sens = dict()
        adc = ADS1115(address=cfg.get_int('Adc', 'Addr'),
                      busnum=cfg.get_int('Adc', 'Bus'))
        sens["Filter"] = PrSensor(adc, cfg.get_int('Pressure.Filter', 'Chan'),
                                  cfg.get_expr('Pressure.Filter', 'Gain'))

        prmax = cfg.get_float('Pressure.Filter', 'Max')

        def checkpr() -> Tuple[float, bool]:
            psi = sens["Filter"].read()
            return psi, psi < prmax

        pumps = dict()
        for key in ("Sample", "Ethanol"):
            pumps[key.lower()] = Pump(cfg.get_int('Motor.' + key, 'Enable'))

        valves = dict()
        for key in ("1", "2", "3", "Ethanol"):
            vkey = "Valve." + key
            valves[key.lower()] = Valve(cfg.get_int(vkey, 'Enable'),
                                        cfg.get_int(vkey, 'IN1'),
                                        cfg.get_int(vkey, 'IN2'),
                                        lopen=cfg.get_string(vkey, 'open'),
                                        lclose=cfg.get_string(vkey, 'close'))

        fm = AnalogFlowMeter(adc, cfg.get_int('AnalogFlowSensor', 'Chan'),
                             cfg.get_expr('AnalogFlowSensor', 'Gain'),
                             cfg.get_array('AnalogFlowSensor', 'Coeff'))
    except BadEntry:
        logger.exception("Configuration error")
        return False

    if args.pump not in pumps:
        logger.critical("Invalid pump name: '%s'", args.pump)
        return False

    if args.valve not in valves:
        logger.critical("Invalid valve: '%s'", args.valve)
        return False

    interval = 1. / args.rate
    print("Enter ctrl-c to exit ...", file=sys.stderr)
    try:
        fm.reset()
        with valves[args.valve]:
            with pumps[args.pump]:
                for tick in ticker(interval):
                    amount, secs = fm.amount()
                    pr, pr_ok = checkpr()
                    rec = OrderedDict(elapsed=round(secs, 3),
                                      vol=round(amount, 3),
                                      pr=round(pr, 3))
                    writerec(rec)
                    if df:
                        df.add_record("flow", rec, ts=tick)
    except KeyboardInterrupt:
        print("done", file=sys.stderr)

    return True
Example #19
0
 def __init__(self, address=0x48, i2cLock=None):
     self.__can = ADS1115(address)
     self.__i2cLock = i2cLock