Exemplo n.º 1
0
    def __init__(self):
        self.left_back = None
        self.right_back = None

        self.commands = Commands()
        self.generalpacket = Packet()
        self.get_data = Packet(8, PacketID.GET_VALUES, Scale.NONE)
        self.alive = Packet(8, PacketID.ALIVE, Scale.NONE)
Exemplo n.º 2
0
    def handle(self, packet):
        """
            Handle a raw protocol packet and return the constructed packet. Since it follows the protocol codes,
            the only allowed response codes are the protocols response codes, any other code will raise a InvalidPacketCode
            exception.

            :param packet: The packet content.
            :return: The packet object or None.
        """
        # Decode the packet fragments.
        code, data, params = protocol.from_packet(packet)

        if code is protocol.SUCCESS_CODE:
            # The packet was succesfull understood by the client.
            return Packet(content=data, params=params, code=code)
        elif code is protocol.ERROR_CODE:
            # The packet had errors or not had been understood by the client.
            if self._on_error is not None:

                # Execute the on error event with the packet data.
                self._on_error(data)
            return None
        else:
            raise protocol.InvalidPacketCode(
                'Invalid response code. Code: {}'.format(code))
Exemplo n.º 3
0
    def findandmapcontrollers(self):
        left_back_port = ""
        right_back_port = ""
        get_data = Packet(8, PacketID.GET_VALUES, Scale.NONE)
        if sys.platform.startswith('linux'):
            temp_list = glob.glob('/dev/tty[A]*')

            for a_port in temp_list:

                try:
                    vesc_usb = serial.Serial(a_port, 115200, timeout=0.1)
                    vesc_usb.flush()
                    sleep(2)
                    get_data.send(vesc_usb)
                    sleep(0.5)
                    if vesc_usb.in_waiting > 5:
                        buffer = Packet()
                        converted = [
                            int(elem.encode("hex"), 16)
                            for elem in vesc_usb.read_all()
                        ]
                        if buffer.process_buffer(converted):
                            self.commands.process_packet(buffer.goodpacket)
                            if self.commands.mcData.vesc_id == 100:
                                left_back_port = a_port
                                print "Found left wheel.\n"
                            elif self.commands.mcData.vesc_id == 200:
                                print "Found right wheel.\n"
                                right_back_port = a_port

                    vesc_usb.close()
                except serial.SerialException:
                    pass

        if len(left_back_port) > 0 and len(right_back_port) > 0:
            self.left_back = serial.Serial(left_back_port, 115200, timeout=0.1)
            self.right_back = serial.Serial(right_back_port,
                                            115200,
                                            timeout=0.1)
            self.left_back.flush()
            self.right_back.flush()
Exemplo n.º 4
0
def process_buffer(buffer):
    """
    This function processes the given buffer (bytearray). When a packet is received, the function calls the process_packet fucntion
    :param buffer: The given bytearray to proces
    :return: None
    """
    global phase, payload, length, crc
    """
    This is an integer that indicates the state the message reading is in.
    0: Starting a package read
    1: Reading payload length - long version
    2: Reading payload length - both versions
    3: Reading payload
    4: Reading CRC checksum - first byte
    5: Reading CRC checksum - second byte
    6: Checking checksum
    """

    for x in range(len(buffer)):

        curr_byte = buffer[x]
        if phase == 0:
            payload = bytearray()
            length = 0
            crc = 0
            if curr_byte == 2:
                phase += 2
            elif curr_byte == 3:
                phase += 1
        elif phase == 1:
            length = curr_byte << 8
            phase += 1
        elif phase == 2:
            length |= curr_byte
            phase += 1
        elif phase == 3:
            payload.append(curr_byte)
            if len(payload) == length:
                phase += 1
        elif phase == 4:
            crc = curr_byte << 8
            phase += 1
        elif phase == 5:
            crc |= curr_byte
            phase += 1
        elif phase == 6:
            phase = 0
            if curr_byte == 3 and packets.calc_crc(payload) == crc:
                process_packet(Packet(payload))
                return True
        else:
            phase = 0
Exemplo n.º 5
0
    def found_terminator(self):
        filename = ''
        data = "".join(self.ibuffer)
        if '\r\n\r\n' not in data and '\n\n' not in data:
            return
        self.set_terminator(None)
        self.ibuffer = []
        LOGGER.info('----> Request: %s', data)

        if ' /result' in data:
            tmp = RE_RESULT.search(data)
            if tmp:
                with open('result.txt', 'wb') as f:
                    f.write(urllib.unquote(tmp.group(1)))
        elif ' /interactive' in data:
            flist = self.get_filelist()
            if flist:
                state_tmp = global_file_state.get(self.addr[0], set())
                not_read = set(flist) - set(state_tmp)
                if not_read:
                    filename = not_read.pop()
                    state_tmp.add(filename)
                    global_file_state[self.addr[0]] = state_tmp

        # Get payload result
        try:
            query = self.parse_query(data)
        except:
            LOGGER.debug('Unparsed query: %r', data)
            return

        reload(config)
        try:
            result = config.PAYLOADS.get(query.path.lstrip('/'), Packet())
        except:
            self.close_when_done()
            return

        result = str(result).format(
            **{
                'host': config.HOST,
                'port': config.LISTEN_PORT,
                'filename': urllib.unquote(filename or query.query)
            })
        LOGGER.debug('Formatted result: %r', result)

        # Sending and closing connection
        self.push(result)
        self.close_when_done()
Exemplo n.º 6
0
              str(packet.get_next_number(32, 1)))
        print("Fault code: " + str(packet.get_next_number(8, 1)))


def get_duty_for_counter(counter):
    return min(0.05 * counter, 0.95)


phase = 0
payload = bytearray()
length = 0
crc = 0
vesc_usb = serial.Serial('COM3', 38400, timeout=0.1)
time.sleep(1)  # give the connection a second to settle

current_control = Packet(8, CURRENT_CONTROL_ID, NO_SCALE, 32, 0.3,
                         CURRENT_CONTROL_ACCURACY)
current_control_high = Packet(8, CURRENT_CONTROL_ID, NO_SCALE, 32, 0.5,
                              CURRENT_CONTROL_ACCURACY)
duty_control = Packet(8, DUTY_CONTROL_ID, NO_SCALE, 32, 0.1,
                      DUTY_CONTROL_ACCURACY)
alive = Packet(8, ALIVE_ID, NO_SCALE)
reboot = Packet(8, REBOOT_ID, NO_SCALE)
stop = Packet(8, 6, 1, 32, 0, CURRENT_CONTROL_ACCURACY)
get_rt_data = Packet(8, GET_VALUES_ID, NO_SCALE)

get_rt_data.send(vesc_usb)
data = [[] for x in range(20)]
counter = 0
data_counter = 0
wait_until = time.time() + 1
data_req_sent = False
Exemplo n.º 7
0
 def setandmonitorPWM(self, leftduty, rightduty):
     Packet(8, PacketID.SET_DUTY, Scale.NONE, 32, leftduty,
            Scale.E5).send(self.left_back)
     Packet(8, PacketID.SET_DUTY, Scale.NONE, 32, -rightduty,
            Scale.E5).send(self.right_back)
     '''