├── CHANGELOG.md
├── LICENSE
├── README.md
├── __pycache__
├── pyspecaprs.cpython-310.pyc
└── pyspecconst.cpython-310.pyc
├── gqrx2pss.py
├── pyspecaprs.py
├── pyspecconst.py
├── pyspecsdr.py
├── requirements.txt
├── rtlcoms.json
└── sdr_bookmarks.json
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | ## PySpecSDR Changelog
2 |
3 | ### Version 1.0.1 (2024/11/22)
4 |
5 | #### Features Added:
6 | + Added PPM (Parts Per Million) frequency correction functionality
7 | - New 'P'/'p' keys to increase/decrease PPM correction
8 | - New 'O' key to set exact PPM correction value
9 | - PPM value displayed in header
10 | - PPM settings saved/loaded with other configurations
11 |
12 | + Added more band presets for various radio services
13 | - Amateur radio bands (160m through 23cm)
14 | - Shortwave radio
15 | - Citizens Band (CB)
16 | - PMR446
17 | - Marine VHF
18 | - GSM bands
19 | - DECT
20 | - LTE bands
21 | - WiFi 2.4/5 GHz
22 | - Digital radio services
23 |
24 | + Added scrolling capability in Help screen
25 | - Up/Down arrow keys for line-by-line scrolling
26 | - PgUp/PgDn for page scrolling
27 | - Visual scrollbar indicator
28 |
29 | + Added pagination to scan results and bookmarks
30 | - Next/Previous page navigation
31 | - Page number indicators
32 | - Improved readability for long lists
33 |
34 | + Added ability to delete bookmarks
35 | - 'd' key in bookmarks menu to delete entries
36 | - Confirmation prompt for deletion
37 |
38 | + Added feature to recall last scan results
39 | - 'C' key shows results from most recent frequency scan
40 | - Maintains scan history between sessions
41 |
42 | #### Improvements:
43 | * ! All characters now use lower ASCII for better compatibility
44 | * ! All visual modes now have consistent frequency labels
45 | * ! Improved signal detection algorithm
46 | * ! Fixed/standardized look across all display modes
47 |
48 | #### Bug Fixes:
49 | * ! Fixed inconsistent character display in some terminals
50 | * ! Fixed frequency label alignment issues
51 | * ! Fixed bookmark sorting and display
52 | * ! Improved error handling for PPM settings
53 | * ! Fixed memory leak in waterfall display
54 |
55 | ### Version 1.0.2 (2024/11/24)
56 |
57 | #### Features Added:
58 | + The x axis has a center marker, with adjustable width, proportional to Bandwidth
59 |
60 | #### Improvements:
61 | * Adjusted calculation for better spectrogram/waterfall visualization
62 |
63 | #### Bug Fixes:
64 | * Fixed Initialization process for LimeSDR
65 | * Revert spectrogram drawing to first release
66 |
67 | ### Version 1.0.3 (2024/11/30)
68 |
69 | #### Features Added:
70 | * The program now displays the Band name if the center frequency is inside a known one
71 | * The '/' key opens the RTLSDR Commands menu (read below)
72 | * Added an utility to convert CSV/GQRX bookmark files to JSON/PySpecSDR format
73 |
74 | #### Bug Fixes:
75 | * Fixed AGC string in header
76 | * Fixed bugs in user inputs
77 |
78 | #### Features Removed:
79 | * RTLSDR version removed. SoapySDR is more capable and supports more devices.
80 |
81 | ### Version 1.0.4 (2024/12/07)
82 |
83 | #### Features Added:
84 | * Named PIPE to /tmp/sdrpipe of audio, to use with any program that decodes signals, like multimon-ng.
85 |
86 | #### Bug Fixes:
87 | * Improved sound quality to NFM and WFM modes, thanks to ChrisDev8 (https://github.com/xqtr/PySpecSDR/issues/3)
88 |
89 | ### Version 1.0.5 (2024/12/15)
90 |
91 | #### Fixes:
92 | * Change string for Narrow FM, to NFM, from FM, to avoid confusion (https://github.com/xqtr/PySpecSDR/issues/3)
93 | * IQ correction added to all demodulation modes (https://github.com/xqtr/PySpecSDR/issues/3)
94 | * Added filter between 300 and 3000 hz to remove low frequency harmonics and high pitched, out of band noise (between 300 and 3000 hz to remove low frequency harmonics and high pitched, out of band noise)
95 | * Converted all audio to Stereo, even in Mono sound the program outputs stereo/two channel sound.
96 |
97 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 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 General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PySpecSDR
2 | ```
3 | ____ _____ _____ ____ ____
4 | / __ \__ __/ ___/____ ___ _____/ ___// __ \/ __ \
5 | / /_/ / / / /\__ \/ __ \/ _ \/ ___/\__ \/ / / / /_/ /
6 | / ____/ /_/ /___/ / /_/ / __/ /__ ___/ / /_/ / _, _/
7 | /_/ \__, //____/ .___/\___/\___//____/_____/_/ |_|
8 | /____/ /_/
9 | version 1.0.4
10 | ```
11 |
12 | ## PySpecSDR - Python SDR Spectrum Analyzer and Signal Processor
13 |
14 | A feature-rich Software Defined Radio (SDR) spectrum analyzer with real-time
15 | visualization, demodulation, and signal analysis capabilities.
16 |
17 | Features:
18 | - Real-time spectrum analysis and waterfall display
19 | - Multiple visualization modes (spectrum, waterfall, persistence, surface, gradient)
20 | - FM, AM, SSB demodulation with audio output
21 | - Frequency scanning and signal classification
22 | - Bookmark management for frequencies of interest
23 | - Automatic Gain Control (AGC)
24 | - Recording capabilities for both RF and audio
25 | - Band presets for common frequency ranges
26 | - Configurable display and processing parameters
27 |
28 | Requirements:
29 | - RTL-SDR compatible device
30 | - Python 3.7 or higher
31 | - Dependencies listed in requirements.txt
32 |
33 | License: GPL-3.0-or-later
34 |
35 | ## Installing Dependencies
36 |
37 | You can install the required dependencies using the requirements.txt file.
38 |
39 | * Install via pip:
40 |
41 | `pip install -r requirements.txt`
42 |
43 | ## Changelog
44 |
45 | Moved to CHANGELOG.md, as it was getting big... :)
46 |
47 | ## RTLSDR Commands Menu
48 | Pressing the '/' key, will show a menu with various RTLSDR commands. These are examples of what you can do with the RTLSDR suite of programs like rtl_433, rtl_power etc. Selecting one, from the menu, will store it in memory, passing the current frequency as a paramater to that command. When you exit the program, this command will be printed on the terminal.
49 |
50 | It's a simple way, to have ready to use RTLSDR commands and use the current frequency. Select one and exit, at the current frequency, to immediately, do something else (like decoding messages).
51 |
52 | The command is not executed, it's just printed on the terminal. Copy/Paste it to use it.
53 |
54 | ## Named PIPE Function
55 |
56 | As from version 1.0.4, PySpecSDR, has the ability to export audio to a named PIPE file, at location /tmp/sdrpipe. This means that you can attach any decoding program to the pipe and decode the signal as you like.
57 |
58 | To start the process press the 'I' (capital I) key. The program will freeze and wait until another program attaches to the PIPE file (/tmp/sdrpipe). When it does, the program will work as before. To finish/end the process, just kill all the processes/programs that are attached to the PIPE file and it will close automatically.
59 |
60 | The data exported to this file, is audio, with sample rate at 44100Hz, 16bit, mono. Below are some examples of commands that you can use:
61 |
62 | ```
63 | sox -t raw -r 44100 -b 16 -e signed-integer /tmp/sdrpipe -t raw - | multimon-ng -t raw -a POCSAG1200 -
64 |
65 | ffmpeg -f s16le -ar 44100 -ac 1 -i /tmp/sdrpipe output.wav
66 | ```
67 |
68 | Multimon-ng, even if it has the ability to attach to a PIPE file, it seems it doesn't work. So using SOX is a trick to make it work. More examples on how to use multimon-ng with SOX, on the [multimon-ng](https://github.com/EliasOenal/multimon-ng) git repo.
69 |
70 |
71 | ## Showcase
72 | 
73 |
74 | 
75 |
76 | Select Band to adjust frequncy and bandwidth
77 |
78 | 
79 |
80 | Select demodulation mode
81 |
82 | 
83 |
84 | Gradient Visualization mode
85 |
86 | 
87 |
88 | Persistent Visualization mode
89 |
90 | 
91 |
92 | Select signal strength to scan for...
93 |
94 | 
95 |
96 | Select band...
97 |
98 | 
99 |
100 | Scanning...
101 |
102 | 
103 |
104 | Results. Select to listen.
105 |
106 | 
107 | 
108 |
109 | ASCII Waterfall
110 |
111 | 
112 |
113 | RTLSDR Commands
114 | 
115 |
116 | Running flawlessly in a Hackberry Pi Q20...
117 | 
118 |
119 |
120 | ## Troubleshooting
121 | ```
122 | 1. If you get "ImportError: No module named 'rtlsdr'":
123 | - Check that pyrtlsdr is installed: pip3 install pyrtlsdr
124 | 2. If you get "usb.core.NoBackendError":
125 | - Install libusb: pip3 install libusb1
126 | 3. If you get "RTLSDRError: No device found":
127 | - Check device connection
128 | - Check udev rules (Linux)
129 | - Check driver installation (Windows)
130 | 4. If you get "OSError: PortAudio library not found":
131 | - Install PortAudio:
132 | Ubuntu/Debian: sudo apt-get install libportaudio2
133 | Fedora: sudo dnf install portaudio-devel
134 | Arch: sudo pacman -S portaudio
135 | macOS: brew install portaudio
136 | ```
137 | Copyright (c) 2024 [XQTR]
138 |
--------------------------------------------------------------------------------
/__pycache__/pyspecaprs.cpython-310.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xqtr/PySpecSDR/6850de67654d35bfb1ab75ab73f7d34c9c08c8bb/__pycache__/pyspecaprs.cpython-310.pyc
--------------------------------------------------------------------------------
/__pycache__/pyspecconst.cpython-310.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xqtr/PySpecSDR/6850de67654d35bfb1ab75ab73f7d34c9c08c8bb/__pycache__/pyspecconst.cpython-310.pyc
--------------------------------------------------------------------------------
/gqrx2pss.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | '''
4 | ____ ____ ____ ____ ____
5 | | _ \ _ _/ ___| _ __ ___ ___/ ___|| _ \| _ \
6 | | |_) | | | \___ \| '_ \ / _ \/ __\___ \| | | | |_) |
7 | | __/| |_| |___) | |_) | __/ (__ ___) | |_| | _ <
8 | |_| \__, |____/| .__/ \___|\___|____/|____/|_| \_\
9 | |___/ |_|
10 |
11 | PySpecSDR - Python SDR Spectrum Analyzer and Signal Processor
12 | ===========================================================
13 |
14 | This is part of the PySpecSDR program.
15 |
16 | It converts a GQRX CSV/Bookmark file to JSON/PySpecSDR format. Make
17 | sure to save the file as sdr_bookmarks.json to load it to PySpecSDR,
18 | as it is. You can also open the file to an editor and add entries from
19 | it.
20 |
21 |
22 | License: GPL-3.0-or-later
23 |
24 | Copyright (c) 2024 [XQTR]
25 |
26 | Permission is hereby granted, free of charge, to any person obtaining a copy
27 | of this software and associated documentation files (the "Software"), to deal
28 | in the Software without restriction, including without limitation the rights
29 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
30 | copies of the Software, and to permit persons to whom the Software is
31 | furnished to do so, subject to the following conditions:
32 |
33 | The above copyright notice and this permission notice shall be included in all
34 | copies or substantial portions of the Software.
35 |
36 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
37 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
38 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
39 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
40 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
41 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
42 | SOFTWARE.
43 |
44 | Author: XQTR
45 | Email: xqtr@gmx.com // xqtr.xqtr@gmail.com
46 | GitHub: https://github.com/xqtr/PySpecSDR
47 | Version: 1.0.0
48 | Last Updated: 2024/11/30
49 |
50 | '''
51 | import csv
52 | import json
53 | import argparse
54 |
55 | def gqrx_to_json(csv):
56 | results = {}
57 | with open(csv) as file:
58 | for line in file:
59 | line = line.strip()
60 | if line.startswith('#'):
61 | pass
62 | elif line.startswith('Untagged'):
63 | pass
64 | elif not line:
65 | pass
66 | else:
67 | #print(line.rstrip())
68 | flds = line.split(';')
69 | freq = float(flds[0])
70 | name = flds[1].strip()
71 | mode = flds[2].strip()
72 | band = float(flds[3].strip())
73 |
74 | if mode.startswith('Narrow'):
75 | mode = "FM"
76 | elif mode.startswith('AM'):
77 | mode = "AM"
78 | elif mode.startswith('WFM'):
79 | mode = "WFM"
80 | elif mode.startswith('CW'):
81 | mode = "CW"
82 | results[name]=[freq,mode,band]
83 | return results
84 |
85 | if __name__ == "__main__":
86 | parser = argparse.ArgumentParser(description='Load GQRX bookmarks from a file and convert to JSON/PySpecSDR format.')
87 | parser.add_argument('readfile', type=str, help='Path to the GQRX bookmarks file')
88 | parser.add_argument('savefile', type=str, help='Filename to JSON file')
89 | args = parser.parse_args()
90 | with open(args.savefile, 'w') as f:
91 | json.dump(gqrx_to_json(args.readfile), f, indent=2)
92 |
--------------------------------------------------------------------------------
/pyspecaprs.py:
--------------------------------------------------------------------------------
1 | def decode_ax25_frame(bit_stream):
2 | """
3 | Decode AX.25 frame from bit stream
4 | Returns decoded packet or None if invalid
5 | """
6 | try:
7 | # Find flag pattern (01111110)
8 | flag = [0, 1, 1, 1, 1, 1, 1, 0]
9 |
10 | # Find start and end flags
11 | start = -1
12 | for i in range(len(bit_stream) - 7):
13 | if bit_stream[i:i+8] == flag:
14 | start = i + 8
15 | break
16 |
17 | if start == -1:
18 | return None
19 |
20 | # Extract data between flags
21 | frame_bits = []
22 | ones_count = 0
23 | i = start
24 |
25 | while i < len(bit_stream) - 7:
26 | bit = bit_stream[i]
27 | frame_bits.append(bit)
28 |
29 | if bit == 1:
30 | ones_count += 1
31 | else:
32 | ones_count = 0
33 |
34 | # Skip stuffed bits
35 | if ones_count == 5 and i + 1 < len(bit_stream) and bit_stream[i+1] == 0:
36 | i += 2
37 | ones_count = 0
38 | continue
39 |
40 | i += 1
41 |
42 | # Check for end flag
43 | if frame_bits[-8:] == flag:
44 | frame_bits = frame_bits[:-8]
45 | break
46 |
47 | # Convert bits to bytes
48 | frame_bytes = []
49 | for i in range(0, len(frame_bits), 8):
50 | if i + 8 <= len(frame_bits):
51 | byte = 0
52 | for j in range(8):
53 | byte |= frame_bits[i+j] << j
54 | frame_bytes.append(byte)
55 |
56 | return decode_aprs_payload(frame_bytes)
57 |
58 | except Exception:
59 | return None
60 |
61 | def decode_aprs_payload(frame_bytes):
62 | """
63 | Decode APRS packet payload
64 | """
65 | try:
66 | if len(frame_bytes) < 14: # Minimum length for valid packet
67 | return None
68 |
69 | # Extract addresses
70 | dest = ''.join([chr((b >> 1) & 0x7F) for b in frame_bytes[0:6]]).strip()
71 | source = ''.join([chr((b >> 1) & 0x7F) for b in frame_bytes[7:13]]).strip()
72 |
73 | # Control and PID fields
74 | ctrl = frame_bytes[13]
75 | pid = frame_bytes[14] if len(frame_bytes) > 14 else None
76 |
77 | # Information field
78 | info = ''
79 | if len(frame_bytes) > 15:
80 | info = ''.join([chr(b) for b in frame_bytes[15:]])
81 |
82 | return f"{source}>{dest}:{info}"
83 |
84 | except Exception:
85 | return None
86 |
87 |
--------------------------------------------------------------------------------
/pyspecconst.py:
--------------------------------------------------------------------------------
1 |
2 | SIGNAL_TYPES = {
3 | 'FM_BROADCAST': {
4 | 'bandwidth': (150e3, 200e3),
5 | 'pattern': 'wideband_fm',
6 | 'description': 'FM Radio Broadcast'
7 | },
8 | 'NARROW_FM': {
9 | 'bandwidth': (10e3, 16e3),
10 | 'pattern': 'narrowband_fm',
11 | 'description': 'Narrow FM (Amateur/Business)'
12 | },
13 | 'AM_BROADCAST': {
14 | 'bandwidth': (8e3, 10e3),
15 | 'pattern': 'am',
16 | 'description': 'AM Radio Broadcast'
17 | },
18 | 'SSB': {
19 | 'bandwidth': (2.4e3, 3e3),
20 | 'pattern': 'ssb',
21 | 'description': 'Single Sideband'
22 | },
23 | 'DIGITAL': {
24 | 'bandwidth': (6e3, 50e3),
25 | 'pattern': 'digital',
26 | 'description': 'Digital Signal'
27 | }
28 | }
29 |
30 | BAND_PRESETS = {
31 | # Amateur Radio Bands
32 | 'HAM160': (1.8e6, 2.0e6, "160m Amateur Band"),
33 | 'HAM80': (3.5e6, 4.0e6, "80m Amateur Band"),
34 | 'HAM60': (5.3515e6, 5.3665e6, "60m Amateur Band"),
35 | 'HAM40': (7.0e6, 7.3e6, "40m Amateur Band"),
36 | 'HAM30': (10.1e6, 10.15e6, "30m Amateur Band"),
37 | 'HAM20': (14.0e6, 14.35e6, "20m Amateur Band"),
38 | 'HAM17': (18.068e6, 18.168e6, "17m Amateur Band"),
39 | 'HAM15': (21.0e6, 21.45e6, "15m Amateur Band"),
40 | 'HAM12': (24.89e6, 24.99e6, "12m Amateur Band"),
41 | 'HAM10': (28.0e6, 29.7e6, "10m Amateur Band"),
42 | 'HAM6': (50.0e6, 54.0e6, "6m Amateur Band"),
43 | 'HAM2': (144.0e6, 148.0e6, "2m Amateur Band"),
44 | 'HAM70CM': (420.0e6, 450.0e6, "70cm Amateur Band"),
45 |
46 | # CB Radio
47 | 'CB': (26.965e6, 27.405e6, "Citizens Band Radio"),
48 |
49 | # Marine Bands
50 | 'MARINE': (156.0e6, 162.025e6, "Marine VHF"),
51 | 'MARINE_MF': (1.605e6, 4.0e6, "Marine MF Band"),
52 |
53 | # Aviation
54 | 'AIR_VOICE': (118.0e6, 137.0e6, "Aircraft Voice Comms"),
55 | 'AIR_NAV': (108.0e6, 117.975e6, "Aircraft Navigation"),
56 |
57 | # Emergency Services
58 | 'NOAA': (162.4e6, 162.55e6, "NOAA Weather Radio"),
59 | 'PUBLIC': (152.0e6, 162.0e6, "Public Safety VHF"),
60 | 'PUBLIC_UHF': (450.0e6, 470.0e6, "Public Safety UHF"),
61 |
62 | # Broadcast
63 | 'AM': (535e3, 1.705e6, "AM Broadcast"),
64 | 'FM': (87.5e6, 108.0e6, "FM Broadcast"),
65 | 'SW1': (2.3e6, 2.495e6, "Shortwave Band 1"),
66 | 'SW2': (3.2e6, 3.4e6, "Shortwave Band 2"),
67 | 'SW3': (4.75e6, 4.995e6, "Shortwave Band 3"),
68 | 'SW4': (5.9e6, 6.2e6, "Shortwave Band 4"),
69 | 'SW5': (7.3e6, 7.35e6, "Shortwave Band 5"),
70 | 'SW6': (9.4e6, 9.9e6, "Shortwave Band 6"),
71 | 'SW7': (11.6e6, 12.1e6, "Shortwave Band 7"),
72 | 'SW8': (13.57e6, 13.87e6, "Shortwave Band 8"),
73 | 'SW9': (15.1e6, 15.8e6, "Shortwave Band 9"),
74 | 'SW10': (17.48e6, 17.9e6, "Shortwave Band 10"),
75 | 'SW11': (21.45e6, 21.85e6, "Shortwave Band 11"),
76 | 'SW12': (25.67e6, 26.1e6, "Shortwave Band 12"),
77 |
78 | # Digital Modes Common Frequencies
79 | 'FT8_40': (7.074e6, 7.076e6, "40m FT8"),
80 | 'FT8_20': (14.074e6, 14.076e6, "20m FT8"),
81 | 'PSK31_40': (7.070e6, 7.071e6, "40m PSK31"),
82 | 'PSK31_20': (14.070e6, 14.071e6, "20m PSK31"),
83 | 'RTTY_40': (7.080e6, 7.125e6, "40m RTTY"),
84 | 'RTTY_20': (14.080e6, 14.099e6, "20m RTTY"),
85 |
86 | # CW (Morse) Common Frequencies
87 | 'CW_80': (3.5e6, 3.6e6, "80m CW"),
88 | 'CW_40': (7.0e6, 7.125e6, "40m CW"),
89 | 'CW_30': (10.1e6, 10.13e6, "30m CW"),
90 | 'CW_20': (14.0e6, 14.15e6, "20m CW"),
91 |
92 | # Satellite
93 | 'SAT_VHF': (145.8e6, 146.0e6, "Amateur Satellite VHF"),
94 | 'SAT_UHF': (435.0e6, 438.0e6, "Amateur Satellite UHF"),
95 | 'NOAA_SAT': (137.0e6, 138.0e6, "NOAA Weather Satellites"),
96 |
97 | # Time Signals
98 | 'WWV': (2.5e6, 20.0e6, "WWV Time Signals"),
99 | 'WWVH': (2.5e6, 15.0e6, "WWVH Time Signals"),
100 | }
101 |
102 | BAND_BANDWIDTHS = {
103 | 'AM': 10e3,
104 | 'NFM': 200e3,
105 | 'WFM': 100e6,
106 | 'HAM160': 2.7e3,
107 | 'HAM80': 2.7e3,
108 | 'HAM40': 2.7e3,
109 | 'HAM20': 2.7e3,
110 | 'CB': 10e3,
111 | 'MARINE': 16e3,
112 | 'AIR_VOICE': 8.33e3,
113 | 'NOAA': 25e3,
114 | 'FT8_40': 3e3,
115 | 'FT8_20': 3e3,
116 | 'PSK31_40': 500,
117 | 'PSK31_20': 500,
118 | 'RTTY_40': 3e3,
119 | 'RTTY_20': 3e3,
120 | 'CW_80': 500,
121 | 'CW_40': 500,
122 | 'CW_30': 500,
123 | 'CW_20': 500,
124 | 'SAT_VHF': 50e3,
125 | 'SAT_UHF': 50e3,
126 | 'NOAA_SAT': 40e3,
127 | }
128 |
129 | MORSE_CODE = {
130 | '.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E',
131 | '..-.': 'F', '--.': 'G', '....': 'H', '..': 'I', '.---': 'J',
132 | '-.-': 'K', '.-..': 'L', '--': 'M', '-.': 'N', '---': 'O',
133 | '.--.': 'P', '--.-': 'Q', '.-.': 'R', '...': 'S', '-': 'T',
134 | '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X', '-.--': 'Y',
135 | '--..': 'Z', '.----': '1', '..---': '2', '...--': '3', '....-': '4',
136 | '.....': '5', '-....': '6', '--...': '7', '---..': '8', '----.': '9',
137 | '-----': '0', '--..--': ',', '.-.-.-': '.', '..--..': '?',
138 | '-..-.': '/', '-....-': '-', '-.--.': '(', '-.--.-': ')',
139 | '.-...': '&', '---...': ':', '-.-.-.': ';', '-...-': '=',
140 | '.-.-.': '+', '.-..-.': '"', '...-..-': '$', '.--.-.': '@',
141 | '..--.-': '_', '...---...': 'SOS'
142 | }
143 |
144 | # Define help content with categories
145 | help_content = [
146 | ("General Controls", [
147 | ("q", "Quit program"),
148 | ("h", "Show this help screen"),
149 | ("w", "Save current settings"),
150 | ("m", "Cycle through display modes"),
151 | ("1-6", "Quick switch display modes"),
152 | ("/", "RTL Commands Selector"),
153 | ]),
154 | ("Frequency Controls", [
155 | ("F/f", "Change frequency up/down by step"),
156 | ("Up/Down", "Change frequency by 1 MHz"),
157 | ("Right/Left", "Change frequency by 0.5 MHz"),
158 | ("x", "Set exact frequency"),
159 | ("T/t", "Increase/decrease frequency step"),
160 | ]),
161 | ("Signal Controls", [
162 | ("B/b", "Increase/reduce bandwidth"),
163 | ("S/s", "Increase/decrease samples"),
164 | ("G/g", "Increase/decrease gain"),
165 | ("A", "Toggle Automatic Gain Control (AGC)"),
166 | ]),
167 | ("Frequency Correction", [
168 | ("P/p", "Increase/decrease PPM correction"),
169 | ("O", "Set exact PPM correction value"),
170 | ]),
171 | ("Audio Controls", [
172 | ("a", "Toggle audio on/off"),
173 | ("d", "Change demodulation mode"),
174 | ("R", "Start/Stop audio recording"),
175 | ("I", "Start/Stop named PIPE at /tmp/sdrpipe"),
176 | ]),
177 | ("Decoders", [
178 | ("M", "Morse Code Decoder (experimental)"),
179 | (".", "APRS Decoder (experimental)"),
180 | ]),
181 | ("Frequency Management", [
182 | ("k/l", "Save/Load frequency bookmark"),
183 | ("n", "Access band presets"),
184 | ("c", "Start frequency scanner"),
185 | ("C", "Show scan results"),
186 | ("", ""),
187 | ]),
188 | ]
--------------------------------------------------------------------------------
/pyspecsdr.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | '''
4 | ____ ____ ____ ____ ____
5 | | _ \ _ _/ ___| _ __ ___ ___/ ___|| _ \| _ \
6 | | |_) | | | \___ \| '_ \ / _ \/ __\___ \| | | | |_) |
7 | | __/| |_| |___) | |_) | __/ (__ ___) | |_| | _ <
8 | |_| \__, |____/| .__/ \___|\___|____/|____/|_| \_\
9 | |___/ |_|
10 |
11 | PySpecSDR - Python SDR Spectrum Analyzer and Signal Processor
12 | ===========================================================
13 |
14 | A feature-rich Software Defined Radio (SDR) spectrum analyzer with real-time
15 | visualization, demodulation, and signal analysis capabilities.
16 |
17 | Features:
18 | - Real-time spectrum analysis and waterfall display
19 | - Multiple visualization modes (spectrum, waterfall, persistence, surface, gradient)
20 | - FM, AM, SSB demodulation with audio output
21 | - Frequency scanning and signal classification
22 | - Bookmark management for frequencies of interest
23 | - Automatic Gain Control (AGC)
24 | - Recording capabilities for both RF and audio
25 | - Band presets for common frequency ranges
26 | - Configurable display and processing parameters
27 |
28 | Requirements:
29 | - RTL-SDR compatible device
30 | - Python 3.7 or higher
31 | - Dependencies listed in requirements.txt
32 |
33 | License: GPL-3.0-or-later
34 |
35 | Copyright (c) 2024 [XQTR]
36 |
37 | Permission is hereby granted, free of charge, to any person obtaining a copy
38 | of this software and associated documentation files (the "Software"), to deal
39 | in the Software without restriction, including without limitation the rights
40 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
41 | copies of the Software, and to permit persons to whom the Software is
42 | furnished to do so, subject to the following conditions:
43 |
44 | The above copyright notice and this permission notice shall be included in all
45 | copies or substantial portions of the Software.
46 |
47 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
48 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
49 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
50 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
51 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
52 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
53 | SOFTWARE.
54 |
55 | Author: XQTR
56 | Email: xqtr@gmx.com // xqtr.xqtr@gmail.com
57 | GitHub: https://github.com/xqtr/PySpecSDR
58 | Version: 1.0.5
59 | Last Updated: 2024/12/15
60 |
61 | Usage:
62 | python3 pyspecsdr.py
63 |
64 | Key Bindings:
65 | q - Quit
66 | h - Show help menu
67 | For full list of controls, press 'h' while running
68 |
69 | Changelog:
70 |
71 | Read the CHANGELOG.md file
72 |
73 |
74 | '''
75 |
76 | from pyspecconst import *
77 | import numpy as np
78 | import curses
79 | from rtlsdr import RtlSdr
80 | from scipy.signal import decimate
81 | import sounddevice as sd
82 | from scipy.signal import butter, lfilter
83 | from scipy.signal import firwin
84 | from scipy.signal import bilinear
85 | from scipy.signal import hilbert
86 | from scipy.signal import welch
87 | from collections import deque
88 | import time
89 | import os
90 | import configparser
91 | import json
92 | import os.path
93 | import wave
94 | import struct
95 | import SoapySDR
96 | from SoapySDR import SOAPY_SDR_RX, SOAPY_SDR_CF32
97 | import signal
98 | import pyspecaprs
99 |
100 |
101 | audio_buffer = deque(maxlen=24) # Increased from 16 for better continuity
102 | SAMPLES = 7
103 | INTENSITY_CHARS = ' .,:|\\' # Simple ASCII characters for intensity levels
104 | BOOKMARK_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sdr_bookmarks.json")
105 | SETTINGS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sdr_settings.ini")
106 | PIPE_PATH = "/tmp/sdrpipe"
107 | PIPE_FILE = None
108 | USE_PIPE = False
109 |
110 | # Add global flag for audio availability
111 | AUDIO_AVAILABLE = False
112 | try:
113 | import sounddevice as sd
114 | AUDIO_AVAILABLE = True
115 | except ImportError:
116 | pass
117 |
118 | # Add these constants near the top of the file
119 | AGC_TARGET_POWER = -30 # Target power level in dB
120 | AGC_ENABLED = False # Global flag for AGC state
121 | AGC_UPDATE_INTERVAL = 0.5 # Seconds between AGC updates
122 | AGC_STEP = 1.0 # Gain adjustment step size
123 | last_agc_update = 0 # Track last AGC update time
124 | SIGNAL_THRESHOLD = -40 # dB threshold for signal detection
125 | SCAN_STEP = 100e3 # 100 kHz steps by default
126 | MIN_SIGNAL_BANDWIDTH = 50e3 # Minimum bandwidth to consider as a signal
127 | SCAN_DWELL_TIME = 0.1 # Seconds to dwell on each frequency
128 | SCAN_ACTIVE = False # Global flag for scan state
129 |
130 | # Add these constants near the top with other constants
131 | WATERFALL_HISTORY = []
132 | WATERFALL_MAX_LINES = 30 # Number of history lines to keep
133 | WATERFALL_MODE = False # Toggle between spectrum and waterfall
134 | WATERFALL_COLORS = [
135 | curses.COLOR_BLACK, # Weakest signal
136 | curses.COLOR_BLUE,
137 | curses.COLOR_CYAN,
138 | curses.COLOR_GREEN,
139 | curses.COLOR_YELLOW,
140 | curses.COLOR_RED, # Strongest signal
141 | ]
142 |
143 | # Add these constants near the top with other constants
144 | DEMOD_MODES = {
145 | 'NFM': {'name': 'NFM', 'bandwidth': 200e3, 'description': 'Narrow FM'},
146 | 'WFM': {'name': 'Wide FM', 'bandwidth': 180e3, 'description': 'Wide FM (Broadcast)'},
147 | 'AM': {'name': 'AM', 'bandwidth': 10e3, 'description': 'Amplitude Modulation'},
148 | 'USB': {'name': 'USB', 'bandwidth': 3e3, 'description': 'Upper Sideband'},
149 | 'LSB': {'name': 'LSB', 'bandwidth': 3e3, 'description': 'Lower Sideband'},
150 | 'RAW': {'name': 'RAW', 'bandwidth': None, 'description': 'Raw IQ Samples'}
151 | }
152 | CURRENT_DEMOD = 'NFM' # Default demodulation mode
153 |
154 | # Add this with other constants near the top of the file
155 | zoom_step = 0.1e6 # 100 kHz zoom step
156 |
157 | # Add near other constants
158 | PERSISTENCE_HISTORY = []
159 | PERSISTENCE_ALPHA = 0.7 # Decay factor
160 | PERSISTENCE_LENGTH = 10 # Number of traces to keep
161 | PERSISTENCE_MODE = False
162 |
163 | # Add near other constants
164 | SURFACE_MODE = False
165 | SURFACE_ANGLE = 45 # Viewing angle in degrees
166 |
167 | # Add near other constants
168 | GRADIENT_COLORS = [
169 | (0, 0, 0), # Black
170 | (0, 0, 139), # Dark Blue
171 | (0, 0, 255), # Blue
172 | (0, 255, 255), # Cyan
173 | (0, 255, 0), # Green
174 | (255, 255, 0), # Yellow
175 | (255, 0, 0), # Red
176 | ]
177 |
178 | # Add with other constants
179 | DISPLAY_MODES = ['SPECTRUM', 'WATERFALL', 'PERSISTENCE', 'SURFACE', 'GRADIENT', 'VECTOR']
180 | current_display_mode = 'SPECTRUM'
181 |
182 | # Add near the top with other constants
183 | DEFAULT_PPM = 0 # Default PPM correction value
184 |
185 | # Add near the top with other global variables
186 | LAST_SCAN_RESULTS = [] # Store the last scan results
187 |
188 | # Variable to save the RTL command
189 | RTL_COMMAND = ""
190 |
191 | def init_colors():
192 | curses.start_color()
193 | curses.init_pair(1, curses.COLOR_YELLOW, curses.COLOR_BLACK)
194 | curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK)
195 | curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)
196 | curses.init_pair(4, curses.COLOR_GREEN, curses.COLOR_BLACK)
197 | curses.init_pair(5, curses.COLOR_CYAN, curses.COLOR_BLACK)
198 | curses.init_pair(6, curses.COLOR_BLUE, curses.COLOR_BLACK)
199 | # Add waterfall color pairs (starting from 10 to avoid conflicts)
200 | for i, color in enumerate(WATERFALL_COLORS):
201 | curses.init_pair(10 + i, color, curses.COLOR_BLACK)
202 |
203 | def showhelp(stdscr):
204 | """Display help information with scrolling capability"""
205 | max_height, max_width = stdscr.getmaxyx()
206 |
207 | # Calculate total content height
208 | total_height = sum(2 + len(section[1]) for section in help_content) + 15
209 | # Initialize scroll position
210 | scroll_pos = 0
211 | max_scroll = max(0, total_height - (max_height - 2))
212 | stdscr.nodelay(0)
213 | while True:
214 | # Clear screen
215 | stdscr.clear()
216 | current_line = 0
217 |
218 | # Draw title
219 | title = "PySpecSDR Help"
220 | stdscr.addstr(0, 2, title, curses.color_pair(1) | curses.A_BOLD)
221 | current_line += 1
222 |
223 | # Draw horizontal line
224 | stdscr.addstr(1, 1, "-" * (max_width - 2), curses.color_pair(2))
225 | current_line += 1
226 |
227 | # Draw visible content
228 | visible_line = 0
229 | startline = 2
230 | for section_title, commands in help_content:
231 | if current_line - scroll_pos >= 0 and current_line - scroll_pos < max_height - 3:
232 | try:
233 | stdscr.addstr(startline + current_line - scroll_pos, 2,
234 | "+" + "-" * (len(section_title) + 2) + "+",
235 | curses.color_pair(4))
236 | except curses.error:
237 | pass
238 | current_line += 1
239 |
240 | if current_line - scroll_pos >= 0 and current_line - scroll_pos < max_height - 3:
241 | try:
242 | stdscr.addstr(startline + current_line - scroll_pos, 2,
243 | "| " + section_title + " |",
244 | curses.color_pair(4) | curses.A_BOLD)
245 | except curses.error:
246 | pass
247 | current_line += 1
248 |
249 | if current_line - scroll_pos >= 0 and current_line - scroll_pos < max_height - 3:
250 | try:
251 | stdscr.addstr(startline + current_line - scroll_pos, 2,
252 | "+" + "-" * (len(section_title) + 2) + "+",
253 | curses.color_pair(4))
254 | except curses.error:
255 | pass
256 | current_line += 1
257 |
258 | for key, description in commands:
259 | if current_line - scroll_pos >= 0 and current_line - scroll_pos < max_height - 3:
260 | try:
261 | key_str = f"[ {key:6} ]"
262 | stdscr.addstr(startline + current_line - scroll_pos, 4, key_str,
263 | curses.color_pair(1) | curses.A_BOLD)
264 | stdscr.addstr(startline + current_line - scroll_pos, 15, "->",
265 | curses.color_pair(2))
266 | stdscr.addstr(startline + current_line - scroll_pos, 18, description,
267 | curses.color_pair(2))
268 | except curses.error:
269 | pass
270 | current_line += 1
271 | current_line += 1
272 |
273 | # Draw scrollbar
274 | if total_height > max_height - 2:
275 | for y in range(2, max_height - 1):
276 | pos = int((y - 2) * total_height / (max_height - 3))
277 | if pos >= scroll_pos and pos <= scroll_pos + max_height:
278 | char = "#"
279 | else:
280 | char = "|"
281 | try:
282 | stdscr.addstr(y, max_width - 1, char, curses.color_pair(2))
283 | except curses.error:
284 | pass
285 |
286 | # Draw navigation instructions
287 | nav_text = "[ UP/DOWN | PgUp/PgDn | q:Exit ]"
288 | nav_pos = (max_width - len(nav_text)) // 2
289 | try:
290 | stdscr.addstr(max_height - 1, nav_pos, nav_text,
291 | curses.color_pair(5) | curses.A_BOLD)
292 | except curses.error:
293 | pass
294 |
295 | stdscr.refresh()
296 |
297 | # Handle input
298 | key = stdscr.getch()
299 | if key == ord('q'):
300 | break
301 | elif key == curses.KEY_UP and scroll_pos > 0:
302 | scroll_pos = max(0, scroll_pos - 1)
303 | elif key == curses.KEY_DOWN and scroll_pos < max_scroll:
304 | scroll_pos = min(max_scroll, scroll_pos + 1)
305 | elif key == curses.KEY_PPAGE: # Page Up
306 | scroll_pos = max(0, scroll_pos - (max_height - 3))
307 | elif key == curses.KEY_NPAGE: # Page Down
308 | scroll_pos = min(max_scroll, scroll_pos + (max_height - 3))
309 |
310 | # Restore original nodelay state
311 | stdscr.nodelay(True)
312 |
313 | # Pipe Functions
314 | def create_pipe():
315 | global PIPE_PATH
316 | """Create a named pipe for output."""
317 | try:
318 | os.mkfifo(PIPE_PATH)
319 | except FileExistsError:
320 | pass # Pipe already exists
321 |
322 | def open_file_pipe():
323 | #Open file and return value
324 | #fifo = open(PIPE_PATH, 'wb', buffering=0)
325 | fifo = open(PIPE_PATH, 'wb', os.O_NONBLOCK)
326 | return fifo
327 |
328 | def write_to_pipe(fifof,data,stdscr):
329 | """Write audio data to the named pipe."""
330 | if data.dtype != np.int16:
331 | data = np.int16(data * 32767)
332 | fifof.write(data)
333 |
334 | def close_file_pipe(fifo):
335 | fifo.close
336 |
337 | def clean_pipe(signum, frame):
338 | """Cleanup function to remove the named pipe."""
339 | if os.path.exists(PIPE_PATH):
340 | #os.remove(PIPE_PATH)
341 | os.unlink(PIPE_PATH)
342 |
343 | def start_pipe_recording(stdscr):
344 | global PIPE_FILE, PIPE_PATH,USE_PIPE
345 | create_pipe()
346 | PIPE_FILE = open_file_pipe()
347 | USE_PIPE = True
348 | stdscr.addstr(0, 0, f"Started recording to {PIPE_PATH}", curses.color_pair(4))
349 | time.sleep(1)
350 |
351 | def stop_pipe_recording(stdscr):
352 | global PIPE_FILE, PIPE_PATH,USE_PIPE
353 | USE_PIPE = False
354 | close_file_pipe(PIPE_FILE)
355 | clean_pipe(None,None)
356 | PIPE_FILE = None
357 | stdscr.addstr(0, 0, "Recording stopped", curses.color_pair(4))
358 | time.sleep(1)
359 |
360 | signal.signal(signal.SIGINT, clean_pipe)
361 | signal.signal(signal.SIGTERM, clean_pipe) # Handle termination signal
362 |
363 | def setfreq(stdscr):
364 | draw_clearheader(stdscr)
365 | stdscr.addstr(0,0,"Enter frequency in Hz: ",curses.color_pair(1) | curses.A_BOLD)
366 | # Enable echo and cursor
367 | curses.echo()
368 | curses.curs_set(1)
369 | stdscr.nodelay(False)
370 | freq = stdscr.getstr()
371 | draw_clearheader(stdscr)
372 | # Disable echo and cursor after input
373 | curses.noecho()
374 | curses.curs_set(0)
375 | stdscr.nodelay(True)
376 |
377 | res = freq.decode('utf-8') # Convert bytes to string
378 | if len(res)<3: return None
379 | if res[-1] in 'mM' or res[-1] in 'kK':
380 | num = res[:-1]
381 | try:
382 | int(num)
383 | except:
384 | return None
385 | else:
386 | try:
387 | int(freq)
388 | except:
389 | return None
390 | return res
391 |
392 |
393 | def draw_clearheader(stdscr):
394 | max_height, max_width = stdscr.getmaxyx()
395 | stdscr.addstr(0, 0, " "*(max_width-1))
396 | stdscr.addstr(1, 0, " "*(max_width-1))
397 |
398 | def draw_header(stdscr, freq_data, frequencies, center_freq, bandwidth, gain, step,
399 | sdr, is_recording=False, recording_duration=None):
400 |
401 | max_height, max_width = stdscr.getmaxyx()
402 |
403 | x_pos = 0
404 | if is_recording:
405 | recording_text = f"Recording: {recording_duration:.1f}s"
406 | stdscr.addstr(0, max_width - len(recording_text) - 1, recording_text,
407 | curses.color_pair(3) | curses.A_BOLD)
408 | available_width = max_width - len(recording_text) - 2
409 | else:
410 | available_width = max_width
411 |
412 | # Draw the colored header
413 | freq_text = f"req: {center_freq/1e6:.6f} MHz"
414 | bw_text = f"andwidth: {bandwidth/1e6:.2f} MHz"
415 | gain_text = f"ain: {gain}"
416 | samples_text = f"amples: {2**SAMPLES}"
417 | step_text = f"ep: {step/1e6:.3f} MHz"
418 | ppm_text = f"PM: {sdr.ppm}" # Add PPM text
419 | agc_text = f"GC: {'On' if AGC_ENABLED else 'Off'}"
420 |
421 | x_pos = 0
422 | stdscr.addstr(0, x_pos, "F", curses.color_pair(1) | curses.A_BOLD)
423 | stdscr.addstr(0, x_pos+1, freq_text, curses.color_pair(2))
424 | x_pos += len(freq_text) + 3
425 | stdscr.addstr(0, x_pos, "B", curses.color_pair(1) | curses.A_BOLD)
426 | stdscr.addstr(0, x_pos+1, bw_text, curses.color_pair(2))
427 | x_pos += len(bw_text) + 3
428 | stdscr.addstr(0, x_pos, "G", curses.color_pair(1) | curses.A_BOLD)
429 | stdscr.addstr(0, x_pos+1, gain_text, curses.color_pair(2))
430 | x_pos = 0
431 | stdscr.addstr(1, x_pos, "S", curses.color_pair(1) | curses.A_BOLD)
432 | stdscr.addstr(1, x_pos+1, samples_text, curses.color_pair(2))
433 | x_pos += len(samples_text) + 3
434 | stdscr.addstr(1, x_pos, "S", curses.color_pair(2))
435 | stdscr.addstr(1, x_pos+1, "t", curses.color_pair(1) | curses.A_BOLD)
436 | stdscr.addstr(1, x_pos+2, step_text, curses.color_pair(2))
437 | x_pos += len(step_text) + 4
438 | try:
439 | stdscr.addstr(1, x_pos, "P", curses.color_pair(1) | curses.A_BOLD)
440 | stdscr.addstr(1, x_pos+1, ppm_text, curses.color_pair(2))
441 | except curses.error:
442 | pass # Ignore if screen is too small
443 | x_pos += len(ppm_text) + 4
444 | stdscr.addstr(1, x_pos, "A", curses.color_pair(1) | curses.A_BOLD)
445 | stdscr.addstr(1, x_pos+1, agc_text, curses.color_pair(2))
446 |
447 | # Add signal strength indicator
448 | peak_power = np.max(freq_data)
449 | avg_power = np.mean(freq_data)
450 | strength_text = f"Peak: {peak_power:.1f} dB Avg: {avg_power:.1f} dB"
451 | stdscr.addstr(1, max_width - len(strength_text) - 1, strength_text, curses.color_pair(2))
452 |
453 | #debug string
454 | #txt = str(sdr.sample_rate)
455 | #stdscr.addstr(0, max_width - len(txt) - 1, txt, curses.color_pair(2) | curses.A_BOLD)
456 |
457 |
458 | def draw_spectrogram(stdscr, freq_data, frequencies, center_freq, bandwidth, gain, step,
459 | sdr, is_recording=False, recording_duration=None):
460 | """Draw the spectrum display with improved signal-to-noise ratio visualization"""
461 | max_height, max_width = stdscr.getmaxyx()
462 |
463 | # Calculate display dimensions
464 | display_width = max_width - 10 # Reserve space for dB scale
465 | display_height = max_height - 4 # Reserve space for header and labels
466 |
467 | # Clear the display area (preserve header)
468 | for y in range(2, max_height-1):
469 | try:
470 | stdscr.addstr(y, 0, " " * (max_width-1), curses.color_pair(1))
471 | except curses.error:
472 | pass
473 |
474 | # Set fixed dB range for display with noise floor adjustment
475 | min_db = np.min(freq_data[np.isfinite(freq_data)])
476 | max_db = np.max(freq_data[np.isfinite(freq_data)])
477 |
478 | # Calculate noise floor (using lower percentile)
479 | noise_floor = np.percentile(freq_data[np.isfinite(freq_data)], 20)
480 |
481 | # Adjust dynamic range to emphasize signals above noise
482 | db_range = max_db - noise_floor
483 | display_min = noise_floor - (db_range * 0.1) # Show some noise below floor
484 | display_max = max_db + (db_range * 0.05) # Add headroom
485 |
486 | # Draw dB scale on the left
487 | for i in range(display_height):
488 | db_value = display_max - (i * (display_max - display_min) / display_height)
489 | if i % 3 == 0: # Show scale every 3 lines
490 | db_label = f"{db_value:4.0f}dB"
491 | try:
492 | stdscr.addstr(i + 2, 0, db_label, curses.color_pair(2))
493 | # Add scale markers
494 | stdscr.addstr(i + 2, 8, "|", curses.color_pair(2))
495 | except curses.error:
496 | pass
497 |
498 | # Normalize data for display using adjusted range
499 | normalized_data = np.clip((freq_data - display_min) / (display_max - display_min), 0, 1)
500 |
501 | # Apply non-linear scaling to emphasize signals
502 | normalized_data = np.power(normalized_data, 0.7) # Adjust exponent to taste
503 |
504 | # Resample data to fit display width
505 | resampled = np.interp(
506 | np.linspace(0, len(normalized_data) - 1, display_width),
507 | np.arange(len(normalized_data)),
508 | normalized_data
509 | )
510 |
511 | # Draw spectrum with improved character selection
512 | for x, value in enumerate(resampled):
513 | if np.isfinite(value):
514 | # Calculate height in display units
515 | height = int(value * display_height)
516 | height = min(height, display_height)
517 |
518 | # First clear the entire column
519 | for y in range(display_height):
520 | try:
521 | stdscr.addstr(y + 2, x + 9, " ", curses.color_pair(1))
522 | except curses.error:
523 | pass
524 |
525 | # Then draw the bar with varied characters based on signal strength
526 | peak_height = 0
527 | for y in range(display_height - height, display_height):
528 | try:
529 | # Calculate relative position in the bar
530 | rel_pos = (y - (display_height - height)) / height if height > 0 else 0
531 |
532 | # Select character based on signal strength and position
533 | if value > 0.8: # Strong signals
534 | char = "#" if rel_pos > 0.5 else "="
535 | elif value > 0.4: # Medium signals
536 | char = "=" if rel_pos > 0.5 else "-"
537 | elif value > 0.2: # Weak signals
538 | char = "-" if rel_pos > 0.5 else "."
539 | else: # Noise level
540 | if rel_pos > 0.7:
541 | char = "."
542 | else:
543 | char = " "
544 |
545 | stdscr.addstr(y + 2, x + 9, char, curses.color_pair(1))
546 |
547 | except curses.error:
548 | pass
549 |
550 | # Use standardized frequency labels
551 | draw_frequency_labels(stdscr, center_freq, bandwidth, display_height, display_width)
552 |
553 | # Run this function before using the rtl-sdr samples to remove dc offset and correct iq
554 | def iq_correction(samples: np.ndarray) -> np.ndarray:
555 | # Remove DC and calculate input power
556 | centered_samples = samples - np.mean(samples)
557 | input_power = np.var(centered_samples)
558 |
559 | # Calculate scaling factor for Q
560 | q_amplitude = np.sqrt(2 * np.mean(samples.imag ** 2))
561 |
562 | # Normalize Q component
563 | normalized_samples = samples / q_amplitude
564 |
565 | i_samples, q_samples = normalized_samples.real, normalized_samples.imag
566 |
567 | # Estimate alpha and sin_phi
568 | alpha_est = np.sqrt(2 * np.mean(i_samples ** 2))
569 | sin_phi_est = (2 / alpha_est) * np.mean(i_samples * q_samples)
570 |
571 | # Estimate cos_phi
572 | cos_phi_est = np.sqrt(1 - sin_phi_est ** 2)
573 |
574 | # Apply phase and amplitude correction
575 | i_new = (1 / alpha_est) * i_samples
576 | q_new = (-sin_phi_est / alpha_est) * i_samples + q_samples
577 |
578 | # Corrected signal
579 | corrected_samples = (i_new + 1j * q_new) / cos_phi_est
580 |
581 | # Calculate and print phase and amplitude errors
582 | phase_error_deg = np.round(np.abs(np.arccos(cos_phi_est) * 180 / np.pi), 4)
583 | amplitude_error_db = np.round(np.abs(20 * np.log10(alpha_est)), 4)
584 |
585 | # Print phase and amplitude errors
586 | #print(f"Phase Error: {phase_error_deg}")
587 | #print(f"Amplitude Error: {amplitude_error_db}")
588 |
589 | return corrected_samples * np.sqrt(input_power / np.var(corrected_samples))
590 |
591 | def decode_mono(samples: np.ndarray, fs: int):
592 | """Decode FM modulation to mono audio."""
593 | demod_gain = fs / (2 * np.pi * np.pi * 75e3) # 75e3 is the frequency deviation
594 |
595 | # FM Demodulation
596 | demod = demod_gain * np.angle(samples[:-1] * samples.conj()[1:])
597 |
598 | # Sample rate after decimation will be 41666.67
599 | decimation = 6
600 |
601 | # Decimate to get mono audio
602 | #mono = signal.decimate(demod, decimation, ftype="fir")
603 | mono = decimate(demod, decimation, ftype="fir")
604 |
605 | # De-emphasis is 75e-6 for North America, 50e-6 for everywhere else
606 | deemphasis = 75e-6
607 |
608 | # Create filter coefficients for de-emphasis
609 | bz, az = bilinear([1], [deemphasis, 1], fs=fs)
610 |
611 | # Apply the de-emphasis filter
612 | mono = lfilter(bz, az, mono)
613 | mono -= mono.mean()
614 |
615 | mono *= 0.75 # Volume factor
616 | mono *= 32768
617 | mono = mono.astype(np.int16)
618 |
619 | return mono
620 |
621 | def demodulate_signal(samples, sample_rate, mode='NFM'):
622 | """Advanced demodulation function supporting multiple modes"""
623 | samples = iq_correction(samples)
624 | if mode == 'NFM':
625 | return demodulate_nfm(samples, sample_rate)
626 | elif mode == 'WFM':
627 | return demodulate_wfm(samples, sample_rate)
628 | elif mode == 'AM':
629 | return demodulate_am(samples)
630 | elif mode == 'USB':
631 | return demodulate_ssb(samples, sample_rate, lower=False)
632 | elif mode == 'LSB':
633 | return demodulate_ssb(samples, sample_rate, lower=True)
634 | elif mode == 'RAW':
635 | return np.real(samples) # Return raw I samples
636 | #return np.zeros_like(samples) # Return silence if mode not recognized
637 | return np.zeros((len(samples), 2)) # Ensure it returns a shape of (n, 2)
638 |
639 | # Filter to cut freq below/higher than 300/3000hz
640 | def butter_bandpass(lowcut, highcut, fs, order=5):
641 | nyq = 0.5 * fs
642 | low = lowcut / nyq
643 | high = highcut / nyq
644 | b, a = butter(order, [low, high], btype='band')
645 | return b, a
646 |
647 | def mono_to_stereo(mono_audio):
648 | """Convert mono audio to stereo by duplicating the mono signal."""
649 | stereo_audio = np.zeros((len(mono_audio), 2)) # Initialize stereo array
650 | stereo_audio[:, 0] = mono_audio # Left channel
651 | stereo_audio[:, 1] = mono_audio # Right channel (duplicate)
652 | return stereo_audio
653 |
654 | def demodulate_nfm(samples, sample_rate, target_rate=44100):
655 | """Simplified FM demodulation"""
656 | # Basic FM demodulation
657 | demod = np.angle(samples[1:] * np.conj(samples[:-1]))
658 |
659 | # Simple scaling
660 | demod = demod * (sample_rate / (2 * np.pi))
661 |
662 | # Apply the bandpass filter for NFM
663 | lowcut = 300.0 # Low cutoff frequency
664 | highcut = 3000.0 # High cutoff frequency
665 | filtered_demod = bandpass_filter(demod, lowcut, highcut, sample_rate)
666 |
667 | # Basic lowpass filter
668 | nyq = sample_rate / 2
669 | cutoff = 15000
670 | taps = firwin(numtaps=65, cutoff=cutoff/nyq)
671 | filtered = lfilter(taps, 1.0, demod)
672 |
673 | # Simple decimation
674 | decimation_factor = int(sample_rate / target_rate)
675 | audio = decimate(filtered, decimation_factor)
676 |
677 | # Basic normalization
678 | audio = audio / np.max(np.abs(audio)) * 0.95
679 | return mono_to_stereo(audio)
680 |
681 | def bandpass_filter(data, lowcut, highcut, sample_rate):
682 | """Apply a bandpass filter to the data."""
683 | from scipy.signal import butter, sosfilt
684 | if lowcut <= 0:
685 | # Use a lowpass filter if lowcut is not valid
686 | sos = butter(10, highcut / (sample_rate / 2), btype='low', output='sos')
687 | else:
688 | sos = butter(10, [lowcut / (sample_rate / 2), highcut / (sample_rate / 2)], btype='band', output='sos')
689 | return sosfilt(sos, data)
690 |
691 |
692 | def demodulate_wfm(samples, sample_rate, target_rate=44100):
693 | """Wide FM demodulation with stereo decoding."""
694 | # Step 1: FM demodulation
695 | demod = np.angle(samples[1:] * np.conj(samples[:-1]))
696 |
697 | # Step 2: Extract the baseband (L+R), pilot, and stereo difference (L-R) signals
698 | # Lowpass filter for L+R (0-15 kHz)
699 | l_plus_r = bandpass_filter(demod, 0, 15000, sample_rate)
700 |
701 |
702 | # Bandpass filter for the 19 kHz pilot tone
703 | pilot = bandpass_filter(demod, 19000 - 200, 19000 + 200, sample_rate)
704 | pilot = np.sin(np.unwrap(np.angle(lfilter([1], [1, -0.99], pilot)))) # Extract phase
705 |
706 | # Bandpass filter for the 38 kHz L-R signal
707 | l_minus_r = bandpass_filter(demod, 38000 - 15000, 38000 + 15000, sample_rate)
708 | l_minus_r = l_minus_r * (2 * pilot) # Demodulate using the pilot tone
709 |
710 | # Lowpass filter the demodulated L-R signal to remove high-frequency artifacts
711 | l_minus_r = bandpass_filter(l_minus_r, 0, 15000, sample_rate)
712 |
713 | # Step 3: Combine L+R and L-R to get L and R
714 | left = (l_plus_r + l_minus_r) / 2
715 | right = (l_plus_r - l_minus_r) / 2
716 |
717 | # Step 4: De-emphasis filter (75 µs time constant)
718 | deemph_tc = 75e-6 # 75 µs (FM standard)
719 | alpha = np.exp(-1 / (deemph_tc * sample_rate))
720 | b = [1 - alpha]
721 | a = [1, -alpha]
722 | left = lfilter(b, a, left)
723 | right = lfilter(b, a, right)
724 |
725 | # Step 5: Decimate to target sample rate
726 | decimation_factor = int(sample_rate / target_rate)
727 | if decimation_factor > 1:
728 | left = decimate(left, decimation_factor, zero_phase=True)
729 | right = decimate(right, decimation_factor, zero_phase=True)
730 |
731 | # Step 6: Normalize the audio
732 | max_val = max(np.max(np.abs(left)), np.max(np.abs(right)))
733 | left /= max_val
734 | right /= max_val
735 |
736 | # Step 7: Combine into stereo
737 | audio = np.column_stack((left, right))
738 | return audio
739 |
740 | def demodulate_am(samples):
741 | """AM demodulation using envelope detection"""
742 | # Get the amplitude envelope
743 | envelope = np.abs(samples)
744 |
745 | # DC removal (high-pass filter)
746 | envelope = envelope - np.mean(envelope)
747 |
748 | # Apply the bandpass filter to remove low and high frequency harmonics
749 | fs = 44100 # Sample rate (adjust as necessary)
750 | lowcut = 300.0 # Low cutoff frequency
751 | highcut = 3000.0 # High cutoff frequency
752 | filtered_envelope = bandpass_filter(envelope, lowcut, highcut, fs)
753 |
754 | # Normalize
755 | audio = filtered_envelope / np.max(np.abs(filtered_envelope)) * 0.95
756 | return mono_to_stereo(audio)
757 |
758 | def demodulate_ssb(samples, sample_rate, lower=True):
759 | """Single-sideband demodulation"""
760 | # Complex bandpass filter
761 | if lower:
762 | # LSB: negative frequencies only
763 | taps = firwin(65, 3000/sample_rate, window='hamming')
764 | analytical = lfilter(taps, 1.0, samples)
765 | analytical = hilbert(np.real(analytical))
766 | else:
767 | # USB: positive frequencies only
768 | taps = firwin(65, 3000/sample_rate, window='hamming')
769 | analytical = lfilter(taps, 1.0, samples)
770 | analytical = hilbert(np.real(analytical))
771 |
772 | # Demodulate
773 | demod = np.real(analytical)
774 |
775 | # Normalize
776 | audio = demod / np.max(np.abs(demod)) * 0.95
777 | return mono_to_stereo(audio)
778 |
779 | # APRS Functions
780 |
781 | def decode_afsk(samples, sample_rate):
782 | """
783 | Demodulate Bell 202 AFSK (1200/2200 Hz)
784 | Returns bit stream
785 | """
786 | # Filter for AFSK tones
787 | filtered_1200 = bandpass_filter(samples, 1100, 1300, sample_rate)
788 | filtered_2200 = bandpass_filter(samples, 2100, 2300, sample_rate)
789 |
790 | # Calculate energy in each band
791 | window = int(sample_rate / 1200) # One bit period
792 | bits = []
793 |
794 | for i in range(0, len(samples) - window, window):
795 | e1200 = np.sum(filtered_1200[i:i+window]**2)
796 | e2200 = np.sum(filtered_2200[i:i+window]**2)
797 | bits.append(1 if e2200 > e1200 else 0)
798 |
799 | return bits
800 |
801 | def decode_aprs(samples, sample_rate):
802 | """
803 | Decode APRS packets from audio samples
804 | Returns list of decoded packets
805 | """
806 | # Convert to real if complex
807 | if np.iscomplexobj(samples):
808 | samples = np.real(samples)
809 |
810 | # Normalize audio
811 | samples = samples / np.max(np.abs(samples))
812 |
813 | # Demodulate AFSK to get bit stream
814 | bits = decode_afsk(samples, sample_rate)
815 |
816 | # Decode AX.25 frame
817 | packet = pyspecaprs.decode_ax25_frame(bits)
818 |
819 | return [packet] if packet else []
820 |
821 | def show_aprs_decoder(stdscr, sdr, sample_rate):
822 | """
823 | Show APRS decoder interface
824 | """
825 | stdscr.clear()
826 | stdscr.addstr(0, 0, "APRS Decoder - Press 'q' to exit")
827 | stdscr.addstr(2, 0, "Listening for APRS packets...")
828 | stdscr.refresh()
829 |
830 | while True:
831 | # Read samples
832 | samples = sdr.read_samples(int(sample_rate * 0.5)) # 0.5 second buffer
833 |
834 | # Decode APRS
835 | packets = decode_aprs(samples, sample_rate)
836 |
837 | # Display results
838 | if packets:
839 | for i, packet in enumerate(packets):
840 | if packet and 4 + i < stdscr.getmaxyx()[0]:
841 | # Clean the packet string - remove null chars and non-printable chars
842 | clean_packet = ''.join(c for c in packet if c.isprintable() or c.isspace())
843 | # Truncate to screen width
844 | max_width = stdscr.getmaxyx()[1] - 1
845 | display_str = clean_packet[:max_width]
846 | try:
847 | stdscr.addstr(4 + i, 0, display_str)
848 | except:
849 | pass # Skip if we can't display this packet
850 |
851 | stdscr.refresh()
852 |
853 | # Check for quit
854 | if stdscr.getch() == ord('q'):
855 | break
856 |
857 | # Morse Code functions
858 |
859 | def decode_morse(samples, sample_rate, threshold=-20):
860 | """
861 | Decode Morse code from audio samples
862 |
863 | Args:
864 | samples: numpy array of audio samples (complex IQ data)
865 | sample_rate: sampling rate in Hz
866 | threshold: signal detection threshold in dB
867 |
868 | Returns:
869 | decoded_text: string of decoded text
870 | timing_data: dict with timing statistics
871 | """
872 | # Convert complex samples to magnitude
873 | envelope = np.abs(samples)
874 |
875 | # Normalize and convert to dB
876 | envelope = envelope / np.max(envelope)
877 | envelope_db = 20 * np.log10(envelope + 1e-10)
878 |
879 | # Rest of the function remains the same...
880 | # Detect signals above threshold
881 | signals = envelope_db > threshold
882 |
883 | # Find transitions
884 | transitions = np.diff(signals.astype(int))
885 | rise_times = np.where(transitions == 1)[0]
886 | fall_times = np.where(transitions == -1)[0]
887 |
888 | if len(rise_times) == 0 or len(fall_times) == 0:
889 | return "", {"dot": 0, "dash": 0, "gap": 0}
890 |
891 | # Ensure we have matching rises and falls
892 | if fall_times[0] < rise_times[0]:
893 | fall_times = fall_times[1:]
894 | if len(rise_times) > len(fall_times):
895 | rise_times = rise_times[:-1]
896 |
897 | # Calculate pulse durations
898 | durations = (fall_times - rise_times) / sample_rate
899 | gaps = (rise_times[1:] - fall_times[:-1]) / sample_rate
900 |
901 | if len(durations) == 0:
902 | return "", {"dot": 0, "dash": 0, "gap": 0}
903 |
904 | # Estimate dot/dash threshold using k-means clustering
905 | if len(durations) > 1:
906 | from scipy.cluster import vq
907 | centroids, _ = vq.kmeans(durations.reshape(-1, 1), 2)
908 | dot_duration = np.min(centroids)
909 | dash_duration = np.max(centroids)
910 | else:
911 | dot_duration = np.min(durations)
912 | dash_duration = dot_duration * 3
913 |
914 | # Classify dots and dashes
915 | morse_symbols = []
916 | current_letter = []
917 |
918 | for i, duration in enumerate(durations):
919 | # Add symbol
920 | if duration < (dot_duration + dash_duration) / 2:
921 | current_letter.append('.')
922 | else:
923 | current_letter.append('-')
924 |
925 | # Check for letter gaps
926 | if i < len(gaps):
927 | if gaps[i] > dot_duration * 3:
928 | morse_symbols.append(''.join(current_letter))
929 | current_letter = []
930 | # Check for word gaps
931 | if gaps[i] > dot_duration * 7:
932 | morse_symbols.append(' ')
933 |
934 | # Add final letter if present
935 | if current_letter:
936 | morse_symbols.append(''.join(current_letter))
937 |
938 | # Translate to text
939 | decoded_text = ''
940 | for symbol in morse_symbols:
941 | if symbol == ' ':
942 | decoded_text += ' '
943 | elif symbol in MORSE_CODE:
944 | decoded_text += MORSE_CODE[symbol]
945 | else:
946 | decoded_text += '?'
947 |
948 | timing_data = {
949 | "dot": dot_duration,
950 | "dash": dash_duration,
951 | "gap": np.mean(gaps) if len(gaps) > 0 else 0
952 | }
953 |
954 | return decoded_text, timing_data
955 |
956 | def show_morse_decoder(stdscr, sdr, sample_rate):
957 | """Display Morse code decoder interface with continuous decoding"""
958 | max_height, max_width = stdscr.getmaxyx()
959 |
960 | # Save original SDR settings
961 | original_freq = sdr.center_freq
962 | original_sample_rate = sdr.sample_rate
963 | original_gain = sdr.gain
964 |
965 | try:
966 | # Configure SDR for Morse reception
967 | sdr.sample_rate = 48000 # Lower sample rate for CW
968 | sdr.bandwidth = 2000 # Narrow bandwidth for CW
969 | time.sleep(0.1) # Let the SDR settle
970 |
971 | # Enable nodelay for continuous updates
972 | stdscr.nodelay(True)
973 |
974 | # Initialize display buffer for scrolling text
975 | text_buffer = []
976 | max_buffer_lines = max_height - 12 # Reserve space for header and timing info
977 |
978 | while True:
979 | try:
980 | # Read new samples
981 | num_samples = int(sdr.sample_rate * 0.5) # 0.5 seconds of data
982 | samples = sdr.read_samples(num_samples)
983 |
984 | if len(samples) == 0:
985 | continue
986 |
987 | # Decode the morse code
988 | decoded_text, timing = decode_morse(samples, sdr.sample_rate)
989 |
990 | if decoded_text.strip(): # Only add non-empty decoded text
991 | text_buffer.append(decoded_text)
992 | # Keep buffer size limited
993 | if len(text_buffer) > max_buffer_lines:
994 | text_buffer.pop(0)
995 |
996 | # Clear screen and show results
997 | stdscr.clear()
998 |
999 | # Show header
1000 | header = "Morse Code Decoder (Press 'q' to quit)"
1001 | stdscr.addstr(0, 2, header, curses.color_pair(1) | curses.A_BOLD)
1002 | stdscr.addstr(1, 2, "-" * len(header), curses.color_pair(2))
1003 |
1004 | # Show current frequency
1005 | freq_info = f"Frequency: {sdr.center_freq/1e6:.3f} MHz"
1006 | stdscr.addstr(2, 2, freq_info, curses.color_pair(2))
1007 |
1008 | # Show timing information
1009 | timing_info = (f"Timing Statistics:\n"
1010 | f"Dot duration: {timing['dot']*1000:.1f} ms\n"
1011 | f"Dash duration: {timing['dash']*1000:.1f} ms\n"
1012 | f"Average gap: {timing['gap']*1000:.1f} ms")
1013 |
1014 | for i, line in enumerate(timing_info.split('\n')):
1015 | stdscr.addstr(4+i, 2, line, curses.color_pair(2))
1016 |
1017 | # Show decoded text header
1018 | stdscr.addstr(9, 2, "Decoded Text:", curses.color_pair(1) | curses.A_BOLD)
1019 |
1020 | # Show scrolling decoded text
1021 | for i, text in enumerate(text_buffer):
1022 | try:
1023 | # Word wrap each line
1024 | words = text.split()
1025 | current_line = ""
1026 | line_num = i
1027 |
1028 | for word in words:
1029 | if len(current_line) + len(word) + 1 > max_width - 4:
1030 | stdscr.addstr(10+line_num, 2, current_line, curses.color_pair(4))
1031 | current_line = word
1032 | line_num += 1
1033 | else:
1034 | current_line += (" " + word if current_line else word)
1035 |
1036 | if current_line:
1037 | stdscr.addstr(10+line_num, 2, current_line, curses.color_pair(4))
1038 |
1039 | except curses.error:
1040 | # Skip if we run out of screen space
1041 | pass
1042 |
1043 | # Show footer
1044 | stdscr.addstr(max_height-2, 2, "Press 'q' to quit", curses.color_pair(2))
1045 |
1046 | stdscr.refresh()
1047 |
1048 | # Check for quit command
1049 | try:
1050 | key = stdscr.getch()
1051 | if key == ord('q'):
1052 | break
1053 | except curses.error:
1054 | pass
1055 |
1056 | # Small delay to prevent excessive CPU usage
1057 | time.sleep(0.1)
1058 |
1059 | except RuntimeError as e:
1060 | # Handle stream errors
1061 | stdscr.addstr(max_height-1, 2, f"Stream error: {str(e)}", curses.color_pair(3))
1062 | stdscr.refresh()
1063 | time.sleep(1)
1064 | continue
1065 |
1066 | finally:
1067 | # Restore original SDR settings
1068 | sdr.center_freq = original_freq
1069 | sdr.sample_rate = original_sample_rate
1070 | sdr.gain = original_gain
1071 | time.sleep(0.1) # Let the SDR settle
1072 |
1073 | # Restore normal terminal behavior
1074 | stdscr.nodelay(False)
1075 |
1076 |
1077 | # End of Morse Code functions
1078 |
1079 | def butter_lowpass(cutoff, fs, order=5):
1080 | nyq = 0.5 * fs
1081 | normal_cutoff = cutoff / nyq
1082 | b, a = butter(order, normal_cutoff, btype='low', analog=False)
1083 | return b, a
1084 |
1085 | def lowpass_filter(data, cutoff=3000, fs=44100, order=5):
1086 | b, a = butter_lowpass(cutoff, fs, order=order)
1087 | y = lfilter(b, a, data)
1088 | return y
1089 |
1090 | def audio_callback(outdata, frames, time, status):
1091 | """Audio callback that writes stereo data to the output."""
1092 | if len(audio_buffer) > 0:
1093 | data = np.concatenate(list(audio_buffer))
1094 | if len(data) >= frames:
1095 | outdata[:] = data[:frames].reshape(-1, 2) # Reshape for stereo output
1096 | audio_buffer.clear()
1097 | if len(data) > frames:
1098 | audio_buffer.append(data[frames:])
1099 | else:
1100 | outdata[:] = np.zeros((frames, 2)) # Stereo output
1101 | else:
1102 | outdata[:] = np.zeros((frames, 2)) # Stereo output
1103 |
1104 | def load_bookmarks():
1105 | try:
1106 | with open(BOOKMARK_FILE, 'r') as f:
1107 | return json.load(f)
1108 | except (FileNotFoundError, json.JSONDecodeError):
1109 | return {}
1110 |
1111 | def save_bookmark(name, freq,bandwidth):
1112 | bookmarks = load_bookmarks()
1113 | bookmarks[name] = [freq, CURRENT_DEMOD, bandwidth]
1114 | with open(BOOKMARK_FILE, 'w') as f:
1115 | json.dump(bookmarks, f, indent=2)
1116 |
1117 | def add_bookmark(stdscr, freq,bandwidth):
1118 | max_height, max_width = stdscr.getmaxyx()
1119 | draw_clearheader(stdscr)
1120 | stdscr.addstr(0, 0, "Enter bookmark name: ", curses.color_pair(1) | curses.A_BOLD)
1121 | curses.echo()
1122 | curses.curs_set(1)
1123 | stdscr.nodelay(False)
1124 | name = stdscr.getstr().decode('utf-8')
1125 | draw_clearheader(stdscr)
1126 | curses.noecho()
1127 | curses.curs_set(0)
1128 | stdscr.nodelay(True)
1129 | if name:
1130 | save_bookmark(name, freq, bandwidth)
1131 |
1132 | def show_bookmarks(stdscr):
1133 | """Display bookmarks with pagination and deletion capability"""
1134 | bookmarks = load_bookmarks()
1135 | if not bookmarks:
1136 | show_popup_msg(stdscr, "No bookmarks found!", error=True)
1137 | return None
1138 |
1139 | # Initialize pagination variables
1140 | max_height, max_width = stdscr.getmaxyx()
1141 | items_per_page = max_height - 7 # Reserve space for header and footer
1142 | total_items = len(bookmarks)
1143 | total_pages = (total_items + items_per_page - 1) // items_per_page
1144 | current_page = 0
1145 |
1146 | while True:
1147 | stdscr.clear()
1148 |
1149 | # Draw header
1150 | header = "Bookmarks"
1151 | stdscr.addstr(0, 2, header, curses.color_pair(1) | curses.A_BOLD)
1152 | stdscr.addstr(1, 2, "-" * len(header), curses.color_pair(2))
1153 |
1154 | # Calculate slice for current page
1155 | start_idx = current_page * items_per_page
1156 | end_idx = min(start_idx + items_per_page, total_items)
1157 | current_items = list(bookmarks.items())[start_idx:end_idx]
1158 |
1159 | # Display bookmarks for current page
1160 | for i, (name, details) in enumerate(current_items, 1):
1161 | freq = details[0]
1162 | mode = details[1]
1163 | band = details[2]
1164 | abs_index = start_idx + i
1165 | line = f"{abs_index:2d}. {name:<20}: {freq/1e6:.3f} MHz {mode:<3} {band:>9}Hz"
1166 | try:
1167 | stdscr.addstr(i + 2, 2, line, curses.color_pair(2))
1168 | except curses.error:
1169 | pass
1170 |
1171 | # Draw footer with navigation help
1172 | footer = f"Page {current_page + 1}/{total_pages} | [n]ext/[p]rev page | [d]elete | [q]uit"
1173 | try:
1174 | stdscr.addstr(max_height-2, 2, footer, curses.color_pair(5))
1175 | stdscr.addstr(max_height-1, 2, "Choice: ", curses.color_pair(1) | curses.A_BOLD)
1176 | except curses.error:
1177 | pass
1178 |
1179 | # Handle input
1180 | curses.echo()
1181 | curses.curs_set(1)
1182 | stdscr.nodelay(False)
1183 |
1184 | try:
1185 | choice = stdscr.getstr().decode('utf-8').lower()
1186 |
1187 | if choice == 'q':
1188 | break
1189 | elif choice == 'n' and current_page < total_pages - 1:
1190 | current_page += 1
1191 | continue
1192 | elif choice == 'p' and current_page > 0:
1193 | current_page -= 1
1194 | continue
1195 | elif choice == 'd':
1196 | # Handle bookmark deletion
1197 | stdscr.addstr(max_height-1, 2, "Enter number to delete: ",
1198 | curses.color_pair(3) | curses.A_BOLD)
1199 | try:
1200 | del_choice = int(stdscr.getstr().decode('utf-8'))
1201 | if 1 <= del_choice <= total_items:
1202 | # Get bookmark name and delete it
1203 | del_name = list(bookmarks.keys())[del_choice - 1]
1204 | del bookmarks[del_name]
1205 | # Save updated bookmarks
1206 | with open(BOOKMARK_FILE, 'w') as f:
1207 | json.dump(bookmarks, f, indent=2)
1208 | # Update pagination variables
1209 | total_items = len(bookmarks)
1210 | total_pages = (total_items + items_per_page - 1) // items_per_page
1211 | current_page = min(current_page, total_pages - 1)
1212 | show_popup_msg(stdscr, f"Deleted bookmark: {del_name}")
1213 | if not bookmarks:
1214 | return None
1215 | except ValueError:
1216 | show_popup_msg(stdscr, "Invalid selection!", error=True)
1217 | else:
1218 | try:
1219 | choice_num = int(choice)
1220 | if 1 <= choice_num <= total_items:
1221 | return list(bookmarks.values())[choice_num - 1]
1222 | except ValueError:
1223 | show_popup_msg(stdscr, "Invalid selection!", error=True)
1224 |
1225 | except curses.error:
1226 | pass
1227 | finally:
1228 | stdscr.nodelay(True)
1229 | curses.noecho()
1230 | curses.curs_set(0)
1231 |
1232 | return None
1233 |
1234 | def record_signal(sdr, duration, filename):
1235 | """Record raw IQ samples to a file"""
1236 | samples = sdr.read_samples(int(duration * sdr.sample_rate))
1237 | np.save(filename, samples)
1238 | return samples
1239 |
1240 | def play_recorded_signal(filename):
1241 | """Play back recorded IQ samples"""
1242 | samples = np.load(filename)
1243 | return samples
1244 |
1245 | def start_audio_recording(filename, sample_rate=44100):
1246 | """Start recording audio to a WAV file"""
1247 | wav_file = wave.open(filename, 'wb')
1248 | wav_file.setnchannels(2) # stereo
1249 | wav_file.setsampwidth(2) # 2 bytes per sample
1250 | wav_file.setframerate(sample_rate)
1251 | return wav_file
1252 |
1253 | def write_audio_samples(wav_file, samples):
1254 | """Write audio samples to the WAV file"""
1255 | # Convert float samples to 16-bit integers
1256 | scaled = np.int16(samples * 32767)
1257 | wav_file.writeframes(scaled.tobytes())
1258 |
1259 | def stop_audio_recording(wav_file):
1260 | """Close the WAV file"""
1261 | wav_file.close()
1262 |
1263 | def save_settings(sdr, bandwidth, freq_step, samples, agc_enabled):
1264 | """Save current SDR settings to a config file"""
1265 | config = configparser.ConfigParser()
1266 |
1267 | # Find current band (if any)
1268 | current_band = None
1269 | for band, (start, end, _) in BAND_PRESETS.items():
1270 | if start <= sdr.center_freq <= end:
1271 | current_band = band
1272 | break
1273 |
1274 | config['SDR'] = {
1275 | 'frequency': str(sdr.center_freq),
1276 | 'sample_rate': str(sdr.sample_rate),
1277 | 'gain': str(sdr.gain),
1278 | 'bandwidth': str(bandwidth),
1279 | 'freq_step': str(freq_step),
1280 | 'samples': str(samples),
1281 | 'agc_enabled': str(agc_enabled),
1282 | 'current_band': str(current_band) if current_band else '',
1283 | 'ppm': str(sdr.ppm) # Add PPM to saved settings
1284 | }
1285 |
1286 | with open(SETTINGS_FILE, 'w') as configfile:
1287 | config.write(configfile)
1288 |
1289 | def load_settings():
1290 | """Load SDR settings from config file"""
1291 | config = configparser.ConfigParser()
1292 | default_settings = {
1293 | 'frequency': '92.5e6',
1294 | 'sample_rate': '1.024e6',
1295 | 'gain': 'auto', # Keep as string for 'auto'
1296 | 'bandwidth': '1e6',
1297 | 'freq_step': '0.1e6',
1298 | 'samples': '7',
1299 | 'agc_enabled': 'False',
1300 | 'current_band': '',
1301 | 'ppm': '0' # Add default PPM value
1302 | }
1303 |
1304 | if os.path.exists(SETTINGS_FILE):
1305 | config.read(SETTINGS_FILE)
1306 | if 'SDR' in config:
1307 | return {
1308 | 'frequency': float(config['SDR'].get('frequency', default_settings['frequency'])),
1309 | 'sample_rate': float(config['SDR'].get('sample_rate', default_settings['sample_rate'])),
1310 | 'gain': config['SDR'].get('gain', default_settings['gain']), # Keep as string
1311 | 'bandwidth': float(config['SDR'].get('bandwidth', default_settings['bandwidth'])),
1312 | 'freq_step': float(config['SDR'].get('freq_step', default_settings['freq_step'])),
1313 | 'samples': int(config['SDR'].get('samples', default_settings['samples'])),
1314 | 'agc_enabled': config['SDR'].get('agc_enabled', default_settings['agc_enabled']) == 'True',
1315 | 'current_band': config['SDR'].get('current_band', default_settings['current_band']),
1316 | 'ppm': int(config['SDR'].get('ppm', default_settings['ppm']))
1317 | }
1318 |
1319 | # Convert default settings to appropriate types
1320 | return {
1321 | 'frequency': float(default_settings['frequency']),
1322 | 'sample_rate': float(default_settings['sample_rate']),
1323 | 'gain': default_settings['gain'], # Keep as string
1324 | 'bandwidth': float(default_settings['bandwidth']),
1325 | 'freq_step': float(default_settings['freq_step']),
1326 | 'samples': int(default_settings['samples']),
1327 | 'agc_enabled': default_settings['agc_enabled'] == 'True',
1328 | 'current_band': default_settings['current_band'],
1329 | 'ppm': int(default_settings['ppm'])
1330 | }
1331 |
1332 | def measure_signal_power(samples):
1333 | """Calculate average power of signal in dB"""
1334 | power = np.mean(np.abs(samples)**2)
1335 | return 10 * np.log10(power + 1e-10) # Add small value to prevent log(0)
1336 |
1337 | def adjust_gain(sdr, current_power, gainindex):
1338 | """Adjust gain to reach target power level"""
1339 | power_diff = AGC_TARGET_POWER - current_power
1340 |
1341 | # Only adjust if difference is significant
1342 | if abs(power_diff) < 2: # 2 dB threshold
1343 | return gainindex
1344 |
1345 | if power_diff > 0: # Signal too weak, increase gain
1346 | gainindex += 1
1347 | if gainindex <= len(sdr.valid_gains_db) - 1:
1348 | sdr.gain = sdr.valid_gains_db[gainindex]
1349 | else:
1350 | gainindex = len(sdr.valid_gains_db) - 1
1351 | else: # Signal too strong, decrease gain
1352 | gainindex -= 1
1353 | if gainindex >= 0:
1354 | sdr.gain = sdr.valid_gains_db[gainindex]
1355 | else:
1356 | gainindex = 0
1357 |
1358 | return gainindex
1359 |
1360 | def show_popup_msg(stdscr,msg,error=False,pause=2):
1361 | draw_clearheader(stdscr)
1362 | if error:
1363 | stdscr.addstr(0, 0, msg, curses.color_pair(3))
1364 | else:
1365 | stdscr.addstr(0, 0, msg, curses.color_pair(4))
1366 | stdscr.refresh()
1367 | time.sleep(pause)
1368 | draw_clearheader(stdscr)
1369 |
1370 | def show_band_presets(stdscr):
1371 | """Display and select from available band presets with scrolling support"""
1372 | max_height, max_width = stdscr.getmaxyx()
1373 | available_height = max_height - 6 # Reserve space for header and footer
1374 |
1375 | # Calculate total entries and pages
1376 | total_entries = len(BAND_PRESETS)
1377 | entries_per_page = available_height
1378 | total_pages = (total_entries + entries_per_page - 1) // entries_per_page
1379 | current_page = 0
1380 |
1381 | while True:
1382 | stdscr.clear()
1383 |
1384 | # Draw header
1385 | header = "Available Band Presets"
1386 | stdscr.addstr(0, 2, header, curses.color_pair(1) | curses.A_BOLD)
1387 | stdscr.addstr(1, 2, "-" * len(header), curses.color_pair(2))
1388 |
1389 | # Calculate slice for current page
1390 | start_idx = current_page * entries_per_page
1391 | end_idx = min(start_idx + entries_per_page, total_entries)
1392 |
1393 | # Display current page of presets
1394 | current_items = list(BAND_PRESETS.items())[start_idx:end_idx]
1395 | for i, (key, (start, end, description)) in enumerate(current_items, 1):
1396 | # Calculate absolute index for selection
1397 | abs_index = start_idx + i
1398 | # Add recommended bandwidth to display if available
1399 | if key in BAND_BANDWIDTHS:
1400 | bw_info = f" (BW: {BAND_BANDWIDTHS[key]/1e3:.0f}kHz)"
1401 | else:
1402 | bw_info = ""
1403 | line = f"{abs_index:2d}. {key:<8} : {description:<25}{bw_info} ({start/1e6:.3f}-{end/1e6:.3f} MHz)"
1404 | try:
1405 | stdscr.addstr(i + 2, 2, line, curses.color_pair(2))
1406 | except curses.error:
1407 | pass
1408 |
1409 | # Draw footer with navigation help
1410 | footer = f"Page {current_page + 1}/{total_pages} | [n]ext/[p]rev page | [q]uit | Enter number to select"
1411 | try:
1412 | stdscr.addstr(max_height-2, 2, footer, curses.color_pair(5))
1413 | stdscr.addstr(max_height-1, 2, "Choice: ", curses.color_pair(1) | curses.A_BOLD)
1414 | except curses.error:
1415 | pass
1416 |
1417 | # Handle input
1418 | curses.echo()
1419 | curses.curs_set(1)
1420 | stdscr.nodelay(False)
1421 |
1422 | try:
1423 | choice = stdscr.getstr().decode('utf-8').lower()
1424 |
1425 | if choice == 'q':
1426 | break
1427 | elif choice == 'n' and current_page < total_pages - 1:
1428 | current_page += 1
1429 | continue
1430 | elif choice == 'p' and current_page > 0:
1431 | current_page -= 1
1432 | continue
1433 |
1434 | try:
1435 | choice_num = int(choice)
1436 | if 1 <= choice_num <= total_entries:
1437 | # Get selected band
1438 | band_key = list(BAND_PRESETS.keys())[choice_num - 1]
1439 | start, end, _ = BAND_PRESETS[band_key]
1440 | # Use recommended bandwidth if available, otherwise calculate
1441 | if band_key in BAND_BANDWIDTHS:
1442 | bandwidth = BAND_BANDWIDTHS[band_key]
1443 | else:
1444 | bandwidth = min(end - start, 2e6) # Limit bandwidth to 2MHz or band width
1445 | return start + (end - start)/2, bandwidth
1446 | except ValueError:
1447 | pass
1448 |
1449 | except curses.error:
1450 | pass
1451 | finally:
1452 | stdscr.nodelay(True)
1453 | curses.noecho()
1454 | curses.curs_set(0)
1455 |
1456 | return None, None
1457 |
1458 | def scan_frequencies(stdscr,sdr, start_freq, end_freq, threshold, step=SCAN_STEP):
1459 | """Scan frequency range and detect signals above threshold"""
1460 | signals = []
1461 | current_freq = start_freq
1462 | samples_per_scan = int(SCAN_DWELL_TIME * sdr.sample_rate)
1463 | max_height, max_width = stdscr.getmaxyx() # Get screen dimensions
1464 |
1465 | # Calculate total steps for progress bar
1466 | total_steps = int((end_freq - start_freq) / step)
1467 | current_step = 0
1468 |
1469 | while current_freq <= end_freq:
1470 | try:
1471 | # Update scanning status display
1472 | draw_scanning_status(stdscr, current_freq, start_freq, end_freq, sdr)
1473 |
1474 | # Check for user interrupt ('q' to quit scanning)
1475 | if stdscr.getch() == ord('q'):
1476 | break
1477 |
1478 | sdr.center_freq = current_freq
1479 | time.sleep(0.01) # Small delay to let SDR settle
1480 | samples = sdr.read_samples(samples_per_scan)
1481 |
1482 | if len(samples) == 0:
1483 | continue
1484 |
1485 | # Compute power spectrum
1486 | spectrum = np.fft.fftshift(np.fft.fft(samples))
1487 | power_db = 10 * np.log10(np.abs(spectrum)**2 + 1e-10)
1488 | max_power = np.max(power_db)
1489 |
1490 | if max_power > threshold:
1491 | # Estimate signal bandwidth
1492 | mask = power_db > threshold
1493 | bandwidth = np.sum(mask) * (sdr.sample_rate / len(power_db))
1494 |
1495 | if bandwidth > MIN_SIGNAL_BANDWIDTH:
1496 | # Classify signal
1497 | signal_type = classify_signal(samples, sdr.sample_rate, bandwidth)
1498 |
1499 | signals.append({
1500 | 'frequency': current_freq,
1501 | 'power': max_power,
1502 | 'bandwidth': bandwidth,
1503 | 'type': signal_type
1504 | })
1505 |
1506 | # Show immediate detection
1507 | status_msg = f"Signal detected at {current_freq/1e6:.3f} MHz ({signal_type})"
1508 | stdscr.addstr(max_height-1, 0, " " * (max_width-1)) # Clear line
1509 | stdscr.addstr(max_height-1, 0, status_msg, curses.color_pair(4))
1510 | stdscr.refresh()
1511 |
1512 | except Exception as e:
1513 | stdscr.addstr(max_height-1, 0, f"Error: {str(e)}", curses.color_pair(3))
1514 | stdscr.refresh()
1515 | time.sleep(0.5)
1516 |
1517 | current_freq += step
1518 | current_step += 1
1519 |
1520 | # Remove duplicates and sort by frequency
1521 | unique_signals = []
1522 | seen_freqs = set()
1523 | for signal in sorted(signals, key=lambda x: x['frequency']):
1524 | rounded_freq = round(signal['frequency'] / 100e3) * 100e3
1525 | if rounded_freq not in seen_freqs:
1526 | seen_freqs.add(rounded_freq)
1527 | unique_signals.append(signal)
1528 |
1529 | return unique_signals
1530 |
1531 | def show_scanner_menu(stdscr):
1532 | """Display scanner configuration menu with band selection"""
1533 | max_height, max_width = stdscr.getmaxyx()
1534 | available_height = max_height - 6 # Reserve space for header and footer
1535 |
1536 | # Calculate total entries and pages
1537 | total_entries = len(BAND_PRESETS)
1538 | entries_per_page = available_height
1539 | total_pages = (total_entries + entries_per_page - 1) // entries_per_page
1540 | current_page = 0
1541 |
1542 | while True:
1543 | stdscr.clear()
1544 |
1545 | # Draw header
1546 | header = "Scanner Configuration - Select Band to Scan"
1547 | stdscr.addstr(0, 2, header, curses.color_pair(1) | curses.A_BOLD)
1548 | stdscr.addstr(1, 2, "-" * len(header), curses.color_pair(2))
1549 |
1550 | # Calculate slice for current page
1551 | start_idx = current_page * entries_per_page
1552 | end_idx = min(start_idx + entries_per_page, total_entries)
1553 |
1554 | # Display current page of presets
1555 | current_items = list(BAND_PRESETS.items())[start_idx:end_idx]
1556 | for i, (key, (start, end, description)) in enumerate(current_items, 1):
1557 | # Calculate absolute index for selection
1558 | abs_index = start_idx + i
1559 | line = f"{abs_index:2d}. {key:<8} : {description:<25} ({start/1e6:.3f}-{end/1e6:.3f} MHz)"
1560 | try:
1561 | stdscr.addstr(i + 2, 2, line, curses.color_pair(2))
1562 | except curses.error:
1563 | pass
1564 |
1565 | # Add custom range option
1566 | custom_option = f"{total_entries + 1}. Custom frequency range"
1567 | try:
1568 | stdscr.addstr(end_idx - start_idx + 3, 2, custom_option, curses.color_pair(4))
1569 | except curses.error:
1570 | pass
1571 |
1572 | # Draw footer with navigation help
1573 | footer = f"Page {current_page + 1}/{total_pages} | [n]ext/[p]rev page | [q]uit | Enter number to select"
1574 | try:
1575 | stdscr.addstr(max_height-3, 2, footer, curses.color_pair(5))
1576 | stdscr.addstr(max_height-2, 2, "Choice: ", curses.color_pair(1) | curses.A_BOLD)
1577 | except curses.error:
1578 | pass
1579 |
1580 | # Handle input
1581 | curses.echo()
1582 | curses.curs_set(1)
1583 | stdscr.nodelay(False)
1584 |
1585 | try:
1586 | choice = stdscr.getstr().decode('utf-8').lower()
1587 |
1588 | if choice == 'q':
1589 | return None, None, None
1590 | elif choice == 'n' and current_page < total_pages - 1:
1591 | current_page += 1
1592 | continue
1593 | elif choice == 'p' and current_page > 0:
1594 | current_page -= 1
1595 | continue
1596 |
1597 | try:
1598 | choice_num = int(choice)
1599 | if 1 <= choice_num <= total_entries:
1600 | # Get selected band
1601 | band_key = list(BAND_PRESETS.keys())[choice_num - 1]
1602 | start, end, _ = BAND_PRESETS[band_key]
1603 |
1604 | # Get threshold
1605 | stdscr.clear()
1606 | stdscr.addstr(0, 2, "Enter signal strength threshold \n(dB, recommended -40 to -20): ",
1607 | curses.color_pair(2))
1608 | threshold = float(stdscr.getstr().decode('utf-8'))
1609 |
1610 | return start, end, threshold
1611 |
1612 | elif choice_num == total_entries + 1:
1613 | # Handle custom range
1614 | stdscr.clear()
1615 | stdscr.addstr(0, 2, "Enter start frequency (MHz): ", curses.color_pair(2))
1616 | start = float(stdscr.getstr().decode('utf-8')) * 1e6
1617 | stdscr.addstr(1, 2, "Enter end frequency (MHz): ", curses.color_pair(2))
1618 | end = float(stdscr.getstr().decode('utf-8')) * 1e6
1619 | stdscr.addstr(2, 2, "Enter signal strength threshold \n(dB, recommended -40 to -20): ",
1620 | curses.color_pair(2))
1621 | threshold = float(stdscr.getstr().decode('utf-8'))
1622 |
1623 | return start, end, threshold
1624 |
1625 | except ValueError:
1626 | pass
1627 |
1628 | except curses.error:
1629 | pass
1630 | finally:
1631 | stdscr.nodelay(True)
1632 | curses.noecho()
1633 | curses.curs_set(0)
1634 |
1635 | return None, None, None
1636 |
1637 | def display_scan_results(stdscr, signals, threshold):
1638 | """Display scanner results with pagination and allow selection"""
1639 | # Ensure we're in the right mode for user input
1640 | stdscr.nodelay(False) # Make sure we wait for input
1641 | curses.echo() # Show user input
1642 | curses.curs_set(1) # Show cursor
1643 |
1644 | try:
1645 | if not signals:
1646 | stdscr.addstr(0, 0, "\nNo signals found above threshold.\n", curses.color_pair(3))
1647 | stdscr.addstr(2, 0, "\nPress any key to continue...", curses.color_pair(2))
1648 | stdscr.getch() # Wait for keypress
1649 | return None
1650 |
1651 | max_height, max_width = stdscr.getmaxyx()
1652 | results_per_page = max_height - 7 # Reserve space for header and footer
1653 | total_pages = (len(signals) + results_per_page - 1) // results_per_page
1654 | current_page = 0
1655 |
1656 | while True:
1657 | stdscr.clear()
1658 |
1659 | # Draw header
1660 | header = f"Detected Signals ({len(signals)} found) - Page {current_page + 1}/{total_pages}"
1661 | stdscr.addstr(0, 0, header, curses.color_pair(1) | curses.A_BOLD)
1662 | stdscr.addstr(1, 0, "-" * len(header), curses.color_pair(2))
1663 |
1664 | # Calculate slice for current page
1665 | start_idx = current_page * results_per_page
1666 | end_idx = min(start_idx + results_per_page, len(signals))
1667 |
1668 | # Display signals for current page
1669 | current_line = 2
1670 | for i, signal in enumerate(signals[start_idx:end_idx], start_idx + 1):
1671 | power_str = f"{signal['power']:.1f}".rjust(6)
1672 | freq_str = f"{signal['frequency']/1e6:.3f}".rjust(8)
1673 | bw_str = f"{signal['bandwidth']/1e3:.1f}".rjust(6)
1674 | type_str = signal['type'].ljust(15)
1675 |
1676 | line = f"{str(i).rjust(3)}. {freq_str} MHz Power: {power_str} dB BW: {bw_str} kHz Type: {type_str}"
1677 |
1678 | # Color code by signal type
1679 | if signal['type'] == 'FM_BROADCAST':
1680 | color = curses.color_pair(4) # Green
1681 | elif signal['type'] == 'DIGITAL':
1682 | color = curses.color_pair(5) # Cyan
1683 | elif signal['type'] == 'UNKNOWN':
1684 | color = curses.color_pair(2) # White
1685 | else:
1686 | color = curses.color_pair(1) # Yellow
1687 |
1688 | stdscr.addstr(current_line, 0, line[:max_width-1], color)
1689 | current_line += 1
1690 |
1691 | # Draw navigation footer
1692 | footer = "Navigation: [n]ext page, [p]revious page, [number] to select, [q]uit"
1693 | stdscr.addstr(max_height-1, 0, footer, curses.color_pair(2))
1694 | stdscr.addstr(max_height-2, 0, "Enter choice: ", curses.color_pair(1) | curses.A_BOLD)
1695 |
1696 | stdscr.refresh()
1697 |
1698 | # Get user input
1699 | try:
1700 | choice = stdscr.getstr().decode('utf-8').lower()
1701 |
1702 | if choice == 'q':
1703 | break
1704 | elif choice == 'n' and current_page < total_pages - 1:
1705 | current_page += 1
1706 | elif choice == 'p' and current_page > 0:
1707 | current_page -= 1
1708 | else:
1709 | try:
1710 | choice_num = int(choice)
1711 | if 1 <= choice_num <= len(signals):
1712 | return signals[choice_num-1]['frequency']
1713 | except ValueError:
1714 | pass
1715 | except curses.error:
1716 | pass
1717 |
1718 | except Exception as e:
1719 | # Debug output for unexpected errors
1720 | stdscr.addstr(max_height-1, 0, f"Display error ({type(e).__name__}): {str(e)}",
1721 | curses.color_pair(3))
1722 | stdscr.refresh()
1723 | stdscr.getch() # Wait for key press to see error
1724 |
1725 | finally:
1726 | # Restore original terminal settings
1727 | stdscr.nodelay(True)
1728 | curses.noecho()
1729 | curses.curs_set(0)
1730 | stdscr.clear()
1731 |
1732 | return None
1733 |
1734 | def draw_scanning_status(stdscr, current_freq, start_freq, end_freq, sdr):
1735 | """Draw scanning progress at the top of the screen"""
1736 | try:
1737 | max_height, max_width = stdscr.getmaxyx()
1738 |
1739 | # Calculate progress percentage
1740 | total_range = end_freq - start_freq
1741 | if total_range > 0: # Prevent division by zero
1742 | progress = (current_freq - start_freq) / total_range
1743 | else:
1744 | progress = 0
1745 |
1746 | # Calculate progress bar width (70% of screen width)
1747 | bar_width = int(max_width * 0.7)
1748 | filled = int(bar_width * progress)
1749 |
1750 | # Clear the status lines
1751 | stdscr.addstr(0, 0, " " * max_width)
1752 | stdscr.addstr(1, 0, " " * max_width)
1753 |
1754 | # Create the status text
1755 | status_text = f"Scanning: {current_freq/1e6:8.3f} MHz "
1756 | progress_bar = "[" + "=" * filled + " " * (bar_width - filled) + "]"
1757 | percentage = f" {progress * 100:3.0f}%"
1758 |
1759 | # Calculate starting position to center the display
1760 | total_length = len(status_text) + len(progress_bar) + len(percentage)
1761 | start_pos = max(0, (max_width - total_length) // 2)
1762 |
1763 | # Draw the components with colors
1764 | stdscr.addstr(0, start_pos, status_text, curses.color_pair(1) | curses.A_BOLD)
1765 | stdscr.addstr(1, start_pos, progress_bar, curses.color_pair(2))
1766 | stdscr.addstr(1, start_pos + len(progress_bar), percentage, curses.color_pair(4))
1767 |
1768 | # Force screen update
1769 | stdscr.refresh()
1770 |
1771 | except curses.error:
1772 | pass # Ignore curses errors
1773 |
1774 | def draw_waterfall(stdscr, freq_data, frequencies, center_freq, bandwidth, gain, step,
1775 | sdr, is_recording=False, recording_duration=None):
1776 | """Draw the waterfall display using ASCII characters"""
1777 | global WATERFALL_HISTORY
1778 | max_height, max_width = stdscr.getmaxyx()
1779 | display_width = max_width - 8
1780 | display_height = max_height - 4
1781 |
1782 | # Add current data to history
1783 | WATERFALL_HISTORY.append(freq_data)
1784 | if len(WATERFALL_HISTORY) > WATERFALL_MAX_LINES:
1785 | WATERFALL_HISTORY.pop(0)
1786 |
1787 | # Normalize all data for consistent coloring
1788 | all_data = np.array(WATERFALL_HISTORY)
1789 | min_val = np.min(all_data[np.isfinite(all_data)])
1790 | max_val = np.max(all_data[np.isfinite(all_data)])
1791 |
1792 | # Draw dB scale on the left
1793 | for i in range(display_height):
1794 | db_value = max_val - (i * (max_val - min_val) / display_height)
1795 | if i % 3 == 0: # Show scale every 3 lines
1796 | db_label = f"{db_value:4.0f}dB"
1797 | try:
1798 | stdscr.addstr(i + 2, 0, db_label, curses.color_pair(2))
1799 | # Add scale markers
1800 | stdscr.addstr(i + 2, 8, "|", curses.color_pair(2))
1801 | except curses.error:
1802 | pass
1803 |
1804 | # Draw each line of the waterfall
1805 | for y, line_data in enumerate(reversed(WATERFALL_HISTORY)):
1806 | if y >= display_height:
1807 | break
1808 |
1809 | # Resample data to fit screen width
1810 | resampled = np.interp(
1811 | np.linspace(0, len(line_data) - 1, display_width),
1812 | np.arange(len(line_data)),
1813 | line_data
1814 | )
1815 |
1816 | # Draw each point in the line using ASCII characters
1817 | for x, value in enumerate(resampled):
1818 | if np.isfinite(value):
1819 | # Normalize value and select ASCII character and color
1820 | norm_value = (value - min_val) / (max_val - min_val)
1821 | color_index = int(norm_value * 5) # 0-5 for the 6 color pairs
1822 |
1823 | if norm_value > 0.75:
1824 | char = "#"
1825 | elif norm_value > 0.5:
1826 | char = "="
1827 | elif norm_value > 0.25:
1828 | char = "-"
1829 | else:
1830 | char = "."
1831 |
1832 | try:
1833 | stdscr.addstr(y + 3, x + 9, char, curses.color_pair(10 + color_index))
1834 | except curses.error:
1835 | pass
1836 |
1837 | # Use standardized frequency labels
1838 | draw_frequency_labels(stdscr, center_freq, bandwidth, display_height, display_width)
1839 |
1840 | def draw_frequency_labels(stdscr, center_freq, bandwidth, display_height, display_width, x_offset=9):
1841 | """Standardized function to draw frequency labels and axis using ASCII only"""
1842 | try:
1843 | # Draw horizontal axis background to reflect center frequency
1844 | half_bw = bandwidth / 2
1845 | start_freq = center_freq - half_bw
1846 | end_freq = center_freq + half_bw
1847 |
1848 | # Calculate center marker width proportional to bandwidth
1849 | # For example: 2MHz -> 4 chars, 1MHz -> 2 chars, 0.5MHz -> 1 char
1850 | center_marker_width = max(1, int(bandwidth / 250000)) # 1 char per 500kHz
1851 | center_x = display_width // 2 # Center position in display units
1852 |
1853 | # Draw the axis background with different characters for different frequency ranges
1854 | axis_line = ""
1855 | for x in range(display_width):
1856 | # Use different characters based on position relative to center
1857 | if abs(x - center_x) < center_marker_width: # Center marker
1858 | axis_line += "="
1859 | else:
1860 | axis_line += "-" # Same character for both sides
1861 |
1862 | # Draw the axis with background
1863 | stdscr.addstr(display_height + 2, x_offset, axis_line, curses.color_pair(2))
1864 |
1865 | # Calculate frequency steps and format labels
1866 | freq_step = bandwidth / 5
1867 |
1868 | # Draw frequency labels and tick marks
1869 | for i in range(6):
1870 | freq = start_freq + (i * freq_step)
1871 | label = f"{freq/1e6:.2f}MHz"
1872 | pos = int(x_offset + (i * (display_width-1)/5))
1873 |
1874 | try:
1875 | # Draw tick mark
1876 | stdscr.addstr(display_height + 2, pos, "|", curses.color_pair(2))
1877 |
1878 | # Center the label under the tick mark
1879 | label_pos = max(pos - len(label)//2, x_offset)
1880 | stdscr.addstr(display_height + 3, label_pos, label, curses.color_pair(2))
1881 | except curses.error:
1882 | pass
1883 |
1884 | # Add band name indicator if frequency is in a known band
1885 | current_band = None
1886 | # Add small tolerance for floating point comparison (1 kHz)
1887 | tolerance = 1e3
1888 | for band, (start, end, description) in BAND_PRESETS.items():
1889 | if (start - tolerance) <= center_freq <= (end + tolerance):
1890 | current_band = band
1891 | break
1892 |
1893 | if current_band:
1894 | try:
1895 | band_text = f"[{current_band}]"
1896 | # Position the band name at the start of the axis
1897 | stdscr.addstr(display_height + 2, x_offset - len(band_text) - 1,
1898 | band_text, curses.color_pair(4) | curses.A_BOLD)
1899 |
1900 | # Debug output (optional)
1901 | #debug_text = f"F:{center_freq/1e6:.3f}MHz B:{start/1e6:.3f}-{end/1e6:.3f}MHz"
1902 | #stdscr.addstr(0, 0, debug_text, curses.color_pair(2))
1903 | except curses.error:
1904 | pass
1905 |
1906 | except curses.error:
1907 | pass
1908 |
1909 | def show_demod_menu(stdscr):
1910 | """Display demodulation mode selection menu"""
1911 | stdscr.clear()
1912 | stdscr.addstr("Select Demodulation Mode:\n\n", curses.color_pair(1) | curses.A_BOLD)
1913 |
1914 | for i, (mode, info) in enumerate(DEMOD_MODES.items(), 1):
1915 | line = f"{i}. {info['name']}: {info['description']}"
1916 | if mode == CURRENT_DEMOD:
1917 | line += " (Current)"
1918 | stdscr.addstr(line + "\n", curses.color_pair(4) | curses.A_BOLD)
1919 | else:
1920 | stdscr.addstr(line + "\n", curses.color_pair(2))
1921 |
1922 | stdscr.addstr("\nEnter choice (or any other key to cancel): ",
1923 | curses.color_pair(1) | curses.A_BOLD)
1924 |
1925 | curses.echo()
1926 | curses.curs_set(1)
1927 | stdscr.nodelay(False)
1928 |
1929 | try:
1930 | choice = int(stdscr.getstr().decode('utf-8'))
1931 | if 1 <= choice <= len(DEMOD_MODES):
1932 | return list(DEMOD_MODES.keys())[choice-1]
1933 | except (ValueError, IndexError):
1934 | pass
1935 | finally:
1936 | stdscr.nodelay(True)
1937 | curses.noecho()
1938 | curses.curs_set(0)
1939 |
1940 | return None
1941 |
1942 | def classify_signal(samples, sample_rate, bandwidth):
1943 | """Classify signal type based on spectral characteristics"""
1944 | # Calculate power spectral density
1945 | freqs, psd = welch(samples, fs=sample_rate, nperseg=1024)
1946 |
1947 | # Calculate basic signal characteristics
1948 | signal_bw = estimate_bandwidth(psd, freqs)
1949 | modulation_index = estimate_modulation_index(samples)
1950 | spectral_flatness = np.exp(np.mean(np.log(psd + 1e-10))) / np.mean(psd)
1951 |
1952 | # Classification logic
1953 | if signal_bw > 150e3:
1954 | if modulation_index > 0.8:
1955 | return 'FM_BROADCAST'
1956 | elif 8e3 <= signal_bw <= 16e3:
1957 | if modulation_index < 0.3:
1958 | return 'NARROW_FM'
1959 | elif 8e3 <= signal_bw <= 10e3:
1960 | if modulation_index < 0.2 and spectral_flatness < 0.3:
1961 | return 'AM_BROADCAST'
1962 | elif 2e3 <= signal_bw <= 3e3:
1963 | if spectral_flatness < 0.2:
1964 | return 'SSB'
1965 | elif spectral_flatness > 0.7:
1966 | return 'DIGITAL'
1967 |
1968 | return 'UNKNOWN'
1969 |
1970 | def estimate_bandwidth(psd, freqs, threshold_db=-20):
1971 | """Estimate signal bandwidth using power spectral density"""
1972 | # Convert to dB
1973 | psd_db = 10 * np.log10(psd + 1e-10)
1974 | max_power = np.max(psd_db)
1975 |
1976 | # Find frequencies above threshold
1977 | mask = psd_db > (max_power + threshold_db)
1978 | if not np.any(mask):
1979 | return 0
1980 |
1981 | # Calculate bandwidth
1982 | freq_range = freqs[mask]
1983 | return freq_range[-1] - freq_range[0]
1984 |
1985 | def estimate_modulation_index(samples):
1986 | """Estimate modulation index using amplitude variation"""
1987 | # Use magnitude of complex samples instead of Hilbert transform
1988 | amplitude_env = np.abs(samples)
1989 | phase_env = np.unwrap(np.angle(samples))
1990 |
1991 | # Calculate variance ratios
1992 | amp_var = np.var(amplitude_env)
1993 | phase_var = np.var(np.diff(phase_env))
1994 |
1995 | return phase_var / (amp_var + 1e-10)
1996 |
1997 | def draw_persistence(stdscr, freq_data, frequencies, center_freq, bandwidth, gain, step,
1998 | sdr, is_recording=False, recording_duration=None):
1999 | """Draw spectrum with persistence effect"""
2000 | global PERSISTENCE_HISTORY
2001 | max_height, max_width = stdscr.getmaxyx()
2002 | display_width = max_width - 8 # Reserve space for dB scale
2003 | display_height = max_height - 4
2004 |
2005 | # Add current data to history
2006 | PERSISTENCE_HISTORY.append(freq_data)
2007 | if len(PERSISTENCE_HISTORY) > PERSISTENCE_LENGTH:
2008 | PERSISTENCE_HISTORY.pop(0)
2009 |
2010 | # Draw dB scale on the left
2011 | min_val = np.min(freq_data[np.isfinite(freq_data)])
2012 | max_val = np.max(freq_data[np.isfinite(freq_data)])
2013 | db_range = max_val - min_val
2014 | for i in range(max_height - 3):
2015 | db_value = max_val - (i * db_range / (max_height - 3))
2016 | if i % 3 == 0: # Show scale every 3 lines
2017 | db_label = f"{db_value:4.0f}dB"
2018 | try:
2019 | stdscr.addstr(i + 2, 0, db_label, curses.color_pair(2))
2020 | except curses.error:
2021 | pass
2022 |
2023 | # Draw each trace with ASCII characters
2024 | for i, historical_data in enumerate(PERSISTENCE_HISTORY):
2025 | alpha = PERSISTENCE_ALPHA ** (PERSISTENCE_LENGTH - i)
2026 | color_pair = int(1 + (5 * (1 - alpha)))
2027 |
2028 | for x in range(display_width):
2029 | try:
2030 | y = int(max_height - 2 - (historical_data[x] / 100 * (max_height - 3)))
2031 | if 2 <= y < max_height - 1:
2032 | stdscr.addstr(y, x + 8, '*', curses.color_pair(color_pair))
2033 | except curses.error:
2034 | pass
2035 |
2036 | # Use standardized frequency labels
2037 | draw_frequency_labels(stdscr, center_freq, bandwidth, display_height, display_width)
2038 |
2039 | def draw_surface_plot(stdscr, freq_data, frequencies, center_freq, bandwidth, gain, step,
2040 | sdr, is_recording=False, recording_duration=None):
2041 | """Draw spectrum as pseudo-3D surface with frequency labels"""
2042 | max_height, max_width = stdscr.getmaxyx()
2043 | display_width = max_width - 8
2044 | display_height = max_height - 4
2045 |
2046 | # Calculate frequency range
2047 | half_bw = bandwidth / 2
2048 | start_freq = center_freq - half_bw
2049 | end_freq = center_freq + half_bw
2050 |
2051 | # Draw surface with ASCII characters
2052 | angle_rad = np.radians(SURFACE_ANGLE)
2053 | for x in range(max_width - 10): # Reserve space for labels
2054 | magnitude = freq_data[x]
2055 | for y in range(int(magnitude)):
2056 | screen_x = int(x - y * np.cos(angle_rad)) + 8 # Offset for labels
2057 | screen_y = int(max_height - 2 - y * np.sin(angle_rad))
2058 |
2059 | if 0 <= screen_x < max_width and 2 <= screen_y < max_height - 1:
2060 | try:
2061 | stdscr.addstr(screen_y, screen_x, '#',
2062 | curses.color_pair(1 + (y % 5)))
2063 | except curses.error:
2064 | pass
2065 |
2066 | # Use standardized frequency labels
2067 | draw_frequency_labels(stdscr, center_freq, bandwidth, display_height, display_width)
2068 |
2069 | # Draw amplitude scale on the left
2070 | min_val = np.min(freq_data[np.isfinite(freq_data)])
2071 | max_val = np.max(freq_data[np.isfinite(freq_data)])
2072 | db_range = max_val - min_val
2073 | for i in range(max_height - 3):
2074 | db_value = max_val - (i * db_range / (max_height - 3))
2075 | if i % 3 == 0: # Show scale every 3 lines
2076 | db_label = f"{db_value:4.0f}dB"
2077 | try:
2078 | stdscr.addstr(i + 2, 0, db_label, curses.color_pair(2))
2079 | except curses.error:
2080 | pass
2081 |
2082 | def interpolate_color(color1, color2, factor):
2083 | """Interpolate between two RGB colors"""
2084 | return tuple(int(color1[i] + (color2[i] - color1[i]) * factor) for i in range(3))
2085 |
2086 | def get_gradient_color(value):
2087 | """Get smooth color from gradient for given value between 0 and 1"""
2088 | if value <= 0:
2089 | return GRADIENT_COLORS[0]
2090 | if value >= 1:
2091 | return GRADIENT_COLORS[-1]
2092 |
2093 | segment_size = 1.0 / (len(GRADIENT_COLORS) - 1)
2094 | segment = int(value / segment_size)
2095 | factor = (value - segment * segment_size) / segment_size
2096 |
2097 | return interpolate_color(GRADIENT_COLORS[segment],
2098 | GRADIENT_COLORS[segment + 1],
2099 | factor)
2100 |
2101 | def draw_gradient_waterfall(stdscr, freq_data, frequencies, center_freq, bandwidth, gain, step,
2102 | sdr, is_recording=False, recording_duration=None):
2103 | """Draw waterfall with ASCII characters for better compatibility"""
2104 | global WATERFALL_HISTORY
2105 | max_height, max_width = stdscr.getmaxyx()
2106 | display_width = max_width - 10
2107 | display_height = max_height - 4
2108 |
2109 | # Add current data to history
2110 | WATERFALL_HISTORY.append(freq_data)
2111 | if len(WATERFALL_HISTORY) > WATERFALL_MAX_LINES:
2112 | WATERFALL_HISTORY.pop(0)
2113 |
2114 | # Normalize data
2115 | all_data = np.array(WATERFALL_HISTORY)
2116 | min_val = np.min(all_data[np.isfinite(all_data)])
2117 | max_val = np.max(all_data[np.isfinite(all_data)])
2118 |
2119 | # Draw dB scale on the left
2120 | for i in range(display_height):
2121 | db_value = max_val - (i * (max_val - min_val) / display_height)
2122 | if i % 3 == 0: # Show scale every 3 lines
2123 | db_label = f"{db_value:4.0f}dB"
2124 | try:
2125 | stdscr.addstr(i + 2, 0, db_label, curses.color_pair(2))
2126 | # Add scale markers
2127 | stdscr.addstr(i + 2, 8, "|", curses.color_pair(2))
2128 | except curses.error:
2129 | pass
2130 |
2131 | # Define ASCII intensity characters (from darkest to brightest)
2132 | intensity_chars = ' ._-=+*#@' # 9 levels of intensity
2133 |
2134 | # Draw each line with ASCII characters
2135 | for y, line_data in enumerate(reversed(WATERFALL_HISTORY)):
2136 | if y >= display_height:
2137 | break
2138 |
2139 | # Resample data to fit display width
2140 | resampled = np.interp(
2141 | np.linspace(0, len(line_data) - 1, display_width),
2142 | np.arange(len(line_data)), line_data)
2143 |
2144 | for x, value in enumerate(resampled):
2145 | if np.isfinite(value):
2146 | # Normalize value between 0 and 1
2147 | normalized = (value - min_val) / (max_val - min_val)
2148 |
2149 | # Convert normalized value to character index
2150 | char_index = int(normalized * (len(intensity_chars) - 1))
2151 | char = intensity_chars[char_index]
2152 |
2153 | # Select color based on intensity
2154 | color_index = int(normalized * 5) # 6 color pairs (0-5)
2155 |
2156 | try:
2157 | stdscr.addstr(y + 2, x + 9, char,
2158 | curses.color_pair(10 + color_index))
2159 | except curses.error:
2160 | pass
2161 |
2162 | # Draw intensity scale on the right
2163 | for i in range(display_height):
2164 | normalized = 1 - (i / display_height)
2165 | char_index = int(normalized * (len(intensity_chars) - 1))
2166 | try:
2167 | stdscr.addstr(i + 2, max_width - 2,
2168 | intensity_chars[char_index] * 2,
2169 | curses.color_pair(10 + int(normalized * 5)))
2170 | except curses.error:
2171 | pass
2172 |
2173 | # Use standardized frequency labels
2174 | draw_frequency_labels(stdscr, center_freq, bandwidth, display_height, display_width)
2175 |
2176 | def draw_vector_display(stdscr, samples, center_freq, bandwidth, gain, step, sdr,
2177 | is_recording=False, recording_duration=None):
2178 | """Draw I/Q samples as vector constellation"""
2179 | max_height, max_width = stdscr.getmaxyx()
2180 | display_width = max_width - 8
2181 | display_height = max_height - 4
2182 |
2183 | # Create coordinate system
2184 | center_x = max_width // 2
2185 | center_y = max_height // 2
2186 | scale = min(max_width, max_height) // 4
2187 |
2188 | # Draw axes with ASCII characters
2189 | for i in range(max_width):
2190 | try:
2191 | stdscr.addstr(center_y, i, '-')
2192 | except curses.error:
2193 | pass
2194 | for i in range(max_height):
2195 | try:
2196 | stdscr.addstr(i, center_x, '|')
2197 | except curses.error:
2198 | pass
2199 |
2200 | # Plot I/Q samples with ASCII dot
2201 | for i, q in zip(np.real(samples), np.imag(samples)):
2202 | x = int(center_x + i * scale)
2203 | y = int(center_y - q * scale)
2204 |
2205 | if 0 <= x < max_width and 0 <= y < max_height:
2206 | try:
2207 | stdscr.addstr(y, x, '.', curses.color_pair(1))
2208 | except curses.error:
2209 | pass
2210 |
2211 | # Use standardized frequency labels
2212 | draw_frequency_labels(stdscr, center_freq, bandwidth, display_height, display_width)
2213 |
2214 | # Add new class to handle different SDR backends
2215 | class SDRDevice:
2216 | def __init__(self, backend='SOAPY', stdscr=None):
2217 | self.backend = backend
2218 | self.device = None
2219 | self.sample_rate = 2.048e6
2220 | self.center_freq = 100e6
2221 | self.gain = 20
2222 | self.bandwidth = 2e6
2223 | self.ppm = DEFAULT_PPM
2224 | self.stdscr = stdscr
2225 | self._valid_gains = None
2226 |
2227 | def enumerate_devices(self):
2228 | """List all available SDR devices"""
2229 | try:
2230 | devices = SoapySDR.Device.enumerate()
2231 | formatted_devices = []
2232 |
2233 | for i, device in enumerate(devices, 1):
2234 | # Extract relevant device information using SoapySDRKwargs methods
2235 | driver = device['driver'] if 'driver' in device else 'Unknown'
2236 | label = device['label'] if 'label' in device else ''
2237 | serial = device['serial'] if 'serial' in device else ''
2238 |
2239 | # Create formatted device string
2240 | device_str = f"{driver}"
2241 | if label:
2242 | device_str += f" ({label})"
2243 | if serial:
2244 | device_str += f" [SN: {serial}]"
2245 |
2246 | formatted_devices.append((i, device_str, device))
2247 |
2248 | return formatted_devices
2249 |
2250 | except Exception as e:
2251 | raise RuntimeError(f"Error enumerating devices: {e}")
2252 |
2253 | def select_device(self):
2254 | """Display device selection menu and return chosen device args"""
2255 | try:
2256 | devices = self.enumerate_devices()
2257 | if not devices:
2258 | raise RuntimeError("No SDR devices found")
2259 |
2260 | if len(devices) == 1:
2261 | # If only one device, use it automatically
2262 | self.stdscr.addstr(0, 0, "Found single SDR device, using it automatically...",
2263 | curses.color_pair(4))
2264 | self.stdscr.refresh()
2265 | time.sleep(1)
2266 | return devices[0][2]
2267 |
2268 | # Display device selection menu
2269 | self.stdscr.clear()
2270 | self.stdscr.addstr(0, 0, "Available SDR Devices:", curses.color_pair(1) | curses.A_BOLD)
2271 | self.stdscr.addstr(1, 0, "-" * 50, curses.color_pair(2))
2272 |
2273 | for idx, name, _ in devices:
2274 | self.stdscr.addstr(idx + 1, 0, f"{idx}. {name}", curses.color_pair(2))
2275 |
2276 | self.stdscr.addstr(len(devices) + 3, 0, "Select device (1-{}): ".format(len(devices)), curses.color_pair(1) | curses.A_BOLD)
2277 |
2278 | # Get user input
2279 | curses.echo()
2280 | curses.curs_set(1)
2281 | self.stdscr.nodelay(False)
2282 |
2283 | while True:
2284 | try:
2285 | choice = int(self.stdscr.getstr().decode('utf-8'))
2286 | if 1 <= choice <= len(devices):
2287 | return devices[choice-1][2]
2288 | else:
2289 | raise ValueError
2290 | except ValueError:
2291 | self.stdscr.addstr(len(devices) + 4, 0, "Invalid choice. Try again: ",
2292 | curses.color_pair(3))
2293 | self.stdscr.refresh()
2294 |
2295 | finally:
2296 | curses.noecho()
2297 | curses.curs_set(0)
2298 | self.stdscr.nodelay(True)
2299 | self.stdscr.clear()
2300 |
2301 | def init_device(self):
2302 | """Initialize SoapySDR device with device selection"""
2303 | try:
2304 | # Get device arguments from selection menu
2305 | args = self.select_device()
2306 |
2307 | # Create device instance with selected device
2308 | self.device = SoapySDR.Device(args)
2309 |
2310 | # Set initial parameters BEFORE creating the stream
2311 | self.set_sample_rate(self.sample_rate)
2312 | self.set_center_freq(self.center_freq)
2313 | self.set_gain(self.gain)
2314 | self.set_bandwidth(self.bandwidth)
2315 |
2316 | # Initialize gain range
2317 | self._valid_gains = self._get_valid_gains()
2318 |
2319 | # Setup RX stream AFTER setting parameters
2320 | self.stream = self.device.setupStream(SOAPY_SDR_RX, SOAPY_SDR_CF32)
2321 | self.device.activateStream(self.stream)
2322 |
2323 | except Exception as e:
2324 | raise RuntimeError(f"Error initializing SoapySDR device: {e}")
2325 |
2326 | def _get_valid_gains(self):
2327 | """Get list of valid gain values"""
2328 | try:
2329 | gain_range = self.device.getGainRange(SOAPY_SDR_RX, 0)
2330 | step = gain_range.step() if gain_range.step() > 0 else 1
2331 | return np.arange(gain_range.minimum(), gain_range.maximum() + step, step)
2332 | except Exception:
2333 | return np.arange(0, 50, 1) # Fallback range
2334 |
2335 | def read_samples(self, num_samples):
2336 | """Read samples from the SDR device"""
2337 | buff = np.array([0]*num_samples, np.complex64)
2338 | ret = self.device.readStream(self.stream, [buff], len(buff))
2339 | if ret.ret < 0:
2340 | raise RuntimeError(f"Stream error: {ret.ret}")
2341 | return buff
2342 |
2343 | def close(self):
2344 | if self.device:
2345 | self.device.deactivateStream(self.stream)
2346 | self.device.closeStream(self.stream)
2347 | self.device = None
2348 |
2349 | @property
2350 | def valid_gains_db(self):
2351 | return self._valid_gains
2352 |
2353 | def set_gain(self, gain):
2354 | """Set the gain value"""
2355 | if gain == 'auto':
2356 | self.device.setGainMode(SOAPY_SDR_RX, 0, True)
2357 | else:
2358 | self.device.setGainMode(SOAPY_SDR_RX, 0, False)
2359 | self.device.setGain(SOAPY_SDR_RX, 0, float(gain))
2360 | self.gain = gain
2361 |
2362 | def set_center_freq(self, freq):
2363 | self.device.setFrequency(SOAPY_SDR_RX, 0, float(freq))
2364 | self.center_freq = freq
2365 |
2366 | def set_sample_rate(self, rate):
2367 | self.device.setSampleRate(SOAPY_SDR_RX, 0, float(rate))
2368 | self.sample_rate = rate
2369 |
2370 | def set_bandwidth(self, bw):
2371 | self.device.setBandwidth(SOAPY_SDR_RX, 0, float(bw))
2372 | self.bandwidth = bw
2373 |
2374 | def set_ppm(self, ppm):
2375 | """Set frequency correction if supported"""
2376 | try:
2377 | if 'freqCorrection' in self.device.getSettingInfo():
2378 | self.device.writeSetting('freqCorrection', str(ppm))
2379 | self.ppm = ppm
2380 | return True
2381 | except Exception as e:
2382 | if self.stdscr:
2383 | self.stdscr.addstr(0, 0, f"PPM correction not supported: {str(e)}",
2384 | curses.color_pair(3) | curses.A_BOLD)
2385 | self.stdscr.refresh()
2386 | time.sleep(1)
2387 | return False
2388 |
2389 | def show_rtl_commands(stdscr, sdr):
2390 | """Display RTL commands from JSON file with pagination"""
2391 | try:
2392 | # Try to load the JSON file
2393 | with open('rtlcoms.json', 'r') as f:
2394 | commands = json.load(f)
2395 | except (FileNotFoundError, json.JSONDecodeError):
2396 | show_popup_msg(stdscr, "rtlcoms.json not found or invalid!", error=True)
2397 | return
2398 |
2399 | max_height, max_width = stdscr.getmaxyx()
2400 | available_height = max_height - 6 # Reserve space for header and footer
2401 |
2402 | # Calculate total entries and pages, accounting for 2 lines per entry
2403 | entries_per_page = available_height // 2 # Divide by 2 since each entry takes 2 lines
2404 | total_entries = len(commands)
2405 | total_pages = (total_entries + entries_per_page - 1) // entries_per_page
2406 | current_page = 0
2407 |
2408 | while True:
2409 | stdscr.clear()
2410 |
2411 | # Draw header
2412 | header = "Available RTL Commands"
2413 | stdscr.addstr(0, 2, header, curses.color_pair(1) | curses.A_BOLD)
2414 | stdscr.addstr(1, 2, "-" * len(header), curses.color_pair(2))
2415 |
2416 | # Calculate slice for current page
2417 | start_idx = current_page * entries_per_page
2418 | end_idx = min(start_idx + entries_per_page, total_entries)
2419 |
2420 | # Display current page of commands
2421 | current_items = list(commands.items())[start_idx:end_idx]
2422 | for i, (name, command) in enumerate(current_items, 1):
2423 | # Calculate absolute index for selection
2424 | abs_index = start_idx + i
2425 |
2426 | # Format the command with actual values
2427 | try:
2428 | formatted_command = command.format(
2429 | freq=f"{sdr.center_freq/1e6:.3f}",
2430 | sample_rate=f"{sdr.sample_rate/1e6:.3f}",
2431 | gain=sdr.gain if isinstance(sdr.gain, str) else f"{sdr.gain:.1f}",
2432 | ppm=sdr.ppm
2433 | )
2434 | except Exception:
2435 | formatted_command = command # Use raw command if formatting fails
2436 |
2437 | # Calculate display position
2438 | display_line = (i - 1) * 2 + 3 # Start at line 3, increment by 2 for each entry
2439 |
2440 | try:
2441 | # Display name in bold white
2442 | name_line = f"{abs_index:2d}. {name}"
2443 | stdscr.addstr(display_line, 2, name_line, curses.color_pair(1) | curses.A_BOLD)
2444 |
2445 | # Display command in cyan on next line
2446 | cmd_line = f" {formatted_command}"
2447 | stdscr.addstr(display_line + 1, 2, cmd_line, curses.color_pair(5))
2448 | except curses.error:
2449 | pass
2450 |
2451 | # Draw footer with navigation help
2452 | footer = f"Page {current_page + 1}/{total_pages} | [n]ext/[p]rev page | [q]uit | Enter number to select"
2453 | try:
2454 | stdscr.addstr(max_height-2, 2, footer, curses.color_pair(5))
2455 | stdscr.addstr(max_height-1, 2, "Choice: ", curses.color_pair(1) | curses.A_BOLD)
2456 | except curses.error:
2457 | pass
2458 |
2459 | # Handle input
2460 | curses.echo()
2461 | curses.curs_set(1)
2462 | stdscr.nodelay(False)
2463 |
2464 | try:
2465 | choice = stdscr.getstr().decode('utf-8').lower()
2466 |
2467 | if choice == 'q':
2468 | break
2469 | elif choice == 'n' and current_page < total_pages - 1:
2470 | current_page += 1
2471 | continue
2472 | elif choice == 'p' and current_page > 0:
2473 | current_page -= 1
2474 | continue
2475 |
2476 | try:
2477 | choice_num = int(choice)
2478 | if 1 <= choice_num <= total_entries:
2479 | # Get selected command
2480 | command = list(commands.values())[choice_num - 1]
2481 | # Format command with current values
2482 | formatted_command = command.format(
2483 | freq=f"{sdr.center_freq/1e6:.3f}",
2484 | sample_rate=f"{sdr.sample_rate/1e6:.3f}",
2485 | gain=sdr.gain if isinstance(sdr.gain, str) else f"{sdr.gain:.1f}",
2486 | ppm=sdr.ppm
2487 | )
2488 | # Store command for display at exit
2489 | global RTL_COMMAND
2490 | RTL_COMMAND = formatted_command
2491 | return
2492 | except ValueError:
2493 | pass
2494 |
2495 | except curses.error:
2496 | pass
2497 | finally:
2498 | stdscr.nodelay(True)
2499 | curses.noecho()
2500 | curses.curs_set(0)
2501 |
2502 | def init_audio_device():
2503 | """Initialize audio device with error handling and backend selection"""
2504 | try:
2505 | # Try to create output stream without specifying backend
2506 | test_stream = sd.OutputStream(
2507 | channels=2,
2508 | samplerate=44100,
2509 | blocksize=2048,
2510 | dtype=np.float32
2511 | )
2512 | test_stream.close()
2513 | return True
2514 | except sd.PortAudioError as e:
2515 | print(f"Audio initialization error: {e}")
2516 | return False
2517 |
2518 | def init_device(self):
2519 | """Initialize SDR device with error handling for PPM correction"""
2520 | try:
2521 | if self.backend == 'RTL':
2522 | self.device = RtlSdr()
2523 |
2524 | # Set basic parameters first, without PPM
2525 | self.device.sample_rate = self.sample_rate
2526 | self.device.center_freq = self.center_freq
2527 | self.device.gain = self.gain
2528 |
2529 | # Don't try to set PPM during initialization
2530 | self.ppm = 0 # Start with 0 PPM
2531 |
2532 | except Exception as e:
2533 | raise RuntimeError(f"Error initializing SDR device: {e}")
2534 |
2535 | def main(stdscr):
2536 | global SCAN_ACTIVE, AGC_ENABLED, last_agc_update, SAMPLES, WATERFALL_MODE, CURRENT_DEMOD,USE_PIPE,PIPE_FILE
2537 | init_colors()
2538 | gainindex = -1
2539 |
2540 | # Get initial screen dimensions
2541 | max_height, max_width = stdscr.getmaxyx()
2542 | # Initialize display mode
2543 | current_display_mode = 'SPECTRUM'
2544 |
2545 | # Initialize audio
2546 | audio_available = init_audio_device()
2547 | if not audio_available:
2548 | stdscr.addstr(0, 0, "Warning: Audio system initialization failed",
2549 | curses.color_pair(3) | curses.A_BOLD)
2550 | stdscr.refresh()
2551 | time.sleep(2)
2552 |
2553 | # Add audio state variables
2554 | audio_enabled = False
2555 | stream = None
2556 |
2557 | # Add new variables for audio recording
2558 | audio_recording = False
2559 | wav_file = None
2560 | recording_start_time = None
2561 |
2562 | # Initialize SDR device with selected backend
2563 | try:
2564 | sdr = SDRDevice(stdscr=stdscr)
2565 | sdr.init_device()
2566 |
2567 | # Load saved settings if available
2568 | settings = load_settings()
2569 | sdr.set_sample_rate(settings['sample_rate'])
2570 | sdr.set_center_freq(settings['frequency'])
2571 |
2572 | # Handle gain setting properly
2573 | if settings['gain'] == 'auto':
2574 | sdr.set_gain('auto')
2575 | gainindex = -1
2576 | else:
2577 | try:
2578 | gain_value = float(settings['gain'])
2579 | valid_gains = sdr.valid_gains_db
2580 | gainindex = min(range(len(valid_gains)),
2581 | key=lambda i: abs(valid_gains[i] - gain_value))
2582 | sdr.set_gain(valid_gains[gainindex])
2583 | except (ValueError, TypeError):
2584 | sdr.set_gain('auto')
2585 | gainindex = -1
2586 |
2587 | # Try to set PPM after device is initialized
2588 | try:
2589 | if settings['ppm'] != 0: # Only try to set non-zero PPM
2590 | sdr.set_ppm(settings['ppm'])
2591 | except Exception as e:
2592 | stdscr.addstr(0, 0, f"Warning: PPM correction not supported: {str(e)}",
2593 | curses.color_pair(3) | curses.A_BOLD)
2594 | stdscr.refresh()
2595 | time.sleep(1)
2596 | sdr.ppm = 0 # Reset to 0 if setting fails
2597 |
2598 | bandwidth = settings['bandwidth']
2599 | freq_step = settings['freq_step']
2600 | SAMPLES = settings['samples']
2601 | AGC_ENABLED = settings['agc_enabled']
2602 |
2603 | # Enable non-blocking input
2604 | stdscr.nodelay(True)
2605 |
2606 | while True:
2607 | try:
2608 | current_time = time.time()
2609 |
2610 | # Update screen dimensions in case terminal was resized
2611 | max_height, max_width = stdscr.getmaxyx()
2612 |
2613 | # Read samples and compute FFT
2614 | try:
2615 | samples = sdr.read_samples((2**SAMPLES) * 256)
2616 | if len(samples) == 0 or np.all(samples == 0):
2617 | stdscr.addstr(max_height-1, 0, "Error reading samples, retrying...",
2618 | curses.color_pair(3))
2619 | stdscr.refresh()
2620 | time.sleep(0.1)
2621 | continue
2622 | except Exception as e:
2623 | stdscr.addstr(max_height-1, 0, f"Error: {str(e)}", curses.color_pair(3))
2624 | stdscr.refresh()
2625 | time.sleep(0.1)
2626 | continue
2627 |
2628 | # Handle AGC if enabled
2629 | if AGC_ENABLED and (current_time - last_agc_update) >= AGC_UPDATE_INTERVAL:
2630 | current_power = measure_signal_power(samples)
2631 | gainindex = adjust_gain(sdr, current_power, gainindex)
2632 | last_agc_update = current_time
2633 |
2634 | # Update audio processing logic
2635 | if AUDIO_AVAILABLE and audio_enabled:
2636 | audio = demodulate_signal(samples, sdr.sample_rate, CURRENT_DEMOD)
2637 | audio_buffer.append(audio)
2638 |
2639 | # Update audio processing logic for PIPE
2640 | if USE_PIPE:
2641 | audio = demodulate_signal(samples, sdr.sample_rate, CURRENT_DEMOD)
2642 | audio_buffer.append(audio)
2643 |
2644 | # Calculate frequency bins
2645 | num_bins = 1024 # Reduced from 2048
2646 | freq_bins = np.fft.fftshift(np.fft.fftfreq(num_bins, d=1/sdr.sample_rate)) + sdr.center_freq
2647 |
2648 | # Compute FFT with improved processing
2649 | fft = np.fft.fft(samples * np.hamming(len(samples)))
2650 | fft = np.fft.fftshift(fft)
2651 |
2652 | # Compute power spectrum with better noise handling
2653 | freq_data = 20 * np.log10(np.abs(fft) + 1e-10)
2654 |
2655 | # Apply moving average smoothing
2656 | window_size = 5
2657 | freq_data = np.convolve(freq_data, np.ones(window_size)/window_size, mode='valid')
2658 |
2659 | # Apply additional noise reduction
2660 | noise_threshold = np.median(freq_data) - 10
2661 | freq_data[freq_data < noise_threshold] = noise_threshold
2662 |
2663 | # Update the draw_spectrogram call to include recording status
2664 | recording_duration = time.time() - recording_start_time if audio_recording else None
2665 |
2666 | draw_header(stdscr, freq_data, freq_bins, sdr.center_freq, bandwidth, sdr.gain, freq_step, sdr, audio_recording, recording_duration)
2667 |
2668 | if current_display_mode == 'SPECTRUM':
2669 | draw_spectrogram(stdscr, freq_data, freq_bins, sdr.center_freq,
2670 | bandwidth, sdr.gain, freq_step, sdr, # Add sdr here
2671 | audio_recording, recording_duration)
2672 | elif current_display_mode == 'WATERFALL':
2673 | draw_waterfall(stdscr, freq_data, freq_bins, sdr.center_freq,
2674 | bandwidth, sdr.gain, freq_step, sdr, # Add sdr here
2675 | audio_recording, recording_duration)
2676 | elif current_display_mode == 'PERSISTENCE':
2677 | draw_persistence(stdscr, freq_data, freq_bins, sdr.center_freq,
2678 | bandwidth, sdr.gain, freq_step, sdr, # Add sdr here
2679 | audio_recording, recording_duration)
2680 | elif current_display_mode == 'SURFACE':
2681 | draw_surface_plot(stdscr, freq_data, freq_bins, sdr.center_freq,
2682 | bandwidth, sdr.gain, freq_step, sdr, # Add sdr here
2683 | audio_recording, recording_duration)
2684 | elif current_display_mode == 'GRADIENT':
2685 | draw_gradient_waterfall(stdscr, freq_data, freq_bins, sdr.center_freq,
2686 | bandwidth, sdr.gain, freq_step, sdr,
2687 | audio_recording, recording_duration)
2688 | elif current_display_mode == 'VECTOR':
2689 | draw_vector_display(stdscr, samples, sdr.center_freq,
2690 | bandwidth, sdr.gain, freq_step, sdr)
2691 |
2692 |
2693 | # Handle user input
2694 | key = stdscr.getch()
2695 | if key == ord('q'): # Quit
2696 | break
2697 | elif key == ord('I'):
2698 | draw_clearheader(stdscr)
2699 | #if not audio_recording and AUDIO_AVAILABLE and audio_enabled and not USE_PIPE:
2700 | if not USE_PIPE:
2701 | # Start recording
2702 | recording_start_time = time.time()
2703 | #show_popup_msg(stdscr,"Sample rate: " + str(sdr.sample_rate),pause=4)
2704 | start_pipe_recording(stdscr)
2705 | elif audio_recording:
2706 | # Stop recording
2707 | stop_pipe_recording(stdscr)
2708 | elif key == ord('a'): # Toggle audio
2709 | if USE_PIPE:
2710 | show_popup_msg(stdscr,"Disable PIPE export first!",error=True)
2711 | else:
2712 | if audio_available:
2713 | audio_enabled = not audio_enabled
2714 | if audio_enabled and stream is None:
2715 | try:
2716 | stream = sd.OutputStream(
2717 | channels=2,
2718 | samplerate=44100,
2719 | callback=audio_callback,
2720 | blocksize=2048,
2721 | latency=0.1,
2722 | dtype=np.float32
2723 | )
2724 | stream.start()
2725 | except sd.PortAudioError as e:
2726 | stdscr.addstr(0, 0, f"Audio error: {str(e)}",
2727 | curses.color_pair(3) | curses.A_BOLD)
2728 | stdscr.refresh()
2729 | time.sleep(2)
2730 | audio_enabled = False
2731 | stream = None
2732 | elif not audio_enabled and stream is not None:
2733 | try:
2734 | stream.stop()
2735 | stream.close()
2736 | except:
2737 | pass
2738 | stream = None
2739 | audio_buffer.clear()
2740 | elif key == curses.KEY_UP: # Increase frequency by 1 MHz
2741 | sdr.set_center_freq(sdr.center_freq + 1e6)
2742 | elif key == curses.KEY_DOWN: # Decrease frequency by 1 MHz
2743 | sdr.set_center_freq(max(0, sdr.center_freq - 1e6))
2744 | elif key == curses.KEY_RIGHT: # Increase frequency by 0.5 MHz
2745 | sdr.set_center_freq(sdr.center_freq + 0.5e6)
2746 | elif key == curses.KEY_LEFT: # Decrease frequency by 0.5 MHz
2747 | sdr.set_center_freq(max(0, sdr.center_freq - 0.5e6))
2748 | elif key == ord('x'): # Set Frequency
2749 | freq = setfreq(stdscr)
2750 | if freq:
2751 | if freq[-1] in 'mM ':
2752 | freq = float(freq[:-1]) * 1e6
2753 | elif freq[-1] in 'kK':
2754 | freq = float(freq[:-1]) * 1e3
2755 | sdr.set_center_freq(int(freq))
2756 | elif key == ord('t'): # Decrease step
2757 | freq_step = max(0.01e6, freq_step - 0.01e6)
2758 | draw_clearheader(stdscr)
2759 | elif key == ord('T'): # Increase step
2760 | freq_step = min(sdr.sample_rate / 2, freq_step + 0.01e6)
2761 | draw_clearheader(stdscr)
2762 | elif key == ord('h'): # Help
2763 | showhelp(stdscr)
2764 | stdscr.clear()
2765 | stdscr.refresh()
2766 | elif key == ord('b'): # Zoom in (reduce bandwidth)
2767 | bandwidth = max(0.1e6, bandwidth - zoom_step)
2768 | draw_clearheader(stdscr)
2769 | elif key == ord('B'): # Zoom out (increase bandwidth)
2770 | bandwidth = min(sdr.sample_rate, bandwidth + zoom_step)
2771 | draw_clearheader(stdscr)
2772 | elif key == ord('f'): # Shift center frequency down
2773 | sdr.set_center_freq(max(0, sdr.center_freq - freq_step))
2774 | draw_clearheader(stdscr)
2775 | elif key == ord('F'): # Shift center frequency up
2776 | sdr.set_center_freq(sdr.center_freq + freq_step)
2777 | draw_clearheader(stdscr)
2778 | elif key == ord('s'): # Decrease samples
2779 | SAMPLES -= 1
2780 | if SAMPLES < 5:
2781 | SAMPLES = 5
2782 | draw_clearheader(stdscr)
2783 | elif key == ord('S'): # Increase samples
2784 | SAMPLES += 1
2785 | if SAMPLES > 12:
2786 | SAMPLES = 12
2787 | draw_clearheader(stdscr)
2788 | elif key == ord('G'):
2789 | gainindex +=1
2790 | if gainindex <= len(sdr.valid_gains_db)-1:
2791 | sdr.set_gain(sdr.valid_gains_db[gainindex])
2792 | else:
2793 | sdr.set_gain("auto")
2794 | gainindex = -1
2795 | draw_clearheader(stdscr)
2796 | elif key == ord('g'):
2797 | gainindex -= 1
2798 | if gainindex < 0:
2799 | sdr.set_gain(sdr.valid_gains_db[0])
2800 | gainindex = 0
2801 | else:
2802 | sdr.set_gain(sdr.valid_gains_db[gainindex])
2803 | draw_clearheader(stdscr)
2804 | elif key == ord('k'): # Save bookmark
2805 | add_bookmark(stdscr, sdr.center_freq, bandwidth)
2806 | elif key == ord('l'): # Load bookmark
2807 | bkm = show_bookmarks(stdscr)
2808 | if bkm is not None:
2809 | new_freq = bkm[0]
2810 | sdr.set_center_freq(new_freq)
2811 | bandwidth = bkm[2]
2812 | CURRENT_DEMOD = bkm[1]
2813 | elif key == ord('R'): # Start/Stop recording
2814 | draw_clearheader(stdscr)
2815 | if not audio_recording and AUDIO_AVAILABLE and audio_enabled:
2816 | # Start recording
2817 | timestamp = time.strftime("%Y%m%d-%H%M%S")
2818 | filename = f"sdr_recording_{timestamp}.wav"
2819 | wav_file = start_audio_recording(filename)
2820 | audio_recording = True
2821 | recording_start_time = time.time()
2822 | stdscr.addstr(max_height-1, 0, f"Started recording to {filename}",
2823 | curses.color_pair(4))
2824 | elif audio_recording:
2825 | # Stop recording
2826 | stop_audio_recording(wav_file)
2827 | audio_recording = False
2828 | wav_file = None
2829 | stdscr.addstr(max_height-1, 0, "Recording stopped",
2830 | curses.color_pair(4))
2831 | else:
2832 | stdscr.addstr(max_height-1, 0,
2833 | "Audio must be enabled to record (press 'a' first)",
2834 | curses.color_pair(3))
2835 | stdscr.refresh()
2836 | elif key == ord('w'): # Save settings
2837 | save_settings(sdr, bandwidth, freq_step, SAMPLES, AGC_ENABLED)
2838 | stdscr.addstr(max_height-1, 0, "Settings saved", curses.color_pair(4))
2839 | stdscr.refresh()
2840 | time.sleep(1) # Show message briefly
2841 | elif key == ord('v'): # Toggle waterfall mode
2842 | WATERFALL_MODE = not WATERFALL_MODE
2843 | WATERFALL_HISTORY.clear() # Clear history when switching modes
2844 | stdscr.clear()
2845 | elif key == ord('r'): # Load settings
2846 | settings = load_settings()
2847 | sdr.set_sample_rate(settings['sample_rate'])
2848 | sdr.set_center_freq(settings['frequency'])
2849 | sdr.set_gain(settings['gain'])
2850 | bandwidth = settings['bandwidth']
2851 | freq_step = settings['freq_step']
2852 | SAMPLES = settings['samples']
2853 | AGC_ENABLED = settings['agc_enabled']
2854 | stdscr.addstr(max_height-1, 0, "Settings loaded", curses.color_pair(4))
2855 | stdscr.refresh()
2856 | time.sleep(1) # Show message briefly
2857 | elif key == ord('A'): # Toggle AGC
2858 | draw_clearheader(stdscr)
2859 | AGC_ENABLED = not AGC_ENABLED
2860 | if not AGC_ENABLED:
2861 | # Reset to manual gain mode
2862 | if gainindex >= 0 and gainindex < len(sdr.valid_gains_db):
2863 | sdr.set_gain(sdr.valid_gains_db[gainindex])
2864 | else:
2865 | sdr.set_gain('auto')
2866 | gainindex = -1
2867 | elif key == ord('n'): # Band presets
2868 | new_freq, new_bandwidth = show_band_presets(stdscr)
2869 | stdscr.clear()
2870 | if new_freq is not None:
2871 | sdr.set_center_freq(new_freq)
2872 | bandwidth = new_bandwidth
2873 | # Adjust gain for the new frequency range
2874 | if AGC_ENABLED:
2875 | # Force an immediate AGC update
2876 | last_agc_update = 0
2877 | show_popup_msg(stdscr,f"Switched to band: {new_freq/1e6:.3f} MHz")
2878 | elif key == ord('c'): # Start frequency scanner
2879 | # Get scanner configuration
2880 | start_freq, end_freq, threshold = show_scanner_menu(stdscr)
2881 | if start_freq is not None:
2882 | SCAN_ACTIVE = True
2883 | signals = []
2884 | current_freq = start_freq
2885 |
2886 | # Scanning loop
2887 | while current_freq <= end_freq and SCAN_ACTIVE:
2888 | # Update progress display
2889 | draw_scanning_status(stdscr, current_freq, start_freq, end_freq, sdr)
2890 |
2891 | # Check for cancel
2892 | if stdscr.getch() == ord('q'):
2893 | SCAN_ACTIVE = False
2894 | break
2895 |
2896 | # Perform scan for current chunk
2897 | try:
2898 | # Set frequency and allow settling time
2899 | sdr.set_center_freq(current_freq)
2900 | time.sleep(0.01) # Short settling time
2901 |
2902 | # Read samples and compute FFT
2903 | samples = sdr.read_samples(2048) # Reduced sample size for speed
2904 | if len(samples) > 0:
2905 | # Compute power spectrum
2906 | spectrum = np.fft.fftshift(np.fft.fft(samples))
2907 | power_db = 10 * np.log10(np.abs(spectrum)**2 + 1e-10)
2908 |
2909 | # Find peak power
2910 | peak_power = np.max(power_db)
2911 |
2912 | # If signal detected
2913 | if peak_power > threshold:
2914 | # Estimate bandwidth
2915 | mask = power_db > (peak_power - 20) # Points within 20dB of peak
2916 | bandwidth = np.sum(mask) * (sdr.sample_rate / len(power_db))
2917 |
2918 | # Only add if bandwidth is reasonable
2919 | if bandwidth > MIN_SIGNAL_BANDWIDTH:
2920 | signals.append({
2921 | 'frequency': current_freq,
2922 | 'power': peak_power,
2923 | 'bandwidth': bandwidth,
2924 | 'type': classify_signal(samples, sdr.sample_rate, bandwidth)
2925 | })
2926 |
2927 | # Debug output
2928 | stdscr.addstr(max_height-1, 0,
2929 | f"Signal found: {current_freq/1e6:.3f} MHz, "
2930 | f"Power: {peak_power:.1f} dB, "
2931 | f"BW: {bandwidth/1e3:.1f} kHz",
2932 | curses.color_pair(4))
2933 | stdscr.refresh()
2934 |
2935 | except Exception as e:
2936 | stdscr.addstr(max_height-1, 0,
2937 | f"Scan error ({type(e).__name__}): {str(e)}",
2938 | curses.color_pair(3))
2939 | stdscr.refresh()
2940 |
2941 | # Move to next frequency
2942 | current_freq += SCAN_STEP
2943 |
2944 | # After scanning, store results globally
2945 | if signals:
2946 | global LAST_SCAN_RESULTS
2947 | LAST_SCAN_RESULTS = signals.copy() # Store a copy of the results
2948 |
2949 | # Display results and get selected frequency
2950 | new_freq = display_scan_results(stdscr, signals, threshold)
2951 |
2952 | # ... rest of existing scanning code ...
2953 |
2954 | # Reset scan state
2955 | SCAN_ACTIVE = False
2956 | stdscr.clear()
2957 | elif key == ord('d'): # Change demodulation mode
2958 | new_mode = show_demod_menu(stdscr)
2959 | if new_mode is not None:
2960 | CURRENT_DEMOD = new_mode
2961 | # Update bandwidth based on mode
2962 | if DEMOD_MODES[CURRENT_DEMOD]['bandwidth']:
2963 | bandwidth = DEMOD_MODES[CURRENT_DEMOD]['bandwidth']
2964 | stdscr.addstr(max_height-1, 0,
2965 | f"Switched to {DEMOD_MODES[CURRENT_DEMOD]['name']} mode",
2966 | curses.color_pair(4))
2967 | stdscr.refresh()
2968 | time.sleep(1)
2969 | elif key == ord('M'): # Add Morse decoder option
2970 | show_morse_decoder(stdscr, sdr, sdr.sample_rate)
2971 | stdscr.clear()
2972 | stdscr.refresh()
2973 | elif key == ord('.'): # Add APRS decoder option
2974 | show_aprs_decoder(stdscr, sdr, sdr.sample_rate)
2975 | stdscr.clear()
2976 | stdscr.refresh()
2977 | elif key == ord('m'): # Mode switch
2978 | current_mode_index = DISPLAY_MODES.index(current_display_mode)
2979 | current_display_mode = DISPLAY_MODES[(current_mode_index + 1) % len(DISPLAY_MODES)]
2980 | stdscr.clear()
2981 | elif key == ord('/'): # RTL Commands
2982 | show_rtl_commands(stdscr, sdr) # Pass sdr here
2983 | elif key == ord('1'): # Spectrum Mode switch
2984 | current_mode_index = 0
2985 | current_display_mode = DISPLAY_MODES[0]
2986 | stdscr.clear()
2987 | elif key == ord('2'): # Waterfall Mode switch
2988 | current_mode_index = 1
2989 | current_display_mode = DISPLAY_MODES[1]
2990 | stdscr.clear()
2991 | elif key == ord('3'): # Persistence Mode switch
2992 | current_mode_index = 2
2993 | current_display_mode = DISPLAY_MODES[2]
2994 | stdscr.clear()
2995 | elif key == ord('4'): # Surface Mode switch
2996 | current_mode_index = 3
2997 | current_display_mode = DISPLAY_MODES[3]
2998 | stdscr.clear()
2999 | elif key == ord('5'): # Gradient Mode switch
3000 | current_mode_index = 4
3001 | current_display_mode = DISPLAY_MODES[4]
3002 | stdscr.clear()
3003 | elif key == ord('6'): # Vector Mode switch
3004 | current_mode_index = 5
3005 | current_display_mode = DISPLAY_MODES[5]
3006 | stdscr.clear()
3007 | elif key == ord('P'): # Increase PPM
3008 | draw_clearheader(stdscr)
3009 | if sdr.ppm < 1000: # Add reasonable limit
3010 | if sdr.set_ppm(sdr.ppm + 1):
3011 | show_popup_msg(stdscr, f"PPM set to {sdr.ppm}")
3012 | else:
3013 | show_popup_msg(stdscr, "Failed to set PPM", error=True)
3014 | elif key == ord('p'): # Decrease PPM
3015 | draw_clearheader(stdscr)
3016 | if sdr.ppm > -1000: # Add reasonable limit
3017 | if sdr.set_ppm(sdr.ppm - 1):
3018 | show_popup_msg(stdscr, f"PPM set to {sdr.ppm}")
3019 | else:
3020 | show_popup_msg(stdscr, "Failed to set PPM", error=True)
3021 | elif key == ord('O'): # Set exact PPM value
3022 | draw_clearheader(stdscr)
3023 | stdscr.addstr(0, 0, "Enter PPM correction value: ",
3024 | curses.color_pair(1) | curses.A_BOLD)
3025 | curses.echo()
3026 | curses.curs_set(1)
3027 | stdscr.nodelay(False)
3028 | try:
3029 | ppm = int(stdscr.getstr().decode('utf-8'))
3030 | if sdr.set_ppm(ppm):
3031 | show_popup_msg(stdscr, f"PPM set to {sdr.ppm}")
3032 | else:
3033 | show_popup_msg(stdscr, "Failed to set PPM", error=True)
3034 | except ValueError:
3035 | show_popup_msg(stdscr, "Invalid PPM value!", error=True)
3036 | finally:
3037 | curses.noecho()
3038 | curses.curs_set(0)
3039 | stdscr.nodelay(True)
3040 | # Add new key handler for showing last results
3041 | elif key == ord('C'): # Show last scan results
3042 | if LAST_SCAN_RESULTS:
3043 | stdscr.nodelay(False)
3044 | curses.flushinp()
3045 |
3046 | # Display the stored results
3047 | new_freq = display_scan_results(stdscr, LAST_SCAN_RESULTS, SIGNAL_THRESHOLD)
3048 |
3049 | # If frequency was selected, tune to it
3050 | if new_freq is not None:
3051 | sdr.set_center_freq(new_freq)
3052 |
3053 | stdscr.nodelay(True)
3054 | stdscr.clear()
3055 | else:
3056 | # Show message if no previous scan results exist
3057 | draw_clearheader(stdscr)
3058 | stdscr.addstr(0, 0, "No previous scan results available", curses.color_pair(3))
3059 | stdscr.refresh()
3060 | time.sleep(2)
3061 | draw_clearheader(stdscr)
3062 |
3063 | # Remove the separate recording duration display since it's now handled in draw_spectrogram
3064 | if audio_recording and AUDIO_AVAILABLE and audio_enabled:
3065 | if len(audio_buffer) > 0:
3066 | audio_data = np.concatenate(list(audio_buffer))
3067 | write_audio_samples(wav_file, audio_data)
3068 | audio_buffer.clear()
3069 |
3070 | if USE_PIPE:
3071 | if len(audio_buffer) > 0:
3072 | try:
3073 | audio_data = np.concatenate(list(audio_buffer))
3074 | write_to_pipe(PIPE_FILE,audio_data,stdscr)
3075 | #write_to_pipe(PIPE_FILE,data[:frames].tobytes())
3076 | audio_buffer.clear()
3077 |
3078 | stdscr.addstr(".")
3079 | except BlockingIOError as e:
3080 | if e.errno == errno.EAGAIN:
3081 | show_popup_msg(stdscr,"No reader available. Skipping write...",error=True,pause=3)
3082 | else:
3083 | raise # Unexpected error, re-raise
3084 | except FileNotFoundError:
3085 | show_popup_msg(stdscr,f"The pipe {PIPE_PATH} was not found.",error=True,pause=3)
3086 | close_file_pipe(PIPE_FILE)
3087 | USE_PIPE = False
3088 | clean_pipe(None,None)
3089 | except BrokenPipeError:
3090 | show_popup_msg(stdscr,f"The reader has closed the pipe. Exiting.",error=True,pause=3)
3091 | close_file_pipe(PIPE_FILE)
3092 | USE_PIPE = False
3093 | clean_pipe(None,None)
3094 | except Exception as e:
3095 | show_popup_msg(stdscr,f"An unexpected error occurred: {e}",error=True,pause=3)
3096 | close_file_pipe(PIPE_FILE)
3097 | USE_PIPE = False
3098 | clean_pipe(None,None)
3099 |
3100 |
3101 |
3102 | except curses.error:
3103 | # Handle curses errors (like terminal resize)
3104 | continue
3105 |
3106 | except KeyboardInterrupt:
3107 | pass
3108 | finally:
3109 | sdr.close()
3110 | if stream:
3111 | stream.stop()
3112 | stream.close()
3113 |
3114 | # Make sure to close the WAV file if we exit while recording
3115 | if wav_file:
3116 | stop_audio_recording(wav_file)
3117 |
3118 |
3119 | def compute_fft(samples):
3120 | """Compute normalized FFT with proper scaling"""
3121 | # Apply window function to reduce spectral leakage
3122 | window = np.hamming(len(samples))
3123 | windowed_samples = samples * window
3124 |
3125 | # Compute FFT and shift zero frequency to center
3126 | fft = np.fft.fftshift(np.fft.fft(windowed_samples))
3127 |
3128 | # Convert to power spectrum in dB, with proper scaling
3129 | power_db = 20 * np.log10(np.abs(fft) + 1e-10)
3130 |
3131 | # Apply calibration factors
3132 | system_gain = -30 # Adjustment for system gain
3133 | ref_level = -70 # Reference level adjustment
3134 |
3135 | # Apply calibration and clip to reasonable range
3136 | power_db = np.clip(power_db + system_gain + ref_level, -100, -20)
3137 |
3138 | return power_db
3139 |
3140 | if __name__ == "__main__":
3141 | curses.wrapper(main)
3142 | if RTL_COMMAND:
3143 | print(RTL_COMMAND)
3144 | try:
3145 | clean_pipe(None, None)
3146 | except:
3147 | pass
3148 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | numpy>=1.20.0
2 | scipy>=1.7.0
3 | sounddevice>=0.4.1
4 | SoapySDR>=0.8.0
5 | pyrtlsdr>=0.2.91
6 |
--------------------------------------------------------------------------------
/rtlcoms.json:
--------------------------------------------------------------------------------
1 | {
2 | "Listen FM Radio":"rtl_fm -f {freq}M -M wbfm -s 200k -r 48k | play -r 48k -t raw -e signed-integer -b 16 -c 1 -V1 -",
3 | "Listen AM":"rtl_fm -f {freq}M -M am -s 12k -r 12k | play -r 12k -t raw -e s -b 16 -c 1 -",
4 | "Listen CB Radio":"rtl_fm -f {freq}M -M am -s 12k -r 12k | play -r 12k -t raw -e s -b 16 -c 1 -",
5 | "Capture NOAA in .wav":"rtl_fm -f 137.62M -M fm -s 60k -g 50 -p 0 -E deemp | sox -t raw -r 60k -e signed -b 16 -c 1 -V1 - NOAA.wav && wxtoimg NOAA.wav NOAA.png",
6 | "Decode Aircraft Transmissions":"dump1090 --net --interactive",
7 | "Decode APRS (def:144.8M)":"rtl_fm -f {freq}M -M fm -s 22050 -r 22050 | direwolf -c direwolf.conf -r 22050 -",
8 | "Decode smart devices (def:433.92M)":"rtl_433 -f {freq}M",
9 | "Decode Pager (def:153.2M)":"rtl_fm -f {freq}M -M fm -s 22050 -r 22050 | multimon-ng -t raw -a POCSAG1200 -",
10 | "Decode GSM signals":"grgsm_livemon -f {freq}M",
11 | "Decode NOAA HRIT/EMWIN Satellite Signals (Def. 1694.1M)":"rtl_fm -f {freq}M -M usb -s 700k -g 50 | goestools",
12 | "Decode MORSE code":"rtl_fm -f {freq}M -M am -s 12k -r 12k | multimon-ng -a CW -t raw -",
13 | "Decode Digital Voice (DMR, D-Star, etc.)":"rtl_fm -f {freq}M -M fm -s 48k -r 48k | dsd -i /dev/stdin -o /dev/stdout",
14 | "Stream to ICECAST server":"rtl_fm -f {freq}M -M wbfm -s 200k -r 48k | ffmpeg -re -i pipe:0 -acodec libmp3lame -f mp3 icecast://source:password@yourserver:8000/mount",
15 | "Receive AIS (Marine Automatic Identification System)":"rtl_fm -f {freq}M -M fm -s 48k -r 48k | aisdecoder -h -d /dev/stdin",
16 | "Monitor Trunked Radio Systems (P25, DMR, etc. Def.851.0125)":"rtl_fm -f {freq}M -M fm -s 48k -g 40 | multimon-ng -a P25 -t raw -",
17 | "Monitor Pager traffic (Def. 138M)":"rtl_fm -f {freq}M -M fm -s 22050 -r 22050 | multimon-ng -a FLEX -t raw -"
18 | }
19 |
--------------------------------------------------------------------------------
/sdr_bookmarks.json:
--------------------------------------------------------------------------------
1 | {
2 | "\u001b": [
3 | 92500000.0,
4 | "NFM",
5 | 1000000.0
6 | ]
7 | }
--------------------------------------------------------------------------------