├── util ├── kraken_pr_stop.sh └── kraken_pr_start.sh ├── _UI └── _web_interface │ ├── assets │ ├── favicon.ico │ ├── kraken_interface_bw_pr.png │ └── style.css │ ├── tooltips.py │ └── kraken_web_interface.py ├── kill.sh ├── settings.json ├── gui_run.sh ├── .gitignore ├── README.md ├── _receiver ├── iq_header.py ├── shmemIface.py └── krakenSDR_receiver.py ├── _signal_processing └── krakenSDR_signal_processor.py └── LICENSE /util/kraken_pr_stop.sh: -------------------------------------------------------------------------------- 1 | cd heimdall_daq_fw/Firmware 2 | ./daq_stop.sh 3 | 4 | cd ../../krakensdr_pr 5 | ./kill.sh 6 | -------------------------------------------------------------------------------- /_UI/_web_interface/assets/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yuvadm/krakensdr_pr/HEAD/_UI/_web_interface/assets/favicon.ico -------------------------------------------------------------------------------- /_UI/_web_interface/assets/kraken_interface_bw_pr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yuvadm/krakensdr_pr/HEAD/_UI/_web_interface/assets/kraken_interface_bw_pr.png -------------------------------------------------------------------------------- /kill.sh: -------------------------------------------------------------------------------- 1 | #/bin/sh! 2 | sudo kill -64 $(ps ax | grep "[p]ython3 _UI/_web_interface/kraken_web_interface.py" | awk '{print $1}') 2> /dev/null 3 | sudo kill -64 $(ps ax | grep "[p]hp" | awk '{print $1}') 2> /dev/null 4 | #sudo pkill -f gunicorn 5 | 6 | -------------------------------------------------------------------------------- /util/kraken_pr_start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #source /home/krakenrf/miniforge3/etc/profile.d/conda.sh <- required for systemd auto startup (comment out eval and use source instead) 4 | 5 | eval "$(conda shell.bash hook)" 6 | conda activate kraken 7 | 8 | ./kraken_pr_stop.sh 9 | sleep 2 10 | 11 | cd heimdall_daq_fw/Firmware 12 | #sudo ./daq_synthetic_start.sh 13 | sudo env "PATH=$PATH" ./daq_start_sm.sh 14 | sleep 2 15 | cd ../../krakensdr_pr 16 | sudo env "PATH=$PATH" ./gui_run.sh 17 | -------------------------------------------------------------------------------- /settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "center_freq": 569.0, 3 | "gain_1": 25.4, 4 | "gain_2": 7.7, 5 | "data_interface": "shmem", 6 | "default_ip": "0.0.0.0", 7 | "en_pr": true, 8 | "clutter_cancel_algo": "Wiener MRE", 9 | "max_bistatic_range": 128, 10 | "max_doppler": 256, 11 | "en_pr_persist": true, 12 | "pr_persist_decay": 0.99, 13 | "pr_dynrange_min": -20, 14 | "pr_dynrange_max": 10, 15 | "en_hw_check": 0, 16 | "en_advanced_daq_cfg": [ 17 | 1 18 | ], 19 | "logging_level": 5, 20 | "disable_tooltips": 0 21 | } -------------------------------------------------------------------------------- /gui_run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | IPADDR="0.0.0.0" 4 | IPPORT="8081" 5 | 6 | echo "Starting KrakenSDR Passive Radar" 7 | 8 | # Use only for debugging 9 | #sudo python3 _UI/_web_interface/kraken_web_interface.py 2> ui.log & 10 | 11 | #sudo gunicorn -w 1 --threads 12 -b $IPADDR:8050 --chdir _UI/_web_interface kraken_web_interface:server 2> ui.log & 12 | #sudo gunicorn -w 1 --threads 2 -b $IPADDR:8050 --chdir _UI/_web_interface kraken_web_interface:server 2> ui.log & 13 | 14 | python3 _UI/_web_interface/kraken_web_interface.py 2> ui.log & 15 | 16 | # Start PHP webserver to interface with Android devices 17 | #echo "Python Server running at $IPADDR:8080" 18 | #echo "PHP Server running at $IPADDR:$IPPORT" 19 | #sudo php -S $IPADDR:$IPPORT -t _android_web 2> /dev/null & 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kraken SDR Passive Radar 2 | 3 | Please consult our Passive Radar Wiki page at https://github.com/krakenrf/krakensdr_docs/wiki/08.-Passive-Radar for more information. 4 | 5 | ## Quickstart Raspberry Pi 4 Image 6 | 7 | The passive radar software is preinstalled on the DOA PI4 Image at https://github.com/krakenrf/krakensdr_doa/releases/ 8 | 9 | By default this image runs the DOA direction finding code on boot. 10 | 11 | To change to the passive radar code, connect a monitor and keyboard (or SSH in), and edit start.sh in the home folder. You will need to comment out the DOA code run lines, and uncomment the passive radar lines. 12 | 13 | Make sure to change the heimdall preconfig file to pr_2ch_2pow20, pr_2ch_2pow21 or pr_2ch_2pow22 14 | 15 | ## Quickstart VirtualBox Image 16 | 17 | See our Wiki for more information about our VirtualBox Image and where to download it https://github.com/krakenrf/krakensdr_docs/wiki/10.-VirtualBox-and-Docker-Images#virtualbox 18 | 19 | Once you are in the OS to start the passive radar code, open a terminal and browse to the `krakensdr_pr` folder. Then run `./kraken_pr_start.sh`. Next see the Running heading below. 20 | 21 | 22 | 23 | 24 | ## Manual Installation 25 | 26 | ### Install script 27 | You can use on of our install scripts to automate a manual install. Details on the Wiki at https://github.com/krakenrf/krakensdr_docs/wiki/10.-VirtualBox,-Docker-Images-and-Install-Scripts#install-scripts 28 | 29 | We recommend using this script instead of manually typing each command one by one. 30 | 31 | ### Manual Hand Install 32 | 33 | This is only required if you are not using the premade images, scripts, and are setting up the software from a clean system. 34 | 35 | 1. Install the prerequisites 36 | 37 | ``` bash 38 | sudo apt update 39 | sudo apt install libfftw3-3 40 | sudo apt install libfftw3-dev 41 | ``` 42 | 43 | 2. Install Heimdall DAQ 44 | 45 | If not done already, first, follow the instructions at https://github.com/krakenrf/heimdall_daq_fw/tree/development to install the Heimdall DAQ Firmware. 46 | 47 | 3. Set up Miniconda environment 48 | 49 | You will have created a Miniconda environment during the Heimdall DAQ install phase. 50 | 51 | Please run the installs in this order as we need to ensure a specific version of dash is installed. 52 | 53 | ``` bash 54 | conda activate kraken 55 | 56 | conda install pandas 57 | conda install orjson 58 | conda install matplotlib 59 | conda install requests 60 | 61 | pip3 install dash_bootstrap_components==1.1.0 62 | pip3 install quart_compress==0.2.1 63 | pip3 install quart==0.17.0 64 | pip3 install dash_devices==0.1.3 65 | 66 | pip3 install pyapril 67 | pip3 install cython 68 | pip3 install pyfftw 69 | 70 | conda install -y dash==1.20.0 71 | conda install -y werkzeug==2.0.2 72 | ``` 73 | 74 | 4. Clone the krakensdr_pr software 75 | 76 | ```bash 77 | cd ~/krakensdr 78 | git clone https://github.com/krakenrf/krakensdr_pr 79 | ``` 80 | 81 | Copy the the *krakensdr_pr/util/kraken_pr_start.sh* and the *krakensdr_doa/util/kraken_pr_stop.sh* scripts into the krakensdr root folder of the project. 82 | ```bash 83 | cd ~/krakensdr 84 | cp krakensdr_pr/util/kraken_pr_start.sh . 85 | cp krakensdr_pr/util/kraken_pr_stop.sh . 86 | ``` 87 | 88 | ## Running 89 | 90 | ### Local operation (Recommended) 91 | 92 | ```bash 93 | ./kraken_pr_start.sh 94 | ``` 95 | 96 | Then browse to KRAKEN_IP_ADDR:8080 in a webbrowser on a computer on the same network. 97 | 98 | When the GUI loads, make sure to set an appropriate passive radar preconfig ini for the Heimdall DAQ. For example, choose "pr_2ch_2pow21", then click on "Reconfigure and Restart DAQ". This will configure the DAQ for passive radar, and then start the processing. 99 | 100 | Please be patient on the first run, at it can take 1-2 minutes for the JIT numba compiler to compile the numba optimized functions, and during this compilation time it may appear that the software has gotten stuck. On subsqeuent runs this loading time will be much faster as it will read from cache. 101 | 102 | Use CH0 to connect your reference antenna, and CH1 for your surveillance antenna.) 103 | 104 | ### Remote operation 105 | 106 | *UNTESTED* 107 | 108 | 1. Start the DAQ Subsystem either remotely. (Make sure that the *daq_chain_config.ini* contains the proper configuration) 109 | (See:https://github.com/krakenrf/heimdall_daq_fw/Documentation) 110 | 2. Set the IP address of the DAQ Subsystem in the settings.json, *default_ip* field. 111 | 3. Start the DoA DSP software by typing: 112 | `./gui_run.sh` 113 | 4. To stop the server and the DSP processing chain run the following script: 114 | `./kill.sh` 115 | 116 | After starting the script a web based server opens at port number 8088, which then can be accessed by typing "KRAKEN_IP:8080/" in the address bar of any web browser. You can find the IP address of the KrakenSDR Pi4 wither via your routers WiFi management page, or by typing "ip addr" into the terminal. You can also use the hostname of the Pi4 in place of the IP address, but this only works on local networks, and not the internet, or mobile hotspot networks. 117 | -------------------------------------------------------------------------------- /_UI/_web_interface/assets/style.css: -------------------------------------------------------------------------------- 1 | /*Globlal Properties*/ 2 | /* Color pallete https://www.color-hex.com/color-palette/7735 */ 3 | /*Tags*/ 4 | body { 5 | background-color: #000000; 6 | color:#ffffff; 7 | margin: 0px; 8 | padding: 0px; 9 | } 10 | *{ 11 | font-size:17px; 12 | font-family: 'Montserrat', sans-serif; 13 | } 14 | h1{ 15 | font-size:22px; 16 | } 17 | a{ 18 | font-size: 22px; 19 | } 20 | input[type="checkbox"]{ 21 | width:20px; 22 | height:20px; 23 | background:white; 24 | border-radius:5px; 25 | border:2px solid #555; 26 | vertical-align: middle; 27 | } 28 | .Select-value-label { 29 | color:white !important; 30 | } 31 | .Select div { 32 | box-sizing:content-box !important; 33 | /*padding-right:7px;*/ 34 | } 35 | .Select-control { 36 | background-color:#000000; 37 | vertical-align:middle; 38 | border-radius:0px; 39 | border:1px solid; 40 | border-color: #bdc3c7; 41 | color:white !important; 42 | height:33px; 43 | } 44 | .Select-value { 45 | /*background-color: rgb(255, 102, 0);*/ 46 | background-color: black; /*antiquewhite;*/ 47 | color: white; /*black;*/ 48 | /*color:#000000;*/ 49 | } 50 | .Select-menu-outer { 51 | background-color: rgb(0, 0, 0); 52 | } 53 | 54 | input, select{ 55 | width: 100%; 56 | } 57 | iframe{ 58 | background-color: transparent; 59 | border: 0px none transparent; 60 | padding: 0px; 61 | overflow: hidden; 62 | } 63 | /*Classes*/ 64 | .header{ 65 | background-color: #000000; 66 | width: 100%; 67 | text-align: center; 68 | padding: 10px; 69 | } 70 | .header a{ 71 | color: white; 72 | text-transform: uppercase; 73 | text-decoration: none; 74 | padding: 5px; 75 | line-height: 40px; 76 | border: 0.1em solid #ffffff; 77 | border-radius:0.05em; 78 | margin: 5px; 79 | } 80 | .header_active, .header a:hover{ 81 | background-color: #f39c12; /*#ff6600c0;*/ 82 | } 83 | .ctr_toolbar{ 84 | background-color: #000000; 85 | height: 50px; 86 | width: 100%; 87 | text-align: center; 88 | } 89 | .ctr_toolbar_item { 90 | text-align: center; 91 | display : inline-block; 92 | position : relative; 93 | margin : 0 auto; 94 | padding : 0px; 95 | float : center; 96 | } 97 | .doa_check{ 98 | text-align: left; 99 | } 100 | .btn{ 101 | height: 40px; 102 | cursor: pointer; 103 | background-color: #7ccc63; /*green;*/ 104 | border: 0.1em solid #000000; 105 | border-radius:0.12em; 106 | color: black; 107 | font-size:20px; 108 | text-decoration: none; 109 | text-align: center; 110 | width: 100%; 111 | transition: all 0.2s; 112 | } 113 | .btn:hover{ 114 | color: rgb(0, 0, 0); 115 | background-color: #f39c12; /*#ff6600;*/ 116 | } 117 | .btn a{ 118 | color: white; 119 | text-decoration: none; 120 | position: relative; 121 | top: 15%; 122 | } 123 | .btn_start{ 124 | height: 40px; 125 | cursor: pointer; 126 | background-color: #7ccc63; /*#02c93d;*/ 127 | border: 0.1em solid #000000; 128 | border-radius:0.12em; 129 | color: rgb(0, 0, 0); 130 | font-size:20px; 131 | text-decoration: none; 132 | text-align: center; 133 | width: 100%; 134 | transition: all 0.2s; 135 | } 136 | .btn_start:hover{ 137 | color: rgb(0, 0, 0); 138 | background-color: #f39c12; /*#ff6600;*/ 139 | } 140 | .btn_stop{ 141 | height: 40px; 142 | cursor: pointer; 143 | background-color: #e74c3c; /*#c40404;*/ 144 | border: 0.1em solid #000000; 145 | border-radius:0.12em; 146 | color: rgb(0, 0, 0); 147 | font-size:20px; 148 | text-decoration: none; 149 | text-align: center; 150 | width: 100%; 151 | } 152 | .btn_stop:hover{ 153 | color: rgb(0, 0, 0); 154 | background-color: #f39c12; /*#ff6600;*/ 155 | } 156 | .btn_save_cfg{ 157 | height: 40px; 158 | cursor: pointer; 159 | background-color: #bdc3c7; /*#b5aef5;*/ 160 | border: 0.1em solid #000000; 161 | border-radius:0.12em; 162 | color: rgb(0, 0, 0); 163 | font-size:20px; 164 | text-decoration: none; 165 | text-align: center; 166 | width: 100%; 167 | } 168 | .btn_save_cfg:hover{ 169 | color: rgb(154, 233, 102); 170 | background-color: #f39c12; /*#ff6600;*/ 171 | } 172 | .tooltip{ 173 | color: rgb(0, 0, 0); 174 | background-color: #ffffff; 175 | opacity: 0.95; 176 | border-radius:0.2em; 177 | width: 300px; 178 | } 179 | .card{ 180 | background-color: #000000; 181 | border: 0.1em solid #ffffff; 182 | border-radius:0.2em; 183 | width: 400px; 184 | max-width: 500px; 185 | padding: 20px; 186 | box-shadow: 0 6px 18px rgba(0, 0, 0, 0.46); 187 | margin: 10px; 188 | float: left; 189 | } 190 | .monitor_card{ 191 | background-color: #000000; 192 | border: 0.1em solid #ffffff; 193 | border-radius:0.2em; 194 | width: 95%; 195 | height: 800px; 196 | overflow:scroll; 197 | box-shadow: 0 6px 18px rgba(0, 0, 0, 0.46); 198 | margin: auto; 199 | } 200 | 201 | .field{ 202 | width: 400px; 203 | display: block; 204 | margin: 10px auto; 205 | padding: 0px; 206 | } 207 | .field-label{ 208 | width: 225px; 209 | display: inline-block; 210 | vertical-align: middle; 211 | } 212 | .field-body{ 213 | width: 165px; 214 | display: inline-block; 215 | } 216 | .field-body-textbox{ 217 | width: 153px; 218 | display: inline-block; 219 | background-color: black; 220 | border: 1px solid; 221 | border-color: #bdc3c7; 222 | color: white; 223 | padding-left: 10px; 224 | height: 33px; 225 | } 226 | .field-body-wide{ 227 | width: 400px; 228 | display: inline-block; 229 | } 230 | 231 | /*Mobile Properties*/ 232 | @media screen and (max-width: 1072px) { 233 | .card{ 234 | width: calc( 100% - 30px ); 235 | padding: 5px; 236 | margin: 20px auto; 237 | float: none; 238 | } 239 | } 240 | 241 | @media screen and (max-width: 500px) { 242 | .field, .field-label, .field-body, input{ 243 | width: calc( 100% - 15px ); 244 | } 245 | } 246 | -------------------------------------------------------------------------------- /_receiver/iq_header.py: -------------------------------------------------------------------------------- 1 | from struct import pack,unpack 2 | import logging 3 | import sys 4 | """ 5 | Desctiption: IQ Frame header definition 6 | For header field description check the corresponding documentation 7 | Total length: 1024 byte 8 | Project: HeIMDALL RTL 9 | Author: Tamás Pető 10 | Status: Finished 11 | Version history: 12 | 1 : Initial version (2019 04 23) 13 | 2 : Fixed 1024 byte length (2019 07 25) 14 | 3 : Noise source state (2019 10 01) 15 | 4 : IQ sync flag (2019 10 21) 16 | 5 : Sync state (2019 11 10) 17 | 6 : Unix Epoch timestamp (2019 12 17) 18 | 6a: Frame type defines (2020 03 19) 19 | 7 : Sync word (2020 05 03) 20 | """ 21 | class IQHeader(): 22 | 23 | FRAME_TYPE_DATA = 0 24 | FRAME_TYPE_DUMMY = 1 25 | FRAME_TYPE_RAMP = 2 26 | FRAME_TYPE_CAL = 3 27 | FRAME_TYPE_TRIGW = 4 28 | 29 | SYNC_WORD = 0x2bf7b95a 30 | 31 | def __init__(self): 32 | 33 | self.logger = logging.getLogger(__name__) 34 | self.header_size = 1024 # size in bytes 35 | self.reserved_bytes = 192 36 | 37 | self.sync_word=self.SYNC_WORD # uint32_t 38 | self.frame_type=0 # uint32_t 39 | self.hardware_id="" # char [16] 40 | self.unit_id=0 # uint32_t 41 | self.active_ant_chs=0 # uint32_t 42 | self.ioo_type=0 # uint32_t 43 | self.rf_center_freq=0 # uint64_t 44 | self.adc_sampling_freq=0 # uint64_t 45 | self.sampling_freq=0 # uint64_t 46 | self.cpi_length=0 # uint32_t 47 | self.time_stamp=0 # uint64_t 48 | self.daq_block_index=0 # uint32_t 49 | self.cpi_index=0 # uint32_t 50 | self.ext_integration_cntr=0 # uint64_t 51 | self.data_type=0 # uint32_t 52 | self.sample_bit_depth=0 # uint32_t 53 | self.adc_overdrive_flags=0 # uint32_t 54 | self.if_gains=[0]*32 # uint32_t x 32 55 | self.delay_sync_flag=0 # uint32_t 56 | self.iq_sync_flag=0 # uint32_t 57 | self.sync_state=0 # uint32_t 58 | self.noise_source_state=0 # uint32_t 59 | self.reserved=[0]*self.reserved_bytes# uint32_t x reserverd_bytes 60 | self.header_version=0 # uint32_t 61 | 62 | def decode_header(self, iq_header_byte_array): 63 | """ 64 | Unpack,decode and store the content of the iq header 65 | """ 66 | iq_header_list = unpack("II16sIIIQQQIQIIQIII"+"I"*32+"IIII"+"I"*self.reserved_bytes+"I", iq_header_byte_array) 67 | 68 | self.sync_word = iq_header_list[0] 69 | self.frame_type = iq_header_list[1] 70 | self.hardware_id = iq_header_list[2].decode() 71 | self.unit_id = iq_header_list[3] 72 | self.active_ant_chs = iq_header_list[4] 73 | self.ioo_type = iq_header_list[5] 74 | self.rf_center_freq = iq_header_list[6] 75 | self.adc_sampling_freq = iq_header_list[7] 76 | self.sampling_freq = iq_header_list[8] 77 | self.cpi_length = iq_header_list[9] 78 | self.time_stamp = iq_header_list[10] 79 | self.daq_block_index = iq_header_list[11] 80 | self.cpi_index = iq_header_list[12] 81 | self.ext_integration_cntr = iq_header_list[13] 82 | self.data_type = iq_header_list[14] 83 | self.sample_bit_depth = iq_header_list[15] 84 | self.adc_overdrive_flags = iq_header_list[16] 85 | self.if_gains = iq_header_list[17:49] 86 | self.delay_sync_flag = iq_header_list[49] 87 | self.iq_sync_flag = iq_header_list[50] 88 | self.sync_state = iq_header_list[51] 89 | self.noise_source_state = iq_header_list[52] 90 | self.header_version = iq_header_list[52+self.reserved_bytes+1] 91 | 92 | def encode_header(self): 93 | """ 94 | Pack the iq header information into a byte array 95 | """ 96 | iq_header_byte_array=pack("II", self.sync_word, self.frame_type) 97 | iq_header_byte_array+=self.hardware_id.encode()+bytearray(16-len(self.hardware_id.encode())) 98 | iq_header_byte_array+=pack("IIIQQQIQIIQIII", 99 | self.unit_id, self.active_ant_chs, self.ioo_type, self.rf_center_freq, self.adc_sampling_freq, 100 | self.sampling_freq, self.cpi_length, self.time_stamp, self.daq_block_index, self.cpi_index, 101 | self.ext_integration_cntr, self.data_type, self.sample_bit_depth, self.adc_overdrive_flags) 102 | for m in range(32): 103 | iq_header_byte_array+=pack("I", self.if_gains[m]) 104 | 105 | iq_header_byte_array+=pack("I", self.delay_sync_flag) 106 | iq_header_byte_array+=pack("I", self.iq_sync_flag) 107 | iq_header_byte_array+=pack("I", self.sync_state) 108 | iq_header_byte_array+=pack("I", self.noise_source_state) 109 | 110 | for m in range(self.reserved_bytes): 111 | iq_header_byte_array+=pack("I",0) 112 | 113 | iq_header_byte_array+=pack("I", self.header_version) 114 | return iq_header_byte_array 115 | 116 | def dump_header(self): 117 | """ 118 | Prints out the content of the header in human readable format 119 | """ 120 | self.logger.info("Sync word: {:d}".format(self.sync_word)) 121 | self.logger.info("Header version: {:d}".format(self.header_version)) 122 | self.logger.info("Frame type: {:d}".format(self.frame_type)) 123 | self.logger.info("Hardware ID: {:16}".format(self.hardware_id)) 124 | self.logger.info("Unit ID: {:d}".format(self.unit_id)) 125 | self.logger.info("Active antenna channels: {:d}".format(self.active_ant_chs)) 126 | self.logger.info("Illuminator type: {:d}".format(self.ioo_type)) 127 | self.logger.info("RF center frequency: {:.2f} MHz".format(self.rf_center_freq/10**6)) 128 | self.logger.info("ADC sampling frequency: {:.2f} MHz".format(self.adc_sampling_freq/10**6)) 129 | self.logger.info("IQ sampling frequency {:.2f} MHz".format(self.sampling_freq/10**6)) 130 | self.logger.info("CPI length: {:d}".format(self.cpi_length)) 131 | self.logger.info("Unix Epoch timestamp: {:d}".format(self.time_stamp)) 132 | self.logger.info("DAQ block index: {:d}".format(self.daq_block_index)) 133 | self.logger.info("CPI index: {:d}".format(self.cpi_index)) 134 | self.logger.info("Extended integration counter {:d}".format(self.ext_integration_cntr)) 135 | self.logger.info("Data type: {:d}".format(self.data_type)) 136 | self.logger.info("Sample bit depth: {:d}".format(self.sample_bit_depth)) 137 | self.logger.info("ADC overdrive flags: {:d}".format(self.adc_overdrive_flags)) 138 | for m in range(32): 139 | self.logger.info("Ch: {:d} IF gain: {:.1f} dB".format(m, self.if_gains[m]/10)) 140 | self.logger.info("Delay sync flag: {:d}".format(self.delay_sync_flag)) 141 | self.logger.info("IQ sync flag: {:d}".format(self.iq_sync_flag)) 142 | self.logger.info("Sync state: {:d}".format(self.sync_state)) 143 | self.logger.info("Noise source state: {:d}".format(self.noise_source_state)) 144 | 145 | def check_sync_word(self): 146 | """ 147 | Check the sync word of the header 148 | """ 149 | if self.sync_word != self.SYNC_WORD: 150 | return -1 151 | else: 152 | return 0 153 | -------------------------------------------------------------------------------- /_receiver/shmemIface.py: -------------------------------------------------------------------------------- 1 | """ 2 | HeIMDALL DAQ Firmware 3 | Python based shared memory interface implementations 4 | 5 | Author: Tamás Pető 6 | License: GNU GPL V3 7 | 8 | This program is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program. If not, see . 20 | """ 21 | import logging 22 | from struct import pack, unpack 23 | from multiprocessing import shared_memory 24 | import numpy as np 25 | import os 26 | 27 | A_BUFF_READY = 1 28 | B_BUFF_READY = 2 29 | INIT_READY = 10 30 | TERMINATE = 255 31 | class outShmemIface(): 32 | 33 | 34 | def __init__(self, shmem_name, shmem_size, drop_mode = False): 35 | 36 | self.init_ok = True 37 | logging.basicConfig(level=logging.INFO) 38 | self.logger = logging.getLogger(__name__) 39 | self.drop_mode = drop_mode 40 | self.dropped_frame_cntr = 0 41 | 42 | self.shmem_name = shmem_name 43 | self.buffer_free = [True, True] 44 | 45 | self.memories = [] 46 | self.buffers = [] 47 | 48 | # Try to remove shared memories if already exist 49 | try: 50 | shmem_A = shared_memory.SharedMemory(name=shmem_name+'_A',create=False, size=shmem_size) 51 | shmem_A.close() 52 | #shmem_A.unkink() 53 | except FileNotFoundError as err: 54 | self.logger.warning("Shared memory not exist") 55 | try: 56 | shmem_B = shared_memory.SharedMemory(name=shmem_name+'_B',create=False, size=shmem_size) 57 | shmem_B.close() 58 | #shmem_B.unkink() 59 | except FileNotFoundError as err: 60 | self.logger.warning("Shared memory not exist") 61 | 62 | # Create the shared memories 63 | self.memories.append(shared_memory.SharedMemory(name=shmem_name+'_A',create=True, size=shmem_size)) 64 | self.memories.append(shared_memory.SharedMemory(name=shmem_name+'_B',create=True, size=shmem_size)) 65 | self.buffers.append(np.ndarray((shmem_size,), dtype=np.uint8, buffer=self.memories[0].buf)) 66 | self.buffers.append(np.ndarray((shmem_size,), dtype=np.uint8, buffer=self.memories[1].buf)) 67 | 68 | # Opening control FIFOs 69 | if self.drop_mode: 70 | bw_fifo_flags = os.O_RDONLY | os.O_NONBLOCK 71 | else: 72 | bw_fifo_flags = os.O_RDONLY 73 | try: 74 | self.fw_ctr_fifo = os.open('_data_control/'+'fw_'+shmem_name, os.O_WRONLY) 75 | self.bw_ctr_fifo = os.open('_data_control/'+'bw_'+shmem_name, bw_fifo_flags) 76 | except OSError as err: 77 | self.logger.critical("OS error: {0}".format(err)) 78 | self.logger.critical("Failed to open control fifos") 79 | self.bw_ctr_fifo = None 80 | self.fw_ctr_fifo = None 81 | self.init_ok = False 82 | 83 | # Send init ready signal 84 | if self.init_ok: 85 | os.write(self.fw_ctr_fifo, pack('B',INIT_READY)) 86 | 87 | def send_ctr_buff_ready(self, active_buffer_index): 88 | # Send buffer ready signal on the forward FIFO 89 | if active_buffer_index == 0: 90 | os.write(self.fw_ctr_fifo, pack('B',A_BUFF_READY)) 91 | elif active_buffer_index == 1: 92 | os.write(self.fw_ctr_fifo, pack('B',B_BUFF_READY)) 93 | 94 | # Deassert buffer free flag 95 | self.buffer_free[active_buffer_index] = False 96 | 97 | def send_ctr_terminate(self): 98 | os.write(self.fw_ctr_fifo, pack('B',TERMINATE)) 99 | self.logger.info("Terminate signal sent") 100 | 101 | def destory_sm_buffer(self): 102 | for memory in self.memories: 103 | memory.close() 104 | memory.unlink() 105 | 106 | if self.fw_ctr_fifo is not None: 107 | os.close(self.fw_ctr_fifo) 108 | 109 | if self.bw_ctr_fifo is not None: 110 | os.close(self.bw_ctr_fifo) 111 | 112 | def wait_buff_free(self): 113 | if self.buffer_free[0]: 114 | return 0 115 | elif self.buffer_free[1]: 116 | return 1 117 | else: 118 | try: 119 | buffer = os.read(self.bw_ctr_fifo, 1) 120 | signal = unpack('B', buffer )[0] 121 | 122 | if signal == A_BUFF_READY: 123 | self.buffer_free[0] = True 124 | return 0 125 | if signal == B_BUFF_READY: 126 | self.buffer_free[1] = True 127 | return 1 128 | except BlockingIOError as err: 129 | self.dropped_frame_cntr +=1 130 | self.logger.warning("Dropping frame.. Total: [{:d}] ".format(self.dropped_frame_cntr)) 131 | return 3 132 | return -1 133 | 134 | 135 | class inShmemIface(): 136 | 137 | def __init__(self, shmem_name, ctr_fifo_path="_data_control/"): 138 | 139 | self.init_ok = True 140 | logging.basicConfig(level=logging.INFO) 141 | self.logger = logging.getLogger(__name__) 142 | self.drop_mode = False 143 | 144 | self.shmem_name = shmem_name 145 | 146 | self.memories = [] 147 | self.buffers = [] 148 | try: 149 | self.fw_ctr_fifo = os.open(ctr_fifo_path+'fw_'+shmem_name, os.O_RDONLY) 150 | self.bw_ctr_fifo = os.open(ctr_fifo_path+'bw_'+shmem_name, os.O_WRONLY) 151 | except OSError as err: 152 | self.logger.critical("OS error: {0}".format(err)) 153 | self.logger.critical("Failed to open control fifos") 154 | self.bw_ctr_fifo = None 155 | self.fw_ctr_fifo = None 156 | self.init_ok = False 157 | 158 | if self.fw_ctr_fifo is not None: 159 | if unpack('B', os.read(self.fw_ctr_fifo, 1))[0] == INIT_READY: 160 | self.memories.append(shared_memory.SharedMemory(name=shmem_name+'_A')) 161 | self.memories.append(shared_memory.SharedMemory(name=shmem_name+'_B')) 162 | self.buffers.append(np.ndarray((self.memories[0].size,), 163 | dtype=np.uint8, 164 | buffer=self.memories[0].buf)) 165 | self.buffers.append(np.ndarray((self.memories[1].size,), 166 | dtype=np.uint8, 167 | buffer=self.memories[1].buf)) 168 | else: 169 | self.init_ok = False 170 | 171 | def send_ctr_buff_ready(self, active_buffer_index): 172 | if active_buffer_index == 0: 173 | os.write(self.bw_ctr_fifo, pack('B',A_BUFF_READY)) 174 | elif active_buffer_index == 1: 175 | os.write(self.bw_ctr_fifo, pack('B',B_BUFF_READY)) 176 | 177 | def destory_sm_buffer(self): 178 | for memory in self.memories: 179 | memory.close() 180 | 181 | if self.fw_ctr_fifo is not None: 182 | os.close(self.fw_ctr_fifo) 183 | 184 | if self.bw_ctr_fifo is not None: 185 | os.close(self.bw_ctr_fifo) 186 | 187 | def wait_buff_free(self): 188 | signal = unpack('B', os.read(self.fw_ctr_fifo, 1))[0] 189 | if signal == A_BUFF_READY: 190 | return 0 191 | elif signal == B_BUFF_READY: 192 | return 1 193 | elif signal == TERMINATE: 194 | return TERMINATE 195 | return -1 196 | -------------------------------------------------------------------------------- /_UI/_web_interface/tooltips.py: -------------------------------------------------------------------------------- 1 | import dash_html_components as html 2 | import dash_bootstrap_components as dbc 3 | 4 | dsp_config_tooltips = html.Div([ 5 | # Antenna arrangement selection 6 | dbc.Tooltip([ 7 | html.P("ULA - Uniform Linear Array"), 8 | html.P("Antenna elements placed on a line with having equal distances between each other"), 9 | html.P("UCA - Uniform Circular Array"), 10 | html.P("Antenna elements are placed on circle equaly distributed on 360°")], 11 | target="label_ant_arrangement", 12 | placement="bottom", 13 | className="tooltip" 14 | ), 15 | # Antenna Spacing 16 | # dbc.Tooltip([ 17 | # html.P("When ULA is selected: Spacing between antenna elements"), 18 | # html.P("When UCA is selected: Radius of the circle on which the elements are placed")], 19 | # target="label_ant_spacing", 20 | # placement="bottom", 21 | # className="tooltip" 22 | # ), 23 | # Enable F-B averaging 24 | dbc.Tooltip([ 25 | html.P("Forward-backward averegaing improves the performance of DoA estimation in multipath environment"), 26 | html.P("(Available only for ULA antenna systems)")], 27 | target="label_en_fb_avg", 28 | placement="bottom", 29 | className="tooltip" 30 | ), 31 | ]) 32 | 33 | daq_ini_config_tooltips = html.Div([ 34 | # DAQ buffer size 35 | dbc.Tooltip([ 36 | html.P("Buffer size of the realtek driver")], 37 | target="label_daq_buffer_size", 38 | placement="bottom", 39 | className="tooltip" 40 | ), 41 | # Sampling frequency 42 | dbc.Tooltip([ 43 | html.P("Raw - ADC sampling frequency of the realtek chip")], 44 | target="label_sample_rate", 45 | placement="bottom", 46 | className="tooltip" 47 | ), 48 | # Enable noise source control 49 | dbc.Tooltip([ 50 | html.P("Enables the utilization of the built-in noise source for calibration")], 51 | target="label_en_noise_source_ctr", 52 | placement="bottom", 53 | className="tooltip" 54 | ), 55 | # Enable squelch mode 56 | dbc.Tooltip([ 57 | html.P("Enable DAQ-side squelch to capture burst like signals - NOTE DISABLED IN THIS VERSION, THIS VERSION USES DSP SIDE SQUELCH ONLY")], 58 | target="label_en_squelch", 59 | placement="bottom", 60 | className="tooltip" 61 | ), 62 | # Squelch threshold 63 | dbc.Tooltip([ 64 | html.P("Amplitude threshold used for the squelch feature."), 65 | html.P("Should take values on range: 0...1"), 66 | html.P("When set to zero the squelch is bypassed")], 67 | target="label_squelch_init_threshold", 68 | placement="bottom", 69 | className="tooltip" 70 | ), 71 | # CPI size 72 | dbc.Tooltip([ 73 | html.P("Length of the Coherent Processing Interval (CPI) after decimation")], 74 | target="label_cpi_size", 75 | placement="bottom", 76 | className="tooltip" 77 | ), 78 | # Decimation raito 79 | dbc.Tooltip([ 80 | html.P("Decimation factor")], 81 | target="label_decimation_ratio", 82 | placement="bottom", 83 | className="tooltip" 84 | ), 85 | # FIR relative bandwidth 86 | dbc.Tooltip([ 87 | html.P("Anti-aliasing filter bandwith after decimation"), 88 | html.P("Should take values on range: (0, 1]"), 89 | html.P("E.g.: ADC sampling frequency: 1 MHz (IQ!) , Decimation ratio: 2, FIR relative bandwith:0.25"), 90 | html.P("Resulting passband bandwidth: 125 kHz ")], 91 | target="label_fir_relative_bw", 92 | placement="bottom", 93 | className="tooltip" 94 | ), 95 | # FIR tap size 96 | dbc.Tooltip([ 97 | html.P("Anti-aliasing FIR filter tap size - Do not set too large, or CPU utilization will be 100%"), 98 | html.P("Should be greater than the decimation ratio")], 99 | target="label_fir_tap_size", 100 | placement="bottom", 101 | className="tooltip" 102 | ), 103 | # FIR tap size 104 | dbc.Tooltip([ 105 | html.P("Window function type for designing the anti-aliasing FIR filter"), 106 | html.P("https://en.wikipedia.org/wiki/Window_function")], 107 | target="label_fir_window", 108 | placement="bottom", 109 | className="tooltip" 110 | ), 111 | # Enable filter reset 112 | dbc.Tooltip([ 113 | html.P("If enabled, the memory of the anti-aliasing FIR filter is reseted at the begining of every new CPI")], 114 | target="label_en_filter_reset", 115 | placement="bottom", 116 | className="tooltip" 117 | ), 118 | # Correlation size 119 | dbc.Tooltip([ 120 | html.P("Number of samples used for the calibration procedure (sample delay and IQ compensation)")], 121 | target="label_correlation_size", 122 | placement="bottom", 123 | className="tooltip" 124 | ), 125 | # Standard channel index 126 | dbc.Tooltip([ 127 | html.P("The selected channel is used as a reference for the IQ compensation")], 128 | target="label_std_ch_index", 129 | placement="bottom", 130 | className="tooltip" 131 | ), 132 | # Enable IQ calibration 133 | dbc.Tooltip([ 134 | html.P("Enables to compensate the amplitude and phase differences of the receiver channels")], 135 | target="label_en_iq_calibration", 136 | placement="bottom", 137 | className="tooltip" 138 | ), 139 | # Gain lock interval 140 | dbc.Tooltip([ 141 | html.P("Minimum number of stable frames before terminating the gain tuning procedure")], 142 | target="label_gain_lock_interval", 143 | placement="bottom", 144 | className="tooltip" 145 | ), 146 | # Require track lock intervention 147 | dbc.Tooltip([ 148 | html.P("When enabled the DAQ firmware waits for manual intervention during the calibraiton procedure"), 149 | html.P("Should be used only for hardave version 1.0")], 150 | target="label_require_track_lock", 151 | placement="bottom", 152 | className="tooltip" 153 | ), 154 | # Amplitude calibraiton mode 155 | dbc.Tooltip([ 156 | html.P("Amplitude difference compensation method applied as part of the IQ compensation"), 157 | html.P("default: Amplitude differences are estimated by calculating the cross-correlations of the channels"), 158 | html.P("disabled: Amplitude differences are not compensated"), 159 | html.P("channel_power: Ampltiude compensation is set in a way to achieve equal channel powers")], 160 | target="label_amplitude_calibration_mode", 161 | placement="bottom", 162 | className="tooltip" 163 | ), 164 | dbc.Tooltip([ 165 | html.P("When periodic calibration track mode is selected the firmware regularly turn on the noise source for a short burst to\ 166 | check whether the IQ calibration is still valid or not. In case the calibrated state is lost, the firmware automatically\ 167 | initiates a reclaibration procedure")], 168 | target="label_calibration_track_mode", 169 | placement="bottom", 170 | className="tooltip" 171 | ), 172 | 173 | # Calibration frame interval 174 | dbc.Tooltip([ 175 | html.P("Number of data frames between two consecutive calibration burst. Used when periodic calibration mode is selected")], 176 | target="label_calibration_frame_interval", 177 | placement="bottom", 178 | className="tooltip" 179 | ), 180 | # Calibration frame burst size 181 | dbc.Tooltip([ 182 | html.P("Number of calibration frames generated in the periodic calibration mode")], 183 | target="label_calibration_frame_burst_size", 184 | placement="bottom", 185 | className="tooltip" 186 | ), 187 | # Amplitude tolerance 188 | dbc.Tooltip([ 189 | html.P("Maximum allowed amplitude difference between the receiver channels")], 190 | target="label_amplitude_tolerance", 191 | placement="bottom", 192 | className="tooltip" 193 | ), 194 | # Phase tolerance 195 | dbc.Tooltip([ 196 | html.P("Maximum allowed phase difference between the receiver channels")], 197 | target="label_phase_tolerance", 198 | placement="bottom", 199 | className="tooltip" 200 | ), 201 | # Maximum sync fails 202 | dbc.Tooltip([ 203 | html.P("Maximum allowed consecutive IQ difference check failures before initiating a recalibration")], 204 | target="label_max_sync_fails", 205 | placement="bottom", 206 | className="tooltip" 207 | ), 208 | ]) 209 | 210 | 211 | -------------------------------------------------------------------------------- /_receiver/krakenSDR_receiver.py: -------------------------------------------------------------------------------- 1 | # KrakenSDR Receiver 2 | 3 | # Copyright (C) 2018-2021 Carl Laufer, Tamás Pető 4 | # 5 | # 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program. If not, see . 18 | # 19 | 20 | # -*- coding: utf-8 -*- 21 | 22 | # Import built-in modules 23 | import sys 24 | import os 25 | import time 26 | from struct import pack, unpack 27 | import socket 28 | import _thread 29 | from threading import Lock 30 | import queue 31 | import logging 32 | #import copy 33 | 34 | # Import third party modules 35 | import numpy as np 36 | from scipy import signal 37 | from iq_header import IQHeader 38 | from shmemIface import inShmemIface 39 | class ReceiverRTLSDR(): 40 | 41 | def __init__(self, data_que, data_interface = "eth", logging_level=10): 42 | """ 43 | Parameter: 44 | ---------- 45 | :param: data_que: Que to communicate with the UI (web iface/Qt GUI) 46 | :param: data_interface: This field is configured by the GUI during instantiation. 47 | Valid values are the followings: 48 | "eth" : The module will receiver IQ frames through an Ethernet connection 49 | "shmem": The module will receiver IQ frames through a shared memory interface 50 | :type : data_interface: string 51 | """ 52 | self.logger = logging.getLogger(__name__) 53 | self.logger.setLevel(logging_level) 54 | 55 | # DAQ parameters 56 | # These values are used by default to configure the DAQ through the configuration interface 57 | # Values are configured externally upon configuration request 58 | self.daq_center_freq = 100 # MHz 59 | self.daq_rx_gain = [0] * 100 # [dB] 60 | 61 | # UI interface 62 | self.data_que = data_que 63 | 64 | # IQ data interface 65 | self.data_interface = data_interface 66 | 67 | # -> Ethernet 68 | self.receiver_connection_status = False 69 | self.port = 5000 70 | self.rec_ip_addr = "127.0.0.1" # Configured by the GUI prior to connection request 71 | self.socket_inst = socket.socket() 72 | self.receiverBufferSize = 2 ** 18 # Size of the Ethernet receiver buffer measured in bytes 73 | 74 | # -> Shared memory 75 | root_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) 76 | daq_path = os.path.join(os.path.dirname(root_path),"heimdall_daq_fw") 77 | self.daq_shmem_control_path = os.path.join(os.path.join(daq_path,"Firmware"),"_data_control/") 78 | self.init_data_iface() 79 | 80 | # Control interface 81 | self.ctr_iface_socket = socket.socket() 82 | self.ctr_iface_port = 5001 83 | self.ctr_iface_thread_lock = Lock() # Used to synchronize the operation of the ctr_iface thread 84 | 85 | self.iq_frame_bytes = None 86 | self.iq_samples = None 87 | self.iq_header = IQHeader() 88 | self.M = 0 # Number of receiver channels, updated after establishing connection 89 | 90 | def init_data_iface(self): 91 | if self.data_interface == "shmem": 92 | # Open shared memory interface to capture the DAQ firmware output 93 | self.in_shmem_iface = inShmemIface("delay_sync_iq", self.daq_shmem_control_path) 94 | if not self.in_shmem_iface.init_ok: 95 | self.logger.critical("Shared memory initialization failed") 96 | self.in_shmem_iface.destory_sm_buffer() 97 | return -1 98 | return 0 99 | 100 | 101 | def eth_connect(self): 102 | """ 103 | Compatible only with DAQ firmwares that has the IQ streaming mode. 104 | HeIMDALL DAQ Firmware version: 1.0 or later 105 | """ 106 | try: 107 | if not self.receiver_connection_status: 108 | if self.data_interface == "eth": 109 | # Establlish IQ data interface connection 110 | self.socket_inst.connect((self.rec_ip_addr, self.port)) 111 | self.socket_inst.sendall(str.encode('streaming')) 112 | test_iq = self.receive_iq_frame() 113 | 114 | self.M = self.iq_header.active_ant_chs 115 | 116 | # Establish control interface connection 117 | self.ctr_iface_socket.connect((self.rec_ip_addr, self.ctr_iface_port)) 118 | self.receiver_connection_status = True 119 | self.ctr_iface_init() 120 | self.logger.info("CTR INIT Center freq: {0}".format(self.daq_center_freq)) 121 | self.set_center_freq(self.daq_center_freq) 122 | self.set_if_gain(self.daq_rx_gain) 123 | except: 124 | errorMsg = sys.exc_info()[0] 125 | self.logger.error("Error message: "+str(errorMsg)) 126 | self.receiver_connection_status = False 127 | self.logger.error("Unexpected error: {0}".format(sys.exc_info()[0])) 128 | 129 | # Re-instantiating sockets 130 | self.socket_inst = socket.socket() 131 | self.ctr_iface_socket = socket.socket() 132 | return -1 133 | 134 | self.logger.info("Connection established") 135 | que_data_packet = [] 136 | que_data_packet.append(['conn-ok',]) 137 | self.data_que.put(que_data_packet) 138 | 139 | def eth_close(self): 140 | """ 141 | Close Ethernet conenctions including the IQ data and the control interfaces 142 | """ 143 | try: 144 | if self.receiver_connection_status: 145 | if self.data_interface == "eth": 146 | self.socket_inst.sendall(str.encode('q')) # Send exit message 147 | self.socket_inst.close() 148 | self.socket_inst = socket.socket() # Re-instantiating socket 149 | 150 | # Close control interface connection 151 | exit_message_bytes=("EXIT".encode()+bytearray(124)) 152 | self.ctr_iface_socket.send(exit_message_bytes) 153 | self.ctr_iface_socket.close() 154 | self.ctr_iface_socket = socket.socket() 155 | 156 | self.receiver_connection_status = False 157 | que_data_packet = [] 158 | que_data_packet.append(['disconn-ok',]) 159 | self.data_que.put(que_data_packet) 160 | except: 161 | errorMsg = sys.exc_info()[0] 162 | self.logger.error("Error message: {0}".format(errorMsg)) 163 | return -1 164 | 165 | if self.data_interface == "shmem": 166 | self.in_shmem_iface.destory_sm_buffer() 167 | 168 | return 0 169 | 170 | def get_iq_online(self): 171 | """ 172 | This function obtains a new IQ data frame through the Ethernet IQ data or the shared memory interface 173 | """ 174 | 175 | # Check connection 176 | if not self.receiver_connection_status: 177 | fail = self.eth_connect() 178 | if fail: 179 | return -1 180 | 181 | if self.data_interface == "eth": 182 | self.socket_inst.sendall(str.encode("IQDownload")) # Send iq request command 183 | self.iq_samples = self.receive_iq_frame() 184 | 185 | elif self.data_interface == "shmem": 186 | active_buff_index = self.in_shmem_iface.wait_buff_free() 187 | if active_buff_index < 0 or active_buff_index > 1: 188 | self.logger.info("Terminating.., signal: {:d}".format(active_buff_index)) 189 | return -1 190 | 191 | buffer = self.in_shmem_iface.buffers[active_buff_index] 192 | iq_header_bytes = buffer[0:1024].tobytes() 193 | self.iq_header.decode_header(iq_header_bytes) 194 | 195 | # Inititalization from header - Set channel numbers 196 | if self.M == 0: 197 | self.M = self.iq_header.active_ant_chs 198 | self.daq_rx_gain = [0] * self.M 199 | 200 | incoming_payload_size = self.iq_header.cpi_length*self.iq_header.active_ant_chs*2*int(self.iq_header.sample_bit_depth/8) 201 | if incoming_payload_size > 0: 202 | iq_samples_in = (buffer[1024:1024 + incoming_payload_size].view(dtype=np.complex64))\ 203 | .reshape(self.iq_header.active_ant_chs, self.iq_header.cpi_length) 204 | self.iq_samples = iq_samples_in.copy() # Must be .copy 205 | 206 | self.in_shmem_iface.send_ctr_buff_ready(active_buff_index) 207 | 208 | def receive_iq_frame(self): 209 | """ 210 | Called by the get_iq_online function. Receives IQ samples over the establed Ethernet connection 211 | """ 212 | total_received_bytes = 0 213 | recv_bytes_count = 0 214 | iq_header_bytes = bytearray(self.iq_header.header_size) # allocate array 215 | view = memoryview(iq_header_bytes) # Get buffer 216 | 217 | self.logger.debug("Starting IQ header reception") 218 | 219 | while total_received_bytes < self.iq_header.header_size: 220 | # Receive into buffer 221 | recv_bytes_count = self.socket_inst.recv_into(view, self.iq_header.header_size-total_received_bytes) 222 | view = view[recv_bytes_count:] # reset memory region 223 | total_received_bytes += recv_bytes_count 224 | 225 | self.iq_header.decode_header(iq_header_bytes) 226 | # Uncomment to check the content of the IQ header 227 | #self.iq_header.dump_header() 228 | 229 | incoming_payload_size = self.iq_header.cpi_length*self.iq_header.active_ant_chs*2*int(self.iq_header.sample_bit_depth/8) 230 | if incoming_payload_size > 0: 231 | # Calculate total bytes to receive from the iq header data 232 | total_bytes_to_receive = incoming_payload_size 233 | receiver_buffer_size = 2**18 234 | 235 | self.logger.debug("Total bytes to receive: {:d}".format(total_bytes_to_receive)) 236 | 237 | total_received_bytes = 0 238 | recv_bytes_count = 0 239 | iq_data_bytes = bytearray(total_bytes_to_receive + receiver_buffer_size) # allocate array 240 | view = memoryview(iq_data_bytes) # Get buffer 241 | 242 | while total_received_bytes < total_bytes_to_receive: 243 | # Receive into buffer 244 | recv_bytes_count = self.socket_inst.recv_into(view, receiver_buffer_size) 245 | view = view[recv_bytes_count:] # reset memory region 246 | total_received_bytes += recv_bytes_count 247 | 248 | self.logger.debug(" IQ data succesfully received") 249 | 250 | # Convert raw bytes to Complex float64 IQ samples 251 | self.iq_samples = np.frombuffer(iq_data_bytes[0:total_bytes_to_receive], dtype=np.complex64).reshape(self.iq_header.active_ant_chs, self.iq_header.cpi_length) 252 | 253 | self.iq_frame_bytes = bytearray()+iq_header_bytes+iq_data_bytes 254 | return self.iq_samples 255 | else: 256 | return 0 257 | 258 | def ctr_iface_init(self): 259 | """ 260 | Initialize connection with the DAQ FW through the control interface 261 | """ 262 | if self.receiver_connection_status: # Check connection 263 | # Assembling message 264 | cmd="INIT" 265 | msg_bytes=(cmd.encode()+bytearray(124)) 266 | try: 267 | _thread.start_new_thread(self.ctr_iface_communication, (msg_bytes,)) 268 | except: 269 | errorMsg = sys.exc_info()[0] 270 | self.logger.error("Unable to start communication thread") 271 | self.logger.error("Error message: {:s}".format(errorMsg)) 272 | 273 | def ctr_iface_communication(self, msg_bytes): 274 | """ 275 | Handles communication on the control interface with the DAQ FW 276 | 277 | Parameters: 278 | ----------- 279 | 280 | :param: msg: Message bytes, that will be sent ont the control interface 281 | :type: msg: Byte array 282 | """ 283 | self.ctr_iface_thread_lock.acquire() 284 | self.logger.debug("Sending control message") 285 | self.ctr_iface_socket.send(msg_bytes) 286 | 287 | # Waiting for the command to take effect 288 | reply_msg_bytes = self.ctr_iface_socket.recv(128) 289 | 290 | self.logger.debug("Control interface communication finished") 291 | self.ctr_iface_thread_lock.release() 292 | 293 | status = reply_msg_bytes[0:4].decode() 294 | if status == "FNSD": 295 | self.logger.info("Reconfiguration succesfully finished") 296 | que_data_packet = [] 297 | que_data_packet.append(['config-ok',]) 298 | self.data_que.put(que_data_packet) 299 | 300 | else: 301 | self.logger.error("Failed to set the requested parameter, reply: {0}".format(status)) 302 | 303 | def set_center_freq(self, center_freq): 304 | """ 305 | Configures the RF center frequency of the receiver through the control interface 306 | 307 | Paramters: 308 | ---------- 309 | :param: center_freq: Required center frequency to set [Hz] 310 | :type: center_freq: float 311 | """ 312 | if self.receiver_connection_status: # Check connection 313 | self.daq_center_freq = int(center_freq) 314 | # Set center frequency 315 | cmd="FREQ" 316 | freq_bytes=pack("Q",int(center_freq)) 317 | msg_bytes=(cmd.encode()+freq_bytes+bytearray(116)) 318 | try: 319 | _thread.start_new_thread(self.ctr_iface_communication, (msg_bytes,)) 320 | except: 321 | errorMsg = sys.exc_info()[0] 322 | self.logger.error("Unable to start communication thread") 323 | self.logger.error("Error message: {:s}".format(errorMsg)) 324 | 325 | def set_if_gain(self, gain): 326 | """ 327 | Configures the IF gain of the receiver through the control interface 328 | 329 | Paramters: 330 | ---------- 331 | :param: gain: IF gain value [dB] 332 | :type: gain: int 333 | """ 334 | if self.receiver_connection_status: # Check connection 335 | self.daq_rx_gain = gain 336 | 337 | # Set center frequency 338 | cmd="GAIN" 339 | 340 | gain_list = [] 341 | for i in range(0, self.M): 342 | gain_list.append(int(gain[i]*10)) 343 | 344 | #gain_list=[297, 37] #[int(gain*10)]*self.M 345 | gain_bytes=pack("I"*self.M, *gain_list) 346 | msg_bytes=(cmd.encode()+gain_bytes+bytearray(128-(self.M+1)*4)) 347 | try: 348 | _thread.start_new_thread(self.ctr_iface_communication, (msg_bytes,)) 349 | except: 350 | errorMsg = sys.exc_info()[0] 351 | self.logger.error("Unable to start communication thread") 352 | self.logger.error("Error message: {:s}".format(errorMsg)) 353 | 354 | def close(self): 355 | """ 356 | Disconnet the receiver module and the DAQ FW 357 | """ 358 | self.eth_close() 359 | 360 | -------------------------------------------------------------------------------- /_signal_processing/krakenSDR_signal_processor.py: -------------------------------------------------------------------------------- 1 | # KrakenSDR Signal Processor 2 | # 3 | # Copyright (C) 2018-2021 Carl Laufer, Tamás Pető 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | # 18 | # 19 | # - coding: utf-8 -*- 20 | 21 | # Import built-in modules 22 | import sys 23 | import os 24 | import time 25 | import logging 26 | import threading 27 | import queue 28 | import math 29 | import multiprocessing 30 | 31 | # Import optimization modules 32 | import numba as nb 33 | from numba import jit, njit 34 | from functools import lru_cache 35 | 36 | # Math support 37 | import numpy as np 38 | import numpy.linalg as lin 39 | #from numba import jit 40 | import pyfftw 41 | 42 | # Signal processing support 43 | import scipy 44 | from scipy import fft 45 | from scipy import signal 46 | from scipy.signal import correlate 47 | from scipy.signal import convolve 48 | 49 | from pyapril import channelPreparation as cp 50 | from pyapril import clutterCancellation as cc 51 | from pyapril import detector as det 52 | 53 | c_dtype = np.complex64 54 | 55 | #import socket 56 | # UDP is useless to us because it cannot work over mobile internet 57 | 58 | # Init UDP 59 | #server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) 60 | #server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) 61 | # Enable broadcasting mode 62 | #server.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) 63 | # Set a timeout so the socket does not block 64 | # indefinitely when trying to receive data. 65 | #server.settimeout(0.2) 66 | 67 | class SignalProcessor(threading.Thread): 68 | 69 | def __init__(self, data_que, module_receiver, logging_level=10): 70 | 71 | """ 72 | Parameters: 73 | ----------- 74 | :param: data_que: Que to communicate with the UI (web iface/Qt GUI) 75 | :param: module_receiver: Kraken SDR DoA DSP receiver modules 76 | """ 77 | super(SignalProcessor, self).__init__() 78 | self.logger = logging.getLogger(__name__) 79 | self.logger.setLevel(logging_level) 80 | 81 | root_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) 82 | #doa_res_file_path = os.path.join(os.path.join(root_path,"_android_web","DOA_value.html")) 83 | #self.DOA_res_fd = open(doa_res_file_path,"w+") 84 | 85 | self.module_receiver = module_receiver 86 | self.data_que = data_que 87 | self.en_spectrum = False 88 | self.en_record = False 89 | self.en_DOA_estimation = True 90 | self.first_frame = 1 # Used to configure local variables from the header fields 91 | self.processed_signal = np.empty(0) 92 | 93 | # Squelch feature 94 | self.data_ready = False 95 | 96 | # DOA processing options 97 | self.en_DOA_Bartlett = False 98 | self.en_DOA_Capon = False 99 | self.en_DOA_MEM = False 100 | self.en_DOA_MUSIC = False 101 | self.en_DOA_FB_avg = False 102 | self.DOA_offset = 0 103 | self.DOA_inter_elem_space = 0.5 104 | self.DOA_ant_alignment = "ULA" 105 | self.DOA_theta = np.linspace(0,359,360) 106 | 107 | # PR processing options 108 | self.PR_clutter_cancellation = "Wiener MRE" 109 | self.max_bistatic_range = 128 110 | self.max_doppler = 256 111 | self.en_PR = True 112 | 113 | 114 | # Processing parameters 115 | self.spectrum_window_size = 2048 #1024 116 | self.spectrum_window = "hann" 117 | self.run_processing = False 118 | self.is_running = False 119 | 120 | 121 | self.channel_number = 4 # Update from header 122 | 123 | # Result vectors 124 | self.DOA_Bartlett_res = np.ones(181) 125 | self.DOA_Capon_res = np.ones(181) 126 | self.DOA_MEM_res = np.ones(181) 127 | self.DOA_MUSIC_res = np.ones(181) 128 | self.DOA_theta = np.arange(0,181,1) 129 | 130 | self.max_index = 0 131 | self.max_frequency = 0 132 | self.fft_signal_width = 0 133 | 134 | self.DOA_theta = np.linspace(0,359,360) 135 | 136 | self.spectrum = None #np.ones((self.channel_number+2,N), dtype=np.float32) 137 | self.spectrum_upd_counter = 0 138 | 139 | def run(self): 140 | """ 141 | Main processing thread 142 | """ 143 | 144 | pyfftw.config.NUM_THREADS = multiprocessing.cpu_count() 145 | pyfftw.config.PLANNER_EFFORT = "FFTW_MEASURE" #"FFTW_PATIENT" 146 | scipy.fft.set_backend(pyfftw.interfaces.scipy_fft) 147 | pyfftw.interfaces.cache.enable() 148 | 149 | 150 | while True: 151 | self.is_running = False 152 | time.sleep(1) 153 | while self.run_processing: 154 | self.is_running = True 155 | 156 | que_data_packet = [] 157 | 158 | #-----> ACQUIRE NEW DATA FRAME <----- 159 | self.module_receiver.get_iq_online() 160 | 161 | start_time = time.time() 162 | 163 | # Check frame type for processing 164 | en_proc = (self.module_receiver.iq_header.frame_type == self.module_receiver.iq_header.FRAME_TYPE_DATA)# or \ 165 | #(self.module_receiver.iq_header.frame_type == self.module_receiver.iq_header.FRAME_TYPE_CAL)# For debug purposes 166 | """ 167 | You can enable here to process other frame types (such as call type frames) 168 | """ 169 | 170 | que_data_packet.append(['iq_header',self.module_receiver.iq_header]) 171 | self.logger.debug("IQ header has been put into the data que entity") 172 | 173 | # Configure processing parameteres based on the settings of the DAQ chain 174 | if self.first_frame: 175 | self.channel_number = self.module_receiver.iq_header.active_ant_chs 176 | self.spectrum_upd_counter = 0 177 | self.spectrum = np.ones((self.channel_number+1, self.spectrum_window_size), dtype=np.float32) 178 | self.first_frame = 0 179 | 180 | decimation_factor = 1 181 | 182 | self.data_ready = False 183 | 184 | if en_proc: 185 | self.processed_signal = self.module_receiver.iq_samples 186 | self.data_ready = True 187 | 188 | first_decimation_factor = 1 #480 189 | 190 | # TESTING: DSP side main decimation - significantly slower than NE10 but it works ok-ish 191 | #decimated_signal = signal.decimate(self.processed_signal, first_decimation_factor, n = 584, ftype='fir', zero_phase=True) #first_decimation_factor * 2, ftype='fir') 192 | #self.processed_signal = decimated_signal #.copy() 193 | #spectrum_signal = decimated_signal.copy() 194 | 195 | max_amplitude = -100 196 | 197 | #max_ch = np.argmax(np.max(self.spectrum[1:self.module_receiver.iq_header.active_ant_chs+1,:], axis=1)) # Find the channel that had the max amplitude 198 | max_amplitude = 0 #np.max(self.spectrum[1+max_ch, :]) #Max amplitude out of all 5 channels 199 | #max_spectrum = self.spectrum[1+max_ch, :] #Send max ch to channel centering 200 | 201 | que_data_packet.append(['max_amplitude',max_amplitude]) 202 | 203 | #-----> SPECTRUM PROCESSING <----- 204 | 205 | if self.en_spectrum and self.data_ready: 206 | 207 | spectrum_samples = self.module_receiver.iq_samples #spectrum_signal #self.processed_signal #self.module_receiver.iq_samples #self.processed_signal 208 | 209 | N = self.spectrum_window_size 210 | 211 | N_perseg = 0 212 | N_perseg = min(N, len(self.processed_signal[0,:])//25) 213 | N_perseg = N_perseg // 1 214 | 215 | for m in range(self.channel_number): 216 | # Get power spectrum 217 | f, Pxx_den = signal.welch(self.processed_signal[m, :], self.module_receiver.iq_header.sampling_freq//first_decimation_factor, 218 | nperseg=N_perseg, 219 | nfft=N, 220 | noverlap=0, #int(N_perseg*0.25), 221 | detrend=False, 222 | return_onesided=False, 223 | window= ('tukey', 0.25), #tukey window gives better time resolution for squelching #self.spectrum_window, #('tukey', 0.25), #self.spectrum_window, 224 | #window=self.spectrum_window, 225 | scaling="spectrum") 226 | 227 | self.spectrum[1+m, :] = np.fft.fftshift(10*np.log10(Pxx_den)) 228 | #self.spectrum[1:self.module_receiver.iq_header.active_ant_chs+1,:] = np.fft.fftshift(10*np.log10(Pxx_den)) 229 | 230 | self.spectrum[0,:] = np.fft.fftshift(f) 231 | 232 | 233 | # Create signal window for plot 234 | # signal_window = np.ones(len(self.spectrum[1,:])) * -100 235 | # signal_window[max(self.max_index - self.fft_signal_width//2, 0) : min(self.max_index + self.fft_signal_width//2, len(self.spectrum[1,:]))] = max(self.spectrum[1,:]) 236 | #signal_window = np.ones(len(max_spectrum)) * -100 237 | #signal_window[max(self.max_index - self.fft_signal_width//2, 0) : min(self.max_index + self.fft_signal_width//2, len(max_spectrum))] = max(max_spectrum) 238 | 239 | #self.spectrum[self.channel_number+1, :] = signal_window #np.ones(len(spectrum[1,:])) * self.module_receiver.daq_squelch_th_dB # Plot threshold line 240 | que_data_packet.append(['spectrum', self.spectrum]) 241 | 242 | #-----> Passive Radar <----- 243 | conf_val = 0 244 | theta_0 = 0 245 | if self.en_PR and self.data_ready and self.channel_number > 1: 246 | 247 | ref_ch = self.module_receiver.iq_samples[0,:] 248 | surv_ch = self.module_receiver.iq_samples[1,:] 249 | 250 | td_filter_dimension = self.max_bistatic_range 251 | 252 | 253 | start = time.time() 254 | 255 | if self.PR_clutter_cancellation == "Wiener MRE": 256 | surv_ch, w = Wiener_SMI_MRE(ref_ch, surv_ch, td_filter_dimension) 257 | #surv_ch, w = cc.Wiener_SMI_MRE(ref_ch, surv_ch, td_filter_dimension) 258 | 259 | end = time.time() 260 | print("Time: " + str((end-start) * 1000)) 261 | 262 | surv_ch = numba_mult(surv_ch, get_window(surv_ch.size)) #surv_ch * get_window(surv_ch.size) #det.windowing(surv_ch, "Hamming") #surv_ch * signal.tukey(surv_ch.size, alpha=0.25) #det.windowing(surv_ch, "hamming") 263 | 264 | max_Doppler = self.max_doppler #256 265 | max_range = self.max_bistatic_range 266 | 267 | #RD_matrix = det.cc_detector_ons(ref_ch, surv_ch, self.module_receiver.iq_header.sampling_freq, max_Doppler, max_range, verbose=0, Qt_obj=None) 268 | RD_matrix = cc_detector_ons(ref_ch, surv_ch, self.module_receiver.iq_header.sampling_freq, max_Doppler, max_range) 269 | 270 | 271 | que_data_packet.append(['RD_matrix', RD_matrix]) 272 | 273 | # Record IQ samples 274 | if self.en_record: 275 | # TODO: Implement IQ frame recording 276 | self.logger.error("Saving IQ samples to npy is obsolete, IQ Frame saving is currently not implemented") 277 | 278 | stop_time = time.time() 279 | que_data_packet.append(['update_rate', stop_time-start_time]) 280 | que_data_packet.append(['latency', int(stop_time*10**3)-self.module_receiver.iq_header.time_stamp]) 281 | 282 | # If the que is full, and data is ready (from squelching), clear the buffer immediately so that useful data has the priority 283 | #if self.data_que.full() and self.data_ready: 284 | # try: 285 | # #self.logger.info("BUFFER WAS NOT EMPTY, EMPTYING NOW") 286 | # self.data_que.get(False) #empty que if not taken yet so fresh data is put in 287 | # except queue.Empty: 288 | # #self.logger.info("DIDNT EMPTY") 289 | # pass 290 | 291 | # Put data into buffer, but if there is no data because its a cal/trig wait frame etc, then only write if the buffer is empty 292 | # Otherwise just discard the data so that we don't overwrite good DATA frames. 293 | try: 294 | self.data_que.put(que_data_packet, False) # Must be non-blocking so DOA can update when dash browser window is closed 295 | except: 296 | # Discard data, UI couldn't consume fast enough 297 | pass 298 | 299 | """ 300 | start = time.time() 301 | end = time.time() 302 | thetime = ((end - start) * 1000) 303 | print ("Time elapsed: ", thetime) 304 | """ 305 | @njit(fastmath=True, parallel=True, cache=True) 306 | def numba_mult(a,b): 307 | return a * b 308 | 309 | @jit(fastmath=True) 310 | def Wiener_SMI_MRE(ref_ch, surv_ch, K): 311 | """ 312 | Description: 313 | ------------ 314 | Performs Wiener filtering with applying the Minimum Redundance Estimation (MRE) technique. 315 | When using MRE, the autocorrelation matrix is not fully estimated, but only the first column. 316 | With this modification the required calculations can be reduced from KxK to K element. 317 | 318 | Parameters: 319 | ----------- 320 | :param K : Filter tap number 321 | :param ref_ch : Reference signal array 322 | :param surv_ch: Surveillance signal array 323 | 324 | :type K : int 325 | :type ref_ch : 1 x N complex numpy array 326 | :type surv_ch: 1 x N complex numpy array 327 | Return values: 328 | -------------- 329 | :return filt: Filtered surveillance channel 330 | :rtype filt: 1 x N complex numpy array 331 | 332 | :return None: Input parameters are not consistent 333 | """ 334 | 335 | N = ref_ch.shape[0] # Number of time samples 336 | R, r = pruned_correlation(ref_ch, surv_ch, K, N) 337 | R_mult = R_eye_memoize(K) 338 | w = fast_w(R, r, K, R_mult) 339 | 340 | #return surv_ch - np.convolve(ref_ch, w)[0:N], w # subtract the zero doppler clutter 341 | return surv_ch - signal.oaconvolve(ref_ch, w)[0:N], w # subtract the zero doppler clutter #oaconvolve saves us about 100-200 ms 342 | 343 | @njit(fastmath=True, parallel=True, cache=True) 344 | def fast_w(R, r, K, R_mult): 345 | # Complete the R matrix based on its Hermitian and Toeplitz property 346 | 347 | for k in nb.prange(1, K): 348 | R[:, k] = shift(R[:, 0], k) 349 | #R[:, K] = shift(R[:,0], K) 350 | 351 | R += np.transpose(np.conjugate(R)) 352 | R *= R_mult #(np.ones(K) - np.eye(K) * 0.5) 353 | 354 | #w = np.dot(lin.inv(R), r) # weight vector 355 | w = lin.inv(R) @ r #np.dot(lin.inv(R), r) # weight vector #matmul (@) may be slightly faster that np.dot for 1D, 2D arrays. 356 | # inverse and dot product run time : 1.1s for 2048*2048 matrix 357 | 358 | return w 359 | 360 | @lru_cache(maxsize=2) 361 | def get_window(size): 362 | return signal.hamming(size) 363 | 364 | #Memoize ~50ms speedup? 365 | @lru_cache(maxsize=2) 366 | def R_eye_memoize(K): 367 | return (np.ones(K) - np.eye(K) * 0.5) 368 | 369 | #Modified pruned correlation, returns R and r directly and saves one FFT 370 | @jit(fastmath=True, cache=True) 371 | def pruned_correlation(ref_ch, surv_ch, clen, N): 372 | """ 373 | Description: 374 | ----------- 375 | Calculates the part of the correlation function of arrays with same size 376 | The total length of the cross-correlation function is 2*N-1, but this 377 | function calculates the values of the cross-correlation between [N-1 : N+clen-1] 378 | Parameters: 379 | ----------- 380 | :param x : input array 381 | :param y : input array 382 | :param clen: correlation length 383 | 384 | :type x: 1 x N complex numpy array 385 | :type y: 1 x N complex numpy array 386 | :type clen: int 387 | Return values: 388 | -------------- 389 | :return corr : part of the cross-correlation function 390 | :rtype corr : 1 x clen complex numpy array 391 | 392 | :return None : inconsistent array size 393 | """ 394 | R = np.zeros((clen, clen), dtype=c_dtype) # Autocorrelation mtx. 395 | 396 | # --calculation-- 397 | # set up input matrices pad zeros if not multiply of the correlation length 398 | cols = clen - 1 #(clen = Filter drowsimension) 399 | rows = np.int32(N / (cols)) + 1 400 | 401 | zeropads = cols * rows - N 402 | x = np.pad(ref_ch, (0, zeropads)) 403 | 404 | # shaping inputs into matrices 405 | xp = np.reshape(x, (rows, cols)) 406 | 407 | # padding matrices for FFT 408 | ypp = np.vstack([xp[1:, :], np.zeros(cols, dtype=c_dtype)]) #vstack appears to be faster than pad 409 | yp = np.concatenate([xp, ypp], axis=1) 410 | 411 | #print("pruned corr xp shape: " + str(xp.shape)) 412 | #print("pruned corr yp shape: " + str(yp.shape)) 413 | 414 | # execute FFT on the matrices 415 | xpw = fft.fft(xp, n = 2*cols, axis=1, workers=4, overwrite_x=True) 416 | bpw = fft.fft(yp, axis=1, workers=4, overwrite_x=True) 417 | 418 | # magic formula which describes the unified equation of the universe 419 | # corr_batches = np.fliplr(fft.fftshift(fft.ifft(corr_mult(xpw, bpw), axis=1, workers=4, overwrite_x=True)).conj()[:, 0:clen]) 420 | corr_batches = fft.fftshift(fft.ifft(corr_mult(xpw, bpw), axis=1, workers=4, overwrite_x=True)).conj()[:, 0:clen] 421 | 422 | # sum each value in a column of the batched correlation matrix 423 | R[:,0] = np.fliplr([np.sum(corr_batches, axis=0)])[0] 424 | 425 | #calc r 426 | y = np.pad(surv_ch, (0, zeropads)) 427 | yp = np.reshape(y, (rows, cols)) 428 | ypp = np.vstack([yp[1:, :], np.zeros(cols, dtype=c_dtype)]) #vstack appears to be faster than pad 429 | yp = np.concatenate([yp, ypp], axis=1) 430 | bpw = fft.fft(yp, axis=1, workers=4, overwrite_x=True) 431 | #corr_batches = np.fliplr(fft.fftshift(fft.ifft(corr_mult(xpw, bpw), axis=1, workers=4, overwrite_x=True)).conj()[:, 0:clen]) 432 | corr_batches = fft.fftshift(fft.ifft(corr_mult(xpw, bpw), axis=1, workers=4, overwrite_x=True)).conj()[:, 0:clen] 433 | #r = np.sum(corr_batches, axis=0) 434 | r = np.fliplr([np.sum(corr_batches, axis=0)])[0] 435 | 436 | return R, r 437 | 438 | @njit(fastmath=True, cache=True) 439 | def shift(x, i): 440 | """ 441 | Description: 442 | ----------- 443 | Similar to np.roll function, but not circularly shift values 444 | Example: 445 | x = |x0|x1|...|xN-1| 446 | y = shift(x,2) 447 | x --> y: |0|0|x0|x1|...|xN-3| 448 | Parameters: 449 | ----------- 450 | :param:x : input array on which the roll will be performed 451 | :param i : delay value [sample] 452 | 453 | :type i :int 454 | :type x: N x 1 complex numpy array 455 | Return values: 456 | -------------- 457 | :return shifted : shifted version of x 458 | :rtype shifted: N x 1 complex numpy array 459 | """ 460 | 461 | N = x.shape[0] 462 | if np.abs(i) >= N: 463 | return np.zeros(N, dtype=c_dtype) 464 | if i == 0: 465 | return x 466 | shifted = np.roll(x, i) 467 | if i < 0: 468 | shifted[np.mod(N + i, N):] = np.zeros(np.abs(i), dtype=c_dtype) 469 | if i > 0: 470 | shifted[0:i] = np.zeros(np.abs(i), dtype=c_dtype) 471 | return shifted 472 | 473 | 474 | @njit(fastmath=True, parallel=True, cache=True) 475 | def resize_and_align(no_sub_tasks, ref_ch, surv_ch, fs, fD_max, r_max): 476 | surv_ch_align = np.reshape(surv_ch,(no_sub_tasks, r_max)) # shaping surveillance signal array into a matrix 477 | pad_zeros = np.expand_dims(np.zeros(r_max, dtype=c_dtype), axis=0) 478 | surv_ch_align = np.vstack((surv_ch_align, pad_zeros)) # padding one row of zeros into the surv matrix 479 | surv_ch_align = np.concatenate((surv_ch_align[0 : no_sub_tasks,:], surv_ch_align[1 : no_sub_tasks +1, :]), axis = 1) 480 | 481 | ref_ch_align = np.reshape(ref_ch, (no_sub_tasks, r_max)) # shaping reference signal array into a matrix 482 | pad_zeros = np.zeros((no_sub_tasks, r_max),dtype = c_dtype) 483 | ref_ch_align = np.concatenate((ref_ch_align, pad_zeros),axis = 1) # shaping 484 | 485 | return ref_ch_align, surv_ch_align 486 | 487 | @njit(fastmath=True, cache=True) 488 | def corr_mult(surv_fft, ref_fft): 489 | return np.multiply(surv_fft, ref_fft.conj()) 490 | 491 | #@jit(fastmath=True, cache=True) 492 | def cc_detector_ons(ref_ch, surv_ch, fs, fD_max, r_max): 493 | """ 494 | Parameters: 495 | ----------- 496 | :param N: Range resolution - N must be a divisor of the input length 497 | :param F: Doppler resolution, F has a theoretical limit. If you break the limit, the output may repeat 498 | itself and get wrong results. F should be less than length/N otherwise use other method! 499 | Return values: 500 | -------------- 501 | :return None: Improper input parameters 502 | 503 | """ 504 | N = ref_ch.size 505 | 506 | # --> Set processing parameters 507 | fD_step = fs / (2 * N) # Doppler frequency step size (with zero padding) 508 | Doppler_freqs_size = int(fD_max / fD_step) 509 | no_sub_tasks = N // r_max 510 | 511 | # Allocate range-Doppler maxtrix 512 | mx = np.zeros((2*Doppler_freqs_size+1, r_max),dtype = c_dtype) #memoize_zeros((2*Doppler_freqs_size+1, r_max), c_dtype) #np.zeros((2*Doppler_freqs_size+1, r_max),dtype = nb.c8) 513 | 514 | ref_ch_align, surv_ch_align = resize_and_align(no_sub_tasks, ref_ch, surv_ch, fs, fD_max, r_max) 515 | 516 | #print("ref_ch_align shape: " + str(ref_ch_align.shape)) 517 | #print("surv_ch_align shape: " + str(surv_ch_align.shape)) 518 | 519 | # row wise fft on both channels 520 | ref_fft = fft.fft(ref_ch_align, axis = 1, overwrite_x=True, workers=4) #pyfftw.interfaces.numpy_fft.fft(ref_ch_align_a, axis = 1, overwrite_input=True, threads=4) #fft.fft(ref_ch_align_a, axis = 1, overwrite_x=True, workers=4) 521 | surv_fft = fft.fft(surv_ch_align, axis = 1, overwrite_x=True, workers=4) #pyfftw.interfaces.numpy_fft.fft(surv_ch_align_a, axis = 1, overwrite_input=True, threads=4) #fft.fft(surv_ch_align_a, axis = 1, overwrite_x=True, workers=4) 522 | 523 | corr = corr_mult(surv_fft, ref_fft) #np.multiply(surv_fft, ref_fft.conj()) 524 | 525 | corr = fft.ifft(corr,axis = 1, workers=4, overwrite_x=True) 526 | 527 | corr_a = pyfftw.empty_aligned(np.shape(corr), dtype=c_dtype) 528 | corr_a[:] = corr #.copy() 529 | 530 | #with scipy.fft.set_backend(pyfftw.interfaces.scipy_fft): 531 | # This is the most computationally intensive part ~120ms, overwrite_x=True gives a big speedup, not sure if it changes the result though... 532 | corr = fft.fft(corr_a, n=2* no_sub_tasks, axis = 0, workers=4, overwrite_x=True) # Setting the output size with "n=.." is faster than doing a concat first. 533 | 534 | # crop and fft shift 535 | mx[ 0 : Doppler_freqs_size, 0 : r_max] = corr[2*no_sub_tasks - Doppler_freqs_size : 2*no_sub_tasks, 0 : r_max] 536 | mx[Doppler_freqs_size : 2 * Doppler_freqs_size+1, 0 : r_max] = corr[ 0 : Doppler_freqs_size+1 , 0 : r_max] 537 | 538 | return mx 539 | 540 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /_UI/_web_interface/kraken_web_interface.py: -------------------------------------------------------------------------------- 1 | # KrakenSDR Signal Processor 2 | # 3 | # Copyright (C) 2018-2021 Carl Laufer, Tamás Pető 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | # 18 | # 19 | # - coding: utf-8 -*- 20 | 21 | # Import built-in modules 22 | import logging 23 | import os 24 | import sys 25 | import queue 26 | import time 27 | import subprocess 28 | import json 29 | # Import third-party modules 30 | 31 | import dash_core_components as dcc 32 | import dash_html_components as html 33 | 34 | import dash_devices as dash 35 | from dash_devices.dependencies import Input, Output, State 36 | 37 | from dash.exceptions import PreventUpdate 38 | from dash.dash import no_update 39 | import plotly.graph_objects as go 40 | import plotly.express as px 41 | import numpy as np 42 | from configparser import ConfigParser 43 | from numba import njit, jit 44 | 45 | from threading import Timer 46 | 47 | # Import Kraken SDR modules 48 | current_path = os.path.dirname(os.path.realpath(__file__)) 49 | root_path = os.path.dirname(os.path.dirname(current_path)) 50 | receiver_path = os.path.join(root_path, "_receiver") 51 | signal_processor_path = os.path.join(root_path, "_signal_processing") 52 | ui_path = os.path.join(root_path, "_UI") 53 | 54 | sys.path.insert(0, receiver_path) 55 | sys.path.insert(0, signal_processor_path) 56 | sys.path.insert(0, ui_path) 57 | 58 | daq_subsystem_path = os.path.join( 59 | os.path.join(os.path.dirname(root_path), 60 | "heimdall_daq_fw"), 61 | "Firmware") 62 | daq_preconfigs_path = os.path.join( 63 | os.path.join(os.path.dirname(root_path), 64 | "heimdall_daq_fw"), 65 | "config_files") 66 | daq_config_filename = os.path.join(daq_subsystem_path, "daq_chain_config.ini") 67 | daq_stop_filename = "daq_stop.sh" 68 | daq_start_filename = "daq_start_sm.sh" 69 | #daq_start_filename = "daq_synthetic_start.sh" 70 | sys.path.insert(0, daq_subsystem_path) 71 | 72 | settings_file_path = os.path.join(root_path, "settings.json") 73 | # Load settings file 74 | settings_found = False 75 | if os.path.exists(settings_file_path): 76 | settings_found = True 77 | with open(settings_file_path, 'r') as myfile: 78 | dsp_settings = json.loads(myfile.read()) 79 | 80 | import ini_checker 81 | from krakenSDR_receiver import ReceiverRTLSDR 82 | from krakenSDR_signal_processor import SignalProcessor 83 | 84 | import tooltips 85 | 86 | class webInterface(): 87 | 88 | def __init__(self): 89 | self.user_interface = None 90 | self.logging_level = dsp_settings.get("logging_level", 0)*10 91 | logging.basicConfig(level=self.logging_level) 92 | self.logger = logging.getLogger(__name__) 93 | self.logger.setLevel(self.logging_level) 94 | self.logger.info("Inititalizing web interface ") 95 | if not settings_found: 96 | self.logger.warning("Web Interface settings file is not found!") 97 | 98 | ############################################# 99 | # Initialize and Configure Kraken modules # 100 | ############################################# 101 | 102 | # Web interface internal 103 | self.disable_tooltips = dsp_settings.get("disable_tooltips", 0) #settings.disable_tooltips 104 | self.page_update_rate = 1 105 | self._avg_win_size = 10 106 | self._update_rate_arr = None 107 | 108 | self.sp_data_que = queue.Queue(1) # Que to communicate with the signal processing module 109 | self.rx_data_que = queue.Queue(1) # Que to communicate with the receiver modules 110 | 111 | self.data_interface = dsp_settings.get("data_interface", "shmem") 112 | 113 | # Instantiate and configure Kraken SDR modules 114 | self.module_receiver = ReceiverRTLSDR(data_que=self.rx_data_que, data_interface=self.data_interface, logging_level=self.logging_level) 115 | self.module_receiver.daq_center_freq = dsp_settings.get("center_freq", 100.0) * 10**6 116 | self.module_receiver.daq_rx_gain = [float(dsp_settings.get("gain_1", 1.4)), float(dsp_settings.get("gain_2", 1.4))] 117 | self.module_receiver.rec_ip_addr = dsp_settings.get("default_ip", "0.0.0.0") 118 | 119 | self.module_signal_processor = SignalProcessor(data_que=self.sp_data_que, module_receiver=self.module_receiver, logging_level=self.logging_level) 120 | self.module_signal_processor.en_PR = dsp_settings.get("en_pr", True) 121 | self.module_signal_processor.PR_clutter_cancellation = dsp_settings.get("clutter_cancel_algo", "Wiener MRE") 122 | self.module_signal_processor.max_bistatic_range = dsp_settings.get("max_bistatic_range", 128) 123 | self.module_signal_processor.max_doppler = dsp_settings.get("max_doppler", 256) 124 | self.en_persist = dsp_settings.get("en_pr_persist", True) 125 | self.pr_persist_decay = dsp_settings.get("pr_persist_decay", 0.99) 126 | self.pr_dynamic_range_min = dsp_settings.get("pr_dynrange_min", -20) 127 | self.pr_dynamic_range_max = dsp_settings.get("pr_dynrange_max", 10) 128 | 129 | self.module_signal_processor.start() 130 | 131 | ############################################# 132 | # UI Status and Config variables # 133 | ############################################# 134 | 135 | # DAQ Subsystem status parameters 136 | self.daq_conn_status = 0 137 | self.daq_cfg_iface_status = 0 # 0- ready, 1-busy 138 | self.daq_restart = 0 # 1-restarting 139 | self.daq_update_rate = 0 140 | self.daq_frame_sync = 1 # Active low 141 | self.daq_frame_index = 0 142 | self.daq_frame_type = "-" 143 | self.daq_power_level = 0 144 | self.daq_sample_delay_sync = 0 145 | self.daq_iq_sync = 0 146 | self.daq_noise_source_state= 0 147 | self.daq_center_freq = dsp_settings.get("center_freq", 100.0) 148 | self.daq_adc_fs = "-" 149 | self.daq_fs = "-" 150 | self.daq_cpi = "-" 151 | self.daq_if_gains ="[,,,,]" 152 | self.en_advanced_daq_cfg = False 153 | self.daq_ini_cfg_dict = read_config_file_dict() 154 | 155 | self.active_daq_ini_cfg = self.daq_ini_cfg_dict['config_name'] #"Default" # Holds the string identifier of the actively loaded DAQ ini configuration 156 | self.tmp_daq_ini_cfg = "Default" 157 | self.daq_cfg_ini_error = "" 158 | 159 | # DSP Processing Parameters and Results 160 | self.spectrum = None 161 | self.daq_dsp_latency = 0 # [ms] 162 | self.logger.info("Web interface object initialized") 163 | 164 | # Passive Radar Data 165 | self.RD_matrix = None 166 | 167 | self.dsp_timer = None 168 | self.update_time = 9999 169 | 170 | self.pathname = "" 171 | self.reset_doa_graph_flag = False 172 | self.reset_spectrum_graph_flag = False 173 | self.CAFMatrixPersist = None 174 | 175 | # Basic DAQ Config 176 | self.decimated_bandwidth = 12.5 177 | 178 | if self.daq_ini_cfg_dict is not None: 179 | self.logger.info("Config file found and read succesfully") 180 | """ 181 | Set the number of channels in the receiver module because it is required 182 | to produce the initial gain configuration message (Only needed in shared-memory mode) 183 | """ 184 | self.module_receiver.M = self.daq_ini_cfg_dict['num_ch'] 185 | #self.module_receiver.M = self.daq_ini_cfg_params[1] 186 | 187 | 188 | def save_configuration(self): 189 | data = {} 190 | 191 | # DAQ Configuration 192 | data["center_freq"] = self.module_receiver.daq_center_freq/10**6 193 | data["gain_1"] = self.module_receiver.daq_rx_gain[0] 194 | data["gain_2"] = self.module_receiver.daq_rx_gain[1] 195 | data["data_interface"] = dsp_settings.get("data_interface", "shmem") #settings.data_interface 196 | data["default_ip"] = dsp_settings.get("default_ip", "0.0.0.0") #settings.default_ip 197 | 198 | # DOA Estimation 199 | data["en_pr"] = self.module_signal_processor.en_PR 200 | 201 | data["clutter_cancel_algo"] = self.module_signal_processor.PR_clutter_cancellation 202 | data["max_bistatic_range"] = self.module_signal_processor.max_bistatic_range 203 | data["max_doppler"] = self.module_signal_processor.max_doppler 204 | data["en_pr_persist"] = self.en_persist 205 | data["pr_persist_decay"] = self.pr_persist_decay 206 | data["pr_dynrange_min"] = self.pr_dynamic_range_min 207 | data["pr_dynrange_max"] = self.pr_dynamic_range_max 208 | 209 | # Web Interface 210 | data["en_hw_check"] = dsp_settings.get("en_hw_check", 0) #settings.en_hw_check 211 | data["en_advanced_daq_cfg"] = self.en_advanced_daq_cfg 212 | data["logging_level"] = dsp_settings.get("logging_level", 0) #settings.logging_level 213 | data["disable_tooltips"] = dsp_settings.get("disable_tooltips", 0) #settings.disable_tooltips 214 | 215 | #settings.write(data) 216 | with open(settings_file_path, 'w') as outfile: 217 | json.dump(data, outfile, indent=2) 218 | 219 | 220 | def start_processing(self): 221 | """ 222 | Starts data processing 223 | 224 | Parameters: 225 | ----------- 226 | :param: ip_addr: Ip address of the DAQ Subsystem 227 | 228 | :type ip_addr : string e.g.:"127.0.0.1" 229 | """ 230 | self.logger.info("Start processing request") 231 | self.first_frame = 1 232 | #self.module_receiver.rec_ip_addr = "0.0.0.0" 233 | self.module_signal_processor.run_processing=True 234 | def stop_processing(self): 235 | self.module_signal_processor.run_processing=False 236 | while self.module_signal_processor.is_running: time.sleep(0.01) # Block until signal processor run_processing while loop ends 237 | def close_data_interfaces(self): 238 | self.module_receiver.eth_close() 239 | def close(self): 240 | pass 241 | def config_daq_rf(self, f0, gain): 242 | """ 243 | Configures the RF parameters in the DAQ module 244 | """ 245 | self.daq_cfg_iface_status = 1 246 | self.module_receiver.set_center_freq(int(f0*10**6)) 247 | self.module_receiver.set_if_gain(gain) 248 | 249 | webInterface_inst.logger.info("Updating receiver parameters") 250 | webInterface_inst.logger.info("Center frequency: {:f} MHz".format(f0)) 251 | #webInterface_inst.logger.info("Gain: {:f} dB".format(gain)) 252 | webInterface_inst.logger.info("Gain: " + ' '.join(str(x) for x in gain) + " dB") 253 | 254 | def read_config_file_dict(config_fname=daq_config_filename): 255 | parser = ConfigParser() 256 | found = parser.read([config_fname]) 257 | ini_data = {} 258 | if not found: 259 | return None 260 | 261 | ini_data['config_name'] = parser.get('meta', 'config_name') 262 | ini_data['num_ch'] = parser.getint('hw', 'num_ch') 263 | ini_data['en_bias_tee'] = parser.get('hw', 'en_bias_tee') 264 | ini_data['daq_buffer_size'] = parser.getint('daq','daq_buffer_size') 265 | ini_data['sample_rate'] = parser.getint('daq','sample_rate') 266 | ini_data['en_noise_source_ctr'] = parser.getint('daq','en_noise_source_ctr') 267 | ini_data['cpi_size'] = parser.getint('pre_processing', 'cpi_size') 268 | ini_data['decimation_ratio'] = parser.getint('pre_processing', 'decimation_ratio') 269 | ini_data['fir_relative_bandwidth'] = parser.getfloat('pre_processing', 'fir_relative_bandwidth') 270 | ini_data['fir_tap_size'] = parser.getint('pre_processing', 'fir_tap_size') 271 | ini_data['fir_window'] = parser.get('pre_processing','fir_window') 272 | ini_data['en_filter_reset'] = parser.getint('pre_processing','en_filter_reset') 273 | ini_data['corr_size'] = parser.getint('calibration','corr_size') 274 | ini_data['std_ch_ind'] = parser.getint('calibration','std_ch_ind') 275 | ini_data['en_iq_cal'] = parser.getint('calibration','en_iq_cal') 276 | ini_data['gain_lock_interval'] = parser.getint('calibration','gain_lock_interval') 277 | ini_data['require_track_lock_intervention'] = parser.getint('calibration','require_track_lock_intervention') 278 | ini_data['cal_track_mode'] = parser.getint('calibration','cal_track_mode') 279 | ini_data['amplitude_cal_mode'] = parser.get('calibration','amplitude_cal_mode') 280 | ini_data['cal_frame_interval'] = parser.getint('calibration','cal_frame_interval') 281 | ini_data['cal_frame_burst_size'] = parser.getint('calibration','cal_frame_burst_size') 282 | ini_data['amplitude_tolerance'] = parser.getint('calibration','amplitude_tolerance') 283 | ini_data['phase_tolerance'] = parser.getint('calibration','phase_tolerance') 284 | ini_data['maximum_sync_fails'] = parser.getint('calibration','maximum_sync_fails') 285 | 286 | ini_data['out_data_iface_type'] = parser.get('data_interface','out_data_iface_type') 287 | 288 | return ini_data 289 | 290 | 291 | def write_config_file_dict(param_dict): 292 | webInterface_inst.logger.info("Write config file: {0}".format(param_dict)) 293 | parser = ConfigParser() 294 | found = parser.read([daq_config_filename]) 295 | if not found: 296 | return -1 297 | 298 | parser['meta']['config_name']=str(param_dict['config_name']) 299 | parser['hw']['num_ch']=str(param_dict['num_ch']) 300 | parser['hw']['en_bias_tee']=str(param_dict['en_bias_tee']) 301 | parser['daq']['daq_buffer_size']=str(param_dict['daq_buffer_size']) 302 | parser['daq']['sample_rate']=str(param_dict['sample_rate']) 303 | parser['daq']['en_noise_source_ctr']=str(param_dict['en_noise_source_ctr']) 304 | # Set these for reconfigure 305 | parser['daq']['center_freq']=str(int(webInterface_inst.module_receiver.daq_center_freq)) 306 | parser['pre_processing']['cpi_size']=str(param_dict['cpi_size']) 307 | parser['pre_processing']['decimation_ratio']=str(param_dict['decimation_ratio']) 308 | parser['pre_processing']['fir_relative_bandwidth']=str(param_dict['fir_relative_bandwidth']) 309 | parser['pre_processing']['fir_tap_size']=str(param_dict['fir_tap_size']) 310 | parser['pre_processing']['fir_window']=str(param_dict['fir_window']) 311 | parser['pre_processing']['en_filter_reset']=str(param_dict['en_filter_reset']) 312 | parser['calibration']['corr_size']=str(param_dict['corr_size']) 313 | parser['calibration']['std_ch_ind']=str(param_dict['std_ch_ind']) 314 | parser['calibration']['en_iq_cal']=str(param_dict['en_iq_cal']) 315 | parser['calibration']['gain_lock_interval']=str(param_dict['gain_lock_interval']) 316 | parser['calibration']['require_track_lock_intervention']=str(param_dict['require_track_lock_intervention']) 317 | parser['calibration']['cal_track_mode']=str(param_dict['cal_track_mode']) 318 | parser['calibration']['amplitude_cal_mode']=str(param_dict['amplitude_cal_mode']) 319 | parser['calibration']['cal_frame_interval']=str(param_dict['cal_frame_interval']) 320 | parser['calibration']['cal_frame_burst_size']=str(param_dict['cal_frame_burst_size']) 321 | parser['calibration']['amplitude_tolerance']=str(param_dict['amplitude_tolerance']) 322 | parser['calibration']['phase_tolerance']=str(param_dict['phase_tolerance']) 323 | parser['calibration']['maximum_sync_fails']=str(param_dict['maximum_sync_fails']) 324 | 325 | ini_parameters = parser._sections 326 | 327 | error_list = ini_checker.check_ini(ini_parameters, dsp_settings.get("en_hw_check", 0)) #settings.en_hw_check) 328 | if len(error_list): 329 | for e in error_list: 330 | webInterface_inst.logger.error(e) 331 | return -1, error_list 332 | else: 333 | with open(daq_config_filename, 'w') as configfile: 334 | parser.write(configfile) 335 | return 0, [] 336 | 337 | def get_preconfigs(config_files_path): 338 | parser = ConfigParser() 339 | preconfigs = [] 340 | preconfigs.append([daq_config_filename, "Current"]) 341 | for root, dirs, files in os.walk(config_files_path): 342 | if len(files): 343 | config_file_path = os.path.join(root, files[0]) 344 | parser.read([config_file_path]) 345 | parameters = parser._sections 346 | preconfigs.append([config_file_path, parameters['meta']['config_name']]) 347 | return preconfigs 348 | 349 | 350 | ############################################# 351 | # Prepare Dash application # 352 | ############################################ 353 | webInterface_inst = webInterface() 354 | 355 | ############################################# 356 | # Prepare component dependencies # 357 | ############################################# 358 | 359 | trace_colors = px.colors.qualitative.Plotly 360 | trace_colors[3] = 'rgb(255,255,51)' 361 | valid_fir_windows = ['boxcar', 'triang', 'blackman', 'hamming', 'hann', 'bartlett', 'flattop', 'parzen' , 'bohman', 'blackmanharris', 'nuttall', 'barthann'] 362 | valid_sample_rates = [0.25, 0.900001, 1.024, 1.4, 1.8, 1.92, 2.048, 2.4, 2.56, 3.2] 363 | valid_daq_buffer_sizes = (2**np.arange(10,21,1)).tolist() 364 | calibration_tack_modes = [['No tracking',0] , ['Periodic tracking',2]] 365 | doa_trace_colors = { 366 | "DoA Bartlett": "#00B5F7", 367 | "DoA Capon" : "rgb(226,26,28)", 368 | "DoA MEM" : "#1CA71C", 369 | "DoA MUSIC" : "rgb(257,233,111)" 370 | } 371 | figure_font_size = 20 372 | 373 | y=np.random.normal(0,1,2**3) 374 | x=np.arange(2**3) 375 | 376 | fig_layout = go.Layout( 377 | paper_bgcolor='rgba(0,0,0,0)', 378 | plot_bgcolor='rgba(0,0,0,0)', 379 | template='plotly_dark', 380 | showlegend=True, 381 | margin=go.layout.Margin( 382 | t=0 #top margin 383 | ) 384 | ) 385 | 386 | fig_dummy = go.Figure(layout=fig_layout) 387 | 388 | for m in range(0, webInterface_inst.module_receiver.M+1): #+1 for the auto decimation window selection 389 | fig_dummy.add_trace(go.Scatter(x=x, 390 | y=y, 391 | name="Channel {:d}".format(m), 392 | line = dict(color = trace_colors[m], 393 | width = 2) 394 | )) 395 | 396 | 397 | fig_dummy.update_xaxes(title_text="Frequency [MHz]") 398 | fig_dummy.update_yaxes(title_text="Amplitude [dB]") 399 | 400 | option = [{"label":"", "value": 1}] 401 | 402 | spectrum_fig = go.Figure(layout=fig_layout) 403 | 404 | for m in range(0, webInterface_inst.module_receiver.M): 405 | spectrum_fig.add_trace(go.Scattergl(x=x, 406 | y=y, 407 | name="Channel {:d}".format(m), 408 | line = dict(color = trace_colors[m], 409 | width = 2) 410 | )) 411 | 412 | 413 | waterfall_init = [[-80] * webInterface_inst.module_signal_processor.spectrum_window_size] * 50 414 | waterfall_fig = go.Figure(layout=fig_layout) 415 | waterfall_fig.add_trace(go.Heatmapgl( 416 | z=waterfall_init, 417 | zsmooth=False, 418 | showscale=False, 419 | hoverinfo='skip', 420 | colorscale=[[0.0, '#000020'], 421 | [0.0714, '#000030'], 422 | [0.1428, '#000050'], 423 | [0.2142, '#000091'], 424 | [0.2856, '#1E90FF'], 425 | [0.357, '#FFFFFF'], 426 | [0.4284, '#FFFF00'], 427 | [0.4998, '#FE6D16'], 428 | [0.5712, '#FE6D16'], 429 | [0.6426, '#FF0000'], 430 | [0.714, '#FF0000'], 431 | [0.7854, '#C60000'], 432 | [0.8568, '#9F0000'], 433 | [0.9282, '#750000'], 434 | [1.0, '#4A0000']])) 435 | 436 | 437 | waterfall_fig.update_xaxes(tickfont_size=1) 438 | waterfall_fig.update_yaxes(tickfont_size=1) 439 | waterfall_fig.update_layout(margin=go.layout.Margin(t=5)) 440 | 441 | 442 | 443 | pr_init = [[-80] * 128] * 128 444 | y_range = list(range(-128, 128)) 445 | 446 | pr_fig = go.Figure(layout=fig_layout) 447 | pr_fig.add_trace(go.Heatmap( 448 | z=pr_init, 449 | y=y_range, 450 | zsmooth='best', #False, 451 | #zsmooth=False, #False, 452 | showscale=False, 453 | #hoverinfo='skip', 454 | colorscale=[[0.0, '#000020'], 455 | [0.0714, '#000030'], 456 | [0.1428, '#000050'], 457 | [0.2142, '#000091'], 458 | [0.2856, '#1E90FF'], 459 | [0.357, '#FFFFFF'], 460 | [0.4284, '#FFFF00'], 461 | [0.4998, '#FE6D16'], 462 | [0.5712, '#FE6D16'], 463 | [0.6426, '#FF0000'], 464 | [0.714, '#FF0000'], 465 | [0.7854, '#C60000'], 466 | [0.8568, '#9F0000'], 467 | [0.9282, '#750000'], 468 | [1.0, '#4A0000']])) 469 | 470 | 471 | #app = dash.Dash(__name__, suppress_callback_exceptions=True, compress=True, update_title="") # cannot use update_title with dash_devices 472 | app = dash.Dash(__name__, suppress_callback_exceptions=True, compress=True) 473 | 474 | # app_log = logger.getLogger('werkzeug') 475 | # app_log.setLevel(settings.logging_level*10) 476 | # app_log.setLevel(30) # TODO: Only during dev time 477 | app.layout = html.Div([ 478 | dcc.Location(id='url', children='/config',refresh=False), 479 | 480 | html.Div([html.Img(src="assets/kraken_interface_bw_pr.png", style={"display": "block", "margin-left": "auto", "margin-right": "auto", "height": "60px"})]), 481 | html.Div([html.A("Configuration", className="header_active" , id="header_config" ,href="/config"), 482 | html.A("Spectrum" , className="header_inactive" , id="header_spectrum",href="/spectrum"), 483 | html.A("Passive Radar" , className="header_inactive" , id="header_doa" ,href="/pr"), 484 | ], className="header"), 485 | 486 | html.Div(id="placeholder_start" , style={"display":"none"}), 487 | html.Div(id="placeholder_stop" , style={"display":"none"}), 488 | html.Div(id="placeholder_save" , style={"display":"none"}), 489 | html.Div(id="placeholder_update_rx" , style={"display":"none"}), 490 | html.Div(id="placeholder_recofnig_daq" , style={"display":"none"}), 491 | html.Div(id="placeholder_update_daq_ini_params", style={"display":"none"}), 492 | html.Div(id="placeholder_update_freq" , style={"display":"none"}), 493 | html.Div(id="placeholder_update_dsp" , style={"display":"none"}), 494 | html.Div(id="placeholder_config_page_upd" , style={"display":"none"}), 495 | html.Div(id="placeholder_spectrum_page_upd" , style={"display":"none"}), 496 | html.Div(id="placeholder_doa_page_upd" , style={"display":"none"}), 497 | html.Div(id="dummy_output" , style={"display":"none"}), 498 | 499 | html.Div(id='page-content') 500 | ]) 501 | def generate_config_page_layout(webInterface_inst): 502 | # Read DAQ config file 503 | daq_cfg_dict = webInterface_inst.daq_ini_cfg_dict 504 | 505 | if daq_cfg_dict is not None: 506 | en_noise_src_values =[1] if daq_cfg_dict['en_noise_source_ctr'] else [] 507 | en_filter_rst_values =[1] if daq_cfg_dict['en_filter_reset'] else [] 508 | en_iq_cal_values =[1] if daq_cfg_dict['en_iq_cal'] else [] 509 | en_req_track_lock_values =[1] if daq_cfg_dict['require_track_lock_intervention'] else [] 510 | 511 | # Read available preconfig files 512 | preconfigs = get_preconfigs(daq_preconfigs_path) 513 | 514 | en_persist_values =[1] if webInterface_inst.en_persist else [] 515 | en_pr_values =[1] if webInterface_inst.module_signal_processor.en_PR else [] 516 | 517 | en_advanced_daq_cfg =[1] if webInterface_inst.en_advanced_daq_cfg else [] 518 | # Calulcate spacings 519 | wavelength= 300 / webInterface_inst.daq_center_freq 520 | 521 | ant_spacing_wavelength = webInterface_inst.module_signal_processor.DOA_inter_elem_space 522 | ant_spacing_meter = round(wavelength * ant_spacing_wavelength, 3) 523 | ant_spacing_feet = ant_spacing_meter*3.2808399 524 | ant_spacing_inch = ant_spacing_meter*39.3700787 525 | 526 | cfg_decimated_bw = ((daq_cfg_dict['sample_rate']) / daq_cfg_dict['decimation_ratio']) / 10**3 527 | cfg_data_block_len = ( daq_cfg_dict['cpi_size'] / (cfg_decimated_bw) ) 528 | cfg_recal_interval = (daq_cfg_dict['cal_frame_interval'] * (cfg_data_block_len/10**3)) / 60 529 | 530 | if daq_cfg_dict['cal_track_mode'] == 0: 531 | cfg_recal_interval = 1 532 | 533 | gain_list = [ 534 | {'label': '0 dB', 'value': 0}, 535 | {'label': '0.9 dB', 'value': 0.9}, 536 | {'label': '1.4 dB', 'value': 1.4}, 537 | {'label': '2.7 dB', 'value': 2.7}, 538 | {'label': '3.7 dB', 'value': 3.7}, 539 | {'label': '7.7 dB', 'value': 7.7}, 540 | {'label': '8.7 dB', 'value': 8.7}, 541 | {'label': '12.5 dB', 'value': 12.5}, 542 | {'label': '14.4 dB', 'value': 14.4}, 543 | {'label': '15.7 dB', 'value': 15.7}, 544 | {'label': '16.6 dB', 'value': 16.6}, 545 | {'label': '19.7 dB', 'value': 19.7}, 546 | {'label': '20.7 dB', 'value': 20.7}, 547 | {'label': '22.9 dB', 'value': 22.9}, 548 | {'label': '25.4 dB', 'value': 25.4}, 549 | {'label': '28.0 dB', 'value': 28.0}, 550 | {'label': '29.7 dB', 'value': 29.7}, 551 | {'label': '32.8 dB', 'value': 32.8}, 552 | {'label': '33.8 dB', 'value': 33.8}, 553 | {'label': '36.4 dB', 'value': 36.4}, 554 | {'label': '37.2 dB', 'value': 37.2}, 555 | {'label': '38.6 dB', 'value': 38.6}, 556 | {'label': '40.2 dB', 'value': 40.2}, 557 | {'label': '42.1 dB', 'value': 42.1}, 558 | {'label': '43.4 dB', 'value': 43.4}, 559 | {'label': '43.9 dB', 'value': 43.9}, 560 | {'label': '44.5 dB', 'value': 44.5}, 561 | {'label': '48.0 dB', 'value': 48.0}, 562 | {'label': '49.6 dB', 'value': 49.6}, 563 | ] 564 | 565 | 566 | #----------------------------- 567 | # Start/Stop Configuration Card 568 | #----------------------------- 569 | start_stop_card = \ 570 | html.Div([ 571 | html.Div([html.Div([html.Button('Start Processing', id='btn-start_proc', className="btn_start", n_clicks=0)], className="ctr_toolbar_item"), 572 | html.Div([html.Button('Stop Processing', id='btn-stop_proc', className="btn_stop", n_clicks=0)], className="ctr_toolbar_item"), 573 | html.Div([html.Button('Save Configuration', id='btn-save_cfg', className="btn_save_cfg", n_clicks=0)], className="ctr_toolbar_item") 574 | ], className="ctr_toolbar"), 575 | ]) 576 | 577 | #----------------------------- 578 | # DAQ Configuration Card 579 | #----------------------------- 580 | # -- > Main Card Layout < -- 581 | daq_config_card_list = \ 582 | [ 583 | html.H2("RF Receiver Configuration", id="init_title_c"), 584 | html.Div([ 585 | html.Div("Center Frequency [MHz]", className="field-label"), 586 | dcc.Input(id='daq_center_freq', value=webInterface_inst.module_receiver.daq_center_freq/10**6, type='number', debounce=True, className="field-body-textbox") 587 | ], className="field"), 588 | html.Div([ 589 | html.Div("Receiver gain", className="field-label"), 590 | dcc.Dropdown(id='daq_rx_gain', 591 | options=gain_list, 592 | value=webInterface_inst.module_receiver.daq_rx_gain[0], clearable=False, style={"display":"inline-block", "padding-bottom":"5px"}, className="field-body"), 593 | #], className="field"), 594 | 595 | html.Div("Receiver 2 gain", className="field-label"), 596 | dcc.Dropdown(id='daq_rx_gain_2', 597 | options=gain_list, 598 | value=webInterface_inst.module_receiver.daq_rx_gain[1], clearable=False, style={"display":"inline-block"}, className="field-body"), 599 | ], className="field"), 600 | 601 | 602 | html.Div([ 603 | html.Button('Update Receiver Parameters', id='btn-update_rx_param', className="btn"), 604 | ], className="field"), 605 | 606 | 607 | html.Div([ 608 | html.Div("Preconfigured DAQ Files", className="field-label"), 609 | dcc.Dropdown(id='daq_cfg_files', 610 | options=[ 611 | {'label': str(i[1]), 'value': i[0]} for i in preconfigs 612 | ], 613 | clearable=False, 614 | value=preconfigs[0][0], 615 | placeholder="Select Configuration File", 616 | persistence=True, 617 | style={"display":"inline-block"}, 618 | className="field-body-wide"), 619 | ], className="field"), 620 | html.Div([ 621 | html.Div("Active Configuration: " + webInterface_inst.active_daq_ini_cfg, id="active_daq_ini_cfg", className="field-label"), 622 | ], className="field"), 623 | html.Div([ 624 | html.Div(webInterface_inst.daq_cfg_ini_error , id="daq_ini_check", className="field-label", style={"color":"red"}), 625 | ], className="field"), 626 | 627 | html.Div([html.Div("Basic Custom DAQ Configuration", id="label_en_basic_daq_cfg" , className="field-label")]), 628 | html.Div([ 629 | html.Div("Data Block Length (ms):", className="field-label"), 630 | dcc.Input(id='cfg_data_block_len', value=cfg_data_block_len, type='number', debounce=True, className="field-body-textbox") 631 | ], className="field"), 632 | html.Div([ 633 | html.Div("Decimated Bandwidth (kHz):", className="field-label"), 634 | dcc.Input(id='cfg_decimated_bw', value=cfg_decimated_bw, type='number', debounce=True, className="field-body-textbox") 635 | ], className="field"), 636 | html.Div([ 637 | html.Div("Recalibration Interval (mins):", className="field-label"), 638 | dcc.Input(id='cfg_recal_interval', value=cfg_recal_interval, type='number', debounce=True, className="field-body-textbox") 639 | ], className="field"), 640 | 641 | html.Div([html.Div("Advanced Custom DAQ Configuration", id="label_en_advanced_daq_cfg" , className="field-label"), 642 | dcc.Checklist(options=option , id="en_advanced_daq_cfg" , className="field-body", value=en_advanced_daq_cfg), 643 | ], className="field"), 644 | ] 645 | 646 | # --> Optional DAQ Subsystem reconfiguration fields <-- 647 | daq_subsystem_reconfiguration_options = [ \ 648 | html.Div([ 649 | 650 | html.H2("DAQ Subsystem Reconfiguration", id="init_title_reconfig"), 651 | html.H3("HW", id="cfg_group_hw"), 652 | html.Div([ 653 | html.Div("# RX Channels:", className="field-label"), 654 | dcc.Input(id='cfg_rx_channels', value=daq_cfg_dict['num_ch'], type='number', debounce=True, className="field-body-textbox") 655 | ], className="field"), 656 | 657 | html.Div([ 658 | html.Div("Bias Tee Control:", className="field-label"), 659 | dcc.Input(id='cfg_en_bias_tee', value=daq_cfg_dict['en_bias_tee'], type='text', debounce=True, className="field-body-textbox") 660 | ], className="field"), 661 | 662 | html.H3("DAQ", id="cfg_group_daq"), 663 | html.Div([ 664 | html.Div("DAQ Buffer Size:", className="field-label", id="label_daq_buffer_size"), 665 | dcc.Dropdown(id='cfg_daq_buffer_size', 666 | options=[ 667 | {'label': i, 'value': i} for i in valid_daq_buffer_sizes 668 | ], 669 | value=daq_cfg_dict['daq_buffer_size'], style={"display":"inline-block"},className="field-body"), 670 | ], className="field"), 671 | html.Div([ 672 | html.Div("Sample Rate [MHz]:", className="field-label", id="label_sample_rate"), 673 | dcc.Dropdown(id='cfg_sample_rate', 674 | options=[ 675 | {'label': i, 'value': i} for i in valid_sample_rates 676 | ], 677 | value=daq_cfg_dict['sample_rate']/10**6, style={"display":"inline-block"},className="field-body") 678 | ], className="field"), 679 | html.Div([ 680 | html.Div("Enable Noise Source Control:", className="field-label", id="label_en_noise_source_ctr"), 681 | dcc.Checklist(options=option , id="en_noise_source_ctr" , className="field-body", value=en_noise_src_values), 682 | ], className="field"), 683 | html.H3("Pre Processing"), 684 | html.Div([ 685 | html.Div("CPI Size [sample]:", className="field-label", id="label_cpi_size"), 686 | dcc.Input(id='cfg_cpi_size', value=daq_cfg_dict['cpi_size'], type='number', debounce=True, className="field-body-textbox") 687 | ], className="field"), 688 | html.Div([ 689 | html.Div("Decimation Ratio:", className="field-label", id="label_decimation_ratio"), 690 | dcc.Input(id='cfg_decimation_ratio', value=daq_cfg_dict['decimation_ratio'], type='number', debounce=True, className="field-body-textbox") 691 | ], className="field"), 692 | html.Div([ 693 | html.Div("FIR Relative Bandwidth:", className="field-label", id="label_fir_relative_bw"), 694 | dcc.Input(id='cfg_fir_bw', value=daq_cfg_dict['fir_relative_bandwidth'], type='number', debounce=True, className="field-body-textbox") 695 | ], className="field"), 696 | html.Div([ 697 | html.Div("FIR Tap Size:", className="field-label", id="label_fir_tap_size"), 698 | dcc.Input(id='cfg_fir_tap_size', value=daq_cfg_dict['fir_tap_size'], type='number', debounce=True, className="field-body-textbox") 699 | ], className="field"), 700 | html.Div([ 701 | html.Div("FIR Window:", className="field-label", id="label_fir_window"), 702 | dcc.Dropdown(id='cfg_fir_window', 703 | options=[ 704 | {'label': i, 'value': i} for i in valid_fir_windows 705 | ], 706 | value=daq_cfg_dict['fir_window'], style={"display":"inline-block"},className="field-body") 707 | ], className="field"), 708 | html.Div([ 709 | html.Div("Enable Filter Reset:", className="field-label", id="label_en_filter_reset"), 710 | dcc.Checklist(options=option , id="en_filter_reset" , className="field-body", value=en_filter_rst_values), 711 | ], className="field"), 712 | html.H3("Calibration"), 713 | html.Div([ 714 | html.Div("Correlation Size [sample]:", className="field-label", id="label_correlation_size"), 715 | dcc.Input(id='cfg_corr_size', value=daq_cfg_dict['corr_size'], type='number', debounce=True, className="field-body-textbox") 716 | ], className="field"), 717 | html.Div([ 718 | html.Div("Standard Channel Index:", className="field-label", id="label_std_ch_index"), 719 | dcc.Input(id='cfg_std_ch_ind', value=daq_cfg_dict['std_ch_ind'], type='number', debounce=True, className="field-body-textbox") 720 | ], className="field"), 721 | html.Div([ 722 | html.Div("Enable IQ Calibration:", className="field-label", id="label_en_iq_calibration"), 723 | dcc.Checklist(options=option , id="en_iq_cal" , className="field-body", value=en_iq_cal_values), 724 | ], className="field"), 725 | html.Div([ 726 | html.Div("Gain Lock Interval [frame]:", className="field-label", id="label_gain_lock_interval"), 727 | dcc.Input(id='cfg_gain_lock', value=daq_cfg_dict['gain_lock_interval'], type='number', debounce=True, className="field-body-textbox") 728 | ], className="field"), 729 | html.Div([ 730 | html.Div("Require Track Lock Intervention (For Kerberos):", className="field-label", id="label_require_track_lock"), 731 | dcc.Checklist(options=option , id="en_req_track_lock_intervention" , className="field-body", value=en_req_track_lock_values), 732 | ], className="field"), 733 | html.Div([ 734 | html.Div("Calibration Track Mode:", className="field-label", id="label_calibration_track_mode"), 735 | dcc.Dropdown(id='cfg_cal_track_mode', 736 | options=[ 737 | {'label': i[0], 'value': i[1]} for i in calibration_tack_modes 738 | ], 739 | value=daq_cfg_dict['cal_track_mode'], style={"display":"inline-block"},className="field-body"), 740 | ], className="field"), 741 | html.Div([ 742 | html.Div("Amplitude Calibration Mode :", className="field-label", id="label_amplitude_calibration_mode"), 743 | dcc.Dropdown(id='cfg_amplitude_cal_mode', 744 | options=[ 745 | {'label': 'default', 'value': 'default'}, 746 | {'label': 'disabled', 'value': 'disabled'}, 747 | {'label': 'channel_power', 'value': 'channel_power'} 748 | ], 749 | value=daq_cfg_dict['amplitude_cal_mode'], style={"display":"inline-block"},className="field-body"), 750 | ], className="field"), 751 | html.Div([ 752 | html.Div("Calibration Frame Interval:", className="field-label", id="label_calibration_frame_interval"), 753 | dcc.Input(id='cfg_cal_frame_interval', value=daq_cfg_dict['cal_frame_interval'], type='number', debounce=True, className="field-body-textbox") 754 | ], className="field"), 755 | html.Div([ 756 | html.Div("Calibration Frame Burst Size:", className="field-label", id="label_calibration_frame_burst_size"), 757 | dcc.Input(id='cfg_cal_frame_burst_size', value=daq_cfg_dict['cal_frame_burst_size'], type='number', debounce=True, className="field-body-textbox") 758 | ], className="field"), 759 | html.Div([ 760 | html.Div("Amplitude Tolerance [dB]:", className="field-label", id="label_amplitude_tolerance"), 761 | dcc.Input(id='cfg_amplitude_tolerance', value=daq_cfg_dict['amplitude_tolerance'], type='number', debounce=True, className="field-body-textbox") 762 | ], className="field"), 763 | html.Div([ 764 | html.Div("Phase Tolerance [deg]:", className="field-label", id="label_phase_tolerance"), 765 | dcc.Input(id='cfg_phase_tolerance', value=daq_cfg_dict['phase_tolerance'], type='number', debounce=True, className="field-body-textbox") 766 | ], className="field"), 767 | html.Div([ 768 | html.Div("Maximum Sync Fails:", className="field-label", id="label_max_sync_fails"), 769 | dcc.Input(id='cfg_max_sync_fails', value=daq_cfg_dict['maximum_sync_fails'], type='number', debounce=True, className="field-body-textbox") 770 | ], className="field"), 771 | ], style={'width': '100%'}, id='adv-cfg-container'), 772 | 773 | # Reconfigure Button 774 | html.Div([ 775 | html.Button('Reconfigure & Restart DAQ chain', id='btn_reconfig_daq_chain', className="btn"), 776 | ], className="field"), 777 | ] 778 | for i in range(len(daq_subsystem_reconfiguration_options)): 779 | daq_config_card_list.append(daq_subsystem_reconfiguration_options[i]) 780 | 781 | daq_config_card = html.Div(daq_config_card_list, className="card") 782 | #----------------------------- 783 | # DAQ Status Card 784 | #----------------------------- 785 | daq_status_card = \ 786 | html.Div([ 787 | html.H2("DAQ Subsystem Status", id="init_title_s"), 788 | html.Div([html.Div("Update rate:" , id="label_daq_update_rate" , className="field-label"), html.Div("- ms" , id="body_daq_update_rate" , className="field-body")], className="field"), 789 | html.Div([html.Div("Latency:" , id="label_daq_dsp_latency" , className="field-label"), html.Div("- ms" , id="body_daq_dsp_latency" , className="field-body")], className="field"), 790 | html.Div([html.Div("Frame index:" , id="label_daq_frame_index" , className="field-label"), html.Div("-" , id="body_daq_frame_index" , className="field-body")], className="field"), 791 | html.Div([html.Div("Frame type:" , id="label_daq_frame_type" , className="field-label"), html.Div("-" , id="body_daq_frame_type" , className="field-body")], className="field"), 792 | html.Div([html.Div("Frame sync:" , id="label_daq_frame_sync" , className="field-label"), html.Div("LOSS" , id="body_daq_frame_sync" , className="field-body", style={"color": "red"})], className="field"), 793 | html.Div([html.Div("Power level:" , id="label_daq_power_level" , className="field-label"), html.Div("-" , id="body_daq_power_level" , className="field-body")], className="field"), 794 | html.Div([html.Div("Connection status:" , id="label_daq_conn_status" , className="field-label"), html.Div("Disconnected", id="body_daq_conn_status" , className="field-body", style={"color": "red"})], className="field"), 795 | html.Div([html.Div("Sample delay snyc:" , id="label_daq_delay_sync" , className="field-label"), html.Div("LOSS" , id="body_daq_delay_sync" , className="field-body", style={"color": "red"})], className="field"), 796 | html.Div([html.Div("IQ snyc:" , id="label_daq_iq_sync" , className="field-label"), html.Div("LOSS" , id="body_daq_iq_sync" , className="field-body", style={"color": "red"})], className="field"), 797 | html.Div([html.Div("Noise source state:" , id="label_daq_noise_source" , className="field-label"), html.Div("Disabled" , id="body_daq_noise_source" , className="field-body", style={"color": "green"})], className="field"), 798 | html.Div([html.Div("RF center frequecy [MHz]:" , id="label_daq_rf_center_freq", className="field-label"), html.Div("- MHz" , id="body_daq_rf_center_freq", className="field-body")], className="field"), 799 | html.Div([html.Div("Sampling frequency [MHz]:" , id="label_daq_sampling_freq" , className="field-label"), html.Div("- MHz" , id="body_daq_sampling_freq" , className="field-body")], className="field"), 800 | html.Div([html.Div("Data block length [ms]:" , id="label_daq_cpi" , className="field-label"), html.Div("- ms" , id="body_daq_cpi" , className="field-body")], className="field"), 801 | html.Div([html.Div("IF gains [dB]:" , id="label_daq_if_gain" , className="field-label"), html.Div("[,] dB" , id="body_daq_if_gain" , className="field-body")], className="field"), 802 | ], className="card") 803 | 804 | #----------------------------- 805 | # DSP Confugartion Card 806 | #----------------------------- 807 | 808 | dsp_config_card = \ 809 | html.Div([ 810 | html.H2("Passive Radar Configuration", id="init_title_d"), 811 | html.Div([html.Div("Enable Passive Radar", id="label_en_pr" , className="field-label"), 812 | dcc.Checklist(options=option , id="en_pr_check" , className="field-body", value=en_pr_values), 813 | ], className="field"), 814 | 815 | html.Div([html.Div("Clutter Cancellation:" , id="label_clutter_cancellation" , className="field-label"), 816 | dcc.Dropdown(id='clutter_cancel_algo', 817 | options=[ 818 | {'label': 'OFF', 'value': "OFF"}, 819 | {'label': 'Wiener MRE' , 'value': "Wiener MRE"}, 820 | ], 821 | value=webInterface_inst.module_signal_processor.PR_clutter_cancellation, style={"display":"inline-block"},className="field-body") 822 | ], className="field"), 823 | 824 | html.Div([html.Div("Max Bistatic Range [km]:" , id="label_max_bistatic_range" , className="field-label"), 825 | dcc.Dropdown(id='max_bistatic_range', 826 | options=[ 827 | {'label': '16', 'value': 16}, 828 | {'label': '32' , 'value': 32}, 829 | {'label': '64' , 'value': 64}, 830 | {'label': '128' , 'value': 128}, 831 | {'label': '256' , 'value': 256}, 832 | {'label': '512' , 'value': 512}, 833 | {'label': '1024' , 'value': 1024}, 834 | ], 835 | value=webInterface_inst.module_signal_processor.max_bistatic_range, style={"display":"inline-block"},className="field-body") 836 | ], className="field"), 837 | 838 | html.Div([html.Div("Max Doppler [Hz]:" , id="label_max_doppler" ,style={"display":"inline-block"}, className="field-label"), 839 | dcc.Input(id="max_doppler", value=webInterface_inst.module_signal_processor.max_doppler, type='number', style={"display":"inline-block"}, debounce=True, className="field-body-textbox") 840 | ], style={'display':'inline-block'}, className="field"), 841 | 842 | html.Div([html.Div("PR Persist", id="label_en_persist" , className="field-label"), 843 | dcc.Checklist(options=option , id="en_persist_check" , className="field-body", value=en_persist_values), 844 | ], className="field"), 845 | 846 | html.Div([html.Div("Persist Decay:" , id="label_persist_decay" ,style={"display":"inline-block"}, className="field-label"), 847 | dcc.Input(id="persist_decay", value=webInterface_inst.pr_persist_decay, type='number', style={"display":"inline-block"}, debounce=True, className="field-body-textbox") 848 | ], style={'display':'inline-block'}, className="field"), 849 | 850 | 851 | html.Div([html.Div("Dynamic Range (Min):" , id="label_dynrange_min" ,style={"display":"inline-block"}, className="field-label"), 852 | dcc.Input(id="dynrange_min", value=webInterface_inst.pr_dynamic_range_min, type='number', style={"display":"inline-block"}, debounce=True, className="field-body-textbox") 853 | ], style={'display':'inline-block'}, className="field"), 854 | 855 | html.Div([html.Div("Dynamic Range (Max):" , id="label_dynrange_max" ,style={"display":"inline-block"}, className="field-label"), 856 | dcc.Input(id="dynrange_max", value=webInterface_inst.pr_dynamic_range_max, type='number', style={"display":"inline-block"}, debounce=True, className="field-body-textbox") 857 | ], style={'display':'inline-block'}, className="field"), 858 | 859 | 860 | 861 | 862 | ], className="card") 863 | 864 | #----------------------------- 865 | # Display Options Card 866 | #----------------------------- 867 | #config_page_component_list = [daq_config_card, daq_status_card, dsp_config_card, display_options_card,squelch_card] 868 | config_page_component_list = [start_stop_card, daq_config_card, daq_status_card, dsp_config_card] 869 | 870 | if not webInterface_inst.disable_tooltips: 871 | config_page_component_list.append(tooltips.dsp_config_tooltips) 872 | config_page_component_list.append(tooltips.daq_ini_config_tooltips) 873 | 874 | return html.Div(children=config_page_component_list) 875 | 876 | spectrum_page_layout = html.Div([ 877 | html.Div([ 878 | dcc.Graph( 879 | id="spectrum-graph", 880 | style={'width': '100%', 'height': '45%'}, 881 | figure=fig_dummy #spectrum_fig #fig_dummy #spectrum_fig #fig_dummy 882 | ), 883 | dcc.Graph( 884 | id="waterfall-graph", 885 | style={'width': '100%', 'height': '65%'}, 886 | figure=waterfall_fig #waterfall fig remains unchanged always due to slow speed to update entire graph #fig_dummy #spectrum_fig #fig_dummy 887 | ), 888 | ], style={'width': '100%', 'height': '80vh'}), #className="monitor_card"), 889 | ]) 890 | 891 | def generate_pr_page_layout(webInterface_inst): 892 | pr_page_layout = html.Div([ 893 | html.Div([ 894 | dcc.Graph( 895 | style={"height": "inherit", "width" : "100%"}, 896 | id="pr-graph", 897 | figure=pr_fig, #fig_dummy #doa_fig #fig_dummy 898 | )], style={'width': '100%', 'height': '85vh'}), #className="monitor_card"), 899 | ]) 900 | return pr_page_layout 901 | 902 | #============================================ 903 | # CALLBACK FUNCTIONS 904 | #============================================ 905 | @app.callback_connect 906 | def func(client, connect): 907 | #print(client, connect, len(app.clients)) 908 | if connect and len(app.clients)==1: 909 | fetch_dsp_data() 910 | elif not connect and len(app.clients)==0: 911 | webInterface_inst.dsp_timer.cancel() 912 | 913 | def fetch_dsp_data(): 914 | daq_status_update_flag = 0 915 | spectrum_update_flag = 0 916 | doa_update_flag = 0 917 | freq_update = no_update 918 | ############################################# 919 | # Fetch new data from back-end ques # 920 | ############################################# 921 | try: 922 | # Fetch new data from the receiver module 923 | que_data_packet = webInterface_inst.rx_data_que.get(False) 924 | for data_entry in que_data_packet: 925 | if data_entry[0] == "conn-ok": 926 | webInterface_inst.daq_conn_status = 1 927 | daq_status_update_flag = 1 928 | elif data_entry[0] == "disconn-ok": 929 | webInterface_inst.daq_conn_status = 0 930 | daq_status_update_flag = 1 931 | elif data_entry[0] == "config-ok": 932 | webInterface_inst.daq_cfg_iface_status = 0 933 | daq_status_update_flag = 1 934 | except queue.Empty: 935 | # Handle empty queue here 936 | webInterface_inst.logger.debug("Receiver module que is empty") 937 | else: 938 | pass 939 | # Handle task here and call q.task_done() 940 | if webInterface_inst.daq_restart: # Set by the restarting script 941 | daq_status_update_flag = 1 942 | try: 943 | # Fetch new data from the signal processing module 944 | que_data_packet = webInterface_inst.sp_data_que.get(False) 945 | for data_entry in que_data_packet: 946 | if data_entry[0] == "iq_header": 947 | webInterface_inst.logger.debug("Iq header data fetched from signal processing que") 948 | iq_header = data_entry[1] 949 | # Unpack header 950 | webInterface_inst.daq_frame_index = iq_header.cpi_index 951 | 952 | if iq_header.frame_type == iq_header.FRAME_TYPE_DATA: 953 | webInterface_inst.daq_frame_type = "Data" 954 | elif iq_header.frame_type == iq_header.FRAME_TYPE_DUMMY: 955 | webInterface_inst.daq_frame_type = "Dummy" 956 | elif iq_header.frame_type == iq_header.FRAME_TYPE_CAL: 957 | webInterface_inst.daq_frame_type = "Calibration" 958 | elif iq_header.frame_type == iq_header.FRAME_TYPE_TRIGW: 959 | webInterface_inst.daq_frame_type = "Trigger wait" 960 | else: 961 | webInterface_inst.daq_frame_type = "Unknown" 962 | 963 | webInterface_inst.daq_frame_sync = iq_header.check_sync_word() 964 | webInterface_inst.daq_power_level = iq_header.adc_overdrive_flags 965 | webInterface_inst.daq_sample_delay_sync = iq_header.delay_sync_flag 966 | webInterface_inst.daq_iq_sync = iq_header.iq_sync_flag 967 | webInterface_inst.daq_noise_source_state= iq_header.noise_source_state 968 | 969 | if webInterface_inst.daq_center_freq != iq_header.rf_center_freq/10**6: 970 | freq_update = 1 971 | 972 | webInterface_inst.daq_center_freq = iq_header.rf_center_freq/10**6 973 | webInterface_inst.daq_adc_fs = iq_header.adc_sampling_freq/10**6 974 | webInterface_inst.daq_fs = iq_header.sampling_freq/10**6 975 | webInterface_inst.daq_cpi = int(iq_header.cpi_length*10**3/iq_header.sampling_freq) 976 | gain_list_str="" 977 | for m in range(iq_header.active_ant_chs): 978 | gain_list_str+=str(iq_header.if_gains[m]/10) 979 | gain_list_str+=", " 980 | webInterface_inst.daq_if_gains =gain_list_str[:-2] 981 | daq_status_update_flag = 1 982 | elif data_entry[0] == "update_rate": 983 | webInterface_inst.daq_update_rate = data_entry[1] 984 | # Set absoluth minimum 985 | #if webInterface_inst.daq_update_rate < 0.1: webInterface_inst.daq_update_rate = 0.1 986 | if webInterface_inst._update_rate_arr is None: 987 | webInterface_inst._update_rate_arr = np.ones(webInterface_inst._avg_win_size)*webInterface_inst.daq_update_rate 988 | webInterface_inst._update_rate_arr[0:webInterface_inst._avg_win_size-2] = \ 989 | webInterface_inst._update_rate_arr[1:webInterface_inst._avg_win_size-1] 990 | webInterface_inst._update_rate_arr[webInterface_inst._avg_win_size-1] = webInterface_inst.daq_update_rate 991 | #webInterface_inst.page_update_rate = np.average(webInterface_inst._update_rate_arr)*0.8 992 | elif data_entry[0] == "latency": 993 | webInterface_inst.daq_dsp_latency = data_entry[1] + webInterface_inst.daq_cpi 994 | elif data_entry[0] == "spectrum": 995 | webInterface_inst.logger.debug("Spectrum data fetched from signal processing que") 996 | spectrum_update_flag = 1 997 | webInterface_inst.spectrum = data_entry[1] 998 | elif data_entry[0] == "RD_matrix": 999 | webInterface_inst.logger.debug("Passive Radar RD Matrix data fetched from signal processing que") 1000 | doa_update_flag = 1 1001 | webInterface_inst.RD_matrix = data_entry[1] 1002 | else: 1003 | webInterface_inst.logger.warning("Unknown data entry: {:s}".format(data_entry[0])) 1004 | except queue.Empty: 1005 | # Handle empty queue here 1006 | webInterface_inst.logger.debug("Signal processing que is empty") 1007 | else: 1008 | pass 1009 | # Handle task here and call q.task_done() 1010 | 1011 | if (webInterface_inst.pathname == "/config" or webInterface_inst.pathname == "/") and daq_status_update_flag: 1012 | update_daq_status() 1013 | elif webInterface_inst.pathname == "/spectrum" and spectrum_update_flag: 1014 | plot_spectrum() 1015 | elif (webInterface_inst.pathname == "/pr" and doa_update_flag): #or (webInterface_inst.pathname == "/doa" and webInterface_inst.reset_doa_graph_flag): 1016 | plot_pr() 1017 | 1018 | webInterface_inst.dsp_timer = Timer(.01, fetch_dsp_data) 1019 | webInterface_inst.dsp_timer.start() 1020 | 1021 | 1022 | def update_daq_status(): 1023 | 1024 | ############################################# 1025 | # Prepare UI component properties # 1026 | ############################################# 1027 | 1028 | if webInterface_inst.daq_conn_status == 1: 1029 | 1030 | if not webInterface_inst.daq_cfg_iface_status: 1031 | daq_conn_status_str = "Connected" 1032 | conn_status_style={"color": "green"} 1033 | else: # Config interface is busy 1034 | daq_conn_status_str = "Reconfiguration.." 1035 | conn_status_style={"color": "orange"} 1036 | else: 1037 | daq_conn_status_str = "Disconnected" 1038 | conn_status_style={"color": "red"} 1039 | 1040 | if webInterface_inst.daq_restart: 1041 | daq_conn_status_str = "Restarting.." 1042 | conn_status_style={"color": "orange"} 1043 | 1044 | if webInterface_inst.daq_update_rate < 1: 1045 | daq_update_rate_str = "{:d} ms".format(round(webInterface_inst.daq_update_rate*1000)) 1046 | else: 1047 | daq_update_rate_str = "{:.2f} s".format(webInterface_inst.daq_update_rate) 1048 | 1049 | daq_dsp_latency = "{:d} ms".format(webInterface_inst.daq_dsp_latency) 1050 | daq_frame_index_str = str(webInterface_inst.daq_frame_index) 1051 | 1052 | daq_frame_type_str = webInterface_inst.daq_frame_type 1053 | if webInterface_inst.daq_frame_type == "Data": 1054 | frame_type_style = frame_type_style={"color": "green"} 1055 | elif webInterface_inst.daq_frame_type == "Dummy": 1056 | frame_type_style = frame_type_style={"color": "white"} 1057 | elif webInterface_inst.daq_frame_type == "Calibration": 1058 | frame_type_style = frame_type_style={"color": "orange"} 1059 | elif webInterface_inst.daq_frame_type == "Trigger wait": 1060 | frame_type_style = frame_type_style={"color": "yellow"} 1061 | else: 1062 | frame_type_style = frame_type_style={"color": "red"} 1063 | 1064 | if webInterface_inst.daq_frame_sync: 1065 | daq_frame_sync_str = "LOSS" 1066 | frame_sync_style={"color": "red"} 1067 | else: 1068 | daq_frame_sync_str = "Ok" 1069 | frame_sync_style={"color": "green"} 1070 | if webInterface_inst.daq_sample_delay_sync: 1071 | daq_delay_sync_str = "Ok" 1072 | delay_sync_style={"color": "green"} 1073 | else: 1074 | daq_delay_sync_str = "LOSS" 1075 | delay_sync_style={"color": "red"} 1076 | 1077 | if webInterface_inst.daq_iq_sync: 1078 | daq_iq_sync_str = "Ok" 1079 | iq_sync_style={"color": "green"} 1080 | else: 1081 | daq_iq_sync_str = "LOSS" 1082 | iq_sync_style={"color": "red"} 1083 | 1084 | if webInterface_inst.daq_noise_source_state: 1085 | daq_noise_source_str = "Enabled" 1086 | noise_source_style={"color": "red"} 1087 | else: 1088 | daq_noise_source_str = "Disabled" 1089 | noise_source_style={"color": "green"} 1090 | 1091 | if webInterface_inst.daq_power_level: 1092 | daq_power_level_str = "Overdrive" 1093 | daq_power_level_style={"color": "red"} 1094 | else: 1095 | daq_power_level_str = "OK" 1096 | daq_power_level_style={"color": "green"} 1097 | 1098 | daq_rf_center_freq_str = str(webInterface_inst.daq_center_freq) 1099 | daq_sampling_freq_str = str(webInterface_inst.daq_fs) 1100 | daq_cpi_str = str(webInterface_inst.daq_cpi) 1101 | 1102 | app.push_mods({ 1103 | 'body_daq_update_rate': {'children': daq_update_rate_str}, 1104 | 'body_daq_dsp_latency': {'children': daq_dsp_latency}, 1105 | 'body_daq_frame_index': {'children': daq_frame_index_str}, 1106 | 'body_daq_frame_sync': {'children': daq_frame_sync_str}, 1107 | 'body_daq_frame_type': {'children': daq_frame_type_str}, 1108 | 'body_daq_power_level': {'children': daq_power_level_str}, 1109 | 'body_daq_conn_status': {'children': daq_conn_status_str }, 1110 | 'body_daq_delay_sync': {'children': daq_delay_sync_str}, 1111 | 'body_daq_iq_sync': {'children': daq_iq_sync_str}, 1112 | 'body_daq_noise_source': {'children': daq_noise_source_str}, 1113 | 'body_daq_rf_center_freq': {'children': daq_rf_center_freq_str}, 1114 | 'body_daq_sampling_freq': {'children': daq_sampling_freq_str}, 1115 | 'body_daq_cpi': {'children': daq_cpi_str}, 1116 | 'body_daq_if_gain': {'children': webInterface_inst.daq_if_gains}, 1117 | }) 1118 | 1119 | app.push_mods({ 1120 | 'body_daq_frame_sync': {'style': frame_sync_style}, 1121 | 'body_daq_frame_type': {'style': frame_type_style}, 1122 | 'body_daq_power_level': {'style': daq_power_level_style}, 1123 | 'body_daq_conn_status': {'style': conn_status_style}, 1124 | 'body_daq_delay_sync': {'style': delay_sync_style}, 1125 | 'body_daq_iq_sync': {'style': iq_sync_style}, 1126 | 'body_daq_noise_source': {'style': noise_source_style}, 1127 | }) 1128 | 1129 | @app.callback( 1130 | Output(component_id="placeholder_update_freq", component_property="children"), 1131 | [Input(component_id ="btn-update_rx_param" , component_property="n_clicks")], 1132 | [State(component_id ="daq_center_freq" , component_property='value'), 1133 | State(component_id ="daq_rx_gain" , component_property='value'), 1134 | State(component_id ="daq_rx_gain_2" , component_property='value')], 1135 | ) 1136 | def update_daq_params(input_value, f0, gain, gain_2): 1137 | webInterface_inst.daq_center_freq = f0 1138 | webInterface_inst.config_daq_rf(f0, [gain, gain_2] ) # CARL: TO CHANGE THIS TO AUTO POPULATE EACH GAIN UP TO M RECEIVERS? 1139 | return 1 1140 | 1141 | @app.callback([Output("page-content" , "children"), 1142 | Output("header_config" ,"className"), 1143 | Output("header_spectrum","className"), 1144 | Output("header_doa" ,"className")], 1145 | [Input("url" , "pathname")]) 1146 | def display_page(pathname): 1147 | global spectrum_fig 1148 | global doa_fig 1149 | webInterface_inst.pathname = pathname 1150 | 1151 | if pathname == "/": 1152 | webInterface_inst.module_signal_processor.en_spectrum = False 1153 | return [generate_config_page_layout(webInterface_inst), "header_active", "header_inactive", "header_inactive"] 1154 | elif pathname == "/config": 1155 | webInterface_inst.module_signal_processor.en_spectrum = False 1156 | return [generate_config_page_layout(webInterface_inst), "header_active", "header_inactive", "header_inactive"] 1157 | elif pathname == "/spectrum": 1158 | webInterface_inst.module_signal_processor.en_spectrum = True 1159 | spectrum_fig = None # Force reload of graphs as axes may change etc 1160 | #time.sleep(1) 1161 | return [spectrum_page_layout, "header_inactive", "header_active", "header_inactive"] 1162 | elif pathname == "/pr": 1163 | webInterface_inst.module_signal_processor.en_spectrum = False 1164 | plot_pr() 1165 | return [generate_pr_page_layout(webInterface_inst), "header_inactive", "header_inactive", "header_active"] 1166 | return Output('dummy_output', 'children', '') #[no_update, no_update, no_update, no_update] 1167 | 1168 | #return [no_update, no_update, no_update, no_update] 1169 | 1170 | 1171 | @app.callback_shared( 1172 | None, 1173 | [Input(component_id='btn-start_proc', component_property='n_clicks')], 1174 | ) 1175 | def start_proc_btn(input_value): 1176 | webInterface_inst.logger.info("Start pocessing btn pushed") 1177 | webInterface_inst.start_processing() 1178 | 1179 | @app.callback_shared( 1180 | None, 1181 | [Input(component_id='btn-stop_proc', component_property='n_clicks')], 1182 | ) 1183 | def stop_proc_btn(input_value): 1184 | webInterface_inst.logger.info("Stop pocessing btn pushed") 1185 | webInterface_inst.stop_processing() 1186 | 1187 | @app.callback_shared( 1188 | None, 1189 | [Input(component_id='btn-save_cfg' , component_property='n_clicks')], 1190 | ) 1191 | def save_config_btn(input_value): 1192 | webInterface_inst.logger.info("Saving DAQ and DSP Configuration") 1193 | webInterface_inst.save_configuration() 1194 | 1195 | def plot_pr(): 1196 | global pr_fig 1197 | 1198 | if webInterface_inst.RD_matrix is not None: 1199 | 1200 | CAFMatrix = np.abs(webInterface_inst.RD_matrix) 1201 | 1202 | CAFMatrix = CAFMatrix / 50 #/ np.amax(CAFMatrix) # Noramlize with the maximum value 1203 | 1204 | if webInterface_inst.CAFMatrixPersist is None or webInterface_inst.CAFMatrixPersist.shape != CAFMatrix.shape or not webInterface_inst.en_persist: 1205 | webInterface_inst.CAFMatrixPersist = CAFMatrix 1206 | else: 1207 | webInterface_inst.CAFMatrixPersist = np.maximum(webInterface_inst.CAFMatrixPersist, CAFMatrix)*webInterface_inst.pr_persist_decay #webInterface_inst.CAFMatrixPersist * 0.5 + CAFMatrix * 0.5 1208 | 1209 | CAFMatrixLog = 20 * np.log10(webInterface_inst.CAFMatrixPersist) 1210 | 1211 | CAFDynRange = webInterface_inst.pr_dynamic_range_min 1212 | CAFMatrixLog[CAFMatrixLog < CAFDynRange] = CAFDynRange 1213 | 1214 | CAFDynRange = webInterface_inst.pr_dynamic_range_max 1215 | CAFMatrixLog[CAFMatrixLog > CAFDynRange] = CAFDynRange 1216 | 1217 | y_height = CAFMatrixLog.shape[0] 1218 | y_range = list(np.arange(-y_height/2, y_height/2)) 1219 | 1220 | app.push_mods({ 1221 | 'pr-graph': {'extendData': [dict(z = [CAFMatrixLog], y = [y_range]), [0], len(CAFMatrixLog)]} 1222 | }) 1223 | 1224 | def plot_spectrum(): 1225 | global spectrum_fig 1226 | global waterfall_fig 1227 | if spectrum_fig == None: 1228 | spectrum_fig = go.Figure(layout=fig_layout) 1229 | 1230 | x=webInterface_inst.spectrum[0,:] + webInterface_inst.daq_center_freq*10**6 1231 | 1232 | # Plot traces 1233 | for m in range(np.size(webInterface_inst.spectrum, 0)-1): 1234 | spectrum_fig.add_trace(go.Scattergl(x=x, 1235 | y=y, #webInterface_inst.spectrum[m+1, :], 1236 | name="Channel {:d}".format(m), 1237 | line = dict(color = trace_colors[m], 1238 | width = 1) 1239 | )) 1240 | 1241 | spectrum_fig.update_xaxes( #title_text=freq_label, 1242 | color='rgba(255,255,255,1)', 1243 | title_font_size=20, 1244 | tickfont_size= 15, #figure_font_size, 1245 | range=[np.min(x), np.max(x)], 1246 | rangemode='normal', 1247 | mirror=True, 1248 | ticks='outside', 1249 | showline=True) 1250 | spectrum_fig.update_yaxes(title_text="Amplitude [dB]", 1251 | color='rgba(255,255,255,1)', 1252 | title_font_size=20, 1253 | tickfont_size=figure_font_size, 1254 | range=[-90, 0], 1255 | mirror=True, 1256 | ticks='outside', 1257 | showline=True) 1258 | 1259 | 1260 | spectrum_fig.update_layout(margin=go.layout.Margin(b=5, t=0)) 1261 | 1262 | webInterface_inst.reset_spectrum_graph_flag = False 1263 | app.push_mods({ 1264 | 'spectrum-graph': {'figure': spectrum_fig}, 1265 | # 'waterfall-graph': {'figure': waterfall_fig} 1266 | }) 1267 | 1268 | else: 1269 | update_data = [] 1270 | for m in range(1, np.size(webInterface_inst.spectrum, 0)): #webInterface_inst.module_receiver.M+1): 1271 | update_data.append(dict(x=webInterface_inst.spectrum[0,:] + webInterface_inst.daq_center_freq*10**6, y=webInterface_inst.spectrum[m, :])) 1272 | 1273 | x_app = [] 1274 | y_app = [] 1275 | for m in range(1, np.size(webInterface_inst.spectrum, 0)): #webInterface_inst.module_receiver.M+1): 1276 | x_app.append(webInterface_inst.spectrum[0,:] + webInterface_inst.daq_center_freq*10**6) 1277 | y_app.append(webInterface_inst.spectrum[m, :]) 1278 | 1279 | update_data = dict(x=x_app, y=y_app) 1280 | 1281 | app.push_mods({ 1282 | 'spectrum-graph': {'extendData': [update_data, list(range(0,len(webInterface_inst.spectrum)-1)), len(webInterface_inst.spectrum[0,:])]}, 1283 | 'waterfall-graph': {'extendData': [dict(z =[[webInterface_inst.spectrum[1, :]]]), [0], 50]} 1284 | }) 1285 | 1286 | 1287 | @app.callback( 1288 | None, 1289 | [Input(component_id ="placeholder_update_freq" , component_property='children'), 1290 | Input(component_id ="en_pr_check" , component_property='value'), 1291 | Input(component_id ="en_persist_check" , component_property='value'), 1292 | Input(component_id ="persist_decay" , component_property='value'), 1293 | Input(component_id ="max_bistatic_range" , component_property='value'), 1294 | Input(component_id ="max_doppler" , component_property='value'), 1295 | Input(component_id ="clutter_cancel_algo" , component_property='value'), 1296 | Input(component_id ="dynrange_max" , component_property='value'), 1297 | Input(component_id ="dynrange_min" , component_property='value')] 1298 | ) 1299 | def update_dsp_params(update_freq, en_pr, en_persist, persist_decay, max_bistatic_range, max_doppler, clutter_cancel_algo, dynrange_max, dynrange_min): #, input_value): 1300 | 1301 | if en_pr is not None and len(en_pr): 1302 | webInterface_inst.logger.debug("Passive Radar enabled") 1303 | webInterface_inst.module_signal_processor.en_PR = True 1304 | else: 1305 | webInterface_inst.module_signal_processor.en_PR = False 1306 | 1307 | if en_persist is not None and len(en_persist): 1308 | webInterface_inst.en_persist = True 1309 | else: 1310 | webInterface_inst.en_persist = False 1311 | 1312 | webInterface_inst.module_signal_processor.PR_clutter_cancellation = clutter_cancel_algo 1313 | webInterface_inst.module_signal_processor.max_bistatic_range = max_bistatic_range 1314 | webInterface_inst.module_signal_processor.max_doppler = max_doppler 1315 | webInterface_inst.pr_persist_decay = persist_decay 1316 | webInterface_inst.pr_dynamic_range_min = dynrange_min 1317 | webInterface_inst.pr_dynamic_range_max = dynrange_max 1318 | 1319 | @app.callback( 1320 | None, 1321 | [Input('cfg_rx_channels' ,'value'), 1322 | Input('cfg_daq_buffer_size' ,'value'), 1323 | Input('cfg_sample_rate' ,'value'), 1324 | Input('en_noise_source_ctr' ,'value'), 1325 | Input('cfg_cpi_size' ,'value'), 1326 | Input('cfg_decimation_ratio' ,'value'), 1327 | Input('cfg_fir_bw' ,'value'), 1328 | Input('cfg_fir_tap_size' ,'value'), 1329 | Input('cfg_fir_window' ,'value'), 1330 | Input('en_filter_reset' ,'value'), 1331 | Input('cfg_corr_size' ,'value'), 1332 | Input('cfg_std_ch_ind' ,'value'), 1333 | Input('en_iq_cal' ,'value'), 1334 | Input('cfg_gain_lock' ,'value'), 1335 | Input('en_req_track_lock_intervention','value'), 1336 | Input('cfg_cal_track_mode' ,'value'), 1337 | Input('cfg_amplitude_cal_mode' ,'value'), 1338 | Input('cfg_cal_frame_interval' ,'value'), 1339 | Input('cfg_cal_frame_burst_size' ,'value'), 1340 | Input('cfg_amplitude_tolerance' ,'value'), 1341 | Input('cfg_phase_tolerance' ,'value'), 1342 | Input('cfg_max_sync_fails' ,'value'), 1343 | Input('cfg_data_block_len' ,'value'), 1344 | Input('cfg_decimated_bw' ,'value'), 1345 | Input('cfg_recal_interval' ,'value'), 1346 | Input('cfg_en_bias_tee' ,'value'), 1347 | Input('daq_cfg_files' , 'value')] 1348 | ) 1349 | def update_daq_ini_params( 1350 | cfg_rx_channels,cfg_daq_buffer_size,cfg_sample_rate,en_noise_source_ctr, \ 1351 | cfg_cpi_size,cfg_decimation_ratio, \ 1352 | cfg_fir_bw,cfg_fir_tap_size,cfg_fir_window,en_filter_reset,cfg_corr_size, \ 1353 | cfg_std_ch_ind,en_iq_cal,cfg_gain_lock,en_req_track_lock_intervention, \ 1354 | cfg_cal_track_mode,cfg_amplitude_cal_mode,cfg_cal_frame_interval, \ 1355 | cfg_cal_frame_burst_size, cfg_amplitude_tolerance,cfg_phase_tolerance, \ 1356 | cfg_max_sync_fails, cfg_data_block_len, cfg_decimated_bw, cfg_recal_interval, cfg_en_bias_tee, config_fname): 1357 | # TODO: Use disctionarry instead of parameter list 1358 | 1359 | ctx = dash.callback_context 1360 | component_id = ctx.triggered[0]['prop_id'].split('.')[0] 1361 | if ctx.triggered: 1362 | if len(ctx.triggered) == 1: # User manually changed one parameter 1363 | webInterface_inst.tmp_daq_ini_cfg = "Custom" 1364 | 1365 | # If is was the preconfig changed, just update the preconfig values 1366 | if component_id == 'daq_cfg_files': 1367 | webInterface_inst.daq_ini_cfg_dict = read_config_file_dict(config_fname) 1368 | webInterface_inst.tmp_daq_ini_cfg = webInterface_inst.daq_ini_cfg_dict['config_name'] 1369 | daq_cfg_dict = webInterface_inst.daq_ini_cfg_dict 1370 | 1371 | if daq_cfg_dict is not None: 1372 | en_noise_src_values =[1] if daq_cfg_dict['en_noise_source_ctr'] else [] 1373 | en_filter_rst_values =[1] if daq_cfg_dict['en_filter_reset'] else [] 1374 | en_iq_cal_values =[1] if daq_cfg_dict['en_iq_cal'] else [] 1375 | en_req_track_lock_values =[1] if daq_cfg_dict['require_track_lock_intervention'] else [] 1376 | 1377 | #en_persist_values =[1] if webInterface_inst.en_persist else [] 1378 | #en_pr_values =[1] if webInterface_inst.module_signal_processor.en_PR else [] 1379 | 1380 | en_advanced_daq_cfg =[1] if webInterface_inst.en_advanced_daq_cfg else [] 1381 | 1382 | cfg_decimated_bw = ((daq_cfg_dict['sample_rate']) / daq_cfg_dict['decimation_ratio']) / 10**3 1383 | cfg_data_block_len = ( daq_cfg_dict['cpi_size'] / (cfg_decimated_bw) ) 1384 | cfg_recal_interval = (daq_cfg_dict['cal_frame_interval'] * (cfg_data_block_len/10**3)) / 60 1385 | 1386 | if daq_cfg_dict['cal_track_mode'] == 0: #If set to no tracking 1387 | cfg_recal_interval = 1 1388 | 1389 | app.push_mods({ 1390 | 'cfg_data_block_len': {'value': cfg_data_block_len}, 1391 | 'cfg_decimated_bw': {'value': cfg_decimated_bw}, 1392 | 'cfg_recal_interval': {'value': cfg_recal_interval}, 1393 | 'cfg_rx_channels': {'value': daq_cfg_dict['num_ch']}, 1394 | 'cfg_daq_buffer_size': {'value': daq_cfg_dict['daq_buffer_size']}, 1395 | 'cfg_sample_rate': {'value': daq_cfg_dict['sample_rate']/10**6}, 1396 | 'en_noise_source_ctr': {'value': en_noise_src_values}, 1397 | 'cfg_cpi_size': {'value': daq_cfg_dict['cpi_size']}, 1398 | 'cfg_decimation_ratio': {'value': daq_cfg_dict['decimation_ratio']}, 1399 | 'cfg_fir_bw': {'value': daq_cfg_dict['fir_relative_bandwidth']}, 1400 | 'cfg_fir_tap_size': {'value': daq_cfg_dict['fir_tap_size']}, 1401 | 'cfg_fir_window': {'value': daq_cfg_dict['fir_window']}, 1402 | 'en_filter_reset': {'value': en_filter_rst_values}, 1403 | 'cfg_cal_frame_interval': {'value': daq_cfg_dict['cal_frame_interval']}, 1404 | 'cfg_corr_size': {'value': daq_cfg_dict['corr_size']}, 1405 | 'cfg_std_ch_ind': {'value': daq_cfg_dict['std_ch_ind']}, 1406 | 'en_iq_cal': {'value': en_iq_cal_values}, 1407 | 'cfg_gain_lock': {'value': daq_cfg_dict['gain_lock_interval']}, 1408 | 'en_req_track_lock_intervention': {'value': en_req_track_lock_values}, 1409 | 'cfg_cal_track_mode': {'value': daq_cfg_dict['cal_track_mode']}, 1410 | 'cfg_amplitude_cal_mode': {'value': daq_cfg_dict['amplitude_cal_mode']}, 1411 | 'cfg_cal_frame_interval': {'value': daq_cfg_dict['cal_frame_interval']}, 1412 | 'cfg_cal_frame_burst_size': {'value': daq_cfg_dict['cal_frame_burst_size']}, 1413 | 'cfg_amplitude_tolerance': {'value': daq_cfg_dict['amplitude_tolerance']}, 1414 | 'cfg_phase_tolerance': {'value': daq_cfg_dict['phase_tolerance']}, 1415 | 'cfg_max_sync_fails': {'value': daq_cfg_dict['maximum_sync_fails']}, 1416 | }) 1417 | 1418 | return Output('dummy_output', 'children', '') #[no_update, no_update, no_update, no_update] 1419 | 1420 | # If the input was from basic DAQ config, update the actual DAQ params 1421 | if component_id == "cfg_data_block_len" or component_id == "cfg_decimated_bw" or component_id == "cfg_recal_interval": 1422 | if not cfg_data_block_len or not cfg_decimated_bw or not cfg_recal_interval: 1423 | return Output('dummy_output', 'children', '') #[no_update, no_update, no_update, no_update] 1424 | 1425 | cfg_daq_buffer_size = 262144 # This is a reasonable DAQ buffer size to use 1426 | cfg_corr_size = 32768 # Reasonable value that never has problems calibrating 1427 | en_noise_source_ctr = [1] 1428 | cfg_fir_bw = 1 1429 | cfg_fir_window = 'hann' 1430 | en_filter_reset = [] 1431 | cfg_std_ch_ind = 0 1432 | en_iq_cal = [1] 1433 | en_req_track_lock_intervention = [] 1434 | cfg_amplitude_cal_mode = 'channel_power' 1435 | cfg_cal_frame_burst_size = 10 1436 | cfg_amplitude_tolerance = 2 1437 | cfg_phase_tolerance = 2 1438 | cfg_max_sync_fails = 10 1439 | 1440 | cfg_decimation_ratio = round( (cfg_sample_rate*10**6) / (cfg_decimated_bw*10**3) ) 1441 | 1442 | cfg_cpi_size = round( (cfg_data_block_len / 10**3) * cfg_decimated_bw*10**3 ) 1443 | cfg_cal_frame_interval = round((cfg_recal_interval*60) / (cfg_data_block_len/10**3)) 1444 | 1445 | while cfg_decimation_ratio * cfg_cpi_size < cfg_daq_buffer_size: 1446 | cfg_daq_buffer_size = (int) (cfg_daq_buffer_size / 2) 1447 | 1448 | cfg_corr_size = (int) (cfg_daq_buffer_size / 2) 1449 | 1450 | # Choose a tap size larger than the decimation ratio 1451 | cfg_fir_tap_size = (int)(cfg_decimation_ratio * 1.2) + 8 1452 | 1453 | if cfg_decimation_ratio == 1: 1454 | cfg_fir_tap_size = 1 1455 | 1456 | cfg_cal_track_mode = 0 1457 | if cfg_cal_frame_interval > 1: 1458 | cfg_cal_track_mode = 2 #[{'label': calibration_tack_modes[1], 'value': calibration_tack_modes[1]}] 1459 | else: 1460 | cfg_cal_track_mode = 0 1461 | 1462 | param_dict = webInterface_inst.daq_ini_cfg_dict 1463 | param_dict['config_name'] = "Custom" 1464 | param_dict['num_ch'] = cfg_rx_channels 1465 | param_dict['en_bias_tee'] = cfg_en_bias_tee 1466 | param_dict['daq_buffer_size'] = cfg_daq_buffer_size 1467 | param_dict['sample_rate'] = int(cfg_sample_rate*10**6) 1468 | param_dict['en_noise_source_ctr'] = 1 if len(en_noise_source_ctr) else 0 1469 | param_dict['cpi_size'] = cfg_cpi_size 1470 | param_dict['decimation_ratio'] = cfg_decimation_ratio 1471 | param_dict['fir_relative_bandwidth'] = cfg_fir_bw 1472 | param_dict['fir_tap_size'] = cfg_fir_tap_size 1473 | param_dict['fir_window'] = cfg_fir_window 1474 | param_dict['en_filter_reset'] = 1 if len(en_filter_reset) else 0 1475 | param_dict['corr_size'] = cfg_corr_size 1476 | param_dict['std_ch_ind'] = cfg_std_ch_ind 1477 | param_dict['en_iq_cal'] = 1 if len(en_iq_cal) else 0 1478 | param_dict['gain_lock_interval'] = cfg_gain_lock 1479 | param_dict['require_track_lock_intervention'] = 1 if len(en_req_track_lock_intervention) else 0 1480 | param_dict['cal_track_mode'] = cfg_cal_track_mode 1481 | param_dict['amplitude_cal_mode'] = cfg_amplitude_cal_mode 1482 | param_dict['cal_frame_interval'] = cfg_cal_frame_interval 1483 | param_dict['cal_frame_burst_size'] = cfg_cal_frame_burst_size 1484 | param_dict['amplitude_tolerance'] = cfg_amplitude_tolerance 1485 | param_dict['phase_tolerance'] = cfg_phase_tolerance 1486 | param_dict['maximum_sync_fails'] = cfg_max_sync_fails 1487 | 1488 | webInterface_inst.daq_ini_cfg_dict = param_dict 1489 | 1490 | if ctx.triggered: 1491 | # If we updated advanced daq, update basic DAQ params 1492 | if component_id == "cfg_sample_rate" or component_id == "cfg_decimation_ratio" or component_id == "cfg_cpi_size" or component_id == "cfg_cal_frame_interval": 1493 | if not cfg_sample_rate or not cfg_decimation_ratio or not cfg_cpi_size: 1494 | return Output('dummy_output', 'children', '') #[no_update, no_update, no_update, no_update] 1495 | 1496 | cfg_decimated_bw = ((int(cfg_sample_rate*10**6)) / cfg_decimation_ratio) / 10**3 1497 | cfg_data_block_len = ( cfg_cpi_size / (cfg_decimated_bw) ) 1498 | cfg_recal_interval = (cfg_cal_frame_interval * (cfg_data_block_len/10**3)) / 60 1499 | 1500 | app.push_mods({ 1501 | 'cfg_data_block_len': {'value': cfg_data_block_len}, 1502 | 'cfg_decimated_bw': {'value': cfg_decimated_bw}, 1503 | 'cfg_recal_interval': {'value': cfg_recal_interval}, 1504 | }) 1505 | # If we updated basic DAQ, update advanced DAQ 1506 | elif component_id == "cfg_data_block_len" or component_id == "cfg_decimated_bw" or component_id == "cfg_recal_interval": 1507 | app.push_mods({ 1508 | 'cfg_decimation_ratio': {'value': cfg_decimation_ratio}, 1509 | 'cfg_cpi_size': {'value': cfg_cpi_size}, 1510 | 'cfg_cal_frame_interval': {'value': cfg_cal_frame_interval}, 1511 | 'cfg_fir_tap_size': {'value': cfg_fir_tap_size}, 1512 | 'cfg_sample_rate': {'value': cfg_sample_rate}, 1513 | 'cfg_daq_buffer_size': {'value': cfg_daq_buffer_size}, 1514 | 'cfg_corr_size': {'value': cfg_corr_size}, 1515 | 'en_noise_source_ctr': {'value': en_noise_source_ctr}, 1516 | 'cfg_fir_bw': {'value': cfg_fir_bw}, 1517 | 'cfg_fir_window': {'value': cfg_fir_window}, 1518 | 'en_filter_reset': {'value': en_filter_reset}, 1519 | 'cfg_std_ch_ind': {'value': cfg_std_ch_ind}, 1520 | 'en_iq_cal': {'value': en_iq_cal}, 1521 | 'en_req_track_lock_intervention': {'value': en_req_track_lock_intervention}, 1522 | 'cfg_amplitude_cal_mode': {'value': cfg_amplitude_cal_mode}, 1523 | 'cfg_cal_frame_burst_size': {'value': cfg_cal_frame_burst_size}, 1524 | 'cfg_amplitude_tolerance': {'value': cfg_amplitude_tolerance}, 1525 | 'cfg_phase_tolerance': {'value': cfg_phase_tolerance}, 1526 | 'cfg_max_sync_fails': {'value': cfg_max_sync_fails}, 1527 | }) 1528 | 1529 | @app.callback(Output('adv-cfg-container', 'style'), 1530 | [Input("en_advanced_daq_cfg", "value")] 1531 | ) 1532 | def toggle_adv_daq(toggle_value): 1533 | webInterface_inst.en_advanced_daq_cfg = toggle_value 1534 | if toggle_value: 1535 | return {'display': 'block'} 1536 | else: 1537 | return {'display': 'none'} 1538 | 1539 | @app.callback( 1540 | None, 1541 | [Input(component_id="btn_reconfig_daq_chain" , component_property="n_clicks")], 1542 | [State(component_id ="daq_center_freq" , component_property='value'), 1543 | State(component_id ="daq_rx_gain" , component_property='value')] 1544 | ) 1545 | def reconfig_daq_chain(input_value, freq, gain): 1546 | 1547 | if input_value is None: 1548 | return Output('dummy_output', 'children', '') #[no_update, no_update, no_update, no_update] 1549 | 1550 | # TODO: Check data interface mode here ! 1551 | # Update DAQ Subsystem config file 1552 | 1553 | config_res, config_err = write_config_file_dict(webInterface_inst.daq_ini_cfg_dict) 1554 | if config_res: 1555 | webInterface_inst.daq_cfg_ini_error = config_err[0] 1556 | return Output("placeholder_recofnig_daq", "children", '-1') 1557 | else: 1558 | webInterface_inst.logger.info("DAQ Subsystem configuration file edited") 1559 | 1560 | # time.sleep(2) 1561 | 1562 | webInterface_inst.daq_restart = 1 1563 | # Restart DAQ Subsystem 1564 | # Stop signal processing 1565 | webInterface_inst.stop_processing() 1566 | # time.sleep(2) 1567 | webInterface_inst.logger.debug("Signal processing stopped") 1568 | 1569 | # Close control and IQ data interfaces 1570 | webInterface_inst.close_data_interfaces() 1571 | webInterface_inst.logger.debug("Data interfaces are closed") 1572 | 1573 | os.chdir(daq_subsystem_path) 1574 | # Kill DAQ subsystem 1575 | daq_stop_script = subprocess.Popen(['bash', daq_stop_filename])#, stdout=subprocess.DEVNULL) 1576 | daq_stop_script.wait() 1577 | webInterface_inst.logger.debug("DAQ Subsystem halted") 1578 | 1579 | # Start DAQ subsystem 1580 | daq_start_script = subprocess.Popen(['bash', daq_start_filename])#, stdout=subprocess.DEVNULL) 1581 | daq_start_script.wait() 1582 | webInterface_inst.logger.debug("DAQ Subsystem restarted") 1583 | 1584 | os.chdir(root_path) 1585 | 1586 | # Reinitialize receiver data interface 1587 | #if webInterface_inst.module_receiver.init_data_iface() == -1: 1588 | # webInterface_inst.logger.critical("Failed to restart the DAQ data interface") 1589 | # webInterface_inst.daq_cfg_ini_error = "Failed to restart the DAQ data interface" 1590 | # return [-1] 1591 | 1592 | # Reset channel number count 1593 | #webInterface_inst.module_signal_processor.first_frame = 1 1594 | 1595 | en_PR = webInterface_inst.module_signal_processor.en_PR 1596 | PR_clutter_cancellation = webInterface_inst.module_signal_processor.PR_clutter_cancellation 1597 | max_bistatic_range = webInterface_inst.module_signal_processor.max_bistatic_range 1598 | max_doppler = webInterface_inst.module_signal_processor.max_doppler 1599 | en_persist = webInterface_inst.en_persist 1600 | pr_persist_decay = webInterface_inst.pr_persist_decay 1601 | pr_dynamic_range_min = webInterface_inst.pr_dynamic_range_min 1602 | pr_dynamic_range_max = webInterface_inst.pr_dynamic_range_max 1603 | 1604 | # Recreate and reinit the receiver and signal processor modules from scratch, keeping current setting values 1605 | daq_center_freq = webInterface_inst.module_receiver.daq_center_freq 1606 | daq_rx_gain = webInterface_inst.module_receiver.daq_rx_gain 1607 | rec_ip_addr = webInterface_inst.module_receiver.rec_ip_addr 1608 | 1609 | logging_level = webInterface_inst.logging_level 1610 | data_interface = webInterface_inst.data_interface 1611 | 1612 | webInterface_inst.module_receiver = ReceiverRTLSDR(data_que=webInterface_inst.rx_data_que, data_interface=data_interface, logging_level=logging_level) 1613 | webInterface_inst.module_receiver.daq_center_freq = daq_center_freq 1614 | webInterface_inst.module_receiver.daq_rx_gain = daq_rx_gain #settings.uniform_gain #daq_rx_gain 1615 | webInterface_inst.module_receiver.rec_ip_addr = rec_ip_addr 1616 | 1617 | webInterface_inst.module_signal_processor = SignalProcessor(data_que=webInterface_inst.sp_data_que, module_receiver=webInterface_inst.module_receiver, logging_level=logging_level) 1618 | webInterface_inst.module_signal_processor.en_PR = en_PR 1619 | webInterface_inst.module_signal_processor.PR_clutter_cancellation = PR_clutter_cancellation 1620 | webInterface_inst.module_signal_processor.max_bistatic_range = max_bistatic_range 1621 | webInterface_inst.module_signal_processor.max_doppler = max_doppler 1622 | webInterface_inst.en_persist = en_persist 1623 | webInterface_inst.pr_persist_decay = pr_persist_decay 1624 | webInterface_inst.pr_dynamic_range_min = pr_dynamic_range_min 1625 | webInterface_inst.pr_dynamic_range_max = pr_dynamic_range_max 1626 | 1627 | webInterface_inst.module_signal_processor.start() 1628 | 1629 | # This must be here, otherwise the gains dont reinit properly? 1630 | #webInterface_inst.module_receiver.M = webInterface_inst.daq_ini_cfg_params[1] 1631 | webInterface_inst.module_receiver.M = webInterface_inst.daq_ini_cfg_dict['num_ch'] 1632 | 1633 | # Restart signal processing 1634 | webInterface_inst.start_processing() 1635 | webInterface_inst.logger.debug("Signal processing started") 1636 | webInterface_inst.daq_restart = 0 1637 | 1638 | webInterface_inst.daq_cfg_ini_error = "" 1639 | webInterface_inst.active_daq_ini_cfg = webInterface_inst.daq_ini_cfg_dict['config_name'] 1640 | 1641 | return Output("daq_cfg_files", "value", daq_config_filename), Output("active_daq_ini_cfg", "children", "Active Configuration: " + webInterface_inst.active_daq_ini_cfg) 1642 | 1643 | 1644 | if __name__ == "__main__": 1645 | # For Development only, otherwise use gunicorn 1646 | # Debug mode does not work when the data interface is set to shared-memory "shmem"! 1647 | app.run_server(debug=False, host="0.0.0.0", port=8080) 1648 | #waitress #serve(app.server, host="0.0.0.0", port=8050) 1649 | 1650 | """ 1651 | html.Div([ 1652 | html.H2("System Logs"), 1653 | dcc.Textarea( 1654 | placeholder = "Enter a value...", 1655 | value = "System logs .. - Curently NOT used", 1656 | style = {"width": "100%", "background-color": "#000000", "color":"#02c93d"} 1657 | ) 1658 | ], className="card") 1659 | """ 1660 | --------------------------------------------------------------------------------