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):
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"}
print "Camera get/set commands: ", self.camState.keys()
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()
def getCmd(self, par):
if par in self.camState:
self.sendLine(self.camState[par])
else:
self.sendLine("ERROR: Unknown parameter, " + par)
if par in self.camState:
self.sendLine(self.camState[par])
else:
self.sendLine("ERROR: Unknown parameter, " + par)
def setCmd(self, s):
par,val = s.split(',',1)
if par in self.camState:
self.camState[par] = val
self.sendLine("OK")
else:
self.sendLine("ERROR: Unknown parameter, " + par)
par,val = s.split(',',1)
if par in self.camState:
self.camState[par] = val
self.sendLine("OK")
else:
self.sendLine("ERROR: Unknown parameter, " + par)
def takeCmd(self, cmd):
if cmd == 'shot':
self.sendLine("OK")
elif cmd == 'multishot':
self.sendLine("OK")
else:
self.sendLine("ERROR:1")
if cmd == 'shot':
self.sendLine("OK")
elif cmd == 'multishot':
self.sendLine("OK")
else:
self.sendLine("ERROR:1")
def clearCmd(self, par):
if par == 'meta':
self.sendLine("OK")
else:
self.sendLine("ERROR:1")
if par == 'meta':
self.sendLine("OK")
else:
self.sendLine("ERROR:1")
def lineReceived(self, line):
print "RECEIVED: " + line
cmd = line.split()
if len(cmd) == 0:
self.sendLine(line)
return
if cmd[0] == "get":
self.getCmd(cmd[1])
elif cmd[0] =="set":
if len(cmd) == 1:
self.sendLine("ERROR:2")
return
self.setCmd(cmd[1])
elif cmd[0] == "take":
if len(cmd) == 1:
self.sendLine("ERROR:2")
return
self.takeCmd(cmd[1])
elif cmd[0] == "clear":
if len(cmd) == 1:
self.sendLine("ERROR:2")
return
self.clearCmd(cmd[1])
else:
self.sendLine("ERROR: Unknown command, " + line)
print "RECEIVED: " + line
cmd = line.split()
if len(cmd) == 0:
self.sendLine(line)
return
if cmd[0] == "get":
self.getCmd(cmd[1])
elif cmd[0] =="set":
if len(cmd) == 1:
self.sendLine("ERROR:2")
return
self.setCmd(cmd[1])
elif cmd[0] == "take":
if len(cmd) == 1:
self.sendLine("ERROR:2")
return
self.takeCmd(cmd[1])
elif cmd[0] == "clear":
if len(cmd) == 1:
self.sendLine("ERROR:2")
return
self.clearCmd(cmd[1])
else:
self.sendLine("ERROR: Unknown command, " + line)
def main():

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -9,11 +9,11 @@ import matplotlib.pyplot as plt
import argparse
def make_delta(q):
delta_q = np.zeros(len(q))
delta_q[0] = 0.0
for i in range(1, len(q)):
delta_q[i] = q[i] - q[i - 1]
return delta_q
delta_q = np.zeros(len(q))
delta_q[0] = 0.0
for i in range(1, len(q)):
delta_q[i] = q[i] - q[i - 1]
return delta_q
parser = argparse.ArgumentParser()
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
if False:
print dir(data)
#print data.T
print len(data)
print len(t)
print dir(data)
#print data.T
print len(data)
print len(t)
delta_t = make_delta(t)
delta_p = make_delta(p)
@@ -50,15 +50,15 @@ print "StepsPerCount: %.6f" % steps_per_count
delta_spc = np.zeros(len(t))
for i in range(len(delta_spc)):
if delta_c[i] == 0:
delta_spc[i] = 0
else:
delta_spc[i] = delta_s[i] / delta_c[i]
if delta_c[i] == 0:
delta_spc[i] = 0
else:
delta_spc[i] = delta_s[i] / delta_c[i]
if False:
print len(t), len(delta_s), len(delta_spc)
print delta_spc
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 len(t), len(delta_s), len(delta_spc)
print delta_spc
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])
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')

View File

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

View File

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

View File

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