view tests/cp_ping.py @ 1:f7c60e525801

cptest and cp_ping.py to test cmd_proto.c.
author Thinker K.F. Li <thinker@branda.to>
date Sat, 21 Feb 2009 20:20:06 +0800
parents
children e410832c3280
line wrap: on
line source

import struct

CP_CMD_PING = 1
CP_CMD_PONG = 2

def csum_add(csum, c):
    return (((csum << 3) | (csum >> 5)) ^ c) & 0xff

def cp_ping(seq, data):
    csum = 0
    csum = csum_add(0, CP_CMD_PING)
    for c in data:
        csum = csum_add(csum, ord(c))
        pass
    csum = csum_add(csum, 0)
    
    cmd_str = struct.pack('BBBBB', ord('J'), ord('C'), seq,
                          len(data) + 1, CP_CMD_PING)
    cmd_str = cmd_str + data + chr(csum)
    return cmd_str

def get_reply(fo):
    import fcntl, os
    import time
    
    reply = ''
    fcntl.fcntl(fo.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
    while True:
        try:
            s = os.read(fo.fileno(), 256)
        except OSError:
            time.sleep(0.5)
            try:
                s = os.read(fo.fileno(), 256)
            except OSError:
                break
            pass
        reply = reply + s
        pass
    return reply

if __name__ == '__main__':
    import sys

    if len(sys.argv) != 2:
        print >> sys.stderr, 'Usage: prog <port device>'
        sys.exit(1)
        pass
    
    port = sys.argv[1]
    
    fo = open(port, 'r+b')
    cmd_str = cp_ping(0, 'hello')
    fo.write(cmd_str)
    fo.flush()
    
    reply = get_reply(fo)
    print repr(reply)
    pass