@yunlefun-home/air-conditioner-core 0.2.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019 YunYouJun 云游君 <me@yunyoujun.cn>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,24 @@
1
+ # @yunlefun-home/air-conditioner-core
2
+
3
+ Framework-agnostic state, reducer, persistence, audio, and notification helpers for [Yun Air Conditioner](https://ac.yunyoujun.cn/).
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add @yunlefun-home/air-conditioner-core
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```ts
14
+ import { createAirConditionerStore } from '@yunlefun-home/air-conditioner-core'
15
+
16
+ const store = createAirConditionerStore()
17
+ store.dispatch({ type: 'status', status: true })
18
+ store.dispatch({ type: 'mode', mode: 'cold' })
19
+ store.dispatch({ type: 'update', payload: { temperature: 26 } })
20
+ ```
21
+
22
+ ## License
23
+
24
+ [MIT](https://github.com/YunYouJun/air-conditioner/blob/dev/LICENSE)
package/dist/index.cjs ADDED
@@ -0,0 +1,269 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/constants.ts
3
+ const acStorageKey = "ac:state";
4
+ /**
5
+ * 各模式对应的显示图标(供各框架视图层复用)。
6
+ */
7
+ const acModeIcons = {
8
+ cold: "❄️",
9
+ hot: "☀️"
10
+ };
11
+ /**
12
+ * 默认音频资源文件名(不含扩展名)。
13
+ *
14
+ * - `beep` 按键「嘀」声
15
+ * - `start` 空调启动声
16
+ * - `work` 持续工作(出风)声
17
+ */
18
+ const acAudioFileNames = {
19
+ beep: "di",
20
+ start: "ac-work",
21
+ work: "air-extractor-fan"
22
+ };
23
+ const minTemperature = 16;
24
+ const maxTemperature = 31;
25
+ const recommendedColdTemperature = 26;
26
+ const recommendedHotTemperature = 20;
27
+ const defaultAcState = {
28
+ mode: "cold",
29
+ status: false,
30
+ temperature: 26
31
+ };
32
+ const soundTimings = {
33
+ startDelayMs: 8e3,
34
+ noiseStartTime: 2,
35
+ noiseDuration: 56
36
+ };
37
+ /**
38
+ * 根据基础路径解析出三个音频文件的完整 URL。
39
+ *
40
+ * 纯字符串拼接,可在任意环境(含 SSR)调用。
41
+ *
42
+ * @param baseUrl 音频目录,如 `/assets/audio`
43
+ * @param ext 文件扩展名,默认 `m4a`
44
+ */
45
+ function resolveAcAudioAssets(baseUrl = "/assets/audio", ext = "m4a") {
46
+ const base = baseUrl.replace(/\/$/, "");
47
+ return {
48
+ beep: `${base}/${acAudioFileNames.beep}.${ext}`,
49
+ start: `${base}/${acAudioFileNames.start}.${ext}`,
50
+ work: `${base}/${acAudioFileNames.work}.${ext}`
51
+ };
52
+ }
53
+ //#endregion
54
+ //#region src/audio.ts
55
+ function createAcAudioController(elements) {
56
+ let playStartSoundTimeoutId;
57
+ let playWorkSoundTimeoutId;
58
+ let playWorkSoundIntervalId;
59
+ function clearWorkTimers() {
60
+ if (playStartSoundTimeoutId) clearTimeout(playStartSoundTimeoutId);
61
+ if (playWorkSoundTimeoutId) clearTimeout(playWorkSoundTimeoutId);
62
+ if (playWorkSoundIntervalId) clearInterval(playWorkSoundIntervalId);
63
+ playStartSoundTimeoutId = void 0;
64
+ playWorkSoundTimeoutId = void 0;
65
+ playWorkSoundIntervalId = void 0;
66
+ }
67
+ function play(audio) {
68
+ if (!audio) return;
69
+ audio.load();
70
+ audio.play();
71
+ }
72
+ function playWorkSound() {
73
+ if (!elements.work) return;
74
+ play(elements.work);
75
+ playWorkSoundTimeoutId = setTimeout(() => {
76
+ playWorkSoundIntervalId = setInterval(() => {
77
+ if (elements.work) elements.work.currentTime = soundTimings.noiseStartTime;
78
+ }, soundTimings.noiseDuration * 1e3);
79
+ }, soundTimings.noiseStartTime * 1e3);
80
+ }
81
+ function playStartSound() {
82
+ play(elements.start);
83
+ playStartSoundTimeoutId = setTimeout(() => {
84
+ playWorkSound();
85
+ }, soundTimings.startDelayMs);
86
+ }
87
+ return {
88
+ beep() {
89
+ play(elements.beep);
90
+ },
91
+ toggleStatusAudio(previousStatus) {
92
+ if (previousStatus) {
93
+ clearWorkTimers();
94
+ if (elements.start) elements.start.load();
95
+ if (elements.work) elements.work.currentTime = soundTimings.noiseStartTime + soundTimings.noiseDuration;
96
+ } else {
97
+ clearWorkTimers();
98
+ playStartSound();
99
+ }
100
+ },
101
+ dispose() {
102
+ clearWorkTimers();
103
+ }
104
+ };
105
+ }
106
+ //#endregion
107
+ //#region src/reducer.ts
108
+ function normalizeAcState(state) {
109
+ return {
110
+ ...defaultAcState,
111
+ ...state,
112
+ temperature: clampTemperature(state?.temperature ?? defaultAcState.temperature)
113
+ };
114
+ }
115
+ function clampTemperature(temperature) {
116
+ return Math.min(31, Math.max(16, temperature));
117
+ }
118
+ function acReducer(state, action) {
119
+ switch (action.type) {
120
+ case "increment": return {
121
+ ...state,
122
+ temperature: clampTemperature(state.temperature + 1)
123
+ };
124
+ case "decrement": return {
125
+ ...state,
126
+ temperature: clampTemperature(state.temperature - 1)
127
+ };
128
+ case "toggleStatus": return {
129
+ ...state,
130
+ status: !state.status
131
+ };
132
+ case "status": return {
133
+ ...state,
134
+ status: action.status
135
+ };
136
+ case "mode": return {
137
+ ...state,
138
+ mode: action.mode
139
+ };
140
+ case "update": return normalizeAcState({
141
+ ...state,
142
+ ...action.payload
143
+ });
144
+ default: throw new Error("Unexpected Ac Action");
145
+ }
146
+ }
147
+ function getRecommendedTemperatureMessage(mode, temperature) {
148
+ return `建议将空调的制${mode === "cold" ? "冷" : "热"}温度调至 ${temperature} 度以${mode === "cold" ? "上" : "下"},为节能减排贡献一份力量!`;
149
+ }
150
+ function getAcActionNotification(previousState, nextState, action) {
151
+ if (action.type === "increment" && previousState.temperature >= 31) return {
152
+ message: "已经是最大温度啦!",
153
+ severity: "error"
154
+ };
155
+ if (action.type === "decrement" && previousState.temperature <= 16) return {
156
+ message: "已经是最小温度啦!",
157
+ severity: "error"
158
+ };
159
+ if (action.type === "mode" && nextState.mode === "cold" && previousState.temperature < 26) return {
160
+ message: getRecommendedTemperatureMessage("cold", 26),
161
+ severity: "success"
162
+ };
163
+ if (action.type === "mode" && nextState.mode === "hot" && previousState.temperature > 20) return {
164
+ message: getRecommendedTemperatureMessage("hot", 20),
165
+ severity: "success"
166
+ };
167
+ }
168
+ //#endregion
169
+ //#region src/storage.ts
170
+ function readAcState(storage, storageKey) {
171
+ if (!storage) return defaultAcState;
172
+ try {
173
+ const raw = storage.getItem(storageKey);
174
+ if (!raw) return defaultAcState;
175
+ return normalizeAcState(JSON.parse(raw));
176
+ } catch {
177
+ return defaultAcState;
178
+ }
179
+ }
180
+ function writeAcState(storage, storageKey, state) {
181
+ if (!storage) return;
182
+ try {
183
+ storage.setItem(storageKey, JSON.stringify(state));
184
+ } catch {}
185
+ }
186
+ function createMemoryStorage(initialValue) {
187
+ const values = new Map(Object.entries(initialValue ?? {}));
188
+ return {
189
+ getItem(key) {
190
+ return values.get(key) ?? null;
191
+ },
192
+ setItem(key, value) {
193
+ values.set(key, value);
194
+ },
195
+ removeItem(key) {
196
+ values.delete(key);
197
+ }
198
+ };
199
+ }
200
+ function getBrowserStorage() {
201
+ if (typeof window === "undefined") return null;
202
+ try {
203
+ return window.localStorage;
204
+ } catch {
205
+ return null;
206
+ }
207
+ }
208
+ //#endregion
209
+ //#region src/store.ts
210
+ function createAirConditionerStore(options = {}) {
211
+ const storageKey = options.storageKey ?? "ac:state";
212
+ const storage = options.storage === void 0 ? getBrowserStorage() : options.storage;
213
+ const persistedState = readAcState(storage, storageKey);
214
+ let state = normalizeAcState({
215
+ ...defaultAcState,
216
+ ...persistedState,
217
+ ...options.initialState
218
+ });
219
+ const listeners = /* @__PURE__ */ new Set();
220
+ return {
221
+ getState() {
222
+ return state;
223
+ },
224
+ dispatch(action) {
225
+ const previousState = state;
226
+ const nextState = acReducer(state, action);
227
+ const notification = getAcActionNotification(previousState, nextState, action);
228
+ const event = {
229
+ action,
230
+ previousState,
231
+ state: nextState,
232
+ notification
233
+ };
234
+ state = nextState;
235
+ writeAcState(storage, storageKey, nextState);
236
+ listeners.forEach((listener) => listener(event));
237
+ if (notification) options.onNotify?.(notification, event);
238
+ return event;
239
+ },
240
+ subscribe(listener) {
241
+ listeners.add(listener);
242
+ return () => {
243
+ listeners.delete(listener);
244
+ };
245
+ }
246
+ };
247
+ }
248
+ //#endregion
249
+ exports.acAudioFileNames = acAudioFileNames;
250
+ exports.acModeIcons = acModeIcons;
251
+ exports.acReducer = acReducer;
252
+ exports.acStorageKey = acStorageKey;
253
+ exports.clampTemperature = clampTemperature;
254
+ exports.createAcAudioController = createAcAudioController;
255
+ exports.createAirConditionerStore = createAirConditionerStore;
256
+ exports.createMemoryStorage = createMemoryStorage;
257
+ exports.defaultAcState = defaultAcState;
258
+ exports.getAcActionNotification = getAcActionNotification;
259
+ exports.getBrowserStorage = getBrowserStorage;
260
+ exports.getRecommendedTemperatureMessage = getRecommendedTemperatureMessage;
261
+ exports.maxTemperature = maxTemperature;
262
+ exports.minTemperature = minTemperature;
263
+ exports.normalizeAcState = normalizeAcState;
264
+ exports.readAcState = readAcState;
265
+ exports.recommendedColdTemperature = recommendedColdTemperature;
266
+ exports.recommendedHotTemperature = recommendedHotTemperature;
267
+ exports.resolveAcAudioAssets = resolveAcAudioAssets;
268
+ exports.soundTimings = soundTimings;
269
+ exports.writeAcState = writeAcState;
@@ -0,0 +1,134 @@
1
+ //#region src/types.d.ts
2
+ type AcMode = 'cold' | 'hot';
3
+ interface AcState {
4
+ /**
5
+ * Whether the air conditioner is powered on.
6
+ */
7
+ status: boolean;
8
+ /**
9
+ * Current work mode.
10
+ */
11
+ mode: AcMode;
12
+ /**
13
+ * Target temperature in Celsius.
14
+ */
15
+ temperature: number;
16
+ }
17
+ type AcAction = {
18
+ type: 'increment' | 'decrement' | 'toggleStatus';
19
+ } | {
20
+ type: 'status';
21
+ status: AcState['status'];
22
+ } | {
23
+ type: 'mode';
24
+ mode: AcState['mode'];
25
+ } | {
26
+ type: 'update';
27
+ payload: Partial<AcState>;
28
+ };
29
+ type AcNotificationSeverity = 'success' | 'error' | 'info';
30
+ interface AcNotification {
31
+ message: string;
32
+ severity: AcNotificationSeverity;
33
+ }
34
+ interface AcChangeEvent {
35
+ action: AcAction;
36
+ previousState: AcState;
37
+ state: AcState;
38
+ notification?: AcNotification;
39
+ }
40
+ type AcStoreListener = (event: AcChangeEvent) => void;
41
+ interface AcStorage {
42
+ getItem: (key: string) => string | null;
43
+ setItem: (key: string, value: string) => void;
44
+ removeItem?: (key: string) => void;
45
+ }
46
+ interface CreateAirConditionerStoreOptions {
47
+ initialState?: Partial<AcState>;
48
+ storage?: AcStorage | null;
49
+ storageKey?: string;
50
+ onNotify?: (notification: AcNotification, event: AcChangeEvent) => void;
51
+ }
52
+ interface AirConditionerStore {
53
+ getState: () => AcState;
54
+ dispatch: (action: AcAction) => AcChangeEvent;
55
+ subscribe: (listener: AcStoreListener) => () => void;
56
+ }
57
+ interface AcAudioElement {
58
+ currentTime: number;
59
+ load: () => void;
60
+ play: () => Promise<unknown> | unknown;
61
+ }
62
+ interface AcAudioElements {
63
+ start: AcAudioElement | null;
64
+ work: AcAudioElement | null;
65
+ beep?: AcAudioElement | null;
66
+ }
67
+ interface AcAudioController {
68
+ beep: () => void;
69
+ toggleStatusAudio: (previousStatus: boolean) => void;
70
+ dispose: () => void;
71
+ }
72
+ //#endregion
73
+ //#region src/audio.d.ts
74
+ declare function createAcAudioController(elements: AcAudioElements): AcAudioController;
75
+ //#endregion
76
+ //#region src/constants.d.ts
77
+ declare const acStorageKey = "ac:state";
78
+ /**
79
+ * 各模式对应的显示图标(供各框架视图层复用)。
80
+ */
81
+ declare const acModeIcons: Record<AcMode, string>;
82
+ /**
83
+ * 默认音频资源文件名(不含扩展名)。
84
+ *
85
+ * - `beep` 按键「嘀」声
86
+ * - `start` 空调启动声
87
+ * - `work` 持续工作(出风)声
88
+ */
89
+ declare const acAudioFileNames: {
90
+ readonly beep: "di";
91
+ readonly start: "ac-work";
92
+ readonly work: "air-extractor-fan";
93
+ };
94
+ declare const minTemperature = 16;
95
+ declare const maxTemperature = 31;
96
+ declare const recommendedColdTemperature = 26;
97
+ declare const recommendedHotTemperature = 20;
98
+ declare const defaultAcState: AcState;
99
+ declare const soundTimings: {
100
+ readonly startDelayMs: 8000;
101
+ readonly noiseStartTime: 2;
102
+ readonly noiseDuration: 56;
103
+ };
104
+ /**
105
+ * 根据基础路径解析出三个音频文件的完整 URL。
106
+ *
107
+ * 纯字符串拼接,可在任意环境(含 SSR)调用。
108
+ *
109
+ * @param baseUrl 音频目录,如 `/assets/audio`
110
+ * @param ext 文件扩展名,默认 `m4a`
111
+ */
112
+ declare function resolveAcAudioAssets(baseUrl?: string, ext?: string): {
113
+ beep: string;
114
+ start: string;
115
+ work: string;
116
+ };
117
+ //#endregion
118
+ //#region src/reducer.d.ts
119
+ declare function normalizeAcState(state: Partial<AcState> | undefined): AcState;
120
+ declare function clampTemperature(temperature: number): number;
121
+ declare function acReducer(state: AcState, action: AcAction): AcState;
122
+ declare function getRecommendedTemperatureMessage(mode: AcState['mode'], temperature: number): string;
123
+ declare function getAcActionNotification(previousState: AcState, nextState: AcState, action: AcAction): AcNotification | undefined;
124
+ //#endregion
125
+ //#region src/storage.d.ts
126
+ declare function readAcState(storage: AcStorage | null | undefined, storageKey: string): AcState;
127
+ declare function writeAcState(storage: AcStorage | null | undefined, storageKey: string, state: AcState): void;
128
+ declare function createMemoryStorage(initialValue?: Record<string, string>): AcStorage;
129
+ declare function getBrowserStorage(): AcStorage | null;
130
+ //#endregion
131
+ //#region src/store.d.ts
132
+ declare function createAirConditionerStore(options?: CreateAirConditionerStoreOptions): AirConditionerStore;
133
+ //#endregion
134
+ export { AcAction, AcAudioController, AcAudioElement, AcAudioElements, AcChangeEvent, AcMode, AcNotification, AcNotificationSeverity, AcState, AcStorage, AcStoreListener, AirConditionerStore, CreateAirConditionerStoreOptions, acAudioFileNames, acModeIcons, acReducer, acStorageKey, clampTemperature, createAcAudioController, createAirConditionerStore, createMemoryStorage, defaultAcState, getAcActionNotification, getBrowserStorage, getRecommendedTemperatureMessage, maxTemperature, minTemperature, normalizeAcState, readAcState, recommendedColdTemperature, recommendedHotTemperature, resolveAcAudioAssets, soundTimings, writeAcState };
@@ -0,0 +1,134 @@
1
+ //#region src/types.d.ts
2
+ type AcMode = 'cold' | 'hot';
3
+ interface AcState {
4
+ /**
5
+ * Whether the air conditioner is powered on.
6
+ */
7
+ status: boolean;
8
+ /**
9
+ * Current work mode.
10
+ */
11
+ mode: AcMode;
12
+ /**
13
+ * Target temperature in Celsius.
14
+ */
15
+ temperature: number;
16
+ }
17
+ type AcAction = {
18
+ type: 'increment' | 'decrement' | 'toggleStatus';
19
+ } | {
20
+ type: 'status';
21
+ status: AcState['status'];
22
+ } | {
23
+ type: 'mode';
24
+ mode: AcState['mode'];
25
+ } | {
26
+ type: 'update';
27
+ payload: Partial<AcState>;
28
+ };
29
+ type AcNotificationSeverity = 'success' | 'error' | 'info';
30
+ interface AcNotification {
31
+ message: string;
32
+ severity: AcNotificationSeverity;
33
+ }
34
+ interface AcChangeEvent {
35
+ action: AcAction;
36
+ previousState: AcState;
37
+ state: AcState;
38
+ notification?: AcNotification;
39
+ }
40
+ type AcStoreListener = (event: AcChangeEvent) => void;
41
+ interface AcStorage {
42
+ getItem: (key: string) => string | null;
43
+ setItem: (key: string, value: string) => void;
44
+ removeItem?: (key: string) => void;
45
+ }
46
+ interface CreateAirConditionerStoreOptions {
47
+ initialState?: Partial<AcState>;
48
+ storage?: AcStorage | null;
49
+ storageKey?: string;
50
+ onNotify?: (notification: AcNotification, event: AcChangeEvent) => void;
51
+ }
52
+ interface AirConditionerStore {
53
+ getState: () => AcState;
54
+ dispatch: (action: AcAction) => AcChangeEvent;
55
+ subscribe: (listener: AcStoreListener) => () => void;
56
+ }
57
+ interface AcAudioElement {
58
+ currentTime: number;
59
+ load: () => void;
60
+ play: () => Promise<unknown> | unknown;
61
+ }
62
+ interface AcAudioElements {
63
+ start: AcAudioElement | null;
64
+ work: AcAudioElement | null;
65
+ beep?: AcAudioElement | null;
66
+ }
67
+ interface AcAudioController {
68
+ beep: () => void;
69
+ toggleStatusAudio: (previousStatus: boolean) => void;
70
+ dispose: () => void;
71
+ }
72
+ //#endregion
73
+ //#region src/audio.d.ts
74
+ declare function createAcAudioController(elements: AcAudioElements): AcAudioController;
75
+ //#endregion
76
+ //#region src/constants.d.ts
77
+ declare const acStorageKey = "ac:state";
78
+ /**
79
+ * 各模式对应的显示图标(供各框架视图层复用)。
80
+ */
81
+ declare const acModeIcons: Record<AcMode, string>;
82
+ /**
83
+ * 默认音频资源文件名(不含扩展名)。
84
+ *
85
+ * - `beep` 按键「嘀」声
86
+ * - `start` 空调启动声
87
+ * - `work` 持续工作(出风)声
88
+ */
89
+ declare const acAudioFileNames: {
90
+ readonly beep: "di";
91
+ readonly start: "ac-work";
92
+ readonly work: "air-extractor-fan";
93
+ };
94
+ declare const minTemperature = 16;
95
+ declare const maxTemperature = 31;
96
+ declare const recommendedColdTemperature = 26;
97
+ declare const recommendedHotTemperature = 20;
98
+ declare const defaultAcState: AcState;
99
+ declare const soundTimings: {
100
+ readonly startDelayMs: 8000;
101
+ readonly noiseStartTime: 2;
102
+ readonly noiseDuration: 56;
103
+ };
104
+ /**
105
+ * 根据基础路径解析出三个音频文件的完整 URL。
106
+ *
107
+ * 纯字符串拼接,可在任意环境(含 SSR)调用。
108
+ *
109
+ * @param baseUrl 音频目录,如 `/assets/audio`
110
+ * @param ext 文件扩展名,默认 `m4a`
111
+ */
112
+ declare function resolveAcAudioAssets(baseUrl?: string, ext?: string): {
113
+ beep: string;
114
+ start: string;
115
+ work: string;
116
+ };
117
+ //#endregion
118
+ //#region src/reducer.d.ts
119
+ declare function normalizeAcState(state: Partial<AcState> | undefined): AcState;
120
+ declare function clampTemperature(temperature: number): number;
121
+ declare function acReducer(state: AcState, action: AcAction): AcState;
122
+ declare function getRecommendedTemperatureMessage(mode: AcState['mode'], temperature: number): string;
123
+ declare function getAcActionNotification(previousState: AcState, nextState: AcState, action: AcAction): AcNotification | undefined;
124
+ //#endregion
125
+ //#region src/storage.d.ts
126
+ declare function readAcState(storage: AcStorage | null | undefined, storageKey: string): AcState;
127
+ declare function writeAcState(storage: AcStorage | null | undefined, storageKey: string, state: AcState): void;
128
+ declare function createMemoryStorage(initialValue?: Record<string, string>): AcStorage;
129
+ declare function getBrowserStorage(): AcStorage | null;
130
+ //#endregion
131
+ //#region src/store.d.ts
132
+ declare function createAirConditionerStore(options?: CreateAirConditionerStoreOptions): AirConditionerStore;
133
+ //#endregion
134
+ export { AcAction, AcAudioController, AcAudioElement, AcAudioElements, AcChangeEvent, AcMode, AcNotification, AcNotificationSeverity, AcState, AcStorage, AcStoreListener, AirConditionerStore, CreateAirConditionerStoreOptions, acAudioFileNames, acModeIcons, acReducer, acStorageKey, clampTemperature, createAcAudioController, createAirConditionerStore, createMemoryStorage, defaultAcState, getAcActionNotification, getBrowserStorage, getRecommendedTemperatureMessage, maxTemperature, minTemperature, normalizeAcState, readAcState, recommendedColdTemperature, recommendedHotTemperature, resolveAcAudioAssets, soundTimings, writeAcState };
package/dist/index.js ADDED
@@ -0,0 +1,248 @@
1
+ //#region src/constants.ts
2
+ const acStorageKey = "ac:state";
3
+ /**
4
+ * 各模式对应的显示图标(供各框架视图层复用)。
5
+ */
6
+ const acModeIcons = {
7
+ cold: "❄️",
8
+ hot: "☀️"
9
+ };
10
+ /**
11
+ * 默认音频资源文件名(不含扩展名)。
12
+ *
13
+ * - `beep` 按键「嘀」声
14
+ * - `start` 空调启动声
15
+ * - `work` 持续工作(出风)声
16
+ */
17
+ const acAudioFileNames = {
18
+ beep: "di",
19
+ start: "ac-work",
20
+ work: "air-extractor-fan"
21
+ };
22
+ const minTemperature = 16;
23
+ const maxTemperature = 31;
24
+ const recommendedColdTemperature = 26;
25
+ const recommendedHotTemperature = 20;
26
+ const defaultAcState = {
27
+ mode: "cold",
28
+ status: false,
29
+ temperature: 26
30
+ };
31
+ const soundTimings = {
32
+ startDelayMs: 8e3,
33
+ noiseStartTime: 2,
34
+ noiseDuration: 56
35
+ };
36
+ /**
37
+ * 根据基础路径解析出三个音频文件的完整 URL。
38
+ *
39
+ * 纯字符串拼接,可在任意环境(含 SSR)调用。
40
+ *
41
+ * @param baseUrl 音频目录,如 `/assets/audio`
42
+ * @param ext 文件扩展名,默认 `m4a`
43
+ */
44
+ function resolveAcAudioAssets(baseUrl = "/assets/audio", ext = "m4a") {
45
+ const base = baseUrl.replace(/\/$/, "");
46
+ return {
47
+ beep: `${base}/${acAudioFileNames.beep}.${ext}`,
48
+ start: `${base}/${acAudioFileNames.start}.${ext}`,
49
+ work: `${base}/${acAudioFileNames.work}.${ext}`
50
+ };
51
+ }
52
+ //#endregion
53
+ //#region src/audio.ts
54
+ function createAcAudioController(elements) {
55
+ let playStartSoundTimeoutId;
56
+ let playWorkSoundTimeoutId;
57
+ let playWorkSoundIntervalId;
58
+ function clearWorkTimers() {
59
+ if (playStartSoundTimeoutId) clearTimeout(playStartSoundTimeoutId);
60
+ if (playWorkSoundTimeoutId) clearTimeout(playWorkSoundTimeoutId);
61
+ if (playWorkSoundIntervalId) clearInterval(playWorkSoundIntervalId);
62
+ playStartSoundTimeoutId = void 0;
63
+ playWorkSoundTimeoutId = void 0;
64
+ playWorkSoundIntervalId = void 0;
65
+ }
66
+ function play(audio) {
67
+ if (!audio) return;
68
+ audio.load();
69
+ audio.play();
70
+ }
71
+ function playWorkSound() {
72
+ if (!elements.work) return;
73
+ play(elements.work);
74
+ playWorkSoundTimeoutId = setTimeout(() => {
75
+ playWorkSoundIntervalId = setInterval(() => {
76
+ if (elements.work) elements.work.currentTime = soundTimings.noiseStartTime;
77
+ }, soundTimings.noiseDuration * 1e3);
78
+ }, soundTimings.noiseStartTime * 1e3);
79
+ }
80
+ function playStartSound() {
81
+ play(elements.start);
82
+ playStartSoundTimeoutId = setTimeout(() => {
83
+ playWorkSound();
84
+ }, soundTimings.startDelayMs);
85
+ }
86
+ return {
87
+ beep() {
88
+ play(elements.beep);
89
+ },
90
+ toggleStatusAudio(previousStatus) {
91
+ if (previousStatus) {
92
+ clearWorkTimers();
93
+ if (elements.start) elements.start.load();
94
+ if (elements.work) elements.work.currentTime = soundTimings.noiseStartTime + soundTimings.noiseDuration;
95
+ } else {
96
+ clearWorkTimers();
97
+ playStartSound();
98
+ }
99
+ },
100
+ dispose() {
101
+ clearWorkTimers();
102
+ }
103
+ };
104
+ }
105
+ //#endregion
106
+ //#region src/reducer.ts
107
+ function normalizeAcState(state) {
108
+ return {
109
+ ...defaultAcState,
110
+ ...state,
111
+ temperature: clampTemperature(state?.temperature ?? defaultAcState.temperature)
112
+ };
113
+ }
114
+ function clampTemperature(temperature) {
115
+ return Math.min(31, Math.max(16, temperature));
116
+ }
117
+ function acReducer(state, action) {
118
+ switch (action.type) {
119
+ case "increment": return {
120
+ ...state,
121
+ temperature: clampTemperature(state.temperature + 1)
122
+ };
123
+ case "decrement": return {
124
+ ...state,
125
+ temperature: clampTemperature(state.temperature - 1)
126
+ };
127
+ case "toggleStatus": return {
128
+ ...state,
129
+ status: !state.status
130
+ };
131
+ case "status": return {
132
+ ...state,
133
+ status: action.status
134
+ };
135
+ case "mode": return {
136
+ ...state,
137
+ mode: action.mode
138
+ };
139
+ case "update": return normalizeAcState({
140
+ ...state,
141
+ ...action.payload
142
+ });
143
+ default: throw new Error("Unexpected Ac Action");
144
+ }
145
+ }
146
+ function getRecommendedTemperatureMessage(mode, temperature) {
147
+ return `建议将空调的制${mode === "cold" ? "冷" : "热"}温度调至 ${temperature} 度以${mode === "cold" ? "上" : "下"},为节能减排贡献一份力量!`;
148
+ }
149
+ function getAcActionNotification(previousState, nextState, action) {
150
+ if (action.type === "increment" && previousState.temperature >= 31) return {
151
+ message: "已经是最大温度啦!",
152
+ severity: "error"
153
+ };
154
+ if (action.type === "decrement" && previousState.temperature <= 16) return {
155
+ message: "已经是最小温度啦!",
156
+ severity: "error"
157
+ };
158
+ if (action.type === "mode" && nextState.mode === "cold" && previousState.temperature < 26) return {
159
+ message: getRecommendedTemperatureMessage("cold", 26),
160
+ severity: "success"
161
+ };
162
+ if (action.type === "mode" && nextState.mode === "hot" && previousState.temperature > 20) return {
163
+ message: getRecommendedTemperatureMessage("hot", 20),
164
+ severity: "success"
165
+ };
166
+ }
167
+ //#endregion
168
+ //#region src/storage.ts
169
+ function readAcState(storage, storageKey) {
170
+ if (!storage) return defaultAcState;
171
+ try {
172
+ const raw = storage.getItem(storageKey);
173
+ if (!raw) return defaultAcState;
174
+ return normalizeAcState(JSON.parse(raw));
175
+ } catch {
176
+ return defaultAcState;
177
+ }
178
+ }
179
+ function writeAcState(storage, storageKey, state) {
180
+ if (!storage) return;
181
+ try {
182
+ storage.setItem(storageKey, JSON.stringify(state));
183
+ } catch {}
184
+ }
185
+ function createMemoryStorage(initialValue) {
186
+ const values = new Map(Object.entries(initialValue ?? {}));
187
+ return {
188
+ getItem(key) {
189
+ return values.get(key) ?? null;
190
+ },
191
+ setItem(key, value) {
192
+ values.set(key, value);
193
+ },
194
+ removeItem(key) {
195
+ values.delete(key);
196
+ }
197
+ };
198
+ }
199
+ function getBrowserStorage() {
200
+ if (typeof window === "undefined") return null;
201
+ try {
202
+ return window.localStorage;
203
+ } catch {
204
+ return null;
205
+ }
206
+ }
207
+ //#endregion
208
+ //#region src/store.ts
209
+ function createAirConditionerStore(options = {}) {
210
+ const storageKey = options.storageKey ?? "ac:state";
211
+ const storage = options.storage === void 0 ? getBrowserStorage() : options.storage;
212
+ const persistedState = readAcState(storage, storageKey);
213
+ let state = normalizeAcState({
214
+ ...defaultAcState,
215
+ ...persistedState,
216
+ ...options.initialState
217
+ });
218
+ const listeners = /* @__PURE__ */ new Set();
219
+ return {
220
+ getState() {
221
+ return state;
222
+ },
223
+ dispatch(action) {
224
+ const previousState = state;
225
+ const nextState = acReducer(state, action);
226
+ const notification = getAcActionNotification(previousState, nextState, action);
227
+ const event = {
228
+ action,
229
+ previousState,
230
+ state: nextState,
231
+ notification
232
+ };
233
+ state = nextState;
234
+ writeAcState(storage, storageKey, nextState);
235
+ listeners.forEach((listener) => listener(event));
236
+ if (notification) options.onNotify?.(notification, event);
237
+ return event;
238
+ },
239
+ subscribe(listener) {
240
+ listeners.add(listener);
241
+ return () => {
242
+ listeners.delete(listener);
243
+ };
244
+ }
245
+ };
246
+ }
247
+ //#endregion
248
+ export { acAudioFileNames, acModeIcons, acReducer, acStorageKey, clampTemperature, createAcAudioController, createAirConditionerStore, createMemoryStorage, defaultAcState, getAcActionNotification, getBrowserStorage, getRecommendedTemperatureMessage, maxTemperature, minTemperature, normalizeAcState, readAcState, recommendedColdTemperature, recommendedHotTemperature, resolveAcAudioAssets, soundTimings, writeAcState };
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@yunlefun-home/air-conditioner-core",
3
+ "type": "module",
4
+ "version": "0.2.0",
5
+ "description": "Framework-agnostic air conditioner state and runtime helpers.",
6
+ "author": {
7
+ "url": "https://www.yunyoujun.cn",
8
+ "email": "me@yunyoujun.cn",
9
+ "name": "YunYouJun"
10
+ },
11
+ "license": "MIT",
12
+ "homepage": "https://ac.yunyoujun.cn/",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/YunYouJun/air-conditioner"
16
+ },
17
+ "keywords": [
18
+ "air-conditioner",
19
+ "smart-home",
20
+ "state-machine",
21
+ "typescript"
22
+ ],
23
+ "sideEffects": false,
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.js",
28
+ "require": "./dist/index.cjs"
29
+ }
30
+ },
31
+ "main": "./dist/index.cjs",
32
+ "module": "./dist/index.js",
33
+ "types": "./dist/index.d.ts",
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "files": [
38
+ "dist"
39
+ ],
40
+ "devDependencies": {
41
+ "tsdown": "^0.22.1",
42
+ "typescript": "^6.0.3",
43
+ "vitest": "^4.1.8"
44
+ },
45
+ "scripts": {
46
+ "build": "tsdown",
47
+ "test": "vitest run",
48
+ "typecheck": "tsc --noEmit"
49
+ }
50
+ }