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)
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 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)
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
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] + ' ')
def endMacro(): global debug, macroFile, prefix, doReloadMacros global commandMonitorList, connected, recordingActive if debug: print("endMacro: entry\n") recordingActive = False if not connected: return try: recording = epics.caget(prefix + "caputRecorderMacroRecording") except: return if (not recording): return epics.camonitor_clear(prefix + "caputRecorderComment") epics.camonitor_clear(prefix + "caputRecorderAddDelayCmd") for pv in commandMonitorList: epics.camonitor_clear(pv) epics.caput(prefix + "caputRecorderMacroRecording", 0) epics.caput(prefix + "caputRecorderUserMessage", "Done") if (not macroFile or not isinstance(macroFile, file)): print("no macro is being recorded\n") return macroFile.write("\n") macroFile.close() macroFile = None doReloadMacros = 1 wake.set()
def is_finished(self): if self.detector_status.is_true(): camonitor_clear(self.pv_name + ':MarReadoutStatus_RBV') camonitor_clear(self.pv_name + ':MarCorrectStatus_RBV') camonitor_clear(self.pv_name + ':MarWritingStatus_RBV') return True else: return False
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)
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()
# 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')
def clear(self): for pv in self.pvs: epics.camonitor_clear(pv)
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 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)
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
def stop(): global debug, prefix epics.camonitor_clear(prefix + "caputRecorderMacroStopStart") epics.camonitor_clear(prefix + "caputRecorderReloadMacros") epics.camonitor_clear(prefix + "caputRecorderMacro") epics.camonitor_clear(prefix + "caputRecorderExecuteMacro") epics.camonitor_clear(prefix + "caputRecorderAbortMacro") epics.camonitor_clear(prefix + "caputRecorderUsers") epics.camonitor_clear(prefix + "caputRecorderHosts") epics.camonitor_clear(prefix + "caputRecorderPrefixes") epics.camonitor_clear(prefix + "caputRecorderAddDelayCmd") epics.camonitor_clear(prefix + "caputRecorderComment") # clear all busy records, and the bo record caputRecorderEditMacros epics.caput(prefix + "caputRecorderMacroStopStart", 0) epics.caput(prefix + "caputRecorderMacroRecording", 0) epics.caput(prefix + "caputRecorderExecuteMacro", 0) epics.caput(prefix + "caputRecorderEditMacros", 0) epics.caput(prefix + "caputRecorderAbortMacro", 0) epics.caput(prefix + "caputRecorderAddDelayCmd", 0) epics.caput(prefix + "caputRecorderSelectFile", 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!'
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]
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: ")
import epics import time import datetime sleep_sec = input("Collect data for how many seconds: ") fh = open('myioc.log', 'w') epics.camonitor('LS1_CB04:CHA_RD', writer=fh.write) time.sleep(int(sleep_sec)) epics.camonitor_clear('LS1_CB04:CHA_RD') fh.close() fh = open('myioc.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]