Beispiel #1
0
 def pack(self):
     bytes = b''
     # pack pressure
     bytes += s_pack("d", self.pressure)
     # pack temperature
     bytes += s_pack("d", self.temperature)
     return bytes
Beispiel #2
0
    def _set_length(self, length: int) -> None:
        """Encode length according to ASN.1 BER.

        `raw_length` will be of 1 byte long if < 128.
        If it's 2+ bytes long, the first byte indicates how many
        bytes follows.

        Example:
            128 == b'\x81\x80', where 0x81 indicates 1 extra byte
            for the length, and 0x80 is the length itself.

        Args:
            length: The length to be encoded.

        Raises:
            ValueError: If `length` is greater than `0xFFFF`.
        """
        # NOTE enable extra_length > 2?
        # NOTE indefinite length?
        if 0 <= length < 0x80:
            self._raw_length = s_pack('!B', length)
        elif 0x80 <= length <= 0xFF:
            self._raw_length = s_pack('!BB', 0x81, length)
        elif 0xFF < length <= 0xFFFF:
            self._raw_length = s_pack('!BH', 0x82, length)
        else:
            raise ValueError(f'data length greater than {0xFFFF}')
        self._length = length
Beispiel #3
0
 def pack(self):
     bytes = b''
     # pack lat
     bytes += s_pack("d", self.lat)
     # pack lon
     bytes += s_pack("d", self.lon)
     # pack alt
     bytes += s_pack("f", self.alt)
     return bytes
Beispiel #4
0
 def pack(self):
    bytes = b''
    # pack accx
    bytes += s_pack("d",self.accx)
    # pack accy
    bytes += s_pack("d",self.accy)
    # pack accz
    bytes += s_pack("d",self.accz)
    return bytes
Beispiel #5
0
 def pack(self):
    bytes = b''
    # pack position
    bytes += self.position.pack()
    # pack age
    bytes += s_pack("Q",self.age)
    # pack sats
    bytes += s_pack("h",self.sats)
    return bytes
Beispiel #6
0
    def _encode(value: Tuple[float, Quality]) -> bytes:
        value, quality = value
        if not isinstance(value, float):
            raise_type('value', float, type(value))
        if not isinstance(quality, Quality):
            raise_type('quality', Quality, type(quality))

        seconds, fraction = map(int, str(value).split('.'))
        byte_stream = s_pack('!I', seconds)
        byte_stream += s_pack('!I', fraction)[1:]
        return byte_stream + bytes(quality)
Beispiel #7
0
 def _encode(value: int) -> bytes:
     if not isinstance(value, int):
         raise_type('value', int, type(value))
     if -0x80 <= value < 0x80:
         return s_pack('!b', value)
     elif -0x8000 <= value < 0x8000:
         return s_pack('!h', value)
     elif -0x80000000 <= value < 0x80000000:
         return s_pack('!i', value)
     elif -0x80 ** 0x9 <= value < 0x80 ** 0x9:  # NOTE change support from 64 to 128?
         return s_pack('!q', value)
     raise ValueError('Signed integer out of supported range')
Beispiel #8
0
    def __init__(self, group_addr, group_port, data_q = None, buffer_size = 65536, name="", iface_ip=None):
        # set thread properties
        Process.__init__(self)
        self.alive = Event()
        self.alive.clear()
        self.daemon = True
        
        # set class attributes
        self.address = group_addr
        self.port = group_port
        self.buffer_size = buffer_size
        self.name = name
        self.data_q = data_q
        self.max_qsize = 512

        # init socket as inet udp multicast
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        group = socket.inet_aton(self.address)
        if iface_ip is None:
            mreq = s_pack('=4sl', group, socket.INADDR_ANY)
        else:
            # 
            print iface_ip
            mreq = group + socket.inet_aton(iface_ip)
            self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(iface_ip))

        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        self.sock.bind((self.address,self.port))
Beispiel #9
0
 def pack(self, val):
     '''Return a binary string packing `val`. If :attr:`sfmt` is None then this method MUST be
        overridden. Raise :class:`ValueError` or :class:`TypeError` if `val` cannot be packed.
     '''
     if self.sfmt is None:
         raise NotImplementedError()
     return s_pack('>' + self.sfmt, val)
Beispiel #10
0
 def request(self, service_name, data=""):
     """
     这里将数据写到缓冲队列,然后让当前请求协程在event上等待
     """
     if self._is_closed:
         logging.error("request in a close cliet")
         raise Exception("connection closed")
     rid = self.rid
     req = (service_name, data, rid)
     req_data = cp_dumps(req)
     req_data_len = len(req_data)
     head = s_pack("i", req_data_len)
     self._send_data.extend((head, req_data))
     if not self._write_open:
         self._write()                                          # 立即尝试写一下,可以降低延迟
         self._start_write()
     event = AsyncResult()
     self._events[rid] = event
     try:
         out = event.get(timeout=DEFAULT_REQUEST_TIMEOUT)       # 在这个event上面等待,阻塞当前协程
         if self._is_closed:
             raise Exception("connection disconnected")
         return out
     finally:
         del self._events[rid]
Beispiel #11
0
 def enet_itom(integer):
     # integer to mac
     if isinstance(integer, int):
         if 0 <= integer < U48:
             return s_pack('!Q', integer)[2:]
         raise ValueError('integer out of supported range')
     raise_type('integer', int, type(integer))
Beispiel #12
0
 def request(self, service_name, data=""):
     """
     这里将数据写到缓冲队列,然后让当前请求协程在event上等待
     """
     if self._is_closed:
         logging.error("request in a close cliet")
         raise Exception("connection closed")
     rid = self.rid
     req = (service_name, data, rid)
     req_data = cp_dumps(req)
     req_data_len = len(req_data)
     head = s_pack("i", req_data_len)
     self._send_data.extend((head, req_data))
     if not self._write_open:
         self._write()  # 立即尝试写一下,可以降低延迟
         self._start_write()
     event = AsyncResult()
     self._events[rid] = event
     try:
         out = event.get(
             timeout=DEFAULT_REQUEST_TIMEOUT)  # 在这个event上面等待,阻塞当前协程
         if self._is_closed:
             raise Exception("connection disconnected")
         return out
     finally:
         del self._events[rid]
Beispiel #13
0
 def enet_itoe(integer, max_range=0xFFFF):
     # integer to ether type
     if isinstance(integer, int):
         if 0 <= integer <= max_range:
             return s_pack('!H', integer)
         raise ValueError('integer out of supported range')
     raise_type('integer', int, type(integer))
Beispiel #14
0
 def enet_stoe(string):
     # string to ether type
     if isinstance(string, str):
         if len(string) == 4:
             return s_pack('!H', int(string, 16))
         raise ValueError('string out of supported length')
     raise_type('string', str, type(string))
Beispiel #15
0
 def _encode(self, value: int) -> bytes:
     if not isinstance(value, int):
         raise_type('value', int, type(value))
     if value < 0:
         raise ValueError('Unsigned integer cannot be negative')
     elif value <= 0xFF and self._min_range <= value <= self._max_range:
         return s_pack('!B', value)
     elif value <= 0xFFFF and self._min_range <= value <= self._max_range:
         return s_pack('!H', value)
     # elif value <= 0xFFFFFF and self._min_range <= value <= self._max_range:
     #     # NOTE regular MMS does not have 24 bits unsigned int
     #     # NOTE 24 bits unsigned int seems to be used only for timestamp
     #     return s_pack('!I', value)[1:]
     elif value <= 0xFFFFFFFF and self._min_range <= value <= self._max_range:
         return s_pack('!I', value)
     raise ValueError('Unsigned integer out of supported range')
Beispiel #16
0
 def __bytes__(self):
     header = self._raw_destination + self._raw_source + self._ether_type
     if self._virtual_lan:
         header += bytes(self._virtual_lan)
     start = self._raw_app_id
     # TODO Implement LENGTH
     end = self._reserved + bytes(self._pdu)
     return header + start + s_pack('!H', len(start + end) + 2) + end
Beispiel #17
0
def int_u16(integer: int,
            min_range: int = 0,
            max_range: int = 0xFFFF) -> bytes:
    if isinstance(integer, int):
        if min_range <= integer <= max_range:
            return s_pack('!H', integer)
        raise ValueError('integer out of supported range')
    raise_type('integer', int, type(integer))
 def send(self, message):
     try:
         data = m_pack(message)
     except Exception as exception:
         print 'Output error:', exception
     else:
         data_size = len(data)
         if data_size > 65536:
             print 'Output error: message too big to be sent'
         else:
             data_size = s_pack('!I', data_size)
             self.wfile.write(data_size + data)
             self.wfile.flush()
Beispiel #19
0
 def send(self, message):
     try:
         data = m_pack(message)
     except Exception as exception:
         print 'Output error:', exception
     else:
         data_size = len(data)
         if data_size > 65536:
             print 'Output error: message too big to be sent'
         else:
             data_size = s_pack('!I', data_size)
             self.wfile.write(data_size + data)
             self.wfile.flush()
Beispiel #20
0
    def write(self, data):
        """
        这里写直接实现成了非阻塞的,目的是为了尽快释放业务协程
        (1)先直接将数据写到当前的数据队列里面去
        (2)检查当前进程是不是打开了写监听,如果是的话,那么就不用管了,说明当前socket已经挂起了写事件,
            但是还在等待写事件的回调,

        注意:存在一些状况,当前连接其实已经关闭了,但是业务层返回数据来发送,这个时候就直接忽略数据,
            因为确实存在业务层都还没有执行完,还有这个socket的引用,但是其实底层已经断开了
        """
        if self._closed:
            return
        length = len(data) if data else 0
        header_data = s_pack("i", length)             # 构建数据的头部
        self._send_data.extend((header_data, data))   # 将头部和数据加入到发送队列里面
        if not self._write_open:                      # 如果没有激活写watcher,那么这里打开
            self._start_write()
Beispiel #21
0
def pack(tup, precision='d', output='chr'):
	if np.size(tup) == 1:
		try: len(tup)
		except: tup=(tup,)
	if precision not in set(['d', 'f']):
		raise ValueError("Optional argument precision must be either 'f' (single precision) or 'd' (double precision).")
	if output not in set(['chr', 'ord']):
		raise ValueError("Optional argument output must be wither 'chr' (pack into string) or 'ord' (pack into array of uint8)")
	l = []
	for var in tup:
		t   = None
		arr = False
		if type(var) == int:
			t='i'
		elif type(var) == float:
			t=precision
		elif type(var) == np.float32:
			t=precision
		elif type(var) == np.float64:
			t=precision
		elif type(var) == np.ndarray:
			arr = True
			if var.dtype == np.dtype(int):
				t='i'
			elif var.dtype == np.dtype(float):
				t=precision
			elif var.dtype == np.float32:
				t=precision
		if not t:
			if arr:
				raise ValueError("Unrecognized type: "+str(var.dtype)+".")
			else:
				raise ValueError("Unrecognized type: "+str(type(var))+".")
		if arr:
			l += [array(t, var).tostring()]
		else:
			l += [s_pack(t, var)]
	stream = ''.join(l)
	if output == 'chr':
		return stream
	else:
		out = np.empty((len(stream)), dtype=np.uint8)
		for i in range(len(stream)):
			out[i] = ord(stream[i])
		return out
Beispiel #22
0
    def _encode(self, value: Tuple[bool, bool, bool, int]) -> bytes:
        leap_seconds_known, clock_failure, clock_not_synchronized, time_accuracy = value
        if not isinstance(leap_seconds_known, bool):
            raise_type('leap_seconds_known', bool, type(leap_seconds_known))
        if not isinstance(clock_failure, bool):
            raise_type('clock_failure', bool, type(clock_failure))
        if not isinstance(clock_not_synchronized, bool):
            raise_type('clock_not_synchronized', bool, type(clock_not_synchronized))
        if not isinstance(time_accuracy, int):
            raise_type('time_accuracy', int, type(time_accuracy))

        if 0 <= time_accuracy <= 24 or time_accuracy == 0x1F:
            self._accuracy = time_accuracy
        else:
            raise ValueError('time_accuracy out of supported range')

        bits = (leap_seconds_known << 7) + (clock_failure << 6) + \
               (clock_not_synchronized << 5) + time_accuracy
        return s_pack('!B', bits)
Beispiel #23
0
    def __init__(self,
                 group_addr,
                 group_port,
                 data_q=None,
                 buffer_size=65536,
                 name="",
                 iface_ip=None):
        # set thread properties
        Process.__init__(self)
        self.alive = Event()
        self.alive.clear()
        self.daemon = True

        # set class attributes
        self.address = group_addr
        self.port = group_port
        self.buffer_size = buffer_size
        self.name = name
        self.data_q = data_q
        self.max_qsize = 512

        # init socket as inet udp multicast
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                                  socket.IPPROTO_UDP)
        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        group = socket.inet_aton(self.address)
        if iface_ip is None:
            mreq = s_pack('=4sl', group, socket.INADDR_ANY)
        else:
            #
            print iface_ip
            mreq = group + socket.inet_aton(iface_ip)
            self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF,
                                 socket.inet_aton(iface_ip))

        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        self.sock.bind((self.address, self.port))
Beispiel #24
0
 def packHeader(self):
     uid = uids.Position3D_Uid
     # pack uid
     return s_pack("I", uid)
Beispiel #25
0
 def packHeader(self):
    uid = uids.Acceleration_Uid
    # pack uid
    return s_pack("I",uid)
Beispiel #26
0
 def packHeader(self):
    uid = uids.Gps_Uid
    # pack uid
    return s_pack("I",uid)
Beispiel #27
0
 def _encode(self, value: float) -> bytes:
     if not isinstance(value, float):
         raise_type('value', float, type(value))
     return self._exponent + s_pack(self._format, value)
Beispiel #28
0
 def packHeader(self):
     uid = uids.Barometer_Uid
     # pack uid
     return s_pack("I", uid)
Beispiel #29
0
 def set_radar_range_mts(self,new_range):
     if new_range >= 50 and new_range <= 24000:
         range_hex = s_pack('<I',new_range*10)
         self.send_command(self.CMD_RANGE,range_hex)
         return True
     return False
Beispiel #30
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from json import loads
from msgpack import packb as m_pack
from socket import AF_INET, SOCK_STREAM, socket
from struct import pack as s_pack
from sys import argv, exit


if __name__ == '__main__':
    if len(argv) < 3:
        print "usage: dummy_client.py <host> <port>"
        exit(1)

    s = socket(AF_INET, SOCK_STREAM)
    s.connect((argv[1], int(argv[2])))

    while 1:
        try:
            data = m_pack(loads(raw_input('json > ')))
            data_size = s_pack('!I', len(data))
            s.sendall(data_size + data)
        except Exception as e:
            print e
Beispiel #31
0
 def set_radar_range_mts(self, new_range):
     if new_range >= 50 and new_range <= 24000:
         range_hex = s_pack('<I', new_range * 10)
         self.send_command(self.CMD_RANGE, range_hex)
         return True
     return False
Beispiel #32
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from json import loads
from msgpack import packb as m_pack
from socket import AF_INET, SOCK_STREAM, socket
from struct import pack as s_pack
from sys import argv, exit

if __name__ == '__main__':
    if len(argv) < 3:
        print "usage: dummy_client.py <host> <port>"
        exit(1)

    s = socket(AF_INET, SOCK_STREAM)
    s.connect((argv[1], int(argv[2])))

    while 1:
        try:
            data = m_pack(loads(raw_input('json > ')))
            data_size = s_pack('!I', len(data))
            s.sendall(data_size + data)
        except Exception as e:
            print e
Beispiel #33
0
 def __bytes__(self):
     prio_dei = self._priority << 1  # add the DPI bit (which is always 0)
     vlan_data = (prio_dei << 12) + self._vid
     return s_pack('!H', vlan_data) + self._ether_type