''' OSC packet serializer/parser ''' import struct import traceback def __string_to_osc(s: str) -> bytes: ''' Convert python string to OSC-string ''' data = s.encode('ascii') to_append = 4 - (len(data) % 4) data += b'\0' * to_append return data def serialize(addr: str, data: list | None = None, log_error : bool = True) -> bytearray | None: ''' Serializes OSC data into bytearray. Refer to README.md for more info. ''' try: # no args if data is None: data = [] type_tag = ',' osc_data = bytes() for d in data: d_type = type(d) # int if d_type is int: type_tag += 'i' osc_data += struct.pack('>i', d) # float elif d_type is float: type_tag += 'f' osc_data += struct.pack('>f', d) # string elif d_type is str: type_tag += 's' osc_data += __string_to_osc(d) # unsuported else: if log_error: print('[!] OSC packet serialize: unsupported data type was provided in \'data\'!') print(' * address: %s' % addr) print(' * data: %s' % data) print(' (bad type is %s)' % d_type) return None # convert type tag to OSC-string type_tag = __string_to_osc(type_tag) # create OSC packet return bytearray(__string_to_osc(addr) + type_tag + osc_data) except: if log_error: traceback.print_exc() return None