class RestSpecial():
    api_key = None
    rest_caller = None

    def __init__(self):
        self.rest_caller = Rest()
        self.f = FileHandler()
     
    # https://openweathermap.org/api/air-pollution
    def call_server_pollution(self, call_params: dict) -> dict:
        """
        params: call_params { "lat": "", "lon": "", "units": "", "language": "", "key": ""}
        """
        data = None
        lat = call_params['lat']
        lon = call_params['lon']
        units = call_params['units']
        language = call_params['language']
        key = call_params['key']
        path = "http://api.openweathermap.org/data/2.5/air_pollution?lat={}&lon={}&units={}&lang={}&appid={}".format(lat, lon, units, language, key)
        data = self.rest_caller.rest_call_get(path=path, headers={}, params={})
        if data['code'] == 200:
            logger.info("Weather API Call was successful.")
        else:
            logger.info("Weather API Call was not successful!")
        return data

    def call_server_weather(self, call_params: dict) -> dict:
        """
        params: call_params { "city": "", "units": "", "language": "", "key": ""}
        """
        data = None
        
        key = call_params['key']
        city = call_params['city']
        units = call_params['units']
        language = call_params['language']
        path = "http://api.openweathermap.org/data/2.5/weather?q={}&units={}&lang={}&appid={}".format(city, units, language, key)

        data = self.rest_caller.rest_call_get(path=path, headers={}, params={})
        if data['code'] == 200:
            logger.info("Weather API Call was successful.")
        else:
            logger.info("Weather API Call was not successful!")
        return data
    
    def save_data(self, data: dict, filename="./data/test.json") -> None:
        try:
            self.f.write_jsonfile(filename=filename, filedata=data)
        except Exception as e:
            logger.error("File saveing went wrong for File: {}\n With Exception: {}".format(filename, e))
        

    def load_data(self, filename="./data/test.json") -> dict:
        try:
            loaded_data = self.f.read_jsonfile(filename=filename)
            if "error" in loaded_data:
                logger.error("File loading went wrong for File: {}".format(filename))
                return {}
            else:
                return loaded_data
        except Exception as e:
            logger.error("File loading went wrong for File: {}\n With Exception: {}".format(filename, e))
    
    def get_data_age_str(self, filename: str) -> str:
        if self.f.is_file(filename):
            last_mod_time_str = self.f.getLastModificationTimeString(filename)
            return last_mod_time_str
        else:
            now = datetime.now()
            date_time = now.strftime("%d.%m.%Y, %H:%M:%S")
            return date_time

    def get_data_age(self, filename: str) -> datetime:
        if self.f.is_file(filename):
            last_mod_time = self.f.getLastModificationTime(filename)
            return last_mod_time
        else:
            return datetime.now()
    
    def dataTimeDiff(self, filename: str, timediff=3600) -> int:
        if self.f.is_file(filename):
            date_obj = self.f.getLastModificationTime(filename)
            diff = datetime.now() - date_obj
            diff_in_hours = diff.total_seconds() // timediff
            return int(diff_in_hours)
        else:
            return 0
Exemplo n.º 2
0
class Weather(Base):
    def __init__(self,
                 observer: Observer,
                 name: str,
                 foreground_color="#ffffff",
                 font_name=""):
        super().__init__(observer, name, foreground_color, font_name)

        self.foreground_color = foreground_color
        self.name = "Weather"
        self.font_name = font_name

        self.main_layout = QVBoxLayout()
        self.setLayout(self.main_layout)

        self.start_widget = StartWidget(self, self.foreground_color,
                                        self.font_name)
        self.main_layout.addWidget(self.start_widget)

        self.r = RestSpecial()
        self.data = None
        self.file_handler = FileHandler()

        self.time_periode = 3600
        self.load_start_config()

    def load_start_config(self):
        config = self.r.load_data(
            "./subscreens/weather_pkg/weather_app_config.json")
        print("load_start_conifg", config)
        if config.get("error") is None:
            self.time_periode = float(config["time_periode"])
            key = config["key"]
            language = config["language"]
            self.start_widget.set_key(key)
            self.start_widget.set_language(language)
            cities = config["cities"]
            for city in cities:

                if city["name"]:
                    self.start_widget.create_new_city(
                        city["name"], UnitSystem[city["unit_system"]])
        else:
            log.error("error: weather_app_config.json not loaded")

    def save_config(self, config: dict):
        config["time_periode"] = self.time_periode
        self.r.save_data(config,
                         "./subscreens/weather_pkg/weather_app_config.json")

    def get_data(self, config: dict) -> dict:
        # TODO: read from config dictionary call param data
        city = "Berlin"
        filepath_str = "./data/weather_{}.json".format(city)

        # check time age
        log.debug("Last time file was modified: {}".format(
            self.r.get_data_age_str(filepath_str)))
        log.debug("Diff in hours: {}h".format(
            self.r.dataTimeDiff(filepath_str)))
        if self.r.dataTimeDiff(
                filepath_str, self.time_periode
        ) >= 1 or not self.file_handler.is_file(filepath_str):
            log.info("call server")
            self.call_server(city=city, language="de")
            self.save_data(filepath=filepath_str)
        # keep old Data
        # TODO: create a toggle/switch/config param for this threshold calling server for new data or not
        elif self.r.dataTimeDiff(filepath_str, self.time_periode) < 1:
            self.load_data(filepath=filepath_str)
        return self.data

    def save_data(self, filepath: str):
        self.r.save_data(data=self.data, filename=filepath)

    def load_data(self, filepath: str):
        self.data = self.r.load_data(filename=filepath)

    def showData(self):
        if self.data is not None:
            self.label.setText("{}°C".format(self.data['main']['temp']))
        else:
            self.label.setText("{}°C".format(
                self.data["data"]['main']['temp']))

    def call_server(self, city: str, language: str) -> dict:
        """
        returns dictionary with response from Rest
        if response HTTP Status != 200 returns None
        """
        if not city:
            city = "Berlin"
        if not language:
            language = "de"  # en, fr, ... , https://openweathermap.org/current#multi

        call_parameter = {
            "city": city,
            "units": "metric",
            "language": language,
            "key": "36dcf663b6964439a18574709e1d6eef"
        }
        new_data = self.r.call_server_weather(call_parameter)
        if new_data['code'] == 200:
            self.data = new_data['data']
        else:
            # check if self.data contains old data, if not set to empty dictionary,
            # it will raise in exception in higher order class, for empty dictionary entrys
            if not self.data:
                self.data = {}
        return self.data