diff --git a/MANIFEST.in b/MANIFEST.in index 2c26807f..7e61ecec 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,7 +1,9 @@ include python_hackrf/pyhackrf_tools/pyhackrf_transfer.pyi -include python_hackrf/pyhackrf_tools/pyhackrf_transfer.pxd +include python_hackrf/pyhackrf_tools/pyhackrf_transfer.pyx include python_hackrf/pyhackrf_tools/pyhackrf_sweep.pyi -include python_hackrf/pyhackrf_tools/pyhackrf_sweep.pxd +include python_hackrf/pyhackrf_tools/pyhackrf_sweep.pyx +include python_hackrf/pyhackrf_tools/pyhackrf_scan.pyi +include python_hackrf/pyhackrf_tools/pyhackrf_scan.pyx include python_hackrf/pylibhackrf/pyhackrf.pyi include python_hackrf/pylibhackrf/pyhackrf.pyx include python_hackrf/pylibhackrf/pyhackrf.pxd diff --git a/README.md b/README.md index f1bcebc9..0eba4c04 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ set PYTHON_HACKRF_LIB_PATH=path_to_libhackrf.dll dir ## Requirements: * Numpy>=2.2.1 -* Cython==0.29.37 +* Cython>=3.1.0,<3.2.1 * Scipy (optional, for faster work) * pyFFTW (optional, for faster work) * pyjnius and android (only for android) diff --git a/android/python_hackrf/__init__.py b/android/python_hackrf/__init__.py index 8c788fcb..7d2c71c7 100644 --- a/android/python_hackrf/__init__.py +++ b/android/python_hackrf/__init__.py @@ -15,7 +15,7 @@ class PythonHackrfRecipe(PyProjectRecipe): hostpython_prerequisites = ['Cython>=3.1.0,<3.2'] site_packages_name = 'python_hackrf' name = 'python_hackrf' - version = '1.4.0' + version = '1.5.0' def get_recipe_env(self, arch: Arch, **kwargs) -> dict[str, Any]: env: dict[str, Any] = super().get_recipe_env(arch, **kwargs) @@ -32,5 +32,9 @@ def get_recipe_env(self, arch: Arch, **kwargs) -> dict[str, Any]: return env + def build_arch(self, arch: Arch) -> None: + super().build_arch(arch) + self.restore_hostpython_prerequisites(['cython']) + recipe = PythonHackrfRecipe() diff --git a/pyproject.toml b/pyproject.toml index aa0498c4..9307b260 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "python_hackrf" -version = "1.4.0" +version = "1.5.0" authors = [ {name="Leonid Gvozdev", email="leo.gvozdev.dev@gmail.com"}, ] @@ -26,10 +26,11 @@ dependencies = [ [build-system] requires = [ - "Cython>=3.1.0,<3.2", + "Cython>=3.1.0,<3.2.1", "setuptools", "wheel", "numpy", + "tomli ; python_version < '3.11'", ] [project.scripts] diff --git a/python_hackrf/__init__.py b/python_hackrf/__init__.py index 87819510..4250a759 100644 --- a/python_hackrf/__init__.py +++ b/python_hackrf/__init__.py @@ -1,10 +1,11 @@ -__version__ = '1.4.0' +__version__ = '1.5.0' from python_hackrf.pylibhackrf import pyhackrf # noqa F401 from python_hackrf.pyhackrf_tools import ( # noqa F401 pyhackrf_operacake, pyhackrf_transfer, pyhackrf_sweep, + pyhackrf_scan, pyhackrf_info, utils, ) diff --git a/python_hackrf/pyhackrf_tools/__init__.py b/python_hackrf/pyhackrf_tools/__init__.py index b2f32036..7fc8077b 100644 --- a/python_hackrf/pyhackrf_tools/__init__.py +++ b/python_hackrf/pyhackrf_tools/__init__.py @@ -1,5 +1,6 @@ from . import pyhackrf_operacake # noqa F401 from . import pyhackrf_transfer # noqa F401 from . import pyhackrf_sweep # noqa F401 +from . import pyhackrf_scan # noqa F401 from . import pyhackrf_info # noqa F401 from . import utils # noqa F401 diff --git a/python_hackrf/pyhackrf_tools/pyhackrf_scan.pyi b/python_hackrf/pyhackrf_tools/pyhackrf_scan.pyi new file mode 100644 index 00000000..9942cad2 --- /dev/null +++ b/python_hackrf/pyhackrf_tools/pyhackrf_scan.pyi @@ -0,0 +1,10 @@ +def stop_all() -> None: + ... + +def stop_sdr(serialno: str) -> None: + ... + +def pyhackrf_scan(frequencies: list[int], samples_per_scan: int, queue: object, sample_rate: int = 20_000_000, baseband_filter_bandwidth: int | None = None, + lna_gain: int = 16, vga_gain: int = 20, amp_enable: bool = False, antenna_enable: bool = False, serial_number: str | None = None, + print_to_console: bool = True) -> None: + ... diff --git a/python_hackrf/pyhackrf_tools/pyhackrf_scan.pyx b/python_hackrf/pyhackrf_tools/pyhackrf_scan.pyx new file mode 100644 index 00000000..a6fcc16b --- /dev/null +++ b/python_hackrf/pyhackrf_tools/pyhackrf_scan.pyx @@ -0,0 +1,306 @@ +# MIT License + +# Copyright (c) 2023-2025 GvozdevLeonid + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# distutils: language = c++ +# cython: language_level = 3str +# cython: freethreading_compatible = True +from libc.stdint cimport uint64_t, uint32_t, uint8_t +from python_hackrf.pylibhackrf cimport pyhackrf as c_pyhackrf +from python_hackrf import pyhackrf +from libcpp.atomic cimport atomic +cimport numpy as cnp +import numpy as np +import threading +import signal +import time +import sys +import os + +cnp.import_array() +FREQ_MIN_MHZ = 0 # 70 MHz +FREQ_MAX_MHZ = 7_250 # 6000 MHZ +FREQ_MIN_HZ = int(FREQ_MIN_MHZ * 1e6) # Hz +FREQ_MAX_HZ = int(FREQ_MAX_MHZ * 1e6) # Hz +AVAILABLE_SAMPLING_RATES = (2_000_000, 4_000_000, 6_000_000, 8_000_000, 10_000_000, 12_000_000, 14_000_000, 16_000_000, 18_000_000, 20_000_000) +AVAILABLE_BASEBAND_FILTER_BANDWIDTHS = (1_750_000, 2_500_000, 3_500_000, 5_000_000, 5_500_000, 6_000_000, 7_000_000, 8_000_000, 9_000_000, 10_000_000, 12_000_000, 14_000_000, 15_000_000, 20_000_000, 24_000_000, 28_000_000) + + +cdef atomic[uint8_t] working_sdrs[16] +cdef dict sdr_ids = {} + +def sigint_callback_handler(sig, frame, sdr_id): + global working_sdrs + working_sdrs[sdr_id].store(0) + + +def init_signals() -> int: + global working_sdrs + + sdr_id = -1 + for i in range(16): + if working_sdrs[i].load() == 0: + sdr_id = i + break + + if sdr_id >= 0: + try: + signal.signal(signal.SIGINT, lambda sig, frame: sigint_callback_handler(sig, frame, sdr_id)) + signal.signal(signal.SIGILL, lambda sig, frame: sigint_callback_handler(sig, frame, sdr_id)) + signal.signal(signal.SIGTERM, lambda sig, frame: sigint_callback_handler(sig, frame, sdr_id)) + signal.signal(signal.SIGABRT, lambda sig, frame: sigint_callback_handler(sig, frame, sdr_id)) + except Exception as ex: + sys.stderr.write(f'Error: {ex}\n') + + return sdr_id + + +def stop_all() -> None: + global working_sdrs + for i in range(16): + working_sdrs[i].store(0) + + +def stop_sdr(serialno: str) -> None: + global sdr_ids, working_sdrs + if serialno in sdr_ids: + working_sdrs[sdr_ids[serialno]].store(0) + + +cpdef int rx_callback(c_pyhackrf.PyHackrfDevice device, cnp.ndarray[cnp.int8_t, ndim=1] buffer, int buffer_length, int valid_length): + global working_sdrs + + cdef dict device_data = device.device_data + cdef uint8_t device_id = device_data['device_id'] + cdef double divider = 1 / 128 + + if not working_sdrs[device_id].load(): + device_data['close_ready'].set() + device_data['hop_ready'].set() + return -1 + + cdef uint64_t to_read = valid_length + if device_data['num_samples'] > 0: + device_data['accepted_bytes'] += valid_length + + if (to_read > device_data['num_samples'] * 2): + to_read = device_data['num_samples'] * 2 + + device_data['buffer'][device_data['samples_per_scan'] - device_data['num_samples']: device_data['samples_per_scan'] - device_data['num_samples'] + (to_read // 2)] = (buffer[:to_read:2] * divider + 1j * buffer[1:to_read:2] * divider).astype(np.complex64) + device_data['num_samples'] -= (to_read // 2) + + if device_data['num_samples'] == 0: + device_data['hop_ready'].set() + else: + return -1 + + return 0 + + +def pyhackrf_scan(frequencies: list[int], samples_per_scan: int, queue: object, sample_rate: int = 20_000_000, baseband_filter_bandwidth: int | None = None, + lna_gain: int = 16, vga_gain: int = 20, amp_enable: bool = False, antenna_enable: bool = False, serial_number: str | None = None, + print_to_console: bool = True) -> None: + + global working_sdrs, sdr_ids + + cdef uint8_t device_id = init_signals() + cdef c_pyhackrf.PyHackrfDevice device + + pyhackrf.pyhackrf_init() + + if serial_number is None: + device = pyhackrf.pyhackrf_open() + else: + device = pyhackrf.pyhackrf_open_by_serial(serial_number) + + working_sdrs[device_id].store(1) + sdr_ids[device.serialno] = device_id + + sample_rate = int(sample_rate) if int(sample_rate) in AVAILABLE_SAMPLING_RATES else 20_000_000 + cdef uint64_t offset = int(sample_rate // 2) + + if baseband_filter_bandwidth is None: + baseband_filter_bandwidth = int(sample_rate * .75) + baseband_filter_bandwidth = int(baseband_filter_bandwidth) if int(baseband_filter_bandwidth) in AVAILABLE_BASEBAND_FILTER_BANDWIDTHS else pyhackrf.pyhackrf_compute_baseband_filter_bw(int(sample_rate * .75)) + + if print_to_console: + sys.stderr.write(f'call pyhackrf_set_sample_rate({sample_rate / 1e6 :.3f} MHz)\n') + device.pyhackrf_set_sample_rate(sample_rate) + + if print_to_console: + sys.stderr.write(f'call pyhackrf_set_baseband_filter_bandwidth({baseband_filter_bandwidth / 1e6 :.3f} MHz)\n') + device.pyhackrf_set_baseband_filter_bandwidth(baseband_filter_bandwidth) + + if lna_gain % 8 and print_to_console: + sys.stderr.write('Warning: lna_gain must be a multiple of 8\n') + + if vga_gain % 2 and print_to_console: + sys.stderr.write('Warning: vga_gain must be a multiple of 2\n') + + device.pyhackrf_set_lna_gain(lna_gain) + device.pyhackrf_set_vga_gain(vga_gain) + + if amp_enable: + if print_to_console: + sys.stderr.write('call pyhackrf_set_amp_enable(True)\n') + device.pyhackrf_set_amp_enable(True) + + if antenna_enable: + if print_to_console: + sys.stderr.write('call pyhackrf_set_antenna_enable(True)\n') + device.pyhackrf_set_antenna_enable(True) + + num_ranges = len(frequencies) // 2 + calculated_frequencies = [] + if pyhackrf.PY_MAX_SWEEP_RANGES < num_ranges: + RuntimeError(f'specify a maximum of {pyhackrf.PY_MAX_SWEEP_RANGES} frequency ranges') + + for i in range(num_ranges): + frequencies[2 * i] = int(frequencies[2 * i] * 1e6) + frequencies[2 * i + 1] = int(frequencies[2 * i + 1] * 1e6) + + if frequencies[2 * i] >= frequencies[2 * i + 1]: + raise RuntimeError('max frequency must be greater than min frequency.') + + if frequencies[2 * i] < FREQ_MIN_HZ: + raise RuntimeError(f'min frequency must must be greater than {FREQ_MIN_MHZ} MHz.') + if frequencies[2 * i + 1] > FREQ_MAX_HZ: + raise RuntimeError(f'max frequency may not be higher {FREQ_MAX_MHZ} MHz.') + + step_count = 1 + (frequencies[2 * i + 1] - frequencies[2 * i] - 1) // sample_rate + frequencies[2 * i + 1] = int(frequencies[2 * i] + step_count * sample_rate) + + frequency = frequencies[2 * i] + for j in range(step_count): + calculated_frequencies.append(frequency) + frequency += sample_rate + + if print_to_console: + sys.stderr.write(f'Scaning from {frequencies[2 * i] / 1e6} MHz to {frequencies[2 * i + 1] / 1e6} MHz\n') + + cdef cnp.ndarray buffer = np.empty(samples_per_scan, dtype=np.complex64) + cdef dict device_data = { + 'device_id': device_id, + + 'accepted_bytes': 0, + + 'samples_per_scan': samples_per_scan, + 'num_samples': samples_per_scan, + 'close_ready': threading.Event(), + 'hop_ready': threading.Event(), + + 'buffer': buffer, + } + + device.device_data = device_data + device.set_rx_callback(rx_callback) + + cdef double time_start = time.time() + cdef double time_prev = time.time() + cdef double timestamp = time.time() + cdef double time_difference = 0 + cdef double scan_rate = 0 + cdef double time_now = 0 + cdef uint64_t scan_count = 0 + cdef uint32_t tune_step = 0 + cdef uint32_t tune_steps = len(calculated_frequencies) + cdef double delay = float(os.environ.get('pyhackrf_scan_await_time', 0.0002)) + + device.pyhackrf_set_freq(calculated_frequencies[tune_step] + offset) + device.pyhackrf_start_rx() + + while device.pyhackrf_is_streaming() and working_sdrs[device_id].load(): + time_now = time.time() + time_difference = time_now - time_prev + + if time_difference >= 1.0: + if print_to_console: + scan_rate = scan_count / (time_now - time_start) + sys.stderr.write(f'{scan_count} total scans completed, {round(scan_rate, 2)} scans/second\n') + + if device_data['accepted_bytes'] == 0: + if print_to_console: + sys.stderr.write('Couldn\'t transfer any data for one second.\n') + break + + device_data['accepted_bytes'] = 0 + time_prev = time_now + + if device_data['hop_ready'].wait(): + device_data['hop_ready'].clear() + device.pyhackrf_stop_rx() + + queue.put({ + 'start_frequency': calculated_frequencies[tune_step], + 'stop_frequency': calculated_frequencies[tune_step] + sample_rate, + 'raw_iq': buffer.copy(), + 'timestamp': timestamp, + }) + + tune_step = (tune_step + 1) % tune_steps + device.pyhackrf_set_freq(calculated_frequencies[tune_step] + offset) + time.sleep(delay) + + if tune_step == 0: + scan_count += 1 + + device_data['num_samples'] = samples_per_scan + + timestamp = time.time() + device.pyhackrf_start_rx() + + if print_to_console: + if not working_sdrs[device_id].load(): + sys.stderr.write('\nExiting...\n') + else: + sys.stderr.write('\nExiting... [ pyhackrf streaming stopped ]\n') + + time_now = time.time() + time_difference = time_now - time_prev + if scan_rate == 0 and time_difference > 0: + scan_rate = scan_count / (time_now - time_start) + + if print_to_console: + sys.stderr.write(f'Total scans: {scan_count} in {time_now - time_start:.5f} seconds ({scan_rate :.2f} scans/second)\n') + + working_sdrs[device_id].store(0) + device_data['close_ready'].wait() + sdr_ids.pop(device.serialno, None) + + if antenna_enable: + try: + device.pyhackrf_set_antenna_enable(False) + except Exception as e: + sys.stderr.write(f'{e}\n') + + try: + device.pyhackrf_close() + if print_to_console: + sys.stderr.write('pyhackrf_close() done\n') + except Exception as e: + sys.stderr.write(f'{e}\n') + + try: + pyhackrf.pyhackrf_exit() + if print_to_console: + sys.stderr.write('pyhackrf_exit() done\n') + except Exception as e: + sys.stderr.write(f'{e}\n') diff --git a/python_hackrf/pyhackrf_tools/pyhackrf_sweep.pyx b/python_hackrf/pyhackrf_tools/pyhackrf_sweep.pyx index f2bbfffd..719ea2a7 100644 --- a/python_hackrf/pyhackrf_tools/pyhackrf_sweep.pyx +++ b/python_hackrf/pyhackrf_tools/pyhackrf_sweep.pyx @@ -21,7 +21,8 @@ # SOFTWARE. # distutils: language = c++ -# cython: language_level=3str +# cython: language_level = 3str +# cython: freethreading_compatible = True try: from pyfftw.interfaces.numpy_fft import fft, fftshift # type: ignore except ImportError: @@ -36,6 +37,7 @@ from python_hackrf import pyhackrf from libcpp.atomic cimport atomic cimport numpy as cnp import numpy as np +import threading import datetime cimport cython import signal @@ -45,9 +47,10 @@ import sys cnp.import_array() -PY_FREQ_MIN_MHZ = 0 # 0 MHz -PY_FREQ_MAX_MHZ = 7_250 # 7250 MHz -PY_FREQ_MAX_HZ = PY_FREQ_MAX_MHZ * 1e6 # Hz +FREQ_MIN_MHZ = 0 # 0 MHz +FREQ_MAX_MHZ = 7_250 # 7250 MHz +FREQ_MIN_HZ = int(FREQ_MIN_MHZ * 1e6) # HZ +FREQ_MAX_HZ = int(FREQ_MAX_MHZ * 1e6) # Hz PY_BLOCKS_PER_TRANSFER = 16 # hackrf sweep settings @@ -106,18 +109,20 @@ cpdef int sweep_callback(c_pyhackrf.PyHackrfDevice device, cnp.ndarray[cnp.int8_ cdef str time_str = datetime.datetime.now().strftime('%Y-%m-%d, %H:%M:%S.%f') cdef dict device_data = device.device_data - cdef double norm_factor = 1 / device_data['fft_size'] cdef uint32_t data_length = device_data['fft_size'] * 2 cdef object sweep_style = device_data['sweep_style'] cdef uint32_t sample_rate = device_data['sample_rate'] cdef uint32_t fft_size = device_data['fft_size'] cdef cnp.ndarray window = device_data['window'] + cdef double psd_norm = device_data['psd_norm'] cdef uint8_t device_id = device_data['device_id'] + cdef double divider = 1 / 128 cdef uint64_t start_frequency = device_data['start_frequency'] - cdef cnp.ndarray fftOut - cdef cnp.ndarray pwr + cdef cnp.ndarray fft_out + cdef cnp.ndarray raw_iq + cdef cnp.ndarray dbfs cdef uint32_t fft_1_start = 1 + (fft_size * 5) // 8 cdef uint32_t fft_1_stop = 1 + (fft_size * 5) // 8 + fft_size // 4 @@ -148,23 +153,25 @@ cpdef int sweep_callback(c_pyhackrf.PyHackrfDevice device, cnp.ndarray[cnp.int8_ device_data['sweep_started'] = True if not working_sdrs[device_id].load(): + device_data['close_ready'].set() return -1 if not device_data['sweep_started']: index += pyhackrf.PY_BYTES_PER_BLOCK continue - if PY_FREQ_MAX_HZ < frequency: + if FREQ_MAX_HZ < frequency: index += pyhackrf.PY_BYTES_PER_BLOCK continue index += (pyhackrf.PY_BYTES_PER_BLOCK - data_length) - fftOut = fft((buffer[index:index + data_length:2] / 128 + 1j * buffer[index + 1:index + data_length:2] / 128) * window) - pwr = np.log10(np.abs(fftOut * norm_factor) ** 2) * 10.0 + raw_iq = buffer[index:index + data_length:2] * divider + 1j * buffer[index + 1:index + data_length:2] * divider + fft_out = fft((raw_iq - raw_iq.mean()) * window) + dbfs = np.log10((fft_out.real**2 + fft_out.imag**2) * psd_norm + 1e-300) * 10.0 if sweep_style == pyhackrf.py_sweep_style.LINEAR: - pwr = fftshift(pwr) + dbfs = fftshift(dbfs) index += data_length @@ -174,18 +181,18 @@ cpdef int sweep_callback(c_pyhackrf.PyHackrfDevice device, cnp.ndarray[cnp.int8_ line = struct.pack('I', record_length) line += struct.pack('Q', frequency) line += struct.pack('Q', frequency + sample_rate // 4) - line += struct.pack('<' + 'f' * (fft_size // 4), *pwr[fft_1_start:fft_1_stop]) + line += struct.pack('<' + 'f' * (fft_size // 4), *dbfs[fft_1_start:fft_1_stop]) line += struct.pack('I', record_length) line += struct.pack('Q', frequency + sample_rate // 2) line += struct.pack('Q', frequency + (sample_rate * 3) // 4) - line += struct.pack('<' + 'f' * (fft_size // 4), *pwr[fft_2_start:fft_2_stop]) + line += struct.pack('<' + 'f' * (fft_size // 4), *dbfs[fft_2_start:fft_2_stop]) else: record_length = 16 + fft_size * 4 line = struct.pack('I', record_length) line += struct.pack('Q', frequency) line += struct.pack('Q', frequency + sample_rate) - line += struct.pack('<' + 'f' * fft_size, *pwr) + line += struct.pack('<' + 'f' * fft_size, *dbfs) device_data['file'].write(line) @@ -195,13 +202,13 @@ cpdef int sweep_callback(c_pyhackrf.PyHackrfDevice device, cnp.ndarray[cnp.int8_ 'timestamp': time_str, 'start_frequency': frequency, 'stop_frequency': frequency + sample_rate // 4, - 'array': pwr[fft_1_start:fft_1_stop].astype(np.float32) + 'dbfs': dbfs[fft_1_start:fft_1_stop].astype(np.float32), }) device_data['queue'].put({ 'timestamp': time_str, 'start_frequency': frequency + sample_rate // 2, 'stop_frequency': frequency + (sample_rate * 3) // 4, - 'array': pwr[fft_2_start:fft_2_stop].astype(np.float32) + 'dbfs': dbfs[fft_2_start:fft_2_stop].astype(np.float32), }) else: @@ -209,23 +216,23 @@ cpdef int sweep_callback(c_pyhackrf.PyHackrfDevice device, cnp.ndarray[cnp.int8_ 'timestamp': time_str, 'start_frequency': frequency, 'stop_frequency': frequency + sample_rate, - 'array': pwr.astype(np.float32) + 'dbfs': dbfs.astype(np.float32), }) else: if sweep_style == pyhackrf.py_sweep_style.INTERLEAVED: line = f'{time_str}, {frequency}, {frequency + sample_rate // 4}, {sample_rate / fft_size}, {fft_size}, ' - for value in pwr[fft_1_start:fft_1_stop]: + for value in dbfs[fft_1_start:fft_1_stop]: line += f'{value:.10f}, ' line += f'\n{time_str}, {frequency + sample_rate // 2}, {frequency + (sample_rate * 3) // 4}, {sample_rate / fft_size}, {fft_size}, ' - for value in pwr[fft_2_start:fft_2_stop]: + for value in dbfs[fft_2_start:fft_2_stop]: line += f'{value:.10f}, ' line = line[:len(line) - 2] + '\n' else: line = f'{time_str}, {frequency}, {frequency + sample_rate}, {sample_rate / fft_size}, {fft_size}, ' - for i in range(len(pwr)): - line += f'{pwr[i]:.2f}, ' + for i in range(len(dbfs)): + line += f'{dbfs[i]:.2f}, ' line = line[:len(line) - 2] + '\n' device_data['file'].write(line) @@ -247,7 +254,6 @@ def pyhackrf_sweep(frequencies: list[int] | None = None, sample_rate: int = 20_0 cdef uint8_t device_id = init_signals() cdef c_pyhackrf.PyHackrfDevice device cdef uint32_t offset = 0 - cdef int i pyhackrf.pyhackrf_init() @@ -319,10 +325,10 @@ def pyhackrf_sweep(frequencies: list[int] | None = None, sample_rate: int = 20_0 step_count = 1 + (frequencies[2 * i + 1] - frequencies[2 * i] - 1) // TUNE_STEP frequencies[2 * i + 1] = int(frequencies[2 * i] + step_count * TUNE_STEP) - if frequencies[2 * i] < PY_FREQ_MIN_MHZ: - raise RuntimeError(f'min frequency must must be greater than {PY_FREQ_MIN_MHZ} MHz.') - if frequencies[2 * i + 1] > PY_FREQ_MAX_MHZ: - raise RuntimeError(f'max frequency may not be higher {PY_FREQ_MAX_MHZ} MHz.') + if frequencies[2 * i] < FREQ_MIN_MHZ: + raise RuntimeError(f'min frequency must must be greater than {FREQ_MIN_MHZ} MHz.') + if frequencies[2 * i + 1] > FREQ_MAX_MHZ: + raise RuntimeError(f'max frequency may not be higher {FREQ_MAX_MHZ} MHz.') if print_to_console: sys.stderr.write(f'Sweeping from {frequencies[2 * i]} MHz to {frequencies[2 * i + 1]} MHz\n') @@ -350,6 +356,8 @@ def pyhackrf_sweep(frequencies: list[int] | None = None, sample_rate: int = 20_0 'start_frequency': int(frequencies[0] * 1e6), 'fft_size': fft_size, 'window': np.hanning(fft_size), + 'psd_norm': 1 / (sample_rate * np.dot(np.hanning(fft_size), np.hanning(fft_size))), + 'close_ready': threading.Event(), 'binary_output': binary_output, 'one_shot': one_shot, @@ -402,9 +410,9 @@ def pyhackrf_sweep(frequencies: list[int] | None = None, sample_rate: int = 20_0 if print_to_console: sys.stderr.write(f'Total sweeps: {device_data["sweep_count"]} in {time_now - time_start:.5f} seconds ({sweep_rate :.2f} sweeps/second)\n') - sdr_ids.pop(device.serialno, None) working_sdrs[device_id].store(0) - device.device_data = {} + device_data['close_ready'].wait() + sdr_ids.pop(device.serialno, None) if antenna_enable: try: diff --git a/python_hackrf/pyhackrf_tools/pyhackrf_transfer.pyx b/python_hackrf/pyhackrf_tools/pyhackrf_transfer.pyx index a446a765..2c3297dc 100644 --- a/python_hackrf/pyhackrf_tools/pyhackrf_transfer.pyx +++ b/python_hackrf/pyhackrf_tools/pyhackrf_transfer.pyx @@ -21,7 +21,8 @@ # SOFTWARE. # distutils: language = c++ -# cython: language_level=3str +# cython: language_level = 3str +# cython: freethreading_compatible = True from python_hackrf.pylibhackrf cimport pyhackrf as c_pyhackrf from libc.stdint cimport uint64_t, uint8_t from python_hackrf import pyhackrf @@ -29,6 +30,7 @@ from libcpp.atomic cimport atomic from libcpp cimport bool as c_bool cimport numpy as cnp import numpy as np +import threading cimport cython import signal import time @@ -102,6 +104,7 @@ cpdef int rx_callback(c_pyhackrf.PyHackrfDevice device, cnp.ndarray[cnp.int8_t, cdef uint8_t device_id = device_data['device_id'] if not working_sdrs[device_id].load(): + device_data['close_ready'].set() return -1 device_data['byte_count'] += valid_length @@ -122,6 +125,7 @@ cpdef int rx_callback(c_pyhackrf.PyHackrfDevice device, cnp.ndarray[cnp.int8_t, if device_data['num_samples'] == 0: working_sdrs[device_id].store(0) + device_data['close_ready'].set() return -1 return 0 @@ -136,6 +140,7 @@ cpdef int tx_callback(c_pyhackrf.PyHackrfDevice device, cnp.ndarray[cnp.int8_t, cdef uint8_t device_id = device_data['device_id'] if device_data['tx_complete'] or not working_sdrs[device_id].load(): + device_data['close_ready'].set() valid_length = 0 return -1 @@ -160,6 +165,7 @@ cpdef int tx_callback(c_pyhackrf.PyHackrfDevice device, cnp.ndarray[cnp.int8_t, # buffer is empty or finished device_data['tx_complete'] = True working_sdrs[device_id].store(0) + device_data['close_ready'].set() valid_length = 0 return -1 @@ -171,6 +177,7 @@ cpdef int tx_callback(c_pyhackrf.PyHackrfDevice device, cnp.ndarray[cnp.int8_t, if device_data['num_samples'] == 0: device_data['tx_complete'] = True working_sdrs[device_id].store(0) + device_data['close_ready'].set() valid_length = writed * 2 return 0 @@ -181,7 +188,9 @@ cpdef int tx_callback(c_pyhackrf.PyHackrfDevice device, cnp.ndarray[cnp.int8_t, writed = len(raw_data) // 8 elif device_data['tx_file'].tell() < 1: # file is empty + device_data['tx_complete'] = True working_sdrs[device_id].store(0) + device_data['close_ready'].set() valid_length = 0 return -1 else: @@ -196,6 +205,7 @@ cpdef int tx_callback(c_pyhackrf.PyHackrfDevice device, cnp.ndarray[cnp.int8_t, if device_data['num_samples'] == 0: device_data['tx_complete'] = True working_sdrs[device_id].store(0) + device_data['close_ready'].set() valid_length = writed * 2 return 0 @@ -208,6 +218,7 @@ cpdef int tx_callback(c_pyhackrf.PyHackrfDevice device, cnp.ndarray[cnp.int8_t, if not device_data['repeat_tx']: device_data['tx_complete'] = True working_sdrs[device_id].store(0) + device_data['close_ready'].set() valid_length = writed * 2 return 0 @@ -220,6 +231,7 @@ cpdef int tx_callback(c_pyhackrf.PyHackrfDevice device, cnp.ndarray[cnp.int8_t, else: device_data['tx_complete'] = True working_sdrs[device_id].store(0) + device_data['close_ready'].set() valid_length = writed * 2 return 0 @@ -244,6 +256,7 @@ cpdef void tx_complete_callback(c_pyhackrf.PyHackrfDevice device, cnp.ndarray[cn if not success: working_sdrs[device_id].store(0) + device_data['close_ready'].set() return device_data['byte_count'] += valid_length @@ -260,6 +273,7 @@ cpdef void flush_callback(c_pyhackrf.PyHackrfDevice device, c_bool success): device_data['flush_complete'] = True working_sdrs[device_id].store(0) + device_data['close_ready'].set() def pyhackrf_transfer(frequency: int | None = None, sample_rate: int = 10_000_000, baseband_filter_bandwidth: int | None = None, i_frequency: int | None = None, lo_frequency: int | None = None, image_reject: pyhackrf.py_rf_path_filter = pyhackrf.py_rf_path_filter.RF_PATH_FILTER_BYPASS, @@ -370,11 +384,14 @@ def pyhackrf_transfer(frequency: int | None = None, sample_rate: int = 10_000_00 'stream_power': 0, 'byte_count': 0, + 'close_ready': threading.Event(), + 'rx_file': open(rx_filename, 'wb') if rx_filename not in ('-', None) else (sys.stdout.buffer if rx_filename == '-' else None), 'tx_file': open(tx_filename, 'rb') if tx_filename not in ('-', None) else (sys.stdin.buffer if tx_filename == '-' else None), 'rx_buffer': rx_buffer, 'tx_buffer': tx_buffer } + device.device_data = device_data if antenna_enable: @@ -414,6 +431,7 @@ def pyhackrf_transfer(frequency: int | None = None, sample_rate: int = 10_000_00 cdef uint64_t byte_count = 0 cdef uint64_t stream_power = 0 cdef double dB_full_scale = 0 + while working_sdrs[device_id].load(): time.sleep(0.05) time_now = time.time() @@ -444,7 +462,10 @@ def pyhackrf_transfer(frequency: int | None = None, sample_rate: int = 10_000_00 if print_to_console: sys.stderr.write(f'Total time: {time_now - time_start:.5f} seconds\n') - time.sleep(.5) + + working_sdrs[device_id].store(0) + device_data['close_ready'].wait() + sdr_ids.pop(device.serialno, None) if rx_filename not in ('-', None): device_data['rx_file'].close() @@ -468,10 +489,6 @@ def pyhackrf_transfer(frequency: int | None = None, sample_rate: int = 10_000_00 except Exception as e: sys.stderr.write(f'{e}\n') - sdr_ids.pop(device.serialno, None) - working_sdrs[device_id].store(0) - device.device_data = {} - if antenna_enable: try: device.pyhackrf_set_antenna_enable(False) diff --git a/python_hackrf/pylibhackrf/chackrf.pxd b/python_hackrf/pylibhackrf/chackrf.pxd index 903cbda8..2661b10a 100644 --- a/python_hackrf/pylibhackrf/chackrf.pxd +++ b/python_hackrf/pylibhackrf/chackrf.pxd @@ -21,10 +21,11 @@ # SOFTWARE. # distutils: language = c++ -# cython: language_level=3str +# cython: language_level = 3str +# cython: freethreading_compatible = True from libc.stdint cimport * -cdef extern from 'hackrf.h': +cdef extern from 'hackrf.h' nogil: int SAMPLES_PER_BLOCK int BYTES_PER_BLOCK int MAX_SWEEP_RANGES @@ -321,7 +322,7 @@ cdef extern from 'hackrf.h': int hackrf_set_user_bias_t_opts(hackrf_device *device, hackrf_bias_t_user_settting_req *req) IF ANDROID: - cdef extern from 'hackrf.h': + cdef extern from 'hackrf.h' nogil: int hackrf_init_on_android() int hackrf_open_on_android(int fileDescriptor, hackrf_device **device) diff --git a/python_hackrf/pylibhackrf/pyhackrf.pxd b/python_hackrf/pylibhackrf/pyhackrf.pxd index 8febb3bb..ad8e67c8 100644 --- a/python_hackrf/pylibhackrf/pyhackrf.pxd +++ b/python_hackrf/pylibhackrf/pyhackrf.pxd @@ -20,7 +20,9 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -# cython: language_level=3str +# distutils: language = c++ +# cython: language_level = 3str +# cython: freethreading_compatible = True from . cimport chackrf cdef class PyHackrfDevice: diff --git a/python_hackrf/pylibhackrf/pyhackrf.pyx b/python_hackrf/pylibhackrf/pyhackrf.pyx index f6bce18f..2a80595c 100644 --- a/python_hackrf/pylibhackrf/pyhackrf.pyx +++ b/python_hackrf/pylibhackrf/pyhackrf.pyx @@ -21,7 +21,8 @@ # SOFTWARE. # distutils: language = c++ -# cython: language_level=3str +# cython: language_level = 3str +# cython: freethreading_compatible = True from python_hackrf import __version__ from libc.stdint cimport uint8_t, uint16_t, uint32_t, uint64_t, uintptr_t from libc.stdlib cimport malloc, free @@ -154,12 +155,13 @@ class py_operacake_ports(IntEnum): @cython.boundscheck(False) @cython.wraparound(False) cdef int __rx_callback(chackrf.hackrf_transfer *transfer) noexcept nogil: - global global_callbacks + cdef uint8_t* buffer_ptr = transfer.buffer cdef uint8_t* np_buffer_ptr cdef int result = -1 with gil: + np_buffer = np.empty(transfer.buffer_length, dtype=np.int8) np_buffer_ptr = np_buffer.ctypes.data @@ -178,12 +180,12 @@ cdef int __rx_callback(chackrf.hackrf_transfer *transfer) noexcept nogil: @cython.boundscheck(False) @cython.wraparound(False) cdef int __tx_callback(chackrf.hackrf_transfer *transfer) noexcept nogil: - global global_callbacks cdef uint8_t* buffer_ptr = transfer.buffer cdef uint8_t* np_buffer_ptr cdef int result = -1 with gil: + np_buffer = np.empty(transfer.buffer_length, dtype=np.int8) valid_length = c_int(transfer.valid_length) np_buffer_ptr = np_buffer.ctypes.data @@ -206,12 +208,12 @@ cdef int __tx_callback(chackrf.hackrf_transfer *transfer) noexcept nogil: @cython.boundscheck(False) @cython.wraparound(False) cdef int __sweep_callback(chackrf.hackrf_transfer *transfer) noexcept nogil: - global global_callbacks cdef uint8_t* buffer_ptr = transfer.buffer cdef uint8_t* np_buffer_ptr cdef int result = -1 with gil: + np_buffer = np.empty(transfer.buffer_length, dtype=np.int8) np_buffer_ptr = np_buffer.ctypes.data @@ -230,11 +232,11 @@ cdef int __sweep_callback(chackrf.hackrf_transfer *transfer) noexcept nogil: @cython.boundscheck(False) @cython.wraparound(False) cdef void __tx_complete_callback(chackrf.hackrf_transfer *transfer, int success) noexcept nogil: - global global_callbacks cdef uint8_t* buffer_ptr = transfer.buffer cdef uint8_t* np_buffer_ptr with gil: + np_buffer = np.empty(transfer.buffer_length, dtype=np.int8) np_buffer_ptr = np_buffer.ctypes.data @@ -249,10 +251,10 @@ cdef void __tx_complete_callback(chackrf.hackrf_transfer *transfer, int success) cdef void __tx_flush_callback(void *flush_ctx, int success) noexcept nogil: - global global_callbacks cdef size_t device_ptr = flush_ctx with gil: + if global_callbacks[device_ptr]['__tx_flush_callback'] is not None: global_callbacks[device_ptr]['__tx_flush_callback'](global_callbacks[device_ptr]['device'], success) @@ -323,13 +325,14 @@ cdef class PyHackrfDevice: self.device_data = {} def __dealloc__(self): - global global_callbacks + cdef int result if self.__hackrf_device is not NULL: if self.__hackrf_device in global_callbacks.keys(): global_callbacks.pop( self.__hackrf_device) - result = chackrf.hackrf_close(self.__hackrf_device) + with nogil: + result = chackrf.hackrf_close(self.__hackrf_device) self.__hackrf_device = NULL raise_error('__dealloc__', result) @@ -342,8 +345,6 @@ cdef class PyHackrfDevice: return &self.__hackrf_device cdef void _setup_device(self): - global global_callbacks - if self.__hackrf_device is not NULL: self.serialno = self.pyhackrf_serialno_read() @@ -361,13 +362,16 @@ cdef class PyHackrfDevice: # ---- device ---- # def pyhackrf_close(self) -> None: - global global_callbacks + cdef int result + if self.__hackrf_device is not NULL: if self.__hackrf_device in global_callbacks.keys(): global_callbacks.pop( self.__hackrf_device) - result = chackrf.hackrf_close(self.__hackrf_device) + with nogil: + result = chackrf.hackrf_close(self.__hackrf_device) self.__hackrf_device = NULL + self.device_data.clear() raise_error('pyhackrf_close()', result) @@ -466,11 +470,21 @@ cdef class PyHackrfDevice: raise_error('pyhackrf_set_baseband_filter_bandwidth()', result) def pyhackrf_set_freq(self, freq_hz: int) -> None: - result = chackrf.hackrf_set_freq(self.__hackrf_device, freq_hz) + cdef int result + cdef uint64_t c_freq_hz = freq_hz + + with nogil: + result = chackrf.hackrf_set_freq(self.__hackrf_device, c_freq_hz) raise_error('pyhackrf_set_freq()', result) def pyhackrf_set_freq_explicit(self, i_freq_hz: int, lo_freq_hz: int, path: py_rf_path_filter) -> None: - result = chackrf.hackrf_set_freq_explicit(self.__hackrf_device, i_freq_hz, lo_freq_hz, path) + cdef int result + cdef chackrf.rf_path_filter c_path = path + cdef uint64_t c_i_freq_hz = i_freq_hz + cdef uint64_t c_lo_freq_hz = lo_freq_hz + + with nogil: + result = chackrf.hackrf_set_freq_explicit(self.__hackrf_device, c_i_freq_hz, c_lo_freq_hz, c_path) raise_error('pyhackrf_set_freq_explicit()', result) def pyhackrf_set_sample_rate_manual(self, freq_hz: int, divider: int) -> None: @@ -486,18 +500,27 @@ cdef class PyHackrfDevice: raise_error('pyhackrf_set_amp_enable()', result) def pyhackrf_set_lna_gain(self, value: int) -> None: - value = int(max(0, min(40, value)) / 8) * 8 - result = chackrf.hackrf_set_lna_gain(self.__hackrf_device, value) + cdef int result + cdef uint32_t c_value = int(max(0, min(40, value)) / 8) * 8 + + with nogil: + result = chackrf.hackrf_set_lna_gain(self.__hackrf_device, c_value) raise_error('pyhackrf_set_lna_gain()', result) def pyhackrf_set_vga_gain(self, value: int) -> None: - value = int(max(0, min(62, value)) / 2) * 2 - result = chackrf.hackrf_set_vga_gain(self.__hackrf_device, value) + cdef int result + cdef uint32_t c_value = int(max(0, min(62, value)) / 2) * 2 + + with nogil: + result = chackrf.hackrf_set_vga_gain(self.__hackrf_device, c_value) raise_error('pyhackrf_set_vga_gain()', result) def pyhackrf_set_txvga_gain(self, value: int) -> None: - value = int(max(0, min(47, value))) - result = chackrf.hackrf_set_txvga_gain(self.__hackrf_device, value) + cdef int result + cdef uint32_t c_value = int(max(0, min(47, value))) + + with nogil: + result = chackrf.hackrf_set_txvga_gain(self.__hackrf_device, c_value) raise_error('pyhackrf_set_txvga_gain()', result) def pyhackrf_set_antenna_enable(self, value: bool) -> None: @@ -516,7 +539,11 @@ cdef class PyHackrfDevice: # ---- streaming ---- # def pyhackrf_is_streaming(self) -> bool: - result = chackrf.hackrf_is_streaming(self.__hackrf_device) + cdef int result + + with nogil: + result = chackrf.hackrf_is_streaming(self.__hackrf_device) + if result == chackrf.hackrf_error.HACKRF_TRUE: return True elif result in (chackrf.hackrf_error.HACKRF_ERROR_STREAMING_THREAD_ERR, chackrf.hackrf_error.HACKRF_ERROR_STREAMING_STOPPED, chackrf.hackrf_error.HACKRF_ERROR_STREAMING_EXIT_CALLED): @@ -555,19 +582,27 @@ cdef class PyHackrfDevice: raise_error('pyhackrf_start_rx_sweep()', result) def pyhackrf_start_rx(self) -> None: + cdef int result result = chackrf.hackrf_start_rx(self.__hackrf_device, __rx_callback, NULL) raise_error('pyhackrf_start_rx()', result) def pyhackrf_stop_rx(self) -> None: - result = chackrf.hackrf_stop_rx(self.__hackrf_device) + cdef int result + + with nogil: + result = chackrf.hackrf_stop_rx(self.__hackrf_device) raise_error('pyhackrf_stop_rx()', result) def pyhackrf_start_tx(self) -> None: + cdef int result result = chackrf.hackrf_start_tx(self.__hackrf_device, __tx_callback, NULL) raise_error('pyhackrf_start_tx()', result) def pyhackrf_stop_tx(self) -> None: - result = chackrf.hackrf_stop_tx(self.__hackrf_device) + cdef int result + + with nogil: + result = chackrf.hackrf_stop_tx(self.__hackrf_device) raise_error('pyhackrf_stop_tx()', result) def pyhackrf_enable_tx_block_complete_callback(self) -> None: @@ -642,8 +677,6 @@ cdef class PyHackrfDevice: # ---- python callbacks setters ---- # def set_rx_callback(self, rx_callback_function) -> None: - global global_callbacks - if self.__hackrf_device is not NULL: global_callbacks[ self.__hackrf_device]['__rx_callback'] = rx_callback_function return @@ -651,8 +684,6 @@ cdef class PyHackrfDevice: raise RuntimeError(f'set_rx_callback() failed: Device not initialized!') def set_tx_callback(self, tx_callback_function) -> None: - global global_callbacks - if self.__hackrf_device is not NULL: global_callbacks[ self.__hackrf_device]['__tx_callback'] = tx_callback_function return @@ -660,8 +691,6 @@ cdef class PyHackrfDevice: raise RuntimeError(f'set_tx_callback() failed: Device not initialized!') def set_sweep_callback(self, sweep_callback_function) -> None: - global global_callbacks - if self.__hackrf_device is not NULL: global_callbacks[ self.__hackrf_device]['__sweep_callback'] = sweep_callback_function return @@ -669,8 +698,6 @@ cdef class PyHackrfDevice: raise RuntimeError(f'set_sweep_callback() failed: Device not initialized!') def set_tx_complete_callback(self, tx_complete_callback_function) -> None: - global global_callbacks - if self.__hackrf_device is not NULL: global_callbacks[ self.__hackrf_device]['__tx_complete_callback'] = tx_complete_callback_function return @@ -678,8 +705,6 @@ cdef class PyHackrfDevice: raise RuntimeError(f'set_tx_complete_callback() failed: Device not initialized!') def set_tx_flush_callback(self, tx_flush_callback_function) -> None: - global global_callbacks - if self.__hackrf_device is not NULL: global_callbacks[ self.__hackrf_device]['__tx_flush_callback'] = tx_flush_callback_function return diff --git a/setup.py b/setup.py index af4ea241..63e5b5b9 100644 --- a/setup.py +++ b/setup.py @@ -8,8 +8,8 @@ from setuptools.command.install import install from Cython.Build import cythonize -INSTALL_REQUIRES = ['Cython>=3.1.0,<3.2', 'numpy'] -SETUP_REQUIRES = ['Cython>=3.1.0,<3.2', 'numpy'] +INSTALL_REQUIRES = ['Cython>=3.1.0,<3.2.1', 'numpy'] +SETUP_REQUIRES = ['Cython>=3.1.0,<3.2.1', 'numpy'] libhackrf_h_paths = [] PLATFORM = sys.platform @@ -102,6 +102,7 @@ def run(self) -> None: # type: ignore Extension( # type: ignore name='python_hackrf.pylibhackrf.pyhackrf', sources=['python_hackrf/pylibhackrf/pyhackrf.pyx'], + libraries=['hackrf'], include_dirs=['python_hackrf/pylibhackrf', *libhackrf_h_paths, numpy.get_include()], extra_compile_args=['-w'], language='c++', @@ -113,6 +114,13 @@ def run(self) -> None: # type: ignore extra_compile_args=['-w'], language='c++', ), + Extension( # type: ignore + name='python_hackrf.pyhackrf_tools.pyhackrf_scan', + sources=['python_hackrf/pyhackrf_tools/pyhackrf_scan.pyx'], + include_dirs=['python_hackrf/pylibhackrf', 'python_hackrf/pyhackrf_tools', *libhackrf_h_paths, numpy.get_include()], + extra_compile_args=['-w'], + language='c++', + ), Extension( # type: ignore name='python_hackrf.pyhackrf_tools.pyhackrf_transfer', sources=['python_hackrf/pyhackrf_tools/pyhackrf_transfer.pyx'],