Created
July 28, 2017 20:30
-
-
Save lukas-hetzenecker/a986ada705767b6d3eab9912c21f4d81 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# weatherservice.py | |
import asyncio | |
import aiohttp | |
from PyQt5.QtCore import pyqtProperty, pyqtSignal, QObject | |
base_url = 'http://api.openweathermap.org/data/2.5/' | |
HEADERS = { | |
'user-agent': ('smart-mirror [email protected]'), | |
} | |
class WeatherService(QObject): | |
weatherChanged = pyqtSignal() | |
cityChanged = pyqtSignal() | |
keyChanged = pyqtSignal() | |
def __init__(self, parent=None): | |
super().__init__(parent) | |
self._city = '' | |
self._key = '' | |
self._temperature = 0 | |
@pyqtProperty('QString', notify=cityChanged) | |
def city(self): | |
return self._city | |
@city.setter | |
def city(self, city): | |
self._city = city | |
self.cityChanged.emit() | |
print("City changed to", city) | |
asyncio.ensure_future(self._update()) | |
@pyqtProperty('QString', notify=keyChanged) | |
def key(self): | |
return self._key | |
@key.setter | |
def key(self, key): | |
self._key = key | |
self.keyChanged.emit() | |
print("Key changed to", key) | |
asyncio.ensure_future(self._update()) | |
@pyqtProperty(int, notify=weatherChanged) | |
def temperature(self): | |
return self._temperature | |
async def _update(self): | |
if not (self._key and self._city): | |
return | |
print("update weather!") | |
url = base_url + 'weather' | |
params = { | |
'q': self._city, | |
'APPID': self._key, | |
'units': 'metric' | |
} | |
async with aiohttp.ClientSession() as session: | |
async with session.get(url, headers=HEADERS, params=params) as resp: | |
print(resp) | |
data = await resp.json() | |
print(data) | |
self._temperature = round(data['main']['temp']) | |
self.weatherChanged.emit() | |
# weatherplugin.py | |
from PyQt5.QtQml import qmlRegisterType, QQmlExtensionPlugin | |
from weatherservice import WeatherService | |
class ChartsPlugin(QQmlExtensionPlugin): | |
def registerTypes(self, uri): | |
qmlRegisterType(WeatherService, "Weather", 1, 0, "WeatherService") | |
# main.py | |
from quamash import QEventLoop, QThreadExecutor | |
from dbus.mainloop.pyqt5 import DBusQtMainLoop | |
DBusQtMainLoop(set_as_default=True) | |
# Create the application instance. | |
app = QApplication(sys.argv) | |
loop = QEventLoop(app) | |
asyncio.set_event_loop(loop) | |
# TODO: more init stuff... | |
with loop: ## context manager calls .close() when loop completes, and releases all resources | |
loop.run_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment