🐈

【猫監視システムへの道】5.tkinterでSwitchBot制御とカメラビューアを統合

に公開
2026/02/26

この記事で実現したこと

  • 第4回で作ったSwitchBotの制御用GUIに下記の機能を追加する。
    • Tapo C210カメラビューア
    • Pan/Tilt/Zoom機能
    • プライバシーモードのON/OFF機能
    • 静止画の保存機能
    • 動画の保存機能(音アリ)
    • 独自の動体検知機能(簡易的なもの)
    • 動体検知の最終検知時刻を表示
    • 音量バー
    • ログの記録

残件

  • プライバシーモード関連 ※Tapo FW 1.5.x?で廃止
  • Pan/Tilt関連 ※Tapo FW 1.5.x?で廃止
  • 動体検知の性能向上(対象を猫だけにする)

環境

2026年1月30日時点で、Tapo FW 1.5.x?とONVIF PTZ、pytapoの互換性が無くなり、
PTZ操作やプライバシーモードの切り替え操作などができないようです。
Pythonやpytapoのライブラリを最新にしてみても解決していません。

  • Windows11
  • SwitchBot Appのバージョン: 7.3
  • SwitchBot Hub miniのファームウエアバージョン: V6.1-5.4
  • Tapoファームウェア: 1.5.1
  • Python3.13.11(64bit)
  • Pythonのライブラリは下記を参照
pip install ffmpeg-python==0.2.0
pip install opencv-python==4.13.0.90
pip install plyer==2.1.0
pip install pygame==2.6.1
pip install pytapo==3.3.56
pip install requests==2.32.5
pip install rtsp==1.1.12

注意事項

FWアップデートによって、既存のコードが使えなくなる可能性が高いため、
PCからTapoアプリを操作したい場合は、
TapoアプリのアップデートとカメラのFWアップデートをOFFにする事を推奨します。

完成した画面

実際の画面

動画・静止画とも問題なく取得できました!

ディレクトリ構成

├── SmartHome.py            # GUI本体(Tkinter)
├── util/
│   ├── __init__.py         # ディレクトリをパッケージとして認識させる空ファイル
│   ├── motion_detector.py  # 動体検知(簡易版)
│   ├── onvif.py            # ONVIF PTZ
│   ├── sb_command.py       # SwitchBot操作用コマンド
│   ├── switchbot.py        # SwitchBot操作用
│   └── recorder.py         # 録画・録音
├── icon/
│   └── Switchbot.png       # GUIのアイコン
└── sound/
    └── shutter.mp3         # 静止画取得時のサウンド

ソースコード

GUI本体

unit/SmartHome.py
import base64
import datetime
import json
import os
import subprocess
import sys
import time
import threading
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import filedialog, font, scrolledtext
import urllib.request

import cv2
import numpy as np
from PIL import Image, ImageTk
from plyer import notification
#from pytapo import Tapo
import requests
from requests.exceptions import HTTPError, RequestException, Timeout
import rtsp

from util.motion_detector import MotionDetector
#from util.onvif import Onvif
import util.sb_command as sb_cmd
from util.switchbot import SwitchBotController
from util.recoder import Recorder

#==================================
# SwitchBot Hub miniとの接続設定
#==================================
# トークンの取得方法
# (1)SwitchBot Appを起動。
# (2)「プロフィール」の「設定」を開く
# (3)「アプリバージョン」部分を10回タップ。
# (4)「デベロッパーオプション」が表示されるので開く。
# (5)トークンを取得。
TOKEN = ''
API_HOST = 'https://api.switch-bot.com'
DEBIVELIST_URL = f'{API_HOST}/v1.0/devices'
HEADERS = {
    'Authorization': TOKEN,
    'Content-Type': 'application/json; charset=utf8'
}

#==================================
# Tapo C210
#==================================
CAM_USER       = ""                 # 自分の環境に合わせる
CAM_PASS       = ""                 # 自分の環境に合わせる。TapoアプリのPWではなく、カメラ自体のPWを使用する
CAM_ADDR       = ""                 # 自分の環境に合わせる。
CAM_PORT       = "554"
CAM_STREAM     = "stream1"          # stream1は1080p(1920x1080)+音声アリ, stream2は360p(640x360)音声無し
CAM_ONVIF_PORT = "2020"

# パンチルトパラメータ
X_STP = 0.1
Y_STP = 0.1
# カメラの○ボタンで移動する初期位置。-1~1の範囲とする
X_DEFALUT = -0.4
Y_DEFALUT =  0.2

#==================================
# UI設定
#==================================
icon_path = os.path.join('icon', 'Switchbot.png')

# フォント(DSEG v046を使用)
# https://www.keshikan.net/fonts.html
FONT_DIG = 'DSEG14 Classic Mini'

# カメラから画像を取得する際の解像度。
if CAM_STREAM == "stream1":
    FRAME_WIDTH = 1920
    FRAME_HEIGHT = 1080
else:
    FRAME_WIDTH = 640
    FRAME_HEIGHT = 360

# キャンバスのサイズ
CANVAS_WIDTH = 640
CANVAS_HEIGHT = 360

#==================================
# その他
#==================================
# 動画と静止画の保存先フォルダ名
VIDEO_DIR = 'Video'

# キャリブレーションから取得した音量計のオフセット
# スマホアプリの騒音計Decibel Xで28.5dB, Tapoで-61.9dBFSの場合
# 28.5 - (-61.9) = 90.4
DB_OFFSET = 90.4

# PCMの1フレームのサイズ。0.1秒分(16000Hz * 0.1秒)
CHUNK = 1600

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)

        # SwitchBot
        self.sb = SwitchBotController(
            TOKEN,
            API_HOST,
            logger=self._logger
        )
        self.temperature, self.humidity = self.sb.get_meter(sb_cmd.DIC_DIV_ID.get('Meter'))

        # 静止画・動画の保存先
        if not os.path.exists(VIDEO_DIR):
            os.makedirs(VIDEO_DIR)

        # 録画・録音関連
        self.capture_flag = False
        self.record_flag = False
        self.rec_start_time = 0.0
        self.writer = None
        self.audio_fp = None
        self.video_file = None
        self.audio_file = None
        self.recorder = Recorder(
            video_dir=VIDEO_DIR,
            canvas_size=(FRAME_WIDTH, FRAME_HEIGHT),
            logger=self._logger
        )

        # 動体検知
        self.motion = MotionDetector()
        self.last_detected_time = "--:--"
        self.label_detected_time = None

        # Tapo C210をONVIF PTZで操作する
        # Tapo FW 1.5.1では「HTTP Error 400: Bad Request」が返る
        """
        self.onvif = Onvif(
            cam_addr=CAM_ADDR,
            cam_port=CAM_ONVIF_PORT,
            user=CAM_USER,
            password=CAM_PASS,
            logger=self._logger
        )
        """

        #####################################################
        # カメラをオープンする
        #####################################################
        self.rtsp_url = f"rtsp://{CAM_USER}:{CAM_PASS}@{CAM_ADDR}:{CAM_PORT}/{CAM_STREAM}"

        # 映像取得用
        try:
            self.rstp = subprocess.Popen(
                [
                    "ffmpeg",
                    "-rtsp_transport", "tcp",
                    "-i", self.rtsp_url,
                    "-an",                                              # 音声なし
                    "-vf", f"scale={FRAME_WIDTH}:{FRAME_HEIGHT}",       # 出力サイズを固定
                    "-pix_fmt", "rgb24",
                    "-f", "rawvideo",
                    "-"
                ],
                stdout=subprocess.PIPE,
                stderr=subprocess.DEVNULL
            )
            print("RTSPにより、カメラとの接続に成功しました")
        except Exception as e:
            print("カメラとのRTSP接続に失敗しました")
            print(e)
            sys.exit(1)

        # 音声取得用(プログレスバー+録音で共用)
        try:
            self.ffmpeg_audio = subprocess.Popen(
                [
                    "ffmpeg",
                    "-rtsp_transport", "tcp",
                    "-i", self.rtsp_url,
                    "-vn",                     # 映像なし
                    "-acodec", "pcm_s16le",    # 16bit PCM
                    "-ac", "1",                # モノラル
                    "-ar", "16000",            # サンプリングレート
                    "-f", "s16le",             # raw PCM
                    "-"
                ],
                stdout=subprocess.PIPE,
                stderr=subprocess.DEVNULL
            )
            print("RTSPにより、カメラとの接続に成功しました(音声)")
        except Exception as e:
            print("カメラとのRTSP接続に失敗しました(音声)")
            print(e)
            sys.exit(1)

        """
        # プライバシーモード、Pan/Tilt用。
        # 2026年1月30日時点で、pytapoからTapo FW 1.5.1に接続できない
        try:
            self.pytapo = Tapo(CAM_ADDR, CAM_USER, CAM_PASS)
            # 現在のプライバシーモード値
            json_object = self.pytapo.getPrivacyMode()
            p_mode = json_object['enabled']
            print('現在のプライバシーモード値: ' + p_mode)
            print("pytapoがカメラとの接続に成功しました")
        except Exception as e:
            print("pytapoがカメラとの接続に失敗しました")
            print(e)
            sys.exit(1)
        """

        #####################################################
        # GUIのデザイン
        #####################################################
        #==================================
        # Window作成
        #==================================
        self.pack()
        master.title('Smart Home Controller')
        master.geometry('840x600')
        master.resizable(False, False)         # リサイズ不可に設定
        # アイコン設定
        if os.path.exists(icon_path):
            photo = tk.PhotoImage(file=icon_path)
            master.iconphoto(False, photo)

        #==================================
        # Tabを定義
        #==================================
        frame_top = tk.Frame(master, width=840, height=600)
        frame_top.propagate(False)
        frame_top.place(x=0, y=0)

        # タブのインスタンスを作成
        nb = ttk.Notebook(master, width=840, height=545)
        nb.place(x=0, y=40)
        tab1 = tk.Frame(nb)
        tab2 = tk.Frame(nb)
        tab3 = tk.Frame(nb)

        # タブに表示する文字列の設定
        nb.add(tab1, text='リビング', padding=4)
        nb.add(tab2, text='ベッドルーム', padding=4)
        nb.add(tab3, text='log', padding=4)

        #==================================
        # Tab1のFrameを定義
        #==================================
        # tab1
        frame1 = tk.Frame(tab1, width=100, height=95, borderwidth=1, relief='solid', padx=5, pady=3)
        frame2 = tk.Frame(tab1, width=240, height=95, borderwidth=1, relief='solid', padx=5, pady=3)
        frame3 = tk.Frame(tab1, width=170, height=95, borderwidth=1, relief='solid', padx=5, pady=3)
        frame4 = tk.Frame(tab1, width=170, height=95, borderwidth=1, relief='solid', padx=5, pady=3)
        frame5 = tk.Frame(tab1, width=125, height=95, borderwidth=1, relief='solid', padx=5, pady=3)
        frame_camera = tk.Frame(tab1, width=825, height=415, borderwidth=1, relief='solid', padx=5, pady=3)

        # Frameサイズを固定
        frame1.propagate(False)
        frame2.propagate(False)
        frame3.propagate(False)
        frame4.propagate(False)
        frame5.propagate(False)
        frame_camera.propagate(False)

        # Frameを配置
        frame1.place(x=0, y=0)
        frame2.place(x=105, y=0)
        frame3.place(x=350, y=0)
        frame4.place(x=525, y=0)
        frame5.place(x=700, y=0)
        frame_camera.place(x=0, y=100)

        #==================================
        # Tab1のWidget配置
        #==================================
        # frame_top: 日付と時刻(YYYY/MM/DD hh:mm)
        self.label_ta = tk.Label(frame_top, font=('メイリオ', 14, 'bold'))
        self.label_ta.place(x=0, y=0)
        self._update_clock()

        #-----------------------------
        # frame1: 湿温度計の情報を表示
        #-----------------------------
        # 湿温度計のラベル
        label_f1 = tk.Label(frame1, text='湿温度計', font=('メイリオ', 12))
        label_f1.place(x=0, y=0)

        # 温度
        self.label_temperature = tk.Label(
            frame1,
            text=self.temperature,
            fg='green',
            bg='lightgray',
            font=(FONT_DIG, 12)
        )
        self.label_temperature.place(x=10, y=30)

        # 単位:度
        label_temperature_unit = tk.Label(frame1, text='°C', font=('メイリオ', 10))
        label_temperature_unit.place(x=60, y=30)

        # 湿度
        self.label_moisture = tk.Label(
            frame1,
            text=self.humidity,
            fg='green',
            bg='lightgray',
            font=(FONT_DIG, 12)
        )
        self.label_moisture.place(x=10, y=60)
        self._update_meter()

        # 単位:%
        label_moisture_unit = tk.Label(frame1, text='%', font=('メイリオ', 10))
        label_moisture_unit.place(x=60, y=60)

        #-----------------------------
        # frame2: エアコン操作
        #-----------------------------
        # エアコンのラベル
        label_f2 = tk.Label(frame2, text='エアコン', font=('メイリオ', 12))
        label_f2.place(x=0, y=0)

        # ボタン
        button_2a = tk.Button(frame2, text='冷房28度', width='8', command=lambda: self._click_btn_sw('air_cool28'))
        button_2a.place(x=10, y=30)
        button_2b = tk.Button(frame2, text='ドライ', width='8', command=lambda: self._click_btn_sw('air_dry'))
        button_2b.place(x=80, y=30)
        button_2c = tk.Button(frame2, text='暖房25度', width='8', command=lambda: self._click_btn_sw('air_hot25'))
        button_2c.place(x=150, y=30)
        button_2d = tk.Button(frame2, text='OFF', width='8', command=lambda: self._click_btn_sw('air_off'), bg='red')
        button_2d.place(x=10, y=60)

        #-----------------------------
        # frame3: リビングの照明操作
        #-----------------------------
        # リビングのラベル
        label_f3 = tk.Label(frame3, text='照明', font=('メイリオ', 12))
        label_f3.place(x=0, y=0)

        # ボタン
        button_3a = tk.Button(frame3, text='ON', width='8', command=lambda: self._click_btn_sw('light_on'))
        button_3a.place(x=10, y=30)
        button_3b = tk.Button(frame3, text='明るさ▲', width='8', command=lambda: self._click_btn_sw('light_up'))
        button_3b.place(x=80, y=30)
        button_3c = tk.Button(frame3, text='OFF', width='8', command=lambda: self._click_btn_sw('light_off'), bg='red')
        button_3c.place(x=10, y=60)
        button_3d = tk.Button(frame3, text='明るさ▼', width='8', command=lambda: self._click_btn_sw('light_down'))
        button_3d.place(x=80, y=60)

        #-----------------------------
        # frame4: TV操作
        #-----------------------------
        # TVのラベル
        label_f4 = tk.Label(frame4, text='TV', font=('メイリオ', 12))
        label_f4.place(x=0, y=0)

        # ボタン
        button_4a = tk.Button(frame4, text='ON', width='8', command=lambda: self._click_btn_sw('tv_on'))
        button_4a.place(x=10, y=30)
        button_4b = tk.Button(frame4, text='Vol▲', width='8', command=lambda: self._click_btn_sw('tv_vup'))
        button_4b.place(x=80, y=30)
        button_4c = tk.Button(frame4, text='OFF', width='8', command=lambda: self._click_btn_sw('tv_off'), bg='red')
        button_4c.place(x=10, y=60)
        button_4d = tk.Button(frame4, text='Vol▼', width='8', command=lambda: self._click_btn_sw('tv_vdown'))
        button_4d.place(x=80, y=60)

        #-----------------------------
        # frame5: 予備エリア
        #-----------------------------

        #-----------------------------
        # frame_camera: カメラ操作
        #-----------------------------
        # カメラのラベル
        label_f5 = tk.Label(frame_camera, text='カメラ', font=('メイリオ', 12))
        label_f5.place(x=0, y=0)

        # カメラの映像表示
        self.canvas = tk.Canvas(frame_camera, width=640, height=360, bg='white')
        self.canvas.place(x=10, y=30)

        #.......................
        # カメラ操作メニュー
        #.......................
        # 配置のオフセット
        op_offset_x = 350 + 310
        op_offset_y = 0

        # プライバシーモード ON/OFF(TDB)
        # 2026年1月30日時点で、pytapoからTapo FW 1.5.1に接続できない
        self.check_privacy_flag = tk.BooleanVar(value=True)
        check_privacy = tk.Checkbutton(
            frame_camera,
            text="プライバシーモード",
            font=font.Font(family="メイリオ", size=10, overstrike=True),
            variable=self.check_privacy_flag,
            onvalue=True,
            offvalue=False
        )
        check_privacy.place(x=op_offset_x, y=op_offset_y + 30)

        # 動体検知結果 ON/OFF
        self.check_move_flag = tk.BooleanVar(value=True)
        check_move = tk.Checkbutton(
            frame_camera,
            text="動体検知結果(赤)",
            font=font.Font(family="メイリオ", size=10, overstrike=False),
            variable=self.check_move_flag,
            onvalue=True,
            offvalue=False
        )
        check_move.place(x=op_offset_x, y=op_offset_y + 50)

        # 最終検知時刻
        label_last_detected_time = tk.Label(frame_camera, text='最終検知時刻:', font=('メイリオ', 10))
        label_last_detected_time.place(x=op_offset_x + 20, y=op_offset_y + 70)

        self.label_detected_time = tk.Label(frame_camera, text=self.last_detected_time, font=('メイリオ', 10))
        self.label_detected_time.place(x=op_offset_x + 110, y=op_offset_y + 70)

        # 動画取得ボタン
        op_offset_y = 125
        button_recode = tk.Button(frame_camera, text='録画', width='8', command=self._click_cam_rec_btn)
        button_recode.place(x=op_offset_x, y=op_offset_y)

        # 静止画取得ボタン
        button_capture = tk.Button(frame_camera, text='静止画', width='8', command=self._click_cam_cap_btn)
        button_capture.place(x=op_offset_x + 75, y=op_offset_y)

        # Pan/Tiltラベル(TDB)
        # 2026年1月30日時点で、ONVIF PTZがTapo FW 1.5.1で使用できない。pytapoも同様。
        op_offset_y = 160
        label_pt = tk.Label(
            frame_camera,
            text='Pan/Tilt',
            font=font.Font(family="メイリオ", size=10, overstrike=True)
        )
        label_pt.place(x=op_offset_x, y=op_offset_y)

        # Pan/Tiltボタン(TDB)
        # 2026年1月30日時点で、ONVIF PTZがTapo FW 1.5.1で使用できない。pytapoも同様。
        op_offset_y = 180
        button_pt_lt = tk.Button(frame_camera, text='\', width='2', command=lambda: self._click_btn_cam_pan(-1, 1))
        button_pt_lt.place(x=op_offset_x + 10, y=op_offset_y)
        button_pt_mt = tk.Button(frame_camera, text='↑', width='2', command=lambda: self._click_btn_cam_pan(0, 1))
        button_pt_mt.place(x=op_offset_x + 40, y=op_offset_y)
        button_pt_rt = tk.Button(frame_camera, text='/', width='2', command=lambda: self._click_btn_cam_pan(1, 1))
        button_pt_rt.place(x=op_offset_x + 70, y=op_offset_y)

        op_offset_y = 210
        button_pt_lm= tk.Button(frame_camera, text='←', width='2', command=lambda: self._click_btn_cam_pan(-1, 0))
        button_pt_lm.place(x=op_offset_x + 10, y=op_offset_y)
        button_pt_mm = tk.Button(frame_camera, text='+', width='2', command=lambda: self._click_btn_cam_pan(X_DEFALUT, Y_DEFALUT))
        button_pt_mm.place(x=op_offset_x + 40, y=op_offset_y)
        button_pt_rm = tk.Button(frame_camera, text='→', width='2', command=lambda: self._click_btn_cam_pan(1, 0))
        button_pt_rm.place(x=op_offset_x + 70, y=op_offset_y)

        op_offset_y = 240
        button_pt_lb = tk.Button(frame_camera, text='/', width='2', command=lambda: self._click_btn_cam_pan(-1, -1))
        button_pt_lb.place(x=op_offset_x + 10, y=op_offset_y)
        button_pt_mb = tk.Button(frame_camera, text='↓', width='2', command=lambda: self._click_btn_cam_pan(0, -1))
        button_pt_mb.place(x=op_offset_x + 40, y=op_offset_y)
        button_pt_rb = tk.Button(frame_camera, text='\', width='2', command=lambda: self._click_btn_cam_pan(1, -1))
        button_pt_rb.place(x=op_offset_x + 70, y=op_offset_y)

        # Zoomラベル
        op_offset_y = 270
        label_zoom = tk.Label(frame_camera, text='Zoom', font=('メイリオ', 10))
        label_zoom.place(x=op_offset_x, y=op_offset_y)

        # Zoomスライダー
        op_offset_y = 290
        self.zoom_var = tk.DoubleVar()
        scale_zoom = ttk.Scale(
            frame_camera,
            variable=self.zoom_var,
            orient=tk.HORIZONTAL,  # 配置の向き、水平(HORIZONTAL)、垂直(VERTICAL)
            length=100,            # 全体の長さ
            from_=1.0,             # 最小値(開始の値)
            to=4.0                 # 最大値(終了の値)
        )
        scale_zoom.place(x=op_offset_x + 10, y=op_offset_y)

        # 目盛り
        op_offset_y = 310
        label_zoom_1 = tk.Label(frame_camera, text='1', font=('メイリオ', 7))
        label_zoom_1.place(x=op_offset_x + 10, y=op_offset_y)
        label_zoom_2 = tk.Label(frame_camera, text='2', font=('メイリオ', 7))
        label_zoom_2.place(x=op_offset_x + 54, y=op_offset_y)
        label_zoom_4 = tk.Label(frame_camera, text='4', font=('メイリオ', 7))
        label_zoom_4.place(x=op_offset_x + 100, y=op_offset_y)

        # Volumeラベル
        op_offset_y = 340
        label_volume = tk.Label(frame_camera, text='Vol[dB]', font=('メイリオ', 10))
        label_volume.place(x=op_offset_x, y=op_offset_y)

        # ProgressBarで音量表示
        op_offset_y = 360
        self.vol = tk.IntVar()
        bar_vol = ttk.Progressbar(frame_camera, maximum=100, mode="determinate", variable=self.vol)
        bar_vol.place(x=op_offset_x + 10, y=op_offset_y)

        # 目盛り
        op_offset_y = 385
        label_0db = tk.Label(frame_camera, text='0', font=('メイリオ', 7))
        label_0db.place(x=op_offset_x + 10, y=op_offset_y)
        label_50db = tk.Label(frame_camera, text='50', font=('メイリオ', 7))
        label_50db.place(x=op_offset_x + 50, y=op_offset_y)
        label_100db = tk.Label(frame_camera, text='100', font=('メイリオ', 7))
        label_100db.place(x=op_offset_x + 100, y=op_offset_y)

        #==================================
        # Tab2を定義
        #==================================
        # TDB

        #==================================
        # Tab3を定義
        #==================================
        self.text_area = scrolledtext.ScrolledText(
            tab3,
            width=115,
            height=38,
            font=('Source Han Code JP', 10),
        )
        self.text_area.grid(column=0, pady=5, padx=5)
        self.text_area.focus()

        # カメラ映像を表示
        self._disp_image()

        # 音量メーター用スレッドを開始(常時)
        threading.Thread(target=self._audio_thread, daemon=True).start()

    def _disp_image(self):
        """
        カメラから取得した映像の加工~Canvasに表示する。
        """
        #==================================
        # カメラから映像を取得
        #==================================
        no_frame_cnt = 0
        while True:
            in_bytes = self.rstp.stdout.read(FRAME_WIDTH * FRAME_HEIGHT * 3)
            if in_bytes:
                frame = np.frombuffer(in_bytes, np.uint8).reshape([FRAME_HEIGHT, FRAME_WIDTH, 3])
                break

            # 1分間何も取得できなかった場合再接続やカメラの再起動等を入れる(TDB)
            if no_frame_cnt > 15:       # 15fpsなので、1秒間に15枚
                self._logger("1分間frameが取得できませんでした。")
                no_frame_cnt = 0

            no_frame_cnt += 1
            time.sleep(0.05)

        #==================================
        # OpenCV 用(動体検知・録画)に変換
        #==================================
        cv_frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

        #==================================
        # 動体検知
        #==================================
        if not self.check_move_flag.get():
            self.motion.reset()
        else:
            detect = False
            color_blue = (0, 0, 255)       # 枠線の色(青)

            # 動き検知
            rects = self.motion.detect(cv_frame)

            # 検出数が多い場合はカメラのPan/Tilt時とみなして、画面に何も描かない(要調整)
            if 300 > len(rects):
                # 差分があった点を画面に描く
                for (x, y, w, h) in rects:
                    # 小さな変更点と大きな変更点は無視する
                    if 200 > w > 20 and 200 > h > 20:
                        cv2.rectangle(
                            cv_frame,           # 対象の画像
                            (x, y),             # 左上の座標
                            (x + w, y + h),     # 右下の座標
                            (0, 0, 255),        # 線の色。RED
                            2                   # 線の太さ
                        )
                        detect = True

            if detect:
                self._logger("動体を検知しました")

                # 最終検知時刻を更新
                now = datetime.datetime.now().strftime("%H:%M")
                self.last_detected_time = now
                self.label_detected_time.config(text=now)

        #==================================
        # 静止画保存
        #==================================
        if self.capture_flag:
            self.recorder.save_image(cv_frame)
            self.capture_flag = False

        #==================================
        # 動画保存(フレーム書き出し+REC表示)
        #==================================
        if self.record_flag:
            # フレームを書き出し
            self.recorder.write_video(cv_frame)

            # 録画開始からの時間を計測
            rec_time = time.perf_counter() - self.rec_start_time
            rec_timestamp = '{0:02d}:{1:02d}:{2:06.3f}'.format(
                int(rec_time // 3600),
                int(rec_time // 60),
                rec_time % 60
            )

            # putText()で画像に書けるのはASCIIコードのみなので、circle()で赤い丸を描く
            cv2.circle(
                cv_frame,
                (20, FRAME_HEIGHT - 23),    # 位置
                14,                         # サイズ
                (0, 0, 255),                # RED
                -1
            )

            # 表示画像の最下部に「REC」と、録画時間の表示を入れる。(保存時には含めない)
            cv2.putText(
                cv_frame,
                f"REC {rec_timestamp}",
                (36, FRAME_HEIGHT - 12),    # 位置
                cv2.FONT_HERSHEY_SIMPLEX,
                1.0,                        # フォントサイズ
                (0, 0, 255),                # RED
                3,
                cv2.LINE_AA
            )

            # 5分経過したら自動停止
            if rec_time >= 5 * 60:
                self._logger("5分経過したため録画を自動停止します")
                self.recorder.stop()
                self.record_flag = False

        #==================================
        # 表示用にリサイズ。
        #==================================
        # CANVAS_WIDTHとFRAME_WIDTHが異なる場合はリサイズ
        if CANVAS_WIDTH != FRAME_WIDTH:
            cv_frame = cv2.resize(cv_frame, (CANVAS_WIDTH, CANVAS_HEIGHT), interpolation=cv2.INTER_LINEAR )

        # 設定を取得
        if self.zoom_var.get() == 0:
            zoom = 1
        else:
            zoom = self.zoom_var.get()

        # キャンバスのサイズを基準として、zoom倍率をかけた大きさに画像をリサイズ。
        # Windows作成時に一瞬だけself.zoom_var.get()=0になる瞬間がある。
        if zoom != 1:
            h, w = cv_frame.shape[:2]
            new_w = int(w * zoom)
            new_h = int(h * zoom)

            # 中央からズーム
            cv_frame = cv2.resize(cv_frame, (new_w, new_h), interpolation=cv2.INTER_LINEAR)

            # 中央を切り出してキャンバスサイズに戻す
            x1 = (new_w - CANVAS_WIDTH) // 2
            y1 = (new_h - CANVAS_HEIGHT) // 2
            cv_frame = cv_frame[y1:y1 + CANVAS_HEIGHT, x1:x1 + CANVAS_WIDTH]

        #==================================
        # キャンバスに描画するためPhotoImageに変換
        #==================================
        disp_frame = cv2.cvtColor(cv_frame, cv2.COLOR_BGR2RGB)
        pil_image = Image.fromarray(disp_frame)
        self.photo_image = ImageTk.PhotoImage(image=pil_image)

        # 画像の描画
        self.canvas.delete("all")
        self.canvas.create_image(
            CANVAS_WIDTH / 2,           # 画像表示位置(Canvasの中心)
            CANVAS_HEIGHT / 2,
            image=self.photo_image      # 表示画像データ
        )

        # _disp_image()を10msごとに実行
        self.after(10, self._disp_image)

    def _click_btn_sw(self, key=None):
        """
        SwitchBot操作用のボタン押下時の動作
        """
        self._logger('push {} botton'.format(key))

        device_id = sb_cmd.DIC_CMD.get(key)[0]
        params = sb_cmd.DIC_CMD.get(key)[1]
        self.sb.post_request(device_id, params)

    def _click_btn_cam_pan(self, x, y):
        """
        Pan/Tiltボタン押下時の動作
        x, y は -1, 0, 1 の方向
        Tapo C210 は速度値が小さいと無視されるため 0.3 以上を推奨
        """
        step = 0.4
        # xml = self.onvif.build_relative_move_xml(x * step, y * step)
        # self.onvif.send_onvif(xml)

    def _click_cam_cap_btn(self):
        """
        静止画取得ボタン押下時
        """
        self.capture_flag = True

    def _click_cam_rec_btn(self):
        """
        録画ボタン押下時
        """
        if not self.record_flag:
            self.recorder.start()
            self.record_flag = True
            self.rec_start_time = time.perf_counter()
        else:
            self.recorder.stop()
            self.record_flag = False

    def _audio_thread(self):
        """
        音声スレッド:
        - 常にRTSP音声を読み取り、音量を計算してプログレスバーを更新
        - 録画中のみ、同じストリームからPCMをファイルに書き出す
        """
        while True:
            data = self.ffmpeg_audio.stdout.read(CHUNK * 2)
            if not data:
                continue

            # 音量メーター処理
            self.db = self._pcm_to_db(data)

            # Tkinterの更新はメインスレッドで
            root.after(0, self.vol.set, self.db)

            # 録画中ならファイルに書き込む
            if self.record_flag:
                self.recorder.write_audio(data)

    def _pcm_to_db(self, pcm):
        """
        PCM16 の numpy 配列を dBFS に変換し、
        キャリブレーション済みの「騒音計風 dB」を返す。
        """
        try:
            audio = np.frombuffer(pcm, dtype=np.int16)
        except Exception:
            return -90

        if len(audio) == 0:
            return -90

        # 正規化
        norm = np.abs(audio).astype(np.float64) / 32768.0

        # 異常値(NaN, Inf)を除去
        norm = np.nan_to_num(norm, nan=0.0, posinf=1.0, neginf=0.0)

        # 絶対に負の値が入らないようにクリップ
        safe = np.clip(norm + 1e-6, 1e-12, None)

        # dBFS計算
        ln_val = np.log(safe)
        dbfs_arr = 20 * ln_val / np.log(10)

        # 異常値を除去
        dbfs_arr = np.nan_to_num(dbfs_arr, nan=-120.0, posinf=0.0, neginf=-120.0)
        # 平均値
        dbfs = float(np.mean(dbfs_arr))

        if np.isnan(dbfs) or np.isinf(dbfs):
            return -90

        # キャリブレーション済のDB_OFFSETを加算
        db = int(dbfs + DB_OFFSET)

        return db

    def _logger(self, text='', level='INFO'):
        """
        ログをLogタブとログファイルに出力する
        """
        dt = datetime.datetime.now()
        date = dt.strftime('%Y/%m/%d %H:%M:%S')
        line = f'[{date}][{level:<7}] {text}'

        # GUIに出力
        # ただし、text_area がまだ無い場合は print に逃がす
        if hasattr(self, "text_area") and self.text_area is not None:
            self.text_area.insert(tk.END, line + '\n')
            self.text_area.see(tk.END)
        else:
            print(line)

        # ファイルに出力
        log_path = "log.txt"

        try:
            with open(log_path, "a", encoding="utf-8") as f:
                f.write(line + "\n")
        except Exception as e:
            print(f"Log write error: {e}")

        # サイズ制御(10KB 超えたら古い行から削除)
        try:
            if os.path.exists(log_path) and os.path.getsize(log_path) > 10 * 1024:
                with open(log_path, "r", encoding="utf-8") as f:
                    lines = f.readlines()

                # 古い行から削除(半分にする)
                keep = lines[len(lines)//2:]

                with open(log_path, "w", encoding="utf-8") as f:
                    f.writelines(keep)

                # ログに記録
                print("log.txt trimmed (size > 10KB)")
        except Exception as e:
            print(f"Log trim error: {e}")

    def _update_clock(self):
        '''
        日付と時刻を1秒ごとに更新する
        表記は YYYY/MM/DD hh:mm:ss
        '''
        now = datetime.datetime.now().strftime('%Y/%m/%d(%a) %H:%M:%S')
        self.label_ta.config(text=now)
        self.after(1000, self._update_clock)

    def _update_meter(self):
        '''
        湿温度計を5分ごとに更新する
        '''
        device_id = sb_cmd.DIC_DIV_ID.get('Meter')
        temp, hum = self.sb.get_meter(device_id)

        if temp is not None:
            self.label_temperature.config(text=temp)
        if hum is not None:
            self.label_moisture.config(text=hum)

        self.after(5 * 60 * 1000, self._update_meter)

if __name__ == "__main__":
    root = tk.Tk()
    app = Application(master=root)
    app.mainloop()

動体検知

簡易版です。
将来的には機械学習で猫だけを検出したいです。
参考サイト:

unit/motion_detector.py
import cv2
import numpy as np

class MotionDetector:
    def __init__(self, blur_size=(21, 21), threshold=25):
        self.avg = None                 # 前フレームを保存用
        self.blur_size = blur_size
        self.threshold = threshold      # 二値化の閾値(要調整)


    def reset(self):
        """
        動体検知の平均フレームをリセット
        """
        self.avg = None


    def detect(self, frame):
        """
        動きを検知し、動いた領域の矩形リストを返す
        frame: BGR (OpenCV frame)
        return: [(x, y, w, h), ...]
        """

        # 白黒画像に変換
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        gray = cv2.GaussianBlur(gray, self.blur_size, 0)

        # 初回は平均フレームを作るだけ
        if self.avg is None:
            self.avg = gray.copy().astype("float")
            return []

        # 現在のフレームと移動平均との差を計算
        cv2.accumulateWeighted(gray, self.avg, 0.5)
        frame_delta = cv2.absdiff(gray, cv2.convertScaleAbs(self.avg))

        # frameDeltaの画像を二値化
        # 閾値が小さすぎると誤検知が増え、大きすぎると検知機能が低下する。
        thresh = cv2.threshold(frame_delta, self.threshold, 255, cv2.THRESH_BINARY)[1]
        thresh = cv2.dilate(thresh, None, iterations=2)

        # 輪郭抽出
        contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        # フォーマットを変更
        rects = []
        for c in contours:
            x, y, w, h = cv2.boundingRect(c)
            rects.append((x, y, w, h))

        return rects

ONVIF PTZ

onvif.pyは、記事3をベースにしたファイルですが、
Tapo FW 1.5.1ではBad Requestが返ってまともに使えないため省略。

SwitchBot操作用

sb_command.pyは記事2と共通のため省略。

unit/switchbot.py
import requests
import json
from requests.exceptions import HTTPError, RequestException, Timeout

class SwitchBotController:
    def __init__(self, token, api_host, logger=None):
        self.token = token
        self.api_host = api_host
        self.logger = logger or (lambda msg: None)

        self.headers = {
            'Authorization': token,
            'Content-Type': 'application/json; charset=utf8'
        }

    def _log(self, msg, level="INFO"):
        """
        GUIのLogタブにログを渡す
        """
        if self.logger:
            self.logger(msg, level)

    def _get_device_status(self, device_id):
        """
        Switchbotデバイスのステータスを取得する。
        """
        url = f"{self.api_host}/v1.0/devices/{device_id}/status"
        try:
            r = requests.get(url, headers=self.headers)
            r.raise_for_status()
            body = r.json()["body"]
            # self._log(f"SwitchBot: status {device_id} → OK")
            return body
        except Timeout:
            self._log(f"SwitchBot timeout error: ", 'ERROR')
        except Exception as e:
            self._log(f"SwitchBot error: {e}", 'ERROR')
            raise

    def get_meter(self, device_id):
        """
        湿温度計の温度・湿度を取得して返す
        """
        try:
            status = self._get_device_status(device_id)
            temp = '{0:4.1f}'.format(status.get('temperature'))
            hum  = '{0:4.1f}'.format(status.get('humidity'))
            self._log(f"SwitchBot Thermo-hygrometer OK: {temp}°C {hum}%")
            return temp, hum
        except Exception as e:
            self._log(f"SwitchBot Thermo-hygrometer error: {e}")
            return None, None

    def post_request(self, device_id, params):
        '''
        デバイスに指示を出す。
        '''
        url = f"{self.api_host}/v1.0/devices/{device_id}/commands"
        try:
            res = requests.post(url, data=json.dumps(params), headers=self.headers)
            data = res.json()
            if data['message'] == 'success':
                self._log(f"SwitchBot Command OK")
            elif data['message'] == 'device offline':
                self._log(f"SwitchBot Command NG. デバイス {device_id} はオフラインです")
            else:
                self._log(f"SwitchBot error: {data}", 'ERROR')
            return data
        except Timeout:
            self._log(f"SwitchBot timeout error: ", 'ERROR')
        except Exception as e:
            self._log(f"SwitchBot error: {e}", 'ERROR')
            raise

録画・録音用

unit/recorder.py
import datetime
import os
import subprocess
import wave

import cv2
from pygame import mixer

# 静止画取得時のサウンド
mixer.init()
SHUTTER_SOUND = mixer.Sound(os.path.join('../', 'sound', 'shutter.mp3'))

class Recorder:
    def __init__(self, video_dir="Video", canvas_size=(640, 360), logger=None):
        self.video_dir = video_dir
        # 音無しの動画ファイル名
        self.video_file_temp = os.path.join(self.video_dir, f"Video_temp.mp4")
        self.canvas_size = canvas_size
        self.logger = logger or (lambda msg: None)  # デフォルトは何もしない

        os.makedirs(video_dir, exist_ok=True)

        self.recording = False
        self.video_writer = None
        self.audio_fp = None

        self.video_file = None
        self.audio_file = None


    def _log(self, msg, level="INFO"):
        """
        GUIのLogタブにログを渡す
        """
        if self.logger:
            self.logger(msg, level)

    def start(self):
        """
        録画開始
        """
        if self.recording:
            return

        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")

        self.video_file = os.path.join(self.video_dir, f"Video_{timestamp}.mp4")
        self.audio_file = os.path.join(self.video_dir, f"Audio_{timestamp}.raw")

        fourcc = cv2.VideoWriter_fourcc(*"mp4v")
        self.video_writer = cv2.VideoWriter(
            self.video_file_temp,
            fourcc,
            15.0,
            self.canvas_size
        )

        self.audio_fp = open(self.audio_file, "wb")

        self.recording = True
        self._log("Recorder: 録画開始")

    def stop(self):
        """
        録画終了
        """
        if not self.recording:
            return

        self.recording = False

        if self.video_writer:
            self.video_writer.release()
            self.video_writer = None

        if self.audio_fp:
            self.audio_fp.close()
            self.audio_fp = None

        # raw→wav変換
        wav_file = self.audio_file.replace(".raw", ".wav")
        self._raw_to_wav(self.audio_file, wav_file)

        # 音声と動画を結合
        self._merge_audio_video(self.video_file_temp, wav_file, self.video_file)

        self._log(f"Recorder: 録画終了 {self.video_file}")

    def write_video(self, frame):
        """
        動画ファイル書き出し
        """
        if self.recording and self.video_writer:
            self.video_writer.write(frame)

    def write_audio(self, pcm_bytes):
        """
        音声ファイル書き出し
        """
        if self.recording and self.audio_fp:
            self.audio_fp.write(pcm_bytes)

    def save_image(self, frame):
        """
        静止画を保存する
        """
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = os.path.join(self.video_dir, f"ScreenShot_{timestamp}.png")
        cv2.imwrite(filename, frame)
        self._log(f"Recorder: 静止画保存 {filename}")

        # シャッター音
        SHUTTER_SOUND.play()

    def _raw_to_wav(self, raw_path, wav_path):
        """
        RawファイルをWavファイルに変換する
        """
        with open(raw_path, "rb") as raw:
            pcm = raw.read()

        with wave.open(wav_path, "wb") as w:
            w.setnchannels(1)
            w.setsampwidth(2)
            w.setframerate(16000)
            w.writeframes(pcm)

        # Rawファイルを削除
        os.remove(raw_path)

    def _merge_audio_video(self, video_file, audio_file, output_file):
        """
        音声ファイルと動画ファイルを結合する
        結合前のファイルは削除する。
        """
        subprocess.run(
            [
                "ffmpeg",
                "-i", video_file,
                "-i", audio_file,
                "-c:v", "copy",
                "-c:a", "aac",
                "-shortest",
                output_file
            ],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL
        )

        # 合成前のファイルを削除
        os.remove(video_file)
        os.remove(audio_file)

最後に

実はこのビューア、2023年時点である程度まで形になっていました。
フリーズ問題の修正や、記事を書くのが面倒で放置していたら、
FWが更新されて実装済機能が使えなくなりました💦
いつかまた使える日が来ると期待して、GUI上に残しています。

Discussion