From 926c74b6e25d20b227cee762764a019c2100fb5e Mon Sep 17 00:00:00 2001 From: L3D Date: Wed, 31 Jul 2024 16:11:08 +0200 Subject: [PATCH] Create custom ping module to detect internet --- defaults/main.yml | 1 + tasks/waybar.yml | 10 ++++++++++ templates/ping.py.j2 | 43 ++++++++++++++++++++++++++++++++++++++++ templates/waybar.css.j2 | 8 ++++++++ templates/waybar.json.j2 | 6 ++++++ 5 files changed, 68 insertions(+) create mode 100644 templates/ping.py.j2 diff --git a/defaults/main.yml b/defaults/main.yml index 2d964ff..ee6dc1d 100644 --- a/defaults/main.yml +++ b/defaults/main.yml @@ -27,6 +27,7 @@ sway__waybar_modules_right: - "custom/weather" - "pulseaudio" - "network" + - "custom/ping" - "cpu" - "memory" - "disk" diff --git a/tasks/waybar.yml b/tasks/waybar.yml index 64fa76c..78d12c5 100644 --- a/tasks/waybar.yml +++ b/tasks/waybar.yml @@ -27,6 +27,16 @@ group: "{{ swayusr.user }}" backup: true +- name: Deploy ping script + become: true + ansible.builtin.template: + src: 'templates/ping.py.j2' + dest: "{{ swayusr.home }}/.config/waybar/ping.py" + mode: '0750' + owner: "{{ swayusr.user }}" + group: "{{ swayusr.user }}" + backup: true + - name: Deploy waybar stylesheet become: true ansible.builtin.template: diff --git a/templates/ping.py.j2 b/templates/ping.py.j2 new file mode 100644 index 0000000..4360f7b --- /dev/null +++ b/templates/ping.py.j2 @@ -0,0 +1,43 @@ +#!/usr/bin/env python +""" +ping waybar widget +{{ ansible_managed }} +""" +import subprocess +import json +import sys + +def check_internet(): + """ + Try to ping a host in the internet, + then return true or false + """ + try: + subprocess.check_call(['ping', '-c', '2', 'c3woc.de'], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + return True + except subprocess.CalledProcessError: + return False + +def main(): + """ + parsing internet status and create output + """ + internet_status = check_internet() + if internet_status: + status = { + "text": "Online", + "tooltip": "Internet connection is active", + "class": "online" + } + else: + status = { + "text": "Offline", + "tooltip": "No internet connection", + "class": "offline" + } + print(json.dumps(status)) + sys.stdout.flush() + +if __name__ == "__main__": + main() diff --git a/templates/waybar.css.j2 b/templates/waybar.css.j2 index cda9b91..cb5bdda 100644 --- a/templates/waybar.css.j2 +++ b/templates/waybar.css.j2 @@ -280,3 +280,11 @@ label:focus { #scratchpad.empty { background-color: transparent; } + +#custom-ping.connected { + color: #00FF00; /* Grün für verbunden */ +} + +#custom-ping.disconnected { + color: #FF0000; /* Rot für nicht verbunden */ +} diff --git a/templates/waybar.json.j2 b/templates/waybar.json.j2 index fc04293..99831eb 100644 --- a/templates/waybar.json.j2 +++ b/templates/waybar.json.j2 @@ -166,6 +166,12 @@ "format": "", "on-click": "wlogout", "tooltip": false + }, + "custom/ping": { + "format": "{}", + "exec": "{{ swayusr.home }}/.config/waybar/ping.py", + "interval": 60, + "return-type": "json" } }