Skip to content

Instantly share code, notes, and snippets.

@itzmeanjan
Last active March 29, 2020 07:27
Show Gist options
  • Save itzmeanjan/f2f7908d4f79c518db30e3ec0d1e5778 to your computer and use it in GitHub Desktop.
Save itzmeanjan/f2f7908d4f79c518db30e3ec0d1e5778 to your computer and use it in GitHub Desktop.
JioFi 3 router's battery status extractor & notifier ( using Linux desktop notification )
#!/usr/bin/python3
'''
Strictly use python version >=3.7.0, because script uses type hinting
Note that : This script doesn't work on Windows/ Mac i.e. notification
service will work only on Linux, having dependeny on `notify-send` program;
though extraction of battery status ( from router management portal )
can be done by this script on any platfrom, given that machine is
connected to JioFi router ( tested to be working on JioFi 3 )
On Ubuntu `notify-send` can be installed :
$ sudo apt-get install libnotify-bin
You need to have `beautifulsoup` library installed for scraping
jiofi management portal page
$ python3 -m pip install beautifupsoup --user
'''
from __future__ import annotations
from typing import Dict
from subprocess import run
from requests import get
from bs4 import BeautifulSoup
def getContent(url: str) -> str:
'''
Sends a GET request to specified url & obtains HTML content,
In case of error, returns None
'''
try:
resp = get(url)
if resp.status_code != 200:
return None
return resp.content
except Exception as e:
print('Error : ' + str(e))
return None
def parseContent(content: str) -> Dict[str, str]:
'''
Given HTML content of webpage, it'll extract `input` tags
with {`batterystatus`, `batterylevel`} id param; and returns
a map with those values
In case of error, returns None
'''
if not content:
return None
tree = BeautifulSoup(content, features='html.parser')
batteryStatus = tree.find('input', attrs={'id': 'batterystatus'})
batteryLevel = tree.find('input', attrs={'id': 'batterylevel'})
return {'status': batteryStatus.get('value'), 'level': batteryLevel.get('value')}
def sendNotification(data: Dict[str, str]) -> bool:
'''
Given battery status of JioFi to which this computer is
connected via WiFi as map; we'll show notification using
`notify-send` program; for which `libnotify-bin` needs to be
installed on your Linux machine
Denotes success by boolean result
'''
if not data:
return False
try:
return run(['sudo', '-u', 'user', 'DISPLAY=:0',
'DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus',
'notify-send', 'JioFi Battery Status',
'Status : <b>{status}</b> Level : <b>{level}</b>'.format(
**data),
'-i', 'battery',
'-u', 'normal']).returncode == 0
except Exception as e:
print('Error : ' + str(e))
return False
def main():
try:
# http://192.168.1.1 is where jiofi router is avaiable, for JioFi 3 ( tested on it)
print(sendNotification(parseContent(getContent('http://192.168.1.1/'))))
except KeyboardInterrupt:
print('\nTerminated')
finally:
return
if __name__ == '__main__':
main()
[Unit]
Description=JioFi Battery Status Notifier
Wants=jiofiNotification.timer
[Service]
User=user
WorkingDirectory=/home/user
ExecStart=/home/user/.local/bin/jiofiBatteryStat.py
[Install]
WantedBy=multi-user.target
Unit]
Description=JioFi Battery Status Notifier
Requires=jiofiNotification.service
[Timer]
Unit=jiofiNotification.service
OnUnitActiveSec=30m
[Install]
WantedBy=timers.target
@itzmeanjan
Copy link
Author

screenshot

motivation

Well I've a JioFi 3 router; but mostly I used to forget that I need to charge it / if it's already charging, I required to pull it out; so I thought of writing a simple script that will automate checking battery status of JioFi for me & show me a desktop notification. As I'm on GNU/Linux machine, I'm making it work on Linux machine only ( notification part ). Though extraction of battery status can be done on any platform, given machine is connected to JioFi 3.

installation

requirements

  • Make sure you've python3 installed ( >=3.7.0 )
$ python3 --version
  • Notification works only on GNU/Linux using libnotify-bin; install it
$ sudo apt-get install libnotify-bin
  • beautifulsoup library required for scraping JioFi management webportal ( supplied at http://192.168.1.1/ )
$ python3 -m pip install beautifulsoup --user

automate with systemd

  • I'm assuming you've a directory $HOME/.local/bin/, where user installed scripts are placed & it's in your PATH variable. If not, modify your shell init script ( for BASH ~/.bashrc ); to append ~/.local/bin/ to PATH variable
$ export PATH="$PATH:$HOME/.local/bin/" # put it end of ~/.bashrc
  • Now source it, to reflect changes
$ source .bashrc # now all scripts placed inside ~/.local/bin/ can be directly invoked
  • Now copy jiofiBatteryStat.py to ~/.local/bin/, make it executable.
$ cp jiofiBatteryStat.py ~/.local/bin/
$ chmod +x ~/.local/bin/ jiofiBatteryStat.py
  • Update {jiofiBatteryStat.py, jiofiNotification.service} file's user fields with your GNU/Linux account username, which can be obtained
$ whoami
  • Now copy jiofiNotification.[service|timer] to /etc/systemd/system
$ sudo cp jiofiNotification.* /etc/systemd/system/ -v
  • Reload systemd daemon
$ sudo systemctl reload-daemon
  • Enable jiofiNotification.timer file
$ sudo systemctl enable jiofiNotification.timer
  • Start service
$ sudo systemctl start jiofiNotification.timer

Now every 30 mins desktop notification to be displayed; showing JioFi 3's Battery Status

Thanking you ... 😉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment