AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / ubuntu / Perguntas / 992699
Accepted
umpirsky
umpirsky
Asked: 2018-01-06 10:10:51 +0800 CST2018-01-06 10:10:51 +0800 CST 2018-01-06 10:10:51 +0800 CST

Executar comando quando inativo/ativo

  • 772

Eu preciso executar o comando personalizado quando:

  1. O computador está ocioso por X minutos (nenhuma tecla pressionada)
  2. Tecla pressionada

O que eu quero alcançar, na verdade, é o recurso de economia de energia para o meu teclado.

Eu quero usar:

g413-led -a 000000
g413-led -a FFFFFF

Para ligar/desligar a luz de fundo do teclado usando https://github.com/MatMoul/g810-led .

O primeiro é bastante fácil usando um dos seguintes:

  • xidle
  • xprintidle
  • xautolock

Por favor, aconselhe se existem maneiras melhores e mais ideais?

Mas que tal acendê-lo novamente ao pressionar a tecla ou retomar do modo inativo? Acho que executar o comando em cada pressionamento de tecla é um exagero. Existe evento para opções de economia de energia? Como funciona a economia de energia do monitor?

insira a descrição da imagem aqui

Posso reutilizar os mesmos eventos/tempo limite?

gnome
  • 2 2 respostas
  • 2488 Views

2 respostas

  • Voted
  1. Best Answer
    umpirsky
    2018-01-08T01:33:24+08:002018-01-08T01:33:24+08:00

    A solução que encontrei são os eventos DBUS.

    Primeiro corro dbus-monitorpara ver quais eventos serão acionados quando o monitor for/acordar do modo de suspensão:

    signal time=1515274499.244468 sender=org.freedesktop.DBus -> destination=:1.394 serial=2 path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=NameAcquired
    string ":1.394"
    signal time=1515274499.244502 sender=org.freedesktop.DBus -> destination=:1.394 serial=4 path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=NameLost
    string ":1.394"
    signal time=1515274559.337480 sender=:1.6 -> destination=:1.2 serial=29015 path=/org/gnome/Mutter/IdleMonitor/Core; interface=org.gnome.Mutter.IdleMonitor; member=WatchFired
    uint32 440
    signal time=1515274559.337878 sender=:1.2 -> destination=(null destination) serial=3288 path=/org/gnome/SessionManager/Presence; interface=org.gnome.SessionManager.Presence; member=StatusChanged
    uint32 3
    signal time=1515274559.338267 sender=:1.2 -> destination=(null destination) serial=3290 path=/org/gnome/SessionManager/Presence; interface=org.freedesktop.DBus.Properties; member=PropertiesChanged
    string "org.gnome.SessionManager.Presence"
    array [
    dict entry(
    string "status"
    variant uint32 3
    )
    ]
    array [
    ]
    signal time=1515274569.389778 sender=:1.6 -> destination=(null destination) serial=29018 path=/org/gnome/Shell; interface=org.gnome.Shell.Extensions; member=ExtensionStatusChanged
    string "[email protected]"
    int32 2
    string ""
    signal time=1515274569.398929 sender=:1.6 -> destination=(null destination) serial=29019 path=/org/gnome/Shell; interface=org.gnome.Shell.Extensions; member=ExtensionStatusChanged
    string "[email protected]"
    int32 2
    string ""
    signal time=1515274569.399633 sender=org.freedesktop.DBus -> destination=:1.6 serial=5195 path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=NameLost
    string "org.kde.StatusNotifierWatcher"
    signal time=1515274569.399660 sender=org.freedesktop.DBus -> destination=(null destination) serial=850 path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=NameOwnerChanged
    string "org.kde.StatusNotifierWatcher"
    string ":1.6"
    string ""
    signal time=1515274569.404274 sender=:1.6 -> destination=(null destination) serial=29022 path=/org/gnome/Shell; interface=org.gnome.Shell.Extensions; member=ExtensionStatusChanged
    string "[email protected]"
    int32 2
    string ""
    signal time=1515274569.442137 sender=:1.6 -> destination=(null destination) serial=29025 path=/org/gnome/Shell; interface=org.gnome.Shell.Extensions; member=ExtensionStatusChanged
    string "[email protected]"
    int32 2
    string ""
    signal time=1515274569.455035 sender=:1.6 -> destination=(null destination) serial=29027 path=/org/gnome/ScreenSaver; interface=org.gnome.ScreenSaver; member=ActiveChanged
    boolean true
    signal time=1515274569.657300 sender=:1.6 -> destination=:1.42 serial=29037 path=/org/gnome/Mutter/IdleMonitor/Core; interface=org.gnome.Mutter.IdleMonitor; member=WatchFired
    uint32 491
    signal time=1515274569.657404 sender=:1.6 -> destination=(null destination) serial=29038 path=/org/gnome/Mutter/DisplayConfig; interface=org.freedesktop.DBus.Properties; member=PropertiesChanged
    string "org.gnome.Mutter.DisplayConfig"
    array [
    dict entry(
    string "PowerSaveMode"
    variant int32 3
    )
    ]
    array [
    ]
    signal time=1515276608.243100 sender=:1.6 -> destination=:1.2 serial=29039 path=/org/gnome/Mutter/IdleMonitor/Core; interface=org.gnome.Mutter.IdleMonitor; member=WatchFired
    uint32 489
    signal time=1515276608.243573 sender=:1.2 -> destination=(null destination) serial=3291 path=/org/gnome/SessionManager/Presence; interface=org.gnome.SessionManager.Presence; member=StatusChanged
    uint32 0
    signal time=1515276608.243843 sender=:1.2 -> destination=(null destination) serial=3292 path=/org/gnome/SessionManager/Presence; interface=org.freedesktop.DBus.Properties; member=PropertiesChanged
    string "org.gnome.SessionManager.Presence"
    array [
    dict entry(
    string "status"
    variant uint32 0
    )
    ]
    array [
    ]
    signal time=1515276608.244032 sender=:1.6 -> destination=:1.42 serial=29040 path=/org/gnome/Mutter/IdleMonitor/Core; interface=org.gnome.Mutter.IdleMonitor; member=WatchFired
    uint32 494
    signal time=1515276608.270459 sender=:1.6 -> destination=(null destination) serial=29042 path=/org/gnome/Mutter/DisplayConfig; interface=org.freedesktop.DBus.Properties; member=PropertiesChanged
    string "org.gnome.Mutter.DisplayConfig"
    array [
    dict entry(
    string "PowerSaveMode"
    variant int32 0
    )
    ]
    array [
    ]
    signal time=1515276623.523917 sender=:1.6 -> destination=:1.42 serial=29043 path=/org/gnome/Mutter/IdleMonitor/Core; interface=org.gnome.Mutter.IdleMonitor; member=WatchFired
    uint32 491
    signal time=1515276623.554451 sender=:1.6 -> destination=(null destination) serial=29047 path=/org/gnome/Mutter/DisplayConfig; interface=org.freedesktop.DBus.Properties; member=PropertiesChanged
    string "org.gnome.Mutter.DisplayConfig"
    array [
    dict entry(
    string "PowerSaveMode"
    variant int32 3
    )
    ]
    array [
    ]
    signal time=1515276668.529836 sender=:1.6 -> destination=:1.2 serial=29048 path=/org/gnome/Mutter/IdleMonitor/Core; interface=org.gnome.Mutter.IdleMonitor; member=WatchFired
    uint32 440
    signal time=1515276668.530236 sender=:1.2 -> destination=(null destination) serial=3293 path=/org/gnome/SessionManager/Presence; interface=org.gnome.SessionManager.Presence; member=StatusChanged
    uint32 3
    signal time=1515276668.530565 sender=:1.2 -> destination=(null destination) serial=3295 path=/org/gnome/SessionManager/Presence; interface=org.freedesktop.DBus.Properties; member=PropertiesChanged
    string "org.gnome.SessionManager.Presence"
    array [
    dict entry(
    string "status"
    variant uint32 3
    )
    ]
    array [
    ]
    signal time=1515279067.394398 sender=:1.6 -> destination=:1.2 serial=29051 path=/org/gnome/Mutter/IdleMonitor/Core; interface=org.gnome.Mutter.IdleMonitor; member=WatchFired
    uint32 498
    signal time=1515279067.394982 sender=:1.2 -> destination=(null destination) serial=3296 path=/org/gnome/SessionManager/Presence; interface=org.gnome.SessionManager.Presence; member=StatusChanged
    uint32 0
    signal time=1515279067.395139 sender=:1.2 -> destination=(null destination) serial=3297 path=/org/gnome/SessionManager/Presence; interface=org.freedesktop.DBus.Properties; member=PropertiesChanged
    string "org.gnome.SessionManager.Presence"
    array [
    dict entry(
    string "status"
    variant uint32 0
    )
    ]
    array [
    ]
    signal time=1515279067.395662 sender=:1.6 -> destination=:1.42 serial=29052 path=/org/gnome/Mutter/IdleMonitor/Core; interface=org.gnome.Mutter.IdleMonitor; member=WatchFired
    uint32 496
    signal time=1515279067.414904 sender=:1.6 -> destination=(null destination) serial=29054 path=/org/gnome/Mutter/DisplayConfig; interface=org.freedesktop.DBus.Properties; member=PropertiesChanged
    string "org.gnome.Mutter.DisplayConfig"
    array [
    dict entry(
    string "PowerSaveMode"
    variant int32 0
    )
    ]
    array [
    ]
    signal time=1515279076.828255 sender=:1.6 -> destination=(null destination) serial=29063 path=/org/gnome/Shell; interface=org.gnome.Shell.Extensions; member=ExtensionStatusChanged
    string "[email protected]"
    int32 1
    string ""
    signal time=1515279076.829775 sender=org.freedesktop.DBus -> destination=(null destination) serial=851 path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=NameOwnerChanged
    string "org.kde.StatusNotifierWatcher"
    string ""
    string ":1.6"
    signal time=1515279076.829812 sender=org.freedesktop.DBus -> destination=:1.6 serial=5215 path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=NameAcquired
    string "org.kde.StatusNotifierWatcher"
    signal time=1515279076.829824 sender=:1.6 -> destination=(null destination) serial=29066 path=/org/gnome/Shell; interface=org.gnome.Shell.Extensions; member=ExtensionStatusChanged
    string "[email protected]"
    int32 1
    string ""
    signal time=1515279076.841923 sender=:1.6 -> destination=(null destination) serial=29067 path=/org/gnome/Shell; interface=org.gnome.Shell.Extensions; member=ExtensionStatusChanged
    string "[email protected]"
    int32 1
    string ""
    signal time=1515279076.844396 sender=:1.6 -> destination=(null destination) serial=29068 path=/org/gnome/Shell; interface=org.gnome.Shell.Extensions; member=ExtensionStatusChanged
    string "[email protected]"
    int32 1
    string ""
    signal time=1515279076.851323 sender=:1.6 -> destination=(null destination) serial=29069 path=/org/gnome/ScreenSaver; interface=org.gnome.ScreenSaver; member=ActiveChanged
    boolean false
    signal time=1515279076.896958 sender=:1.6 -> destination=(null destination) serial=29218 path=/StatusNotifierWatcher; interface=org.kde.StatusNotifierWatcher; member=StatusNotifierItemRegistered
    string "/"
    signal time=1515279076.921110 sender=:1.38 -> destination=(null destination) serial=2735 path=/org/gnome/evolution/dataserver/CalendarView/1887/93; interface=org.gnome.evolution.dataserver.CalendarView; member=complete
    array [
    string ""
    string ""
    ]
    signal time=1515279076.924727 sender=:1.34 -> destination=(null destination) serial=2701 path=/org/gnome/evolution/dataserver/CalendarView/1870/92; interface=org.gnome.evolution.dataserver.CalendarView; member=complete
    array [
    string ""
    string ""
    ]
    signal time=1515279077.686970 sender=:1.6 -> destination=(null destination) serial=30014 path=/StatusNotifierWatcher; interface=org.freedesktop.DBus.Properties; member=PropertiesChanged
    string "org.kde.StatusNotifierWatcher"
    array [
    dict entry(
    string "RegisteredStatusNotifierItems"
    variant array [
    string ":1.66/org/ayatana/NotificationItem/software_update_available"
    ]
    )
    ]
    array [
    

    Primeiro tentei ir para org.gnome.Mutter.IdleMonitor, mas uint32os valores aumentavam constantemente, não sei por quê?

    Eu resolvi com StatusChanged, aqui está o script final:

    #!/bin/bash
    # Turn keyboard backlight on/off using https://github.com/MatMoul/g810-led
    
    g413-led -a FFFFFF # always turn on on startup (it turns off for some reason on reboot)
    
    dbus-monitor --session "type=signal,interface=org.gnome.SessionManager.Presence,member=StatusChanged" |
      while read x; do
          case "$x" in
            *"uint32 3"*) g413-led -a 000000;;
            *"uint32 0"*) g413-led -a FFFFFF;;
          esac
      done
    

    Os eventos do protetor de tela também podem funcionar:

    g413-led -a FFFFFF # always turn on on startup (it turns off for some reason on reboot)
    
    dbus-monitor --session "type='signal',interface='org.gnome.ScreenSaver'" |
      while read x; do
          case "$x" in
            *"boolean true"*) g413-led -a 000000;;
            *"boolean false"*) g413-led -a FFFFFF;;
          esac
      done
    

    Claro, você pode colocar qualquer comando que desejar. A vantagem do primeiro script em comparação com este é que ele acende o teclado antes do login do usuário, o que facilita a digitação da senha.

    A única desvantagem é que os teclados acendem após o login do usuário, não ao pressionar a tecla, mas posso viver com isso.

    Eu estava experimentando:

    dbus-monitor --session "type='signal',interface='org.freedesktop.DBus.Properties',path='/org/gnome/Mutter/DisplayConfig'" | grep 'variant int32' |
      while read x; do
          case "$x" in
            *"variant int32 3"*) g413-led -a 000000;;
            *"variant int32 0"*) g413-led -a FFFFFF;;
          esac
      done
    

    mas não funcionou por algum motivo, provavelmente problema grep.

    • 4
  2. Jacob Vlijm
    2018-01-08T03:06:44+08:002018-01-08T03:06:44+08:00

    Minúsculo processo em segundo plano

    Sua configuração parece bastante complicada para um problema simples. O que eu faria é simplesmente executar um pequeno processo de backround, verificando o tempo ocioso uma vez a cada 2 segundos ou mais, executar uma ação se o tempo ocioso exceder o limite, outra ação se ele mudar para um tempo ocioso abaixo do definido.

    O roteiro:

    #!/usr/bin/env python3
    import time
    import subprocess
    
    # set idle time (seconds)
    t = 60
    
    # set commands
    on_idle = ["g413", "-led", "-a", "000000"]
    on_active = ["g413", "-led", "-a", "FFFFFF"]
    
    def set_state(cmd):
        subprocess.Popen(cmd)
    
    def get_idle():
        return int(subprocess.check_output("xprintidle").decode("utf-8").strip())/1000
    
    idle1 = 0
    
    while True:
        time.sleep(2)
        idle2 = get_idle()
        # if idle time exceeds (passes) the limit, run one command
        if all([idle2 >= t, idle1 < t]):
            set_state(on_idle)
        # if idle time switches to below (passes) the limit, run another command
        elif all([idle2 <= t, idle1 > t]):
            set_state(on_active)
        idle1 = idle2
    

    Usar

    • Certifique -se de que xprintidleestá instalado

      sudo apt install xprintidle
      
    • Copie o script em um arquivo vazio, salve-o comoswitch_light.py

    • Defina o tempo ocioso desejado para agir após:

      # set idle time (seconds)
      t = 60
      
    • Execute-o pelo comando:

      python3 /path/to/switch_light.py
      
    • Se tudo funcionar bem, adicione-o a Aplicativos de inicialização.

    Notas)

    • Não pude testar pois não tenho seu teclado, mas testado com outros comandos, cumpre bem o seu papel.

    • Você pode usar o script com qualquer outro comando:

      # set commands
      on_idle = ["g413", "-led", "-a", "000000"]
      on_active = ["g413", "-led", "-a", "FFFFFF"]
      

      Apenas certifique-se de separar os argumentos como no exemplo.

    • Se você deseja apenas uma ação para exceder o tempo ocioso (ou o contrário), apenas comente:

      # if idle time switches to below (passes) the limit, run another 
      elif all([idle2 <= t, idle1 > t]):
          set_state(on_active)
      
    • 2

relate perguntas

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Existe um comando para listar todos os usuários? Também para adicionar, excluir, modificar usuários, no terminal?

    • 9 respostas
  • Marko Smith

    Como excluir um diretório não vazio no Terminal?

    • 4 respostas
  • Marko Smith

    Como descompactar um arquivo zip do Terminal?

    • 9 respostas
  • Marko Smith

    Como instalo um arquivo .deb por meio da linha de comando?

    • 11 respostas
  • Marko Smith

    Como instalo um arquivo .tar.gz (ou .tar.bz2)?

    • 14 respostas
  • Marko Smith

    Como listar todos os pacotes instalados

    • 24 respostas
  • Martin Hope
    Flimm Como posso usar o docker sem sudo? 2014-06-07 00:17:43 +0800 CST
  • Martin Hope
    led-Zepp Como faço para salvar a saída do terminal em um arquivo? 2014-02-15 11:49:07 +0800 CST
  • Martin Hope
    ubuntu-nerd Como descompactar um arquivo zip do Terminal? 2011-12-11 20:37:54 +0800 CST
  • Martin Hope
    TheXed Como instalo um arquivo .deb por meio da linha de comando? 2011-05-07 09:40:28 +0800 CST
  • Martin Hope
    Ivan Como listar todos os pacotes instalados 2010-12-17 18:08:49 +0800 CST
  • Martin Hope
    David Barry Como determino o tamanho total de um diretório (pasta) na linha de comando? 2010-08-06 10:20:23 +0800 CST
  • Martin Hope
    jfoucher "Os seguintes pacotes foram retidos:" Por que e como resolvo isso? 2010-08-01 13:59:22 +0800 CST
  • Martin Hope
    David Ashford Como os PPAs podem ser removidos? 2010-07-30 01:09:42 +0800 CST

Hot tag

10.10 10.04 gnome networking server command-line package-management software-recommendation sound xorg

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve