示例#1
0
def read_board_id(bus, i2cbus, mux, mux_val):
	print "Should read 0x57 to ID the board type";
	board_type=[];
	board_type_read = -1;

	while board_type_read < 128:
		try:
			if (board_type_read == -1):
				board_type_tmp = bus.read_i2c_block_data(0x57, 0, 32);
			else:
				board_type_tmp = bus.read_i2c_block_data(0x57, board_type_read, 32);
			for member in board_type_tmp:
				board_type.append(member);
			board_type_read = len(board_type);
#		      print "board_type_read=%d, %d" % (board_type_read, len(board_type));
		except IOError:
			print "Error reading board ID";
			break;

	print "Read %d bytes checking board_type" % board_type_read;
	if (board_type_read >= 128):
		board_name ="";
		board_sub_type ="";
		board_mfg_date="";
		board_test_time="";
		board_sn="";
		for byte in range (0, 0x10):
			if (isprint(chr(board_type[byte]))):
				board_name += "%c" % board_type[byte];
		for byte in range (0x10, 0x20):
			if (isprint(chr(board_type[byte]))):
				board_sub_type += "%c" % board_type[byte];
		for byte in range (0x20, 0x30):
			if (isprint(chr(board_type[byte]))):
				board_mfg_date += "%c" % board_type[byte];
		for byte in range (0x30, 0x40):
			if (isprint(chr(board_type[byte]))):
				board_test_time += "%c" % board_type[byte];
		for byte in range (0x50, 0x60):
			if (isprint(chr(board_type[byte]))):
				board_sn += "%c" % board_type[byte];

		print "--> BOARD INFO <--";
		print "NAME: %s" % board_name;
		print "SUB_TYPE: %s" % board_sub_type;
		print "MFG_DATE: %s" % board_mfg_date;
		print "TEST_TIME: %s" % board_test_time;
		print "SERIAL: %s" % board_sn;
示例#2
0
	return start + g_bytesPerHalfRow

def hexdump(data):
	g_bytesPerRow = 16
	pos = 0
	size = len(data)
	while  pos < size:
		row_start = pos

		print '%.4X:  ' % pos,
		
		pos = hexdump_half_row(data, pos)
		pos = hexdump_half_row(data, pos)

		sys.stdout.write("|")

		i = row_start
		while i < row_start + g_bytesPerRow and i < size:
			c = data[i]
			if isprint(c):
				sys.stdout.write("%c" % c)
			else:
				sys.stdout.write("%c" % '.')
			i = i + 1
				
		for i in range(i, row_start + g_bytesPerRow):
			sys.stdout.write(" ")
示例#3
0
    def getAttributes(self, path):
        attributes = {}
        sys_path = "/sys%s" % path
        try:
            names = os.listdir(sys_path)
        except OSError:
            return attributes

        for name in names:
            name_path = posixpath.join(sys_path, name)
            if name[0] == "." \
               or name in ["dev", "uevent"] \
               or posixpath.isdir(name_path) \
               or posixpath.islink(name_path):
                continue

            try:
                value = open(name_path, "r").read().strip()
            except IOError:
                continue

            value = value.split("\n")[0]
            if [c for c in value if not isprint(c)]:
                continue

            attributes[name] = value

        return attributes
示例#4
0
    def doRead(self):
        """ Input is ready! """
        curses.noecho()
        c = self.stdscr.getch()  # read a character

        if c == curses.KEY_BACKSPACE:
            self.searchText = self.searchText[:-1]

        elif c == curses.KEY_ENTER or c == 10:
            text = self.searchText
            self.searchText = ''

            self.print_line(">> %s" % text)

            try:
                if self.callback:
                    self.callback.on_line(text)
            except Exception as e:
                self.print_line(str(e))

            self.stdscr.refresh()

        elif isprint(c):
            if len(self.searchText) == self.cols - 2:
                return
            self.searchText = self.searchText + chr(c)

        self.stdscr.addstr(self.rows - 1, 0,
                           self.searchText + (' ' * (
                           self.cols - len(self.searchText) - 2)))

        self.paintStatus(self.statusText + ' %d' % len(self.searchText))
        self.stdscr.move(self.rows - 1, len(self.searchText))
        self.stdscr.refresh()
示例#5
0
 def handle_input(self, input):
     input = self.translate_input(input)
     if input in range(curses.KEY_F0, curses.KEY_F10) or \
             input == curses.KEY_UP or input == curses.KEY_DOWN:
         logging.debug("Got special key, breaking")
         self.input = input
         return ord(ctrl('g'))
     else:
         self.input = None
     if input is not None and isprint(input):
         self.text_buff.append(chr(input))
         self.text.append(input)
         if not self.is_valid():
             if len(self.text) > 0:
                 self.text.pop()
                 length = len(self.text_buff)
                 temp_buff = self.text_buff[:length-49]
                 self.set_repo(self.text_buff[length-49:])
                 length = len(self.text_buff)
                 self.text_buff = temp_buff + self.text_buff[length-49:]
         if self.masked:
             input = self.masked_char
     elif input == curses.KEY_BACKSPACE or input == ord(ctrl('H')):
         if len(self.text) > 0:
             self.text.pop()
             self.text_buff.pop()
   
     return input
示例#6
0
    async def _get_packet(self) -> Tuple[str, str]:
        """Get the next valid packet, along with an isoformat datetime string."""

        try:
            raw_packet = await self.reader.readline()
            raw_packet = raw_packet.decode("ascii").strip()
        except (serial.SerialException, UnicodeDecodeError):
            return

        raw_packet = "".join(char for char in raw_packet if isprint(char))

        if not raw_packet:
            return

        packet_dt = dt.now().isoformat()

        if self._packet_log:  # TODO: make this async
            self._packet_log.write(f"{packet_dt} {raw_packet}\r\n")

        if not MESSAGE_REGEX.match(raw_packet):
            _LOGGER.warning("Packet structure is not valid, >> %s <<",
                            raw_packet)
            return

        if len(raw_packet[50:]) != 2 * int(raw_packet[46:49]):
            _LOGGER.warning("Packet payload length not valid, >> %s <<",
                            raw_packet)
            return

        if int(raw_packet[46:49]) > 48:  # TODO: a ?corrupt pkt of 55 seen
            _LOGGER.warning("Packet payload length excessive, >> %s <<",
                            raw_packet)
            return

        return f"{packet_dt} {raw_packet}"
示例#7
0
    def process(self, key):
        if key == ENTER:
            self.selected = self.vis_items[self.highlighted]
            return Response.enter

        elif key == ESCAPE:
            return Response.escape

        elif key in BACKSPACE and self.letters:
            self.highlighted = 0
            self.letters.pop(-1)
            return Response.keepon

        elif key in UP:
            self.highlighted = max([0, self.highlighted - 1])
            return Response.keepon

        elif key in DOWN:
            self.highlighted = min([self.max_items - 1, self.highlighted + 1])
            return Response.keepon

        elif ascii.isprint(key):
            val = chr(key)
            self.highlighted = 0
            self.letters.append(val)
            return Response.keepon

        else:
            return Response.keepon
示例#8
0
 def key_event(self, key):
     if ca.isprint(key):
         self.value.insert(self._offset + self.cursor, chr(key))
         self.cursor += 1
         self._fix_single_move()
         self.changed()
     elif key == curses.KEY_LEFT:
         if self.cursor + self._offset > 0:
             self.cursor -= 1
             self._fix_single_move()
     elif key == curses.KEY_RIGHT:
         if self.cursor + self._offset < len(self.value):
             self.cursor += 1
             self._fix_single_move()
     elif key == ca.BS or key == curses.KEY_BACKSPACE:
         if self.cursor + self._offset > 0:
             del self.value[self._offset + self.cursor - 1]
             self.cursor -= 1
             if self.cursor == 0:
                 self._shift_cursor_to_middle()
             self.changed()
     else:
         return False
     self.touch()
     return True
示例#9
0
    def doRead(self):
        """ Input is ready! """
        curses.noecho()
        c = self.stdscr.getch()  # read a character

        if c == curses.KEY_BACKSPACE:
            self.searchText = self.searchText[:-1]

        elif c == curses.KEY_ENTER or c == 10:
            text = self.searchText
            self.searchText = ''

            self.print_line(">> %s" % text)

            try:
                if self.callback:
                    self.callback.on_line(text)
            except Exception as e:
                self.print_line(str(e))

            self.stdscr.refresh()

        elif isprint(c):
            if len(self.searchText) == self.cols - 2:
                return
            self.searchText = self.searchText + chr(c)

        self.stdscr.addstr(
            self.rows - 1, 0,
            self.searchText + (' ' * (self.cols - len(self.searchText) - 2)))

        self.paintStatus(self.statusText + ' %d' % len(self.searchText))
        self.stdscr.move(self.rows - 1, len(self.searchText))
        self.stdscr.refresh()
示例#10
0
def main_loop(stdscr):
    (screen_h, screen_w) = stdscr.getmaxyx()
    win = curses.newwin(1, screen_w, screen_h - 1, 0)

    locale.setlocale(locale.LC_ALL, "")
    code = locale.getpreferredencoding()

    #print group_setup[0]
    #print group_setup1[0]
    ch = win.getch()
    #print ch
    stdscr.addstr(0, 0, group_setup[0].encode(code))
    #stdscr.addstr(group_setup1[0])
    stdscr.refresh()
    ch = win.getch()
    stdscr.addstr(1, 0, group_setup[1].encode(code))
    stdscr.addstr(2, 50, group_setup[1].encode(code))
    stdscr.addstr(3, 50, group_setup1[1].encode(code))
    stdscr.addstr(4, 50, a.encode(code))
    stdscr.addstr(5, 50, b.encode(code))
    stdscr.addstr(6, 50, "b[0].isprint: " + str(ascii.isprint(ord(b[0]))))
    stdscr.addstr(7, 50, b)
    stdscr.refresh()
    win.nodelay(False)
    #print(ch)
    x = 50
    y = 8
    while True:
        ch = win.get_wch()
        stdscr.addstr(y, x, ch)
        x = x + 1
        if x > 100:
            x = 50
            y = y + 1
        stdscr.refresh()
示例#11
0
  def run( self ):
    print ''.join(["Listening for input on ", self.tty.port, " in new thread."])
    while(1):
      self.ttylock.acquire()
      #wait for a single character
      char = self.tty.read()
      #if no input, just wait
      if( char == '' ):
        pass
      # if user hit ctrl-c, erase buffer
      elif( char == '\x03'):
        self.clearbuffer()
        self.tty.write('\r\n')
      #if user hit enter, send message
      elif( char == '\r' ):
        self.tty.write('\r\n')
        self.notify( self.textbuffer )
        self.clearbuffer()
      #if buffer is full, beep
      elif( self._maxbuf > 0 and len( self.textbuffer ) >= self._maxbuf ):
        self.tty.write('\x07')
      #if character is printable and buffer not full, echo it and add to buffer
      elif( isprint( char ) ):
        self.textbuffer = ''.join( [ self.textbuffer, char ] )
        self.tty.write( char )

      self.ttylock.release()
      time.sleep(0.01)
示例#12
0
        class ttcp_t():
            def __init__(self,
                         length,
                         udp,
                         port,
                         numblocks,
                         ipaddr,
                         verbose=False):
                self.ipaddr = ipaddr
                self.port = port
                self.length = length
                self.udp = udp
                self.numblocks = numblocks
                self.conn = -1
                self.status = -1
                self.address = (self.ipaddr, self.port)
                if udp:
                    self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                else:
                    self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.s.settimeout(3)
                self.msg = ""
                self.usewheel = verbose

            def start(self):
                index = 0
                wheel = ["\\\b", "|\b", "/\b", "-\b"]
                self.status = -1
                try:
                    self.s.connect(self.address)
                except socket.timeout, e:
                    self.msg = "failed to connect"
                    return

                j = 0
                buf = ''
                for i in range(0, self.length):
                    while not isprint(j & 0x7F):
                        j = j + 1
                    buf = buf + chr(j & 0x7F)
                    j = j + 1

                if self.usewheel:
                    sys.stdout.write(wheel[index])

                if (self.udp):
                    self.s.send(' !"#')

                for i in range(0, self.numblocks):
                    try:
                        self.s.send(buf)
                    except socket.timeout, e:
                        self.msg = "Data socket timed out sending block %d." % i
                        return

                    index = (index + 1) & 0x3
                    if self.usewheel:
                        sys.stdout.write(wheel[index])
                        sys.stdout.flush()
示例#13
0
	def processInput(self,key):
		if(ascii.isprint(key) or ascii.isspace(key)):
			self.text=self.text + chr(key)
			return True
		if(key==ascii.DEL):
			self.text=self.text[:-1]
			return True
		return False
示例#14
0
def unicode_to_alpha(uni):
    '''
    Convert a six-dot Unicode Braille character to a SimBraille one.
    Printable ASCII is returned unchanged.  Unprintable ASCII not allowed.
    '''
    if ASCII.isprint(uni):
        return uni
    return mapping[ord(uni) - UNICODE_BRAILLE_BASE]
示例#15
0
def printable(input):
   r = []
   for char in input:
      if isprint(char):
         r += char
      else:
         r += "."
   return ''.join(r)
示例#16
0
 def processInput(self, key):
     if (ascii.isprint(key) or ascii.isspace(key)):
         self.text = self.text + chr(key)
         return True
     if (key == ascii.DEL):
         self.text = self.text[:-1]
         return True
     return False
def printable(input):
    r = []
    for char in input:
        if isprint(char):
            r += char
        else:
            r += "."
    return ''.join(r)
示例#18
0
def rawText(i):
    s = ""
    while not isControl(x[i]):
        if ca.isprint(x[i]):
            s += x[i]
        else:
            s += '\\x%02x' % ord(x[i])
        i += 1
    return (s, i)
def sfdisk_escape_string(value: str):
    chars = []
    for char in map(chr, value.encode("utf-8")):
        if not isprint(char) or iscntrl(char) or char in ['"', "\\", "`", "$"]:
            hex_val = hex(int(char))
            chars.append(f"\\x{hex_val}")
        else:
            chars.append(char)
    return '"' + "".join(chars) + '"'
示例#20
0
def is_printable(c):
    '''see if a character is printable'''
    global have_ascii
    if have_ascii:
        return ascii.isprint(c)
    if isinstance(c, int):
        ic = c
    else:
        ic = ord(c)
    return ic >= 32 and ic <= 126
示例#21
0
def is_printable(c):
    '''see if a character is printable'''
    global have_ascii
    if have_ascii:
        return ascii.isprint(c)
    if isinstance(c, int):
        ic = c
    else:
        ic = ord(c)
    return ic >= 32 and ic <= 126
示例#22
0
	def main(self, scr):
		self.init_colors()
		self.scr = scr
		for song in self.songs:
			self.filename = song
			self.selected_line = 0
			self.song = irank.Song(song)
			self.draw()
			logging.debug("editing song: %s" % (song,))

			def save():
				logging.debug("Saving file %s with comment: %s" % (
					self.filename, self.song.values.flatten()))
				self.song.save()

			while True:
				ch = self.scr.getch()
				if ch == ascii.NL:
					save()
					break
				elif ch == curses.KEY_UP or ch == ord('k'):
					self.select(PREVIOUS)
				elif ch == curses.KEY_DOWN or ch == ord('j'):
					self.select(NEXT)
				elif ch == curses.KEY_LEFT or ch == ord(' ') or ch == ord('h'):
					self.add_rating(-1)
				elif ch == curses.KEY_RIGHT or ch == ord('l'):
					self.add_rating(1)
				elif ch == curses.KEY_HOME or ch == ord('g'):
					self.move_to(0)
				elif ch == curses.KEY_END or ch == ord('G'):
					self.move_to(len(self.song.values)-1)
				elif ch == ascii.ESC:
					break
				elif ch == ascii.EOT: # ctrl-D
					return
				elif ascii.isprint(ch) and ascii.unctrl(ch) in "12345":
					self.set_rating(int(ascii.unctrl(ch)))
				elif ascii.isprint(ch) and ascii.unctrl(ch) == '`':
					self.set_rating(0)
				self.draw()
示例#23
0
    def main(self, scr):
        self.init_colors()
        self.scr = scr
        for song in self.songs:
            self.filename = song
            self.selected_line = 0
            self.song = irank.Song(song)
            self.draw()
            logging.debug("editing song: %s" % (song, ))

            def save():
                logging.debug("Saving file %s with comment: %s" %
                              (self.filename, self.song.values.flatten()))
                self.song.save()

            while True:
                ch = self.scr.getch()
                if ch == ascii.NL:
                    save()
                    break
                elif ch == curses.KEY_UP or ch == ord('k'):
                    self.select(PREVIOUS)
                elif ch == curses.KEY_DOWN or ch == ord('j'):
                    self.select(NEXT)
                elif ch == curses.KEY_LEFT or ch == ord(' ') or ch == ord('h'):
                    self.add_rating(-1)
                elif ch == curses.KEY_RIGHT or ch == ord('l'):
                    self.add_rating(1)
                elif ch == curses.KEY_HOME or ch == ord('g'):
                    self.move_to(0)
                elif ch == curses.KEY_END or ch == ord('G'):
                    self.move_to(len(self.song.values) - 1)
                elif ch == ascii.ESC:
                    break
                elif ch == ascii.EOT:  # ctrl-D
                    return
                elif ascii.isprint(ch) and ascii.unctrl(ch) in "12345":
                    self.set_rating(int(ascii.unctrl(ch)))
                elif ascii.isprint(ch) and ascii.unctrl(ch) == '`':
                    self.set_rating(0)
                self.draw()
示例#24
0
    def operate(self, c):
        # Add a character.
        if ascii.isprint(c):
            self.tag_redraw()
            self._text += chr(c)

        # Delete a character.
        elif c in {ascii.BS, ascii.DEL, curses.KEY_BACKSPACE}:
            self.tag_redraw()
            self._text = self._text[:-1]

        return 'CONTINUE'
示例#25
0
文件: window.py 项目: Ikke/ktane
 def event(self, ev, c):
     if ascii.isprint(ev):
         self.text += c
     elif ev in [curses.KEY_BACKSPACE, KEY_BACKSPACE]:
         self.text = self.text[:-1]
     elif ev in [curses.KEY_ENTER, KEY_ENTER]:
         curses.curs_set(0)
         logging.debug("LineInput: Enter pressed, {} callbacks".format(len(self.ready_callbacks)))
         for cb in self.ready_callbacks:
             cb(self.text)
     else:
         self.text += c
示例#26
0
文件: window.py 项目: Ikke/ktane
 def event(self, ev, c):
     if ascii.isprint(ev):
         self.text += c
     elif ev in [curses.KEY_BACKSPACE, KEY_BACKSPACE]:
         self.text = self.text[:-1]
     elif ev in [curses.KEY_ENTER, KEY_ENTER]:
         curses.curs_set(0)
         logging.debug("LineInput: Enter pressed, {} callbacks".format(len(self.ready_callbacks)))
         for cb in self.ready_callbacks:
             cb(self.text)
     else:
         self.text += c
示例#27
0
文件: uiTools.py 项目: JustMe23/arm
def getPrintable(line, keepNewlines = True):
  """
  Provides the line back with non-printable characters stripped.
  
  Arguments:
    line          - string to be processed
    stripNewlines - retains newlines if true, stripped otherwise
  """
  
  line = line.replace('\xc2', "'")
  line = "".join([char for char in line if (isprint(char) or (keepNewlines and char == "\n"))])
  return line
示例#28
0
文件: uiTools.py 项目: zhou-kz/arm
def getPrintable(line, keepNewlines = True):
  """
  Provides the line back with non-printable characters stripped.
  
  Arguments:
    line          - string to be processed
    stripNewlines - retains newlines if true, stripped otherwise
  """
  
  line = line.replace('\xc2', "'")
  line = "".join([char for char in line if (isprint(char) or (keepNewlines and char == "\n"))])
  return line
示例#29
0
def printable(input):
    '''!
         Filter out non-printable characters from an input string

         @param input (str) Input string

         @return String with non-printable characters removed
                 None if invalid input data type
    '''
    if input is not None and isString(input):
        return ''.join(char for char in input if isprint(char))
    else:
        return None
示例#30
0
 def clean(text):
     try:
         clean_text = str(''.join(
             (ascii.isprint(c) and c) or
             ((c == '\n' or c == '\r') and '\n') or
             '?' for c in text
             ))
             # curses.unctrl(c) for c in text
         return clean_text
     except Exception as ex:
         print ('WARNING: Unexpected error encountered in %s' %
                inspect.stack()[0][3])
         raise # Don't catch all without raising
示例#31
0
def DumpHex(str, fmt, address, size):
    out_fmt = {
        'B' : '{:02x} ',
        'H' : '{:04x} ',
        'I' : '{:08x} ',
        'Q' : '{:16x} '
    }
    out_unknown = {
        'B' : 'xx ',
        'H' : 'xxxx ',
        'I' : 'xxxxxxxx ',
        'Q' : 'xxxxxxxxxxxxxxxx '
    }
    out_size = {
        'B' : 1,
        'H' : 2,
        'I' : 4,
        'Q' : 8
    }

    #Adjust size to have enough for the type of data requested.
    if (size%out_size[fmt] != 0):
       size += out_size[fmt]-(size%out_size[fmt])

    mem = ReadMemory(address, size)
    j = 0
    hex_str = "{:08x}: ".format(address);
    chr_str = ""
    # Output the data read from memory
    while (size > j):
        # Print the data
        if (j%out_size[fmt] == 0):
            hex_str += out_fmt[fmt].format(unpack_from(fmt, mem, j)[0])
        byte = chr(unpack_from("B", mem, j)[0])
        if (isprint(byte)):
            chr_str += byte
        else:
            chr_str += '.'
        j += 1
        if (j%16 == 0):
            print str + hex_str + chr_str
            hex_str = "{:08x}: ".format(address+j);
            chr_str = ""
    #Take care of any trailing data.
    if (j%16 != 0):
        while (j%16 != 0):
            if (j%out_size[fmt] == 0):
                hex_str += out_unknown[fmt]
            chr_str += "."
            j += 1;
        print str + hex_str + chr_str
示例#32
0
def alpha_to_unicode(alpha):
    '''
    Convert an alpha to a Unicode character.
    '''
    alpha = alpha.upper()
    try:
        if ASCII.isprint(alpha):  # includes ASCII space, 0x20
            return chr(UNICODE_BRAILLE_BASE + mapping.index(alpha))
        elif ASCII.isspace(alpha):
            return alpha
        else:
            return chr(UNICODE_BRAILLE_BASE)
    except ValueError:
        return 0
示例#33
0
文件: validator.py 项目: pvh/reddit
    def run(self, text, text2 = ''):
        text = VLength.run(self, text, text2)

        if text is None:
            return None

        try:
            if all(isprint(str(x)) for x in text):
                return str(text)
        except UnicodeEncodeError:
            pass

        self.set_error(errors.BAD_STRING)
        return None
示例#34
0
def get_printable(line, keep_newlines = True):
  """
  Provides the line back with non-printable characters stripped.

  :param str line: string to be processed
  :param str keep_newlines: retains newlines if **True**, stripped otherwise

  :returns: **str** of the line with only printable content
  """

  line = line.replace('\xc2', "'")
  line = filter(lambda char: isprint(char) or (keep_newlines and char == '\n'), line)

  return line
示例#35
0
    def parse(self):
        def tab(white_count, line):
            self.space(white_count, line)
            if not self.allow_tabs:
                self.error.incr('tab')

        def carriage_return(white_count, line):
            self.error.incr('eol-cr')
            self.eol(white_count, line)

        def line_feed(white_count, line):
            if not self.window.matches('\r\n'):
                self.eol(white_count, line)

        class line():
            def invalidate(self, string):
                remove = -len(string)
                if (string == ''.join(self.content[remove:])):
                    del self.content[remove:]

        line = line()
        line.number = 1
        line.content = []

        white_count = 0
        whitespace = {
            ' ': self.space,
            '\t': tab,
            '\r': carriage_return,
            '\n': line_feed
        }
        for char in open(self.path, 'rb').read():
            self.window.add(char)
            try:
                whitespace[char](white_count, line)
                self.in_url = False
            except KeyError:
                if not isprint(char):
                    self.error.incr('non-ascii')
                if self.window.matches(self.url_preface):
                    line.invalidate(self.url_preface[:-1])
                    self.in_url = True
                if not self.in_url and self.is_valid(self.window):
                    line.content.append(char)
                white_count = 0
        if line.content:
            self.eol(white_count, line)
        return self.report()
示例#36
0
    def _get_packet(self, timeout=0.1) -> Tuple[str, str]:
        """Get the next packet, along with an isoformat dt string."""

        if self.fake_port:
            raw_packet = self.fake_port.readline().strip()

            if raw_packet:
                packet_dt = raw_packet[:26]
                raw_packet = raw_packet[27:]
            else:
                return "EOF", None

        else:
            self.ser.timeout = timeout

            try:
                raw_packet = self.ser.readline().decode("ascii").strip()
            except UnicodeDecodeError:
                return None, None

            raw_packet = "".join(char for char in raw_packet if isprint(char))

            if not raw_packet:
                return None, None

            if not isinstance(raw_packet, str):
                _LOGGER.warning("Packet datatype is not a string, >> %s <<", raw_packet)
                return None, None

            packet_dt = dt.now().isoformat()

            if self._packet_log:
                self._packet_log.write(f"{packet_dt} {raw_packet}\r\n")

        if not MESSAGE_REGEX.match(raw_packet):
            _LOGGER.warning("Packet structure is not valid, >> %s <<", raw_packet)
            return None, None

        if len(raw_packet[50:]) != 2 * int(raw_packet[46:49]):
            _LOGGER.warning("Packet payload length is not valid, >> %s <<", raw_packet)
            return None, None

        if int(raw_packet[46:49]) > 48:
            _LOGGER.warning("Packet payload length is excessive, >> %s <<", raw_packet)
            return None, None

        return raw_packet, packet_dt
示例#37
0
    def __init__(self, *args, **kwargs):
        super(DhcpOptionToDhcpGroupAdminForm, self).__init__(*args, **kwargs)

        if self.instance:
            printable = True
            if self.instance.value:
                for c in self.instance.value:
                    if not isprint(c):
                        printable = False
                        break

            if printable:
                self.fields['readable_value'].initial = self.instance.value
            else:
                self.fields['readable_value'].initial = '0x' + binascii.hexlify(self.instance.value)

            self.original_value = self.fields['readable_value'].initial
示例#38
0
def hexdump(data, indent):
    res = ''
    for i in range(0, len(data), 16):
        if i:
            for k in range(0, indent):
                res += ' '
        for j in range(i, min(i + 16, len(data))):
            res += '{0:02x} '.format(ord(data[j]))
        for k in range(min(i + 16, len(data)), i + 16):
            res += '   '
        for j in range(i, min(i + 16, len(data))):
            if ascii.isprint(data[j]):
                res += data[j]
            else:
                res += '.'
        res += '\n'
    return res
    def handle_input(self, input_key):
        '''
        For each keystroke, determine if it's a special character (and needs
        to end editing), printable character, or backspace.

        For special characters, send the return the done-editing code (CTRL-G),
        and store the special character for processing by parent window
        objects.

        If printable, append it to self.text, and try to validate. If
        validation fails, reject the character.

        '''
        input_key = self.translate_input(input_key)
        if self.is_special_char(input_key):
            self.input_key = input_key
            return EditField.CMD_DONE_EDIT
        else:
            self.input_key = None
        if isprint(input_key) or (ismeta(input_key) and
                                  input_key < curses.KEY_MIN):
            # isprint: ASCII characters
            # ismeta and < curses.KEY_MIN: Remaining UTF-8 characters
            # > curses.KEY_MIN: Special key such as down arrow, backspace, etc.
            self.text.append(unichr(input_key))
            if not self.is_valid():
                if len(self.text) > 0:
                    self.text.pop()
                return None
            self._modified = True
            if self.masked:
                input_key = self.masked_char
        elif input_key == curses.KEY_BACKSPACE:
            if len(self.text) > 0:
                del_char = self.text.pop()
                self._modified = True
                del_width = charwidth(del_char)
                if textwidth(self.get_text()) >= self.area.columns:
                    self.scroll(columns=-del_width)
            self.is_valid()
            # Run self.is_valid here so that any functional side effects can
            # occur, but don't check the return value (removing a character
            # from a valid string should never be invalid, and even if it were,
            # it would not make sense to add the deleted character back in)

        return input_key
示例#40
0
文件: ui.py 项目: hunner/irc-256
  def run(self):
    while 1:
      ch = self.screen.getch()
      if ch != -1:
        if ch == ord('\n'):
          msg = self.input_line.data
          self.add_line(Line('chat', msg, timestamp=True))
          self.server.privmsg(self.room, msg)
          self.input_line.clear_data()
          self._draw_input()
        elif ch == 127: #backspace
          self.input_line.backspace()
          self._draw_input()
        elif isprint(ch):
          self.input_line.add_ch(chr(ch))

      self.irc.process_once()
示例#41
0
 def display(self):
     for i in range(len(self.data)):
         if i % 10 == 0:
             self.disp_cols_helper()
         u = xorpad(self.data[i], self.pad)
         sanitized = bytearray()
         for c in u:
             if not isprint(c):
                 sanitized.append(ord('?'))
             else:
                 sanitized.append(c)
         print('{row:{width}d}{space:{space_width}}{content}'.format(
             width=self.left_margin - 2,
             space_width=2,
             space='',
             row=i,
             content=sanitized.decode()))
示例#42
0
    def check_payload(self, test):
        from curses.ascii import isprint

        if os.path.isfile(test):
            with open(test, "r") as ins:
                for line in ins:
                    result = self.browser_socket_handler.query(''.join(
                        [x for x in line if isprint(x)]))
                    if result:
                        self.result = self.result + "\n" + line
        elif os.path.exists(self.configuration['INPUT']):
            for name in os.listdir(self.configuration['INPUT']):
                self.check_payload(self.configuration['INPUT'] + "/" + name)
        else:
            self.result = self.browser_socket_handler.query(
                self.configuration['INPUT'])
        pass
示例#43
0
 def process_input(self, ch):
     if isprint(ch):
         self._set_term(self._term + chr(ch))
     elif ch in (BS, KEY_BACKSPACE):
         self._set_term(self._term[:-1])
     elif unctrl(ch) == "^W":
         self._set_term(self._strip_last_word(self._term))
     elif unctrl(ch) == "^N":
         self._set_match_highlight(self._match_highlight + 1)
     elif unctrl(ch) == "^P":
         self._set_match_highlight(self._match_highlight - 1)
     elif ch in (KEY_ENTER, CR, LF):
         return ("select", self._get_selected_item())
     elif ch in (ESC, ) or unctrl(ch) in ("^C", "^G"):
         return ("abort", self._get_selected_item())
     elif ch == TAB and self._tab_exits:
         return ("tab", self._get_selected_item())
示例#44
0
    def handle_input(self, input_key):
        '''
        For each keystroke, determine if it's a special character (and needs
        to end editing), printable character, or backspace.

        For special characters, send the return the done-editing code (CTRL-G),
        and store the special character for processing by parent window
        objects.

        If printable, append it to self.text, and try to validate. If
        validation fails, reject the character.

        '''
        input_key = self.translate_input(input_key)
        if self.is_special_char(input_key):
            self.input_key = input_key
            return EditField.CMD_DONE_EDIT
        else:
            self.input_key = None
        if isprint(input_key) or (ismeta(input_key)
                                  and input_key < curses.KEY_MIN):
            # isprint: ASCII characters
            # ismeta and < curses.KEY_MIN: Remaining UTF-8 characters
            # > curses.KEY_MIN: Special key such as down arrow, backspace, etc.
            self.text.append(unichr(input_key))
            if not self.is_valid():
                if len(self.text) > 0:
                    self.text.pop()
                return None
            self._modified = True
            if self.masked:
                input_key = self.masked_char
        elif input_key == curses.KEY_BACKSPACE:
            if len(self.text) > 0:
                del_char = self.text.pop()
                self._modified = True
                del_width = charwidth(del_char)
                if textwidth(self.get_text()) >= self.area.columns:
                    self.scroll(columns=-del_width)
            self.is_valid()
            # Run self.is_valid here so that any functional side effects can
            # occur, but don't check the return value (removing a character
            # from a valid string should never be invalid, and even if it were,
            # it would not make sense to add the deleted character back in)

        return input_key
示例#45
0
def hexdump(data, indent):
    res = ''
    for i in range(0, len(data), 16):
        if i:
            for k in range(0, indent):
                res += ' '
        for j in range(i, min(i + 16, len(data))):
            res += '{0:02x} '.format(ord(data[j]))
        for k in range(min(i + 16, len(data)), i + 16):
            res += '   '
        for j in range(i, min(i + 16, len(data))):
            if ascii.isprint(data[j]):
                res += data[j]
            else:
                res += '.'
        res += '\n'
    return res
示例#46
0
 def on_key(self, ch) -> bool:
     if self is self.container.focus:
         cmd = self.cmd.get(ch)
         if cmd is not None:
             cmd()
             self._cursor_refresh()
             return True
         elif isinstance(ch, str):
             if _ascii.isascii(ch):
                 if _ascii.isprint(ch):
                     self.add_char(ch)
                     self._cursor_refresh()
                     return True
             else:
                 self.add_char(ch)
                 self._cursor_refresh()
                 return True
     return False
示例#47
0
def dump_vendor():
	# SFF-8472 Table 4-1
	# bytes 96-127

	vendor_hex = ""
	vendor_isprint = ""

	for byte in range (96, 128):
		vendor_hex=vendor_hex +('%-2.2x' % sff_data[byte])

		v_char = '%c' % sff_data[byte];

		if (isprint(v_char)):
			vendor_isprint = vendor_isprint + v_char;
		else:
			vendor_isprint = vendor_isprint + ' ';
	print vendor_hex
	print vendor_isprint
示例#48
0
    def add_data(self, data, color = None):
        global Colors
        newdata = ""
        for ch in str(data):
            #printable characters and \t \n and are output to the screen
            #all others are hexlified
            if ascii.isprint(ch) or  ch == "\t" or ch == "\n":
                newdata += ch
            else:
                newdata +=  "\\" +  str(hex(ord(ch)))[1:]

        if color is None:
            dcolor = Colors.YELLOW
            if self.evencolor:
                dcolor = Colors.CYAN
            self.evencolor = not self.evencolor
        else:
            dcolor = Colors.get_color(color) 
            

        self.data.append([newdata, dcolor])
示例#49
0
  def run( self ):
    print ''.join(["Listening for input on ", self.tty.ser.port, " in new thread."])
    while(1):
      self.ttylock.acquire()
      #wait for a single character
      char = self.tty.read()
      #if no input, just wait
      if( char == '' ):
        pass
      # if user hit ctrl-c, erase buffer
      elif( char == '\x03'):
        self.clearbuffer()
        self.tty.write('\r\n')
        self.linepos = 0
      #if user hit enter, send message
      elif( char == '\r' ):
        self.tty.write('\r\n')
        self.notify( self.textbuffer )
        self.clearbuffer()
        self.linepos = 0
        
      #if buffer is full, beep
      elif( self._maxbuf > 0 and len( self.textbuffer ) >= self._maxbuf ):
        self.tty.write('\x07')
      #if character is printable and buffer not full, echo it and add to buffer
      elif( isprint( char ) ):
        self.textbuffer = ''.join( [ self.textbuffer, char ] )
        self.tty.write( char )
        self.linepos += 1
        # Wrap input lines if they are greater than
        # 60 columns. This wan't necessary on the TI-745
        # because it would wrap automatically
        if self.linepos > self._columns:
          self.tty.write( '\r\n' )
          self.linepos = 0

      self.ttylock.release()
      time.sleep(0.01)
示例#50
0
 def _XMLContentFilter (self, content, was_array_typecode=None) :
     result = "" # RVO
     typecode = { float:'d', complex:'D' }
     type_content = type(content)
     if was_array_typecode != None :
         t = pretty.NumericString_(was_array_typecode, content)
     elif type_content in [float, complex] :
         t = pretty.NumericString_(typecode[type_content], content)
     elif type_content == long :
         t = repr(content)
     else : 
         t = str(content)
     for ii in xrange(0,len(t)) :
         c = t[ii]
         if not isprint(c) :
             result += "&#"+hex(ord(c))[1:]+";"
         else :
             if c in self.specialCharToEscapeSeq_ :
                 esc_seq = self.specialCharToEscapeSeq_[t[ii]]
                 result = result + esc_seq
             else :
                 result = result + t[ii]
     return result
示例#51
0
def M2Image (s) :
    '''code from m2k to output a string with m2k understanding of literals'''
    global M2ImageLookup
    # The final result
    result = ""
    ender = ""

    # Start of with a quote
    result += '"'

    # Go through, looking for special sequences and output
    for c in s :
        if c in M2ImageLookup :
            ender = M2ImageLookup[c]
        elif isprint(c) :
            ender = c
        else :
            # Build a hexadecimal escape sequence.  The output is always
            # going to be a \x followed by 2 hex digits
            ender = hex(ord(c))
        result += ender
    # End with a quote
    result += '"'
    return result
示例#52
0
	def _input_iteration(self):
		ch = self.mainscr.getch()
		if QUITTING_TIME.isSet(): return False
		logging.debug("input: %r (%s / %s, ctrl=%s)" % (ch, ascii.unctrl(ch), ascii.ctrl(ch), ascii.isctrl(ch)))
		if ascii.isprint(ch):
			self.add_char(chr(ch))
		elif ch in (ascii.BS, ascii.DEL, curses.KEY_BACKSPACE):
			self.remove_char()
		elif ch == ascii.NL:
			self.open_selected()
		elif ch == curses.KEY_UP or (ascii.ismeta(ch) and ascii.unctrl(ch) == 'a'): # shift+tab???
			self.select(PREVIOUS)
		elif ch == curses.KEY_DOWN or ch == curses.ascii.TAB:
			self.select(NEXT)
		elif ch == curses.KEY_LEFT:
			self.move_cursor(backwards=True)
		elif ch == curses.KEY_RIGHT:
			self.move_cursor()
		elif ch == curses.KEY_HOME:
			self.move_cursor_to(0)
		elif ch == curses.KEY_END:
			self.move_cursor_to(len(self.query))
		elif ascii.isctrl(ch) and ascii.ctrl(ch) in (ascii.STX, ascii.ETX, ascii.CAN, ascii.ETX): # ctrl-c, variously o_O
			logging.debug("copy to clipboard")
			self.copy_selected_path_to_clipboard()
		elif ch == ascii.ESC:
			self.set_query("")
		elif ch == ascii.EOT: # ctrl-D
			logging.debug("EOF")
			return False
		else:
			logging.debug("not handled...")
		self.ui_lock.acquire()
		self.update()
		self.ui_lock.release()
		return True
示例#53
0
	def printable(self,theinput):
		return ''.join([char for char in theinput if isprint(char)])
示例#54
0
    return 'e'
  else:
    #print "Mode of list:", maxitem
    return maxitem

lcase = range(ord('a'), ord('z')+1)
print map(chr, lcase)

inums = []
with open('cipher1.txt', 'r') as f:
    for line in f:
        snums = line.split(',')
        inums.extend(map(int, snums))
        print inums

for key1 in lcase:
    for key2 in lcase:
        for key3 in lcase:
            xorkey = [key1, key2, key3]
            newstring = []
            for i,inum in enumerate(inums):
                newstring.append(chr(inum ^ xorkey[i % 3]))
#            mode = print_mode(newstring)
#            if (mode == 'e'):
            printable = map(lambda x: isprint(x) or (x == '\n'), newstring)
            if (all(printable)):
                mode = print_mode(newstring) 
                if (mode == 'e' or mode == ' ' or mode == 't' or mode == 'a'):
                    print map(chr,xorkey), ''.join(newstring)
                    print 'Sum:', sum(map(ord, newstring))
示例#55
0
文件: main.py 项目: GrIvA/fbless
    def get_utf8_string (self):
        # This method replaces curses getstr in case of utf8
        # encoding.  The problem with original getstr is that
        # it treats multi-byte utf8 character as {2-6} bytes,
        # which leads to the wrong behaviour when handling
        # backspace key.  Backspace key deletes exactly one
        # byte, so user has to press the key 2-6 times.
        # 
        # In this method we analyze if a character starts 
        # a multi-byte, and read the correct number of bytes
        # for the symbol.  We adjust backspace to delete the
        # last utf8 character we read.  We reject any ascii
        # service symbol like ESC, F1, etc, by applying 
        # ascii.isprint.
        
        # FIXME: Is it a valid check for utf-8 encoding?
        assert default_charset == 'UTF-8'
        
        ss = []
        while True:
            c = self.screen.getch ()
            
            # xterm passes backspace hit as curses.KEY_BACKSPACE,
            # other terminals pass it as ascii.BS or ascii.DEL.
            # So here we unify backspace to ascii.BS and 
            # Skip any other service symbol, like F1, KEY_UP, etc
            if c == curses.KEY_BACKSPACE:
                c = ascii.BS
            elif c > 0xff:
                continue

            # In utf8 every multi-byte symbol starts with a byte
            # that encodes the number of symbols. Here is a table:
            #    Bytes     Max value    First byte (binary)
            #      1         0x7f         0xxxxxxx
            #      2         0x7ff        110xxxxx
            #      3         0xffff       1110xxxx
            #      4         0x1fffff     11110xxx
            #      5         0x3ffffff    111110xx
            #      6         0x7fffffff   1111110x
            # 
            # So in essence, the first position of '0' bit if 
            # counting from the left hand side is a number of 
            # bytes in a utf8 multi-char.
            byte_count = 0
            for i in xrange (8):
                if not bool (c & (1 << (7 - i))):
                    byte_count = i;
                    break;

            # Now when we know a number of bytes, we have to call
            # getch() byte_count - 1 times, in order to read the
            # whole character.
            if byte_count > 6 or byte_count == 1:
                raise Exception ("invalid utf8 leading character")

            c = [c]
            if byte_count >= 2:
                for i in xrange (byte_count - 1):
                    c.append (self.screen.getch ())
            
            # Create a string from the list of bytes.
            cc = "".join ([chr (x) for x in  c])

            # String is done, if user hit ENTER.
            if cc == chr (ascii.NL):
                break
            
            # In case of backspace, delete the last character
            # or continue if input is empty.
            if cc in (chr (ascii.DEL), chr (ascii.BS)):
                if len (ss) == 0:
                    continue
                ss.pop () 
                y, x = curses.getsyx ()
                self.screen.move (y, x - 1)
                self.screen.delch ()
                continue

            # Do not save character, if it is something
            # non-printable, like ESC or similar.
            if len (cc) == 1 and not ascii.isprint (ord (cc)):
                continue 
            
            # Append symbol to the list of symbols and put
            # it on the screen.
            ss.append (cc)
            self.screen.addstr (cc)

        # Combine characters from list `ss' into a string
        return "".join (ss)
示例#56
0
    def _needescape(c):
        """
        Return True if character needs escaping, else False.
        """

        return not ascii.isprint(c) or c == '"' or c == '\\' or ascii.isctrl(c)
示例#57
0
文件: find.py 项目: Robopoly/phenny
def printable (str):
    from curses.ascii import isprint
    return ''.join([char for char in str if isprint(char)])