-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgtk.py
180 lines (152 loc) · 6.52 KB
/
gtk.py
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("WebKit2", "4.1")
from gi.repository import Gtk, WebKit2, GdkPixbuf, GLib, Gdk
import os
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
from matplotlib.ticker import FuncFormatter
from mpl_toolkits.axisartist.parasite_axes import HostAxes
import time as timeLib
import requests
from datetime import datetime
import math
import threading
import asyncio
# Configurazione
LIVE_URL_ID = "xRPjKQtRXR8" # ID DELLA LIVE
LAYOUT = "vertical" # "vertical" o "horizontal" | "vertical": grafico a sinistra e live a destra; "horizontal": grafico sopra e live sotto
FULLSCREEN = False # Mostra la finestra in modalità fullscreen
URL = "https://api.wheretheiss.at/v1/satellites/25544"
MAX_DATA_STORE_LEN = 5 # Numero massimo di dati da memorizzare
POLLING_DELAY = 10 # In secondi
REQ_TIMEOUT = 7 # Secondi massimi prima che la richiesta venga interrotta
OUTPUT_DPI = 300 # Dpi dell'output (grandezza dell'immagine). Abbassare se diventa troppo lento a renderizzare
# Store di dati.
time = [] # Tempo (in unix), asse x
latitude = [] # Latitudine
longitude = [] # Longitudine
altitude = [] # Altitudine
os.environ["WEBKIT_DISABLE_DMABUF_RENDERER"] = "1" # Risolve il problema "AcceleratedSurfaceDMABuf was unable to construct a complete framebuffer"
os.unsetenv("SESSION_MANAGER") # Disattiva l'avviso "Qt: Session management error: None of the authentication protocols specified are supported"
def toDate(unix, pos):
return datetime.fromtimestamp(unix).strftime("%H:%M:%S")
FORMATTER = FuncFormatter(toDate)
def updateLocation():
try:
res = requests.get(URL, timeout=REQ_TIMEOUT).json()
pos = {}
if len(time) > MAX_DATA_STORE_LEN:
time.pop(0)
if len(latitude) > MAX_DATA_STORE_LEN:
latitude.pop(0)
if len(longitude) > MAX_DATA_STORE_LEN:
longitude.pop(0)
if len(altitude) > MAX_DATA_STORE_LEN:
altitude.pop(0)
time.append(math.floor(datetime.timestamp(datetime.now())))
latitude.append(float(res["latitude"]))
longitude.append(float(res["longitude"]))
altitude.append(round(float(res["altitude"]), 1))
print("✅ Posizione ottenuta con successo")
return True # Successo
except [ValueError, TimeoutError] as e:
print(e)
print("⚠️ Errore nell'ottenimento della posizione")
timeLib.sleep(1)
return False # Errore
def genGraph():
# Ottieni figura
fig = plt.figure(figsize=(10, 6))
# Creazione del grafico
host = fig.add_axes([0.15, 0.1, 0.65, 0.8], axes_class=HostAxes)
par1 = host.get_aux_axes(viewlim_mode=None, sharex=host)
par2 = host.get_aux_axes(viewlim_mode=None, sharex=host)
# Imposta la posizione dei margini e etichette per host e parassiti
host.axis["right"].set_visible(False)
par1.axis["right"].set_visible(True)
par1.axis["right"].major_ticklabels.set_visible(True)
par1.axis["right"].label.set_visible(True)
par2.axis["right2"] = par2.new_fixed_axis(loc="right", offset=(78, 0))
# Imposta le etichette
host.set_xlabel("Tempo")
host.set_ylabel("Latitudine")
par1.set_ylabel("Longitudine")
par2.set_ylabel("Altitudine (Km)")
host.xaxis.set_major_formatter(FORMATTER)
host.set_title("Posizione dell'ISS")
latp, = host.plot(time, latitude, label="Latitudine", marker="o")
lonp, = par1.plot(time, longitude, label="Longitudine", marker="o")
altp, = par2.plot(time, altitude, label="Altitudine", marker="o", color="green")
host.set_xticks(time)
host.set_yticks(latitude)
par1.set_yticks(longitude)
par2.set_yticks(altitude)
host.yaxis.get_label().set_color(latp.get_color())
par1.yaxis.get_label().set_color(lonp.get_color())
par2.yaxis.get_label().set_color(altp.get_color())
host.tick_params(axis="y")
par1.tick_params(axis="y")
par2.tick_params(axis="y")
host.legend(labelcolor="linecolor")
host.grid(True, alpha=0.5)
plt.xticks(rotation=20)
plt.savefig("output.png", dpi=OUTPUT_DPI)
plt.clf()
print("✅ Grafico generato con successo")
class Window(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Tracker ISS")
if (FULLSCREEN): Gtk.Window.fullscreen(self)
self.set_default_size(800, 600)
CURRENT_ORIENTATION = Gtk.Orientation.HORIZONTAL if LAYOUT == "vertical" else Gtk.Orientation.VERTICAL
box = Gtk.Box(orientation=CURRENT_ORIENTATION, spacing=10)
self.add(box)
self.default_image = Gtk.Image()
IMG_SIZE = {}
if LAYOUT == "vertical": IMG_SIZE = {"width": 400, "height": 600}
else: IMG_SIZE = {"width": 600, "height": 400}
self.pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename="output.png", width=IMG_SIZE['width'], height=IMG_SIZE['height'], preserve_aspect_ratio=True)
self.image = Gtk.Image.new_from_pixbuf(self.pixbuf)
context = Gtk.StyleContext()
box.pack_start(self.image, False, False, 0)
# Crea WebView
self.webview = WebKit2.WebView()
box.pack_start(
self.webview, True, True, 0
)
# Carica diretta yt
youtube_url = f"https://www.youtube-nocookie.com/embed/{LIVE_URL_ID}?autoplay=1&mute=1&controls=0"
self.webview.load_uri(youtube_url)
self.connect("delete-event", self.set_running)
GLib.timeout_add_seconds(2, self.reload_img, self.image)
def reload_img(self, widget, event=None):
try:
width = self.get_size()[0]
height = self.get_size()[1]
finalW = width / 2 if LAYOUT == "vertical" else -1
finalH = height / 2 if LAYOUT == "horizontal" else -1
self.image.set_size_request(finalW, finalH)
self.pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename="output.png", width=finalW, height=finalH, preserve_aspect_ratio=True)
self.image.set_from_pixbuf(self.pixbuf)
except Exception as e: None
#print(e)
return True
def set_running(self, widget, boh):
os._exit(0)
def launchGUI():
win = Window()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
print("> Avvio della GUI")
t1 = threading.Thread(target=launchGUI)
t1.start()
while True:
print("Ottenendo la positizone")
if not updateLocation(): continue
print("Generando il grafico")
try: genGraph()
except Exception as e: print(e)
print(f"Prossimo aggiornamento in {POLLING_DELAY} secondi...")
timeLib.sleep(POLLING_DELAY)