Reindent *.py with reindent.py

This commit is contained in:
Douglas Clowes
2014-07-04 11:28:11 +10:00
parent 7129c0608b
commit 522a5544a8
12 changed files with 635 additions and 638 deletions

View File

@@ -8,62 +8,62 @@ from twisted.protocols.basic import LineReceiver
class CamServ(LineReceiver): class CamServ(LineReceiver):
def __init__(self): def __init__(self):
self.camState = {'camera': "clock=1mhz,bin=1x,size=2048,gain=1xhs,flip=normal,xpos=0,ypos=0,exposure=0.777,temperature=-50,threshold=800,shutteropentime=100,shutterclosetime=200", 'file': "path=/experiments/dingo/data,basename=DingoTst,startnumber=1,imageformat=tiff,experimentdetail=this is an experiment", 'meta': "sx=100,sy=200,experiment=testing3", 'status': "camera status", 'state': "Idle", 'info': "camera info"} self.camState = {'camera': "clock=1mhz,bin=1x,size=2048,gain=1xhs,flip=normal,xpos=0,ypos=0,exposure=0.777,temperature=-50,threshold=800,shutteropentime=100,shutterclosetime=200", 'file': "path=/experiments/dingo/data,basename=DingoTst,startnumber=1,imageformat=tiff,experimentdetail=this is an experiment", 'meta': "sx=100,sy=200,experiment=testing3", 'status': "camera status", 'state': "Idle", 'info': "camera info"}
print "Camera get/set commands: ", self.camState.keys() print "Camera get/set commands: ", self.camState.keys()
def getCmd(self, par): def getCmd(self, par):
if par in self.camState: if par in self.camState:
self.sendLine(self.camState[par]) self.sendLine(self.camState[par])
else: else:
self.sendLine("ERROR: Unknown parameter, " + par) self.sendLine("ERROR: Unknown parameter, " + par)
def setCmd(self, s): def setCmd(self, s):
par,val = s.split(',',1) par,val = s.split(',',1)
if par in self.camState: if par in self.camState:
self.camState[par] = val self.camState[par] = val
self.sendLine("OK") self.sendLine("OK")
else: else:
self.sendLine("ERROR: Unknown parameter, " + par) self.sendLine("ERROR: Unknown parameter, " + par)
def takeCmd(self, cmd): def takeCmd(self, cmd):
if cmd == 'shot': if cmd == 'shot':
self.sendLine("OK") self.sendLine("OK")
elif cmd == 'multishot': elif cmd == 'multishot':
self.sendLine("OK") self.sendLine("OK")
else: else:
self.sendLine("ERROR:1") self.sendLine("ERROR:1")
def clearCmd(self, par): def clearCmd(self, par):
if par == 'meta': if par == 'meta':
self.sendLine("OK") self.sendLine("OK")
else: else:
self.sendLine("ERROR:1") self.sendLine("ERROR:1")
def lineReceived(self, line): def lineReceived(self, line):
print "RECEIVED: " + line print "RECEIVED: " + line
cmd = line.split() cmd = line.split()
if len(cmd) == 0: if len(cmd) == 0:
self.sendLine(line) self.sendLine(line)
return return
if cmd[0] == "get": if cmd[0] == "get":
self.getCmd(cmd[1]) self.getCmd(cmd[1])
elif cmd[0] =="set": elif cmd[0] =="set":
if len(cmd) == 1: if len(cmd) == 1:
self.sendLine("ERROR:2") self.sendLine("ERROR:2")
return return
self.setCmd(cmd[1]) self.setCmd(cmd[1])
elif cmd[0] == "take": elif cmd[0] == "take":
if len(cmd) == 1: if len(cmd) == 1:
self.sendLine("ERROR:2") self.sendLine("ERROR:2")
return return
self.takeCmd(cmd[1]) self.takeCmd(cmd[1])
elif cmd[0] == "clear": elif cmd[0] == "clear":
if len(cmd) == 1: if len(cmd) == 1:
self.sendLine("ERROR:2") self.sendLine("ERROR:2")
return return
self.clearCmd(cmd[1]) self.clearCmd(cmd[1])
else: else:
self.sendLine("ERROR: Unknown command, " + line) self.sendLine("ERROR: Unknown command, " + line)
def main(): def main():

View File

@@ -82,236 +82,236 @@ _POSDIR = _CW
# Some descriptive names for default register values per chopper. # Some descriptive names for default register values per chopper.
# The values are indexed by UID. # The values are indexed by UID.
RVAL = { RVAL = {
'mode': {1: _RPM, 2: _PHASE, 3: _PHASE}, 'mode': {1: _RPM, 2: _PHASE, 3: _PHASE},
'dir' : {1: _POSDIR, 2: _POSDIR, 3: _POSDIR} 'dir' : {1: _POSDIR, 2: _POSDIR, 3: _POSDIR}
} }
class Fermi_Prot(LineReceiver): class Fermi_Prot(LineReceiver):
def __init__(self): def __init__(self):
self.flags = INFO self.flags = INFO
self.mbhlen = 7 self.mbhlen = 7
self.fcbyte = 7 self.fcbyte = 7
self.datstart=8 self.datstart=8
self.MBAP = namedtuple('MBAP','TID PID len UID') self.MBAP = namedtuple('MBAP','TID PID len UID')
self.MBFN={1:self.rcoils,3:self.rhregs,5:self.wcoil,16:self.wmregs} self.MBFN={1:self.rcoils,3:self.rhregs,5:self.wcoil,16:self.wmregs}
self.setRawMode() self.setRawMode()
self.RegVal = {} self.RegVal = {}
self.FermiCoil = {} self.FermiCoil = {}
for uid in [1,2,3]: for uid in [1,2,3]:
self.FermiCoil[uid] = [0,0,0,0] self.FermiCoil[uid] = [0,0,0,0]
mode = RVAL['mode'][uid] mode = RVAL['mode'][uid]
dir = RVAL['dir'][uid] dir = RVAL['dir'][uid]
sys_stat = _AVC_ON|_OK sys_stat = _AVC_ON|_OK
self.RegInfo = { self.RegInfo = {
10: ['U16', 'System Status Information (R)'], 10: ['U16', 'System Status Information (R)'],
12: ['U16', 'Interlock Status Information (R)'], 12: ['U16', 'Interlock Status Information (R)'],
14: ['U16', 'Rotational Speed (R)'], 14: ['U16', 'Rotational Speed (R)'],
16: ['F32', 'Encoder Angle (MB350PC/R ONLY) (R)'], 16: ['F32', 'Encoder Angle (MB350PC/R ONLY) (R)'],
18: ['U32', 'Phase Veto Count (R)'], 18: ['U32', 'Phase Veto Count (R)'],
20: ['U32', 'Read and Clear Phase Veto Count (R)'], 20: ['U32', 'Read and Clear Phase Veto Count (R)'],
22: ['U32', 'Read and Clear Phase Veto Count (R)' ], 22: ['U32', 'Read and Clear Phase Veto Count (R)' ],
24: ['F32', 'Read PHASE ACCURACY (R)'], 24: ['F32', 'Read PHASE ACCURACY (R)'],
26: ['F32', 'Read PHASE REPEATABILITY (R)'], 26: ['F32', 'Read PHASE REPEATABILITY (R)'],
28: ['F32', 'Read PHASE OK (R)'], 28: ['F32', 'Read PHASE OK (R)'],
30: ['U32', 'Set VETO WINDOW 100ns (RW)'], 30: ['U32', 'Set VETO WINDOW 100ns (RW)'],
32: ['U32', 'Set VETO WINDOW 50ns (RW)'], 32: ['U32', 'Set VETO WINDOW 50ns (RW)'],
34: ['U32', 'Set MOTOR CONTROL MODE (RW)'], 34: ['U32', 'Set MOTOR CONTROL MODE (RW)'],
1000: ['U32', 'Set ROTATIONAL SPEED SETPOINT (RW)'], 1000: ['U32', 'Set ROTATIONAL SPEED SETPOINT (RW)'],
1002: ['F32', 'Set HOMING ANGLE SETPOINT (MB350PC/R ONLY) (RW)'], 1002: ['F32', 'Set HOMING ANGLE SETPOINT (MB350PC/R ONLY) (RW)'],
1004: ['F32', 'Set MOTOR KP (RW)'], 1004: ['F32', 'Set MOTOR KP (RW)'],
1006: ['F32', 'Set MOTOR KI (RW)'], 1006: ['F32', 'Set MOTOR KI (RW)'],
1008: ['F32', 'Set MOTOR KPhase (RW)'], 1008: ['F32', 'Set MOTOR KPhase (RW)'],
1010: ['F32', 'Set REFERENCE DELAY (RW)'], 1010: ['F32', 'Set REFERENCE DELAY (RW)'],
1012: ['F32', 'Set REFERENCE PERIOD (RW)'], 1012: ['F32', 'Set REFERENCE PERIOD (RW)'],
1014: ['U32', 'Set SYNC SOURCE (RW)'], 1014: ['U32', 'Set SYNC SOURCE (RW)'],
1016: ['U32', 'Set MOTOR DIRECTION (RW)'] 1016: ['U32', 'Set MOTOR DIRECTION (RW)']
} }
self.RegVal[uid] = { self.RegVal[uid] = {
10: sys_stat, 10: sys_stat,
12: 0x0, 12: 0x0,
14: 0, 14: 0,
16: 0, 16: 0,
18: 0, 18: 0,
20: 0, 20: 0,
22: 0, 22: 0,
24: 0, 24: 0,
26: 0, 26: 0,
28: 0, 28: 0,
30: 0, 30: 0,
32: 0, 32: 0,
34: mode, 34: mode,
1000: 0, 1000: 0,
1002: 0, 1002: 0,
1004: 0, 1004: 0,
1006: 0, 1006: 0,
1008: 0, 1008: 0,
1010: 0, 1010: 0,
1012: 400000, 1012: 400000,
1014: 0, 1014: 0,
1016: dir 1016: dir
} }
def debug(self, flags, *args): def debug(self, flags, *args):
if (self.flags & flags): if (self.flags & flags):
print args print args
def getFR(self, SA,QR): def getFR(self, SA,QR):
uid = self.mbap.UID uid = self.mbap.UID
type = self.RegInfo[SA][0] type = self.RegInfo[SA][0]
if (type == 'U32' or type == 'F32'): if (type == 'U32' or type == 'F32'):
NE = QR/2 NE = QR/2
else: else:
NE = QR NE = QR
EA = 2*NE + SA EA = 2*NE + SA
self.debug(RREG, 'NE = %d EA = %d ' % (NE,EA)) self.debug(RREG, 'NE = %d EA = %d ' % (NE,EA))
data = [] data = []
for a in range(SA, EA, 2): for a in range(SA, EA, 2):
self.debug(RREG, 'reg %d = %s' % (a, self.RegInfo[a][1])) self.debug(RREG, 'reg %d = %s' % (a, self.RegInfo[a][1]))
data += [self.RegVal[uid][a]] data += [self.RegVal[uid][a]]
return data return data
def setFR(self, SA, QR, data): def setFR(self, SA, QR, data):
uid = self.mbap.UID uid = self.mbap.UID
type = self.RegInfo[SA][0] type = self.RegInfo[SA][0]
if (type == 'U32' or type == 'F32'): if (type == 'U32' or type == 'F32'):
NE = QR/2 NE = QR/2
fs = '>%dI' fs = '>%dI'
else: else:
NE = QR NE = QR
fs = '>%dH' fs = '>%dH'
EA = 2*NE + SA EA = 2*NE + SA
self.debug(WREG, 'NE = %d EA = %d ' % (NE,EA)) self.debug(WREG, 'NE = %d EA = %d ' % (NE,EA))
t = unpack(fs % NE,data) t = unpack(fs % NE,data)
self.debug(WREG, 'setFR(): t = ', map(hex, t)) self.debug(WREG, 'setFR(): t = ', map(hex, t))
i = 0 i = 0
for a in range(SA, EA, 2): for a in range(SA, EA, 2):
n = t[i] n = t[i]
self.debug(WREG, 'setFR() a = ', a, ' i = ', i, 'setFR() n = ', n) self.debug(WREG, 'setFR() a = ', a, ' i = ', i, 'setFR() n = ', n)
self.debug(INFO, 'set reg %d = %s' % (a, self.RegInfo[a][1]), ' to ', hex(n)) self.debug(INFO, 'set reg %d = %s' % (a, self.RegInfo[a][1]), ' to ', hex(n))
self.RegVal[uid][a] = n self.RegVal[uid][a] = n
i += 1 i += 1
return return
def rawDataReceived(self, ADU): def rawDataReceived(self, ADU):
self.debug(COMS, "Received ADU ", ADU.encode('hex')) self.debug(COMS, "Received ADU ", ADU.encode('hex'))
self.ADU = ADU self.ADU = ADU
dl = len(ADU) dl = len(ADU)
self.mbap = self.MBAP._make(unpack('>3HB',ADU[:self.mbhlen])) self.mbap = self.MBAP._make(unpack('>3HB',ADU[:self.mbhlen]))
self.fcode = unpack('>B', ADU[self.fcbyte])[0] self.fcode = unpack('>B', ADU[self.fcbyte])[0]
self.debug(COMS, self.mbap, 'fcode = ', self.fcode) self.debug(COMS, self.mbap, 'fcode = ', self.fcode)
self.MBFN[self.fcode]() self.MBFN[self.fcode]()
def connectionMade(self): def connectionMade(self):
self.debug(INFO, "Connection made") self.debug(INFO, "Connection made")
def getPDU(self): def getPDU(self):
return self.ADU[self.datstart:] return self.ADU[self.datstart:]
def rcoils(self): def rcoils(self):
# FC = Function Code # FC = Function Code
# SA = Start Address, QC = Quantity of Coils # SA = Start Address, QC = Quantity of Coils
# BC = Byte Count, CS = Coil Status (each bit = status of one coil) # BC = Byte Count, CS = Coil Status (each bit = status of one coil)
# Request: FC<1B>, SA<2B>, QC<2B> # Request: FC<1B>, SA<2B>, QC<2B>
# Response: FC<1B>, BC<1B>, CS<n*B> # Response: FC<1B>, BC<1B>, CS<n*B>
# n = number of eights in QC plus 1 if there is a remainder. # n = number of eights in QC plus 1 if there is a remainder.
# ie n = QC // 8 + (1 if QC % 8 else 0) # ie n = QC // 8 + (1 if QC % 8 else 0)
uid = self.mbap.UID uid = self.mbap.UID
PDU = self.getPDU() PDU = self.getPDU()
(SA, QC) = unpack('>2H',PDU) (SA, QC) = unpack('>2H',PDU)
self.debug(RCOIL, 'rcoils:SA=%d, QC=%d' % (SA,QC)) self.debug(RCOIL, 'rcoils:SA=%d, QC=%d' % (SA,QC))
hdr = self.mbap._replace(len = 4) hdr = self.mbap._replace(len = 4)
BC = 1 # ByteCount BC = 1 # ByteCount
#TODO Coil values should be an array of bytes with each bit representing a coil #TODO Coil values should be an array of bytes with each bit representing a coil
if (self.FermiCoil[uid][SA] == 0xFF00): if (self.FermiCoil[uid][SA] == 0xFF00):
data = 1 data = 1
else: else:
data = 0 data = 0
resp = pack('>3HB', *hdr) + pack('>2B%dB' % BC, self.fcode, BC, data) resp = pack('>3HB', *hdr) + pack('>2B%dB' % BC, self.fcode, BC, data)
self.debug(RCOIL, 'resp = ', resp.encode('hex')) self.debug(RCOIL, 'resp = ', resp.encode('hex'))
self.sendLine(resp) self.sendLine(resp)
def wcoil(self): def wcoil(self):
uid = self.mbap.UID uid = self.mbap.UID
PDU = self.getPDU() PDU = self.getPDU()
(OA, OV) = unpack('>2H', self.ADU[self.datstart:]) (OA, OV) = unpack('>2H', self.ADU[self.datstart:])
self.debug(WCOIL, 'wcoil:OA=%d, OV=%X' % (OA,OV)) self.debug(WCOIL, 'wcoil:OA=%d, OV=%X' % (OA,OV))
# TODO This really just toggles IDLE speed so it's only correct for OA=2 (ie coil 3) # TODO This really just toggles IDLE speed so it's only correct for OA=2 (ie coil 3)
self.FermiCoil[uid][OA] ^= OV self.FermiCoil[uid][OA] ^= OV
if (OA == CSTART): if (OA == CSTART):
self.debug(INFO, "START") self.debug(INFO, "START")
self.RegVal[uid][10] |= (_RUN|_LEV) self.RegVal[uid][10] |= (_RUN|_LEV)
self.debug(INFO, 'RUNNING, LEVITATING') self.debug(INFO, 'RUNNING, LEVITATING')
# Don't set speed if idling # Don't set speed if idling
if (self.FermiCoil[uid][2] == 0x0000): if (self.FermiCoil[uid][2] == 0x0000):
# Set RotSpeed value # Set RotSpeed value
self.RegVal[uid][14] = self.RegVal[uid][1000] self.RegVal[uid][14] = self.RegVal[uid][1000]
if (self.RegVal[uid][34] == _PHASE): if (self.RegVal[uid][34] == _PHASE):
self.debug(INFO, 'PHASELOCKED') self.debug(INFO, 'PHASELOCKED')
self.RegVal[uid][10] |= _PHLOCK self.RegVal[uid][10] |= _PHLOCK
else: else:
self.debug(INFO, 'UP TO SPEED') self.debug(INFO, 'UP TO SPEED')
self.RegVal[uid][10] |= _UP_TO_SPEED self.RegVal[uid][10] |= _UP_TO_SPEED
elif (OA == CSTOP): elif (OA == CSTOP):
self.debug(INFO, "STOP") self.debug(INFO, "STOP")
self.RegVal[uid][14] = 0 self.RegVal[uid][14] = 0
if (self.RegVal[uid][34] == _PHASE): if (self.RegVal[uid][34] == _PHASE):
self.debug(INFO, 'NOT UP TO SPEED, NOT RUNNING, NOT LEVITATING, NOT PHASELOCKED') self.debug(INFO, 'NOT UP TO SPEED, NOT RUNNING, NOT LEVITATING, NOT PHASELOCKED')
self.RegVal[uid][10] &= ~(_UP_TO_SPEED|_RUN|_LEV|_PHLOCK) self.RegVal[uid][10] &= ~(_UP_TO_SPEED|_RUN|_LEV|_PHLOCK)
else: else:
self.debug(INFO, 'NOT UP TO SPEED, NOT RUNNING, NOT LEVITATING') self.debug(INFO, 'NOT UP TO SPEED, NOT RUNNING, NOT LEVITATING')
self.RegVal[uid][10] &= ~(_UP_TO_SPEED|_RUN|_LEV) self.RegVal[uid][10] &= ~(_UP_TO_SPEED|_RUN|_LEV)
elif (OA == CIDLE): elif (OA == CIDLE):
self.debug(INFO, "TOGGLE IDLE") self.debug(INFO, "TOGGLE IDLE")
if (self.RegVal[uid][34] == _PHASE): if (self.RegVal[uid][34] == _PHASE):
lockflag = _PHLOCK lockflag = _PHLOCK
flagname = '_PHLOCK' flagname = '_PHLOCK'
else: else:
lockflag = _UP_TO_SPEED lockflag = _UP_TO_SPEED
flagname = '_UP_TO_SPEED' flagname = '_UP_TO_SPEED'
if ( (self.RegVal[uid][10] & lockflag) > 0): if ( (self.RegVal[uid][10] & lockflag) > 0):
self.debug(INFO, "SET IDLE SPEED") self.debug(INFO, "SET IDLE SPEED")
self.RegVal[uid][14] = 0 self.RegVal[uid][14] = 0
self.debug(INFO, "UNSET %s" % flagname) self.debug(INFO, "UNSET %s" % flagname)
self.RegVal[uid][10] &= ~(lockflag) self.RegVal[uid][10] &= ~(lockflag)
else: else:
self.debug(INFO, "SET RUN SPEED") self.debug(INFO, "SET RUN SPEED")
self.RegVal[uid][14] = self.RegVal[uid][1000] self.RegVal[uid][14] = self.RegVal[uid][1000]
self.debug(INFO, "SET %s" % flagname) self.debug(INFO, "SET %s" % flagname)
self.RegVal[uid][10] |= lockflag self.RegVal[uid][10] |= lockflag
elif (OA == CRESET): elif (OA == CRESET):
self.debug(INFO, "RESET") self.debug(INFO, "RESET")
self.debug(WCOIL, 'resp = ', self.ADU.encode('hex')) self.debug(WCOIL, 'resp = ', self.ADU.encode('hex'))
self.sendLine(self.ADU) self.sendLine(self.ADU)
def rhregs(self): def rhregs(self):
uid = self.mbap.UID uid = self.mbap.UID
PDU = self.getPDU() PDU = self.getPDU()
(SA, QR) = unpack('>2H', self.ADU[self.datstart:]) (SA, QR) = unpack('>2H', self.ADU[self.datstart:])
self.debug(RHREGS, 'rhregs:SA=%d, QR=%d' % (SA,QR)) self.debug(RHREGS, 'rhregs:SA=%d, QR=%d' % (SA,QR))
regval = self.getFR(SA,QR) regval = self.getFR(SA,QR)
self.debug(RHREGS, 'rhregs:data = ', regval) self.debug(RHREGS, 'rhregs:data = ', regval)
hdr = self.mbap._replace(len = 3 + 2*QR) hdr = self.mbap._replace(len = 3 + 2*QR)
self.debug(RHREGS, 'hdr = ', hdr) self.debug(RHREGS, 'hdr = ', hdr)
type = self.RegInfo[SA][0] type = self.RegInfo[SA][0]
if (type == 'U32' or type == 'F32'): if (type == 'U32' or type == 'F32'):
NE = QR/2 NE = QR/2
resp = pack('>3HB', *hdr) + pack('>2B%dI' % NE, self.fcode, 2*QR, *regval) resp = pack('>3HB', *hdr) + pack('>2B%dI' % NE, self.fcode, 2*QR, *regval)
else: else:
resp = pack('>3HB', *hdr) + pack('>2B%dH' % QR, self.fcode, 2*QR, *regval) resp = pack('>3HB', *hdr) + pack('>2B%dH' % QR, self.fcode, 2*QR, *regval)
self.debug(RHREGS, 'resp = ', resp.encode('hex')) self.debug(RHREGS, 'resp = ', resp.encode('hex'))
self.sendLine(resp) self.sendLine(resp)
def wmregs(self): def wmregs(self):
PDU = self.getPDU() PDU = self.getPDU()
(SA, QR, BC) = unpack('>2HB',PDU[:5]) (SA, QR, BC) = unpack('>2HB',PDU[:5])
data = PDU[5:] data = PDU[5:]
self.debug(WMREGS, 'wmregs:SA=%d, QR=%d, BC=%d' % (SA,QR,BC), 'data = ', map(hex, unpack('>%dH' % QR, data)) ) self.debug(WMREGS, 'wmregs:SA=%d, QR=%d, BC=%d' % (SA,QR,BC), 'data = ', map(hex, unpack('>%dH' % QR, data)) )
self.setFR(SA, QR, data) self.setFR(SA, QR, data)
hdr = self.mbap._replace(len = 7) hdr = self.mbap._replace(len = 7)
resp = pack('>3HB', *hdr) + pack('>B2H', self.fcode, SA, QR) resp = pack('>3HB', *hdr) + pack('>B2H', self.fcode, SA, QR)
self.debug(WMREGS, 'resp = ', resp.encode('hex')) self.debug(WMREGS, 'resp = ', resp.encode('hex'))
self.sendLine(resp) self.sendLine(resp)

View File

@@ -85,4 +85,3 @@ class GalilFactory(ServerFactory):
p = self.protocol(self.device) p = self.protocol(self.device)
p.factory = self p.factory = self
return p return p

View File

@@ -26,9 +26,9 @@ class HidenFactory(ServerFactory):
if __name__ == '__main__': if __name__ == '__main__':
class TestProtocol: class TestProtocol:
def __init__(self, theDevice, theTerm = "\n"): def __init__(self, theDevice, theTerm = "\n"):
self.device = theDevice self.device = theDevice
self.response = "" self.response = ""
self.term = theTerm self.term = theTerm
class TestDevice: class TestDevice:
def __init__(self): def __init__(self):

View File

@@ -6,48 +6,48 @@ from twisted.internet import reactor, protocol
class NVS_Prot(protocol.Protocol): class NVS_Prot(protocol.Protocol):
def __init__(self): def __init__(self):
self.fields = [ self.fields = [
'state' , 'rspeed', 'aspeed', 'sspeed', 'aveto' , 'ploss' , 'sploss', 'state' , 'rspeed', 'aspeed', 'sspeed', 'aveto' , 'ploss' , 'sploss',
'ttang' , 'rtemp' , 'wflow' , 'winlt' , 'woutt' , 'vacum' , 'wvalv' , 'ttang' , 'rtemp' , 'wflow' , 'winlt' , 'woutt' , 'vacum' , 'wvalv' ,
'vvalv' , 'vibrt' , 'bcuun' , 'sdate' , 'stime' 'vvalv' , 'vibrt' , 'bcuun' , 'sdate' , 'stime'
] ]
self.state = { self.state = {
'state' : {'fname': '#STATE ', 'fval':'BRAKING'}, 'state' : {'fname': '#STATE ', 'fval':'BRAKING'},
'rspeed': {'fname': '#RSPEED', 'fval': 25476}, 'rspeed': {'fname': '#RSPEED', 'fval': 25476},
'aspeed': {'fname': '#ASPEED', 'fval': 0}, 'aspeed': {'fname': '#ASPEED', 'fval': 0},
'sspeed': {'fname': '#SSPEED', 'fval': 0.3}, 'sspeed': {'fname': '#SSPEED', 'fval': 0.3},
'aveto' : {'fname': '#AVETO ', 'fval': 'nok'}, 'aveto' : {'fname': '#AVETO ', 'fval': 'nok'},
'ploss' : {'fname': '#PLOSS ', 'fval': 290.2}, 'ploss' : {'fname': '#PLOSS ', 'fval': 290.2},
'sploss': {'fname': '#SPLOS ', 'fval': 25422}, 'sploss': {'fname': '#SPLOS ', 'fval': 25422},
'ttang' : {'fname': '#TTANG ', 'fval': 0.000}, 'ttang' : {'fname': '#TTANG ', 'fval': 0.000},
'rtemp' : {'fname': '#RTEMP ', 'fval': 23.9}, 'rtemp' : {'fname': '#RTEMP ', 'fval': 23.9},
'wflow' : {'fname': '#WFLOW ', 'fval': 0.1}, 'wflow' : {'fname': '#WFLOW ', 'fval': 0.1},
'winlt' : {'fname': '#WINLT ', 'fval': 20.3}, 'winlt' : {'fname': '#WINLT ', 'fval': 20.3},
'woutt' : {'fname': '#WOUTT ', 'fval': 21.0}, 'woutt' : {'fname': '#WOUTT ', 'fval': 21.0},
'vacum' : {'fname': '#VACUM ', 'fval': 0.1922}, 'vacum' : {'fname': '#VACUM ', 'fval': 0.1922},
'wvalv' : {'fname': '#WVALV ', 'fval': ' clos'}, 'wvalv' : {'fname': '#WVALV ', 'fval': ' clos'},
'vvalv' : {'fname': '#VVALV ', 'fval': ' open'}, 'vvalv' : {'fname': '#VVALV ', 'fval': ' open'},
'vibrt' : {'fname': '#VIBRT ', 'fval': 0.08}, 'vibrt' : {'fname': '#VIBRT ', 'fval': 0.08},
'bcuun' : {'fname': '#BCUUN ', 'fval': 0.0}, 'bcuun' : {'fname': '#BCUUN ', 'fval': 0.0},
'sdate' : {'fname': '#SDATE ', 'fval': '24.04.2013'}, 'sdate' : {'fname': '#SDATE ', 'fval': '24.04.2013'},
'stime' : {'fname': '#STIME ', 'fval': '13:53:10'} 'stime' : {'fname': '#STIME ', 'fval': '13:53:10'}
} }
def dataReceived(self, data): def dataReceived(self, data):
print "RECEIVED ", data print "RECEIVED ", data
reply = 'N#SOS#ACCEPT' reply = 'N#SOS#ACCEPT'
for k in self.fields: for k in self.fields:
reply += self.state[k]['fname'] + '= ' + str(self.state[k]['fval']) reply += self.state[k]['fname'] + '= ' + str(self.state[k]['fval'])
reply += '#' reply += '#'
print "REPLY ", reply print "REPLY ", reply
self.transport.write(reply) self.transport.write(reply)
def main(): def main():
factory = protocol.ServerFactory() factory = protocol.ServerFactory()
factory.protocol = NVS_Prot factory.protocol = NVS_Prot
reactor.listenTCP(60001,factory) reactor.listenTCP(60001,factory)
reactor.run() reactor.run()
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@@ -26,9 +26,9 @@ class PfeifferFactory(ServerFactory):
if __name__ == '__main__': if __name__ == '__main__':
class TestProtocol: class TestProtocol:
def __init__(self, theDevice, theTerm = "\r\n"): def __init__(self, theDevice, theTerm = "\r\n"):
self.device = theDevice self.device = theDevice
self.response = "" self.response = ""
self.term = theTerm self.term = theTerm
class TestDevice: class TestDevice:
def __init__(self): def __init__(self):

View File

@@ -22,9 +22,9 @@ class LakeshoreFactory(ServerFactory):
if __name__ == '__main__': if __name__ == '__main__':
class TestProtocol: class TestProtocol:
def __init__(self, theDevice, theTerm = "\r\n"): def __init__(self, theDevice, theTerm = "\r\n"):
self.device = theDevice self.device = theDevice
self.response = "" self.response = ""
self.term = theTerm self.term = theTerm
class TestDevice: class TestDevice:
def __init__(self): def __init__(self):

View File

@@ -26,9 +26,9 @@ class MercuryFactory(ServerFactory):
if __name__ == '__main__': if __name__ == '__main__':
class TestProtocol: class TestProtocol:
def __init__(self, theDevice, theTerm = "\r\n"): def __init__(self, theDevice, theTerm = "\r\n"):
self.device = theDevice self.device = theDevice
self.response = "" self.response = ""
self.term = theTerm self.term = theTerm
class TestDevice: class TestDevice:
def __init__(self): def __init__(self):

View File

@@ -9,11 +9,11 @@ import matplotlib.pyplot as plt
import argparse import argparse
def make_delta(q): def make_delta(q):
delta_q = np.zeros(len(q)) delta_q = np.zeros(len(q))
delta_q[0] = 0.0 delta_q[0] = 0.0
for i in range(1, len(q)): for i in range(1, len(q)):
delta_q[i] = q[i] - q[i - 1] delta_q[i] = q[i] - q[i - 1]
return delta_q return delta_q
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument("csv_file", help="TrackingFile.csv", nargs="?") parser.add_argument("csv_file", help="TrackingFile.csv", nargs="?")
@@ -28,10 +28,10 @@ data = np.loadtxt(csv_file, delimiter=",", skiprows=1, unpack=True)
t, p, s, c = data t, p, s, c = data
if False: if False:
print dir(data) print dir(data)
#print data.T #print data.T
print len(data) print len(data)
print len(t) print len(t)
delta_t = make_delta(t) delta_t = make_delta(t)
delta_p = make_delta(p) delta_p = make_delta(p)
@@ -50,15 +50,15 @@ print "StepsPerCount: %.6f" % steps_per_count
delta_spc = np.zeros(len(t)) delta_spc = np.zeros(len(t))
for i in range(len(delta_spc)): for i in range(len(delta_spc)):
if delta_c[i] == 0: if delta_c[i] == 0:
delta_spc[i] = 0 delta_spc[i] = 0
else: else:
delta_spc[i] = delta_s[i] / delta_c[i] delta_spc[i] = delta_s[i] / delta_c[i]
if False: if False:
print len(t), len(delta_s), len(delta_spc) print len(t), len(delta_s), len(delta_spc)
print delta_spc print delta_spc
for i in range(len(t)): for i in range(len(t)):
print "%4d: %18.6f %18.6f %18.6f %18.6f %18.6f" % (i, t[i], delta_t[i], delta_s[i], delta_c[i], delta_spc[i]) print "%4d: %18.6f %18.6f %18.6f %18.6f %18.6f" % (i, t[i], delta_t[i], delta_s[i], delta_c[i], delta_spc[i])
ax1.plot(p, delta_spc - steps_per_count, c='r', label='delta steps per count') ax1.plot(p, delta_spc - steps_per_count, c='r', label='delta steps per count')
ax1.plot(p, (s - s[0])/(c - c[0]) - steps_per_count, c='b', label='steps / counts') ax1.plot(p, (s - s[0])/(c - c[0]) - steps_per_count, c='b', label='steps / counts')

View File

@@ -119,7 +119,7 @@ def load_dir(theDir):
if file.endswith((".swp", ".swo", ".hdf", "~", ".bck", ".pyc")): if file.endswith((".swp", ".swo", ".hdf", "~", ".bck", ".pyc")):
continue continue
if file.startswith(("core.", "SICServer")): if file.startswith(("core.", "SICServer")):
continue continue
if not file in myDirs: if not file in myDirs:
myDirs[file] = {} myDirs[file] = {}
myDirs[file][root[theLen:]] = {} myDirs[file][root[theLen:]] = {}
@@ -184,7 +184,7 @@ if __name__ == "__main__":
if key.endswith((".swp", ".swo", ".hdf", "~", ".bck", ".pyc")): if key.endswith((".swp", ".swo", ".hdf", "~", ".bck", ".pyc")):
continue continue
if key.startswith(("core.", "SICServer")): if key.startswith(("core.", "SICServer")):
continue continue
for entry in sorted(gmap[key]): for entry in sorted(gmap[key]):
if entry.endswith(("/data", "/log")): if entry.endswith(("/data", "/log")):
continue continue
@@ -202,7 +202,7 @@ if __name__ == "__main__":
if key.endswith((".swp", ".swo", ".hdf", "~", ".bck", ".pyc")): if key.endswith((".swp", ".swo", ".hdf", "~", ".bck", ".pyc")):
continue continue
if key.startswith(("core.", "SICServer")): if key.startswith(("core.", "SICServer")):
continue continue
for entry in sorted(gmap[key]): for entry in sorted(gmap[key]):
target = os.path.join(entry, key) target = os.path.join(entry, key)
#print "Looking in fmap for", os.path.join(entry, key) #print "Looking in fmap for", os.path.join(entry, key)
@@ -267,7 +267,7 @@ if __name__ == "__main__":
if key.endswith((".swp", ".swo", ".hdf", "~", ".bck", ".pyc")): if key.endswith((".swp", ".swo", ".hdf", "~", ".bck", ".pyc")):
continue continue
if key.startswith(("core.", "SICServer")): if key.startswith(("core.", "SICServer")):
continue continue
for entry in sorted(gmap[key]): for entry in sorted(gmap[key]):
target = os.path.join(entry, key) target = os.path.join(entry, key)
#print "Looking in fmap for", os.path.join(entry, key) #print "Looking in fmap for", os.path.join(entry, key)
@@ -327,7 +327,7 @@ if __name__ == "__main__":
if key.endswith((".swp", ".swo", ".hdf", "~", ".bck", ".pyc")): if key.endswith((".swp", ".swo", ".hdf", "~", ".bck", ".pyc")):
continue continue
if key.startswith(("core.", "SICServer")): if key.startswith(("core.", "SICServer")):
continue continue
for entry in sorted(gmap[key]): for entry in sorted(gmap[key]):
target = os.path.join(entry, key) target = os.path.join(entry, key)
#print "Looking in fmap for", os.path.join(entry, key) #print "Looking in fmap for", os.path.join(entry, key)
@@ -378,5 +378,3 @@ if __name__ == "__main__":
except: except:
pass pass
print "Copies (%d) in: %s" % (count, tgt) print "Copies (%d) in: %s" % (count, tgt)

View File

@@ -23,18 +23,18 @@ server_port = {
'quieck': 60014} 'quieck': 60014}
} }
inst_test_sockoffset = { inst_test_sockoffset = {
'echidna' : 0, 'echidna' : 0,
'wombat' : 100, 'wombat' : 100,
'kowari' : 200, 'kowari' : 200,
'dingo' : 300, 'dingo' : 300,
'quokka' : 400, 'quokka' : 400,
'platypus' : 500, 'platypus' : 500,
'pelican' : 600, 'pelican' : 600,
'taipan' : 700, 'taipan' : 700,
'lyrebird' : 800, 'lyrebird' : 800,
'kookaburra' : 900, 'kookaburra' : 900,
'bilby' : 1000, 'bilby' : 1000,
'emu' : 1100 'emu' : 1100
} }
deflt_dir = '/usr/local/sics/server' deflt_dir = '/usr/local/sics/server'
@@ -194,27 +194,27 @@ def main(**kwargs):
cmd_grp.add_argument('cmd', choices=['start', 'stop', 'status']) cmd_grp.add_argument('cmd', choices=['start', 'stop', 'status'])
# Advanced arguments # Advanced arguments
adv_grp.add_argument('-c', '--config', help= args_config_help % inst_config, adv_grp.add_argument('-c', '--config', help= args_config_help % inst_config,
default = inst_config ) default = inst_config )
adv_grp.add_argument('-d', '--dir', help=args_dir_help % deflt_dir, adv_grp.add_argument('-d', '--dir', help=args_dir_help % deflt_dir,
default = deflt_dir) default = deflt_dir)
adv_grp.add_argument('-t', '--test', adv_grp.add_argument('-t', '--test',
choices=['fullsim', 'fakedev', 'scriptval'], choices=['fullsim', 'fakedev', 'scriptval'],
help=args_dir_help % deflt_test, default=deflt_test) help=args_dir_help % deflt_test, default=deflt_test)
adv_grp.add_argument('-u', '--user', help= args_user_help % deflt_user, adv_grp.add_argument('-u', '--user', help= args_user_help % deflt_user,
default = deflt_user ) default = deflt_user )
adv_grp.add_argument('--sockoffset', adv_grp.add_argument('--sockoffset',
help= args_sockoffset_help % deflt_sockoffset, help= args_sockoffset_help % deflt_sockoffset,
choices=inst_test_sockoffset.keys(), choices=inst_test_sockoffset.keys(),
default = deflt_sockoffset ) default = deflt_sockoffset )
exc_grp = parser.add_mutually_exclusive_group() exc_grp = parser.add_mutually_exclusive_group()
exc_grp.add_argument('--sicsonly', help= args_sicsonly_help, exc_grp.add_argument('--sicsonly', help= args_sicsonly_help,
action='store_true', default=False) action='store_true', default=False)
exc_grp.add_argument('--scriptval', help= args_scriptval_help, exc_grp.add_argument('--scriptval', help= args_scriptval_help,
action='store_true', default=False) action='store_true', default=False)
exc_grp.add_argument('--dev', exc_grp.add_argument('--dev',
help= args_dir_help % (server_port['sics']['server'] + help= args_dir_help % (server_port['sics']['server'] +
inst_test_sockoffset[inst_name]), inst_test_sockoffset[inst_name]),
action='store_true') action='store_true')
args = parser.parse_args() args = parser.parse_args()
# By default don't launch script validator in development environments. # By default don't launch script validator in development environments.
if args.dev: if args.dev:

View File

@@ -1,5 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim: tabstop=8 softtabstop=2 shiftwidth=2 nocin si et ft=python # vim: tabstop=8 softtabstop=4 shiftwidth=4 nocin si et ft=python
# View Screen has 3 parts # View Screen has 3 parts
# (Instrument Configuration), (Configuration Options), (Option Implementation) # (Instrument Configuration), (Configuration Options), (Option Implementation)
@@ -30,192 +30,192 @@ from collections import defaultdict
class InstConfigData: class InstConfigData:
msg_index = 4 msg_index = 4
# configuration_dict: dict of instrument configurations as defined below, # configuration_dict: dict of instrument configurations as defined below,
# {configname: {'enabled':T/F, 'cascade_list':[(option, dflt_imp)]} } # {configname: {'enabled':T/F, 'cascade_list':[(option, dflt_imp)]} }
configuration_dict = defaultdict(dict) configuration_dict = defaultdict(dict)
# opt_dict: dict of configuration options as defined below, # opt_dict: dict of configuration options as defined below,
# {optname:{'enabled': T/F/Always, 'imptype':optype, 'selected_imp':dflt}} # {optname:{'enabled': T/F/Always, 'imptype':optype, 'selected_imp':dflt}}
opt_dict = defaultdict(dict) opt_dict = defaultdict(dict)
# imp_dict: dict of implementations indexed by optype, # imp_dict: dict of implementations indexed by optype,
# {optype: [impname] } # {optype: [impname] }
imp_dict = defaultdict(list) imp_dict = defaultdict(list)
def __init__(self): def __init__(self):
return return
def __get_configurations(self): def __get_configurations(self):
for s in self.file_parser.sections(): for s in self.file_parser.sections():
cascade_list = [] cascade_list = []
if self.file_parser.has_option(s, 'cascade'): if self.file_parser.has_option(s, 'cascade'):
enabled = self.file_parser.get(s, 'enabled') enabled = self.file_parser.get(s, 'enabled')
for cascade_str in self.file_parser.get(s,'cascade').split(','): for cascade_str in self.file_parser.get(s,'cascade').split(','):
cascade_list.append(tuple(cascade_str.split(':'))) cascade_list.append(tuple(cascade_str.split(':')))
if enabled.lower() in ['true','always']: if enabled.lower() in ['true','always']:
stateval = True stateval = True
else: else:
stateval = False stateval = False
self.configuration_dict[s]['enabled'] = stateval self.configuration_dict[s]['enabled'] = stateval
self.configuration_dict[s]['cascade_list'] = cascade_list self.configuration_dict[s]['cascade_list'] = cascade_list
def __get_options(self): def __get_options(self):
for s in self.file_parser.sections(): for s in self.file_parser.sections():
if self.file_parser.has_option(s, 'implementation'): if self.file_parser.has_option(s, 'implementation'):
selected_imp = self.file_parser.get(s, 'implementation') selected_imp = self.file_parser.get(s, 'implementation')
imptype = self.file_parser.get(s, 'optype') imptype = self.file_parser.get(s, 'optype')
enabled = self.file_parser.get(s, 'enabled').lower() enabled = self.file_parser.get(s, 'enabled').lower()
if enabled == 'always': if enabled == 'always':
stateval = True stateval = True
permanent = True permanent = True
elif enabled == 'true': elif enabled == 'true':
stateval = True stateval = True
permanent = False permanent = False
else: else:
stateval = False stateval = False
permanent = False permanent = False
self.opt_dict[s]['enabled'] = stateval self.opt_dict[s]['enabled'] = stateval
self.opt_dict[s]['permanent'] = permanent self.opt_dict[s]['permanent'] = permanent
self.opt_dict[s]['imptype'] = imptype self.opt_dict[s]['imptype'] = imptype
self.opt_dict[s]['selected_imp'] = selected_imp self.opt_dict[s]['selected_imp'] = selected_imp
def __get_implementations(self): def __get_implementations(self):
for s in self.file_parser.sections(): for s in self.file_parser.sections():
if self.file_parser.has_option(s, 'imptype'): if self.file_parser.has_option(s, 'imptype'):
key = self.file_parser.get(s, 'imptype') key = self.file_parser.get(s, 'imptype')
self.imp_dict[key].append(s) self.imp_dict[key].append(s)
def read_config_file(self, config_filename): def read_config_file(self, config_filename):
self.config_filename = config_filename self.config_filename = config_filename
self.file_parser = ConfigParser.SafeConfigParser() self.file_parser = ConfigParser.SafeConfigParser()
self.file_parser.read(config_filename) self.file_parser.read(config_filename)
self.__get_options() self.__get_options()
self.__get_implementations() self.__get_implementations()
self.__get_configurations() self.__get_configurations()
return return
def backup_files(self): def backup_files(self):
for idx in range(8, 0, -1): for idx in range(8, 0, -1):
if os.path.exists(self.config_filename + "." + str(idx)): if os.path.exists(self.config_filename + "." + str(idx)):
os.rename(self.config_filename + "." + str(idx), os.rename(self.config_filename + "." + str(idx),
self.config_filename + "." + str(idx + 1)) self.config_filename + "." + str(idx + 1))
if os.path.exists(self.config_filename): if os.path.exists(self.config_filename):
os.rename(self.config_filename, self.config_filename + ".1") os.rename(self.config_filename, self.config_filename + ".1")
def write_config_file(self): def write_config_file(self):
for item,dict in self.opt_dict.iteritems(): for item,dict in self.opt_dict.iteritems():
if self.file_parser.get(item, 'enabled').lower() == 'always': if self.file_parser.get(item, 'enabled').lower() == 'always':
enabled = 'Always' enabled = 'Always'
else: else:
enabled = dict['enabled'].__str__() enabled = dict['enabled'].__str__()
self.file_parser.set(item, 'enabled', enabled) self.file_parser.set(item, 'enabled', enabled)
self.file_parser.set(item, 'implementation', dict['selected_imp']) self.file_parser.set(item, 'implementation', dict['selected_imp'])
self.file_parser.set(item, 'optype', dict['imptype']) self.file_parser.set(item, 'optype', dict['imptype'])
for item,dict in self.configuration_dict.iteritems(): for item,dict in self.configuration_dict.iteritems():
enabled = dict['enabled'].__str__() enabled = dict['enabled'].__str__()
self.file_parser.set(item, 'enabled', enabled) self.file_parser.set(item, 'enabled', enabled)
with open(self.config_filename,'w') as cfile: with open(self.config_filename,'w') as cfile:
for section in sorted(self.file_parser.sections()): for section in sorted(self.file_parser.sections()):
cfile.write("[%s]\n" % section) cfile.write("[%s]\n" % section)
for option in sorted(self.file_parser.options(section)): for option in sorted(self.file_parser.options(section)):
cfile.write("%s = %s\n" % (option, self.file_parser.get(section, option))) cfile.write("%s = %s\n" % (option, self.file_parser.get(section, option)))
cfile.write("\n") cfile.write("\n")
#self.file_parser.write(cfile) #self.file_parser.write(cfile)
def cf_statechange(self, checkbox, new_state, udat=None): def cf_statechange(self, checkbox, new_state, udat=None):
cfg_id = checkbox.get_label() cfg_id = checkbox.get_label()
self.configuration_dict[cfg_id]['enabled'] = new_state self.configuration_dict[cfg_id]['enabled'] = new_state
def opt_statechange(self, checkbox, new_state, udat=None): def opt_statechange(self, checkbox, new_state, udat=None):
opt = checkbox.get_label() opt = checkbox.get_label()
dbg.msg(3, 'InstConfigData:opt_statechange({0},{1},{2})'.format(opt, new_state, udat)) dbg.msg(3, 'InstConfigData:opt_statechange({0},{1},{2})'.format(opt, new_state, udat))
self.opt_dict[opt]['enabled'] = new_state self.opt_dict[opt]['enabled'] = new_state
def imp_statechange(self, button, new_state, opt): def imp_statechange(self, button, new_state, opt):
selected_imp = button.get_label() selected_imp = button.get_label()
dbg.msg(self.msg_index, 'InstConfigData:imp_statechange({0},{1},{2})'.format(selected_imp, new_state, opt)) dbg.msg(self.msg_index, 'InstConfigData:imp_statechange({0},{1},{2})'.format(selected_imp, new_state, opt))
self.msg_index = (self.msg_index - 3) % 2 + 4 self.msg_index = (self.msg_index - 3) % 2 + 4
if new_state == True: if new_state == True:
self.opt_dict[opt]['selected_imp'] = selected_imp self.opt_dict[opt]['selected_imp'] = selected_imp
## TODO Configuration Editor ## TODO Configuration Editor
## Configuration Viewer ## Configuration Viewer
Palette = [ Palette = [
('body', 'dark cyan', '', 'standout'), ('body', 'dark cyan', '', 'standout'),
('focus', 'dark red', '', 'standout'), ('focus', 'dark red', '', 'standout'),
('head', 'light red', 'black'), ('head', 'light red', 'black'),
] ]
#FIXME Replace the [(name,stateval)] list imp_states with list of item names #FIXME Replace the [(name,stateval)] list imp_states with list of item names
class RadioButtonListWalker(urwid.SimpleListWalker): class RadioButtonListWalker(urwid.SimpleListWalker):
button_dict = {} button_dict = {}
def __init__(self, item_states, on_state_change=None, user_data=None): def __init__(self, item_states, on_state_change=None, user_data=None):
radio_grp = [] radio_grp = []
mapped_rb_list = [] mapped_rb_list = []
for item,stateval in item_states: for item,stateval in item_states:
rb = urwid.RadioButton(radio_grp, item, state=stateval, on_state_change=on_state_change, user_data=user_data) rb = urwid.RadioButton(radio_grp, item, state=stateval, on_state_change=on_state_change, user_data=user_data)
self.button_dict[item] = rb self.button_dict[item] = rb
mapped_rb = urwid.AttrMap(rb, 'body', 'focus') mapped_rb = urwid.AttrMap(rb, 'body', 'focus')
mapped_rb_list.append(mapped_rb) mapped_rb_list.append(mapped_rb)
super(RadioButtonListWalker, self).__init__(mapped_rb_list) super(RadioButtonListWalker, self).__init__(mapped_rb_list)
return return
class CheckBoxListWalker(urwid.SimpleListWalker): class CheckBoxListWalker(urwid.SimpleListWalker):
button_dict = {} button_dict = {}
def __init__(self, item_states, on_state_change = None, user_data = None): def __init__(self, item_states, on_state_change = None, user_data = None):
mapped_cb_list = [] mapped_cb_list = []
for item,stateval in item_states: for item,stateval in item_states:
cb = urwid.CheckBox(item, state = stateval, on_state_change = on_state_change, user_data = user_data) cb = urwid.CheckBox(item, state = stateval, on_state_change = on_state_change, user_data = user_data)
self.button_dict[item] = cb self.button_dict[item] = cb
mapped_cb = urwid.AttrMap(cb, 'body', 'focus') mapped_cb = urwid.AttrMap(cb, 'body', 'focus')
mapped_cb_list.append(mapped_cb) mapped_cb_list.append(mapped_cb)
super(CheckBoxListWalker, self).__init__(mapped_cb_list) super(CheckBoxListWalker, self).__init__(mapped_cb_list)
return return
# Selects listwalker to display for ImpListBox on focus # Selects listwalker to display for ImpListBox on focus
class OptionListWalker(CheckBoxListWalker): class OptionListWalker(CheckBoxListWalker):
def __init__(self, opt_dict, statechange_cb): def __init__(self, opt_dict, statechange_cb):
urwid.register_signal(OptionListWalker, ['focus_change']) urwid.register_signal(OptionListWalker, ['focus_change'])
item_states = [(i,d['enabled']) for i,d in opt_dict.iteritems()] item_states = [(i,d['enabled']) for i,d in opt_dict.iteritems()]
item_states.sort() item_states.sort()
super(OptionListWalker, self).__init__(item_states, statechange_cb) super(OptionListWalker, self).__init__(item_states, statechange_cb)
return return
def set_focus(self, pos): def set_focus(self, pos):
dbg.msg(0, 'OptionListWalker:set_focus({0}) -> emit focus_change'.format(pos)) dbg.msg(0, 'OptionListWalker:set_focus({0}) -> emit focus_change'.format(pos))
urwid.emit_signal(self, 'focus_change', pos) urwid.emit_signal(self, 'focus_change', pos)
return super(OptionListWalker, self).set_focus(pos) return super(OptionListWalker, self).set_focus(pos)
# ClosedListBox implements a ListBox which prevents selection outside of the # ClosedListBox implements a ListBox which prevents selection outside of the
# list using the 'up' or 'down' keys # list using the 'up' or 'down' keys
class ClosedListBox(urwid.ListBox): class ClosedListBox(urwid.ListBox):
def keypress(self, size, key): def keypress(self, size, key):
"""Prevents navigating outside of a ClosedListBox with the up and down arrow keys""" """Prevents navigating outside of a ClosedListBox with the up and down arrow keys"""
pos = self.get_focus()[1] pos = self.get_focus()[1]
ll = len(self.body) ll = len(self.body)
if (pos <= 0 and key == 'up') or (pos >= ll-1 and key == 'down'): if (pos <= 0 and key == 'up') or (pos >= ll-1 and key == 'down'):
return return
else: else:
return super(ClosedListBox, self).keypress(size, key) return super(ClosedListBox, self).keypress(size, key)
# List of Checkboxes # List of Checkboxes
class OptionListBox(ClosedListBox): class OptionListBox(ClosedListBox):
def __init__(self, listwalker): def __init__(self, listwalker):
super(OptionListBox, self).__init__(listwalker) super(OptionListBox, self).__init__(listwalker)
return return
# Contains OptionListWalker dict indexed by option # Contains OptionListWalker dict indexed by option
# Contains ImpListBox # Contains ImpListBox
@@ -223,14 +223,14 @@ class OptionListBox(ClosedListBox):
# Tracks selected implementation for each option # Tracks selected implementation for each option
# and sets selection on ImpListBox # and sets selection on ImpListBox
class InstConfigManager: class InstConfigManager:
cf_msg_index = 8 cf_msg_index = 8
options = [] options = []
imp_lw_dict = {} imp_lw_dict = {}
def __init__(self, cfdat): def __init__(self, cfdat):
self.cfdat = cfdat self.cfdat = cfdat
urwid.register_signal(InstConfigManager, ['focus_change']) urwid.register_signal(InstConfigManager, ['focus_change'])
for opt,dict in cfdat.opt_dict.iteritems(): for opt,dict in cfdat.opt_dict.iteritems():
self.options.append((opt, dict['imptype'])) self.options.append((opt, dict['imptype']))
# imp_items = [] # imp_items = []
# for imp in cfdat.imp_dict[dict['imptype']]: # for imp in cfdat.imp_dict[dict['imptype']]:
# if imp == dict['selected_imp']: # if imp == dict['selected_imp']:
@@ -240,172 +240,172 @@ class InstConfigManager:
# imp_items.sort() # imp_items.sort()
# self.imp_lw_dict[opt] = RadioButtonListWalker(imp_items, on_state_change=self.imp_statechange, user_data=opt) # self.imp_lw_dict[opt] = RadioButtonListWalker(imp_items, on_state_change=self.imp_statechange, user_data=opt)
self.options.sort() self.options.sort()
# imp_items.sort() # imp_items.sort()
firstopt = self.options[0][0] firstopt = self.options[0][0]
self.imp_lw = self.__gen_imp_listwalker(firstopt) self.imp_lw = self.__gen_imp_listwalker(firstopt)
# self.imp_lw = RadioButtonListWalker([], on_state_change=self.imp_statechange, user_data=firstopt) # self.imp_lw = RadioButtonListWalker([], on_state_change=self.imp_statechange, user_data=firstopt)
self.option_lw = OptionListWalker(cfdat.opt_dict, self.opt_statechange) self.option_lw = OptionListWalker(cfdat.opt_dict, self.opt_statechange)
self.imp_lb = ImpListBox(self.imp_lw) self.imp_lb = ImpListBox(self.imp_lw)
urwid.connect_signal(self.option_lw, 'focus_change', self.update_imp_lb) urwid.connect_signal(self.option_lw, 'focus_change', self.update_imp_lb)
item_states = [(i,d['enabled']) for i,d in cf_dat.configuration_dict.iteritems()] item_states = [(i,d['enabled']) for i,d in cf_dat.configuration_dict.iteritems()]
item_states.sort() item_states.sort()
self.cfg_lw = RadioButtonListWalker(item_states, on_state_change = self.cf_statechange) self.cfg_lw = RadioButtonListWalker(item_states, on_state_change = self.cf_statechange)
self.config_lb = OptionListBox(self.cfg_lw) self.config_lb = OptionListBox(self.cfg_lw)
self.opt_lb = OptionListBox(self.option_lw) self.opt_lb = OptionListBox(self.option_lw)
self.opt_lb.set_focus(0) self.opt_lb.set_focus(0)
return return
def __gen_imp_listwalker(self, opt): def __gen_imp_listwalker(self, opt):
imp_items = [] imp_items = []
dict = self.cfdat.opt_dict[opt] dict = self.cfdat.opt_dict[opt]
for imp in self.cfdat.imp_dict[dict['imptype']]: for imp in self.cfdat.imp_dict[dict['imptype']]:
if imp == dict['selected_imp']: if imp == dict['selected_imp']:
imp_items.append((imp, True)) imp_items.append((imp, True))
else: else:
imp_items.append((imp, False)) imp_items.append((imp, False))
imp_items.sort() imp_items.sort()
return RadioButtonListWalker(imp_items, on_state_change=self.imp_statechange, user_data=opt) return RadioButtonListWalker(imp_items, on_state_change=self.imp_statechange, user_data=opt)
def cf_statechange(self, button, new_state, udat=None): def cf_statechange(self, button, new_state, udat=None):
self.cfdat.cf_statechange(button, new_state, udat) self.cfdat.cf_statechange(button, new_state, udat)
b = button.get_label() b = button.get_label()
cascade = self.cfdat.configuration_dict[b]['cascade_list'] cascade = self.cfdat.configuration_dict[b]['cascade_list']
if new_state == True: if new_state == True:
for opt in self.cfdat.opt_dict.keys(): for opt in self.cfdat.opt_dict.keys():
if self.cfdat.opt_dict[opt]['permanent'] == False: if self.cfdat.opt_dict[opt]['permanent'] == False:
self.option_lw.button_dict[opt].set_state(False) self.option_lw.button_dict[opt].set_state(False)
for opt,imp in cascade: for opt,imp in cascade:
self.option_lw.button_dict[opt].set_state(True) self.option_lw.button_dict[opt].set_state(True)
imp_lw = self.__gen_imp_listwalker(opt) imp_lw = self.__gen_imp_listwalker(opt)
imp_lw.button_dict[imp].set_state(True) imp_lw.button_dict[imp].set_state(True)
currpos = self.opt_lb.get_focus()[1] currpos = self.opt_lb.get_focus()[1]
self.opt_lb.set_focus(currpos) self.opt_lb.set_focus(currpos)
dbg.msg(self.cf_msg_index, 'InstConfigManager:cf_statechange({0},{1},{2}), cascade = {3}'.format(b, new_state, udat, cascade)) dbg.msg(self.cf_msg_index, 'InstConfigManager:cf_statechange({0},{1},{2}), cascade = {3}'.format(b, new_state, udat, cascade))
self.cf_msg_index = (self.cf_msg_index - 7) % 2 + 8 self.cf_msg_index = (self.cf_msg_index - 7) % 2 + 8
return return
def opt_statechange(self, button, new_state, udat=None): def opt_statechange(self, button, new_state, udat=None):
self.cfdat.opt_statechange(button, new_state, udat) self.cfdat.opt_statechange(button, new_state, udat)
return return
def imp_statechange(self, button, new_state, udat=None): def imp_statechange(self, button, new_state, udat=None):
self.cfdat.imp_statechange(button, new_state, udat) self.cfdat.imp_statechange(button, new_state, udat)
return return
def update_imp_lb(self, pos): def update_imp_lb(self, pos):
optname = self.options[pos][0] optname = self.options[pos][0]
optype = self.options[pos][1] optype = self.options[pos][1]
mstr = 'InstConfigManager:update_imp_lb({0}) -> select {1}'.format(pos, optype) mstr = 'InstConfigManager:update_imp_lb({0}) -> select {1}'.format(pos, optype)
dbg.msg(1, mstr) dbg.msg(1, mstr)
self.imp_lw = self.__gen_imp_listwalker(optname) self.imp_lw = self.__gen_imp_listwalker(optname)
self.imp_lb.use_listwalker(self.imp_lw) self.imp_lb.use_listwalker(self.imp_lw)
return return
# List of RadioButtons # List of RadioButtons
class ImpListBox(ClosedListBox): class ImpListBox(ClosedListBox):
def __init__(self, listwalker): def __init__(self, listwalker):
super(ImpListBox, self).__init__(listwalker) super(ImpListBox, self).__init__(listwalker)
return return
def use_listwalker(self, liswalker): def use_listwalker(self, liswalker):
self.body.contents[:] = liswalker self.body.contents[:] = liswalker
return return
class InstConfigView(urwid.Pile): class InstConfigView(urwid.Pile):
def __init__(self, cf_dat, cf_man, dbmsg): def __init__(self, cf_dat, cf_man, dbmsg):
self.cf_dat = cf_dat self.cf_dat = cf_dat
self.cf_man = cf_man self.cf_man = cf_man
option_ListBoxes = [ option_ListBoxes = [
self.cf_man.config_lb, self.cf_man.config_lb,
self.cf_man.opt_lb, self.cf_man.opt_lb,
self.cf_man.imp_lb, self.cf_man.imp_lb,
dbmsg] dbmsg]
super(InstConfigView, self).__init__(option_ListBoxes) super(InstConfigView, self).__init__(option_ListBoxes)
return return
def keyinput(self, key): def keyinput(self, key):
if key == 'meta q': if key == 'meta q':
raise urwid.ExitMainLoop() raise urwid.ExitMainLoop()
elif key == 'w': elif key == 'w':
self.cf_dat.backup_files() self.cf_dat.backup_files()
self.cf_dat.write_config_file() self.cf_dat.write_config_file()
elif key in ['right', 'tab']: elif key in ['right', 'tab']:
if self.get_focus() == self.cf_man.config_lb: if self.get_focus() == self.cf_man.config_lb:
self.set_focus(self.cf_man.opt_lb) self.set_focus(self.cf_man.opt_lb)
elif self.get_focus() == self.cf_man.opt_lb: elif self.get_focus() == self.cf_man.opt_lb:
self.set_focus(self.cf_man.imp_lb) self.set_focus(self.cf_man.imp_lb)
else: else:
self.set_focus(self.cf_man.config_lb) self.set_focus(self.cf_man.config_lb)
elif key in ['left', 'shift tab']: elif key in ['left', 'shift tab']:
if self.get_focus() == self.cf_man.config_lb: if self.get_focus() == self.cf_man.config_lb:
self.set_focus(self.cf_man.imp_lb) self.set_focus(self.cf_man.imp_lb)
elif self.get_focus() == self.cf_man.opt_lb: elif self.get_focus() == self.cf_man.opt_lb:
self.set_focus(self.cf_man.config_lb) self.set_focus(self.cf_man.config_lb)
else: else:
self.set_focus(self.cf_man.opt_lb) self.set_focus(self.cf_man.opt_lb)
return return
import pdb import pdb
class DEBUG: class DEBUG:
msgTextDict = {} msgTextDict = {}
msglist = [] msglist = []
msg_ids = [ 'm0', 'm1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9' ] msg_ids = [ 'm0', 'm1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9' ]
def __init__(self, enabled=False): def __init__(self, enabled=False):
self.enabled = enabled self.enabled = enabled
if enabled: if enabled:
for msgID in self.msg_ids: for msgID in self.msg_ids:
msgText = urwid.Text(u'Space for message {0}'.format(msgID)) msgText = urwid.Text(u'Space for message {0}'.format(msgID))
self.msgTextDict[msgID] = msgText self.msgTextDict[msgID] = msgText
self.msglist.append(urwid.AttrMap(msgText, 'body', 'focus')) self.msglist.append(urwid.AttrMap(msgText, 'body', 'focus'))
mlw = urwid.SimpleListWalker(self.msglist) mlw = urwid.SimpleListWalker(self.msglist)
self.mlb = urwid.ListBox(mlw) self.mlb = urwid.ListBox(mlw)
return return
def msg(self, index, msg): def msg(self, index, msg):
if self.enabled: if self.enabled:
mid = self.msg_ids[index] mid = self.msg_ids[index]
self.msgTextDict[mid].set_text(msg) self.msgTextDict[mid].set_text(msg)
return return
dbg = DEBUG(enabled=True) dbg = DEBUG(enabled=True)
def main(config_ini): def main(config_ini):
global cf_dat, cf_man, cf_viewer global cf_dat, cf_man, cf_viewer
# Make configuration data # Make configuration data
cf_dat = InstConfigData() cf_dat = InstConfigData()
cf_dat.read_config_file(config_ini) cf_dat.read_config_file(config_ini)
# Make configuration editor # Make configuration editor
cf_man = InstConfigManager(cf_dat) cf_man = InstConfigManager(cf_dat)
# Make configuration viewer # Make configuration viewer
cf_viewer = InstConfigView(cf_dat, cf_man, dbg.mlb) cf_viewer = InstConfigView(cf_dat, cf_man, dbg.mlb)
urwid.MainLoop(cf_viewer, Palette, unhandled_input=cf_viewer.keyinput).run() urwid.MainLoop(cf_viewer, Palette, unhandled_input=cf_viewer.keyinput).run()
return return
if '__main__' == __name__: if '__main__' == __name__:
default_ini = "/usr/local/sics/sics_config.ini" default_ini = "/usr/local/sics/sics_config.ini"
parser = argparse.ArgumentParser(description = """ parser = argparse.ArgumentParser(description = """
Edit a configuration (*.ini) file using python urwid widget library. Edit a configuration (*.ini) file using python urwid widget library.
Options can be enabled or disabled with mouse or spacebar. Options can be enabled or disabled with mouse or spacebar.
Navigate with arrow keys. Navigate with arrow keys.
Press W to save. Press W to save.
Press Alt-Q to quit. Press Alt-Q to quit.
The default configuration filename is %s. The default configuration filename is %s.
""" % default_ini) """ % default_ini)
parser.add_argument("-v", "--verbose", action="store_true", help="give more info in the footer") parser.add_argument("-v", "--verbose", action="store_true", help="give more info in the footer")
parser.add_argument("path", nargs="?", default = default_ini, help="name of file to edit [%s]" % default_ini) parser.add_argument("path", nargs="?", default = default_ini, help="name of file to edit [%s]" % default_ini)
args = parser.parse_args() args = parser.parse_args()
default_ini = os.path.abspath(args.path) default_ini = os.path.abspath(args.path)
main(default_ini) main(default_ini)