camon 5.1 KB
Newer Older
1
2
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# Copyright 2015 Helmholtz-Zentrum Berlin für Materialien und Energie GmbH
# <https://www.helmholtz-berlin.de>
#
# Author: Bernhard Kuner <bernhard.kuner@helmholtz-berlin.de>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
# 
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
# 
# You should have received a copy of the GNU General Public License along with
# this program.  If not, see <http://www.gnu.org/licenses/>.

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import ca
import re
import time
from optparse import OptionParser
from signal import *
from sys import stdout
import sys

def procSig(signum, frame):
    if signum == 2:
	sys.exit()

def matchRe(matchStr,reStr) :
    """
    Return tupel with matches, maybe empty if reStr contains no '()' 
        or 'None' if 'matchStr' doesn't match 'reStr'
	
    Check for matches:  
    
    	if matchRe('huhu','xxx') is not None : 
	
    get match data:
    
	try:
	    (a,b) = matchRe('my/file.ext','(.*)\.(.+)')
	except typeError:
	    sys.exit()
    """
    regx = re.compile(reStr)
    m = regx.match(matchStr)
    if m is not None :
    	return m.groups()
    else:
    	return None

class monPV :
    """
    Create a monitored PV, 

    - setup the PV, or throw any ca.caError
    - access the updated value
    - set/read event flag
    """	
    def __init__(self, pv,Type=-1):
    	self.val = None
	self.event = False
	def myCB(ch,val) : 
	    self.val = val
	    self.event = True
	ca.Monitor(pv,myCB)
    def get(self) : 
    	"""
	- o.get()     Return: PV.VAL
	"""
    	if self.val != None : 
	    return self.val[0] 
	else : 
	    return None
    def getAll(self) : 
	"""
	- o.getAll()  Return: (VAL,STAT,SEVR,TS)
	"""
    	return self.val
    def testEvent(self) : 
	"""
	o.testEvent() Return: True if any monitor occured since last call of testEvent() or False if not
	"""
    	if self.event == True : 
	    self.event = False
	    return True
	else : 
	    return False

def caExist(chName) :
    """
    Return: True if chName is found, otherwise False
    """
    try :
        ch = ca.channel(chName)
    	ch.wait_conn(dt=0.1,wait=10)
	return True
    except ca.caError,e:
	return False

def printTableHeader(header,minWidth=10) :
    """
    Print formated table
    
    Parameter:
    
    - rT,	# The table, a array reference (rows) of an array reference (columns)
    - header,	# Header (optional )
    - sortIdx	# Index of the column the table should be sorted to (optional)
    """
    formatMax = []	    # max item length of a collumn

    def choose(x):
	(a,b) = x
	if x[0] < x[1]: return x[1] 
	else: return x[0]
    def length(x):
    	if x is not None:
	    l = len(str(x))
	    if l<minWidth:
	    	l = minWidth
	    return l
	else:
	    print x
	    return minWidth
    for row in header[0]:
	formatMax = map(lambda x: length(x),row)
    for row in header[1:]:
	fLen = map(lambda x: length(x),row)
	print fLen
	formatMax = map(lambda x: choose(x),zip(formatMax,fLen))
    for line in header:
    	print " | ".join(map(lambda x:("%%%ds"%x[0])%x[1] ,zip(formatMax,line)) )
    print "-+-".join(map(lambda x: x*'-' ,formatMax) )
    return formatMax
    
signal(SIGINT,procSig) #2
usage = " %prog [options] PV1 PV1 ..."
parser = OptionParser(usage=usage,
		 version="%%prog 1.0",
    		 description="channel access monitor with table output"
    		 )
parser.add_option("-t","--timestamp",
		 action="store_true", # default: None
		 help="print timestamp for each measurement"
    		 )
parser.add_option("-w","--minWidth",
		 action="store", 
		 help="Minimal width of collumn"
    		 )
def prFormat(x):
    (width,v) = x
    val = v
    if len(val) > width:
	val = val[0:width]
    return  ("%%%ds" % width) % val

def printLine(formatMax,line):
    print " | ".join(map(lambda x:prFormat(x) ,zip(formatMax,line)) )
#    print " | ".join(map(lambda x:("%%%ds"%x[0])%x[1] ,zip(formatMax,line)) )

(options, args) = parser.parse_args()

minWidth = 15
if options.minWidth: minWidth = int(options.minWidth)
head1 = []
head2 = []
pvs = []

if options.timestamp:
    head1.append("Time          ")
    head2.append("              ")

for pv in args:
    (devn,signal) = matchRe(pv,"(.*?):(.*)")
    if caExist(pv) is True:
    	head1.append(devn)
    	head2.append(signal)
	pvs.append(monPV(pv))
    else:
    	print "Skip PV not found: ",pv

format = printTableHeader((head1,head2),minWidth)
line = ['']*len(format)

while 1:
    idx=0
    hasData=False
    for pv in pvs:
    	pv.get()
	if pv.testEvent() is True:    
    	    (val,stat,sevr,ts) = pv.getAll()
#	    print val,stat,sevr,ca.TS2Ascii(ts)
	    if options.timestamp: 
		line[0] = ca.TS2Ascii(ts)[10:24]
	    	line[idx+1] = str(val)
	    else:
	    	line[idx] = str(val)
    	    hasData=True
	else:
	    line[idx] = ""
	idx += 1
    if hasData is True:
    	printLine(format,line)