From 82ccda964461e64fc153a877fc86cdf40ae2973b Mon Sep 17 00:00:00 2001
From: Whitney Armstrong <warmstrong@anl.gov>
Date: Thu, 31 Jan 2019 22:13:36 -0600
Subject: [PATCH] 	modified:   README.rst

	new file:   bin/add_run_comment
	new file:   bin/auto_full_replay_service
	new file:   bin/runplan_kine_update_service
---
 src/python/README.rst                      |  20 +++-
 src/python/bin/add_run_comment             | 114 +++++++++++++++++++++
 src/python/bin/auto_full_replay_service    |  81 +++++++++++++++
 src/python/bin/runplan_kine_update_service |  64 ++++++++++++
 4 files changed, 278 insertions(+), 1 deletion(-)
 create mode 100755 src/python/bin/add_run_comment
 create mode 100755 src/python/bin/auto_full_replay_service
 create mode 100755 src/python/bin/runplan_kine_update_service

diff --git a/src/python/README.rst b/src/python/README.rst
index 3430fa1..f008e64 100644
--- a/src/python/README.rst
+++ b/src/python/README.rst
@@ -1,7 +1,25 @@
 Hall C
-------
+======
 
 To use (with caution), simply do::
 
     >>> import hallc
     >>> 
+
+Scripts
+-------
+
+add_run_comment
+  Used to add a a comment to a "run list" json file.
+
+auto_full_replay_service
+  The service  script that waits for a new coda run to start and launches the full run replay.
+
+hallc_runinfo_service
+  The service script that has a bunch of callbacks connected to epics variables to write the `auto_standard.kinematics` and `db2/run_list.json` files. 
+  The main epics variables that are connected to CODA are `hcCOINRunInProgress` (0 or 1) and `hcCOINRunNumber`.
+  These are watched for changes indicated the start/end of run for creating/finalizing the kinematics/run_list entries.
+
+runplan_kine_update_service
+  Runplan monitoring
+
diff --git a/src/python/bin/add_run_comment b/src/python/bin/add_run_comment
new file mode 100755
index 0000000..c951437
--- /dev/null
+++ b/src/python/bin/add_run_comment
@@ -0,0 +1,114 @@
+#!/usr/bin/python
+from epics import caget, caput, camonitor, PV
+import epics
+import time
+import subprocess
+import json
+import sys
+#from multiprocessing import Pool
+import copy
+import os.path
+import threading
+
+import argparse
+
+parser = argparse.ArgumentParser(description='Add a run comment and other annotations to a json format run list file.')
+parser.add_argument('-r', '--run','--run-number',
+        #default = int(caget("hcCOINRunNumber")),
+        required = True,
+        help = 'Run number to associated with the comment and/or annotate.',
+        dest='run')
+parser.add_argument('-a','--append', 
+        action = "store_true",
+        help='append to existing comments',
+        dest='append')
+parser.add_argument('-u','--update', 
+        action = "store_true",
+        help='update run file')
+parser.add_argument('-f', '--file', 
+        default = 'db2/run_list_extra.json',
+        help = 'The json run file to add a comment in. Default: db2/run_list_extra.json',
+        dest='file')
+parser.add_argument('-c', '--comment', 
+        help = 'specify the comment on the commandline',
+        required = True,
+        default = None,
+        dest='comment')
+parser.add_argument('-k', '--kine', 
+        help = 'specify the kinematic setting',
+        default = None,
+        dest='kinematic')
+args = parser.parse_args()
+
+#@print args.run
+#@print args.append
+
+target_mass_amu = {"2":1.00794,"3":2.014101, "5":26.92} 
+target_desc     = {"2":"LH2",  "3": "LD2",   "5":"DUMMY"}
+
+def get_json(filename):
+    the_json = {}
+    if os.path.isfile(args.file) :
+        with open(args.file) as data_file:
+            the_json = json.loads(data_file.read())
+    return the_json
+
+def main():
+    """ """
+    if not args.comment :
+        comment = raw_input(str("Comment for run {} :").format(args.run))
+    else : 
+        comment = str(args.comment)
+    
+
+    the_json = {}
+    if os.path.isfile(args.file) :
+        with open(args.file) as data_file:
+            the_json = json.loads(data_file.read())
+
+    if str(args.run) in the_json.keys(): 
+        old_comment = None
+        if "comment" in the_json[str(args.run)].keys(): 
+            old_comment =  the_json[str(args.run)]["comment"]
+            #print old_comment
+        if args.append and old_comment:
+            comment = old_comment + ", " + comment
+        the_json[str(args.run)]["comment"] = comment
+    else :
+        the_json.update({str(args.run) : {"comment": comment}})
+
+    if args.kinematic :
+        kinematic = str(args.kinematic)
+        the_json[str(args.run)]["kinematic"] = kinematic
+    #print  the_json
+    #update(the_json, {"comment": comment})
+    #with open(out_file_name,'w') as data_file:
+    #    json.dump(the_json,data_file)
+    #print json.dumps(the_json, sort_keys=True, ensure_ascii=False, indent=2)
+    #jif os.path.isdir(os.path.basename(args.file)) :
+    #if os.path.isfile(args.file) and not args.update:
+    if os.path.exists(args.file) and not args.update:
+        print "Cannot overwrite existing file: {}".format(args.file)
+        print "use -u to  update existing file "
+    elif not os.path.exists(os.path.dirname(args.file)):
+        print "Cannot create file: {}".format(args.file)
+        print "Directory {} does not exist".format(os.path.dirname(args.file))
+    elif not os.path.isfile(args.file) or args.update:
+        with open(args.file, 'w') as f:
+            f.write(json.dumps(the_json, sort_keys=True, ensure_ascii=False, indent=2))
+    else : 
+        print "aborted"
+    #            print "Writing to output file : {}".format(args.file)
+    #run_list.current_run.PrintJSON()
+
+
+if __name__ == "__main__":
+    try:
+        main()
+    except KeyboardInterrupt:
+        print 'aborted.'
+        sys.exit(0)
+
+
+
+
diff --git a/src/python/bin/auto_full_replay_service b/src/python/bin/auto_full_replay_service
new file mode 100755
index 0000000..f067279
--- /dev/null
+++ b/src/python/bin/auto_full_replay_service
@@ -0,0 +1,81 @@
+#!/usr/bin/env python
+# encoding: utf-8
+
+import sys, os
+import curses
+#import epics
+from epics import caget, caput, camonitor, PV
+import epics
+import threading
+from time import sleep
+
+from subprocess import call
+import subprocess
+            
+
+import argparse
+
+#parser = argparse.ArgumentParser(description='Accumulate run information.')
+##parser.add_argument('-k', '--kine', 
+##        default = 'DBASE/COIN/auto_standard.kinematics', 
+##        help = 'output put for automatic standard.kinematics',
+##        dest='kinematics')
+#parser.add_argument('-i','--input', 
+#        default = 'db2/run_list.json', 
+#        help='input json run database',
+#        dest='input_file')
+#args = parser.parse_args()
+#
+##print args.kinematics
+#print args.input_file
+#
+#
+#cursor_x = 0
+#cursor_y = 0
+#k = 0
+
+
+class AutoReplay:
+    run_in_progress = 0
+    run_number = 0
+    last_replay_run_number = 0
+
+    def onRunNumberChange(self, pvname=None, value=None, host=None, **kws):
+        self.run_number = int(value)
+        print "run number changed {}".format(self.run_number)
+
+    def onRunInProgressChange(self, pvname=None, value=None, host=None, **kws):
+        new_value = int(value)
+        print "test" 
+        if (self.run_in_progress == 1) and (new_value == 0) :
+            subprocess.call(
+                    ["cd /home/cdaq/hallc-online/hallc_replay_sidis_fall18 && ./run_full_auto_sidis.sh {} &> logs/auto_replay_{}.log & ".format(int(self.run_number),int(self.run_number))],shell=True) 
+            self.run_in_progress = new_value
+            self.last_replay_run_number = self.run_number
+        self.run_in_progress = new_value
+
+    def Print(self):
+        print self.run_number
+        print self.run_in_progress
+
+    def __init__(self):
+        print "derp"
+        self.last_replay_run_number = 0
+        self.run_number_pv      = PV( 'hcCOINRunNumber')
+        self.run_number_pv.add_callback(self.onRunNumberChange)
+        self.run_in_progress_pv = PV( 'hcCOINRunInProgress')
+        self.run_in_progress_pv.add_callback(self.onRunInProgressChange)
+        self.run_number  = self.run_number_pv.get()
+        self.run_in_progress = self.run_in_progress_pv.get()
+
+        #run_in_progress_pv.get()
+
+def main():
+    auto_replay = AutoReplay()
+    auto_replay.Print()
+    while True:
+        sleep(0.01)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/src/python/bin/runplan_kine_update_service b/src/python/bin/runplan_kine_update_service
new file mode 100755
index 0000000..627d148
--- /dev/null
+++ b/src/python/bin/runplan_kine_update_service
@@ -0,0 +1,64 @@
+#!/usr/bin/env python
+# encoding: utf-8
+
+import sys, os
+import curses
+#import epics
+from epics import caget, caput, camonitor, PV
+import epics
+import threading
+from time import sleep
+from subprocess import call
+import subprocess
+
+import argparse
+
+parser = argparse.ArgumentParser(description='Accumulate run information.')
+#parser.add_argument('-k', '--kine', 
+#        default = 'DBASE/COIN/auto_standard.kinematics', 
+#        help = 'output put for automatic standard.kinematics',
+#        dest='kinematics')
+parser.add_argument('-i','--input', 
+        default = 'db2/run_list.json', 
+        help='input json run database',
+        dest='input_file')
+args = parser.parse_args()
+
+kine_setting_num_pv   = PV('hcKinematicSettingNumber')
+kine_setting_group_pv = PV('hcKinematicSettingGroup')
+kine_setting_id_pv    = PV('hcKinematicSettingID')
+run_in_progress_pv    = PV('hcCOINRunInProgress')
+
+def update_epics_kinematics(pvname=None, value=None, host=None, **kws):
+    p = subprocess.Popen(['bash','/group/c-csv/cdaq/csv_run_plan/bin/get_current_setting.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    out, err = p.communicate()
+    #print out
+    values = out.split()
+    epics.caput('hcKinematicSettingGroup', int(values[0]))
+    epics.caput('hcKinematicSettingNumber',int(values[1]))
+    epics.caput('hcKinematicSettingID',    int(values[2]))
+    print values[0]
+    print values[1]
+    print values[2]
+    sleep(1)
+    print kine_setting_group_pv.get()
+    print kine_setting_num_pv.get()
+    print kine_setting_id_pv.get()
+
+def main():
+    run_in_progress_pv.add_callback(update_epics_kinematics)
+    try:
+        while True:
+            sleep(0.01)
+    except KeyboardInterrupt:
+        """user wants control back"""
+        print "done"
+
+if __name__ == "__main__":
+    main()
+
+#         subprocess.call(
+#                   ["cd /home/cdaq/hallc-online/hallc_replay_sidis_fall18 && ./run_full_auto_sidis.sh {} &> logs/auto_replay_{}.log & ".format(int(self.run_number),int(self.run_number))],shell=True) 
+#            self.run_in_progress = new_value
+
+
-- 
GitLab