/
m2mnsdlinterface.cpp
3246 lines (2879 loc) · 129 KB
/
m2mnsdlinterface.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
/*
* Copyright (c) 2015 ARM Limited. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Needed for PRIu64 on FreeRTOS
#include <stdio.h>
// Note: this macro is needed on armcc to get the the limit macros like UINT16_MAX
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
// Note: this macro is needed on armcc to get the the PRI*32 macros
// from inttypes.h in a C++ code.
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <assert.h>
#include <inttypes.h>
#include <stdlib.h>
#include "include/nsdlaccesshelper.h"
#include "include/m2mnsdlobserver.h"
#include "include/m2mtlvdeserializer.h"
#include "include/m2mtlvserializer.h"
#include "include/m2mnsdlinterface.h"
#include "include/m2mreporthandler.h"
#include "mbed-client/m2mstring.h"
#include "mbed-client/m2msecurity.h"
#include "mbed-client/m2mserver.h"
#include "mbed-client/m2mobject.h"
#include "mbed-client/m2mendpoint.h"
#include "mbed-client/m2mobjectinstance.h"
#include "mbed-client/m2mresource.h"
#include "mbed-client/m2mblockmessage.h"
#include "mbed-client/m2mconstants.h"
#include "mbed-client/uriqueryparser.h"
#include "mbed-trace/mbed_trace.h"
#include "sn_grs.h"
#include "mbed-client/m2minterfacefactory.h"
#include "mbed-client/m2mdevice.h"
#include "randLIB.h"
#include "common_functions.h"
#include "sn_nsdl_lib.h"
#include "sn_coap_protocol.h"
#include "m2mnotificationhandler.h"
#include "eventOS_event_timer.h"
#include "eventOS_scheduler.h"
#include "ns_hal_init.h"
#define MBED_CLIENT_NSDLINTERFACE_TASKLET_INIT_EVENT 0 // Tasklet init occurs always when generating a tasklet
#define MBED_CLIENT_NSDLINTERFACE_EVENT 30
#define MBED_CLIENT_NSDLINTERFACE_BS_EVENT 31
#define MBED_CLIENT_NSDLINTERFACE_BS_PUT_EVENT 32
#define MBED_CLIENT_NSDLINTERFACE_BS_FINISH_EVENT 33
#ifdef MBED_CONF_MBED_CLIENT_EVENT_LOOP_SIZE
#define MBED_CLIENT_EVENT_LOOP_SIZE MBED_CONF_MBED_CLIENT_EVENT_LOOP_SIZE
#else
#define MBED_CLIENT_EVENT_LOOP_SIZE 1024
#endif
#define BUFFER_SIZE 21
#define TRACE_GROUP "mClt"
#define MAX_QUERY_COUNT 10
const char *MCC_VERSION = "mccv=1.4.0";
int8_t M2MNsdlInterface::_tasklet_id = -1;
extern "C" void nsdlinterface_tasklet_func(arm_event_s *event)
{
// skip the init event as there will be a timer event after
if (event->event_type == MBED_CLIENT_NSDLINTERFACE_EVENT) {
eventOS_scheduler_mutex_wait();
M2MNsdlInterface::nsdl_coap_data_s *coap_data = (M2MNsdlInterface::nsdl_coap_data_s*)event->data_ptr;
M2MNsdlInterface *interface = (M2MNsdlInterface*)sn_nsdl_get_context(coap_data->nsdl_handle);
if (interface) {
interface->resource_callback_handle_event(coap_data->received_coap_header, &coap_data->address);
if (coap_data->received_coap_header->coap_status == COAP_STATUS_PARSER_BLOCKWISE_MSG_RECEIVED &&
coap_data->received_coap_header->payload_ptr) {
coap_data->nsdl_handle->grs->sn_grs_free(coap_data->received_coap_header->payload_ptr);
coap_data->received_coap_header->payload_ptr = 0;
}
}
M2MNsdlInterface::memory_free(coap_data->received_coap_header->payload_ptr);
sn_coap_parser_release_allocated_coap_msg_mem(coap_data->nsdl_handle->grs->coap, coap_data->received_coap_header);
M2MNsdlInterface::memory_free(coap_data->address.addr_ptr);
M2MNsdlInterface::memory_free(coap_data);
eventOS_scheduler_mutex_release();
} else if (event->event_type == MBED_CLIENT_NSDLINTERFACE_BS_EVENT) {
M2MNsdlInterface::nsdl_coap_data_s *coap_data = (M2MNsdlInterface::nsdl_coap_data_s*)event->data_ptr;
M2MNsdlInterface *interface = (M2MNsdlInterface*)sn_nsdl_get_context(coap_data->nsdl_handle);
sn_coap_hdr_s *coap_response = sn_nsdl_build_response(coap_data->nsdl_handle,
coap_data->received_coap_header,
coap_data->received_coap_header->msg_code);
if (coap_response) {
coap_response->msg_type = coap_data->received_coap_header->msg_type;
if (sn_nsdl_send_coap_message(coap_data->nsdl_handle, &coap_data->address, coap_response) == 0) {
interface->store_bs_finished_response_id(coap_response->msg_id);
} else {
tr_error("Failed to send final response for BS finished");
}
sn_coap_parser_release_allocated_coap_msg_mem(coap_data->nsdl_handle->grs->coap, coap_response);
} else {
tr_error("Failed to create final response message for BS finished");
}
// Release the memory
M2MNsdlInterface::memory_free(coap_data->received_coap_header->payload_ptr);
sn_coap_parser_release_allocated_coap_msg_mem(coap_data->nsdl_handle->grs->coap, coap_data->received_coap_header);
M2MNsdlInterface::memory_free(coap_data->address.addr_ptr);
M2MNsdlInterface::memory_free(coap_data);
} else if (event->event_type == MBED_CLIENT_NSDLINTERFACE_BS_PUT_EVENT) {
M2MNsdlInterface::nsdl_coap_data_s *coap_data = (M2MNsdlInterface::nsdl_coap_data_s*)event->data_ptr;
M2MNsdlInterface *interface = (M2MNsdlInterface*)sn_nsdl_get_context(coap_data->nsdl_handle);
interface->handle_bootstrap_put_message(coap_data->received_coap_header, &coap_data->address);
M2MNsdlInterface::memory_free(coap_data->received_coap_header->payload_ptr);
sn_coap_parser_release_allocated_coap_msg_mem(coap_data->nsdl_handle->grs->coap, coap_data->received_coap_header);
M2MNsdlInterface::memory_free(coap_data->address.addr_ptr);
M2MNsdlInterface::memory_free(coap_data);
} else if (event->event_type == MBED_CLIENT_NSDLINTERFACE_BS_FINISH_EVENT) {
nsdl_s *nsdl_handle = (nsdl_s*)event->data_ptr;
M2MNsdlInterface *interface = (M2MNsdlInterface*)sn_nsdl_get_context(nsdl_handle);
interface->handle_bootstrap_finish_ack(event->event_data);
}
}
M2MNsdlInterface::M2MNsdlInterface(M2MNsdlObserver &observer, M2MConnectionHandler &connection_handler)
: _observer(observer),
_endpoint(NULL),
_nsdl_handle(NULL),
_security(NULL),
_server(NULL),
_nsdl_execution_timer(*this),
_registration_timer(*this),
_connection_handler(connection_handler),
_counter_for_nsdl(0),
_next_coap_ping_send_time(0),
_server_address(NULL),
_custom_uri_query_params(NULL),
_notification_handler(new M2MNotificationHandler()),
_bootstrap_id(0),
_binding_mode(M2MInterface::NOT_SET),
_identity_accepted(false),
_nsdl_execution_timer_running(false),
_notification_send_ongoing(false),
_registered(false),
_bootstrap_finish_ack_received(false)
{
tr_debug("M2MNsdlInterface::M2MNsdlInterface()");
_event.data.data_ptr = NULL;
_event.data.event_data = 0;
_event.data.event_id = 0;
_event.data.sender = 0;
_event.data.event_type = 0;
_event.data.priority = ARM_LIB_MED_PRIORITY_EVENT;
_server = new M2MServer();
// This initializes libCoap and libNsdl
// Parameters are function pointers to used memory allocation
// and free functions in structure and used functions for sending
// and receiving purposes.
_nsdl_handle = sn_nsdl_init(&(__nsdl_c_send_to_server), &(__nsdl_c_received_from_server),
&(__nsdl_c_memory_alloc), &(__nsdl_c_memory_free), &(__nsdl_c_auto_obs_token));
sn_nsdl_set_context(_nsdl_handle, this);
ns_hal_init(NULL, MBED_CLIENT_EVENT_LOOP_SIZE, NULL, NULL);
eventOS_scheduler_mutex_wait();
if (M2MNsdlInterface::_tasklet_id < 0) {
M2MNsdlInterface::_tasklet_id = eventOS_event_handler_create(nsdlinterface_tasklet_func, MBED_CLIENT_NSDLINTERFACE_TASKLET_INIT_EVENT);
assert(M2MNsdlInterface::_tasklet_id >= 0);
}
eventOS_scheduler_mutex_release();
_event.data.receiver = M2MNsdlInterface::_tasklet_id;
// Randomize the initial auto obs token. Range is in 1 - 1023
_auto_obs_token = randLIB_get_random_in_range(AUTO_OBS_TOKEN_MIN, AUTO_OBS_TOKEN_MAX);
initialize();
}
M2MNsdlInterface::~M2MNsdlInterface()
{
tr_debug("M2MNsdlInterface::~M2MNsdlInterface() - IN");
if (_endpoint) {
memory_free(_endpoint->endpoint_name_ptr);
memory_free(_endpoint->domain_name_ptr);
memory_free(_endpoint->type_ptr);
memory_free(_endpoint->lifetime_ptr);
memory_free(_endpoint);
}
delete _notification_handler;
_base_list.clear();
_security = NULL;
delete _server;
sn_nsdl_destroy(_nsdl_handle);
_nsdl_handle = NULL;
memory_free(_server_address);
free_request_context_list();
memory_free(_custom_uri_query_params);
tr_debug("M2MNsdlInterface::~M2MNsdlInterface() - OUT");
}
bool M2MNsdlInterface::initialize()
{
tr_debug("M2MNsdlInterface::initialize()");
bool success = false;
// Sets the packet retransmission attempts and time interval
sn_nsdl_set_retransmission_parameters(_nsdl_handle,
MBED_CLIENT_RECONNECTION_COUNT,
MBED_CLIENT_RECONNECTION_INTERVAL);
sn_nsdl_handle_block2_response_internally(_nsdl_handle, false);
// Allocate the memory for endpoint
_endpoint = (sn_nsdl_ep_parameters_s*)memory_alloc(sizeof(sn_nsdl_ep_parameters_s));
if (_endpoint) {
memset(_endpoint, 0, sizeof(sn_nsdl_ep_parameters_s));
success = true;
}
M2MResource* update_trigger = _server->get_resource(M2MServer::RegistrationUpdate);
if (update_trigger) {
update_trigger->set_execute_function(execute_callback(this,
&M2MNsdlInterface::update_trigger_callback));
}
add_object_to_list(_server);
create_nsdl_object_structure(_server);
ns_list_init(&_request_context_list);
return success;
}
void M2MNsdlInterface::create_endpoint(const String &name,
const String &type,
const int32_t life_time,
const String &domain,
const uint8_t mode,
const String &/*context_address*/)
{
tr_info("M2MNsdlInterface::create_endpoint( name %s type %s lifetime %" PRId32 ", domain %s, mode %d)",
name.c_str(), type.c_str(), life_time, domain.c_str(), mode);
_endpoint_name = name;
_binding_mode = mode;
calculate_new_coap_ping_send_time();
if (_endpoint){
memset(_endpoint, 0, sizeof(sn_nsdl_ep_parameters_s));
if (!_endpoint_name.empty()) {
memory_free(_endpoint->endpoint_name_ptr);
_endpoint->endpoint_name_ptr = alloc_string_copy((uint8_t*)_endpoint_name.c_str(), _endpoint_name.length());
_endpoint->endpoint_name_len = _endpoint_name.length();
}
if (!type.empty()) {
_endpoint->type_ptr = alloc_string_copy((uint8_t*)type.c_str(), type.length());
_endpoint->type_len = type.length();
}
if (!domain.empty()) {
_endpoint->domain_name_ptr = alloc_string_copy((uint8_t*)domain.c_str(), domain.length());
_endpoint->domain_name_len = domain.length();
}
// nsdl binding mode is only 3 least significant bits
_endpoint->binding_and_mode = (sn_nsdl_oma_binding_and_mode_t)((uint8_t)mode & 0x07);
// If lifetime is less than zero then leave the field empty
if (life_time > 0) {
set_endpoint_lifetime_buffer(life_time);
}
}
}
void M2MNsdlInterface::update_endpoint(const String &name)
{
_endpoint_name = name;
if (_endpoint){
if (!_endpoint_name.empty()) {
memory_free(_endpoint->endpoint_name_ptr);
_endpoint->endpoint_name_ptr = alloc_string_copy((uint8_t*)_endpoint_name.c_str(), _endpoint_name.length());
_endpoint->endpoint_name_len = _endpoint_name.length();
}
}
}
void M2MNsdlInterface::update_domain(const String &domain)
{
if (_endpoint){
memory_free(_endpoint->domain_name_ptr);
_endpoint->domain_name_len = 0;
if (!domain.empty()) {
_endpoint->domain_name_ptr = alloc_string_copy((uint8_t*)domain.c_str(), domain.length());
_endpoint->domain_name_len = domain.length();
}
}
}
void M2MNsdlInterface::set_endpoint_lifetime_buffer(int lifetime)
{
tr_debug("M2MNsdlInterface::set_endpoint_lifetime_buffer - %d", lifetime);
if (lifetime < 60) {
return;
}
_server->set_resource_value(M2MServer::Lifetime, lifetime);
if (_endpoint && _endpoint->lifetime_ptr) {
memory_free(_endpoint->lifetime_ptr);
_endpoint->lifetime_ptr = NULL;
_endpoint->lifetime_len = 0;
}
char buffer[20+1];
uint32_t size = m2m::itoa_c(lifetime, buffer);
if (_endpoint && size <= sizeof(buffer)) {
_endpoint->lifetime_len = 0;
_endpoint->lifetime_ptr = alloc_string_copy((uint8_t*)buffer, size);
if (_endpoint->lifetime_ptr) {
_endpoint->lifetime_len = size;
}
}
set_retransmission_parameters();
}
void M2MNsdlInterface::delete_endpoint()
{
tr_debug("M2MNsdlInterface::delete_endpoint()");
if (_endpoint) {
free(_endpoint->lifetime_ptr);
memory_free(_endpoint);
_endpoint = NULL;
}
}
bool M2MNsdlInterface::create_nsdl_list_structure(const M2MBaseList &list)
{
tr_debug("M2MNsdlInterface::create_nsdl_list_structure()");
bool success = false;
if(!list.empty()) {
tr_debug("M2MNsdlInterface::create_nsdl_list_structure - Object count is %d", list.size());
M2MBaseList::const_iterator it;
it = list.begin();
for ( ; it != list.end(); it++ ) {
// Create NSDL structure for all Objects inside
success = create_nsdl_structure(*it);
tr_debug("M2MNsdlInterface::create_nsdl_list_structure - create %d", success);
add_object_to_list(*it);
}
}
if (!success) {
tr_error("M2MNsdlInterface::create_nsdl_list_structure - fail!");
}
return success;
}
bool M2MNsdlInterface::remove_nsdl_resource(M2MBase *base)
{
sn_nsdl_dynamic_resource_parameters_s* resource = base->get_nsdl_resource();
return sn_nsdl_pop_resource(_nsdl_handle, resource);
}
bool M2MNsdlInterface::create_bootstrap_resource(sn_nsdl_addr_s *address)
{
#ifndef MBED_CLIENT_DISABLE_BOOTSTRAP_FEATURE
tr_debug("M2MNsdlInterface::create_bootstrap_resource()");
_identity_accepted = false;
_bootstrap_finish_ack_received = false;
bool success = false;
tr_debug("M2MNsdlInterface::create_bootstrap_resource() - endpoint name: %.*s", _endpoint->endpoint_name_len,
_endpoint->endpoint_name_ptr);
if (_bootstrap_id == 0) {
// Take copy of the address, uri_query_parameters() will modify the source buffer
bool msg_sent = false;
if (_server_address) {
char *address_copy = M2MBase::alloc_string_copy(_server_address);
if (address_copy) {
char* query = parse_uri_query_parameters(_server_address);
if (query != NULL) {
size_t query_len = 1 + strlen(query) + 1 + strlen(MCC_VERSION) + 1;
if (query_len <= MAX_URI_QUERY_LEN) {
char query_params[MAX_URI_QUERY_LEN];
strcpy(query_params, "&");
strcat(query_params, query);
strcat(query_params, "&");
strcat(query_params, MCC_VERSION);
msg_sent = true;
sn_nsdl_clear_coap_resending_queue(_nsdl_handle);
_bootstrap_id = sn_nsdl_oma_bootstrap(_nsdl_handle,
address,
_endpoint,
query_params);
free(_server_address);
_server_address = M2MBase::alloc_string_copy(address_copy);
} else {
tr_error("M2MNsdlInterface::create_bootstrap_resource() - max uri param length reached (%lu)",
(unsigned long)query_len);
}
}
free(address_copy);
}
}
if (!msg_sent) {
sn_nsdl_clear_coap_resending_queue(_nsdl_handle);
_bootstrap_id = sn_nsdl_oma_bootstrap(_nsdl_handle,
address,
_endpoint,
NULL);
}
success = _bootstrap_id != 0;
tr_debug("M2MNsdlInterface::create_bootstrap_resource - _bootstrap_id %d", _bootstrap_id);
}
return success;
#else
(void)address;
(void)bootstrap_endpoint_name;
return false;
#endif //MBED_CLIENT_DISABLE_BOOTSTRAP_FEATURE
}
void M2MNsdlInterface::set_server_address(uint8_t* address,
uint8_t address_length,
const uint16_t port,
sn_nsdl_addr_type_e address_type)
{
tr_debug("M2MNsdlInterface::set_server_address()");
set_NSP_address(_nsdl_handle, address, address_length, port, address_type);
}
bool M2MNsdlInterface::send_register_message()
{
tr_info("M2MNsdlInterface::send_register_message()");
bool success = false;
if (_server_address) {
success = parse_and_send_uri_query_parameters();
}
// If URI parsing fails or there is no parameters, try again without parameters
if (!success) {
sn_nsdl_clear_coap_resending_queue(_nsdl_handle);
success = sn_nsdl_register_endpoint(_nsdl_handle,_endpoint, NULL) != 0;
}
return success;
}
void M2MNsdlInterface::send_request(const char *uri,
const sn_coap_msg_code_e msg_code,
const size_t offset,
const bool async,
const uint16_t payload_len,
uint8_t *payload_ptr,
request_data_cb data_cb,
request_error_cb error_cb,
void *context)
{
int32_t message_id = 0;
uint32_t token = 0;
request_context_s *data_request = NULL;
// Check the duplicate items
request_context_s *data = (request_context_s *)ns_list_get_first(&_request_context_list);
while (data) {
if ((strcmp(uri, data->uri_path) == 0) && (offset == data->received_size)) {
tr_debug("M2MNsdlInterface::send_request - item already exists");
data_request = data;
break;
}
data = (request_context_s *)ns_list_get_next(&_request_context_list, data);
}
if (data_request == NULL) {
data_request = (struct request_context_s*)memory_alloc(sizeof(struct request_context_s));
if (data_request == NULL) {
error_cb(FAILED_TO_ALLOCATE_MEMORY, context);
return;
}
data_request->resend = false;
data_request->context = context;
data_request->async_req = async;
data_request->received_size = offset;
data_request->uri_path = (char*)alloc_string_copy((uint8_t*)uri, strlen(uri));
if (data_request->uri_path == NULL) {
memory_free(data_request);
error_cb(FAILED_TO_ALLOCATE_MEMORY, context);
return;
}
data_request->on_request_data_cb = data_cb;
data_request->on_request_error_cb = error_cb;
randLIB_get_n_bytes_random(&token, sizeof(token));
if (!token) {
token++;
}
data_request->msg_token = token;
data_request->msg_code = msg_code;
ns_list_add_to_end(&_request_context_list, data_request);
}
bool send_message = true;
if (data_request->msg_code == COAP_MSG_CODE_REQUEST_GET && !_registered) {
// CoAP download(GET) should happen only when client is registered
send_message = false;
}
if (send_message) {
message_id = sn_nsdl_send_request(_nsdl_handle,
data_request->msg_code,
data_request->uri_path,
data_request->msg_token,
data_request->received_size,
payload_len,
payload_ptr);
if (message_id == -4) {
data_request->resend = true;
} else if (message_id <= 0) {
ns_list_remove(&_request_context_list, data_request);
memory_free(data_request->uri_path);
memory_free(data_request);
error_cb(FAILED_TO_ALLOCATE_MEMORY, context);
}
} else {
tr_error("M2MNsdlInterface::send_request - not registered");
}
}
bool M2MNsdlInterface::send_update_registration(const uint32_t lifetime)
{
tr_info("M2MNsdlInterface::send_update_registration( lifetime %" PRIu32 ")", lifetime);
bool success = false;
int32_t ret = 0;
_registration_timer.stop_timer();
bool lifetime_changed = true;
// If new resources have been created after registration those must be created and published to the server.
create_nsdl_list_structure(_base_list);
// Check if resource(1/0/1) value has been updated and update it into _endpoint struct
if (lifetime == 0) {
lifetime_changed = lifetime_value_changed();
if (lifetime_changed) {
set_endpoint_lifetime_buffer(_server->resource_value_int(M2MServer::Lifetime));
}
} else {
set_endpoint_lifetime_buffer(lifetime);
}
if (_nsdl_handle) {
if (!lifetime_changed) {
tr_debug("M2MNsdlInterface::send_update_registration - regular update");
ret = sn_nsdl_update_registration(_nsdl_handle, NULL, 0);
} else {
if (_endpoint && _endpoint->lifetime_ptr) {
tr_debug("M2MNsdlInterface::send_update_registration - new lifetime value");
ret = sn_nsdl_update_registration(_nsdl_handle,
_endpoint->lifetime_ptr,
_endpoint->lifetime_len);
}
}
}
if (ret >= 0) {
success = true;
}
_registration_timer.start_timer(registration_time() * 1000,
M2MTimerObserver::Registration,
false);
return success;
}
bool M2MNsdlInterface::send_unregister_message()
{
tr_info("M2MNsdlInterface::send_unregister_message");
if (is_unregister_ongoing()) {
tr_debug("M2MNsdlInterface::send_unregister_message - unregistration already in progress");
return true;
}
bool success = false;
int32_t ret = 0;
ret = sn_nsdl_unregister_endpoint(_nsdl_handle);
if (ret == -4) {
tr_warn("Failed to send registration update. Clearing queue and retrying.");
sn_nsdl_clear_coap_resending_queue(_nsdl_handle);
ret = sn_nsdl_unregister_endpoint(_nsdl_handle);
}
if (ret >= 0) {
success = true;
}
return success;
}
// XXX: move these to common place, no need to copy these wrappers to multiple places:
void *M2MNsdlInterface::memory_alloc(uint32_t size)
{
if(size)
return malloc(size);
else
return 0;
}
void M2MNsdlInterface::memory_free(void *ptr)
{
if(ptr)
free(ptr);
}
uint8_t* M2MNsdlInterface::alloc_string_copy(const uint8_t* source, uint16_t size)
{
assert(source != NULL);
uint8_t* result = (uint8_t*)memory_alloc(size + 1);
if (result) {
memcpy(result, source, size);
result[size] = '\0';
}
return result;
}
uint8_t M2MNsdlInterface::send_to_server_callback(struct nsdl_s * /*nsdl_handle*/,
sn_nsdl_capab_e /*protocol*/,
uint8_t *data_ptr,
uint16_t data_len,
sn_nsdl_addr_s *address)
{
tr_debug("M2MNsdlInterface::send_to_server_callback(data size %d)", data_len);
_observer.coap_message_ready(data_ptr,data_len,address);
return 1;
}
uint8_t M2MNsdlInterface::received_from_server_callback(struct nsdl_s *nsdl_handle,
sn_coap_hdr_s *coap_header,
sn_nsdl_addr_s *address)
{
tr_debug("M2MNsdlInterface::received_from_server_callback");
_observer.coap_data_processed();
uint8_t value = 0;
request_context_s request_context;
if(nsdl_handle && coap_header) {
bool is_bootstrap_msg = nsdl_handle->is_bs_server;
if (coap_header->token_len == sizeof(nsdl_handle->register_token) &&
memcmp(coap_header->token_ptr, &nsdl_handle->register_token, sizeof(nsdl_handle->register_token)) == 0) {
handle_register_response(coap_header);
} else if (coap_header->token_len == sizeof(nsdl_handle->unregister_token) &&
memcmp(coap_header->token_ptr,
&nsdl_handle->unregister_token,
sizeof(nsdl_handle->unregister_token)) == 0) {
handle_unregister_response(coap_header);
} else if (coap_header->token_len == sizeof(nsdl_handle->update_register_token) &&
memcmp(coap_header->token_ptr,
&nsdl_handle->update_register_token,
sizeof(nsdl_handle->update_register_token)) == 0) {
handle_register_update_response(coap_header);
} else if (coap_header->token_ptr && is_response_to_request(coap_header, request_context)) {
handle_request_response(coap_header, &request_context);
}
#ifndef MBED_CLIENT_DISABLE_BOOTSTRAP_FEATURE
else if (coap_header->token_len == sizeof(nsdl_handle->bootstrap_token) &&
memcmp(coap_header->token_ptr, &nsdl_handle->bootstrap_token, sizeof(nsdl_handle->bootstrap_token)) == 0) {
handle_bootstrap_response(coap_header);
}
#endif //MBED_CLIENT_DISABLE_BOOTSTRAP_FEATURE
else {
sn_coap_hdr_s *coap_response = NULL;
bool execute_value_updated = false;
M2MObjectInstance *obj_instance = NULL;
if (COAP_MSG_CODE_REQUEST_PUT == coap_header->msg_code) {
if (is_bootstrap_msg) {
send_empty_ack(coap_header, address);
nsdl_coap_data_s *nsdl_coap_data = create_coap_event_data(coap_header,
address,
nsdl_handle,
coap_header->msg_code);
if (nsdl_coap_data) {
_event.data.event_type = MBED_CLIENT_NSDLINTERFACE_BS_PUT_EVENT;
_event.data.data_ptr = (void*)nsdl_coap_data;
eventOS_event_send_user_allocated(&_event);
return 2; // freeing will be performed in MBED_CLIENT_NSDLINTERFACE_BS_PUT_EVENT event
} else {
tr_error("M2MNsdlInterface::received_from_server_callback() - BS PUT failed to allocate nsdl_coap_data_s!");
coap_response = sn_nsdl_build_response(_nsdl_handle,
coap_header,
COAP_MSG_CODE_RESPONSE_REQUEST_ENTITY_TOO_LARGE);
}
} else {
tr_debug("M2MNsdlInterface::received_from_server_callback - Method not allowed (PUT).");
coap_response = sn_nsdl_build_response(_nsdl_handle,
coap_header,
COAP_MSG_CODE_RESPONSE_METHOD_NOT_ALLOWED);
}
}
else if (COAP_MSG_CODE_REQUEST_DELETE == coap_header->msg_code) {
if (is_bootstrap_msg) {
handle_bootstrap_delete(coap_header, address);
} else {
tr_debug("M2MNsdlInterface::received_from_server_callback - Method not allowed (DELETE).");
coap_response = sn_nsdl_build_response(_nsdl_handle,
coap_header,
COAP_MSG_CODE_RESPONSE_METHOD_NOT_ALLOWED);
}
} else if (COAP_MSG_CODE_REQUEST_POST == coap_header->msg_code) {
execute_value_updated = handle_post_response(coap_header,
address,
coap_response,
obj_instance,
is_bootstrap_msg);
} else if (COAP_STATUS_BUILDER_BLOCK_SENDING_DONE == coap_header->coap_status &&
coap_header->msg_code == COAP_MSG_CODE_RESPONSE_CONTENT) {
M2MBase *base = find_resource("", coap_header->msg_id);
if (base) {
handle_notification_delivered(base);
}
} else if (COAP_MSG_CODE_EMPTY == coap_header->msg_code) {
handle_empty_ack(coap_header, is_bootstrap_msg);
// Retransmission done
} else if (COAP_STATUS_BUILDER_MESSAGE_SENDING_FAILED == coap_header->coap_status) {
tr_info("M2MNsdlInterface::received_from_server_callback - message sending failed, id %d", coap_header->msg_id);
// Report notification status back to application
M2MBase *base = find_resource("", coap_header->msg_id);
if (base) {
base->send_notification_delivery_status(*base, NOTIFICATION_STATUS_SEND_FAILED);
}
_observer.registration_error(M2MInterface::NetworkError, true);
// Handle Server-side expections during registration flow
// Client might receive error from server due to temporary connection/operability reasons,
// server might not recover the flow in this case, so it is better for Client to restart registration.
} else if (nsdl_handle->register_token &&
((coap_header->msg_code == COAP_MSG_CODE_RESPONSE_INTERNAL_SERVER_ERROR) ||
(coap_header->msg_code == COAP_MSG_CODE_RESPONSE_BAD_GATEWAY) ||
(coap_header->msg_code == COAP_MSG_CODE_RESPONSE_SERVICE_UNAVAILABLE) ||
(coap_header->msg_code == COAP_MSG_CODE_RESPONSE_GATEWAY_TIMEOUT))) {
tr_error("M2MNsdlInterface::received_from_server_callback - registration error %d", coap_header->msg_code);
tr_error("M2MNsdlInterface::received_from_server_callback - unexpected error received from server");
// Try to do clean register again
_observer.registration_error(M2MInterface::NetworkError, true);
} else {
// Add warn for any message that gets this far. We might be missing some handling in above.
tr_warn("M2MNsdlInterface::received_from_server_callback - msg was ignored %d", coap_header->msg_code);
}
// Send response to server
if (coap_response) {
tr_debug("M2MNsdlInterface::received_from_server_callback - send CoAP response");
(sn_nsdl_send_coap_message(_nsdl_handle, address, coap_response) == 0) ? value = 0 : value = 1;
sn_nsdl_release_allocated_coap_msg_mem(_nsdl_handle, coap_response);
}
// Tell to application that value has been updated
if (execute_value_updated) {
value_updated(obj_instance);
}
}
}
return value;
}
uint8_t M2MNsdlInterface::resource_callback(struct nsdl_s *nsdl_handle,
sn_coap_hdr_s *received_coap_header,
sn_nsdl_addr_s *address,
sn_nsdl_capab_e /*nsdl_capab*/)
{
tr_debug("M2MNsdlInterface::resource_callback()");
assert(received_coap_header);
_observer.coap_data_processed();
// Use piggypacked response for any other types than POST
if (received_coap_header->msg_code != COAP_MSG_CODE_REQUEST_POST) {
uint8_t status = resource_callback_handle_event(received_coap_header, address);
if (received_coap_header->coap_status == COAP_STATUS_PARSER_BLOCKWISE_MSG_RECEIVED) {
memory_free(received_coap_header->payload_ptr);
}
sn_nsdl_release_allocated_coap_msg_mem(_nsdl_handle, received_coap_header);
return status;
}
send_empty_ack(received_coap_header, address);
nsdl_coap_data_s *nsdl_coap_data = create_coap_event_data(received_coap_header,
address,
nsdl_handle,
received_coap_header->msg_code);
if (nsdl_coap_data) {
_event.data.event_type = MBED_CLIENT_NSDLINTERFACE_EVENT;
_event.data.data_ptr = (void*)nsdl_coap_data;
eventOS_event_send_user_allocated(&_event);
} else {
tr_error("M2MNsdlInterface::resource_callback() - failed to allocate nsdl_coap_data_s!");
}
return 0;
}
uint8_t M2MNsdlInterface::resource_callback_handle_event(sn_coap_hdr_s *received_coap_header,
sn_nsdl_addr_s *address)
{
tr_debug("M2MNsdlInterface::resource_callback_handle_event");
uint8_t result = 1;
uint8_t *payload = NULL;
bool free_payload = true;
sn_coap_hdr_s *coap_response = NULL;
sn_coap_msg_code_e msg_code = COAP_MSG_CODE_RESPONSE_CHANGED; // 4.00
String resource_name = coap_to_string(received_coap_header->uri_path_ptr,
received_coap_header->uri_path_len);
bool execute_value_updated = false;
M2MBase* base = find_resource(resource_name, 0);
bool subscribed = false;
if (base) {
if (COAP_MSG_CODE_REQUEST_GET == received_coap_header->msg_code) {
coap_response = base->handle_get_request(_nsdl_handle, received_coap_header,this);
if (coap_response && coap_response->options_list_ptr && coap_response->options_list_ptr->observe != STOP_OBSERVATION) {
subscribed = true;
}
} else if (COAP_MSG_CODE_REQUEST_PUT == received_coap_header->msg_code) {
coap_response = base->handle_put_request(_nsdl_handle, received_coap_header, this, execute_value_updated);
} else if (COAP_MSG_CODE_REQUEST_POST == received_coap_header->msg_code) {
if (base->base_type() == M2MBase::ResourceInstance) {
msg_code = COAP_MSG_CODE_RESPONSE_BAD_REQUEST;
} else {
coap_response = base->handle_post_request(_nsdl_handle,
received_coap_header,
this,
execute_value_updated,
address);
if (base->base_type() == M2MBase::Resource) {
M2MResource *res = (M2MResource*) base;
if (res->delayed_response()) {
tr_debug("M2MNsdlInterface::resource_callback_handle_event - final response sent by application");
sn_nsdl_release_allocated_coap_msg_mem(_nsdl_handle, coap_response);
return 0;
}
}
// Separate response used for POST
if (coap_response) {
coap_response->msg_type = COAP_MSG_TYPE_CONFIRMABLE;
}
}
} else if (COAP_MSG_CODE_REQUEST_DELETE == received_coap_header->msg_code) {
// Delete the object instance
M2MBase::BaseType type = base->base_type();
if(M2MBase::ObjectInstance == type) {
M2MBase* base_object = find_resource(base->uri_path(), 0);
if(base_object) {
M2MObject &object = ((M2MObjectInstance*)base_object)->get_parent_object();
int slash_found = resource_name.find_last_of('/');
// Object instance validty checks done in upper level, no need for error handling
if (slash_found != -1) {
String object_name;
object_name = resource_name.substr(slash_found + 1, resource_name.length());
if (object.remove_object_instance(strtoul(
object_name.c_str(),
NULL,
10))) {
msg_code = COAP_MSG_CODE_RESPONSE_DELETED;
}
}
}
} else {
msg_code = COAP_MSG_CODE_RESPONSE_BAD_REQUEST; // 4.00
}
}
} else {
tr_error("M2MNsdlInterface::resource_callback_handle_event() - Resource NOT FOUND");
msg_code = COAP_MSG_CODE_RESPONSE_BAD_REQUEST; // 4.00
}
if (!coap_response) {
coap_response = sn_nsdl_build_response(_nsdl_handle,
received_coap_header,
msg_code);
}
// This copy will be passed to resource instance
if (received_coap_header->payload_len > 0 && received_coap_header->payload_ptr) {
payload = (uint8_t*)memory_alloc(received_coap_header->payload_len);
if (payload) {
assert(received_coap_header->payload_ptr);
memcpy(payload, received_coap_header->payload_ptr, received_coap_header->payload_len);
}
else {
if (coap_response) {
coap_response->msg_code = COAP_MSG_CODE_RESPONSE_REQUEST_ENTITY_TOO_LARGE;
}
}
}
if (coap_response &&
coap_response->coap_status != COAP_STATUS_PARSER_BLOCKWISE_MSG_RECEIVING &&
coap_response->msg_code != COAP_MSG_CODE_EMPTY) {
(sn_nsdl_send_coap_message(_nsdl_handle, address, coap_response) == 0) ? result = 0 : result = 1;
if (coap_response->payload_ptr) {
free(coap_response->payload_ptr);
coap_response->payload_ptr = NULL;
}
// See if there any pending notification to be sent after resource is subscribed.
if (subscribed) {
_notification_handler->send_notification(this);
}
}
// If the external blockwise storing is enabled call value updated only when all blocks have been received
if (execute_value_updated &&
coap_response &&
coap_response->coap_status != COAP_STATUS_PARSER_BLOCKWISE_MSG_RECEIVING &&
coap_response->msg_code < COAP_MSG_CODE_RESPONSE_BAD_REQUEST) {
if ((COAP_MSG_CODE_REQUEST_PUT == received_coap_header->msg_code) &&
(base->base_type() == M2MBase::Resource ||
base->base_type() == M2MBase::ResourceInstance)) {
M2MResourceBase* res = (M2MResourceBase*)base;
// Clear the old resource value since the data is now passed to application
if (res->block_message() && res->block_message()->is_block_message()) {
res->clear_value();
}
else {
// Ownership of payload moved to resource, skip the freeing.
free_payload = false;
res->set_value_raw(payload, received_coap_header->payload_len);
}
}
if (coap_response->msg_code != COAP_MSG_CODE_RESPONSE_REQUEST_ENTITY_TOO_LARGE) {
value_updated(base);
}
}