-
Notifications
You must be signed in to change notification settings - Fork 128
/
main.c
3580 lines (3317 loc) · 106 KB
/
main.c
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) 2019-2023, Dmitry (DiSlord) [email protected]
* Based on TAKAHASHI Tomohiro (TTRFTECH) [email protected]
* All rights reserved.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* The software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "ch.h"
#include "hal.h"
#include "usbcfg.h"
#include "si5351.h"
#include "nanovna.h"
#include <chprintf.h>
#include <string.h>
/*
* Shell settings
*/
// If need run shell as thread (use more amount of memory fore stack), after
// enable this need reduce spi_buffer size, by default shell run in main thread
// #define VNA_SHELL_THREAD
static BaseSequentialStream *shell_stream = 0;
threads_queue_t shell_thread;
// Shell new line
#define VNA_SHELL_NEWLINE_STR "\r\n"
// Shell command promt
#define VNA_SHELL_PROMPT_STR "ch> "
// Shell max arguments
#define VNA_SHELL_MAX_ARGUMENTS 4
// Shell max command line size
#define VNA_SHELL_MAX_LENGTH 64
// Shell frequency printf format
//#define VNA_FREQ_FMT_STR "%lu"
#define VNA_FREQ_FMT_STR "%u"
// Shell command functions prototypes
typedef void (*vna_shellcmd_t)(int argc, char *argv[]);
#define VNA_SHELL_FUNCTION(command_name) \
static void command_name(int argc, char *argv[])
// Shell command line buffer, args, nargs, and function ptr
static char shell_line[VNA_SHELL_MAX_LENGTH];
static char *shell_args[VNA_SHELL_MAX_ARGUMENTS + 1];
static uint16_t shell_nargs;
static volatile vna_shellcmd_t shell_function = 0;
#define ENABLED_DUMP_COMMAND
// Allow get threads debug info
//#define ENABLE_THREADS_COMMAND
// Enable vbat_offset command, allow change battery voltage correction in config
#define ENABLE_VBAT_OFFSET_COMMAND
// Info about NanoVNA, need fore soft
#define ENABLE_INFO_COMMAND
// Enable color command, allow change config color for traces, grid, menu
#define ENABLE_COLOR_COMMAND
// Enable transform command
#define ENABLE_TRANSFORM_COMMAND
// Enable sample command
//#define ENABLE_SAMPLE_COMMAND
// Enable I2C command for send data to AIC3204, used for debug
//#define ENABLE_I2C_COMMAND
// Enable LCD command for send data to LCD screen, used for debug
//#define ENABLE_LCD_COMMAND
// Enable output debug data on screen on hard fault
//#define ENABLE_HARD_FAULT_HANDLER_DEBUG
// Enable test command, used for debug
//#define ENABLE_TEST_COMMAND
// Enable stat command, used for debug
//#define ENABLE_STAT_COMMAND
// Enable gain command, used for debug
//#define ENABLE_GAIN_COMMAND
// Enable port command, used for debug
//#define ENABLE_PORT_COMMAND
// Enable si5351 register write, used for debug
//#define ENABLE_SI5351_REG_WRITE
// Enable i2c timing command, used for debug
//#define ENABLE_I2C_TIMINGS
// Enable band setting command, used for debug
//#define ENABLE_BAND_COMMAND
// Enable scan_bin command (need use ex scan in future)
#define ENABLE_SCANBIN_COMMAND
// Enable debug for console command
//#define DEBUG_CONSOLE_SHOW
// Enable usart command
#define ENABLE_USART_COMMAND
// Enable config command
#define ENABLE_CONFIG_COMMAND
#ifdef __USE_SD_CARD__
// Enable SD card console command
#define ENABLE_SD_CARD_COMMAND
#endif
static void apply_CH0_error_term(float data[4], float c_data[CAL_TYPE_COUNT][2]);
static void apply_CH1_error_term(float data[4], float c_data[CAL_TYPE_COUNT][2]);
static void cal_interpolate(int idx, freq_t f, float data[CAL_TYPE_COUNT][2]);
static uint16_t get_sweep_mask(void);
static void update_frequencies(void);
static int set_frequency(freq_t freq);
static void set_frequencies(freq_t start, freq_t stop, uint16_t points);
static bool sweep(bool break_on_operation, uint16_t ch_mask);
static void transform_domain(uint16_t ch_mask);
uint8_t sweep_mode = SWEEP_ENABLE;
// current sweep point (used for continue sweep if user break)
static uint16_t p_sweep = 0;
// Sweep measured data
float measured[2][SWEEP_POINTS_MAX][2];
#undef VERSION
#define VERSION "1.2.27"
// Version text, displayed in Config->Version menu, also send by info command
const char *info_about[]={
"Board: " BOARD_NAME,
"2019-2024 Copyright NanoVNA.com",
"based on @DiSlord @edy555 ... source",
"Licensed under GPL.",
"Version: " VERSION " ["\
"p:"define_to_STR(SWEEP_POINTS_MAX)", "\
"IF:"define_to_STR(FREQUENCY_IF_K)"k, "\
"ADC:"define_to_STR(AUDIO_ADC_FREQ_K1)"k, "\
"Lcd:"define_to_STR(LCD_WIDTH)"x"define_to_STR(LCD_HEIGHT)\
"]", "Build Time: " __DATE__ " - " __TIME__,
// "Kernel: " CH_KERNEL_VERSION,
// "Compiler: " PORT_COMPILER_NAME,
"Architecture: " PORT_ARCHITECTURE_NAME " Core Variant: " PORT_CORE_VARIANT_NAME,
// "Port Info: " PORT_INFO,
"Platform: " PLATFORM_NAME,
0 // sentinel
};
// Allow draw some debug on LCD
#ifdef DEBUG_CONSOLE_SHOW
void my_debug_log(int offs, char *log){
static uint16_t shell_line_y = 0;
lcd_set_foreground(LCD_FG_COLOR);
lcd_set_background(LCD_BG_COLOR);
lcd_fill(FREQUENCIES_XPOS1, shell_line_y, LCD_WIDTH-FREQUENCIES_XPOS1, 2 * FONT_GET_HEIGHT);
lcd_drawstring(FREQUENCIES_XPOS1 + offs, shell_line_y, log);
shell_line_y+=FONT_STR_HEIGHT;
if (shell_line_y >= LCD_HEIGHT - FONT_STR_HEIGHT*4) shell_line_y=0;
}
#define DEBUG_LOG(offs, text) my_debug_log(offs, text);
#else
#define DEBUG_LOG(offs, text)
#endif
#ifdef __USE_SMOOTH__
static float arifmetic_mean(float v0, float v1, float v2){
return (v0+2*v1+v2)/4;
}
static float geometry_mean(float v0, float v1, float v2){
float v = vna_cbrtf(vna_fabsf(v0*v1*v2));
if (v0+v1+v2 < 0) v = -v;
return v;
}
uint8_t smooth_factor = 0;
void set_smooth_factor(uint8_t factor){
if (factor > 8) factor = 8;
smooth_factor = factor;
request_to_redraw(REDRAW_CAL_STATUS);
}
uint8_t get_smooth_factor(void) {
return smooth_factor;
}
// Allow smooth complex data point array (this remove noise, smooth power depend form count)
// see https://terpconnect.umd.edu/~toh/spectrum/Smoothing.html
static void measurementDataSmooth(uint16_t ch_mask){
int j;
// ch_mask = 2;
// memcpy(measured[0], measured[1], sizeof(measured[0]));
float (*smooth_func)(float v0, float v1, float v2) = VNA_MODE(VNA_MODE_SMOOTH) ? arifmetic_mean : geometry_mean;
for (int ch = 0; ch < 2; ch++,ch_mask>>=1) {
if ((ch_mask&1)==0) continue;
int count = 1<<(smooth_factor-1), n;
float *data = measured[ch][0];
for (n = 0; n < count; n++){
float prev_re = data[2*0 ];
float prev_im = data[2*0+1];
// first point smooth (use first and second points), disabled it made phase shift
// data[0] = smooth_func(prev_re, prev_re, data[2 ]);
// data[1] = smooth_func(prev_im, prev_im, data[2+1]);
// simple data smooth on 3 points
for (j = 1; j < sweep_points - 1; j++){
float old_re = data[2*j ]; // save current data point for next point smooth
float old_im = data[2*j+1];
data[2*j ] = smooth_func(prev_re, data[2*j ], data[2*j+2]);
data[2*j+1] = smooth_func(prev_im, data[2*j+1], data[2*j+3]);
prev_re = old_re;
prev_im = old_im;
}
// last point smooth, disabled it made phase shift
// data[2*j ] = smooth_func(data[2*j ], data[2*j ], prev_re);
// data[2*j+1] = smooth_func(data[2*j+1], data[2*j+1], prev_im);
}
}
}
#endif
static THD_WORKING_AREA(waThread1, 1024);
static THD_FUNCTION(Thread1, arg)
{
(void)arg;
chRegSetThreadName("sweep");
#ifdef __FLIP_DISPLAY__
if(VNA_MODE(VNA_MODE_FLIP_DISPLAY))
lcd_set_flip(true);
#endif
/*
* UI (menu, touch, buttons) and plot initialize
*/
ui_init();
//Initialize graph plotting
plot_init();
while (1) {
bool completed = false;
uint16_t mask = get_sweep_mask();
if (sweep_mode&(SWEEP_ENABLE|SWEEP_ONCE)) {
completed = sweep(true, mask);
sweep_mode&=~SWEEP_ONCE;
} else {
__WFI();
}
// Run Shell command in sweep thread
while (shell_function) {
shell_function(shell_nargs - 1, &shell_args[1]);
shell_function = 0;
osalThreadDequeueNextI(&shell_thread, MSG_OK);
}
// Process UI inputs
sweep_mode|= SWEEP_UI_MODE;
ui_process();
sweep_mode&=~SWEEP_UI_MODE;
// Process collected data, calculate trace coordinates and plot only if scan completed
if (completed) {
#ifdef __USE_SMOOTH__
// START_PROFILE;
if (smooth_factor)
measurementDataSmooth(mask);
// STOP_PROFILE;
#endif
// START_PROFILE
if ((props_mode & DOMAIN_MODE) == DOMAIN_TIME) transform_domain(mask);
// STOP_PROFILE;
// Prepare draw graphics, cache all lines, mark screen cells for redraw
request_to_redraw(REDRAW_PLOT);
}
request_to_redraw(REDRAW_BATTERY);
#ifndef DEBUG_CONSOLE_SHOW
// plot trace and other indications as raster
draw_all();
#endif
}
}
void
pause_sweep(void)
{
sweep_mode &= ~SWEEP_ENABLE;
}
static inline void
resume_sweep(void)
{
sweep_mode |= SWEEP_ENABLE;
}
void
toggle_sweep(void)
{
sweep_mode ^= SWEEP_ENABLE;
}
//
// Optimized Kaiser window functions for transform domain
//
// Zero-order modified Bessel function
// (x/2)^(2n)
// Bessel I0 = 1 + ---------- => For bessel_I0_ext(z) set input as z = (x/2)^2 (input range 0 .. beta*beta/4)
// (n!)^2
//
// z^n z z^2 z^3 z^4 z^5 z^n
// 1 + ------ = 1 + --- + --- + --- + --- + ----- ...... + ------
// (n!)^2 1 4 36 576 14400 (n!)^2
float bessel_I0_ext(float z) {
// Set calculated elements count, more size - less error but longer (bigger beta also need more size for less error)
// Use BESSEL_SIZE = 12 (last used n = 12), use constant size faster then check every time limits in float
// For beta = 6 and BESSEL_SIZE = 12 max error 4.2e-7
// For beta = 13 and BESSEL_SIZE = 12 max error 2.5e-4
#define BESSEL_SIZE 12
int i = BESSEL_SIZE - 1;
// Precalculated multipliers: 1 / (n!^2)
static const float besseli0_k[BESSEL_SIZE - 1] = {
// 1.0000000000000000000000000000000e+00, // 1 / ( 1!^2)
2.5000000000000000000000000000000e-01, // 1 / ( 2!^2)
2.7777777777777777777777777777778e-02, // 1 / ( 3!^2)
1.7361111111111111111111111111111e-03, // 1 / ( 4!^2)
6.9444444444444444444444444444444e-05, // 1 / ( 5!^2)
1.9290123456790123456790123456790e-06, // 1 / ( 6!^2)
3.9367598891408415217939027462837e-08, // 1 / ( 7!^2)
6.1511873267825648778029730410683e-10, // 1 / ( 8!^2)
7.5940584281266233059295963469979e-12, // 1 / ( 9!^2)
7.5940584281266233059295963469979e-14, // 1 / (10!^2)
6.2760813455591928148178482206594e-16, // 1 / (11!^2)
4.3583898233049950102901723754579e-18, // 1 / (12!^2)
// 2.5789288895295828463255457842946e-20, // 1 / (13!^2)
// 1.3157800456783585950640539715789e-22, // 1 / (14!^2)
// 5.8479113141260382002846843181284e-25, // 1 / (15!^2)
// 2.2843403570804836719862048117689e-27, // 1 / (16!^2)
// 7.9042918930120542283259682068128e-30, // 1 / (17!^2)
};
float term = z, ret = 1.0f + z;
do {ret += (term*= z) * besseli0_k[BESSEL_SIZE - 1 - i];} while(--i);
return ret;
}
// Kaiser window
// bessel_I0(beta*sqrt(1 - (2*k/N - 1)^2))
// Kaiser = -------------------------------------
// bessel_I0(beta)
// Move out constant divider: bessel_I0(beta) = bessel_I0_ext(beta * beta / 4)
// Made calculation optimization (in integer)
// x = (2*k)/(n-1) - 1 = (set n=n-1) = 2*k/n - 1 = (2*k-n)/n
// calculate kaiser window vs bessel_I0(w) there:
// n*n - (2*k-n)*(2*k-n) 4*k*(n-k)
// w = beta*sqrt(1 - x*x) = beta * sqrt(---------------------) = beta * sqrt(---------)
// n*n n*n
// bessel_I0(w) = bessel_I0_ext(z) (there z = (w*w)/4 for speed)
// w^2 k*(n-k)
// z = --- = beta * beta * (-------)
// 4 n*n
// return = bessel_I0_ext(z)
static float kaiser_window_ext(uint32_t k, uint32_t n, uint16_t beta) {
if (beta == 0) return 1.0f;
n = n - 1;
k = k * (n - k) * beta * beta;
n = n * n;
return bessel_I0_ext((float)k / n);
}
static void
transform_domain(uint16_t ch_mask)
{
// use spi_buffer as temporary buffer and calculate ifft for time domain
// Need 2 * sizeof(float) * FFT_SIZE bytes for work
#if 2*4*FFT_SIZE > (SPI_BUFFER_SIZE * LCD_PIXEL_SIZE)
#error "Need increase spi_buffer or use less FFT_SIZE value"
#endif
int i;
uint16_t offset = 0;
uint8_t is_lowpass = FALSE;
switch (domain_func) {
// case TD_FUNC_BANDPASS:
// break;
case TD_FUNC_LOWPASS_IMPULSE:
case TD_FUNC_LOWPASS_STEP:
is_lowpass = TRUE;
offset = sweep_points;
break;
}
uint16_t window_size = sweep_points + offset;
uint16_t beta = 0;
switch (domain_window) {
// case TD_WINDOW_MINIMUM:
// beta = 0; // this is rectangular
// break;
case TD_WINDOW_NORMAL:
beta = 6;
break;
case TD_WINDOW_MAXIMUM:
beta = 13;
break;
}
// Add amplitude correction for not full size FFT data and also add computed default scale
// recalculate the scale factor if any window details are changed. The scale factor is to compensate for windowing.
// Add constant multiplier for kaiser_window_ext use 1.0f / bessel0_ext(beta*beta/4.0f)
// Add constant multiplier 1.0f / FFT_SIZE
static float window_scale = 0.0f;
static uint16_t td_cache = 0;
// Check mode cache data
uint16_t td_check = (props_mode & (TD_WINDOW|TD_FUNC))|(sweep_points<<5);
if (td_cache!=td_check){
td_cache = td_check;
if (domain_func == TD_FUNC_LOWPASS_STEP)
window_scale = FFT_SIZE * bessel_I0_ext(beta*beta/4.0f);
else {
window_scale = 0.0f;
for (int i = 0; i < sweep_points; i++)
window_scale += kaiser_window_ext(i + offset, window_size, beta);
if (domain_func == TD_FUNC_LOWPASS_IMPULSE) window_scale*= 2.0f;
// window_scale/= FFT_SIZE // add correction from kaiser_window summ
// window_scale*= FFT_SIZE // add default from FFT_SIZE
// window_scale/= bessel_I0_ext(beta*beta/4.0f) // for get result as kaiser_window summ
// window_scale*= bessel_I0_ext(beta*beta/4.0f) // for set correction on calculated kaiser_window for value
}
window_scale = 1.0f / window_scale;
#ifdef USE_FFT_WINDOW_BUFFER
// Cache window function data to static buffer
static float kaiser_data[FFT_SIZE];
for (i = 0; i < sweep_points; i++)
kaiser_data[i] = kaiser_window_ext(i + offset, window_size, beta) * window_scale;
#endif
}
// Made Time Domain Calculations
for (int ch = 0; ch < 2; ch++,ch_mask>>=1) {
if ((ch_mask&1)==0) continue;
// Prepare data in tmp buffer (use spi_buffer), apply window function and constant correction factor
float* tmp = (float*)spi_buffer;
float *data = measured[ch][0];
for (i = 0; i < sweep_points; i++) {
#ifdef USE_FFT_WINDOW_BUFFER
float w = kaiser_data[i];
#else
float w = kaiser_window_ext(i + offset, window_size, beta) * window_scale;
#endif
tmp[i * 2 + 0] = data[i * 2 + 0] * w;
tmp[i * 2 + 1] = data[i * 2 + 1] * w;
}
// Fill zeroes last
for (; i < FFT_SIZE; i++) {
tmp[i * 2 + 0] = 0.0f;
tmp[i * 2 + 1] = 0.0f;
}
// For lowpass mode swap
if (is_lowpass) {
for (i = 1; i < sweep_points; i++) {
tmp[(FFT_SIZE - i) * 2 + 0] = tmp[i * 2 + 0];
tmp[(FFT_SIZE - i) * 2 + 1] = -tmp[i * 2 + 1];
}
}
// Made iFFT in temp buffer
fft_inverse((float(*)[2])tmp);
// set img part as zero
if (is_lowpass){
for (i = 0; i < sweep_points; i++)
tmp[i*2+1] = 0.0f;
}
if (domain_func == TD_FUNC_LOWPASS_STEP) {
for (i = 1; i < sweep_points; i++)
tmp[i*2+0]+= tmp[i*2+0-2];
}
// Copy data back
memcpy(measured[ch], tmp, sizeof(measured[0]));
}
}
// Shell commands output
int shell_printf(const char *fmt, ...)
{
if (shell_stream == NULL) return 0;
va_list ap;
int formatted_bytes;
va_start(ap, fmt);
formatted_bytes = chvprintf(shell_stream, fmt, ap);
va_end(ap);
return formatted_bytes;
}
static void shell_write(const void *buf, uint32_t size) {streamWrite(shell_stream, buf, size);}
static int shell_read(void *buf, uint32_t size) {return streamRead(shell_stream, buf, size);}
//static void shell_put(uint8_t c) {streamPut(shell_stream, c);}
//static uint8_t shell_getc(void) {return streamGet(shell_stream);}
#ifdef __USE_SERIAL_CONSOLE__
// Serial Shell commands output
int serial_shell_printf(const char *fmt, ...)
{
va_list ap;
int formatted_bytes;
va_start(ap, fmt);
formatted_bytes = chvprintf((BaseSequentialStream *)&SD1, fmt, ap);
va_end(ap);
return formatted_bytes;
}
#endif
//
// Function used for search substring v in list
// Example need search parameter "center" in "start|stop|center|span|cw" getStringIndex return 2
// If not found return -1
// Used for easy parse command arguments
static int get_str_index(const char *v, const char *list)
{
int i = 0;
while (1) {
const char *p = v;
while (1) {
char c = *list;
if (c == '|') c = 0;
if (c == *p++) {
// Found, return index
if (c == 0) return i;
list++; // Compare next symbol
continue;
}
break; // Not equal, break
}
// Set new substring ptr
while (1) {
// End of string, not found
if (*list == 0) return -1;
if (*list++ == '|') break;
}
i++;
}
return -1;
}
VNA_SHELL_FUNCTION(cmd_pause)
{
(void)argc;
(void)argv;
pause_sweep();
}
VNA_SHELL_FUNCTION(cmd_resume)
{
(void)argc;
(void)argv;
// restore frequencies array and cal
update_frequencies();
resume_sweep();
}
VNA_SHELL_FUNCTION(cmd_reset)
{
(void)argc;
(void)argv;
#ifdef __DFU_SOFTWARE_MODE__
if (argc == 1) {
if (get_str_index(argv[0], "dfu") == 0) {
shell_printf("Performing reset to DFU mode" VNA_SHELL_NEWLINE_STR);
enter_dfu();
return;
}
}
#endif
shell_printf("Performing reset" VNA_SHELL_NEWLINE_STR);
NVIC_SystemReset();
}
// Use macro, std isdigit more big
#define _isdigit(c) (c >= '0' && c <= '9')
// Rewrite universal standart str to value functions to more compact
//
// Convert string to int32
int32_t my_atoi(const char *p)
{
int32_t value = 0;
uint32_t c;
bool neg = false;
if (*p == '-') {neg = true; p++;}
if (*p == '+') p++;
while ((c = *p++ - '0') < 10)
value = value * 10 + c;
return neg ? -value : value;
}
// Convert string to uint32
// 0x - for hex radix
// 0o - for oct radix
// 0b - for bin radix
// default dec radix
uint32_t my_atoui(const char *p)
{
uint32_t value = 0, radix = 10, c;
if (*p == '+') p++;
if (*p == '0') {
switch (p[1]) {
case 'x': radix = 16; break;
case 'o': radix = 8; break;
case 'b': radix = 2; break;
default: goto calculate;
}
p+=2;
}
calculate:
while (1) {
c = *p++ - '0';
// c = to_upper(*p) - 'A' + 10
if (c >= 'A' - '0') c = (c&(~0x20)) - ('A' - '0') + 10;
if (c >= radix) return value;
value = value * radix + c;
}
}
float
my_atof(const char *p)
{
int neg = FALSE;
if (*p == '-')
neg = TRUE;
if (*p == '-' || *p == '+')
p++;
float x = my_atoi(p);
while (_isdigit((int)*p))
p++;
if (*p == '.' || *p == ',') {
float d = 1.0f;
p++;
while (_isdigit((int)*p)) {
d *= 1e-1f;
x += d * (*p - '0');
p++;
}
}
if (*p) {
int exp = 0;
if (*p == 'e' || *p == 'E') exp = my_atoi(&p[1]);
else if (*p == 'G') exp = 9; // Giga
else if (*p == 'M') exp = 6; // Mega
else if (*p == 'k') exp = 3; // kilo
else if (*p == 'm') exp = -3; // milli
else if (*p == 'u') exp = -6; // micro
else if (*p == 'n') exp = -9; // nano
else if (*p == 'p') exp =-12; // pico
if (exp > 0) do {x*= 1e+1f;} while (--exp);
if (exp < 0) do {x*= 1e-1f;} while (++exp);
}
return neg ? -x : x;
}
#ifdef __USE_SMOOTH__
VNA_SHELL_FUNCTION(cmd_smooth)
{
if (argc != 1) {
shell_printf("usage: %s" VNA_SHELL_NEWLINE_STR \
"current: %u" VNA_SHELL_NEWLINE_STR, "smooth {0-8}", smooth_factor);
return;
}
set_smooth_factor(my_atoui(argv[0]));
}
#endif
#ifdef ENABLE_CONFIG_COMMAND
VNA_SHELL_FUNCTION(cmd_config) {
static const char cmd_mode_list[] =
"auto"
#ifdef __USE_SMOOTH__
"|avg"
#endif
#ifdef __USE_SERIAL_CONSOLE__
"|connection"
#endif
"|mode"
"|grid"
"|dot"
#ifdef __USE_BACKUP__
"|bk"
#endif
#ifdef __FLIP_DISPLAY__
"|flip"
#endif
#ifdef __DIGIT_SEPARATOR__
"|separator"
#endif
#ifdef __SD_CARD_DUMP_TIFF__
"|tif"
#endif
;
int idx;
if (argc == 2 && (idx = get_str_index(argv[0], cmd_mode_list)) >= 0) {
apply_VNA_mode(idx, my_atoui(argv[1]));
}
else
shell_printf("usage: config {%s} [0|1]" VNA_SHELL_NEWLINE_STR, cmd_mode_list);
}
#endif
#ifdef __VNA_MEASURE_MODULE__
VNA_SHELL_FUNCTION(cmd_measure) {
static const char cmd_measure_list[] =
"none"
#ifdef __USE_LC_MATCHING__
"|lc" // Add LC match function
#endif
#ifdef __S21_MEASURE__
"|lcshunt" // Enable LC shunt measure option
"|lcseries" // Enable LC series measure option
"|xtal" // Enable XTAL measure option
#endif
#ifdef __S11_CABLE_MEASURE__
"|cable" // Enable S11 cable measure option
#endif
#ifdef __S11_RESONANCE_MEASURE__
"|resonance" // Enable S11 resonance search option
#endif
;
int idx;
if (argc == 1 && (idx = get_str_index(argv[0], cmd_measure_list)) >= 0)
plot_set_measure_mode(idx);
else
shell_printf("usage: measure {%s}" VNA_SHELL_NEWLINE_STR, cmd_measure_list);
}
#endif
#ifdef USE_VARIABLE_OFFSET
VNA_SHELL_FUNCTION(cmd_offset)
{
if (argc != 1) {
shell_printf("usage: %s" VNA_SHELL_NEWLINE_STR \
"current: %u" VNA_SHELL_NEWLINE_STR, "offset {frequency offset(Hz)}", IF_OFFSET);
return;
}
si5351_set_frequency_offset(my_atoi(argv[0]));
}
#endif
VNA_SHELL_FUNCTION(cmd_freq)
{
if (argc != 1) {
shell_printf("usage: freq {frequency(Hz)}" VNA_SHELL_NEWLINE_STR);
return;
}
uint32_t freq = my_atoui(argv[0]);
pause_sweep();
set_frequency(freq);
return;
}
void set_power(uint8_t value){
request_to_redraw(REDRAW_CAL_STATUS);
if (value > SI5351_CLK_DRIVE_STRENGTH_8MA) value = SI5351_CLK_DRIVE_STRENGTH_AUTO;
if (current_props._power == value) return;
current_props._power = value;
// Update power if pause, need for generation in CW mode
if (!(sweep_mode&SWEEP_ENABLE)) si5351_set_power(value);
}
VNA_SHELL_FUNCTION(cmd_power)
{
if (argc != 1) {
shell_printf("usage: power {0-3}|{255 - auto}" VNA_SHELL_NEWLINE_STR \
"power: %d" VNA_SHELL_NEWLINE_STR, current_props._power);
return;
}
set_power(my_atoi(argv[0]));
}
#ifdef __USE_RTC__
VNA_SHELL_FUNCTION(cmd_time)
{
(void)argc;
(void)argv;
uint32_t dt_buf[2];
dt_buf[0] = rtc_get_tr_bcd(); // TR should be read first for sync
dt_buf[1] = rtc_get_dr_bcd(); // DR should be read second
static const uint8_t idx_to_time[] = {6,5,4,2, 1, 0};
static const char time_cmd[] = "y|m|d|h|min|sec";
// 0 1 2 4 5 6
// time[] ={sec, min, hr, 0, day, month, year, 0}
uint8_t *time = (uint8_t*)dt_buf;
if (argc == 3 && get_str_index(argv[0], "b") == 0){
rtc_set_time(my_atoui(argv[1]), my_atoui(argv[2]));
return;
}
if (argc!=2) goto usage;
int idx = get_str_index(argv[0], time_cmd);
uint32_t val = my_atoui(argv[1]);
if (idx < 0 || val > 99)
goto usage;
// Write byte value in struct
time[idx_to_time[idx]] = ((val/10)<<4)|(val%10); // value in bcd format
rtc_set_time(dt_buf[1], dt_buf[0]);
return;
usage:
shell_printf("20%02x/%02x/%02x %02x:%02x:%02x" VNA_SHELL_NEWLINE_STR \
"usage: time {[%s] 0-99} or {b 0xYYMMDD 0xHHMMSS}" VNA_SHELL_NEWLINE_STR,
time[6], time[5], time[4], time[2], time[1], time[0], time_cmd);
}
#endif
#ifdef __VNA_ENABLE_DAC__
VNA_SHELL_FUNCTION(cmd_dac)
{
if (argc != 1) {
shell_printf("usage: %s" VNA_SHELL_NEWLINE_STR \
"current: %u" VNA_SHELL_NEWLINE_STR, "dac {value(0-4095)}", config._dac_value);
return;
}
dac_setvalue_ch2(my_atoui(argv[0])&0xFFF);
}
#endif
VNA_SHELL_FUNCTION(cmd_threshold)
{
uint32_t value;
if (argc != 1) {
shell_printf("usage: %s" VNA_SHELL_NEWLINE_STR \
"current: %u" VNA_SHELL_NEWLINE_STR, "threshold {frequency in harmonic mode}", config._harmonic_freq_threshold);
return;
}
value = my_atoui(argv[0]);
config._harmonic_freq_threshold = value;
}
VNA_SHELL_FUNCTION(cmd_saveconfig)
{
(void)argc;
(void)argv;
config_save();
shell_printf("Config saved" VNA_SHELL_NEWLINE_STR);
}
VNA_SHELL_FUNCTION(cmd_clearconfig)
{
if (argc != 1) {
shell_printf("usage: clearconfig {protection key}" VNA_SHELL_NEWLINE_STR);
return;
}
if (get_str_index(argv[0], "1234") != 0) {
shell_printf("Key unmatched." VNA_SHELL_NEWLINE_STR);
return;
}
clear_all_config_prop_data();
shell_printf("Config and all cal data cleared." VNA_SHELL_NEWLINE_STR \
"Do reset manually to take effect. Then do touch cal and save." VNA_SHELL_NEWLINE_STR);
}
VNA_SHELL_FUNCTION(cmd_data)
{
int i;
int sel = 0;
float (*array)[2];
if (argc == 1)
sel = my_atoi(argv[0]);
if (sel < 0 || sel >=7)
goto usage;
array = sel < 2 ? measured[sel] : cal_data[sel-2];
for (i = 0; i < sweep_points; i++)
shell_printf("%f %f" VNA_SHELL_NEWLINE_STR, array[i][0], array[i][1]);
return;
usage:
shell_printf("usage: data [array]" VNA_SHELL_NEWLINE_STR);
}
VNA_SHELL_FUNCTION(cmd_capture)
{
// read pixel count at one time (PART*2 bytes required for read buffer)
(void)argc;
(void)argv;
int y;
// Check buffer limits, if less possible reduce rows count
#define READ_ROWS 2
#if (SPI_BUFFER_SIZE*LCD_PIXEL_SIZE) < (LCD_RX_PIXEL_SIZE*LCD_WIDTH*READ_ROWS)
#error "Low size of spi_buffer for cmd_capture"
#endif
// Text on screenshot
if (argc > 0) {
lcd_set_colors(LCD_FG_COLOR, LCD_BG_COLOR);
for (int i = 0; i < argc; i++)
lcd_printf(OFFSETX + CELLOFFSETX + 2, AREA_HEIGHT_NORMAL - (argc - i) * FONT_STR_HEIGHT - 2, argv[i]);
request_to_redraw(REDRAW_AREA);
}
// read 2 row pixel time
for (y = 0; y < LCD_HEIGHT; y += READ_ROWS) {
// use uint16_t spi_buffer[2048] (defined in ili9341) for read buffer
lcd_read_memory(0, y, LCD_WIDTH, READ_ROWS, (uint16_t *)spi_buffer);
shell_write(spi_buffer, READ_ROWS * LCD_WIDTH * sizeof(uint16_t));
}
}
#if 0
VNA_SHELL_FUNCTION(cmd_gamma)
{
float gamma[2];
(void)argc;
(void)argv;
pause_sweep();
chMtxLock(&mutex);
wait_dsp(4);
calculate_gamma(gamma);
chMtxUnlock(&mutex);
shell_printf("%d %d" VNA_SHELL_NEWLINE_STR, gamma[0], gamma[1]);
}
#endif
static void (*sample_func)(float *gamma) = calculate_gamma;
#ifdef ENABLE_SAMPLE_COMMAND
VNA_SHELL_FUNCTION(cmd_sample)
{
if (argc != 1) goto usage;
// 0 1 2
static const char cmd_sample_list[] = "gamma|ampl|ref";
switch (get_str_index(argv[0], cmd_sample_list)) {
case 0:
sample_func = calculate_gamma;
return;
case 1:
sample_func = fetch_amplitude;
return;
case 2:
sample_func = fetch_amplitude_ref;
return;
default:
break;
}
usage:
shell_printf("usage: sample {%s}" VNA_SHELL_NEWLINE_STR, cmd_sample_list);
}
#endif
config_t config = {
.magic = CONFIG_MAGIC,
._harmonic_freq_threshold = FREQUENCY_THRESHOLD,
._IF_freq = FREQUENCY_OFFSET,
._touch_cal = DEFAULT_TOUCH_CONFIG,
._vna_mode = 0, // USB mode, search max
._brightness = DEFAULT_BRIGHTNESS,
._dac_value = 1922,
._vbat_offset = 450,
._bandwidth = BANDWIDTH_1000,
._lcd_palette = LCD_DEFAULT_PALETTE,
._serial_speed = SERIAL_DEFAULT_BITRATE,
._xtal_freq = XTALFREQ,
._measure_r = MEASURE_DEFAULT_R,
._lever_mode = LM_MARKER,
#ifdef __MS5351__
._band_mode = 1,
#else
._band_mode = 0,
#endif
};
properties_t current_props;
// NanoVNA Default settings
static const trace_t def_trace[TRACES_MAX] = {//enable, type, channel, smith format, scale, refpos
{ TRUE, TRC_LOGMAG, 0, MS_RX, 10.0, NGRIDY-1 },
{ TRUE, TRC_LOGMAG, 1, MS_REIM, 10.0, NGRIDY-1 },
{ TRUE, TRC_SMITH, 0, MS_RX, 1.0, 0 },
{ TRUE, TRC_PHASE, 1, MS_REIM, 90.0, NGRIDY/2 }
};
static const marker_t def_markers[MARKERS_MAX] = {
{ TRUE, 0, 20*POINTS_COUNT_DEFAULT/100-1, 0 },
#if MARKERS_MAX > 1
{FALSE, 0, 30*POINTS_COUNT_DEFAULT/100-1, 0 },
#endif
#if MARKERS_MAX > 2
{FALSE, 0, 40*POINTS_COUNT_DEFAULT/100-1, 0 },
#endif
#if MARKERS_MAX > 3
{FALSE, 0, 50*POINTS_COUNT_DEFAULT/100-1, 0 },
#endif
#if MARKERS_MAX > 4
{FALSE, 0, 60*POINTS_COUNT_DEFAULT/100-1, 0 },
#endif
#if MARKERS_MAX > 5
{FALSE, 0, 70*POINTS_COUNT_DEFAULT/100-1, 0 },
#endif
#if MARKERS_MAX > 6
{FALSE, 0, 80*POINTS_COUNT_DEFAULT/100-1, 0 },
#endif
#if MARKERS_MAX > 7
{FALSE, 0,90*POINTS_COUNT_DEFAULT/100-1, 0 },
#endif
};
// Load propeties default settings
static void load_default_properties(void) {
//Magic add on caldata_save
current_props.magic = PROPERTIES_MAGIC;
current_props._frequency0 = 50000; // start = 50kHz
current_props._frequency1 = 900000000; // end = 900MHz
current_props._var_freq = 0;
current_props._sweep_points = POINTS_COUNT_DEFAULT; // Set default points count
current_props._cal_frequency0 = 50000; // calibration start = 50kHz
current_props._cal_frequency1 = 900000000; // calibration end = 900MHz
current_props._cal_sweep_points = POINTS_COUNT_DEFAULT; // Set calibration default points count