def _cmdCallback(self, cmdVar=None): """!Command callback """ # call the callback, if justified: # function exists, last message code matches and command does not have a reportable failure if (self.callFunc is not None) and ( self.cmdVar.lastCode in self.callCodes) and not self._reportFailure: # either the command succeeded, or checking for success is disabled try: self.callFunc(self.cmdVar) except Exception as e: # callback failed; fail this command traceback.print_exc(file=sys.stderr) # is this always needed? Timer(0, self._finish, e) return if self.cmdVar.isDone: if self._reportFailure: try: reason = self.cmdVar.lastReply.string except Exception: reason = "why? (no lastReply)" msgStr = "Command %s failed: %s" % (self.cmdVar, reason) print(msgStr) Timer(0, self._finish, RuntimeError(msgStr)) else: print("Command %s done" % (self.cmdVar, )) Timer(0, self._finish)
def __init__(self, endpoint, connCallback = None, stateCallback = None, sockReadCallback = None, sockStateCallback = None, name = "", ): """Construct a socket server Inputs: - endpoint: a Twisted endpoint, e.g. twisted.internet.endpoints.TCP4ClientEndpoint - connCallback: function to call when a client connects; it receives the following arguments: - sock, a Socket - stateCallback: function to call when server changes state; it receives one argument: this server - sockReadCallback: function for each server socket to call when it receives data; See BaseSocket.addReadCallback for details - sockStateCallback: function for each server socket to call when it receives data See BaseSocket.addStateCallback for details - name: a string to identify this socket; strictly optional """ self._endpoint = endpoint self._protocol = None self._closeDeferred = None BaseServer.__init__(self, connCallback = connCallback, stateCallback = stateCallback, sockReadCallback = sockReadCallback, sockStateCallback = sockStateCallback, name = name, ) self._numConn = 0 Timer(0, self._startListening) # let device be fully constructed before listening
def __init__(self, dev, userCmd, timeLim): """!Start connecting a device @param[in] dev device @param[in] userCmd user command associated with the connection, or None @param[in] timeLim time limit (sec) to make this connection """ self.dev = dev self._timeLim = timeLim self.userCmd = expandUserCmd(userCmd) self._connTimer = Timer() self._addedConnCallback = False if self.dev.isConnected and self.dev.conn.isConnected: # already done; don't send init self.finish() return self.dev._ignoreConnCallback = True self.dev.setState(self.dev.Connecting) self.dev.conn.addStateCallback(self.connCallback) self._addedConnCallback = True if self.dev.conn.mayConnect: self.dev.conn.connect(timeLim=timeLim) else: if self._timeLim: # start timer for the connection that is occurring now self._connTimer.start(self._timeLim, self.finish, "timed out waiting for connection")
def __init__( self, cmdStr, userID=0, cmdID=0, callFunc=None, timeLim=None, ): """Construct a BaseCmd @param[in] cmdStr command string @param[in] userID user ID number @param[in] cmdID command ID number @param[in] callFunc function to call when command changes state; receives one argument: this command @param[in] timeLim time limit for command (sec); if None or 0 then no time limit """ self._cmdStr = cmdStr self.userID = int(userID) self.cmdID = int(cmdID) self._state = self.Ready self._textMsg = "" self._hubMsg = "" self._cmdToTrack = None self._linkedCommands = [] self._parentCmd = None self._writeToUsers = None # set by baseActor.ExpandCommand # set by baseActor.newCmd to flag this as a command created # from socket input self.userCommanded = False self._timeoutTimer = Timer() self.setTimeLimit(timeLim) RO.AddCallback.BaseMixin.__init__(self, callFunc)
def __init__(self, dev, userCmd, timeLim): """!Start disconnecting a device """ self.dev = dev self.userCmd = expandUserCmd(userCmd) self._timeLim = timeLim self._connTimer = Timer() self._addedConnCallback = False if self.dev.conn.isDisconnected: if self.dev.state != self.dev.Disconnected: self.dev.setState(self.dev.Disconnected, "socket disconnected") if not self.userCmd.isDone: self.userCmd.setState(self.userCmd.Done) return self.dev._ignoreConnCallback = True if self.dev.state != self.dev.Disconnected: self.dev.setState(self.dev.Disconnecting) if self.dev.conn.isConnected: initUserCmd = UserCmd(cmdStr="Init via device.DisconnectDevice", callFunc=self.initCallback, timeLim=timeLim) self.dev.init(userCmd=initUserCmd, timeLim=timeLim, getStatus=False) else: # not fully connected, so cannot send init, but not fully disconnected yet, so finish disconnecting textMsg = "%s connection state=%s; cannot initialize before disconnecting" % ( self.dev.name, self.dev.conn.state) self.dev.writeToUsers("w", "text=%s" % (quoteStr(textMsg), )) self.startDisconnect() return
def runQueue(self): if self.isBusy: return if self.cmdQueue: self.currCmdWrapper = self.cmdQueue.popleft() self.currCmdWrapper.setStateFunc(self._cmdWrapperDone) # self.currCmdWrapper.startCmd(self.dispatcher) Timer(0, self.currCmdWrapper.startCmd, self.dispatcher)
def addInOrder(): if not cmdStrListCopy: # all commands have been added to the queue self.commandsLeft = False return else: cmdStr = cmdStrListCopy.pop(0) self.cmdQueue.addCmd(self.makeCmd(cmdStr), nullCallFunc) # print 'adding', cmdStr # print 'command queue!', [x.cmdVerb for x in self.cmdQueue.cmdQueue] Timer(timeStep, addInOrder)
def runTest(): global clientSocket try: testStr = next(strIter) print("Client writing %r" % (testStr, )) if binary: clientSocket.write(testStr) else: clientSocket.writeLine(testStr) Timer(0.001, runTest) except StopIteration: pass
def read(self, nChar): """Read at most nChar characters; if nChar=None then get all chars """ if nChar is None: data, self.__buffer = self.__buffer, "" else: data, self._buffer = self._buffer[0:nChar], self._buffer[nChar:] #print "%s.read(nChar=%r) returning %r; remaining buffer=%r" % (self, nChar, data, self.__buffer) if self.__buffer and self._readCallback: Timer(0, self._readCallback, self) return data
def initCallback(self, userCmd): """!Callback for device initialization """ # print("%s.initCallback(userCmd=%r); _callbacks=%s" % (self, userCmd, userCmd._callbacks)) if not userCmd.isDone: return if userCmd.didFail: reason = userCmd.getMsg( ) or "init command failed for unknown reasons" else: reason = None Timer(0, self.finish, reason)
def __init__(self, name, port): """!Construct a fake device controller @param[in] name name of device controller @param[in] port port on which to command device controller """ self.replyTimer = Timer() TCPServer.__init__( self, port=port, stateCallback=self.stateCallback, sockReadCallback=self.sockReadCallback, sockStateCallback=self.sockStateCallback, )
def readLine(self, default=None): """Read a line of data; return default if a line is not present """ res = self.lineEndPattern.split(self.__buffer, 1) if len(res) == 1: # readDelimiter not found; leave the buffer alone and don't bother to call the callback again #print "%s.readLine(default=%r) returning the default; remaining buffer=%r" % (self, default, self.__buffer) return default self.__buffer = res[1] #print "%s.readLine(default=%r) returning %r; remaining buffer=%r" % (self, default, res[0], self.__buffer) if self.__buffer and self._readCallback: Timer(0, self._readCallback, self) return res[0]
def __init__( self, endpoint=None, protocol=None, state=BaseSocket.Connected, readCallback=nullCallback, stateCallback=nullCallback, timeLim=None, name="", ): """Construct a Socket Inputs: - endpoint a Twisted endpoint, e.g. twisted.internet.endpoints.TCP4ClientEndpoint; - protocol a Twisted protocol; you must either specify endpoint or protocol, but not both - state the initial state - readCallback function to call when data read; receives: self - stateCallback a state callback function; see addStateCallback for details - timeLim time limit to make connection (sec); no limit if None or 0 - name a string to identify this socket; strictly optional """ #print "Socket(name=%r, endpoint=%r, protocol=%r, state=%r, readCallback=%r, stateCallback=%r)" % \ # (name, endpoint, protocol, state, readCallback, stateCallback) if bool(endpoint is None) == bool(protocol is None): raise RuntimeError("Must provide one of endpoint or protocol") self._endpoint = endpoint self._endpointDeferred = None self._protocol = None self._data = None self._connectTimer = Timer() BaseSocket.__init__(self, state=state, readCallback=readCallback, stateCallback=stateCallback, name=name) if protocol is not None: self._connectionMade(protocol) else: if timeLim: self._connectTimer.start(timeLim, self._connectTimeout) self._setState(BaseSocket.Connecting) self._endpointDeferred = self._endpoint.connect( _SocketProtocolFactory()) setCallbacks( deferred=self._endpointDeferred, callback=self._connectionMade, errback=self._connectionLost, )
def startDisconnect(self): """!Start disconnecting the connection """ if self.dev.conn.isDone and not self.dev.conn.isConnected: # fully disconnected; no more to be done Timer(0, self.finish) else: if self._timeLim: # start timer for disconnection self._connTimer.start(self._timeLim, self.finish, "timed out waiting for disconnection") self.dev.conn.addStateCallback(self.connCallback) self._addedConnCallback = True self.dev.conn.disconnect()
def cmdCallback(self, cmd): # allow commands to run for 0.15 seconds before killing # print cmd.cmdVerb, cmd.state # print 'q: ', [x.cmd.cmdVerb for x in self.cmdQueue.cmdQueue] if cmd.isDone: # print 'cmd %s finished with state %s and txtMsg=%s'%(cmd.cmdVerb, cmd.state, cmd.textMsg) if cmd.didFail: self.failOrder.append(cmd.cmdVerb) else: self.doneOrder.append(cmd.cmdVerb) elif cmd.isActive: Timer(0.15, self.setDone, cmd) if (not self.cmdQueue.cmdQueue) and (self.cmdQueue.currExeCmd.cmd.isDone) and not self.commandsLeft: # must be last command and its done # the queue is empty and last command is done, end the test self.deferred.callback('go')
def __init__(self, priorityDict, killFunc=None): """ This is an object which keeps track of commands and smartly handles command collisions based on rules chosen by you. @param[in] priorityDict a dictionary keyed by cmdVerb, with integer values or Immediate @ param[in] killFunc: a function to call when a running command needs to be killed. Accepts 2 parameters, the command to be canceled, and the command doing the killing. This function must eventually ensure that the running command is canceled safely allowing for the next queued command to go. Or None """ self.cmdQueue = [] dumCmd = UserCmd() dumCmd.setState(dumCmd.Done) dumCmd.cmdVerb = 'dummy' self.currExeCmd = QueuedCommand(dumCmd, 0, lambda cmdVar: None) self.priorityDict = priorityDict self.killFunc = killFunc self.ruleDict = {} self.queueTimer = Timer() self._enabled = True
def __init__(self, filterWheelDev, shutterDev, name="arcticICC", userPort = UserPort, test=False, ): """!Construct an ArcticActor @param[in] filterWheelDev a FilterWheelDevice instance @param[in] shutterDev a ShutterDevice instance @param[in] name actor name; used for logging @param[in] userPort port on which this service runs @param[in] test bool. If true, use a fake camera. """ self.imageDir = ImageDir self.test = test self.setCamera() self.filterWheelDev = filterWheelDev self.shutterDev = shutterDev self._tempSetpoint = None self.expNum = 0 self.exposeCmd = UserCmd() self.exposeCmd.setState(UserCmd.Done) self.pollTimer = Timer() self.expName = None self.comment = None self.expStartTime = None self.expType = None self.expTime = None self.resetConfig = None Actor.__init__(self, userPort = userPort, maxUsers = 1, devs = (filterWheelDev, shutterDev), name = name, version = __version__, doConnect = True, doDevNameCmds = False, doDebugMsgs = self.test, )
def finish(self, reason=None): """!Call on success or failure to finish the command @param[in] reason: reason for failure (if non-empty then failure is assumed) """ self._connTimer.cancel() self.dev._ignoreConnCallback = False if self._addedConnCallback: self.dev.conn.removeStateCallback(self.connCallback) if reason or not self.dev.conn.isConnected: reason = reason or "unknown reason" self.dev.setState(self.dev.Failed, reason) if not self.userCmd.isDone: self.userCmd.setState(self.userCmd.Failed, textMsg="%s failed to connect: %s" % (self.dev, reason)) Timer(0, self.dev.conn.disconnect) else: self.dev.setState(self.dev.Connected) if not self.userCmd.isDone: self.userCmd.setState(self.userCmd.Done)
def __init__(self): self.moveTimer = Timer()
def diffuIn(self): Timer(0.2, self._setDiffuPos, 1) # set on a timer to emulate move time
def diffuOut(self): Timer(0.2, self._setDiffuPos, 0) # set on a timer to emulate move time
def _holdOpen(userCmd): Timer(float(expTime), userCmd.setState, userCmd.Done) self.status.shutterTimer.startTimer() self.status.lastExpTime = -1 self.status.lastDesExpTime = expTime
def connCallback(self, conn): """!Callback for device connection state """ if self.dev.conn.isDone: Timer(0, self.finish)