def escape_delimit(s):
    """
    escapes bytes 0x7e, 0x7d, 0x11 (XON), 0x13 (XOFF)
    0x7e and 0x7d will be escaped to 0x7d 0x5e and 0x7d 0x5d
    0x11 and 0x13 will be escaped to 0x7d 0x31 and 0x7d 0x33

    0x7e - packet start/end
    0x7d - escape character. escapes the following byte by inverting bit 5.

    example:
         40 09 00 be ef 05 7d    06 01 02 03 04 05
    becomes:
      7e 40 09 00 be ef 05 7d 5d 06 01 02 03 04 05 7e
    """
    r = []
    r.append(chr(0x7e))
    for c in s:
        cc = ord(c)
        if cc == 0x7d or cc == 0x7e or cc == 0x11 or cc == 0x13:
            r.append(chr(0x7d))
            r.append(chr(cc ^ 32))
        else:
            r.append(c)
    r.append(chr(0x7e))
    return "".join(r)