Beispiel #1
0
def myaddress():

    mylist = hat_list(filter_by_id=HatIDs.MCC_134)

    address = mylist[0].address

    return str(address)
Beispiel #2
0
def index2():
    #address = select_hat_device(HatIDs.MCC_134)
    mylist = hat_list(filter_by_id=HatIDs.MCC_134)
    address = mylist[1].address

    hat = mcc134(address)
    tc_type = TcTypes.TYPE_K  # change this to the desired thermocouple type
    delay_between_reads = 1  # Seconds
    channels = (0, 1, 2, 3)

    lib = cdll.LoadLibrary('/usr/local/lib/liblifepo4wered.so')

    for channel in channels:
        hat.tc_type_write(channel, tc_type)

    tempZero = str("{:.2f}".format((hat.t_in_read(0) * 1.8) + 32))
    tempOne = str("{:.2f}".format((hat.t_in_read(1) * 1.8) + 32))
    tempTwo = str("{:.2f}".format((hat.t_in_read(2) * 1.8) + 32))
    tempThree = str("{:.2f}".format((hat.t_in_read(3) * 1.8) + 32))

    vbat = str(lib.read_lifepo4wered(10))

    return jsonify(temp1=tempZero,
                   temp2=tempOne,
                   temp3=tempTwo,
                   temp4=tempThree,
                   BatteryVoltage=vbat)
Beispiel #3
0
def main():
    """ Main function """
    log_period = 5*60

    if KEY == "<my_key>":
        print("The default key must be changed to the user's personal IFTTT "
              "Webhooks key before using this example.")
        sys.exit()

    # Find the first MCC 128
    mylist = hats.hat_list(filter_by_id=hats.HatIDs.MCC_128)
    if not mylist:
        print("No MCC 128 boards found")
        sys.exit()

    board = hats.mcc128(mylist[0].address)

    board.a_in_mode_write(hats.AnalogInputMode.SE)
    board.a_in_range_write(hats.AnalogInputRange.BIP_10V)

    while True:
        # read the voltages
        value_0 = board.a_in_read(0)
        value_1 = board.a_in_read(1)

        send_trigger(EVENT_NAME, "{:.3f}".format(value_0),
                     "{:.3f}".format(value_1))
        print("Sent data {0:.3f}, {1:.3f}.".format(value_0, value_1))
        time.sleep(log_period)
Beispiel #4
0
def create_hat_selector():
    """
    Gets a list of available MCC 134 devices and creates a corresponding
    dash-core-components Dropdown element for the user interface.

    Returns:
        dcc.Dropdown: A dash-core-components Dropdown object.
    """
    hats = hat_list(filter_by_id=HatIDs.MCC_134)
    hat_selection_options = []
    for hat in hats:
        # Create the label from the address and product name
        label = '{0}: {1}'.format(hat.address, hat.product_name)
        # Create the value by converting the descriptor to a JSON object
        option = {'label': label, 'value': json.dumps(hat._asdict())}
        hat_selection_options.append(option)

    selection = None
    if hat_selection_options:
        selection = hat_selection_options[0]['value']

    return dcc.Dropdown(  # pylint: disable=no-member
        id='hatSelector',
        options=hat_selection_options,
        value=selection,
        clearable=False)
Beispiel #5
0
 def run(self, channels=[0, 2, 4]):
     '''
     Run class that will be called by Cortix
     Returns data in predetermined format (format undecided)
     '''
     hatlist = hat_list()
     for i in hatlist:
         ad = i.address
     hat = mcc118(ad)
     options = OptionFlags.DEFAULT
     avgs = dict()
     mcc = self.get_port('mcc-plot')
     tempfile = '{}/{}.csv'.format(self.wrk_dir, self.fname)
     if os.path.exists(tempfile):
         os.remove(tempfile)
     check = True
     while True:
         self.timestamp = str(datetime.datetime.now())[:-7]
         minutes = self.timestamp[14:16]
         filetime = str(datetime.datetime.now())[:10]
         self.filename = os.path.join(self.db_dir,
                                      self.fname + filetime + '.csv')
         for i in channels:
             if str(i) not in avgs:
                 avgs[str(i)] = []
             value = hat.a_in_read(i, options)
             avgs[str(i)].append(value)
         if len(avgs[str(i)]) < 400:
             len(avgs[str(i)])
             time.sleep(0.00005)
             continue
         for i in channels:
             i = str(i)
             avgs[i] = sum(avgs[i]) / len(avgs[i])
         if not os.path.isfile(self.filename):
             header = 'Date and Time, '
             with open(self.filename, 'w') as f:
                 for i in channels:
                     header += 'Chan {}, '.format(i)
                 header += '\sn'
                 f.write(header)
         dataline = self.timestamp
         with open(self.filename, 'a') as f:
             for i in channels:
                 dataline += ', '
                 dataline += '{}'.format(avgs[str(i)])
             dataline += '\n'
             f.write(dataline)
         if minutes == '59' and check == True:
             self.df = pd.read_csv(self.filename,
                                   sep=', ',
                                   engine='python',
                                   index_col=False)
             self.send(self.df, mcc)
             check == False
         if minutes != '59':
             check = True
         avgs = dict()
Beispiel #6
0
def CheckDAQBoard():

    # get hat list of MCC daqhat boards
    board_list = hat_list(filter_by_id=HatIDs.ANY)
    if not board_list:
        print("No boards found")
        sys.exit()
    for entry in board_list:
        if entry.id == HatIDs.MCC_118:
            print("Board {}: MCC 118".format(entry.address))
            board = mcc118(entry.address)
    return board
Beispiel #7
0
    def __init__(self):
        '''
        Detect boards and get ready to be interrupted
        '''
        self.running = False

        # get hat list of MCC daqhat boards
        self.boards = hat_list(filter_by_id=HatIDs.MCC_118)
        self.boardsEntry = []
        for entry in self.boards:
            self.boardsEntry.append(mcc118(entry.address))
        if not self.boards:
            sys.stderr.write("No boards found\n")
            sys.exit()
Beispiel #8
0
    def main(self):

        lis=daqhats.hat_list()
        for i in lis:
            print(i)
            ad=i.address
        hat=mcc118(ad)
        options = OptionFlags.DEFAULT
        chan=0
        lis=[]
        while True:
            value = hat.a_in_read(0, options)
            print(value)
            time.sleep(0.1)
Beispiel #9
0
    def discover(cls):
        device_enumeration: list = []

        board_list = hat_list(filter_by_id=HatIDs.ANY)
        board_num = 0
        board_index = 0
        if not board_list:
            return device_enumeration
        for device in board_list:
            board_num = device.address
            # ul.create_daq_device(board_num, device)
            board_index = board_index + 2
            device_enumeration.append(MCCDAQHat(board_num, mcc152(board_num)))
        return device_enumeration
Beispiel #10
0
def select_hat_device(filter_by_id):
    # type: (HatIDs) -> int
    """
    This function performs a query of available DAQ HAT devices and determines
    the address of a single DAQ HAT device to be used in an example.  If a
    single HAT device is present, the address for that device is automatically
    selected, otherwise the user is prompted to select an address from a list
    of displayed devices.

    Args:
        filter_by_id (int): If this is :py:const:`HatIDs.ANY` return all DAQ
            HATs found.  Otherwise, return only DAQ HATs with ID matching this
            value.

    Returns:
        int: The address of the selected device.

    Raises:
        Exception: No HAT devices are found or an invalid address was selected.

    """
    selected_hat_address = None

    # Get descriptors for all of the available HAT devices.
    hats = hat_list(filter_by_id=filter_by_id)
    number_of_hats = len(hats)

    # Verify at least one HAT device is detected.
    if number_of_hats < 1:
        raise HatError(0, 'Error: No HAT devices found')
    elif number_of_hats == 1:
        selected_hat_address = hats[0].address
    else:
        # Display available HAT devices for selection.
        for hat in hats:
            print('Address ', hat.address, ': ', hat.product_name, sep='')
        print('')

        address = int(input('Select the address of the HAT device to use: '))

        # Verify the selected address if valid.
        for hat in hats:
            if address == hat.address:
                selected_hat_address = address
                break

    if selected_hat_address is None:
        raise ValueError('Error: Invalid HAT selection')

    return selected_hat_address
Beispiel #11
0
def main():
    """ Main function """

    if KEY == "<my_key>":
        print("The default key must be changed to the user's personal IFTTT "
              "Webhooks key before using this example.")
        sys.exit()

    # Find the first MCC 152
    mylist = hat_list(filter_by_id=HatIDs.MCC_152)
    if not mylist:
        print("No MCC 152 boards found")
        sys.exit()

    print("Using MCC 152 {}.".format(mylist[0].address))
    board = mcc152(mylist[0].address)

    # Reset the DIO to defaults (all channels input, pull-up resistors
    # enabled).
    board.dio_reset()

    # Read the initial input values so we don't trigger an interrupt when
    # we enable them.
    value = board.dio_input_read_bit(CHANNEL)

    # Enable latched input so we know that the value changed even if it changes
    # back to the original value before the interrupt callback.
    board.dio_config_write_bit(CHANNEL, DIOConfigItem.INPUT_LATCH, 1)

    # Unmask (enable) interrupts on the channel.
    board.dio_config_write_bit(CHANNEL, DIOConfigItem.INT_MASK, 0)

    print("Current input value is {}".format(value))
    print("Waiting for changes, Ctrl-C to exit. ")

    while True:
        # wait for a change
        wait_for_interrupt(-1)

        # a change occurred, verify it was from this channel before sending
        # a trigger
        status = board.dio_int_status_read_bit(CHANNEL)

        if status == 1:
            # Read the input to clear the active interrupt.
            value = board.dio_input_read_bit(CHANNEL)

            send_trigger(EVENT_NAME, "{}".format(value))
            print("Sent value {}.".format(value))
Beispiel #12
0
def main():
    """ Main function """
    log_period = 5 * 60
    channel = 0
    tc_type = TcTypes.TYPE_T

    if KEY == "<my_key>":
        print("The default key must be changed to the user's personal IFTTT "
              "Webhooks key before using this example.")
        sys.exit()

    # Find the first MCC 134
    mylist = hat_list(filter_by_id=HatIDs.MCC_134)
    if not mylist:
        print("No MCC 134 boards found")
        sys.exit()

    board = mcc134(mylist[0].address)

    # Configure the thermocouple type on the desired channel
    board.tc_type_write(channel, tc_type)

    # Set library update interval to a longer time since we are not reading
    # often.
    if log_period > 255:
        board.update_interval_write(60)
    else:
        board.update_interval_write(log_period)

    print("Logging temperatures, Ctrl-C to exit.")

    while True:
        # read the temperature
        temperature = board.t_in_read(channel)

        # check for errors
        if temperature == mcc134.OPEN_TC_VALUE:
            temp_val = "Open"
        elif temperature == mcc134.OVERRANGE_TC_VALUE:
            temp_val = "Overrange"
        elif temperature == mcc134.COMMON_MODE_TC_VALUE:
            temp_val = "Common mode"
        else:
            temp_val = "{:.2f}".format(temperature)

        send_trigger(EVENT_NAME, temp_val)

        time.sleep(log_period)
Beispiel #13
0
    def __mcc_118(self):
        '''
        IR 7040 "intelligent ratemeter from Mirion Tech. Inc.
        '''

        filename = self.__wrk_dir + '/mcc_118_data.csv'
        fout = open(filename, 'w')
        fout.write('This is the header\n')

        hatlist = hat_list()
        for i in hatlist:
            ad = i.address
        hat = mcc118(ad)
        options = OptionFlags.DEFAULT
        chan = 0
        while True:
            value = hat.a_in_read(0, options)
            fout.write(str(value) + '\n')
            time.sleep(0.1)
Beispiel #14
0
def main():
    """ Main function """

    # Find the first MCC 118
    mylist = hats.hat_list(filter_by_id=hats.HatIDs.MCC_118)
    if not mylist:
        print("No MCC 118 boards found")
        sys.exit()

    board = hats.mcc118(mylist[0].address)

    while True:
        # read the voltages
        value_0 = board.a_in_read(0)
        value_1 = board.a_in_read(1)

        send_trigger(EVENT_NAME, "{:.3f}".format(value_0),
                     "{:.3f}".format(value_1))
        print("Sent data {0:.3f}, {1:.3f}.".format(value_0, value_1))
        time.sleep(5*60)
    while True:
        try:
            s.connect(("8.8.8.8", 80))
            macAddress = s.getsockname()[0]
            s.close()
            return macAddress
        except:
            log("Failed to connect to internet... will try again soon.")
            time.sleep(5.0)

# Tell the world that we've booted and how to connect over ssh.  To login, use:
# ssh [email protected], where xxx.xxx.xxx is the MAC address from the tweet.
sendTweet("Booted with MAC address " + findMacAddress())

# Find the MCC 134
hats = hat_list(filter_by_id=HatIDs.MCC_134)
if not hats:
    sendTweet('No MCC 134 found, quiting')
    sys.exit()
else:
    log('Found MCC134')

board = mcc134(hats[0].address)

# Configure the thermocouple type on the channel 0
board.tc_type_write(channel, tc_type)

# Create new joke instance
weeklyJoke = Joke()

while True:
Beispiel #16
0
 def list_devices(self):
     """ List detected devices """
     self.dev_list = hat_list(HatIDs.MCC_118)
     addr_list = ["{}".format(dev.address) for dev in self.dev_list]
     return addr_list
Beispiel #17
0
def select_hat_devices(filter_by_id, number_of_devices):
    """
    This function performs a query of available DAQ HAT devices and determines
    the addresses of the DAQ HAT devices to be used in the example.  If the
    number of HAT devices present matches the requested number of devices,
    a list of all mcc118 objects is returned in order of address, otherwise the
    user is prompted to select addresses from a list of displayed devices.

    Args:
        filter_by_id (int): If this is :py:const:`HatIDs.ANY` return all DAQ
            HATs found.  Otherwise, return only DAQ HATs with ID matching this
            value.
        number_of_devices (int): The number of devices to be selected.

    Returns:
        list[mcc118]: A list of mcc118 objects for the selected devices
        (Note: The object at index 0 will be used as the master).

    Raises:
        HatError: Not enough HAT devices are present.

    """
    selected_hats = []

    # Get descriptors for all of the available HAT devices.
    hats = hat_list(filter_by_id=filter_by_id)
    number_of_hats = len(hats)

    # Verify at least one HAT device is detected.
    if number_of_hats < number_of_devices:
        error_string = ('Error: This example requires {0} MCC 118 HATs - '
                        'found {1}'.format(number_of_devices, number_of_hats))
        raise HatError(0, error_string)
    elif number_of_hats == number_of_devices:
        for i in range(number_of_devices):
            selected_hats.append(mcc118(hats[i].address))
    else:
        # Display available HAT devices for selection.
        for hat in hats:
            print('Address ', hat.address, ': ', hat.product_name, sep='')
        print('')

        for device in range(number_of_devices):
            valid = False
            while not valid:
                input_str = 'Enter address for HAT device {}: '.format(device)
                address = int(input(input_str))

                # Verify the selected address exists.
                if any(hat.address == address for hat in hats):
                    valid = True
                else:
                    print('Invalid address - try again')

                # Verify the address was not previously selected
                if any(hat.address() == address for hat in selected_hats):
                    print('Address already selected - try again')
                    valid = False

                if valid:
                    selected_hats.append(mcc118(address))

    return selected_hats
# The Python package is named daqhats. Use it in your code with import daqhats.
#

# read MCC 118 voltage inputs and display channel values (analog input values)

#!/usr/bin/env python
#
import sys
from daqhats import hat_list, HatIDs, mcc118

# get hat list of MCC daqhat boards
board_list = hat_list(filter_by_id = HatIDs.ANY)
if not board_list:
    print("No boards found")
    sys.exit()

# Read and display every channel
for entry in board_list: 
    if entry.id == HatIDs.MCC_118:
        print("Board {}: MCC 118".format(entry.address))
        board = mcc118(entry.address)
        for channel in range(board.info().NUM_AI_CHANNELS):
            value = board.a_in_read(channel)
            print("Ch {0}: {1:.3f}".format(channel, value))	
Beispiel #19
0
def main():
    """ Main function """

    if KEY == "<my_key>":
        print("The default key must be changed to the user's personal IFTTT "
              "Webhooks key before using this example.")
        sys.exit()

    # Find the first MCC 134
    mylist = hat_list(filter_by_id=HatIDs.MCC_134)
    if not mylist:
        print("No MCC 134 boards found")
        sys.exit()

    board = mcc134(mylist[0].address)

    # Configure for type T thermocouple
    board.tc_type_write(CHANNEL, TcTypes.TYPE_T)

    # Read and display current temperature
    temperature = board.t_in_read(CHANNEL)
    print("Current temperature: {:.2f}.".format(temperature))
    print("Monitoring temperature, Ctrl-C to exit. ")

    alarm_set = False
    error_value = 0.0

    while True:
        # read the temperature
        temperature = board.t_in_read(CHANNEL)

        # check for errors
        if temperature == mcc134.OPEN_TC_VALUE:
            if error_value != temperature:
                error_value = temperature
                send_trigger(EVENT_NAME, "{:.0f}".format(temperature),
                             "{:.2f}".format(CLEAR_THRESHOLD),
                             "Open thermocouple")
                print("Open thermocouple.")
        elif temperature == mcc134.OVERRANGE_TC_VALUE:
            if error_value != temperature:
                error_value = temperature
                send_trigger(EVENT_NAME, "{:.0f}".format(temperature),
                             "{:.2f}".format(CLEAR_THRESHOLD), "Overrange")
                print("Overrange.")
        elif temperature == mcc134.COMMON_MODE_TC_VALUE:
            if error_value != temperature:
                error_value = temperature
                send_trigger(EVENT_NAME, "{:.0f}".format(temperature),
                             "{:.2f}".format(CLEAR_THRESHOLD),
                             "Common mode error")
                print("Common mode error.")
        else:
            # compare against the thresholds; change the logic if using falling
            # temperature alarm
            if alarm_set:
                if ((ALARM_RISING and (temperature < CLEAR_THRESHOLD)) or
                    (not ALARM_RISING and (temperature > CLEAR_THRESHOLD))):
                    # we crossed the clear threshold, send a trigger
                    alarm_set = False
                    send_trigger(EVENT_NAME, "{:.2f}".format(temperature),
                                 "{:.2f}".format(CLEAR_THRESHOLD), "cleared")
                    print("Temp: {:.2f}, alarm cleared.".format(temperature))
            else:
                if ((ALARM_RISING and (temperature >= ALARM_THRESHOLD)) or
                    (not ALARM_RISING and (temperature <= ALARM_THRESHOLD))):
                    # we crossed the alarm threshold, send a trigger
                    alarm_set = True
                    send_trigger(EVENT_NAME, "{:.2f}".format(temperature),
                                 "{:.2f}".format(ALARM_THRESHOLD), "set")
                    print("Temp: {:.2f}, alarm set.".format(temperature))

        time.sleep(1)
    ]
except (OSError, serial.SerialException) as e:
    print("Problem setting up the OMRON sensors", e)
    exit()

# set up connection to Graphite database
sock = socket.socket()
sock.connect((GRAPHITE_IP, GRAPHITE_PORT))
starttime = time.time()

# configure the thermocouple
# type e
tc_type = daqhats.TcTypes.TYPE_E
delay_between_read = 60  # in seconds
channels = (0, 1)  # of four possible
tc_address = daqhats.hat_list(filter_by_id=daqhats.HatIDs.MCC_134)[0].address
tc_hat = daqhats.mcc134(tc_address)
try:
    for channel in channels:
        tc_hat.tc_type_write(channel, tc_type)
except (HatError, ValueError) as e:
    print("\n", e)
    exit()

db = ([])
ii = 0
while True:
    ####
    #### OMRON 2JCIE BU01 environmental sensor
    ####
    # loop over two sensors
Beispiel #21
0
 def listDevices(self):
     self.dev_list = hat_list(HatIDs.MCC_118)
     addr_list = ["{}".format(dev.address) for dev in self.dev_list]
     return addr_list