Skip to content

Commit

Permalink
Add stimulator thermometer agent (#695)
Browse files Browse the repository at this point in the history
* Adding stimulator thermometer agent.

* fix: revision accoriding to comments to PR

* fix: revision according to comments to PR
  • Loading branch information
dixilo authored Feb 20, 2025
1 parent e18b573 commit d75bb12
Show file tree
Hide file tree
Showing 6 changed files with 433 additions and 0 deletions.
81 changes: 81 additions & 0 deletions docs/agents/stimulator_thermometer.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
.. highlight:: rst

.. _stimulator_thermometer:

============================
Stimulator Thermometer Agent
============================
This is an OCS agent to acquire temperature data of the stimulator.

.. argparse::
:module: socs.agents.stimulator_thermometer.agent
:func: make_parser
:prog: agent.py

Configuration File Examples
---------------------------
Below are useful configurations examples for the relevant OCS files and for
running the agent.

OCS Site Config
```````````````
To configure the stimulator thermometer agent we need to add a StimThermometerAgent
block to our ocs configuration file. Here is an example configuration block
using all of the available arguments::

{'agent-class': 'StimThermometerAgent',
'instance-id': 'stim_thermo',
'arguments': [['--paths-spinode', [
'/sys/bus/spi/devices/spi3.0/',
'/sys/bus/spi/devices/spi3.1/',
'/sys/bus/spi/devices/spi3.2/',
'/sys/bus/spi/devices/spi3.3/']]]}

Description
-----------
The stimulator utilizes the MAX31856 and MAX31865 devices to read thermocouple and PT1000 sensors, respectively.
These devices are connected to the KR260 board within the stimulator readout box
via a Raspberry Pi-compatible pin header using a 4-wire SPI configuration.
The programmable logic (PL) of the KR260 is configured with an AXI SPI IP core
to facilitate SPI communication between the CPU and these devices.

The operating system on the KR260 CPU recognizes these devices through
a device tree overlay, as shown below::

&axi_quad_spi{
temperature-sensor@0 {
compatible = "maxim,max31856";
spi-max-frequency = <5000000>;
reg = <0x0>;
spi-cpha;
thermocouple-type = <0x05>;
};
};

The compatible property is set to the corresponding device to load the appropriate driver.
After applying the device tree overlay, the devices can be accessed via the Industrial I/O (IIO) subsystem.
Temperature readings can then be obtained by accessing the corresponding files, such as:
``/sys/bus/iio/devices/iio:device2/in_temp_raw``.

The agent reads these files and publishes the acquired data to the feed.

Agent API
---------

.. autoclass:: socs.agents.stimulator_thermometer.agent.StimThermometerAgent
:members:

Supporting APIs
---------------

.. autoclass:: socs.agents.stimulator_thermometer.drivers.StimThermoError
:members:

.. autoclass:: socs.agents.stimulator_thermometer.drivers.Iio
:members:

.. autoclass:: socs.agents.stimulator_thermometer.drivers.Max31856
:members:

.. autoclass:: socs.agents.stimulator_thermometer.drivers.Max31865
:members:
1 change: 1 addition & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ API Reference Full API documentation for core parts of the SOCS library.
agents/scpi_psu
agents/smurf_crate_monitor
agents/smurf_timing_card
agents/stimulator_thermometer
agents/suprsync
agents/synacc
agents/tektronix3021c
Expand Down
Empty file.
158 changes: 158 additions & 0 deletions socs/agents/stimulator_thermometer/agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
#!/usr/bin/env python3
"""OCS agent for thermometer board in the stimulator box
"""
import argparse
import os
import time

import txaio
from ocs import ocs_agent, site_config
from ocs.ocs_twisted import Pacemaker, TimeoutLock

from socs.agents.stimulator_thermometer.drivers import (Max31856,
from_spi_node_path)

LOCK_RELEASE_SEC = 1.
LOCK_RELEASE_TIMEOUT = 10


class StimThermometerAgent:
"""OCS agent class for stimulator thermometer.
Parameters
----------
paths_spinode : list of str or pathlib.Path
List of path to SPI nodes of temperature devices.
"""

def __init__(self, agent, paths_spinode):
self.active = True
self.agent = agent
self.log = agent.log
self.lock = TimeoutLock()
self.take_data = False

self.devices = [from_spi_node_path(path) for path in paths_spinode]

self.initialized = False

agg_params = {'frame_length': 60}
self.agent.register_feed('temperatures',
record=True,
agg_params=agg_params,
buffer_time=1)

@ocs_agent.param('sampling_frequency', type=float, default=1)
def acq(self, session, params):
"""acq()
**Process** - Fetch temperatures from the thermometer readers.
Parameters
----------
sampling_frequency : float, optional
Sampling frequency in Hz, default to 1 Hz.
Notes
-----
An example of the session data::
>>> response.session['data']
{"Channel_0": {"T":15.092116135817285},
"Channel_1": {"T":15.092116135817285},
"Channel_2": {"T":15.40625,"T_cj":16.796875},
"Channel_3": {"T":15.4921875,"T_cj":16.453125}},
...
"timestamp": 1738827824.2523127
}
"""
f_sample = params['sampling_frequency']
pace_maker = Pacemaker(f_sample)

with self.lock.acquire_timeout(timeout=0, job='acq') as acquired:
if not acquired:
self.log.warn(
f'Could not start acq because {self.lock.job} is already running')
return False, 'Could not acquire lock.'

self.take_data = True
session.data = {}
last_release = time.time()

while self.take_data:
if time.time() - last_release > LOCK_RELEASE_SEC:
last_release = time.time()
if not self.lock.release_and_acquire(timeout=LOCK_RELEASE_TIMEOUT):
print(f'Re-acquire failed: {self.lock.job}')
return False, 'Could not re-acquire lock.'

current_time = time.time()

for ch_num, dev in enumerate(self.devices):
data = {'timestamp': current_time, 'block_name': f'temp_{ch_num}', 'data': {}}
chan_string = f'Channel_{ch_num}'

temp = dev.get_temp()
data['data'][chan_string + '_T'] = temp
self.agent.publish_to_feed('temperatures', data)

if isinstance(dev, Max31856):
cjtemp = dev.get_temp_ambient()
data['data'][chan_string + '_T_cj'] = cjtemp
field_dict = {chan_string: {'T': temp, 'T_cj': cjtemp}}
else:
field_dict = {chan_string: {'T': temp}}

session.data.update(field_dict)

session.data.update({'timestamp': current_time})
pace_maker.sleep()

self.agent.feeds['temperatures'].flush_buffer()

return True, 'Acquisition exited cleanly.'

def _stop_acq(self, session, params=None):
if self.take_data:
self.take_data = False
return True, 'requested to stop taking data.'

return False, 'acq is not currently running.'


def make_parser(parser=None):
if parser is None:
parser = argparse.ArgumentParser()

pgroup = parser.add_argument_group('Agent Options')
pgroup.add_argument('--paths-spinode', nargs='*', type=str, required=True,
help="Path to the spi nodes.")

return parser


def main(args=None):
"""Boot OCS agent"""
txaio.start_logging(level=os.environ.get('LOGLEVEL', 'info'))

parser = make_parser()
args = site_config.parse_args('StimThermometerAgent',
parser=parser,
args=args)

agent_inst, runner = ocs_agent.init_site_agent(args)
stim_max_agent = StimThermometerAgent(agent_inst, args.paths_spinode)

agent_inst.register_process(
'acq',
stim_max_agent.acq,
stim_max_agent._stop_acq,
startup=True
)

runner.run(agent_inst, auto_reconnect=True)


if __name__ == '__main__':
main()
Loading

0 comments on commit d75bb12

Please sign in to comment.