def test_pv2():
    global change_count
    change_count = 0
    epics.camonitor(pvname2, callback=onChange)
    wait(5)
    epics.camonitor_clear(pvname2)
    assert change_count > 5
def dataLog():
    "Logs PV data to a file; PVs must be in pvlist"
    now = timestamp()
    if os.environ['NFSHOME']:
        filepath = os.environ['NFSHOME'] + '/pvLog/' + now + '/'
    else:
        filepath = '~/pvLog/' + now + '/'
    if not os.path.exists(filepath):
        os.makedirs(filepath)
    msg1 = 'Dumping data to %s ,...PID is %s.' % (filepath, str(pid))
    msgPV.put(msg1)
    filename = filepath + 'pvlog-' + timestamp('s') + '.dat'
    if caMonFlag:
        writer1 = Writer(filename, 'w')
        epics.camonitor(pv1.pvname, writer=writer1.write)
        sleep(monitorTime)
        epics.camonitor_clear(pv1.pvname)
    else:
        with open(filename, 'w') as datafile:
            datafile.write('%-*s %s%s' % (22, 'Timestamp', pv1.pvname, '\n'))
            npts = int(monitorTime / dataInt)
            for i in range(npts):
                start = time()
                datafile.write(
                    str(timestamp('us')) + ' ' + str(pv1.value) + '\n')
                elapsedTime = time() - start
                if dataInt - elapsedTime > 0:
                    sleep(dataInt - elapsedTime)
                #epics.poll(evt=7.e-3, iot=0.1)
    msgPV.put('Data dumped')
    filenamePV.put(filename)
Beispiel #3
0
    def __init__(self, name, pvs):
        print('--Detector %s--' % name)

        def update_array(arr, i, value=None, pvname=None, **kwargs):
            print('%s[%d]=%s (%s updated)' % (pvname, i, value, name))
            arr[i] = value
            self.updated = True

        self.name = name
        # All of the PVs:
        self.pvs = sum((list_ for list_ in pvs.values()), [])
        for category, pvs_ in pvs.iteritems():
            arr = [0] * len(pvs_)
            setattr(self, category, arr)
            #print('category', category, 'array', arr)
            for i, pv in enumerate(pvs_):
                if not pv:
                    continue

                cb = lambda arr=arr, i=i, **kwargs: update_array(arr, i, **kwargs)
                value = epics.caget(pv)
                #print('Monitoring "%s" = %s (%s[%d])' % (pv, value, category, i))
                epics.camonitor(pv, callback=cb)
                cb(pvname=pv, value=value)

        # TODO assumes all spectra are same length
        # sometimes type(self.spectrum[1]) == int? TODO: bug

        self.spectrum[0] = np.arange(len(self.spectrum[1]))
def EmailAlert():
    camonitor('BL5:CS:Scan:Alarm')
    while caget('BL5:CS:Scan:Alarm') > 0:
        SERVER = "160.91.4.26"
        FROM = "*****@*****.**"
        TO = ["*****@*****.**",
              "*****@*****.**"]  #"*****@*****.**"] must be a list

        SUBJECT = "Alarm from CNCS BL-5"
        TIME = str(datetime.datetime.now())
        TEXT = "This is CNCS, BL-5 at ORNL.\n One of my scan alarm triggered at: {0}\n Please contact IMMEDIATELY the Hall Coordinator !!!".format(
            TIME)

        # Prepare actual message
        message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\n
    
       %s
       """ % (FROM, ", ".join(TO), SUBJECT, TEXT)

        # Send the mail
        server = smtplib.SMTP(SERVER)
        server.sendmail(FROM, TO, message)
        server.quit()

        print("Humans notified at: {0}".format(TIME))
Beispiel #5
0
    def monitor(self, callback):
        if callback:

            def monitor_cb(newval):
                self.__value__ = float(newval.split()[3])
                callback(err=None)

            camonitor(self.pvname, monitor_cb)
Beispiel #6
0
    def setUserWatcher(self):
        """
        Sets up a epics.camonitor against the PV set by the configuration file
        
        Callback:
            setUser()
        """

        epics.camonitor(self.userChangePV, callback=self.setUser)
Beispiel #7
0
    def __init__(self, pvname, callback=None):
        self.pvname = pvname
        self.__value__ = None
        if callback:

            def monitor_cb(newval):
                self.__value__ = float(newval.split()[3])
                callback(err=None)

            camonitor(self.pvname, monitor_cb)
Beispiel #8
0
    def __init__(self):
        epics.ca.find_libca()
        db = self.getDB()
        variables = db["variables"]
        for variable in variables:
            if variable["isLiveVariable"] == 1:
                pvName = variable["id"]
                camonitor(pvName, None, pvValueChanged)

        #Clean dead threads
        self.monitorThread = threading.Thread(target=self.threadCleaner)
Beispiel #9
0
def go(argv=[]):
    global debug, prefix, commandMonitorList, startTime, recordTiming, waitCompletion, ifMacroExists
    global macroFileName, macros

    if len(argv) > 0:
        prefix = argv[0]
        commandMonitorList = [prefix + "caputRecorderCommand"]
    else:
        print usage
        return

    if len(argv) > 1:
        for arg in argv[1:]:
            if arg.endswith(".py"):
                macroFileName = arg
            else:
                commandMonitorList.append(arg + "caputRecorderCommand")
    if debug: print "initial commandMonitorList", commandMonitorList

    # see if prefix+"caputRecorderCommand" exists
    #default_commandPV = epics.PV(prefix+"caputRecorderCommand", timeout=2)

    # imort the macros module
    (macroModuleName, ext) = os.path.splitext(os.path.basename(macroFileName))
    macros = __import__(macroModuleName)
    #print "macroFileName='%s'" % macroFileName
    #print "dir(macros)=", dir(macros)

    debug = epics.caget(prefix + "caputRecorderDebug")
    epics.camonitor(prefix + "caputRecorderDebug", callback=debugMonFunc)

    recordTiming = epics.caget(prefix + "caputRecorderRecordTiming")
    epics.camonitor(prefix + "caputRecorderRecordTiming",
                    callback=recordTimingMonFunc)

    waitCompletion = epics.caget(prefix + "caputRecorderWaitCompletion")
    epics.camonitor(prefix + "caputRecorderWaitCompletion",
                    callback=waitCompletionMonFunc)

    ifMacroExists = epics.caget(prefix + "caputRecorderIfMacroExists",
                                as_string=True)
    epics.camonitor(prefix + "caputRecorderIfMacroExists",
                    callback=ifMacroExistsMonFunc)

    epics.camonitor(prefix + "caputRecorderEditMacros",
                    callback=editMacrosMonFunc)

    # This is part of our mechanism to exit when a new version of caputRecorder is launched
    startTime = time.strftime("%c")
    epics.caput(prefix + "caputRecorderStartTime", startTime)
    stop()
    start()
    stop()
Beispiel #10
0
    def same_wire(self):
        self.proc.expect([pexpect.TIMEOUT, pexpect.EOF], timeout=0.25)

        t1 = PV('wire1')
        t2 = PV('wire2')

        camonitor('wire1')
        camonitor('wire2')

        t1.put(65, wait=True)
        time.sleep(1)


        return(caget('wire1'), caget('wire2'))
Beispiel #11
0
 def detectorChanged(self):
     """
     Checks and changes the detector
     """
     self.currentDetector = str(self.detectorComboBox.currentText())
     self.detectorStatus = 0
     if self.currentDetector != 'None':
         self.detPV = self.detectors[self.currentDetector]['PV']
         self.connection = caget(self.detPV + 'AsynIO.CNCT', as_string=True)
         if self.connection is None:
             QMessageBox.warning(
                 self, 'Detector Error',
                 'Please make sure the soft-IOC of the ' +
                 self.currentDetector + ' is running', QMessageBox.Ok)
         else:
             self.palette.setColor(QPalette.Foreground, Qt.green)
             self.detectorConnectionLabel.setText('Connected')
             self.detectorConnectionLabel.setPalette(self.palette)
             self.detectorStatus = 1
             self.set_det_alignment_mode()
             self.detStatusLabel.setText('Done')
             self.detStatusLabel.setPalette(self.palette)
             camonitor(self.detPV + 'Acquire',
                       callback=self.getDetectorStatus)
             camonitor(self.detPV.split(':')[0] +
                       ':image1:ArrayCounter_RBV',
                       callback=self.onArrayDataUpdate)
             #camonitor(self.detPV+'ArrayCounter_RBV',callback=self.onImageFileUpdate)
             self.expTimeLineEdit.setText(
                 caget(self.detPV + 'AcquireTime', as_string=True))
             self.shutterModeChanged()
             self.arrayDataUpdated.connect(self.updateDetectorImage)
             #self.imageFileUpdated.connect(self.updateImageInfo)
             return 1
     else:
         self.palette.setColor(QPalette.Foreground, Qt.red)
         self.detectorConnectionLabel.clear()
         self.detStatusLabel.clear()
         try:
             camonitor_clear(self.detPV + 'Acquire')
             camonitor_clear(self.detPV + 'DetectorState_RBV')
             camonitor_clear(self.detPV + 'ArrayCounter_RBV')
         except:
             pass
         self.detImgFolderLineEdit.clear()
         self.carsImgFolderLineEdit.clear()
         self.expTimeLineEdit.clear()
         self.sleepTimeLineEdit.clear()
    def __init__(self, input_pv_name, output_pv_name):

        Driver.__init__(self)

        self.input_pv_name = input_pv_name
        self.output_pv_name = output_pv_name

        self.data_buffer = []

        self.queue = Queue()

        self.process_thread = threading.Thread(target=self.processThread)
        self.process_thread.setDaemon(True)
        self.process_thread.start()

        camonitor(self.input_pv_name, callback=self.enqueueData)
 def onStartUpdate(self):
     self.cutSeriesExists = False
     self.widSeriesExists = False
     epics.caput(BYTES2STR(self.detPV + "cam1:ArrayCounter"), 0)
     epics.caput(BYTES2STR(self.detPV + "cam1:Acquire"), 1)
     epics.camonitor(BYTES2STR(self.detPV + "image1:ArrayCounter_RBV"),
                     callback=self.onArrayDataUpdate)
     self.arrayDataUpdated.connect(self.start_stop_Update)
     self.startUpdate = True
     self.startTime = time.time()
     self.posTimeData = []
     self.widTimeData = []
     self.startUpdatePushButton.setEnabled(False)
     self.stopUpdatePushButton.setEnabled(True)
     self.setOutputOptions(enabled=False)
     self.detPVLineEdit.setEnabled(False)
Beispiel #14
0
def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('--pv',
                        action='append',
                        help='PV to monitor (can be used multiple times).')
    parser.add_argument('--script',
                        help="Script to run if the PVs don't update anymore.")
    parser.add_argument('--tolerance',
                        type=int,
                        default=30,
                        help="Number of times we tolerate non-changing values")
    args = parser.parse_args()

    PVs = args.pv
    data = {}

    check = Check()

    for pv in PVs:
        data[pv] = tuple()
        epics.camonitor(pv,
                        callback=functools.partial(recv_value_update, data))
    try:
        last_hash = hash_function(data)
        while True:
            time.sleep(2)
            if hash_function(data) == last_hash:
                check.register_failed_try({})
            else:
                check.clear_failed_tries()
            if check.number_of_failed_tries() > args.tolerance:
                # no change!!! need to run script...
                print(dt.now().isoformat(),
                      "running script because the data didn't change...")
                status = subprocess.call(
                    args.script, shell=True)  #stdout=None, stderr=None)
                check.clear_failed_tries()
    except KeyboardInterrupt:
        pass
    for pv in PVs:
        epics.camonitor_clear(pv)
Beispiel #15
0
    def __init__(self, PV_input, PV_output):

        Driver.__init__(self)

        self.PV_input = PV_input
        self.PV_output = PV_output

        # created variables
        self.dataBuffer = []

        # start queue
        self.queue = Queue()

        # start others threads
        self.process_thread = threading.Thread(target=self.processThread)
        self.process_thread.setDaemon(True)
        self.process_thread.start()

        # monitor of PV element
        camonitor(self.PV_input, callback=self.enqueueData)
def test_with_camonitor():
    pv = PV(mypv, auto_monitor=True, callback=lambda **args:...)
    pv.wait_for_connection()

    # check that the PV is connected and  data is received
    assert pv.connected is True
    assert pv.get() is not None

    # use camonitor
    received = {'flag': False}

    def callback(**args):
        received['flag'] = True

    camonitor(mypv, callback=callback)
    time.sleep(1)

    # check that the monitor receives data
    assert received['flag'] is True

    # disconnect PV object
    pv.disconnect()
    time.sleep(1)

    # check that the PV is disconnected and doesn't receive data
    assert pv.connected is False
    assert pv.get() is None

    # reset the flag to check that new data is received by camonitor
    received['flag'] = False
    time.sleep(1)
    assert received['flag'] is True

    # clear the monitor
    camonitor_clear(mypv)
    time.sleep(1)

    # reset the flag to check that no new data is received by camonitor
    received['flag'] = False
    time.sleep(1)
    assert received['flag'] is False
Beispiel #17
0
 def monitor(self):
     for pv in self.pvList:
         epics.camonitor(pv, writer=self.saver)
     time.sleep(self.monitorTime)
     for pv in self.pvList:
         epics.camonitor_clear(pv)
     pvs = [[] for i in range(len(pvList))]
     for val in self.vals:
         for i in xrange(len(self.pvList)):
             if self.pvList[i] in val:
                 pvs[i].append(val)
     lengths = [len(item) for item in pvs]
     lmin = min([len(item) for item in pvs])
     lmax = max([len(item) for item in pvs])
     with open(self.filename, 'w') as datafile:
         #try:
         for j in range(0, 10):
             for i in range(len(self.pvList)):
                 print i, j, len(pvs[i]), pvs[i][j]
                 if j < len(pvs[i]):
                     if self.show: sys.stdout.write(pvs[i][j] + ' ')
Beispiel #18
0
 def __init__(self, pv_name):
     self.detector_status = self.StatusChecker(3)
     self.pv_name = pv_name
     camonitor(pv_name + ':MarReadoutStatus_RBV',
               writer=partial(self.detector_status.set_status, 0, 'Idle', True))
     camonitor(pv_name + ':MarCorrectStatus_RBV',
               writer=partial(self.detector_status.set_status, 1, 'Idle', True))
     camonitor(pv_name + ':MarWritingStatus_RBV',
               writer=partial(self.detector_status.set_status, 2, 'Idle', True))
Beispiel #19
0
def camonitor(mself, self, args):
    """
    $ monitor pv1 [[pv2] [pv3]...]
    Monitor until Ctrl-C is pressed
    """
    pvs = args.pvs
    print('Monitoring PVs:', ', '.join(pvs))

    def changed(pvname='', value='', timestamp='', **kwargs):
        print('%s\t%s\t%s' % (timestamp, pvname, value))

    try:
        for pv in pvs:
            epics.camonitor(pv, callback=changed)

        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        pass
    except Exception as ex:
        logger.error('Monitor failed: (%s) %s' % (ex.__class__.__name__, ex))
    finally:
        for pv in pvs:
            epics.camonitor_clear(pv)
Beispiel #20
0
 def __init__(self, pv_name):
     self.detector_status = self.StatusChecker(3)
     self.pv_name = pv_name
     camonitor(pv_name + ':MarReadoutStatus_RBV',
               writer=partial(self.detector_status.set_status, 0, 'Idle',
                              True))
     camonitor(pv_name + ':MarCorrectStatus_RBV',
               writer=partial(self.detector_status.set_status, 1, 'Idle',
                              True))
     camonitor(pv_name + ':MarWritingStatus_RBV',
               writer=partial(self.detector_status.set_status, 2, 'Idle',
                              True))
Beispiel #21
0
def start():
    global debug, prefix, wake, doStartMacro, doStopMacro, doReloadMacros, doexecuteMacro
    global doSelectMacro, doAbortMacro, executingMacro, msgQueue
    global allowedUsers, forbiddenUsers, allowedHosts, forbiddenHosts
    global commandMonitorList, exitProgram, doEditMacros, macroFileName
    global doSelectFile, defaultPath, defaultFile

    wake.clear()

    # this monitor will kill us if a new copy of the program is executed
    epics.camonitor(prefix + "caputRecorderStartTime",
                    callback=startStringMonFunc)

    # Build lists of the PVs we'll monitor while recording
    userPrefixes = epics.caget(prefix + "caputRecorderPrefixes",
                               as_string=True)
    if userPrefixes:
        makeCommandMonitorList(userPrefixes)

    epics.camonitor(prefix + "caputRecorderMacroStopStart",
                    callback=stopStartMonFunc)
    epics.camonitor(prefix + "caputRecorderReloadMacros",
                    callback=reloadMacrosMonFunc)
    epics.camonitor(prefix + "caputRecorderMacro", callback=selectMacroMonFunc)
    epics.camonitor(prefix + "caputRecorderExecuteMacro",
                    callback=executeMacroMonFunc)
    epics.camonitor(prefix + "caputRecorderAbortMacro",
                    callback=abortMacroMonFunc)
    epics.camonitor(prefix + "caputRecorderUsers", callback=usersMonFunc)
    epics.camonitor(prefix + "caputRecorderHosts", callback=hostsMonFunc)
    epics.camonitor(prefix + "caputRecorderPrefixes", callback=prefixesMonFunc)
    reloadMacros()
    # We probably won't get a monitor from Users or Hosts, so do cagets
    users = epics.caget(prefix + "caputRecorderUsers", as_string=True)
    (allowedUsers, forbiddenUsers) = calcAllowed(users)
    if (debug):
        print "allowedUsers='%s', forbiddenUsers='%s'" % (allowedUsers,
                                                          forbiddenUsers)
    hosts = epics.caget(prefix + "caputRecorderHosts", as_string=True)
    (allowedHosts, forbiddenHosts) = calcAllowed(hosts)
    if (debug):
        print "allowedHosts='%s', forbiddenHosts='%s'" % (allowedHosts,
                                                          forbiddenHosts)

    # heartbeat
    heartbeatThread = threading.Thread(target=heartbeat)
    heartbeatThread.daemon = True
    heartbeatThread.start()

    # message and queue
    msgQueue = Queue.Queue(maxsize=100)
    writeThread = threading.Thread(target=writer)
    writeThread.daemon = True
    writeThread.start()

    while (1):
        try:
            wake.wait(1)
        except:
            pass

        if wake.is_set():
            if debug: print "start: wake.is_set()"
            wake.clear()
        if doStartMacro:
            if debug: print "start: doStartMacro=True"
            doStartMacro = 0
            startMacro()
        if doStopMacro:
            if debug: print "start: doStopMacro=True"
            doStopMacro = 0
            endMacro()
        if doReloadMacros:
            if debug: print "start: doReloadMacros=True"
            doReloadMacros = 0
            reloadMacros()
        if doSelectMacro:
            if debug: print "start: doSelectMacro=True"
            doSelectMacro = 0
            selectMacro()
        if doexecuteMacro:
            if debug: print "start: doexecuteMacro=True"
            executeMacro()
            doexecuteMacro = 0
            epics.caput(prefix + "caputRecorderExecuteMacro", 0)
        if doAbortMacro:
            doAbortMacro = 0
            epics.caput(prefix + "caputRecorderAbortMacro", 0)
        if doEditMacros:
            doEditMacros = 0
            epics.caput(prefix + "caputRecorderEditMacros", 0)
            editor = os.environ['EDITOR']
            os.system(editor + " " + macroFileName + "&")
        if doSelectFile:
            doSelectFile = 0
            epics.caput(prefix + "caputRecorderSelectFile", 0)
            if HAVE_FILE_SELECTOR:
                app = wx.App()
                path = wx.FileSelector("Choose a file",
                                       default_path=defaultPath,
                                       default_filename=defaultFile,
                                       flags=wx.OPEN)
                (defaultPath, defaultFile) = os.path.split(path)
                app.Destroy()
                if debug:
                    print "path='%s', defaultPath='%s', defaultFile='%s'" % (
                        path, defaultPath, defaultFile)
                epics.caput(prefix + "caputRecorderGbl_filepath", defaultPath)
                epics.caput(prefix + "caputRecorderGbl_filename", defaultFile)
        if exitProgram:
            sys.exit()
    stop()
#! /usr/bin/python

import epics

from epics import camonitor

while 1:

	camonitor("CB:HV:BOX:19:read_dhcp")
	camonitor("CB:HV:BOX:19:read_ip")
	camonitor("CB:HV:BOX:19:read_mask")
	camonitor("CB:HV:BOX:19:read_gate")
	camonitor("CB:HV:BOX:19:read_dns")
	camonitor("CB:HV:BOX:19:read_ntpserver")
	camonitor("CB:HV:BOX:19:read_utczone")
	camonitor("CB:HV:BOX:19:read_r1")
	camonitor("CB:HV:BOX:19:read_r2")
	camonitor("CB:HV:BOX:19:read_ntp")
	camonitor("CB:HV:BOX:19:read_umin")
	camonitor("CB:HV:BOX:19:read_levels")
	camonitor("CB:HV:BOX:19:read_neg")
	camonitor("CB:HV:BOX:19:read_mem")
	camonitor("CB:HV:BOX:19:read_file")
	camonitor("CB:HV:BOX:19:read_reg_div")
	camonitor("CB:HV:BOX:19:read_cards")
	camonitor("CB:HV:BOX:19:read_m0")
	camonitor("CB:HV:BOX:19:read_n0")
	camonitor("CB:HV:BOX:19:read_m1")
	camonitor("CB:HV:BOX:19:read_n1")
	camonitor("CB:HV:BOX:19:read_m2")
	camonitor("CB:HV:BOX:19:read_n2")
Beispiel #23
0
def go(argv=[]):
    global debug, prefix, commandMonitorList, startString, recordTiming, waitCompletion, ifMacroExists
    global macroFileName, macros

    if len(argv) > 0:
        prefix = argv[0]
        commandMonitorList = [prefix + "caputRecorderCommand"]
    else:
        print usage
        return

    if len(argv) > 1:
        for arg in argv[1:]:
            if arg.endswith(".py"):
                macroFileName = arg
            else:
                commandMonitorList.append(arg + "caputRecorderCommand")
    if debug: print "initial commandMonitorList", commandMonitorList

    # see if prefix+"caputRecorderCommand" exists
    #default_commandPV = epics.PV(prefix+"caputRecorderCommand", timeout=2)

    # imort the macros module
    (macroModuleName, ext) = os.path.splitext(os.path.basename(macroFileName))
    macros = __import__(macroModuleName)
    #print "macroFileName='%s'" % macroFileName
    #print "dir(macros)=", dir(macros)

    debug = epics.caget(prefix + "caputRecorderDebug")
    epics.camonitor(prefix + "caputRecorderDebug", callback=debugMonFunc)

    recordTiming = epics.caget(prefix + "caputRecorderRecordTiming")
    epics.camonitor(prefix + "caputRecorderRecordTiming",
                    callback=recordTimingMonFunc)

    waitCompletion = epics.caget(prefix + "caputRecorderWaitCompletion")
    epics.camonitor(prefix + "caputRecorderWaitCompletion",
                    callback=waitCompletionMonFunc)

    ifMacroExists = epics.caget(prefix + "caputRecorderIfMacroExists",
                                as_string=True)
    epics.camonitor(prefix + "caputRecorderIfMacroExists",
                    callback=ifMacroExistsMonFunc)

    epics.camonitor(prefix + "caputRecorderEditMacros",
                    callback=editMacrosMonFunc)
    if HAVE_FILE_SELECTOR:
        epics.camonitor(prefix + "caputRecorderSelectFile",
                        callback=selectFileMonFunc)

    # This is part of our mechanism to exit when a new version of caputRecorder is launched
    # Defend against user hammering on the "(re)start caputRecorder" button, launching
    # multiple copies of caputRecorder that will have the same time string, by appending
    # a string of random hex digits.
    startString = time.strftime("%c_") + os.urandom(3).encode('hex')
    epics.caput(prefix + "caputRecorderStartTime", startString)
    stop()
    start()
    stop()
Beispiel #24
0
def startMacro():
    global debug, macroFile, prefix, macroFunctionNames
    global commandMonitorList, connected, timeOfLastPut, ifMacroExists
    global macroFileName, recordingActive

    if debug: print("startMacro: entry\n")
    if not connected:
        return

    busy = epics.caget(prefix + "caputRecorderMacroRecording")
    if (busy):
        epics.caput(prefix + "caputRecorderUserMessage",
                    "a macro is already being recorded")
        return
    tryMacroName = epics.caget(prefix + "caputRecorderMacroName")

    # check macroName for problems
    if (tryMacroName == ""):
        epics.caput(prefix + "caputRecorderUserMessage",
                    "*** macro name is empty")
        epics.caput(prefix + "caputRecorderMacroStopStart", 0)
        return
    # function name must start with a letter
    macroName = ""
    if tryMacroName[0] not in string.letters:
        macroName = "a"
    # function name must consist of letters, digits, and underscores
    for c in tryMacroName:
        if c in legalChars:
            macroName += c
        else:
            macroName += "_"
    # function name must be 25 characters or less (mbboRecord string length)
    if len(macroName) > 25: macroName = macroName[:25]
    if (macroName in keyword.kwlist):
        epics.caput(prefix + "caputRecorderUserMessage",
                    "*** macro name is a python keyword")
        epics.caput(prefix + "caputRecorderMacroStopStart", 0)
        return
    # See of function name is already defined
    appending = False
    if debug: print "startMacro: ifMacroExists=", ifMacroExists
    if macroName in macroFunctionNames:
        if debug: print "ifMacroExists=%s" % ifMacroExists
        if ifMacroExists == "Fail":
            epics.caput(prefix + "caputRecorderUserMessage",
                        "*** macro name is already in use")
            epics.caput(prefix + "caputRecorderMacroStopStart", 0)
            return
        if ifMacroExists == "Replace":
            timeString = time.strftime("_%y%m%d-%H%M%S")
            shutil.copy(macroFileName, macroFileName + timeString)
        dl = deleteFunction(macroFileName, macroName)
        if ifMacroExists == "Append":
            macroFile = open(macroFileName, "a")
            macroFile.writelines(dl)
            macroFile.close()
            appending = True
            epics.caput(prefix + "caputRecorderUserMessage",
                        "appending to existing macro")
        else:
            # replace

            epics.caput(prefix + "caputRecorderUserMessage",
                        "replacing existing macro")

    epics.caput(prefix + "caputRecorderMacroRecording", 1)
    epics.caput(prefix + "caputRecorderUserMessage", "Recording")
    macroFile = open(macroFileName, "a")
    if appending == False:
        macroFile.write("def %s():\n" % macroName)
    else:
        macroFile.write("\t# appended to existing macro...\n")

    # It's not legal to have a python function with no commands in it.
    # Defend against user stopping recording without doing any caputs
    # by writing dummy command to set the record date.
    now = time.strftime("%c")
    macroFile.write("\trecordDate = \"%s\"\n" % now)
    macroFile.flush()
    timeOfLastPut = None
    epics.camonitor(prefix + "caputRecorderComment", callback=commentMonFunc)
    epics.camonitor(prefix + "caputRecorderAddDelayCmd", callback=delayMonFunc)

    # If this is the first time we're connecting to a commandMonitorList pv,
    # we might get an initial value callback.  We want to ignore that, because the
    # user didn't do it.  So, monitor and unmonitor all the commandMonitorList pvs,
    # to flush out any initial value callbacks, then monitor the pvs and set
    # recordingActive==True.
    for pv in commandMonitorList:
        try:
            epics.camonitor(pv, callback=commandMonFunc)
        except:
            pass

    for pv in commandMonitorList:
        try:
            epics.camonitor_clear(pv)
        except:
            pass

    for pv in commandMonitorList:
        try:
            epics.camonitor(pv, callback=commandMonFunc)
        except:
            print "Can't monitor '%s'" % pv
    recordingActive = True
Beispiel #25
0
init = 40
firstValve = 101
lastValve = 350
tempo = 5

# scan: scan rate for the valve position
scan = caget('CTRL-SUP-BOY:PERF-SCAN.VAL')
maxLoop = int(caget('CTRL-SUP-BOY:PERF-LOOP.VAL'))

# define a callback function on 'pvname' and 'value'
def onChanges(pvname=None, value=None, **kw):
    scan = caget('CTRL-SUP-BOY:PERF-SCAN.VAL')
    print pvname, str(value), repr(kw)

camonitor('CTRL-SUP-BOY:PERF-SCAN.VAL', callback=onChanges)

# Valve status initialisation
for iValve in range(firstValve, lastValve+1):
    caput('CTRL-SUP-BOY:VC'+ str(iValve) + '-FB', init)
    caput('CTRL-SUP-BOY:VC'+ str(iValve) + '-CO', init)
    caput('CTRL-SUP-BOY:VC'+ str(iValve) + '-TRIP', 0)
    caput('CTRL-SUP-BOY:VC'+ str(iValve) + '-INTLK', 0)
    caput('CTRL-SUP-BOY:VC'+ str(iValve) + '-FOMD', 0)
    caput('CTRL-SUP-BOY:VC'+ str(iValve) + '-LOMD', 0)
    caput('CTRL-SUP-BOY:VC'+ str(iValve) + '-MAMD', 0)
    caput('CTRL-SUP-BOY:VC'+ str(iValve) + '-AUMD', 0)
    caput('CTRL-SUP-BOY:VC'+ str(iValve) + '-IOERR', 0)
    caput('CTRL-SUP-BOY:VC'+ str(iValve) + '-IOSIM', 0)

# wait for START
Beispiel #26
0
pvname1 = pvnames.updating_pvlist[0]
pvname2 = pvnames.updating_pvlist[1]


def wait(t=30):
    t0 = time.time()
    while time.time() - t0 < t:
        time.sleep(0.01)


def onChange(pvname, value=None, char_value=None, timestamp=None, **kw):
    print '  new value: %s = %s (%s) ' % (pvname, char_value,
                                          time.ctime(timestamp))


epics.camonitor(pvname1, callback=onChange)
epics.camonitor(pvname2, callback=onChange)

print '## Monitor 2 PVs with epics.camonitor for 10sec'

wait(10)

print '## clear monitor for ', pvname2

epics.camonitor_clear(pvname2)

print '## Monitor remaining PV for 10sec'
wait(10)

print 'done!'
 def setWatcher(self):
     epics.camonitor("13SIM1:TIFF1:FilePath", callback=self.printUser)
Beispiel #28
0
pvname1 = pvnames.updating_pvlist[0]
pvname2 = pvnames.updating_pvlist[1]


def wait(t=30):
    t0 = time.time()
    while time.time() - t0 < t:
        time.sleep(0.01)


def onChange(pvname, value=None, char_value=None, timestamp=None, **kw):
    print "  new value: %s = %s (%s) " % (pvname, char_value, time.ctime(timestamp))


epics.camonitor(pvname1, callback=onChange)
epics.camonitor(pvname2, callback=onChange)


print "## Monitor 2 PVs with epics.camonitor for 10sec"

wait(10)

print "## clear monitor for ", pvname2

epics.camonitor_clear(pvname2)

print "## Monitor remaining PV for 10sec"
wait(10)

print "done!"
#! /usr/bin/python

import epics

from epics import camonitor

while 1:

    camonitor("CB:HV:BOX:19:read_dhcp")
    camonitor("CB:HV:BOX:19:read_ip")
    camonitor("CB:HV:BOX:19:read_mask")
    camonitor("CB:HV:BOX:19:read_gate")
    camonitor("CB:HV:BOX:19:read_dns")
    camonitor("CB:HV:BOX:19:read_ntpserver")
    camonitor("CB:HV:BOX:19:read_utczone")
    camonitor("CB:HV:BOX:19:read_r1")
    camonitor("CB:HV:BOX:19:read_r2")
    camonitor("CB:HV:BOX:19:read_ntp")
    camonitor("CB:HV:BOX:19:read_umin")
    camonitor("CB:HV:BOX:19:read_levels")
    camonitor("CB:HV:BOX:19:read_neg")
    camonitor("CB:HV:BOX:19:read_mem")
    camonitor("CB:HV:BOX:19:read_file")
    camonitor("CB:HV:BOX:19:read_reg_div")
    camonitor("CB:HV:BOX:19:read_cards")
    camonitor("CB:HV:BOX:19:read_m0")
    camonitor("CB:HV:BOX:19:read_n0")
    camonitor("CB:HV:BOX:19:read_m1")
    camonitor("CB:HV:BOX:19:read_n1")
    camonitor("CB:HV:BOX:19:read_m2")
    camonitor("CB:HV:BOX:19:read_n2")
Beispiel #30
0
# Example for interacting with the 'fishtank' IOC
from time import sleep
from epics import caget, caput, camonitor, camonitor_clear

# The first call actually creates the PV and establishes a 'monitor'
print("Tank temperature is %f" % caget('training:tank'))

# Calling it again just returns the last received value
print("Tank temperature is %f" % caget('training:tank'))

# To force a 'get':
print("Tank temperature is %f" % caget('training:tank', use_monitor=False))

# Caput defaults to fire-and-forget
caput('training:setpoint', 30)

# To use put-callback and await completsion:
caput('training:setpoint', 30, wait=True)


# To receive updates on received values
def handle_value_update(pvname, value, **kw):
    print("%s = %s" % (pvname, str(value)))
    # print("Stuff: " + str(kw))


camonitor('training:tank', callback=handle_value_update)
sleep(5)
camonitor_clear('training:tank')
import epics
import time
import datetime
sleep_sec = input("Collect data for how many seconds: ")
fh = open('deviceioc.log', 'w')
epics.camonitor('CCM18I-5576:ChA', writer=fh.write)
time.sleep(int(sleep_sec))
epics.camonitor_clear('CCM18I-5576:ChA')
fh.close()
fh = open('deviceioc.log', 'r')

for i in fh.readlines():
    big_list = i.split(" ")
itr = 0
datetime_list = []
while itr < len(big_list):
    if big_list[itr][:4] == "2019":
        d = big_list[itr]
        t = big_list[itr + 1]
        date_time_object = datetime.datetime(int(d[:4]), int(d[5:7]),
                                             int(d[8:10]), int(t[:2]),
                                             int(t[3:5]), int(t[6:8]),
                                             int(t[9:14]) * 10, None)
        datetime_list.append(date_time_object)
    itr += 1

difference_list = []
itr2 = 0
delta_list = []
while itr2 < len(datetime_list) - 1:
    delta = datetime_list[itr2 + 1] - datetime_list[itr2]
Beispiel #32
0
def caGetAndMonitor(PVName, File):
	PV = epics.PV(PVName)
	File.writeln("%s %s %s" % (PVName, datetime.datetime.fromtimestamp(PV.timestamp).strftime('%Y-%m-%d %H:%M:%S'), PV.value))
	epics.camonitor(PVName, File.writeln)
Beispiel #33
0
import epics
import time
import numpy as np

data = []


def cb(pvname, timestamp, *args, **kwargs):
    data.append(timestamp)


if __name__ == '__main__':
    pvname = 'LS1_CB04:CHA_RD'
    epics.camonitor(pvname, callback=cb)
    time.sleep(5)
    print(np.mean(1.0 / np.diff(data)))
Beispiel #34
0
__author__ = 'gpd_user'

from epics import caget, caput, PV, camonitor

print caget('13IDD:m95.VAL')

caput('13IDD:m95.VELO', 1)
caput('13IDD:m95.VAL', 2, wait=True)

print caget('13IDD:m95.VELO')
caput('13IDD:m95.VELO', 0.1)
print caget('13IDD:m95.VELO')


omega_val = PV('13IDD:m95.VAL')


def get_value(val):
    print val


camonitor('13IDD:m95.VAL')

caput('13IDD:m95.VAL', 1, wait=True)
caput('13IDD:m95.VAL', 1.1, wait=True)
print 'process finished'

 def start_inst_list_monitor(self):
     logging.info("Setting up monitors on {}".format(INST_LIST_PV))
     self.inst_list_callback(char_value=epics.caget(INST_LIST_PV, as_string=True))
     epics.camonitor(INST_LIST_PV, callback=self.inst_list_callback)
Beispiel #36
0
#! /usr/bin/python

import epics, sys, time

from epics import camonitor

while 1:

    camonitor ("CB:HV:BOX:19:0:0:set_volt.PACT")
Beispiel #37
0
 def monitor(self):
     for pv in self.pvList:
         epics.camonitor(pv, writer=self.write)
     time.sleep(self.monitorTime)
     for pv in self.pvList:
         epics.camonitor_clear(pv)
Beispiel #38
0
    axis = DateAxisItem(orientation='bottom')
    axis.attachToPlotItem(w.getPlotItem())

    #Request historical data to EPICS Archivers
    requester = ArchiverRequester('http', '10.0.38.59', '11998')
    r = requester.requestHistoricalData('LNLS:ANEL:corrente',
                                        datetime(2019, 5, 17))

    #Transform data received
    dataArray = np.array(r[0]['data'])
    valuesArray = np.array([])

    for data in dataArray:
        valuesArray = np.append(valuesArray, data['val'])

    # Create time axis
    now = time.time()
    timestamps = np.linspace(now - 3600, now, len(valuesArray))

    # Plot historical data
    curve = w.plot(x=timestamps, y=valuesArray)
    w.show()

    #Start monitoring PV value
    epics.camonitor('LNLS:ANEL:corrente', callback=updateData)

    updateSignalizer = UpdateSignalizer()
    updateSignalizer.updateSignal.connect(updatePlot)

    sys.exit(app.exec_())
 def watchForUserChangeOver(self):
     epics.camonitor(self.userChangePV, callback=self.setUser)
import epics
import time

time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
device = input('Please input device PV name: ')

fh = open('%s_%s.log' % (device, time), 'w')
epics.camonitor('%s' % device, writer=fh.write)

print("Data logging......")

stop = input('If you want to stop EPICS logger, please input any key:')
print()

if stop == True:
    epics.camonitor_clear('%s' % device)
    fh.close()

read_file = input("Input any key to show data log, input 0 to exit: ")
def monitorUser():
    epics.camonitor("13SIM1:TIFF1:FilePath_RBV", callback=userChange)