File: firmware.py

package info (click to toggle)
zigpy-zigate 0.13.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 288 kB
  • sloc: python: 2,167; makefile: 3
file content (76 lines) | stat: -rw-r--r-- 2,396 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import argparse
from collections import OrderedDict
import json
import logging
import os
import urllib.request

URL = "https://api.github.com/repos/fairecasoimeme/ZiGate/releases"
LOGGER = logging.getLogger("ZiGate Firmware")


def get_releases():
    LOGGER.info("Searching for ZiGate firmware")
    releases = OrderedDict()
    r = urllib.request.urlopen(URL)
    if r.status == 200:
        for release in json.loads(r.read()):
            if release.get("draft"):
                continue
            if release.get("prerelease"):
                continue
            for asset in release["assets"]:
                if "pdm" in asset["name"].lower():
                    continue
                if asset["name"].endswith(".bin"):
                    LOGGER.info("Found %s", asset["name"])
                    releases[asset["name"]] = asset["browser_download_url"]
    return releases


def download(url, dest="/tmp"):
    filename = url.rsplit("/", 1)[1]
    LOGGER.info("Downloading %s to %s", url, dest)
    r = urllib.request.urlopen(url)
    if r.status == 200:
        filename = os.path.join(dest, filename)
        with open(filename, "wb") as fp:
            fp.write(r.read())
        LOGGER.info("Done")
        return filename
    else:
        LOGGER.error("Error downloading %s %s", r.status, r.reason)


def download_latest(dest="/tmp"):
    LOGGER.info("Download latest firmware")
    releases = get_releases()
    if releases:
        latest = list(releases.keys())[0]
        LOGGER.info("Latest is %s", latest)
        return download(releases[latest], dest)


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "command",
        help="Command to start",
        choices=["list", "download", "download-latest"],
    )
    parser.add_argument("--url", help="Download URL")
    parser.add_argument(
        "--dest", help="Download folder, default to /tmp", default="/tmp"
    )
    args = parser.parse_args()
    if args.command == "list":
        for k, v in get_releases().items():
            print(k, v)
    elif args.command == "download":
        if not args.url:
            LOGGER.error("You have to give a URL to download using --url")
        else:
            download(args.url, args.dest)
    elif args.command == "download-latest":
        download_latest(args.dest)