<a id="api-device"></a>

# Device

### *class* joulescope.v1.device.Device(driver, device_path)

#### *property* buffer_duration

The stream buffer duration.

#### close(timeout=None)

Close this device and release resources.

* **Parameters:**
  **timeout** – The timeout in seconds.  None uses the default timeout.

#### *property* driver

The underlying pyjoulescope_driver.Driver instance.

#### extio_status()

Read the EXTIO GPI value.

* **Returns:**
  A dict containing the extio status.  Each key is the status
  item name.  The value is itself a dict with the following keys:
  * name: The status name, which is the same as the top-level key.
  * value: The actual value
  * units: The units, if applicable.
  * format: The recommended formatting string (optional).

The most interesting key is “gpi_value” which returns the present
general purpose input signal values.  The remaining keys simply
copy parameter settings for convenience.

#### *property* firmware

The running firmware image, which is one of:

* ‘app’: the application firmware.
* ‘bootloader’: the JS110 or JS220 bootloader, which the device
  path shows with the “&” model prefix.
* ‘recovery’: the JS320 recovery image.  The driver does not yet
  report it, so a JS320 is always ‘app’.

#### info()

Get the device information structure.

* **Returns:**
  The device information structure.

#### *property* input_sampling_frequency

The original input sampling frequency.

#### *property* is_streaming

Check if the device is streaming.

* **Returns:**
  True if streaming.  False if not streaming.

#### *property* model

The lowercase model, such as “js220”.

#### open(event_callback_fn=None, mode=None, timeout=None)

Open this device.

* **Parameters:**
  * **event_callback_fn** – The function(event, message) to call on
    asynchronous events, mostly to allow robust handling of device
    errors.  “event” is one of the `DeviceEvent` values,
    and the message is a more detailed description of the event.
  * **mode** – The open mode which is one of:
    \* ‘defaults’: Reconfigure the device for default operation.
    \* ‘restore’: Update our state with the current device state.
    \* ‘raw’: Open the device in raw mode for development or firmware update.
    \* None: equivalent to ‘defaults’.
  * **timeout** – The timeout in seconds.  None uses the default timeout.

#### *property* output_sampling_frequency

The output sampling frequency.

#### parameter_get(name, dtype=None)

Get a parameter value.

* **Parameters:**
  * **name** – The parameter name.
  * **dtype** – The data type for the parameter.  None (default)
    attempts to convert the value to the enum string.
    ‘actual’ returns the value in its actual type used by the driver.
* **Raises:**
  **KeyError** – if name not found.

#### parameter_set(name, value)

Set a parameter value.

* **Parameters:**
  * **name** – The parameter name
  * **value** – The new parameter value
* **Raises:**
  * **KeyError** – if name not found.
  * **ValueError** – if value is not allowed

#### parameters(name=None)

Get the list of `joulescope.parameter.Parameter` instances.

* **Parameters:**
  **name** – The optional name of the parameter to retrieve.
  None (default) returns a list of all parameters.
* **Returns:**
  The list of all parameters.  If name is provided, then just
  return that single parameters.

The parameter options reflect the values supported by this device.
For backwards compatibility, [`parameter_set()`](#joulescope.v1.device.Device.parameter_set) also accepts the
legacy values of other Joulescope models where possible.

#### publish(topic, value, timeout=None)

Publish to the underlying joulescope_driver instance.

* **Parameters:**
  * **topic** – The publish topic.
  * **value** – The publish value.
  * **timeout** – The timeout in float seconds to wait for this operation
    to complete.  None waits the default amount.
    0 does not wait and subscription will occur asynchronously.

#### query(topic, timeout=None)

Query the underlying joulescope_driver instance.

* **Parameters:**
  * **topic** – The publish topic to query.
  * **timeout** – The timeout in float seconds to wait for this operation
    to complete.  None waits the default amount.
    0 does not wait and subscription will occur asynchronously.
* **Returns:**
  The value associated with topic.

#### read(duration=None, contiguous_duration=None, out_format=None, fields=None)

Read data from the device.

* **Parameters:**
  * **duration** – The duration in seconds for the capture.
    The duration must fit within the stream_buffer.
  * **contiguous_duration** – The contiguous duration in seconds for
    the capture.  As opposed to duration, this ensures that the
    duration has no missing samples.  Missing samples usually
    occur when the device first starts.
    The duration must fit within the stream_buffer.
  * **out_format** – 

    The output format which is one of:
    * calibrated: The Nx2 np.ndarray(float32) with columns current and voltage.
    * samples_get: The StreamBuffer samples get format.  Use the fields
      parameter to optionally specify the signals to include.
    * None: equivalent to ‘calibrated’.
  * **fields** – The fields for samples_get when out_format=samples_get.

If streaming was already in progress, it will be restarted.
If neither duration or contiguous duration is specified, the capture
will only be stopped by callbacks registered through
[`stream_process_register()`](#joulescope.v1.device.Device.stream_process_register).

#### *property* sampling_frequency

The output sampling frequency.

#### start(stop_fn=None, duration=None, contiguous_duration=None)

Start data streaming.

* **Parameters:**
  * **stop_fn** – The function(event, message) called when the device stops.
    The device can stop “automatically” on errors.
    Call [`stop()`](#joulescope.v1.device.Device.stop) to stop from the caller.
    This function will be called from the USB processing thread.
    Any calls back into self MUST BE resynchronized.
  * **duration** – The duration in seconds for the capture.
  * **contiguous_duration** – The contiguous duration in seconds for
    the capture.  As opposed to duration, this ensures that the
    duration has no missing samples.  Missing samples usually
    occur when the device first starts.

If streaming was already in progress, it will be restarted.

#### statistics_accumulators_clear()

Clear the charge and energy accumulators.

#### *property* statistics_callback

Get the first registered statistics callback.

#### statistics_callback_register(cbk, source=None)

Register a statistics callback.

* **Parameters:**
  * **cbk** – The callable(data) where data is a statistics data
    structure.  See the [statistics documentation](https://docs.joulescope.com/en/software/pyjoulescope/api/statistics.html)
    for details on the data format.
    This function will be called from the USB processing thread.
    Any calls back into self MUST BE resynchronized.
    See [`statistics_get()`](#joulescope.v1.device.Device.statistics_get) to receive statistics on the
    caller’s thread instead.
  * **source** – 

    The statistics source, which is one of:
    * None (default): the model and scan config default,
      see [`statistics_source`](#joulescope.v1.device.Device.statistics_source).
    * ’sensor’: computed on the instrument.
    * ’host’: computed by the host driver from the full-rate
      sample stream, so it requires streaming.  ‘stream_buffer’
      is the legacy v0 name.

    The JS110 supports both sources, even at the same time.
    The JS220 and JS320 only compute statistics on the
    instrument: they ignore ‘host’, with a DeprecationWarning.
* **Raises:**
  **ValueError** – If source is not a statistics source name.

WARNING: calling [`statistics_callback()`](#joulescope.v1.device.Device.statistics_callback) after calling this method
may result in unusual behavior.  Do not mix these API calls.

#### statistics_callback_unregister(cbk, source=None)

Unregister a statistics callback.

* **Parameters:**
  * **cbk** – The callback previously provided to
    [`statistics_callback_register()`](#joulescope.v1.device.Device.statistics_callback_register).
  * **source** – The source provided to
    [`statistics_callback_register()`](#joulescope.v1.device.Device.statistics_callback_register).  None (default)
    searches all sources.

#### statistics_get(timeout=None)

Get the next statistics value on the caller’s thread.

* **Parameters:**
  **timeout** – The maximum time to wait in float seconds.
  None (default) waits 2 seconds.
* **Returns:**
  The statistics data structure, the same as provided to
  [`statistics_callback_register()`](#joulescope.v1.device.Device.statistics_callback_register) callbacks.
* **Raises:**
  * **RuntimeError** – If the device is not open.
  * **TimeoutError** – If no statistics value arrives in time.

The first call starts buffering statistics values until
[`close()`](#joulescope.v1.device.Device.close), so consecutive calls return consecutive values
without gaps.  The buffer holds the 100 most recent values,
which is 50 seconds at the default reduction_frequency of 2 Hz.

#### statistics_iter(count=None, timeout=None)

Iterate over statistics values on the caller’s thread.

* **Parameters:**
  * **count** – The number of statistics values.  None (default)
    iterates until the device closes or the caller stops.
  * **timeout** – The maximum time to wait for each value in
    float seconds.  None (default) waits 2 seconds.
* **Returns:**
  The iterator over statistics data structures.
* **Raises:**
  * **RuntimeError** – If the device is not open.
  * **TimeoutError** – If a statistics value does not arrive in time.

Example:

```default
for stats in device.statistics_iter(count=10):
    print(stats['signals']['current']['µ']['value'])
```

See [`statistics_get()`](#joulescope.v1.device.Device.statistics_get).

#### *property* statistics_source

The default statistics source, which is one of:

* ‘sensor’: computed on the instrument.
* ‘host’: computed by the host driver from the full-rate
  sample stream.

The JS220 and JS320 always use ‘sensor’.  The JS110 uses ‘sensor’
when scanned with config=’off’, and ‘host’ otherwise.
[`statistics_callback_register()`](#joulescope.v1.device.Device.statistics_callback_register) selects the source for each
callback.

#### status()

Get the current device status.

* **Returns:**
  A dict containing constant status information.

Deprecated: the v1 backend has no status to report, so this
always returns the same values.

#### stop()

Stop data streaming.

* **Returns:**
  True if stopped.  False if was already stopped.

This method is always safe to call, even after the device has been
stopped or removed.

#### stream_process_register(obj)

Register a stream process object.

* **Parameters:**
  **obj** – The instance compatible with `StreamProcessApi`.
  The instance must remain valid until its [`close()`](#joulescope.v1.device.Device.close) is
  called.

Call [`stream_process_unregister()`](#joulescope.v1.device.Device.stream_process_unregister) to disconnect the instance.

#### stream_process_unregister(obj)

Unregister a stream process object.

* **Parameters:**
  **obj** – The instance compatible with `StreamProcessApi` that was
  previously registered using [`stream_process_register()`](#joulescope.v1.device.Device.stream_process_register).

#### subscribe(topic, flags, fn, timeout=None)

Subscribe to receive topic updates.

* **Parameters:**
  * **self** – The driver instance.
  * **topic** – Subscribe to this topic string.
  * **flags** – 

    The flags or list of flags for this subscription.
    The flags can be int32 jsdrv_subscribe_flag_e or string
    mnemonics, which are:
    - pub: Subscribe to normal values
    - pub_retain: Subscribe to normal values and immediately publish
      all matching retained values.  With timeout, this function does
      not return successfully until all retained values have been
      published.
    - metadata_req: Subscribe to metadata requests (not normally useful).
    - metadata_rsp: Subscribe to metadata updates.
    - metadata_rsp_retain: Subscribe to metadata updates and immediately
      publish all matching retained metadata values.
    - query_req: Subscribe to all query requests (not normally useful).
    - query_rsp: Subscribe to all query responses.
    - return_code: Subscribe to all return code responses.
  * **fn** – The function to call on each publish.  Note that python
    dynamically constructs bound methods.  To unsubscribe a method,
    provide the exact same bound method instance to unsubscribe.
    This constrain usually means that the caller needs to hold onto
    the instance.method value passed to this function.
  * **timeout** – The timeout in float seconds to wait for this operation
    to complete.  None waits the default amount.
    0 does not wait and subscription will occur asynchronously.
* **Raises:**
  **RuntimeError** – on subscribe failure.

#### unsubscribe(topic, fn, timeout=None)

Unsubscribe a callback to a topic.

* **Parameters:**
  * **topic** – Unsubscribe from this topic string.
  * **fn** – The callback function to unsubscribe.
  * **timeout** – The timeout in float seconds to wait for this operation
    to complete.  None waits the default amount.
    0 does not wait and subscription will occur asynchronously.

#### unsubscribe_all(fn, timeout=None)

Unsubscribe a callback from all topics.

* **Parameters:**
  * **fn** – The callback function to unsubscribe.
  * **timeout** – The timeout in float seconds to wait for this operation
    to complete.  None waits the default amount.
    0 does not wait and subscription will occur asynchronously.

#### view_factory()

Construct a new View into the device’s data.

* **Returns:**
  A View-compatible instance.
