def reset_usb(self):
		if self.debug: Logging.info("Resetting connected usb interfaces")
		for i in subprocess.check_output(["lsusb"]).split("\n"):
			for k in self.interfaces:
				if k in i:
					try:
						subprocess.check_output(["sudo", "usbreset", "/dev/bus/usb/%s/%s" % (i[4:7], i[15:18])])
					except subprocess.CalledProcessError:
						self.reset_usb_controller()
	def reset_usb_controller(self):
		if self.debug: Logging.warning("Resetting usb controller")
		operating_system = open("/etc/issue").read()
		if operating_system == 'Debian GNU/Linux 7 \\n \\l\n\n':
			subprocess.check_output(["sudo", "service", "udev", "restart"])
		elif operating_system == "Raspbian GNU/Linux 7 \\n \\l\n\n":
			pass
		else:
			Logging.warning("OS does not support usb interface reset. Due to the instability issues with linux_gpib this could lead to problems.")
	def write(self, str, calls=0):
		try:
			gpib.write(self.id, str)
			self.last_write = str
		except gpib.GpibError:
			if calls == 2:
				Logging.error("Unrecoverable error. Please reboot")
				raw_input("Press ENTER when done.")
				exit(1)
			self.reset()
			self.write(str, calls=calls + 1)
 def write(self, str, calls=0):
     try:
         gpib.write(self.id, str)
         self.last_write = str
     except gpib.GpibError:
         if calls == 2:
             Logging.error("Unrecoverable error. Please reboot")
             raw_input("Press ENTER when done.")
             exit(1)
         self.reset()
         self.write(str, calls=calls + 1)
 def reset_usb_controller(self):
     if self.debug: Logging.warning("Resetting usb controller")
     operating_system = open("/etc/issue").read()
     if operating_system == 'Debian GNU/Linux 7 \\n \\l\n\n':
         subprocess.check_output(["sudo", "service", "udev", "restart"])
     elif operating_system == "Raspbian GNU/Linux 7 \\n \\l\n\n":
         pass
     else:
         Logging.warning(
             "OS does not support usb interface reset. Due to the instability issues with linux_gpib this could lead to problems."
         )
 def reset_usb(self):
     if self.debug: Logging.info("Resetting connected usb interfaces")
     for i in subprocess.check_output(["lsusb"]).split("\n"):
         for k in self.interfaces:
             if k in i:
                 try:
                     subprocess.check_output([
                         "sudo", "usbreset",
                         "/dev/bus/usb/%s/%s" % (i[4:7], i[15:18])
                     ])
                 except subprocess.CalledProcessError:
                     self.reset_usb_controller()
	def __init__(self, debug=False):
		if os.geteuid() != 0:
			Logging.error("You need to have root privileges to run this script.")
			self.started = False
			exit(1)
		self.started = True
		self.devices = {}
		self.drivers = {}
		self.debug = debug
		for i in dir(Drivers.USBTMC):
			if i[0] != "_" and i != "GenericDriver":
					driver = getattr(Drivers.USBTMC, i)
					if hasattr(driver, "DEVICES"):
						self.drivers.update(driver.DEVICES)
		if self.debug: Logging.info("Drivers for following devices have been loaded: %s" % self.drivers)
		devices = usbtmc.list_devices()
		progress_bar = ProgressBar(len(devices))
		progress = 0
		device_number = 0
		for device in devices:
			driver_avaliable = False
			inst = usbtmc.Instrument(device.idVendor, device.idProduct, device.serial_number)
			device_id = inst.ask("*IDN?")
			for i in self.drivers:
				if i in device_id:
					self.devices[device_number] = self.drivers[i](inst, device_id)
					driver_avaliable = True
			if not driver_avaliable:
				self.devices[device_number] = Drivers.USBTMC.GenericDriver.GenericDriver(inst, device_id)
			progress += 1
			device_number += 1
			progress_bar.update(progress)
		for i in self.devices:
			Logging.header("%s discovered on virtual port %s" % (self.devices[i].device_id, i))
		Logging.success("Discovery finished successfully!")
	def __init__(self, sad=0, timeout=13, send_eoi=1, eos_mode=0, debug=False, reset=False, interfaces=[]):
		if os.geteuid() != 0:
			Logging.error("You need to have root privileges to run this script.")
			self.started = False
			exit(1)
		self.debug = debug
		self.reset = reset
		self.devices = {}
		self.started = True
		self.drivers = {}
		# We go through each driver and look at the attribute DEVICES which contains all devices the driver should be loaded for.
		for i in dir(Drivers.GPIB):
			if i[0] != "_" and i != "GenericDriver":
				driver = getattr(Drivers.GPIB, i)
				if hasattr(driver, "DEVICES"):
					self.drivers.update(driver.DEVICES)
		if self.debug: Logging.info("Drivers for following devices have been loaded: %s" % self.drivers)
		self.reset_usb_controller()
		# Interface ids are used to determine which usb connections need to be reset
		# Example:
		"""
		Bus 001 Device 006: ID 3923:709b National Instruments Corp. GPIB-USB-HS
		"""
		self.interfaces = ["3923:709b", "0957:0518"] + interfaces
		self.reset_interfaces()
		progress_bar = ProgressBar(30)
		discovered = {}
		for pad in range(0, 31):
			id = gpib.dev(0, pad, sad, timeout, send_eoi, eos_mode)
			try:
				driver_avaliable = False
				gpib.clear(id)
				gpib.write(id, "*IDN?")
				device_id = gpib.read(id, 1024).rstrip()
				for i in self.drivers:
					if i in device_id:
						self.devices[pad] = self.drivers[i](GPIBCommunicator(id, self.reset_interfaces), device_id)
						driver_avaliable = True
				if not driver_avaliable:
					self.devices[pad] = Drivers.GPIB.GenericDriver.GenericDriver(GPIBCommunicator(id, self.reset_interfaces), device_id)
				discovered[id] = device_id
			except gpib.GpibError:
				pass
			progress_bar.update(pad)
		for i in discovered:
			Logging.header("%s on %s" % (discovered[i], i - 16))
		Logging.success("Discovery finished successfully!")
Exemplo n.º 9
0
 def __init__(self, debug=False):
     if os.geteuid() != 0:
         Logging.error(
             "You need to have root privileges to run this script.")
         self.started = False
         exit(1)
     self.started = True
     self.devices = {}
     self.drivers = {}
     self.debug = debug
     for i in dir(Drivers.USBTMC):
         if i[0] != "_" and i != "GenericDriver":
             driver = getattr(Drivers.USBTMC, i)
             if hasattr(driver, "DEVICES"):
                 self.drivers.update(driver.DEVICES)
     if self.debug:
         Logging.info("Drivers for following devices have been loaded: %s" %
                      self.drivers)
     devices = usbtmc.list_devices()
     progress_bar = ProgressBar(len(devices))
     progress = 0
     device_number = 0
     for device in devices:
         driver_avaliable = False
         inst = usbtmc.Instrument(device.idVendor, device.idProduct,
                                  device.serial_number)
         device_id = inst.ask("*IDN?")
         for i in self.drivers:
             if i in device_id:
                 self.devices[device_number] = self.drivers[i](inst,
                                                               device_id)
                 driver_avaliable = True
         if not driver_avaliable:
             self.devices[
                 device_number] = Drivers.USBTMC.GenericDriver.GenericDriver(
                     inst, device_id)
         progress += 1
         device_number += 1
         progress_bar.update(progress)
     for i in self.devices:
         Logging.header("%s discovered on virtual port %s" %
                        (self.devices[i].device_id, i))
     Logging.success("Discovery finished successfully!")
 def reset_interfaces(self, calls=0):
     if self.debug: Logging.info("Resetting connected interfaces")
     self.reset_usb()
     time.sleep(2)
     if self.debug: Logging.info("Running gpib_config")
     try:
         subprocess.check_call(["sudo", "gpib_config"])
     except subprocess.CalledProcessError:
         if calls == 2:
             Logging.error("No interface connected")
             exit(1)
         self.reset_interfaces(calls=calls + 1)
     time.sleep(2)
	def reset_interfaces(self, calls=0):
		if self.debug: Logging.info("Resetting connected interfaces")
		self.reset_usb()
		time.sleep(2)
		if self.debug: Logging.info("Running gpib_config")
		try:
			subprocess.check_call(["sudo", "gpib_config"])
		except subprocess.CalledProcessError:
			if calls == 2:
				Logging.error("No interface connected")
				exit(1)
			self.reset_interfaces(calls=calls + 1)
		time.sleep(2)
	def read(self, len=512, calls=0):
		try:
			result = gpib.read(self.id, len).rstrip("\n")
		except gpib.GpibError, e:
			Logging.warning(str(e))
			if str(e) == "read() failed: A read or write of data bytes has been aborted, possibly due to a timeout or reception of a device clear command.":
				Logging.info("Last write didn't succeed. Resending...")
				self.reset()
				self.write(self.last_write)
			if calls == 2:
				Logging.error("Unrecoverable error. Please reboot")
				raw_input("Press ENTER when done.")
				exit(1)
			self.reset()
			result = self.read(calls=calls + 1)
    def __init__(self, debug=False, baud=19200, timeout=0.1, parity=serial.PARITY_EVEN, rtscts=True, dsrdtr=True):
        self.devices = {}
        self.drivers = {}
        self.debug = debug
        for i in dir(Drivers.Serial):
            if i[0] != "_" and i != "GenericDriver":
                    driver = getattr(Drivers.Serial, i)
                    if hasattr(driver, "DEVICES"):
                        self.drivers.update(driver.DEVICES)
        if self.debug: Logging.info("Drivers for following devices have been loaded: %s" % self.drivers)
        dev_devices = []
        for dev_device in os.listdir("/dev/"):
            if "USB" in dev_device:   # Should be extended to also search for 'real' serial interfaces
                dev_devices.append(dev_device)
        progress_bar = ProgressBar(len(dev_devices))
        progress = 0
        device_number = 0
        for device in dev_devices:
            driver_avaliable = False
            
            ser = serial.Serial(port='/dev/' + device, baudrate=baud, bytesize=serial.EIGHTBITS, parity=serial.PARITY_EVEN, stopbits=serial.STOPBITS_ONE, timeout=timeout, xonxoff=False, rtscts=True, write_timeout=None, dsrdtr=None, inter_byte_timeout=None)

            ser.reset_input_buffer()
            ser.reset_output_buffer()
            
            inst = io.TextIOWrapper(io.BufferedRWPair(ser, ser, 1), newline=None, line_buffering = True, encoding='ascii') 
            time.sleep(1) # activation of serial interface does usually take some time
            
            # Asking for the device identifier
            inst.write(unicode('*IDN?\n'))
            time.sleep(0.1)
            ret = inst.readline()    
            device_id =ret.rstrip()

            for i in self.drivers:
                if i in device_id:
                    self.devices[device_number] = self.drivers[i](inst, device_id)
                    driver_avaliable = True
            if not driver_avaliable:
                self.devices[device_number] = Drivers.Serial.GenericDriver.GenericDriver(inst, device_id)
            
            progress += 1
            device_number += 1
            progress_bar.update(progress)
        for i in self.devices:
            Logging.header("%s discovered on virtual port %s" % (self.devices[i].device_id, i))
        Logging.success("Discovery finished successfully!")
 def read(self, len=512, calls=0):
     try:
         result = gpib.read(self.id, len).rstrip("\n")
     except gpib.GpibError, e:
         Logging.warning(str(e))
         if str(
                 e
         ) == "read() failed: A read or write of data bytes has been aborted, possibly due to a timeout or reception of a device clear command.":
             Logging.info("Last write didn't succeed. Resending...")
             self.reset()
             self.write(self.last_write)
         if calls == 2:
             Logging.error("Unrecoverable error. Please reboot")
             raw_input("Press ENTER when done.")
             exit(1)
         self.reset()
         result = self.read(calls=calls + 1)
# Written for pyserial 3.X (update via pip if needed)

import TermOut.Logging as Logging

try:
    import serial
except ImportError:
    Logging.error("pyserial not installed")
    exit(1)

import io  # suggested from pyserial developers to use for commands linke readline()

from TermOut.ProgressBar import ProgressBar
import os
import time
import sys
import Drivers.Serial


class Serial:
    def __init__(self,
                 debug=False,
                 baud=19200,
                 timeout=0.1,
                 parity=serial.PARITY_EVEN,
                 rtscts=True,
                 dsrdtr=True):
        self.devices = {}
        self.drivers = {}
        self.debug = debug
        for i in dir(Drivers.Serial):
Exemplo n.º 16
0
"""
Created by: Nico Leidenfrost, Philip Trauner

Required software:
- USBTMC: https://github.com/python-ivi/python-usbtmc
- PyUSB: https://github.com/walac/pyusb
"""

import TermOut.Logging as Logging
try:
    import usbtmc
except ImportException:
    Logging.error("usbtmc not installed")
    exit(1)
from TermOut.ProgressBar import ProgressBar
import os
import time
import subprocess
import sys
import Drivers.USBTMC


class USBTMC:
    def __init__(self, debug=False):
        if os.geteuid() != 0:
            Logging.error(
                "You need to have root privileges to run this script.")
            self.started = False
            exit(1)
        self.started = True
        self.devices = {}
    def __init__(self,
                 sad=0,
                 timeout=13,
                 send_eoi=1,
                 eos_mode=0,
                 debug=False,
                 reset=False,
                 interfaces=[]):
        if os.geteuid() != 0:
            Logging.error(
                "You need to have root privileges to run this script.")
            self.started = False
            exit(1)
        self.debug = debug
        self.reset = reset
        self.devices = {}
        self.started = True
        self.drivers = {}
        # We go through each driver and look at the attribute DEVICES which contains all devices the driver should be loaded for.
        for i in dir(Drivers.GPIB):
            if i[0] != "_" and i != "GenericDriver":
                driver = getattr(Drivers.GPIB, i)
                if hasattr(driver, "DEVICES"):
                    self.drivers.update(driver.DEVICES)
        if self.debug:
            Logging.info("Drivers for following devices have been loaded: %s" %
                         self.drivers)
        self.reset_usb_controller()
        # Interface ids are used to determine which usb connections need to be reset
        # Example:
        """
		Bus 001 Device 006: ID 3923:709b National Instruments Corp. GPIB-USB-HS
		"""
        self.interfaces = ["3923:709b", "0957:0518"] + interfaces
        self.reset_interfaces()
        progress_bar = ProgressBar(30)
        discovered = {}
        for pad in range(0, 31):
            id = gpib.dev(0, pad, sad, timeout, send_eoi, eos_mode)
            try:
                driver_avaliable = False
                gpib.clear(id)
                gpib.write(id, "*IDN?")
                device_id = gpib.read(id, 1024).rstrip()
                for i in self.drivers:
                    if i in device_id:
                        self.devices[pad] = self.drivers[i](GPIBCommunicator(
                            id, self.reset_interfaces), device_id)
                        driver_avaliable = True
                if not driver_avaliable:
                    self.devices[
                        pad] = Drivers.GPIB.GenericDriver.GenericDriver(
                            GPIBCommunicator(id, self.reset_interfaces),
                            device_id)
                discovered[id] = device_id
            except gpib.GpibError:
                pass
            progress_bar.update(pad)
        for i in discovered:
            Logging.header("%s on %s" % (discovered[i], i - 16))
        Logging.success("Discovery finished successfully!")
import TermOut.Logging as Logging
try:
    import gpib
except ImportError:
    Logging.error("linux_gpib not installed or Python bindings not built")
    exit(1)
from TermOut.ProgressBar import ProgressBar
import os
import subprocess
import time
import sys
import Drivers.GPIB


class GPIB:
    def __init__(self,
                 sad=0,
                 timeout=13,
                 send_eoi=1,
                 eos_mode=0,
                 debug=False,
                 reset=False,
                 interfaces=[]):
        if os.geteuid() != 0:
            Logging.error(
                "You need to have root privileges to run this script.")
            self.started = False
            exit(1)
        self.debug = debug
        self.reset = reset
        self.devices = {}
from USBTMC import USBTMC
from GPIB import GPIB
from Serial import Serial
import time
import TermOut.Logging as Logging

usb = USBTMC()
gpib = GPIB()
serial = Serial()

devices = []

for i in usb.devices:
	devices.append(usb.devices[i])

for i in gpib.devices:
	devices.append(gpib.devices[i])

for i in serial.devices:
	devices.append(serial.devices[i])

print(devices)
while 1:
	k = 0
	for i in devices:
		Logging.info(i.get("*IDN?").rstrip())
		k += 1
	Logging.header("Got answer from %s devices." % str(k))
	time.sleep(2)
#!/usr/bin/python

import sys
import os
from TermOut import Logging
import importlib

if sys.platform == "win32":
    Logging.error("Windows is not supported.")
    exit(1)

if len(sys.argv) == 2:
    if os.path.isfile(sys.argv[1]):
        import_path = os.path.dirname(sys.argv[1])
        if import_path != "":
            sys.path.append(os.path.abspath(import_path))
            os.chdir(import_path)
        importlib.import_module(
            os.path.basename(os.path.splitext(sys.argv[1])[0]))
    else:
        Logging.error("File does not exist")
else:
    Logging.error("Specify python file as second argument")
"""
Created by: Nico Leidenfrost, Philip Trauner

Required software:
- USBTMC: https://github.com/python-ivi/python-usbtmc
- PyUSB: https://github.com/walac/pyusb
"""

import TermOut.Logging as Logging
try:
	import usbtmc
except ImportException:
	Logging.error("usbtmc not installed")
	exit(1)
from TermOut.ProgressBar import ProgressBar
import os
import time
import subprocess
import sys
import Drivers.USBTMC

class USBTMC:
	def __init__(self, debug=False):
		if os.geteuid() != 0:
			Logging.error("You need to have root privileges to run this script.")
			self.started = False
			exit(1)
		self.started = True
		self.devices = {}
		self.drivers = {}
		self.debug = debug
import TermOut.Logging as Logging
try:
	import gpib
except ImportError:
	Logging.error("linux_gpib not installed or Python bindings not built")
	exit(1)
from TermOut.ProgressBar import ProgressBar
import os
import subprocess
import time
import sys
import Drivers.GPIB


class GPIB:
	def __init__(self, sad=0, timeout=13, send_eoi=1, eos_mode=0, debug=False, reset=False, interfaces=[]):
		if os.geteuid() != 0:
			Logging.error("You need to have root privileges to run this script.")
			self.started = False
			exit(1)
		self.debug = debug
		self.reset = reset
		self.devices = {}
		self.started = True
		self.drivers = {}
		# We go through each driver and look at the attribute DEVICES which contains all devices the driver should be loaded for.
		for i in dir(Drivers.GPIB):
			if i[0] != "_" and i != "GenericDriver":
				driver = getattr(Drivers.GPIB, i)
				if hasattr(driver, "DEVICES"):
					self.drivers.update(driver.DEVICES)
    def __init__(self,
                 debug=False,
                 baud=19200,
                 timeout=0.1,
                 parity=serial.PARITY_EVEN,
                 rtscts=True,
                 dsrdtr=True):
        self.devices = {}
        self.drivers = {}
        self.debug = debug
        for i in dir(Drivers.Serial):
            if i[0] != "_" and i != "GenericDriver":
                driver = getattr(Drivers.Serial, i)
                if hasattr(driver, "DEVICES"):
                    self.drivers.update(driver.DEVICES)
        if self.debug:
            Logging.info("Drivers for following devices have been loaded: %s" %
                         self.drivers)
        dev_devices = []
        for dev_device in os.listdir("/dev/"):
            if "USB" in dev_device:  # Should be extended to also search for 'real' serial interfaces
                dev_devices.append(dev_device)
        progress_bar = ProgressBar(len(dev_devices))
        progress = 0
        device_number = 0
        for device in dev_devices:
            driver_avaliable = False

            ser = serial.Serial(port='/dev/' + device,
                                baudrate=baud,
                                bytesize=serial.EIGHTBITS,
                                parity=serial.PARITY_EVEN,
                                stopbits=serial.STOPBITS_ONE,
                                timeout=timeout,
                                xonxoff=False,
                                rtscts=True,
                                write_timeout=None,
                                dsrdtr=None,
                                inter_byte_timeout=None)

            ser.reset_input_buffer()
            ser.reset_output_buffer()

            inst = io.TextIOWrapper(io.BufferedRWPair(ser, ser, 1),
                                    newline=None,
                                    line_buffering=True,
                                    encoding='ascii')
            time.sleep(
                1
            )  # activation of serial interface does usually take some time

            # Asking for the device identifier
            inst.write(unicode('*IDN?\n'))
            time.sleep(0.1)
            ret = inst.readline()
            device_id = ret.rstrip()

            for i in self.drivers:
                if i in device_id:
                    self.devices[device_number] = self.drivers[i](inst,
                                                                  device_id)
                    driver_avaliable = True
            if not driver_avaliable:
                self.devices[
                    device_number] = Drivers.Serial.GenericDriver.GenericDriver(
                        inst, device_id)

            progress += 1
            device_number += 1
            progress_bar.update(progress)
        for i in self.devices:
            Logging.header("%s discovered on virtual port %s" %
                           (self.devices[i].device_id, i))
        Logging.success("Discovery finished successfully!")
# Written for pyserial 3.X (update via pip if needed)

import TermOut.Logging as Logging

try:
    import serial
except ImportError:
    Logging.error("pyserial not installed")
    exit(1)

import io # suggested from pyserial developers to use for commands linke readline() 

from TermOut.ProgressBar import ProgressBar
import os
import time
import sys
import Drivers.Serial

class Serial:
    def __init__(self, debug=False, baud=19200, timeout=0.1, parity=serial.PARITY_EVEN, rtscts=True, dsrdtr=True):
        self.devices = {}
        self.drivers = {}
        self.debug = debug
        for i in dir(Drivers.Serial):
            if i[0] != "_" and i != "GenericDriver":
                    driver = getattr(Drivers.Serial, i)
                    if hasattr(driver, "DEVICES"):
                        self.drivers.update(driver.DEVICES)
        if self.debug: Logging.info("Drivers for following devices have been loaded: %s" % self.drivers)
        dev_devices = []
        for dev_device in os.listdir("/dev/"):