示例#1
0
def unsubscribe(sock, topics):
    """
        Description:
            取消订阅一组主题消息。
        Args:
            sock(Socket):
                客户端socket对象。
            topics(array[string]):
                将要取消订阅的主题数组,数组单元为主题字符串。
        Returns:
            packetIdentifier(int)
                本次请求使用的报文标识符。
        Raises:
            IOException
                socket连接异常。
    """
    packetIdentifier = generatePacketIdentifier()
    tmpUnsubscribes.append({
        'packetIdentifier': packetIdentifier,
        'topics': topics
    })
    sendMessage(sock, Encoders.UNSUBSCRIBE_Encoder(packetIdentifier, topics))
    print("[" + getTime() + "]" + " [CLIENT/INFO] Packet " +
          str(packetIdentifier) + ": Unsubscribing...")
    return packetIdentifier
示例#2
0
def publishAtQos2(sock, topic, message, retain):
    """
        Description:
            发送一则服务质量等级为2的消息。
        Args:
            sock(Socket):
                客户端socket对象。
            topic(string):
                消息主题。
            message(string):
                消息内容。
            retain(int):
                消息保留标志。
        Returns:
            packetIdentifier(int)
                本次请求使用的报文标识符。
        Raises:
            IOException
                socket连接异常。
    """
    packetIdentifier = generatePacketIdentifier()
    sendMessage(
        sock,
        Encoders.PUBLISH_Encoder(0, 2, retain, topic, packetIdentifier,
                                 message))
    tmpPublishAtQos2.append({
        "packetIdentifier": packetIdentifier,
        "waitingFor": 'PUBREC'
    })
    return packetIdentifier
示例#3
0
def main():
    try:
        dataLog = DataLog.DataLog(logDir = 'logs/')
        dataLog.updateLog({'velocity_units':velocityUnits})

        encoders = Encoders.Encoders(countsPerRevolution = countsPerRevolution, units = velocityUnits)
        #time.sleep(2) #allow encoder time to attach

        motors = Motors.Motors(i2c_bus_num,nmotors,min_throttle_percentage, max_throttle_percentage, min_throttle_pulse_width, max_throttle_pulse_width)
        
        #start motor communication
        motors.setPWMfreq(PWM_frequency)
        motors.motor_startup()
        for i in xrange(3):
            motors.setPWM(i, 0)
        
        freq = 1/2.0

        dataLog.updateLog({'start_time': time.time()})

        while True:
            #get measured velocity array
            #calculate commanded velocities array
            #convert commanded velocities to throttle
            #send commanded PWM signal to motors
            loop_start_time = time.time()
            count_array = encoders.returnCountArray()
            measured_velocities = encoders.getVelocities()
            print measured_velocities
            command_time = time.time()
            commanded_throttles = [wave(100,2*pi/nmotors*pwmNum, freq, command_time) for pwmNum in xrange(nmotors)]
            for pwmNum, throttle in enumerate(commanded_throttles):
                motors.setPWM(pwmNum,throttle)
            loop_end_time = time.time()

            #write information to logs
            log_info = {
                'counts': dict(zip(['time', 0, 1, 2], count_array)),
                'commanded_velocity': dict(zip(['time', 0, 1, 2],[command_time] + map(actuatorVelocityModel, commanded_throttles))),
                'commanded_throttle': dict(zip(['time', 0, 1, 2],[command_time] + commanded_throttles)),
                'measured_velocity': dict(zip(['time', 0, 1, 2], measured_velocities)),
                'iteration_latency': loop_end_time - loop_start_time,
                'command_latency': loop_end_time - command_time,
                'measurement_to_command_latency': command_time - measured_velocities[0]
                }
            dataLog.updateLog(log_info)

    except KeyboardInterrupt:
        for i in xrange(3):
            motors.setPWM(i, 0)
        dataLog.saveLog(baseName = 'Closed_Loop_Test')   
示例#4
0
def ping(sock):
    """
        Description:
            向服务器发送PING请求。
        Args:
            sock(Socket):
                客户端socket对象。
        Returns:
            None
        Raises:
            IOException
                socket连接异常。
    """
    print("[" + getTime() + "]" + " [CLIENT/INFO] Sending heartbeat...")
    sendMessage(sock, Encoders.PINGREQ_Encoder())
    print("[" + getTime() + "]" + " [CLIENT/INFO] Heartbeat sent.")
示例#5
0
def disconnect(sock):
    """
        Description:
            主动断开与服务端的连接。
        Args:
            sock(Socket):
                客户端socket对象。
        Returns:
            None
        Raises:
            IOException
                socket连接异常。
    """
    print("[" + getTime() + "]" +
          " [CLIENT/INFO] Sending DISCONNECT message...")
    sendMessage(sock, Encoders.DISCONNECT_Encoder())
	def __init__(self, leftMotorOutA, leftMotorOutB, leftPwm, rightMotorOutA, rightMotorOutB, rightPwm, liftServoPin, pinchServoPin):
		print 'create robot'

		self.leftMotor = Motor.motor(leftMotorOutA, leftMotorOutB, leftPwm)
		self.rightMotor = Motor.motor(rightMotorOutA, rightMotorOutB, rightPwm)

		self.claw = Claw.claw(liftServoPin, pinchServoPin)

		self.irSensors = IrSensor.irSensor()

		self.encoders = Encoders.easy_encoders()

		self.leftPid = pid_control.easy_PID(P_GAIN, I_GAIN, D_GAIN)
		self.rightPid = pid_control.easy_PID(P_GAIN, I_GAIN, D_GAIN)

      		self.pixyObj = easy_pixy_test.easy_pixy()
	def __init__(self, leftMotorOutA, leftMotorOutB, leftPwm, rightMotorOutA, rightMotorOutB, rightPwm, liftServoPin, pinchServoPin):
		#Set up colorized logger
		self.logger = logging.getLogger('maze_run')
		coloredlogs.install(level='DEBUG')
		

		#Create objects related to robot
		self.logger.info('create robot')
		self.leftMotor = Motor.motor(leftMotorOutA, leftMotorOutB, leftPwm)
		self.rightMotor = Motor.motor(rightMotorOutA, rightMotorOutB, rightPwm)
		self.claw = Claw.claw(liftServoPin, pinchServoPin)
		self.irSensors = IrSensor.irSensor()
		self.encoders = Encoders.easy_encoders()
		self.leftPid = pid_control.easy_PID(P_GAIN, I_GAIN, D_GAIN)
		self.rightPid = pid_control.easy_PID(P_GAIN, I_GAIN, D_GAIN)
      		self.pixyObj = easy_pixy_test.easy_pixy()
		self.PREVIOUS_CORRECTION_VALUE = 0
	
		self.pickedup = False
示例#8
0
def publishAtQos0(sock, topic, message, retain):
    """
        Description:
            发送一则服务质量等级为0的消息。
        Args:
            sock(Socket):
                客户端socket对象。
            topic(string):
                消息主题。
            message(string):
                消息内容。
            retain(int):
                消息保留标志。
        Returns:
            None
        Raises:
            IOException
                socket连接异常。
    """
    sendMessage(sock, Encoders.PUBLISH_Encoder(0, 0, retain, topic, 0,
                                               message))
    print("[" + getTime() + "]" + " [CLIENT/INFO] Message published at Qos0" +
          ".")
示例#9
0
 def decode(self, data):
     """
         Description:
             对于给定的报文字节串进行解码,并实现对应的逻辑响应。
         Args:
             data(byte[])
                 待解码的报文字节串。
         Returns:
             None
         Raises:
             Decoders.IllegalMessageException
                 消息解码错误。
             IOException
                 socket连接错误。
     """
     if data == b'':
         return
     try:
         messageType, results = Decoders.message_Decoder(data)
         if messageType == definition.messageType.CONNECT:
             if results['clientId'].isalnum(
             ) and results['clientId'].__len__(
             ) >= 1 and results['clientId'].__len__() <= 23:
                 self.clientId = results['clientId']
                 if checkUser(results['userName'],
                              results['password']) == 2:
                     if results['cleanSession'] == 1:
                         removeSubscribe(results['clientId'])
                     self.keepAlive = results['keepAlive']
                     self.willFlag = results['willFlag']
                     if self.willFlag == 1:
                         self.willTopic = results['willTopic']
                         self.willMessage = results['willMessage']
                         self.willQos = results['willQos']
                         self.willRetain = results['willRetain']
                     print("[" + getTime() + "]" +
                           " [SERVER/INFO] Client " + str(self.address) +
                           " has connected.")
                     sessionPresent = getSubscribe(self.clientId).__len__()
                     if sessionPresent > 0:
                         sessionPresent = 1
                     self.send(
                         Encoders.CONNACK_Encoder(
                             sessionPresent,
                             definition.ConnackReturnCode.ACCEPTED))
                     scs = getSubscribe(self.clientId)
                     for sc in scs:
                         for retainedMessage in retainedMessages:
                             if checkFatherSon(
                                     sc[1], retainedMessage['topic']
                             ) or retainedMessage['topic'] == sc[1]:
                                 packetIdentifier = generatePacketIdentifier(
                                 )
                                 print(111)
                                 self.send(
                                     Encoders.PUBLISH_Encoder(
                                         0, sc[2], 0,
                                         retainedMessage['topic'],
                                         packetIdentifier,
                                         retainedMessage['message']))
                                 if sc[2] == 2:
                                     timer = threading.Timer(
                                         ACK_TIMEOUT, pubrecNotReceived, [
                                             self,
                                         ])
                                     timeoutTimers.append({
                                         'clientId':
                                         self.getClientId(),
                                         'packetIdentifier':
                                         packetIdentifier,
                                         'waitingFor':
                                         'PUBREC',
                                         'timer':
                                         timer
                                     })
                                     timer.start()
                                 elif sc[2] == 1:
                                     timer = threading.Timer(
                                         ACK_TIMEOUT, pubackNotReceived, [
                                             self,
                                         ])
                                     timeoutTimers.append({
                                         'clientId':
                                         self.getClientId(),
                                         'packetIdentifier':
                                         packetIdentifier,
                                         'waitingFor':
                                         'PUBACK',
                                         'timer':
                                         timer
                                     })
                                     timer.start()
                                 print(
                                     "[" + getTime() + "]" +
                                     " [SERVER/INFO] A retained message sent to Client "
                                     + str(self.address) + " at packet " +
                                     str(packetIdentifier) + " .")
                                 retainedMessages.remove(retainedMessage)
                                 break
                     keepAliveThread = threading.Thread(target=self.counter)
                     keepAliveThread.start()
                 elif checkUser(results['userName'],
                                results['password']) == 0:
                     self.send(
                         Encoders.CONNACK_Encoder(
                             0, definition.ConnackReturnCode.
                             REFUSED_INVALID_USER))
                     print("[" + getTime() + "]" +
                           " [SERVER/INFO] Client " + str(self.address) +
                           " has disconnected: Illegal User or Password.")
                     self.onDisconnect()
                 else:
                     self.send(
                         Encoders.CONNACK_Encoder(
                             0, definition.ConnackReturnCode.
                             REFUSED_UNAUTHORIZED))
                     print("[" + getTime() + "]" +
                           " [SERVER/INFO] Client " + str(self.address) +
                           " has disconnected: Unauthorized user.")
                     self.onDisconnect()
             else:
                 self.send(
                     Encoders.CONNACK_Encoder(
                         0, definition.ConnackReturnCode.
                         REFUSED_ILLEGAL_CLIENTID))
                 print("[" + getTime() + "]" + " [SERVER/INFO] Client " +
                       str(self.address) +
                       " has disconnected: Illegal ClientId.")
                 self.onDisconnect()
         elif messageType == definition.messageType.SUBSCRIBE:
             print("[" + getTime() + "]" + " [SERVER/INFO] Client " +
                   str(self.address) + " subscribing...")
             packetIdentifier = results['packetIdentifier']
             topics = results['topics']
             returnCodes = []
             for i in range(0, topics.__len__()):
                 removeSubscribe(self.clientId, topics[i]['topic'])
                 addSubscribe(self.clientId, topics[i]['topic'],
                              topics[i]['qos'])
                 returnCodes.append(topics[i]['qos'])
             self.send(
                 Encoders.SUBACK_Encoder(packetIdentifier, returnCodes))
             print("[" + getTime() + "]" + " [SERVER/INFO] Client " +
                   str(self.address) + " subscribed.")
             print("[" + getTime() + "]" +
                   " [SERVER/INFO] Current subscirbes: " +
                   str(getAllSubscribe()) + " .")
         elif messageType == definition.messageType.UNSUBSCRIBE:
             print("[" + getTime() + "]" + " [SERVER/INFO] Client " +
                   str(self.address) + " unsubscribing...")
             packetIdentifier = results['packetIdentifier']
             topics = results['topics']
             for i in range(0, topics.__len__()):
                 removeSubscribe(self.clientId, topics[i])
             self.send(Encoders.UNSUBACK_Encoder(packetIdentifier))
             print("[" + getTime() + "]" + " [SERVER/INFO] Client " +
                   str(self.address) + " unsubscribed.")
             print("[" + getTime() + "]" +
                   " [SERVER/INFO] Current subscirbes: " +
                   str(getAllSubscribe()) + " .")
         elif messageType == definition.messageType.PINGREQ:
             print("[" + getTime() + "]" + " [SERVER/INFO] Client " +
                   str(self.address) + " sent a heartbeat.")
             self.send(Encoders.PINGRESP_Encoder())
         elif messageType == definition.messageType.PUBLISH:
             print("[" + getTime() + "]" + " [SERVER/INFO] Client " +
                   str(self.address) + " sent a message.")
             messageQueue.put({
                 'retain': results['retain'],
                 'topic': results['topic'],
                 'message': results['message']
             })
             if results['qos'] == 1:
                 self.send(
                     Encoders.PUBACK_Encoder(results['packetIdentifier']))
                 print("[" + getTime() + "]" +
                       " [SERVER/INFO] PUBACK responded to Client " +
                       str(self.address) + " at packet " +
                       str(results['packetIdentifier']) + " .")
             elif results['qos'] == 2:
                 self.send(
                     Encoders.PUBREC_Encoder(results['packetIdentifier']))
                 print("[" + getTime() + "]" +
                       " [SERVER/INFO] PUBREC responded to Client " +
                       str(self.address) + " at packet " +
                       str(results['packetIdentifier']) + " .")
         elif messageType == definition.messageType.PUBREL:
             self.send(Encoders.PUBCOMP_Encoder(
                 results['packetIdentifier']))
             print("[" + getTime() + "]" +
                   " [SERVER/INFO] PUBCOMP responded to Client " +
                   str(self.address) + " at packet " +
                   str(results['packetIdentifier']) + " .")
         elif messageType == definition.messageType.PUBACK:
             print("[" + getTime() + "]" + " [SERVER/INFO] Client " +
                   str(self.address) + " responded a PUBACK.")
             clientId = self.clientId
             packetIdentifier = results['packetIdentifier']
             try:
                 for i in range(0, timeoutTimers.__len__()):
                     if timeoutTimers[i][
                             'packetIdentifier'] == packetIdentifier and timeoutTimers[
                                 i]['clientId'] == clientId and timeoutTimers[
                                     i]['waitingFor'] == 'PUBACK':
                         timeoutTimers[i]['timer'].cancel()
             except:
                 pass
         elif messageType == definition.messageType.PUBREC:
             print("[" + getTime() + "]" + " [SERVER/INFO] Client " +
                   str(self.address) + " responded a PUBREC.")
             clientId = self.clientId
             packetIdentifier = results['packetIdentifier']
             self.send(Encoders.PUBREL_Encoder(packetIdentifier))
             print("[" + getTime() + "]" +
                   " [SERVER/INFO] PUBREL responded to Client " +
                   str(self.address) + " at packet " +
                   str(packetIdentifier) + " .")
             try:
                 for i in range(0, timeoutTimers.__len__()):
                     if timeoutTimers[i][
                             'packetIdentifier'] == packetIdentifier and timeoutTimers[
                                 i]['clientId'] == clientId and timeoutTimers[
                                     i]['waitingFor'] == 'PUBREC':
                         timeoutTimers[i]['timer'].cancel()
                         break
                 timer = threading.Timer(ACK_TIMEOUT,
                                         self.pubcompNotReceived)
                 timeoutTimers.append({
                     'clientId': self.getClientId(),
                     'packetIdentifier': packetIdentifier,
                     'waitingFor': 'PUBCOMP',
                     'timer': timer
                 })
                 timer.start()
             except:
                 pass
         elif messageType == definition.messageType.PUBCOMP:
             print("[" + getTime() + "]" + " [SERVER/INFO] Client " +
                   str(self.address) + " responded a PUBCOMP.")
             clientId = self.clientId
             packetIdentifier = results['packetIdentifier']
             try:
                 for i in range(0, timeoutTimers.__len__()):
                     if timeoutTimers[i][
                             'packetIdentifier'] == packetIdentifier and timeoutTimers[
                                 i]['clientId'] == clientId and timeoutTimers[
                                     i]['waitingFor'] == 'PUBCOMP':
                         timeoutTimers[i]['timer'].cancel()
                         break
             except:
                 pass
         elif messageType == definition.messageType.DISCONNECT:
             self.onDisconnect()
             print("[" + getTime() + "]" + " [SERVER/INFO] Client " +
                   str(self.address) + " has disconnected.")
     except Decoders.IllegalMessageException:
         print(data)
         print("[" + getTime() + "]" + " [SERVER/INFO] Client " +
               str(self.address) +
               " has disconnected: Illegal Message Received.")
         self.onDisconnect()
示例#10
0
def publishFromQueue():
    """
        Description:
            从线程安全的messageQueue中按队列顺序发送消息。
        Args:
            None
        Returns:
            None
        Raises:
            IOException
                socket连接异常。
    """
    while True:
        if messageQueue.qsize() != 0:
            messageItem = messageQueue.get()
            subscribers = getSubscribers(messageItem['topic'])
            for i in range(0, subscribers.__len__()):
                subscriber = subscribers[i][0]
                qos = subscribers[i][2]
                connectionsLock.acquire()
                if qos == 0:
                    for j in range(0, connections.__len__()):
                        if connections[j].getClientId() == subscriber:
                            connections[j].send(
                                Encoders.PUBLISH_Encoder(
                                    0, qos, 0, messageItem['topic'], 0,
                                    messageItem['message']))
                elif qos == 1:
                    packetIdentifier = generatePacketIdentifier()
                    for j in range(0, connections.__len__()):
                        if connections[j].getClientId() == subscriber:
                            connections[j].send(
                                Encoders.PUBLISH_Encoder(
                                    0, qos, 0, messageItem['topic'],
                                    packetIdentifier, messageItem['message']))
                            timer = threading.Timer(ACK_TIMEOUT,
                                                    pubackNotReceived, [
                                                        connections[j],
                                                    ])
                            timeoutTimers.append({
                                'clientId':
                                connections[j].getClientId(),
                                'packetIdentifier':
                                packetIdentifier,
                                'waitingFor':
                                'PUBACK',
                                'timer':
                                timer
                            })
                            timer.start()
                elif qos == 2:
                    packetIdentifier = generatePacketIdentifier()
                    for j in range(0, connections.__len__()):
                        if connections[j].getClientId() == subscriber:
                            connections[j].send(
                                Encoders.PUBLISH_Encoder(
                                    0, qos, 0, messageItem['topic'],
                                    packetIdentifier, messageItem['message']))
                            timer = threading.Timer(ACK_TIMEOUT,
                                                    pubrecNotReceived, [
                                                        connections[j],
                                                    ])
                            timeoutTimers.append({
                                'clientId':
                                connections[j].getClientId(),
                                'packetIdentifier':
                                packetIdentifier,
                                'waitingFor':
                                'PUBREC',
                                'timer':
                                timer
                            })
                            timer.start()
                connectionsLock.release()
            if messageItem['retain'] == 1:
                addRetain(messageItem)
            print("[" + getTime() + "]" +
                  " [SERVER/INFO] Queue processed a message." +
                  str(messageQueue.qsize()) + " message(s) in queue, " +
                  str(retainedMessages.__len__()) + " message(s) retained.")
示例#11
0
def decode(data, sock):
    """
        Description:
            解码报文,并做出对应的逻辑响应。
        Args:
            data(byte[]):
                待解码的报文字符串。
            sock(Socket):
                客户端socket对象。
        Returns:
            None
        Raises:
            IOException
                socket连接异常。
            Decoders.IllegalMessageException
                报文解码异常。
    """
    global alive, sessionPresent, subscribes
    try:
        messageType, results = Decoders.message_Decoder(data)
        if messageType == definition.messageType.CONNACK:
            if results['sessionPresent'] == 0:
                subscribes = []
            if results['returnCode'] == definition.ConnackReturnCode.ACCEPTED:
                print("[" + getTime() + "]" + " [CLIENT/INFO] MQTT Connected!")
            elif results[
                    'returnCode'] == definition.ConnackReturnCode.REFUSED_ILLEGAL_CLIENTID:
                print("[" + getTime() + "]" +
                      " [CLIENT/INFO] MQTT Disconnected: Illegal ClientID.")
                alive = SOCKET_DISCONNECTED
                sock.close()
            elif results[
                    'returnCode'] == definition.ConnackReturnCode.REFUSED_INVALID_USER:
                print("[" + getTime() + "]" +
                      " [CLIENT/INFO] MQTT Disconnected: Invalid User.")
                alive = SOCKET_DISCONNECTED
                sock.close()
            elif results[
                    'returnCode'] == definition.ConnackReturnCode.REFUSED_SERVER_UNAVAILABLE:
                print(
                    "[" + getTime() + "]" +
                    " [CLIENT/INFO] MQTT Disconnected: Server temporarily unavailable."
                )
                alive = SOCKET_DISCONNECTED
                sock.close()
            elif results[
                    'returnCode'] == definition.ConnackReturnCode.REFUSED_UNAUTHORIZED:
                print("[" + getTime() + "]" +
                      " [CLIENT/INFO] MQTT Disconnected: Unauthorized.")
                alive = SOCKET_DISCONNECTED
                sock.close()
            elif results[
                    'returnCode'] == definition.ConnackReturnCode.REFUSED_UNSUPPORTED_PROTOCOL:
                print(
                    "[" + getTime() + "]" +
                    " [CLIENT/INFO] MQTT Disconnected: Unsupported protocol.")
                alive = SOCKET_DISCONNECTED
                sock.close()
        elif messageType == definition.messageType.SUBACK:
            packetIdentifier = results['packetIdentifier']
            for i in range(0, tmpSubscribes.__len__()):
                if tmpSubscribes[i]['packetIdentifier'] == packetIdentifier:
                    for j in range(0, tmpSubscribes[i]['topics'].__len__()):
                        if results['returnCodes'][
                                j] == definition.SubackReturnCode.FAILURE:
                            print(
                                "[" + getTime() + "]" +
                                " [CLIENT/WARN] Subscribe failure at topic " +
                                tmpSubscribes[i]['topics'][j]['topic'] + ".")
                        elif results['returnCodes'][
                                j] == definition.SubackReturnCode.SUCCESS_MAX_QOS_0:
                            print(
                                "[" + getTime() + "]" +
                                " [CLIENT/INFO] Subscribe success at topic " +
                                tmpSubscribes[i]['topics'][j]['topic'] +
                                ", Qos 0 .")
                            removeSubscribe(
                                tmpSubscribes[i]['topics'][j]['topic'])
                            subscribes.append({
                                'topic':
                                tmpSubscribes[i]['topics'][j]['topic'],
                                'qos':
                                0
                            })
                        elif results['returnCodes'][
                                j] == definition.SubackReturnCode.SUCCESS_MAX_QOS_1:
                            print(
                                "[" + getTime() + "]" +
                                " [CLIENT/INFO] Subscribe success at topic " +
                                tmpSubscribes[i]['topics'][j]['topic'] +
                                ", Qos 1 .")
                            removeSubscribe(
                                tmpSubscribes[i]['topics'][j]['topic'])
                            subscribes.append({
                                'topic':
                                tmpSubscribes[i]['topics'][j]['topic'],
                                'qos':
                                1
                            })
                        elif results['returnCodes'][
                                j] == definition.SubackReturnCode.SUCCESS_MAX_QOS_2:
                            print(
                                "[" + getTime() + "]" +
                                " [CLIENT/INFO] Subscribe success at topic " +
                                tmpSubscribes[i]['topics'][j]['topic'] +
                                ", Qos 2 .")
                            removeSubscribe(
                                tmpSubscribes[i]['topics'][j]['topic'])
                            subscribes.append({
                                'topic':
                                tmpSubscribes[i]['topics'][j]['topic'],
                                'qos':
                                2
                            })
                    tmpSubscribes.pop(i)
                    break
            print("[" + getTime() + "]" +
                  " [CLIENT/INFO] Current subscribes: " + str(subscribes) +
                  " .")
        elif messageType == definition.messageType.UNSUBACK:
            packetIdentifier = results['packetIdentifier']
            for i in range(0, tmpUnsubscribes.__len__()):
                if tmpUnsubscribes[i]['packetIdentifier'] == packetIdentifier:
                    for j in range(0, tmpUnsubscribes[i]['topics'].__len__()):
                        removeSubscribe(tmpUnsubscribes[i]['topics'][j])
                    tmpUnsubscribes.pop(i)
                    print("[" + getTime() + "]" + " [CLIENT/INFO] Packet " +
                          str(packetIdentifier) + ": Unsubscribe success.")
                    break
            print("[" + getTime() + "]" +
                  " [CLIENT/INFO] Current subscribes: " + str(subscribes) +
                  " .")
        elif messageType == definition.messageType.PUBACK:
            packetIdentifier = results['packetIdentifier']
            print("[" + getTime() + "]" + " [CLIENT/INFO] Packet " +
                  str(packetIdentifier) + ": PUBACK received.")
            for i in range(0, tmpPublishAtQos1.__len__()):
                if tmpPublishAtQos1[i][
                        'packetIdentifier'] == packetIdentifier and tmpPublishAtQos1[
                            i]['waitingFor'] == 'PUBACK':
                    tmpPublishAtQos1.pop(i)
                    break
        elif messageType == definition.messageType.PUBREC:
            packetIdentifier = results['packetIdentifier']
            print("[" + getTime() + "]" + " [CLIENT/INFO] Packet " +
                  str(packetIdentifier) + ": PUBREC received.")
            sendMessage(sock, Encoders.PUBREL_Encoder(packetIdentifier))
            print("[" + getTime() + "]" + " [CLIENT/INFO] Packet " +
                  str(packetIdentifier) + ": PUBREL sent.")
            for i in range(0, tmpPublishAtQos2.__len__()):
                if tmpPublishAtQos2[i][
                        'packetIdentifier'] == packetIdentifier and tmpPublishAtQos2[
                            i]['waitingFor'] == 'PUBREC':
                    tmpPublishAtQos2[i]['waitingFor'] = 'PUBCOMP'
                    break
        elif messageType == definition.messageType.PUBCOMP:
            packetIdentifier = results['packetIdentifier']
            print("[" + getTime() + "]" + " [CLIENT/INFO] Packet " +
                  str(packetIdentifier) + ": PUBCOMP received.")
            for i in range(0, tmpPublishAtQos2.__len__()):
                if tmpPublishAtQos2[i][
                        'packetIdentifier'] == packetIdentifier and tmpPublishAtQos2[
                            i]['waitingFor'] == 'PUBCOMP':
                    tmpPublishAtQos2.pop(i)
                    break
        elif messageType == definition.messageType.PUBLISH:
            qos = results['qos']
            topic = results['topic']
            message = results['message']
            packetIdentifier = results['packetIdentifier']
            if qos == 0:
                print("[" + getTime() + "]" +
                      " [CLIENT/INFO] A message received: topic - " + topic +
                      " , message - " + message + " .")
                messageReceived.append({'topic': topic, 'message': message})
            elif qos == 1:
                print("[" + getTime() + "]" +
                      " [CLIENT/INFO] A message received: topic - " + topic +
                      " , message - " + message + " .")
                messageReceived.append({'topic': topic, 'message': message})
                sendMessage(sock, Encoders.PUBACK_Encoder(packetIdentifier))
                print("[" + getTime() + "]" + " [CLIENT/INFO] Packet " +
                      str(packetIdentifier) + ": PUBACK sent.")
            elif qos == 2:
                print(
                    "[" + getTime() + "]" +
                    " [CLIENT/INFO] A message received but not confirmed: topic - "
                    + topic + " , message - " + message + " .")
                tmpReceiveAtQos2.append({
                    'packetIdentifier': packetIdentifier,
                    'topic': topic,
                    'message': message
                })
                sendMessage(sock, Encoders.PUBREC_Encoder(packetIdentifier))
                print("[" + getTime() + "]" + " [CLIENT/INFO] Packet " +
                      str(packetIdentifier) + ": PUBREC sent.")
        elif messageType == definition.messageType.PUBREL:
            packetIdentifier = results['packetIdentifier']
            print("[" + getTime() + "]" + " [CLIENT/INFO] Packet " +
                  str(packetIdentifier) + ": PUBREL received.")
            for i in range(0, tmpReceiveAtQos2.__len__()):
                if tmpReceiveAtQos2[i]['packetIdentifier'] == packetIdentifier:
                    res = tmpReceiveAtQos2.pop(i)
                    messageReceived.append({
                        'topic': res['topic'],
                        'message': res['message']
                    })
                    print(
                        "[" + getTime() + "]" +
                        " [CLIENT/INFO] A message received and confirmed: topic - "
                        + res['topic'] + " , message - " + res['message'] +
                        " .")
                    sendMessage(sock,
                                Encoders.PUBCOMP_Encoder(packetIdentifier))
                    print("[" + getTime() + "]" + " [CLIENT/INFO] Packet " +
                          str(packetIdentifier) + ": PUBCOMP sent.")
                    break
        elif messageType == definition.messageType.PINGRESP:
            print("[" + getTime() + "]" +
                  " [CLIENT/INFO] Heartbeat response received.")
    except Decoders.IllegalMessageException as e:
        print(data)
        print("[" + getTime() + "]" +
              " [CLIENT/INFO] MQTT Disconnected: Illegal message received.")
        sock.close()
示例#12
0
def startClient(serverHost,
                serverPort,
                userNameFlag,
                passwordFlag,
                willRetain,
                willQos,
                willFlag,
                cleanSession,
                keepAlive,
                clientId,
                willTopic='',
                willMessage='',
                userName='',
                password=''):
    """
        Description:
            启动客户端。
        Args:
            serverHost(string)
                服务器地址。
            serverPort(int)
                服务器端口。
            userNameFlag(int)
                用户名标志,1为存在用户名字段,0为不存在。
            passwordFlag(int)
                密码标志,1为存在密码字段,0为不存在。
            willRetain(int)
                遗嘱保留(willFlag = 0时必须设置为0),1为遗嘱保留,0为遗嘱不保留。
            willQos(int)
                遗嘱消息服务质量(willFlag = 0时必须设置为0)。
            willFlag(int)
                遗嘱标志。
            cleanSession(int)
                清理会话标志,1为清除历史订阅信息,0为不清除。
            keepAlive(int)
                保活时长,单位为s。
            clientId(int)
                ClientID。
            willTopic(string)
                遗嘱消息主题(仅willFlag = 1时可设置)。
            willMessage(string)
                遗嘱消息内容(仅willFlag = 1时可设置)。
            userName(string)
                用户名(仅userNameFlag = 1时可设置)。
            password(string)
                密码(仅password = 1时可设置)。
        Returns:
            Socket:
                客户端socket对象。
        Raises:
            IOException
                socket连接错误。
    """
    print("====Eason MQTT-Client v1.0====")
    global alive
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setblocking(True)
        print("[" + getTime() + "]" + " [CLIENT/INFO] Socket Connecting...")
        sock.connect((serverHost, serverPort))
    except:
        print("[" + getTime() + "]" +
              " [CLIENT/INFO] Socket Disconnected: Can not connect to server.")
        alive = SOCKET_DISCONNECTED
        input("Press ENTER to continue...")
        sys.exit(0)
    alive = SOCKET_CONNECTED
    print("[" + getTime() + "]" + " [CLIENT/INFO] Socket Connected.")
    receiveThread = threading.Thread(target=receive, args=(sock, ))
    receiveThread.start()
    sendMessage(
        sock,
        Encoders.CONNECT_Encoder(userNameFlag, passwordFlag, willRetain,
                                 willQos, willFlag, cleanSession, keepAlive,
                                 clientId, willTopic, willMessage, userName,
                                 password))
    print("[" + getTime() + "]" + " [CLIENT/INFO] MQTT Connecting...")
    return sock
示例#13
0
文件: ProBot.py 项目: csik/ProBot-1
    print('2 - MidiDevice')
    userChoice = input('\nYour choice is: ')

    print('\nChoose the type of control of the ProBots motors:')
    print('\n1 - Sabertooth 2x25')
    print('2 - PWM Controller OSMC3-2')
    userChoice1 = input('\nYour choice is: ')

    userChoice = str(userChoice)
    userChoice1 = str(userChoice1)

# Initialization of classes from local files
PC = Sabertooth.PacketizedCommunication()
Battery = BatteryMonitor.BatteryVoltage()
PID = Controllers.PIDControllers()
Enc = Encoders.EncodersReadings()
Pconst = ProBotConstants.Constants()
Restartconst = RestartProgram.Restart()
UserChoice = Pub_Sub.userChoice(userChoice)

#PWM.start(channel, duty, freq, polarity)
PWM.start(Pconst.PWM_RF, 0, Pconst.PWM_Freq, 0)
PWM.start(Pconst.PWM_RR, 0, Pconst.PWM_Freq, 0)
PWM.start(Pconst.PWM_LF, 0, Pconst.PWM_Freq, 0)
PWM.start(Pconst.PWM_LR, 0, Pconst.PWM_Freq, 0)

# Configuration the type of GPIO's
GPIO.setup(Pconst.RedLED, GPIO.OUT)
GPIO.setup(Pconst.GreenLED, GPIO.OUT)
GPIO.setup(Pconst.BlueLED, GPIO.OUT)
示例#14
0
def logicTest():
    '''
        报文解析的逻辑测试。请复制到src文件夹下进行测试。
    '''
    print(
        Decoders.CONNECT_Decoder(
            Encoders.CONNECT_Encoder(1, 0, 1, 2, 1, 0, 256, 'eason0212', 'is',
                                     'ijsfs', 'eason')))
    print(
        Decoders.CONNACK_Decoder(
            Encoders.CONNACK_Encoder(
                1, definition.ConnackReturnCode.REFUSED_ILLEGAL_CLIENTID)))
    print(
        Decoders.PUBLISH_Decoder(
            Encoders.PUBLISH_Encoder(1, 2, 1, 'hhh', 10, 'hhhhh')))
    print(Decoders.PUBACK_Decoder(Encoders.PUBACK_Encoder(10)))
    print(Decoders.PUBREC_Decoder(Encoders.PUBREC_Encoder(10)))
    print(Decoders.PUBREL_Decoder(Encoders.PUBREL_Encoder(10)))
    print(Decoders.PUBCOMP_Decoder(Encoders.PUBCOMP_Encoder(10)))
    print(
        Decoders.SUBSCRIBE_Decoder(
            Encoders.SUBSCRIBE_Encoder(11, [{
                'topic': '2333',
                'qos': 1
            }, {
                'topic': '2433',
                'qos': 2
            }])))
    print(Decoders.SUBACK_Decoder(Encoders.SUBACK_Encoder(11, [0, 128])))
    print(
        Decoders.UNSUBSCRIBE_Decoder(
            Encoders.UNSUBSCRIBE_Encoder(12, ['2333', '2433', '2533'])))
    print(Decoders.UNSUBACK_Decoder(Encoders.UNSUBACK_Encoder(12)))
    print(Decoders.PINGREQ_Decoder(Encoders.PINGREQ_Encoder()))
    print(Decoders.PINGRESP_Decoder(Encoders.PINGRESP_Encoder()))
    print(Decoders.DISCONNECT_Decoder(Encoders.DISCONNECT_Encoder()))