NanoPi NEO3 Plus + HDMIモニタ + コンソール出力

前回まで…

NanoPi NEO3 Plus に HDMI を生やす
やりたいこと3000円くらいの NanoPi NEO3 Plus だって HDMI 出力できるんだ!と証明したい。…本末転倒だけどw せっかくの 48mm 角な小型 SBC が台無しだけど!w結果:できるにはできるけど、制限ありそれでも、こ…

使いたい SBC は NanoPi NEO3 Plus 。
この SBC に HDMI 出力はない。
なので、USB-HDMI アダプタを使って HDMI コネクタを生やす。
Display Link SDK を使って画像や動画を HDMI モニタに出力する。
(Display Link SDK を使えるのは Synaptics 社の Display Link チップを搭載したUSB-HDMIアダプタのみ)

ここまでは普通にOK
(音声は出せないよ)

次はコンソールの出力先にしてみる。

コンソールの出力先にする

ただし、起動時のログが表示される段階ではまだ表示されないので、ラズパイみたいな HDMI モニタの使い方とはならないので注意…とはいえ、それは dmesg 等で確認すればよい、と割り切ろう。

さて、早速、コンソール表示をさせるためのコードは…と行きたいところだったけど、最初にちょっとひと手間かけて横幅を変更しておくと良いかも。

というのも、デフォルトでコンソール(tty1)の横幅が240文字になってる。
今回使いたいモニタは 10.1 インチで、1024 x 600 という解像度なので、フォントサイズを14ptとするとだいぶ右にはみ出て見えなくなる。
なので、半分の120文字程度にしておく。

NanoPi NEO3 Plus あたりは、通常であれば SSH で繋げてあれこれやってると思うので、SSH から tty1 の横幅を変更するには以下の通りに実行する。

$ sudo sh -c 'stty cols 120 < /dev/tty1'

繋げる HDMI モニタのサイズや解像度によっては 120 以外にしたい場合もあると思う。
なので、上記コマンドで調整を何度かすることになると思うけど、値が決まって永続化したい場合は下記のようにすると良い。

$ sudo vi /etc/systemd/system/getty.target.wants/getty@tty1.service

開かれたファイル内の [Service] セクションに以下を追加する。

ExecStartPost=/bin/sh -c '/bin/stty cols 120 < /dev/tty1 || true'

追記が終わったら、設定の反映とサービスの再起動を行う。

$ sudo systemctl daemon-reload
$ sudo systemctl restart getty@tty1.service

んで、以下のコードで例えば dl_console.py といった感じでファイルを作成。

import time
import numpy
from PIL import Image, ImageDraw, ImageFont
import dlsdk
 
width = 1024
height = 600
max_lines = 33
font_size = 14
 
 
 
def read_vcs1_around_cursor() -> str:
    with open("/dev/vcsa1", "rb") as f:
        header = f.read(4)
    rows, cols, _cx, cy = header[0], header[1], header[2], header[3]
 
    with open("/dev/vcs1", "rb") as f:
        raw = f.read().replace(b"\x00", b" ").decode("latin1", errors="replace") 
 
    lines = [raw[i * cols:(i + 1) * cols] for i in range(rows)]
    end_idx = min(len(lines), cy + 1)
    start_idx = max(0, end_idx - max_lines)
    return "\n".join(lines[start_idx:end_idx])
 
 
def init_displaylink(width, height):
 
    print("Initializing DisplayLink...", flush=True)
    status = dlsdk.create_system()
    print("Initialize:", status, flush=True)
    if status != dlsdk.dlsdk_status.DLSDK_SUCCESS:
        return None
 
    devices = dlsdk.get_devices()
    if not devices:
        print("DisplayLink device not found", flush=True)
        return None
 
    displays = devices[0].get_displays()
    if not displays:
        print("Display not found", flush=True)
        return None
 
    display = displays[0]
 
    status, modes = display.modes()
    if status != dlsdk.dlsdk_status.DLSDK_SUCCESS:
        print("Cannot get display modes", flush=True)
        return None
 
    target_mode = None
    for mode in modes:
        w = mode.resolution.width
        h = mode.resolution.height
        hz = mode.refresh_rate_hz
        if w == width and h == height and hz == 60:
            target_mode = mode
            break
 
    if target_mode is None:
        print("Target mode not found", flush=True)
        return None
 
    status = display.power_on(mode=target_mode)
    print("Power ON:", status, flush=True)
    if status != dlsdk.dlsdk_status.DLSDK_SUCCESS:
        print("Failed to set display mode", flush=True)
        return None
 
    print(f"Resolution: {width} x {height}", flush=True)
    return display
 
 
def main():
 
    display = init_displaylink(width, height)
    if display is None:
        raise SystemExit("DisplayLink initialization failed")
 
    font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", font_size)
    bg_template = Image.new("RGB", (width, height), (0, 0, 0))
 
    frame = None
    prev_text = None
 
    pixel_count = width * height
    blank_bytes = b"\x00" * pixel_count
 
    try:
        while True:
            #text_content = read_vcs1_text(cols=80)
            #text_content = read_vcs1_aligned()
            text_content = read_vcs1_around_cursor()
 
            if text_content != prev_text:
                img = bg_template.copy()
                draw = ImageDraw.Draw(img)
                draw.text((20, 30),
                          text_content,
                          font=font,
                          fill=(255, 255, 255))
 
                rgb_bytes = img.tobytes()
                xrgb = bytearray(pixel_count * 4)
                xrgb[0::4] = rgb_bytes[2::3]
                xrgb[1::4] = rgb_bytes[1::3]
                xrgb[2::4] = rgb_bytes[0::3]
                xrgb[3::4] = blank_bytes
 
                frame = numpy.frombuffer(xrgb, dtype=numpy.uint8).reshape((height, width,     4))
                frame = numpy.ascontiguousarray(frame, dtype=numpy.uint8)
                prev_text = text_content
 
                if frame is not None:
                    status = display.show(
                        dlsdk.DLSDK_PIXEL_FORMAT_XRGB,
                        frame
                    )
                    if status != dlsdk.dlsdk_status.DLSDK_SUCCESS:
                        print(f"Dispaly.show() status:", status, flush=True)
 
            time.sleep(0.1)
 
    except Exception as e:
        print(f"Interrupted: {e}", flush=True)
 
 
 
if __name__ == "__main__":
    main()

これを次のように実行すればコンソールが表示される。はず。

(venv)$ ./bin/python dl_console.py

NanoPi NEO3 Plus にキーボードを繋げて打ち込むとちゃんと HDMI モニタその文字が反映されるはず。

こんな感じにね。

上手く表示され、入力もちゃんと反映されたら、いったん CTRL+C で終了させる。

ここまででも、Pythonを実行することで任意でコンソール出力を有効にすることができるようになったので、普段はコンソール表示が不要ならここまででも良いかな。

作ったPythonコードをサービス化して自動起動する

コンソール表示をメインで使いたい場合はサービス化して自動起動するのが便利。

まずはサービスとして起動するための設定ファイルを作成する。

$ sudo vi /etc/systemd/system/dl_console.service

中身は以下のようにする。

[Unit]
Description=Console by Display Link Direct SDK
After=local-fs.target
Wants=local-fs.target
 
[Service]
Type=simple
ExecStart=/home/hoge/[venvName]/bin/python /home/hoge/[venvName]/dl_console.py
WorkingDirectory=/home/hoge/[venvName]
Restart=always
RestartSec=5
 
[Install]
WantedBy=sysinit.target

ファイルを作り終えたら、反映と有効化&起動。

$ sudo systemctl daemon-reload
$ sudo systemctl enable dl_console.service
$ sudo systemctl start dl_console.service

そして、NanoPi NEO3 Plus を再起動。

$ sudo reboot

これでうまくいくはず~

この記事にコメントしてみる