Пример #1
0
    def writeCommandsToDevice(self):
        try:
            while True:
                print "writeCommandsToDevice: Waiting for a command to write."
                command, resultDefered = self.commandQueue.get_nowait()
                print "writeCommandsToDevice: Got a command to write. %s" % repr(command)
                transId = Modbus.getTransactionId(command)
                self.sentCommands[str(transId)] = resultDefered

                command = [ord(c) for c in command]
                self.device.write(command, checksum=False, modbus=True)
        except Exception, e:
            print type(e), e
            print "writeCommandsToDevice: No more commands to write."
Пример #2
0
    def loopingRead(self):
        self.deviceClosedEvent.clear()  # The device isn't close, so set the flag to False.

        while self.running:

            # Busy wait just for a bit because we recently received a
            # command. It's worth busy waiting to see if another will come.
            while True:
                sleep(0.002)
                now = datetime.now()
                if now - self.lastCommandTime > BUSY_WAIT_TIME:
                    break
                if not self.commandQueue.empty():
                    break

            if not self.commandQueue.empty():
                self.writeCommandsToDevice()

            try:
                # print "Start read."
                packet = self.device.read(64)
                # print "Read returned. Len = %s" % len(packet)

                if len(packet) != 0:
                    protoId = Modbus.getProtocolId(packet)
                    if protoId == 0:
                        transId = Modbus.getTransactionId(packet)
                        print "---------------------------------   Calling callback for transId = %s" % transId
                        self.sentCommands[str(transId)].callback(packet)
                        self.sentCommands.pop(str(transId))
                        self.lastCommandTime = datetime.now()

                    else:
                        # print "Got spontaneous data!"
                        self.sendSpontaneousData(packet)

            except Exception, e:
                if str(e).endswith("-7"):
                    # print "Read timed out."
                    pass
                elif self.closingDevice:
                    # We're closing the device anyway.
                    pass
                else:
                    print type(e), e
                    self.deviceLost()