Contenu | Rechercher | Menus

Annonce

Si vous avez des soucis pour rester connecté, déconnectez-vous puis reconnectez-vous depuis ce lien en cochant la case
Me connecter automatiquement lors de mes prochaines visites.

À propos de l'équipe du forum.

#1 Le 11/02/2020, à 01:51

Compte supprimé

Prog d'Alerte pour batterie déchargée/ animation visuelle et sonore

Bonjour, voici un petit programme qui vous alertera lorsque votre batterie devra être rechargée.
Je me suis amusé en utilisant synthèse vocale, animation graphique, sonore pour agrémenter le tout.
L'alerte se fait en trois parties toutes les 3minutes . Lorsque la batterie atteint 25%, la 1er alerte commence . 3 minutes après rappel à l'ordre . Puis vient la 3eme alerte avec une animation réalisée avec python.

Ce programme est destiné à Ubuntu 18.04 voir plus. Il devrait s'afficher correctement sur la plupart des écrans.

Pour l'essayer:
1/ Télécharger l'archive depuis votre navigateur :

https://www.cjoint.com/c/JBljBguN3Ff

2/ Copier/coller dans un terminal le script ci-dessous (ne pas oublier d'appuyer sur la touche return en dernière ligne)

#!/bin/bash
cd ~/Téléchargements
tar xvf JBljBguN3Ff_dossier-script-batterie.tar
sleep 0.5
cp -r ~/Téléchargements/home/fab/.dossier_script_batterie/ ~/.dossier_script_batterie
sleep 0.5
rm JBljBguN3Ff_dossier-script-batterie.tar
rm -r ~/Téléchargements/home
sudo apt install acpi python-tk python-imaging-tk python3-tk
sleep 0.5
crontab -l 1> /dev/null 2> /dev/null >/tmp/fichier
echo "*/3 * * * * DISPLAY=:0 bash ~/.dossier_script_batterie/scriptbatterie.sh" >> /tmp/fichier
crontab /tmp/fichier

Voilà, c'est fait. Maintenant le script s'exécutera lorsque la batterie sera à 25%. Vous ne serez plus jamais surpris par l'extinction de votre pc et vous préserverez vos batteries de décharge profonde (10% selon la distribution).
J'ignore si ce code vous sera utile. En tous cas je me suis bien amusé...

Si vous voulez désinstaller le programme:

rm -r ~/.dossier_script_batterie/scriptbatterie.sh

note: Si vous souhaitez modifier le parametre des 25 %, éditez le fichier ~/.dossier_script_batterie/scriptbatterie.sh et remplacer le 25 situé ligne 9 par la valeur de votre choix.

 9 ---> elif test "$etat_batterie" -lt 25 ;then

Dernière modification par Compte supprimé (Le 11/02/2020, à 12:21)

#2 Le 11/02/2020, à 12:19

Compte supprimé

Re : Prog d'Alerte pour batterie déchargée/ animation visuelle et sonore

oups je viens de tenter l'instalation , j'ai une erreur qui s'est glissé dans l'archive hmm . Je vais rectifier ça ... Ne téléchargez donc pas le programme maintenant, avant que je ne rectifie le tir

Maintenant, cela devrait fonctionner.
Si vous voulez voir le resultat sans pour cela attendre que votre batterie soit déchargée, modifiez la valeur de l'alerte à 100 comme précisée dans la note du post ci dessus . Le pc ne doit pas être branché sur secteur sinon il ne se passera rien.

Dernière modification par Compte supprimé (Le 11/02/2020, à 12:28)

#3 Le 11/02/2020, à 12:45

grandtoubab

Re : Prog d'Alerte pour batterie déchargée/ animation visuelle et sonore

surement un bel exercice mais c'est déjà fait par gnome-power-manager

https://help.gnome.org/users/gnome-powe … html.en_GB


1581420980.png

gnome-power-manager/testing,unstable,now 3.32.0-2 amd64  [installé]

Et ça fonctionne


Linux tout seul sur HP Pavilion DV7 et Acer Aspire T650, Canon MG3650 en wifi
Debian 11 Bullseye Gnome/Xorg, Gnome/Wayland avec SDDM
https://bidouilledebian.wordpress.com/
ON M'A VU DANS LE VERCORS, SAUTER A L'ELASTIQUE..... J'AI DANS LES BOTTES DES MONTAGNES DE QUESTIONS....

Hors ligne

#4 Le 11/02/2020, à 13:16

Compte supprimé

Re : Prog d'Alerte pour batterie déchargée/ animation visuelle et sonore

Certes, mais mon prog est beaucoup plus ludique. tongue
Je ne me contente pas d'ouvrir une fenêtre d'alerte ou d'émettre une alerte sonore. Je propose une animation , un scénario et de la fantaisie. wink

eh oui pour moi, c'était un bon exercice . Il m'a fallu gérer dans la partie graphique  la gestion des différences d'écran , écrire un programme à deux mains (bash et python), et plein d'autres trucs que j'ai appréhendé pour la première fois. Certaines mises en œuvre m'ont questionné ... Bref oui un bon exercice pour moi. D'ailleurs, je suis preneur de tout conseil afin d'améliorer le code ou la façon de faire wink

Dernière modification par Compte supprimé (Le 11/02/2020, à 13:22)

#5 Le 11/02/2020, à 13:56

grandtoubab

Re : Prog d'Alerte pour batterie déchargée/ animation visuelle et sonore

Je ne suis pas un expert en code , pour des besoins de test de ma batterie je me suis fait ce simple script "batterie"

#!/bin/bash
#set -x
while true
do
date
echo capacité $(cat /sys/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0C0A:00/power_supply/BAT0/capacity)
sleep 60
done
 bash batterie
mardi 11 février 2020, 12:49:36 (UTC+0100)
capacité 90
mardi 11 février 2020, 12:50:36 (UTC+0100)
capacité 90
mardi 11 février 2020, 12:51:36 (UTC+0100)
capacité 89
mardi 11 février 2020, 12:52:36 (UTC+0100)
capacité 87
mardi 11 février 2020, 12:53:36 (UTC+0100)
capacité 86
mardi 11 février 2020, 12:54:36 (UTC+0100)
capacité 85

Et c'est là que j'ai compris que ma batterie perdait 1% par minute donc en 1h40 elle est vide sad

Dernière modification par grandtoubab (Le 11/02/2020, à 13:57)


Linux tout seul sur HP Pavilion DV7 et Acer Aspire T650, Canon MG3650 en wifi
Debian 11 Bullseye Gnome/Xorg, Gnome/Wayland avec SDDM
https://bidouilledebian.wordpress.com/
ON M'A VU DANS LE VERCORS, SAUTER A L'ELASTIQUE..... J'AI DANS LES BOTTES DES MONTAGNES DE QUESTIONS....

Hors ligne

#6 Le 11/02/2020, à 14:41

Compte supprimé

Re : Prog d'Alerte pour batterie déchargée/ animation visuelle et sonore

Dans mon programme, la gestion de batterie, en elle même, se résume à quelques lignes . Ce qui m'a pris plus de temps, c'est ce qu'il y a autour big_smile (la programmation , le montage sonore avec Audacity que je découvrais pour l'occasion, gimp...)

Pour les curieux qui ne veulent pas télécharger l'archive. Ci-joint la partie code (qui ne fonctionnera évidemment pas sans l'archive)
Il est composé d'un script bash et d'un script python . Les deux fonctionnent en même temps, ils sont une entité à part entière (c'est à dire qu'il faut les considérer comme un seul programme). L'appel se fait depuis le script bash.

#!/bin/bash
#Ce script nécessite d'installer le paquet acpi


etat_batterie=$(acpi -V|grep Discharging|cut -d "," -f2|sed s/%//)

if [ -z "$etat_batterie" ]; then
        exit
elif test "$etat_batterie" -lt 25;then
	if [ -f /tmp/flag ];then
		if [ "$(cat /tmp/flag)" == 1 ];then
			paplay ~/.dossier_script_batterie/t_sourd_je_fatigue.wav
			echo "2">/tmp/flag
			exit
		elif [ "$(cat /tmp/flag)" == 2 ];then
			paplay ~/.dossier_script_batterie/tu_fais_chier_je_vais_meteindre.wav
			rm /tmp/flag
			paplay coeur_decompte.wav &
			pid_paplay=$(pidof paplay)
			python3 warning.py & 
			pid_python=$(pidof -s python3)
		
			while kill -0 $pid_python 2> /dev/null; do
        			etat_batterie=$(acpi -V|grep Discharging|cut -d "," -f2|sed s/%//)
				if [ -n "$etat_batterie" ]
				then
					continue
				else 
					kill -9 $pid_paplay
					kill -9 $pid_python
					paplay ~/.dossier_script_batterie/merci.wav &
					rm /tmp/flag
					exit
				fi
			done

			kill -9 $pid_paplay 2> /dev/null
		fi
	else
		notify-send -u normal -t 50000 -i /usr/share/mate-power-manager/icons/hicolor/48x48/status/gpm-battery-020.png "Attention batterie à""$etat_batterie""%" "Branche moi stp" && paplay ~/.dossier_script_batterie/je_fatigue_recharge_moi.wav
			echo "1">/tmp/flag
			exit
                        
	fi
fi
 
#!/usr/bin/env python3

import os
from PIL import Image
import random
import time
import tkinter as tk

sens = 1
compteur = 0
CHEMIN = os.environ.get('HOME', 'username')


def fonction():
    """Déplacement du warning- Remarque la boucle sera intérompue à la 29s
depuis l'appel de mort() à partir du corps du programme."""
    global sens
    global compteur
    if sens == 1:
        compteur += 1
        if compteur == L - LOB_war:
            sens = -1
    else:
        compteur -= 1
        if compteur == 0:
            sens = 1
    can.move(warning, sens, 0)
    root.after(1, fonction)


def sortie(event):
    try:
        root.destroy()
    except:
        quit()


def mort():
    crane = dict()
    can.delete(warning)
    can.delete(mots)
    flag = False
    for i in range(1, 2):
        for x, y, a in [(1, 1, 'c1'), (710, 600, 'c2'), (1420, 1, 'c3'),
                        (710, 1, 'c4'), (1, 600, 'c5'), (1420, 600, 'c6')]:
            if flag:
                can.delete(crane[a])
            root.update()
            crane[a] = can.create_image(int(x*COEFF_L), int(y*COEFF_H),
                                        anchor='nw', image=photocrane)
            root.update()
            time.sleep(1/2)
        flag = True
# étape2
    for y in range(int(600*COEFF_H), 1, -2):
        can.move(crane['c2'], 0, -2)
        can.move(crane['c5'], 0, -2)
        can.move(crane['c6'], 0, -2)
        root.update()
    for i in ['c2', 'c5', 'c6']:
        can.delete(crane[i])
    root.update()
    for x in range(int(1*COEFF_L), int(710*COEFF_L), 2):
        can.move(crane['c1'], 2, 0)
        root.update()
    for x in range(int(1420*COEFF_L), int(710*COEFF_L), -2):
        can.move(crane['c3'], -2, 0)
        root.update()
    can.delete(crane['c1'])
    can.delete(crane['c3'])
# bouche qui bouge.
    for i in range(10):
        can.delete(crane['c4'])
        crane['c4_2'] = can.create_image(int(710*COEFF_L), int(1*COEFF_H),
                                         anchor='nw', image=photocrane2)
        root.update()
        time.sleep(1/10)
        can.delete(crane['c4_2'])
        crane['c4_3'] = can.create_image(int(710*COEFF_L), int(1*COEFF_H),
                                         anchor='nw', image=photocrane3)
        root.update()
        time.sleep(1/10)
        can.delete(crane['c4_3'])
        crane['c4'] = can.create_image(int(710*COEFF_L), int(1*COEFF_H),
                                       anchor='nw', image=photocrane)
        root.update()
    can.delete(crane['c4'])
# taille crane(500*480) qui diminue 'sur place' jusqu'à 250*240p en cinq images
    ecart = 0  # resize de 10 pixels
    img = Image.open(CHEMIN +
                     "/.dossier_script_batterie/crane.png", 'r')
    HOB, LOB = img.size
    for i in range(0, 25):
        ecart += 10
        image = img.resize((int((HOB-ecart)*COEFF_H),
                            int((LOB-ecart)*COEFF_H)))
        image.save('/tmp/craneresize.png')
        photocranebis = tk.PhotoImage(file="/tmp/craneresize.png")
        cranediminue = can.create_image(int((710+ecart/2)*COEFF_L),
                                        int((1+ecart/2)*COEFF_H),
                                        anchor='nw', image=photocranebis)
        root.update()
        if i == 24:
            can.delete(cranediminue)
# le crane tourne sur place et s'accélère
# à noter que je repars sur une nouvelle image de
# 300*290 dont le masque est suffisant(+50p)pour permettre la rotation
# sans tronquer l'image (qui elle reste à 250*240)
    img = Image.open('/tmp/crane_masque_grandi.png', "r")
    HOB, LOB = img.size
    cranetourne = dict()
    phototourne = dict()
    acceleration = [100, 50, 25, 10, 5]
    for angle in range(0, 361, 30):
        phototourne[angle] = tk.PhotoImage(
            file="/tmp/crane_tourne"+str(angle)+".png")
    while acceleration:
        accelere = acceleration.pop()
        for angle in range(0, 361, 30):
            cranetourne[angle] = can.create_image(
                int((710+(ecart/2)-25)*COEFF_L),
                int((y+(ecart/2)-25)*COEFF_H),
                anchor='nw', image=phototourne[angle])
            time.sleep(1/accelere)
            root.update()
            can.delete(cranetourne[angle])
# sénario cranes qui tournent et partent au hazard d'une direction
# puis rebondi sur limite du canevas
    boucle = 5
    angle = 0
    x = 0
    y = 0
    sensx = 1
    sensy = 1
    pos = [1, -1]
    randomy = pos[random.randint(0, 1)] * 4
    randomx = pos[random.randint(0, 1)] * 4
    while True:
        y += randomy * sensx
        x += randomx * sensy
        if angle == 390:
            angle = 0
        cranetourne[angle] = can.create_image(int((710+x+ecart/2-25)*COEFF_L),
                                              int((y+ecart/2-25)*COEFF_H),
                                              anchor='nw',
                                              image=phototourne[angle])
        root.update()
        time.sleep(1/100)
        can.delete(cranetourne[angle])
        angle += 30
        time.sleep(1/100)
        if (y+ecart/2-25) * COEFF_H > (1080-HOB) * COEFF_H:
            sensx *= -1
            boucle -= 1
            if boucle == 0:
                root.destroy()
                break
        elif(y+ecart/2-25) * COEFF_H < 1:
            sensx *= -1
            boucle -= 1
            if boucle == 0:
                root.destroy()
                break
        elif(710+x+ecart/2-25) * COEFF_L > (1920-LOB) * COEFF_L:
            sensy *= -1
            boucle -= 1
            if boucle == 0:
                break
                root.destroy()
        elif (710+x+ecart/2-25)*COEFF_L < 0:
            sensy *= -1
            boucle -= 1
            if boucle == 0:
                root.destroy()
                break

            
def apropos(event):
    global imapropos
    photoapropos = tk.PhotoImage(file="/tmp/apropos.png")
    imapropos = can.create_image(int(960*COEFF_L), int(520*COEFF_H)
                                 ,
                                 anchor='center', image=photoapropos, tag="quitter")
    can.tag_bind("quitter", "<Button-1>", quitteapropos)
    
    root.update()
    
def quitteapropos(event):
    can.delete(imapropos)
  
    
# Début du programme
root = tk.Tk()
# soit L ,H, largeur et hauteur pixel de la machine hôte
L = root.winfo_screenwidth()
H = root.winfo_screenheight()
COEFF_L = L / 1920
COEFF_H = H / 1080

# Chargement photos ---->resize
img = Image.open(CHEMIN +
                 "/.dossier_script_batterie/warningbis.png",
                 'r')
HOB, LOB = img.size
image = img.resize((int(HOB*COEFF_L), int(LOB*COEFF_L)))
image.save('/tmp/warning.png')

img = Image.open(CHEMIN+"/.dossier_script_batterie/crane.png", 'r')
HOB, LOB = img.size
image = img.resize((int(HOB*COEFF_L), int(LOB*COEFF_L)))
image.save('/tmp/crane.png')

img = Image.open(CHEMIN+"/.dossier_script_batterie/crane2.png", 'r')
HOB, LOB = img.size
image = img.resize((int(HOB*COEFF_L), int(LOB*COEFF_L)))
image.save('/tmp/crane2.png')

img = Image.open(CHEMIN+"/.dossier_script_batterie/crane3.png", 'r')
HOB, LOB = img.size
image = img.resize((int(HOB*COEFF_L), int(LOB*COEFF_L)))
image.save('/tmp/crane3.png')

img = Image.open(CHEMIN +
                 "/.dossier_script_batterie/crane_masque_grandi.png"
                 , 'r')
HOB, LOB = img.size
image = img.resize((int(HOB*COEFF_L), int(LOB*COEFF_L)))
image.save('/tmp/crane_masque_grandi.png')

img = Image.open(CHEMIN +"/.dossier_script_batterie/apropos.png"
                 , 'r')
HOB, LOB = img.size
image = img.resize((int(HOB*COEFF_L), int(LOB*COEFF_L)))
image.save('/tmp/apropos.png')

# Création têtes qui tournent
img = Image.open('/tmp/crane_masque_grandi.png')
HOB, LOB = img.size
for angle in range(0, 361, 30):
        crane = img.rotate(angle)
        crane.save("/tmp/crane_tourne"+str(angle)+".png")
# #########
root.attributes('-fullscreen', 1)
can = tk.Canvas(root, width=L, height=int(1080/COEFF_L),
                background='black')
can.pack()

bouton = tk.PhotoImage (file=CHEMIN + "/.dossier_script_batterie/bouton.png")
can.create_image(int(1920*COEFF_L), 1, anchor='ne', image=bouton, tag="choisir")
can.tag_bind("choisir", "<Button-1>", apropos)

photo = tk.PhotoImage(file="/tmp/warning.png")
photocrane = tk.PhotoImage(file="/tmp/crane.png")
photocrane2 = tk.PhotoImage(file="/tmp/crane2.png")
photocrane3 = tk.PhotoImage(file="/tmp/crane3.png")
img = Image.open("/tmp/warning.png")
LOB_war = img.size[1]
warning = can.create_image(1, int(540*COEFF_H), anchor='w', image=photo)
mots = can.create_text(int(960*COEFF_L), int(1000*COEFF_H),
                       text="Appuie sur une touche pour quitter",
                       font=("Courrier", int(60*L/1920), 'bold'),
                       anchor='center', fill="red")
root.after(28500, mort)
root.bind('<KeyPress>', sortie)

fonction()
root.mainloop()