Example #1
0
    def __main_thread(self):
        while self.__running.is_set():
            self.__event_mainthread.wait()  # 此时主信号=True

            p = PDU(info=b'ACK PACKET')

            if len(self.seq_and_info) != 0:
                seq, info = self.seq_and_info.pop(0)

                # 去掉填充的字符
                info = info.rstrip(b'\x00')

                print("seq=%d exp=%d last=%d" % (seq, self.seq_expected, self.lastseq))

                if seq == self.seq_expected:
                    self.recv_info.append(info)

                    # 新开一个文件指针
                    if self.path is None:
                        # 如果是第一次收到这个端口发送的文件,则收到的是文件名
                        self.path = f'{dir_out}/books/{get_timestamp()}_{self.target[1]}'
                        os.makedirs(self.path, exist_ok=True)
                        self.file_out = info.decode().split('/')[-1].split('.')[0]
                    else:
                        file = f'{self.path}/{self.file_out}.txt'
                        with open(file, 'ab') as f:
                            f.write(info)

                    print("%s received seq=%d, num of received packet:%d\n" %
                          (self.my_binding.getsockname(), seq, len(self.recv_info)), end='')
                    self.lastseq = seq
                    self.seq_expected = (seq + 1) % args.max_sending_no
                    # 发送反馈
                p.update(ack=self.lastseq)
                send_pdu(p, self.my_binding, self.target)
Example #2
0
 def test_wrong_ip(self):
     pdu = PDU("my_pdu", {
         "ip": "127.0.0.1",
         "outlet%i" % (DUMMY_DEVICE_OUTLET): DUMMY_DEVICE.id
     })
     with self.assertRaises(DeviceError):
         pdu.off(DUMMY_DEVICE)
Example #3
0
    def send(self, recevier, content):
        self.wait(self.set_mode_pdu)

        if len(content) <= 70:
            content_len_zips = [PDU.encode(self.smsc, recevier, content)]
        else:
            content_len_zips = PDU.encode_long(self.smsc, recevier, content)

        for z in content_len_zips:
            content, code_len = z
            self.wait(self.set_msg_len, code_len)
            self.wait(self.send_msg, content)
Example #4
0
    def __init__(self, my_binding, sendto_sock, filelist):
        self.mybinding = my_binding
        self.target = sendto_sock
        self.filelist = filelist
        self.fileptr = args.sending_window_size - 1

        '''Events'''
        self.__event_mainthread = Event()
        self.__event_send = Event()
        self.__event_endsend = Event()
        self.__event_slide = Event()
        self.__event_endslide = Event()
        self.__event_timer = Event()
        self.__event_timeout = Event()
        self.__running = Event()

        '''Threads'''
        self.__thread_main = Thread(target=self.__main_thread)  # 主线程
        self.__thread_sending = Thread(target=self.__thread_send)   # 发送线程
        self.__thread_sliding = Thread(target=self.__thread_slide)  # 滑窗线程
        self.__thread_timeouting = Thread(target=self.__thread_timeouter)   # 超时控制定时器线程池

        '''Utils'''
        # 最大序号
        self.max_no = args.max_sending_no
        # 发送窗口序号列表
        self.sw_nolist = list(range(0, args.sending_window_size))
        # 发送窗口帧列表
        self.sw_pdulist = [PDU(seq=i, info=self.filelist[i]) for i in self.sw_nolist]
        self.sw_timeouter = [None]*args.sending_window_size
        self.last_sent = -1     # 记录最后一个已发送的帧
        self.sw_recvlist = []   # 记录收到的帧的ack
        self.success_sent = 0   # 成功发送并接收的包数
Example #5
0
    def __main_thread(self):
        p = PDU(info=b'ACK PACKET')
        while self.__running.is_set():
            self.__event_mainthread.wait()  # 此时主信号=True

            if len(self.seq_and_info) != 0:
                seq, info = self.seq_and_info.pop(0)

                # 去掉填充的字符
                info = info.rstrip(b'\x00')

                if seq == self.seq_expected:

                    self.recv_info.append(info)
                    self.logs.recv_catch(self.my_binding.getsockname(),
                                         self.target, seq, -1, 'OK')

                    # 新开一个文件指针
                    if self.path is None:
                        # 如果是第一次收到这个端口发送的文件,则收到的是文件名
                        self.path = f'{dir_out}/books/{get_timestamp()}_{self.target[1]}'
                        os.makedirs(self.path, exist_ok=True)
                        self.file_out = info.decode().split('/')[-1].split(
                            '.')[0]
                    else:
                        file = f'{self.path}/{self.file_out}.txt'
                        with open(file, 'ab') as f:
                            f.write(info)

                    self.lastseq = seq
                    self.seq_expected = (seq + 1) % args.max_sending_no
                    send_status = 'ACK'

                else:
                    self.logs.recv_catch(self.my_binding.getsockname(),
                                         self.target, seq, -1, 'NoErr')
                    send_status = 'RT'

                p.update(ack=self.lastseq)
                send_pdu(p, self.my_binding, self.target)
                self.logs.send_catch(self.my_binding.getsockname(),
                                     self.target, p.seq, p.ack, send_status)
Example #6
0
 def test_correct_settings(self):
     pdu = PDU("my_pdu", {
         "ip": PDU_IP,
         "outlet%i" % (DUMMY_DEVICE_OUTLET): DUMMY_DEVICE.id
     })
     pdu.off(DUMMY_DEVICE)
     pdu.on(DUMMY_DEVICE)
Example #7
0
 def test_wrong_outlets_config(self):
     pdu = PDU("my_pdu", {"ip": PDU_IP})
     with self.assertRaises(DeviceError):
         pdu.off(DUMMY_DEVICE)
Example #8
0
import sys
sys.path.append("/home/user/_cluster/cntrl_hac")
sys.path.append("/home/user/_cluster/testutil_hac")
from exceptionz import DeviceError
from pdu import PDU

import unittest

# Working PDU.
PDU_IP = "192.168.50.110"
# Some device connected to PDU.
DUMMY_DEVICE = PDU("dummy", {"ip": None})
DUMMY_DEVICE_OUTLET = 8


class TestsForPDU(unittest.TestCase):
    def test_correct_settings(self):
        pdu = PDU("my_pdu", {
            "ip": PDU_IP,
            "outlet%i" % (DUMMY_DEVICE_OUTLET): DUMMY_DEVICE.id
        })
        pdu.off(DUMMY_DEVICE)
        pdu.on(DUMMY_DEVICE)

    def test_wrong_ip(self):
        pdu = PDU("my_pdu", {
            "ip": "127.0.0.1",
            "outlet%i" % (DUMMY_DEVICE_OUTLET): DUMMY_DEVICE.id
        })
        with self.assertRaises(DeviceError):
            pdu.off(DUMMY_DEVICE)
Example #9
0
 def read_can_bus(self):
     can_msg = self.can_bus.recv()
     if self.is_j1939_frame(can_msg) and can_msg.dlc == 8:
         return PDU(can_msg)
     else:
         return None
Example #10
0
def decode_packet(data):
    """decode the data, return some kind of PDU."""
    if _debug: decode_packet._debug("decode_packet %r", data)

    # empty strings are some other kind of pcap content
    if not data:
        return None

    # assume it is ethernet for now
    d = decode_ethernet(data)
    data = d['data']

    # there could be a VLAN header
    if (d['type'] == 0x8100):
        if _debug: decode_packet._debug("    - vlan found")

        d = decode_vlan(data)
        data = d['data']

    # look for IP packets
    if (d['type'] == 0x0800):
        if _debug: decode_packet._debug("    - IP found")

        d = decode_ip(data)
        pduSource, pduDestination = d['source_address'], d[
            'destination_address']
        data = d['data']

        if (d['protocol'] == 'udp'):
            if _debug: decode_packet._debug("    - UDP found")

            d = decode_udp(data)
            data = d['data']

            pduSource = Address((pduSource, d['source_port']))
            pduDestination = Address((pduDestination, d['destination_port']))
            if _debug:
                decode_packet._debug("    - pduSource: %r", pduSource)
                decode_packet._debug("    - pduDestination: %r",
                                     pduDestination)
        else:
            if _debug: decode_packet._debug("    - not a UDP packet")
            return None
    else:
        if _debug: decode_packet._debug("    - not an IP packet")
        return None

    # check for empty
    if not data:
        if _debug: decode_packet._debug("    - empty packet")
        return None

    # build a PDU
    pdu = PDU(data, source=pduSource, destination=pduDestination)

    # check for a BVLL header
    if (pdu.pduData[0] == '\x81'):
        if _debug: decode_packet._debug("    - BVLL header found")

        xpdu = BVLPDU()
        xpdu.decode(pdu)
        pdu = xpdu

        # make a more focused interpretation
        atype = bvl_pdu_types.get(pdu.bvlciFunction)
        if not atype:
            if _debug:
                decode_packet._debug("    - unknown BVLL type: %r",
                                     pdu.bvlciFunction)
            return pdu

        # decode it as one of the basic types
        try:
            xpdu = pdu
            bpdu = atype()
            bpdu.decode(pdu)
            if _debug: decode_packet._debug("    - bpdu: %r", bpdu)

            pdu = bpdu

            # lift the address for forwarded NPDU's
            if atype is ForwardedNPDU:
                pdu.pduSource = bpdu.bvlciAddress
            # no deeper decoding for some
            elif atype not in (DistributeBroadcastToNetwork,
                               OriginalUnicastNPDU, OriginalBroadcastNPDU):
                return pdu

        except Exception, err:
            if _debug: decode_packet._debug("    - decoding Error: %r", err)
            return xpdu
Example #11
0
def decode_packet(data):
    """decode the data, return some kind of PDU."""
    if _debug: decode_packet._debug("decode_packet %r", data)

    # empty strings are some other kind of pcap content
    if not data:
        return None

    # assume it is ethernet for now
    d = decode_ethernet(data)
    data = d['data']

    # there could be a VLAN header
    if (d['type'] == 0x8100):
        if _debug: decode_packet._debug("    - vlan found")

        d = decode_vlan(data)
        data = d['data']

    # look for IP packets
    if (d['type'] == 0x0800):
        if _debug: decode_packet._debug("    - IP found")

        d = decode_ip(data)
        pduSource, pduDestination = d['source_address'], d['destination_address']
        data = d['data']

        if (d['protocol'] == 'udp'):
            if _debug: decode_packet._debug("    - UDP found")

            d = decode_udp(data)
            data = d['data']

            pduSource = Address((pduSource, d['source_port']))
            pduDestination = Address((pduDestination, d['destination_port']))
            if _debug:
                decode_packet._debug("    - pduSource: %r", pduSource)
                decode_packet._debug("    - pduDestination: %r", pduDestination)
        else:
            if _debug: decode_packet._debug("    - not a UDP packet")
            return None
    else:
        if _debug: decode_packet._debug("    - not an IP packet")
        return None

    # check for empty
    if not data:
        if _debug: decode_packet._debug("    - empty packet")
        return None

    # build a PDU
    pdu = PDU(data, source=pduSource, destination=pduDestination)

    # check for a BVLL header
    if (pdu.pduData[0] == '\x81'):
        if _debug: decode_packet._debug("    - BVLL header found")

        xpdu = BVLPDU()
        xpdu.decode(pdu)
        pdu = xpdu

        # make a more focused interpretation
        atype = bvl_pdu_types.get(pdu.bvlciFunction)
        if not atype:
            if _debug: decode_packet._debug("    - unknown BVLL type: %r", pdu.bvlciFunction)
            return pdu

        # decode it as one of the basic types
        try:
            xpdu = pdu
            bpdu = atype()
            bpdu.decode(pdu)
            if _debug: decode_packet._debug("    - bpdu: %r", bpdu)

            pdu = bpdu

            # lift the address for forwarded NPDU's
            if atype is ForwardedNPDU:
                pdu.pduSource = bpdu.bvlciAddress
            # no deeper decoding for some
            elif atype not in (DistributeBroadcastToNetwork, OriginalUnicastNPDU, OriginalBroadcastNPDU):
                return pdu

        except Exception, err:
            if _debug: decode_packet._debug("    - decoding Error: %r", err)
            return xpdu
Example #12
0
def makePacket(type, seq_number, offset, data, src_ip, dest_ip):
    packet = PDU(type, seq_number, offset, 0, data)
    packet.packet["csum"] = checksum_calc(data, src_ip, dest_ip)
    return [packet]
Example #13
0
def read_current(ip, port):
    p = PDU(ip)
    c = p.port_info(port, 'current')
    del p
    return c
Example #14
0
    while True:
        try:
            # Create station instance
            aavs_station = station.Station(station.configuration)
            aavs_station.connect()
            _connect_station(aavs_station)

            pdu_list = getPDUinfo(PDU_FILE)
            pdu_handler = []
            for i in range(nof_tiles):
                tile_pdu, tile_port = [
                    (k[1], int(k[2])) for k in pdu_list
                    if k[0] == aavs_station.tiles[i].get_ip()
                ][0]
                pdu_handler += [(PDU(tile_pdu), tile_port)]

            while True:
                try:
                    logging.info("\n\nReading current and temperatures...")
                    for i in range(nof_tiles):
                        logging.info(
                            "Tile %02d\tIP: %s\tCurrent: %3.1f\tBoard: %3.1f\tFPGA-0: %3.1f\tFPGA-1: %3.1f"
                            % (i + 1, aavs_station.tiles[i].get_ip(),
                               pdu_handler[i][0].port_info(
                                   pdu_handler[i][1], 'current'),
                               aavs_station.tiles[i].get_temperature(),
                               aavs_station.tiles[i].get_fpga0_temperature(),
                               aavs_station.tiles[i].get_fpga1_temperature()))
                    time.sleep(opts.interval)
                except KeyboardInterrupt:
 def _load_pdu_devices(self):
     self.pdu_devices = {}
     for id, settings in self._conf.get_sections_by_prefix("pdu"):
         self.pdu_devices[id] = PDU(id, settings)
def decode_packet(data):
    """decode the data, return some kind of PDU."""
    if _debug: decode_packet._debug("decode_packet %r", data)

    # empty strings are some other kind of pcap content
    if not data:
        return None

    # assume it is ethernet for now
    d = decode_ethernet(data)
    data = d['data']

    # there could be a VLAN header
    if (d['type'] == 0x8100):
        if _debug: decode_packet._debug("    - vlan found")

        d = decode_vlan(data)
        data = d['data']

    # look for IP packets
    if (d['type'] == 0x0800):
        if _debug: decode_packet._debug("    - IP found")

        d = decode_ip(data)
        pduSource, pduDestination = d['source_address'], d[
            'destination_address']
        data = d['data']

        if (d['protocol'] == 'udp'):
            if _debug: decode_packet._debug("    - UDP found")

            d = decode_udp(data)
            data = d['data']

            pduSource = Address((pduSource, d['source_port']))
            pduDestination = Address((pduDestination, d['destination_port']))
            if _debug:
                decode_packet._debug("    - pduSource: %r", pduSource)
                decode_packet._debug("    - pduDestination: %r",
                                     pduDestination)
        else:
            if _debug: decode_packet._debug("    - not a UDP packet")
            return None
    else:
        if _debug: decode_packet._debug("    - not an IP packet")
        return None

    # check for empty
    if not data:
        if _debug: decode_packet._debug("    - empty packet")
        return None

    # build a PDU
    pdu = PDU(data, source=pduSource, destination=pduDestination)

    # check for a BVLL header
    if (pdu.pduData[0] == '\x81'):
        if _debug: decode_packet._debug("    - BVLL header found")

        xpdu = BVLPDU()
        xpdu.decode(pdu)
        pdu = xpdu

        # make a more focused interpretation
        atype = bvl_pdu_types.get(pdu.bvlciFunction)
        if not atype:
            if _debug:
                decode_packet._debug("    - unknown BVLL type: %r",
                                     pdu.bvlciFunction)
            return pdu

        # decode it as one of the basic types
        try:
            xpdu = pdu
            bpdu = atype()
            bpdu.decode(pdu)
            if _debug: decode_packet._debug("    - bpdu: %r", bpdu)

            pdu = bpdu

            # lift the address for forwarded NPDU's
            if atype is ForwardedNPDU:
                pdu.pduSource = bpdu.bvlciAddress
            # no deeper decoding for some
            elif atype not in (DistributeBroadcastToNetwork,
                               OriginalUnicastNPDU, OriginalBroadcastNPDU):
                return pdu

        except Exception as err:
            if _debug: decode_packet._debug("    - decoding Error: %r", err)
            return xpdu

    # check for version number
    if (pdu.pduData[0] != '\x01'):
        if _debug:
            decode_packet._debug("    - not a version 1 packet: %s...",
                                 _hexify(pdu.pduData[:30]))
        return None

    # it's an NPDU
    try:
        npdu = NPDU()
        npdu.decode(pdu)
    except Exception as err:
        if _debug: decode_packet._debug("    - decoding Error: %r", err)
        return None

    # application or network layer message
    if npdu.npduNetMessage is None:
        if _debug:
            decode_packet._debug(
                "    - not a network layer message, try as an APDU")

        # decode as a generic APDU
        try:
            xpdu = APDU()
            xpdu.decode(npdu)
            apdu = xpdu
        except Exception as err:
            if _debug: decode_packet._debug("    - decoding Error: %r", err)
            return npdu

        # "lift" the source and destination address
        if npdu.npduSADR:
            apdu.pduSource = npdu.npduSADR
        else:
            apdu.pduSource = npdu.pduSource
        if npdu.npduDADR:
            apdu.pduDestination = npdu.npduDADR
        else:
            apdu.pduDestination = npdu.pduDestination

        # make a more focused interpretation
        atype = apdu_types.get(apdu.apduType)
        if not atype:
            if _debug:
                decode_packet._debug("    - unknown APDU type: %r",
                                     apdu.apduType)
            return apdu

        # decode it as one of the basic types
        try:
            xpdu = apdu
            apdu = atype()
            apdu.decode(xpdu)
        except Exception as err:
            if _debug: decode_packet._debug("    - decoding Error: %r", err)
            return xpdu

        # decode it at the next level
        if isinstance(apdu, ConfirmedRequestPDU):
            atype = confirmed_request_types.get(apdu.apduService)
            if not atype:
                if _debug:
                    decode_packet._debug(
                        "    - no confirmed request decoder: %r",
                        apdu.apduService)
                return apdu

        elif isinstance(apdu, UnconfirmedRequestPDU):
            atype = unconfirmed_request_types.get(apdu.apduService)
            if not atype:
                if _debug:
                    decode_packet._debug(
                        "    - no unconfirmed request decoder: %r",
                        apdu.apduService)
                return apdu

        elif isinstance(apdu, SimpleAckPDU):
            atype = None

        elif isinstance(apdu, ComplexAckPDU):
            atype = complex_ack_types.get(apdu.apduService)
            if not atype:
                if _debug:
                    decode_packet._debug("    - no complex ack decoder: %r",
                                         apdu.apduService)
                return apdu

        elif isinstance(apdu, SegmentAckPDU):
            atype = None

        elif isinstance(apdu, ErrorPDU):
            atype = error_types.get(apdu.apduService)
            if not atype:
                if _debug:
                    decode_packet._debug("    - no error decoder: %r",
                                         apdu.apduService)
                return apdu

        elif isinstance(apdu, RejectPDU):
            atype = None

        elif isinstance(apdu, AbortPDU):
            atype = None
        if _debug: decode_packet._debug("    - atype: %r", atype)

        # deeper decoding
        try:
            if atype:
                xpdu = apdu
                apdu = atype()
                apdu.decode(xpdu)
        except Exception as err:
            if _debug: decode_packet._debug("    - decoding error: %r", err)
            return xpdu

        # success
        return apdu

    else:
        # make a more focused interpretation
        ntype = npdu_types.get(npdu.npduNetMessage)
        if not ntype:
            if _debug:
                decode_packet._debug("    - no network layer decoder: %r",
                                     npdu.npduNetMessage)
            return npdu
        if _debug: decode_packet._debug("    - ntype: %r", ntype)

        # deeper decoding
        try:
            xpdu = npdu
            npdu = ntype()
            npdu.decode(xpdu)
        except Exception as err:
            if _debug: decode_packet._debug("    - decoding error: %r", err)
            return xpdu

        # success
        return npdu