From b6e5efe2a51839e54e3febf42c6d140fa54bfae2 Mon Sep 17 00:00:00 2001 From: Mohamed Tahiri Date: Fri, 21 Jul 2023 02:53:52 +0200 Subject: [PATCH 1/6] First version --- custom_components/mawaqit/__init__.py | 38 +++++++++++++++++++++++---- custom_components/mawaqit/const.py | 4 +++ custom_components/mawaqit/mawaqit.py | 2 +- custom_components/mawaqit/sensor.py | 34 ++++++++++++++++-------- 4 files changed, 61 insertions(+), 17 deletions(-) diff --git a/custom_components/mawaqit/__init__.py b/custom_components/mawaqit/__init__.py index 07b47fb..6c7d8eb 100755 --- a/custom_components/mawaqit/__init__.py +++ b/custom_components/mawaqit/__init__.py @@ -217,6 +217,22 @@ def get_new_prayer_times(self): res['Next Salat Name']=salat_name[liste.index(min(liste))] #15 minutes before next salat res['Next Salat Preparation'] = (datetime.strptime(min(liste), '%Y-%m-%d %H:%M:%S')-timedelta(minutes=15)).strftime('%Y-%m-%d %H:%M:%S').split(" ",1)[1].rsplit(':', 1)[0] + + # if jumu'a is set as dhuhr, then jumu'a time is the same as dhuhr time + if data["jumuaAsDuhr"]: + res['Jumua'] = res['Dhuhr'] + elif data["jumua"] is not None: + res['Jumua'] = data["jumua"] + + # if mosque has 2 jumu'a, then the second jumu'a is Jumua 2, can be None. + if data["jumua2"] is not None: + res['Jumua 2'] = data["jumua2"] + + if data["aidPrayerTime"] is not None: + res['Aid'] = data["aidPrayerTime"] + if data["aidPrayerTime2"] is not None: + res['Aid 2'] = data["aidPrayerTime2"] + res['Mosque_label']=data["label"] res['Mosque_localisation']=data["localisation"] res['Mosque_url']=data["url"] @@ -331,14 +347,26 @@ async def async_update(self, *_): return for prayer, time in prayer_times.items(): - tomorrow=(dt_util.now().date()+timedelta(days=1)).strftime("%Y-%m-%d") - aujourdhui=dt_util.now().date() - maintenant = dt_util.now().time().strftime("%H:%M") + + tomorrow = (dt_util.now().date()+timedelta(days=1)).strftime("%Y-%m-%d") + aujourdhui = dt_util.now().date().strftime("%Y-%m-%d") + + maintenant = dt_util.now().time().strftime("%H:%M") + if is_date_parsing(time): if datetime.strptime(time, '%H:%M') < datetime.strptime(maintenant, '%H:%M'): - pray=tomorrow + pray = tomorrow else: - pray=aujourdhui + pray = aujourdhui + + if prayer == "Jumua" or prayer == "Jumua 2": + # On convertit la date en datetime pour pouvoir faire des calculs dessus. + pray_date = dt_util.strptime(pray, "%Y-%m-%d") + # Le calcul ci-dessous permet de rajouter le nombre de jours nécessaires pour arriver au prochain vendredi. + pray_date += timedelta(days=(4 - dt_util.now().weekday() + 7) % 7) + # On convertit la date en string pour pouvoir la mettre dans le dictionnaire. + pray = pray_date.strftime("%Y-%m-%d") + self.prayer_times_info[prayer] = dt_util.parse_datetime( f"{pray} {time}" ) diff --git a/custom_components/mawaqit/const.py b/custom_components/mawaqit/const.py index c1a6837..f1526a9 100755 --- a/custom_components/mawaqit/const.py +++ b/custom_components/mawaqit/const.py @@ -11,6 +11,10 @@ "Asr": "Adhan", "Maghrib": "Adhan", "Isha": "Adhan", + "Jumua": "Adhan", + "Jumua 2": "Adhan", + "Aid": "Adhan", + "Aid 2": "Adhan", "next_mawaqit": "time", "Fajr Iqama": "", "Dhuhr Iqama": "", diff --git a/custom_components/mawaqit/mawaqit.py b/custom_components/mawaqit/mawaqit.py index 9db74ce..e38e6ba 100755 --- a/custom_components/mawaqit/mawaqit.py +++ b/custom_components/mawaqit/mawaqit.py @@ -148,7 +148,7 @@ async def fetch_prayer_times(self) -> dict: 'Api-Access-Token': format(api_token)} api_url_base = 'https://mawaqit.net/api/2.0/' api_url = api_url_base + 'mosque/' + mosque_id + '/prayer-times' - + async with self.session.get(api_url, data=None, headers=headers) as response: if response.status != 200: raise NotAuthenticatedException diff --git a/custom_components/mawaqit/sensor.py b/custom_components/mawaqit/sensor.py index 5a357aa..3c46292 100755 --- a/custom_components/mawaqit/sensor.py +++ b/custom_components/mawaqit/sensor.py @@ -28,11 +28,15 @@ async def async_setup_entry(hass, config_entry, async_add_entities): entities = [] for sensor_type in SENSOR_TYPES: - if sensor_type in ["Fajr", "Shurouq", "Dhuhr", "Asr", "Maghrib", "Isha", "Fajr Iqama", "Shurouq Iqama", "Dhuhr Iqama", "Asr Iqama", "Maghrib Iqama", "Isha Iqama", "Next Salat Name", "Next Salat Time" ]: #add "Next Salat Preparation" to the list in case a sensor is needed 15 min before salat time - entities.append(MawaqitPrayerTimeSensor(sensor_type, client)) - - + if sensor_type in ["Fajr", "Shurouq", "Dhuhr", "Asr", "Maghrib", "Isha", + "Jumua", "Jumua 2", "Aid", "Aid 2", + "Fajr Iqama", "Shurouq Iqama", "Dhuhr Iqama", "Asr Iqama", "Maghrib Iqama", "Isha Iqama", + "Next Salat Name", "Next Salat Time"]: #add "Next Salat Preparation" to the list in case a sensor is needed 15 min before salat time + sensor = MawaqitPrayerTimeSensor(sensor_type, client) + if sensor.native_value is not None: + entities.append(sensor) async_add_entities(entities, True) + name = 'My Mosque' sensor1 = [MyMosqueSensor(name, hass)] async_add_entities(sensor1, True) @@ -77,12 +81,17 @@ def icon(self): @property def native_value(self): """Return the state of the sensor. .astimezone(dt_util.UTC)""" - if self.sensor_type in ["Fajr", "Shurouq", "Dhuhr", "Asr", "Maghrib", "Isha", "Next Salat Time", "Fajr Iqama", "Shurouq Iqama", "Dhuhr Iqama", "Asr Iqama", "Maghrib Iqama", "Isha Iqama", "Next Salat Preparation" ]: - return ( - self.client.prayer_times_info.get(self.sensor_type).astimezone( - dt_util.UTC - ) - ) + if self.sensor_type in ["Fajr", "Shurouq", "Dhuhr", "Asr", "Maghrib", "Isha", + "Jumua", "Jumua 2", "Aid", "Aid 2", + "Fajr Iqama", "Shurouq Iqama", "Dhuhr Iqama", "Asr Iqama", "Maghrib Iqama", "Isha Iqama", + "Next Salat Time", "Next Salat Preparation"]: + + time = self.client.prayer_times_info.get(self.sensor_type) + if time is not None: + return time.astimezone(dt_util.UTC) + else: + return None + else: return ( self.client.prayer_times_info.get(self.sensor_type) @@ -96,7 +105,10 @@ def should_poll(self): @property def device_class(self): """Return the device class.""" - if self.sensor_type in ["Fajr", "Shurouq", "Dhuhr", "Asr", "Maghrib", "Isha", "Next Salat Time", "Fajr Iqama", "Shurouq Iqama", "Dhuhr Iqama", "Asr Iqama", "Maghrib Iqama", "Isha Iqama", "Next Salat Preparation" ]: + if self.sensor_type in ["Fajr", "Shurouq", "Dhuhr", "Asr", "Maghrib", "Isha", + "Jumua", "Jumua 2", "Aid", "Aid 2", + "Fajr Iqama", "Shurouq Iqama", "Dhuhr Iqama", "Asr Iqama", "Maghrib Iqama", "Isha Iqama", + "Next Salat Time", "Next Salat Preparation"]: return DEVICE_CLASS_TIMESTAMP #else: # return str From 703162cbdd541fe61b5cf2b949c72cf9f029bd29 Mon Sep 17 00:00:00 2001 From: Mohamed Tahiri Date: Fri, 21 Jul 2023 02:59:28 +0200 Subject: [PATCH 2/6] modified: custom_components/mawaqit/__init__.py --- custom_components/mawaqit/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/mawaqit/__init__.py b/custom_components/mawaqit/__init__.py index 6c7d8eb..00db2d3 100755 --- a/custom_components/mawaqit/__init__.py +++ b/custom_components/mawaqit/__init__.py @@ -363,7 +363,7 @@ async def async_update(self, *_): # On convertit la date en datetime pour pouvoir faire des calculs dessus. pray_date = dt_util.strptime(pray, "%Y-%m-%d") # Le calcul ci-dessous permet de rajouter le nombre de jours nécessaires pour arriver au prochain vendredi. - pray_date += timedelta(days=(4 - dt_util.now().weekday() + 7) % 7) + pray_date += timedelta(days=(4 - pray_date.weekday() + 7) % 7) # On convertit la date en string pour pouvoir la mettre dans le dictionnaire. pray = pray_date.strftime("%Y-%m-%d") From 62074cb2148aa3345f089edc5c079cb37cdf666c Mon Sep 17 00:00:00 2001 From: mohaThr <98562658+mohaThr@users.noreply.github.com> Date: Fri, 21 Jul 2023 03:35:27 +0200 Subject: [PATCH 3/6] Fix Issue #36 --- custom_components/mawaqit/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/mawaqit/__init__.py b/custom_components/mawaqit/__init__.py index 00db2d3..b0b8d62 100755 --- a/custom_components/mawaqit/__init__.py +++ b/custom_components/mawaqit/__init__.py @@ -361,7 +361,7 @@ async def async_update(self, *_): if prayer == "Jumua" or prayer == "Jumua 2": # On convertit la date en datetime pour pouvoir faire des calculs dessus. - pray_date = dt_util.strptime(pray, "%Y-%m-%d") + pray_date = datetime.strptime(pray, "%Y-%m-%d") # Le calcul ci-dessous permet de rajouter le nombre de jours nécessaires pour arriver au prochain vendredi. pray_date += timedelta(days=(4 - pray_date.weekday() + 7) % 7) # On convertit la date en string pour pouvoir la mettre dans le dictionnaire. From 1a12639eff69046232b3e534f637dba5c5f364db Mon Sep 17 00:00:00 2001 From: Mohamed Tahiri Date: Thu, 14 Sep 2023 19:23:14 +0200 Subject: [PATCH 4/6] Fix issue #36 --- custom_components/mawaqit/__init__.py | 16 +++++++--------- custom_components/mawaqit/const.py | 4 ++-- custom_components/mawaqit/sensor.py | 9 ++++----- 3 files changed, 13 insertions(+), 16 deletions(-) diff --git a/custom_components/mawaqit/__init__.py b/custom_components/mawaqit/__init__.py index b0b8d62..7ff81f5 100755 --- a/custom_components/mawaqit/__init__.py +++ b/custom_components/mawaqit/__init__.py @@ -181,11 +181,11 @@ def get_new_prayer_times(self): #text_file.close() #readiding prayer times - f = open('{dir}/data/pray_time.txt'.format(dir=current_dir, name="" )) + f = open('{dir}/data/pray_time.txt'.format(dir=current_dir, name="")) data = json.load(f) calendar = data["calendar"] today = datetime.today() - index_month = month = today.month -1 + index_month = today.month - 1 month_times = calendar[index_month] index_day = today.day day_times = month_times[str(index_day)] @@ -194,14 +194,12 @@ def get_new_prayer_times(self): maintenant = today.time().strftime("%H:%M") - - day_times = month_times[str(index_day)] day_times_tomorrow = month_times[str(index_day+1)] maintenant = today.time().strftime("%H:%M") tomorrow=(datetime.today()+timedelta(days=1)).strftime("%Y-%m-%d") aujourdhui=(datetime.today()+timedelta(days=0)).strftime("%Y-%m-%d") - print(tomorrow) + liste=[] for j in range(len(salat_name)): if salat_name[j] == "Shurouq": @@ -228,10 +226,10 @@ def get_new_prayer_times(self): if data["jumua2"] is not None: res['Jumua 2'] = data["jumua2"] - if data["aidPrayerTime"] is not None: - res['Aid'] = data["aidPrayerTime"] - if data["aidPrayerTime2"] is not None: - res['Aid 2'] = data["aidPrayerTime2"] + #if data["aidPrayerTime"] is not None: + # res['Aid'] = data["aidPrayerTime"] + #if data["aidPrayerTime2"] is not None: + # res['Aid 2'] = data["aidPrayerTime2"] res['Mosque_label']=data["label"] res['Mosque_localisation']=data["localisation"] diff --git a/custom_components/mawaqit/const.py b/custom_components/mawaqit/const.py index f1526a9..cef8caf 100755 --- a/custom_components/mawaqit/const.py +++ b/custom_components/mawaqit/const.py @@ -13,8 +13,8 @@ "Isha": "Adhan", "Jumua": "Adhan", "Jumua 2": "Adhan", - "Aid": "Adhan", - "Aid 2": "Adhan", + #"Aid": "Adhan", + #"Aid 2": "Adhan", "next_mawaqit": "time", "Fajr Iqama": "", "Dhuhr Iqama": "", diff --git a/custom_components/mawaqit/sensor.py b/custom_components/mawaqit/sensor.py index 3c46292..8094d92 100755 --- a/custom_components/mawaqit/sensor.py +++ b/custom_components/mawaqit/sensor.py @@ -29,12 +29,11 @@ async def async_setup_entry(hass, config_entry, async_add_entities): entities = [] for sensor_type in SENSOR_TYPES: if sensor_type in ["Fajr", "Shurouq", "Dhuhr", "Asr", "Maghrib", "Isha", - "Jumua", "Jumua 2", "Aid", "Aid 2", + "Jumua", "Jumua 2", #"Aid", "Aid 2", "Fajr Iqama", "Shurouq Iqama", "Dhuhr Iqama", "Asr Iqama", "Maghrib Iqama", "Isha Iqama", "Next Salat Name", "Next Salat Time"]: #add "Next Salat Preparation" to the list in case a sensor is needed 15 min before salat time sensor = MawaqitPrayerTimeSensor(sensor_type, client) - if sensor.native_value is not None: - entities.append(sensor) + entities.append(sensor) async_add_entities(entities, True) name = 'My Mosque' @@ -82,7 +81,7 @@ def icon(self): def native_value(self): """Return the state of the sensor. .astimezone(dt_util.UTC)""" if self.sensor_type in ["Fajr", "Shurouq", "Dhuhr", "Asr", "Maghrib", "Isha", - "Jumua", "Jumua 2", "Aid", "Aid 2", + "Jumua", "Jumua 2", #"Aid", "Aid 2", "Fajr Iqama", "Shurouq Iqama", "Dhuhr Iqama", "Asr Iqama", "Maghrib Iqama", "Isha Iqama", "Next Salat Time", "Next Salat Preparation"]: @@ -106,7 +105,7 @@ def should_poll(self): def device_class(self): """Return the device class.""" if self.sensor_type in ["Fajr", "Shurouq", "Dhuhr", "Asr", "Maghrib", "Isha", - "Jumua", "Jumua 2", "Aid", "Aid 2", + "Jumua", "Jumua 2", #"Aid", "Aid 2", "Fajr Iqama", "Shurouq Iqama", "Dhuhr Iqama", "Asr Iqama", "Maghrib Iqama", "Isha Iqama", "Next Salat Time", "Next Salat Preparation"]: return DEVICE_CLASS_TIMESTAMP From 52ece0f10df0ae59b28ac0f5f61d9651aaff874c Mon Sep 17 00:00:00 2001 From: mohaThr <98562658+mohaThr@users.noreply.github.com> Date: Fri, 15 Sep 2023 18:52:25 +0200 Subject: [PATCH 5/6] Fix issue #36 and typos --- custom_components/mawaqit/__init__.py | 223 +++++++++++++------------- 1 file changed, 109 insertions(+), 114 deletions(-) diff --git a/custom_components/mawaqit/__init__.py b/custom_components/mawaqit/__init__.py index 7ff81f5..b31c70c 100755 --- a/custom_components/mawaqit/__init__.py +++ b/custom_components/mawaqit/__init__.py @@ -1,15 +1,17 @@ """The mawaqit_prayer_times component.""" -from datetime import timedelta import logging import os import json -import sys +# import sys import shutil -from datetime import datetime -#from mawaqit_times_calculator import MawaqitClient, exceptions -from .mawaqit import MawaqitClient, BadCredentialsException + +from datetime import datetime, timedelta +from dateutil import parser as date_parser + +from .mawaqit import BadCredentialsException #, MawaqitClient from requests.exceptions import ConnectionError as ConnError + import voluptuous as vol from homeassistant.config_entries import SOURCE_IMPORT @@ -18,9 +20,7 @@ from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.event import async_call_later, async_track_point_in_time import homeassistant.util.dt as dt_util -from homeassistant.helpers import aiohttp_client -from datetime import datetime, timedelta -from dateutil import parser as date_parser +# from homeassistant.helpers import aiohttp_client from .const import ( @@ -38,13 +38,13 @@ CALC_METHODS, ) -from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_PASSWORD, CONF_USERNAME, CONF_API_KEY, CONF_TOKEN - +# from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_PASSWORD, CONF_USERNAME, CONF_API_KEY, CONF_TOKEN _LOGGER = logging.getLogger(__name__) PLATFORMS = ["sensor"] + CONFIG_SCHEMA = vol.Schema( vol.All( cv.deprecated(DOMAIN), @@ -59,12 +59,14 @@ extra=vol.ALLOW_EXTRA, ) + def is_date_parsing(date_str): try: return bool(date_parser.parse(date_str)) except ValueError: return False - + + async def async_setup(hass, config): """Import the Mawaqit Prayer component from config.""" if DOMAIN in config: @@ -73,7 +75,6 @@ async def async_setup(hass, config): DOMAIN, context={"source": SOURCE_IMPORT}, data=config[DOMAIN] ) ) - return True @@ -91,8 +92,6 @@ async def async_setup_entry(hass, config_entry): return True - - async def async_unload_entry(hass, config_entry): """Unload Mawaqit Prayer entry from config_entry.""" current_dir = os.path.dirname(os.path.realpath(__file__)) @@ -108,10 +107,10 @@ async def async_unload_entry(hass, config_entry): except OSError as e: print("Error: %s : %s" % (dir_path, e.strerror)) - if hass.data[DOMAIN].event_unsub: hass.data[DOMAIN].event_unsub() hass.data.pop(DOMAIN) + return await hass.config_entries.async_unload_platforms(config_entry, PLATFORMS) @@ -127,138 +126,142 @@ def __init__(self, hass, config_entry): self.event_unsub = None - @property def calc_method(self): """Return the calculation method.""" return self.config_entry.options[CONF_CALC_METHOD] + def get_new_prayer_times(self): """Fetch prayer times for today.""" mawaqit_login = self.config_entry.data.get("username") mawaqit_password = self.config_entry.data.get("password") - mawaqit_latitude = self.config_entry.data.get("latitude") # self.hass.config.latitude - mawaqit_longitude = self.config_entry.data.get("longitude") #self.hass.config.longitude - - mosquee = self.config_entry.options.get("calculation_method") - - - + mawaqit_latitude = self.config_entry.data.get("latitude") + mawaqit_longitude = self.config_entry.data.get("longitude") + mosque = self.config_entry.options.get("calculation_method") current_dir = os.path.dirname(os.path.realpath(__file__)) - - - - name_servers=[] uuid_servers=[] CALC_METHODS=[] + with open('{}/data/all_mosquee_NN.txt'.format(current_dir), "r") as f: distros_dict = json.load(f) + for distro in distros_dict: name_servers.extend([distro["label"]]) uuid_servers.extend([distro["uuid"]]) CALC_METHODS.extend([distro["label"]]) - - - - if mosquee=="nearest" or mosquee=="no mosque in neighborhood" : + if mosque == "nearest" or mosque == "no mosque in neighborhood": indice = 0 else: - indice = name_servers.index(mosquee) - mosque_id = uuid_servers[indice] - - + indice = name_servers.index(mosque) - #update my_mosque file whenever the user changes it in the option - #f = open('{dir}/data/all_mosquee_NN.txt'.format(dir=current_dir )) - #data = json.load(f) - #text_file = open('{}/data/my_mosquee_NN.txt'.format(current_dir), "w") - #json.dump(data[indice], text_file) - #text_file.close() + mosque_id = uuid_servers[indice] - #readiding prayer times + # We get the prayer times of the year from pray_time.txt f = open('{dir}/data/pray_time.txt'.format(dir=current_dir, name="")) + data = json.load(f) calendar = data["calendar"] + + # Then, we get the prayer times of the day into this file today = datetime.today() index_month = today.month - 1 - month_times = calendar[index_month] + month_times = calendar[index_month] # Calendar of the month + index_day = today.day - day_times = month_times[str(index_day)] - salat_name = ["Fajr", "Shurouq", "Dhuhr", "Asr", "Maghrib", "Isha" ] - res = {salat_name[i]: day_times[i] for i in range(len(salat_name))} - - maintenant = today.time().strftime("%H:%M") - - day_times = month_times[str(index_day)] - day_times_tomorrow = month_times[str(index_day+1)] - maintenant = today.time().strftime("%H:%M") - tomorrow=(datetime.today()+timedelta(days=1)).strftime("%Y-%m-%d") - aujourdhui=(datetime.today()+timedelta(days=0)).strftime("%Y-%m-%d") - - liste=[] - for j in range(len(salat_name)): - if salat_name[j] == "Shurouq": - pray=tomorrow + " " +"23:59:00" #never account shurouq in the calculation of next_salat + day_times = month_times[str(index_day)] # Today's times + + prayer_names = ["Fajr", "Shurouq", "Dhuhr", "Asr", "Maghrib", "Isha" ] + res = {prayer_names[i]: day_times[i] for i in range(len(prayer_names))} + + try: + day_times_tomorrow = month_times[str(index_day + 1)] + except KeyError: + # If index_day + 1 == 32 (or 31) and the month contains only 31 (or 30) days + # We take the first prayer of the following month + day_times_tomorrow = calendar[index_month + 1]["1"] + + now = today.time().strftime("%H:%M") + + today = datetime.today().strftime("%Y-%m-%d") + tomorrow = (datetime.today() + timedelta(days=1)).strftime("%Y-%m-%d") + + prayers = [] + for j in range(len(prayer_names)): + if prayer_names[j] == "Shurouq": + pray = tomorrow + " " + "23:59:00" # We never take in account shurouq in the calculation of next_salat else: - if datetime.strptime(day_times[j], '%H:%M') < datetime.strptime(maintenant, '%H:%M'): - pray=tomorrow + " " + day_times_tomorrow[j] +":00" + if datetime.strptime(day_times[j], '%H:%M') < datetime.strptime(now, '%H:%M'): + pray = tomorrow + " " + day_times_tomorrow[j] + ":00" else: - pray=aujourdhui + " " + day_times[j] +":00" - liste.append(pray) - - res['Next Salat Time']=min(liste).split(" ",1)[1].rsplit(':', 1)[0] - res['Next Salat Name']=salat_name[liste.index(min(liste))] - #15 minutes before next salat - res['Next Salat Preparation'] = (datetime.strptime(min(liste), '%Y-%m-%d %H:%M:%S')-timedelta(minutes=15)).strftime('%Y-%m-%d %H:%M:%S').split(" ",1)[1].rsplit(':', 1)[0] + pray = today + " " + day_times[j] + ":00" + + prayers.append(pray) + + # Then the next prayer is the nearest prayer time, so the min of the prayers list + next_prayer = min(prayers) + res['Next Salat Time'] = next_prayer.split(" ", 1)[1].rsplit(':', 1)[0] + res['Next Salat Name'] = prayer_names[prayers.index(next_prayer)] + + minutes_bnp = 15 + # 15 minutes Before Next Prayer + res['Next Salat Preparation'] = (datetime.strptime(next_prayer, '%Y-%m-%d %H:%M:%S')-timedelta(minutes=minutes_bnp)).strftime('%Y-%m-%d %H:%M:%S').split(" ", 1)[1].rsplit(':', 1)[0] - # if jumu'a is set as dhuhr, then jumu'a time is the same as dhuhr time + # if Jumu'a is set as Dhuhr, then Jumu'a time is the same as Friday's Dhuhr time if data["jumuaAsDuhr"]: - res['Jumua'] = res['Dhuhr'] + # Then, Jumu'a time should be the Dhuhr time of the next Friday + today = datetime.today() + # We get the next Friday + next_friday = today + timedelta((4 - today.weekday() + 7) % 7) + # We get the next Friday's Dhuhr time from the calendar + next_friday_dhuhr = calendar[next_friday.month - 1][str(next_friday.day)][2] + res['Jumua'] = next_friday_dhuhr + + # If jumu'a is set as a specific time, then we use that time elif data["jumua"] is not None: res['Jumua'] = data["jumua"] - # if mosque has 2 jumu'a, then the second jumu'a is Jumua 2, can be None. + # if mosque has only one jumu'a, then 'Jumua 2' can be None. if data["jumua2"] is not None: res['Jumua 2'] = data["jumua2"] - #if data["aidPrayerTime"] is not None: - # res['Aid'] = data["aidPrayerTime"] - #if data["aidPrayerTime2"] is not None: - # res['Aid 2'] = data["aidPrayerTime2"] - res['Mosque_label']=data["label"] res['Mosque_localisation']=data["localisation"] - res['Mosque_url']=data["url"] + res['Mosque_url']=data["url"] res['Mosque_image']=data["image"] - #Iqama timing + # The Iqama countdown from Adhan is stored in pray_time.txt as well. iqamaCalendar = data["iqamaCalendar"] - iqama= iqamaCalendar[index_month][str(index_day)] + iqamas = iqamaCalendar[index_month][str(index_day)] # Today's iqama times. try: - iqama=[int(s.replace("+", "")) for s in iqama] + # The iqama countdown is stored as a string with a + sign. + # So, we need to remove the + and convert the countdown to an int. + iqamas = [int(countdown.replace("+", "")) for countdown in iqamas] except ValueError: - iqama = [0,0,0,0,0] + iqamas = [0, 0, 0, 0, 0] - salat=[datetime.strptime(s, '%H:%M') for s in day_times] - del salat[1] #no iqama for shurouq - iqama_list = [] - for (item1, item2) in zip(salat, iqama): - iqama_list.append((item1+ timedelta(minutes=item2)).strftime("%H:%M")) - iqama_name = ["Fajr Iqama", "Dhuhr Iqama", "Asr Iqama", "Maghrib Iqama", "Isha Iqama" ] - res1 = {iqama_name[i]: iqama_list[i] for i in range(len(iqama_name))} - res2 = {**res, **res1} - return res2 + # We store the prayer times of the day in HH:MM format. + prayers = [datetime.strptime(prayer, '%H:%M') for prayer in day_times] + del prayers[1] # Because there's no iqama for shurouq. - - + # We store the iqama times of the day in HH:MM format. + iqama_times = [] - + for (prayer, iqama) in zip(prayers, iqamas): + iqama_times.append((prayer + timedelta(minutes=iqama)).strftime("%H:%M")) + iqama_names = ["Fajr Iqama", "Dhuhr Iqama", "Asr Iqama", "Maghrib Iqama", "Isha Iqama"] + + res1 = {iqama_names[i]: iqama_times[i] for i in range(len(iqama_names))} + + res2 = {**res, **res1} + + return res2 async def async_schedule_future_update(self): @@ -298,20 +301,13 @@ async def async_schedule_future_update(self): midnight_dt = self.prayer_times_info["Next Salat Time"] Fajr_dt = self.prayer_times_info["Fajr"] Dhuhr_dt = self.prayer_times_info["Dhuhr"] - #Shurouq_dt = self.prayer_times_info["Shurouq"] Asr_dt = self.prayer_times_info["Asr"] Maghrib_dt = self.prayer_times_info["Maghrib"] Isha_dt = self.prayer_times_info["Isha"] - liste=[] - liste.append(Fajr_dt) - #liste.append(Shurouq_dt) - liste.append(Dhuhr_dt) - liste.append(Asr_dt) - liste.append(Maghrib_dt) - liste.append(Isha_dt) - midnight_dt = min(liste) - + prayer_times = [Fajr_dt, Dhuhr_dt, Asr_dt, Maghrib_dt, Isha_dt] + + midnight_dt = min(prayer_times) if now > dt_util.as_utc(midnight_dt): next_update_at = midnight_dt + timedelta(days=0, minutes=1, seconds=0) @@ -346,25 +342,24 @@ async def async_update(self, *_): for prayer, time in prayer_times.items(): - tomorrow = (dt_util.now().date()+timedelta(days=1)).strftime("%Y-%m-%d") - aujourdhui = dt_util.now().date().strftime("%Y-%m-%d") + tomorrow = (dt_util.now().date() + timedelta(days=1)).strftime("%Y-%m-%d") + today = dt_util.now().date().strftime("%Y-%m-%d") - maintenant = dt_util.now().time().strftime("%H:%M") + now = dt_util.now().time().strftime("%H:%M") if is_date_parsing(time): - if datetime.strptime(time, '%H:%M') < datetime.strptime(maintenant, '%H:%M'): + if datetime.strptime(time, '%H:%M') < datetime.strptime(now, '%H:%M'): pray = tomorrow else: - pray = aujourdhui + pray = today if prayer == "Jumua" or prayer == "Jumua 2": - # On convertit la date en datetime pour pouvoir faire des calculs dessus. + # We convert the date to datetime to be able to do calculations on it. pray_date = datetime.strptime(pray, "%Y-%m-%d") - # Le calcul ci-dessous permet de rajouter le nombre de jours nécessaires pour arriver au prochain vendredi. + # The calculation below allows to add the number of days necessary to arrive at the next Friday. pray_date += timedelta(days=(4 - pray_date.weekday() + 7) % 7) - # On convertit la date en string pour pouvoir la mettre dans le dictionnaire. + # We convert the date to string to be able to put it in the dictionary. pray = pray_date.strftime("%Y-%m-%d") - self.prayer_times_info[prayer] = dt_util.parse_datetime( f"{pray} {time}" ) @@ -374,11 +369,12 @@ async def async_update(self, *_): await self.async_schedule_future_update() - _LOGGER.debug("New prayer times retrieved. Updating sensors") + _LOGGER.debug("New prayer times retrieved. Updating sensors.") async_dispatcher_send(self.hass, DATA_UPDATED) async def async_setup(self): """Set up the Mawaqit prayer client.""" + await self.async_add_options() try: @@ -386,7 +382,6 @@ async def async_setup(self): except (BadCredentialsException, ConnError) as err: raise ConfigEntryNotReady from err - await self.async_update() self.config_entry.add_update_listener(self.async_options_updated) From 58cecf06a62aaefaeab9fa137c255aaf0ff9a994 Mon Sep 17 00:00:00 2001 From: mohaThr <98562658+mohaThr@users.noreply.github.com> Date: Thu, 21 Sep 2023 09:49:32 +0200 Subject: [PATCH 6/6] Update variable names --- custom_components/mawaqit/__init__.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/custom_components/mawaqit/__init__.py b/custom_components/mawaqit/__init__.py index b31c70c..a74078d 100755 --- a/custom_components/mawaqit/__init__.py +++ b/custom_components/mawaqit/__init__.py @@ -208,9 +208,10 @@ def get_new_prayer_times(self): res['Next Salat Time'] = next_prayer.split(" ", 1)[1].rsplit(':', 1)[0] res['Next Salat Name'] = prayer_names[prayers.index(next_prayer)] - minutes_bnp = 15 # 15 minutes Before Next Prayer - res['Next Salat Preparation'] = (datetime.strptime(next_prayer, '%Y-%m-%d %H:%M:%S')-timedelta(minutes=minutes_bnp)).strftime('%Y-%m-%d %H:%M:%S').split(" ", 1)[1].rsplit(':', 1)[0] + countdown_next_prayer = 15 + res['Next Salat Preparation'] = (datetime.strptime(next_prayer, '%Y-%m-%d %H:%M:%S')-timedelta(minutes=countdown_next_prayer)).strftime('%Y-%m-%d %H:%M:%S').split(" ", 1)[1].rsplit(':', 1)[0] + # if Jumu'a is set as Dhuhr, then Jumu'a time is the same as Friday's Dhuhr time if data["jumuaAsDuhr"]: