forked from Yurik72/ESPHap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
arduino_homekit_server.cpp
4387 lines (3702 loc) · 128 KB
/
arduino_homekit_server.cpp
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
#include "port_x.h"
#ifdef ARDUINO8266_SERVER_CPP
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiServer.h>
#include <WiFiClient.h>
#include <ESP8266mDNS.h>
#include <LEAmDNS.h>
#include "user_interface.h"
//#include <wolfssl/wolfcrypt/settings.h>
#include <homekit.h>
#include <characteristics.h>
#include <tlv.h>
#include <types.h>
//#include <wolfssl/wolfcrypt/hash.h> //wc_sha512
//#include <wolfssl.h>
#include <wolfssl/wolfcrypt/hash.h>
#include <wolfssl/wolfcrypt/coding.h>
//#include "constants.h"
#include "esphap_base64.h"
#include "pairing.h"
#include "storage.h"
#include "query_params.h"
#include "esphap_cJSON.h"
#include "cJSON_memory.h"
#include "json.h"
#include "esphap_debug.h"
#include "port.h"
#include "http_parser.h"
#include "query_params.h"
#include "cQueue.h"
#include "crypto.h"
#include "watchdog.h"
#include "arduino_homekit_server.h"
#define HOMEKIT_SERVER_PORT 5556
#define HOMEKIT_ARDUINO_SERVER_PORT HOMEKIT_SERVER_PORT
#define HOMEKIT_MAX_CLIENTS 8
#define CLIENT_CONTEXT_CACHE_SIZE 8
#define HOMEKIT_MDNS_SERVICE "hap"//"_hap"
#define HOMEKIT_MDNS_PROTO "tcp"//"_tcp"
#define HOMEKIT_EVENT_QUEUE_SIZE 4 //original is 20
//See WiFiClient.h WIFICLIENT_MAX_FLUSH_WAIT_MS
#define HOMEKIT_SOCKET_FLUSH_WAIT_MS 500 //milliseconds
#define DISCONNECT_ALIVE_DELAY_S 4
#define WIFI_CLIENT_SYNC true
#define WIFI_CLIENT_NODELAY true //in theory not neccessary to set false when sync true
//#define TCP_DEFAULT_KEEPALIVE_IDLE_SEC 7200 // 2 hours
//#define TCP_DEFAULT_KEEPALIVE_INTERVAL_SEC 75 // 75 sec
//#define TCP_DEFAULT_KEEPALIVE_COUNT 9 // fault after 9 failures
//const int idle = 180; /* 180 sec idle before start sending probes */
#define HOMEKIT_SOCKET_KEEPALIVE_IDLE_SEC 120
//const int interval = 30; /* 30 sec between probes */
#define HOMEKIT_SOCKET_KEEPALIVE_INTERVAL_SEC 20
//const int maxpkt = 4; /* Drop connection after 4 probes without response */
#define HOMEKIT_SOCKET_KEEPALIVE_IDLE_COUNT 4
// if 180 + 30 * 4 = 300 sec without socket response, disconected it.
#ifdef HOMEKIT_DEBUG
#define TLV_DEBUG(values) tlv_debug(values)
#else
#define TLV_DEBUG(values)
#endif
#define CLIENT_DEBUG(client, message, ...) DEBUG("[Client %d] " message, client->socket, ##__VA_ARGS__)
#define CLIENT_INFO(client, message, ...) INFO("[Client %d] " message, client->socket, ##__VA_ARGS__)
#define CLIENT_ERROR(client, message, ...) ERROR("[Client %d] " message, client->socket, ##__VA_ARGS__)
client_context_t *current_client_context = NULL;
WiFiEventHandler arduino_homekit_gotiphandler;
#define HOMEKIT_NOTIFY_EVENT(server, event) \
if ((server)->config->on_event) \
(server)->config->on_event(event);
extern "C" {
typedef struct {
WiFiServer *wifi_server;
char* accessory_id;
ed25519_key* accessory_key;
homekit_server_config_t *config;
byte data[1024 + 18];
byte output_buffer[1024];
#ifdef PAIRVERIFY_USE_MEMORYBUFFER
byte data_verify[1024];
#endif
bool paired;
pairing_context_t *pairing_context;
http_parser parser;
json_stream json;
//int listen_fd;
//fd_set fds;
//int max_fd;
int nfds;// arduino homekit uses this to record client count
bool request_completed;
client_context_t *clients;
} homekit_server_t;
struct _client_context_t {
homekit_server_t *server;
//int socket;
WiFiClient *socket; //new and delete
homekit_endpoint_t endpoint;
query_param_t *endpoint_params;
char *body;
size_t body_length;
//http_parser parser;
int pairing_id;
byte permissions;
bool disconnect;
homekit_characteristic_t *current_characteristic;
homekit_value_t *current_value;
bool encrypted;
byte read_key[32];
byte write_key[32];
int count_reads;
int count_writes;
bool is_wrong_endpoint = false;
//QueueHandle_t event_queue;
Queue_t *event_queue;
pair_verify_context_t *verify_context;
homekit_client_step_t step; // WangBin added
bool error_write; // WangBin added
bool is_static;
bool is_used;
long disconnect_ms;
struct _client_context_t *next;
};
}
void client_context_free(client_context_t *c);
void pairing_context_free(pairing_context_t *context);
void client_send_chunk(byte *data, size_t size, void *arg);
void homekit_server_close_client(homekit_server_t *server, client_context_t *context);
void homekit_mdns_init(homekit_server_t *server);
void homekit_init_client_context(client_context_t *c, WiFiClient *wifiClient);
homekit_server_t *running_server = nullptr;
bool arduino_homekit_preinit(homekit_server_t *server);
static client_context_t cache_client_contexts[CLIENT_CONTEXT_CACHE_SIZE];
static bool is_initialized = false;
static bool mdns_announce=false;
#ifdef USE_STATIC_HTTP_BODY
byte static_http_body[512];
#endif
homekit_value_t HOMEKIT_DEFAULT_CPP() {
homekit_value_t homekit_value;
//homekit_value.is_null = false;//该值为默认,不用设置
return homekit_value;
}
homekit_value_t HOMEKIT_NULL_CPP() {
homekit_value_t homekit_value;
homekit_value.is_null = true;
return homekit_value;
}
homekit_value_t HOMEKIT_BOOL_CPP(bool value) {
homekit_value_t homekit_value = HOMEKIT_DEFAULT_CPP();
homekit_value.format = homekit_format_bool;
homekit_value.bool_value = value;
return homekit_value;
};
homekit_value_t HOMEKIT_INT_CPP(uint8_t value) {
homekit_value_t homekit_value = HOMEKIT_DEFAULT_CPP();
homekit_value.format = homekit_format_int;
homekit_value.int_value = value;
return homekit_value;
}
homekit_value_t HOMEKIT_UINT8_CPP(uint8_t value) {
homekit_value_t homekit_value = HOMEKIT_DEFAULT_CPP();
homekit_value.format = homekit_format_uint8;
homekit_value.int_value = value;
return homekit_value;
}
homekit_value_t HOMEKIT_UINT16_CPP(uint16_t value) {
homekit_value_t homekit_value = HOMEKIT_DEFAULT_CPP();
homekit_value.format = homekit_format_uint16;
homekit_value.int_value = value;
return homekit_value;
}
homekit_value_t HOMEKIT_UINT32_CPP(uint32_t value) {
homekit_value_t homekit_value = HOMEKIT_DEFAULT_CPP();
homekit_value.format = homekit_format_uint32;
homekit_value.int_value = value;
return homekit_value;
}
homekit_value_t HOMEKIT_UINT64_CPP(uint64_t value) {
homekit_value_t homekit_value = HOMEKIT_DEFAULT_CPP();
homekit_value.format = homekit_format_uint64;
homekit_value.int_value = value;
return homekit_value;
}
homekit_value_t HOMEKIT_FLOAT_CPP(float value) {
homekit_value_t homekit_value = HOMEKIT_DEFAULT_CPP();
homekit_value.format = homekit_format_float;
homekit_value.float_value = value;
return homekit_value;
}
homekit_value_t HOMEKIT_STRING_CPP(char *value) {
homekit_value_t homekit_value = HOMEKIT_DEFAULT_CPP();
homekit_value.format = homekit_format_string;
homekit_value.string_value = value;
return homekit_value;
}
homekit_value_t HOMEKIT_TLV_CPP(tlv_values_t *value) {
homekit_value_t homekit_value = HOMEKIT_DEFAULT_CPP();
homekit_value.format = homekit_format_tlv;
homekit_value.tlv_values = value;
return homekit_value;
}
homekit_value_t HOMEKIT_DATA_CPP(uint8_t *value, size_t size) {
homekit_value_t homekit_value = HOMEKIT_DEFAULT_CPP();
homekit_value.format = homekit_format_data;
//homekit_value.data_value = value;
//homekit_value.data_size = size;
return homekit_value;
}
homekit_server_t* server_new() {
homekit_server_t *server = (homekit_server_t*)malloc(sizeof(homekit_server_t));
server->wifi_server = new WiFiServer(HOMEKIT_SERVER_PORT);
server->wifi_server->begin();
#ifdef WIFI_CLIENT_NODELAY
server->wifi_server->setNoDelay(WIFI_CLIENT_NODELAY);
#else
server->wifi_server->setNoDelay(true);
#endif
#ifdef WIFI_CLIENT_SYNC
WiFiClient::setDefaultSync(WIFI_CLIENT_SYNC);
#endif
#ifdef WIFI_CLIENT_NODELAY
WiFiClient::setDefaultNoDelay(WIFI_CLIENT_NODELAY);
#endif
http_parser_init(&server->parser, HTTP_REQUEST);
json_init(&server->json, server->output_buffer, sizeof(server->output_buffer),
client_send_chunk, NULL);
DEBUG("WiFiServer begin at port: %d\n", HOMEKIT_ARDUINO_SERVER_PORT);
//FD_ZERO(&server->fds);
//server->max_fd = 0;
server->nfds = 0;
server->config = NULL;
server->paired = false;
server->pairing_context = NULL;
server->clients = NULL;
server->accessory_id = NULL;
server->accessory_key = NULL;
return server;
}
void server_free(homekit_server_t *server) {
if (server->pairing_context)
pairing_context_free(server->pairing_context);
if (server->clients) {
client_context_t *client = server->clients;
while (client) {
client_context_t *next = client->next;
client_context_free(client);
client = next;
}
}
if (server->accessory_id)
free(server->accessory_id);
if (server->accessory_key)
crypto_ed25519_free(server->accessory_key);
if (server->wifi_server) {
server->wifi_server->stop();
server->wifi_server->close();
delete server->wifi_server;
server->wifi_server = nullptr;
}DEBUG("homekit_server_t delete WiFiServer at port: d\n", HOMEKIT_ARDUINO_SERVER_PORT);
if (server == running_server) {
running_server = NULL;
}
free(server);
}
void tlv_debug(const tlv_values_t *values) {
DEBUG("Got following TLV values:");
for (tlv_t *t = values->head; t; t = t->next) {
char *escaped_payload = binary_to_string(t->value, t->size);
DEBUG("Type %d value (%d bytes): %s", t->type, t->size, escaped_payload);
free(escaped_payload);
}
}
pair_verify_context_t* pair_verify_context_new() {
pair_verify_context_t *context = (pair_verify_context_t*)malloc(sizeof(pair_verify_context_t));
context->secret = NULL;
context->secret_size = 0;
context->session_key = NULL;
context->session_key_size = 0;
context->device_public_key = NULL;
context->device_public_key_size = 0;
context->accessory_public_key = NULL;
context->accessory_public_key_size = 0;
return context;
}
void pair_verify_context_free(pair_verify_context_t *context) {
if (context->secret)
free(context->secret);
context->secret = NULL;
if (context->session_key)
free(context->session_key);
context->session_key = NULL;
if (context->device_public_key)
free(context->device_public_key);
context->device_public_key = NULL;
if (context->accessory_public_key)
free(context->accessory_public_key);
context->accessory_public_key = NULL;
free(context);
}
//==========================
// client_context new and free and handling
//============================
void server_static_init() {
if (is_initialized)
return;
for (int i = 0; i < CLIENT_CONTEXT_CACHE_SIZE; i++) {
client_context_t*c = &(cache_client_contexts[i]);
homekit_init_client_context(c,NULL);
c->is_static = true;
c->is_used = false;
}
is_initialized = true;
}
void homekit_init_client_context(client_context_t *c, WiFiClient *wifiClient) {
c->server = NULL;
c->endpoint_params = NULL;
c->is_wrong_endpoint = false;
c->body = NULL;
c->body_length = 0;
c->pairing_id = -1;
c->encrypted = false;
c->count_reads = 0;
c->count_writes = 0;
c->disconnect = false;
c->disconnect_ms = 0;
c->event_queue = (Queue_t*)malloc(sizeof(Queue_t));
q_init(c->event_queue, sizeof(characteristic_event_t*),
HOMEKIT_EVENT_QUEUE_SIZE, LIFO, true);
c->verify_context = NULL;
c->next = NULL;
c->socket = wifiClient;
c->step = HOMEKIT_CLIENT_STEP_NONE;
c->error_write = false;
c->is_static = false;
c->is_used = false;
}
client_context_t* client_context_new(WiFiClient *wifiClient) {
for (int i = 0; i < CLIENT_CONTEXT_CACHE_SIZE; i++) {
client_context_t*c = &(cache_client_contexts[i]);
if (!c->is_used) {
c->socket = wifiClient;
c->is_used = true;
CLIENT_INFO(c, "Got client content from the cache %d",i);
return c;
}
}
client_context_t *c = (client_context_t*)malloc(sizeof(client_context_t));
homekit_init_client_context(c, wifiClient);
return c;
}
void client_context_free(client_context_t *c) {
CLIENT_INFO(c, "client content free");
c->body_length = 0;
c->is_wrong_endpoint = false;
c->pairing_id = -1;
c->encrypted = false;
c->count_reads = 0;
c->count_writes = 0;
c->error_write = false;
c->disconnect = false;
c->step = HOMEKIT_CLIENT_STEP_NONE;
if (c->verify_context)
pair_verify_context_free(c->verify_context);
c->verify_context = nullptr;
c->disconnect_ms = 0;
if (c->endpoint_params)
query_params_free(c->endpoint_params);
c->endpoint_params = nullptr;
#ifdef USE_STATIC_HTTP_BODY
if (c->body && c->body ==(char*) static_http_body) {
c->body = nullptr;
}
#endif
if (c->body)
free(c->body);
c->body = nullptr;
c->body_length = 0;
if (c->socket) {
c->socket->stop();
delete c->socket;
c->socket = nullptr;
}
characteristic_event_t *event = NULL;
if (c->event_queue ) {
while (q_pop(c->event_queue, &event)) {
CLIENT_INFO(c, "Client queue is not empty destruct them..");
homekit_value_destruct(&event->value);
free(event);
}
}
if (c->is_static) {
c->is_used = false;
if (c->event_queue)
q_clean(c->event_queue);
return;
}
if (c->event_queue) {
//c->event_queue->clear();
characteristic_event_t *event = NULL;
q_clean(c->event_queue);
q_kill(c->event_queue);
free(c->event_queue);
}
free(c);
}
pairing_context_t *saved_preinit_pairing_context = nullptr;
pairing_context_t* pairing_context_new() {
pairing_context_t *context = (pairing_context_t*)malloc(sizeof(pairing_context_t));
context->srp = crypto_srp_new();
context->client = NULL;
context->public_key = NULL;
context->public_key_size = 0;
return context;
}
void pairing_context_free(pairing_context_t *context) {
if (context == saved_preinit_pairing_context) {
INFO("Free saved_preinit_pairing_context");
if (saved_preinit_pairing_context) {
saved_preinit_pairing_context = nullptr;
}
}
if (context->srp) {
crypto_srp_free(context->srp);
}
if (context->public_key) {
free(context->public_key);
}
free(context);
}
//=====================
//pairing context
//=====================
void client_notify_characteristic(homekit_characteristic_t *ch, homekit_value_t value,
void *client);
void write_characteristic_json(json_stream *json, client_context_t *client,
const homekit_characteristic_t *ch, characteristic_format_t format,
const homekit_value_t *value) {
json_string(json, "aid");
//json_uint32(json, ch->service->accessory->id);
json_integer(json, ch->service->accessory->id);
json_string(json, "iid");
//json_uint32(json, ch->id);
json_integer(json, ch->id);
if (format & characteristic_format_type) {
json_string(json, "type");
json_string(json, ch->type);
}
if (format & characteristic_format_perms) {
json_string(json, "perms");
json_array_start(json);
if (ch->permissions & homekit_permissions_paired_read)
json_string(json, "pr");
if (ch->permissions & homekit_permissions_paired_write)
json_string(json, "pw");
if (ch->permissions & homekit_permissions_notify)
json_string(json, "ev");
if (ch->permissions & homekit_permissions_additional_authorization)
json_string(json, "aa");
if (ch->permissions & homekit_permissions_timed_write)
json_string(json, "tw");
if (ch->permissions & homekit_permissions_hidden)
json_string(json, "hd");
json_array_end(json);
}
if ((format & characteristic_format_events) && (ch->permissions & homekit_permissions_notify)) {
bool events = homekit_characteristic_has_notify_callback(ch, client_notify_characteristic,
client);
json_string(json, "ev");
json_boolean(json, events);
}
if (format & characteristic_format_meta) {
if (ch->description) {
json_string(json, "description");
json_string(json, ch->description);
}
const char *format_str = NULL;
switch (ch->format) {
case homekit_format_bool:
format_str = "bool";
break;
case homekit_format_uint8:
format_str = "uint8";
break;
case homekit_format_uint16:
format_str = "uint16";
break;
case homekit_format_uint32:
format_str = "uint32";
break;
case homekit_format_uint64:
format_str = "uint64";
break;
case homekit_format_int:
format_str = "int";
break;
case homekit_format_float:
format_str = "float";
break;
case homekit_format_string:
format_str = "string";
break;
case homekit_format_tlv:
format_str = "tlv8";
break;
case homekit_format_data:
format_str = "data";
break;
}
if (format_str) {
json_string(json, "format");
json_string(json, format_str);
}
const char *unit_str = NULL;
switch (ch->unit) {
case homekit_unit_none:
break;
case homekit_unit_celsius:
unit_str = "celsius";
break;
case homekit_unit_percentage:
unit_str = "percentage";
break;
case homekit_unit_arcdegrees:
unit_str = "arcdegrees";
break;
case homekit_unit_lux:
unit_str = "lux";
break;
case homekit_unit_seconds:
unit_str = "seconds";
break;
}
if (unit_str) {
json_string(json, "unit");
json_string(json, unit_str);
}
if (ch->min_value) {
json_string(json, "minValue");
json_float(json, *ch->min_value);
}
if (ch->max_value) {
json_string(json, "maxValue");
json_float(json, *ch->max_value);
}
if (ch->min_step) {
json_string(json, "minStep");
json_float(json, *ch->min_step);
}
if (ch->max_len) {
json_string(json, "maxLen");
//json_uint32(json, *ch->max_len);
json_integer(json, *ch->max_len);
}
if (ch->max_data_len) {
json_string(json, "maxDataLen");
//json_uint32(json, *ch->max_data_len);
json_integer(json, *ch->max_len);
}
if (ch->valid_values.count) {
json_string(json, "valid-values");
json_array_start(json);
for (int i = 0; i < ch->valid_values.count; i++) {
//json_uint16(json, ch->valid_values.values[i]);
json_integer(json, ch->valid_values.values[i]);
}
json_array_end(json);
}
if (ch->valid_values_ranges.count) {
json_string(json, "valid-values-range");
json_array_start(json);
for (int i = 0; i < ch->valid_values_ranges.count; i++) {
json_array_start(json);
json_integer(json, ch->valid_values_ranges.ranges[i].start);
json_integer(json, ch->valid_values_ranges.ranges[i].end);
json_array_end(json);
}
json_array_end(json);
}
}
if (ch->permissions & homekit_permissions_paired_read) {
homekit_value_t v = value ? *value : ch->getter_ex ? ch->getter_ex(ch) : ch->value;
if (v.is_null) {
// json_string(json, "value"); json_null(json);
}
else if (v.format != ch->format) {
ERROR("Characteristic value format is different from characteristic format");
}
else {
switch (v.format) {
case homekit_format_bool: {
json_string(json, "value");
json_boolean(json, v.bool_value);
break;
}
case homekit_format_uint8:
// {
// json_string(json, "value");
// json_uint8(json, v.uint8_value);
// break;
// }
case homekit_format_uint16:
// {
// json_string(json, "value");
// json_uint16(json, v.uint16_value);
// break;
// }
case homekit_format_uint32:
// {
// json_string(json, "value");
// json_uint32(json, v.uint32_value);
// break;
// }
case homekit_format_uint64:
// {
// json_string(json, "value");
// json_uint64(json, v.uint64_value);
// break;
// }
case homekit_format_int: {
json_string(json, "value");
json_integer(json, v.int_value);
break;
}
case homekit_format_float: {
json_string(json, "value");
json_float(json, v.float_value);
break;
}
case homekit_format_string: {
json_string(json, "value");
json_string(json, v.string_value);
break;
}
case homekit_format_tlv: {
json_string(json, "value");
if (!v.tlv_values) {
json_string(json, "");
}
else {
size_t tlv_size = 0;
tlv_format(v.tlv_values, NULL, &tlv_size);
if (tlv_size == 0) {
json_string(json, "");
}
else {
byte *tlv_data = (byte*)malloc(tlv_size);
tlv_format(v.tlv_values, tlv_data, &tlv_size);
size_t encoded_tlv_size = base64_encoded_size(tlv_data, tlv_size);
byte *encoded_tlv_data = (byte*)malloc(encoded_tlv_size + 1);
CLIENT_INFO(client,"write tlv json encoded_tlv_size:%d,tlv_size:%d", encoded_tlv_size, tlv_size);
//base64_encode_(tlv_data, tlv_size, encoded_tlv_data);
esphap_base64_encode(tlv_data, tlv_size, encoded_tlv_data);
encoded_tlv_data[encoded_tlv_size] = 0;
json_string(json, (char*)encoded_tlv_data);
free(encoded_tlv_data);
free(tlv_data);
}
}
break;
}
case homekit_format_data: {
// json_string(json, "value");
// if (!v.data_value || v.data_size == 0) {
// json_string(json, "");
// } else {
// size_t encoded_data_size = base64_encoded_size(v.data_value, v.data_size);
// byte *encoded_data = (byte*) malloc(encoded_data_size + 1);
// base64_encode_(v.data_value, v.data_size, encoded_data);
// encoded_data[encoded_data_size] = 0;
// json_string(json, (char*) encoded_data);
// free(encoded_data);
// }
break;
}
}
}
if (!value && ch->getter_ex) {
// called getter to get value, need to free it
homekit_value_destruct(&v);
}
}
}
void write(client_context_t *context, byte *data, int data_size) {
if (context == nullptr || context->socket == nullptr) {
CLIENT_ERROR(context, "The socket is null! (or is closed)");
return;
}
if (context->disconnect) {
context->error_write = true;
return;
}
if (context->error_write ) {
CLIENT_ERROR(context, "error_in_write_data is true, abort write data");
return;
}
int availableForWrite = context->socket->availableForWrite();
bool isChunked = false;
if (availableForWrite < data_size) {
CLIENT_INFO(context, "Socket not available to write size:%d,available:%d", data_size, availableForWrite);
//if(availableForWrite)
context->socket->flush(); //???
isChunked = true;// TCP_MSS < 1460;
}
int attempts = 0;
while (!availableForWrite && attempts < 5) {
availableForWrite = context->socket->availableForWrite();
CLIENT_INFO(context, "Attempt :%d, available:%d", attempts, availableForWrite);
if (!availableForWrite) {
optimistic_yield(1000);
}
else {
isChunked = availableForWrite < data_size;
break;
}
attempts++;
}
int write_size = 0;
//CLIENT_INFO(context, "write size:%d,available:%d, sync:%d,nodelay:%d", data_size, availableForWrite, context->socket->getSync(), context->socket->getNoDelay());
if (isChunked) {
int writed = 0;
int write_oustanding = data_size;
while (availableForWrite && writed< data_size) {
int chunk_writed = context->socket->write(data+writed, min(write_oustanding,availableForWrite));
availableForWrite = context->socket->availableForWrite();
writed += chunk_writed;
write_oustanding -= chunk_writed;
CLIENT_INFO(context, "Socket send chunked :%d,available:%d", writed, availableForWrite);
context->socket->flush(); //???
}
write_size = writed;
}
else {
write_size = context->socket->write(data, data_size);
context->socket->flush();
}
optimistic_yield(1000);
// availableForWrite = context->socket->availableForWrite();
// CLIENT_DEBUG(context, "socket.write, data_size=%d, write_size=%d, availableForWrite=%d, WriteError=%d",
// data_size, write_size, availableForWrite, context->socket->getWriteError());
if (write_size != data_size) {
context->error_write = true;
//context->socket->keepAlive(1, 1, 1); // fast disconnected internally in 1 second.
CLIENT_ERROR(context, "socket.write, data_size=%d, write_size=%d", data_size, write_size);
}
}
int client_send_encrypted_(client_context_t *context,
byte *payload, size_t size) {
CLIENT_DEBUG(context, "client_send_encrypted_ size=%d", size);
if (!context || !context->encrypted)
return -1;
byte nonce[12];
memset(nonce, 0, sizeof(nonce));
byte encrypted[1024 + 18];
int payload_offset = 0;
while (payload_offset < size) {
size_t chunk_size = size - payload_offset;
if (chunk_size > 1024)
chunk_size = 1024;
byte aead[2] = { chunk_size % 256, chunk_size / 256 };
memcpy(encrypted, aead, 2);
byte i = 4;
int x = context->count_reads++;
while (x) {
nonce[i++] = x % 256;
x /= 256;
}
size_t available = sizeof(encrypted) - 2;
int r = crypto_chacha20poly1305_encrypt(context->read_key, nonce, aead, 2,
payload + payload_offset, chunk_size, encrypted + 2, &available);
if (r) {
ERROR("Failed to chacha encrypt payload (code %d)", r);
return -1;
}
payload_offset += chunk_size;
write(context, encrypted, available + 2);
}
return 0;
}
int client_decrypt_(client_context_t *context,
byte *payload, size_t payload_size, byte *decrypted, size_t *decrypted_size) {
if (!context || !context->encrypted)
return -1;
const size_t block_size = 1024 + 16 + 2;
size_t required_decrypted_size = payload_size / block_size * 1024;
if (payload_size % block_size > 0)
required_decrypted_size += payload_size % block_size - 16 - 2;
if (*decrypted_size < required_decrypted_size) {
*decrypted_size = required_decrypted_size;
return -2;
}
*decrypted_size = required_decrypted_size;
byte nonce[12];
memset(nonce, 0, sizeof(nonce));
int payload_offset = 0;
int decrypted_offset = 0;
while (payload_offset < payload_size) {
size_t chunk_size = payload[payload_offset] + payload[payload_offset + 1] * 256;
if (chunk_size + 18 > payload_size - payload_offset) {
// Unfinished chunk
break;
}
byte i = 4;
int x = context->count_writes++;
while (x) {
nonce[i++] = x % 256;
x /= 256;
}
size_t decrypted_len = *decrypted_size - decrypted_offset;
int r = crypto_chacha20poly1305_decrypt(context->write_key, nonce, payload + payload_offset,
2, payload + payload_offset + 2, chunk_size + 16, decrypted, &decrypted_len);
if (r) {
ERROR("Failed to chacha decrypt payload (code %d)", r);
return -1;
}
decrypted_offset += decrypted_len;
payload_offset += chunk_size + 18;
}
return payload_offset;
}
//将设备的notify事件(如各种状态改变存起来)
void client_notify_characteristic(homekit_characteristic_t *ch, homekit_value_t value,
void *context) {
client_context_t *client = (client_context_t*)context;
if (client->current_characteristic == ch && client->current_value
&& homekit_value_equal(client->current_value, &value)) {
// This value is set by this client, no need to send notification
CLIENT_DEBUG(client, "This value is set by this client, no need to send notification");
return;
}
CLIENT_DEBUG(client, "Got characteristic %d.%d change event",
ch->service->accessory->id, ch->id);
//DEBUG("Got characteristic %d.%d change event", ch->service->accessory->id, ch->id);
if (!client->event_queue) {
ERROR("Client has no event queue. Skipping notification");
return;
}
characteristic_event_t *event = (characteristic_event_t*)malloc(
sizeof(characteristic_event_t));
event->characteristic = ch;
homekit_value_copy(&event->value, &value);
DEBUG("Sending event to client %d", client->socket);
//xQueueSendToBack(client->event_queue, &event, 10);*/
//client->event_queue->add(event);
//q_push第二个参数要传指针地址
q_push(client->event_queue, &event);
}
void client_send(client_context_t *context, byte *data, size_t data_size) {
CLIENT_DEBUG(context, "send data size=%d, encrypted=%s",
data_size, context->encrypted ? "true" : "false");
#ifdef HOMEKIT_DEBUG
if (data_size < 4096) {
char *payload = binary_to_string(data, data_size);
CLIENT_DEBUG(context, "Sending payload: %s", payload);
free(payload);
}
#endif
if (context->encrypted) {
int r = client_send_encrypted_(context, data, data_size);
if (r) {