Exemplo n.º 1
0
 def _create_records(self, pvs):
     start = time.time()
     for pv in pvs:
         builder.SetDeviceName(pv)
         builder.aIn('I', initial_value=0.1)
         builder.aOut('SETI', initial_value=0.1)
     print("    Time per pv: {0}".format((time.time() - start) / len(pvs)))
Exemplo n.º 2
0
    def validate_ioc_test_func(
            self,
            device_name,
            record_func,
            child_conn,
            validate_pass: bool):
        """Start the IOC with the specified validate method"""

        builder.SetDeviceName(device_name)

        kwarg = {}
        if record_func in [builder.WaveformIn, builder.WaveformOut]:
            kwarg = {"length": WAVEFORM_LENGTH}  # Must specify when no value

        kwarg["validate"] = (
            self.validate_always_pass
            if validate_pass
            else self.validate_always_fail
        )

        record_func("VALIDATE-RECORD", **kwarg)

        dispatcher = asyncio_dispatcher.AsyncioDispatcher()
        builder.LoadDatabase()
        softioc.iocInit(dispatcher)

        child_conn.send("R")

        # Keep process alive while main thread runs CAGET
        if child_conn.poll(TIMEOUT):
            val = child_conn.recv()
            assert val == "D", "Did not receive expected Done character"
Exemplo n.º 3
0
    def setUp(self):
        print self.__doc__
        builder.SetDeviceName(self.__doc__.split(" ")[0])
        self.controller = PIController.PIController(host="127.0.0.1", port=50000, debug=True)
        self.scan = PIStepScan.PIStepScan(self.controller)

        random.seed()
Exemplo n.º 4
0
 def __init__(self, machine, name):
     builder.SetDeviceName(name)
     self.com = ModbusClient(host=machine, port=4000, auto_open=True)  #4000
     self.com.mode(constants.MODBUS_RTU)
     stat = self.com.open()
     self.pv_stat = builder.aIn("stat")
     self.pv_stat.PREC = 1
     self.pv_stat.LOPR = 0
     self.pv_stat.HOPR = 100
     self.pv_temp = builder.aIn("temp")
     self.pv_temp.PREC = 1
     self.pv_temp.LOPR = 0
     self.pv_temp.HOPR = 100
     self.pv_humi = builder.aIn("humidity")
     self.pv_humi.PREC = 1
     self.pv_humi.LOPR = 0
     self.pv_humi.HOPR = 100
     self.pv_humi.HSV = "MINOR"
     self.pv_humi.HHSV = "MAJOR"
     self.pv_humi.HIGH = 45
     self.pv_humi.HIHI = 50
     self.pv_flow = builder.aIn("flow")
     self.pv_flow.PREC = 0
     self.pv_flow.LOPR = 0
     self.pv_flow.HOPR = 600
     self.pv_flow.LOLO = 250
     self.pv_flow.LOW = 300
     self.pv_flow.HIGH = 480
     self.pv_flow.HIHI = 520
     self.pv_flow.LSV = "MINOR"
     self.pv_flow.LLSV = "MAJOR"
     self.pv_flow.HSV = "MINOR"
     self.pv_flow.HHSV = "MAJOR"
     self.stat_pv = builder.boolIn("status",
                                   ZNAM="off",
                                   ONAM="on",
                                   DESC=name)
     self.stat_pv.ZSV = "MAJOR"
     self.pv_on = builder.boolOut("on",
                                  ZNAM="0",
                                  ONAM="1",
                                  HIGH=0.1,
                                  on_update=self.turnOn)
     self.pv_off = builder.boolOut("off",
                                   ZNAM="0",
                                   ONAM="1",
                                   HIGH=0.1,
                                   on_update=self.turnOff)
     self.busy = False
     self.pv_act = builder.boolOut("activity", ZNAM="0", ONAM="1", HIGH=1)
     self.pv_was_on = builder.boolOut("was_on",
                                      ZNAM="0",
                                      ONAM="1",
                                      HIGH=1.5)
     self.pv_was_off = builder.boolOut("was_off",
                                       ZNAM="0",
                                       ONAM="1",
                                       HIGH=1.5)
     self.id_temp = 0
     self.id_stat = 1
Exemplo n.º 5
0
    def _create_feedback_records(self, feedback_csv):
        """Create all the feedback records from the .csv file at the location
        passed, see create_csv.py for more information; records for two edge
        cases are also created.

        Args:
            feedback_csv (string): The filepath to the .csv file to load the
                                    records in accordance with.
        """
        csv_reader = csv.DictReader(open(feedback_csv))
        for line in csv_reader:
            prefix, suffix = line["pv"].split(":", 1)
            builder.SetDeviceName(prefix)
            in_record = builder.aIn(suffix,
                                    initial_value=int(line["value"]),
                                    MDEL="-1")
            self._feedback_records[(int(line["index"]),
                                    line["field"])] = in_record
        # Special case: BPM ID for the x axis of beam position plot, since we
        # cannot currently create Waveform records via CSV.
        bpm_ids = [
            int(pv[2:4]) + 0.1 * int(pv[14:16])
            for pv in self.lattice.get_element_pv_names("BPM", "x", pytac.RB)
        ]
        builder.SetDeviceName("SR-DI-EBPM-01")
        bpm_id_record = builder.Waveform("BPMID",
                                         NELM=len(bpm_ids),
                                         initial_value=bpm_ids)
        self._feedback_records[(0, "bpm_id")] = bpm_id_record
        # Special case: EMIT STATUS for the vertical emittance feedback, since
        # we cannot currently create mbbIn records via CSV.
        builder.SetDeviceName("SR-DI-EMIT-01")
        emit_status_record = builder.mbbIn("STATUS",
                                           initial_value=0,
                                           ZRVL=0,
                                           ZRST="Successful",
                                           PINI="YES")
        self._feedback_records[(0, "emittance_status")] = emit_status_record
Exemplo n.º 6
0
    def on_update_test_func(
        self, device_name, record_func, conn, always_update
    ):

        builder.SetDeviceName(device_name)

        li = builder.longIn("ON-UPDATE-COUNTER-RECORD", initial_value=0)

        def on_update_func(new_val):
            """Increments li record each time main out record receives caput"""
            li.set(li.get() + 1)

        kwarg = {}
        if record_func is builder.WaveformOut:
            kwarg = {"length": WAVEFORM_LENGTH}  # Must specify when no value

        record_func(
            "ON-UPDATE-RECORD",
            on_update=on_update_func,
            always_update=always_update,
            **kwarg)

        def on_update_done(_):
            conn.send("C")  # "Complete"
        # Put to the action record after we've done all other Puts, so we know
        # all the callbacks have finished processing
        builder.Action("ON-UPDATE-DONE", on_update=on_update_done)

        dispatcher = asyncio_dispatcher.AsyncioDispatcher()
        builder.LoadDatabase()
        softioc.iocInit(dispatcher)

        conn.send("R")  # "Ready"

        log("CHILD: Sent R over Connection to Parent")

        # Keep process alive while main thread runs CAGET
        if conn.poll(TIMEOUT):
            val = conn.recv()
            assert val == "D", "Did not receive expected Done character"

        log("CHILD: Received exit command, child exiting")
Exemplo n.º 7
0
    def __init__(self):

        #prefix for the PVs
        builder.SetDeviceName("iocmon")

        #open the configuration
        csv = pd.read_csv("config.csv")

        #all slow controls machines
        self.machines = {}

        #load machines and iocs from the configuration
        for i in csv.iterrows():
            host = i[1]["host"].strip()

            if host not in self.machines:
                sleep(0.3)
                self.machines[host] = machine(i[1])

            self.machines[host].add_ioc(i[1])
Exemplo n.º 8
0
def main():
    if "-v" in sys.argv:
        logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)
        sys.argv.remove("-v")
    else:
        logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)

    # Determine the ring mode
    if sys.argv[1:]:
        ring_mode = sys.argv[1]
    else:
        try:
            ring_mode = str(os.environ["RINGMODE"])
        except KeyError:
            try:
                value = caget("SR-CS-RING-01:MODE", format=2)
                ring_mode = value.enums[int(value)]
            except ca_nothing:
                ring_mode = "DIAD"

    # Create PVs.
    server = atip_server.ATIPServer(
        ring_mode,
        DATADIR / "limits.csv",
        DATADIR / "feedback.csv",
        DATADIR / "mirrored.csv",
        DATADIR / "tunefb.csv",
    )

    # Add special case out record for SOFB to write to.
    builder.SetDeviceName("CS-CS-MSTAT-01")
    builder.aOut("FBHEART", initial_value=10)

    # Start the IOC.
    builder.LoadDatabase()
    softioc.iocInit()
    server.monitor_mirrored_pvs()
    server.setup_tune_feedback()

    softioc.interactive_ioc(globals())
Exemplo n.º 9
0
    def blocking_test_func(self, device_name, conn):

        builder.SetDeviceName(device_name)

        count_rec = builder.longIn("BLOCKING-COUNTER", initial_value=0)

        async def blocking_update_func(new_val):
            """A function that will block for some time"""
            log("CHILD: blocking_update_func starting")
            await asyncio.sleep(0.5)
            log("CHILD: Finished sleep!")
            completed_count = count_rec.get() + 1
            count_rec.set(completed_count)
            log(
                "CHILD: blocking_update_func finished, completed ",
                completed_count
            )

        builder.longOut(
            "BLOCKING-REC",
            on_update=blocking_update_func,
            always_update=True,
            blocking=True
        )


        dispatcher = asyncio_dispatcher.AsyncioDispatcher()
        builder.LoadDatabase()
        softioc.iocInit(dispatcher)

        conn.send("R")  # "Ready"

        log("CHILD: Sent R over Connection to Parent")

        # Keep process alive while main thread runs CAGET
        if conn.poll(TIMEOUT):
            val = conn.recv()
            assert val == "D", "Did not receive expected Done character"

        log("CHILD: Received exit command, child exiting")
import sys
import os

from pkg_resources import require
require('cothread==2.13')
require('numpy==1.11.1')
require('epicsdbbuilder==1.0')

from softioc import softioc, builder
from epicsdbbuilder import records  #, MS, CP, ImportRecord
"""#builder.SetDeviceName('IOC-TEST')
builder.SetDeviceName('SFX44126-PY-IOC-01')
"""

builder.SetDeviceName('BL03I-EA-XBPM-01')

x1sigcurr = builder.aOut('SumAll:MeanValue_RBV', initial_value=30e-09)
x1r = builder.mbbOut('DRV:Range', initial_value=0)
x1psy = builder.mbbOut('DRV:PositionScaleY', initial_value=1)
x1psx = builder.mbbOut('DRV:PositionScaleX', initial_value=1)

builder.SetDeviceName('BL03I-EA-XBPM-02')

x2sigcurr = builder.aOut('SumAll:MeanValue_RBV', initial_value=1.02991e-06)
x2r = builder.mbbOut('DRV:Range', initial_value=0)
x2psy = builder.mbbOut('DRV:PositionScaleY', initial_value=1)
x2psx = builder.mbbOut('DRV:PositionScaleX', initial_value=1)

builder.SetDeviceName('BL03I-MO-DCM-01')

A = 1
Exemplo n.º 11
0
from multiprocessing.connection import Client
import sys

from softioc import softioc, builder, pvlog

from conftest import ADDRESS, select_and_recv

if __name__ == "__main__":
    with Client(ADDRESS) as conn:
        import cothread

        # Being run as an IOC, so parse args and set prefix
        parser = ArgumentParser()
        parser.add_argument('prefix', help="The PV prefix for the records")
        parsed_args = parser.parse_args()
        builder.SetDeviceName(parsed_args.prefix)

        import sim_records

        # Run the IOC
        builder.LoadDatabase()
        softioc.iocInit()

        conn.send("R")  # "Ready"

        select_and_recv(conn, "D")  # "Done"
        # Attempt to ensure all buffers flushed - C code (from `import pvlog`)
        # may not be affected by these calls...
        sys.stdout.flush()
        sys.stderr.flush()
Exemplo n.º 12
0
from softioc import builder
from mainframe import mainframe
import time
import threading

from datetime import datetime

builder.SetDeviceName("tpc_grid_leak")

#create mainframe object, set telnet port
mf = mainframe(9038)


#_____________________________________________________________________________
def do_monit():
    while True:
        time.sleep(3)
        #print "before: ", datetime.now()
        mf.do_read()
        #print "after: ", datetime.now()


#_____________________________________________________________________________
def loop_monit():
    #initialize lecroy mainframe from config file
    mf.init_config()
    #periodically read measured current and voltage
    tid = threading.Thread(target=do_monit)
    tid.start()
Exemplo n.º 13
0
def run_ioc(record_configurations: list, conn, set_enum, get_enum):
    """Creates a record and starts the IOC. `initial_value` will be set on
    the record at different times based on the `set_enum` parameter."""

    builder.SetDeviceName(DEVICE_NAME)

    records: List[RecordWrapper] = []

    # Create records from the given list
    for configuration in record_configurations:
        kwarg = {}

        (
            record_name,
            creation_func,
            initial_value,
            expected_value,
            expected_type,
        ) = configuration

        if set_enum == SetValueEnum.INITIAL_VALUE:
            kwarg["initial_value"] = initial_value
        elif creation_func in [builder.WaveformIn, builder.WaveformOut]:
            kwarg["length"] = WAVEFORM_LENGTH  # Must specify when no value
            # Related to this issue:
            # https://github.com/dls-controls/pythonSoftIOC/issues/37

        out_rec = creation_func(record_name, **kwarg)

        if set_enum == SetValueEnum.SET_BEFORE_INIT:
            out_rec.set(initial_value)

        records.append(out_rec)

    dispatcher = asyncio_dispatcher.AsyncioDispatcher()
    builder.LoadDatabase()
    softioc.iocInit(dispatcher)
    conn.send("R")  # "Ready"

    # Record list and record config list should always be in line
    for record, configuration in zip(records, record_configurations):
        (
            record_name,
            creation_func,
            initial_value,
            expected_value,
            expected_type,
        ) = configuration

        if set_enum == SetValueEnum.SET_AFTER_INIT:
            record.set(initial_value)

    for record in records:
        if get_enum == GetValueEnum.GET:
            conn.send(record.get())
            # Some tests do a caput and require another .get()
            if set_enum == SetValueEnum.CAPUT:
                if conn.poll(TIMEOUT):
                    val = conn.recv()
                    if val == "G":
                        conn.send(record.get())
                    else:
                        pytest.fail(f"Received unexpected character {val}")

    # Keep process alive while main thread works.
    # This is most applicable to CAGET tests.
    while (True):
        if conn.poll(TIMEOUT):
            val = conn.recv()
            if val == "D":  # "Done"
                break
Exemplo n.º 14
0
import sys
from pkg_resources import require
import logging

require('dls_feedback_manager==1.2')
require('cothread==2.14')
require('numpy==1.11.1')
require('epicsdbbuilder==1.2')

from softioc import softioc, builder

formatter = '%(asctime)s, %(funcName)s, %(levelname)s, %(message)s'
logging.basicConfig(format=formatter, level=logging.INFO)

## Creates name for feedback PVs created during run.
builder.SetDeviceName('BL24I-EA-FDBK-01')

import XBPM_range_manager, XBPM_feedback_manager, XBPM_pid_params

xbpm1_pid_params_list = [
    XBPM_pid_params.XBPMPIDParamsClass(KP=-0.0050,
                                       KI=0.000,
                                       KD=0.000,
                                       feedback="FPITCH:FB1",
                                       position="FB1"),  # pitch
    XBPM_pid_params.XBPMPIDParamsClass(KP=-0.0100,
                                       KI=0.000,
                                       KD=0.000,
                                       feedback="FPITCH:FB2",
                                       position="FB2")
]  # roll
Exemplo n.º 15
0
import time
import threading
import numpy as np
import ctypes
from Channel import Channel
from softioc import builder, softioc

builder.SetDeviceName('sTGC')


class STGC():
    def __init__(self, ip):
        self.ip = ip
        self.boards = [3, 7]
        self.channels = [0]
        self.lib = ctypes.cdll.LoadLibrary(
            '/star/u/sysuser/users/lukas/CAENHVWrapper-5.82/lib/x64/libcaenhvwrapper.so.5.82'
        )
        self.handle = ctypes.c_int(0)
        self.result0 = self.lib.CAENHV_InitSystem(0, 0, self.ip, "admin",
                                                  "admin",
                                                  ctypes.byref(self.handle))
        print "sTGC is using {0} boards".format(len(self.boards))
        #### Process Variables ####
        self.pv = []
        self.chanlist = []
        for i in range(0, len(self.boards)):
            base_PV = "{0}:Temp".format(self.boards[i])
            self.pv.append(builder.aIn(base_PV))
            for j in range(0, len(self.channels)):
                self.chanlist.append(
Exemplo n.º 16
0
from softioc import builder, softioc
from softioc.builder import records

builder.SetDeviceName("XX-XX-XX-01")

py_record = builder.aOut("VAL1", initial_value=5, on_update=print)
soft_record = records.ao("VAL2", VAL=10)

calc = records.calc("CALC", CALC="A*B", INPA=builder.CP(py_record), B=1)

soft_record.OUT = builder.PP(calc.B)

builder.LoadDatabase()
softioc.iocInit()

softioc.interactive_ioc(globals())
Exemplo n.º 17
0
import time
import pandas as pd
import threading
from datetime import datetime

from Channel import Channel
from softioc import builder, softioc, alarm
builder.SetDeviceName('tpc_grid_leak')
import subprocess


class TPC():
    def __init__(self, ip):
        self.readData = builder.boolOut('readData',
                                        on_update=self.place_voltages,
                                        HIGH=0.1)
        self.on = builder.boolOut('on', on_update=self.turnOn, HIGH=0.1)
        self.off = builder.boolOut('off', on_update=self.turnOff, HIGH=0.1)
        self.avrgVolt = builder.aIn('avrgVolt')
        self.avrgTemp = builder.longIn('avrgTemp')
        self.avrgVoltInner = builder.aIn('avrgVoltInner')
        self.avrgVoltOuter = builder.aIn('avrgVoltOuter')
        self.marker = builder.longIn('marker')
        self.setVoltInner_pv = builder.aOut("setVoltInner",
                                            on_update=self.setVoltInner)
        self.setVoltOuter_pv = builder.aOut("setVoltOuter",
                                            on_update=self.setVoltOuter)
        self.write_voltages_pv = builder.boolOut("write_voltages",
                                                 on_update=self.write_voltages,
                                                 HIGH=0.1)
        self.datacsv = "data.csv"
Exemplo n.º 18
0
# Import the basic framework components.
from softioc import softioc, builder, asyncio_dispatcher
import asyncio

# Create an asyncio dispatcher, the event loop is now running
dispatcher = asyncio_dispatcher.AsyncioDispatcher()

# Set the record prefix
builder.SetDeviceName("MY-DEVICE-PREFIX")

# Create some records
ai = builder.aIn('AI', initial_value=5)
ao = builder.aOut('AO', initial_value=12.45, always_update=True,
                  on_update=lambda v: ai.set(v))

# Boilerplate get the IOC started
builder.LoadDatabase()
softioc.iocInit(dispatcher)

# Start processes required to be run after iocInit
async def update():
    while True:
        ai.set(ai.get() + 1)
        await asyncio.sleep(1)

asyncio.run_coroutine_threadsafe(update(), dispatcher.loop)

# Finally leave the IOC running with an interactive shell.
softioc.interactive_ioc(globals())
Exemplo n.º 19
0
import time
import threading
import numpy as np
import ctypes
from Channel import Channel
from softioc import builder, softioc
builder.SetDeviceName('MTD:HV')


class MTD():
    def __init__(self, ip):
        self.ip = ip
        self.boards = [1, 3, 5, 7]
        self.channels = [0, 1, 2, 3, 4, 5]
        self.lib = ctypes.cdll.LoadLibrary(
            '/home/mtd/CAENHVWrapper-5.82/lib/x64/libcaenhvwrapper.so.5.82')
        self.handle = ctypes.c_int(0)
        #self.result0 = self.lib.CAENHV_InitSystem(2, 0, self.ip, "admin", "admin", ctypes.byref(self.handle)) # for CAEN SY4527
        self.result0 = self.lib.CAENHV_InitSystem(
            0, 0, self.ip, "admin", "admin",
            ctypes.byref(self.handle))  # for CAEN SY1527
        print "MTD is using {0} boards".format(len(self.boards))
        #### Read INITIAL values for self.on and self.standby ####
        try:
            self.values = {}
            with open("init_val.txt", "r") as f:
                for line in f:
                    variable, value = line.split(",")
                    self.values[variable] = value.strip("\n")
        except:
            print "!!! init_val.txt not found, setting default values !!!"
Exemplo n.º 20
0
    def _create_records(self, limits_csv):
        """Create all the standard records from both lattice and element Pytac
        fields. Several assumptions have been made for simplicity and
        efficiency, these are:
            - That bend elements all share a single PV, and are the only
               element family to do so.
            - That every field that has an out type record (SP) will also have
               an in type record (RB).
            - That all lattice fields are never setpoint and so only in records
               need to be created for them.

        Args:
            limits_csv (string): The filepath to the .csv file from which to
                                    load the pv limits.
        """
        limits_dict = {}
        if limits_csv is not None:
            csv_reader = csv.DictReader(open(limits_csv))
            for line in csv_reader:
                limits_dict[line["pv"]] = (
                    float(line["upper"]),
                    float(line["lower"]),
                    int(line["precision"]),
                )
        bend_in_record = None
        for element in self.lattice:
            if element.type_ == "BEND":
                # Create bends only once as they all share a single PV.
                if bend_in_record is None:
                    value = element.get_value("b0",
                                              units=pytac.ENG,
                                              data_source=pytac.SIM)
                    get_pv = element.get_pv_name("b0", pytac.RB)
                    upper, lower, precision = limits_dict.get(
                        get_pv, (None, None, None))
                    builder.SetDeviceName(get_pv.split(":", 1)[0])
                    in_record = builder.aIn(
                        get_pv.split(":", 1)[1],
                        LOPR=lower,
                        HOPR=upper,
                        PREC=precision,
                        MDEL="-1",
                        initial_value=value,
                    )
                    set_pv = element.get_pv_name("b0", pytac.SP)
                    upper, lower, precision = limits_dict.get(
                        set_pv, (None, None, None))
                    builder.SetDeviceName(set_pv.split(":", 1)[0])
                    out_record = builder.aOut(
                        set_pv.split(":", 1)[1],
                        LOPR=lower,
                        HOPR=upper,
                        PREC=precision,
                        initial_value=value,
                        on_update_name=self._on_update,
                        always_update=True,
                    )
                    self._in_records[in_record] = ([element.index], "b0")
                    self._out_records[out_record] = in_record
                    bend_in_record = in_record
                else:
                    self._in_records[bend_in_record][0].append(element.index)
            else:
                # Create records for all other families.
                for field in element.get_fields()[pytac.SIM]:
                    value = element.get_value(field,
                                              units=pytac.ENG,
                                              data_source=pytac.SIM)
                    get_pv = element.get_pv_name(field, pytac.RB)
                    upper, lower, precision = limits_dict.get(
                        get_pv, (None, None, None))
                    builder.SetDeviceName(get_pv.split(":", 1)[0])
                    in_record = builder.aIn(
                        get_pv.split(":", 1)[1],
                        LOPR=lower,
                        HOPR=upper,
                        PREC=precision,
                        MDEL="-1",
                        initial_value=value,
                    )
                    self._in_records[in_record] = (element.index, field)
                    try:
                        set_pv = element.get_pv_name(field, pytac.SP)
                    except HandleException:
                        self._rb_only_records.append(in_record)
                    else:
                        upper, lower, precision = limits_dict.get(
                            set_pv, (None, None, None))
                        builder.SetDeviceName(set_pv.split(":", 1)[0])
                        out_record = builder.aOut(
                            set_pv.split(":", 1)[1],
                            LOPR=lower,
                            HOPR=upper,
                            PREC=precision,
                            initial_value=value,
                            on_update_name=self._on_update,
                            always_update=True,
                        )
                        self._out_records[out_record] = in_record
        # Now for lattice fields.
        lat_fields = self.lattice.get_fields()
        for field in set(lat_fields[pytac.LIVE]) & set(lat_fields[pytac.SIM]):
            # Ignore basic devices as they do not have PVs.
            if not isinstance(self.lattice.get_device(field), BasicDevice):
                get_pv = self.lattice.get_pv_name(field, pytac.RB)
                value = self.lattice.get_value(field,
                                               units=pytac.ENG,
                                               data_source=pytac.SIM)
                builder.SetDeviceName(get_pv.split(":", 1)[0])
                in_record = builder.aIn(get_pv.split(":", 1)[1],
                                        PREC=4,
                                        initial_value=value,
                                        MDEL="-1")
                self._in_records[in_record] = (0, field)
                self._rb_only_records.append(in_record)
        print("~*~*Woah, we're halfway there, Wo-oah...*~*~")
Exemplo n.º 21
0
import time
import threading

import epics
from softioc import builder
from webmon import run_webmon

#local PVs
builder.SetDeviceName("tpc_caen_monit")
#trip indicator
trip_pv = builder.boolIn("is_trip", ZNAM=0, ONAM=1)
#anode sum current, inner and outer
sum_curr_in_pv = builder.aIn("sum_curr_in")
sum_curr_out_pv = builder.aIn("sum_curr_out")

#status of tripped channel
tripstat = 512

#voltage and current values, status value
npv=192
valV = [0. for i in range(npv)]
valI = [0. for i in range(npv)]
valS = [0 for i in range(npv)]

#sector and channel numbers
numSec = [None]*npv
numCh = [None]*npv
#dictionary from PV board and chan to array index
pdict = {}
#inner/outer channels, 0 = inner, 1 = outer
Exemplo n.º 22
0
import sys
import logging

from pkg_resources import require
require('cothread==2.13')
require('epicsdbbuilder==1.0')
require("numpy")

from softioc import softioc, builder

import PIController
import PIStepScan

if __name__ == '__main__':
    # Prepare params for IOC
    builder.SetDeviceName("BL13J-MO-PI-01:SCAN")
    builder.stringIn('WHOAMI', VAL='PI scan controller')
    builder.stringIn('HOSTNAME', VAL=os.uname()[1])

    logging.basicConfig(level=logging.DEBUG)

    # Connect to PI controller
    # Terminal server
    # pi_controller = PIController("172.23.82.5", 4011)
    # Ethernet
    #pi_controller = PIController.PIController("172.23.82.249", 50000, debug=False)
    pi_controller = PIController.PIController("Fake address 01", 50000,
                                              debug=True)

    # Step scan logic and records
    pi_step_scan = PIStepScan.PIStepScan(pi_controller)
import sys
import os

from pkg_resources import require
require('cothread==2.13')
require('numpy==1.11.1')
require('epicsdbbuilder==1.0')

from softioc import softioc, builder
from epicsdbbuilder import records  #, MS, CP, ImportRecord

##############################################

builder.SetDeviceName('BL04I-EA-XBPM-01')

x1sigcurr = builder.aOut('SumAll:MeanValue_RBV', initial_value=5)
x1r = builder.mbbOut('DRV:Range', initial_value=0)
x1psy = builder.mbbOut('DRV:PositionScaleY', initial_value=790)
x1psx = builder.mbbOut('DRV:PositionScaleX', initial_value=1200)

##############################################

builder.SetDeviceName('BL04I-EA-XBPM-02')

x2sigcurr = builder.aOut('SumAll:MeanValue_RBV', initial_value=7)
x2r = builder.aOut('DRV:Range', initial_value=0)
x2psy = builder.aOut('DRV:PositionScaleY', initial_value=247)
x2psx = builder.aOut('DRV:PositionScaleX', initial_value=1200)

##############################################
Exemplo n.º 24
0
from epdchan import epdchan
import paho.mqtt.client as mqtt
from watchdog import watchdog
from softioc import builder
import time
import pandas as pd

#EPD PVs
builder.SetDeviceName('EPD')

#list of all EPD channels as 3-index list
npp = 12
ntile = 31
elist = []
#east/west loop
for ew in range(0, 2):
    elist.append([])
    #PP loop
    for ipp in range(0, npp + 1):
        elist[ew].append([])
        #tile loop
        for itile in range(ntile + 1):
            #PP starts at 1, handled in epdchan constructor
            elist[ew][ipp].append(epdchan(ew, ipp, itile))

#watchdog timer for 60 seconds
wdt = watchdog(60, elist)

#file holding alarm limit values
csvlim = "limits.csv"
lframe = pd.read_csv(csvlim)
import sys
import os

from pkg_resources import require

require('cothread==2.13')
require('numpy==1.11.1')
require('epicsdbbuilder==1.0')

from softioc import softioc, builder
from epicsdbbuilder import records  #, MS, CP, ImportRecord

##############################################

builder.SetDeviceName('BL24I-EA-XBPM-01')

x1sigcurr = builder.aOut('SumAll:MeanValue_RBV', initial_value=5)
x1r = builder.mbbOut('DRV:Range', initial_value=0)
x1psy = builder.mbbOut('DRV:PositionScaleY', initial_value=1)
x1psx = builder.mbbOut('DRV:PositionScaleX', initial_value=1)

##############################################

builder.SetDeviceName('BL24I-OP-DCM-01')

A = 1
x1SF = builder.aOut('ENERGY', initial_value=11.882)
pitch = builder.aOut('FPITCH:FB1', initial_value=0.554)
roll = builder.aOut('FPITCH:FB2', initial_value=0.0261)

##############################################
Exemplo n.º 26
0
    def _create_mirror_records(self, mirror_csv):
        """Create all the mirror records from the .csv file at the location
        passed, see create_csv.py for more information.

        Args:
            mirror_csv (string): The filepath to the .csv file to load the
                                    records in accordance with.
        """
        csv_reader = csv.DictReader(open(mirror_csv))
        for line in csv_reader:
            # Parse arguments.
            input_pvs = line["in"].split(", ")
            if (len(input_pvs) > 1) and (line["mirror type"]
                                         in ["basic", "inverse", "refresh"]):
                raise IndexError("Transformation, refresher, and basic mirror "
                                 "types take only one input PV.")
            elif (len(input_pvs) < 2) and (line["mirror type"]
                                           in ["collate", "summate"]):
                raise IndexError("collation and summation mirror types take at"
                                 " least two input PVs.")
            monitor = input_pvs  # need to update to support camonitor multiple
            # Convert input pvs to record objects
            input_records = []
            for pv in input_pvs:
                try:
                    input_records.append(self.all_record_names[pv])
                except KeyError:
                    input_records.append(caget_mask(pv))
            # Create output record.
            prefix, suffix = line["out"].split(":", 1)
            builder.SetDeviceName(prefix)
            if line["mirror type"] == "refresh":
                # Refresh records come first as do not require an output record
                pass
            elif line["output type"] == "caput":
                output_record = caput_mask(line["out"])
            elif line["output type"] == "aIn":
                value = float(line["value"])
                output_record = builder.aIn(suffix,
                                            initial_value=value,
                                            MDEL="-1")
            elif line["output type"] == "longIn":
                value = int(line["value"])
                output_record = builder.longIn(suffix,
                                               initial_value=value,
                                               MDEL="-1")
            elif line["output type"] == "Waveform":
                value = numpy.asarray(line["value"][1:-1].split(", "),
                                      dtype=float)
                output_record = builder.Waveform(suffix, initial_value=value)
            else:
                raise TypeError("{0} isn't a supported mirroring output type;"
                                "please enter 'caput', 'aIn', 'longIn', or "
                                "'Waveform'.".format(line["output type"]))
            # Update the mirror dictionary.
            for pv in monitor:
                if pv not in self._mirrored_records:
                    self._mirrored_records[pv] = []
            if line["mirror type"] == "basic":
                self._mirrored_records[monitor[0]].append(output_record)
            elif line["mirror type"] == "inverse":
                # Other transformation types are not yet supported.
                transformation = transform(numpy.invert, output_record)
                self._mirrored_records[monitor[0]].append(transformation)
            elif line["mirror type"] == "summate":
                summation_object = summate(input_records, output_record)
                for pv in monitor:
                    self._mirrored_records[pv].append(summation_object)
            elif line["mirror type"] == "collate":
                collation_object = collate(input_records, output_record)
                for pv in monitor:
                    self._mirrored_records[pv].append(collation_object)
            elif line["mirror type"] == "refresh":
                refresh_object = refresher(self, line["out"])
                self._mirrored_records[pv].append(refresh_object)
            else:
                raise TypeError("{0} is not a valid mirror type; please enter "
                                "a currently supported type from: 'basic', "
                                "'summate', 'collate', 'inverse', and "
                                "'refresh'.".format(line["mirror type"]))
Exemplo n.º 27
0
# Determine the ring mode
if sys.argv[1:]:
    ring_mode = sys.argv[1]
else:
    try:
        ring_mode = str(os.environ['RINGMODE'])
    except KeyError:
        try:
            value = caget('SR-CS-RING-01:MODE', format=2)
            ring_mode = value.enums[int(value)]
        except ca_nothing:
            ring_mode = 'DIAD'

# Create PVs.
server = atip_server.ATIPServer(ring_mode, os.path.join(here, 'limits.csv'),
                                os.path.join(here, 'feedback.csv'),
                                os.path.join(here, 'mirrored.csv'),
                                os.path.join(here, 'tunefb.csv'))

# Add special case out record for SOFB to write to.
builder.SetDeviceName('CS-CS-MSTAT-01')
builder.aOut('FBHEART', initial_value=10)

# Start the IOC.
builder.LoadDatabase()
softioc.iocInit()
server.monitor_mirrored_pvs()

softioc.interactive_ioc(globals())