summaryrefslogtreecommitdiff
path: root/python-gehomesdk.spec
blob: 0d99933e81ac08c9a9c4e4c9476ad72beaa6a99e (plain)
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
%global _empty_manifest_terminate_build 0
Name:		python-gehomesdk
Version:	0.5.11
Release:	1
Summary:	Python SDK for GE Home Appliances
License:	MIT
URL:		https://github.com/simbaja/gehome
Source0:	https://mirrors.aliyun.com/pypi/web/packages/10/48/d5fb8af155eb9203509316538bc2c0799e9beef1f946ef5631e9b1c70352/gehomesdk-0.5.11.tar.gz
BuildArch:	noarch

Requires:	python3-aiohttp
Requires:	python3-bidict
Requires:	python3-requests
Requires:	python3-websockets
Requires:	python3-humanize
Requires:	python3-lxml
Requires:	python3-slixmpp

%description
# gehomesdk
Python SDK for GE WiFi-enabled (SmartHQ) appliances.
The primary goal is to use this to power integrations for [Home Assistant](https://www.home-assistant.io/), though that
will probably need to wait on some new entity types.   

**Forked from Andrew Mark's [repository](https://github.com/ajmarks/gekitchen).**

## Installation

```pip install gehomesdk```

## Changelog

Please click [here](CHANGELOG.md) for change information.

## Usage

### gehome-appliance-data

As of 0.5.0, after installation, you should now be able to use the gehome-appliance-data application:

`gehome-appliance-data [-h] -u USERNAME -p PASSWORD [-r {US,EU}]`

The parameters are as follows:
* -u or --username: Your SmartHQ Username
* -p or --password: Your SmartHQ Password
* -r or --region: Your SmartHQ Region

This application will set up a client, iterate over all appliances, and will update the state every minute.  It will also capture all state changes as they happen (useful for figuring out which values correspond to which function).  You can exit at any time by keyboard interrupt `ctrl^C`

### Credentials

Create a `credentials.py` and place in the `examples` directory.  It should contain the following:

```
USERNAME = "your@email.com"
PASSWORD = "supersecret"
REGION = "US or EU"
```

You will need to replace the username/password values with your credentials.  After that, you can run the `websocket_example.py` (**preferred**) or `xmpp_example.py` sample files.  These will generate information about your appliances and are useful if you'd like to help implement more functionality.

### Simple example
Here we're going to run the client in a pre-existing event loop.  We're also going to register some event callbacks
to update appliances every five minutes and to turn on our oven the first time we see it.  Because that is safe!
```python
import aiohttp
import asyncio
import logging
from gehomesdk.secrets import USERNAME, PASSWORD
from gehomesdk import GeWebsocketClient

_LOGGER = logging.getLogger(__name__)


if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG, format='%(levelname)-8s %(message)s')

    loop = asyncio.get_event_loop()
    client = GeWebsocketClient(loop, USERNAME, PASSWORD, REGION)

    session = aiohttp.ClientSession()
    asyncio.ensure_future(client.async_get_credentials_and_run(session), loop=loop)
    loop.run_until_complete(asyncio.sleep(60))

    for appliance in client.appliances:
        print(appliance)
```

## Authentication
The authentication process has a few steps.  First, for both the websocket and XMPP APIs, we use Oauth2 to authenticate
to the HTTPS API.  From there, we can either get a websocket endpoint with `access_token` or proceed with the XMPP login
flow.  For XMPP, we get a mobile device token, which in turn be used to get a new `Bearer` token, which, finally,
is used to get XMPP credentials to authenticate to the Jabber server.  In `gehomesdk`, going from username/password
to XMPP credentials is handled by `do_full_xmpp_flow(username, password)`.

## Useful functions
### `do_full_xmpp_flow(username, password)`
Function to authenticate to the web API and get XMPP credentials.  Returns a `dict` of XMPP credentials
### `do_full_wss_flow(username, password)`
Function to authenticate to the web API and get websocket credentials.  Returns a `dict` of WSS credentials

## Objects
### GeWebsocketClient(event_loop=None, username=None, password=None)
Main Websocket client
 * `event_loop: asyncio.AbstractEventLoop` Optional event loop.  If `None`, the client will use `asyncio.get_event_loop()`
 * `username`/`password` Optional strings to use when authenticating
#### Useful Methods
 * `async_get_credentials(session, username=None, password=None)` Get new WSS credentials using either the specified 
 `username` and `password` or ones already set in the constructor. 
 * `get_credentials(username=None, password=None)` Blocking version of the above
 * `add_event_handler(event, callback)` Add an event handler
 * `disconnect()` Disconnect the client
 * `async_run_client()` Run the client
 * `async_get_credentials_and_run(sessions, username=None, password=None)` Authenticate and run the client
#### Properties
 * `appliances` A `Dict[str, GeAppliance]` of all known appliances keyed on the appliances' JIDs.
#### Events
* `EVENT_ADD_APPLIANCE` - Triggered immediately after a new appliance is added, before the initial update request has
even been sent. The `GeAppliance` object is passed to the callback.
* `EVENT_APPLIANCE_INITIAL_UPDATE` - Triggered when an appliance's type changes, at which point we know at least a 
little about the appliance. The `GeAppliance` object is passed to the callback.
* `EVENT_APPLIANCE_STATE_CHANGE` - Triggered when an appliance message with a new state, different from the existing, cached
state is received.  A tuple `(appliance, state_changes)` is passed to the callback, where `appliance` is the 
`GeAppliance` object with the updated state and `state_changes` is a dictionary `{erd_key: new_value}` of the changed
state.
* `EVENT_APPLIANCE_UPDATE_RECEIVED` - Triggered after processing an ERD update message whether or not the state changed
* `EVENT_CONNECTED` - Triggered when the API connects, after adding basic subscriptions
* `EVENT_DISCONNECTED` - Triggered when the API disconnects
* `EVENT_GOT_APPLIANCE_LIST` - Triggered when we get the list of appliances

### GeXmppClient(xmpp_credentials, event_loop=None, **kwargs)
Main XMPP client, and a subclass of `slixmpp.ClientXMPP`.
 * `xmpp_credentials: dict` A dictionary of XMPP credentials, usually obtained from either `do_full_login_flow` or, in a
 more manual process, `get_xmpp_credentials` 
 * `event_loop: asyncio.AbstractEventLoop` Optional event loop.  If `None`, the client will use `asyncio.get_event_loop()`
 * `**kwargs` Passed to `slixmpp.ClientXMPP`
#### Useful Methods
 * `connect()` Connect to the XMPP server
 * `process_in_running_loop(timeout: Optional[int] = None)` Run in an existing event loop.  If `timeout` is given, stop
 running after `timeout` seconds
 * `add_event_handler(name: str, func: Callable)` Add an event handler.  In addition to the events supported by
 `slixmpp.ClientXMPP`, we've added some more event types detailed below.
#### Properties
 * `appliances` A `Dict[str, GeAppliance]` of all known appliances keyed on the appliances' JIDs.
#### Events
In addition to the standard `slixmpp` events, the `GeClient` object has support for the following:
* `EVENT_ADD_APPLIANCE` - Triggered immediately after a new appliance is added, before the initial update request has
even been sent. The `GeAppliance` object is passed to the callback.
* `EVENT_APPLIANCE_INITIAL_UPDATE` - Triggered when an appliance's type changes, at which point we know at least a 
little about the appliance. The `GeAppliance` object is passed to the callback.
* `EVENT_APPLIANCE_STATE_CHANGE` - Triggered when an appliance message with a new state, different from the existing, cached
state is received.  A tuple `(appliance, state_changes)` is passed to the callback, where `appliance` is the 
`GeAppliance` object with the updated state and `state_changes` is a dictionary `{erd_key: new_value}` of the changed
state.

### GeAppliance(mac_addr, client)
Representation of a single appliance
 * `mac_addr: Union[str, slixmpp.JID]` The appliance's MAC address, which is what GE uses as unique identifiers 
 * `client: GeBaseClient` The client used to communicate with the device
#### Useful Methods
 * `decode_erd_value(erd_code: ErdCodeType, erd_value: str)` Decode a raw ERD property value.
 * `encode_erd_value(erd_code: ErdCodeType, erd_value: str)` Decode a raw ERD property value.
 * `get_erd_value(erd_code: ErdCodeType)` Get the cached value of ERD code `erd_code`.  If `erd_code` is a string, this
 function will attempt to convert it to an `ErdCode` object first.
 * `async_request_update()` Request the appliance send an update of all properties
 * `set_available()` Mark the appliance as available
 * `async_set_erd_value(erd_code: ErdType, value)` Tell the device to set the property represented by `erd_code` to `value` 
 * `set_unavailable()` Mark the appliance as unavailable
 * `update_erd_value(erd_code: ErdType, value)` Update the local property cache value for `erd_code` to `value`, where
 value is the not yet decoded hex string sent from the API. Returns `True` if that is a change in state, `False` otherwise.
 * `update_erd_values(self, erd_values: Dict[ErdCodeType, str])` Update multiple values in the local property cache.
 Returns a dictionary of changed states or an empty `dict` if nothing actually changed.
#### Properties
 * `appliance_type: Optional[ErdApplianceType]` The type of appliance, `None` if unknown
 * `available: bool` `True` if the appliance is available, otherwise `False`
 * `mac_addr` The appliance's MAC address (used as the appliance ID)
 

### Useful `Enum` types
* `ErdCode` `Enum` of known ERD property codes
* `ErdApplianceType` Values for `ErdCode.APPLIANCE_TYPE`
* `ErdMeasurementUnits` Values for `ErdCode.TEMPERATURE_UNIT`
* `ErdOvenCookMode` Possible oven cook modes, used for `OvenCookSetting` among other things
* `ErdOvenState` Values for `ErdCode.LOWER_OVEN_CURRENT_STATE` and `ErdCode.UPPER_OVEN_CURRENT_STATE` 

### Other types
* `OvenCookSetting` A `namedtuple` of an `ErdOvenCookMode` and an `int` temperature
* `OvenConfiguration` A `namedtuple` of boolean properties representing an oven's physical configuration



## API Overview

The GE SmartHQ app communicates with devices through (at least) three different APIs: XMPP, HTTP REST, and what they 
seem to call MQTT (though that's not really accurate).  All of them are based around sending (pseudo-)HTTP requests
back and forth.  Device properties are represented by hex codes (represented by `ErdCode` objects in `gehomesdk`), and 
values are sent as hexadecimal strings without leading `"0x"`, then json encoded as a dictionary.  One thing that is
important to note is that not all appliances support every API.

For further documentation of appliance commands, please see the GEMaker Github repositories at:
[https://github.com/GEMakers](https://github.com/GEMakers).  Not every appliance has documentation there, but many do, and it is useful for decoding values that you may see coming from the API.  There is also another Github repository [here](https://github.com/doitaljosh/ge-appliances-re) that has more information about reverse engineering the GE protocols.

1. REST - We can access or set most device properties via HTTP REST.  Unfortunately, relying on this means we need to
 result to constantly polling the devices, which is less than desirable, especially, e.g., for ovens that where we want
 to know exactly when a timer finishes. This API is not directly supported.
2. Websocket "MQTT" - The WSS "MQTT" API is basically a wrapper around the REST API with the ability to subscribe to a
 device, meaning that we can treat it as (in Home Assistant lingo) IoT Cloud Push instead of IoT Cloud Polling.  In 
 `gehomesdk`, support for the websocket API is provided by the `GeWebsocketClient` class. 
2. XMPP - As far as I can tell, there seems to be little, if any, benefit to the XMPP API except that it will notify
 the client if a new device becomes available.  I suspect that this can be achieved with websocket API as well via
 subscriptions, but have not yet tested.  Support for the XMPP API is provided by the `GeXmppClient` class, based on
  [`slixmpp`](https://slixmpp.readthedocs.io/), which it requires as an optional dependency.  

### XMPP API
The device informs the client of a state change by sending a `PUBLISH` message like this, informing us that the value of
property 0x5205 (`ErdCode.LOWER_OVEN_KITCHEN_TIMER` in `gehomesdk`) is now "002d" (45 minutes):

```xml
<body>
    <publish>
        <method>PUBLISH</method>
        <uri>/UUID/erd/0x5205</uri>
        <json>{"0x5205":"002d"}</json>
    </publish>
</body>
```

Similarly, we can set the timer to 45 minutes by `POST`ing to the same "endpoint":
```xml
<body>
    <request>
        <method>POST</method>
        <uri>/UUID/erd/0x5205</uri>
        <json>{"0x5205":"002d"}</json>
    </request>
</body>
``` 
In `gehomesdk`, that would handled by the `GeAppliance.set_erd_value` method:
```python
appliance.async_set_erd_value(ErdCode.LOWER_OVEN_KITCHEN_TIMER, timedelta(minutes=45))
```

We can also get a specific property, or, more commonly, request a full cache refresh by `GET`ing the `/UUID/cache` 
endpoint:

```xml
<body>
    <request>
        <id>0</id>
        <method>GET</method>
        <uri>/UUID/cache</uri>
    </request>
</body>
```

The device will then respond to the `GET` with a `response` having a json payload:
```xml
<body>
    <response>
        <id>0</id>
        <method>GET</method>
        <uri>/UUID/cache</uri>
        <json>{
            "0x0006":"00",
            "0x0007":"00",
            "0x0008":"07",
            "0x0009":"00",
            "0x000a":"03",
            "0x0089":"",
            ...
        }</json>
    </response>
</body>
```


%package -n python3-gehomesdk
Summary:	Python SDK for GE Home Appliances
Provides:	python-gehomesdk
BuildRequires:	python3-devel
BuildRequires:	python3-setuptools
BuildRequires:	python3-pip
%description -n python3-gehomesdk
# gehomesdk
Python SDK for GE WiFi-enabled (SmartHQ) appliances.
The primary goal is to use this to power integrations for [Home Assistant](https://www.home-assistant.io/), though that
will probably need to wait on some new entity types.   

**Forked from Andrew Mark's [repository](https://github.com/ajmarks/gekitchen).**

## Installation

```pip install gehomesdk```

## Changelog

Please click [here](CHANGELOG.md) for change information.

## Usage

### gehome-appliance-data

As of 0.5.0, after installation, you should now be able to use the gehome-appliance-data application:

`gehome-appliance-data [-h] -u USERNAME -p PASSWORD [-r {US,EU}]`

The parameters are as follows:
* -u or --username: Your SmartHQ Username
* -p or --password: Your SmartHQ Password
* -r or --region: Your SmartHQ Region

This application will set up a client, iterate over all appliances, and will update the state every minute.  It will also capture all state changes as they happen (useful for figuring out which values correspond to which function).  You can exit at any time by keyboard interrupt `ctrl^C`

### Credentials

Create a `credentials.py` and place in the `examples` directory.  It should contain the following:

```
USERNAME = "your@email.com"
PASSWORD = "supersecret"
REGION = "US or EU"
```

You will need to replace the username/password values with your credentials.  After that, you can run the `websocket_example.py` (**preferred**) or `xmpp_example.py` sample files.  These will generate information about your appliances and are useful if you'd like to help implement more functionality.

### Simple example
Here we're going to run the client in a pre-existing event loop.  We're also going to register some event callbacks
to update appliances every five minutes and to turn on our oven the first time we see it.  Because that is safe!
```python
import aiohttp
import asyncio
import logging
from gehomesdk.secrets import USERNAME, PASSWORD
from gehomesdk import GeWebsocketClient

_LOGGER = logging.getLogger(__name__)


if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG, format='%(levelname)-8s %(message)s')

    loop = asyncio.get_event_loop()
    client = GeWebsocketClient(loop, USERNAME, PASSWORD, REGION)

    session = aiohttp.ClientSession()
    asyncio.ensure_future(client.async_get_credentials_and_run(session), loop=loop)
    loop.run_until_complete(asyncio.sleep(60))

    for appliance in client.appliances:
        print(appliance)
```

## Authentication
The authentication process has a few steps.  First, for both the websocket and XMPP APIs, we use Oauth2 to authenticate
to the HTTPS API.  From there, we can either get a websocket endpoint with `access_token` or proceed with the XMPP login
flow.  For XMPP, we get a mobile device token, which in turn be used to get a new `Bearer` token, which, finally,
is used to get XMPP credentials to authenticate to the Jabber server.  In `gehomesdk`, going from username/password
to XMPP credentials is handled by `do_full_xmpp_flow(username, password)`.

## Useful functions
### `do_full_xmpp_flow(username, password)`
Function to authenticate to the web API and get XMPP credentials.  Returns a `dict` of XMPP credentials
### `do_full_wss_flow(username, password)`
Function to authenticate to the web API and get websocket credentials.  Returns a `dict` of WSS credentials

## Objects
### GeWebsocketClient(event_loop=None, username=None, password=None)
Main Websocket client
 * `event_loop: asyncio.AbstractEventLoop` Optional event loop.  If `None`, the client will use `asyncio.get_event_loop()`
 * `username`/`password` Optional strings to use when authenticating
#### Useful Methods
 * `async_get_credentials(session, username=None, password=None)` Get new WSS credentials using either the specified 
 `username` and `password` or ones already set in the constructor. 
 * `get_credentials(username=None, password=None)` Blocking version of the above
 * `add_event_handler(event, callback)` Add an event handler
 * `disconnect()` Disconnect the client
 * `async_run_client()` Run the client
 * `async_get_credentials_and_run(sessions, username=None, password=None)` Authenticate and run the client
#### Properties
 * `appliances` A `Dict[str, GeAppliance]` of all known appliances keyed on the appliances' JIDs.
#### Events
* `EVENT_ADD_APPLIANCE` - Triggered immediately after a new appliance is added, before the initial update request has
even been sent. The `GeAppliance` object is passed to the callback.
* `EVENT_APPLIANCE_INITIAL_UPDATE` - Triggered when an appliance's type changes, at which point we know at least a 
little about the appliance. The `GeAppliance` object is passed to the callback.
* `EVENT_APPLIANCE_STATE_CHANGE` - Triggered when an appliance message with a new state, different from the existing, cached
state is received.  A tuple `(appliance, state_changes)` is passed to the callback, where `appliance` is the 
`GeAppliance` object with the updated state and `state_changes` is a dictionary `{erd_key: new_value}` of the changed
state.
* `EVENT_APPLIANCE_UPDATE_RECEIVED` - Triggered after processing an ERD update message whether or not the state changed
* `EVENT_CONNECTED` - Triggered when the API connects, after adding basic subscriptions
* `EVENT_DISCONNECTED` - Triggered when the API disconnects
* `EVENT_GOT_APPLIANCE_LIST` - Triggered when we get the list of appliances

### GeXmppClient(xmpp_credentials, event_loop=None, **kwargs)
Main XMPP client, and a subclass of `slixmpp.ClientXMPP`.
 * `xmpp_credentials: dict` A dictionary of XMPP credentials, usually obtained from either `do_full_login_flow` or, in a
 more manual process, `get_xmpp_credentials` 
 * `event_loop: asyncio.AbstractEventLoop` Optional event loop.  If `None`, the client will use `asyncio.get_event_loop()`
 * `**kwargs` Passed to `slixmpp.ClientXMPP`
#### Useful Methods
 * `connect()` Connect to the XMPP server
 * `process_in_running_loop(timeout: Optional[int] = None)` Run in an existing event loop.  If `timeout` is given, stop
 running after `timeout` seconds
 * `add_event_handler(name: str, func: Callable)` Add an event handler.  In addition to the events supported by
 `slixmpp.ClientXMPP`, we've added some more event types detailed below.
#### Properties
 * `appliances` A `Dict[str, GeAppliance]` of all known appliances keyed on the appliances' JIDs.
#### Events
In addition to the standard `slixmpp` events, the `GeClient` object has support for the following:
* `EVENT_ADD_APPLIANCE` - Triggered immediately after a new appliance is added, before the initial update request has
even been sent. The `GeAppliance` object is passed to the callback.
* `EVENT_APPLIANCE_INITIAL_UPDATE` - Triggered when an appliance's type changes, at which point we know at least a 
little about the appliance. The `GeAppliance` object is passed to the callback.
* `EVENT_APPLIANCE_STATE_CHANGE` - Triggered when an appliance message with a new state, different from the existing, cached
state is received.  A tuple `(appliance, state_changes)` is passed to the callback, where `appliance` is the 
`GeAppliance` object with the updated state and `state_changes` is a dictionary `{erd_key: new_value}` of the changed
state.

### GeAppliance(mac_addr, client)
Representation of a single appliance
 * `mac_addr: Union[str, slixmpp.JID]` The appliance's MAC address, which is what GE uses as unique identifiers 
 * `client: GeBaseClient` The client used to communicate with the device
#### Useful Methods
 * `decode_erd_value(erd_code: ErdCodeType, erd_value: str)` Decode a raw ERD property value.
 * `encode_erd_value(erd_code: ErdCodeType, erd_value: str)` Decode a raw ERD property value.
 * `get_erd_value(erd_code: ErdCodeType)` Get the cached value of ERD code `erd_code`.  If `erd_code` is a string, this
 function will attempt to convert it to an `ErdCode` object first.
 * `async_request_update()` Request the appliance send an update of all properties
 * `set_available()` Mark the appliance as available
 * `async_set_erd_value(erd_code: ErdType, value)` Tell the device to set the property represented by `erd_code` to `value` 
 * `set_unavailable()` Mark the appliance as unavailable
 * `update_erd_value(erd_code: ErdType, value)` Update the local property cache value for `erd_code` to `value`, where
 value is the not yet decoded hex string sent from the API. Returns `True` if that is a change in state, `False` otherwise.
 * `update_erd_values(self, erd_values: Dict[ErdCodeType, str])` Update multiple values in the local property cache.
 Returns a dictionary of changed states or an empty `dict` if nothing actually changed.
#### Properties
 * `appliance_type: Optional[ErdApplianceType]` The type of appliance, `None` if unknown
 * `available: bool` `True` if the appliance is available, otherwise `False`
 * `mac_addr` The appliance's MAC address (used as the appliance ID)
 

### Useful `Enum` types
* `ErdCode` `Enum` of known ERD property codes
* `ErdApplianceType` Values for `ErdCode.APPLIANCE_TYPE`
* `ErdMeasurementUnits` Values for `ErdCode.TEMPERATURE_UNIT`
* `ErdOvenCookMode` Possible oven cook modes, used for `OvenCookSetting` among other things
* `ErdOvenState` Values for `ErdCode.LOWER_OVEN_CURRENT_STATE` and `ErdCode.UPPER_OVEN_CURRENT_STATE` 

### Other types
* `OvenCookSetting` A `namedtuple` of an `ErdOvenCookMode` and an `int` temperature
* `OvenConfiguration` A `namedtuple` of boolean properties representing an oven's physical configuration



## API Overview

The GE SmartHQ app communicates with devices through (at least) three different APIs: XMPP, HTTP REST, and what they 
seem to call MQTT (though that's not really accurate).  All of them are based around sending (pseudo-)HTTP requests
back and forth.  Device properties are represented by hex codes (represented by `ErdCode` objects in `gehomesdk`), and 
values are sent as hexadecimal strings without leading `"0x"`, then json encoded as a dictionary.  One thing that is
important to note is that not all appliances support every API.

For further documentation of appliance commands, please see the GEMaker Github repositories at:
[https://github.com/GEMakers](https://github.com/GEMakers).  Not every appliance has documentation there, but many do, and it is useful for decoding values that you may see coming from the API.  There is also another Github repository [here](https://github.com/doitaljosh/ge-appliances-re) that has more information about reverse engineering the GE protocols.

1. REST - We can access or set most device properties via HTTP REST.  Unfortunately, relying on this means we need to
 result to constantly polling the devices, which is less than desirable, especially, e.g., for ovens that where we want
 to know exactly when a timer finishes. This API is not directly supported.
2. Websocket "MQTT" - The WSS "MQTT" API is basically a wrapper around the REST API with the ability to subscribe to a
 device, meaning that we can treat it as (in Home Assistant lingo) IoT Cloud Push instead of IoT Cloud Polling.  In 
 `gehomesdk`, support for the websocket API is provided by the `GeWebsocketClient` class. 
2. XMPP - As far as I can tell, there seems to be little, if any, benefit to the XMPP API except that it will notify
 the client if a new device becomes available.  I suspect that this can be achieved with websocket API as well via
 subscriptions, but have not yet tested.  Support for the XMPP API is provided by the `GeXmppClient` class, based on
  [`slixmpp`](https://slixmpp.readthedocs.io/), which it requires as an optional dependency.  

### XMPP API
The device informs the client of a state change by sending a `PUBLISH` message like this, informing us that the value of
property 0x5205 (`ErdCode.LOWER_OVEN_KITCHEN_TIMER` in `gehomesdk`) is now "002d" (45 minutes):

```xml
<body>
    <publish>
        <method>PUBLISH</method>
        <uri>/UUID/erd/0x5205</uri>
        <json>{"0x5205":"002d"}</json>
    </publish>
</body>
```

Similarly, we can set the timer to 45 minutes by `POST`ing to the same "endpoint":
```xml
<body>
    <request>
        <method>POST</method>
        <uri>/UUID/erd/0x5205</uri>
        <json>{"0x5205":"002d"}</json>
    </request>
</body>
``` 
In `gehomesdk`, that would handled by the `GeAppliance.set_erd_value` method:
```python
appliance.async_set_erd_value(ErdCode.LOWER_OVEN_KITCHEN_TIMER, timedelta(minutes=45))
```

We can also get a specific property, or, more commonly, request a full cache refresh by `GET`ing the `/UUID/cache` 
endpoint:

```xml
<body>
    <request>
        <id>0</id>
        <method>GET</method>
        <uri>/UUID/cache</uri>
    </request>
</body>
```

The device will then respond to the `GET` with a `response` having a json payload:
```xml
<body>
    <response>
        <id>0</id>
        <method>GET</method>
        <uri>/UUID/cache</uri>
        <json>{
            "0x0006":"00",
            "0x0007":"00",
            "0x0008":"07",
            "0x0009":"00",
            "0x000a":"03",
            "0x0089":"",
            ...
        }</json>
    </response>
</body>
```


%package help
Summary:	Development documents and examples for gehomesdk
Provides:	python3-gehomesdk-doc
%description help
# gehomesdk
Python SDK for GE WiFi-enabled (SmartHQ) appliances.
The primary goal is to use this to power integrations for [Home Assistant](https://www.home-assistant.io/), though that
will probably need to wait on some new entity types.   

**Forked from Andrew Mark's [repository](https://github.com/ajmarks/gekitchen).**

## Installation

```pip install gehomesdk```

## Changelog

Please click [here](CHANGELOG.md) for change information.

## Usage

### gehome-appliance-data

As of 0.5.0, after installation, you should now be able to use the gehome-appliance-data application:

`gehome-appliance-data [-h] -u USERNAME -p PASSWORD [-r {US,EU}]`

The parameters are as follows:
* -u or --username: Your SmartHQ Username
* -p or --password: Your SmartHQ Password
* -r or --region: Your SmartHQ Region

This application will set up a client, iterate over all appliances, and will update the state every minute.  It will also capture all state changes as they happen (useful for figuring out which values correspond to which function).  You can exit at any time by keyboard interrupt `ctrl^C`

### Credentials

Create a `credentials.py` and place in the `examples` directory.  It should contain the following:

```
USERNAME = "your@email.com"
PASSWORD = "supersecret"
REGION = "US or EU"
```

You will need to replace the username/password values with your credentials.  After that, you can run the `websocket_example.py` (**preferred**) or `xmpp_example.py` sample files.  These will generate information about your appliances and are useful if you'd like to help implement more functionality.

### Simple example
Here we're going to run the client in a pre-existing event loop.  We're also going to register some event callbacks
to update appliances every five minutes and to turn on our oven the first time we see it.  Because that is safe!
```python
import aiohttp
import asyncio
import logging
from gehomesdk.secrets import USERNAME, PASSWORD
from gehomesdk import GeWebsocketClient

_LOGGER = logging.getLogger(__name__)


if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG, format='%(levelname)-8s %(message)s')

    loop = asyncio.get_event_loop()
    client = GeWebsocketClient(loop, USERNAME, PASSWORD, REGION)

    session = aiohttp.ClientSession()
    asyncio.ensure_future(client.async_get_credentials_and_run(session), loop=loop)
    loop.run_until_complete(asyncio.sleep(60))

    for appliance in client.appliances:
        print(appliance)
```

## Authentication
The authentication process has a few steps.  First, for both the websocket and XMPP APIs, we use Oauth2 to authenticate
to the HTTPS API.  From there, we can either get a websocket endpoint with `access_token` or proceed with the XMPP login
flow.  For XMPP, we get a mobile device token, which in turn be used to get a new `Bearer` token, which, finally,
is used to get XMPP credentials to authenticate to the Jabber server.  In `gehomesdk`, going from username/password
to XMPP credentials is handled by `do_full_xmpp_flow(username, password)`.

## Useful functions
### `do_full_xmpp_flow(username, password)`
Function to authenticate to the web API and get XMPP credentials.  Returns a `dict` of XMPP credentials
### `do_full_wss_flow(username, password)`
Function to authenticate to the web API and get websocket credentials.  Returns a `dict` of WSS credentials

## Objects
### GeWebsocketClient(event_loop=None, username=None, password=None)
Main Websocket client
 * `event_loop: asyncio.AbstractEventLoop` Optional event loop.  If `None`, the client will use `asyncio.get_event_loop()`
 * `username`/`password` Optional strings to use when authenticating
#### Useful Methods
 * `async_get_credentials(session, username=None, password=None)` Get new WSS credentials using either the specified 
 `username` and `password` or ones already set in the constructor. 
 * `get_credentials(username=None, password=None)` Blocking version of the above
 * `add_event_handler(event, callback)` Add an event handler
 * `disconnect()` Disconnect the client
 * `async_run_client()` Run the client
 * `async_get_credentials_and_run(sessions, username=None, password=None)` Authenticate and run the client
#### Properties
 * `appliances` A `Dict[str, GeAppliance]` of all known appliances keyed on the appliances' JIDs.
#### Events
* `EVENT_ADD_APPLIANCE` - Triggered immediately after a new appliance is added, before the initial update request has
even been sent. The `GeAppliance` object is passed to the callback.
* `EVENT_APPLIANCE_INITIAL_UPDATE` - Triggered when an appliance's type changes, at which point we know at least a 
little about the appliance. The `GeAppliance` object is passed to the callback.
* `EVENT_APPLIANCE_STATE_CHANGE` - Triggered when an appliance message with a new state, different from the existing, cached
state is received.  A tuple `(appliance, state_changes)` is passed to the callback, where `appliance` is the 
`GeAppliance` object with the updated state and `state_changes` is a dictionary `{erd_key: new_value}` of the changed
state.
* `EVENT_APPLIANCE_UPDATE_RECEIVED` - Triggered after processing an ERD update message whether or not the state changed
* `EVENT_CONNECTED` - Triggered when the API connects, after adding basic subscriptions
* `EVENT_DISCONNECTED` - Triggered when the API disconnects
* `EVENT_GOT_APPLIANCE_LIST` - Triggered when we get the list of appliances

### GeXmppClient(xmpp_credentials, event_loop=None, **kwargs)
Main XMPP client, and a subclass of `slixmpp.ClientXMPP`.
 * `xmpp_credentials: dict` A dictionary of XMPP credentials, usually obtained from either `do_full_login_flow` or, in a
 more manual process, `get_xmpp_credentials` 
 * `event_loop: asyncio.AbstractEventLoop` Optional event loop.  If `None`, the client will use `asyncio.get_event_loop()`
 * `**kwargs` Passed to `slixmpp.ClientXMPP`
#### Useful Methods
 * `connect()` Connect to the XMPP server
 * `process_in_running_loop(timeout: Optional[int] = None)` Run in an existing event loop.  If `timeout` is given, stop
 running after `timeout` seconds
 * `add_event_handler(name: str, func: Callable)` Add an event handler.  In addition to the events supported by
 `slixmpp.ClientXMPP`, we've added some more event types detailed below.
#### Properties
 * `appliances` A `Dict[str, GeAppliance]` of all known appliances keyed on the appliances' JIDs.
#### Events
In addition to the standard `slixmpp` events, the `GeClient` object has support for the following:
* `EVENT_ADD_APPLIANCE` - Triggered immediately after a new appliance is added, before the initial update request has
even been sent. The `GeAppliance` object is passed to the callback.
* `EVENT_APPLIANCE_INITIAL_UPDATE` - Triggered when an appliance's type changes, at which point we know at least a 
little about the appliance. The `GeAppliance` object is passed to the callback.
* `EVENT_APPLIANCE_STATE_CHANGE` - Triggered when an appliance message with a new state, different from the existing, cached
state is received.  A tuple `(appliance, state_changes)` is passed to the callback, where `appliance` is the 
`GeAppliance` object with the updated state and `state_changes` is a dictionary `{erd_key: new_value}` of the changed
state.

### GeAppliance(mac_addr, client)
Representation of a single appliance
 * `mac_addr: Union[str, slixmpp.JID]` The appliance's MAC address, which is what GE uses as unique identifiers 
 * `client: GeBaseClient` The client used to communicate with the device
#### Useful Methods
 * `decode_erd_value(erd_code: ErdCodeType, erd_value: str)` Decode a raw ERD property value.
 * `encode_erd_value(erd_code: ErdCodeType, erd_value: str)` Decode a raw ERD property value.
 * `get_erd_value(erd_code: ErdCodeType)` Get the cached value of ERD code `erd_code`.  If `erd_code` is a string, this
 function will attempt to convert it to an `ErdCode` object first.
 * `async_request_update()` Request the appliance send an update of all properties
 * `set_available()` Mark the appliance as available
 * `async_set_erd_value(erd_code: ErdType, value)` Tell the device to set the property represented by `erd_code` to `value` 
 * `set_unavailable()` Mark the appliance as unavailable
 * `update_erd_value(erd_code: ErdType, value)` Update the local property cache value for `erd_code` to `value`, where
 value is the not yet decoded hex string sent from the API. Returns `True` if that is a change in state, `False` otherwise.
 * `update_erd_values(self, erd_values: Dict[ErdCodeType, str])` Update multiple values in the local property cache.
 Returns a dictionary of changed states or an empty `dict` if nothing actually changed.
#### Properties
 * `appliance_type: Optional[ErdApplianceType]` The type of appliance, `None` if unknown
 * `available: bool` `True` if the appliance is available, otherwise `False`
 * `mac_addr` The appliance's MAC address (used as the appliance ID)
 

### Useful `Enum` types
* `ErdCode` `Enum` of known ERD property codes
* `ErdApplianceType` Values for `ErdCode.APPLIANCE_TYPE`
* `ErdMeasurementUnits` Values for `ErdCode.TEMPERATURE_UNIT`
* `ErdOvenCookMode` Possible oven cook modes, used for `OvenCookSetting` among other things
* `ErdOvenState` Values for `ErdCode.LOWER_OVEN_CURRENT_STATE` and `ErdCode.UPPER_OVEN_CURRENT_STATE` 

### Other types
* `OvenCookSetting` A `namedtuple` of an `ErdOvenCookMode` and an `int` temperature
* `OvenConfiguration` A `namedtuple` of boolean properties representing an oven's physical configuration



## API Overview

The GE SmartHQ app communicates with devices through (at least) three different APIs: XMPP, HTTP REST, and what they 
seem to call MQTT (though that's not really accurate).  All of them are based around sending (pseudo-)HTTP requests
back and forth.  Device properties are represented by hex codes (represented by `ErdCode` objects in `gehomesdk`), and 
values are sent as hexadecimal strings without leading `"0x"`, then json encoded as a dictionary.  One thing that is
important to note is that not all appliances support every API.

For further documentation of appliance commands, please see the GEMaker Github repositories at:
[https://github.com/GEMakers](https://github.com/GEMakers).  Not every appliance has documentation there, but many do, and it is useful for decoding values that you may see coming from the API.  There is also another Github repository [here](https://github.com/doitaljosh/ge-appliances-re) that has more information about reverse engineering the GE protocols.

1. REST - We can access or set most device properties via HTTP REST.  Unfortunately, relying on this means we need to
 result to constantly polling the devices, which is less than desirable, especially, e.g., for ovens that where we want
 to know exactly when a timer finishes. This API is not directly supported.
2. Websocket "MQTT" - The WSS "MQTT" API is basically a wrapper around the REST API with the ability to subscribe to a
 device, meaning that we can treat it as (in Home Assistant lingo) IoT Cloud Push instead of IoT Cloud Polling.  In 
 `gehomesdk`, support for the websocket API is provided by the `GeWebsocketClient` class. 
2. XMPP - As far as I can tell, there seems to be little, if any, benefit to the XMPP API except that it will notify
 the client if a new device becomes available.  I suspect that this can be achieved with websocket API as well via
 subscriptions, but have not yet tested.  Support for the XMPP API is provided by the `GeXmppClient` class, based on
  [`slixmpp`](https://slixmpp.readthedocs.io/), which it requires as an optional dependency.  

### XMPP API
The device informs the client of a state change by sending a `PUBLISH` message like this, informing us that the value of
property 0x5205 (`ErdCode.LOWER_OVEN_KITCHEN_TIMER` in `gehomesdk`) is now "002d" (45 minutes):

```xml
<body>
    <publish>
        <method>PUBLISH</method>
        <uri>/UUID/erd/0x5205</uri>
        <json>{"0x5205":"002d"}</json>
    </publish>
</body>
```

Similarly, we can set the timer to 45 minutes by `POST`ing to the same "endpoint":
```xml
<body>
    <request>
        <method>POST</method>
        <uri>/UUID/erd/0x5205</uri>
        <json>{"0x5205":"002d"}</json>
    </request>
</body>
``` 
In `gehomesdk`, that would handled by the `GeAppliance.set_erd_value` method:
```python
appliance.async_set_erd_value(ErdCode.LOWER_OVEN_KITCHEN_TIMER, timedelta(minutes=45))
```

We can also get a specific property, or, more commonly, request a full cache refresh by `GET`ing the `/UUID/cache` 
endpoint:

```xml
<body>
    <request>
        <id>0</id>
        <method>GET</method>
        <uri>/UUID/cache</uri>
    </request>
</body>
```

The device will then respond to the `GET` with a `response` having a json payload:
```xml
<body>
    <response>
        <id>0</id>
        <method>GET</method>
        <uri>/UUID/cache</uri>
        <json>{
            "0x0006":"00",
            "0x0007":"00",
            "0x0008":"07",
            "0x0009":"00",
            "0x000a":"03",
            "0x0089":"",
            ...
        }</json>
    </response>
</body>
```


%prep
%autosetup -n gehomesdk-0.5.11

%build
%py3_build

%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
	find usr/lib -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
	find usr/lib64 -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
	find usr/bin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
	find usr/sbin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
	find usr/share/man -type f -printf "\"/%h/%f.gz\"\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .

%files -n python3-gehomesdk -f filelist.lst
%dir %{python3_sitelib}/*

%files help -f doclist.lst
%{_docdir}/*

%changelog
* Thu Jun 08 2023 Python_Bot <Python_Bot@openeuler.org> - 0.5.11-1
- Package Spec generated