PythonのPyserialでインタラクティブなシリアルコンソールを実装する

CooltermとかZtermとかあるけど、Pythonでやりたかったので。
これでRaspberry piのターミナルからArduinoをコントロールできる。
https://github.com/shohei/avr_parrot_echo

ポイントとしては、
(1)マルチスレッドを実装する。キーボード中断が入った時の処理としてスレッドをキルしないと、プログラムが終わらない。
(2)raw_inputの後ろに改行コードを付けて送る。付けないとprint data, したときに、即時に標準出力に出ない。
(3)sys.stdout.write()を使うと綺麗に表示される。print data,だと全角文字っぽく表示されてしまった。
(4)ArduinoのSerial.available()的な感じで、通信が安定するまで待たないといけない。
参考:マルチスレッドのキル http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python

sp.py

import serial
import threading
import sys
import commands

try:
    status, output = commands.getstatusoutput("ls /dev/tty.usb*")
    dev_port = output
    s = serial.Serial(port=dev_port,baudrate=9600)
except:
    print "No usb device found."
    exit()

def thread2():
    while True:
        data = s.read()
        sys.stdout.write(data)

t2 = threading.Thread(target=thread2)
t2.start()

print "Press <Enter> to exit."
print "Wait a moment for initializing......"
while(True):
    try:
        key = raw_input()
        if(key==""):
            t2._Thread__stop()
            exit()
        key += "\n"
        s.write(key)
    except:
        print "\nstop thread2"
        t2._Thread__stop()
        exit()

AVR側

/* Name: main.c
 * Author: <insert your name here>
 * Copyright: <insert your copyright message here>
 * License: <insert your license reference here>
 */

#include <avr/io.h>
#include <util/delay.h>
#include "usart.h"
#include <avr/interrupt.h>

ISR(USART_RX_vect)
{
    char data = Usart::USART_recv(); //UDRバッファを読み出さないとここが無限ループになる。USART_RXCの仕様か。
    Usart::USART_Transmit(data);
}

int main(void)
{
    int ubrr = Usart::getUBRR(9600);
    Usart::USART_init(ubrr);
    sei();
    Usart::putString("Initializing success.\n");//Stabilize serial communication:通信準備完了

    for(;;){
    }
    return 0;   /* never reached */
}