Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Ardupilot
GitHub Repository: Ardupilot/ardupilot
Path: blob/master/Tools/cameras_gimbals/xfrobot-download/xfrobot-download.py
4232 views
1
#!/usr/bin/env python3
2
3
# flake8: noqa
4
5
"""
6
Downloads image and video files from an XFRobot camera connected via ethernet
7
"""
8
9
import os
10
import re
11
from argparse import ArgumentParser
12
from urllib.request import urlretrieve, urlopen
13
from urllib.error import URLError, HTTPError
14
from html.parser import HTMLParser
15
16
# prefix string for output
17
prefix_str = "xfrobot-download.py: "
18
ip_address_default = "192.168.144.108"
19
20
# directory suffixes
21
MEDIA_DIRS = {
22
"image": "IMG",
23
"video": "VID"
24
}
25
26
# HTML parser to extract links from HTML pages
27
class LinkExtractor(HTMLParser):
28
def __init__(self):
29
super().__init__()
30
self.links = []
31
32
def handle_starttag(self, tag, attrs):
33
if tag == 'a':
34
for attr in attrs:
35
if attr[0] == 'href':
36
self.links.append(attr[1])
37
38
# extract file links from HTML page
39
def extract_file_links(base_url):
40
try:
41
with urlopen(base_url) as response:
42
html = response.read().decode('utf-8')
43
parser = LinkExtractor()
44
parser.feed(html)
45
return [link for link in parser.links if re.search(r'\.(jpg|jpeg|png|mp4|mov)$', link, re.IGNORECASE)]
46
except Exception as e:
47
print(prefix_str + f"Failed to fetch or parse URL {base_url}: {e}")
48
return []
49
50
# download files from the given list of links
51
# returns the number of successfully downloaded files
52
def download_files(base_url, links, dest_dir):
53
count = 0
54
for link in links:
55
filename = os.path.basename(link)
56
full_url = link if link.startswith("http") else base_url + filename
57
dest_path = os.path.join(dest_dir, filename)
58
print(prefix_str + f"Downloading {filename} from {full_url}")
59
try:
60
urlretrieve(full_url, dest_path)
61
count += 1
62
except (URLError, HTTPError) as e:
63
print(prefix_str + f"Failed to download {filename}: {e}")
64
return count
65
66
# main function
67
def main():
68
parser = ArgumentParser(description="Download files from an XFRobot camera")
69
parser.add_argument("--ipaddr", default=ip_address_default, help="IP address of camera")
70
parser.add_argument("--dest", default=".", help="Destination directory")
71
args = parser.parse_args()
72
73
if not os.path.exists(args.dest):
74
print(prefix_str + "Invalid destination directory")
75
return
76
77
for media_type, subdir in MEDIA_DIRS.items():
78
print(prefix_str + f"Fetching {media_type} files")
79
base_url = f"http://{args.ipaddr}/static/{subdir}/"
80
links = extract_file_links(base_url)
81
count = download_files(base_url, links, args.dest)
82
print(prefix_str + f"Downloaded {count} {media_type} file(s)")
83
84
if __name__ == "__main__":
85
main()
86
87