-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathntn.c
More file actions
996 lines (783 loc) · 23.5 KB
/
ntn.c
File metadata and controls
996 lines (783 loc) · 23.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
/*
* Copyright (c) 2025 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: LicenseRef-Nordic-5-Clause
*/
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/zbus/zbus.h>
#include <zephyr/smf.h>
#include <modem/lte_lc.h>
#include <date_time.h>
#include <modem/nrf_modem_lib.h>
#include <modem/ntn.h>
#include <nrf_modem_at.h>
#include <nrf_modem_gnss.h>
#include <modem/modem_info.h>
#include <zephyr/task_wdt/task_wdt.h>
#include <zephyr/net/socket.h>
#include <errno.h>
#include "app_common.h"
#include "ntn.h"
#include "button.h"
LOG_MODULE_REGISTER(ntn_module, CONFIG_APP_NTN_LOG_LEVEL);
/* Define channels provided by this module */
ZBUS_CHAN_DEFINE(NTN_CHAN,
struct ntn_msg,
NULL,
NULL,
ZBUS_OBSERVERS_EMPTY,
ZBUS_MSG_INIT(0)
);
/* Register subscriber */
ZBUS_MSG_SUBSCRIBER_DEFINE(ntn);
/* Observe NTN channel */
ZBUS_CHAN_ADD_OBS(NTN_CHAN, ntn, 0);
ZBUS_CHAN_ADD_OBS(BUTTON_CHAN, ntn, 0);
#define MAX_MSG_SIZE sizeof(struct ntn_msg)
/* State machine states */
enum ntn_module_state {
STATE_RUNNING,
STATE_GNSS,
STATE_NTN,
STATE_IDLE,
};
/* State object */
struct ntn_state_object {
struct smf_ctx ctx;
const struct zbus_channel *chan;
uint8_t msg_buf[MAX_MSG_SIZE];
struct k_timer ntn_timer;
bool socket_connected;
bool ntn_initialized;
bool gnss_initialized;
struct nrf_modem_gnss_pvt_data_frame last_pvt;
int sock_fd;
uint64_t location_validity_end_time;
};
static struct k_work timer_work;
static struct k_work gnss_location_work;
/* Forward declarations */
static void gnss_event_handler(int event);
static void lte_lc_evt_handler(const struct lte_lc_evt *const evt);
/* Forward declarations */
static void state_running_entry(void *obj);
static enum smf_state_result state_running_run(void *obj);
static void state_gnss_entry(void *obj);
static enum smf_state_result state_gnss_run(void *obj);
static void state_gnss_exit(void *obj);
static void state_ntn_entry(void *obj);
static enum smf_state_result state_ntn_run(void *obj);
static void state_ntn_exit(void *obj);
static void state_idle_entry(void *obj);
static enum smf_state_result state_idle_run(void *obj);
/* State machine definition */
static const struct smf_state states[] = {
[STATE_RUNNING] = SMF_CREATE_STATE(state_running_entry, state_running_run, NULL,
NULL, &states[STATE_GNSS]),
[STATE_GNSS] = SMF_CREATE_STATE(state_gnss_entry, state_gnss_run, state_gnss_exit,
&states[STATE_RUNNING], NULL),
[STATE_NTN] = SMF_CREATE_STATE(state_ntn_entry, state_ntn_run, state_ntn_exit,
&states[STATE_RUNNING], NULL),
[STATE_IDLE] = SMF_CREATE_STATE(state_idle_entry, state_idle_run, NULL,
&states[STATE_RUNNING], NULL),
};
/* Helper function to publish NTN messages */
static void ntn_msg_publish(enum ntn_msg_type type)
{
int err;
struct ntn_msg msg = {
.type = type
};
err = zbus_chan_pub(&NTN_CHAN, &msg, K_SECONDS(1));
if (err) {
LOG_ERR("Failed to publish NTN message, error: %d", err);
return;
}
}
static void publish_last_pvt(const struct nrf_modem_gnss_pvt_data_frame *pvt)
{
int err;
struct ntn_msg msg = {
.type = NTN_LOCATION_SEARCH_DONE,
.pvt = *pvt
};
err = zbus_chan_pub(&NTN_CHAN, &msg, K_SECONDS(1));
if (err) {
LOG_ERR("Failed to publish last PVT message, error: %d", err);
}
}
static void timer_work_handler(struct k_work *work)
{
ntn_msg_publish(NTN_TIMEOUT);
}
/* Timer callback for NTN mode timeout */
static void ntn_timer_handler(struct k_timer *timer)
{
k_work_submit(&timer_work);
}
static void apply_gnss_time(const struct nrf_modem_gnss_pvt_data_frame *pvt_data)
{
int err;
struct tm gnss_time = {
.tm_year = pvt_data->datetime.year - 1900,
.tm_mon = pvt_data->datetime.month - 1,
.tm_mday = pvt_data->datetime.day,
.tm_hour = pvt_data->datetime.hour,
.tm_min = pvt_data->datetime.minute,
.tm_sec = pvt_data->datetime.seconds,
};
err = date_time_set(&gnss_time);
if (err) {
LOG_ERR("Failed to apply GNSS time, error: %d", err);
}
}
static void gnss_location_work_handler(struct k_work *work)
{
int err;
struct nrf_modem_gnss_pvt_data_frame pvt_data;
/* Read PVT data in thread context */
err = nrf_modem_gnss_read(&pvt_data, sizeof(pvt_data), NRF_MODEM_GNSS_DATA_PVT);
if (err != 0) {
LOG_ERR("Failed to read GNSS data nrf_modem_gnss_read(), err: %d", err);
return;
}
if (pvt_data.flags & NRF_MODEM_GNSS_PVT_FLAG_FIX_VALID) {
LOG_DBG("Got valid GNSS location: lat: %f, lon: %f, alt: %f",
(double)pvt_data.latitude,
(double)pvt_data.longitude,
(double)pvt_data.altitude);
apply_gnss_time(&pvt_data);
publish_last_pvt(&pvt_data);
}
/* Log SV (Satellite Vehicle) data */
for (int i = 0; i < NRF_MODEM_GNSS_MAX_SATELLITES; i++) {
if (pvt_data.sv[i].sv == 0) {
/* SV not valid, skip */
continue;
}
LOG_DBG("SV: %3d C/N0: %4.1f el: %2d az: %3d signal: %d in fix: %d unhealthy: %d",
pvt_data.sv[i].sv,
pvt_data.sv[i].cn0 * 0.1,
pvt_data.sv[i].elevation,
pvt_data.sv[i].azimuth,
pvt_data.sv[i].signal,
pvt_data.sv[i].flags & NRF_MODEM_GNSS_SV_FLAG_USED_IN_FIX ? 1 : 0,
pvt_data.sv[i].flags & NRF_MODEM_GNSS_SV_FLAG_UNHEALTHY ? 1 : 0);
}
}
/* Helper functions */
static int set_ntn_dormant_mode(void)
{
int err;
/* Set modem to dormant mode without loosing registration */
err = lte_lc_func_mode_set(LTE_LC_FUNC_MODE_OFFLINE_KEEP_REG);
if (err) {
LOG_ERR("lte_lc_func_mode_set, error: %d", err);
return err;
}
return 0;
}
static int set_ntn_active_mode(struct ntn_state_object *state)
{
int err;
uint32_t location_validity_time;
uint64_t current_time = k_uptime_get();
if (state->location_validity_end_time > current_time) {
location_validity_time =
(uint32_t)(state->location_validity_end_time - current_time) / MSEC_PER_SEC;
} else {
location_validity_time = 1;
}
if (state->ntn_initialized) {
/* Configure NTN system mode */
err = lte_lc_system_mode_set(LTE_LC_SYSTEM_MODE_NTN_NBIOT,
LTE_LC_SYSTEM_MODE_PREFER_AUTO);
if (err) {
LOG_ERR("Failed to set NTN system mode, error: %d", err);
return err;
}
LOG_DBG("NTN initialized, using AT+CFUN=21");
err = lte_lc_func_mode_set(LTE_LC_FUNC_MODE_ACTIVATE_LTE);
if (err) {
LOG_ERR("lte_lc_func_mode_set, error: %d", err);
return err;
}
err = ntn_location_set((double)state->last_pvt.latitude,
(double)state->last_pvt.longitude,
(float)state->last_pvt.altitude,
location_validity_time);
if (err) {
LOG_ERR("Failed to set location, error: %d", err);
return err;
}
} else {
struct lte_lc_cellular_profile ntn_profile = {
.id = 0,
.act = LTE_LC_ACT_NTN,
.uicc = LTE_LC_UICC_PHYSICAL,
};
struct lte_lc_cellular_profile tn_profile = {
.id = 1,
.act = LTE_LC_ACT_LTEM || LTE_LC_ACT_NBIOT,
.uicc = LTE_LC_UICC_PHYSICAL,
};
/* Power off modem */
err = lte_lc_power_off();
if (err) {
LOG_ERR("lte_lc_power_off, error: %d", err);
return err;
}
/* Set NTN profile */
err = lte_lc_cellular_profile_configure(&ntn_profile);
if (err) {
LOG_ERR("Failed to set NTN profile, error: %d", err);
return err;
}
/* Set TN profile */
err = lte_lc_cellular_profile_configure(&tn_profile);
if (err) {
LOG_ERR("Failed to set TN profile, error: %d", err);
return err;
}
/* Configure NTN system mode */
err = lte_lc_system_mode_set(LTE_LC_SYSTEM_MODE_NTN_NBIOT,
LTE_LC_SYSTEM_MODE_PREFER_AUTO);
if (err) {
LOG_ERR("Failed to set NTN system mode, error: %d", err);
return err;
}
err = ntn_location_set((double)state->last_pvt.latitude,
(double)state->last_pvt.longitude,
(float)state->last_pvt.altitude,
location_validity_time);
if (err) {
LOG_ERR("Failed to set location, error: %d", err);
return err;
}
#if defined(CONFIG_APP_NTN_BANDLOCK_ENABLE)
err = nrf_modem_at_printf("AT%%XBANDLOCK=2,,\"%i\"", CONFIG_APP_NTN_BANDLOCK);
if (err) {
LOG_ERR("Failed to set NTN band lock, error: %d", err);
return err;
}
#endif
#if defined(CONFIG_APP_NTN_CHANNEL_SELECT_ENABLE)
err = nrf_modem_at_printf("AT%%CHSELECT=1,14,%i", CONFIG_APP_NTN_CHANNEL_SELECT);
if (err) {
LOG_ERR("Failed to set NTN channel, error: %d", err);
return err;
}
#endif
err = lte_lc_psm_req(false);
if (err) {
LOG_ERR("Failed to deactivate legacy PSM, error: %d", err);
return err;
}
state->ntn_initialized = true;
k_sleep(K_MSEC(5000));
LOG_DBG("NTN now initialized, using lte_lc_connect_async to connect to network");
err = lte_lc_connect_async(lte_lc_evt_handler);
if (err) {
LOG_ERR("lte_lc_connect_async, error: %d\n", err);
return err;
}
}
return 0;
}
static int set_gnss_active_mode(struct ntn_state_object *state)
{
int err;
if (state->gnss_initialized) {
/* Configure GNSS system mode */
err = lte_lc_system_mode_set(LTE_LC_SYSTEM_MODE_GPS, LTE_LC_SYSTEM_MODE_PREFER_AUTO);
if (err) {
LOG_ERR("Failed to set GNSS system mode, error: %d", err);
return err;
}
/* Activate GNSS fun mode */
err = lte_lc_func_mode_set(LTE_LC_FUNC_MODE_ACTIVATE_GNSS);
if (err) {
LOG_ERR("Failed to activate GNSS fun mode, error: %d", err);
return err;
}
} else {
/* Power off modem */
err = lte_lc_power_off();
if (err) {
LOG_ERR("lte_lc_power_off, error: %d", err);
return err;
}
/* Configure GNSS system mode */
err = lte_lc_system_mode_set(LTE_LC_SYSTEM_MODE_GPS, LTE_LC_SYSTEM_MODE_PREFER_AUTO);
if (err) {
LOG_ERR("Failed to set GNSS system mode, error: %d", err);
return err;
}
/* Activate GNSS mode */
err = lte_lc_func_mode_set(LTE_LC_FUNC_MODE_ACTIVATE_GNSS);
if (err) {
LOG_ERR("Failed to activate GNSS fun mode, error: %d", err);
return err;
}
state->gnss_initialized=true;
}
err = nrf_modem_gnss_fix_interval_set(0);
if (err) {
LOG_ERR("Failed to set GNSS fix interval, error: %d", err);
}
err = nrf_modem_gnss_fix_retry_set(180);
if (err) {
LOG_ERR("Failed to set GNSS fix retry, error: %d", err);
}
err = nrf_modem_gnss_start();
if (err) {
LOG_ERR("Failed to start GNSS, error: %d", err);
}
return 0;
}
static int set_gnss_inactive_mode(void)
{
int err;
/* Set modem to CFUN=30 mode when exiting GNSS state */
err = lte_lc_func_mode_set(LTE_LC_FUNC_MODE_DEACTIVATE_GNSS);
if (err) {
LOG_ERR("lte_lc_func_mode_set, error: %d", err);
return err;
}
return 0;
}
/* Socket functions */
static int sock_open_and_connect(struct ntn_state_object *state)
{
int err;
struct sockaddr_storage host_addr;
struct sockaddr_in *server4 = ((struct sockaddr_in *)&host_addr);
server4->sin_family = AF_INET;
server4->sin_port = htons(CONFIG_APP_NTN_SERVER_PORT);
(void)inet_pton(AF_INET, CONFIG_APP_NTN_SERVER_ADDR, &server4->sin_addr);
/* Create UDP socket */
state->sock_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (state->sock_fd < 0) {
LOG_ERR("Failed to create UDP socket, error: %d", errno);
return -errno;
}
/* Connect socket */
err = connect(state->sock_fd, (struct sockaddr *)&host_addr, sizeof(struct sockaddr_in));
if (err < 0) {
LOG_ERR("Failed to connect socket, error: %d", errno);
close(state->sock_fd);
state->sock_fd = -1;
return -errno;
}
return 0;
}
static int sock_send_gnss_data(struct ntn_state_object *state)
{
int err;
char message[256];
char imei[16] = {0};
char imei_suffix[5];
size_t imei_len;
char temp[16] = {0};
if (state->sock_fd < 0) {
LOG_ERR("Socket not connected");
return -ENOTCONN;
}
err = modem_info_string_get(MODEM_INFO_IMEI, imei, sizeof(imei));
if (err < 0) {
err = snprintk(imei, sizeof(imei), "N/A");
if (err < 0 || err >= sizeof(imei)) {
LOG_ERR("Failed to get IMEI, error: %d", err);
return -EINVAL;
}
}
/* Extract last 4 characters of IMEI safely */
imei_len = strnlen(imei, sizeof(imei));
if (imei_len > 4) {
err = snprintk(imei_suffix, sizeof(imei_suffix), "%s", imei + (imei_len - 4));
if (err < 0 || err >= sizeof(imei_suffix)) {
LOG_ERR("Failed to get IMEI suffix, error: %d", err);
return -EINVAL;
}
} else {
err = snprintk(imei_suffix, sizeof(imei_suffix), "N/A");
if (err < 0 || err >= sizeof(imei_suffix)) {
LOG_ERR("Failed to get IMEI suffix, error: %d", err);
return -EINVAL;
}
LOG_WRN("IMEI is too short, using N/A");
}
imei_suffix[sizeof(imei_suffix) - 1] = '\0';
/* Get the temperature from the modem */
err = modem_info_string_get(MODEM_INFO_TEMP, temp, sizeof(temp));
if (err < 0) {
err = snprintk(temp, sizeof(temp), "N/A");
if (err < 0 || err >= sizeof(temp)) {
LOG_ERR("Failed to get temperature, error: %d", err);
return -EINVAL;
}
}
temp[sizeof(temp) - 1] = '\0';
#if defined(CONFIG_APP_NTN_SEND_GNSS_DATA)
/* Format GNSS data as string */
err = snprintk(message, sizeof(message),
"Device: *%s, temp: %s, lat=%.2f, lon=%.2f, alt=%.2f, "
"time=%04d-%02d-%02d %02d:%02d:%02d",
imei_suffix, temp,
(double)state->last_pvt.latitude, (double)state->last_pvt.longitude, (double)state->last_pvt.altitude,
state->last_pvt.datetime.year, state->last_pvt.datetime.month, state->last_pvt.datetime.day,
state->last_pvt.datetime.hour, state->last_pvt.datetime.minute, state->last_pvt.datetime.seconds);
if (err < 0 || err >= sizeof(message)) {
LOG_ERR("Failed to format GNSS data, error: %d", err);
return -EINVAL;
}
#else
err = snprintk(message, sizeof(message),
"Device: *%s, temp: %s",
imei_suffix, temp);
if (err < 0 || err >= sizeof(message)) {
LOG_ERR("Failed to format GNSS data, error: %d", err);
return -EINVAL;
}
#endif
/* Send data */
err = send(state->sock_fd, message, strlen(message), 0);
if (err < 0) {
LOG_ERR("Failed to send GNSS data, error: %d", errno);
return -errno;
}
LOG_DBG("Sent GNSS data payload of %d bytes", strlen(message));
return 0;
}
static void ntn_event_handler(const struct ntn_evt *evt)
{
switch (evt->type) {
case NTN_EVT_LOCATION_REQUEST:
LOG_DBG("NTN location requested: %s, accuracy: %d m",
evt->location_request.requested ? "true" : "false",
evt->location_request.accuracy);
ntn_msg_publish(NTN_LOCATION_REQUEST);
break;
default:
break;
}
}
/* State handlers */
static void state_running_entry(void *obj)
{
int err;
struct ntn_state_object *state = (struct ntn_state_object *)obj;
LOG_INF("Initializing NTN module");
k_work_init(&timer_work, timer_work_handler);
k_work_init(&gnss_location_work, gnss_location_work_handler);
k_timer_init(&state->ntn_timer, ntn_timer_handler, NULL);
err = nrf_modem_lib_init();
if (err) {
LOG_ERR("Failed to initialize the modem library, error: %d", err);
return;
}
/* Register GNSS event handler */
nrf_modem_gnss_event_handler_set(gnss_event_handler);
/* Register LTE event handler */
lte_lc_register_handler(lte_lc_evt_handler);
/* Register handler for default PDP context 0. */
err = lte_lc_pdn_default_ctx_events_enable();
if (err) {
LOG_ERR("lte_lc_pdn_default_ctx_events_enable, error: %d", err);
return;
}
ntn_register_handler(ntn_event_handler);
k_timer_start(&state->ntn_timer, K_MINUTES(CONFIG_APP_NTN_TIMER_TIMEOUT_MINUTES), K_NO_WAIT);
}
static enum smf_state_result state_running_run(void *obj)
{
struct ntn_state_object *state = (struct ntn_state_object *)obj;
if (state->chan == &NTN_CHAN) {
struct ntn_msg *msg = (struct ntn_msg *)state->msg_buf;
if (msg->type == NTN_TIMEOUT) {
/* Timer expired, restart timer and transition to GNSS mode */
k_timer_start(&state->ntn_timer,
K_MINUTES(CONFIG_APP_NTN_TIMER_TIMEOUT_MINUTES),
K_NO_WAIT);
smf_set_state(SMF_CTX(state), &states[STATE_NTN]);
return SMF_EVENT_HANDLED;
}
if (msg->type == NTN_LOCATION_REQUEST) {
uint64_t current_time = k_uptime_get();
if (current_time < state->location_validity_end_time) {
LOG_DBG("NTN location is still valid, skipping location request");
return SMF_EVENT_HANDLED;
}
LOG_DBG("NTN location requested, location is invalid, going to GNSS mode");
smf_set_state(SMF_CTX(state), &states[STATE_GNSS]);
return SMF_EVENT_HANDLED;
}
} else if (state->chan == &BUTTON_CHAN) {
k_timer_start(&state->ntn_timer,
K_MINUTES(CONFIG_APP_NTN_TIMER_TIMEOUT_MINUTES),
K_NO_WAIT);
smf_set_state(SMF_CTX(state), &states[STATE_NTN]);
return SMF_EVENT_HANDLED;
}
return SMF_EVENT_PROPAGATE;
}
static void state_gnss_entry(void *obj)
{
int err;
struct ntn_state_object *state = (struct ntn_state_object *)obj;
/* Close socket if it was open */
if (state->sock_fd >= 0) {
close(state->sock_fd);
state->sock_fd = -1;
state->socket_connected = false;
}
LOG_INF("Entering GNSS mode");
err = set_gnss_active_mode(state);
if (err) {
LOG_ERR("Unable to set GNSS mode");
return;
}
}
static enum smf_state_result state_gnss_run(void *obj)
{
struct ntn_state_object *state = (struct ntn_state_object *)obj;
if (state->chan == &NTN_CHAN) {
struct ntn_msg *msg = (struct ntn_msg *)state->msg_buf;
switch (msg->type) {
case NTN_LOCATION_SEARCH_DONE:
/* Location search completed, transition to NTN mode */
memcpy(&state->last_pvt, &msg->pvt, sizeof(state->last_pvt));
state->location_validity_end_time =
k_uptime_get() +
CONFIG_APP_NTN_LOCATION_VALIDITY_TIME_SECONDS * MSEC_PER_SEC;
smf_set_state(SMF_CTX(state), &states[STATE_NTN]);
return SMF_EVENT_HANDLED;
case GNSS_SEARCH_FAILED:
LOG_ERR("GNSS search failed, going to idle state");
smf_set_state(SMF_CTX(state), &states[STATE_IDLE]);
return SMF_EVENT_HANDLED;
case NTN_LOCATION_REQUEST:
LOG_DBG("NTN location requested, already in GNSS mode");
return SMF_EVENT_HANDLED;
default:
break;
}
}
return SMF_EVENT_PROPAGATE;
}
static void state_gnss_exit(void *obj)
{
int err;
LOG_INF("Exiting GNSS mode");
err = nrf_modem_gnss_stop();
if (err) {
LOG_ERR("Failed to stop GNSS, error: %d", err);
}
err = set_gnss_inactive_mode();
if (err) {
LOG_ERR("Failed to set GNSS inactive mode, error: %d", err);
}
}
static void state_ntn_entry(void *obj)
{
int err;
struct ntn_state_object *state = (struct ntn_state_object *)obj;
LOG_INF("Entering NTN mode");
err = set_ntn_active_mode(state);
if (err) {
LOG_ERR("Failed to set NTN active mode, error: %d", err);
}
}
static enum smf_state_result state_ntn_run(void *obj)
{
struct ntn_state_object *state = (struct ntn_state_object *)obj;
int err;
if (state->chan == &NTN_CHAN) {
struct ntn_msg *msg = (struct ntn_msg *)state->msg_buf;
if (msg->type != NTN_NETWORK_CONNECTED) {
return SMF_EVENT_PROPAGATE;
}
LOG_DBG("Setting up socket");
/* Network is connected, set up socket */
err = sock_open_and_connect(state);
if (err) {
LOG_ERR("Failed to connect socket, error: %d", err);
state->socket_connected = false;
} else {
LOG_DBG("Socket connected successfully");
state->socket_connected = true;
/* Send initial GNSS data if available */
if (state->last_pvt.flags & NRF_MODEM_GNSS_PVT_FLAG_FIX_VALID) {
LOG_DBG("Sending initial GNSS data");
err = sock_send_gnss_data(state);
if (err) {
LOG_ERR("Failed to send initial GNSS data, error: %d", err);
} else {
LOG_DBG("Initial GNSS data sent successfully");
}
} else {
LOG_DBG("No valid GNSS data available to send initially");
}
}
/*
* In future, we should wait until we get ACK for data being transmitted,
* and send CFUN=45 only after data were sent successfully.
*
* It may take 10s to send data in NTN.
* k_sleep is added as intermediate solution
*/
k_sleep(K_MSEC(20000));
smf_set_state(SMF_CTX(state), &states[STATE_IDLE]);
return SMF_EVENT_HANDLED;
}
return SMF_EVENT_PROPAGATE;
}
static void state_ntn_exit(void *obj)
{
struct ntn_state_object *state = (struct ntn_state_object *)obj;
int err;
/* Close socket if it was open */
if (state->sock_fd >= 0) {
close(state->sock_fd);
state->sock_fd = -1;
state->socket_connected = false;
}
err = set_ntn_dormant_mode();
if (err) {
LOG_ERR("Failed to set NTN dormant mode, error: %d", err);
}
}
static void state_idle_entry(void *obj)
{
ARG_UNUSED(obj);
LOG_DBG("%s", __func__);
}
static enum smf_state_result state_idle_run(void *obj)
{
ARG_UNUSED(obj);
LOG_DBG("%s", __func__);
return SMF_EVENT_PROPAGATE;
}
static void lte_lc_evt_handler(const struct lte_lc_evt *const evt)
{
switch (evt->type) {
case LTE_LC_EVT_NW_REG_STATUS:
if (evt->nw_reg_status == LTE_LC_NW_REG_UICC_FAIL) {
LOG_ERR("No SIM card detected!");
} else if (evt->nw_reg_status == LTE_LC_NW_REG_NOT_REGISTERED) {
LOG_WRN("Not registered, check rejection cause");
} else if (evt->nw_reg_status == LTE_LC_NW_REG_REGISTERED_HOME) {
LOG_DBG("LTE_LC_NW_REG_REGISTERED_HOME");
} else if (evt->nw_reg_status == LTE_LC_NW_REG_REGISTERED_ROAMING) {
LOG_DBG("LTE_LC_NW_REG_REGISTERED_ROAMING");
}
break;
case LTE_LC_EVT_PDN:
switch (evt->pdn.type) {
case LTE_LC_EVT_PDN_ACTIVATED:
LOG_DBG("PDN connection activated");
ntn_msg_publish(NTN_NETWORK_CONNECTED);
break;
case LTE_LC_EVT_PDN_DEACTIVATED:
LOG_DBG("PDN connection deactivated");
ntn_msg_publish(NTN_NETWORK_DISCONNECTED);
break;
case LTE_LC_EVT_PDN_NETWORK_DETACH:
LOG_DBG("PDN connection network detached");
ntn_msg_publish(NTN_NETWORK_DISCONNECTED);
break;
case LTE_LC_EVT_PDN_SUSPENDED:
LOG_DBG("PDN connection suspended");
ntn_msg_publish(NTN_NETWORK_DISCONNECTED);
break;
case LTE_LC_EVT_PDN_RESUMED:
LOG_DBG("PDN connection resumed");
ntn_msg_publish(NTN_NETWORK_CONNECTED);
default:
break;
}
break;
case LTE_LC_EVT_MODEM_EVENT:
if (evt->modem_evt.type == LTE_LC_MODEM_EVT_RESET_LOOP) {
LOG_WRN("The modem has detected a reset loop!");
} else if (evt->modem_evt.type == LTE_LC_MODEM_EVT_LIGHT_SEARCH_DONE) {
LOG_DBG("LTE_LC_MODEM_EVT_LIGHT_SEARCH_DONE");
}
break;
case LTE_LC_EVT_RRC_UPDATE:
if (evt->rrc_mode == LTE_LC_RRC_MODE_CONNECTED) {
LOG_DBG("LTE_LC_RRC_MODE_CONNECTED");
}
else if (evt->rrc_mode == LTE_LC_RRC_MODE_IDLE) {
LOG_DBG("LTE_LC_RRC_MODE_IDLE");
}
break;
default:
break;
}
}
static void gnss_event_handler(int event)
{
switch (event) {
case NRF_MODEM_GNSS_EVT_PVT:
/* Schedule work to handle PVT data in thread context */
k_work_submit(&gnss_location_work);
break;
/* TODO: add handling for GNSS_SEARCH_FAILED, see mosh gnss.c */
default:
break;
}
}
static void ntn_wdt_callback(int channel_id, void *user_data)
{
LOG_ERR("NTN watchdog expired, Channel: %d, Thread: %s",
channel_id, k_thread_name_get((k_tid_t)user_data));
}
static void ntn_module_thread(void)
{
int err;
int task_wdt_id;
const uint32_t wdt_timeout_ms = CONFIG_APP_NTN_WATCHDOG_TIMEOUT_SECONDS * MSEC_PER_SEC;
const uint32_t execution_time_ms =
(CONFIG_APP_NTN_MSG_PROCESSING_TIMEOUT_SECONDS * MSEC_PER_SEC);
const k_timeout_t zbus_wait_ms = K_MSEC(wdt_timeout_ms - execution_time_ms);
struct ntn_state_object ntn_state = {
.sock_fd = -1,
};
task_wdt_id = task_wdt_add(wdt_timeout_ms, ntn_wdt_callback, (void *)k_current_get());
if (task_wdt_id < 0) {
LOG_ERR("Failed to add task to watchdog: %d", task_wdt_id);
SEND_FATAL_ERROR();
return;
}
/* Initialize state machine */
smf_set_initial(SMF_CTX(&ntn_state), &states[STATE_RUNNING]);
while (true) {
err = task_wdt_feed(task_wdt_id);
if (err) {
LOG_ERR("task_wdt_feed, error: %d", err);
SEND_FATAL_ERROR();
return;
}
/* Wait for messages */
err = zbus_sub_wait_msg(&ntn, &ntn_state.chan, ntn_state.msg_buf, zbus_wait_ms);
if (err == -ENOMSG) {
continue;
} else if (err) {
LOG_ERR("zbus_sub_wait_msg, error: %d", err);
SEND_FATAL_ERROR();
return;
}
/* Run state machine */
err = smf_run_state(SMF_CTX(&ntn_state));
if (err) {
LOG_ERR("Failed to run state machine, error: %d", err);
continue;
}
}
}
K_THREAD_DEFINE(ntn_module_thread_id,
CONFIG_APP_NTN_THREAD_STACK_SIZE,
ntn_module_thread, NULL, NULL, NULL,
K_LOWEST_APPLICATION_THREAD_PRIO, 0, 0);