Beispiel #1
0
    def add_msdu(self, msdu, msdu_len=-1):
        # Default msdu len
        if msdu_len == -1:
            msdu_len = len(msdu)

        mpdu_len = msdu_len + len(self.dot11hdr) + 4  # msdu + mac80211 + FCS

        if mpdu_len % 4 != 0:
            padding = "\x00" * (4 - (mpdu_len % 4))  # Align to 4 octets
        else:
            padding = ""
        mpdu_len <<= 4
        crc_fun = crcmod.mkCrcFun(0b100000111, rev=True, initCrc=0x00, xorOut=0xFF)

        crc = crc_fun(struct.pack('<H', mpdu_len))
        maccrc = dot11crc(str(self.dot11hdr / msdu))
        delim_sig = 0x4E

        #print('a-mpdu: len %d crc %02x delim %02x' % (mpdu_len >> 4, crc, delim_sig))
        #hexdump(maccrc)
        ampdu_header = struct.pack('<HBB', mpdu_len, crc, delim_sig)
        #hexdump(ampdu_header)

        self.data = self.data / ampdu_header / self.dot11hdr / msdu / maccrc / padding

        self.num_subframes += 1
Beispiel #2
0
def probe_response():
    rt = RadioTap(len=18, present='Flags+Rate+Channel+dBm_AntSignal+Antenna', notdecoded='\x00\x6c' + get_frequency(CHANNEL) + '\xc0\x00\xc0\x01\x00\x00')
    beacon_packet = Dot11(subtype=5, addr1='ff:ff:ff:ff:ff:ff', addr2="be:da:de:ad:be:ef", addr3="be:da:de:ad:be:ef", SC=0x3060) \
                    / Dot11ProbeResp(timestamp=time.time(), beacon_interval=0x0064, cap=0x2104) \
                    / Dot11Elt(ID='SSID', info="injected SSID") \
                    / Dot11Elt(ID='Rates', info=AP_RATES) \
                    / Dot11Elt(ID='DSset', info=chr(1))

    # Update sequence number
    beacon_packet.SC = 0x3060

    mpdu_len = len(beacon_packet) + 4

    if mpdu_len % 4 != 0:
        padding = "\x00" * (4 - (mpdu_len % 4))  # Align to 4 octets
    else:
        padding = ""
    mpdu_len <<= 4
    crc_fun = crcmod.mkCrcFun(0b100000111, rev=True, initCrc=0x00, xorOut=0xFF)

    crc = crc_fun(struct.pack('<H', mpdu_len))
    maccrc = dot11crc(str(beacon_packet))
    delim_sig = 0x4E

    #print('a-mpdu: len %d crc %02x delim %02x' % (mpdu_len >> 4, crc, delim_sig))
    #hexdump(maccrc)
    ampdu_header = struct.pack('<HBB', mpdu_len, crc, delim_sig)
    #hexdump(ampdu_header)

    data = ampdu_header / beacon_packet / maccrc / padding
    data /= "\x00\x00\x20\x4e" * 8
    data = str(data)

    return data
Beispiel #3
0
    def read(self, length):
        preamble = ["\xFF", "\xFA"]
        input = [0x00, 0x00]
        input[1] = self.ser.read(1)
        while True:
            if input == preamble:
                break
            else:
                input[0] = input[1]
                input[1] = self.ser.read(1)

        while self.ser.inWaiting() < length + 2:
            pass

            # Get data
        data = self.ser.read(length)

        # Get checksum
        input = self.ser.read(2)
        checksum = struct.unpack("H", input)[0]

        # Verify checksum
        crc16 = crcmod.mkCrcFun(0x11021, 0xFFFF, True)
        calcChecksum = crc16(data)
        calcChecksum = (~calcChecksum) % 2 ** 16  # convert to uint16_t

        if checksum != calcChecksum:
            print "Failed checksum."
            return

        return data
Beispiel #4
0
def create_object_id_no_ctx(enterprise_number, local_id_length=8):
    """ Facility function that works without an application context."""
    # I agree that the following is ugly and quite probably not as fast
    # as I would like it. Goal is to create a random string with a length
    # of exactly local_id_length.
    local_id_format = ''.join(['%0', str(local_id_length), 'x'])
    local_obj_id = local_id_format % random.randrange(16**local_id_length)

    crc_val = 0
    id_length = str(unichr(8 + len(local_obj_id)))
    # the poly given in the CDMI 1.0.2 spec ()x8005) is wrong,
    # CRC-16 is specified as below
    crc_func = crcmod.mkCrcFun(0x18005, initCrc=0x0000,
                               xorOut=0x0000)

    struct_id = struct.Struct('!cxhccH%ds' % local_id_length)
    packed_id_no_crc = struct_id.pack('\0',
                                      enterprise_number,
                                      '\0',
                                      id_length,
                                      0,
                                      local_obj_id)

    crc_val = crc_func(packed_id_no_crc)

    packed_id = struct_id.pack('\0',
                               enterprise_number,
                               '\0',
                               id_length,
                               crc_val,
                               local_obj_id)

    return packed_id
 def __init__(self):
     Thread.__init__(self)
     self._dev = None
     self.crc16 = crcmod.mkCrcFun(0x18005, 0x0000, True) 
     self._queue = b""
     self._cmdcond = CmdConditions()
     self._stopev = False
    def PackPacket(self):
        # Packet Shape
        # Start flag          : 1100
        # LEDCommands Flag    : 2 bit
        # Light Intenisty Flag : 4 bit
        # OptoKineticFlag     : 2 bit
        # Directionality Flag : 8 bit
        # Parachute Flag      : 2 bit
        # CRC                :
        # End Flag           : 0011

        self.cpacket = 0b1100
        self.cpacket = self.cpacket << 2
        self.cpacket = self.cpacket + self.Commands.LEDCommand
        self.cpacket = self.cpacket << 4
        self.cpacket = self.cpacket + self.Commands.LEDIntensity
        self.cpacket = self.cpacket << 2
        self.cpacket = self.cpacket + self.Commands.OptoKinetic
        self.cpacket = self.cpacket << 8
        self.cpacket = self.cpacket + self.Commands.Directionality
        self.cpacket = self.cpacket << 2
        self.cpacket = self.cpacket + self.Commands.ParachuteCommand
        # Generate CRC
        data = 0b0000111111111111111111
        crc32_func = crcmod.mkCrcFun(0x104C11DB7, initCrc=0, xorOut=0xFFFFFFFF)
        crc = crc32_func(str(data))
        self.cpacket = self.cpacket << 32
        self.cpacket = self.cpacket + crc
        self.cpacket = self.cpacket << 4
        self.cpacket = self.cpacket + 0b0011
Beispiel #7
0
    def __init__(self, bus_nb = 2, addr = 0x07):
        self.__i2c_fd ={
                    "in": open("/dev/i2c-"+str(bus_nb), 'rb', buffering=0),
                    "out": open("/dev/i2c-"+str(bus_nb), 'wb', buffering=0)
                    }
        for fd in self.__i2c_fd.values():
            fcntl.ioctl(fd, TrexIO.__I2C_TENBIT, 0)
            if fcntl.ioctl(fd, TrexIO.__I2C_SLAVE, 7) < 0:
                raise IOError(
                    "Can not find a T-rex at address %d on bus %d"%(addr, bus_nb)
                            )
                        
        self.__reset_bytes = (0,0,0,0)

        # this list will be used as a "pointer of pointers" to speed up
        # the dict updates

                    

                    
        self.__status = dict(
                    zip(
                        TrexIO.__status_dict_strings, 
                        [0]*len(TrexIO.__status_dict_strings)
                        )
                    )
                    
        self.compute_crc = crcmod.mkCrcFun(0x131, initCrc=0) #Dallas polynom
        self.reset()
Beispiel #8
0
    def __init__(self, port):

        try:
            import termios
            fd = open(port)
            tmp = termios.tcgetattr(fd.fileno())
            termios.tcsetattr(fd.fileno(), termios.TCSADRAIN, tmp)
            fd.close()
        except (ImportError, IOError, termios.error):
            pass

        self._msg = FWRTSSMessage()

        self._ser = None

        self._buf = []

        self._crc = crcmod.mkCrcFun(0x104c11db7, initCrc=0xFFFFFFFF, xorOut=0, rev=False)

        try:
            self._ser = serial.Serial(port, 115200)
            self._ser.flush()
            self._ser.flushInput()
            self._ser.flushOutput()
            self._ser.timeout = 0.2
        except serial.serialutil.SerialException, e:
            raise FWRTSSError(str(e))
	def read(self,length):
		preamble = ['\xFF','\xFA'];
		input = [0x00,0x00]
		input[1] = self.ser.read(1)
		while ( True ):
			if ( input == preamble ):
				break
			else:
				input[0] = input[1]
				input[1] = self.ser.read(1)
		
		while ( self.ser.inWaiting() < length + 2 ):
			pass

		#Get data
		data = self.ser.read(length)

		#Get checksum
		input = self.ser.read(2)
		checksum = struct.unpack('H',input)[0]

		#Verify checksum
		crc16 = crcmod.mkCrcFun(0x11021,0xFFFF,True)
		#crc16 = crcmod.mkCrcFun(0x11021,0xFFFF,False) # xmodem
		calcChecksum = crc16(data)
		calcChecksum = (~calcChecksum) % 2**16  # convert to uint16_t
		#calcChecksum = (calcChecksum) % 2**16 # xmodem

		if ( checksum != calcChecksum ):
			print "Failed checksum."
			return
		      
		return data
Beispiel #10
0
 def __init__(self, countchannel, triggerchannel, binwidth, roistart, roistop, filename=None, parent = None, FPGASerial="A6VTOYBO"):
     QThread.__init__(self, parent)
     self.channel = countchannel
     self.triggerchannel = triggerchannel
     self.binwidth = binwidth
     self.roistart = roistart
     self.roistop = roistop
     self.numberOfBins = (roistop-roistart)/binwidth+1
     self.histogram = numpy.zeros(self.numberOfBins)
     self.exiting = False
     self.crc8 = crcmod.mkCrcFun(poly=0x107, initCrc=0xff, xorOut=0x00, rev=False)
     self.Connection = ftd2xx.openEx(FPGASerial);
     self.Connection.setBaudRate(3000000)
     self.Connection.setDataCharacteristics(8, 0, 0)
     self.Connection.setFlowControl(0, 0, 0)
     self.Connection.setTimeouts(500, 500)
     self.Connection.resetDevice()
     self.Connection.purge()
     self.integration_time = 100.0;
     command = struct.pack('>BBBI', 0x10, 0, 0x11, int(500*50000 )  )
     self.Connection.write(command)    
     command = struct.pack('>BB', 0x12, 0x0  )
     self.Connection.write(command)    
     self.Mutex = QMutex()
     self.filename = filename
     self.binfile = None
     if self.filename is not None:
         self.binfile = open(self.filename, 'wb')
     self.clearStatus()
     self.maxPretriggerPhotons = 1000000
Beispiel #11
0
 def __init__(self, bus_nb = 2, addr = 0x07):
     self.bus=smbus.SMBus(bus_nb)
     self.addr = addr
     self.cmd_left = 0
     self.cmd_right = 0
     self.use_pid = 0
     self.compute_crc = crcmod.mkCrcFun(0x131, initCrc=0) #Dallas polynom
     self.stop()
Beispiel #12
0
 def test_known_answers(self):
     for crcfun_params, v in self.known_answers:
         crcfun = mkCrcFun(*crcfun_params)
         self.assertEqual(crcfun('',0), 0, "Wrong answer for CRC parameters %s, input ''" % (crcfun_params,))
         for i, msg in enumerate(self.test_messages):
             self.assertEqual(crcfun(msg), v[i], "Wrong answer for CRC parameters %s, input '%s'" % (crcfun_params,msg))
             self.assertEqual(crcfun(msg[4:], crcfun(msg[:4])), v[i], "Wrong answer for CRC parameters %s, input '%s'" % (crcfun_params,msg))
             self.assertEqual(crcfun(msg[-1:], crcfun(msg[:-1])), v[i], "Wrong answer for CRC parameters %s, input '%s'" % (crcfun_params,msg))
Beispiel #13
0
def encodeTransfer(formatString,values):
	header = '\xFF\xFA'
	data = struct.pack(formatString,*values)
	crc16 = crcmod.mkCrcFun(0x11021,0xFFFF,True)
	calcChecksum = crc16(data)
	calcChecksum = (~calcChecksum) % 2**16  # convert to uint16_t
	
	return header + data + struct.pack('H',calcChecksum)
Beispiel #14
0
def crc8(polynomial, init):
	check_fn = crcmod.mkCrcFun(0x100 | polynomial, initCrc=init, rev=False)

	def crc8_fn(data, check):
		data_s = ''.join(map(chr, data))
		calculated = check_fn(data_s)
		return calculated == check

	return crc8_fn
Beispiel #15
0
    def test_compare_poly(self):
        """Compare various CRCs of this crcmod module to a pure
        polynomial-based implementation."""
        for crcfun_params, crc_poly_fun in self.test_poly_crcs:
            # The following function should produce the same result as
            # the associated polynomial CRC function.
            crcfun = mkCrcFun(*crcfun_params)

            for msg in self.test_messages:
                self.assertEqual(crcfun(msg), crc_poly_fun(msg))
Beispiel #16
0
    def test_compare_crc32(self):
        """The binascii module has a 32-bit CRC function that is used in a wide range
        of applications including the checksum used in the ZIP file format.
        This test compares the CRC-32 implementation of this crcmod module to
        that of binascii.crc32."""
        # The following function should produce the same result as
        # self.reference_crc32 which is derived from binascii.crc32.
        crc32 = mkCrcFun(g32,0,1,0xFFFFFFFF)

        for msg in self.test_messages:
            self.assertEqual(crc32(msg), self.reference_crc32(msg))
Beispiel #17
0
def _crccomp32():
    """Internal function used by crc32()"""
    try:
        from crcmod import mkCrcFun
    except ImportError:
        raise AssertionError("Python crcmod module not installed")
    crc_polynomial = 0x104C11DB7
    crc_initial = 0xFFFFFFFFL
    crc = mkCrcFun(crc_polynomial, crc_initial, False)
    while True:
        yield crc
 def __init__(self, device=None, device_id=None):
     self.devid = device
     self.serial_mode = None
     self.dev = None
     if device_id is not None:
         self.device_id = device_id
         self.dev = pylibftdi.serial_device.SerialDevice(self.device_id)
     else:
         self.dev = pylibftdi.serial_device.SerialDevice() #TODO fix device id
     self.dev.baudrate = 117200
     self.crcfunc = crcmod.mkCrcFun(0x104c11db7, initCrc=0, xorOut=0xFFFFFFFF)
Beispiel #19
0
def caculate_crc( _data ):
    try:
        hexData = binascii.a2b_hex(_data)
        xorOut_ty=0x0000
        rev_ty=False
        initCrc_ty=0xffff
        xmodem_crc_func = crcmod.mkCrcFun(0x11021, rev=rev_ty, initCrc=initCrc_ty, xorOut=xorOut_ty)        
        return [ True,hex(xmodem_crc_func(hexData)) ]
    except Exception,e:
        print Exception,":",e
        traceback.print_exc()
        return [ False, None]
 def __init__(self, serial_name, file_name):
     self.crc_fun=crcmod.mkCrcFun(0x104C11DB7, 0xFFFFFFFF, rev=False)
     try:
         self.serial = serial.Serial(serial_name, 1200, inter_byte_timeout=self.TIMEOUT_S)
     except serial.SerialException:
         error("Cannot open COM port " + serial_name)
     print("Open serial port " + self.serial.name)
     if file_name:
         try:
             self.file = open(file_name,"rb")
         except IOError:
             error("Cannot open file " + file_name)
         print("Open file " + file_name)
 def __init__(self, input_file, output_file, max_rec_size, fill_space, header_loc, in_valid_mask):
     self.mot_filename = input_file
     self.out_filename = output_file
     self.max_block_size = max_rec_size
     self.max_fill_space = fill_space
     self.header_location = header_loc
     self.input_valid_mask = in_valid_mask
     self.header_bytes_left = self.FL_LI_STRUCT_SIZE
     self.fileheader = ""
     self.filesize = 0
     #Used for CRC - CCITT - x^16 + x^12 + x^5 + 1
     self.g16 = 0x11021
     self.crc_init = 0x1D0F
     #CRC used for the entire file - Image CRC
     self.file_crc = crcmod.Crc(self.g16, self.crc_init, 0)
     #CRC used for each block
     self.crc = crcmod.mkCrcFun(self.g16,self.crc_init,0)       
Beispiel #22
0
    def __init__(self, micromodem, dest,rate = 1, timeout=60,pad='\x1a',ymodem_enabled = True,unified_log=None,log_path=None, ):
        assert isinstance(micromodem, Micromodem), "micromodem object isn't a Micromodem: %r" & micromodem
        assert rate in range(0,6), "Invalid Rate: %d" & rate
        assert dest != micromodem.id, "Can't send file to self."
        self.pad = pad

        self.rate = Rates[rate]
        self.micromodem = micromodem
        self.micromodem.set_config('RXP',1)
        self.micromodem.set_config('MOD',1)
        #use CRC-8/CDMA2000 instead of CRC-16 CCITT Unreflected.
        self.calc_crc = crcmod.mkCrcFun(0x19b, rev=False, initCrc=0xff, xorOut=0x00)
        if unified_log is None:
            unified_log = UnifiedLog(log_path=log_path)
        self.log = unified_log.getLogger("xmodem.{0}".format(micromodem.name))
        self.target_id = dest
        self.timeout = timeout
        self.ymodem_mode = True
Beispiel #23
0
def decodeTransfer(queue,formatString):
	length = struct.calcsize(formatString)

	if ( queue.empty() ):
		return

	preamble = ['\xFF','\xFA'];
	input = [0x00,0x00]
	input[1] = queue.get(0,0)
	print input[1]
	while ( True ):
		if ( input == preamble ):
			break
		else:
			if ( queue.empty() ):
				return
			input[0] = input[1]
			input[1] = queue.get(0,0)

	if queue.qsize() < length + 2:
		return

	#Get data
	data = ''
	for i in range(length):
		data += queue.get()

	#Get checksum
	input = queue.get()
	input += queue.get()
	checksum = struct.unpack('H',input)[0]

	#Verify checksum
	crc16 = crcmod.mkCrcFun(0x11021,0xFFFF,True)
	calcChecksum = crc16(data)
	calcChecksum = (~calcChecksum) % 2**16  # convert to uint16_t

	if ( checksum != calcChecksum ):
		print "Failed checksum."
		return
	      
	return struct.unpack(formatString,data)
    def __init__(self, path, baud):
        self.fp = Serial(
            port     = path,
            baudrate = baud,
            bytesize = serial.EIGHTBITS,
            parity   = serial.PARITY_NONE,
            stopbits = serial.STOPBITS_ONE
        )
        # CRC-16 with generator polynomial X^16 + X^12 + X^5 + 1.
        self.crc = crcmod.mkCrcFun(0b10001000000100001, 0, False)
        self.recv_cbs = []
        self.cb_lock = threading.Lock()

        self.decode_pos = 0
        self.discard_stat = 0
        self.recv_buf = bytearray()

        self.read_th = rt = threading.Thread(target=self.reader())
        rt.daemon = True
        rt.start()
Beispiel #25
0
def _main(argv):

    parser = argparse.ArgumentParser(argv)
    parser.add_argument("-v", "--verbose",
                        help="increase output verbosity",
                        action="store_true")
    parser.add_argument("-i", "--infile",
                        help="file to read",
                        required=True)
    parser.add_argument("-o", "--outfile",
                        help="file to write",
                        required=True)
    args = parser.parse_args()

    with open(args.infile, mode='rb') as infile, open(
        args.outfile, mode='wb') as outfile:

        dvb_crc32 = crcmod.mkCrcFun(0x104c11db7,
                                    rev=False,
                                    initCrc=0xFFFFFFFF,
                                    xorOut=0)
        blocks = [bytearray() for i in range(8192)]
        max_block = 0

        for block_number, block_data, crc in (
                read_block(infile, dvb_crc32, args.verbose)):

            if crc == 0:
                if block_number > max_block:
                    max_block = block_number

                blocks[block_number] = block_data

        for index, block in enumerate(blocks):
            if index > max_block:
                break
            if len(block) == 0:
                print "Missing block: %u" % index
                break
            else:
                outfile.write(block)
Beispiel #26
0
    def __init__(self, domain):
        """Loads data to memory. Creates index directory if needed and raises DistutilsFileError if failed.
        Raises IdexFingerpringException

        domain - index storage ID
        """
        try:
            POLYNOMIAL = 0x1AABBCCDDFFEEDDCC # must be 65 bit long

            self._debug = 0

            self._hashes = set()
            self._crc_fun = crcmod.mkCrcFun(POLYNOMIAL, initCrc=0)

            # When run from the unit test, index directory path will be tweaked in Config
            file_path =Config.value(mirror0.SECTION_COMMON, "index_directory") 
            dir_util.mkpath(file_path)

            file_name = domain + ".crc64"
            self._file_path = os.path.join(file_path, file_name)
            with open(self._file_path, "a+b") as f:
                data = f.read()
                if len(data) % CRC_LEN:
                    raise IndexFingerprintException("%s is corrupt!" % file_name)
                count = len(data) / CRC_LEN
                for i in range(0, count):
                    string_val = data[i*CRC_LEN : (i + 1)*CRC_LEN]
                    int_val = Index._string_long(string_val)
                    self._hashes.update([int_val])
                log("Read %i hashes from %s" % (count, file_name))

            file_name = domain + ".log"
            self._log_file_path = os.path.join(file_path, file_name)
            # Rewrite through centralized logging
            with open(self._log_file_path, "a") as f:
                f.write("\n\nSTARTED %s\n" % time.strftime("%d %b %Y %H:%M:%S"))

        except IndexFingerprintException as e:
            format_exc(self, "__init__", e)
            log(self._file_path, ERROR)
            raise
Beispiel #27
0
    def __init__(self, *, domain):
        """Loads data to memory. Creates index directory if needed and raises DistutilsFileError, OSError
        Raises IdexFingerpringException
        domain - index storage ID
        """
        POLYNOMIAL = 0x1AABBCCDDFFEEDDCC # must be 65 bit long

        self._hashes = set()
        self._crc_fun = crcmod.mkCrcFun(POLYNOMIAL, initCrc=0)

        try:
            # When run from the unit test, index directory path will be tweaked in Config
            file_path =Config.value(mirror0.SECTION_COMMON, "index_directory") 
            mkpath(file_path)

            file_name = domain + ".crc64"
            self._file_path = os.path.join(file_path, file_name)
            with open(self._file_path, "rb") as f:
                data = f.read()
        except (OSError, DistutilsFileError) as e:
            format_exc(self, "Index init failed", e)
            raise
                        
        if len(data) % CRC_LEN:
            msg = "{} is corrupt!".format(self._file_path)
            log(msg, ERROR)
            raise IndexFingerprintException(msg) 

        count = len(data) // CRC_LEN
        for i in range(0, count):
            string_val = data[i*CRC_LEN : (i + 1)*CRC_LEN]
            int_val = _bytes_to_long(string_val)
            self._hashes.update([int_val])
        log("Read {} hashes from {}".format(count, file_name))

        file_name = domain + ".log"
        self._log_file_path = os.path.join(file_path, file_name)
        self.index_log("\n\nSTARTED {}\n".format(time.strftime("%d %b %Y %H:%M:%S")))
def ukhas_format(datum):

    callsign = "UBSEDS9"

    # Time
    time_str = "{:02}:{:02}:{:02}".format(
        datum['time'].hour, datum['time'].minute, datum['time'].second)

    # Location
    coords = datum['coords']
    location_str = "{:.6f},{:.6f},{}".format(
        coords[0], coords[1], int(round(coords[2])))

    # Everything
    ukhas_str = "{},{},{},{},{},{},{},-1".format(
        callsign, time_str, location_str, datum['satellites'],
        datum['battery'], datum['solar'], datum['temperature']);

    # Checksum
    crc16 = crcmod.mkCrcFun(0x11021, 0xFFFF, False, 0x0000)
    checksum =  "{:04X}".format(crc16(ukhas_str))

    return "$${}*{}".format(ukhas_str, checksum)
	def __init__(self, socketPath, debug=False, F=160E6):
		self.__socketPath = socketPath
		self.__socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
		self.__socket.connect(self.__socketPath)
		self.__crcFunc = crcmod.mkCrcFun(0x104C11DB7, rev=False, initCrc=0x0A1CB27F)
		self.__lastSN = randrange(0, 2**15-1)
		self.__pendingReplies = 0
		self.__recvBuffer = bytearray([]);
		self.__debug = debug
		self.__dataFramesIndexes = []
		self.__sync0 = 0
		self.__lastSync = 0
		self.__frameLength = 1024.0 / F
		shmName, s0, p1, s1 = self.__getSharedMemoryInfo()
		self.__dshm = DSHM.SHM(shmName)
		#self.__shmParams = (s0, p1, s1)
		#self.__shm = SharedMemory(shmName)
		#self.__shmmap = mmap.mmap(self.__shm.fd, self.__shm.size)
		#os.close(self.__shm.fd)
		self.config = None
		self.__activeAsics = [ False for x in range(64) ]
		self.__asicType = [ None for x in range(64) ]
		return None
Beispiel #30
0
 def __init__(self):
     self.__crc = crcmod.mkCrcFun(0x11021, 0xffff, False, 0x0000)
Beispiel #31
0
import binascii
import crcmod
from enum import Enum

from Chameleon.MFDESFire import MFDESFireDecode
from Chameleon.utils import TrafficSource

# Parameters for CRC_A
CRC_INIT = 0x6363
POLY = 0x11021
CRC_A_func = crcmod.mkCrcFun(POLY, initCrc=CRC_INIT, xorOut=0)


class ReaderCMD(Enum):
    NONE = 0
    SELECT = 1
    RATS = 2
    PPS = 3


readerCMD = ReaderCMD.NONE


# Map card types string to decoder
def DummyCardDecoder(data, source):
    return ""


CardTypesMap = {
    "None": {
        "ApplicationDecoder": DummyCardDecoder
Beispiel #32
0
import crcmod

# https://tools.ietf.org/html/rfc3533#section-6
# http://www.onicos.com/staff/iz/formats/ogg.html
# https://en.wikipedia.org/wiki/Ogg#Page_structure
OGG_FIRST_PAGE_HEADER = struct.Struct("<4sBBQLLLB")
OGG_FIRST_PAGE_HEADER_CRC_OFFSET = 22
OGG_FIRST_PAGE_HEADER_CRC = struct.Struct("<L")

# https://tools.ietf.org/html/rfc7845#section-5.1
OGG_OPUS_ID_HEADER = struct.Struct("<8sBBHLhB")
OGG_OPUS_ID_HEADER_GAIN_OFFSET = 16
OGG_OPUS_ID_HEADER_GAIN = struct.Struct("<h")

ogg_page_crc = crcmod.mkCrcFun(0x104C11DB7, initCrc=0, rev=False)


def parse_oggopus_output_gain(file: BinaryIO) -> int:
    # noqa: D200
    """
    Parse an OggOpus file headers, read and return its output gain, and set file seek position to start of Opus header.
    """
    #
    # Ogg header
    #

    # check fields of Ogg page header
    chunk = file.read(OGG_FIRST_PAGE_HEADER.size)
    first_ogg_page = bytearray()
    first_ogg_page.extend(chunk)
Beispiel #33
0
class USBSniffer(OVPacketHandler):
    """ USB Sniffer packet sink -- receives sniffed packets from the OpenVizsla. """

    HANDLED_PACKET_NUMBERS = [0xac, 0xad, 0xa0]

    USB_PACKET_REPORT = 0xa0

    data_crc = staticmethod(crcmod.mkCrcFun(0x18005))

    def bytes_necessary_to_determine_size(self, packet_number):
        if packet_number == 0xa0:
            return 5
        return 1

    def __init__(self, write_handler, high_speed=False):
        """ Set up our core USB Sniffer sink, which accepts wrapped USB events and passes them to our event sinks. """

        self.high_speed = high_speed
        self.got_start = False

        # Start off with an empty array of packet sinks -- sinks should be registered by calling ``.register_sink`.
        self._sinks = []

        # Call the super-constructor.
        super().__init__(write_handler)

    def _packet_size(self, buf):
        """ Return the packet size for our core USB events. """

        if buf[0] != self.USB_PACKET_REPORT:
            return 2
        else:
            return (buf[4] << 8 | buf[3]) + 8

    def register_sink(self, sink):
        """ Registers a USBEventSink to receive any USB events. """

        self._sinks.append(sink)

    def emit_usb_packet(self, ts, buf, flags):
        for sink in self._sinks:
            sink.handle_usb_packet(ts, buf, flags)

    @staticmethod
    def decode_flags(flags):
        ret = ""
        ret += "Error " if flags & USBEventFlags.ERROR else ""
        ret += "Overflow" if flags & USBEventFlags.OVERFLOW else ""
        ret += "Clipped " if flags & USBEventFlags.CLIPPED else ""
        ret += "Truncated " if flags & USBEventFlags.TRUNCATED else ""
        ret += "First " if flags & USBEventFlags.FIRST else ""
        ret += "Last " if flags & USBEventFlags.LAST else ""
        return ret.rstrip()

    def handle_packet(self, buf):
        """ Separates the input flags from the core meta-data extracted from the OV USB packet. """

        if buf[0] == self.USB_PACKET_REPORT:

            # Parse the flags and timeout from our buffer.
            # TODO: replace with a call to struct.unpack
            flags = buf[1] | buf[2] << 8
            ts = buf[5] | buf[6] << 8 | buf[7] << 16

            # TODO: validate packet size (buf[3] and buf[4])?

            # TODO: get rid of me?
            if flags != 0 and flags != USBEventFlags.FIRST and flags != USBEventFlags.LAST:
                print("PERR: %04X (%s)" % (flags, self.decode_flags(flags)))

            if flags & USBEventFlags.FIRST:
                self.got_start = True

            if self.got_start:
                self.emit_usb_packet(ts, buf[8:], flags)

            if flags & USBEventFlags.LAST:
                self.got_start = False

        else:
            print("got interesting packet {}".format(buf[0]))
Beispiel #34
0
codetext = text.encode('utf-8')
#len 9218,str类型

#去除最后的空格
msg = codetext[:-1]

#去除CRC数值
msg = codetext[:-6]

#去除CRC数值及前一个空格
msg = codetext[:-7]

#去除整行CRC=
msg = codetext[:-12]

#去除整行CRC=及前一个回车
msg = codetext[:-13]

#去除Note以后
msg = codetext[:-78]

#遍历所有组合,0x10000-0x1FFFF,65536-131071
p = range(0b10000000000000001, 0b11111111111111111, 2)
result = []
for i in p:
    crc16_func = crcmod.mkCrcFun(i, initCrc=0xFFFF, xorOut=0)
    crc_value = crc16_func(msg)
    if crc_value == 0:
        result.append(i)
#初始值为全0或全1,均找不到匹配的结果
Beispiel #35
0
def mkPredefinedCrcFun(crc_name):
    definition = _get_definition_by_name(crc_name)
    return crcmod.mkCrcFun(poly=definition['poly'],
                           initCrc=definition['init'],
                           rev=definition['reverse'],
                           xorOut=definition['xor_out'])
Beispiel #36
0
import copy
import crcmod
from selfdrive.car.nissan.values import CAR

nissan_checksum = crcmod.mkCrcFun(0x11d, initCrc=0x00, rev=False, xorOut=0xff)


def create_steering_control(packer, car_fingerprint, apply_steer, frame,
                            steer_on, lkas_max_torque):
    if car_fingerprint == CAR.XTRAIL:
        idx = (frame % 16)
        values = {
            "DESIRED_ANGLE": apply_steer,
            "SET_0x80_2": 0x80,
            "SET_0x80": 0x80,
            "MAX_TORQUE": lkas_max_torque if steer_on else 0,
            "COUNTER": idx,
            "LKA_ACTIVE": steer_on,
        }

        dat = packer.make_can_msg("LKAS", 0, values)[2]

        values["CRC"] = nissan_checksum(dat[:7])

    return packer.make_can_msg("LKAS", 0, values)


def create_acc_cancel_cmd(packer, cruise_throttle_msg, frame):
    values = copy.copy(cruise_throttle_msg)

    values["CANCEL_BUTTON"] = 1
Beispiel #37
0
#from BadNet0 import *
#from BadNet1 import *
#from BadNet2 import *
from BadNet5 import *
#from BadNet4 import *
#from BadNet5 import *

#main
serverIP = '127.0.0.1'
blksz = 1024  #Bulk size for receiving file in chunks
RUPHeaderFormat = 'I I H H H'
RUPHeaderSize = 14

#CRC16 for Checksum
crc16_func = crcmod.mkCrcFun(0x11021, initCrc=0, rev=True, xorOut=0xFFFF)
checksum_correct = 1

if len(sys.argv) < 2:
    print('Server Port No. missing in command line arguments')
    serverPort = raw_input('Enter Server Port No.: ')
else:
    serverPort = sys.argv[1]

serverPort = int(serverPort)

#Creating server socket for control connection
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind((serverIP, serverPort))

#**********************************************************
Beispiel #38
0
    def __init__(self, magicbyte="\x31\x78"):
        super(HS304, self).__init__("HS304")

        self.magicbyte = magicbyte
        self.CRC16 = crcmod.mkCrcFun(0x11021,
                                     initCrc=0x422e,
                                     rev=False,
                                     xorOut=0x0000)
        self.CRC8 = crcmod.mkCrcFun(0x101,
                                    initCrc=0x1d,
                                    rev=False,
                                    xorOut=0x00)

        # Lookup table for payload byte 0 (Keyboard HID byte 2)
        self.LUT0 = [[
            0xa1, 0x21, 0xe1, 0x61, 0x81, 0x01, 0xc1, 0x41, 0xb1, 0x31, 0xf1,
            0x71, 0x91, 0x11, 0xd1, 0x51, 0xa9, 0x29, 0xe9, 0x69, 0x89, 0x09,
            0xc9, 0x49, 0xb9, 0x39, 0xf9, 0x79, 0x99, 0x19, 0xd9, 0x59, 0xa5,
            0x25, 0xe5, 0x65, 0x85, 0x05, 0xc5, 0x45, 0xb5, 0x35, 0xf5, 0x75,
            0x95, 0x15, 0xd5, 0x55, 0xad, 0x2d, 0xed, 0x6d, 0x8d, 0x0d, 0xcd,
            0x4d, 0xbd, 0x3d, 0xfd, 0x7d, 0x9d, 0x1d, 0xdd, 0x5d, 0xa3, 0x23,
            0xe3, 0x63, 0x83, 0x03, 0xc3, 0x43, 0xb3, 0x33, 0xf3, 0x73, 0x93,
            0x13, 0xd3, 0x53, 0xab, 0x2b, 0xeb, 0x6b, 0x8b, 0x0b, 0xcb, 0x4b,
            0xbb, 0x3b, 0xfb, 0x7b, 0x9b, 0x1b, 0xdb, 0x5b, 0xa7, 0x27, 0xe7,
            0x67, 0x87, 0x07, 0xc7, 0x47, 0xb7, 0x37, 0xf7, 0x77, 0x97, 0x17,
            0xd7, 0x57, 0xaf, 0x2f, 0xef, 0x6f, 0x8f, 0x0f, 0xcf, 0x4f, 0xbf,
            0x3f, 0xff, 0x7f, 0x9f, 0x1f, 0xdf, 0x5f, 0xa0, 0x20, 0xe0, 0x60,
            0x80, 0x00, 0xc0, 0x40, 0xb0, 0x30, 0xf0, 0x70, 0x90, 0x10, 0xd0,
            0x50, 0xa8, 0x28, 0xe8, 0x68, 0x88, 0x08, 0xc8, 0x48, 0xb8, 0x38,
            0xf8, 0x78, 0x98, 0x18, 0xd8, 0x58, 0xa4, 0x24, 0xe4, 0x64, 0x84,
            0x04, 0xc4, 0x44, 0xb4, 0x34, 0xf4, 0x74, 0x94, 0x14, 0xd4, 0x54,
            0xac, 0x2c, 0xec, 0x6c, 0x8c, 0x0c, 0xcc, 0x4c, 0xbc, 0x3c, 0xfc,
            0x7c, 0x9c, 0x1c, 0xdc, 0x5c, 0xa2, 0x22, 0xe2, 0x62, 0x82, 0x02,
            0xc2, 0x42, 0xb2, 0x32, 0xf2, 0x72, 0x92, 0x12, 0xd2, 0x52, 0xaa,
            0x2a, 0xea, 0x6a, 0x8a, 0x0a, 0xca, 0x4a, 0xba, 0x3a, 0xfa, 0x7a,
            0x9a, 0x1a, 0xda, 0x5a, 0xa6, 0x26, 0xe6, 0x66, 0x86, 0x06, 0xc6,
            0x46, 0xb6, 0x36, 0xf6, 0x76, 0x96, 0x16, 0xd6, 0x56, 0xae, 0x2e,
            0xee, 0x6e, 0x8e, 0x0e, 0xce, 0x4e, 0xbe, 0x3e, 0xfe, 0x7e, 0x9e,
            0x1e, 0xde, 0x5e
        ].index(x) for x in range(256)]

        # Lookup table for payload byte 3 (Mouse HID byte 0)
        self.LUT3 = [[
            0x66, 0xe6, 0x26, 0xa6, 0x46, 0xc6, 0x06, 0x86, 0x76, 0xf6, 0x36,
            0xb6, 0x56, 0xd6, 0x16, 0x96, 0x6e, 0xee, 0x2e, 0xae, 0x4e, 0xce,
            0x0e, 0x8e, 0x7e, 0xfe, 0x3e, 0xbe, 0x5e, 0xde, 0x1e, 0x9e, 0x62,
            0xe2, 0x22, 0xa2, 0x42, 0xc2, 0x02, 0x82, 0x72, 0xf2, 0x32, 0xb2,
            0x52, 0xd2, 0x12, 0x92, 0x6a, 0xea, 0x2a, 0xaa, 0x4a, 0xca, 0x0a,
            0x8a, 0x7a, 0xfa, 0x3a, 0xba, 0x5a, 0xda, 0x1a, 0x9a, 0x64, 0xe4,
            0x24, 0xa4, 0x44, 0xc4, 0x04, 0x84, 0x74, 0xf4, 0x34, 0xb4, 0x54,
            0xd4, 0x14, 0x94, 0x6c, 0xec, 0x2c, 0xac, 0x4c, 0xcc, 0x0c, 0x8c,
            0x7c, 0xfc, 0x3c, 0xbc, 0x5c, 0xdc, 0x1c, 0x9c, 0x60, 0xe0, 0x20,
            0xa0, 0x40, 0xc0, 0x00, 0x80, 0x70, 0xf0, 0x30, 0xb0, 0x50, 0xd0,
            0x10, 0x90, 0x68, 0xe8, 0x28, 0xa8, 0x48, 0xc8, 0x08, 0x88, 0x78,
            0xf8, 0x38, 0xb8, 0x58, 0xd8, 0x18, 0x98, 0x67, 0xe7, 0x27, 0xa7,
            0x47, 0xc7, 0x07, 0x87, 0x77, 0xf7, 0x37, 0xb7, 0x57, 0xd7, 0x17,
            0x97, 0x6f, 0xef, 0x2f, 0xaf, 0x4f, 0xcf, 0x0f, 0x8f, 0x7f, 0xff,
            0x3f, 0xbf, 0x5f, 0xdf, 0x1f, 0x9f, 0x63, 0xe3, 0x23, 0xa3, 0x43,
            0xc3, 0x03, 0x83, 0x73, 0xf3, 0x33, 0xb3, 0x53, 0xd3, 0x13, 0x93,
            0x6b, 0xeb, 0x2b, 0xab, 0x4b, 0xcb, 0x0b, 0x8b, 0x7b, 0xfb, 0x3b,
            0xbb, 0x5b, 0xdb, 0x1b, 0x9b, 0x65, 0xe5, 0x25, 0xa5, 0x45, 0xc5,
            0x05, 0x85, 0x75, 0xf5, 0x35, 0xb5, 0x55, 0xd5, 0x15, 0x95, 0x6d,
            0xed, 0x2d, 0xad, 0x4d, 0xcd, 0x0d, 0x8d, 0x7d, 0xfd, 0x3d, 0xbd,
            0x5d, 0xdd, 0x1d, 0x9d, 0x61, 0xe1, 0x21, 0xa1, 0x41, 0xc1, 0x01,
            0x81, 0x71, 0xf1, 0x31, 0xb1, 0x51, 0xd1, 0x11, 0x91, 0x69, 0xe9,
            0x29, 0xa9, 0x49, 0xc9, 0x09, 0x89, 0x79, 0xf9, 0x39, 0xb9, 0x59,
            0xd9, 0x19, 0x99
        ].index(x) for x in range(256)]

        # Lookup table for payload byte 4 (Mouse HID byte 1)
        self.LUT4 = [[
            0xb1, 0x31, 0xf1, 0x71, 0x91, 0x11, 0xd1, 0x51, 0xa1, 0x21, 0xe1,
            0x61, 0x81, 0x00, 0xc1, 0x41, 0xb9, 0x39, 0xf9, 0x79, 0x99, 0x19,
            0xd9, 0x59, 0xa9, 0x29, 0xe9, 0x69, 0x89, 0x09, 0xc9, 0x49, 0xb5,
            0x35, 0xf5, 0x75, 0x95, 0x15, 0xd5, 0x55, 0xa5, 0x25, 0xe5, 0x65,
            0x85, 0x05, 0xc5, 0x45, 0xbd, 0x3d, 0xfd, 0x7d, 0x9d, 0x1d, 0xdd,
            0x5d, 0xad, 0x2d, 0xed, 0x6d, 0x8d, 0x0d, 0xcd, 0x4d, 0xb3, 0x33,
            0xf3, 0x73, 0x93, 0x13, 0xd3, 0x53, 0xa3, 0x23, 0xe3, 0x63, 0x83,
            0x03, 0xc3, 0x43, 0xbb, 0x3b, 0xfb, 0x7b, 0x9b, 0x1b, 0xdb, 0x5b,
            0xab, 0x2b, 0xeb, 0x6b, 0x8b, 0x0b, 0xcb, 0x4b, 0xb7, 0x37, 0xf7,
            0x77, 0x97, 0x17, 0xd7, 0x57, 0xa7, 0x27, 0xe7, 0x67, 0x87, 0x07,
            0xc7, 0x47, 0xbf, 0x3f, 0xff, 0x7f, 0x9f, 0x1f, 0xdf, 0x5f, 0xaf,
            0x2f, 0xef, 0x6f, 0x8f, 0x0f, 0xcf, 0x4f, 0xb0, 0x30, 0xf0, 0x70,
            0x90, 0x10, 0xd0, 0x50, 0xa0, 0x20, 0xe0, 0x60, 0x80, 0x01, 0xc0,
            0x40, 0xb8, 0x38, 0xf8, 0x78, 0x98, 0x18, 0xd8, 0x58, 0xa8, 0x28,
            0xe8, 0x68, 0x88, 0x08, 0xc8, 0x48, 0xb4, 0x34, 0xf4, 0x74, 0x94,
            0x14, 0xd4, 0x54, 0xa4, 0x24, 0xe4, 0x64, 0x84, 0x04, 0xc4, 0x44,
            0xbc, 0x3c, 0xfc, 0x7c, 0x9c, 0x1c, 0xdc, 0x5c, 0xac, 0x2c, 0xec,
            0x6c, 0x8c, 0x0c, 0xcc, 0x4c, 0xb2, 0x32, 0xf2, 0x72, 0x92, 0x12,
            0xd2, 0x52, 0xa2, 0x22, 0xe2, 0x62, 0x82, 0x02, 0xc2, 0x42, 0xba,
            0x3a, 0xfa, 0x7a, 0x9a, 0x1a, 0xda, 0x5a, 0xaa, 0x2a, 0xea, 0x6a,
            0x8a, 0x0a, 0xca, 0x4a, 0xb6, 0x36, 0xf6, 0x76, 0x96, 0x16, 0xd6,
            0x56, 0xa6, 0x26, 0xe6, 0x66, 0x86, 0x06, 0xc6, 0x46, 0xbe, 0x3e,
            0xfe, 0x7e, 0x9e, 0x1e, 0xde, 0x5e, 0xae, 0x2e, 0xee, 0x6e, 0x8e,
            0x0e, 0xce, 0x4e
        ].index(x) for x in range(256)]

        # Lookup table for payload byte 5 (Mouse HID byte 2)
        self.LUT5 = [[
            0x75, 0xf5, 0x35, 0xb5, 0x55, 0xd5, 0x15, 0x95, 0x65, 0xe5, 0x25,
            0xa5, 0x45, 0xc5, 0x05, 0x85, 0x7d, 0xfd, 0x3d, 0xbd, 0x5d, 0xdd,
            0x1d, 0x9d, 0x6d, 0xed, 0x2d, 0xad, 0x4d, 0xcd, 0x0d, 0x8d, 0x71,
            0xf1, 0x31, 0xb1, 0x51, 0xd1, 0x11, 0x91, 0x61, 0xe1, 0x21, 0xa1,
            0x41, 0xc1, 0x01, 0x81, 0x79, 0xf9, 0x39, 0xb9, 0x59, 0xd9, 0x19,
            0x99, 0x69, 0xe9, 0x29, 0xa9, 0x49, 0xc9, 0x09, 0x89, 0x77, 0xf7,
            0x37, 0xb7, 0x57, 0xd7, 0x17, 0x97, 0x67, 0xe7, 0x27, 0xa7, 0x47,
            0xc7, 0x07, 0x87, 0x7f, 0xff, 0x3f, 0xbf, 0x5f, 0xdf, 0x1f, 0x9f,
            0x6f, 0xef, 0x2f, 0xaf, 0x4f, 0xcf, 0x0f, 0x8f, 0x73, 0xf3, 0x33,
            0xb3, 0x53, 0xd3, 0x13, 0x93, 0x63, 0xe3, 0x23, 0xa3, 0x43, 0xc3,
            0x03, 0x83, 0x7b, 0xfb, 0x3b, 0xbb, 0x5b, 0xdb, 0x1b, 0x9b, 0x6b,
            0xeb, 0x2b, 0xab, 0x4b, 0xcb, 0x0b, 0x8b, 0x74, 0xf4, 0x34, 0xb4,
            0x54, 0xd4, 0x14, 0x94, 0x64, 0xe4, 0x24, 0xa4, 0x44, 0xc4, 0x04,
            0x84, 0x7c, 0xfc, 0x3c, 0xbc, 0x5c, 0xdc, 0x1c, 0x9c, 0x6c, 0xec,
            0x2c, 0xac, 0x4c, 0xcc, 0x0c, 0x8c, 0x70, 0xf0, 0x30, 0xb0, 0x50,
            0xd0, 0x10, 0x90, 0x60, 0xe0, 0x20, 0xa0, 0x40, 0xc0, 0x00, 0x80,
            0x78, 0xf8, 0x38, 0xb8, 0x58, 0xd8, 0x18, 0x98, 0x68, 0xe8, 0x28,
            0xa8, 0x48, 0xc8, 0x08, 0x88, 0x76, 0xf6, 0x36, 0xb6, 0x56, 0xd6,
            0x16, 0x96, 0x66, 0xe6, 0x26, 0xa6, 0x46, 0xc6, 0x06, 0x86, 0x7e,
            0xfe, 0x3e, 0xbe, 0x5e, 0xde, 0x1e, 0x9e, 0x6e, 0xee, 0x2e, 0xae,
            0x4e, 0xce, 0x0e, 0x8e, 0x72, 0xf2, 0x32, 0xb2, 0x52, 0xd2, 0x12,
            0x92, 0x62, 0xe2, 0x22, 0xa2, 0x42, 0xc2, 0x02, 0x82, 0x7a, 0xfa,
            0x3a, 0xba, 0x5a, 0xda, 0x1a, 0x9a, 0x6a, 0xea, 0x2a, 0xaa, 0x4a,
            0xca, 0x0a, 0x8a
        ].index(x) for x in range(256)]

        # Lookup table for payload byte 6 (Keyboard HID byte 1)
        self.LUT6 = [[
            0x31, 0xb1, 0x71, 0xf1, 0x11, 0x91, 0x51, 0xd1, 0x21, 0xa1, 0x61,
            0xe1, 0x01, 0x81, 0x41, 0xc1, 0x39, 0xb9, 0x79, 0xf9, 0x19, 0x99,
            0x59, 0xd9, 0x29, 0xa9, 0x69, 0xe9, 0x09, 0x89, 0x49, 0xc9, 0x35,
            0xb5, 0x75, 0xf5, 0x15, 0x95, 0x55, 0xd5, 0x25, 0xa5, 0x65, 0xe5,
            0x05, 0x85, 0x45, 0xc5, 0x3d, 0xbd, 0x7d, 0xfd, 0x1d, 0x9d, 0x5d,
            0xdd, 0x2d, 0xad, 0x6d, 0xed, 0x0d, 0x8d, 0x4d, 0xcd, 0x33, 0xb3,
            0x73, 0xf3, 0x13, 0x93, 0x53, 0xd3, 0x23, 0xa3, 0x63, 0xe3, 0x03,
            0x83, 0x43, 0xc3, 0x3b, 0xbb, 0x7b, 0xfb, 0x1b, 0x9b, 0x5b, 0xdb,
            0x2b, 0xab, 0x6b, 0xeb, 0x0b, 0x8b, 0x4b, 0xcb, 0x37, 0xb7, 0x77,
            0xf7, 0x17, 0x97, 0x57, 0xd7, 0x27, 0xa7, 0x67, 0xe7, 0x07, 0x87,
            0x47, 0xc7, 0x3f, 0xbf, 0x7f, 0xff, 0x1f, 0x9f, 0x5f, 0xdf, 0x2f,
            0xaf, 0x6f, 0xef, 0x0f, 0x8f, 0x4f, 0xcf, 0x30, 0xb0, 0x70, 0xf0,
            0x10, 0x90, 0x50, 0xd0, 0x20, 0xa0, 0x60, 0xe0, 0x00, 0x80, 0x40,
            0xc0, 0x38, 0xb8, 0x78, 0xf8, 0x18, 0x98, 0x58, 0xd8, 0x28, 0xa8,
            0x68, 0xe8, 0x08, 0x88, 0x48, 0xc8, 0x34, 0xb4, 0x74, 0xf4, 0x14,
            0x94, 0x54, 0xd4, 0x24, 0xa4, 0x64, 0xe4, 0x04, 0x84, 0x44, 0xc4,
            0x3c, 0xbc, 0x7c, 0xfc, 0x1c, 0x9c, 0x5c, 0xdc, 0x2c, 0xac, 0x6c,
            0xec, 0x0c, 0x8c, 0x4c, 0xcc, 0x32, 0xb2, 0x72, 0xf2, 0x12, 0x92,
            0x52, 0xd2, 0x22, 0xa2, 0x62, 0xe2, 0x02, 0x82, 0x42, 0xc2, 0x3a,
            0xba, 0x7a, 0xfa, 0x1a, 0x9a, 0x5a, 0xda, 0x2a, 0xaa, 0x6a, 0xea,
            0x0a, 0x8a, 0x4a, 0xca, 0x36, 0xb6, 0x76, 0xf6, 0x16, 0x96, 0x56,
            0xd6, 0x26, 0xa6, 0x66, 0xe6, 0x06, 0x86, 0x46, 0xc6, 0x3e, 0xbe,
            0x7e, 0xfe, 0x1e, 0x9e, 0x5e, 0xde, 0x2e, 0xae, 0x6e, 0xee, 0x0e,
            0x8e, 0x4e, 0xce
        ].index(x) for x in range(256)]
import crcmod  # pip -[--proxy <addr>] install crcmod
from intelhex import IntelHex  # pip [--proxy <addr>] install intelhex, needs latest version
import struct
import textwrap
import sys
import math
import ntpath
from collections import namedtuple

#tool version number
tool_version = "1.0"
#CRC related data
# CRC Polynomial used by OAD for CC254x
#crc16 = crcmod.mkCrcFun(0x18005, rev=False, initCrc=0x0000, xorOut=0x0000)
# CRC Poly used by OAD for CC26xx
crc16 = crcmod.mkCrcFun(0x11021, rev=False, initCrc=0x0000, xorOut=0x0000)

OAD_HDR_FMT = 'HHHH4sHBB'
OadHdr = namedtuple('OadImgHdr',
                    'crc crcShdw imgVer imgLen usrId imgAddr imgType status')
#the below dictionary contains the mapping from imgType string to an integeer
imgTypes = {'app': 1, 'stack': 2, 'np': 3, 'production': 4}

#Meta data status field measures success as 0xFF
META_STATUS_SUCCESS = 0xFF
META_STATUS_PREPENDED = 0XFE
#External flash layout (this info is in ext_flash_layout.h)
EXT_FL_SECTOR_1_SECTOR = "APP: 0x00000 - 0x1FFFF"
EXT_FL_SECTOR_2_SECTOR = "STACK/NP: 0x20000 - 0x3FFFF"
EXT_FL_SECTOR_3_SECTOR = "Factory: 0x40000 - 0x5FFFF"
EXT_FL_PG_SIZE = 4096
Beispiel #40
0
def SerialSend(cmd2):
    sreturn = C.create_string_buffer(30)
    sendsize = C.c_uint32(30)
    rsize = C.c_uint32(30)
    stimeout = C.c_uint32(50)
    crc16 = crcmod.mkCrcFun(0x1755b, rev=False, initCrc=0xFFFF, xorOut=0x0000)

    cmd = cmd2
    cmd = cmd.replace('\x5c','\x5c\x5c').replace('\xff','\x5c\xff')
    cmd = '\xff' + cmd
    cmd = '\x00' + cmd

    print cmd2
    print map(hex,cmd)

    crccalc = bytes(cmd[0:])

    print crccalc[0]

    a = crc16(crccalc[0])
    print(a)
    crccalc = bytes(cmd[1:])
    for d in crccalc:
        a = crc16(d,a)

    print(map(str,crccalc))
    print(a)
    crc = "".join(map(chr,divmod((a ^ 0xFFFF),256 )))
    crc = crc.replace('\x5c','\x5c\x5c')
    cmd = cmd + crc
 
    cmd = cmd.replace('\x3e','\x5c\x3e')
    cmd = '\x3e' + cmd + '\x3e'

    print "crc is:"
    print crc
    print map(str,crc)
    print "cmd is:"
    print map(hex,cmd)
    print map(str,cmd)
    print(str(cmd))
    print(bytes(cmd))
    print cmd


    print("Command to send to serial:", map(hex,cmd))
    print str(cmd)
    print len(cmd)
    sendcmd = C.create_string_buffer(bytes(cmd))
    sendsize.value = len(cmd)
    rval = imaq.imgSessionSerialFlush(sid)
    imaq.imgShowError(rval, text)
    print("buffer flushed: " + (text.value))
    if rval != 0:
        print("Not connected to Scicam")


    rval = imaq.imgSessionSerialWrite(sid, C.byref(sendcmd), C.byref(sendsize), stimeout)
    imaq.imgShowError(rval, text)
    print("Sent: " + (text.value))
    rval = imaq.imgSessionSerialReadBytes(sid, C.byref(sreturn), C.byref(rsize), stimeout)
    imaq.imgShowError(rval, text)
    print("Received: " + (text.value))
    rsizeval = rsize.value
    ret = sreturn.raw

    if ret[0] == '\x3e' and ret[rsizeval-1] == '\x3e':
        if ret[1] == '\xa0' or ret[1] == '\x20' or ret[1] == '\x00':
            crccalc = bytes(ret[1:rsizeval-3])
            a = crc16(crccalc[0])
            crccalc = str(ret[2:rsizeval-3]).replace('\x5c\x5c','\x5c').replace('\x5c\x3e','\x3e').replace('\x5c\xff','\xff')
            for d in crccalc:
                a = crc16(d,a)
                #print d, hex(a), hex(a ^ 0xFFFF)
                
            crc = "".join(map(chr,divmod((a ^ 0xFFFF),256 )))
            crcret = bytes(ret[rsizeval-3:rsizeval-1])
            #print crc, crcret
            if crc == crcret:
                print "good CRC"
                serial_ret = str(map("{0:>02x}".format,map(ord,crccalc[1:]))).translate(None,"[]',")
                print serial_ret
                return serial_ret
            else:
                print "bad CRC"
                return -3
        else:
            print "bad ack/nak/null"
            return -2
    else:
        print "incomplete packet?"
        return -1
Beispiel #41
0
def crccreate(b, length):
    crc16_func = crcmod.mkCrcFun(0x18005,
                                 initCrc=0xFFFF,
                                 rev=True,
                                 xorOut=0x0000)
    return crc16_func(b[0:length])
Beispiel #42
0
def crccheck(b,length):
    print('传过来的b,和lenght',b,'   ',length)
    crc16_func = crcmod.mkCrcFun(0x18005, initCrc=0xFFFF, rev=True, xorOut=0x0000)
    return crc16_func(b[0:length]) == bytesToInt(b[length], b[length + 1])
    def run(self):
        try:
            global recvFlag
            while True:
                crc16_ibm = crcmod.mkCrcFun(0x18005,
                                            rev=True,
                                            initCrc=0x0000,
                                            xorOut=0x0000)
                print 'start recv'
                msg = self.socket.recv()
                print 'finish recv'
                if len(msg) < 6:
                    print 'warning: length of msg is less than 6! Ignore this msg'
                    continue
                LENGTH = struct.unpack('!I', msg[1:5])[0]
                if LENGTH != (len(msg) - 5):
                    print "warning0: the length of msg is not equal to LENGTH! Ignore this msg"
                    continue
                HEADER = msg[0]
                CODE = msg[5:6]
                DATA = msg[6:-2]
                CRC16 = struct.unpack('!H', msg[-2:])[0]
                if (HEADER != '\xBB'):
                    print 'Do not handle the msg begin with %s! Ignore this msg' % (
                        HEADER, )
                    continue
                if (CODE != '\x08'):
                    print 'Do not handle the msg with code %s! Ignore this msg' % (
                        CODE, )
                    continue
                if crc16_ibm(msg[5:-2]) != CRC16:
                    print 'CRC check fail!'
                    continue
                if len(DATA) < 36:
                    print "warning: the length of msg is less than 36! Ignore this msg"
                    continue
                num_samp = struct.unpack('!l', DATA[24:28])[0]
                if len(DATA) != num_samp * 8 + 36:
                    print "warning1: the length of msg is not equal to LENGTH! Ignore this msg"
                    continue
                print 'writing a iq msg'

                freq = struct.unpack("!d", DATA[0:8])[0]
                samp_rate = struct.unpack('!d', DATA[8:16])[0]
                gain = struct.unpack('!d', DATA[16:24])[0]
                bandwidth = struct.unpack('!d', DATA[28:36])[0]
                real_part = struct.unpack('!%s' % ('f' * num_samp, ),
                                          DATA[36:36 + num_samp * 4])
                imag_part = struct.unpack(
                    '!%s' % ('f' * num_samp, ),
                    DATA[36 + num_samp * 4:36 + num_samp * 8])
                # self.q.put("recvd")

                local_time1 = time.strftime("%Y%m%d%H%M%S",
                                            time.localtime(time.time()))
                self.path = r'D:\postgraduate_program\usrp_recvfiles\auto_recognize\oc_%s.dat' % (
                    local_time1)
                f = open(self.path, 'w+')
                f.write(
                    str(freq) + ' ' + str(bandwidth) + ' ' + str(samp_rate) +
                    ' ')
                for i in range(len(real_part)):
                    f.write(str(real_part[i]) + ' ')
                f.write('\n')
                f.close()
                print len(real_part)
                print 'write worked'
                recvFlag = 1
                # flag = 1
                # if flag == 1:
                # break
        except KeyboardInterrupt:
            pass
        print 'end collect_recv at:', ctime()
    def run(self):
        print 'start scan_recv at:', ctime()
        try:
            while True:
                crc16_ibm = crcmod.mkCrcFun(0x18005,
                                            rev=True,
                                            initCrc=0x0000,
                                            xorOut=0x0000)
                # print 'before socket.recv'
                msg = self.socket.recv()
                # print 'recved'
                if len(msg) < 6:
                    print 'warning: length of msg is less than 6! Ignore this msg'
                    continue
                LENGTH = struct.unpack('!I', msg[1:5])[0]
                if LENGTH != (len(msg) - 5):
                    print "warning0: the length of msg is not equal to LENGTH! Ignore this msg"
                    continue
                HEADER = msg[0]
                CODE = msg[5:6]
                DATA = msg[6:-2]
                CRC16 = struct.unpack('!H', msg[-2:])[0]
                if (HEADER != '\xBB'):
                    print 'Do not handle the msg begin with %s! Ignore this msg' % (
                        HEADER, )
                    continue
                if (CODE != '\x06'):
                    print 'Do not handle the msg with code %s! Ignore this msg' % (
                        CODE, )
                    continue
                if crc16_ibm(msg[5:-2]) != CRC16:
                    print 'CRC check fail!'
                    continue
                if len(DATA) < 12:
                    print "warning1: the length of msg is less than 12! Ignore this msg"
                    continue
                freq_resolution = struct.unpack('!d', DATA[0:8])[0]
                n_freq = struct.unpack('!I', DATA[8:12])[0]
                if len(DATA) != n_freq * (4 + 8) + 12:
                    print "warning1: the length of msg is not equal to LENGTH! Ignore this msg"
                    continue

                # print 'receiving a spectrum msg!'
                bins = struct.unpack('!%s' % ('f' * n_freq, ),
                                     DATA[12:12 + n_freq * 4])
                freq_list = struct.unpack(
                    '!%s' % ('d' * n_freq, ),
                    DATA[12 + n_freq * 4:12 + n_freq * (4 + 8)])
                # Do what you want to do, here is a example.
                bins = [c + 4 for c in bins]
                filename = self.path % self.localtime
                f = open(filename, 'w+')
                print filename
                for i in range(len(freq_list)):
                    f.write(str(freq_list[i]) + ' ')
                f.write('\n')
                for i in range(len(bins)):
                    f.write(str(bins[i]) + ' ')
                f.write('\n')
                f.close()
                # print 'written!', ctime()
                break
            self.q.put("recvd")
        except KeyboardInterrupt:
            pass
        print 'end scan_recv at:', ctime()
Beispiel #45
0
 def __init__(self, callback):
     self.state = WAITING
     self.pkt = b""
     self.b = bytearray()
     self.crc_func = crcmod.mkCrcFun(0x11021, rev=True, initCrc=0xffff, xorOut=0x0000)
     self.callback = callback
Beispiel #46
0
#try:
h = pi.i2c_open(I2C_BUS, I2C_SLAVE)
#except:
#  eprint("i2c open failed")
#  exit(1)

#def i2cOpen():
#  global h
#  try:
#    h = pi.i2c_open(I2C_BUS, I2C_SLAVE)
#  except:
#    eprint("i2c open failed")
#    exit(1)

f_crc8 = crcmod.mkCrcFun(0x131, 0xFF, False, 0x00)


def calcCRC(TwoBdataArray):
    byteData = ''.join(chr(x) for x in TwoBdataArray)
    return f_crc8(byteData)


# print(hex(calcCRC([0xBE,0xEF])))


def readNBytes(n):
    try:
        (count, data) = pi.i2c_read_device(h, n)
    except:
        eprint("error: i2c_read failed")
Beispiel #47
0
        spacing - spacing in mm
        timestamp - milliseconds since 1970
        """
        try:
            data = np.asarray(image)
        except Exception as e:
            _print('ERROR, INVALID IMAGE. \n' + str(e))
            self._valid_message = False
            return
        data = data.reshape(dim)
        ImageMessage.__init__(self, data, spacing, timestamp)


# http://slicer-devel.65872.n3.nabble.com/OpenIGTLinkIF-and-CRC-td4031360.html
CRC64 = crcmod.mkCrcFun(0x142F0E1EBA9EA3693,
                        rev=False,
                        initCrc=0x0000000000000000,
                        xorOut=0x0000000000000000)


# https://github.com/openigtlink/OpenIGTLink/blob/cf9619e2fece63be0d30d039f57b1eb4d43b1a75/Source/igtlutil/igtl_util.c#L168
def _igtl_nanosec_to_frac(nanosec):
    base = 1000000000  # 10^9
    mask = 0x80000000
    r = 0x00000000
    while mask:
        base += 1
        base >>= 1
        if (nanosec >= base):
            r |= mask
            nanosec = nanosec - base
        mask >>= 1
Beispiel #48
0
def upload():

    # Identify all the sbd files again
    for root, dirs, files in os.walk("."):
        #if root != ".": # Ignore files in this directory - only process subdirectories
        #if root == ".": # Ignore subdirectories - only process this directory
        if len(files) > 0:
            # Find filenames with the correct format (imei-momsn.bin)
            valid_files = [
                afile for afile in files
                if ((afile[-4:] == '.bin') and (afile[15:16] == '-'))
            ]
        else:
            valid_files = []
        if len(valid_files) > 0:
            for filename in sorted_nicely(valid_files):
                longfilename = os.path.join(root, filename)
                msnum = filename[16:-4]  # Get the momsn
                imei = filename[0:15]  # Get the imei

                ignore_me = False  # Should we ignore this file?

                # Check if this file is in the list
                # If it isn't then this must be a new SBD file so try and process it
                try:
                    index = sbd.index(longfilename)
                except:
                    index = -1
                if index == -1:
                    sbd.append(
                        longfilename
                    )  # Add new filename to list so even if invalid we don't process it again

                    # Read the sbd file and unpack the data using numpy loadtxt
                    try:  # Messages without RockBLOCK destination
                        gpstime,latitude,longitude,altitude,speed,heading,pressure,humidity,temperature,battery = \
                            np.loadtxt(longfilename, delimiter=',', unpack=True, \
                            usecols=(0,1,2,3,4,5,8,9,10), converters={0:mdates.strpdate2num('%Y%m%d%H%M%S')})
                    except:  # Messages with RockBLOCK destination
                        try:
                            gpstime,latitude,longitude,altitude,speed,heading,pressure,humidity,temperature,battery = \
                                np.loadtxt(longfilename, delimiter=',', unpack=True, \
                                usecols=(1,2,3,4,5,6,9,10,11), converters={1:mdates.strpdate2num('%Y%m%d%H%M%S')})
                        except:
                            print 'Ignoring', filename
                            ignore_me = True

                    if (ignore_me == False):
                        if upload_this_IMEI == "":
                            upload_this_IMEI = imei
                            print 'Uploading messages from IMEI', imei

                        if (imei == upload_this_IMEI):
                            print 'Found new SBD file from beacon IMEI', imei, 'with MOMSN', msnum
                            pressure = int(
                                round(pressure))  # Convert pressure to integer
                            time_str = mdates.num2date(gpstime).strftime(
                                '%H:%M:%S,%y%m%d'
                            )  # Time string (HH:MM:SS,YYMMDD)
                            location_str = "{:.6f},{:.6f},{}".format(
                                latitude, longitude,
                                int(round(altitude)))  # Location

                            # Assemble the UKHAS format string
                            ukhas_str = "{},{},{},{:.2f},{:.1f},{},{},{},{},{}".format( \
                                callsign, time_str, location_str, speed, heading, pressure, humidity, temperature, battery, msnum)

                            # Calculate checksum
                            crc16 = crcmod.mkCrcFun(0x11021, 0xFFFF, False,
                                                    0x0000)
                            checksum = "{:04X}".format(crc16(ukhas_str))

                            # Append the checksum
                            ukhas_str = "$${}*{}".format(ukhas_str, checksum)
                            print 'Uploading:', ukhas_str

                            # Packet ID
                            packet_base64 = base64.standard_b64encode(
                                ukhas_str + "\n")
                            packet_sha256 = hashlib.sha256(
                                packet_base64).hexdigest()

                            # Time Created = backlog time
                            time_created = mdates.num2date(gpstime).strftime(
                                '%Y-%m-%dT%H:%M:%S+00:00')

                            # Time Uploaded = now
                            now = datetime.utcnow()
                            time_uploaded = now.replace(
                                microsecond=0).isoformat() + "+00:00"
Beispiel #49
0
    'NET', 'CST', 'CO', 'SO', 'TO', 'SAVE', 'BAUD', 'NODEADR', 'GNODEADR',
    'GADV', 'EN', 'DI', 'GTIMEOUT', 'TIMEOUT', 'UPTIME', 'SADV'
]

from crcmod.predefined import mkCrcFun as mkCrcFunPre
from crcmod import mkCrcFun

crcfuncs = {}
crcnames = [
    'crc-8', 'crc-8-darc', 'crc-8-i-code', 'crc-8-itu', 'crc-8-maxim',
    'crc-8-rohc', 'crc-8-wcdma'
]
for crc_name in crcnames:
    crcfuncs[crc_name] = mkCrcFunPre(crc_name)

crcfuncs['CRC-13-BBC'] = mkCrcFun(0x1CF5)

cmds = {}
for cmd in FMCC:
    cmds[cmd] = {}
    for crc_name, crc_func in crcfuncs.items():
        cmds[cmd][crc_name] = crc_func(bytes(cmd, 'ascii'))

crccount = {}
for crc_name in crcnames:
    crccount[crc_name] = [0] * 256
    for cmd, value in cmds.items():
        crccount[crc_name][value[crc_name]] += 1

from collections import Counter
import operator
Beispiel #50
0
        return cls.msg("00", flag)

    @classmethod
    def msg(cls, resType, flag):
        result = [resType, flagEncode(flag), "01"]
        result.extend(timeEncode(True))  # 当前时间
        result.append("00")  # 开店时间闭店时间
        result.append("00")  # 开店时间闭店时间
        result.append("17")  # 开店时间闭店时间
        result.append("3B")  # 开店时间闭店时间
        crc = getCrC(result)
        result.append(crc)
        return "".join(result)


crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)


def getCrC(msgs: list):
    msg = b""
    for m in msgs:
        msg = msg + int(m, 16).to_bytes(int(len(m) / 2), "big")
    return crc16(msg).to_bytes(2, "big").hex().upper()


def timeEncode(week=False):
    """
    格式化时间 将时间转为16进制字符形式
    :return [year,month,day,hour,minute,second]
    """
    now = datetime.now()
Beispiel #51
0
class SCD30I2CInterface:
    i2c_addr = 0x61

    def __init__(self, interface, logger):
        self.lower = interface
        self._logger = logger
        self._level = logging.DEBUG if self._logger.name == __name__ else logging.TRACE

    def _log(self, message, *args):
        self._logger.log(self._level, "SCD30: " + message, *args)

    _crc = staticmethod(crcmod.mkCrcFun(0x131, initCrc=0xff, rev=False))

    async def _read_raw(self, addr, length=0):
        assert length % 2 == 0
        acked = await self.lower.write(self.i2c_addr,
                                       struct.pack(">H", addr),
                                       stop=True)
        if acked is False:
            raise SCD30Error("SCD30 did not acknowledge address write")
        crc_data = await self.lower.read(self.i2c_addr,
                                         length // 2 * 3,
                                         stop=True)
        if crc_data is None:
            raise SCD30Error("SCD30 did not acknowledge data read")
        self._log("addr=%#06x data=<%s>", addr, dump_hex(crc_data))
        data = bytearray()
        for index, (chunk,
                    crc) in enumerate(struct.iter_unpack(">2sB", crc_data)):
            if self._crc(chunk) != crc:
                raise SCD30Error("CRC failed on word {}".format(index))
            data += chunk
        return data

    async def _write_raw(self, cmd, data=b""):
        assert len(data) % 2 == 0
        crc_data = bytearray()
        for chunk, in struct.iter_unpack(">2s", data):
            crc_data += chunk
            crc_data.append(self._crc(chunk))
        self._log("cmd=%#06x args=<%s>", cmd, dump_hex(crc_data))
        acked = await self.lower.write(self.i2c_addr,
                                       struct.pack(">H", cmd) + crc_data,
                                       stop=True)
        if acked is False:
            raise SCD30Error("SCD30 did not acknowledge command write")

    async def _read(self, addr, format):
        return struct.unpack(
            format, await self._read_raw(addr, struct.calcsize(format)))

    async def _write(self, cmd, format="", *args):
        await self._write_raw(cmd, struct.pack(format, *args))

    async def soft_reset(self):
        self._log("soft reset")
        await self._write(CMD_SOFT_RESET)

    async def firmware_version(self):
        major, minor = await self._read(CMD_FIRMWARE_VER, ">BB")
        self._log("firmware major=%d minor=%d", major, minor)
        return major, minor

    async def is_data_ready(self):
        ready, = await self._read(CMD_DATA_READY, ">H")
        self._log("data ready=%d", ready)
        return bool(ready)

    async def start_measurement(self, pressure_mbar=None):
        assert pressure_mbar is None or pressure_mbar in range(700, 1200)
        if pressure_mbar is None:
            self._log("start measurement")
        else:
            self._log("start measurement pressure=%d [mbar]", pressure_mbar)
        await self._write(CMD_START_MEASURE, ">H", pressure_mbar or 0)

    async def stop_measurement(self):
        self._log("stop measurement")
        await self._write(CMD_STOP_MEASURE)

    async def read_measurement(self):
        co2_ppm, temp_degC, rh_pct = \
            await self._read(CMD_READ_MEASURE, ">fff")
        self._log("measured CO₂=%.2f [ppm] T=%.2f [°C] RH=%.2f [%%]", co2_ppm,
                  temp_degC, rh_pct)
        return SCD30Measurement(co2_ppm, temp_degC, rh_pct)

    async def get_measurement_interval(self):
        interval_s, = await self._read(CMD_INTERVAL, ">H")
        self._log("measurement interval get=%d [s]", interval_s)
        return interval_s

    async def set_measurement_interval(self, interval_s):
        assert 2 <= interval_s <= 1800
        self._log("measurement interval set=%d [s]", interval_s)
        await self._write(CMD_INTERVAL, ">H", interval_s)

    async def get_auto_self_calibration(self):
        enabled, = await self._read(CMD_AUTO_SELF_CAL, ">H")
        self._log("auto calibration status=%d", enabled)
        return bool(enabled)

    async def set_auto_self_calibration(self, enabled):
        self._log("auto calibration %s", "enable" if enabled else "disable")
        await self._write(CMD_AUTO_SELF_CAL, ">H", bool(enabled))

    async def get_forced_calibration(self):
        co2_ppm, = await self._read(CMD_FORCE_RECAL, ">H")
        self._log("forced calibration get=%d [ppm]", co2_ppm)
        return co2_ppm

    async def set_forced_calibration(self, co2_ppm):
        assert 400 <= co2_ppm <= 2000
        self._log("forced calibration set=%d [ppm]", co2_ppm)
        await self._write(CMD_FORCE_RECAL, ">H", co2_ppm)

    async def get_temperature_offset(self):
        temp_degC_100ths, = await self._read(CMD_TEMP_OFFSET, ">H")
        temp_degC = temp_degC_100ths / 100
        self._log("temperature offset get=%.2f [°C]", temp_degC)
        return temp_degC

    async def set_temperature_offset(self, temp_degC):
        assert 0.0 <= temp_degC
        self._log("temperature offset set=%.2f [°C]", temp_degC)
        temp_degC_100ths = int(temp_degC * 100)
        await self._write(CMD_TEMP_OFFSET, ">H", temp_degC_100ths)

    async def get_altitude_compensation(self):
        altitude_m, = await self._read(CMD_ALTITUDE_COMP, ">H")
        self._log("altitude compensation get=%d [m]", altitude_m)
        return altitude_m

    async def set_altitude_compensation(self, altitude_m):
        self._log("altitude compensation set=%d [m]", altitude_m)
        await self._write(CMD_ALTITUDE_COMP, ">H", altitude_m)
Beispiel #52
0
def init_crc():
    POLYNOMIAL = 0x1d5  # 0xd5 + leading 1
    crc = crcmod.mkCrcFun(poly=POLYNOMIAL, initCrc=0, rev=False)
    return crc
Beispiel #53
0
def crc(inBytes, init=0x00000000):
    return crcmod.mkCrcFun(0x104C11DB7,
                           initCrc=init,
                           rev=True,
                           xorOut=0x00000000)(inBytes)
Beispiel #54
0
import crcmod

from common.op_params import opParams
from selfdrive.car.hyundai.values import CAR, CHECKSUM

hyundai_checksum = crcmod.mkCrcFun(0x11D, initCrc=0xFD, rev=False, xorOut=0xdf)


def create_lkas11(packer, frame, car_fingerprint, apply_steer, steer_req,
                  lkas11, sys_warning, sys_state, enabled, left_lane,
                  right_lane, left_lane_depart, right_lane_depart,
                  lfa_available, bus):
    values = lkas11
    values["CF_Lkas_LdwsSysState"] = 3 if steer_req else sys_state
    values["CF_Lkas_SysWarning"] = sys_warning
    values["CF_Lkas_LdwsLHWarning"] = left_lane_depart
    values["CF_Lkas_LdwsRHWarning"] = right_lane_depart
    values["CR_Lkas_StrToqReq"] = apply_steer
    values["CF_Lkas_ActToi"] = steer_req
    values["CF_Lkas_ToiFlt"] = 0
    values["CF_Lkas_MsgCount"] = frame % 0x10
    values["CF_Lkas_Chksum"] = 0

    if values["CF_Lkas_LdwsOpt_USM"] == 4:
        values["CF_Lkas_LdwsOpt_USM"] = 3

    if lfa_available:
        values["CF_Lkas_LdwsActivemode"] = int(left_lane) + (
            int(right_lane) << 1)
        values["CF_Lkas_LdwsOpt_USM"] = 2
Beispiel #55
0
class MemoryFloppyAppletTool(GlasgowAppletTool, applet=MemoryFloppyApplet):
    help = "manipulate raw disk images captured from IBM/Shugart floppy drives"
    description = """
    Dissect raw disk images (i.e. RDATA samples) and extract MFM-encoded sectors into linear
    disk images.

    Any errors during extraction are logged, the linear image is filled and padded to
    the necessary geometry, and all areas that were not recovered from the raw image are filled
    with the following repeating byte patterns:

        * <FA11> for sectors completely missing from the raw image;
        * <DEAD> for sectors whose header was found but data was corrupted;
        * <BAAD> for sectors that were marked as "deleted" (i.e. bad blocks) in the raw image,
          and no decoding was attempted.

    ("Deleted" sectors are not currently recognized.)
    """

    @classmethod
    def add_arguments(cls, parser):
        p_operation = parser.add_subparsers(dest="operation",
                                            metavar="OPERATION")

        p_index = p_operation.add_parser(
            "index",
            help="discover and verify raw disk image contents and MFM sectors")
        p_index.add_argument(
            "-n",
            "--no-decode",
            action="store_true",
            default=False,
            help=
            "do not attempt to decode track data, just index tracks (much faster)"
        )
        p_index.add_argument("file",
                             metavar="RAW-FILE",
                             type=argparse.FileType("rb"),
                             help="read raw disk image from RAW-FILE")

        p_raw2img = p_operation.add_parser(
            "raw2img", help="extract raw disk images into linear disk images")
        p_raw2img.add_argument(
            "-s",
            "--sector-size",
            metavar="BYTES",
            type=int,
            default=512,
            help="amount of bytes per sector (~always the default: %(default)s)"
        )
        p_raw2img.add_argument(
            "-t",
            "--sectors-per-track",
            metavar="COUNT",
            type=int,
            required=True,
            help="amount of sectors per track (9 for DD, 18 for HD, ...)")
        p_raw2img.add_argument("raw_file",
                               metavar="RAW-FILE",
                               type=argparse.FileType("rb"),
                               help="read raw disk image from RAW-FILE")
        p_raw2img.add_argument("linear_file",
                               metavar="LINEAR-FILE",
                               type=argparse.FileType("wb"),
                               help="write linear disk image to LINEAR-FILE")

    crc_mfm = staticmethod(crcmod.mkCrcFun(0x11021, initCrc=0xffff, rev=False))

    def iter_tracks(self, file):
        while True:
            header = file.read(struct.calcsize(">BBL"))
            if header == b"": break
            head, track, size = struct.unpack(">BBL", header)
            yield track, head, file.read(size)

    def iter_mfm_sectors(self, symbstream, verbose=False):
        state = "IDLE"
        count = 0
        data = bytearray()
        header = None
        size = None
        for offset, (comma, symbol) in enumerate(symbstream):
            self.logger.trace("state=%s sym=%s.%02X", state,
                              "K" if comma else "D", symbol)

            if comma and symbol == 0xA1:
                if state == "IDLE":
                    data.clear()
                    count = 1
                    state = "SYNC"
                elif state == "SYNC":
                    count += 1
                else:
                    self.logger.warning("desync sym-off=%d state=%s sym=K.A1",
                                        offset, state)
                    data.clear()
                    count = 1
                    state = "SYNC"

                data.append(symbol)
                continue

            data.append(symbol)
            if state == "IDLE":
                continue
            elif state == "SYNC":
                if count < 3:
                    self.logger.warning("early data sym-off=%d sync-n=%d",
                                        offset, count)
                if symbol == 0xFE:
                    count = 6  # CYL+HD+SEC+NO+CRCH/L
                    state = "FORMAT"
                elif symbol == 0xFB:
                    if header is None:
                        self.logger.warning("spurious sector sym-off=%d",
                                            offset)
                    else:
                        count = 2 + size  # DATA+CRCH/L
                        state = "SECTOR"
                else:
                    self.logger.warning("unknown mark sym-off=%d type=%02X",
                                        offset, symbol)
                    state = "IDLE"
                continue

            if state in ("FORMAT", "SECTOR"):
                count -= 1
                if count == 0 and self.crc_mfm(data) != 0:
                    self.logger.warning(
                        "wrong checksum sym-off=%d state=%s type=%02X", offset,
                        state, data[2])
                    state = "IDLE"
                    continue

            if count == 0 and state == "FORMAT":
                cyl, hd, sec, no = struct.unpack(">BBBB", data[4:-2])
                size = 1 << (7 + no)

                header = cyl, hd, sec
                self.logger.log(logging.INFO if verbose else logging.DEBUG,
                                "  header cyl=%2d hd=%d sec=%2d size=%d",
                                *header, size)

            if count == 0 and state == "SECTOR":
                yield (header, data[4:-2])

                header = None

            if count == 0:
                state = "IDLE"

    async def run(self, args):
        if args.operation == "index":
            for head, track, bytestream in self.iter_tracks(args.file):
                self.logger.info("track %d head %d: %d samples captured", head,
                                 track,
                                 len(bytestream) * 8)
                if args.no_decode:
                    continue

                mfm = SoftwareMFMDecoder(self.logger)
                symbstream = mfm.demodulate(mfm.lock(mfm.bits(bytestream)))
                for _ in self.iter_mfm_sectors(symbstream, verbose=True):
                    pass

        if args.operation == "raw2img":
            image = bytearray()
            next_lba = 0
            missing = 0

            try:
                curr_lba = 0
                for head, track, bytestream in self.iter_tracks(args.raw_file):
                    self.logger.info("processing track %d head %d", head,
                                     track)

                    mfm = SoftwareMFMDecoder(self.logger)
                    symbstream = mfm.demodulate(mfm.lock(mfm.bits(bytestream)))

                    sectors = {}
                    seen = set()
                    for (cyl, hd,
                         sec), data in self.iter_mfm_sectors(symbstream):
                        if sec not in range(1, 1 + args.sectors_per_track):
                            self.logger.error(
                                "sector at C/H/S %d/%d/%d overflows track geometry "
                                "(%d sectors per track)", cyl, hd, sec,
                                args.sectors_per_track)
                            continue

                        if sec in seen:
                            # Due to read redundancy, seeing this is not an error in general,
                            # though this could be a sign of a strange invalid track. We do not
                            # currently aim to handle these cases, so just ignore them.
                            self.logger.debug(
                                "duplicate sector at C/H/S %d/%d/%d", cyl, hd,
                                sec)
                            continue
                        else:
                            seen.add(sec)

                        lba = ((cyl << 1) + hd) * args.sectors_per_track + (
                            sec - 1)
                        self.logger.info("  mapping C/H/S %d/%d/%d to LBA %d",
                                         cyl, hd, sec, lba)

                        if len(data) != args.sector_size:
                            self.logger.error(
                                "sector at LBA %d has size %d (%d expected)",
                                lba, len(data), args.sector_size)
                        elif lba in sectors:
                            self.logger.error("duplicate sector at LBA %d",
                                              lba)
                        else:
                            sectors[lba] = data

                        if len(seen) == args.sectors_per_track:
                            self.logger.debug(
                                "found all sectors on this track")
                            break

                    last_lba = curr_lba + args.sectors_per_track
                    while curr_lba < last_lba:
                        if curr_lba in sectors:
                            args.linear_file.seek(curr_lba * args.sector_size)
                            args.linear_file.write(sectors[curr_lba])
                        else:
                            missing += 1
                            args.linear_file.seek(curr_lba * args.sector_size)
                            args.linear_file.write(b"\xFA\x11" *
                                                   (args.sector_size // 2))
                            self.logger.error("sector at LBA %d missing",
                                              curr_lba)
                        curr_lba += 1
            finally:
                self.logger.info("%d/%d sectors missing", missing, last_lba)
Beispiel #56
0
def crccheckhole(b,length):
    crc16_func = crcmod.mkCrcFun(0x18005, initCrc=0xFFFF, rev=True, xorOut=0x0000)

    return hex(crc16_func(b[0:length]))==bytesToHex(b[length],b[length+1])
Beispiel #57
0
class USBSimplePrintSink(USBEventSink):
    """ Most basic sink for USB events: report them directly to the console. """

    import crcmod
    data_crc = staticmethod(crcmod.mkCrcFun(0x18005))

    def __init__(self, highspeed):
        self.frameno = None
        self.subframe = 0
        self.highspeed = highspeed

        self.last_ts_frame = 0

        self.last_ts_print = 0
        self.last_ts_pkt = 0
        self.ts_base = 0
        self.ts_roll_cyc = 2**24

    def handle_usb_packet(self, ts, buf, flags):
        CRC_BAD = 1
        CRC_GOOD = 2
        CRC_NONE = 3
        crc_check = CRC_NONE

        ts_delta_pkt = ts - self.last_ts_pkt
        self.last_ts_pkt = ts

        if ts_delta_pkt < 0:
            self.ts_base += self.ts_roll_cyc

        ts += self.ts_base

        suppress = False

        msg = ""

        if len(buf) != 0:
            pid = buf[0] & 0xF
            if (buf[0] >> 4) ^ 0xF != pid:
                msg += "Err - bad PID of %02x" % pid
            elif pid == 0x5:
                if len(buf) < 3:
                    msg += "RUNT frame"
                else:
                    frameno = buf[1] | (buf[2] << 8) & 0x7
                    if self.frameno == None:
                        self.subframe = None
                    else:
                        if self.subframe == None:
                            if frameno == (self.frameno + 1) & 0xFF:
                                self.subframe = 0 if self.highspeed else None
                        else:
                            self.subframe += 1
                            if self.subframe == 8:
                                if frameno == (self.frameno + 1) & 0xFF:
                                    self.subframe = 0
                                else:
                                    msg += "WTF Subframe %d" % self.frameno
                                    self.subframe = None
                            elif self.frameno != frameno:
                                msg += "WTF frameno %d" % self.frameno
                                self.subframe = None

                    self.frameno = frameno

                    self.last_ts_frame = ts
                    suppress = True
                    msg += "Frame %d.%c" % (frameno, '?' if self.subframe
                                            == None else "%d" % self.subframe)
            elif pid in [0x3, 0xB, 0x7]:
                n = {3: 0, 0xB: 1, 0x7: 2}[pid]

                msg += "DATA%d: %s" % (n, hd(buf[1:]))

                if len(buf) > 2:
                    calc_check = self.data_crc(buf[1:-2]) ^ 0xFFFF
                    pkt_check = buf[-2] | buf[-1] << 8

                    if calc_check != pkt_check:
                        msg += "\tUnexpected ERR CRC"

            elif pid == 0xF:
                msg += "MDATA: %s" % hd(buf[1:])
            elif pid in [0x01, 0x09, 0x0D, 0x04]:
                if pid == 1:
                    name = "OUT"
                elif pid == 9:
                    name = "IN"
                elif pid == 0xD:
                    name = "SETUP"
                elif pid == 0x04:
                    name = "PING"
                if len(buf) < 3:
                    msg += "RUNT: %s %s" % (name, " ".join("%02x" % i
                                                           for i in buf))
                else:

                    addr = buf[1] & 0x7F
                    endp = (buf[2] & 0x7) << 1 | buf[1] >> 7

                    msg += "%-5s: %d.%d" % (name, addr, endp)
            elif pid == 2:
                msg += "ACK"
            elif pid == 0xA:
                msg += "NAK"
            elif pid == 0xE:
                msg += "STALL"
            elif pid == 0x6:
                msg += "NYET"
            elif pid == 0xC:
                msg += "PRE-ERR"
                pass
            elif pid == 0x8:
                msg += "SPLIT"
                pass
            else:
                msg += "WUT"

        if not suppress:
            crc_char_d = {CRC_BAD: '!', CRC_GOOD: 'C', CRC_NONE: ' '}

            flag_field = "[  %s%s%s%s%s%s]" % (
                'L' if flags & 0x20 else ' ', 'F' if flags & 0x10 else ' ',
                'T' if flags & 0x08 else ' ', 'C' if flags & 0x04 else ' ',
                'O' if flags & 0x02 else ' ', 'E' if flags & 0x01 else ' ')
            delta_subframe = ts - self.last_ts_frame
            delta_print = ts - self.last_ts_print
            self.last_ts_print = ts
            RATE = 60.0e6

            subf_print = ''
            frame_print = ''

            if self.frameno != None:
                frame_print = "%3d" % self.frameno

            if self.subframe != None:
                subf_print = ".%d" % self.subframe

            print("%s %10.6f d=%10.6f [%3s%2s +%7.3f] [%3d] %s " %
                  (flag_field, ts / RATE, (delta_print) / RATE, frame_print,
                   subf_print, delta_subframe / RATE * 1E6, len(buf), msg))
Beispiel #58
0
def hash(module, function, bits=13, print_hash=True):
    crc32_func = crcmod.mkCrcFun(0x11EDC6F41, initCrc=0, xorOut=0)
    h = crc32_func(unicode(module) + function + "\x00")
    print "[+] 0x%08X = %s!%s" % (h, module.lower(), function)
    return h
Beispiel #59
0
from uvscada.util import hexdump

from collections import namedtuple
import struct
import serial
import random
import crcmod

# Forward CRC-16-CCITT
crcf = crcmod.mkCrcFun(poly=0x11021, initCrc=0x0000, rev=False, xorOut=0x0000)

# namedtuple
PCmd = namedtuple('PCmd', 'res0 seq sum res3')
PCMD_FMT = 'BBB6s'

'''
Volt: mV
Amp: mA
Resistance: mOhm
'''

fields = '''\
res1
res2
Application Version
Product Code
Input Voltage[1]
Operation Mode[1]
Operation Status[1]
Cycle Number[1]
Minute[1]
Beispiel #60
0
import crcmod
import collections
import random
from pwn import *

Entry = collections.namedtuple("Entry",
                               ["bits", "delta", "bit_len", "lookahead"])

crc16 = crcmod.mkCrcFun(0x18005, initCrc=0, xorOut=0)
crc32 = crcmod.mkCrcFun(0x11EDC6F41, initCrc=0, xorOut=0xFFFFFFFF)
crc64 = crcmod.mkCrcFun(0x142F0E1EBA9EA3693,
                        initCrc=0,
                        xorOut=0xFFFFFFFFFFFFFFFF)

# Retry until you don't get "Cannot choose from an empty sequence" error
N = 512
DECAY = 0.9
LOOKAHEAD_BITS = 8
OTHER_LEVEL = 0.4
RANDOM = 1 / 100


def bits_to_s(num):
    s = b""
    for i in range(N):
        if (num >> i) & 1:
            s += b"A"
        else:
            s += b"a"
    return s