首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Intel NUC HTPC怠速关机

Intel NUC HTPC怠速关机
EN

Ask Ubuntu用户
提问于 2018-01-14 22:45:13
回答 1查看 192关注 0票数 2

我正在运行英特尔Nuc上的HTPC,运行Xenial。当我按下电源按钮时,它会运行powerbtn.sh,这会启动关机,但我的覆盆子能够唤醒它,正如我所希望的那样。

问题是,在空闲5分钟时,如何使ubuntu运行。我关心的两个因素是,MythTV和ssh不应该在10分钟内服务。

我想我可以用这里的解决方案当SSH连接打开时,防止机器休眠阻止SSH

我认为操作系统应该自动考虑到MythTV。

但我该如何把所有这些都放在一起,让它发挥作用呢?

谢谢您抽时间见我!

编辑:经过深思熟虑,我想出了这个脚本,我计划每15分钟在cron上运行一次。如有任何建议,将不胜感激。

代码语言:javascript
复制
#!/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
EN

回答 1

Ask Ubuntu用户

发布于 2018-01-17 22:38:43

我无法让MythTV系统事件工作。我尽了最大的努力利用权限,但都徒劳无功。这是我目前的工作代码。用设置替换数据库变量。如果有任何步骤失败程序将退出,请将其保存为/etc/cron.daily/idle_htpc.py。每隔15分钟sudo crontab -e一次

步骤1:查看是否有SSH连接

第二步:检查是否正在播放现场或录制的视频。如果不睡5分钟

第三步:再次检查是否正在播放现场或录制的视频

步骤4:检查在最后5分钟内是否有一个活动流,以防脚本在第2步休眠时有一个5分钟以下的流。但是,如果有记录的回放,这里就无法检测到。

第5步:检查下一个即将到来的录音,如果有,并且是>5分钟以后,设置ACPI唤醒,3分钟前开始和关闭,否则清除ACPI唤醒和关闭。

希望这能帮上忙。

代码语言:javascript
复制
#!/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
EN
页面原文内容由Ask Ubuntu提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://askubuntu.com/questions/995938

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档