-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathesc_node.cpp
More file actions
826 lines (710 loc) · 31 KB
/
esc_node.cpp
File metadata and controls
826 lines (710 loc) · 31 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
//
// Copyright 2010-2011,2014 Ettus Research LLC
// Copyright 2018 Ettus Research, a National Instruments Company
//
// SPDX-License-Identifier: GPL-3.0-or-later
//
//Modified by Oren Rodney Collaco
// ESC sensor node
#include "esc_dft.hpp" //implementation
#include <uhd/usrp/multi_usrp.hpp>
#include <uhd/utils/safe_main.hpp>
#include <uhd/utils/thread.hpp>
#include <curses.h>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <chrono>
#include <complex>
#include <cstdlib>
#include <iostream>
#include <thread>
#include <sstream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <mutex>
// For different N310 as ESC node, use different node numbers
#define SENSOR_NODE 1
#define FFT_AVERAGES 2
// Paths to the certificates,keys and the url of the OpenSAS server
std::string client_crt_path = "../certs/client_10.147.20.75-0.crt";
std::string client_key_path = "../certs/client_10.147.20.75-0.key";
std::string ca_crt_path = "../certs/ca.crt";
// Path to Open-SAS URL
std::string opensas_url = "https://10.147.20.75:1443/sas-api/";
#define FFT_ON_FPGA 0
// #define DEBUG 1
#define DEBUG 0
#define STATS 1
// #define STATS 0
#define STATS_FFT 0
// #define STATS_FFT 0
// based on the input shape the model will be trained to detect
#define DETECTION_SAMPLE_SIZE 102400
// the threshold for the detection
#define DETECTION_THRESHOLD -70
#if SENSOR_NODE == 1
#define SENSOR_ID "xG-OpenSense-Node1"
#define SENSOR_LAT 38.88089743634038
#define SENSOR_LON -77.11569278866236
#elif SENSOR_NODE == 2
#define SENSOR_ID "xG-OpenSense-Node2"
#define SENSOR_LAT 38.880863506784166
#define SENSOR_LON -77.11578465431765
#elif SENSOR_NODE == 3
#define SENSOR_ID "xG-OpenSense-Node3"
#define SENSOR_LAT 38.88099087303452
#define SENSOR_LON -77.11574442118396
#elif SENSOR_NODE == 4
#define SENSOR_ID "xG-OpenSense-Node4"
#define SENSOR_LAT 38.88091988203791
#define SENSOR_LON 77.11583494573478
#endif
namespace po = boost::program_options;
using std::chrono::high_resolution_clock;
// struct to hold the channel power data and location
struct channel_data {
float channel_pwr[15];
double lat;
double lon;
};
struct channel_data data;
size_t num_avgs = FFT_AVERAGES;
std::mutex curl_mutex;
void post_power_data(channel_data data, std::string url);
void post_iq_data(std::vector<std::complex<float>>& buff, size_t len, uint8_t channel, std::string url);
void post_iq_data_nocurl(std::vector<std::complex<float>>& buff, size_t len, uint8_t channel, std::string url);
void post_json(std::string json_str, std::string url);
int compute_average_on_bins(float *dft, size_t len);
void set_center_frequency(uint32_t freq, uhd::usrp::multi_usrp::sptr usrp, po::variables_map vm);
double get_center_freq(int channel);
int UHD_SAFE_MAIN(int argc, char* argv[])
{
//initialize channel power data
data.lat = SENSOR_LAT;
data.lon = SENSOR_LON;
//init channel power data
for (int i = 0; i < 15; i++) {
data.channel_pwr[i] = -100;
}
// variables to be set by po
std::string args, ant, subdev, ref;
size_t len;
double rate, freq, gain, bw, frame_rate, step;
float ref_lvl, dyn_rng;
bool show_controls, observe;
// //initialize required variables
// rate = 10416667; //125e6/12
// freq = 3555000000; //3.555 GHz
// gain = 80;
// setup the program options
po::options_description desc("Allowed options");
// clang-format off
desc.add_options()
("help", "help message")
("args", po::value<std::string>(&args)->default_value(""), "multi uhd device address args")
// hardware parameters
("rate", po::value<double>(&rate), "rate of incoming samples (sps)")
("freq", po::value<double>(&freq), "RF center frequency in Hz")
("gain", po::value<double>(&gain), "gain for the RF chain")
("ant", po::value<std::string>(&ant), "antenna selection")
("subdev", po::value<std::string>(&subdev), "subdevice specification")
("bw", po::value<double>(&bw), "analog frontend filter bandwidth in Hz")
("observe", po::value<bool>(&observe)->default_value(false), "Keeps observing on detected channel for 10 seconds")
// display parameters
("num-bins", po::value<size_t>(&len)->default_value(512), "the number of bins in the DFT")
("num-avgs", po::value<size_t>(&num_avgs)->default_value(FFT_AVERAGES), "the number of averages in the DFT")
;
// clang-format on
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
// print the help message
if (vm.count("help") or not vm.count("rate")) {
std::cout << boost::format("UHD RX ASCII Art DFT %s") % desc << std::endl;
return EXIT_FAILURE;
}
// create a usrp device
std::cout << std::endl;
std::cout << boost::format("Creating the usrp device with: %s...") % args
<< std::endl;
uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);
// Lock mboard clocks
if (vm.count("ref")) {
usrp->set_clock_source(ref);
}
// always select the subdevice first, the channel mapping affects the other settings
if (vm.count("subdev"))
usrp->set_rx_subdev_spec(subdev);
std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;
// set the sample rate
if (not vm.count("rate")) {
std::cerr << "Please specify the sample rate with --rate" << std::endl;
return EXIT_FAILURE;
}
std::cout << boost::format("Setting RX Rate: %f Msps...") % (rate / 1e6) << std::endl;
usrp->set_rx_rate(rate);
std::cout << boost::format("Actual RX Rate: %f Msps...") % (usrp->get_rx_rate() / 1e6)
<< std::endl
<< std::endl;
// set the center frequency
if (not vm.count("freq")) {
std::cerr << "Please specify the center frequency with --freq" << std::endl;
return EXIT_FAILURE;
}
std::cout << boost::format("Setting RX Freq: %f MHz...") % (freq / 1e6) << std::endl;
uhd::tune_request_t tune_request(freq);
if (vm.count("int-n"))
tune_request.args = uhd::device_addr_t("mode_n=integer");
usrp->set_rx_freq(tune_request);
std::cout << boost::format("Actual RX Freq: %f MHz...") % (usrp->get_rx_freq() / 1e6)
<< std::endl
<< std::endl;
// set the rf gain
if (vm.count("gain")) {
std::cout << boost::format("Setting RX Gain: %f dB...") % gain << std::endl;
usrp->set_rx_gain(gain);
std::cout << boost::format("Actual RX Gain: %f dB...") % usrp->get_rx_gain()
<< std::endl
<< std::endl;
} else {
gain = usrp->get_rx_gain();
}
// set the analog frontend filter bandwidth
if (vm.count("bw")) {
std::cout << boost::format("Setting RX Bandwidth: %f MHz...") % (bw / 1e6)
<< std::endl;
usrp->set_rx_bandwidth(bw);
std::cout << boost::format("Actual RX Bandwidth: %f MHz...")
% (usrp->get_rx_bandwidth() / 1e6)
<< std::endl
<< std::endl;
} else {
bw = usrp->get_rx_bandwidth();
}
// set the antenna
if (vm.count("ant"))
usrp->set_rx_antenna(ant);
std::this_thread::sleep_for(std::chrono::seconds(1)); // allow for some setup time
// Check Ref and LO Lock detect
std::vector<std::string> sensor_names;
sensor_names = usrp->get_rx_sensor_names(0);
if (std::find(sensor_names.begin(), sensor_names.end(), "lo_locked")
!= sensor_names.end()) {
uhd::sensor_value_t lo_locked = usrp->get_rx_sensor("lo_locked", 0);
std::cout << boost::format("Checking RX: %s ...") % lo_locked.to_pp_string()
<< std::endl;
UHD_ASSERT_THROW(lo_locked.to_bool());
}
sensor_names = usrp->get_mboard_sensor_names(0);
if ((ref == "mimo")
and (std::find(sensor_names.begin(), sensor_names.end(), "mimo_locked")
!= sensor_names.end())) {
uhd::sensor_value_t mimo_locked = usrp->get_mboard_sensor("mimo_locked", 0);
std::cout << boost::format("Checking RX: %s ...") % mimo_locked.to_pp_string()
<< std::endl;
UHD_ASSERT_THROW(mimo_locked.to_bool());
}
if ((ref == "external")
and (std::find(sensor_names.begin(), sensor_names.end(), "ref_locked")
!= sensor_names.end())) {
uhd::sensor_value_t ref_locked = usrp->get_mboard_sensor("ref_locked", 0);
std::cout << boost::format("Checking RX: %s ...") % ref_locked.to_pp_string()
<< std::endl;
UHD_ASSERT_THROW(ref_locked.to_bool());
}
// create a receive streamer
uhd::stream_args_t stream_args("fc32"); // complex floats
uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);
// allocate recv buffer and metatdata
uhd::rx_metadata_t md;
std::vector<std::complex<float>> buff(len);
std::vector<std::complex<float>> detect_buff(DETECTION_SAMPLE_SIZE);
//------------------------------------------------------------------
//-- Initialize
//------------------------------------------------------------------
//initscr(); // curses init
//Create issue stream command asking for buf samples
uhd::stream_cmd_t stream_cmd_normal(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_MORE);
stream_cmd_normal.num_samps = size_t(buff.size());
stream_cmd_normal.stream_now = true;
stream_cmd_normal.time_spec = uhd::time_spec_t();
//Create issue stream command asking for buf samples
uhd::stream_cmd_t stream_cmd_detect(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_MORE);
stream_cmd_detect.num_samps = size_t(detect_buff.size());
stream_cmd_detect.stream_now = true;
stream_cmd_detect.time_spec = uhd::time_spec_t();
auto next_refresh = high_resolution_clock::now();
auto data_sent_time = high_resolution_clock::now();
auto iq_data_sent_time = high_resolution_clock::now();
auto observe_time = high_resolution_clock::now();
#if STATS
auto detection_stats_time = high_resolution_clock::now();
#endif
#if STATS_FFT
auto fft_stats_time = high_resolution_clock::now();
#endif
//------------------------------------------------------------------
//-- Main loop
//------------------------------------------------------------------
int i = 0;
bool new_data_available = false;
//Wait 20 us before starting to stream
while (high_resolution_clock::now() < next_refresh + std::chrono::microseconds(20)) {
continue;
}
//Verify the waiting time was correct
auto duration = high_resolution_clock::now() - next_refresh;
std::cout << "Verifying timing (20us): " << duration.count() / 1000 << " us" << std::endl;
while (true) {
//Tell USRP to only stream x amount of samples until asked again.
rx_stream->issue_stream_cmd(stream_cmd_normal);
// read a buffer's worth of samples every iteration
size_t num_rx_samps = rx_stream->recv(&buff.front(), buff.size(), md);
if (num_rx_samps != buff.size())
continue;
#if DEBUG
// Print the first 10 IQ samples
int j = 0;
while (j < 5) {
std::cout << "Sample " << j << ": " << buff[j] << std::endl;
j++;
}
#endif
// // check and update the display refresh condition
if (high_resolution_clock::now() < next_refresh) {
continue;
}
next_refresh = high_resolution_clock::now()
+ std::chrono::microseconds(int64_t(1e6 / frame_rate));
#if STATS_FFT
fft_stats_time = high_resolution_clock::now();
#endif
// calculate the dft
esc_dft::log_pwr_dft_type lpdft(
esc_dft::log_pwr_dft(&buff.front(), num_rx_samps));
// re-order the dft so dc in in the center
const size_t len = lpdft.size() - 1 + lpdft.size() % 2; // make it odd
esc_dft::log_pwr_dft_type dft(len);
for (size_t n = 0; n < len; n++) {
dft[n] = lpdft[(n + len / 2) % len];
}
#if STATS_FFT
auto fft_stats_duration = (high_resolution_clock::now() - fft_stats_time);
std::cout << "FFT time: " << fft_stats_duration.count() / 1000 << " us" << std::endl;
#endif
// int64_t average = 0;
// std::cout << " Ch = " << i+1;
// for(int i = 0; i < dft.size(); i++){
// average = (average + dft[i])/2;
// }
// std::cout << " " << average;
// data.channel_pwr[i] = average;
// i+=1;
// if(i > 14){
// post_power_data(data, "https://10.147.20.60:1443/sas-api/measurements");
// post_iq_data(&buff, len, 14, "https://10.147.20.60:1443/sas-api/samples");
// i = 0;
// freq = 3555e6; //Set to channel one center back i.e. 3.555 GHz
// std::cout << "\n";
// }
// else{
// freq += 10e6; //Increment frequency by 10 MHz to observe the next channel
// set_center_frequency(freq, usrp, vm);
// }
// check if any channels are above the threshold
int detect_channel = compute_average_on_bins(dft.data(), len);
#if DEBUG
//print detect channel
std::cout << "Detect channel: " << detect_channel << std::endl;
#endif
if(detect_channel < 0){
if(high_resolution_clock::now() > data_sent_time){
data_sent_time = high_resolution_clock::now()
+ std::chrono::microseconds(int64_t(250e3));
#if DEBUG
//Now send the data to the server
printf("Sending power meas");
#endif
post_power_data(data, opensas_url + "measurements");
}
}
else{
auto detection_stats_duration = (high_resolution_clock::now() - detection_stats_time);
//while observe time is not reached, keep looking for signals
if(high_resolution_clock::now() > iq_data_sent_time){
size_t num_rx_detect_samps = 0;
//Change center frequency to the detected channel
#if STATS
detection_stats_time = high_resolution_clock::now();
#endif
set_center_frequency(get_center_freq(detect_channel), usrp, vm);
#if STATS
detection_stats_duration = (high_resolution_clock::now() - detection_stats_time);
std::cout << "Freq shift time ch" << detect_channel << ": " << detection_stats_duration.count() / 1000 << " us" << std::endl;
#endif
//Change sample rate to 10.24 MHz to capture 1 ms of data for the detected channel
std::cout << boost::format("Setting RX Rate: %f Msps...") % (10.24e6 / 1e6) << std::endl;
#if STATS
detection_stats_time = high_resolution_clock::now();
#endif
usrp->set_rx_rate(10.24e6);
#if STATS
detection_stats_duration = (high_resolution_clock::now() - detection_stats_time);
std::cout << "Srate change time: " << detection_stats_duration.count() / 1000 << " us" << std::endl;
#endif
std::cout << boost::format("Actual RX Rate: %f Msps...") % (usrp->get_rx_rate() / 1e6)
<< std::endl
<< std::endl;
// Set observe time to 100 ms ahead of current time
observe_time = high_resolution_clock::now();
auto observe_duration = (high_resolution_clock::now() - observe_time);
while((observe_duration.count() /1000) < 1000e3){
#if STATS
detection_stats_time = high_resolution_clock::now();
#endif
num_rx_detect_samps = 0;
rx_stream->issue_stream_cmd(stream_cmd_detect);
while (num_rx_detect_samps < detect_buff.size()) {
// Wait for the next buffer of samples
num_rx_detect_samps += rx_stream->recv(&detect_buff.front(), detect_buff.size(), md);
// Print the number of samples received
std::cout << "Received " << num_rx_detect_samps << " samples" << std::endl;
if (num_rx_samps != detect_buff.size())
continue;
}
#if STATS
detection_stats_duration = (high_resolution_clock::now() - detection_stats_time);
std::cout << "Samples recv time: " << detection_stats_duration.count() / 1000 << " us" << std::endl;
#endif
//Calculate FFT on 512 samples in detect_buff
// calculate the dft
// esc_dft::log_pwr_dft_type detect_dft(
// esc_dft::log_pwr_dft(&detect_buff.front(), 512));
post_power_data(data, opensas_url + "measurements");
//Check if the average of all bins is above the threshold
//Compute average on all bins without using compute_average_on_bins function
// int64_t average = 0;
// for(int i = 0; i < detect_dft.size(); i++){
// average = (average + detect_dft[i])/2;
// }
// std::cout << "Detected average: " << average << std::endl;
//If average is above threshold, send the data to the server
// if(average > DETECTION_THRESHOLD){
#if STATS
detection_stats_time = high_resolution_clock::now();
#endif
post_iq_data_nocurl(detect_buff, detect_buff.size(), detect_channel, opensas_url + "samples");
#if STATS
detection_stats_duration = (high_resolution_clock::now() - detection_stats_time);
std::cout << "Https req time: " << detection_stats_duration.count() / 1000 << " us" << std::endl;
#endif
// }
observe_duration = (high_resolution_clock::now() - observe_time);
//Print observe duration
std::cout << "Observe duration: " << observe_duration.count() / 1000 << " us" << std::endl;
}
//Change sample rate back to 122.88 MHz
std::cout << boost::format("Setting RX Rate: %f Msps...") % (122.88e6 / 1e6) << std::endl;
usrp->set_rx_rate(122.88e6);
std::cout << boost::format("Actual RX Rate: %f Msps...") % (usrp->get_rx_rate() / 1e6)
<< std::endl
<< std::endl;
if(!observe)
iq_data_sent_time = high_resolution_clock::now()
+ std::chrono::microseconds(int64_t(50e3));
#if STATS
detection_stats_time = high_resolution_clock::now();
#endif
set_center_frequency(3650e6, usrp, vm);
#if STATS
detection_stats_duration = (high_resolution_clock::now() - detection_stats_time);
std::cout << "Freq return time: " << detection_stats_duration.count() / 1000 << " us" << std::endl;
#endif
}
}
}
//------------------------------------------------------------------
//-- Cleanup
//------------------------------------------------------------------
rx_stream->issue_stream_cmd(uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS);
endwin(); // curses done
// finished
std::cout << std::endl << "Done!" << std::endl << std::endl;
return EXIT_SUCCESS;
}
/*
Computes average on fft points - start_point - end_point_offset bins excluding start_point bins at the beginning and end_point_offset bins at the end, returns -1 if no bins are above threshold,
else returns the index of channel with power above threshold
*/
int compute_average_on_bins(float *dft, size_t len){
// Calculate number of averages we want to take
int num_averages = 15;
int channel_offset = 5;
int skip_steps = 1;
int start_point = 10;
int end_point_offset = 10;
int detect_channel = -1;
float max = -100;
// Calculate average of first 34 elements
int step = 41;
float temp_avg = 0;
for (int i = channel_offset; i < num_averages-1; i++) {
double sum = 0;
for (int j = ((i - channel_offset + skip_steps) * step) + start_point; j < (i + 1 - channel_offset + skip_steps) * step + start_point; j++) {
sum = sum + dft[j];
}
temp_avg = sum / step;
// Use FFT_AVERAGES to determine the number of averages to take
data.channel_pwr[i] = (data.channel_pwr[i] * (num_avgs - 1) + temp_avg) / num_avgs;
#if DEBUG
std::cout << " Ch = " << i;
std::cout << " " << data.channel_pwr[i];
#endif
// Check if the average is above the threshold
if(data.channel_pwr[i] > DETECTION_THRESHOLD){
// Check if the average is greater than the max
if(data.channel_pwr[i] > max){
// Update the max and the channel
max = data.channel_pwr[i];
detect_channel = i;
}
}
}
// Calculate average of last "step" elements, excluding the last element
double sum = 0;
for (int i = len-(step * (skip_steps+1))-end_point_offset; i < len-(step * (skip_steps)) - end_point_offset; i++) {
sum += dft[i];
}
temp_avg = sum / step;
// Use FFT_AVERAGES to determine the number of averages to take
data.channel_pwr[num_averages-1] = (data.channel_pwr[num_averages-1] * (num_avgs - 1) + temp_avg) / num_avgs;
// Check if the last element is above the threshold
if(data.channel_pwr[num_averages-1] > DETECTION_THRESHOLD){
if(data.channel_pwr[num_averages-1] > max){
max = data.channel_pwr[num_averages-1];
detect_channel = num_averages-1;
}
}
#if DEBUG
std::cout << " Ch = " << 14;
std::cout << " " << data.channel_pwr[num_averages-1];
std::cout << "\n";
#endif
return detect_channel;
}
/**
* Calculates the center frequency in MHz for a given channel number.
*
* @param channel The channel number, between 0 and 14 (inclusive).
* @return The center frequency in MHz.
*/
double get_center_freq(int channel) {
const double channelWidth = 10.0e6; // The width of each channel in MHz.
const double baseFreq = 3550.0e6; // The frequency of the first channel in MHz.
// Calculate the center frequency of the specified channel using the formula:
// centerFreq = baseFreq + (channel * channelWidth) + (channelWidth / 2.0)
double centerFreq = baseFreq + (channel * channelWidth) + (channelWidth / 2.0);
// Return the center frequency to the caller.
return centerFreq;
}
//Function to set the center frequency via the UHD driver
void set_center_frequency(uint32_t freq, uhd::usrp::multi_usrp::sptr usrp, po::variables_map vm){
uhd::tune_request_t tune_request(freq);
if (vm.count("int-n"))
tune_request.args = uhd::device_addr_t("mode_n=integer");
usrp->set_rx_freq(tune_request);
std::cout << boost::format("RX Freq: %f MHz...\n") % (usrp->get_rx_freq() / 1e6);
}
//Function to send HTTPS post request for all the power values
void post_power_data(channel_data data, std::string url) {
// Construct the JSON payload
std::stringstream json_ss;
json_ss << "{";
json_ss << "\"sensor_id\":\"" << SENSOR_ID << "\"," ;
json_ss << "\"lat\":" << data.lat << ",";
json_ss << "\"lon\":" << data.lon << ",";
json_ss << "\"channels\":[";
for (int i = 0; i < 14; i++) {
if(data.channel_pwr[i] > DETECTION_THRESHOLD)
json_ss << "{\"id\":" << i << ",\"power\":" << data.channel_pwr[i] << ",\"detected\":true,\"signal\":\"unknown\"},";
else
json_ss << "{\"id\":" << i << ",\"power\":" << data.channel_pwr[i] << ",\"detected\":false,\"signal\":\"unknown\"},";
}
if(data.channel_pwr[14] > DETECTION_THRESHOLD)
json_ss << "{\"id\":14,\"power\":" << data.channel_pwr[14] << ",\"detected\":true,\"signal\":\"unknown\"}";
else
json_ss << "{\"id\":14,\"power\":" << data.channel_pwr[14] << ",\"detected\":false,\"signal\":\"unknown\"}";
json_ss << "]}";
std::string json_str = json_ss.str();
// Construct the curl command
std::string command = "curl -X POST -H 'Content-Type: application/json' --data '" + json_str + "' --cert " + client_crt_path + " --key " + client_key_path + " --cacert " + ca_crt_path + " " + url;
post_json(json_str, url);
}
/*
Function to send HTTPS post request for the IQ samples for further processing if a
power level is above a threshold.
*/
void post_iq_data(std::vector<std::complex<float>>& buff, size_t len, uint8_t channel, std::string url){
std::stringstream json_ss;
json_ss << "{";
json_ss << "\"sensor_info\": {";
json_ss << "\"sensor_id\":\"" << SENSOR_ID << "\"," ;
json_ss << "\"lat\":" << data.lat << ",";
json_ss << "\"lon\":" << data.lon << "},";
json_ss << "\"detected_channel\":" << (int)channel << ",";
json_ss << "\"iq_samples\":[";
for (int i = 0; i < len - 1; i++) {
json_ss << "[" << buff.at(i).real() << "," << buff.at(i).imag() << "],";
}
json_ss << "[" << buff.at(len - 1).real() << "," << buff.at(len - 1).imag() << "]";
json_ss << "]}";
std::string json_str = json_ss.str();
//Print the JSON string
//std::cout << json_str << std::endl;
//Nofity the user that the data is being sent
std::cout << "Sending 100k IQ samples to OpenSAS..." << std::endl;
// Construct the curl command
std::string command = "curl -X POST -H 'Content-Type: application/json' --data '" + json_str + "' --cert " + client_crt_path + " --key " + client_key_path + " --cacert " + ca_crt_path + " " + url;
// Execute the curl command
system(command.c_str());
std::cout << command.c_str() << std::endl;
//Nofity the user that the data has been sent
std::cout << "Data sent." << std::endl;
}
/*
*/
void post_iq_data_nocurl(std::vector<std::complex<float>>& buff, size_t len, uint8_t channel, std::string url) {
std::stringstream json_ss;
json_ss << "{";
json_ss << "\"sensor_info\": {";
json_ss << "\"sensor_id\":\"" << SENSOR_ID << "\"," ;
json_ss << "\"lat\":" << data.lat << ",";
json_ss << "\"lon\":" << data.lon << "},";
json_ss << "\"detected_channel\":" << (int)channel << ",";
json_ss << "\"iq_samples\":[";
for (int i = 0; i < len - 1; i++) {
json_ss << "[" << buff.at(i).real() << "," << buff.at(i).imag() << "],";
}
json_ss << "[" << buff.at(len - 1).real() << "," << buff.at(len - 1).imag() << "]";
json_ss << "]}";
std::string json_str = json_ss.str();
#if DEBUG
//Nofity the user that the data is being sent
std::cout << "Sending data to server..." << std::endl;
#endif
//Print the JSON string
// std::cout << json_str << std::endl;
post_json(json_str, url);
}
void post_json(std::string json_str, std::string url) {
char url_new[url.length() + 1];
strcpy(url_new, url.c_str());
// Find the protocol component
char *protocol = strtok(url_new, ":/");
// Find the hostname component
char *hostname = strtok(NULL, ":/");
// Find the port component
char *port = strtok(NULL, "/");
// Find the path component
char *path = strtok(NULL, "");
std::string path_str(path);
#if DEBUG
// Print the components
std::cout << "Protocol: " << protocol << std::endl;
std::cout << "Hostname: " << hostname << std::endl;
std::cout << "Port: " << port << std::endl;
std::cout << "Path: " << path_str << std::endl;
#endif
// Initialize OpenSSL
SSL_library_init();
SSL_CTX *ssl_ctx = SSL_CTX_new(TLS_client_method());
// Load the client certificate and key
if (SSL_CTX_use_certificate_file(ssl_ctx, client_crt_path.c_str(), SSL_FILETYPE_PEM) <= 0) {
perror("ERROR loading client certificate");
return;
}
if (SSL_CTX_use_PrivateKey_file(ssl_ctx, client_key_path.c_str(), SSL_FILETYPE_PEM) <= 0) {
perror("ERROR loading client private key");
return;
}
// Load the CA certificate
if (SSL_CTX_load_verify_locations(ssl_ctx, ca_crt_path.c_str(), nullptr) <= 0) {
perror("ERROR loading CA certificate");
return;
}
// Create a socket
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("ERROR opening socket");
return;
}
// Set a timeout for the socket
struct timeval timeout;
timeout.tv_sec = 5; // 5 seconds timeout
timeout.tv_usec = 0;
if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0) {
perror("ERROR setting socket options");
return;
}
// Set the server address
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(atoi(port));
if (inet_pton(AF_INET, hostname, &serv_addr.sin_addr) <= 0) {
perror("ERROR invalid address");
return;
}
// Connect to the server
if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
perror("ERROR connecting");
return;
}
// Create an SSL object and attach it to the socket
SSL *ssl = SSL_new(ssl_ctx);
SSL_set_fd(ssl, sockfd);
// Establish the SSL connection
if (SSL_connect(ssl) != 1) {
perror("ERROR establishing SSL connection");
return;
}
// Send the HTTP POST request
std::string post_req = "POST /" + path_str + " HTTP/1.1\r\n";
post_req += "Host: " + url + "\r\n";
post_req += "Content-Type: application/json\r\n";
post_req += "Content-Length: " + std::to_string(json_str.size()) + "\r\n";
post_req += "\r\n";
post_req += json_str;
if (SSL_write(ssl, post_req.c_str(), post_req.size()) < 0) {
perror("ERROR writing to socket");
return;
}
// Read the response from the server
char buffer[1024];
int bytes_read = SSL_read(ssl, buffer, sizeof(buffer));
// Check if any data was received
if (bytes_read <= 0) {
if (bytes_read == 0) {
std::cerr << "ERROR: Server closed the connection" << std::endl;
} else if (errno == EAGAIN || errno == EWOULDBLOCK) {
std::cerr << "ERROR: Timeout while reading from socket" << std::endl;
} else {
perror("ERROR reading from socket");
}
SSL_shutdown(ssl);
SSL_free(ssl);
SSL_CTX_free(ssl_ctx);
close(sockfd);
return;
}
// Close the SSL connection and the socket
SSL_shutdown(ssl);
SSL_free(ssl);
SSL_CTX_free(ssl_ctx);
close(sockfd);
}