├── .github └── workflows │ ├── main.yaml │ └── release.yaml ├── .gitignore ├── CHANGELOG.md ├── INSTALL.md ├── LICENSE.GPLv3 ├── OPTIONS_EXPLAINED.md ├── README.md ├── hrf.py ├── imgs └── 145.png ├── libhackrf.py ├── linux_setup.sh ├── requirements.txt ├── rflh.py ├── rotor.conf ├── rotor.py └── rtl.py /.github/workflows/main.yaml: -------------------------------------------------------------------------------- 1 | name: Package Application with Pyinstaller 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - develop 8 | pull_request: 9 | branches: 10 | - main 11 | - develop 12 | 13 | jobs: 14 | build: 15 | 16 | runs-on: ubuntu-20.04 17 | 18 | steps: 19 | - uses: actions/checkout@v2 20 | 21 | - name: Setup Script 22 | run: ./linux_setup.sh 23 | 24 | - name: Python requisite installs 25 | run: pip3 install -r requirements.txt pyinstaller 26 | 27 | - name: App creation 28 | run: python3 -m PyInstaller -yF --hidden-import Hamlib rflh.py 29 | 30 | - name: Test App 31 | run: cp rotor.conf dist/ && chmod +x ./dist/rflh && ./dist/rflh 145 -d 32 | 33 | - uses: actions/upload-artifact@v2 34 | with: 35 | name: rflh 36 | path: dist/rflh 37 | 38 | -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | name: Build and Release 2 | on: 3 | push: 4 | branches: 5 | - main 6 | pull_request: 7 | branches: 8 | - main 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-20.04 13 | steps: 14 | - uses: actions/checkout@v2 15 | 16 | - name: Setup Script 17 | run: ./linux_setup.sh 18 | 19 | - name: Python requisite installs 20 | run: pip3 install -r requirements.txt pyinstaller 21 | 22 | - name: App creation 23 | run: python3 -m PyInstaller -yF --hidden-import Hamlib rflh.py 24 | 25 | - name: Test App 26 | run: cp rotor.conf dist/ && chmod +x ./dist/rflh && ./dist/rflh 145 -d 27 | 28 | - uses: actions/upload-artifact@v2 29 | with: 30 | name: rflh 31 | path: dist/rflh 32 | 33 | release: 34 | runs-on: ubuntu-20.04 35 | needs: [build] 36 | steps: 37 | - uses: actions/checkout@master 38 | - name: Create release 39 | uses: Roang-zero1/github-create-release-action@master 40 | env: 41 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 42 | - name: Create GitHub release 43 | uses: Roang-zero1/github-upload-release-artifacts-action@master 44 | with: 45 | releaseId: ${{ needs.create_release.outputs.id }} 46 | args: dist/rflh 47 | env: 48 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 49 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | data/* 2 | build/* 3 | _* 4 | dist/* 5 | *.pyc 6 | *.pyo 7 | .vscode/ 8 | test.py 9 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) 6 | and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). 7 | 8 | 20 | 21 | ## 2022-01-08 22 | 23 | - Changed: Graph tool changed from plotly to pure mathplotlib. 24 | - Removed: dark/light themes. 25 | - Changed: Now the default is to save the csv & png file with the graph, if you have GUI on your system you can issue a '-i/--interactive' option to popup a matplotlib graph. 26 | - Changed: Documentation to reflect the changes. 27 | 28 | ## 2022-01-07 29 | 30 | - First release! 31 | - Issues: 32 | - Incomplete documentation 33 | - Issues with the pyinstaller and plotly 34 | - Must clarify the use of rotctld -------------------------------------------------------------------------------- /INSTALL.md: -------------------------------------------------------------------------------- 1 | # Install instructions 2 | 3 | ## Linux 4 | 5 | In linux you have a setup script on the project folder named `linux_setup.sh`, it has all the install steps. Just run it like this from a console: 6 | 7 | ```sh 8 | ./linux_setup.sh 9 | ``` 10 | 11 | It will ask for your credentials once and will install all the needed tools, after it finished (with no errors I hope!) you can jump to the test section below. 12 | 13 | ## Windows [in progress] 14 | 15 | I have not experience deploying it on Windows yet (I will try to deploy it and document this later) 16 | 17 | ## Hamlib rotctld setup 18 | 19 | You have a file called rotor.conf in the app folder, there you have some example section for a dummy rotor, a network rotor using hamlib protocol, a Yaesu GS-232A & B models and SPID Rot2Prog one. 20 | 21 | Just copy ot modify one of the sections and when finished go to the DEFAULT section and set the 'rotor' var to the name of the rotor you use, in the example the NET rotor is selected. 22 | 23 | That's is, the rotor class will handle the config and connection to the rotor specified. 24 | 25 | ## Testing 26 | 27 | Note: This section is focused on linux, I think that the windows testing procedure will not differ much once installed properly as all test instructions uses the same console apps. 28 | 29 | ### Native RTL-SDR support 30 | 31 | Plug your RTL-SDR to the PC and run this on the console. If success this command will hang in there until you press CTRL+C 32 | 33 | ```sh 34 | pavel@agathad:~/$ rtl_test 35 | Found 1 device(s): 36 | 0: Realtek, RTL2838UHIDIR, SN: 00000001 37 | 38 | Using device 0: Generic RTL2832U OEM 39 | Detached kernel driver 40 | Found Rafael Micro R820T tuner 41 | Supported gain values (29): 0.0 0.9 1.4 2.7 3.7 7.7 8.7 12.5 14.4 15.7 16.6 19.7 20.7 22.9 25.4 28.0 29.7 32.8 33.8 36.4 37.2 38.6 40.2 42.1 43.4 43.9 44.5 48.0 49.6 42 | [R82XX] PLL not locked! 43 | Sampling at 2048000 S/s. 44 | 45 | Info: This tool will continuously read from the device, and report if 46 | samples get lost. If you observe no further output, everything is fine. 47 | 48 | Reading samples in async mode... 49 | Allocating 15 zero-copy buffers 50 | lost at least 180 bytes 51 | ``` 52 | 53 | ### Python3 RTL-SDR support 54 | 55 | Just run the rtl.py file, like this 56 | 57 | ```sh 58 | pavel@agathad:~/$ python3 rtl.py 59 | Detached kernel driver 60 | Found Rafael Micro R820T tuner 61 | [R82XX] PLL not locked! 62 | Bin bw is 8 khz, with 245 segments, 6 samples in the BW 63 | Frequency: 440. MHz, 200 Khz bandwidth 64 | Mean level: -104.62619156247725 65 | Reattached kernel driver 66 | 67 | ``` 68 | 69 | If you see the `Mean level: -xxx.yyyyyyyyy` line all is fine. 70 | 71 | ### Native HackRF support 72 | 73 | To test the support just plug the HackRF One and run this on your console: 74 | 75 | ```sh 76 | pavel@agathad:~/$ hackrf_info 77 | hackrf_info version: 2021.03.1 78 | libhackrf version: 2021.03.1 (0.6) 79 | Found HackRF 80 | Index: 0 81 | Serial number: 0000000000000000QRSTUVWXYZ 82 | Board ID Number: 2 (HackRF One) 83 | Firmware Version: 2021.03.1 (API:1.04) 84 | Part ID Number: 0xa0000000 0x005e0000 85 | pavel@agathad:~/$ 86 | ``` 87 | 88 | If you see some similar info then you have the support already. 89 | 90 | ### Python3 HackRF support 91 | 92 | Just run the hrf.py file, like this 93 | 94 | ```sh 95 | pavel@agathad:~/$ python3 hrf.py 96 | Bin bw is 8 khz, with 960 segments, 6 samples in the BW 97 | Frequency: 440. MHz, 200 Khz bandwidth 98 | Mean level: -107.43880857116446 99 | Releasing the HackRF One 100 | ``` 101 | 102 | If you see the `Mean level: -xxx.yyyyyyyyy` line all is fine. 103 | 104 | ### Hamlib rotctld support 105 | 106 | For the rotor comms you need to setup your rotor with the hamlib `rotctld` tool to listen in the localhost for instructions, the script will talk to it. See the rotctld configuration section below. 107 | 108 | To test the rotor run the `rotor.py` script and you will get a result like this (please allow some time to the rotor to move to the 0, 0 position) 109 | 110 | ```sh 111 | pavel@agathad:~/rflh/$ python3 rotor.py 112 | Azimuth, actual: 0.0, set: 0 113 | Azimuth, actual: 10.0, set: 10 114 | Azimuth, actual: 20.0, set: 20 115 | Azimuth, actual: 30.0, set: 30 116 | Azimuth, actual: 40.0, set: 40 117 | Azimuth, actual: 50.0, set: 50 118 | Azimuth, actual: 60.0, set: 60 119 | Azimuth, actual: 70.0, set: 70 120 | Azimuth, actual: 80.0, set: 80 121 | Azimuth, actual: 90.0, set: 90 122 | pavel@agathad:~/rflh/$ 123 | ``` 124 | 125 | ## Let's Go! 126 | 127 | After testing you have all pieces working it's time to test it for real. 128 | 129 | 0. Connect all the rotor neded cables. 130 | 0. Connect the SDR device to the antenna connected to the rotor and to the PC 131 | 132 | Fire a sample runs: 133 | 134 | ```sh 135 | python3 rflh.py 145.000 -i 136 | ``` 137 | 138 | **Note:** to use the HackRf is just to add the `-o` option to that line. 139 | 140 | If all goes well you will see a poping up windows at the end with a graph and have a 'data' folder with the CSV & image files. 141 | 142 | Is then time to take a peek on the [explained option](OPTIONS_EXPLAINED.md) -------------------------------------------------------------------------------- /LICENSE.GPLv3: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /OPTIONS_EXPLAINED.md: -------------------------------------------------------------------------------- 1 | # Options Explained 2 | 3 | This file details the technical aspects of the options and some related low level stuff. 4 | 5 | The full feature and option list is given on the console runnig the script with `-h` or `--help` to show them: 6 | 7 | ```sh 8 | pavel@agathad:~/rflh$ python3 rflh.py -h 9 | usage: rflh.py [-h] [-b BANDWIDTH] [-s STEP] [-u] [-t BUCKETSIZE] [-p PPM] [-q] [-j] [-n] [-d] [-l LNA] [-v VGA] [-a] [-o] [-i] frequency 10 | 11 | Sweep the 360 degrees around recording the levels of a frequency at a given bandwidth; using rotctld and a RTL-SDR (default) or a HackRF One for spectrum sensing. 12 | 13 | positional arguments: 14 | frequency The center frequency to listen to, in MHz, "145.170" for 145.170 MHz 15 | 16 | optional arguments: 17 | -h, --help show this help message and exit 18 | -b BANDWIDTH, --bandwidth BANDWIDTH 19 | The bandwidth to sample in kHz: 1-800 kHz using the RTL-SDR or 1kHz-MHz 20 | using the HackRF, 20kHz by default 21 | -s STEP, --step STEP Azimuth steps in degrees, 10 degrees by default, see project README.md 22 | for details. 23 | -u, --paused Sweep mode: paused mode means move to target azimuth & take a measurement 24 | the repeat it (slow). The default is to make one full turn and do 25 | measurements on the fly (faster but may fail, read the documentation) 26 | -t BUCKETSIZE, --bucketsize BUCKETSIZE 27 | Bucket size: how many bytes to get for processing at each sample time, 28 | 1.024 Mbytes by default (use 2^n units or it will fail) 1.024 Mbytes = 1024000 29 | -p PPM, --ppm PPM Frequency correction for you device, by default 0.0 30 | -q, --quiet Quiet: supress output, default: verbose 31 | -j, --just_data Don't generate the web graph, default: generate it 32 | -n, --nofile Don't save the csv file, default: save it 33 | -i, --interactive Pop up a Matplotlib interactive graph with the results, default is no pop up 34 | -d, --dummy Don't use the rotor or the RTL-SDR or HackRF, just generate a dummy 35 | dataset and plot it; it implies --nofile; just for testing purposes 36 | -l LNA, --lna LNA LNA gain value: 0-49.6 dB in 0.4 dB for the RTL-SDR or 0-40 dB in 8 dB 37 | steps for HackRF. Defaults: 28.0 for the RTL-SDR & 32 for the HackRF 38 | -v VGA, --vga VGA VGA gain value (Only HackRF One): 0-62 in 2 units steps, 30 by default 39 | -a, --amp_on Amplifier on (Only HackRF One): by default it's disabled; WATCH OUT! 40 | some firmware revision has this option reversed (mine has it) 41 | -o, --hackrfone Use a HackRF One instead the default: RTL-SDR 42 | 43 | pavel@agathad:~/rflh$ 44 | ``` 45 | 46 | ## SDR devices 47 | 48 | By default it detect and uses the first RTL-SDR device detected, but if you need to use a HackRF One just issue the `-o` or `--hackrfone` switch and it will look for that device instead. 49 | 50 | **RTL-SDR:** it's the default, the script will look for a rtl-device and complain if none is found. Requires pyrtlsdr installed and rtl-sdr support on your PC, see [Install requisites](INSTALL_REQUISITES.md) for more details. 51 | 52 | The RTL-SDR device is used with a 2.04 Mhz of bandwidth and only the left half is used, discarding the left-most part of this spectrum slice as it has reduced accuracy it will allow you to sample up to 800 kHz of the spectrum at once. 53 | 54 | **HackRF One:** you must select it with the `-o` or `--hackrfone`, the script will look for a rtl-device and complain if none is found. You need support for the HackRF One on your PC, see [Install requisites](INSTALL_REQUISITES.md) for more details. 55 | 56 | The HackRF One device is used with at the native 8 Mhz of bandwidth and only the left half is used, discarding the left-most part of this spectrum slice as it has reduced accuracy it will allow you to sample up to 3 MHz of the spectrum at once. 57 | 58 | ## Bandwidth 59 | 60 | You can use the `-b` option to select from 1-800 kHz using the RTL-SDR and from 1 kHz to 3 MHz using the HackRF One. The default is 20 kHz. 61 | 62 | We use a pre-calculated bin size to get at least 6 bins for the bandwidth of your selection. 63 | 64 | ## Azimuth step 65 | 66 | By default we use 10 degrees of step, but you can select a lower value. Most rotor has a minimum step of 5 degrees. 67 | 68 | This selection interacts with the [Sweep Mode](#sweep-mode) & [Bucket size](#bucket-size) options, see below. 69 | 70 | ## Sweep mode 71 | 72 | The sweep mode by default is fast, TLDR: we force the rotor to go to az=0 & el=0 (park/start position) and then order it to go to az=360 & el=0; we keep track of the current position and launch measurements as needed without stopping the rotor. 73 | 74 | **Note:** That measurements have a given [Bucket size](#bucket-size) and the bigger the longer it will take to process it, that can spoil the fast mode. 75 | 76 | Depending on your rotor turning speed and hardware processing power to handle the bucket size, the sweep will complete or fail with an error complaining that the azimuth step is to short. 77 | 78 | If the bucket size took to long to process and the next position is over the next target position it will fail. 79 | 80 | In this scenario the azimuth step & bucket size depends entirely on your hardware, if you get fails with the needed parameters, then you must try the paused/slow mode. 81 | 82 | On paused sweep mode, we make blocking calls to the rotor to move to a ceirtain poisition, once we get there we take measurements and then move to the next position (remmember: blocking call); yes this mode is slow, around 3x slower than the fastmode on my hardware. 83 | 84 | For example in fastmode and 5 degrees my hardware took 55 seconds, and 3 min 48 seconds on paused sweep mode. (bucket size of 512k) 85 | 86 | **Tip:** In fast mode you will see (if you don't select the quiet switch) that the app shows the position and level but will show more data... 87 | 88 | ``` 89 | (...) 90 | 310(307.5);-102,16941998017171 91 | 320(317.5);-101,77656601734243 92 | 330(327.5);-101,55990296468812 93 | 340(337.5);-101,583492037594 94 | 350(347.5);-102,01302571365707 95 | Scan took 0:53 96 | CSVFile: data/20220108_1357_rtl_145.17MHz_300kHz_10o.csv 97 | Parking the rotor in the background 98 | Reattached kernel driver 99 | Dynamc range: 2.9333941135273136 dB, 10%: 0.2933394113527314 100 | Min: -104.78663648956817, Max -101.26656355333539 101 | ImgFile: data/20220108_1357_rtl_145.17MHz_300kHz_10o.png 102 | ``` 103 | 104 | See the line `350(347.5);-102,01302571365707` this measurements correspond to the 350 degree point but mean position during the sampling was 347.5 degrees, this is shown as a measuremnt of the real error in the fast sweep mode. 105 | 106 | This is used to fail when the sampling and processing can't cope with the rotor speed. 107 | 108 | ## Bucket size 109 | 110 | That's the amount of data to collect for a given spectrum sampling, by default 1.024 Mbytes will be collected. 111 | 112 | You can tune this parameter to your needs for example lower it to detect fast peaks or make it bigger for long integration periods to sample steady but low signals. 113 | 114 | It interacts with the fast sweep mode, as the bigger the longer the PC took to process the samples and that can spoil the fast (default) sweep mode. 115 | 116 | ## PPM error 117 | 118 | Almost all SDR devices has a ppm error on the internal clock signal (most cheap RTL-SDR has it) you need to characterize the ppm error of your device and suply it here, can be a negative value and by default it's assumed 0.0 ppm units. 119 | 120 | If you are sampling bandwidth of more than ~50 khz you can ignore the ppm correction as it's useles on that scenarios. 121 | 122 | But if you are using lower bandwidth and particullary with high bucket sizes you need a ppm correction for precise measurements. 123 | 124 | ## Just data 125 | 126 | As it's name implies it does not generate the pandas dataset and corresponding web visualization at the end of the sweep. The `just data` option is good to use on no GUI envs or networked ones, as a headless Raspberry Pi or other SBC. 127 | 128 | ## No file 129 | 130 | This option will stop the CSV file creation with the data for the sweep. Useful when you are just testing and don't mind the datasets creation at the end of the sweep. 131 | 132 | ## Interactive graph 133 | 134 | If you issue the `-i` option on a GUI system you will see a matplotlib graph with pan/zoom/saving features to interact to. 135 | 136 | ## Dummy data 137 | 138 | This option is to test the plotting options and only used on the developing stage. 139 | 140 | ## LNA (Low noise amplifier) Gain 141 | 142 | This option sets the LNA amplification for the selected SDR device, take into account that the LNA levels are discrete values, the corresponding lib will truncate the valued you pased to the nearest possible value. 143 | 144 | **RTL-SDR LNA levels** 145 | 146 | - Valid Gain levels: 0.0 to 49.6 dB 147 | - Step is 0.4 dB 148 | 149 | **HackRF One LNA levels** 150 | 151 | - Valid Gain levels: 0.0 to 40.0 dB 152 | - Step is 8.0 dB 153 | 154 | By default we set them at my sweetspot levels range for each device in my exprience: 155 | 156 | - RTL-SDR: 28.0 dB 157 | - HackRF One: 32.0 dB 158 | 159 | ## VGA gain (Only for the HackRF) 160 | 161 | The VGA gain is a unique feature of the HackRF One, it goes from 0.0 to 62.0 dB in 2.0 dB steps. By default it's set to 30.0 dB 162 | 163 | ## AMP On (Only for the HackRF) 164 | 165 | The `amp on` is a unique feature of the HackRF One, it's an internal, but it has a trick: 166 | 167 | On some hardware revisions its function is inverted! Yes, when you turn on the amplifier in software it got shut off in the hardware, weird. 168 | 169 | You have to check on your particular device the effects of this switch. My hardware has it reversed, so I shut it off by default (aka: turned on bu default) 170 | 171 | ## Examples (use cases) 172 | 173 | **Scenario 1:** Elevated noise floor on 70cm satellite band on some direction, broadband noise. 174 | 175 | - Will use 500 kHz of bandwidth. 176 | - High integration (bucket of ~8 Mbytes) 177 | - Slow scan as signal is noise and will ignore fast changing signals. 178 | - Step of 10 degrees (default) 179 | - High gain as we are measuring noise. 180 | - PPM here is useless as we are sampling the background noise. 181 | - Interactive graph popup 182 | 183 | ```h 184 | pavel@agathad:~/rflh/$ python3 rflh.py 436 -b 500 -t 8192000 -u -l 40 -i 185 | [...] 186 | ``` 187 | 188 | **Scenario 2:** Unknown digital intruder on the 2m satellite band (145.828 Mhz) ~12khz width, intermitent signal (~ 0.5 seconds pulse interval) 189 | 190 | - Will use 15 kHz of bandwidth 191 | - Will use the ppm as we need accurate results and low bandwidth 192 | - Low integration (bucket of ~512 kbytes) to detect fast changing signals & fast sweep 193 | - Fast sweep to allow detection of fast changing signals (default) 194 | - Step of 5 degrees as I'm using a 4x15 el EME yagis with a narrow beamwidth 195 | - Default gain as we are using a +20dB LNA and high gain yagui array. 196 | 197 | ```h 198 | pavel@agathad:~/rflh/$ python3 rflh.py 145.828 -b 15 -p 56 -t 512000 -s 5 199 | [...] 200 | ``` 201 | 202 | Graph shows peaks but no defined signal, will sweep again several times to get only csv data and process it on MS Excel or LO Calc later (no need for graphs, just data) 203 | 204 | ```h 205 | pavel@agathad:~/rflh/$ python3 rflh.py 145.828 -b 15 -p 56 -t 512000 -s 5 -j 206 | [...] 207 | ``` 208 | 209 | **Scenario 3:** New [OEM] 6m yagui and need to check the radiation lobes as the datasheet is to good to be true. 210 | 211 | Neigbor HAM 800m away will radiate an 2khz wide MT63 transmission for about 2 minutes with 5W on 50.15 Mhz (antenna sweetspot according to the OEM) with his vertical antenna (omni) 212 | 213 | - Will use 3 kHz of bandwidth. 214 | - Will use the ppm as we need accurate results and low bandwidth 215 | - Medium integration for accuracy (bucket of ~2 Mbytes) 216 | - Slow scan as signal may vary/reflect 217 | - Step of 10 degrees (default) 218 | - Lower gain as we are measuring a near & powerful signal. 219 | - No data, just graph 220 | - Interactive graph popup 221 | 222 | ```h 223 | pavel@agathad:~/rflh/$ python3 rflh.py 145.828 -b 3 -p 56 -t 2048000 -u -l 14 -n -i 224 | [...] 225 | ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RF Light House (rflh) 2 | 3 | A python script to use a rotor and a SDR device (RTL-SDR or HackRF One) to measure the RF level around and get a data set and beautiful interactive graphics. 4 | 5 | ![background noise measurement 145 Mhz](/imgs/145.png) 6 | 7 | WARNING: This repository is new and under construction, you will see some [TODO] & "(work in progress...)" sections/docs yet. 8 | 9 | ## Motivation 10 | 11 | This project born from a friend's challenge to measure the background noise impact on my 70cm satellite band noise floor, from a new 2/3/4G cellular tower that my ISP is setting up 50m away from my antennas and with direct sight. 12 | 13 | Soon I realized the true potential of it and it get bigger and feature rich quickly. 14 | 15 | ## Features 16 | 17 | At the end of the execution you get: 18 | 19 | - A cvs file in the data folder with the resulting data 20 | - A png image in the data folder with the rose plot 21 | 22 | Both files are named as follows: `YYYMMDD_HHMM_device_freqMHz_BWkHz_stepo` with the matching .csv and .png extensions. The runtime text on the console name the files created for easy parsing (unless you select the 'quiet' option) 23 | 24 | For example a real fast scan showing the references to the img & cvs file for parsing: 25 | 26 | ``` 27 | 310(307.5);-102,16941998017171 28 | 320(317.5);-101,77656601734243 29 | 330(327.5);-101,55990296468812 30 | 340(337.5);-101,583492037594 31 | 350(347.5);-102,01302571365707 32 | Scan took 0:53 33 | CSVFile: data/20220108_1357_rtl_145.17MHz_300kHz_10o.csv 34 | Parking the rotor in the background 35 | Reattached kernel driver 36 | Dynamc range: 2.9333941135273136 dB, 10%: 0.2933394113527314 37 | Min: -104.78663648956817, Max -101.26656355333539 38 | ImgFile: data/20220108_1357_rtl_145.17MHz_300kHz_10o.png 39 | ``` 40 | 41 | You can stop the generation of the cvs and the image files if not needed, take a peek on the options. 42 | 43 | Also if you are on a GUI enviroment you can issue the '-i' or '--interactive' switch and at the end of the sweep a interactive matplotlib graph will popup. 44 | 45 | For a more detailed technical stuff on the features see [OPTIONS_EXPLAINED.md](OPTIONS_EXPLAINED.md) (work in progress...) 46 | 47 | ## Installation 48 | 49 | As any script in python you will need some dependencies, default dev env is Ubuntu Linux 20.04 LTS. I'm working/testing a single portable file for linux/windows/mac but it's not ready yet (pyinstall stuff) 50 | 51 | The installation of the utilities & python modules are covered in the [Install](INSTALL.md) document. 52 | 53 | At the end of the we have some examples / use cases at the end of the [OPTIONS_EXPLAINED.md](OPTIONS_EXPLAINED.md) document. 54 | 55 | ## Author, contributions, code & donations 56 | 57 | The author is Pavel Milanes Costa (CO7WT), you can join the team contributing with code fix, improvements, bug reports, ideas, etc. Use te "Issues" tab for that. 58 | 59 | This software is Free Software under GPLv3, see [LICENCE](LICENSE.GPLv3); free as in freedom. 60 | 61 | If you find this piece of soft usefull and want to support the author with a tip, hardware donation or just a change for a coffee please contact me at pavelmc@gmail.com for instructions. 62 | 63 | For money tips you can use my [QvaPay donation page](https://qvapay.com/payme/pavelmc), thanks in advance! 64 | -------------------------------------------------------------------------------- /hrf.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import numpy as np 3 | from time import sleep 4 | from scipy import signal 5 | from libhackrf import * 6 | 7 | class RF(object): 8 | def __init__(self, ppm): 9 | try: 10 | self.hrf = HackRF() 11 | except: 12 | print("Are you sure that there is a HackRF One connected?\nI can't find it!") 13 | sys.exit() 14 | 15 | # HackRF setup 16 | self.hrf.lna_gain = 32 17 | self.hrf.vga_gain = 30 18 | self.hrf.sample_rate = 8e6 19 | #self.hrf.freq_correction = ppm #TODO 20 | self.bw = 50 21 | self.f = 101500000 22 | self.freq = self.f - 2e6 23 | self.nperseg = 256 24 | self.bbw = 0 25 | self.samples = 1.024e6 26 | 27 | # enable/disable the built-in amplifier: 28 | #self.hrf.enable_amp() 29 | self.hrf.disable_amp() 30 | 31 | def set_freq(self, freq): 32 | ''' 33 | freq in hz 34 | We put the freq in the middle of the lower half 35 | 0----*----F----3----4 36 | ''' 37 | 38 | self.freq = freq 39 | self.f = freq + (self.hrf.sample_rate / 4) 40 | self.hrf.center_freq = self.f 41 | 42 | def set_bw(self, bw): 43 | ''' 44 | bw in khz (between 1khz and 3 Mhz) 45 | ''' 46 | 47 | # failsafe 48 | bw = int(bw) 49 | 50 | # calculate the neede nperseg to get at least N samples in the bw 51 | if (bw < 1): 52 | raise ValueError("bw must be greather than 1khz") 53 | if (bw > 3e3): 54 | raise ValueError("bw must be lower than 3 Mhz") 55 | 56 | # N is the desired samples in the bw selected 57 | N = 5 58 | self.bw = bw * 1000 59 | self.nperseg = int((self.hrf.sample_rate / self.bw) * (N + 1)) 60 | self.bbw = self.hrf.sample_rate / self.nperseg 61 | 62 | print("Bin bw is {} khz, with {} segments, {} samples in the BW".format( 63 | int(self.bbw/1e3), self.nperseg, N + 1)) 64 | 65 | def set_gain_lna(self, gain): 66 | self.hrf.lna_gain = gain 67 | 68 | def set_gain_vga(self, gain): 69 | self.hrf.vga_gain = gain 70 | 71 | def amp_on(self): 72 | self.hrf.enable_amp() 73 | 74 | def amp_off(self): 75 | self.hrf.disable_amp() 76 | 77 | def get_average(self): 78 | 79 | # get the samples 80 | samples = self.hrf.read_samples(self.samples) 81 | freqs, Pxx = signal.welch( 82 | samples, fs=self.hrf.sample_rate, nperseg=self.nperseg, return_onesided=False) 83 | 84 | # # use matplotlib to estimate and plot the PSD 85 | # psd(samples, NFFT=8192, Fs=self.hrf.sample_rate / 86 | # 1e6, Fc=self.hrf.center_freq/1e6) 87 | # xlabel('Frequency (MHz)') 88 | # ylabel('Relative power (dB)') 89 | # show() 90 | 91 | # Shift frequencies by the center frequency during sample stage 92 | freqs += self.f 93 | 94 | # Use the 'power' formula for dB (10*log10(X)) 95 | # The 'np.abs(Pxx)' is there because 'Pxx' is complex-valued 96 | adB = 10 * np.log10(np.abs(Pxx)) 97 | 98 | # Parse the arrays to get just the needed ones, amplitude and samples 99 | ampsum = 0 100 | samples = 0 101 | index = 0 102 | 103 | start = self.freq - (self.bw/2) 104 | stop = self.freq + (self.bw/2) 105 | for fs in freqs: 106 | if (fs >= start and fs <= stop): 107 | ampsum += adB[index] 108 | samples += 1 109 | index += 1 110 | 111 | # calc mean 112 | average_db = ampsum / samples 113 | return average_db 114 | 115 | def fast(self): 116 | # do a fast scan, just 512k samples 117 | self.bucket(512e3) 118 | 119 | def bucket(self, s): 120 | # set the sampling bucket size 121 | self.samples = s 122 | 123 | def close(self): 124 | # release the hackrf 125 | self.hrf.close() 126 | 127 | if __name__ == "__main__": 128 | hrf = RF(0) 129 | hrf.set_freq(446000000) 130 | hrf.set_bw(50) 131 | man_level = hrf.get_average() 132 | # debug 133 | print("Frequency: 440. MHz, 200 Khz bandwidth") 134 | print("Mean level: {}".format(man_level)) 135 | 136 | -------------------------------------------------------------------------------- /imgs/145.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stdevPavelmc/rflh/172da796ce86e34d901aeb4bd4af9ab64548187f/imgs/145.png -------------------------------------------------------------------------------- /libhackrf.py: -------------------------------------------------------------------------------- 1 | # TODO: only use transfer->valid_length in callbacks 2 | # TODO: make error messages more informative 3 | 4 | from ctypes import * 5 | import logging 6 | import os 7 | import numpy as np 8 | import time 9 | 10 | try: 11 | from itertools import izip 12 | except ImportError: 13 | izip = zip 14 | 15 | path = os.path.dirname(__file__) 16 | logging.basicConfig() 17 | logger = logging.getLogger('HackRf Core') 18 | logger.setLevel(logging.DEBUG) 19 | 20 | #libhackrf = CDLL('/usr/local/lib/libhackrf.so') 21 | libhackrf = CDLL('libhackrf.so.0') 22 | 23 | def enum(*sequential, **named): 24 | enums = dict(zip(sequential, range(len(sequential))), **named) 25 | return type('Enum', (), enums) 26 | 27 | HackRfVendorRequest = enum( 28 | HACKRF_VENDOR_REQUEST_SET_TRANSCEIVER_MODE=1, 29 | HACKRF_VENDOR_REQUEST_MAX2837_WRITE=2, 30 | HACKRF_VENDOR_REQUEST_MAX2837_READ=3, 31 | HACKRF_VENDOR_REQUEST_SI5351C_WRITE=4, 32 | HACKRF_VENDOR_REQUEST_SI5351C_READ=5, 33 | HACKRF_VENDOR_REQUEST_SAMPLE_RATE_SET=6, 34 | HACKRF_VENDOR_REQUEST_BASEBAND_FILTER_BANDWIDTH_SET=7, 35 | HACKRF_VENDOR_REQUEST_RFFC5071_WRITE=8, 36 | HACKRF_VENDOR_REQUEST_RFFC5071_READ=9, 37 | HACKRF_VENDOR_REQUEST_SPIFLASH_ERASE=10, 38 | HACKRF_VENDOR_REQUEST_SPIFLASH_WRITE=11, 39 | HACKRF_VENDOR_REQUEST_SPIFLASH_READ=12, 40 | HACKRF_VENDOR_REQUEST_CPLD_WRITE=13, 41 | HACKRF_VENDOR_REQUEST_BOARD_ID_READ=14, 42 | HACKRF_VENDOR_REQUEST_VERSION_STRING_READ=15, 43 | HACKRF_VENDOR_REQUEST_SET_FREQ=16, 44 | HACKRF_VENDOR_REQUEST_AMP_ENABLE=17, 45 | HACKRF_VENDOR_REQUEST_BOARD_PARTID_SERIALNO_READ=18, 46 | HACKRF_VENDOR_REQUEST_SET_LNA_GAIN=19, 47 | HACKRF_VENDOR_REQUEST_SET_VGA_GAIN=20, 48 | HACKRF_VENDOR_REQUEST_SET_TXVGA_GAIN=21) 49 | 50 | HackRfConstants = enum( 51 | LIBUSB_ENDPOINT_IN=0x80, 52 | LIBUSB_ENDPOINT_OUT=0x00, 53 | HACKRF_DEVICE_OUT=0x40, 54 | HACKRF_DEVICE_IN=0xC0, 55 | HACKRF_USB_VID=0x1d50, 56 | HACKRF_USB_PID=0x6089) 57 | 58 | HackRfError = enum( 59 | HACKRF_SUCCESS=0, 60 | HACKRF_TRUE=1, 61 | HACKRF_ERROR_INVALID_PARAM=-2, 62 | HACKRF_ERROR_NOT_FOUND=-5, 63 | HACKRF_ERROR_BUSY=-6, 64 | HACKRF_ERROR_NO_MEM=-11, 65 | HACKRF_ERROR_LIBUSB=-1000, 66 | HACKRF_ERROR_THREAD=-1001, 67 | HACKRF_ERROR_STREAMING_THREAD_ERR=-1002, 68 | HACKRF_ERROR_STREAMING_STOPPED=-1003, 69 | HACKRF_ERROR_STREAMING_EXIT_CALLED=-1004, 70 | HACKRF_ERROR_OTHER=-9999, 71 | # Python defaults to returning none 72 | HACKRF_ERROR=None) 73 | 74 | HackRfTranscieverMode = enum( 75 | HACKRF_TRANSCEIVER_MODE_OFF=0, 76 | HACKRF_TRANSCEIVER_MODE_RECEIVE=1, 77 | HACKRF_TRANSCEIVER_MODE_TRANSMIT=2) 78 | 79 | # Data structures 80 | _libusb_device_handle = c_void_p 81 | _pthread_t = c_ulong 82 | 83 | p_hackrf_device = c_void_p 84 | 85 | class hackrf_transfer(Structure): 86 | _fields_ = [("device", p_hackrf_device), 87 | ("buffer", POINTER(c_byte)), 88 | ("buffer_length", c_int), 89 | ("valid_length", c_int), 90 | ("rx_ctx", c_void_p), 91 | ("tx_ctx", c_void_p) ] 92 | 93 | class read_partid_serialno_t(Structure): 94 | _fields_ = [("part_id", c_uint32*2), 95 | ("serial_no", c_uint32*4) ] 96 | 97 | class hackrf_device_list_t(Structure): 98 | _fields_ = [("serial_numbers", POINTER(c_char_p)), 99 | ("usb_board_ids", c_void_p), 100 | ("usb_device_index", POINTER(c_int)), 101 | ("devicecount", c_int), 102 | ("usb_devices", POINTER(c_void_p)), 103 | ("usb_devicecount", c_int) ] 104 | 105 | # 106 | #_callback = CFUNCTYPE(c_int, POINTER(hackrf_transfer)) 107 | _callback = CFUNCTYPE(c_int, POINTER(hackrf_transfer)) 108 | 109 | 110 | # extern ADDAPI int ADDCALL hackrf_init(); 111 | libhackrf.hackrf_init.restype = c_int 112 | libhackrf.hackrf_init.argtypes = [] 113 | # extern ADDAPI int ADDCALL hackrf_exit(); 114 | libhackrf.hackrf_exit.restype = c_int 115 | libhackrf.hackrf_exit.argtypes = [] 116 | # extern ADDAPI int ADDCALL hackrf_open(hackrf_device** device); 117 | libhackrf.hackrf_open.restype = c_int 118 | libhackrf.hackrf_open.argtypes = [POINTER(p_hackrf_device)] 119 | # extern ADDAPI int ADDCALL hackrf_open_by_serial 120 | # (const char* const desired_serial_number, hackrf_device** device); 121 | # TODO: check that this one works 122 | f = libhackrf.hackrf_open_by_serial 123 | f.restype = c_int 124 | f.argtypes = [POINTER(p_hackrf_device)] 125 | 126 | #extern ADDAPI int ADDCALL hackrf_device_list_open 127 | # (hackrf_device_list_t *list, int idx, hackrf_device** device); 128 | f = libhackrf.hackrf_device_list_open 129 | f.restype = c_int 130 | f.arg_types = [POINTER(hackrf_device_list_t), c_int, POINTER(p_hackrf_device)] 131 | #f.arg_types = [hackrf_device_list_t, c_int, POINTER(p_hackrf_device)] 132 | 133 | # extern ADDAPI int ADDCALL hackrf_close(hackrf_device* device); 134 | libhackrf.hackrf_close.restype = c_int 135 | libhackrf.hackrf_close.argtypes = [p_hackrf_device] 136 | 137 | # extern ADDAPI int ADDCALL hackrf_set_sample_rate(hackrf_device* 138 | # device, const double freq_hz); 139 | libhackrf.hackrf_set_sample_rate.restype = c_int 140 | libhackrf.hackrf_set_sample_rate.argtypes = [p_hackrf_device, c_double] 141 | 142 | # GAIN SETTINGS 143 | # extern ADDAPI int ADDCALL hackrf_set_amp_enable(hackrf_device* 144 | # device, const uint8_t value); 145 | libhackrf.hackrf_set_amp_enable.restype = c_int 146 | libhackrf.hackrf_set_amp_enable.argtypes = [p_hackrf_device, c_uint8] 147 | # extern ADDAPI int ADDCALL hackrf_set_lna_gain(hackrf_device* device, 148 | # uint32_t value); 149 | libhackrf.hackrf_set_lna_gain.restype = c_int 150 | libhackrf.hackrf_set_lna_gain.argtypes = [p_hackrf_device, c_uint32] 151 | # extern ADDAPI int ADDCALL hackrf_set_vga_gain(hackrf_device* device, 152 | # uint32_t value); 153 | libhackrf.hackrf_set_vga_gain.restype = c_int 154 | libhackrf.hackrf_set_vga_gain.argtypes = [p_hackrf_device, c_uint32] 155 | 156 | # START AND STOP RX 157 | # extern ADDAPI int ADDCALL hackrf_start_rx(hackrf_device* device, 158 | # hackrf_sample_block_cb_fn callback, void* rx_ctx); 159 | libhackrf.hackrf_start_rx.restype = c_int 160 | libhackrf.hackrf_start_rx.argtypes = [p_hackrf_device, _callback, c_void_p] 161 | # extern ADDAPI int ADDCALL hackrf_stop_rx(hackrf_device* device); 162 | libhackrf.hackrf_stop_rx.restype = c_int 163 | libhackrf.hackrf_stop_rx.argtypes = [p_hackrf_device] 164 | 165 | #extern ADDAPI hackrf_device_list_t* ADDCALL hackrf_device_list(); 166 | f = libhackrf.hackrf_device_list 167 | f.restype = POINTER(hackrf_device_list_t) 168 | f.argtypes = [] 169 | 170 | 171 | def hackrf_device_list(): 172 | return libhackrf.hackrf_device_list() 173 | 174 | 175 | # dictionary containing all hackrf_devices in use 176 | _hackrf_dict = dict() 177 | def get_dict(): 178 | return _hackrf_dict 179 | 180 | 181 | def read_samples_cb(hackrf_transfer): 182 | 183 | # let's access the contents 184 | c = hackrf_transfer.contents 185 | 186 | # c.device is an int representing the pointer to the hackrf device 187 | # we can get the pointer with p_hackrf_device(c.device) 188 | this_hackrf = _hackrf_dict[c.device] 189 | 190 | if len(this_hackrf.buffer) == this_hackrf.num_bytes: 191 | this_hackrf.still_sampling = False 192 | return 0 193 | 194 | # like == case, but cut down the buffer to size 195 | if len(this_hackrf.buffer) > this_hackrf.num_bytes: 196 | this_hackrf.still_sampling = False 197 | this_hackrf.buffer = this_hackrf.buffer[0:this_hackrf.num_bytes] 198 | return 0 199 | 200 | # grab the buffer data and concatenate it 201 | values = cast(c.buffer, POINTER(c_byte*c.buffer_length)).contents 202 | this_hackrf.buffer = this_hackrf.buffer + bytearray(values) 203 | 204 | #print("len(bd) = ",len(this_hackrf.buffer)) 205 | 206 | return 0 207 | 208 | rs_callback = _callback(read_samples_cb) 209 | 210 | ## extern ADDAPI int ADDCALL hackrf_start_tx(hackrf_device* device, 211 | ## hackrf_sample_block_cb_fn callback, void* tx_ctx); 212 | #libhackrf.hackrf_start_tx.restype = c_int 213 | #libhackrf.hackrf_start_tx.argtypes = [POINTER(hackrf_device), _callback, c_void_p] 214 | ## extern ADDAPI int ADDCALL hackrf_stop_tx(hackrf_device* device); 215 | #libhackrf.hackrf_stop_tx.restype = c_int 216 | #libhackrf.hackrf_stop_tx.argtypes = [POINTER(hackrf_device)] 217 | # extern ADDAPI int ADDCALL hackrf_is_streaming(hackrf_device* device); 218 | libhackrf.hackrf_is_streaming.restype = c_int 219 | libhackrf.hackrf_is_streaming.argtypes = [p_hackrf_device] 220 | ## extern ADDAPI int ADDCALL hackrf_max2837_read(hackrf_device* device, 221 | ## uint8_t register_number, uint16_t* value); 222 | #libhackrf.hackrf_max2837_read.restype = c_int 223 | #libhackrf.hackrf_max2837_read.argtypes = [ 224 | # POINTER(hackrf_device), c_uint8, POINTER(c_uint16)] 225 | ## extern ADDAPI int ADDCALL hackrf_max2837_write(hackrf_device* device, 226 | ## uint8_t register_number, uint16_t value); 227 | #libhackrf.hackrf_max2837_write.restype = c_int 228 | #libhackrf.hackrf_max2837_write.argtypes = [POINTER(hackrf_device), c_uint8, c_uint16] 229 | ## extern ADDAPI int ADDCALL hackrf_si5351c_read(hackrf_device* device, 230 | ## uint16_t register_number, uint16_t* value); 231 | #libhackrf.hackrf_si5351c_read.restype = c_int 232 | #libhackrf.hackrf_si5351c_read.argtypes = [ 233 | # POINTER(hackrf_device), c_uint16, POINTER(c_uint16)] 234 | ## extern ADDAPI int ADDCALL hackrf_si5351c_write(hackrf_device* device, 235 | ## uint16_t register_number, uint16_t value); 236 | #libhackrf.hackrf_si5351c_write.restype = c_int 237 | #libhackrf.hackrf_si5351c_write.argtypes = [POINTER(hackrf_device), c_uint16, c_uint16] 238 | ## extern ADDAPI int ADDCALL 239 | ## hackrf_set_baseband_filter_bandwidth(hackrf_device* device, const 240 | ## uint32_t bandwidth_hz); 241 | #libhackrf.hackrf_set_baseband_filter_bandwidth.restype = c_int 242 | #libhackrf.hackrf_set_baseband_filter_bandwidth.argtypes = [ 243 | # POINTER(hackrf_device), c_uint32] 244 | ## extern ADDAPI int ADDCALL hackrf_rffc5071_read(hackrf_device* device, 245 | ## uint8_t register_number, uint16_t* value); 246 | #libhackrf.hackrf_rffc5071_read.restype = c_int 247 | #libhackrf.hackrf_rffc5071_read.argtypes = [ 248 | # POINTER(hackrf_device), c_uint8, POINTER(c_uint16)] 249 | ## extern ADDAPI int ADDCALL hackrf_rffc5071_write(hackrf_device* 250 | ## device, uint8_t register_number, uint16_t value); 251 | #libhackrf.hackrf_rffc5071_write.restype = c_int 252 | #libhackrf.hackrf_rffc5071_write.argtypes = [POINTER(hackrf_device), c_uint8, c_uint16] 253 | ## extern ADDAPI int ADDCALL hackrf_spiflash_erase(hackrf_device* 254 | ## device); 255 | #libhackrf.hackrf_spiflash_erase.restype = c_int 256 | #libhackrf.hackrf_spiflash_erase.argtypes = [POINTER(hackrf_device)] 257 | ## extern ADDAPI int ADDCALL hackrf_spiflash_write(hackrf_device* 258 | ## device, const uint32_t address, const uint16_t length, unsigned char* 259 | ## const data); 260 | #libhackrf.hackrf_spiflash_write.restype = c_int 261 | #libhackrf.hackrf_spiflash_write.argtypes = [ 262 | # POINTER(hackrf_device), c_uint32, c_uint16, POINTER(c_ubyte)] 263 | ## extern ADDAPI int ADDCALL hackrf_spiflash_read(hackrf_device* device, 264 | ## const uint32_t address, const uint16_t length, unsigned char* data); 265 | #libhackrf.hackrf_spiflash_read.restype = c_int 266 | #libhackrf.hackrf_spiflash_read.argtypes = [ 267 | # POINTER(hackrf_device), c_uint32, c_uint16, POINTER(c_ubyte)] 268 | ## extern ADDAPI int ADDCALL hackrf_cpld_write(hackrf_device* device, 269 | ## unsigned char* const data, const unsigned int total_length); 270 | #libhackrf.hackrf_cpld_write.restype = c_int 271 | #libhackrf.hackrf_cpld_write.argtypes = [POINTER(hackrf_device), POINTER(c_ubyte), c_uint] 272 | ## extern ADDAPI int ADDCALL hackrf_board_id_read(hackrf_device* device, 273 | ## uint8_t* value); 274 | #libhackrf.hackrf_board_id_read.restype = c_int 275 | #libhackrf.hackrf_board_id_read.argtypes = [POINTER(hackrf_device), POINTER(c_uint8)] 276 | ## extern ADDAPI int ADDCALL hackrf_version_string_read(hackrf_device* 277 | ## device, char* version, uint8_t length); 278 | #libhackrf.hackrf_version_string_read.restype = c_int 279 | #libhackrf.hackrf_version_string_read.argtypes = [POINTER(hackrf_device), POINTER(c_char), c_uint8] 280 | # extern ADDAPI int ADDCALL hackrf_set_freq(hackrf_device* device, 281 | # const uint64_t freq_hz); 282 | libhackrf.hackrf_set_freq.restype = c_int 283 | libhackrf.hackrf_set_freq.argtypes = [p_hackrf_device, c_uint64] 284 | # 285 | ## extern ADDAPI int ADDCALL hackrf_set_freq_explicit(hackrf_device* device, 286 | ## const uint64_t if_freq_hz, const uint64_t lo_freq_hz, 287 | ## const enum rf_path_filter path);, 288 | ## libhackrf.hackrf_set_freq_explicit.restype = c_int 289 | ## libhackrf.hackrf_set_freq_explicit.argtypes = [c_uint64, 290 | ## c_uint64, ] 291 | # 292 | ## extern ADDAPI int ADDCALL 293 | ## hackrf_set_sample_rate_manual(hackrf_device* device, const uint32_t 294 | ## freq_hz, const uint32_t divider); 295 | #libhackrf.hackrf_set_sample_rate_manual.restype = c_int 296 | #libhackrf.hackrf_set_sample_rate_manual.argtypes = [ 297 | # POINTER(hackrf_device), c_uint32, c_uint32] 298 | # 299 | # extern ADDAPI int ADDCALL 300 | # hackrf_board_partid_serialno_read(hackrf_device* device, 301 | # read_partid_serialno_t* read_partid_serialno); 302 | f = libhackrf.hackrf_board_partid_serialno_read 303 | f.restype = c_int 304 | f.argtypes = [p_hackrf_device, POINTER(read_partid_serialno_t)] 305 | 306 | ## extern ADDAPI int ADDCALL hackrf_set_txvga_gain(hackrf_device* 307 | ## device, uint32_t value); 308 | #libhackrf.hackrf_set_txvga_gain.restype = c_int 309 | #libhackrf.hackrf_set_txvga_gain.argtypes = [POINTER(hackrf_device), c_uint32] 310 | ## extern ADDAPI int ADDCALL hackrf_set_antenna_enable(hackrf_device* 311 | ## device, const uint8_t value); 312 | #libhackrf.hackrf_set_antenna_enable.restype = c_int 313 | #libhackrf.hackrf_set_antenna_enable.argtypes = [POINTER(hackrf_device), c_uint8] 314 | # 315 | ## extern ADDAPI const char* ADDCALL hackrf_error_name(enum hackrf_error errcode); 316 | ## libhackrf.hackrf_error_name.restype = POINTER(c_char) 317 | ## libhackrf.hackrf_error_name.argtypes = [] 318 | # 319 | ## extern ADDAPI const char* ADDCALL hackrf_board_id_name(enum hackrf_board_id board_id); 320 | ## libhackrf.hackrf_board_id_name.restype = POINTER(c_char) 321 | ## libhackrf.hackrf_board_id_name.argtypes = [] 322 | # 323 | ## extern ADDAPI const char* ADDCALL hackrf_filter_path_name(const enum rf_path_filter path); 324 | ## libhackrf.hackrf_filter_path_name.restype = POINTER(c_char) 325 | ## libhackrf.hackrf_filter_path_name.argtypes = [] 326 | # 327 | 328 | 329 | class HackRF(object): 330 | 331 | _center_freq = 100e6 332 | _sample_rate = 20e6 333 | device_opened = False 334 | 335 | def __init__(self, device_index=0): 336 | self.open(device_index) 337 | 338 | # TODO: initialize defaults here 339 | self.disable_amp() 340 | self.set_lna_gain(16) 341 | self.set_vga_gain(16) 342 | 343 | self.buffer = bytearray() 344 | self.num_bytes = 16*262144 345 | 346 | def open(self, device_index=0): 347 | 348 | # pointer to device structure 349 | self.dev_p = p_hackrf_device(None) 350 | 351 | hdl = hackrf_device_list() 352 | result = libhackrf.hackrf_device_list_open(hdl, device_index, pointer(self.dev_p)) 353 | if result != 0: 354 | raise IOError('Error code %d when opening HackRF' % (result)) 355 | 356 | # This is how I used to do it... 357 | # Note I only pass in the dev_p here, but it worked. 358 | # But above, I have to pass in a pointer(self.dev_p) 359 | # They should both take the same thing 360 | #result = libhackrf.hackrf_open(self.dev_p) 361 | #if result != 0: 362 | # raise IOError('Error code %d when opening HackRF' % (result)) 363 | 364 | # self.dev_p.value returns the integer value of the pointer 365 | 366 | _hackrf_dict[self.dev_p.value] = self 367 | #print("self.dev_p.value = ", self.dev_p.value) 368 | 369 | self.device_opened = True 370 | 371 | def close(self): 372 | if not self.device_opened: 373 | return 374 | 375 | libhackrf.hackrf_close(self.dev_p) 376 | self.device_opened = False 377 | 378 | def __del__(self): 379 | print("Releasing the HackRF One") 380 | self.close() 381 | 382 | # sleep_time in seconds 383 | # I used to have just pass in the while loop 384 | def read_samples(self,num_samples=131072,sleep_time=0.05): 385 | 386 | num_bytes = 2*num_samples 387 | self.num_bytes = int(num_bytes) 388 | 389 | self.buffer = bytearray() 390 | 391 | # start receiving 392 | result = libhackrf.hackrf_start_rx(self.dev_p, rs_callback, None) 393 | if result != 0: 394 | raise IOError("Error in hackrf_start_rx") 395 | self.still_sampling = True # this does get called 396 | 397 | while self.still_sampling: 398 | if sleep_time: 399 | time.sleep(sleep_time) 400 | 401 | # stop receiving 402 | result = libhackrf.hackrf_stop_rx(self.dev_p) 403 | if result != 0: 404 | raise IOError("Error in hackrf_stop_rx") 405 | 406 | # convert samples to iq 407 | iq = bytes2iq(self.buffer) 408 | 409 | return iq 410 | 411 | 412 | # setting the center frequency 413 | def set_freq(self, freq): 414 | freq = int(freq) 415 | result = libhackrf.hackrf_set_freq(self.dev_p, freq) 416 | if result != 0: 417 | raise IOError('Error code %d when setting frequency to %d Hz'\ 418 | % (result, freq)) 419 | 420 | self._center_freq = freq 421 | return 422 | 423 | def get_freq(self): 424 | return self._center_freq 425 | 426 | center_freq = property(get_freq, set_freq) 427 | 428 | 429 | # sample rate 430 | def set_sample_rate(self, rate): 431 | result = libhackrf.hackrf_set_sample_rate(self.dev_p, rate) 432 | if result != 0: 433 | # TODO: make this error message better 434 | raise IOError('Sample rate set failure') 435 | self._sample_rate = rate 436 | return 437 | 438 | def get_sample_rate(self): 439 | return self._sample_rate 440 | 441 | sample_rate = property(get_sample_rate, set_sample_rate) 442 | 443 | def get_serial_no(self): 444 | return get_serial_no(self.dev_p) 445 | 446 | def enable_amp(self): 447 | result = libhackrf.hackrf_set_amp_enable(self.dev_p, 1) 448 | if result != 0: 449 | # TODO: make this a better message 450 | raise IOError("error enabling amp") 451 | return 0 452 | 453 | def disable_amp(self): 454 | result = libhackrf.hackrf_set_amp_enable(self.dev_p, 0) 455 | if result != 0: 456 | # TODO: make this a better message 457 | raise IOError("error disabling amp") 458 | return 0 459 | 460 | # rounds down to multiple of 8 (15 -> 8, 39 -> 32), etc. 461 | # internally, hackrf_set_lna_gain does the same thing 462 | # But we take care of it so we can keep track of the correct gain 463 | def set_lna_gain(self, gain): 464 | gain -= (gain % 8) # round DOWN to multiple of 8 465 | result = libhackrf.hackrf_set_lna_gain(self.dev_p, gain) 466 | if result != 0: 467 | # TODO: make this a better message 468 | raise IOError("error setting lna gain") 469 | self._lna_gain = gain 470 | # print("LNA gain set to",gain,"dB.") 471 | return 0 472 | 473 | def get_lna_gain(self): 474 | return self._lna_gain 475 | 476 | lna_gain = property(get_lna_gain, set_lna_gain) 477 | 478 | def set_vga_gain(self, gain): 479 | gain -= (gain % 2) 480 | result = libhackrf.hackrf_set_vga_gain(self.dev_p, gain) 481 | if result != 0: 482 | # TODO: make this a better message 483 | raise IOError("error setting vga gain") 484 | self._vga_gain = gain 485 | # print("VGA gain set to",gain,"dB.") 486 | return 0 487 | 488 | def get_vga_gain(self): 489 | return self._vga_gain 490 | 491 | vga_gain = property(get_vga_gain, set_vga_gain) 492 | 493 | # rx_cb_fn is a callback function (in python) 494 | def start_rx(self, rx_cb_fn): 495 | rx_cb = _callback(rx_cb_fn) 496 | result = libhackrf.hackrf_start_rx(self.dev_p, rx_cb, None) 497 | if result != 0: 498 | raise IOError("start_rx failure") 499 | 500 | def stop_rx(self): 501 | result = libhackrf.hackrf_stop_rx(self.dev_p) 502 | if result != 0: 503 | raise IOError("stop_rx failure"); 504 | 505 | 506 | 507 | # returns serial number as a string 508 | # it is too big to be a single number, so make it a string 509 | # the returned string matches the hackrf_info output 510 | def get_serial_no(dev_p): 511 | sn = read_partid_serialno_t() 512 | result = libhackrf.hackrf_board_partid_serialno_read(dev_p, sn) 513 | if result != 0: 514 | raise IOError("Error %d while getting serial number" % (result)) 515 | 516 | 517 | # convert the serial number to a string 518 | sn_str = "" 519 | for i in xrange(0,4): 520 | sni = sn.serial_no[i] 521 | if sni == 0: 522 | sn_str += "00000000" 523 | else: 524 | sn_str += hex(sni)[2:-1] 525 | 526 | return sn_str 527 | 528 | # converts byte array to iq values 529 | def bytes2iq(data): 530 | values = np.array(data).astype(np.int8) 531 | iq = values.astype(np.float64).view(np.complex128) 532 | iq /= 127.5 533 | iq -= (1 + 1j) 534 | 535 | return iq 536 | 537 | 538 | # really, user shouldn't have to call this function at all 539 | result = libhackrf.hackrf_init() 540 | if result != 0: 541 | print("error initializing the hackrf library") 542 | -------------------------------------------------------------------------------- /linux_setup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Setup script for any debian based distro (Debian, Ubuntu, Min, etc) 4 | 5 | # update package database 6 | sudo apt update 7 | 8 | # install python3 ans requisites 9 | sudo apt install -y python3 python3-pip 10 | 11 | # install rtl-sdr native support 12 | sudo apt install -y librtlsdr0 rtl-sdr librtlsdr-dev libusb-1.0-0 13 | 14 | # install python rtlsdr support 15 | pip3 install pyrtlsdr 16 | 17 | # install hackrf native support 18 | sudo apt install -y libhackrf0 libhackrf-dev hackrf 19 | 20 | # install support for hamlib (rotctld) python included 21 | sudo apt install -y libhamlib2 libhamlib-utils python3-libhamlib2 22 | 23 | # install app dependencies 24 | pip3 install matplotlib numpy scipy 25 | 26 | # end 27 | echo "Done!" -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | scipy==1.3.3 2 | pyrtlsdr==0.2.92 3 | matplotlib==3.1.2 4 | numpy==1.17.4 5 | -------------------------------------------------------------------------------- /rflh.py: -------------------------------------------------------------------------------- 1 | import time 2 | import argparse 3 | import os 4 | import matplotlib.pyplot as plt 5 | import random as rnd 6 | from math import pi 7 | from rotor import * 8 | 9 | # description 10 | parser = argparse.ArgumentParser(description='Sweep the 360o around recording the signals levels of a frequency at a given bandwidth; using rotctld and a RTL-SDR (default) or a HackRF One for spectrum sensing.') 11 | 12 | # frequency 13 | parser.add_argument( 14 | 'frequency', 15 | type=float, 16 | help='The center frequency to listen to, in MHz, "145.170" for 145.170 MHz') 17 | 18 | # -b / --bandwidth 19 | parser.add_argument( 20 | '-b ', '--bandwidth', 21 | type=int, 22 | help='The bandwidth to sample in kHz: 1-800 kHz using the RTL-SDR or 1kHz-MHz using the HackRF, 20kHz by default') 23 | 24 | # -s / --step 25 | parser.add_argument( 26 | '-s', '--step', 27 | type=int, 28 | help='Azimuth steps in degrees, 10 degrees by default, see project README.md for details.') 29 | 30 | # -u / --paused 31 | parser.add_argument( 32 | '-u', '--paused', 33 | help='Sweep mode: paused mode means move to target azimuth & take a measurement the repeat it (slow). The default is to make one full turn and do measurements on the fly (faster but may fail, read the documentation)', 34 | action="store_true") 35 | 36 | # -bs / --bucketsize 37 | parser.add_argument( 38 | '-t', '--bucketsize', 39 | type=int, 40 | help='Bucket size: how many bytes to get for processing at each sample time, 1.024 Mbytes by default (use 2^n units or it will fail) 1.024 Mbytes = 1024000') 41 | 42 | # -p / --ppm 43 | parser.add_argument( 44 | '-p', '--ppm', 45 | type=int, 46 | help='Frequency correction for you device, by default 0.0') 47 | 48 | # -q / --quiet 49 | parser.add_argument( 50 | '-q', '--quiet', 51 | help='Quiet: supress output, default: verbose', 52 | action="store_true") 53 | 54 | # -j / --just_data 55 | parser.add_argument( 56 | '-j', '--just_data', 57 | help='Don\'t generate & save the graph, default: generate & save it', 58 | action="store_true") 59 | 60 | # -n / --nofile 61 | parser.add_argument( 62 | '-n', '--nofile', 63 | help='Don\'t save the csv file, default: save it', 64 | action="store_true") 65 | 66 | # -i / --interactive 67 | parser.add_argument( 68 | '-i', '--interactive', 69 | help='Pop up a Matplotlib interactive graph with the results, default is no pop up', 70 | action="store_true") 71 | 72 | # -d / --dummy 73 | parser.add_argument( 74 | '-d', '--dummy', 75 | help='Don\'t use the rotor or the RTL-SDR or HackRF, just generate a dummy dataset and plot it; it implies --nofile; just for testing purposes', 76 | action="store_true") 77 | 78 | # -l / --lna 79 | parser.add_argument( 80 | '-l', '--lna', 81 | type=float, 82 | help='LNA gain value: 0-49.6 dB in 0.4 dB for the RTL-SDR or 0-40 dB in 8 dB steps for HackRF. Defaults: 28.0 for the RTL-SDR & 32 for the HackRF') 83 | 84 | # -v / --vga 85 | parser.add_argument( 86 | '-v', '--vga', 87 | type=int, 88 | help='VGA gain value (Only HackRF One): 0-62 in 2 units steps, 30 by default') 89 | 90 | # -a / --amp_on 91 | parser.add_argument( 92 | '-a', '--amp_on', 93 | help='Amplifier on (Only HackRF One): by default it\'s disabled; WATCH OUT! some firmware revision has this option reversed (mine has it)', 94 | action="store_true") 95 | 96 | # -o / --hackrfone 97 | parser.add_argument( 98 | '-o', '--hackrfone', 99 | help='Use a HackRF One instead the default: RTL-SDR', 100 | action="store_true") 101 | 102 | args = parser.parse_args() 103 | 104 | # args setup 105 | fq = float(args.frequency) 106 | bw = 20 107 | if args.bandwidth: 108 | bw = args.bandwidth 109 | 110 | if args.step: 111 | if args.step < 6: 112 | print("WARNING: You selected a azimuth step lower/equal than 6 degrees: most rotors can't handle that") 113 | astep = args.step 114 | else: 115 | astep = 10 116 | 117 | just_data = False 118 | if args.just_data: 119 | just_data = True 120 | 121 | quiet = False 122 | if args.quiet: 123 | quiet = True 124 | 125 | nofile = False 126 | if args.nofile: 127 | nofile = True 128 | 129 | interactive = False 130 | if args.interactive: 131 | interactive = True 132 | 133 | dummy = False 134 | if args.dummy: 135 | dummy = True 136 | 137 | lna_gain = None 138 | if args.lna: 139 | lna_gain = args.lna 140 | 141 | vga_gain = None 142 | if args.vga: 143 | vga_gain = args.vga 144 | 145 | amp_on = False 146 | if args.amp_on: 147 | amp_on = True 148 | 149 | hackrfone = False 150 | if args.hackrfone: 151 | hackrfone = True 152 | 153 | ppm = 0 154 | if args.ppm: 155 | ppm = args.ppm 156 | 157 | # bucketsize 158 | bucketsize = 1.024e6 159 | if args.bucketsize: 160 | bucketsize = args.bucketsize 161 | 162 | paused = False 163 | if args.paused: 164 | paused = True 165 | elif args.step and args.step <= 5: 166 | print("WARNING: You selected a step less than 6 degrees & fast scanning, most hardware can\'t handle that!") 167 | 168 | # conditional load of the device 169 | if hackrfone: 170 | from hrf import * 171 | if not quiet: 172 | print("Using HackRF One as RF device") 173 | else: 174 | from rtl import * 175 | if not quiet: 176 | print("Using RTL-SDR as RF device") 177 | 178 | # instantiating if not testing 179 | if not dummy: 180 | r = Rotor() 181 | rf = RF(ppm) 182 | 183 | device = 'rtl' 184 | if hackrfone: 185 | device = 'hackrf' 186 | 187 | # array that will hold the data 188 | labels = [] 189 | levels = [] 190 | f = fq * 1000000 191 | duration = 0 192 | 193 | def clean_house(): 194 | if not dummy: 195 | rf.close() 196 | r.go_to(0, 0) 197 | 198 | # All is wraped to detect Ctrl+c 199 | try: 200 | # RF setup & rotor parking 201 | if not dummy: 202 | # set HackRF 203 | rf.set_freq(f) 204 | rf.set_bw(bw) 205 | rf.bucket(bucketsize) 206 | if vga_gain != None and hackrfone: 207 | rf.set_gain_vga(vga_gain) 208 | if not quiet: 209 | print("VGA gain set to {}".format(vga_gain)) 210 | if lna_gain != None: 211 | rf.set_gain_lna(lna_gain) 212 | if not quiet: 213 | print("LNA gain set to {}".format(lna_gain)) 214 | if amp_on and hackrfone: 215 | rf.amp_on() 216 | if not quiet: 217 | print("Amp turned on!") 218 | 219 | # rotor parking advice 220 | if not quiet: 221 | print("Parking the rotor, please wait...") 222 | 223 | # rotor parking (blocking) 224 | r.set_position(0, 0) 225 | 226 | # rotor parking advice 227 | if not quiet: 228 | if not dummy: 229 | print("Parking done, starting the sweep") 230 | print("Sweep for {} Hz ({} MHz) with {} kHz of bandwidth & {} degrees of step.".format( 231 | f, f/1e6, bw, astep)) 232 | 233 | # getting time for the file 234 | dt = time.strftime("%Y%m%d_%H%M") 235 | 236 | # if dummy data 237 | if not dummy: 238 | if paused: 239 | # slow scanning 240 | tstart = time.time() 241 | for p in range(0, 360, astep): 242 | labels.append(str(p)) 243 | r.set_position(p, 0) 244 | l = rf.get_average() 245 | levels.append(l) 246 | if not quiet: 247 | print("{};{}".format(p, str(l).replace(".", ","))) 248 | 249 | tstop = time.time() 250 | else: 251 | # fast scanning 252 | a = 0 253 | at = astep 254 | tstart = time.time() 255 | # zero 256 | labels.append(str(a)) 257 | l = rf.get_average() 258 | levels.append(l) 259 | if not quiet: 260 | print("0(0);{}".format(str(l).replace(".", ","))) 261 | # start turning! 262 | r.go_to(360) 263 | while a < (360 - astep): 264 | (a, e) = r.get_position() 265 | if (at - a) < (astep / 2): 266 | # data 267 | l = rf.get_average() 268 | levels.append(l) 269 | (an, e) = r.get_position() 270 | am = (an + a) / 2 271 | labels.append(str(at)) 272 | # debug 273 | if not quiet: 274 | print("{}({});{}".format(at, am, str(l).replace(".", ","))) 275 | if (am - at) >= astep: 276 | print("ERROR!\n\nThe selected azimuth step is to small or bucket size to big, please adjust them and try again!") 277 | clean_house() 278 | sys.exit() 279 | 280 | # increment at 281 | at += astep 282 | 283 | tstop = time.time() 284 | 285 | # time elapsed 286 | duration = tstop - tstart 287 | if not quiet: 288 | print("Scan took {}:{}".format(int(duration/60), int(duration % 60))) 289 | 290 | # Create the name for the file if not told otherwise 291 | if not nofile: 292 | dfolder = os.path.join(os.getcwd(), 'data') 293 | # the data folder exists? 294 | if not os.path.exists(dfolder): 295 | os.mkdir(dfolder) 296 | else: 297 | if not os.path.isdir(dfolder): 298 | os.unlink(dfolder) 299 | os.path.mkdir(dfolder) 300 | 301 | # 20211219_2221_rtl_436.5MHz_200kHz_10o.csv 302 | savefile = "{}_{}_{}MHz_{}kHz_{}o".format(dt, device, fq, bw, astep) 303 | with open(os.path.join(dfolder, savefile + '.csv'), 'w') as f: 304 | # write header 305 | f.writelines("Degrees;dBFs\n") 306 | i = 0 307 | for v in labels: 308 | f.writelines(str(v) + ";" + str(levels[i]).replace(".", ",") + "\n") 309 | i = i + 1 310 | 311 | if not quiet: 312 | print("CSVFile: data/{}".format(savefile + ".csv")) 313 | else: 314 | # fake data 315 | rnd.seed() 316 | astep = 5 317 | units = 360/astep 318 | labels = [x for x in range(0, 360, astep)] 319 | start = rnd.randint(-1100, -600) 320 | stop = rnd.randint(start, 50) 321 | levels = [] 322 | for l in labels: 323 | levels.append(rnd.randrange(start, stop)/10.0) 324 | 325 | if not quiet and not dummy: 326 | print("Parking the rotor in the background") 327 | clean_house() 328 | 329 | # statistics 330 | margin = 0.5 331 | amin = min(levels) 332 | amax = max(levels) 333 | tmargin = abs(amax - amin) 334 | if tmargin < 1: 335 | margin = 0.5 336 | else: 337 | margin = tmargin * 0.1 338 | lmin = amin - margin 339 | lmax = amax + margin 340 | 341 | if not quiet: 342 | print("Dynamc range: {} dB, 10%: {}".format(tmargin, margin)) 343 | print("Min: {}, Max {}".format(lmin, lmax)) 344 | 345 | if not just_data: 346 | speed = 'fast' 347 | if paused: 348 | speed = 'paused' 349 | 350 | title = u"{}: ({}: {}) {:.3f} MHz, BW: {:.1f} kHz,\n{}o steps, {:.1f} dB of DNR".format( 351 | device.upper(), 352 | speed, 353 | "{}:{} min".format( 354 | int(duration / 60), 355 | int(duration % 60) 356 | ), 357 | fq, 358 | bw, 359 | astep, 360 | tmargin 361 | ) 362 | 363 | # Turn interactive plotting off 364 | plt.ioff() 365 | 366 | # create 367 | fig = plt.figure() 368 | ax = fig.add_subplot(label='title') 369 | fig.subplots_adjust(top=0.85) 370 | 371 | # Set titles for the figure and the subplot respectively 372 | fig.suptitle(title, fontsize=12, fontweight='normal') 373 | 374 | # repeat the last value to close the plot 375 | levels += levels[:1] 376 | 377 | # how many ticks/labels on the plot 378 | N = len(labels) 379 | 380 | # What will be the angle of each axis in the plot? (we divide the plot / number of variable) 381 | angles = [n / float(N) * 2 * pi for n in range(N)] 382 | # repeat the first one to close the graph 383 | angles += angles[:1] 384 | 385 | # Initialise the spider plot 386 | ax = plt.subplot(111, polar=True, label='graph') 387 | 388 | # Draw one axe per variable + add labels 389 | plt.xticks(angles, labels, color='grey', size=8) 390 | 391 | # set labels limits 392 | plt.ylim(lmin, lmax) 393 | 394 | # Plot data 395 | ax.plot(angles, levels, linewidth=1, linestyle='solid') 396 | 397 | # rotate 398 | ax.set_theta_zero_location('N') 399 | 400 | # make it clockwise 401 | ax.set_theta_direction(-1) 402 | 403 | # Fill area 404 | ax.fill(angles, levels, 'b', alpha=0.1) 405 | 406 | # save only if not dummy 407 | if not dummy and not just_data: 408 | plt.savefig( 409 | os.path.join(dfolder, savefile + '.png'), 410 | bbox_inches='tight' 411 | ) 412 | if not quiet: 413 | print("ImgFile: data/{}".format(savefile + ".png")) 414 | 415 | # Show the graph if instructed to 416 | if interactive: 417 | plt.show() 418 | 419 | except KeyboardInterrupt: 420 | print("\n\nCatching Ctrl+C: cleaning the house before leaving...") 421 | clean_house() 422 | sys.exit() 423 | -------------------------------------------------------------------------------- /rotor.conf: -------------------------------------------------------------------------------- 1 | [DEFAULT] 2 | rotor=NET 3 | 4 | [DUMMY] 5 | model=1 6 | device= 7 | options= 8 | 9 | [NET] 10 | model=2 11 | device=10.42.1.6:4533 12 | options= 13 | 14 | [GS-232A] 15 | model=601 16 | device=/dev/ttyS0 17 | options= 18 | 19 | [GS-232B] 20 | model=603 21 | device=/dev/ttyUSB0 22 | options= 23 | 24 | [ROT2PROG] 25 | model=901 26 | device=/dev/ttyUSB1 27 | options=-s 600 -C az_resolution=2 -C el_resolution=2 28 | -------------------------------------------------------------------------------- /rotor.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import Hamlib 4 | import time 5 | import subprocess 6 | from pathlib import Path 7 | from configparser import ConfigParser 8 | 9 | # default vars 10 | MINSTEP = 5.0 11 | configfile = 'rotor.conf' 12 | 13 | class Rotor(): 14 | def __init__(self): 15 | # load config and start the sub-process control if needed 16 | self.loadconfig() 17 | self.start_rotor() 18 | 19 | # limits 20 | self.MIN_AZ = 0 21 | self.MIN_EL = 0 22 | self.MAX_AZ = 360 23 | self.MAX_EL = 90 24 | 25 | def loadconfig(self): 26 | # find the correct place for the config file 27 | local = True 28 | cwd = os.getcwd() 29 | defcf = os.path.join(cwd, configfile) 30 | 31 | # load config from the rotor.conf file 32 | config = ConfigParser() 33 | if os.path.exists(defcf) and os.path.isfile(defcf): 34 | print("rotor.conf at: {}".format(defcf)) 35 | config.read(defcf) 36 | else: 37 | if local: 38 | print("Can't find the '{}' in the local directory".format(configfile)) 39 | print("Please copy & edit the rotor.conf file from the project page to this directory.") 40 | sys.exit() 41 | else: 42 | import shutils 43 | shutil.copyfile(os.path.join(sys._MEIPASS, configfile), defcf) 44 | print("No rotor config file, a new one has been created, please edit it with your particular rotor configs and try it again.") 45 | print(defcf) 46 | sys.exit() 47 | 48 | self.default = config.get('DEFAULT', 'rotor') 49 | self.model = config.get(self.default, 'model') 50 | self.device = config.get(self.default, 'device') 51 | self.options = config.get(self.default, 'options') 52 | 53 | def start_rotor(self): 54 | # Disable all debug output from Hamlib 55 | Hamlib.rig_set_debug(Hamlib.RIG_DEBUG_NONE) 56 | 57 | # Create rotor object of type net 58 | # self.rot = Hamlib.Rot(Hamlib.ROT_MODEL_NETROTCTL) 59 | self.rot = Hamlib.Rot(int(self.model)) 60 | 61 | # Setup device 62 | self.rot.set_conf("rot_pathname", self.device) 63 | 64 | # setup extra options 65 | opts = self.options.strip() 66 | if len(opts) > 0: 67 | if not (len(opt) % 2): 68 | print("Strange, options must be in pairs, trying but may fail...") 69 | 70 | pairs = [] 71 | cmds = [] 72 | s = opts.split(' ') 73 | for i in range(len(s)/2): 74 | cmd = s[i*2] 75 | data = s[i*2 + 1] 76 | if cmd == '-s': 77 | cmds.append(['serial-speed', data]) 78 | if cmd == '-C': 79 | cmds.append([data.split('=')[0], 80 | data.split('=')[1]]) 81 | 82 | for (opt, value) in cmds: 83 | self.rot.set_conf(opt, value) 84 | 85 | # Open rotor 86 | # The Python bindings for Hamlib does not return anything 87 | # so we have no knowledge if this was actually successful... 88 | self.rot.open() 89 | 90 | # get the limits from the rotor 91 | self.MIN_AZ = float(self.rot.get_conf("min_az")) 92 | self.MIN_EL = float(self.rot.get_conf("min_el")) 93 | self.MAX_AZ = float(self.rot.get_conf("max_az")) 94 | self.MAX_EL = float(self.rot.get_conf("max_el")) 95 | 96 | def set_position(self, az, elv): 97 | # check limits 98 | az = min(self.MAX_AZ, max(self.MIN_AZ, az)) 99 | elv = min(self.MAX_EL, max(self.MIN_EL, elv)) 100 | 101 | # ask postion 102 | [aaz, ael] = self.get_position() 103 | diff = az - aaz 104 | if abs(diff) <= MINSTEP: 105 | self.rot.set_position(aaz + (2 * diff), ael) 106 | time.sleep(0.25) 107 | self.rot.set_position(az, elv) 108 | 109 | while (abs(aaz - az) > 1): 110 | time.sleep(1) 111 | [aaz, ael] = self.get_position() 112 | 113 | def get_position(self): 114 | pos = self.rot.get_position() 115 | return pos 116 | 117 | def go_to(self, az, elv=0): 118 | self.rot.set_position(az, elv) 119 | 120 | def close(self): 121 | # close all connections 122 | if self.rot: 123 | self.rot.close() 124 | 125 | if __name__ == "__main__": 126 | r = Rotor() 127 | a = 0 128 | for az in range(0, 90, 10): 129 | r.set_position(az, 0) 130 | (a, e) = r.get_position() 131 | print("Azimuth, actual: {}, set: {}".format(a, az)) 132 | 133 | # park 134 | r.go_to(0, 0) 135 | r.close() 136 | -------------------------------------------------------------------------------- /rtl.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import numpy as np 3 | from time import sleep 4 | from scipy import signal 5 | from rtlsdr import RtlSdr 6 | 7 | class RF(object): 8 | def __init__(self, ppm): 9 | # rtl-sdr 10 | try: 11 | self.rtl = RtlSdr() 12 | except: 13 | print("Are you sure that there is a HackRF One connected?\nI can't find it!") 14 | sys.exit() 15 | 16 | # setup 17 | self.rtl.gain = 28.0 18 | # Warn! samples must be 2^n number, aka 2048 instead of 2k, 512 instead of 500 19 | self.rtl.sample_rate = 2.048e6 20 | if ppm != 0: 21 | self.rtl.freq_correction = ppm 22 | self.bw = 50 23 | self.f = 101500000 24 | self.freq = self.f - 0.512e6 25 | self.nperseg = 256 26 | self.bbw = 0 27 | self.samples = 1.024e6 28 | 29 | def set_freq(self, freq): 30 | ''' 31 | freq in hz 32 | We put the freq in the middle of the lower half 33 | 0----*----F----3----4 34 | ''' 35 | 36 | self.freq = freq 37 | self.f = freq + (self.rtl.sample_rate / 4) 38 | self.rtl.center_freq = self.f 39 | 40 | def set_bw(self, bw): 41 | ''' 42 | bw in khz (between 1khz and 3 Mhz) 43 | ''' 44 | 45 | # failsafe 46 | bw = int(bw) 47 | 48 | # calculate the neede nperseg to get at least N samples in the bw 49 | if (bw < 1): 50 | raise ValueError("bw must be greather than 1kHz") 51 | if (bw > 800e3): 52 | raise ValueError("bw must be lower than 800 kHz") 53 | 54 | # N is the desired samples in the bw selected 55 | N = 5 56 | self.bw = bw * 1000 57 | self.nperseg = int((self.rtl.sample_rate / self.bw) * (N + 1)) 58 | self.bbw = self.rtl.sample_rate / self.nperseg 59 | 60 | print("Bin bw is {} khz, with {} segments, {} samples in the BW".format( 61 | int(self.bbw/1e3), self.nperseg, N + 1)) 62 | 63 | def set_gain_lna(self, gain): 64 | self.rtl.gain = gain 65 | 66 | # compat option against hackrf 67 | def set_gain_vga(self, gain): 68 | return True 69 | 70 | # compat option against hackrf 71 | def amp_on(self): 72 | return True 73 | 74 | # compat option against hackrf 75 | def amp_off(self): 76 | return True 77 | 78 | def get_average(self): 79 | 80 | # get the samples 81 | samples = self.rtl.read_samples(self.samples) 82 | freqs, Pxx = signal.welch( 83 | samples, fs=self.rtl.sample_rate, nperseg=self.nperseg, return_onesided=False) 84 | 85 | # # use matplotlib to estimate and plot the PSD 86 | # psd(samples, NFFT=8192, Fs=self.rtl.sample_rate / 87 | # 1e6, Fc=self.rtl.center_freq/1e6) 88 | # xlabel('Frequency (MHz)') 89 | # ylabel('Relative power (dB)') 90 | # show() 91 | 92 | # Shift frequencies by the center frequency during sample stage 93 | freqs += self.f 94 | 95 | # Use the 'power' formula for dB (10*log10(X)) 96 | # The 'np.abs(Pxx)' is there because 'Pxx' is complex-valued 97 | adB = 10 * np.log10(np.abs(Pxx)) 98 | 99 | # Parse the arrays to get just the needed ones, amplitude and samples 100 | ampsum = 0 101 | samples = 0 102 | index = 0 103 | 104 | start = self.freq - (self.bw/2) 105 | stop = self.freq + (self.bw/2) 106 | for fs in freqs: 107 | if (fs >= start and fs <= stop): 108 | ampsum += adB[index] 109 | samples += 1 110 | index += 1 111 | 112 | # calc mean 113 | average_db = ampsum / samples 114 | return average_db 115 | 116 | def bucket(self, s): 117 | # set the sampling bucket size 118 | self.samples = s 119 | 120 | def fast(self): 121 | # set the sampling bucket size 122 | self.bucket(512e3) 123 | 124 | def close(self): 125 | # release the hackrf 126 | self.rtl.close() 127 | 128 | if __name__ == "__main__": 129 | rtl = RF(68) 130 | rtl.set_freq(145000000) 131 | rtl.set_bw(50) 132 | rtl.fast() 133 | man_level = rtl.get_average() 134 | # debug 135 | print("Frequency: 440. MHz, 200 Khz bandwidth") 136 | print("Mean level: {}".format(man_level)) 137 | 138 | --------------------------------------------------------------------------------