Newer
Older
stm32 / bin / swoproxy.py
#!/usr/bin/env python3
# -*- coding : UTF-8 -*-

# @file swoproxy.py
# @brief J-Link GDB ServerのSWOサービスポートに接続し標準出力へ垂れ流す
# @details 終了はCtrl-Cで行う。
# GDB Serverが動作していなくてもこのスクリプトは動き続けて、GDB Serverが
# 起動したらconnectしに行く。
# connectしている状態でGDB Serverが終了した場合は、再度待ち状態に入る。
#
# つまりは、このスクリプトを立ち上げっぱなしにしておけば、Eclipseなどの
# デバッガ上でデバッグ実行したときにSWOからの出力文字を表示できる。
# 
# 使用許諾は The MIT License です。
# 参照 https://opensource.org/licenses/mit-license.php
# @copyright
# Copyright (c) 2020 molelord
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

# 参考にしたサイト
# https://qiita.com/keiusukematsuda/items/362450fda4beca76c030
# https://docs.python.org/ja/3/library/exceptions.html
# http://adastra-soft.com/poor-man-arm-cortex-m-swo/

import socket

# for time.sleep()
import time

target_ip   = "localhost"
buffer_size = 4096

# J-Link GDB ServerのSWO portのデフォルト
target_port = 2332

while True:
    try:
        tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        tcp_client.connect((target_ip, target_port))

        while True:
            response = tcp_client.recv(buffer_size)

            count = 0
            # データ形式は
            # http://adastra-soft.com/poor-man-arm-cortex-m-swo/
            # のSWIT packetになっているはず
            swit_byte0 = True
            for i in response:
                if swit_byte0:
                    swit_byte0 = False
                    payload_size = i & 0x03;
                    if (payload_size == 0x3):
                        payload_size = 4
                    continue

                if payload_size > 0:
                    # テキトウにflushしつつ文字を出力
                    count += 1
                    print(chr(i), end='', flush=(count & 0xF))

                    payload_size -= 1
                    if payload_size == 0:
                        swit_byte0 = True

    except ConnectionError as ex:
        tcp_client.close()
        time.sleep(1)