Skip to content

Commit

Permalink
initial commit of v2!
Browse files Browse the repository at this point in the history
This is a huge step in fixing many of the mistakes that we've done in the
past and making himawaripy awesome again.

* No more `config.py` madness.

  It was the stupidest mistake I've ever done. Configuration file was
  unnecessary after all and worse still, it was a native Python script that
  went into the installation directory, making it impossible for different
  users sharing the same system have different configs.

  Now there are only command line arguments. Many thanks to @p4block for
  raising the issue.

* Time offset confusion

  Maybe it is just me but I think we thought what `hour_offset` was. There is
  nothing useful (literally) in documentation indicating what it is (except
  its name). Is it offset from GMT, offset from himawari (which orbits
  GMT+10:00)? It also caused many errors, such as requesting the image of
  Earth from the future: boramalper#85, boramalper#82...

  Now you can either let himawaripy automatically detect it for you or you
  can give _your offset from GMT_ to let the script fetch right images.

* Save battery

  You might not want himawaripy to drain your battery by downloading 64
  tiles in every 10 minutes.

  Now you can stop himawaripy from refreshing when on battery by passing
  `--save-battery` argument. Thanks to @vician's suggestion.

* Retry on failure

  Internet sometimes does not just work. Retry up to 3 times for each file
  before giving up so that not the whole process stops because of a small
  temporary error.

  Thanks to @cameronleger.

* Output directory

  Now you can set the output directory for himawaripy if you would like to.

... besides general cleanup, improvements bla bla bla.

Sincerely,
Bora
  • Loading branch information
boramalper committed Oct 13, 2016
1 parent e5d6e05 commit a9fd7f5
Show file tree
Hide file tree
Showing 7 changed files with 271 additions and 197 deletions.
93 changes: 55 additions & 38 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
# himawaripy
*Put near-realtime picture of Earth as your desktop background*

![By /u/hardypart](https://i.imgur.com/UoZMp5Y.gif)

himawaripy is a Python 3 script that fetches near-realtime (10 minutes delayed)
picture of Earth as its taken by
[Himawari 8 (ひまわり8号)](https://en.wikipedia.org/wiki/Himawari_8) and sets it
as your desktop background.

Set a cronjob that runs in every 10 minutes to automatically get the
Set a cronjob (or systemd service) that runs in every 10 minutes to automatically get the
near-realtime picture of Earth.

## Supported Desktop Environments
Expand All @@ -24,13 +26,40 @@ near-realtime picture of Earth.
* any other desktop environments that are not mentioned above.

## Configuration
You can configure the level of detail, by modifying the script. You can set the
global variable `level` to `4`, `8`, `16`, or `20` to increase the quality (and
thus the file size as well). Please keep in mind that it will also take more
time to download the tiles.

You can also change the path of the latest picture, which is by default
`~/.himawari/himawari-latest.png`, by changing the `output_file` variable.
usage: [-h] [--version] [--auto-offset | -o OFFSET] [-l {4,8,16,20}]
[-d DEADLINE] [--save-battery] [--output-dir OUTPUT_DIR]

set (near-realtime) picture of Earth as your desktop background

optional arguments:
-h, --help show this help message and exit
--version show program's version number and exit
--auto-offset determine offset automatically
-o OFFSET, --offset OFFSET
UTC time offset in hours, must be less than or equal
to +10
-l {4,8,16,20}, --level {4,8,16,20}
increases the quality (and the size) of each tile.
possible values are 4, 8, 16, 20
-d DEADLINE, --deadline DEADLINE
deadline in minutes to download all the tiles, set 0
to cancel
--save-battery stop updating on battery
--output-dir OUTPUT_DIR
directory to save the temporary background image

Most of the time himawaripy can accurately detect your timezone if you pass the flag `--auto-offset`, although you may
also set it manually by `-o` (or `--offset`) flag. If your timezone is beyond GMT by more than 10 hours, use the closest
one (either `+10` or `-12`).

Increasing the level will increase the quality of the image as well as the time taken to download all the tiles and the
memory consumption. For instance choosing 20 will make himawaripy use ~700 MiB of memory at its peak and the image will
be around ~200 MB.

You should set a deadline compatible with your cronjob (or timer) settings to assure that script will terminate in X
minutes before it is started again.

You might use `--save-battery` to disable refreshing while running on battery power.

### Nitrogen
If you use nitrogen for setting your wallpaper, you have to enter this in your
Expand All @@ -40,28 +69,19 @@ If you use nitrogen for setting your wallpaper, you have to enter this in your
file=/home/USERNAME/.himawari/himawari-latest.png
mode=4
bgcolor=#000000

## Prerequisites

You need a valid python3 installation including the python3-setuptools package:

sudo apt install python3
sudo apt install python3-setuptools

## Installation
* You need a valid python3 installation including the python3-setuptools package


cd ~
git clone https://github.com/boramalper/himawaripy.git

# configure
cd ~/himawaripy/
vi himawaripy/config.py

# install
sudo python3 setup.py install

# test whether it's working
himawaripy
himawaripy --auto-offset

# Get the installation path of himawaripy by running the command
which -- himawaripy
Expand All @@ -72,26 +92,28 @@ You need a valid python3 installation including the python3-setuptools package:
crontab -e

### Add the line:
*/10 * * * * <INSTALLATION_PATH>
*/10 * * * * <INSTALLATION_PATH> # command line arguments here

## OR, alternatively use the provided systemd timer

### Configure
vi systemd/himawaripy.service
# Replace "<INSTALLATION_PATH>" with the output of the aforementioned command.
# Replace "<INSTALLATION_PATH>" with the output of the aforementioned command and command line arguments

### Copy systemd configuration
cp systemd/himawaripy.{service,timer} $HOME/.config/systemd/user/
cp systemd/himawaripy.{service,timer} ~/.config/systemd/user/

### Enable and start the timer
systemctl --user enable --now himawaripy.timer

### For KDE Users
#### KDE 5.7+
To change the wallpaper in KDE 5.7+, desktop widgets must be unlocked. If you dom't want to leave them unlocked, the pre-KDE 5.7 method can still be used.
To change the wallpaper in KDE 5.7+, desktop widgets must be unlocked. If you dom't want to leave them unlocked,
the pre-KDE 5.7 method can still be used.

To unlock desktop widgets ([from the KDE userbase](https://userbase.kde.org/Plasma#Widgets)):
> Open the Desktop Toolbox or the Panel Toolbox or right click on the Desktop - if you see an item labeled Unlock Widgets then select that, and then proceed to add widgets to your Desktop or your Panel.
> Open the Desktop Toolbox or the Panel Toolbox or right click on the Desktop - if you see an item labeled Unlock
> Widgets then select that, and then proceed to add widgets to your Desktop or your Panel.
#### Before KDE 5.7
> So the issue here is that KDE does not support changing the desktop wallpaper
Expand All @@ -112,18 +134,21 @@ Many thanks to [xenithorb](https://github.com/xenithorb) [for the solution](http

### For Mac OSX Users

OSX has deprecated crontab, and replaced it with `launchd`. To set up a launch agent, copy the provided sample `plist` file in `osx/com.user.himawaripy.plist` to `~/Library/LaunchAgents`, and edit the following entries if required
OSX has deprecated crontab, and replaced it with `launchd`. To set up a launch agent, copy the provided sample `plist`
file in `osx/org.boramalper.himawaripy.plist` to `~/Library/LaunchAgents`, and edit the following entries if required

mkdir -p ~/Library/LaunchAgents/
cp osx/com.user.himawaripy.plist ~/Library/LaunchAgents/
cp osx/org.boramalper.himawaripy.plist ~/Library/LaunchAgents/

* `ProgrammingArguments` needs to be the `/path/to/himawaripy/installation`. This *should* be `/usr/local/bin/himawaripy` by default, but himawaripy may be installed elsewhere.
* `ProgrammingArguments` needs to be the path to himawaripy installation. This *should* be `/usr/local/bin/himawaripy`
by default, but himawaripy may be installed elsewhere.

* `StartInterval` controls the interval between successive runs, set to 10 minutes (600 seconds) by default, edit as desired.
* `StartInterval` controls the interval between successive runs, set to 10 minutes (600 seconds) by default,
edit as desired.

Finally, to launch it, enter this into the console:

launchctl load ~/Library/LaunchAgents/com.user.himawaripy.plist
launchctl load ~/Library/LaunchAgents/org.boramalper.himawaripy.plist


## Uninstallation
Expand All @@ -136,20 +161,12 @@ Finally, to launch it, enter this into the console:
systemctl --user disable --now himawaripy.timer
rm $HOME/.config/systemd/user/himawaripy.{timer,service}

# Remove the data directory
# By default, `~/.himawari`. Check `output_file` variable in config.py
# in case you've changed it.
rm -rf ~/.himawari

# Uninstall the package
sudo pip3 uninstall himawaripy

If you would like to share why, you can contact me on github or
[send an e-mail](mailto:bora@boramalper.org).

## Example
![Earth, as 2016/02/04/13:30:00 GMT](http://i.imgur.com/4XA6WaM.jpg)

## Attributions
Thanks to *[MichaelPote](https://github.com/MichaelPote)* for the [initial
implementation](https://gist.github.com/MichaelPote/92fa6e65eacf26219022) using
Expand Down
194 changes: 194 additions & 0 deletions himawaripy/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
#!/usr/bin/env python3

import argparse
from datetime import timedelta, datetime
import io
import itertools as it
import json
import multiprocessing as mp
import multiprocessing.dummy as mp_dummy
import os
import os.path as path
import sys
from time import strptime, strftime, mktime
import urllib.request
from glob import iglob, glob
import threading
import time

import appdirs
from PIL import Image
from dateutil.tz import tzlocal

from .utils import set_background, get_desktop_environment


# Semantic Versioning: Major, Minor, Patch
HIMAWARIPY_VERSION = (2, 0, 0)
counter = None
HEIGHT = 550
WIDTH = 550


def calculate_time_offset(latest_date, auto, preferred_offset):
if auto:
preferred_offset = int(datetime.now(tzlocal()).strftime("%z")[0:3])
print("Detected offset: UTC{:+03d}:00".format(preferred_offset))
if 11 >= preferred_offset > 10:
preferred_offset = 10
print("Offset is greater than +10, +10 will be used...")
elif 12 >= preferred_offset > 11:
preferred_offset = -12
print("Offset is greater than +10, -12 will be used...")

himawari_offset = 10 # UTC+10:00 is the time zone that himawari is over
offset = int(preferred_offset - himawari_offset)

offset_tmp = datetime.fromtimestamp(mktime(latest_date)) + timedelta(hours=offset)
offset_time = offset_tmp.timetuple()

return offset_time


def download_chunk(args):
global counter

x, y, latest, level = args
url_format = "http://himawari8.nict.go.jp/img/D531106/{}d/{}/{}_{}_{}.png"
url = url_format.format(level, WIDTH, strftime("%Y/%m/%d/%H%M%S", latest), x, y)

tiledata = download(url)

with counter.get_lock():
counter.value += 1
if counter.value == level * level:
print("Downloading tiles: completed.")
else:
print("Downloading tiles: {}/{} completed...".format(counter.value, level * level))
return x, y, tiledata


def parse_args():
parser = argparse.ArgumentParser(description="set (near-realtime) picture of Earth as your desktop background",
epilog="http://labs.boramalper.org/himawaripy")

parser.add_argument("--version", action="version", version="%(prog)s {}.{}.{}".format(*HIMAWARIPY_VERSION))

group = parser.add_mutually_exclusive_group()

group.add_argument("--auto-offset", action="store_true", dest="auto_offset", default=False,
help="determine offset automatically")
group.add_argument("-o", "--offset", type=int, dest="offset", default=10,
help="UTC time offset in hours, must be less than or equal to +10")

parser.add_argument("-l", "--level", type=int, choices=[4, 8, 16, 20], dest="level", default=4,
help="increases the quality (and the size) of each tile. possible values are 4, 8, 16, 20")
parser.add_argument("-d", "--deadline", type=int, dest="deadline", default=6,
help="deadline in minutes to download all the tiles, set 0 to cancel")
parser.add_argument("--save-battery", action="store_true", dest="save_battery", default=False,
help="stop refreshing on battery")
parser.add_argument("--output-dir", type=str, dest="output_dir",
help="directory to save the temporary background image",
default=appdirs.user_cache_dir(appname="himawaripy", appauthor=False))

args = parser.parse_args()

if not -12 <= args.offset <= 10:
sys.exit("OFFSET has to be between -12 and +10!\n")

if not args.deadline >= 0:
sys.exit("DEADLINE has to be greater than (or equal to if you want to disable) zero!\n")

return args


def is_discharging():
if not sys.platform.startswith("linux"): # I hope this will not end up like Windows 95/98 checks one day...
sys.exit("Battery saving feature works only on linux!\n")

if len(glob("/sys/class/power_supply/BAT*")) > 1:
print("Multiple batteries detected, using BAT0.")

with open("/sys/class/power_supply/BAT0/status") as f:
status = f.readline().strip()

return status == "Discharging"


def download(url):
exception = None

for i in range(1, 4): # retry max 3 times
try:
with urllib.request.urlopen(url) as response:
return response.read()
except Exception as e:
exception = e
print("[{}/3] Retrying to download '{}'...".format(i, url))
time.sleep(1)
pass

if exception:
raise exception
else:
sys.exit("Could not download '{}'!\n".format(url))


def thread_main(args):
global counter
counter = mp.Value("i", 0)

level = args.level # since we are going to use it a lot of times

print("Updating...")
latest_json = download("http://himawari8-dl.nict.go.jp/himawari8/img/D531106/latest.json")
latest = strptime(json.loads(latest_json.decode("utf-8"))["date"], "%Y-%m-%d %H:%M:%S")

print("Latest version: {} GMT.".format(strftime("%Y/%m/%d %H:%M:%S", latest)))
requested_time = calculate_time_offset(latest, args.auto_offset, args.offset)
if args.auto_offset or args.offset != 10:
print("Offset version: {} GMT.".format(strftime("%Y/%m/%d %H:%M:%S", requested_time)))

png = Image.new("RGB", (WIDTH * level, HEIGHT * level))

p = mp_dummy.Pool(level * level)
print("Downloading tiles...")
res = p.map(download_chunk, it.product(range(level), range(level), (requested_time,), (args.level,)))

for (x, y, tiledata) in res:
tile = Image.open(io.BytesIO(tiledata))
png.paste(tile, (WIDTH * x, HEIGHT * y, WIDTH * (x + 1), HEIGHT * (y + 1)))

for file in iglob(path.join(args.output_dir, "himawari-*.png")):
os.remove(file)

output_file = path.join(args.output_dir, strftime("himawari-%Y%m%dT%H%M%S.png", requested_time))
print("Saving to '%s'..." % (output_file,))
os.makedirs(path.dirname(output_file), exist_ok=True)
png.save(output_file, "PNG")

if not set_background(output_file):
sys.exit("Your desktop environment '{}' is not supported!\n".format(get_desktop_environment()))


def main():
args = parse_args()

print("himawaripy {}.{}.{}".format(*HIMAWARIPY_VERSION))

if args.save_battery and is_discharging():
sys.exit("Discharging!\n")

main_thread = threading.Thread(target=thread_main, args=(args,), name="himawaripy-main-thread", daemon=True)
main_thread.start()
main_thread.join(args.deadline * 60 if args.deadline else None)

if args.deadline and main_thread.is_alive():
sys.exit("Timeout!\n")

print()
sys.exit(0)


if __name__ == "__main__":
main()
18 changes: 0 additions & 18 deletions himawaripy/config.py

This file was deleted.

Loading

0 comments on commit a9fd7f5

Please sign in to comment.