-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathllms-full.txt
More file actions
2085 lines (1594 loc) · 49.6 KB
/
llms-full.txt
File metadata and controls
2085 lines (1594 loc) · 49.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SinricPro Python SDK - Complete LLM Context
> Official Python SDK for SinricPro - Control IoT devices with Alexa and Google Home
> Version: 3.0.0 | License: CC BY-SA 4.0 | Python: 3.10+
> Repository: https://github.com/sinricpro/python-sdk
## Table of Contents
1. [Overview](#overview)
2. [Architecture](#architecture)
3. [Installation & Setup](#installation--setup)
4. [Complete Device Reference](#complete-device-reference)
5. [Complete Capabilities Reference](#complete-capabilities-reference)
6. [Action Constants](#action-constants)
7. [Advanced Patterns](#advanced-patterns)
8. [Complete Examples](#complete-examples)
9. [Error Handling](#error-handling)
10. [Migration from C++/Node.js](#migration-from-cnode-js)
11. [Troubleshooting](#troubleshooting)
---
## 1. Overview
### What is SinricPro?
SinricPro is a cloud platform that enables IoT devices to be controlled via voice assistants (Alexa, Google Home) and mobile apps. This Python SDK allows you to:
- Control devices remotely via WebSocket connection
- Receive commands from Alexa/Google Home
- Send device state updates to the cloud
- Handle bidirectional communication with HMAC-SHA256 signatures
### Key Features
- ✅ **Async/Await Only** - Pure async implementation, no sync wrapper
- ✅ **Type Safe** - Full type hints with Python 3.10+ syntax
- ✅ **Auto-Reconnection** - Handles connection drops automatically
- ✅ **Rate Limiting** - Built-in event rate limiting
- ✅ **Signature Verification** - HMAC-SHA256 message signing
- ✅ **16 Device Types** - Comprehensive device support
- ✅ **18 Capabilities** - Modular capability system
- ✅ **Cross-Platform** - Linux, Windows, macOS, Raspberry Pi
### Philosophy
1. **Async-first**: Everything is async/await - no blocking operations
2. **Type hints everywhere**: Full type safety for IDE support
3. **Pythonic**: snake_case, clear naming, idiomatic Python
4. **Capability mixins**: Modular design using multiple inheritance
5. **Event-driven**: Callback-based event handling
6. **Immutable where possible**: Configuration objects are immutable
---
## 2. Architecture
### Core Components
#### SinricPro (Main Class)
```python
class SinricPro:
"""Singleton managing WebSocket connection and device registry"""
@classmethod
def get_instance() -> SinricPro:
"""Get singleton instance"""
def add(self, device: SinricProDevice) -> None:
"""Register a device"""
async def begin(self, config: SinricProConfig) -> None:
"""Start WebSocket connection"""
async def stop(self) -> None:
"""Stop connection and cleanup"""
def get_device(self, device_id: str) -> SinricProDevice | None:
"""Get device by ID"""
```
#### SinricProConfig
```python
@dataclass
class SinricProConfig:
app_key: str # UUID format
app_secret: str # Min 32 chars
debug: bool = False
def __post_init__(self):
# Validates app_key and app_secret format
```
#### SinricProDevice (Base Class)
```python
class SinricProDevice:
"""Base class for all devices"""
def __init__(self, device_id: str, product_type: str):
self._device_id = device_id # 24 hex chars
self._product_type = product_type
def get_device_id(self) -> str:
"""Get device ID"""
def get_product_type(self) -> str:
"""Get product type"""
async def handle_request(self, request: SinricProRequest) -> bool:
"""Override to handle incoming requests"""
async def send_event(
self,
action: str,
value: dict[str, Any],
cause: str = "PHYSICAL_INTERACTION"
) -> bool:
"""Send event to cloud"""
```
### WebSocket Communication Flow
```
User says "Alexa, turn on the light"
↓
Alexa Cloud
↓
SinricPro Cloud
↓
WebSocket Message (signed with HMAC-SHA256)
↓
Python SDK receives message
↓
Verify signature
↓
Route to device by deviceId
↓
Call device.handle_request()
↓
Device routes to capability handler
↓
Capability calls registered callback
↓
Callback controls hardware, returns True/False
↓
SDK sends response back
↓
SinricPro Cloud
↓
Alexa says "OK"
```
### Message Format
**Request from Cloud:**
```json
{
"header": {
"payloadVersion": 2,
"signatureVersion": 1
},
"payload": {
"action": "setPowerState",
"createdAt": 1234567890,
"deviceId": "507f1f77bcf86cd799439011",
"replyToken": "uuid-here",
"type": "request",
"value": {
"state": "On"
}
},
"signature": {
"HMAC": "base64-signature-here"
}
}
```
**Response to Cloud:**
```json
{
"header": {
"payloadVersion": 2,
"signatureVersion": 1
},
"payload": {
"action": "setPowerState",
"createdAt": 1234567890,
"deviceId": "507f1f77bcf86cd799439011",
"message": "OK",
"replyToken": "uuid-here",
"success": true,
"type": "response",
"value": {
"state": "On"
}
},
"signature": {
"HMAC": "base64-signature-here"
}
}
```
**Event to Cloud:**
```json
{
"header": {
"payloadVersion": 2,
"signatureVersion": 1
},
"payload": {
"action": "setPowerState",
"cause": {
"type": "PHYSICAL_INTERACTION"
},
"createdAt": 1234567890,
"deviceId": "507f1f77bcf86cd799439011",
"type": "event",
"value": {
"state": "On"
}
},
"signature": {
"HMAC": "base64-signature-here"
}
}
```
### Capability Mixin Pattern
Devices inherit from SinricProDevice + capability mixins:
```python
class SinricProLight(
SinricProDevice,
PowerStateController,
BrightnessController,
ColorController,
ColorTemperatureController,
SettingController,
PushNotification
):
def __init__(self, device_id: str):
super().__init__(device_id=device_id, product_type="LIGHT")
async def handle_request(self, request: SinricProRequest) -> bool:
# Route actions to capability handlers
if request.action == ACTION_SET_POWER_STATE:
state = request.request_value.get("state") == "On"
success, response_value = await self.handle_power_state_request(state, self)
request.response_value = response_value
return success
# ... etc
```
Each capability provides:
- Callback registration methods (`on_*`)
- Request handlers (`handle_*_request`)
- Event senders (`send_*_event`)
---
## 3. Installation & Setup
### Installation
```bash
# From PyPI (when published)
pip install sinricpro
# From source
git clone https://github.com/sinricpro/python-sdk
cd python-sdk
pip install -e .
```
### Basic Setup
```python
import asyncio
from sinricpro import SinricPro, SinricProSwitch, SinricProConfig
async def on_power_state(state: bool) -> bool:
"""Called when Alexa says "turn on/off" """
print(f"Switch {'ON' if state else 'OFF'}")
# TODO: Control GPIO/relay here
return True # Return True on success
async def main():
# Get singleton instance
sinric = SinricPro.get_instance()
# Create device
switch = SinricProSwitch("YOUR_DEVICE_ID_HERE")
# Register callback
switch.on_power_state(on_power_state)
# Add to SinricPro
sinric.add(switch)
# Configure
config = SinricProConfig(
app_key="YOUR_APP_KEY", # From portal
app_secret="YOUR_APP_SECRET", # From portal
debug=True # Enable debug logs
)
# Connect and run
await sinric.begin(config)
# Keep running
while True:
await asyncio.sleep(1)
if __name__ == "__main__":
asyncio.run(main())
```
### Getting Credentials
1. Go to https://sinric.pro
2. Create account
3. Go to Credentials section
4. Copy App Key (UUID format)
5. Copy App Secret (long string)
6. Create a device, copy Device ID (24 hex chars)
---
## 4. Complete Device Reference
### 4.1 SinricProSwitch
**Product Type:** `"SWITCH"`
**Capabilities:**
- PowerStateController
- SettingController
- PushNotification
**Methods:**
```python
# Callbacks
switch.on_power_state(callback: Callable[[bool], Awaitable[bool]])
switch.on_setting(callback: Callable[[str, Any], Awaitable[bool]])
# Events
await switch.send_power_state_event(state: bool, cause: str = "PHYSICAL_INTERACTION")
await switch.send_push_notification(message: str)
```
**Example:**
```python
switch = SinricProSwitch("device_id")
async def on_power(state: bool) -> bool:
GPIO.output(RELAY_PIN, GPIO.HIGH if state else GPIO.LOW)
return True
async def on_setting(setting: str, value: Any) -> bool:
if setting == "auto_off_timer":
# Set timer
return True
return False
switch.on_power_state(on_power)
switch.on_setting(on_setting)
# Report physical button press
await switch.send_power_state_event(True)
```
---
### 4.2 SinricProLight
**Product Type:** `"LIGHT"`
**Capabilities:**
- PowerStateController
- BrightnessController
- ColorController
- ColorTemperatureController
- SettingController
- PushNotification
**Methods:**
```python
# Callbacks
light.on_power_state(callback: Callable[[bool], Awaitable[bool]])
light.on_brightness(callback: Callable[[int], Awaitable[bool]])
light.on_adjust_brightness(callback: Callable[[int], Awaitable[bool]])
light.on_color(callback: Callable[[int, int, int], Awaitable[bool]]) # r, g, b
light.on_color_temperature(callback: Callable[[int], Awaitable[bool]])
light.on_increase_color_temperature(callback: Callable[[None], Awaitable[bool]])
light.on_decrease_color_temperature(callback: Callable[[None], Awaitable[bool]])
light.on_setting(callback: Callable[[str, Any], Awaitable[bool]])
# Events
await light.send_power_state_event(state: bool)
await light.send_brightness_event(brightness: int) # 0-100
await light.send_color_event(r: int, g: int, b: int) # 0-255 each
await light.send_color_temperature_event(temperature: int) # 2200-7000K
await light.send_push_notification(message: str)
```
**Example:**
```python
light = SinricProLight("device_id")
async def on_brightness(brightness: int) -> bool:
# brightness: 0-100
pwm.ChangeDutyCycle(brightness)
return True
async def on_color(r: int, g: int, b: int) -> bool:
# r, g, b: 0-255
set_rgb_strip(r, g, b)
return True
async def on_color_temp(temp: int) -> bool:
# temp: 2200-7000 Kelvin
set_white_temperature(temp)
return True
light.on_brightness(on_brightness)
light.on_color(on_color)
light.on_color_temperature(on_color_temp)
```
---
### 4.3 SinricProDimSwitch
**Product Type:** `"DIMMABLE_SWITCH"`
**Capabilities:**
- PowerStateController
- PowerLevelController (NOT BrightnessController!)
- SettingController
- PushNotification
**IMPORTANT:** DimSwitch uses PowerLevelController, not BrightnessController
**Methods:**
```python
# Callbacks
dimswitch.on_power_state(callback: Callable[[bool], Awaitable[bool]])
dimswitch.on_power_level(callback: Callable[[int], Awaitable[bool]])
dimswitch.on_adjust_power_level(callback: Callable[[int], Awaitable[tuple[bool, int]]]) # Returns tuple!
dimswitch.on_setting(callback: Callable[[str, Any], Awaitable[bool]])
# Events
await dimswitch.send_power_state_event(state: bool)
await dimswitch.send_power_level_event(level: int) # 0-100
await dimswitch.send_push_notification(message: str)
```
**Example:**
```python
dimswitch = SinricProDimSwitch("device_id")
current_level = 0
async def on_power_level(level: int) -> bool:
global current_level
current_level = level
pwm.ChangeDutyCycle(level)
return True
async def on_adjust_power_level(delta: int) -> tuple[bool, int]:
global current_level
new_level = max(0, min(100, current_level + delta))
current_level = new_level
pwm.ChangeDutyCycle(new_level)
return True, new_level # Return tuple!
dimswitch.on_power_level(on_power_level)
dimswitch.on_adjust_power_level(on_adjust_power_level)
```
**Actions:**
- `ACTION_SET_POWER_LEVEL` - "setPowerLevel"
- `ACTION_ADJUST_POWER_LEVEL` - "adjustPowerLevel"
---
### 4.4 SinricProMotionSensor
**Product Type:** `"MOTION_SENSOR"`
**Capabilities:**
- MotionSensor
- SettingController
- PushNotification
**Methods:**
```python
# Callbacks
sensor.on_setting(callback: Callable[[str, Any], Awaitable[bool]])
# Events
await sensor.send_motion_event(detected: bool) # True = motion detected
await sensor.send_push_notification(message: str)
```
**Example:**
```python
sensor = SinricProMotionSensor("device_id")
# Monitor GPIO pin
def on_motion_detected():
asyncio.create_task(sensor.send_motion_event(True))
print("Motion detected!")
GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=on_motion_detected)
```
---
### 4.5 SinricProContactSensor
**Product Type:** `"CONTACT_SENSOR"`
**Capabilities:**
- ContactSensor
- SettingController
- PushNotification
**Methods:**
```python
# Callbacks
sensor.on_setting(callback: Callable[[str, Any], Awaitable[bool]])
# Events
await sensor.send_contact_event(detected: bool) # True=open, False=closed
await sensor.send_push_notification(message: str)
```
**Example:**
```python
contact = SinricProContactSensor("device_id")
# Monitor magnetic reed switch
previous_state = None
while True:
is_open = GPIO.input(REED_PIN) == GPIO.HIGH
if is_open != previous_state:
await contact.send_contact_event(is_open)
if is_open:
await contact.send_push_notification("Door opened!")
previous_state = is_open
await asyncio.sleep(0.1)
```
---
### 4.6 SinricProTemperatureSensor
**Product Type:** `"TEMPERATURE_SENSOR"`
**Capabilities:**
- TemperatureSensor
- SettingController
- PushNotification
**Methods:**
```python
# Callbacks
sensor.on_setting(callback: Callable[[str, Any], Awaitable[bool]])
# Events
await sensor.send_temperature_event(temperature: float, humidity: float)
await sensor.send_push_notification(message: str)
```
**Example:**
```python
temp = SinricProTemperatureSensor("device_id")
while True:
# Read DHT22 sensor
humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, DHT_PIN)
if humidity is not None and temperature is not None:
await temp.send_temperature_event(temperature, humidity)
await asyncio.sleep(60) # Every 60 seconds
```
---
### 4.7 SinricProAirQualitySensor
**Product Type:** `"AIR_QUALITY_SENSOR"`
**Capabilities:**
- AirQualitySensor
- TemperatureSensor
- SettingController
- PushNotification
**Methods:**
```python
# Callbacks
sensor.on_setting(callback: Callable[[str, Any], Awaitable[bool]])
# Events
await sensor.send_air_quality_event(pm1_0: int, pm2_5: int, pm10: int)
await sensor.send_temperature_event(temperature: float, humidity: float)
await sensor.send_push_notification(message: str)
```
**Example:**
```python
air = SinricProAirQualitySensor("device_id")
while True:
# Read PMS5003 sensor
data = pms5003.read()
pm1_0 = data.pm1_0
pm2_5 = data.pm2_5
pm10 = data.pm10
await air.send_air_quality_event(pm1_0, pm2_5, pm10)
# Also send temperature if available
temp, humidity = read_dht22()
await air.send_temperature_event(temp, humidity)
# Alert if PM2.5 is high
if pm2_5 > 35:
await air.send_push_notification(f"High PM2.5: {pm2_5} μg/m³")
await asyncio.sleep(60)
```
---
### 4.8 SinricProPowerSensor
**Product Type:** `"POWER_SENSOR"`
**Capabilities:**
- PowerSensor
- SettingController
- PushNotification
**Methods:**
```python
# Callbacks
sensor.on_setting(callback: Callable[[str, Any], Awaitable[bool]])
# Events
await sensor.send_power_sensor_event(
voltage: float,
current: float,
power: float | None = None, # Auto-calculated if None
apparent_power: float | None = None,
reactive_power: float | None = None,
factor: float | None = None, # Auto-calculated if apparentPower provided
cause: str = "PERIODIC_POLL"
)
await sensor.send_push_notification(message: str)
```
**Important:**
- Action: `ACTION_POWER_USAGE` ("powerUsage")
- SDK automatically adds `startTime` and `wattHours` fields
- `wattHours` calculated as: `(current_time - start_time) * power / 3600.0`
- `power` auto-calculated as `voltage * current` if not provided
- `factor` auto-calculated as `power / apparentPower` if apparentPower provided
**Example:**
```python
power = SinricProPowerSensor("device_id")
while True:
# Read INA219
voltage = ina219.voltage()
current = ina219.current() / 1000.0 # mA to A
power_w = ina219.power() / 1000.0 # mW to W
# Can omit power - will be calculated
await power.send_power_sensor_event(
voltage=voltage,
current=current,
# power=power_w, # Optional - SDK calculates if omitted
)
# Or send complete data
await power.send_power_sensor_event(
voltage=120.0,
current=2.5,
power=300.0,
apparent_power=310.0,
reactive_power=50.0,
factor=0.97
)
# startTime and wattHours added automatically by SDK
await asyncio.sleep(60)
```
---
### 4.9 SinricProBlinds
**Product Type:** `"BLINDS"`
**Capabilities:**
- PowerStateController
- OpenCloseController (uses RangeController internally)
- SettingController
- PushNotification
**Methods:**
```python
# Callbacks
blinds.on_power_state(callback: Callable[[bool], Awaitable[bool]])
blinds.on_open_close(callback: Callable[[int], Awaitable[bool]]) # 0=closed, 100=open
blinds.on_setting(callback: Callable[[str, Any], Awaitable[bool]])
# Events
await blinds.send_power_state_event(state: bool)
await blinds.send_open_close_event(position: int) # 0-100
await blinds.send_push_notification(message: str)
```
**Example:**
```python
blinds = SinricProBlinds("device_id")
async def on_open_close(position: int) -> bool:
# position: 0=closed, 100=open
steps = int((position / 100.0) * TOTAL_STEPS)
stepper_motor.move_to(steps)
return True
async def on_power(state: bool) -> bool:
# Enable/disable motor driver
GPIO.output(ENABLE_PIN, GPIO.HIGH if state else GPIO.LOW)
return True
blinds.on_open_close(on_open_close)
blinds.on_power_state(on_power)
# Report physical button press
await blinds.send_open_close_event(75) # 75% open
```
**Actions:**
- Uses `ACTION_SET_RANGE_VALUE` ("setRangeValue") internally
- Provides semantic `on_open_close()` callback
---
### 4.10 SinricProGarageDoor
**Product Type:** `"GARAGE_DOOR"`
**Capabilities:**
- ModeController
- SettingController
- PushNotification
**Methods:**
```python
# Callbacks
garage.on_mode_state(callback: Callable[[str], Awaitable[bool]]) # "OPEN" or "CLOSED"
garage.on_setting(callback: Callable[[str, Any], Awaitable[bool]])
# Events
await garage.send_mode_event(state: str) # "OPEN" or "CLOSED"
await garage.send_push_notification(message: str)
```
**Example:**
```python
garage = SinricProGarageDoor("device_id")
async def on_mode_state(state: str) -> bool:
# state: "OPEN" or "CLOSED"
if state == "OPEN":
trigger_garage_opener()
await asyncio.sleep(15) # Wait for door to open
elif state == "CLOSED":
trigger_garage_closer()
await asyncio.sleep(15)
return True
garage.on_mode_state(on_mode_state)
# Report door sensor
if door_sensor_open:
await garage.send_mode_event("OPEN")
else:
await garage.send_mode_event("CLOSED")
```
---
### 4.11 SinricProLock
**Product Type:** `"LOCK"`
**Capabilities:**
- LockController
- SettingController
- PushNotification
**Methods:**
```python
# Callbacks
lock.on_lock_state(callback: Callable[[bool], Awaitable[bool]]) # True=locked
lock.on_setting(callback: Callable[[str, Any], Awaitable[bool]])
# Events
await lock.send_lock_state_event(locked: bool) # True=locked, False=unlocked
await lock.send_push_notification(message: str)
```
**Example:**
```python
lock = SinricProLock("device_id")
async def on_lock_state(locked: bool) -> bool:
if locked:
# Engage lock
servo.angle = 0
else:
# Disengage lock
servo.angle = 90
return True
lock.on_lock_state(on_lock_state)
# Report physical lock/unlock
await lock.send_lock_state_event(True)
await lock.send_push_notification("Door locked")
```
---
### 4.12 SinricProThermostat
**Product Type:** `"THERMOSTAT"`
**Capabilities:**
- PowerStateController
- ThermostatController
- TemperatureSensor
- SettingController
- PushNotification
**Methods:**
```python
# Callbacks
thermo.on_power_state(callback: Callable[[bool], Awaitable[bool]])
thermo.on_thermostat_mode(callback: Callable[[str], Awaitable[bool]]) # AUTO, COOL, HEAT, ECO
thermo.on_target_temperature(callback: Callable[[float], Awaitable[bool]])
thermo.on_setting(callback: Callable[[str, Any], Awaitable[bool]])
# Events
await thermo.send_power_state_event(state: bool)
await thermo.send_temperature_event(temperature: float, humidity: float)
await thermo.send_push_notification(message: str)
```
**Example:**
```python
thermo = SinricProThermostat("device_id")
async def on_thermostat_mode(mode: str) -> bool:
# mode: "AUTO", "COOL", "HEAT", "ECO", "OFF"
set_hvac_mode(mode)
return True
async def on_target_temp(temp: float) -> bool:
set_target_temperature(temp)
return True
thermo.on_thermostat_mode(on_thermostat_mode)
thermo.on_target_temperature(on_target_temp)
# Report current temperature
while True:
temp, humidity = read_sensor()
await thermo.send_temperature_event(temp, humidity)
await asyncio.sleep(60)
```
---
### 4.13 SinricProWindowAC
**Product Type:** `"AC_UNIT"`
**Capabilities:**
- PowerStateController
- ThermostatController
- TemperatureSensor
- RangeController (for fan speed)
- SettingController
- PushNotification
**Methods:**
```python
# Callbacks
ac.on_power_state(callback: Callable[[bool], Awaitable[bool]])
ac.on_thermostat_mode(callback: Callable[[str], Awaitable[bool]])
ac.on_target_temperature(callback: Callable[[float], Awaitable[bool]])
ac.on_range_value(callback: Callable[[int], Awaitable[bool]]) # Fan speed
ac.on_adjust_range_value(callback: Callable[[int], Awaitable[bool]])
ac.on_setting(callback: Callable[[str, Any], Awaitable[bool]])
# Events
await ac.send_power_state_event(state: bool)
await ac.send_temperature_event(temperature: float, humidity: float)
await ac.send_range_value_event(speed: int)
await ac.send_push_notification(message: str)
```
**Example:**
```python
ac = SinricProWindowAC("device_id")
async def on_thermostat_mode(mode: str) -> bool:
send_ir_command(f"MODE_{mode}")
return True
async def on_target_temp(temp: float) -> bool:
send_ir_command(f"TEMP_{int(temp)}")
return True
async def on_fan_speed(speed: int) -> bool:
# Convert 0-100 to LOW/MED/HIGH
if speed < 33:
send_ir_command("FAN_LOW")
elif speed < 66:
send_ir_command("FAN_MED")
else:
send_ir_command("FAN_HIGH")
return True
ac.on_thermostat_mode(on_thermostat_mode)
ac.on_target_temperature(on_target_temp)
ac.on_range_value(on_fan_speed)
```
---
### 4.14 SinricProFan
**Product Type:** `"FAN"`
**Capabilities:**
- PowerStateController
- RangeController (for speed)
- SettingController
- PushNotification
**Methods:**
```python
# Callbacks
fan.on_power_state(callback: Callable[[bool], Awaitable[bool]])
fan.on_range_value(callback: Callable[[int], Awaitable[bool]]) # Speed 0-100
fan.on_adjust_range_value(callback: Callable[[int], Awaitable[bool]])
fan.on_setting(callback: Callable[[str, Any], Awaitable[bool]])
# Events
await fan.send_power_state_event(state: bool)
await fan.send_range_value_event(speed: int)
await fan.send_push_notification(message: str)
```
**Example:**
```python
fan = SinricProFan("device_id")
async def on_fan_speed(speed: int) -> bool:
pwm.ChangeDutyCycle(speed)
return True
async def on_setting(setting: str, value: Any) -> bool:
if setting == "oscillate":
GPIO.output(OSC_PIN, GPIO.HIGH if value else GPIO.LOW)
return True
return False
fan.on_range_value(on_fan_speed)
fan.on_setting(on_setting)
```
---