homebridge-prayer-times 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Abdulaziz
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,196 @@
1
+ <p align="center">
2
+
3
+ <img src="https://raw.githubusercontent.com/homebridge/branding/latest/logos/homebridge-color-round-stylized.png" width="150">
4
+
5
+ </p>
6
+
7
+ <p align="center">
8
+ <a href="https://www.npmjs.com/package/homebridge-prayer-times"><img src="https://img.shields.io/npm/v/homebridge-prayer-times?style=for-the-badge" alt="npm version"></a>
9
+ <a href="https://www.npmjs.com/package/homebridge-prayer-times"><img src="https://img.shields.io/npm/dt/homebridge-prayer-times?style=for-the-badge" alt="npm downloads"></a>
10
+ <a href="https://github.com/aziz66/homebridge-prayer-times/stargazers"><img src="https://img.shields.io/github/stars/aziz66/homebridge-prayer-times?style=for-the-badge" alt="GitHub stars"></a>
11
+ <br>
12
+ <a href="https://github.com/aziz66/homebridge-prayer-times/issues"><img src="https://img.shields.io/github/issues/aziz66/homebridge-prayer-times?style=for-the-badge" alt="GitHub issues"></a>
13
+ <a href="https://github.com/aziz66/homebridge-prayer-times"><img src="https://img.shields.io/github/last-commit/aziz66/homebridge-prayer-times?style=for-the-badge" alt="GitHub last commit"></a>
14
+ <a href="https://github.com/aziz66/homebridge-prayer-times/releases"><img src="https://img.shields.io/github/v/release/aziz66/homebridge-prayer-times?style=for-the-badge" alt="GitHub release"></a>
15
+ <br>
16
+ <a href="https://www.npmjs.com/package/homebridge-prayer-times"><img src="https://img.shields.io/node/v/homebridge-prayer-times?style=for-the-badge" alt="Node.js version"></a>
17
+ <a href="https://www.npmjs.com/package/homebridge-prayer-times"><img src="https://img.shields.io/npm/l/homebridge-prayer-times?style=for-the-badge" alt="license"></a>
18
+ <a href="https://ko-fi.com/aziz66"><img src="https://img.shields.io/badge/Ko--fi-Support%20Me-FF5E5B?style=for-the-badge&logo=ko-fi&logoColor=white" alt="Ko-fi"></a>
19
+ </p>
20
+
21
+ # homebridge-prayer-times
22
+
23
+ Islamic prayer times as HomeKit sensors. Automate your home around salah times — dim lights at Maghrib, turn on lights at Fajr, and more.
24
+
25
+ ## What It Does
26
+
27
+ This Homebridge plugin fetches daily Islamic prayer times from the [AlAdhan API](https://aladhan.com) and exposes them as HomeKit motion and contact sensors. Since prayer times shift daily based on astronomical calculations, fixed-time HomeKit automations don't work — this plugin solves that.
28
+
29
+ Each prayer creates a **motion sensor** (triggers automations at adhan time) and a **contact sensor** (stays open for a configurable prayer window).
30
+
31
+ ## How It Appears in Apple Home
32
+
33
+ <p align="center">
34
+ <img src="homebridge_prayer_times_homekit_ux.svg" alt="HomeKit UX diagram showing prayer time accessories in Apple Home" width="680">
35
+ </p>
36
+
37
+ Each prayer appears as a native HomeKit accessory in your Home app. The plugin uses three types of sensors:
38
+
39
+ - **Motion Sensor** — triggers at adhan time, stays active for `motionDuration` minutes. This is what drives your automations.
40
+ - **Contact Sensor** — opens at adhan time, stays open for `windowDuration` minutes. Use for conditional automations like "while prayer window is open, keep lights dim."
41
+ - **Light Sensor** *(optional)* — shows minutes until the next prayer as a lux value. Enables threshold automations like "when countdown < 10, flash a light."
42
+
43
+ Optional **pre-adhan alert** sensors trigger before each prayer to give you a heads-up.
44
+
45
+ ## Example Automations
46
+
47
+ - **Fajr** motion detected → turn on hallway lights at 20%
48
+ - **Maghrib** motion detected → set living room to warm dim
49
+ - **Isha** motion detected → activate night mode scene
50
+ - **Sunrise** motion detected → open smart blinds
51
+ - **Dhuhr** contact open → set phone to Do Not Disturb (via Shortcuts)
52
+ - 15 min before **Dhuhr** → flash office light briefly (pre-adhan alert)
53
+ - During Ramadan: **Fajr** motion → turn on kitchen lights for suhoor
54
+
55
+ ## Installation
56
+
57
+ ### Via Homebridge UI (Recommended)
58
+
59
+ Search for `homebridge-prayer-times` in the Homebridge plugin tab and click Install.
60
+
61
+ ### Via npm
62
+
63
+ ```bash
64
+ npm install -g homebridge-prayer-times
65
+ ```
66
+
67
+ ## Configuration
68
+
69
+ Configure via the Homebridge UI settings form, or add manually to `config.json`:
70
+
71
+ ```json
72
+ {
73
+ "platforms": [
74
+ {
75
+ "platform": "PrayerTimes",
76
+ "name": "Prayer Times",
77
+ "location": {
78
+ "mode": "city",
79
+ "city": "Dubai",
80
+ "country": "United Arab Emirates"
81
+ },
82
+ "calculationMethod": 4,
83
+ "school": 0,
84
+ "motionDuration": 30,
85
+ "windowDuration": 30,
86
+ "preAdhanAlert": false,
87
+ "preAdhanMinutes": 15,
88
+ "showCountdown": false
89
+ }
90
+ ]
91
+ }
92
+ ```
93
+
94
+ ### Location Modes
95
+
96
+ - **City & Country** — simple, just enter your city and country names
97
+ - **Coordinates** — use latitude/longitude for precise location
98
+
99
+ ```json
100
+ "location": {
101
+ "mode": "coordinates",
102
+ "latitude": 25.2048,
103
+ "longitude": 55.2708
104
+ }
105
+ ```
106
+
107
+ ### Options
108
+
109
+ | Option | Default | Description |
110
+ |--------|---------|-------------|
111
+ | `calculationMethod` | 4 (Umm Al-Qura) | Prayer time calculation method |
112
+ | `school` | 0 (Shafi) | Asr calculation school |
113
+ | `timezone` | auto-detect | IANA timezone (e.g. `Asia/Dubai`) |
114
+ | `motionDuration` | 30 | Minutes the motion sensor stays active after adhan |
115
+ | `windowDuration` | 30 | Minutes the contact sensor stays open after adhan |
116
+ | `preAdhanAlert` | false | Create sensors that trigger before each prayer |
117
+ | `preAdhanMinutes` | 15 | Minutes before prayer for pre-adhan alert |
118
+ | `showCountdown` | false | Light sensor showing minutes until next prayer |
119
+ | `prayers.fajr` | true | Enable/disable individual prayers |
120
+
121
+ ### Sensor Behavior
122
+
123
+ | Time | Motion Sensor | Contact Sensor |
124
+ |------|---------------|----------------|
125
+ | Before prayer | `false` | Closed |
126
+ | At adhan time | `true` (for `motionDuration` min) | Open (for `windowDuration` min) |
127
+ | After window ends | `false` | Closed |
128
+
129
+ Both `motionDuration` and `windowDuration` can be configured independently. For example, you might want the motion trigger to last 5 minutes (just to fire automations) but the contact window to stay open for 60 minutes (to represent the prayer period).
130
+
131
+ ## How It Works
132
+
133
+ 1. At startup and daily at 00:05, the plugin fetches prayer times from the AlAdhan API
134
+ 2. Times are cached to disk so restarts don't require new API calls
135
+ 3. For each enabled prayer, a `setTimeout` is scheduled
136
+ 4. When the timer fires, the **motion sensor** triggers (stays active for `motionDuration` minutes)
137
+ 5. The **contact sensor** opens at adhan time and closes after `windowDuration` minutes
138
+ 6. HomeKit automations respond to these sensor state changes
139
+ 7. If Homebridge restarts mid-day, sensors resume their correct state based on elapsed time
140
+
141
+ ## Calculation Methods
142
+
143
+ | ID | Method | Region |
144
+ |----|--------|--------|
145
+ | 2 | Islamic Society of North America (ISNA) | North America |
146
+ | 3 | Muslim World League (MWL) | Europe, Far East |
147
+ | 4 | Umm Al-Qura University, Makkah | Arabian Peninsula |
148
+ | 5 | Egyptian General Authority of Survey | Africa, Middle East |
149
+ | 7 | Institute of Geophysics, University of Tehran | Iran |
150
+ | 8 | Gulf Region | UAE, Qatar, Kuwait, Bahrain |
151
+ | 9 | Kuwait | Kuwait |
152
+ | 10 | Qatar | Qatar |
153
+ | 11 | Majlis Ugama Islam Singapura (MUIS) | Singapore |
154
+ | 12 | Union des Organisations Islamiques de France | France |
155
+ | 13 | Diyanet Isleri Baskanligi | Turkey |
156
+ | 14 | Spiritual Administration of Muslims of Russia | Russia |
157
+ | 15 | Moonsighting Committee | Worldwide |
158
+ | 16 | Dubai (unofficial) | Dubai |
159
+ | 17 | JAKIM | Malaysia |
160
+ | 18 | Tunisia | Tunisia |
161
+ | 19 | Algeria | Algeria |
162
+ | 20 | KEMENAG | Indonesia |
163
+ | 21 | Morocco | Morocco |
164
+ | 22 | Portugal | Portugal |
165
+ | 23 | Jordan | Jordan |
166
+ | 1 | University of Islamic Sciences, Karachi | Pakistan |
167
+ | 0 | Shia Ithna-Ashari | Shia communities |
168
+
169
+ ## Troubleshooting
170
+
171
+ **No accessories appear**
172
+ - Ensure you have configured a location (city/country or coordinates) in the plugin settings
173
+ - Check Homebridge logs for error messages
174
+
175
+ **Prayer times seem wrong**
176
+ - Verify your calculation method matches your region
177
+ - Check your timezone setting (or leave blank for auto-detect)
178
+ - Hanafi users: set school to 1 for later Asr time
179
+
180
+ **API errors**
181
+ - The plugin retries with escalating backoff (5min, then 30min, then hourly) until it succeeds
182
+ - Cached times are used as a fallback while retrying
183
+ - Check your internet connection
184
+ - The AlAdhan API is free and doesn't require authentication
185
+
186
+ **Sensors stuck or not updating**
187
+ - Restart Homebridge — the plugin will re-fetch times and reschedule all sensors
188
+ - All sensor states reset cleanly at the daily 00:05 refresh
189
+
190
+ ## Credits
191
+
192
+ Prayer times provided by the [AlAdhan API](https://aladhan.com) — free, open, and no API key required.
193
+
194
+ ## License
195
+
196
+ Apache-2.0
@@ -0,0 +1,150 @@
1
+ {
2
+ "pluginAlias": "PrayerTimes",
3
+ "pluginType": "platform",
4
+ "singular": true,
5
+ "headerDisplay": "Islamic prayer times as HomeKit sensors. Automate your home around salah times.",
6
+ "footerDisplay": "Prayer times powered by [AlAdhan API](https://aladhan.com)",
7
+ "schema": {
8
+ "type": "object",
9
+ "properties": {
10
+ "name": {
11
+ "title": "Plugin Name",
12
+ "type": "string",
13
+ "default": "Prayer Times",
14
+ "required": true
15
+ },
16
+ "location": {
17
+ "title": "Location Settings",
18
+ "type": "object",
19
+ "properties": {
20
+ "mode": {
21
+ "title": "Location Mode",
22
+ "type": "string",
23
+ "default": "city",
24
+ "oneOf": [
25
+ { "title": "City & Country", "enum": ["city"] },
26
+ { "title": "Coordinates (Latitude/Longitude)", "enum": ["coordinates"] }
27
+ ]
28
+ },
29
+ "city": {
30
+ "title": "City",
31
+ "type": "string",
32
+ "placeholder": "e.g. Dubai",
33
+ "condition": { "functionBody": "return model.location.mode === 'city'" }
34
+ },
35
+ "country": {
36
+ "title": "Country",
37
+ "type": "string",
38
+ "placeholder": "e.g. United Arab Emirates",
39
+ "condition": { "functionBody": "return model.location.mode === 'city'" }
40
+ },
41
+ "latitude": {
42
+ "title": "Latitude",
43
+ "type": "number",
44
+ "placeholder": "e.g. 25.2048",
45
+ "condition": { "functionBody": "return model.location.mode === 'coordinates'" }
46
+ },
47
+ "longitude": {
48
+ "title": "Longitude",
49
+ "type": "number",
50
+ "placeholder": "e.g. 55.2708",
51
+ "condition": { "functionBody": "return model.location.mode === 'coordinates'" }
52
+ }
53
+ }
54
+ },
55
+ "calculationMethod": {
56
+ "title": "Calculation Method",
57
+ "type": "integer",
58
+ "default": 4,
59
+ "oneOf": [
60
+ { "title": "Islamic Society of North America (ISNA)", "enum": [2] },
61
+ { "title": "Muslim World League (MWL)", "enum": [3] },
62
+ { "title": "Umm Al-Qura University, Makkah", "enum": [4] },
63
+ { "title": "Egyptian General Authority of Survey", "enum": [5] },
64
+ { "title": "Institute of Geophysics, University of Tehran", "enum": [7] },
65
+ { "title": "Gulf Region", "enum": [8] },
66
+ { "title": "Kuwait", "enum": [9] },
67
+ { "title": "Qatar", "enum": [10] },
68
+ { "title": "Singapore (MUIS)", "enum": [11] },
69
+ { "title": "France (UOIF)", "enum": [12] },
70
+ { "title": "Turkey (Diyanet)", "enum": [13] },
71
+ { "title": "Russia", "enum": [14] },
72
+ { "title": "Moonsighting Committee", "enum": [15] },
73
+ { "title": "Dubai (unofficial)", "enum": [16] },
74
+ { "title": "JAKIM (Malaysia)", "enum": [17] },
75
+ { "title": "Tunisia", "enum": [18] },
76
+ { "title": "Algeria", "enum": [19] },
77
+ { "title": "KEMENAG (Indonesia)", "enum": [20] },
78
+ { "title": "Morocco", "enum": [21] },
79
+ { "title": "Portugal", "enum": [22] },
80
+ { "title": "Jordan", "enum": [23] },
81
+ { "title": "Karachi", "enum": [1] },
82
+ { "title": "Shia Ithna-Ashari", "enum": [0] }
83
+ ]
84
+ },
85
+ "school": {
86
+ "title": "Asr Calculation",
87
+ "type": "integer",
88
+ "default": 0,
89
+ "oneOf": [
90
+ { "title": "Shafi / Maliki / Hanbali (standard)", "enum": [0] },
91
+ { "title": "Hanafi (later Asr)", "enum": [1] }
92
+ ]
93
+ },
94
+ "timezone": {
95
+ "title": "Timezone",
96
+ "type": "string",
97
+ "placeholder": "e.g. Asia/Dubai (leave blank for auto-detect)",
98
+ "description": "IANA timezone. Leave blank to use system timezone."
99
+ },
100
+ "prayers": {
101
+ "title": "Prayers to Expose",
102
+ "type": "object",
103
+ "properties": {
104
+ "fajr": { "title": "Fajr", "type": "boolean", "default": true },
105
+ "sunrise": { "title": "Sunrise", "type": "boolean", "default": true },
106
+ "dhuhr": { "title": "Dhuhr", "type": "boolean", "default": true },
107
+ "asr": { "title": "Asr", "type": "boolean", "default": true },
108
+ "maghrib": { "title": "Maghrib", "type": "boolean", "default": true },
109
+ "isha": { "title": "Isha", "type": "boolean", "default": true }
110
+ }
111
+ },
112
+ "motionDuration": {
113
+ "title": "Motion Sensor Active Duration (minutes)",
114
+ "type": "integer",
115
+ "default": 30,
116
+ "minimum": 1,
117
+ "maximum": 120,
118
+ "description": "How long the motion sensor stays triggered after adhan time."
119
+ },
120
+ "windowDuration": {
121
+ "title": "Prayer Window Duration (minutes)",
122
+ "type": "integer",
123
+ "default": 30,
124
+ "minimum": 1,
125
+ "maximum": 360,
126
+ "description": "How long the contact sensor stays open after adhan time. Use this for automations like 'while prayer window is open, keep lights dim'."
127
+ },
128
+ "preAdhanAlert": {
129
+ "title": "Pre-Adhan Alert",
130
+ "type": "boolean",
131
+ "default": false,
132
+ "description": "Create additional motion sensors that trigger before each prayer."
133
+ },
134
+ "preAdhanMinutes": {
135
+ "title": "Pre-Adhan Alert Minutes",
136
+ "type": "integer",
137
+ "default": 15,
138
+ "minimum": 5,
139
+ "maximum": 60,
140
+ "condition": { "functionBody": "return model.preAdhanAlert === true" }
141
+ },
142
+ "showCountdown": {
143
+ "title": "Next Prayer Countdown",
144
+ "type": "boolean",
145
+ "default": false,
146
+ "description": "Show minutes until next prayer as a light sensor value."
147
+ }
148
+ }
149
+ }
150
+ }
@@ -0,0 +1,14 @@
1
+ import type { Logging } from 'homebridge';
2
+ import type { PrayerTimesConfig, PrayerTimings } from './settings.js';
3
+ export declare class AladhanApi {
4
+ private readonly config;
5
+ private readonly storagePath;
6
+ private readonly log;
7
+ private readonly cachePath;
8
+ constructor(config: PrayerTimesConfig, storagePath: string, log: Logging);
9
+ fetchTimings(date?: Date): Promise<PrayerTimings | null>;
10
+ private buildUrl;
11
+ private cleanTimings;
12
+ private readCache;
13
+ private writeCache;
14
+ }
@@ -0,0 +1,107 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import path from 'node:path';
3
+ export class AladhanApi {
4
+ config;
5
+ storagePath;
6
+ log;
7
+ cachePath;
8
+ constructor(config, storagePath, log) {
9
+ this.config = config;
10
+ this.storagePath = storagePath;
11
+ this.log = log;
12
+ this.cachePath = path.join(storagePath, 'prayer-times-cache.json');
13
+ }
14
+ async fetchTimings(date) {
15
+ const d = date ?? new Date();
16
+ const dateStr = `${String(d.getDate()).padStart(2, '0')}-${String(d.getMonth() + 1).padStart(2, '0')}-${d.getFullYear()}`;
17
+ // Check cache first
18
+ const cached = await this.readCache();
19
+ if (cached && cached.date === dateStr) {
20
+ this.log.debug('Using cached prayer times for', dateStr);
21
+ return cached.timings;
22
+ }
23
+ // Build API URL
24
+ const url = this.buildUrl(dateStr);
25
+ if (!url) {
26
+ return cached?.timings ?? null;
27
+ }
28
+ try {
29
+ this.log.info('Fetching prayer times from AlAdhan API for', dateStr);
30
+ const response = await fetch(url, { signal: AbortSignal.timeout(10000) });
31
+ const json = await response.json();
32
+ if (!response.ok || json.code !== 200 || !json.data?.timings) {
33
+ const detail = typeof json.data === 'string' ? json.data : json.status;
34
+ throw new Error(`API error (${json.code}): ${detail}`);
35
+ }
36
+ const timings = this.cleanTimings(json.data.timings);
37
+ const meta = json.data.meta;
38
+ await this.writeCache({
39
+ date: dateStr,
40
+ timings,
41
+ meta: { timezone: meta.timezone, method: meta.method.name },
42
+ });
43
+ this.log.info(`Prayer times fetched — timezone: ${meta.timezone}, method: ${meta.method.name}`);
44
+ return timings;
45
+ }
46
+ catch (error) {
47
+ this.log.error('Failed to fetch prayer times:', error.message);
48
+ if (cached) {
49
+ this.log.warn('Using cached prayer times (may be stale)');
50
+ return cached.timings;
51
+ }
52
+ return null;
53
+ }
54
+ }
55
+ buildUrl(dateStr) {
56
+ const loc = this.config.location;
57
+ if (!loc) {
58
+ this.log.error('No location configured');
59
+ return null;
60
+ }
61
+ const method = this.config.calculationMethod ?? 4;
62
+ const school = this.config.school ?? 0;
63
+ if (loc.mode === 'coordinates' && loc.latitude !== undefined && loc.longitude !== undefined) {
64
+ const tz = this.config.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone;
65
+ const base = `https://api.aladhan.com/v1/timings/${dateStr}`;
66
+ const params = `latitude=${loc.latitude}&longitude=${loc.longitude}`
67
+ + `&method=${method}&school=${school}&timezonestring=${encodeURIComponent(tz)}`;
68
+ return `${base}?${params}`;
69
+ }
70
+ if (loc.mode === 'city' && loc.city?.trim() && loc.country?.trim()) {
71
+ const city = loc.city.trim();
72
+ const country = loc.country.trim();
73
+ const base = `https://api.aladhan.com/v1/timingsByCity/${dateStr}`;
74
+ const params = `city=${encodeURIComponent(city)}`
75
+ + `&country=${encodeURIComponent(country)}&method=${method}&school=${school}`;
76
+ return `${base}?${params}`;
77
+ }
78
+ this.log.error('Invalid location configuration');
79
+ return null;
80
+ }
81
+ cleanTimings(timings) {
82
+ const cleaned = { ...timings };
83
+ for (const key of Object.keys(cleaned)) {
84
+ // Strip timezone suffixes like " (BST)" from "HH:mm (BST)"
85
+ cleaned[key] = cleaned[key].replace(/\s*\(.*\)$/, '');
86
+ }
87
+ return cleaned;
88
+ }
89
+ async readCache() {
90
+ try {
91
+ const data = await fs.readFile(this.cachePath, 'utf-8');
92
+ return JSON.parse(data);
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ }
98
+ async writeCache(cache) {
99
+ try {
100
+ await fs.writeFile(this.cachePath, JSON.stringify(cache, null, 2), 'utf-8');
101
+ }
102
+ catch (error) {
103
+ this.log.warn('Failed to write cache:', error.message);
104
+ }
105
+ }
106
+ }
107
+ //# sourceMappingURL=aladhanApi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aladhanApi.js","sourceRoot":"","sources":["../src/alad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