From 675d45644e73eacc70067c185a6ee56cb0ad02b3 Mon Sep 17 00:00:00 2001 From: Christian Ruiz Date: Sat, 14 Sep 2024 22:01:56 +0200 Subject: [PATCH] data_conversions preparation --- .gitignore | 1 + SpectrumScan.py | 131 +++++++++++++++++++++++++++++++----------------- platformio.ini | 20 ++++---- src/main.cpp | 31 +++++++++--- 4 files changed, 120 insertions(+), 63 deletions(-) diff --git a/.gitignore b/.gitignore index 89cc49c..3da96e1 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ .vscode/c_cpp_properties.json .vscode/launch.json .vscode/ipch +out/* diff --git a/SpectrumScan.py b/SpectrumScan.py index acc37a0..f1a6b1f 100644 --- a/SpectrumScan.py +++ b/SpectrumScan.py @@ -12,25 +12,36 @@ from datetime import datetime from argparse import RawTextHelpFormatter # number of samples in each scanline -SCAN_WIDTH = 33 +SCAN_WIDTH = 20 +SCAN_MIN_FREQ = "FREQ 850" # scanline Serial start/end markers -SCAN_MARK_START = 'SCAN ' -SCAN_MARK_FREQ = 'FREQ ' -SCAN_MARK_END = ' END' +SCAN_MARK_START = "SCAN " +SCAN_MARK_FREQ = "FREQ " +SCAN_MARK_END = " END" # output path -OUT_PATH = 'out' +OUT_PATH = "out" # default settings DEFAULT_BAUDRATE = 115200 -DEFAULT_COLOR_MAP = 'viridis' +DEFAULT_COLOR_MAP = "viridis" DEFAULT_SCAN_LEN = 200 DEFAULT_RSSI_OFFSET = -11 + # Print iterations progress # from https://stackoverflow.com/questions/3173320/text-progress-bar-in-terminal-with-block-characters -def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 50, fill = '█', printEnd = "\r"): +def printProgressBar( + iteration, + total, + prefix="", + suffix="", + decimals=1, + length=50, + fill="█", + printEnd="\r", +): """ Call in a loop to create terminal progress bar @params: @@ -45,14 +56,16 @@ def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, """ percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) filledLength = int(length * iteration // total) - bar = fill * filledLength + '-' * (length - filledLength) - print(f'\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd) - if iteration == total: + bar = fill * filledLength + "-" * (length - filledLength) + print(f"\r{prefix} |{bar}| {percent}% {suffix}", end=printEnd) + if iteration == total: print() def main(): - parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter, description=''' + parser = argparse.ArgumentParser( + formatter_class=RawTextHelpFormatter, + description=""" RadioLib SX126x_Spectrum_Scan plotter script. Displays output from SX126x_Spectrum_Scan example as grayscale and @@ -63,35 +76,41 @@ def main(): 1. Upload the SX126x_Spectrum_Scan example to your Arduino board with SX1262 connected. 2. Run the script with appropriate arguments. 3. Once the scan is complete, output files will be saved to out/ - ''') - parser.add_argument('port', - type=str, - help='COM port to connect to the device') - parser.add_argument('--speed', + """, + ) + parser.add_argument("port", type=str, help="COM port to connect to the device") + parser.add_argument( + "--speed", default=DEFAULT_BAUDRATE, type=int, - help=f'COM port baudrate (defaults to {DEFAULT_BAUDRATE})') - parser.add_argument('--map', + help=f"COM port baudrate (defaults to {DEFAULT_BAUDRATE})", + ) + parser.add_argument( + "--map", default=DEFAULT_COLOR_MAP, type=str, - help=f'Matplotlib color map to use for the output (defaults to "{DEFAULT_COLOR_MAP}")') - parser.add_argument('--len', + help=f'Matplotlib color map to use for the output (defaults to "{DEFAULT_COLOR_MAP}")', + ) + parser.add_argument( + "--len", default=DEFAULT_SCAN_LEN, type=int, - help=f'Number of scanlines to record (defaults to {DEFAULT_SCAN_LEN})') - parser.add_argument('--offset', + help=f"Number of scanlines to record (defaults to {DEFAULT_SCAN_LEN})", + ) + parser.add_argument( + "--offset", default=DEFAULT_RSSI_OFFSET, type=int, - help=f'Default RSSI offset in dBm (defaults to {DEFAULT_RSSI_OFFSET})') - parser.add_argument('--freq', - default=-1, - type=float, - help=f'Default starting frequency in MHz') + help=f"Default RSSI offset in dBm (defaults to {DEFAULT_RSSI_OFFSET})", + ) + parser.add_argument( + "--freq", default=-1, type=float, help=f"Default starting frequency in MHz" + ) args = parser.parse_args() freq_mode = False scan_len = args.len - if (args.freq != -1): + if args.freq != -1: freq_mode = True scan_len = 1000 @@ -103,74 +122,92 @@ def main(): # list of frequencies in frequency mode freq_list = [] + + start=False # open the COM port with serial.Serial(args.port, args.speed, timeout=None) as com: - while(True): + while True: + # read a single line + try: + line = com.readline().decode("utf-8") + #print(line) + except: + continue + + if start: + if SCAN_MIN_FREQ not in line: + continue + else: + start=False # update the progress bar if not freq_mode: printProgressBar(row, scan_len) - # read a single line - try: - line = com.readline().decode('utf-8') - except: - continue + if SCAN_MARK_FREQ in line: - new_freq = float(line.split(' ')[1]) + new_freq = float(line.split(" ")[1]) if (len(freq_list) > 1) and (new_freq < freq_list[-1]): break freq_list.append(new_freq) - print('{:.3f}'.format(new_freq), end = '\r') + print("{:.3f}".format(new_freq), end="\r") continue # check the markers if (SCAN_MARK_START in line) and (SCAN_MARK_END in line): # get the values - scanline = line[len(SCAN_MARK_START):-len(SCAN_MARK_END)].split(',') + scanline = line[len(SCAN_MARK_START) : -len(SCAN_MARK_END)].split(",") for col in range(SCAN_WIDTH): arr[col][row] = int(scanline[col]) - + # increment the row counter row = row + 1 # check if we're done if (not freq_mode) and (row >= scan_len): break - + # scale to the number of scans (sum of any given scanline) num_samples = arr.sum(axis=0)[0] - arr *= (num_samples/arr.max()) + print("NUM SAMPLES:",num_samples) + print("ARR.MAX:",arr.max()) + print("ARR.SHAPE:",arr.shape) + print("LEN_FREQS:",len(freq_list)) + arr *= num_samples / arr.max() if freq_mode: scan_len = len(freq_list) # create the figure fig, ax = plt.subplots() + + #print(arr) + print(freq_list) # display the result as heatmap - extent = [0, scan_len, -4*(SCAN_WIDTH + 1), args.offset] + extent = [0, scan_len, -4 * (SCAN_WIDTH + 1), args.offset] if freq_mode: extent[0] = freq_list[0] extent[1] = freq_list[-1] - im = ax.imshow(arr[:,:scan_len], cmap=args.map, extent=extent) + im = ax.imshow(arr[:, :scan_len], cmap=args.map, extent=extent) fig.colorbar(im) - # set some properites and show - timestamp = datetime.now().strftime('%y-%m-%d %H-%M-%S') - title = f'RadioLib SX126x Spectral Scan {timestamp}' + # set some properites and show + timestamp = datetime.now().strftime("%y-%m-%d %H-%M-%S") + title = f"RadioLib SX126x Spectral Scan {timestamp}" if freq_mode: plt.xlabel("Frequency [Hz]") else: plt.xlabel("Time [sample]") plt.ylabel("RSSI [dBm]") - ax.set_aspect('auto') + ax.set_aspect("auto") fig.suptitle(title) fig.canvas.manager.set_window_title(title) plt.savefig(f'{OUT_PATH}/{title.replace(" ", "_")}.png', dpi=300) plt.show() + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/platformio.ini b/platformio.ini index 0b7648d..02135e9 100644 --- a/platformio.ini +++ b/platformio.ini @@ -9,12 +9,6 @@ ; https://docs.platformio.org/page/projectconf.html [platformio] -; for env:vision-master-e190 -; src_dir = tft_src -; for env:vision-master-e290 -; src_dir = eink_src -; for env:heltec_wifi_lora_32_V3 -; src_dir = src ;;Default [env:heltec_wifi_lora_32_V3] platform = espressif32 @@ -26,6 +20,8 @@ board_build.f_cpu = 240000000 lib_deps = ropg/Heltec_ESP32_LoRa_v3@^0.9.1 adafruit/Adafruit ST7735 and ST7789 Library@^1.10.4 + adafruit/Adafruit GFX Library@^1.11.10 + adafruit/Adafruit BusIO@^1.16.1 build_flags = -DHELTEC_POWER_BUTTON [env:lilygo-T3S3-v1-2] @@ -39,6 +35,8 @@ lib_deps = ropg/Heltec_ESP32_LoRa_v3@^0.9.1 RadioLib adafruit/Adafruit ST7735 and ST7789 Library@^1.10.4 + adafruit/Adafruit GFX Library@^1.11.10 + adafruit/Adafruit BusIO@^1.16.1 build_flags = -DLILYGO -DT3_S3_V1_2_SX1262 @@ -62,6 +60,8 @@ board_build.flash_size = 80000000L lib_deps = ropg/Heltec_ESP32_LoRa_v3@^0.9.1 adafruit/Adafruit ST7735 and ST7789 Library@^1.10.4 + adafruit/Adafruit GFX Library@^1.11.10 + adafruit/Adafruit BusIO@^1.16.1 build_flags = -DLILYGO [env:vision-master-e290] @@ -91,11 +91,11 @@ build_flags = lib_deps = SPI Wire - adafruit/Adafruit BusIO @ 1.9.6 https://github.com/HelTecAutomation/Heltec_ESP32/ - adafruit/Adafruit GFX Library@^1.11.10 ropg/Heltec_ESP32_LoRa_v3@^0.9.1 adafruit/Adafruit ST7735 and ST7789 Library@^1.10.4 + adafruit/Adafruit GFX Library@^1.11.10 + adafruit/Adafruit BusIO@^1.16.1 [env:vision-master-t190] platform = espressif32 @@ -124,8 +124,8 @@ build_flags = lib_deps = SPI Wire - adafruit/Adafruit BusIO @ 1.9.6 https://github.com/HelTecAutomation/Heltec_ESP32/ - adafruit/Adafruit GFX Library@^1.11.10 ropg/Heltec_ESP32_LoRa_v3@^0.9.1 adafruit/Adafruit ST7735 and ST7789 Library@^1.10.4 + adafruit/Adafruit GFX Library@^1.11.10 + adafruit/Adafruit BusIO@^1.16.1 diff --git a/src/main.cpp b/src/main.cpp index acfc13b..7aa595c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -157,8 +157,8 @@ typedef enum } TSCAN_METOD_ENUM; #define SCAN_METHOD -// #define METHOD_SPECTRAL // Spectral scan method -#define METHOD_RSSI // Uncomment this and comment METHOD_SPECTRAL fot RSSI +#define METHOD_SPECTRAL // Spectral scan method +// #define METHOD_RSSI // Uncomment this and comment METHOD_SPECTRAL fot RSSI // Output Pixel Formula // 1 = rssi / 4, 2 = (rssi / 2) - 22 or 20 @@ -241,15 +241,16 @@ uint64_t detection_count = 0; bool single_page_scan = false; bool SOUND_ON = false; -// #define PRINT_DEBUG +#define PRINT_DEBUG #define PRINT_PROFILE_TIME +// #define PRINT_OUTPUT -#ifdef PRINT_PROFILE_TIME +// #ifdef PRINT_PROFILE_TIME uint64_t loop_start = 0; uint64_t loop_time = 0; uint64_t scan_time = 0; uint64_t scan_start_time = 0; -#endif +// #endif uint64_t x, y, range_item, w = WATERFALL_START, i = 0; int osd_x = 1, osd_y = 2, col = 0, max_bin = 32; @@ -889,6 +890,10 @@ void loop(void) #ifdef PRINT_DEBUG Serial.printf("Step:%d Freq: %f\n", x, freq); #endif + +#ifdef PRINT_OUTPUT + Serial.printf("FREQ %f\n", freq); +#endif // SpectralScan Method #ifdef METHOD_SPECTRAL { @@ -913,6 +918,7 @@ void loop(void) // read the results Array to which the results will be saved state = radio.spectralScanGetResult(result); display.drawString(0, 64 - 10, "scanGetResult:" + String(state)); + Serial.printf("curious %d\n", result[0]); } #endif @@ -921,6 +927,9 @@ void loop(void) { #ifdef PRINT_DEBUG Serial.println("METHOD RSSI"); +#endif +#ifdef PRINT_OUTPUT + Serial.print("SCAN "); #endif // memset // memset(result, 0, RADIOLIB_SX126X_SPECTRAL_SCAN_RES_SIZE); @@ -952,6 +961,10 @@ void loop(void) #ifdef PRINT_DEBUG Serial.printf("RSSI: %d IDX: %d\n", rssi, result_index); #endif +#ifdef PRINT_OUTPUT + Serial.printf("%d,", rssi); +#endif + // avoid buffer overflow if (result_index < RADIOLIB_SX126X_SPECTRAL_SCAN_RES_SIZE) { @@ -963,7 +976,9 @@ void loop(void) } else { - Serial.print("Out-of-Range: result_index %d\n"); +#ifndef PRINT_OUTPUT + Serial.printf("Out-of-Range:result_index %d\n", result_index); +#endif } } } @@ -1156,6 +1171,10 @@ void loop(void) #ifdef PRINT_DEBUG Serial.println("....\n"); #endif + +#ifdef PRINT_OUTPUT + Serial.print(" END\n"); +#endif if (first_run || ANIMATED_RELOAD) { display.display();