diff --git a/.gitignore b/.gitignore index 868139ac84a3c9d54009d39932c400f70aa6b886..a9d44d884ce7f4318b0e306224c2fdfdb8562ee1 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,7 @@ setup.py *.egg-info last_params last_params.yml + +\.idea/ + +dstat_interface/core/experiments/__pycache__/ diff --git a/CHANGELOG b/CHANGELOG index 8dd9358a63960720b0e749f002d1433ec44f87e0..49d3422436f22443c08a2983abe0f1f20db0c5d9 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,35 @@ +Version 1.4.6 + -Fixed data output for SWV/DPV forward/reverse current + -Working progress bars + -Refactored a lot of plotting code + -Calibration should work properly now + +Version 1.4.5 + -Made board definitions modular + -Fix several bugs with experiment parameters + -Uses DAC unit based parameters now (**REQUIRES dstat-firmware@9e4a9f or higher**) + -Change package import structure again (main must always be run as module now) + -Workaround for weird Gtk+3 redrawing bug on Windows + +Version 1.4.4 + -Make connection code more robust + -Execute button disabled until DStat is ready to start + -Supports new firmware version strings added in dstat-firmware@c5f9701 + -Experimental firmware upgrade tool (see DStat Menu) + -Fix many bugs + +Version 1.4.3 + -Fix another critical bug with Windows multiprocessing + -Allow normal exit even if DStat was never connected + -Store last parameters in user folder + +Version 1.4.2 + -Refactor to fix critical bug preventing running packaged versions. + +Version 1.4.1 + -Fixed voltage axis orientation for LSV, CV, SWV, and DPV (Thanks to Dan Bizzotto @ UBC) + -Tweaked paver files to make version detection work without git. + Version 1.4 -Switched to GTK+3 -Support new DStat communications protocol (requires dstat-firmware>fe50c38) diff --git a/MANIFEST.in b/MANIFEST.in index fefb590607d8a1af6e0f25aa8254d806bced5d50..711422bec61f13a1cdd36f8ff1f9c15f689fd444 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,7 +1,14 @@ include RELEASE-VERSION include version.py include setup.py +include main.py include paver-minilib.zip +include LICENSE +include CHANGELOG +include README.markdown +include core/utils/RELEASE-VERSION recursive-include dstat_interface * recursive-exclude dstat_interface *.pyc recursive-exclude dstat_interface *~ +recursive_exclude core last_params.yml +recursive-exclude . .DS_Store \ No newline at end of file diff --git a/README.markdown b/README.markdown index e47af15c9e60b4222d8462ea70f6718e752a1e65..573ea72e58b8d3271257dd55d6771a725a724edb 100644 --- a/README.markdown +++ b/README.markdown @@ -1,6 +1,8 @@ ##### _DStat is described in detail in [Dryden MDM, Wheeler AR (2015) DStat: A Versatile, Open-Source Potentiostat for Electroanalysis and Integration. PLoS ONE 10(10): e0140349. doi: 10.1371/journal.pone.0140349](http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0140349) If you use this information in published work, please cite accordingly._ --- +## Python 2.7 is now discontinued and gtk has always been a pain for cross-platform use, so I am in the process of writing a new interface in Python 3 and Qt that I hope will be working before too long. + This is the documentation for the DStat interface software. The DStat interface is written primarily in Python and runs on Linux, Mac, and Windows. It is the main method for running experiments on the DStat, controlling experimental parameters and collecting and plotting data. @@ -14,6 +16,7 @@ It currently has no abilities for analyzing recorded data or opening previously 2. [Old Homebrew Instructions](#old-homebrew-instructions) 1. [Linux](#linux) 2. [Windows](#windows) + 3. [Upgrading](#upgrading) 2. [Getting Started](#Getting-Started) # Introduction @@ -30,8 +33,10 @@ dstat-interface has moved to gtk+3 and we now recommend Anaconda/Miniconda for i 1. [Install Miniconda](https://repo.continuum.io/miniconda/Miniconda2-latest-MacOSX-x86_64.sh) It doesn't matter if you pick Python 2.7 or 3.5—this just sets Miniconda's default Python. (Skip if Miniconda or Anaconda are already installed) - 2. Create a new environment for dstat. In a terminal type: -````conda create -n dstat -c mdryden python=2.7 dstat-interface dstat-interface-deps```` + 2. Download the [conda env file](conda-env.yml). + + 3. In the terminal, create the dstat environment (replacing with the actual path to the file on your computer): +````conda env create -f ```` 3. Then to run dstat-interface: ````source activate dstat @@ -40,10 +45,12 @@ dstat-interface has moved to gtk+3 and we now recommend Anaconda/Miniconda for i #### Old Homebrew Instructions The easiest way to get most of the necessary requirements to run dstat-interface is using [Homebrew](http://brew.sh): - brew tap homebrew/python - brew update - brew install python gobject-introspection gtk+3 pygobject3 py2cairo scipy zeromq - brew install matplotlib --with-pygtk +```shell +brew tap homebrew/python +brew update +brew install python gobject-introspection gtk+3 pygobject3 py2cairo scipy zeromq +brew install matplotlib --with-pygtk +``` Be patient on the last step—matplotlib needs to be compiled and may take 2 or 3 minutes. @@ -56,17 +63,26 @@ The final requirements, can be installed using python's pip system: ## Linux Linux prerequisite installation is similar to that of MacOS with Homebrew, only using your distribution's native package manager rather than Homebrew, and X11 will likely be installed already. Some distributions may not have packages available for installing matplotlib or numpy, in which case, they should be installed using pip. -The final requirements, can be installed using python's pip system: +These instructions were tested on Ubuntu 17.04: - pip install pandas pyserial pyzmq pyyaml seaborn zmq-plugin +````shell +sudo apt-get install gobject-introspection python-gobject python-pip +pip install dstat-interface +```` + +You will need to add your user to the `dialout` group to access virtual serial ports (replace with your username): + +```shell +sudo usermod -a -G dialout +``` ## Windows The following terminal commands will result in a full installation of dstat-interface and its requirements, assuming [64-bit Miniconda][1] is installed: -```` +```shell conda create -n dstat -c mdryden python=2 dstat-interface activate dstat -```` +``` To finish the installation, GTK+3 and its Python bindings must be installed: @@ -84,12 +100,35 @@ and `deactivate` will return to the root environment. Therefore, to run dstat-interface from our environment, we must first activate it (if not already done) before launching it: - activate dstat - python -m dstat_interface.main +```shell +activate dstat +python -m dstat_interface.main +``` [1]: https://repo.continuum.io/miniconda/Miniconda2-latest-Windows-x86_64.exe [2]: https://sourceforge.net/projects/pygobjectwin32/ +## Upgrading + +Anaconda builds can be upgraded to the latest version by issuing this command (from an activated conda environment): + +```shell +conda upgrade -c mdryden dstat-interface # For MacOS, be sure to upgrade dstat-interface-deps as well +``` + +pip installs can be upgraded similarly: + +```shell +pip install --upgrade dstat-interface +``` + +You can also run development builds directly from a cloned git repository (from an activated conda environment): + +```shell +cd ~/src/dstat-interface/dstat_interface # Replace with path to dstat_interface folder inside repository +python -m main +``` + # Getting started ## Interface overview diff --git a/conda-env.yml b/conda-env.yml new file mode 100644 index 0000000000000000000000000000000000000000..8bce2bc1d5361d1cc80348a6a2fc7797b0d6820e --- /dev/null +++ b/conda-env.yml @@ -0,0 +1,137 @@ +name: dstat +channels: + - conda-forge + - mdryden + - defaults +dependencies: + - ca-certificates=2018.4.16=0 + - certifi=2018.4.16=py27_0 + - nb_conda_kernels=2.1.0=py27_0 + - openssl=1.0.2o=0 + - appnope=0.1.0=py27_0 + - backports=1.0=py27_0 + - backports_abc=0.5=py27_0 + - bleach=1.5.0=py27_0 + - configparser=3.5.0=py27_0 + - curl=7.54.1=0 + - cycler=0.10.0=py27_0 + - decorator=4.1.2=py27_0 + - entrypoints=0.2.3=py27_0 + - enum34=1.1.6=py27_0 + - expat=2.1.0=0 + - freetype=2.5.5=2 + - funcsigs=1.0.2=py27hb9f6266_0 + - functools32=3.2.3.2=py27_0 + - get_terminal_size=1.0.0=py27_0 + - gettext=0.19.8=1 + - git=2.11.1=0 + - html5lib=0.9999999=py27_0 + - icu=54.1=0 + - intel-openmp=2018.0.0=h8158457_8 + - ipykernel=4.6.1=py27_0 + - ipython=5.3.0=py27_0 + - ipython-notebook=4.0.4=py27_0 + - ipython_genutils=0.2.0=py27_0 + - jbig=2.1=0 + - jinja2=2.9.6=py27_0 + - jpeg=9b=0 + - jsonschema=2.6.0=py27_0 + - jupyter_client=5.1.0=py27_0 + - jupyter_core=4.3.0=py27_0 + - krb5=1.13.2=0 + - libcxx=4.0.1=h579ed51_0 + - libcxxabi=4.0.1=hebd6815_0 + - libffi=3.2.1=1 + - libgfortran=3.0.1=h93005f0_2 + - libiconv=1.14=0 + - libpng=1.6.30=1 + - libssh2=1.8.0=0 + - libtiff=4.0.6=3 + - llvmlite=0.21.0=py27hac8ee23_0 + - markupsafe=1.0=py27_0 + - matplotlib=2.0.2=np113py27_0 + - mistune=0.7.4=py27_0 + - mkl=2018.0.1=hfbd8650_4 + - nbconvert=5.2.1=py27_0 + - nbformat=4.4.0=py27_0 + - notebook=5.0.0=py27_0 + - numba=0.36.2=np113py27h7c931aa_0 + - numpy=1.13.3=py27h62f9060_0 + - pandas=0.20.3=py27_0 + - pandocfilters=1.4.2=py27_0 + - path.py=10.3.1=py27_0 + - pathlib2=2.3.0=py27_0 + - patsy=0.4.1=py27_0 + - pcre=8.39=1 + - pexpect=4.2.1=py27_0 + - pickleshare=0.7.4=py27_0 + - pip=9.0.1=py27_1 + - prompt_toolkit=1.0.15=py27_0 + - ptyprocess=0.5.2=py27_0 + - pygments=2.2.0=py27_0 + - pyparsing=2.2.0=py27_0 + - pyqt=5.6.0=py27_2 + - python=2.7.13=0 + - python-dateutil=2.6.1=py27_0 + - pytz=2017.2=py27_0 + - pyyaml=3.12=py27_0 + - pyzmq=16.0.2=py27_0 + - qt=5.6.2=2 + - readline=6.2=2 + - scandir=1.5=py27_0 + - scipy=1.0.0=py27h793f721_0 + - seaborn=0.8=py27_0 + - setuptools=36.4.0=py27_0 + - simplegeneric=0.8.1=py27_1 + - singledispatch=3.4.0.3=py27_0 + - sip=4.18=py27_0 + - six=1.10.0=py27_0 + - sqlite=3.13.0=0 + - ssl_match_hostname=3.5.0.1=py27_0 + - statsmodels=0.8.0=np113py27_0 + - subprocess32=3.2.7=py27_0 + - terminado=0.6=py27_0 + - testpath=0.3.1=py27_0 + - tk=8.5.18=0 + - tornado=4.5.2=py27_0 + - traitlets=4.3.2=py27_0 + - wcwidth=0.1.7=py27_0 + - wheel=0.29.0=py27_0 + - xz=5.2.3=0 + - yaml=0.1.6=0 + - zlib=1.2.11=0 + - adwaita-icon-theme=3.24.0=1 + - arrow=0.10.0=py27_0 + - at-spi2-atk=2.24.1=2 + - at-spi2-core=2.24.1=2 + - atk=2.24.0=3 + - cairo-gobject=1.14.8=8 + - dbus-client=1.10.18=0 + - dfu-programmer=0.7.2=2 + - dstat-interface=1.4.6=py27_0 + - dstat-interface-deps=1.0=0 + - gdk-pixbuf=2.36.6=2 + - glib=2.52.2=5 + - gobject-introspection=1.52.1=2 + - gtk3=3.22.15=4 + - harfbuzz=1.4.6=3 + - libepoxy=1.4.2=5 + - libusb=1.0.21=0 + - pango=1.40.6=2 + - pixman=0.34.0=1 + - py2cairo=1.10.0=py27_0 + - pygobject3=3.24.2=py27_3 + - pyserial=3.3=py27_0 + - zmq-plugin=0.2.post14=py27_0 + - pip: + - backports.shutil-get-terminal-size==1.0.0 + - backports.shutil-which==3.5.1 + - backports.ssl-match-hostname==3.5.0.1 + - chardet==3.0.4 + - colorama==0.3.9 + - idna==2.6 + - paver==1.2.4 + - pygobject==3.24.1 + - requests==2.18.4 + - urllib3==1.22 + - vmprof==0.4.10 diff --git a/dstat_interface/interface/__init__.py b/dstat_interface/core/__init__.py similarity index 100% rename from dstat_interface/interface/__init__.py rename to dstat_interface/core/__init__.py diff --git a/dstat_interface/analysis.py b/dstat_interface/core/analysis.py similarity index 96% rename from dstat_interface/analysis.py rename to dstat_interface/core/analysis.py index 3190989961710fef302ce07853761fe666b4d331..747df181ff7a3c1dacbe68a158c536b88704b6f2 100755 --- a/dstat_interface/analysis.py +++ b/dstat_interface/core/analysis.py @@ -21,16 +21,19 @@ Functions for analyzing data. """ import logging +import os from numpy import mean, trapz -logger = logging.getLogger('dstat.analysis') +logger = logging.getLogger(__name__) +mod_dir = os.path.dirname(os.path.abspath(__file__)) class AnalysisOptions(object): """Analysis options window.""" def __init__(self, builder): self.builder = builder - self.builder.add_from_file('interface/analysis_options.glade') + self.builder.add_from_file( + os.path.join(mod_dir, 'interface/analysis_options.glade')) self.builder.connect_signals(self) self.window = self.builder.get_object('analysis_dialog') diff --git a/dstat_interface/drivers/VirtualSerial.inf b/dstat_interface/core/drivers/VirtualSerial.inf similarity index 100% rename from dstat_interface/drivers/VirtualSerial.inf rename to dstat_interface/core/drivers/VirtualSerial.inf diff --git a/dstat_interface/dstat-interface.bat b/dstat_interface/core/dstat-interface.bat similarity index 100% rename from dstat_interface/dstat-interface.bat rename to dstat_interface/core/dstat-interface.bat diff --git a/dstat_interface/dstat.spec b/dstat_interface/core/dstat.spec similarity index 100% rename from dstat_interface/dstat.spec rename to dstat_interface/core/dstat.spec diff --git a/dstat_interface/core/dstat/__init__.py b/dstat_interface/core/dstat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1fb1ae912ef9bcc22c488a7df37de0af8ac3385f --- /dev/null +++ b/dstat_interface/core/dstat/__init__.py @@ -0,0 +1,3 @@ +from . import comm +from . import dfu +from . import state \ No newline at end of file diff --git a/dstat_interface/core/dstat/boards.py b/dstat_interface/core/dstat/boards.py new file mode 100755 index 0000000000000000000000000000000000000000..421e02c2ae406533241b1008d85ee97d650154d0 --- /dev/null +++ b/dstat_interface/core/dstat/boards.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# DStat Interface - An interface for the open hardware DStat potentiostat +# Copyright (C) 2017 Michael D. M. Dryden - +# Wheeler Microfluidics Laboratory +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import division, absolute_import, print_function, unicode_literals +import sys +import inspect +import logging + +from pkg_resources import parse_version, parse_requirements + +logger = logging.getLogger(__name__) + + +class BaseBoard(object): + pcb_version = 'x.x.x' + booster = False + + def __init__(self): + self.max_freq = 5000 + self.max_scans = 255 + self.max_time = 65535 + + self.setup() + assert len(self.gain) == self.gain_settings + assert len(self.gain_labels) == self.gain_settings + if self.gain_trim is not None: + assert len(self.gain_trim) == self.gain_settings + + def setup(self): + """Override in subclasses to provide correct numbers""" + self.gain = [1, 1e2, 3e3, 3e4, 3e5, 3e6, 3e7, 1e8] + self.gain_labels = ["Bypass", "100 Ω (15 mA FS)", "3 kΩ (500 µA FS)", + "30 kΩ (50 µA FS)", "300 kΩ (5 µA FS)", + "3 MΩ (500 nA FS)", "30 MΩ (50 nA FS)", + "100 MΩ (15 nA FS)" + ] + self.gain_trim = [None, 'r100_trim', 'r3k_trim', + 'r30k_trim', 'r300k_trim', 'r3M_trim', + 'r30M_trim', 'r100M_trim'] + self.gain_settings = len(self.gain) + self.gain_default_index = 2 + self.re_voltage_scale = 1 + + def test_mv(self, mv): + """Return true if voltage in mV is in range.""" + dac = float(mv)*self.re_voltage_scale/(3000./65536) + 32768 + + if 0 <= dac <= 65535: + return True + else: + return False + + def test_freq(self, hz): + """Return true if frequency in Hz is in range.""" + return 0 < float(hz) < self.max_freq + + def test_scans(self, n): + """Return true if number of scans is valid.""" + return 0 < int(n) < self.max_scans + + def test_s(self, s): + """Return true if time in integer seconds is valid.""" + return 0 < int(s) < self.max_time + + +class V1_1Board(BaseBoard): + pcb_version = '1.1' + + def setup(self): + self.gain = [1e2, 3e2, 3e3, 3e4, 3e5, 3e6, 3e7, 5e8] + self.gain_labels = [None, "300 Ω (5 mA FS)", + "3 kΩ (500 µA FS)", "30 kΩ (50 µA FS)", + "300 kΩ (5 µA FS)", "3 MΩ (500 nA FS)", + "30 MΩ (50 nA FS)", "500 MΩ (3 nA FS)" + ] + self.gain_trim = None + self.gain_settings = len(self.gain) + self.gain_default_index = 2 + self.re_voltage_scale = 1 + + +class V1_2Board(BaseBoard): + pcb_version = '1.2' + + def setup(self): + self.gain = [1, 1e2, 3e3, 3e4, 3e5, 3e6, 3e7, 1e8] + self.gain_labels = ["Bypass", "100 Ω (15 mA FS)", "3 kΩ (500 µA FS)", + "30 kΩ (50 µA FS)", "300 kΩ (5 µA FS)", + "3 MΩ (500 nA FS)", "30 MΩ (50 nA FS)", + "100 MΩ (15 nA FS)" + ] + self.gain_trim = [None, 'r100_trim', 'r3k_trim', + 'r30k_trim', 'r300k_trim', 'r3M_trim', + 'r30M_trim', 'r100M_trim'] + self.gain_settings = len(self.gain) + self.gain_default_index = 2 + self.re_voltage_scale = 1 + + +def __get_all_subclasses(cls): + all_subclasses = [] + + for subclass in cls.__subclasses__(): + all_subclasses.append(subclass) + all_subclasses.extend(__get_all_subclasses(subclass)) + + return all_subclasses + + +def find_board(version, booster=False): + """Returns highest compatible board class or None if none available.""" + boards = __get_all_subclasses(BaseBoard) + candidates = [] + for board in boards: + req = next(parse_requirements('dstat~={}'.format(board.pcb_version))) + if board.booster == booster and version in req: + candidates.append(board) + try: + picked = sorted(candidates, + key=lambda board: parse_version(board.pcb_version))[-1] + logger.info("Picked %s", picked) + return picked + except IndexError: + logger.warning("No matching board definition for ver: %s.", version) + return None diff --git a/dstat_interface/core/dstat/comm.py b/dstat_interface/core/dstat/comm.py new file mode 100755 index 0000000000000000000000000000000000000000..605961d47f3bf18699537d75515432d483ae9081 --- /dev/null +++ b/dstat_interface/core/dstat/comm.py @@ -0,0 +1,622 @@ +#!/usr/bin/env python +# DStat Interface - An interface for the open hardware DStat potentiostat +# Copyright (C) 2014 Michael D. M. Dryden - +# Wheeler Microfluidics Laboratory +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +from __future__ import division, absolute_import, print_function, unicode_literals + +import time +import struct +import multiprocessing as mp +from collections import OrderedDict +import logging + +from pkg_resources import parse_version + +try: + import gi + + gi.require_version('Gtk', '3.0') + from gi.repository import Gtk, GObject +except ImportError: + import sys + + print("ERR: GTK not available") + sys.exit(1) +import serial +from serial.tools import list_ports + +from . import state +from ..errors import InputError, VarError + +logger = logging.getLogger(__name__) +dstat_logger = logging.getLogger("{}.DSTAT".format(__name__)) +exp_logger = logging.getLogger("{}.Experiment".format(__name__)) + + +class AlreadyConnectedError(Exception): + def __init__(self): + super(AlreadyConnectedError, self).__init__(self, + "Serial instance already connected.") + + +class NotConnectedError(Exception): + def __init__(self): + super(NotConnectedError, self).__init__(self, + "Serial instance not connected.") + + +class ConnectionError(Exception): + def __init__(self): + super(ConnectionError, self).__init__(self, + "Could not connect.") + + +class TransmitError(Exception): + def __init__(self): + super(TransmitError, self).__init__(self, + "No reply received.") + + +def _serial_process(ser_port, proc_pipe, ctrl_pipe, data_pipe): + ser_logger = logging.getLogger("{}._serial_process".format(__name__)) + connected = False + + for i in range(5): + time.sleep(1) # Give OS time to enumerate + + try: + ser = serial.Serial(ser_port, timeout=1) + ser_logger.info("Connecting") + time.sleep(.5) + connected = True + except serial.SerialException: + pass + + if connected is True: + break + + try: + if ser.isOpen() is False: + ser_logger.info("Connection Error") + proc_pipe.send("SERIAL_ERROR") + return 1 + except UnboundLocalError: # ser doesn't exist + ser_logger.info("Connection Error") + proc_pipe.send("SERIAL_ERROR") + return 1 + + ser.write(b'!0 ') + + for i in range(10): + if ser.readline().rstrip() == b"@ACK 0": + if ser.readline().rstrip() == b"@RCV 0": + break + else: + time.sleep(.5) + ser.reset_input_buffer() + ser.write(b'!0 ') + time.sleep(.1) + + while True: + # These can only be called when no experiment is running + if ctrl_pipe.poll(): + ctrl_buffer = ctrl_pipe.recv() + if ctrl_buffer in ('a', "DISCONNECT"): + proc_pipe.send("ABORT") + try: + ser.write(b'a') + except serial.SerialException: + return 0 + ser_logger.info("ABORT") + + if ctrl_buffer == "DISCONNECT": + ser_logger.info("DISCONNECT") + ser.rts = False + ser._update_dtr_state() # Need DTR update on Windows + + ser.close() + proc_pipe.send("DISCONNECT") + return 0 + else: + ser.write(ctrl_buffer.encode('ascii')) + + elif proc_pipe.poll(): + while ctrl_pipe.poll(): + ctrl_pipe.recv() + try: + proc, params, state = proc_pipe.recv() + if params is None: + return_code = proc(state=state).run(ser, ctrl_pipe, data_pipe) + else: + return_code = proc(params, state).run(ser, ctrl_pipe, data_pipe) + except serial.SerialException: + proc_pipe.send("DISCONNECT") + ser.rts = False + ser._update_dtr_state() # Need DTR update on Windows + ser.close() + return 0 + ser_logger.info('Return code: %s', str(return_code)) + + proc_pipe.send(return_code) + + else: + time.sleep(.1) + + +class SerialConnection(GObject.Object): + __gsignals__ = { + 'connected': (GObject.SIGNAL_RUN_FIRST, None, ()), + 'disconnected': (GObject.SIGNAL_RUN_FIRST, None, ()) + } + + def __init__(self): + super(SerialConnection, self).__init__() + self.connected = False + + def connect(self, ser_port): + if self.connected is False: + self.proc_pipe_p, self.proc_pipe_c = mp.Pipe(duplex=True) + self.ctrl_pipe_p, self.ctrl_pipe_c = mp.Pipe(duplex=True) + self.data_pipe_p, self.data_pipe_c = mp.Pipe(duplex=True) + + self.proc = mp.Process(target=_serial_process, args=(ser_port, + self.proc_pipe_c, self.ctrl_pipe_c, + self.data_pipe_c)) + self.proc.start() + time.sleep(2) + if self.proc.is_alive() is False: + raise ConnectionError() + return False + self.connected = True + self.emit('connected') + return True + else: + raise AlreadyConnectedError() + return False + + def assert_connected(self): + if self.connected is False: + raise NotConnectedError() + + def start_exp(self, exp): + self.assert_connected() + clean_state = exp.state + try: + clean_state['dstat_version'] = None # Remove unpickleable Version class instance + except (TypeError, KeyError): + pass + try: + self.proc_pipe_p.send((type(exp), exp.parameters, clean_state)) + except AttributeError: + self.proc_pipe_p.send((type(exp), None, clean_state)) + + def stop_exp(self): + self.send_ctrl('a') + + def get_proc(self, block=False): + self.assert_connected() + + if block is True: + return self.proc_pipe_p.recv() + else: + if self.proc_pipe_p.poll() is True: + return self.proc_pipe_p.recv() + else: + return None + + def get_ctrl(self, block=False): + self.assert_connected() + + if block is True: + return self.ctrl_pipe_p.recv() + else: + if self.ctrl_pipe_p.poll() is True: + return self.ctrl_pipe_p.recv() + else: + return None + + def get_data(self, block=False): + self.assert_connected() + + if block is True: + return self.data_pipe_p.recv() + else: + if self.data_pipe_p.poll() is True: + return self.data_pipe_p.recv() + else: + return None + + def flush_data(self): + self.assert_connected() + + while self.data_pipe_p.poll() is True: + self.data_pipe_p.recv() + + def send_ctrl(self, ctrl): + self.assert_connected() + + self.ctrl_pipe_p.send(ctrl) + + def disconnect(self): + logger.info("Disconnecting") + self.send_ctrl('DISCONNECT') + self.proc.join() + self.emit('disconnected') + self.connected = False + + +class VersionCheck(object): + def __init__(self, parameters=None, state=None): + self.parameters = parameters + self.state = state + + def run(self, ser, ctrl_pipe, data_pipe): + """Tries to contact DStat and get version. Returns a tuple of + (major, minor). If no response, returns empty tuple. + + Arguments: + ser_port -- address of serial port to use + """ + try: + ser.reset_input_buffer() + ser.write('!1\n'.encode('ascii')) + + for i in range(10): + if ser.readline().rstrip() == b"@ACK 1": + ser.write(b'V\n') + if ser.readline().rstrip() == b"@RCV 1": + break + else: + time.sleep(.5) + ser.reset_input_buffer() + ser.write(b'!1\n') + time.sleep(.1) + + for line in ser: + line = line.decode('ascii') + dstat_logger.info(line) + if line.startswith('V'): + input = line.lstrip('V') + elif line.startswith("#"): + dstat_logger.info(line.strip()) + elif line.lstrip().startswith("@DONE"): + dstat_logger.debug(line.strip()) + ser.reset_input_buffer() + break + + pcb, sep, firmware = input.strip().rpartition('-') + + if pcb == "": + pcb = firmware + firmware = False + logger.info("Your firmware does not support version detection.") + + data_pipe.send((pcb, False)) + + else: + logger.info( + "Firmware Version: {}".format( + hex(int(firmware)).lstrip('0x') + ) + ) + data_pipe.send(( + pcb, + hex(int(firmware)).lstrip('0x') + )) + + logger.info( + "PCB Version: {}".format(pcb) + ) + + status = "DONE" + + except UnboundLocalError as e: + status = "SERIAL_ERROR" + except serial.SerialException as e: + logger.error('SerialException: %s', e) + status = "SERIAL_ERROR" + finally: + return status + + +def version_check(ser_port): + """Tries to contact DStat and get version. Stores version in state. + If no response, returns False, otherwise True. + + Arguments: + ser_port -- address of serial port to use + """ + state.ser = SerialConnection() + + state.ser.connect(ser_port) + state.ser.start_exp(VersionCheck()) + result = state.ser.get_proc(block=True) + if result == "SERIAL_ERROR": + state.dstat_version = None + state.firmware_version = None + return False + else: + buffer = state.ser.get_data(block=True) + version, state.firmware_version = buffer + state.dstat_version = parse_version(version) + logger.debug("version_check done") + time.sleep(.1) + + return True + + +class Settings(object): + def __init__(self, parameters=None, state=None): + self.parameters = parameters + self.state = state + self.task = parameters['task'] + try: + self.settings = parameters['settings'] + except KeyError: + pass + + def run(self, ser, ctrl_pipe, data_pipe): + """Tries to contact DStat and get settings. Returns dict of + settings. + """ + + self.ser = ser + + if self.task == 'w': + self.write() + + if self.task == 'r': + data_pipe.send(self.read()) + + status = "DONE" + + return status + + def read(self): + self.ser.reset_input_buffer() + self.ser.write('!2\n'.encode('ascii')) + + for i in range(10): + if self.ser.readline().rstrip() == b"@ACK 2": + self.ser.write('SR\n'.encode('ascii')) + if self.ser.readline().rstrip() == b"@RCV 2": + break + else: + time.sleep(.5) + self.ser.reset_input_buffer() + self.ser.write('!2\n'.encode('ascii')) + time.sleep(.1) + + for line in self.ser: + line_in = line.decode('ascii') + if line_in.lstrip().startswith('S'): + input = line_in.lstrip().lstrip('S') + elif line_in.lstrip().startswith("#"): + dstat_logger.info(line_in.strip()) + elif line_in.lstrip().startswith("@DONE"): + dstat_logger.debug(line_in.strip()) + self.ser.reset_input_buffer() + break + + parted = input.rstrip().split(':') + settings = OrderedDict((setting.split('.')[0], setting.split('.')[1]) for setting in parted) + + return settings + + def write_command(self, cmd, params=None, retry=5): + """Write command to serial with optional number of retries.""" + + def get_reply(retries=3): + while True: + reply = self.ser.readline().rstrip() + if reply.startswith(b'#'): + dstat_logger.info(reply) + elif reply == b"": + retries -= 1 + if retries <= 0: + raise TransmitError + else: + return reply + + n = len(cmd) + if params is not None: + n_params = len(params) + + for _ in range(retry): + tries = 5 + while True: + time.sleep(0.2) + self.ser.reset_input_buffer() + self.ser.write('!{}\n'.format(n).encode('ascii')) + time.sleep(.1) + + try: + reply = get_reply() + except TransmitError: + if tries <= 0: + continue + tries -= 1 + pass + else: + break + + if reply != f"@ACK {n}".encode('ascii'): + logger.warning("Expected ACK got: {}".format(reply)) + continue + + tries = 5 + + while True: + self.ser.write('{}\n'.format(cmd).encode('ascii')) + try: + reply = get_reply() + except TransmitError: + if tries <= 0: + continue + tries -= 1 + pass + else: + break + + if reply != f"@RCV {n}".encode('ascii'): + logger.warning("Expected RCV got: {}".format(reply)) + continue + + if params is None: + return True + + tries = 5 + + while True: + try: + reply = get_reply() + except TransmitError: + if tries <= 0: + continue + tries -= 1 + pass + else: + break + + if reply != f"@RQP {n_params}".encode('ascii'): + logger.warning("Expected RQP got: {}".format(reply)) + continue + + tries = 5 + + for i in params: + while True: + self.ser.write(i + " ".encode('ascii')) + try: + reply = get_reply() + if reply == f"@RCVC {i}".encode('ascii'): + break + except TransmitError: + if tries <= 0: + continue + tries -= 1 + pass + else: + break + return True + return False + + def write(self): + # write_buffer = range(len(self.settings)) + # + # for i in self.settings: # make sure settings are in right order + # write_buffer[self.settings[i][0]] = self.settings[i][1] + + to_write = " ".join(self.settings.values()) + " " + # n = len(to_write) + logger.debug("to_write = %s", to_write) + + if not self.write_command('SW' + to_write): + logger.error("Could not write command.") + + +def read_settings(): + """Tries to contact DStat and get settings. Returns dict of + settings. + """ + + state.ser.flush_data() + state.ser.start_exp(Settings(parameters={'task': 'r'})) + state.settings = state.ser.get_data(block=True) + + logger.info("Read settings from DStat") + logger.debug("read_settings: %s", state.ser.get_proc(block=True)) + + return + + +def write_settings(): + """Tries to write settings to DStat from global settings var. + """ + + logger.debug("Settings to write: %s", state.settings) + + state.ser.flush_data() + state.ser.start_exp(Settings(parameters={'task': 'w', 'settings': state.settings})) + logger.info("Wrote settings to DStat") + logger.debug("write_settings: %s", state.ser.get_proc(block=True)) + + return + + +class LightSensor(object): + def __init__(self): + pass + + def run(self, ser, ctrl_pipe, data_pipe): + """Tries to contact DStat and get light sensor reading. Returns uint of + light sensor clear channel. + """ + + ser.reset_input_buffer() + ser.write('!'.encode('ascii')) + + while not ser.read() == b"@": + self.ser.reset_input_buffer() + ser.write('!'.encode('ascii')) + + ser.write('T'.encode('ascii')) + for line in ser: + if line.lstrip().startswith(b'T'): + input = line.lstrip().lstrip(b'T') + elif line.lstrip().startswith(b"#"): + dstat_logger.info(line.lstrip().rstrip()) + elif line.lstrip().startswith(b"@DONE"): + dstat_logger.debug(line.lstrip().rstrip()) + ser.reset_input_buffer() + break + + parted = input.rstrip().split(b'.') + + data_pipe.send(parted[0]) + status = "DONE" + + return status + + +def read_light_sensor(): + """Tries to contact DStat and get light sensor reading. Returns uint of + light sensor clear channel. + """ + + state.ser.flush_data() + state.ser.start_exp(LightSensor()) + + logger.debug("read_light_sensor: %s", state.ser.get_proc(block=True)) + + return state.ser.get_data(block=True) + + +class SerialDevices(object): + """Retrieves and stores list of serial devices in self.ports""" + + def __init__(self): + self.ports = [] + self.refresh() + + def refresh(self): + """Refreshes list of ports.""" + try: + self.ports, _, _ = zip(*list_ports.grep("DSTAT")) + except ValueError: + self.ports = [] + logger.error("No serial ports found") diff --git a/dstat_interface/core/dstat/dfu.py b/dstat_interface/core/dstat/dfu.py new file mode 100755 index 0000000000000000000000000000000000000000..a903a7f40c8023caf0027f5ca150e4c54d79ecfb --- /dev/null +++ b/dstat_interface/core/dstat/dfu.py @@ -0,0 +1,380 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# DStat Interface - An interface for the open hardware DStat potentiostat +# Copyright (C) 2014 Michael D. M. Dryden - +# Wheeler Microfluidics Laboratory +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import (absolute_import, division, + print_function, unicode_literals) + +import subprocess +import sys +import os +import time +import logging +from tempfile import mkdtemp +from zipfile import ZipFile + +if sys.version_info >= (3,): + import urllib.request as urllib2 + import urllib.parse as urlparse +else: + import urllib2 + import urlparse + +logger = logging.getLogger(__name__) + +try: + import gi + gi.require_version('Gtk', '3.0') + from gi.repository import Gtk +except ImportError: + print("ERR: GTK not available") + sys.exit(1) + +import serial + +from . import state +from .comm import dstat_logger, exp_logger + +fwurl = "http://microfluidics.utoronto.ca/gitlab/api/v4/projects/4/jobs/artifacts/master/download?job=1.2.3&private_token=zkgSx1FaaTP7yLyFKkX6" + + +class FWDialog(object): + def __init__(self, parent, connect, stop_callback, disconnect_callback, signal='activate'): + self.parent = parent + self.stop = stop_callback + self.disconnect = disconnect_callback + connect.connect(signal, self.activate) + + def activate(self, widget=None, data=None): + for name, result in assert_deps().items(): + if result is not True: + logger.error("Can't use firmware update module.") + self.missing_deps() + return + + self.stop() # Stop OCP + version_result, master = test_firmware_version() + + if version_result is False: + self.git_error() + return + + if version_result == 'latest': + message = "Your firmware is already up to date. (or on a descendent branch)" + secondary = "Click yes to reflash firmware anyways." + elif version_result == 'devel': + message = "Your firmware is not on the master branch." + secondary = "You may have a development version. " \ + "Click yes to reflash firmware anyways." + elif version_result == 'old': + message = "Your firmware is out of date." + secondary = "Click yes to flash the latest firmware." + + dialog = Gtk.MessageDialog(self.parent, 0, Gtk.MessageType.INFO, + Gtk.ButtonsType.YES_NO, message) + dialog.format_secondary_text(secondary) + dialog.get_content_area().add( + Gtk.Label( + label="Installed version: {}".format(state.firmware_version))) + + dialog.get_content_area().add( + Gtk.Label(label="Latest version: {}".format(master))) + + dialog.show_all() + response = dialog.run() + + if response == Gtk.ResponseType.YES: + try: + download_fw() + except: + self.dl_error() + return + + dstat_enter_dfu() + + self.dfu_notice() + self.disconnect() + try: + dfu_program() + except: + self.dfu_error() + + dialog.destroy() + + else: + dialog.destroy() + + def missing_deps(self): + dialog = Gtk.MessageDialog( + self.parent, 0, Gtk.MessageType.ERROR, + Gtk.ButtonsType.OK, "Missing Dependencies") + + dialog.format_secondary_text('Check console for more info.') + + dialog.connect('response', self.destroy) + dialog.show() + + def git_error(self): + dialog = Gtk.MessageDialog( + self.parent, 0, Gtk.MessageType.ERROR, + Gtk.ButtonsType.OK, "Git Error") + + dialog.format_secondary_text('Check console for more info.') + + dialog.connect('response', self.destroy) + dialog.show() + + def dl_error(self): + dialog = Gtk.MessageDialog( + self.parent, 0, Gtk.MessageType.ERROR, + Gtk.ButtonsType.OK, "Download Error") + + dialog.format_secondary_text('Check console for more info.') + + dialog.connect('response', self.destroy) + dialog.show() + + def dfu_notice(self): + dialog = Gtk.MessageDialog( + self.parent, 0, Gtk.MessageType.INFO, + Gtk.ButtonsType.OK, "Note about DFU") + + dialog.format_secondary_text("Click OK once the DStat has connected in " + + "DFU mode. Windows doesn't seem to like the automatic reboot. " + + "Try holding down the reset button while plugging the " + + 'USB port in (No LEDs should be lit), then click OK. Make sure ' + + 'the DFU driver from the dfu-programmer directory is installed.') + + dialog.run() + dialog.destroy() + + def dfu_error(self): + dialog = Gtk.MessageDialog( + self.parent, 0, Gtk.MessageType.ERROR, + Gtk.ButtonsType.OK, "Could not update over DFU") + + dialog.format_secondary_text('Check console for more info.') + + dialog.connect('response', self.destroy) + dialog.show() + + def destroy(self, widget=None, data=None): + widget.destroy() + + +def assert_deps(): + deps = {'git' : 'git --version', + 'dfu-programmer' : 'dfu-programmer --version'} + + result = {} + + for key, command in deps.items(): + try: + output = subprocess.check_output(command.split(), + stderr=subprocess.STDOUT).decode(sys.stdout.encoding) + logger.info("Assert: %s", command) + logger.info("Result: %s", output) + result[key] = True + except subprocess.CalledProcessError: + logger.warning("{} is not available.".format(key)) + result[key] = False + + return result + + +def download_fw(): # from https://stackoverflow.com/a/16518224 + temp_dir = mkdtemp() + logger.info("Temporary directory: {}".format(temp_dir)) + os.chdir(temp_dir) # Go to temporary directory + + u = urllib2.urlopen(fwurl) + + scheme, netloc, path, query, fragment = urlparse.urlsplit(fwurl) + filename = os.path.basename(path) + if not filename: + filename = 'downloaded.file' + + with open(filename, 'wb') as f: + meta = u.info() + meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all + meta_length = meta_func("Content-Length") + file_size = None + if meta_length: + file_size = int(meta_length[0]) + logger.info("Downloading: {0} Bytes: {1}".format(fwurl, file_size)) + + file_size_dl = 0 + block_sz = 8192 + while True: + buffer = u.read(block_sz) + if not buffer: + break + + file_size_dl += len(buffer) + f.write(buffer) + + status = "{0:16}".format(file_size_dl) + if file_size: + status += " [{0:6.2f}%]".format(file_size_dl * 100 / file_size) + status += chr(13) + logger.info(status) + + with ZipFile(filename, mode='r') as z: + fw_path = z.extract('dstat-firmware.hex') + + return fw_path + + +def test_firmware_version(current=None): + if current is None: + current = state.firmware_version + + temp_dir = mkdtemp() + logger.info("Temporary directory: {}".format(temp_dir)) + os.chdir(temp_dir) # Go to temporary directory + + command = "git clone http://microfluidics.utoronto.ca/gitlab/dstat/dstat-firmware.git" + logger.info('Cloning master') + try: + output = subprocess.check_output(command.split(), + stderr=subprocess.STDOUT).decode(sys.stdout.encoding) + except subprocess.CalledProcessError as e: + logger.error("git failed with error code {}".format(e.returncode)) + logger.error("Output: {}".format(e.output)) + return False, None + logger.info(output) + + os.chdir("./dstat-firmware") + + command = "git rev-parse --short master" + master = subprocess.check_output(command.split(), stderr=subprocess.STDOUT).decode(sys.stdout.encoding) + logger.info("Current master commit: {}".format(master)) + + command = "git merge-base --is-ancestor master {}".format(current) + test = subprocess.call(command.split()) + logger.info(test) + + if test == 0: # already newest + logger.info('Firmware is latest available (or on a newer descendent branch).') + return 'latest', master + elif test == 1: # old version + logger.info('Firmware is out of date.') + return 'old', master + elif test == 128: # newer or different branch + logger.info('Firmware is not on the master branch.') + return 'devel', master + else: + logger.error('Unexpected git error. Git exited {}'.format(test)) + return False, None + + +def dfu_program(path='./dstat-firmware.hex'): + """Tries to program DStat over USB with DFU with hex file at path.""" + try: + command = "dfu-programmer atxmega256a3u erase" + output = subprocess.check_output(command.split(), + stderr=subprocess.STDOUT).decode(sys.stdout.encoding) + logger.info("%s\n%s", command, output) + command = "dfu-programmer atxmega256a3u flash {}".format(path) + output = subprocess.check_output(command.split(), + stderr=subprocess.STDOUT).decode(sys.stdout.encoding) + logger.info("%s\n%s", command, output) + command = "dfu-programmer atxmega256a3u launch" + output = subprocess.check_output(command.split(), + stderr=subprocess.STDOUT).decode(sys.stdout.encoding) + logger.info("%s\n%s", command, output) + except subprocess.CalledProcessError as e: + logger.error("{} failed with output:".format(" ".join(e.cmd))) + logger.error(e.output) + raise + + +def dstat_enter_dfu(): + """Tries to contact DStat and get version. Stores version in state. + If no response, returns False, otherwise True. + + Arguments: + ser_port -- address of serial port to use + """ + exp = DFUMode() + state.ser.start_exp(exp) + while True: + result = state.ser.get_proc(block=True) + if result in ('SERIAL_ERROR', 'DONE'): + break + logger.info(result) + + time.sleep(.1) + + return True + + +class DFUMode(object): + def __init__(self): + pass + + def run(self, ser, ctrl_pipe, data_pipe): + """Tries to contact DStat and get version. Returns a tuple of + (major, minor). If no response, returns empty tuple. + + Arguments: + ser_port -- address of serial port to use + """ + status = None + try: + ser.write(b'!2\n') + exp_logger.info('!2') + + for i in range(10): + if ser.readline().rstrip() == b"@ACK 2": + dstat_logger.info('@ACK 2') + ser.write(b'SF\n') + exp_logger.info('SF') + status = "DONE" + time.sleep(5) + break + else: + time.sleep(.5) + ser.reset_input_buffer() + ser.write(b'!2\n') + exp_logger.info('!2') + time.sleep(.1) + + except UnboundLocalError as e: + status = "SERIAL_ERROR" + except serial.SerialException as e: + logger.error('SerialException: %s', e) + status = "SERIAL_ERROR" + finally: + return status + + +if __name__ == "__main__": + log_handler = logging.StreamHandler() + log_formatter = logging.Formatter( + fmt='%(asctime)s %(levelname)s: [%(name)s] %(message)s', + datefmt='%H:%M:%S' + ) + log_handler.setFormatter(log_formatter) + logger.setLevel(level=logging.INFO) + logger.addHandler(log_handler) + + dstat_enter_dfu() + time.sleep(2) + dfu_program(sys.argv[1]) \ No newline at end of file diff --git a/dstat_interface/core/dstat/state.py b/dstat_interface/core/dstat/state.py new file mode 100644 index 0000000000000000000000000000000000000000..49064813b2abe4c4074bf706f3ce48500e0d6380 --- /dev/null +++ b/dstat_interface/core/dstat/state.py @@ -0,0 +1,29 @@ +from collections import OrderedDict + + +def reset(): + """Resets state variables.""" + + settings = OrderedDict() + ser = None + dstat_version = None + firmware_version = None + board_instance = None + + +def get_state(): + """ + Get state variables + :return dict of pickleable state variables + """ + return {'settings': settings, + 'dstat_version': dstat_version, + 'firmware_version': firmware_version, + 'board_instance': board_instance} + + +settings = OrderedDict() +ser = None +dstat_version = None +firmware_version = None +board_instance = None diff --git a/dstat_interface/errors.py b/dstat_interface/core/errors.py similarity index 100% rename from dstat_interface/errors.py rename to dstat_interface/core/errors.py diff --git a/dstat_interface/core/experiments/__init__.py b/dstat_interface/core/experiments/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6991a974fe8d810854f78bd2c311ce17ec56619e --- /dev/null +++ b/dstat_interface/core/experiments/__init__.py @@ -0,0 +1,17 @@ +# __all__ = [] +# +# import pkgutil +# import inspect +# from . import cal, chronoamp, cv +# +# +# for loader, name, is_pkg in pkgutil.walk_packages(__path__): +# print loader, name, is_pkg +# module = loader.find_module(name).load_module(name) +# +# for name, value in inspect.getmembers(module): +# if name.startswith('__'): +# continue +# +# globals()[name] = value +# __all__.append(name) \ No newline at end of file diff --git a/dstat_interface/experiments/cal.py b/dstat_interface/core/experiments/cal.py similarity index 87% rename from dstat_interface/experiments/cal.py rename to dstat_interface/core/experiments/cal.py index 98d82b6bbd0c15467ee4cc41d65455a5917bcd7d..3da92806959b3c4cb9d1dc2407190a9facfd1058 100755 --- a/dstat_interface/experiments/cal.py +++ b/dstat_interface/core/experiments/cal.py @@ -21,15 +21,14 @@ import time import struct import logging - -from errors import InputError, VarError +logger = logging.getLogger(__name__) import serial -logger = logging.getLogger("dstat.experiments.cal") +from ..errors import InputError, VarError +from ..dstat import state +from ..experiments.experiment_template import Experiment, dstat_logger -import state -from experiments.experiment_template import Experiment, dstat_logger def measure_offset(time): gain_trim_table = [None, 'r100_trim', 'r3k_trim', 'r30k_trim', 'r300k_trim', @@ -48,6 +47,7 @@ def measure_offset(time): return gain_offset + class CALExp(Experiment): id = 'cal' """Offset calibration experiment""" @@ -57,15 +57,16 @@ class CALExp(Experiment): self.scan = 0 self.data = [] - self.commands = ["EA2 3 1 ", "EG", "ER"] + self.commands = ["EA2 3 1 ", "EG"] self.commands[1] += str(self.parameters['gain']) self.commands[1] += " " self.commands[1] += "0 " - self.commands[2] += "1 32768 " - self.commands[2] += str(self.parameters['time']) - self.commands[2] += " " - self.commands[2] += "0 " # disable photodiode interlock + + self.commands.append( + ("ER1 0", ["32768", str(self.parameters['time'])]) + ) + def serial_handler(self): """Handles incoming serial transmissions from DStat. Returns False @@ -100,6 +101,7 @@ class CALExp(Experiment): elif line.lstrip().startswith("@DONE"): dstat_logger.debug(line.lstrip().rstrip()) self.serial.flushInput() + self.experiment_done() return True except serial.SerialException: @@ -114,13 +116,16 @@ class CALExp(Experiment): seconds, milliseconds, current = struct.unpack(' +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import division, absolute_import, print_function, unicode_literals + +from ..dstat import state + +import logging + +try: + import gi + gi.require_version('Gtk', '3.0') + from gi.repository import Gtk, GObject +except ImportError: + import sys + print("ERR: GTK not available") + sys.exit(1) + +logger = logging.getLogger(__name__) + + +class BaseLoop(GObject.GObject): + __gsignals__ = { + 'experiment_done': (GObject.SIGNAL_RUN_FIRST, None, tuple()), + 'progress_update': (GObject.SIGNAL_RUN_FIRST, None, (float,)) + } + + def __init__(self, experiment, callbacks=None): + GObject.GObject.__init__(self) + self.line = None + self.lastdataline = 0 + self.current_exp = experiment + self.experiment_proc = None + + for signal, cb in callbacks.items(): + try: + self.connect(signal, cb) + except TypeError: + logger.warning("Invalid signal %s", signal) + + def run(self): + self.experiment_proc = [ + GObject.idle_add(self.experiment_running_data), + GObject.idle_add(self.experiment_running_proc), + GObject.timeout_add(100, self.update_progress) + ] + + def experiment_running_data(self): + """Receive data from experiment process and add to + current_exp.data['data]. + Run in GTK main loop. + + Returns: + True -- when experiment is continuing to keep function in GTK's queue. + False -- when experiment process signals EOFError or IOError to remove + function from GTK's queue. + """ + try: + incoming = state.ser.get_data() + while incoming is not None: + try: + self.line = incoming[0] + if self.line > self.lastdataline: + newline = True + try: + logger.info("running scan_process()") + self.current_exp.scan_process(self.lastdataline) + except AttributeError: + pass + self.lastdataline = self.line + else: + newline = False + self.current_exp.store_data(incoming, newline) + except TypeError: + pass + + incoming = state.ser.get_data() + return True + + except EOFError as err: + logger.error(err) + self.experiment_done() + return False + except IOError as err: + logger.error(err) + self.experiment_done() + return False + + def experiment_running_proc(self): + """Receive proc signals from experiment process. + Run in GTK main loop. + + Returns: + True -- when experiment is continuing to keep function in GTK's queue. + False -- when experiment process signals EOFError or IOError to remove + function from GTK's queue. + """ + try: + ctrl_buffer = state.ser.get_ctrl() + try: + if ctrl_buffer is not None: + self.current_exp.ctrl_loop(ctrl_buffer) + except AttributeError: + pass + + proc_buffer = state.ser.get_proc() + if proc_buffer is not None: + if proc_buffer in ["DONE", "SERIAL_ERROR", "ABORT"]: + self.experiment_done() + if proc_buffer == "SERIAL_ERROR": + self.on_serial_disconnect_clicked() + + else: + logger.warning("Unrecognized experiment return code: %s", + proc_buffer) + return False + return True + + except EOFError as err: + logger.warning("EOFError: %s", err) + self.experiment_done() + return False + except IOError as err: + logger.warning("IOError: %s", err) + self.experiment_done() + return False + + def experiment_done(self): + logger.info("Experiment done") + for proc in self.experiment_proc: + GObject.source_remove(proc) + self.current_exp.scan_process(self.lastdataline) + self.current_exp.experiment_done() + self.emit("experiment_done") + + def update_progress(self): + try: + progress = self.current_exp.get_progress() + except AttributeError: + progress = -1 + self.emit("progress_update", progress) + return True + + +class PlotLoop(BaseLoop): + def experiment_running_plot(self, force_refresh=False): + """Plot all data in current_exp.data. + Run in GTK main loop. Always returns True so must be manually + removed from GTK's queue. + """ + if self.line is None: + return True + for plot in self.current_exp.plots: + if (plot.scan_refresh and self.line > self.lastdataline): + while self.line > self.lastline: + # make sure all of last line is added + plot.updateline(self.current_exp, self.lastdataline) + self.lastdataline += 1 + plot.updateline(self.current_exp, self.line) + plot.redraw() + else: + while self.line > self.lastdataline: + # make sure all of last line is added + plot.updateline(self.current_exp, self.lastdataline) + self.lastdataline += 1 + plot.updateline(self.current_exp, self.line) + + if plot.continuous_refresh is True or force_refresh is True: + plot.redraw() + return True + + def run(self): + super(PlotLoop, self).run() + self.experiment_proc.append( + GObject.timeout_add(200, self.experiment_running_plot) + ) + + def experiment_done(self): + logger.info("Experiment done") + for proc in self.experiment_proc: + GObject.source_remove(proc) + self.current_exp.scan_process(self.lastdataline) + self.current_exp.experiment_done() + self.experiment_running_plot(force_refresh=True) + self.emit("experiment_done") \ No newline at end of file diff --git a/dstat_interface/experiments/experiment_template.py b/dstat_interface/core/experiments/experiment_template.py similarity index 52% rename from dstat_interface/experiments/experiment_template.py rename to dstat_interface/core/experiments/experiment_template.py index 29aa8393aa81d89eb7bb2dc7a6763881bb45f342..32b1d290594bd2895d574c6cbc6f7eb56a94be19 100755 --- a/dstat_interface/experiments/experiment_template.py +++ b/dstat_interface/core/experiments/experiment_template.py @@ -17,85 +17,92 @@ # # You should have received a copy of the GNU General Public License # along with this program. If not, see . +from __future__ import division, absolute_import, print_function, unicode_literals + import logging import struct -from datetime import datetime +import time from collections import OrderedDict from copy import deepcopy +from datetime import datetime from math import ceil -import time try: import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GObject except ImportError: - print "ERR: GTK not available" + import sys + print("ERR: GTK not available") sys.exit(1) - + + from matplotlib.figure import Figure import matplotlib.gridspec as gridspec -import matplotlib.pyplot as plt -from matplotlib.backends.backend_gtk3agg \ - import FigureCanvasGTK3Agg as FigureCanvas - +# from matplotlib.backends.backend_gtk3agg \ + # import FigureCanvasGTK3Agg as FigureCanvas + +from matplotlib.backends.backend_gtk3cairo \ + import FigureCanvasGTK3Cairo as FigureCanvas + + from pandas import DataFrame - -try: - import seaborn as sns - sns.set(context='paper', style='darkgrid') -except ImportError: - pass +import seaborn as sns +sns.set(context='paper', style='darkgrid') + import serial -logger = logging.getLogger("dstat.comm") -dstat_logger = logging.getLogger("dstat.comm.DSTAT") -exp_logger = logging.getLogger("dstat.comm.Experiment") +from ..dstat import comm +from ..dstat.comm import TransmitError +from . import experiment_loops + +logger = logging.getLogger(__name__) +dstat_logger = logging.getLogger("{}.DSTAT".format(comm.__name__)) +exp_logger = logging.getLogger("{}.Experiment".format(__name__)) -from errors import InputError, VarError -import state -class Experiment(object): +class Experiment(GObject.Object): """Store and acquire a potentiostat experiment. Meant to be subclassed to by different experiment types and not used instanced directly. Subclass must instantiate self.plotbox as the PlotBox class to use and define id as a class attribute. """ id = None - - def __init__(self, parameters): + Loops = experiment_loops.PlotLoop + __gsignals__ = { + 'exp_ready': (GObject.SIGNAL_RUN_FIRST, None, ()), + 'exp_done': (GObject.SIGNAL_RUN_FIRST, None, ()), + } + + def __init__(self, parameters=None, state=None): """Adds commands for gain and ADC.""" + super(Experiment, self).__init__() + self.current_command = None self.parameters = parameters + self.state = state self.databytes = 8 self.datapoint = 0 self.scan = 0 self.time = 0 self.plots = [] - - major, minor = state.dstat_version - if major >= 1: - if minor == 1: - self.__gaintable = [1e2, 3e2, 3e3, 3e4, 3e5, 3e6, 3e7, 5e8] - elif minor >= 2: - self.__gaintable = [1, 1e2, 3e3, 3e4, 3e5, 3e6, 3e7, 1e8] - self.__gain_trim_table = ['r100_trim', 'r100_trim', 'r3k_trim', - 'r30k_trim', 'r300k_trim', 'r3M_trim', - 'r30M_trim', 'r100M_trim'] - else: - raise VarError(parameters['version'], "Invalid version parameter.") - - self.gain = self.__gaintable[int(self.parameters['gain'])] - self.gain_trim = int( - state.settings[ - self.__gain_trim_table[int(self.parameters['gain'])] - ][1] - ) + self.re_voltage_scale = self.state['board_instance'].re_voltage_scale + + self.gain = self.state['board_instance'].gain[int(self.parameters['gain'])] + + try: + self.gain_trim = int( + self.state['settings'][ + self.state['board_instance'].gain_trim[int(self.parameters['gain'])] + ] + ) + except AttributeError: + logger.debug("No gain trim table.") self.commands = ["EA", "EG"] - if self.parameters['buffer_true']: + if self.parameters['buffer_true']: self.commands[0] += "2" else: self.commands[0] += "0" @@ -103,82 +110,129 @@ class Experiment(object): p=self.parameters) self.commands[1] += "{p[gain]} {p[short_true]:d} ".format( p=self.parameters) - + + self.plotlims = {'current_voltage' : {'xlims' : (0, 1)} + } + self.setup() self.time = [datetime.utcnow()] - + + def setup_loops(self, callbacks): + self.loops = self.__class__.Loops(self, callbacks) + self.loops.run() + def setup(self): - self.data = OrderedDict(current_voltage=[([],[])]) - + self.data = OrderedDict(current_voltage=[([], [])]) self.columns = ['Voltage (mV)', 'Current (A)'] - self.plot_format = { - 'current_voltage' : {'labels' : self.columns, - 'xlims' : (0, 1) - } - } + # list of scans, tuple of dimensions, list of data self.line_data = ([], []) + + plot = PlotBox(['current_voltage']) + plot.setlims('current_voltage', **self.plotlims['current_voltage']) + + self.plots.append(plot) - self.plots.append(PlotBox(['current_voltage'])) - - def write_command(self, cmd, params=None, retry=10): + def write_command(self, cmd, params=None, retry=5): """Write command to serial with optional number of retries.""" - def get_reply(): - reply = self.serial.readline().rstrip() - if reply.startswith('#'): - dstat_logger.info(reply) - return get_reply() - return reply + def get_reply(retries=3): + while True: + reply = self.serial.readline().decode('ascii').rstrip() + if reply.startswith('#'): + dstat_logger.info(reply) + elif reply == "": + retries -= 1 + if retries <= 0: + raise TransmitError + else: + return reply n = len(cmd) if params is not None: n_params = len(params) for _ in range(retry): - time.sleep(0.2) - self.serial.reset_input_buffer() - self.serial.write('!{}\n'.format(n)) - time.sleep(.1) - - reply = get_reply() - + tries = 5 + while True: + time.sleep(0.2) + self.serial.reset_input_buffer() + self.serial.write('!{}\n'.format(n).encode('ascii')) + time.sleep(.1) + + try: + reply = get_reply() + except TransmitError: + if tries <= 0: + continue + tries -= 1 + pass + else: + break + if reply != "@ACK {}".format(n): - logger.warning("Invalid response: {}".format(reply)) + logger.warning("Expected ACK got: {}".format(reply)) continue - - self.serial.write('{}\n'.format(cmd)) - reply = get_reply() + tries = 5 + while True: + self.serial.write('{}\n'.format(cmd).encode('ascii')) + try: + reply = get_reply() + except TransmitError: + if tries <= 0: + continue + tries -= 1 + pass + else: + break + if reply != "@RCV {}".format(n): - logger.warning("Invalid response: {}".format(reply)) + logger.warning("Expected RCV got: {}".format(reply)) continue if params is None: return True - reply = get_reply() + tries = 5 + while True: + try: + reply = get_reply() + except TransmitError: + if tries <= 0: + break + tries -= 1 + pass + else: + break + if reply != "@RQP {}".format(n_params): - logger.warning("Invalid response: {}".format(reply)) + logger.warning("Expected RQP got: {}".format(reply)) continue - - self.serial.write(" ".join(params) + " ") - - reply = get_reply() - if reply != "@RCP {}".format(n_params): - logger.warning("Invalid response: {}".format(reply)) - continue + tries = 5 + for i in params: + while True: + self.serial.write("{} ".format(i).encode('ascii')) + try: + reply = get_reply() + if reply == "@RCVC {}".format(i): + break + except TransmitError: + if tries <= 0: + continue + tries -= 1 + pass + else: + break return True - return False def run(self, ser, ctrl_pipe, data_pipe): """Execute experiment. Connects and sends handshake signal to DStat - then sends self.commands. Don't call directly as a process in Windows, - use run_wrapper instead. + then sends self.commands. """ self.serial = ser self.ctrl_pipe = ctrl_pipe @@ -188,8 +242,9 @@ class Experiment(object): try: for i in self.commands: + self.current_command = i status = "DONE" - if isinstance(i, (str, unicode)): + if isinstance(i, (str, bytes)): logger.info("Command: %s", i) if not self.write_command(i): @@ -225,26 +280,30 @@ class Experiment(object): data to self.data_pipe as result of self.data_handler). """ scan = 0 + + def check_ctrl(): + if self.ctrl_pipe.poll(): + input = self.ctrl_pipe.recv() + logger.info("serial_handler: %s", input) + if input == b"DISCONNECT": + self.serial.write(b'a') + self.serial.reset_input_buffer() + logger.info("serial_handler: ABORT pressed!") + time.sleep(.3) + return False + elif input == 'a': + self.serial.write(b'a') + else: + self.serial.write(input) + try: while True: - if self.ctrl_pipe.poll(): - input = self.ctrl_pipe.recv() - logger.debug("serial_handler: %s", input) - if input == "DISCONNECT": - self.serial.write('a') - self.serial.reset_input_buffer() - logger.info("serial_handler: ABORT pressed!") - time.sleep(.3) - return False - elif input == 'a': - self.serial.write('a') - + check_ctrl() for line in self.serial: - if self.ctrl_pipe.poll(): - if self.ctrl_pipe.recv() == 'a': - self.serial.write('a') - - if line.startswith('B'): + check_ctrl() + line_in = line.decode("ascii") + + if line_in.startswith('B'): data = self.data_handler( (scan, self.serial.read(size=self.databytes))) data = self.data_postprocessing(data) @@ -252,24 +311,23 @@ class Experiment(object): self.data_pipe.send(data) try: self.datapoint += 1 - except AttributeError: #Datapoint counting is optional + except AttributeError: # Datapoint counting is optional pass - elif line.lstrip().startswith('S'): + elif line_in.lstrip().startswith('S'): scan += 1 - elif line.lstrip().startswith("#"): - dstat_logger.info(line.lstrip().rstrip()) + elif line_in.lstrip().startswith("#"): + dstat_logger.info(line_in.strip()) - elif line.lstrip().startswith("@DONE"): - dstat_logger.debug(line.lstrip().rstrip()) + elif line_in.lstrip().startswith("@DONE"): + dstat_logger.debug(line_in.strip()) time.sleep(.3) return True except serial.SerialException: return False - - + def data_handler(self, data_input): """Takes data_input as tuple -- (scan, data). Returns: @@ -278,8 +336,8 @@ class Experiment(object): scan, data = data_input voltage, current = struct.unpack(' 1: + prog = 1 + return prog + else: + return 1 - (abs(self.stop_mv - self.data['swv'][-1][0][-1])/self.max_mv) + except IndexError: + return 0 + + +class DPVExp(SWVExp): + """Diffential Pulse Voltammetry experiment.""" + id = 'dpv' + def setup(self): + self.datatype = "SWVData" + self.xlabel = "Voltage (mV)" + self.ylabel = "Current (A)" + self.data = { + 'swv' : [([], [], [], [])] + } # voltage, current, forwards, reverse + self.line_data = ([], [], [], []) + self.datalength = 2 + self.databytes = 10 + self.columns = ['Voltage (mV)', 'Net Current (A)', + 'Forward Current (A)', 'Reverse Current (A)'] + + self.plotlims = { + 'swv': { + 'xlims': tuple(sorted( + (int(self.parameters['start']), + int(self.parameters['stop'])) + ) + ) + } + } + + plot = SWVBox() + plot.setlims('swv', **self.plotlims['swv']) + self.plots.append(plot) + + self.stop_mv = int(self.parameters['stop']) + self.max_mv = abs(int(self.parameters['start']) - int(self.parameters['stop'])) + + self.commands += "E" + self.commands[2] += "D" + self.commands[2] += str(self.parameters['clean_s']) + self.commands[2] += " " + self.commands[2] += str(self.parameters['dep_s']) + self.commands[2] += " " + self.commands[2] += str(int( + int(self.parameters['clean_mV'])/ + self.re_voltage_scale* + (65536./3000)+32768 + )) + self.commands[2] += " " + self.commands[2] += str(int( + int(self.parameters['dep_mV'])/ + self.re_voltage_scale* + (65536./3000)+32768 + )) + self.commands[2] += " " + self.commands[2] += str(int( + int(self.parameters['start'])/ + self.re_voltage_scale* + (65536./3000)+32768 + )) + self.commands[2] += " " + self.commands[2] += str(int( + int(self.parameters['stop'])/ + self.re_voltage_scale* + (65536./3000)+32768 + )) + self.commands[2] += " " + self.commands[2] += str(int( + int(self.parameters['step'])/ + self.re_voltage_scale* + (65536./3000) + )) + self.commands[2] += " " + self.commands[2] += str(int( + int(self.parameters['pulse'])/ + self.re_voltage_scale* + (65536./3000) + )) + self.commands[2] += " " + self.commands[2] += str(self.parameters['period']) + self.commands[2] += " " + self.commands[2] += str(self.parameters['width']) + self.commands[2] += " " + + def get_progress(self): + try: + return 1 - (abs(self.stop_mv - self.data['swv'][-1][0][-1])/self.max_mv) + except IndexError: + return 0 diff --git a/dstat_interface/core/interface/__init__.py b/dstat_interface/core/interface/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/dstat_interface/interface/acv.glade b/dstat_interface/core/interface/acv.glade similarity index 100% rename from dstat_interface/interface/acv.glade rename to dstat_interface/core/interface/acv.glade diff --git a/dstat_interface/interface/adc_pot.glade b/dstat_interface/core/interface/adc_pot.glade similarity index 100% rename from dstat_interface/interface/adc_pot.glade rename to dstat_interface/core/interface/adc_pot.glade diff --git a/dstat_interface/interface/adc_pot.py b/dstat_interface/core/interface/adc_pot.py similarity index 78% rename from dstat_interface/interface/adc_pot.py rename to dstat_interface/core/interface/adc_pot.py index 8e731629f4091076d045d58c7031346b24407ae7..a8c25c787d5183cd0494476ce36fe63d713cf805 100755 --- a/dstat_interface/interface/adc_pot.py +++ b/dstat_interface/core/interface/adc_pot.py @@ -17,40 +17,28 @@ # # You should have received a copy of the GNU General Public License # along with this program. If not, see . +import os.path +from pkg_resources import parse_version try: import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk except ImportError: - print "ERR: GTK not available" + import sys + print("ERR: GTK not available") sys.exit(1) -from errors import InputError, VarError +from ..errors import InputError, VarError +from ..dstat import state -v1_1_gain = [(0, "100 Ω (15 mA FS)", "0"), - (1, "300 Ω (5 mA FS)", "1"), - (2, "3 kΩ (500 µA FS)", "2"), - (3, "30 kΩ (50 µA FS)", "3"), - (4, "300 kΩ (5 µA FS)", "4"), - (5, "3 MΩ (500 nA FS)", "5"), - (6, "30 MΩ (50 nA FS)", "6"), - (7, "500 MΩ (3 nA FS)", "7")] +mod_dir = os.path.dirname(os.path.abspath(__file__)) -v1_2_gain = [(0, "Bypass", "0"), - (1, "100 Ω (15 mA FS)", "1"), - (2, "3 kΩ (500 µA FS)", "2"), - (3, "30 kΩ (50 µA FS)", "3"), - (4, "300 kΩ (5 µA FS)", "4"), - (5, "3 MΩ (500 nA FS)", "5"), - (6, "30 MΩ (50 nA FS)", "6"), - (7, "100 MΩ (15 nA FS)", "7")] - class adc_pot(object): def __init__(self): self.builder = Gtk.Builder() - self.builder.add_from_file('interface/adc_pot.glade') + self.builder.add_from_file(os.path.join(mod_dir,'adc_pot.glade')) self.builder.connect_signals(self) self.cell = Gtk.CellRendererText() @@ -81,7 +69,7 @@ class adc_pot(object): self.gain_liststore = self.builder.get_object('gain_liststore') self.ui['gain_index'].pack_start(self.cell, True) self.ui['gain_index'].add_attribute(self.cell, 'text', 1) - self.ui['gain_index'].set_active(2) + # self.ui['gain_index'].set_active(2) self._params = {} @@ -135,15 +123,19 @@ class adc_pot(object): for i in self.ui: self.ui[i].set_active(self._params[i]) - def set_version(self, version): + def set_version(self, boost=None): """ Sets menus for DStat version. """ + try: + if self.version == state.board_instance: + return + except AttributeError: + pass + + self.version = state.board_instance + self.gain_liststore.clear() - if version[0] == 1: - if version[1] == 1: - for i in v1_1_gain: - self.gain_liststore.append(str(i)) - elif version[1] >= 2: - for i in v1_2_gain: - self.gain_liststore.append(i) + + for n, i in enumerate(self.version.gain_labels): + self.gain_liststore.append((n, i, str(n))) - \ No newline at end of file + self.ui['gain_index'].set_active(self.version.gain_default_index) \ No newline at end of file diff --git a/dstat_interface/interface/analysis_options.glade b/dstat_interface/core/interface/analysis_options.glade similarity index 100% rename from dstat_interface/interface/analysis_options.glade rename to dstat_interface/core/interface/analysis_options.glade diff --git a/dstat_interface/interface/calib.glade b/dstat_interface/core/interface/calib.glade similarity index 100% rename from dstat_interface/interface/calib.glade rename to dstat_interface/core/interface/calib.glade diff --git a/dstat_interface/interface/chronoamp.glade b/dstat_interface/core/interface/chronoamp.glade similarity index 100% rename from dstat_interface/interface/chronoamp.glade rename to dstat_interface/core/interface/chronoamp.glade diff --git a/dstat_interface/interface/cv.glade b/dstat_interface/core/interface/cv.glade similarity index 100% rename from dstat_interface/interface/cv.glade rename to dstat_interface/core/interface/cv.glade diff --git a/dstat_interface/interface/data_view.py b/dstat_interface/core/interface/data_view.py similarity index 95% rename from dstat_interface/interface/data_view.py rename to dstat_interface/core/interface/data_view.py index e4bd711f0d2af0f95f9bbda50a591419019644f2..e7c4db65ea4a99114c760dd14df70e3bc16104ed 100644 --- a/dstat_interface/interface/data_view.py +++ b/dstat_interface/core/interface/data_view.py @@ -1,7 +1,7 @@ from __future__ import division, absolute_import, print_function, unicode_literals import logging -logger = logging.getLogger("dstat.interface.data_view") +logger = logging.getLogger(__name__) from collections import OrderedDict diff --git a/dstat_interface/interface/db.glade b/dstat_interface/core/interface/db.glade similarity index 100% rename from dstat_interface/interface/db.glade rename to dstat_interface/core/interface/db.glade diff --git a/dstat_interface/interface/db.py b/dstat_interface/core/interface/db.py similarity index 98% rename from dstat_interface/interface/db.py rename to dstat_interface/core/interface/db.py index cc31db72e427d88d504ab7100992404621cdb5b6..e3622924e57590fc850be2dc95d7b2d5396bc881 100755 --- a/dstat_interface/interface/db.py +++ b/dstat_interface/core/interface/db.py @@ -30,7 +30,7 @@ except ImportError: print "ERR: GTK not available" sys.exit(1) -logger = logging.getLogger('dstat.interface.db') +logger = logging.getLogger(__name__) class DB_Window(GObject.GObject): __gsignals__ = { diff --git a/dstat_interface/interface/dpv.glade b/dstat_interface/core/interface/dpv.glade similarity index 100% rename from dstat_interface/interface/dpv.glade rename to dstat_interface/core/interface/dpv.glade diff --git a/dstat_interface/core/interface/dstatinterface.glade b/dstat_interface/core/interface/dstatinterface.glade new file mode 100644 index 0000000000000000000000000000000000000000..889e1d671a3b61dbabb1b9e230f73bfb00b4367c --- /dev/null +++ b/dstat_interface/core/interface/dstatinterface.glade @@ -0,0 +1,737 @@ + + + + + + False + 5 + True + dialog + DStat-interface + © Michael Dryden 2014 + This software is licensed under the GNU GPL v3 + http://microfluidics.utoronto.ca/dstat + Wheeler Microfuidics Lab + Michael Dryden +Thanks to Christian Fobel for help with Dropbot Plugin + + image-missing + gpl-3-0 + + + True + False + vertical + 2 + + + True + False + end + + + True + True + 0 + + + + + + + + + + + + True + False + center + gtk-missing-image + + + True + False + image7 + + + True + False + gtk-save-as + + + True + False + gtk-save-as + + + True + False + gtk-open + + + True + False + gtk-preferences + + + True + False + image7 + + + True + False + gtk-save-as + + + True + False + image7 + + + + + + + + + False + 6 + Main + 1200 + 800 + + + + True + False + vertical + + + True + False + + + True + False + File + + + True + False + + + Save Experiment Data… + True + False + image8 + False + + + + + + Save Plot… + True + False + image3 + False + + + + + + Save Parameters… + True + False + image4 + False + + + + + + Load Parameters… + True + False + image5 + False + + + + + + gtk-quit + True + False + True + True + + + + + + + + + + True + False + DStat + + + True + False + + + System Information + True + False + image7 + False + + + + + Firmware… + True + False + image2 + False + + + + + Reset EEPROM + True + False + image9 + False + + + + + + + + + True + False + Dropbot + + + True + False + + + gtk-connect + True + False + True + True + + + + + + gtk-disconnect + True + False + False + True + True + + + + + + + + + + True + False + Analysis + + + True + False + + + Analysis Options… + True + False + image6 + False + + + + + + + + + + True + False + About + + + True + False + + + gtk-about + True + False + True + True + + + + + + + + + + False + True + 0 + + + + + True + True + 300 + True + True + + + True + False + vertical + + + True + False + vertical + + + True + False + vertical + + + + + + False + False + 0 + + + + + True + False + Experiment: + + + + + + False + False + 10 + 1 + + + + + + + + True + False + + + False + True + 3 + + + + + False + False + 0 + + + + + True + False + vertical + + + + + + True + True + 1 + + + + + True + False + + + gtk-execute + True + True + True + True + + + + True + True + 0 + + + + + gtk-stop + True + False + True + True + True + + + + True + True + 1 + + + + + True + False + + + True + True + 2 + + + + + False + False + 2 + + + + + True + False + True + 10 + 15 + 5 + 2 + + + False + True + 3 + + + + + False + True + + + + + True + True + True + + + True + False + vertical + + + True + True + bottom + + + + + + + + + + + + + + + + + + + + + True + True + -1 + + + + + True + False + start + + + Autosave + True + True + False + True + + + False + True + 0 + + + + + True + False + start + select-folder + False + Select a Save Folder + + + True + True + 1 + + + + + True + True + True + start + 32 + + filename + False + gtk-file + False + False + File name + File name + + + False + True + 2 + + + + + False + False + 0 + + + + + + + True + False + Plot + + + False + + + + + + + + + + + + + + + + + True + True + + + + + True + True + 1 + + + + + True + False + + + True + False + 2 + + + True + True + end + 0 + + + + + True + False + Serial Port: + + + False + True + 5 + 1 + + + + + 128 + True + False + start + serial_liststore + + + False + False + 2 + + + + + gtk-connect + True + True + True + True + + + + False + False + 3 + + + + + Connect (PMT mode) + True + True + True + + + + False + False + 4 + + + + + gtk-disconnect + True + True + True + True + + + + False + False + 5 + + + + + gtk-refresh + True + True + True + True + + + + False + False + 6 + + + + + True + False + start + OCP: + True + + + False + False + 3 + 7 + + + + + False + True + 2 + + + + + + + 100 + 5 + 1 + 10 + + diff --git a/dstat_interface/interface/exp_int.py b/dstat_interface/core/interface/exp_int.py similarity index 84% rename from dstat_interface/interface/exp_int.py rename to dstat_interface/core/interface/exp_int.py index 397fe91bcc1c2dfb393d54cd3168604c2c31d79e..401c2cdb21f02d308f8721e32ea1958c15f80329 100755 --- a/dstat_interface/interface/exp_int.py +++ b/dstat_interface/core/interface/exp_int.py @@ -27,16 +27,20 @@ try: gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GObject except ImportError: + import sys print("ERR: GTK not available") sys.exit(1) -import dstat_comm -import state -import experiments as exp -import experiments.cal as cal +from ..dstat import comm, state +from ..experiments import (cal, chronoamp, cv, experiment_template, + idle, lsv, pot, swv) import __main__ -from errors import InputError, VarError -logger = logging.getLogger("dstat.interface.exp_int") +from ..errors import InputError, VarError + +logger = logging.getLogger(__name__) + +mod_dir = os.path.dirname(os.path.abspath(__file__)) + class ExpInterface(GObject.Object): """Generic experiment interface class. Should be subclassed to implement @@ -44,8 +48,8 @@ class ExpInterface(GObject.Object): to set id and experiment class to run. """ __gsignals__ = { - b'run_utility': (GObject.SIGNAL_RUN_FIRST, None, ()), - b'done_utility': (GObject.SIGNAL_RUN_FIRST, None, ()) + 'run_utility': (GObject.SIGNAL_RUN_FIRST, None, ()), + 'done_utility': (GObject.SIGNAL_RUN_FIRST, None, ()) } id = None @@ -58,14 +62,17 @@ class ExpInterface(GObject.Object): self.builder.connect_signals(self) self.entry = {} # to be used only for str parameters self._params = None - + + def get_experiment(self, parameters, state=None): + return self.__class__.experiment(parameters, state) + def _fill_params(self): self._params = dict.fromkeys(self.entry.keys()) @property def params(self): """Dict of parameters""" - if self._params == None: + if self._params is None: self._fill_params() self._get_params() return self._params @@ -77,7 +84,7 @@ class ExpInterface(GObject.Object): @params.setter def params(self, params): - if self._params == None: + if self._params is None: self._fill_params() for i in self._params: try: @@ -97,7 +104,8 @@ class ExpInterface(GObject.Object): self.emit('run_utility') def on_done_utility(self, data=None): self.emit('done_utility') - + + class Chronoamp(ExpInterface): """Experiment class for chronoamperometry. Extends ExpInterface class to support treeview neeeded for CA. @@ -108,10 +116,10 @@ class Chronoamp(ExpInterface): get_params(self) """ id = 'cae' - experiment = exp.Chronoamp + experiment = chronoamp.Chronoamp def __init__(self): """Extends superclass method to support treeview.""" - super(Chronoamp, self).__init__('interface/chronoamp.glade') + super(Chronoamp, self).__init__(os.path.join(mod_dir, 'chronoamp.glade')) self.name = "Chronoamperometry" @@ -144,9 +152,9 @@ class Chronoamp(ExpInterface): self.builder.get_object('potential_entry').get_text()) time = int(self.builder.get_object('time_entry').get_text()) - if (potential > 1499 or potential < -1500): + if not state.board_instance.test_mv(potential): raise ValueError("Potential out of range") - if (time < 1 or time > 65535): + if not state.board_instance.test_s(time): raise ValueError("Time out of range") self.model.append([potential, time]) @@ -187,10 +195,10 @@ class Chronoamp(ExpInterface): class LSV(ExpInterface): """Experiment class for LSV.""" id = 'lsv' - experiment = exp.LSVExp + experiment = lsv.LSVExp def __init__(self): """Adds entry listings to superclass's self.entry dict""" - super(LSV, self).__init__('interface/lsv.glade') + super(LSV, self).__init__(os.path.join(mod_dir, 'lsv.glade')) self.name = "Linear Sweep Voltammetry" self.entry['clean_mV'] = self.builder.get_object('clean_mV') @@ -204,10 +212,10 @@ class LSV(ExpInterface): class CV(ExpInterface): """Experiment class for CV.""" id = 'cve' - experiment = exp.CVExp + experiment = cv.CVExp def __init__(self): """Adds entry listings to superclass's self.entry dict""" - super(CV, self).__init__('interface/cv.glade') + super(CV, self).__init__(os.path.join(mod_dir, 'cv.glade')) self.name = "Cyclic Voltammetry" self.entry['clean_mV'] = self.builder.get_object('clean_mV') @@ -223,10 +231,10 @@ class CV(ExpInterface): class SWV(ExpInterface): """Experiment class for SWV.""" id = 'swv' - experiment = exp.SWVExp + experiment = swv.SWVExp def __init__(self): """Adds entry listings to superclass's self.entry dict""" - super(SWV, self).__init__('interface/swv.glade') + super(SWV, self).__init__(os.path.join(mod_dir, 'swv.glade')) self.name = "Square Wave Voltammetry" self.entry['clean_mV'] = self.builder.get_object('clean_mV') @@ -262,10 +270,10 @@ class SWV(ExpInterface): class DPV(ExpInterface): """Experiment class for DPV.""" id = 'dpv' - experiment = exp.DPVExp + experiment = swv.DPVExp def __init__(self): """Adds entry listings to superclass's self.entry dict""" - super(DPV, self).__init__('interface/dpv.glade') + super(DPV, self).__init__(os.path.join(mod_dir, 'dpv.glade')) self.name = "Differential Pulse Voltammetry" @@ -297,10 +305,10 @@ class DPV(ExpInterface): class PD(ExpInterface): """Experiment class for PD.""" id = 'pde' - experiment = exp.PDExp + experiment = chronoamp.PDExp def __init__(self): """Adds entry listings to superclass's self.entry dict""" - super(PD, self).__init__('interface/pd.glade') + super(PD, self).__init__(os.path.join(mod_dir, 'pd.glade')) self.name = "Photodiode/PMT" @@ -351,7 +359,7 @@ class PD(ExpInterface): self.bool[i].set_active(self._params[i]) self.builder.get_object('voltage_adjustment').set_value( - self._params['voltage'] ) + self._params['voltage']) def on_light_button_clicked(self, data=None): __main__.MAIN.on_pot_stop_clicked() @@ -363,12 +371,12 @@ class PD(ExpInterface): try: self.builder.get_object('light_label').set_text(str( dstat_comm.read_light_sensor())) - dstat_comm.read_settings() - state.settings['tcs_enabled'][1] = '1' # Make sure TCS enabled - dstat_comm.write_settings() + comm.read_settings() + state.settings['tcs_enabled'] = '1' # Make sure TCS enabled + comm.write_settings() self.builder.get_object('threshold_entry').set_text(str( - state.settings['tcs_clear_threshold'][1])) + state.settings['tcs_clear_threshold'])) __main__.MAIN.start_ocp() finally: @@ -382,12 +390,12 @@ class PD(ExpInterface): i.set_sensitive(False) try: - state.settings['tcs_clear_threshold'][1] = self.builder.get_object( + state.settings['tcs_clear_threshold'] = self.builder.get_object( 'threshold_entry').get_text() - dstat_comm.write_settings() - dstat_comm.read_settings() + comm.write_settings() + comm.read_settings() self.builder.get_object('threshold_entry').set_text( - str(state.settings['tcs_clear_threshold'][1])) + str(state.settings['tcs_clear_threshold'])) __main__.MAIN.start_ocp() finally: @@ -405,10 +413,10 @@ class PD(ExpInterface): class POT(ExpInterface): """Experiment class for Potentiometry.""" id = 'pot' - experiment = exp.PotExp + experiment = pot.PotExp def __init__(self): """Adds entry listings to superclass's self.entry dict""" - super(POT, self).__init__('interface/potexp.glade') + super(POT, self).__init__(os.path.join(mod_dir, 'potexp.glade')) self.name = "Potentiometry" self.entry['time'] = self.builder.get_object('time_entry') @@ -416,10 +424,10 @@ class POT(ExpInterface): class CAL(ExpInterface): """Experiment class for Calibrating gain.""" id = 'cal' - experiment = exp.CALExp + experiment = cal.CALExp def __init__(self): """Adds entry listings to superclass's self.entry dict""" - super(CAL, self).__init__('interface/calib.glade') + super(CAL, self).__init__(os.path.join(mod_dir, 'calib.glade')) self.name = "Calilbration" self.entry['time'] = self.builder.get_object('time_entry') @@ -442,22 +450,22 @@ class CAL(ExpInterface): try: __main__.MAIN.on_pot_stop_clicked() __main__.MAIN.stop_ocp() - dstat_comm.read_settings() + comm.read_settings() self.entry['R100'].set_text(str( - state.settings['r100_trim'][1])) + state.settings['r100_trim'])) self.entry['R3k'].set_text(str( - state.settings['r3k_trim'][1])) + state.settings['r3k_trim'])) self.entry['R30k'].set_text(str( - state.settings['r30k_trim'][1])) + state.settings['r30k_trim'])) self.entry['R300k'].set_text(str( - state.settings['r300k_trim'][1])) + state.settings['r300k_trim'])) self.entry['R3M'].set_text(str( - state.settings['r3M_trim'][1])) + state.settings['r3M_trim'])) self.entry['R30M'].set_text(str( - state.settings['r30M_trim'][1])) + state.settings['r30M_trim'])) self.entry['R100M'].set_text(str( - state.settings['r100M_trim'][1])) + state.settings['r100M_trim'])) __main__.MAIN.start_ocp() @@ -472,14 +480,14 @@ class CAL(ExpInterface): __main__.MAIN.on_pot_stop_clicked() __main__.MAIN.stop_ocp() - state.settings['r100_trim'][1] = self.entry['R100'].get_text() - state.settings['r3k_trim'][1] = self.entry['R3k'].get_text() - state.settings['r30k_trim'][1] = self.entry['R30k'].get_text() - state.settings['r300k_trim'][1] = self.entry['R300k'].get_text() - state.settings['r3M_trim'][1] = self.entry['R3M'].get_text() - state.settings['r30M_trim'][1] = self.entry['R30M'].get_text() - state.settings['r100M_trim'][1] = self.entry['R100M'].get_text() - dstat_comm.write_settings() + state.settings['r100_trim'] = self.entry['R100'].get_text() + state.settings['r3k_trim'] = self.entry['R3k'].get_text() + state.settings['r30k_trim'] = self.entry['R30k'].get_text() + state.settings['r300k_trim'] = self.entry['R300k'].get_text() + state.settings['r3M_trim'] = self.entry['R3M'].get_text() + state.settings['r30M_trim'] = self.entry['R30M'].get_text() + state.settings['r100M_trim'] = self.entry['R100M'].get_text() + comm.write_settings() __main__.MAIN.start_ocp() @@ -487,7 +495,7 @@ class CAL(ExpInterface): GObject.timeout_add(700, restore_buttons, self.buttons) def on_measure_button_clicked(self, data=None): - if (int(self.entry['time'].get_text()) <= 0 or int(self.entry['time'].get_text()) > 65535): + if int(self.entry['time'].get_text()) <= 0 or int(self.entry['time'].get_text()) > 65535: logger.error("ERR: Time out of range") return @@ -502,28 +510,29 @@ class CAL(ExpInterface): for i in offset: logger.info("{} {}".format(i, str(-offset[i]))) - state.settings[i][1] = str(-offset[i]) + state.settings[i] = str(-offset[i]) self.entry['R100'].set_text(str( - state.settings['r100_trim'][1])) + state.settings['r100_trim'])) self.entry['R3k'].set_text(str( - state.settings['r3k_trim'][1])) + state.settings['r3k_trim'])) self.entry['R30k'].set_text(str( - state.settings['r30k_trim'][1])) + state.settings['r30k_trim'])) self.entry['R300k'].set_text(str( - state.settings['r300k_trim'][1])) + state.settings['r300k_trim'])) self.entry['R3M'].set_text(str( - state.settings['r3M_trim'][1])) + state.settings['r3M_trim'])) self.entry['R30M'].set_text(str( - state.settings['r30M_trim'][1])) + state.settings['r30M_trim'])) self.entry['R100M'].set_text(str( - state.settings['r100M_trim'][1])) + state.settings['r100M_trim'])) __main__.MAIN.start_ocp() finally: GObject.timeout_add(700, restore_buttons, self.buttons) __main__.MAIN.spinner.stop() + def restore_buttons(buttons): """ Should be called with GObject callback """ for i in buttons: diff --git a/dstat_interface/interface/exp_window.py b/dstat_interface/core/interface/exp_window.py similarity index 84% rename from dstat_interface/interface/exp_window.py rename to dstat_interface/core/interface/exp_window.py index 413d43a2e8d00a8004ffc7bf0ac432448c3dad68..cced5a5905e914f13428da170b8f1c7e9b3b4075 100755 --- a/dstat_interface/interface/exp_window.py +++ b/dstat_interface/core/interface/exp_window.py @@ -26,18 +26,21 @@ try: gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GObject except ImportError: - print "ERR: GTK not available" + import sys + print("ERR: GTK not available") sys.exit(1) -import interface.exp_int as exp +from . import exp_int + +logger = logging.getLogger(__name__) -logger = logging.getLogger("dstat.interface.exp_window") class Experiments(GObject.Object): __gsignals__ = { 'run_utility': (GObject.SIGNAL_RUN_FIRST, None, ()), 'done_utility': (GObject.SIGNAL_RUN_FIRST, None, ()) } + def __init__(self, builder): super(Experiments,self).__init__() self.builder = builder @@ -46,13 +49,14 @@ class Experiments(GObject.Object): # (experiment index in UI, experiment) classes = {c.id : c() # Make class instances - for _, c in inspect.getmembers(exp, inspect.isclass) - if issubclass(c, exp.ExpInterface) - and c is not exp.ExpInterface + for _, c in inspect.getmembers(exp_int, inspect.isclass) + if issubclass(c, exp_int.ExpInterface) + and c is not exp_int.ExpInterface } self.classes = OrderedDict(sorted(classes.items())) - #fill exp_section + + # fill exp_section exp_section = self.builder.get_object('exp_section_box') self.containers = {} @@ -85,7 +89,10 @@ class Experiments(GObject.Object): """Change the experiment window when experiment box changed.""" self.set_exp(self.expcombobox.get_active_id()) - def setup_exp(self, parameters): + def setup_exp(self, parameters, state=None): + """Takes parameters. + Returns experiment instance. + """ exp = self.classes[self.expcombobox.get_active_id()] try: exp.param_test(parameters) @@ -94,8 +101,8 @@ class Experiments(GObject.Object): "Experiment {} has no defined parameter test.".format( exp.name) ) - return exp.experiment(parameters) - + return exp.get_experiment(parameters, state) + def hide_exps(self): for key in self.containers: self.containers[key].hide() @@ -117,4 +124,7 @@ class Experiments(GObject.Object): return self.classes[experiment].params def set_params(self, experiment, parameters): - self.classes[experiment].params = parameters \ No newline at end of file + try: + self.classes[experiment].params = parameters + except KeyError as e: + logger.warning("Tried to load inavlid experiment with id %s", e.args) \ No newline at end of file diff --git a/dstat_interface/core/interface/hw_info.py b/dstat_interface/core/interface/hw_info.py new file mode 100755 index 0000000000000000000000000000000000000000..3a8228b91893a103debf76d5867e09dc129996c9 --- /dev/null +++ b/dstat_interface/core/interface/hw_info.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from __future__ import (absolute_import, division, + print_function, unicode_literals) + +from ..dstat import state, dfu +from ..dstat.comm import dstat_logger, exp_logger + +import logging +import time +import serial + +logger = logging.getLogger(__name__) + +try: + import gi + gi.require_version('Gtk', '3.0') + from gi.repository import Gtk, GObject +except ImportError: + print("ERR: GTK not available") + sys.exit(1) + +class InfoDialog(object): + def __init__(self, parent, connect, signal='activate'): + self.parent = parent + connect.connect(signal, self.activate) + + def activate(self, object=None, data=None): + self.dialog = Gtk.MessageDialog(self.parent, 0, Gtk.MessageType.INFO, + Gtk.ButtonsType.OK, "DStat Info") + self.dialog.format_secondary_text( + "PCB Version: {}\n".format(state.dstat_version.base_version) + + "Firmware Version: {}".format(state.firmware_version) + ) + + self.dialog.connect('response', self.destroy) + self.dialog.show() + + def destroy(self, object=None, data=None): + self.dialog.destroy() + + +class ResetDialog(object): + def __init__(self, parent, connect, stop_callback, disconnect_callback, signal='activate'): + self.parent = parent + self.stop = stop_callback + self.disconnect = disconnect_callback + connect.connect(signal, self.activate) + + def activate(self, object=None, data=None): + dialog = Gtk.MessageDialog(self.parent, 0, Gtk.MessageType.WARNING, + Gtk.ButtonsType.OK_CANCEL, "EEPROM Reset") + dialog.format_secondary_text("This will reset the DStat's EEPROM settings, then disconneect." + ) + + response = dialog.run() + if response == Gtk.ResponseType.OK: + self.dstat_reset_eeprom() + dialog.destroy() + + def dstat_reset_eeprom(self): + """Tries to contact DStat and resets EEPROM. + If no response, returns False, otherwise True. + """ + self.stop() + exp = EEPROMReset() + state.ser.start_exp(exp) + logger.info("Resetting DStat EEPROM…") + while True: + result = state.ser.get_proc(block=True) + if result in ('SERIAL_ERROR', 'DONE', 'ABORT'): + break + logger.info(result) + + self.disconnect() + + +class EEPROMReset(object): + def __init__(self): + pass + + def run(self, ser, ctrl_pipe, data_pipe): + status = None + try: + ser.write(b'!2\n') + exp_logger.info('!2') + + for i in range(10): + if ser.readline().rstrip() == b"@ACK 2": + dstat_logger.info('@ACK 2') + ser.write(b'SD\n') + exp_logger.info('SD') + status = "DONE" + time.sleep(5) + break + else: + time.sleep(.5) + ser.reset_input_buffer() + ser.write(b'!2\n') + exp_logger.info('!2') + time.sleep(.1) + + except UnboundLocalError as e: + status = "SERIAL_ERROR" + except serial.SerialException as e: + logger.error('SerialException: %s', e) + status = "SERIAL_ERROR" + finally: + return status \ No newline at end of file diff --git a/dstat_interface/interface/lsv.glade b/dstat_interface/core/interface/lsv.glade similarity index 100% rename from dstat_interface/interface/lsv.glade rename to dstat_interface/core/interface/lsv.glade diff --git a/dstat_interface/interface/pd.glade b/dstat_interface/core/interface/pd.glade similarity index 100% rename from dstat_interface/interface/pd.glade rename to dstat_interface/core/interface/pd.glade diff --git a/dstat_interface/plot.py b/dstat_interface/core/interface/plot.py similarity index 98% rename from dstat_interface/plot.py rename to dstat_interface/core/interface/plot.py index 7e87c41b05021601d353953f9ddc9ce2bdbbefa8..cc0d89b70368c777b427919639caa2649edc074e 100755 --- a/dstat_interface/plot.py +++ b/dstat_interface/core/interface/plot.py @@ -25,7 +25,8 @@ try: gi.require_version('Gtk', '3.0') from gi.repository import Gtk except ImportError: - print "ERR: GTK not available" + import sys + print("ERR: GTK not available") sys.exit(1) from matplotlib.figure import Figure diff --git a/dstat_interface/interface/plot_ui.py b/dstat_interface/core/interface/plot_ui.py similarity index 90% rename from dstat_interface/interface/plot_ui.py rename to dstat_interface/core/interface/plot_ui.py index b0ff570fb85c4875576e73cdcb6a663c3d7a7c77..5976273fced0ff0c8d5cbb3de893ee35bd8ae258 100644 --- a/dstat_interface/interface/plot_ui.py +++ b/dstat_interface/core/interface/plot_ui.py @@ -1,12 +1,13 @@ import logging -logger = logging.getLogger("dstat.interface.plot_ui") +logger = logging.getLogger(__name__) try: import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk except ImportError: - print "ERR: GTK not available" + import sys + print("ERR: GTK not available") sys.exit(1) from matplotlib.backends.backend_gtk3 \ diff --git a/dstat_interface/interface/potexp.glade b/dstat_interface/core/interface/potexp.glade similarity index 100% rename from dstat_interface/interface/potexp.glade rename to dstat_interface/core/interface/potexp.glade diff --git a/dstat_interface/interface/save.py b/dstat_interface/core/interface/save.py similarity index 97% rename from dstat_interface/interface/save.py rename to dstat_interface/core/interface/save.py index 76a714e49b41d0fb54347b224bf2aec2984aa573..cde0ca39043753ec7a57dd1e6076adb1fb38fb8f 100755 --- a/dstat_interface/interface/save.py +++ b/dstat_interface/core/interface/save.py @@ -22,21 +22,20 @@ from __future__ import division, absolute_import, print_function, unicode_litera import io import os +import logging +logger = logging.getLogger(__name__) + try: import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk except ImportError: + import sys print("ERR: GTK not available") sys.exit(1) -import numpy as np -import logging -logger = logging.getLogger("dstat.interface.save") - -from errors import InputError, VarError -from params import save_params, load_params +from ..params import save_params, load_params def manSave(current_exp): fcd = Gtk.FileChooserDialog("Save…", None, Gtk.FileChooserAction.SAVE, @@ -164,6 +163,7 @@ def man_param_load(window): elif response == Gtk.ResponseType.CANCEL: fcd.destroy() + def autoSave(exp, path, name): if name == "": name = "file" @@ -173,6 +173,7 @@ def autoSave(exp, path, name): save_text(exp, path) + def autoPlot(exp, path, name): if name == "": name = "file" @@ -202,7 +203,8 @@ def save_text(exp, path): for key, text in savestrings.items(): with open('{}-{}.txt'.format(save_path, key), 'w') as f: f.write(text) - + + def save_plot(exp, path): """Saves everything in exp.plots to path. Appends a number for duplicates. If no file extension or unknown, uses pdf. diff --git a/dstat_interface/interface/swv.glade b/dstat_interface/core/interface/swv.glade similarity index 100% rename from dstat_interface/interface/swv.glade rename to dstat_interface/core/interface/swv.glade diff --git a/dstat_interface/microdrop.py b/dstat_interface/core/microdrop.py similarity index 100% rename from dstat_interface/microdrop.py rename to dstat_interface/core/microdrop.py diff --git a/dstat_interface/params.py b/dstat_interface/core/params.py similarity index 93% rename from dstat_interface/params.py rename to dstat_interface/core/params.py index 0aa85802c1dd47a248743b01beb1c8dc84b55f74..a42778c04d4bc25fca9a0d3a74cea4fedea2fef7 100755 --- a/dstat_interface/params.py +++ b/dstat_interface/core/params.py @@ -21,16 +21,16 @@ import logging import yaml -from errors import InputError +from .errors import InputError + +logger = logging.getLogger(__name__) -logger = logging.getLogger('dstat.params') def get_params(window): """Fetches and returns dict of all parameters for saving.""" selection = window.exp_window.expcombobox.get_active_id() - parameters = {} - parameters['experiment_index'] = selection + parameters = {'experiment_index' : selection} try: parameters['version'] = window.version @@ -46,6 +46,7 @@ def get_params(window): return parameters + def save_params(window, path): """Fetches current params and saves to path.""" logger.info("Save to: %s", path) @@ -54,6 +55,7 @@ def save_params(window, path): with open(path, 'w') as f: yaml.dump(params, f) + def load_params(window, path): """Loads params from a path into UI elements.""" @@ -65,9 +67,10 @@ def load_params(window, path): pass with open(path, 'r') as f: - params = yaml.load(f) + params = yaml.load(f, Loader=yaml.SafeLoader) set_params(window, params) + def set_params(window, params): window.adc_pot.params = params if 'experiment_index' in params: diff --git a/dstat_interface/plugin.py b/dstat_interface/core/plugin.py similarity index 95% rename from dstat_interface/plugin.py rename to dstat_interface/core/plugin.py index 59ec93d013d7c1a6e3410f6722fc4b6ed5f55edb..ad1058edfa072c17b7c6c253a4f3123a3d1d1d7c 100644 --- a/dstat_interface/plugin.py +++ b/dstat_interface/core/plugin.py @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- import logging -from params import get_params, set_params, load_params, save_params -from interface.save import save_text, save_plot -from zmq_plugin.plugin import Plugin as ZmqPlugin -from zmq_plugin.schema import decode_content_data +from .params import get_params, set_params, load_params, save_params +from .interface.save import save_text, save_plot +# from zmq_plugin.plugin import Plugin as ZmqPlugin +# from zmq_plugin.schema import decode_content_data import gtk import zmq diff --git a/dstat_interface/core/utils/__init__.py b/dstat_interface/core/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/dstat_interface/version.py b/dstat_interface/core/utils/version.py similarity index 81% rename from dstat_interface/version.py rename to dstat_interface/core/utils/version.py index 343f158f74594923d656e5be8ad57b09b3c56a1c..0bc434bb77f6e19c3cf7febde5bfa45636fafec4 100644 --- a/dstat_interface/version.py +++ b/dstat_interface/core/utils/version.py @@ -35,6 +35,7 @@ With that setup, a new release can be labelled by simply invoking: git tag -s v1.0 """ +from __future__ import division, absolute_import, print_function, unicode_literals __author__ = ('Douglas Creager ', 'Michal Nazarewicz ') @@ -48,9 +49,14 @@ __all__ = ('getVersion') import re import subprocess import sys +import os.path +import inspect +import logging +logger = logging.getLogger(__name__) -RELEASE_VERSION_FILE = 'RELEASE-VERSION' +RELEASE_VERSION_FILE = '{}/RELEASE-VERSION'.format( + os.path.dirname(os.path.abspath(inspect.stack()[0][1]))) # http://www.python.org/dev/peps/pep-0386/ _PEP386_SHORT_VERSION_RE = r'\d+(?:\.\d+)+(?:(?:[abc]|rc)\d+(?:\.\d+)*)?' @@ -60,7 +66,7 @@ _GIT_DESCRIPTION_RE = r'^v(?P%s)-(?P\d+)-g(?P[\da-f]+)$' % ( _PEP386_SHORT_VERSION_RE) -def readGitVersion(): +def read_git_version(): try: proc = subprocess.Popen(('git', 'describe', '--long', '--match', 'v[0-9]*.*'), @@ -68,7 +74,7 @@ def readGitVersion(): data, _ = proc.communicate() if proc.returncode: return None - ver = data.splitlines()[0].strip() + ver = data.splitlines()[0].strip().decode('utf-8') proc = subprocess.Popen(('git', 'rev-parse', '--abbrev-ref', 'HEAD'), stdout=subprocess.PIPE, stderr=subprocess.PIPE) branch, _ = proc.communicate() @@ -80,9 +86,9 @@ def readGitVersion(): if not ver: return None m = re.search(_GIT_DESCRIPTION_RE, ver) + if not m: - sys.stderr.write('version: git description (%s) is invalid, ' - 'ignoring\n' % ver) + logger.warning('Git description (%s) is invalid, ignoring', ver) return None commits = int(m.group('commits')) @@ -99,7 +105,7 @@ def readGitVersion(): return version -def readReleaseVersion(): +def read_release_version(): try: fd = open(RELEASE_VERSION_FILE) try: @@ -107,29 +113,28 @@ def readReleaseVersion(): finally: fd.close() if not re.search(_PEP386_VERSION_RE, ver): - sys.stderr.write('version: release version (%s) is invalid, ' - 'will use it anyway\n' % ver) + logger.warning('release version (%s) is invalid, will use it anyways', ver) return ver except: return None -def writeReleaseVersion(version): +def write_release_version(version): fd = open(RELEASE_VERSION_FILE, 'w') fd.write('%s\n' % version) fd.close() -def getVersion(): - release_version = readReleaseVersion() - version = readGitVersion() or release_version +def get_version(): + release_version = read_release_version() + version = read_git_version() or release_version if not version: raise ValueError('Cannot find the version number') if version != release_version: - writeReleaseVersion(version) + write_release_version(version) return version if __name__ == '__main__': - print getVersion() + print(get_version()) diff --git a/dstat_interface/dstat_comm.py b/dstat_interface/dstat_comm.py deleted file mode 100755 index b50aa6434b3b3070d37bfacaebe3a89807c4b920..0000000000000000000000000000000000000000 --- a/dstat_interface/dstat_comm.py +++ /dev/null @@ -1,466 +0,0 @@ -#!/usr/bin/env python -# DStat Interface - An interface for the open hardware DStat potentiostat -# Copyright (C) 2014 Michael D. M. Dryden - -# Wheeler Microfluidics Laboratory -# -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . - -import serial -from serial.tools import list_ports -import time -import struct -import multiprocessing as mp -from collections import OrderedDict -import logging - -try: - import gi - gi.require_version('Gtk', '3.0') - from gi.repository import Gtk, GObject -except ImportError: - print "ERR: GTK not available" - sys.exit(1) - -from errors import InputError, VarError - -logger = logging.getLogger("dstat.comm") -dstat_logger = logging.getLogger("dstat.comm.DSTAT") -exp_logger = logging.getLogger("dstat.comm.Experiment") - -import state - -class AlreadyConnectedError(Exception): - def __init__(self): - super(AlreadyConnectedError, self).__init__(self, - "Serial instance already connected.") - -class NotConnectedError(Exception): - def __init__(self): - super(NotConnectedError, self).__init__(self, - "Serial instance not connected.") - -class ConnectionError(Exception): - def __init__(self): - super(ConnectionError, self).__init__(self, - "Could not connect.") - - -def _serial_process(ser_port, proc_pipe, ctrl_pipe, data_pipe): - ser_logger = logging.getLogger("dstat.comm._serial_process") - - connected = False - - try: - ser = serial.Serial(ser_port, timeout=1) - time.sleep(2) - ser.reset_input_buffer() - ser_logger.info("Reattaching DStat udc") - # ser.write("!R") # Send restart command - ser.close() - except serial.SerialException: - return 1 - - for i in range(5): - time.sleep(1) # Give OS time to enumerate - - try: - ser = serial.Serial(ser_port, timeout=1) - ser_logger.info("Connecting") - time.sleep(2) - connected = True - except serial.SerialException: - pass - - if connected is True: - break - - if ser.isOpen() is False: - ser_logger.info("Connection Error") - return 1 - - ser.write('!0 ') - - for i in range(10): - if ser.readline().rstrip()=="@ACK 0": - if ser.readline().rstrip()=="@RCV 0": - break - else: - time.sleep(.5) - ser.reset_input_buffer() - ser.write('!0 ') - time.sleep(.1) - - - while True: - # These can only be called when no experiment is running - if ctrl_pipe.poll(): - ctrl_buffer = ctrl_pipe.recv() - - if ctrl_buffer == ('a' or "DISCONNECT"): - proc_pipe.send("ABORT") - ser.write('a') - ser_logger.info("ABORT") - - if ctrl_buffer == "DISCONNECT": - ser_logger.info("DISCONNECT") - ser.close() - proc_pipe.send("DISCONNECT") - return 0 - - elif proc_pipe.poll(): - while ctrl_pipe.poll(): - ctrl_pipe.recv() - try: - return_code = proc_pipe.recv().run(ser, ctrl_pipe, data_pipe) - except serial.SerialException: - proc_pipe.send("DISCONNECT") - return 0 - ser_logger.info('Return code: %s', str(return_code)) - - proc_pipe.send(return_code) - - else: - time.sleep(.1) - - - -class SerialConnection(GObject.Object): - __gsignals__ = { - 'connected': (GObject.SIGNAL_RUN_FIRST, None, ()), - 'disconnected': (GObject.SIGNAL_RUN_FIRST, None, ()) - } - - def __init__(self): - super(SerialConnection, self).__init__() - self.connected = False - - def connect(self, ser_port): - if self.connected is False: - self.proc_pipe_p, self.proc_pipe_c = mp.Pipe(duplex=True) - self.ctrl_pipe_p, self.ctrl_pipe_c = mp.Pipe(duplex=True) - self.data_pipe_p, self.data_pipe_c = mp.Pipe(duplex=True) - - self.proc = mp.Process(target=_serial_process, args=(ser_port, - self.proc_pipe_c, self.ctrl_pipe_c, - self.data_pipe_c)) - self.proc.start() - time.sleep(2) - if self.proc.is_alive() is False: - raise ConnectionError() - return False - self.connected = True - self.emit('connected') - return True - else: - raise AlreadyConnectedError() - return False - - def assert_connected(self): - if self.connected is False: - raise NotConnectedError() - - def start_exp(self, exp): - self.assert_connected() - - self.proc_pipe_p.send(exp) - - def stop_exp(self): - self.assert_connected() - self.send_ctrl('a') - - def get_proc(self, block=False): - self.assert_connected() - - if block is True: - return self.proc_pipe_p.recv() - else: - if self.proc_pipe_p.poll() is True: - return self.proc_pipe_p.recv() - else: - return None - - def get_data(self, block=False): - self.assert_connected() - - if block is True: - return self.data_pipe_p.recv() - else: - if self.data_pipe_p.poll() is True: - return self.data_pipe_p.recv() - else: - return None - - def flush_data(self): - self.assert_connected() - - while self.data_pipe_p.poll() is True: - self.data_pipe_p.recv() - - def send_ctrl(self, ctrl): - self.assert_connected() - - self.ctrl_pipe_p.send(ctrl) - - def disconnect(self): - self.send_ctrl('a') - time.sleep(.2) - self.proc.terminate() - self.emit('disconnected') - self.connected = False - -class VersionCheck(object): - def __init__(self): - pass - - def run(self, ser, ctrl_pipe, data_pipe): - """Tries to contact DStat and get version. Returns a tuple of - (major, minor). If no response, returns empty tuple. - - Arguments: - ser_port -- address of serial port to use - """ - try: - ser.reset_input_buffer() - ser.write('!1\n') - - for i in range(10): - if ser.readline().rstrip()=="@ACK 1": - ser.write('V\n') - if ser.readline().rstrip()=="@RCV 1": - break - else: - time.sleep(.5) - ser.reset_input_buffer() - ser.write('!1\n') - time.sleep(.1) - - for line in ser: - dstat_logger.info(line) - if line.startswith('V'): - input = line.lstrip('V') - elif line.startswith("#"): - dstat_logger.info(line.lstrip().rstrip()) - elif line.lstrip().startswith("@DONE"): - dstat_logger.debug(line.lstrip().rstrip()) - ser.reset_input_buffer() - break - - parted = input.rstrip().split('.') - e = "PCB version: " - e += str(input.rstrip()) - dstat_logger.info(e) - - data_pipe.send((int(parted[0]), int(parted[1]))) - status = "DONE" - - except UnboundLocalError as e: - status = "SERIAL_ERROR" - except SerialException as e: - logger.error('SerialException: %s', e) - status = "SERIAL_ERROR" - - finally: - return status - -def version_check(ser_port): - """Tries to contact DStat and get version. Returns a list of - [(major, minor), serial instance]. If no response, returns empty tuple. - - Arguments: - ser_port -- address of serial port to use - """ - state.ser = SerialConnection() - - state.ser.connect(ser_port) - state.ser.start_exp(VersionCheck()) - result = state.ser.get_proc(block=True) - if result == "SERIAL_ERROR": - buffer = 1 - else: - buffer = state.ser.get_data(block=True) - logger.debug("version_check done") - time.sleep(.1) - - return buffer - - -class Settings(object): - def __init__(self, task, settings=None): - self.task = task - self.settings = settings - - def run(self, ser, ctrl_pipe, data_pipe): - """Tries to contact DStat and get settings. Returns dict of - settings. - """ - - self.ser = ser - - if 'w' in self.task: - self.write() - - if 'r' in self.task: - data_pipe.send(self.read()) - - status = "DONE" - - return status - - def read(self): - settings = OrderedDict() - self.ser.reset_input_buffer() - self.ser.write('!2\n') - - for i in range(10): - if self.ser.readline().rstrip()=="@ACK 2": - self.ser.write('SR\n') - if self.ser.readline().rstrip()=="@RCV 2": - break - else: - time.sleep(.5) - self.ser.reset_input_buffer() - self.ser.write('!2\n') - time.sleep(.1) - - for line in self.ser: - if line.lstrip().startswith('S'): - input = line.lstrip().lstrip('S') - elif line.lstrip().startswith("#"): - dstat_logger.info(line.lstrip().rstrip()) - elif line.lstrip().startswith("@DONE"): - dstat_logger.debug(line.lstrip().rstrip()) - self.ser.reset_input_buffer() - break - - parted = input.rstrip().split(':') - - for i in range(len(parted)): - settings[parted[i].split('.')[0]] = [i, parted[i].split('.')[1]] - - return settings - - def write(self): - write_buffer = range(len(self.settings)) - - for i in self.settings: # make sure settings are in right order - write_buffer[self.settings[i][0]] = self.settings[i][1] - - to_write = " ".join(write_buffer) + " " - n = len(to_write) - - self.ser.reset_input_buffer() - self.ser.write('!{}\n'.format(n)) - - for i in range(10): - if self.ser.readline().rstrip()=="@ACK {}".format(n): - self.ser.write('SW\n') - if self.ser.readline().rstrip()=="@RCV {}".format(n): - break - else: - time.sleep(.5) - self.ser.reset_input_buffer() - self.ser.write('!{}\n'.format(n)) - time.sleep(.1) - - for line in self.ser: - if line.lstrip().startswith("#"): - dstat_logger.info(line.lstrip().rstrip()) - elif line.lstrip().startswith("@DONE"): - dstat_logger.debug(line.lstrip().rstrip()) - self.ser.reset_input_buffer() - break - -def read_settings(): - """Tries to contact DStat and get settings. Returns dict of - settings. - """ - - state.ser.flush_data() - state.ser.start_exp(Settings(task='r')) - state.settings = state.ser.get_data(block=True) - - logger.debug("read_settings: %s", state.ser.get_proc(block=True)) - - return - -def write_settings(): - """Tries to write settings to DStat from global settings var. - """ - - state.ser.flush_data() - state.ser.start_exp(Settings(task='w', settings=state.settings)) - - logger.debug("write_settings: %s", state.ser.get_proc(block=True)) - - return - -class LightSensor: - def __init__(self): - pass - - def run(self, ser, ctrl_pipe, data_pipe): - """Tries to contact DStat and get light sensor reading. Returns uint of - light sensor clear channel. - """ - - ser.reset_input_buffer() - ser.write('!') - - while not ser.read()=="@": - self.ser.reset_input_buffer() - ser.write('!') - - ser.write('T') - for line in ser: - if line.lstrip().startswith('T'): - input = line.lstrip().lstrip('T') - elif line.lstrip().startswith("#"): - dstat_logger.info(line.lstrip().rstrip()) - elif line.lstrip().startswith("@DONE"): - dstat_logger.debug(line.lstrip().rstrip()) - ser.reset_input_buffer() - break - - parted = input.rstrip().split('.') - - data_pipe.send(parted[0]) - status = "DONE" - - return status - -def read_light_sensor(): - """Tries to contact DStat and get light sensor reading. Returns uint of - light sensor clear channel. - """ - - state.ser.flush_data() - state.ser.start_exp(LightSensor()) - - logger.debug("read_light_sensor: %s", state.ser.get_proc(block=True)) - - return state.ser.get_data(block=True) - -class SerialDevices(object): - """Retrieves and stores list of serial devices in self.ports""" - def __init__(self): - try: - self.ports, _, _ = zip(*list_ports.comports()) - except ValueError: - self.ports = [] - logger.error("No serial ports found") - - def refresh(self): - """Refreshes list of ports.""" - self.ports, _, _ = zip(*list_ports.comports()) \ No newline at end of file diff --git a/dstat_interface/experiments/__init__.py b/dstat_interface/experiments/__init__.py deleted file mode 100644 index b1fb5aef786aa35925adcf27bdf6b5f62d4be960..0000000000000000000000000000000000000000 --- a/dstat_interface/experiments/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -__all__ = [] - -import pkgutil -import inspect - -for loader, name, is_pkg in pkgutil.walk_packages(__path__): - module = loader.find_module(name).load_module(name) - - for name, value in inspect.getmembers(module): - if name.startswith('__'): - continue - - globals()[name] = value - __all__.append(name) \ No newline at end of file diff --git a/dstat_interface/experiments/cv.py b/dstat_interface/experiments/cv.py deleted file mode 100644 index fbeda5653354d01592b20cf5ca4bba310a81d527..0000000000000000000000000000000000000000 --- a/dstat_interface/experiments/cv.py +++ /dev/null @@ -1,42 +0,0 @@ -import time -import struct - -from experiments.experiment_template import PlotBox, Experiment - -class CVExp(Experiment): - id = 'cve' - """Cyclic Voltammetry experiment""" - def setup(self): - super(CVExp, self).setup() - self.datatype = "CVData" - self.xlabel = "Voltage (mV)" - self.ylabel = "Current (A)" - self.datalength = 2 * self.parameters['scans'] # x and y for each scan - self.databytes = 6 # uint16 + int32 - self.plot_format['current_voltage']['xlims'] = ( - int(self.parameters['v1']), - int(self.parameters['v2']) - ) - - self.commands += "E" - self.commands[2] += "C" - self.commands[2] += str(self.parameters['clean_s']) - self.commands[2] += " " - self.commands[2] += str(self.parameters['dep_s']) - self.commands[2] += " " - self.commands[2] += str(int(int(self.parameters['clean_mV'])* - (65536./3000)+32768)) - self.commands[2] += " " - self.commands[2] += str(int(int(self.parameters['dep_mV'])* - (65536./3000)+32768)) - self.commands[2] += " " - self.commands[2] += str(self.parameters['v1']) - self.commands[2] += " " - self.commands[2] += str(self.parameters['v2']) - self.commands[2] += " " - self.commands[2] += str(self.parameters['start']) - self.commands[2] += " " - self.commands[2] += str(self.parameters['scans']) - self.commands[2] += " " - self.commands[2] += str(self.parameters['slope']) - self.commands[2] += " " \ No newline at end of file diff --git a/dstat_interface/experiments/lsv.py b/dstat_interface/experiments/lsv.py deleted file mode 100644 index 9042a5e4c01fea7eaed4d595ede6f31fe89594fd..0000000000000000000000000000000000000000 --- a/dstat_interface/experiments/lsv.py +++ /dev/null @@ -1,37 +0,0 @@ -import time -import struct - -from experiments.experiment_template import PlotBox, Experiment - -class LSVExp(Experiment): - """Linear Scan Voltammetry experiment""" - id = 'lsv' - def setup(self): - super(LSVExp, self).setup() - - self.datatype = "linearData" - self.datalength = 2 - self.databytes = 6 # uint16 + int32 - self.plot_format['current_voltage']['xlims'] = ( - int(self.parameters['start']), - int(self.parameters['stop']) - ) - - self.commands += "E" - self.commands[2] += "L" - self.commands[2] += str(self.parameters['clean_s']) - self.commands[2] += " " - self.commands[2] += str(self.parameters['dep_s']) - self.commands[2] += " " - self.commands[2] += str(int(int(self.parameters['clean_mV'])* - (65536./3000)+32768)) - self.commands[2] += " " - self.commands[2] += str(int(int(self.parameters['dep_mV'])* - (65536./3000)+32768)) - self.commands[2] += " " - self.commands[2] += str(self.parameters['start']) - self.commands[2] += " " - self.commands[2] += str(self.parameters['stop']) - self.commands[2] += " " - self.commands[2] += str(self.parameters['slope']) - self.commands[2] += " " \ No newline at end of file diff --git a/dstat_interface/experiments/swv.py b/dstat_interface/experiments/swv.py deleted file mode 100644 index 2f3ba803da10e61f15078946485867b641081547..0000000000000000000000000000000000000000 --- a/dstat_interface/experiments/swv.py +++ /dev/null @@ -1,147 +0,0 @@ -import time -import struct -from copy import deepcopy - -from experiments.experiment_template import PlotBox, Experiment - -class SWVBox(PlotBox): - def format_plots(self): - """ - Creates and formats subplots needed. Overrides superclass. - """ - - self.subplots = {'swv' : self.figure.add_subplot(111)} - - for key, subplot in self.subplots.items(): - subplot.ticklabel_format(style='sci', scilimits=(0, 3), - useOffset=False, axis='y') - subplot.plot([],[]) - -class SWVExp(Experiment): - """Square Wave Voltammetry experiment""" - id = 'swv' - def setup(self): - self.plots.append(SWVBox(['swv'])) - - self.datatype = "SWVData" - self.xlabel = "Voltage (mV)" - self.ylabel = "Current (A)" - self.data = { - 'swv' : [([], [], [], [])] - } # voltage, current, forwards, reverse - self.line_data = ([], [], [], []) - self.datalength = 2 * self.parameters['scans'] - self.databytes = 10 - self.columns = ['Voltage (mV)', 'Net Current (A)', - 'Forward Current (A)', 'Reverse Current (A)'] - self.plot_format = { - 'swv' : {'labels' : ('Voltage (mV)', - 'Current (A)' - ), - 'xlims' : (int(self.parameters['start']), - int(self.parameters['stop'])) - } - } - - self.commands += "E" - self.commands[2] += "S" - self.commands[2] += str(self.parameters['clean_s']) - self.commands[2] += " " - self.commands[2] += str(self.parameters['dep_s']) - self.commands[2] += " " - self.commands[2] += str(int(int(self.parameters['clean_mV'])* - (65536./3000)+32768)) - self.commands[2] += " " - self.commands[2] += str(int(int(self.parameters['dep_mV'])* - (65536./3000)+32768)) - self.commands[2] += " " - self.commands[2] += str(self.parameters['start']) - self.commands[2] += " " - self.commands[2] += str(self.parameters['stop']) - self.commands[2] += " " - self.commands[2] += str(self.parameters['step']) - self.commands[2] += " " - self.commands[2] += str(self.parameters['pulse']) - self.commands[2] += " " - self.commands[2] += str(self.parameters['freq']) - self.commands[2] += " " - self.commands[2] += str(self.parameters['scans']) - self.commands[2] += " " - - def data_handler(self, input_data): - """Overrides Experiment method to calculate difference current""" - scan, data = input_data - # uint16 + int32 - voltage, forward, reverse = struct.unpack(' - - - - - False - 5 - True - dialog - DStat-interface - 1.0.3 - © Michael Dryden 2014 - This software is licensed under the GNU GPL v3 - http://microfluidics.utoronto.ca/dstat - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - Michael Dryden -Thanks to Christian Fobel for help with Dropbot Plugin - - image-missing - - - True - False - vertical - 2 - - - True - False - end - - - True - True - 0 - - - - - - - - - - - - True - False - center - gtk-missing-image - - - True - False - gtk-save-as - - - True - False - gtk-save-as - - - True - False - gtk-open - - - True - False - gtk-preferences - - - True - False - gtk-save-as - - - - - - - - - False - 6 - Main - 1200 - 800 - - - - True - False - vertical - - - True - False - - - True - False - File - - - True - False - - - Save Experiment Data… - True - False - image8 - False - - - - - - Save Plot… - True - False - image3 - False - - - - - - Save Parameters… - True - False - image4 - False - - - - - - Load Parameters… - True - False - image5 - False - - - - - - gtk-quit - True - False - True - True - - - - - - - - - - True - False - Dropbot - - - True - False - - - gtk-connect - True - False - True - True - - - - - - gtk-disconnect - True - False - False - True - True - - - - - - - - - - True - False - Analysis - - - True - False - - - Analysis Options… - True - False - image6 - False - - - - - - - - - - True - False - About - - - True - False - - - gtk-about - True - False - True - True - - - - - - - - - - False - True - 0 - - - - - True - True - 300 - True - True - - - True - False - vertical - - - True - False - vertical - - - True - False - vertical - - - - - - False - False - 0 - - - - - True - False - Experiment: - - - - - - False - False - 10 - 1 - - - - - True - False - - - False - True - 2 - - - - - False - False - 0 - - - - - True - False - vertical - - - - - - True - True - 1 - - - - - True - False - - - gtk-execute - True - True - True - True - - - - True - True - 0 - - - - - gtk-stop - True - False - True - True - True - - - - True - True - 1 - - - - - True - False - - - True - True - 2 - - - - - False - False - 2 - - - - - False - True - - - - - True - True - True - - - True - False - vertical - - - True - True - bottom - - - - - - - - - - - - - - - - - - - - - True - True - -1 - - - - - True - False - start - - - Autosave - True - True - False - True - - - False - True - 0 - - - - - True - False - start - select-folder - False - Select a Save Folder - - - True - True - 1 - - - - - True - True - True - start - 32 - - filename - False - gtk-file - False - False - File name - File name - - - False - True - 2 - - - - - False - False - 0 - - - - - - - True - False - Plot - - - False - - - - - - - - - - - - - - - - - True - True - - - - - True - True - 1 - - - - - True - False - - - True - False - 2 - - - True - True - end - 0 - - - - - True - False - Serial Port: - - - False - True - 5 - 1 - - - - - 128 - True - False - start - serial_liststore - - - False - False - 2 - - - - - gtk-connect - True - True - True - True - - - - False - False - 3 - - - - - Connect (PMT mode) - True - True - True - - - - False - False - 4 - - - - - gtk-disconnect - True - True - True - True - - - - False - False - 5 - - - - - gtk-refresh - True - True - True - True - - - - False - False - 6 - - - - - True - False - start - OCP: - True - - - False - False - 3 - 7 - - - - - False - True - 2 - - - - - - - 100 - 5 - 1 - 10 - - diff --git a/dstat_interface/interface_test.spec.bak b/dstat_interface/interface_test.spec.bak deleted file mode 100644 index 2a51ef2895825490862096abd32fa88549014575..0000000000000000000000000000000000000000 --- a/dstat_interface/interface_test.spec.bak +++ /dev/null @@ -1,25 +0,0 @@ -# -*- mode: python -*- -a = Analysis(['interface_test.py'], - hiddenimports=[], - hookspath=None, - runtime_hooks=None) -glade_tree = Tree('./interface', prefix = 'interface', excludes=['*.py','*.pyc']) -drivers_tree = Tree('./drivers', prefix = 'drivers') -pyz = PYZ(a.pure) -exe = EXE(pyz, - a.scripts, - exclude_binaries=True, - name='interface_test.exe', - debug=False, - strip=None, - upx=True, - console=True ) -coll = COLLECT(exe, - drivers_tree, - glade_tree, - a.binaries, - a.zipfiles, - a.datas, - strip=None, - upx=True, - name='interface_test') diff --git a/dstat_interface/main.py b/dstat_interface/main.py index 32c58f027b2662765dcebdd8e843e047f95eaac5..4fd1164b91dfa18957ba90ef71d6b8a9a4b2f234 100755 --- a/dstat_interface/main.py +++ b/dstat_interface/main.py @@ -20,68 +20,71 @@ """ GUI Interface for Wheeler Lab DStat """ +from __future__ import division, absolute_import, print_function, unicode_literals + import sys import os +import platform import multiprocessing import uuid -from copy import deepcopy from collections import OrderedDict from datetime import datetime +import logging +from pkg_resources import parse_version + +from serial import SerialException +import zmq + + +from dstat_interface.core.utils.version import get_version +from dstat_interface.core.experiments import idle, pot +from dstat_interface.core import params, analysis, dstat +from dstat_interface.core.dstat import boards +from dstat_interface.core.interface import (exp_window, adc_pot, plot_ui, data_view, + save, hw_info) +from dstat_interface.core.errors import InputError +# from dstat_interface.core.plugin import DstatPlugin, get_hub_uri -# try: -# import pygtk -# pygtk.require('2.0') -# except ImportError: -# print "ERR: PyGTK 2.0 not available" -# sys.exit(1) try: import gi gi.require_version('Gtk', '3.0') - from gi.repository import Gtk, GObject + from gi.repository import Gtk, GObject, GLib except ImportError: - print "ERR: GTK not available" + print("ERR: GTK not available") sys.exit(1) -from serial import SerialException -import logging -os.chdir(os.path.dirname(os.path.abspath(sys.argv[0]))) - -from version import getVersion -import interface.save as save -import dstat_comm as comm -import experiments as exp -import interface.exp_window as exp_window -import interface.adc_pot as adc_pot -import interface.plot_ui -import interface.data_view -import plot -import params -import parameter_test -import analysis -import zmq -import state -from errors import InputError - -from plugin import DstatPlugin, get_hub_uri +mod_dir = os.path.dirname(os.path.abspath(__file__)) +conf_path = os.path.join(os.path.expanduser("~"), '.dstat-interface') # Setup Logging -root_logger = logging.getLogger("dstat") -root_logger.setLevel(level=logging.INFO) +logger = logging.getLogger(__name__) +core_logger = logging.getLogger("dstat_interface.core") +loggers = [logger, core_logger] + log_handler = logging.StreamHandler() log_formatter = logging.Formatter( fmt='%(asctime)s %(levelname)s: [%(name)s] %(message)s', datefmt='%H:%M:%S' ) log_handler.setFormatter(log_formatter) -root_logger.addHandler(log_handler) -logger = logging.getLogger("dstat.main") +for log in loggers: + log.setLevel(level=logging.INFO) + log.addHandler(log_handler) -class Main(object): + +class Main(GObject.Object): """Main program """ + __gsignals__ = { + 'exp_start': (GObject.SignalFlags.RUN_FIRST, None, ()), + 'exp_stop': (GObject.SignalFlags.RUN_FIRST, None, ()) + } + def __init__(self): + super(Main, self).__init__() self.builder = Gtk.Builder() - self.builder.add_from_file('interface/dstatinterface.glade') + self.builder.add_from_file( + os.path.join(mod_dir, 'core/interface/dstatinterface.glade')) self.builder.connect_signals(self) self.cell = Gtk.CellRendererText() @@ -92,6 +95,8 @@ class Main(object): self.aboutdialog = self.builder.get_object('aboutdialog1') self.stopbutton = self.builder.get_object('pot_stop') self.startbutton = self.builder.get_object('pot_start') + self.startbutton.set_sensitive(False) + self.exp_progressbar = self.builder.get_object('exp_progressbar') self.adc_pot = adc_pot.adc_pot() self.error_context_id = self.statusbar.get_context_id("error") @@ -111,15 +116,15 @@ class Main(object): # Setup Plots self.plot_notebook = self.builder.get_object('plot_notebook') self.main_notebook = self.builder.get_object('main_notebook') - self.data_view = interface.data_view.DataPage(self.main_notebook) - self.info_page = interface.data_view.InfoPage(self.main_notebook) + self.data_view = data_view.DataPage(self.main_notebook) + self.info_page = data_view.InfoPage(self.main_notebook) - #fill adc_pot_box + # fill adc_pot_box self.adc_pot_box = self.builder.get_object('gain_adc_box') self.adc_pot_container = self.adc_pot.builder.get_object('vbox1') self.adc_pot_container.reparent(self.adc_pot_box) - #fill serial + # fill serial self.serial_connect = self.builder.get_object('serial_connect') self.serial_pmt_connect = self.builder.get_object('pmt_mode') self.serial_disconnect = self.builder.get_object('serial_disconnect') @@ -127,9 +132,8 @@ class Main(object): self.serial_combobox = self.builder.get_object('serial_combobox') self.serial_combobox.pack_start(self.cell, True) self.serial_combobox.add_attribute(self.cell, 'text', 0) - self.serial_liststore = self.builder.get_object('serial_liststore') - self.serial_devices = comm.SerialDevices() + self.serial_devices = dstat.comm.SerialDevices() for i in self.serial_devices.ports: self.serial_liststore.append([i]) @@ -139,10 +143,33 @@ class Main(object): self.spinner = self.builder.get_object('spinner') self.mainwindow = self.builder.get_object('window1') - + + self.menu_dstat_info = self.builder.get_object('menu_dstat_info') + self.menu_dstat_info.set_sensitive(False) + self.dstat_info_window = hw_info.InfoDialog( + parent=self.mainwindow, + connect=self.menu_dstat_info + ) + self.menu_dstat_fw = self.builder.get_object('menu_dstat_fw') + self.menu_dstat_fw.set_sensitive(False) + self.dstat_fw_window = dstat.dfu.FWDialog( + parent=self.mainwindow, + connect=self.menu_dstat_fw, + stop_callback=self.stop_ocp, + disconnect_callback=self.on_serial_disconnect_clicked + ) + self.menu_dstat_reset = self.builder.get_object('menu_dstat_reset') + self.menu_dstat_reset.set_sensitive(False) + self.menu_dstat_reset_window = hw_info.ResetDialog( + parent=self.mainwindow, + connect=self.menu_dstat_reset, + stop_callback=self.stop_ocp, + disconnect_callback=self.on_serial_disconnect_clicked + ) + # Set Version Strings try: - ver = getVersion() + ver = get_version() except ValueError: ver = "1.x" logger.warning("Could not fetch version number") @@ -152,12 +179,11 @@ class Main(object): self.mainwindow.show_all() self.exp_window.hide_exps() - self.expnumber = 0 self.connected = False self.pmt_mode = False - + self.menu_dropbot_connect = self.builder.get_object( 'menu_dropbot_connect') self.menu_dropbot_disconnect = self.builder.get_object( @@ -186,72 +212,105 @@ class Main(object): def quit(self): """Disconnect and save parameters on quit.""" - params.save_params(self, 'last_params.yml') - - self.on_serial_disconnect_clicked() + + try: + params.save_params(self, os.path.join(conf_path, 'last_params.yml')) + self.on_serial_disconnect_clicked() + except KeyError: + pass + mainloop.quit() def on_gtk_about_activate(self, menuitem, data=None): """Display the about window.""" - self.response = self.aboutdialog.run() # waits for user to click close + self.aboutdialog.run() # waits for user to click close self.aboutdialog.hide() def on_menu_analysis_options_activate(self, menuitem, data=None): self.analysis_opt_window.show() - def on_serial_refresh_clicked(self, data=None): """Refresh list of serial devices.""" - self.serial_devices.refresh() - self.serial_liststore.clear() + try: + self.serial_devices.refresh() + self.serial_liststore.clear() + except ValueError: + logger.warning("No DStats found") for i in self.serial_devices.ports: self.serial_liststore.append([i]) - def on_serial_connect_clicked(self, data=None): + def on_serial_connect_clicked(self, widget): """Connect and retrieve DStat version.""" + selection = self.serial_combobox.get_active_iter() + if selection is None: + return + if widget is self.serial_pmt_connect: + self.pmt_mode = True + self.adc_pot.ui['short_true'].set_active(True) + self.adc_pot.ui['short_true'].set_sensitive(False) + try: self.serial_connect.set_sensitive(False) - state.dstat_version = comm.version_check(self.serial_liststore.get_value( - self.serial_combobox.get_active_iter(), 0)) + self.serial_pmt_connect.set_sensitive(False) + dstat.comm.version_check( + self.serial_liststore.get_value(selection, 0) + ) + + dstat.state.board_instance = boards.find_board( + dstat.state.dstat_version)() self.statusbar.remove_all(self.error_context_id) - if not len(state.dstat_version) == 2: - self.statusbar.push(self.error_context_id, - "Communication Error") - return + self.adc_pot.set_version() + self.statusbar.push( + self.message_context_id, + "DStat version: {}".format( + dstat.state.dstat_version.base_version) + ) - else: - self.adc_pot.set_version(state.dstat_version) - self.statusbar.push(self.error_context_id, - "".join(["DStat version: ", - str(state.dstat_version[0]), - ".", str(state.dstat_version[1])]) - ) + dstat.comm.read_settings() - comm.read_settings() + try: + if dstat.state.settings['dac_units_true'] != '1': + dstat.state.settings['dac_units_true'] = '1' + dstat.comm.write_settings() + except KeyError: + logger.warning("Connected DStat does not support sending DAC units.") + dialog = Gtk.MessageDialog( + parent=self.window, + flags=0, message_type=Gtk.MessageType.WARNING, + buttons=Gtk.ButtonsType.OK, + text="Connected DStat does not support sending DAC units." + + "Update firmware or set potentials will be incorrect!") - self.start_ocp() - self.connected = True - self.serial_connect.set_sensitive(False) - self.serial_pmt_connect.set_sensitive(False) - self.serial_disconnect.set_sensitive(True) + dialog.run() + dialog.destroy() - except AttributeError as err: - logger.warning("AttributeError: %s", err) - self.serial_connect.set_sensitive(True) - except TypeError as err: - logger.warning("TypeError: %s", err) + self.start_ocp() + self.connected = True + self.serial_disconnect.set_sensitive(True) + + except: self.serial_connect.set_sensitive(True) + self.serial_pmt_connect.set_sensitive(True) + self.adc_pot.ui['short_true'].set_sensitive(True) + raise if self.params_loaded == False: try: - params.load_params(self, 'last_params.yml') + try: + os.makedirs(conf_path) + except OSError: + if not os.path.isdir(conf_path): + raise + params.load_params(self, + os.path.join(conf_path, 'last_params.yml') + ) except IOError: logger.info("No previous parameters found.") - + def on_serial_disconnect_clicked(self, data=None): """Disconnect from DStat.""" if self.connected == False: @@ -262,46 +321,53 @@ class Main(object): self.stop_ocp() else: self.on_pot_stop_clicked() - state.ser.send_ctrl("DISCONNECT") - state.ser.disconnect() + dstat.state.ser.disconnect() except AttributeError as err: logger.warning("AttributeError: %s", err) pass - + + if self.pmt_mode is True: + self.adc_pot.ui['short_true'].set_sensitive(True) + self.pmt_mode = False self.connected = False self.serial_connect.set_sensitive(True) self.serial_pmt_connect.set_sensitive(True) self.serial_disconnect.set_sensitive(False) + self.startbutton.set_sensitive(False) + self.stopbutton.set_sensitive(False) + self.menu_dstat_info.set_sensitive(False) + self.menu_dstat_fw.set_sensitive(False) + self.menu_dstat_reset.set_sensitive(False) self.adc_pot.ui['short_true'].set_sensitive(True) - - def on_pmt_mode_clicked(self, data=None): - """Connect in PMT mode""" - self.pmt_mode = True - self.adc_pot.ui['short_true'].set_active(True) - self.adc_pot.ui['short_true'].set_sensitive(False) - self.on_serial_connect_clicked() + + dstat.state.reset() def start_ocp(self, data=None): """Start OCP measurements.""" - - if state.dstat_version[0] >= 1 and state.dstat_version[1] >= 2: + if dstat.state.dstat_version >= parse_version('1.2'): # Flush data pipe - state.ser.flush_data() + dstat.state.ser.flush_data() - if self.pmt_mode == True: + if self.pmt_mode is True: logger.info("Start PMT idle mode") - state.ser.start_exp(exp.PMTIdle()) + dstat.state.ser.start_exp(idle.PMTIdle(state=dstat.state.get_state())) + self.ocp_is_running = True + self.ocp_proc = (GLib.timeout_add(250, self.ocp_running_proc) + , + ) else: logger.info("Start OCP") - state.ser.start_exp(exp.OCPExp()) + dstat.state.ser.start_exp(idle.OCPExp(state=dstat.state.get_state())) - self.ocp_proc = (GObject.timeout_add(300, self.ocp_running_data), - GObject.timeout_add(250, self.ocp_running_proc) - ) - self.ocp_is_running = True + self.ocp_proc = (GLib.timeout_add(300, self.ocp_running_data), + GLib.timeout_add(250, self.ocp_running_proc) + ) + self.ocp_is_running = False + + GLib.timeout_add(100, self.ocp_assert) # Check if getting data else: logger.info("OCP measurements not supported on v1.1 boards.") @@ -310,23 +376,37 @@ class Main(object): def stop_ocp(self, data=None): """Stop OCP measurements.""" - if state.dstat_version[0] >= 1 and state.dstat_version[1] >= 2: + if dstat.state.dstat_version >= parse_version('1.2'): if self.pmt_mode == True: logger.info("Stop PMT idle mode") else: logger.info("Stop OCP") - state.ser.send_ctrl('a') - + dstat.state.ser.send_ctrl('a') + for i in self.ocp_proc: - GObject.source_remove(i) + GLib.source_remove(i) while self.ocp_running_proc(): pass - self.ocp_is_running = False self.ocp_disp.set_text("") + self.ocp_is_running = False + self.startbutton.set_sensitive(True) + self.menu_dstat_info.set_sensitive(True) + self.menu_dstat_fw.set_sensitive(True) + self.menu_dstat_reset.set_sensitive(True) else: logger.error("OCP measurements not supported on v1.1 boards.") return + def ocp_assert(self): + if self.ocp_is_running: + self.startbutton.set_sensitive(True) + self.menu_dstat_info.set_sensitive(True) + self.menu_dstat_fw.set_sensitive(True) + self.menu_dstat_reset.set_sensitive(True) + return False + else: + return True + def ocp_running_data(self): """Receive OCP value from experiment process and update ocp_disp field @@ -337,9 +417,9 @@ class Main(object): """ try: - incoming = state.ser.get_data() + incoming = dstat.state.ser.get_data() while incoming is not None: - if isinstance(incoming, basestring): # test if incoming is str + if isinstance(incoming, bytes): # test if incoming is str self.on_serial_disconnect_clicked() return False @@ -348,10 +428,11 @@ class Main(object): "{0:.3f}".format(incoming), " V"]) self.ocp_disp.set_text(data) + self.ocp_is_running = True except ValueError: pass - incoming = state.ser.get_data() + incoming = dstat.state.ser.get_data() return True @@ -370,16 +451,16 @@ class Main(object): """ try: - proc_buffer = state.ser.get_proc() + proc_buffer = dstat.state.ser.get_proc() while proc_buffer is not None: logger.debug("ocp_running_proc: %s", proc_buffer) if proc_buffer in ["DONE", "SERIAL_ERROR", "ABORT"]: if proc_buffer == "SERIAL_ERROR": self.on_serial_disconnect_clicked() - state.ser.flush_data() + dstat.state.ser.flush_data() return False - proc_buffer = state.ser.get_proc() + proc_buffer = dstat.state.ser.get_proc() return True except EOFError: @@ -417,7 +498,7 @@ class Main(object): self.stop_ocp() self.statusbar.remove_all(self.error_context_id) - state.ser.flush_data() + dstat.state.ser.flush_data() parameters = {} parameters['metadata'] = self.metadata @@ -439,35 +520,33 @@ class Main(object): self.startbutton.set_sensitive(False) self.stopbutton.set_sensitive(True) self.statusbar.remove_all(self.error_context_id) + + try: + del self.current_exp + except AttributeError: + pass + + callbacks = {'experiment_done' : self.experiment_done, + 'progress_update' : self.progress_update} + + self.current_exp = self.exp_window.setup_exp(parameters, state=dstat.state.get_state()) - self.current_exp = self.exp_window.setup_exp(parameters) - - interface.plot_ui.replace_notebook_exp( + plot_ui.replace_notebook_exp( self.plot_notebook, self.current_exp, self.window ) - - for plot in self.current_exp.plots: - plot.changetype(self.current_exp) self.data_view.clear_exps() self.info_page.clear() - state.ser.start_exp(self.current_exp) + dstat.state.ser.start_exp(self.current_exp) # Flush data pipe - state.ser.flush_data() - - self.plot_proc = GObject.timeout_add(200, - self.experiment_running_plot) - self.experiment_proc = ( - GObject.idle_add(self.experiment_running_data), - GObject.idle_add(self.experiment_running_proc) - ) - + dstat.state.ser.flush_data() + self.current_exp.setup_loops(callbacks) return experiment_id except ValueError as i: - logger.info("ValueError: %s",i) + logger.info("ValueError: %s", i) self.statusbar.push(self.error_context_id, "Experiment parameters must be integers.") exceptions() @@ -501,6 +580,12 @@ class Main(object): exceptions() raise + def progress_update(self, widget, progress): + if 0 <= progress <= 1: + self.exp_progressbar.set_fraction(progress) + else: + self.exp_progressbar.pulse() + def experiment_running_data(self): """Receive data from experiment process and add to current_exp.data['data]. @@ -512,27 +597,35 @@ class Main(object): function from GTK's queue. """ try: - incoming = state.ser.get_data() + incoming = dstat.state.ser.get_data() while incoming is not None: try: self.line, data = incoming if self.line > self.lastdataline: newline = True + try: + logger.info("running scan_process()") + self.current_exp.scan_process(self.lastdataline) + except AttributeError: + pass self.lastdataline = self.line else: newline = False self.current_exp.store_data(incoming, newline) + + if newline: + self.experiment_running_plot() except TypeError: pass - incoming = state.ser.get_data() + incoming = dstat.state.ser.get_data() return True except EOFError as err: - print err + logger.error(err) self.experiment_done() return False except IOError as err: - print err + logger.error(err) self.experiment_done() return False @@ -546,7 +639,14 @@ class Main(object): function from GTK's queue. """ try: - proc_buffer = state.ser.get_proc() + ctrl_buffer = dstat.state.ser.get_ctrl() + try: + if ctrl_buffer is not None: + self.current_exp.ctrl_loop(ctrl_buffer) + except AttributeError: + pass + + proc_buffer = dstat.state.ser.get_proc() if proc_buffer is not None: if proc_buffer in ["DONE", "SERIAL_ERROR", "ABORT"]: self.experiment_done() @@ -574,53 +674,32 @@ class Main(object): removed from GTK's queue. """ for plot in self.current_exp.plots: - if self.line > self.lastline: - plot.addline() - # make sure all of last line is added - plot.updateline(self.current_exp, self.lastline) - self.lastline = self.line - plot.updateline(self.current_exp, self.line) + if plot.scan_refresh and self.line > self.lastline: + while self.line > self.lastline: + # make sure all of last line is added + plot.updateline(self.current_exp, self.lastline) + self.lastline += 1 + plot.updateline(self.current_exp, self.line) + plot.redraw() + else: + while self.line > self.lastline: + # make sure all of last line is added + plot.updateline(self.current_exp, self.lastline) + self.lastline += 1 + plot.updateline(self.current_exp, self.line) if plot.continuous_refresh is True or force_refresh is True: plot.redraw() return True - def experiment_done(self): + def experiment_done(self, widget=None): """Clean up after data acquisition is complete. Update plot and copy data to raw data tab. Saves data if autosave enabled. """ try: - self.current_exp.experiment_done() - GObject.source_remove(self.experiment_proc[0]) - GObject.source_remove(self.plot_proc) # stop automatic plot update - self.experiment_running_plot(force_refresh=True) - - - # # Shutter stuff - # if (self.current_exp.parameters['shutter_true'] and - # self.current_exp.parameters['sync_true']): - # self.ft_plot.updateline(self.current_exp, 0) - # self.ft_plot.redraw() - # - # line_buffer = [] - # - # for scan in self.current_exp.data['ft']: - # for dimension in scan: - # for i in range(len(dimension)): - # try: - # line_buffer[i] += "%s " % dimension[i] - # except IndexError: - # line_buffer.append("") - # line_buffer[i] += "%s " % dimension[i] - # - # for i in line_buffer: - # self.databuffer.insert_at_cursor("%s\n" % i) - # Run Analysis analysis.do_analysis(self.current_exp) - self.current_exp.experiment_done() - # Write DStat commands self.info_page.set_text(self.current_exp.get_info_text()) @@ -668,17 +747,24 @@ class Main(object): self.metadata = None # Reset metadata self.spinner.stop() - self.startbutton.set_sensitive(True) + self.exp_progressbar.set_fraction(0) self.stopbutton.set_sensitive(False) self.start_ocp() self.completed_experiment_ids[self.active_experiment_id] =\ datetime.utcnow() + # Temporary fix for weird drawing bug on windows Gtk+3 + if platform.system() == 'Windows': + position = self.window.get_position() + self.window.hide() + self.window.show() + self.window.move(*position) + def on_pot_stop_clicked(self, data=None): """Stop current experiment. Signals experiment process to stop.""" try: - state.ser.stop_exp() + dstat.state.ser.stop_exp() except AttributeError: pass @@ -711,14 +797,14 @@ class Main(object): """Listen for remote control connection from µDrop.""" # Prompt user for 0MQ plugin hub URI. - zmq_plugin_hub_uri = get_hub_uri(parent=self.window) + # zmq_plugin_hub_uri = get_hub_uri(parent=self.window) self.dropbot_enabled = True self.menu_dropbot_connect.set_sensitive(False) self.menu_dropbot_disconnect.set_sensitive(True) self.statusbar.push(self.message_context_id, "Waiting for µDrop to connect…") - self.enable_plugin(zmq_plugin_hub_uri) + # self.enable_plugin(zmq_plugin_hub_uri) def on_menu_dropbot_disconnect_activate(self, menuitem=None, data=None): """Disconnect µDrop connection and stop listening.""" @@ -739,14 +825,14 @@ class Main(object): ''' self.cleanup_plugin() # Initialize 0MQ hub plugin and subscribe to hub messages. - self.plugin = DstatPlugin(self, 'dstat-interface', hub_uri, - subscribe_options={zmq.SUBSCRIBE: ''}) - # Initialize sockets. - self.plugin.reset() - - # Periodically process outstanding message received on plugin sockets. - self.plugin_timeout_id = Gtk.timeout_add(500, - self.plugin.check_sockets) + # self.plugin = DstatPlugin(self, 'dstat-interface', hub_uri, + # subscribe_options={zmq.SUBSCRIBE: ''}) + # # Initialize sockets. + # self.plugin.reset() + # + # # Periodically process outstanding message received on plugin sockets. + # self.plugin_timeout_id = Gtk.timeout_add(500, + # self.plugin.check_sockets) def cleanup_plugin(self): if self.plugin_timeout_id is not None: @@ -757,9 +843,8 @@ class Main(object): if __name__ == "__main__": multiprocessing.freeze_support() - GObject.threads_init() MAIN = Main() - mainloop = GObject.MainLoop() + mainloop = GLib.MainLoop() try: mainloop.run() except KeyboardInterrupt: diff --git a/dstat_interface/mr_db b/dstat_interface/mr_db deleted file mode 160000 index 72481e585d92d0adab6537718a4d18164df1b445..0000000000000000000000000000000000000000 --- a/dstat_interface/mr_db +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 72481e585d92d0adab6537718a4d18164df1b445 diff --git a/dstat_interface/parameter_test.py b/dstat_interface/parameter_test.py deleted file mode 100755 index ec629439eac8b2f53edaa63ea6590fa0c9ef0319..0000000000000000000000000000000000000000 --- a/dstat_interface/parameter_test.py +++ /dev/null @@ -1,242 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# DStat Interface - An interface for the open hardware DStat potentiostat -# Copyright (C) 2014 Michael D. M. Dryden - -# Wheeler Microfluidics Laboratory -# -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . - -import logging - -from errors import InputError - -logger = logging.getLogger("dstat.parameter_test") - -def lsv_test(params): - """Test LSV parameters for sanity""" - test_parameters = ['clean_mV', 'dep_mV', 'clean_s', 'dep_s', 'start', - 'stop', 'slope'] - parameters = {} - for i in params: - if i in test_parameters: - parameters[i] = int(params[i]) - - if (parameters['clean_mV'] > 1499 or - parameters['clean_mV'] < -1500): - raise InputError(parameters['clean_mV'], - "Clean potential exceeds hardware limits.") - if (parameters['dep_mV'] > 1499 or - parameters['dep_mV'] < -1500): - raise InputError(parameters['dep_mV'], - "Deposition potential exceeds hardware limits.") - if (parameters['clean_s'] < 0): - raise InputError(parameters['clean_s'], - "Clean time cannot be negative.") - if (parameters['dep_s'] < 0): - raise InputError(parameters['dep_s'], - "Deposition time cannot be negative.") - if (parameters['start'] > 1499 or parameters['start'] < -1500): - raise InputError(parameters['start'], - "Start parameter exceeds hardware limits.") - if (parameters['stop'] > 1499 or parameters['stop'] < -1500): - raise InputError(parameters['stop'], - "Stop parameter exceeds hardware limits.") - if (parameters['slope'] > 2000 or parameters['slope'] < 1): - raise InputError(parameters['slope'], - "Slope parameter exceeds hardware limits.") - if parameters['start'] == parameters['stop']: - raise InputError(parameters['start'], - "Start cannot equal Stop.") - -def cv_test(params): - """Test CV parameters for sanity""" - test_parameters = ['clean_mV', 'dep_mV', 'clean_s', 'dep_s', 'start', - 'stop', 'slope', 'v1', 'v2', 'scans'] - parameters = {} - for i in params: - if i in test_parameters: - parameters[i] = int(params[i]) - - if (parameters['clean_mV'] > 1499 or - parameters['clean_mV'] < -1500): - raise InputError(parameters['clean_mV'], - "Clean potential exceeds hardware limits.") - if (parameters['dep_mV'] > 1499 or - parameters['dep_mV'] < -1500): - raise InputError(parameters['dep_mV'], - "Deposition potential exceeds hardware limits.") - if (parameters['clean_s'] < 0): - raise InputError(parameters['clean_s'], - "Clean time cannot be negative.") - if (parameters['dep_s'] < 0): - raise InputError(parameters['dep_s'], - "Deposition time cannot be negative.") - if (parameters['start'] > 1499 or parameters['start'] < -1500): - raise InputError(parameters['start'], - "Start parameter exceeds hardware limits.") - if (parameters['slope'] > 2000 or parameters['slope'] < 1): - raise InputError(parameters['slope'], - "Slope parameter exceeds hardware limits.") - if (parameters['v1'] > 1499 or parameters['v1'] < -1500): - raise InputError(parameters['v1'], - "Vertex 1 parameter exceeds hardware limits.") - if (parameters['v2'] > 1499 or parameters['v2'] < -1500): - raise InputError(parameters['v2'], - "Vertex 2 parameter exceeds hardware limits.") - if (parameters['scans'] < 1 or parameters['scans'] > 255): - raise InputError(parameters['scans'], - "Scans parameter outside limits.") - if parameters['v1'] == parameters['v2']: - raise InputError(parameters['v1'], - "Vertex 1 cannot equal Vertex 2.") - -def swv_test(params): - """Test SWV parameters for sanity""" - test_parameters = ['clean_mV', 'dep_mV', 'clean_s', 'dep_s', 'start', - 'stop', 'step', 'pulse', 'freq'] - parameters = {} - for i in params: - if i in test_parameters: - parameters[i] = int(params[i]) - - if params['cyclic_true'] : - if int(params['scans']) < 1: - raise InputError(params['scans'], - "Must have at least one scan.") - else: - params['scans'] = 0 - - # check parameters are within hardware limits (doesn't - # check if pulse will go out of bounds, but instrument - # checks this (I think)) - if (parameters['clean_mV'] > 1499 or - parameters['clean_mV'] < -1500): - raise InputError(parameters['clean_mV'], - "Clean potential exceeds hardware limits.") - if (parameters['dep_mV'] > 1499 or - parameters['dep_mV'] < -1500): - raise InputError(parameters['dep_mV'], - "Deposition potential exceeds hardware limits.") - if (parameters['clean_s'] < 0): - raise InputError(parameters['clean_s'], - "Clean time cannot be negative.") - if (parameters['dep_s'] < 0): - raise InputError(parameters['dep_s'], - "Deposition time cannot be negative.") - if (parameters['start'] > 1499 or parameters['start'] < -1500): - raise InputError(parameters['start'], - "Start parameter exceeds hardware limits.") - if (parameters['step'] > 200 or parameters['step'] < 1): - raise InputError(parameters['step'], - "Step height parameter exceeds hardware limits.") - if (parameters['stop'] > 1499 or parameters['stop'] < -1500): - raise InputError(parameters['stop'], - "Stop parameter exceeds hardware limits.") - if (parameters['pulse'] > 150 or parameters['pulse'] < 1): - raise InputError(parameters['pulse'], - "Pulse height parameter exceeds hardware limits.") - if (parameters['freq'] < 1 or parameters['freq'] > 1000): - raise InputError(parameters['freq'], - "Frequency parameter outside limits.") - if parameters['start'] == parameters['stop']: - raise InputError(parameters['start'], - "Start cannot equal Stop.") - -def dpv_test(params): - """Test DPV parameters for sanity""" - test_parameters = ['clean_mV', 'dep_mV', 'clean_s', 'dep_s', 'start', - 'stop', 'step', 'pulse', 'period', 'width'] - parameters = {} - for i in params: - if i in test_parameters: - parameters[i] = int(params[i]) - - if (parameters['clean_mV'] > 1499 or - parameters['clean_mV'] < -1500): - raise InputError(parameters['clean_mV'], - "Clean potential exceeds hardware limits.") - if (parameters['dep_mV'] > 1499 or - parameters['dep_mV'] < -1500): - raise InputError(parameters['dep_mV'], - "Deposition potential exceeds hardware limits.") - if (parameters['clean_s'] < 0): - raise InputError(parameters['clean_s'], - "Clean time cannot be negative.") - if (parameters['dep_s'] < 0): - raise InputError(parameters['dep_s'], - "Deposition time cannot be negative.") - if (parameters['start'] > 1499 or parameters['start'] < -1500): - raise InputError(parameters['start'], - "Start parameter exceeds hardware limits.") - if (parameters['step'] > 200 or parameters['step'] < 1): - raise InputError(parameters['step'], - "Step height parameter exceeds hardware limits.") - if (parameters['stop'] > 1499 or parameters['stop'] < -1500): - raise InputError(parameters['stop'], - "Stop parameter exceeds hardware limits.") - if (parameters['pulse'] > 150 or parameters['pulse'] < 1): - raise InputError(parameters['pulse'], - "Pulse height parameter exceeds hardware limits.") - if (parameters['period'] < 1 or parameters['period'] > 1000): - raise InputError(parameters['period'], - "Period parameter outside limits.") - if (parameters['width'] < 1 or parameters['width'] > 1000): - raise InputError(parameters['width'], - "Width parameter outside limits.") - if parameters['period'] <= parameters['width']: - raise InputError(parameters['width'], - "Width must be less than period.") - if parameters['start'] == parameters['stop']: - raise InputError(parameters['start'], - "Start cannot equal Stop.") - -def pd_test(parameters): - """Test PD parameters for sanity""" - - if (int(parameters['time']) <= 0): - raise InputError(parameters['time'], - "Time must be greater than zero.") - if (int(parameters['time']) > 65535): - raise InputError(parameters['time'], - "Time must fit in 16-bit counter.") - if (parameters['sync_true'] and parameters['shutter_true']): - if (float(parameters['sync_freq']) > 30 or - float(parameters['sync_freq']) <= 0): - raise InputError(parameters['sync_freq'], - "Frequency must be between 0 and 30 Hz.") - if (float(parameters['fft_start']) < 0 or - float(parameters['fft_start']) > float(parameters['time'])-1): - raise InputError(parameters['fft_start'], - "FFT must start between 0 and time-1.") - if float(parameters['fft_int']) < 0: - raise InputError( - parameters['fft_int'], - "Integral bandwidth must be greater than 0" - ) - -def pot_test(params): - """Test POT parameters for sanity""" - test_parameters = ['time'] - parameters = {} - for i in params: - if i in test_parameters: - parameters[i] = int(params[i]) - - if (int(parameters['time']) <= 0): - raise InputError(parameters['time'], - "Time must be greater than zero.") - if (int(parameters['time']) > 65535): - raise InputError(parameters['time'], - "Time must fit in 16-bit counter.") \ No newline at end of file diff --git a/dstat_interface/state.py b/dstat_interface/state.py deleted file mode 100644 index 7e3f1958894aab4a5482c65cca03cb5f3cdd1d93..0000000000000000000000000000000000000000 --- a/dstat_interface/state.py +++ /dev/null @@ -1,5 +0,0 @@ -from collections import OrderedDict - -settings = OrderedDict() -ser = None -dstat_version = None \ No newline at end of file diff --git a/images/k.pdf b/images/k.pdf deleted file mode 100644 index c831664d9292c8f42f4c5a20dc52a31e1d64fe25..0000000000000000000000000000000000000000 Binary files a/images/k.pdf and /dev/null differ diff --git a/pavement.py b/pavement.py index 0aea7f58afe84674e34958f65404241569de2066..fc1985513bd26b0dcc6e930acc67ab36cf3bfdda 100644 --- a/pavement.py +++ b/pavement.py @@ -1,7 +1,7 @@ import sys from paver.easy import task, needs, path, sh, cmdopts, options -from paver.setuputils import setup, install_distutils_tasks +from paver.setuputils import setup, install_distutils_tasks, find_packages from distutils.extension import Extension from distutils.dep_util import newer @@ -13,12 +13,13 @@ setup(name='dstat_interface', description='Interface software for DStat potentiostat.', keywords='', author='Michael D. M Dryden', - author_email='mdryden@chemutoronto.ca', + author_email='mdryden@chem.utoronto.ca', url='http://microfluidics.utoronto.ca/dstat', license='GPLv3', - packages=['dstat_interface', ], + packages=find_packages(), install_requires=['matplotlib', 'numpy', 'pyserial', 'pyzmq', - 'pyyaml','seaborn', 'zmq-plugin>=0.2.post2'], + 'pyyaml','seaborn', 'setuptools', + 'zmq-plugin>=0.2.post2'], # Install data listed in `MANIFEST.in` include_package_data=True) diff --git a/version.py b/version.py index 343f158f74594923d656e5be8ad57b09b3c56a1c..ae2f3d2232f717f9989c82b4efeb1344111aadd9 100644 --- a/version.py +++ b/version.py @@ -48,9 +48,11 @@ __all__ = ('getVersion') import re import subprocess import sys +import os.path +import inspect - -RELEASE_VERSION_FILE = 'RELEASE-VERSION' +RELEASE_VERSION_FILE = '{}/RELEASE-VERSION'.format( + os.path.dirname(os.path.abspath(inspect.stack()[0][1]))) # http://www.python.org/dev/peps/pep-0386/ _PEP386_SHORT_VERSION_RE = r'\d+(?:\.\d+)+(?:(?:[abc]|rc)\d+(?:\.\d+)*)?'