Ejemplo n.º 1
0
    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)
Ejemplo n.º 2
0
 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
Ejemplo n.º 3
0
    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")
Ejemplo n.º 4
0
    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)
Ejemplo n.º 5
0
    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
Ejemplo n.º 6
0
    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)
Ejemplo n.º 7
0
 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)
Ejemplo n.º 8
0
 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
Ejemplo n.º 9
0
    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
Ejemplo n.º 10
0
    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)
Ejemplo n.º 11
0
    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,
        )
Ejemplo n.º 12
0
    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]
Ejemplo n.º 13
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,
            )
Ejemplo n.º 14
0
    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()
Ejemplo n.º 15
0
 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')
Ejemplo n.º 16
0
 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
Ejemplo n.º 17
0
    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,
            )
Ejemplo n.º 18
0
    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)
Ejemplo n.º 19
0
 def __init__(self):
     self.moveTimer = Timer()
Ejemplo n.º 20
0
 def diffuIn(self):
     Timer(0.2, self._setDiffuPos, 1)  # set on a timer to emulate move time
Ejemplo n.º 21
0
 def diffuOut(self):
     Timer(0.2, self._setDiffuPos, 0)  # set on a timer to emulate move time
Ejemplo n.º 22
0
 def _holdOpen(userCmd):
     Timer(float(expTime), userCmd.setState, userCmd.Done)
     self.status.shutterTimer.startTimer()
     self.status.lastExpTime = -1
     self.status.lastDesExpTime = expTime
Ejemplo n.º 23
0
 def connCallback(self, conn):
     """!Callback for device connection state
     """
     if self.dev.conn.isDone:
         Timer(0, self.finish)