jetperch / pyjoulescope

Joulescope driver and utilities
https://www.joulescope.com
Apache License 2.0
37 stars 11 forks source link

Consider using context managers for scan operations #1

Closed markcampanelli closed 4 years ago

markcampanelli commented 4 years ago

Consider using a Pythonic context manager for scan operations.

Using the context manager pattern,

js = joulescope.scan_require_one()
js.open()
try:
    js.parameter_set('source', 'on')
    js.parameter_set('i_range', 'auto')
    data = js.read(contiguous_duration=0.25)
finally:
    js.close()

becomes the more streamlined

with joulescope.scan_require_one() as js:
    js.parameter_set('source', 'on')
    js.parameter_set('i_range', 'auto')
    data = js.read(contiguous_duration=0.25)

where the context manager handles opening and closing the device, doing so even when an exception is raised.

Optionally, one could also pass a configuration dict to joulescope.scan_require_one(), such as

with joulescope.scan_require_one(config={'source': 'on', 'i_range': 'auto'}) as js:
    data = js.read(contiguous_duration=0.25)
mliberty1 commented 4 years ago

I took a quick look at this, and adding a context manager is straightforward. Adding a config is also easy, but I would want it to take a config string with a mode rather than detailed parameter setttings. The parameters can vary from device to device (they don't currently), so the driver should abstract the details, at least at this level. How about:

:param config: The initial default configuration following device open.
    Choices are ['auto', 'off', 'ignore', None].
    * 'auto': enable the sensor and start collecting data with
      current sensor autoranging.
    * 'ignore' or None: Leave the device in its existing state.
    * 'off': Turn the sensor off and disable data collection.

Then the use case becomes:

import joulescope
with joulescope.scan_require_one(config='auto') as js:
    data = js.read(contiguous_duration=0.25)

I went ahead an implemented this in commit fa8f3ded. Let me know if you have feedback!

mliberty1 commented 4 years ago

Available in 0.5.0.