Выключение Intel NUC HTPC на холостом ходу

Я использую HTPC на Intel Nuc под управлением Xenial. Когда я нажимаю кнопку питания, он запускает powerbtn.sh, который инициирует выключение, но моя малина может разбудить его, как я хочу.

Вопрос в том, как мне заставить Ubuntu запускать это в режиме ожидания в течение 5 минут. Я обеспокоен двумя факторами, что MythTV и ssh не должны служить в течение этого 10-минутного периода.

Я думаю, что мог бы заблокировать SSH, используя приведенное здесь решение. Предотвращение перехода компьютера в спящий режим при подключениях SSH

Я считаю, что MythTV должна автоматически учитываться ОС.

Но как мне собрать все это воедино и заставить его работать?

Спасибо за ваше время!

РЕДАКТИРОВАТЬ: После долгих размышлений я придумал это скрипт, который я планирую запускать на cron каждые 15 минут. Любые предложения будут с благодарностью

#!/bin/bash

#check for SSH sessions, and prevent suspending:
if [ "$(who | grep -cv "(:")" -gt 1 ]; then
    echo "SSH session(s) are on. Not suspending."
    exit 1
fi

#check for MythTV sessions, and preventing suspending:
if [ "$(netstat -tun | grep :6543 | grep -i established | wc -l)" -gt 0 ]; then
    echo "MythTV  is still streaming. Not suspending."
    exit 1
fi

sleep 5m

#check for SSH sessions, and prevent suspending:
if [ "$(who | grep -cv "(:")" -gt 1 ]; then
    echo "SSH session(s) are on. Not suspending."
    exit 1
fi

#check for MythTV sessions, and preventing suspending:
if [ "$(netstat -tun | grep :6543 | grep -i established | wc -l)" -gt 0 ]; then
    echo "MythTV  is still streaming. Not suspending."
    exit 1
fi

echo "Safe to shutdown from MythTV and SSH"
/etc/acpi/powerbtn.sh
2
задан 15 January 2018 в 04:27

1 ответ

Я не смог заставить работать системные события MythTV. Попробовал мою лучшую игру с разрешениями все напрасно. Вот мой текущий рабочий код. Замените переменные базы данных вашими настройками. Сохраните его, как, скажем, /etc/cron.daily/idle_htpc.py. Если какой-либо шаг завершится неудачно, программа закроется. Просто sudo crontab -e это за каждые 5-59/15 * * * * /etc/cron.daily/idle_htpc.py /var/log/htpc_out 2> /var/log/htpc_err 15 минут

Шаг 1: посмотрите, есть ли какие-либо SSH-соединения

Шаг 2: Проверьте, воспроизводится ли в данный момент живое или записанное видео. Если не спите в течение 5 минут

Шаг 3: еще раз проверьте, воспроизводится ли в данный момент живое или записанное видео

Шаг 4: Проверьте, был ли прямой эфир в течение последних 5 минут только в В этом случае сценарий продолжался менее 5 минут, пока сценарий находился в спящем режиме на шаге 2. Однако, если было записано воспроизведение, здесь нет средств для обнаружения.

Шаг 5: Проверьте следующую предстоящую запись, и если она есть, и она> 5 минут, установите активацию ACPI за 3 минуты до времени запуска и выключения, или отмените активацию и отключение ACPI.

Надеюсь, это кому-нибудь поможет.

#!/usr/bin/python3

import pymysql
import pymysql.cursors
from datetime import timedelta,datetime
import subprocess
import time
import sys

print ( datetime.now().strftime("%Y-%m-%d %H:%M:%S"), file=sys.stdout)

def check_Logins():
    #Returns the number of SSH connections
    #result= subprocess.run('who | grep -cv "(:"', stdout=subprocess.PIPE, shell=True)
    result= subprocess.run("netstat -n |grep tcp |grep ':22' |wc -l", stdout=subprocess.PIPE, shell=True)
    print ('Logins:'+result.stdout.decode('UTF-8'), file=sys.stdout)
    return (int(result.stdout.decode('UTF-8')))

def check_if_InUse():
    #Checks if a live stream or a previosuly recorded program is being served at this moment. If yes, non zero value is returned
    InUse=1
    connection = pymysql.connect(host=$host,
                             user=$username,
                             password=$password,
                             db=$db,
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

    try:
        with connection.cursor() as cursor:
            # Read a single record
            sql = "select count(*) from inuseprograms where recusage !='jobqueue' and recusage !='flagger'"
            cursor.execute(sql)
            result = cursor.fetchone()
            InUse = result["count(*)"]
    finally:
        connection.close()
    print ("Count: "+str(InUse), file=sys.stdout)
    return InUse

def check_live_5min():
    #Checks if there were any live streams served in last 5 minutes
    RecInUse_5min=1
    connection = pymysql.connect(host=$host,
                             user=$username,
                             password=$password,
                             db=$db,
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

    try:
        with connection.cursor() as cursor:
            # Read a single record
            sql = "select max(starttime) from recordedseek"
            cursor.execute(sql)
            result = cursor.fetchone()
            print ('Recent: ', result['max(starttime)'], file=sys.stdout)
            print ('Current: ',datetime.utcnow(), file=sys.stdout)
            if datetime.utcnow()-result['max(starttime)']>=timedelta(minutes=5):
                RecInUse_5min =0
    finally:
        connection.close()
    return RecInUse_5min

def get_next_rec():
    #Returns a tuple indicating if there is any scheduled recording if yes, how far into the future
    retdata = (True, timedelta(minutes=1))
    connection = pymysql.connect(host=$host,
                             user=$username,
                             password=$password,
                             db=$db,
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

    try:
        with connection.cursor() as cursor:
            # Read a single record
            sql = "select MIN(next_record) from record where recordid!=1 and next_record IS NOT NULL;"
            cursor.execute(sql)
            result = cursor.fetchone()
            if result['MIN(next_record)'] is None: #no scheduled recordings
                retdata= (False,timedelta(minutes=1))
            else:
                retdata= (True,result['MIN(next_record)']-datetime.utcnow())
    finally:
       connection.close()
    return retdata

if check_Logins()==0:
    print ('First check passed', file=sys.stdout)

    if check_if_InUse() == 0:
        print ('Second check passed', file=sys.stdout)
        time.sleep(5*60)

        if check_if_InUse() == 0:
            print ('Third check passed', file=sys.stdout)
            if check_live_5min()==0:
                print ('Fourth check passed', file=sys.stdout)
                (valid,upcoming) = get_next_rec()

                # Clear any previously set wakeup time 
                result = subprocess.run('echo 0 > /sys/class/rtc/rtc0/wakealarm',stdout=subprocess.PIPE,shell=True)
                print ('Clear:'+result.stdout.decode('UTF-8'), file=sys.stdout)

                if valid is True:
                    # Generate wakeup time string
                    upcoming = upcoming - timedelta(minutes=3)
                    wakeup_string="'+"+str(upcoming.days)+" days + "+str(max([int(upcoming.seconds/60)-3,0]))+" minutes'"
                    print ('Setting for '+wakeup_string, file=sys.stdout)
                    wakeup_command="echo `date '+%s' -d " +wakeup_string+ "` > /sys/class/rtc/rtc0/wakealarm"
                    #Setup wakeup time
                    result = subprocess.run(wakeup_command,stderr=subprocess.PIPE, shell=True)
                    print ('Set:'+result.stderr.decode('UTF-8'), file=sys.stdout)
                    #Check if alarm is set. It should show the unix time stamp
                    result= subprocess.run('cat /sys/class/rtc/rtc0/wakealarm', stdout=subprocess.PIPE, shell=True)
                    print ('Check:'+result.stdout.decode('UTF-8'), file=sys.stdout)

                print ('Shutting down', file=sys.stdout)
                subprocess.Popen(['/sbin/shutdown', '-h', 'now'])
0
ответ дан 15 January 2018 в 04:27

Другие вопросы по тегам:

Похожие вопросы: