示例#1
0
def session(request):
    s = Session(add_all=False)
    s, _ = _add_device(s)
    yield s

    # force session destruction
    s._close()
示例#2
0
def session(request):
    """Default session adding all attached devices."""
    s = Session()
    yield s

    # force session destruction
    s._close()
示例#3
0
def test_read_initial_data():
    """Verify data values of HI-Z samples on initial attach.

    See https://github.com/analogdevicesinc/m1k-fw/issues/9 for details.
    """
    sys.stdout.write('\n')
    prompt(
        'unplug the device, ground the metal USB connector, and plug it back in'
    )

    # create our own session to avoid detach exceptions
    session = Session(add_all=False)
    session, device = _add_device(session)

    samples = device.get_samples(100)
    assert len(samples) == 100

    # verify all samples are near 0
    tests = []
    for sample in samples:
        for x in chain.from_iterable(sample):
            tests.append(abs(round(x)) == 0)

    # old firmware versions exhibit bad data, newer versions should fix the issue
    if float(device.fwver) <= 2.10:
        assert not all(tests)
    else:
        assert all(tests)

    # request a bunch of extra samples to flush bad values
    device.get_samples(10000)
    # force session destruction
    session._close()
示例#4
0
def test_read_continuous_dataflow_raises():
    """Verify workflows that lead to data flow issues."""
    # create a session that doesn't ignore data flow issues
    session = Session(add_all=False, ignore_dataflow=False)
    session.scan()
    session.add(session.available_devices[0])
    device = session.devices[0]

    session.start(0)
    time.sleep(.5)
    with pytest.raises(SampleDrop):
        device.read(1000)

    # force session destruction
    session._close()
示例#5
0
def session(request):
    s = Session(add_all=False)

    if s.scan() == 0:
        # no devices plugged in
        raise ValueError

    s.add(s.available_devices[0])
    yield s

    # force session destruction
    s._close()
 def __init__(self):
     #start session
     self.session = Session()
     #define sample rate
     self.sample_rate=100000
     #define streaming sample size
     self.sample_size=1
     #get device
     try:
         self.device=self.session.devices[0]
     except IndexError:
         print("No Device Found")
         sys.exit(1)
     #initialize default mode to HI_Z
     self.device.channels['A'].mode=Mode.HI_Z
     self.device.channels['B'].mode=Mode.HI_Z
     #streaming parameters
     self._streaming=False
     self._lock=threading.RLock()
     #mode 
     self.mode_dict={'HI_Z': Mode.HI_Z,'SVMI': Mode.SVMI,'SIMV':Mode.SIMV}
     self.port_dict={'PIO_0': 28,'PIO_1': 29,'PIO_2': 47,'PIO_3': 3}
     self.read_samples=RRN.NewStructure("edu.rpi.robotics.m1k.read_samples")
     #wave dict
     self.wavedict = {
     ('A','sine'): self.device.channels['A'].sine,
     ('A','triangle'): self.device.channels['A'].triangle,
     ('A','sawtooth'): self.device.channels['A'].sawtooth,
     ('A','stairstep'): self.device.channels['A'].stairstep,
     ('A','square'): self.device.channels['A'].square,
     ('B','sine'): self.device.channels['B'].sine,
     ('B','triangle'): self.device.channels['B'].triangle,
     ('B','sawtooth'): self.device.channels['B'].sawtooth,
     ('B','stairstep'): self.device.channels['B'].stairstep,
     ('B','square'): self.device.channels['B'].square
     }
     # avoid crashing flag
     self.need_streaming=False
    samples_raw = dev.read(NUM_SAM_PTS, timeout=-1, skipsamples=True)
    for x in samples_raw:
        samples[0].append(x[0][0])
        samples[1].append(x[1][0])
    return (samples)


def data_gen():  # Must be iterator, therefor yield and While-loop
    #print('data_gen() ausgeführt.')
    while True:
        samples = get_samples()
        yield samples


try:
    session = Session()
    if session.devices:
        print('ADALM1000 gefunden...')
        dev = session.devices[0]
        # Set both channels to high impedance mode.
        chan_a = dev.channels['A']
        chan_a.mode = Mode.HI_Z
        chan_b = dev.channels['B']
        chan_b.mode = Mode.SVMI
        #chan_b.sine(0, 5, WAVEFORM_SAMPLES, -(WAVEFORM_SAMPLES / 4))
        chan_b.square(0, 5, WAVEFORM_SAMPLES, -(WAVEFORM_SAMPLES / 4), 0.5)
        # Start a continuous session.
        session.start(0)
        x = np.arange(0, num_dsp_pts, 1)
        fig, ax = plt.subplots()
        line_a, = ax.plot(x,
示例#8
0

def refill_data(num_samples, v=None):
    if v is None:
        # fill channels with a static, random integer between 0 and 5
        v = random.randint(0, 5)
    return [v] * num_samples
    # fill channels with a static, random float between -0.2 and 0.2
    #return [random.uniform(-0.2,0.2)] * num_samples


if __name__ == '__main__':
    # don't throw KeyboardInterrupt on Ctrl-C
    signal(SIGINT, SIG_DFL)

    session = Session()

    if session.devices:
        # Grab the first device from the session.
        dev = session.devices[0]

        # Ignore read buffer sample drops when printing to stdout.
        dev.ignore_dataflow = sys.stdout.isatty()

        # Set both channels to source voltage, measure current mode.
        chan_a = dev.channels['A']
        chan_b = dev.channels['B']
        chan_a.mode = Mode.SVMI
        chan_b.mode = Mode.SVMI
        #chan_a.mode = Mode.SIMV
        #chan_b.mode = Mode.SIMV
示例#9
0
def session():
    s = Session(add_all=False)
    yield s

    # force session destruction
    s._close()
示例#10
0

def set_channel_a_mode(received_mode, setpoint):
    """Set channel A mode."""
    if received_mode == Mode.SVMI:
        CHAN_A.mode = Mode.SVMI
        CHAN_A.write([setpoint], -1)
    elif received_mode == Mode.SIMV:
        CHAN_A.mode = Mode.SIMV
        CHAN_A.write([setpoint], -1)
    else:
        CHAN_A.mode = Mode.HI_Z


if __name__ == "__main__":
    SESSION = Session()
    VALID_SETPOINT = 0.0

    print 'Wait for device to be detected...'
    while not SESSION.devices:
        SESSION = Session()
    print 'Device detected...'

    if SESSION.devices:
        # Grab the first device from the session.
        DEV = SESSION.devices[0]

        # Set both channels to source voltage, measure current mode.
        CHAN_A = DEV.channels['A']
        CHAN_B = DEV.channels['B']
        CHAN_A.mode = Mode.HI_Z
示例#11
0
def session(request):
    s = Session()
    yield s

    # force session destruction
    s._close()
示例#12
0
FIRST_STAGE = False
SECOND_STAGE = True
THIRD_STAGE = False
FOURTH_STAGE = False

# Stop script execution until user press ENTER
BRAKE_SCRIPT = False

USB = LED(12)
if __name__ == '__main__':
    USB.off()
    sleep(2)
    USB.on()
    sleep(2)

    global_.session = Session()

    # print 'Wait for device to be detected...', \
    #     TEXT['orange'], inspect.stack()[0][1], TEXT['default']
    print TEXT['turquoise'], inspect.stack()[0][1], TEXT['default']
    while not global_.session.devices:
        global_.session = Session()
        sleep(1)
    # print 'Device detected... Continue calibration...'

    BOARD_NUMBER = len(global_.session.devices)
    if VIEW_DEBUG_MESSAGES:
        print 'Number of detected boards:', BOARD_NUMBER

    if global_.session.devices:
        while ORDER_INDEX <= BOARD_NUMBER:
示例#13
0
7.6.2020, S Mack
"""

import time

from pysmu import Session

# assign digital pins
PIO_0 = 28
PIO_1 = 29
PIO_2 = 47
PIO_3 = 3

try:
    session = Session(ignore_dataflow=True, queue_size=10000)
    if session.devices:
        dev = session.devices[0]
        while True:
            # get state of PIO0
            state = dev.ctrl_transfer(0xc0, 0x91, PIO_3, 0, 0, 1, 100)
            # funktioniert nicht...
            #for ch in state:
            #    print(ch)
            print(list(state))
            time.sleep(1)
    else:
        print('no devices attached')

except KeyboardInterrupt:
    print()
示例#14
0
def session(request):
    session = Session(add_all=False)
    session.scan()
    return session
示例#15
0
#!/usr/bin/env python
#
# Simple script showing how custom functions can be executed during hotplug
# events, use Ctrl-C to exit.

from __future__ import print_function

from signal import signal, SIG_DFL, SIGINT
import time

from pysmu import Session

session = Session()
last_devices = session.available_devices

while True:
    time.sleep(2)

    session.scan()
    available_devices = session.available_devices

    for other_device in last_devices:
        found = False

        for device in available_devices:
            if other_device.serial == device.serial:
                found = True
                break

        if not found:
            print("Device detached!")
示例#16
0
#!/usr/bin/env python
#
# Simple script showing how to get a set number of samples from all devices
# connected to a system.

from __future__ import print_function

import sys

from pysmu import Session, Mode


if __name__ == '__main__':
    session = Session()

    if not session.devices:
        sys.exit(1)

    for idx, dev in enumerate(session.devices):
        # Set all devices in the session to use source voltage, measure current
        # mode for channel A with a constant value based on their index.
        dev.channels['A'].mode = Mode.SVMI
        dev.channels['A'].constant(idx % 6)
        # Set all devices in the session to use source current, measure voltage
        # mode for channel B with a constant value of 0.05.
        dev.channels['B'].mode = Mode.SIMV
        dev.channels['B'].constant(0.05)

    # Run the session for at least 10 captured samples in noncontinuous mode.
    for dev_idx, samples in enumerate(session.get_samples(1000)):
        print('dev: {}'.format(dev_idx))
示例#17
0
    'Frequenz Start/Stopp: {}/{} Hz, Sin-Min: {} mA, Sin-Max: {} mA\n\n'.
    format(START_FREQ, STOP_FREQ, AWGB_IVAL_MIN, AWGB_IVAL_MAX))
meas_file.write(
    't [s]; f [Hz]; U_DC [V]; I_DC [mA]; U_AC [V]; I_AC [mA]; R_Diff [Ohm]; C [mAh] \n\n'
)

# 2. Thread starten
th.Thread(target=key_capture_thread,
          args=(),
          name='key_capture_thread',
          daemon=True).start()
print('Zum Beenden Return drücken...')
print()

session = Session(ignore_dataflow=True,
                  sample_rate=SAMP_RATE,
                  queue_size=NUM_SAMPLES)
if session.devices:
    dev = session.devices[0]
    DevID = dev.serial
    print("Device ID:" + str(DevID))
    FWRev = float(dev.fwver)
    HWRev = str(dev.hwver)
    print('Firmware Revision: {}, Hardware Revision: {}'.format(FWRev, HWRev))
    print()
    if FWRev < 2.17:
        print("WARNUNG: Firmware version > 2.16 noetig!")

    session.flush()
    CHA = dev.channels['A']  # Open CHA
    CHA.mode = Mode.HI_Z_SPLIT  # Put CHA in Hi Z split mode
示例#18
0
from signal import signal, SIG_DFL, SIGINT
import time

from pysmu import Session


def attached(dev):
    """Run when a device is plugged in."""
    print('device attached: {}'.format(dev))

def detached(dev):
    """Run when a device is unplugged."""
    print('device detached: {}'.format(dev))


if __name__ == '__main__':
    # don't throw KeyboardInterrupt on Ctrl-C
    signal(SIGINT, SIG_DFL)

    session = Session()

    # Register the functions above to get triggered during physical attach or
    # detach events. Multiple functions can be registered for either trigger if
    # required.
    session.hotplug_attach(attached)
    session.hotplug_detach(detached)

    print('waiting for hotplug events...')
    while True:
        time.sleep(1)
示例#19
0
#!/usr/bin/env python
#
# Simple script showing how to perform a non-continuous, multi-run session
# while changing cyclic buffer values.

from __future__ import print_function

import sys

from pysmu import Session, Mode

if __name__ == '__main__':
    session = Session()

    if not session.devices:
        sys.exit(1)

    for dev in session.devices:
        dev.channels['A'].mode = Mode.SVMI
        dev.channels['B'].mode = Mode.SIMV

    for x in range(21):
        # Write 1000 samples of incrementing voltage and current values to
        # channel A and B, respectively, for every device in the session.
        v = x * (5 / 20.0)
        i = ((x * (4 / 20.0)) / 10.0) - 0.2
        data = (([v] * 1000, [i] * 1000) for dev in session.devices)
        session.write(data, cyclic=True)

        for dev, samples in enumerate(session.get_samples(10)):
            print('dev: {}: chan A voltage: {}, chan B current: {}'.format(
示例#20
0
#!/usr/bin/env python
#
# Simple script showing how to write a sine/cosine wave to the attached devices and
# plot the resulting voltage output for both channels using matplotlib.

from __future__ import print_function

from collections import defaultdict
import sys

from pysmu import Session, Mode
import matplotlib.pyplot as plt

if __name__ == '__main__':
    session = Session()

    if not session.devices:
        sys.exit(1)

    waveform_samples = 500

    for i, dev in enumerate(session.devices):
        # Output a sine wave for channel A voltage.
        dev.channels['A'].mode = Mode.SVMI
        dev.channels['A'].sine(0, 5, waveform_samples, -(waveform_samples / 4))
        # Output a cosine wave for channel B voltage.
        dev.channels['B'].mode = Mode.SVMI
        dev.channels['B'].sine(0, 5, waveform_samples, 0)

    chan_a = defaultdict(list)
    chan_b = defaultdict(list)
示例#21
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ADALM1000
Beide ADCs auslesen
https://analogdevicesinc.github.io/libsmu/classsmu_1_1Signal.html

6.6.2020, S Mack
"""

import time

from pysmu import Session, Mode

try:
    session = Session()
    if session.devices:
        dev = session.devices[0]
        # Set both channels to high impedance mode.
        chan_a = dev.channels['A']
        chan_b = dev.channels['B']
        chan_a.mode = Mode.HI_Z
        chan_b.mode = Mode.HI_Z
        while True:
            samples = dev.get_samples(1000)
            for x in samples:
                print("{: 6f} {: 6f} {: 6f} {: 6f}".format(x[0][0], x[0][1], x[1][0], x[1][1]))
            time.sleep(1)
    else:
        print('no devices attached')
    
示例#22
0
                self.line_a.set_data(self.x_vals[:(self.n_d_pts - disp_start)],
                                     vals_a[disp_start:])
                self.line_b.set_data(self.x_vals[:(self.n_d_pts - disp_start)],
                                     vals_b[disp_start:])
        else:
            self.line_a.set_ydata(vals_a)  # plot new values
            self.line_b.set_ydata(vals_b)  # plot new values

    def yield_samples(self):  # Must be iterator and separate method
        while True:
            samples = self.get_samples()
            yield samples


try:
    session = Session()
    if session.devices:
        print('ADALM1000 gefunden...')
        fig, ax = plt.subplots()
        my_scope = Scope(ax,
                         session,
                         H_MAX,
                         V_RANGE,
                         n_s_pts=N_S_PTS,
                         red_rate=RED_RATE,
                         mode_a='Hi_Z',
                         mode_b='Hi_Z',
                         trig=TRIG)
        ani = animation.FuncAnimation(fig,
                                      func=my_scope.show_samples,
                                      frames=my_scope.yield_samples,