Press "Enter" to skip to content

python脚本监控家里电视是否开机及开机时常

家里小朋友放学会自己打开电视看,需要控制小朋友看电视时常,写一个脚本来进行监控。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import subprocess
import time
import requests

def ping_ip(ip):
    try:
        response = subprocess.run(['ping', '-c', '1', ip], stdout=subprocess.PIPE)
        return response.returncode == 0
    except Exception as e:
        print(f"Error pinging {ip}: {e}")
        return False

def call_api(url, data):
    try:
        response = requests.post(url, json=data)
        print(f"API response: {response.status_code}, {response.text}")
    except Exception as e:
        print(f"Error calling API: {e}")

def format_duration(seconds):
    hours = seconds // 3600
    minutes = (seconds % 3600) // 60
    return f"{hours}小时{minutes}分钟"

# 电视机的ip
ip_address = "192.168.1.200"
api_url = "https://wechat.alert.url/send_message"

ip_alive = False
start_time = None

while True:
    is_up = ping_ip(ip_address)
    if is_up and not ip_alive:
        ip_alive = True
        start_time = time.time()
        call_api(api_url, {"userid": "wechatpin", "message": "电视开机了"})
    elif not is_up and ip_alive:
        ip_alive = False
        end_time = time.time()
        alive_duration = format_duration(int(end_time - start_time))
        message = f"电视关机了,开机时常{alive_duration}"
        call_api(api_url, {"userid": "wechatpin", "message": message})
        start_time = None
    time.sleep(60)

容器化部署,Dockerfile文件:

# 使用官方 Python 基础镜像
FROM python:3.9-slim

# 安装 ping 命令
RUN apt-get update && \
    apt-get install -y iputils-ping && \
    rm -rf /var/lib/apt/lists/*

# 设置工作目录
WORKDIR /app

# 将 Python 脚本复制到容器内
COPY main.py .

# 安装所需的 Python 依赖
RUN pip install --no-cache-dir requests

# 当容器启动时运行脚本
CMD ["python", "./main.py"]

家里路由器给了电视固定的IP地址,脚本逻辑是每分钟ping电视ip,如果发现能ping通,发消息通知并且开始计时,如果发现电视关机了,汇总开机时长并且报告。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注