def parse_dci_0_0(dci_hex_bytes): dci = pd.Series() bit_stream = bitstring.BitStream(dci_hex_bytes) dci['ul_fmt'] = bit_stream.read('uint:1') #dci['rballoc_type'] = bit_stream.read('uint:1') #dci['riv'] = bit_stream.read('uint:16') dci['ul_startPrb'], dci['ul_Prbnum'] = riv2startandlen(bit_stream.read('uint:16'), bwp_rbnum=51) dci['ul_timealloc'] = bit_stream.read('uint:2') dci['ul_hop'] = bit_stream.read('uint:1') dci['ul_mcs'] = bit_stream.read('uint:5') dci['ul_ndi'] = bit_stream.read('uint:1') dci['ul_rv'] = bit_stream.read('uint:2') dci['ul_harqid'] = bit_stream.read('uint:4') dci['ul_tpc'] = bit_stream.read('uint:2') return dci
def bins_from_string(bs, search_header=True): """ :param bs: :param search_header: :return: :rtype: bitstring.BitStream """ header = b'BUFR' if search_header: idx_header = bs.find(header) if idx_header != -1: bs = bs[bs.find(header):] else: raise BpclError('Cannot find starting signature: {}'.format(header)) return bitstring.BitStream(bytes=bs)
def write_ts(bs, new_ts): new_ts_bin = bin(new_ts) new_ts_bin_len = len(new_ts_bin) - 2 ts_bits33 = bitstring.BitStream(length=33) ts_bits33.overwrite(new_ts_bin, pos=-new_ts_bin_len) ts_bits33.pos = 0 # print('writ', ts_bits33.bin) part1 = ts_bits33.read(3) part2 = ts_bits33.read(15) part3 = ts_bits33.read(15) bs.pos += 4 bs.overwrite(part1) bs.pos += 1 bs.overwrite(part2) bs.pos += 1 bs.overwrite(part3) bs.pos += 1
def sendCmdToQueue(self, command: bytes, data: bytes): # attachData = None # if data is not None and len(data) > 0: # attachData = True stream = bitstring.BitStream() stream.append("int:32=" + str(len(self.sessionId))) stream.append(bytearray(self.sessionId, encoding="utf-8")) stream.append("int:8=" + str(command)) if data is not None: stream.append(data) self.commandChannel.basic_publish(exchange=self.commandExchangeName, routing_key="", body=stream.bytes)
def __init__(self, master=None): self.nb = 1024 self.chipNum = 0 self.bitFlips = None self.bits = bitstring.BitStream(uint=0, length=self.nb) self.reset() self.bigfont = tkFont.Font(family="Helvetica", size=12) self.font = tkFont.Font(family="Helvetica", size=10) self.squareSize = int(math.sqrt(self.nb)) self.zoomFactor = int(480 / self.squareSize) self.colorMapFun = self.mapBitGrayscale Frame.__init__(self, master) master.protocol("WM_DELETE_WINDOW", self._delete_window) self.statusStr = 'Not Connected' self.updateTitle() self.grid() self.createWidgets()
def decode_normal_entry(entry_bytes): stream = bitstring.BitStream(bytes=entry_bytes) fat_file = FatFile() fat_file.name = stream.read('bytes:11').decode().strip() raw_attrs = stream.readlist(['2', '1', '1', '1', '1', '1', '1']) raw_attrs.reverse() fat_file.attrs = raw_attrs reserved = stream.read('bytes:1') fat_file.create_time = stream.read('uintle:24') fat_file.create_date = stream.read('uintle:16') fat_file.last_access_date = stream.read('uintle:16') zeros = stream.read('bytes:2') fat_file.last_modified_time = stream.read('uintle:16') fat_file.last_modified_date = stream.read('uintle:16') fat_file.first_cluster = stream.read('uintle:16') fat_file.file_size = stream.read('uintle:32') return fat_file
def to_bytes(self): """Encode packet to utf-8 byte sequence.""" bs = bitstring.BitArray(length=384) bs[0:2] = bitstring.pack('uint: 2', self.__li) bs[2:5] = bitstring.pack('uint: 3', self.__vn) bs[5:8] = bitstring.pack('uint: 3', self.__mode) bs[8:16] = bitstring.pack('uint: 8', self.__stratum) bs[16:24] = bitstring.pack('uint: 8', self.__poll) bs[24:32] = bitstring.pack('int: 8', self.__precision) bs[32:64] = bitstring.pack('int: 32', self.__root_delay) bs[64:96] = bitstring.pack('int: 32', self.__root_dispersion) bs[96:128] = bitstring.BitStream(self.__reference_id) bs[128:192] = bitstring.pack('uint: 64', self.__reference_timestamp) bs[192:256] = bitstring.pack('uint: 64', self.__originate_timestamp) bs[256:320] = bitstring.pack('uint: 64', self.__receive_timestamp) bs[320:384] = bitstring.pack('uint: 64', self.__transmit_timestamp) return bs.tobytes()
def from_hex(self, data): reversed_bytes = bitstring.BitArray(bytearray(reversed(data))) reversed_bits = bitstring.BitStream(reversed(reversed_bytes)) for phase in ['I', 'II', 'III']: intensidad_dA = bitstring.BitArray(reversed(reversed_bits.read(24))).uint # in dA tension_dV = bitstring.BitArray(reversed(reversed_bits.read(30))).uint # in dV bitstring.BitArray(reversed(reversed_bits.read(1))) # not used invalid = bitstring.BitArray(reversed(reversed_bits.read(1))).bool # valid 0/invalid 1 ipiv = InstantPhaseVI(phase, intensidad_dA / 10.0, tension_dV / 10.0, not invalid) self.valores.append(ipiv) dt = TimeA() dt.from_hex(data[21:26]) self.valores.append(dt) return self.valores
def from_hex(self, data): reversed_bytes = bitstring.BitArray(bytes(reversed(data))) reversed_bits = bitstring.BitStream(reversed(reversed_bytes)) self.minute = bitstring.BitArray(reversed(reversed_bits.read(6))).uint self.TIS = reversed_bits.read(1).uint self.IV = reversed_bits.read(1).uint self.hour = bitstring.BitArray(reversed(reversed_bits.read(5))).uint self.RES1 = bitstring.BitArray(reversed(reversed_bits.read(2))).uint self.SU = reversed_bits.read(1).uint self.dayofmonth = bitstring.BitArray(reversed(reversed_bits.read(5)))\ .uint self.dayofweek = bitstring.BitArray(reversed(reversed_bits.read(3)))\ .uint self.month = bitstring.BitArray(reversed(reversed_bits.read(4))).uint self.ETI = bitstring.BitArray(reversed(reversed_bits.read(2))).uint self.PTI = bitstring.BitArray(reversed(reversed_bits.read(2))).uint self.year = bitstring.BitArray(reversed(reversed_bits.read(7))).uint self.RES2 = reversed_bits.read(1).uint
def pack9_to_ascii(x): """ 8 bit byte ascii string to 9 bit byte ascii string """ bits = "" # pad to for char in x: bits += bin(ord(char))[2:].rjust(9, "0") pad = len(bits) % 8 if pad: bits += "0" * (8 - pad) bits = "0b" + bits bstream = bitstring.BitStream(bits) return bstream.read(len(bstream)).hex.decode("hex")
def unpack_blob_to_json(self, blob:bytes) -> str: """ unpacks the BSM_Blob received from VISSIM and returns the JSON string filled with received values """ # Unpack the blob: blob = bitstring.BitStream(blob).unpack(self.blobStructure) # Validate the vehicle type and convert it into a string: if blob[10] in VEH_TYPE_DICT.keys(): vehicle_Type = VEH_TYPE_DICT[blob[10]] else: vehicle_Type = VEH_TYPE_DICT[0] # Formulate JSON object containing BSM information: bsmJson = { "MsgType": "BSM", "Timestamp_posix": time.time(), "Timestamp_verbose": str(datetime.datetime.now()), "BasicVehicle": { "msgCount" : blob[0], "temporaryID": blob[1], "secMark_Second": blob[2], "speed_MeterPerSecond": (blob[6] / MULTIPLIER_SPEED), "heading_Degree": (blob[7] / MULTIPLIER_HEADING), "type": vehicle_Type, "position": { "latitude_DecimalDegree": (blob[3] / MULTIPLIER_LATITUDE), "longitude_DecimalDegree": (blob[4] / MULTIPLIER_LONGITUDE), "elevation_Meter": (blob[5] / MULTIPLIER_ELEVATION) }, "size": { "length_cm": (blob[8] / MULTIPLIER_LENGTH), "width_cm": (blob[9] / MULTIPLIER_WIDTH) } } } # Convert the JSON object into a JSON string: bsmJson = json.dumps(bsmJson) # Return the JSON string: return bsmJson
def test242pixels(): brightness = 1 period = 22.0 pixels = bitstring.BitStream() for i in range(242): red = int(127 + 127 * math.cos(2 * math.pi * (i / period))) green = int(127 + 127 * math.cos(2 * math.pi * ((i + period / 3) / period))) blue = int(127 + 127 * math.cos(2 * math.pi * ((i + 2 * period / 3) / period))) pixels += led_frame(red, green, blue, brightness) while (True): data = start_frame data += pixels data += end_frame #print(data) gf.vendor_request_out(vendor_requests.SPI_WRITE, data=data.bytes) time.sleep(0.1) pixels.ror(32)
def init( self, obj ): ''' Initialize a field value based on its ftype. ''' ftype = self.TypeCode attr = self.Name if 'intbe' in ftype or ftype.startswith('bits'): setattr( obj, attr, self.Default if self.Default else 0 ) elif ftype == 'bool': setattr( obj, attr, False ) elif ftype == 'string': setattr( obj, attr, u'' ) elif ftype.startswith('array'): setattr( obj, attr, [] ) elif ftype == 'bitarray': setattr( obj, attr, bytes() ) elif ftype == 'bytesToEnd': assert False setattr( obj, attr, bitstring.BitStream() ) else: assert ftype.startswith('skip'), 'Unknown field type: "{}"'.format(ftype)
def pack(self, data): '''Transform a structured format into a binary representation.''' bits = bitstring.BitStream() if hasattr(data, '__pack__'): data.__pack__() for f in self._fieldlist: logging.debug('packing field %s as "%s"' % (f.name, f.spec)) try: bits.append(f.pack(data[f.name])) except KeyError: try: bits.append(f.pack(f.default)) except AttributeError: raise KeyError(f.name) return bits
def get_reply(self): """Waits for and returns Reply. Returns: First complete reply if expected message ID was not specified, otherwise first complete reply of expected message ID. Raises: PacketCorrupted: Packet is corrupt. """ try: #self.open() ################################ IN CASE GUI CLOSED PORT # Wait for the '@' character. while not self.conn.read() == "@": pass # Read one line at a time until packet is complete and parsed. packet = bitstring.BitStream("0x40") while True: # Read until new line. current_line = self.conn.readline() for char in current_line: packet.append("0x{:02X}".format(ord(char))) # Try to parse. try: reply = Reply(packet) break except PacketIncomplete: # Keep looking. continue rospy.logdebug("Received %s: %s", reply.name, reply.payload) return reply except select.error as (code, msg): # Set SIGINT as KeyboardInterrupt correctly, because pyserial has # problems. if code == errno.EINTR: raise KeyboardInterrupt() # Otherwise, reraise. raise
def byteVectToBitStream(self, byteVect, bitLen): """ Take a byte array, byteVect, where bit 0 of the first byte, byte 0, is the lsb, or "first" bit. Create a BitStream() where the lsb is the first, or left-most bit with index 0 for easy handling as a BitStream(). Truncate the BitSTream so that it is bitLen long. """ # bit vectors are sent by shift: command with bit 0 of byte 0 # the first bit. Pad bits are therefore in the msbs of the # last byte. Therefore, create BitStream() first, then byte # swap before truncating. # Use BitStream() constructor directly for creating TMS # and TDI BitStreams. Assuming that it is more efficient # than previous method with bitstring.pack(). # # Actually measured the time difference between # byteVectToBitStreamOLD() and byteVectToBitStream() and found # byteVectToBitStreamOLD() to take on average 6ms while # byteVectToBitStream() took only 4ms. When processing two # byte vectors in shift: command, this is a total savings of 4 ms bs = bitstring.BitStream(bytes=byteVect, length=len(byteVect) * 8) # length is a bit length # Fix LSB first # # [@@@ Save time by dealing with bits in original order? Probably not since putting into the natural order of a BitStream()] #@@@#for bn in range(0,len(byteVect)): #@@@# bs.reverse(start=bn*8,end=(bn*8)+8) #@@@#b3 = bitstring.BitStream('') #@@@#for bn in range(0,len(byteVect)): #@@@# a = bs[bn*8:(bn+1)*8] #@@@# a.reverse() #@@@# b3 += a #@@@#return b3[0:bitLen] ## Using built-in commands are way faster than looping in ## Python. Like 100x faster in some case with large vectors. bs.byteswap() bs.reverse() # Return truncated BitStream return bs[0:bitLen]
def encode(self, msgid='', channel="B"): msg = bitstring.BitStream() for field in self.fields: name = field[0] type = field[1] value = getattr(self, name) if hasattr(self, type + "_convert"): value = getattr(self, type + "_convert")(value, *field[2:]) else: args = {} args[type] = value args["length"] = field[2] value = bitstring.Bits(**args) msg.append(value) pad, payload = payload_armour(msg) return encode_avidm(payload, pad, 1, 1, msgid, channel)
def deserialize(self, packed): header = bitstring.BitStream(packed[0:UP_HEADER_SIZE]) try: self.up_id, type_value, self.data = header.unpack('uint:8, uint:8, uint:8') self.type = eTypeUp(type_value) except ValueError as e: raise DeserializationException("Can't deserialize up message header : {}".format(str(e))) if self.type == eTypeUp.ACK_DOWN: self.data = sAckDown() elif self.type == eTypeUp.HMI_STATE: self.data = sHMIState() elif self.type == eTypeUp.ODOM_REPORT: self.data = sOdomReport() elif self.type == eTypeUp.SENSOR_VALUE: self.data = sSensorValue() try: self.data.deserialize(packed[UP_HEADER_SIZE:]) except ValueError as e: raise DeserializationException("Can't deserialize up message payload : {}".format(str(e)))
def MessageFactory(src): if isinstance(src, bitstring.ConstBitArray): bits = src elif hasattr(src, 'read'): bits = bitstring.BitStream(src) else: raise InvalidMessage() mark = bits.pos try: msg = packedmessage.MessageParser.unpack(bits) logging.debug('this is an FTS-0001 (C) message.') except ValueError: logging.debug('not a packed message; assuming this ' 'is an FTS-0001 (B) message.') bits.pos = mark msg = diskmessage.MessageParser.unpack(bits) return msg
def decode(cls, address, data): [opcode] = struct.unpack('!H', data[8:10]) if(opcode not in cls.opcode_map): raise NotImplementedError('%x' % opcode) klass = cls.opcode_map[opcode] b = bitstring.BitStream(bytes=data) fields = dict() for name, fmt in klass.schema: accessor = getattr(klass, 'parse_%s' % name, None) if(callable(accessor)): fields[name] = accessor(b, fmt) else: fields[name] = b.read(fmt) p = klass(address=address) for k,v in fields.items(): setattr(p, k, v) return p
def read_packet(stream): global version_sum version, id = read_header(stream) version_sum += version packets = [] if id == 4: # literal packets.append(read_literal(stream)) else: # operator length_type_id = stream.read('uint:1') packets = [] if length_type_id: count = stream.read('uint:11') packets = [read_packet(stream) for i in range(count)] else: length = stream.read('uint:15') sub_stream = bitstring.BitStream(bin=stream.read('bin:{}'.format(length))) while sub_stream.pos + 8 < sub_stream.len: packets.append(read_packet(sub_stream)) return operators[id](packets)
def parse_dci_1_1(dci_hex_bytes): dci = pd.Series() bit_stream = bitstring.BitStream(dci_hex_bytes) dci['dl_fmt'] = bit_stream.read('uint:1') dci['dl_bwpid'] = bit_stream.read('uint:1') #dci['rballoc_type'] = bit_stream.read('uint:1') #dci['riv'] = bit_stream.read('uint:16') dci['dl_startPrb'], dci['dl_Prbnum'] = riv2startandlen(bit_stream.read('uint:16')) dci['dl_timealloc'] = bit_stream.read('uint:3') dci['dl_mcs'] = bit_stream.read('uint:5') dci['dl_ndi'] = bit_stream.read('uint:1') dci['dl_rv'] = bit_stream.read('uint:2') dci['dl_harqid'] = bit_stream.read('uint:4') dci['dl_dai'] = bit_stream.read('uint:2') dci['dl_tpc'] = bit_stream.read('uint:2') dci['dl_pucch_res'] = bit_stream.read('uint:3') dci['dl_K1'] = bit_stream.read('uint:3') dci['dl_antenna_port'] = bit_stream.read('uint:4') dci['dl_srs'] = bit_stream.read('uint:2') dci['dl_dmrs'] = bit_stream.read('uint:1') return dci
def _on_message(self, ws, message): """ receive message(binary) from MTA dispatch only payload(utf-8 str) included in message to CallBack Function message format : aplication Identifier length (1byte) deviceIdentifier length (1byte) payload length (4byte) aplication Identifier deviceIdentifier payload """ self.info("mtaDevice._on_message(%s)" % message) if self._dispatchFunction is not None: byteMessage = bitstring.BitStream(bytes=message, length=len(message) * 8) startIndex = 0 aplIdByteLength = byteMessage[startIndex:startIndex + 8].int startIndex += 8 devIdByteLength = byteMessage[startIndex:startIndex + 8].int startIndex += 8 payloadByteLength = byteMessage[startIndex:startIndex + 32].int startIndex += 32 aplIdBitLength = aplIdByteLength * 8 devIdBitLength = devIdByteLength * 8 payloadBitLength = payloadByteLength * 8 aplId = byteMessage[startIndex:startIndex + aplIdBitLength].bytes startIndex += aplIdBitLength devId = byteMessage[startIndex:startIndex + devIdBitLength].bytes startIndex += devIdBitLength payload = byteMessage[startIndex:startIndex + payloadBitLength].bytes self._dispatchFunction(payload) pass
def from_hex(self, data): reversed_bytes = bitstring.BitArray(bytearray(reversed(data))) reversed_bits = bitstring.BitStream(reversed(reversed_bytes)) for name in ['Total', 'Phase I', 'Phase II', 'Phase III']: potencia_activa = bitstring.BitArray(reversed(reversed_bits.read(24))).uint # kW potencia_reactiva = bitstring.BitArray(reversed(reversed_bits.read(24))).uint # kVAr factor_potencia = bitstring.BitArray(reversed(reversed_bits.read(10))).uint # cos phi in millis is_exporting_activa = bitstring.BitArray(reversed(reversed_bits.read(1))).bool # 0 importada/ 1 exportada is_exporting_reactiva = bitstring.BitArray(reversed(reversed_bits.read(1))).bool # 0 Q1/Q4 / 1 Q2/Q3 bitstring.BitArray(reversed(reversed_bits.read(3))) # not used invalid = bitstring.BitArray(reversed(reversed_bits.read(1))).bool # 0 valid/ 1 invalid ip = InstantPower( name, potencia_activa, potencia_reactiva, factor_potencia / 1000.0, is_exporting_activa, is_exporting_reactiva, not invalid ) self.valores.append(ip) dt = TimeA() dt.from_hex(data[32:37]) self.valores.append(dt) # Localized datetime return self.valores
def fromBytearray(self, frame=None): ''' Create HCV frame from a bytearray frame. ''' if not frame: frame = self._frame fmt = self._format streamData = bitstring.BitStream(self._frame) # List of format strings fmtStr = fmt.split(',') # Get all keywords from bitstring formatString keys = [ kw.split('=')[1].strip() for kw in fmtStr if len(kw.split('=')) > 1 ] # Create dictionary from keys and stream data frameDict = dict(zip(keys, streamData.unpack(fmt))) # Assign items to self self.update(frameDict) return frameDict
def send_data(self, TMS_stream, TDI_stream): TDO_stream = BitStream() index = 0 n = len(TDI_stream) while (index < n): if ((self.get_state() == self.SHIFT_DR or self.get_state() == self.SHIFT_IR) and TMS_stream[index] == False): end = TMS_stream.find(BitStream('0b1'), index) if (end): end = end[0] else: end = len(TMS_stream) if (self.get_state() == self.SHIFT_IR): self.ir = TDI_stream[index:end + 1] self.ir.reverse() if (self.verbosity_level >= 2): print('New IR: {}'.format(self.ir.bin)) if (self.ir == bitstring.BitStream('0b000101')): TDO_stream += self.jtag_data(TDI_stream[index:end], False) else: TDO_stream += self.jtag_data(TDI_stream[index:end], True) index = end else: TDO_stream += self.jtag_general(TMS_stream[index:index + 1], TDI_stream[index:index + 1]) index += 1 return TDO_stream
def from_hex(self, data): reversed_bytes = bitstring.BitArray(bytearray(reversed(data))) reversed_bits = bitstring.BitStream(reversed(reversed_bytes)) milliseconds = bitstring.BitArray(reversed(reversed_bits.read(10))).uint self.microseconds = milliseconds * 1000 self.seconds = bitstring.BitArray(reversed(reversed_bits.read(6))).uint self.minute = bitstring.BitArray(reversed(reversed_bits.read(6))).uint self.TIS = reversed_bits.read(1).uint self.IV = reversed_bits.read(1).uint self.hour = bitstring.BitArray(reversed(reversed_bits.read(5))).uint self.RES1 = bitstring.BitArray(reversed(reversed_bits.read(2))).uint self.SU = reversed_bits.read(1).uint self.dayofmonth = bitstring.BitArray( reversed(reversed_bits.read(5)) ).uint or 1 self.dayofweek = bitstring.BitArray(reversed(reversed_bits.read(3))).uint self.month = bitstring.BitArray( reversed(reversed_bits.read(4)) ).uint or 1 self.ETI = bitstring.BitArray(reversed(reversed_bits.read(2))).uint self.PTI = bitstring.BitArray(reversed(reversed_bits.read(2))).uint self.year = bitstring.BitArray(reversed(reversed_bits.read(7))).uint self.RES2 = reversed_bits.read(1).uint
def sendMessage(self, message): """ send message(utf-8 str) to MTA """ self.info("mtaDevice.sendMessage(%s" % message[:40 if len(message) > 45 else len(message)] + '...)' if len(message) > 45 else ')') self._dstApl = "RENV" aplIdLength = bitstring.BitStream(int=len(self._dstApl), length=8) devIdLength = bitstring.BitStream(int=len(self._deviceName), length=8) payloadLength = bitstring.BitStream(int=len(message), length=32) aplId = bitstring.BitStream(bytes=self._dstApl, length=len(self._dstApl) * 8) devId = bitstring.BitStream(bytes=self._deviceName, length=len(self._deviceName) * 8) payload = bitstring.BitStream(bytes=message, length=len(message) * 8) sendData = aplIdLength + devIdLength + payloadLength + aplId + devId + payload self._ws.send(sendData.bytes, websocket.ABNF.OPCODE_BINARY) pass
else: a_eta_hour = 24 if eta == "current": a_eta_minute = timestamp.minute else: a_eta_minute = 60 a_draught = locale.atoi(splitvdm[11]) * 10 # * 0.1 m a_destination = splitvdm[1] if (a_destination == ''): a_destination = splitvdm[12] if (a_destination == ''): a_destination = 'FG DEMO' a_destination = (a_destination + ' ')[0:20] a_dte = 1 a_spare = 0 vdmmap['type'] = bitstring.BitStream(uint=a_type, length=6) vdmmap['repeat'] = bitstring.BitStream(uint=a_repeat, length=2) vdmmap['mmsi'] = bitstring.BitStream(uint=a_mmsi, length=30) vdmmap['versn'] = bitstring.BitStream(uint=a_versn, length=2) vdmmap['imo'] = bitstring.BitStream(uint=a_imo, length=30) vdmmap['callsign'] = bitstring.pack( 'bin:42', intvec2bitstring(aisdecode(a_callsign))) # length=42 vdmmap['name'] = bitstring.pack('bin:120', intvec2bitstring( aisdecode(a_name))) # length=120 vdmmap['shiptype'] = bitstring.BitStream(uint=a_shiptype, length=8) vdmmap['to_bow'] = bitstring.BitStream(uint=a_to_bow, length=9) vdmmap['to_stern'] = bitstring.BitStream(uint=a_to_stern, length=9) vdmmap['to_port'] = bitstring.BitStream(uint=a_to_port, length=6) vdmmap['to_stbd'] = bitstring.BitStream(uint=a_to_stbd, length=6) vdmmap['fixtype'] = bitstring.BitStream(uint=a_fixtype, length=4)
def pack(self, val): bits = bitstring.BitStream() for data in val: bits.append(self.field.pack(data)) return bits