├── AS3935 ├── __init__.py └── AS3935_i2c_spi.py ├── AUTHORS ├── .github ├── FUNDING.yml └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── Docs └── images │ ├── Context.png │ ├── AsDiscovered.png │ ├── DiscoveryV1.2.png │ ├── DiscoveryV2.0.png │ ├── test-hardware.jpg │ ├── spi-transactions.jpg │ └── spi-clocks-verified.jpg ├── TEST ├── genTestFiles ├── storm_config.csv ├── storm_nearby_config.ini ├── storm_nearby_config.csv ├── storm_config.ini ├── storm_config.ini.dist └── testGenStorm.py ├── requirements.txt ├── isp-lightning.service ├── copyright ├── .gitignore ├── config.ini.dist ├── THEOPS.md ├── README-SPI.md ├── README.md ├── THEOPS-SPI.md └── LICENSE /AS3935/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Stephen M Moraco 2 | 3 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: ironsheep 2 | patreon: IronSheep 3 | -------------------------------------------------------------------------------- /Docs/images/Context.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ironsheep/lightning-detector-MQTT2HA-Daemon/HEAD/Docs/images/Context.png -------------------------------------------------------------------------------- /Docs/images/AsDiscovered.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ironsheep/lightning-detector-MQTT2HA-Daemon/HEAD/Docs/images/AsDiscovered.png -------------------------------------------------------------------------------- /Docs/images/DiscoveryV1.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ironsheep/lightning-detector-MQTT2HA-Daemon/HEAD/Docs/images/DiscoveryV1.2.png -------------------------------------------------------------------------------- /Docs/images/DiscoveryV2.0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ironsheep/lightning-detector-MQTT2HA-Daemon/HEAD/Docs/images/DiscoveryV2.0.png -------------------------------------------------------------------------------- /Docs/images/test-hardware.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ironsheep/lightning-detector-MQTT2HA-Daemon/HEAD/Docs/images/test-hardware.jpg -------------------------------------------------------------------------------- /Docs/images/spi-transactions.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ironsheep/lightning-detector-MQTT2HA-Daemon/HEAD/Docs/images/spi-transactions.jpg -------------------------------------------------------------------------------- /Docs/images/spi-clocks-verified.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ironsheep/lightning-detector-MQTT2HA-Daemon/HEAD/Docs/images/spi-clocks-verified.jpg -------------------------------------------------------------------------------- /TEST/genTestFiles: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | (set -x; ./testGenStorm.py --config_file storm_config.ini -w --output_file storm_config.csv) 4 | (set -x; ./testGenStorm.py --config_file storm_nearby_config.ini -w --output_file storm_nearby_config.csv) 5 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # 2 | paho-mqtt>=1.4.0 3 | wheel>=0.29.0 4 | sdnotify>=0.3.1 5 | Unidecode>=0.4.21 6 | RPi.GPIO>=0.5.11 7 | colorama>=0.4.3 8 | smbus>=1.1 9 | tzlocal>=1.3 10 | #python3-spi>=0.3.1 11 | spidev>=3.5 12 | pigpio>=1.4.6 13 | -------------------------------------------------------------------------------- /isp-lightning.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=ISP AS3935 Lightning Detector MQTT Client/Daemon 3 | Documentation=https://github.com/ironsheep/lightning-detector-MQTT2HA-Daemon 4 | After=network.target mosquitto.service 5 | 6 | [Service] 7 | Type=notify 8 | User=daemon 9 | Group=daemon 10 | WorkingDirectory=/opt/ISP-lightning-mqtt-daemon/ 11 | ExecStart=/usr/bin/python3 -u /opt/ISP-lightning-mqtt-daemon/ISP-lightning-mqtt-daemon.py 12 | StandardOutput=null 13 | #StandardOutput=syslog 14 | #SyslogIdentifier=ISPliDet 15 | StandardError=journal 16 | Environment=PYTHONUNBUFFERED=1 17 | Restart=always 18 | 19 | [Install] 20 | WantedBy=multi-user.target 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for improving the Lightning Detector MQTT2HA Daemon 4 | title: '' 5 | labels: feature request 6 | assignees: '' 7 | --- 8 | 9 | **Is your feature request related to a problem? Please describe.** 10 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 11 | 12 | **Describe the solution you'd like** 13 | A clear and concise description of what you want to happen. 14 | 15 | **Describe alternatives you've considered** 16 | A clear and concise description of any alternative solutions or features you've considered. 17 | 18 | **Additional context** 19 | Add any other context or screenshots about the feature request here. 20 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Report an issue you are experiencing with the Lightning Detector MQTT2HA Daemon 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | --- 8 | 9 | 12 | 13 | **Checklist:** 14 | 15 | - [ ] I updated to the latest version available 16 | - [ ] I double-checked my hardware connections 17 | - [ ] I checked that my MQTT broker is otherwise working 18 | 19 | **Release with the issue:** 20 | 21 | **Last working release (if known):** 22 | 23 | **Hardware, Operating System, Python version:** 24 | 25 | 28 | 29 | **Description of problem:** 30 | 31 | 34 | 35 | **Python errors shown in the logs (if applicable):** 36 | 37 | ``` 38 | 39 | ``` 40 | 41 | **Additional information:** 42 | -------------------------------------------------------------------------------- /TEST/storm_config.csv: -------------------------------------------------------------------------------- 1 | # record-nbr, time-seconds, dist_km, energy 2 | # start 00:00:00 from 63 km 3 | 1, 34.8, 63, 6902 4 | 2, 256.2, 31, 2793 5 | 3, 286.8, 27, 56328 6 | 4, 411.6, 12, 82178 7 | 5, 416.4, 12, 59017 8 | 6, 431.4, 10, 27865 9 | 7, 456.6, 6, 68101 10 | # start 00:08:36 from 0.2 km 11 | 8, 597.6, 1, 28190 12 | 9, 719.4, 1, 92540 13 | 10, 747.0, 1, 65894 14 | # start 00:12:54 from 0.2 km 15 | 11, 790.2, 1, 17366 16 | 12, 858.0, 1, 13797 17 | # start 00:15:00 from 4.6 km 18 | 13, 901.2, 1, 261101 19 | 14, 924.0, 5, 192585 20 | 15, 951.0, 6, 147252 21 | 16, 961.2, 6, 126306 22 | 17, 966.0, 6, 136969 23 | 18, 987.0, 6, 128922 24 | 19, 991.8, 6, 130571 25 | 20, 1088.4, 10, 179770 26 | 21, 1101.6, 10, 278536 27 | 22, 1130.4, 12, 253344 28 | 23, 1153.8, 12, 200018 29 | 24, 1179.0, 14, 226826 30 | 25, 1222.8, 14, 255098 31 | 26, 1241.4, 14, 124736 32 | 27, 1279.8, 17, 218934 33 | 28, 1283.4, 17, 253146 34 | 29, 1296.0, 17, 187584 35 | 30, 1305.6, 17, 127462 36 | 31, 1320.0, 17, 230014 37 | 32, 1330.2, 17, 264238 38 | # start 00:23:00 from 21.4 km 39 | 33, 1501.8, 24, 71850 40 | 34, 1507.8, 24, 10221 41 | 35, 1548.0, 27, 105506 42 | 36, 1954.2, 40, 113659 43 | 37, 1967.4, 40, 47663 44 | 38, 2308.8, 63, 73167 45 | 39, 2368.8, 63, 86431 46 | 40, 2451.6, 63, 74626 47 | -------------------------------------------------------------------------------- /copyright: -------------------------------------------------------------------------------- 1 | This project created by Stephen M Moraco on 2 | Wed Jun 17 12:43:10 MDT 2020. 3 | 4 | It was downloaded from github.com/ironsheep/lightning-detector-MQTT2HA-Daemon. 5 | 6 | Authors: 7 | 8 | Stephen M Moraco 9 | 10 | Copyright: 11 | 12 | The overall lightning-detector-MQTT2HA-Daemon project is 13 | 14 | Copyright © 2020 Iron Sheep Productions, LLC 15 | 16 | LICENSE 17 | 18 | This program is free software; you can redistribute it and/or modify 19 | it under the terms of the GNU General Public License as published by 20 | the Free Software Foundation; version 3 of the License. 21 | 22 | This program is distributed in the hope that it will be useful, but 23 | WITHOUT ANY WARRANTY; without even the implied warranty of 24 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 25 | General Public License for more details. 26 | 27 | You should have received a copy of the GNU General Public License along 28 | with this program; if not, write to the Free Software Foundation, Inc., 29 | 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. 30 | 31 | This project is: 32 | 33 | Copyright © 2020 Iron Sheep Productions, LLC 34 | 35 | and is also licensed under the GPL version 3. 36 | 37 | For a complete copy of the license, see `[LICENSE](LICENSE)'. 38 | -------------------------------------------------------------------------------- /TEST/storm_nearby_config.ini: -------------------------------------------------------------------------------- 1 | # Configuration file for testGenStorm.py 2 | # Source: https://github.com/ironsheep/lightning-detector-MQTT2HA-Daemon 3 | # 4 | # Uncomment and adapt all settings as needed. 5 | # Some settings can be configured by environment variables. 6 | # If an env variable is set, it takes precedence over settings in this file 7 | 8 | [Storm] 9 | 10 | # define the path of the storm it passes [nearby | overhead] default = overhead 11 | 12 | # storm_closest_from = %-of-storm-duration 13 | storm_closest_from = 50 14 | 15 | # storm_closest_to = %-of-storm-duration 16 | storm_closest_to = 55 17 | 18 | # storm_min_distance = km [overhead = 0, non-zero = nearby] 19 | storm_min_distance = 15 20 | 21 | # storm_max_distance = km [def = out-of-range] 22 | #storm_max_distance = 63 23 | 24 | # storm_early_duration = hh:mm 25 | storm_early_duration = 0:20 26 | 27 | # storm_middle_duration = hh:mm 28 | storm_middle_duration = 0:05 29 | 30 | # storm_late_duration = hh:mm 31 | storm_late_duration = 0:10 32 | 33 | # storm_early_strikes = # [0-n] 34 | storm_early_strikes = 15 35 | 36 | # storm_middle_strikes = # [0-n] 37 | storm_middle_strikes = 30 38 | 39 | # storm_late_strikes = # [0-n] 40 | storm_late_strikes = 10 41 | 42 | # storm_early_energy = range [0-300000] 43 | storm_early_energy = 50-5000 44 | 45 | # storm_middle_energy = range [0-300000] 46 | storm_middle_energy = 50000-280000 47 | 48 | # storm_late_energy = range [0-300000] 49 | storm_late_energy = 5000-140000 50 | 51 | -------------------------------------------------------------------------------- /TEST/storm_nearby_config.csv: -------------------------------------------------------------------------------- 1 | # record-nbr, time-seconds, dist_km, energy 2 | # start 00:00:00 from 63 km 3 | 1, 33.6, 63, 4388 4 | 2, 35.4, 63, 1562 5 | 3, 70.2, 63, 3569 6 | 4, 150.0, 63, 1632 7 | 5, 157.2, 63, 2763 8 | 6, 176.4, 63, 602 9 | 7, 187.8, 63, 2170 10 | 8, 331.8, 63, 3174 11 | 9, 763.2, 27, 4267 12 | 10, 783.6, 27, 1971 13 | 11, 784.8, 27, 383 14 | 12, 796.8, 27, 2129 15 | 13, 859.8, 24, 1991 16 | # start 00:17:30 from 15.8 km 17 | 14, 1085.4, 14, 2788 18 | # start 00:19:15 from 15.8 km 19 | 15, 1193.4, 17, 1275 20 | # start 00:20:00 from 18.1 km 21 | 16, 1215.6, 17, 193216 22 | 17, 1217.4, 17, 235867 23 | 18, 1222.2, 17, 67678 24 | 19, 1226.4, 17, 116666 25 | 20, 1228.8, 17, 65240 26 | 21, 1243.2, 20, 187997 27 | 22, 1258.2, 20, 124563 28 | 23, 1258.8, 20, 139882 29 | 24, 1267.2, 20, 61476 30 | 25, 1270.2, 20, 158555 31 | 26, 1290.6, 20, 97919 32 | 27, 1296.6, 20, 119965 33 | 28, 1304.4, 20, 91858 34 | 29, 1308.0, 20, 193141 35 | 30, 1314.6, 20, 242950 36 | 31, 1326.0, 24, 190248 37 | 32, 1332.0, 24, 57198 38 | 33, 1339.2, 24, 219527 39 | 34, 1343.4, 24, 218620 40 | 35, 1348.8, 24, 228908 41 | 36, 1350.0, 24, 252268 42 | 37, 1361.4, 24, 226993 43 | 38, 1380.0, 27, 99183 44 | 39, 1384.2, 27, 136899 45 | 40, 1400.4, 27, 73474 46 | 41, 1411.8, 27, 194601 47 | 42, 1414.8, 27, 258919 48 | 43, 1422.6, 27, 206056 49 | 44, 1439.4, 27, 171023 50 | 45, 1485.6, 31, 152427 51 | # start 00:25:00 from 33.1 km 52 | 46, 1545.0, 34, 72108 53 | 47, 1627.8, 37, 19391 54 | 48, 1646.4, 40, 56629 55 | 49, 1693.8, 40, 66652 56 | 50, 1777.2, 63, 84942 57 | 51, 1818.0, 63, 64923 58 | 52, 1923.0, 63, 13825 59 | 53, 1986.0, 63, 47678 60 | 54, 1997.4, 63, 11082 61 | 55, 2011.2, 63, 33561 62 | -------------------------------------------------------------------------------- /TEST/storm_config.ini: -------------------------------------------------------------------------------- 1 | # Configuration file for testGenStorm.py 2 | # Source: https://github.com/ironsheep/lightning-detector-MQTT2HA-Daemon 3 | # 4 | # Uncomment and adapt all settings as needed. 5 | # Some settings can be configured by environment variables. 6 | # If an env variable is set, it takes precedence over settings in this file 7 | 8 | [Storm] 9 | 10 | # define the path of the storm it passes [nearby | overhead] 11 | 12 | # percentage 1-100 - closet the storm will be (% of total time of storm) 13 | # storm_closest_from = %-of-storm-duration 14 | storm_closest_from = 20 15 | # storm_closest_to = %-of-storm-duration 16 | storm_closest_to = 30 17 | 18 | # where will the stom be relative to overhead(0km) our location 19 | # storm_min_distance = km [overhead = 0, non-zero = nearby] 20 | storm_min_distance = 0 21 | # storm_max_distance = km [def = out-of-range] 22 | #storm_max_distance = 63 23 | 24 | ### Three bands of storm (just for argument sake) [early|middle|late] 25 | # describe each band in terms of = time(duration), # detections during, range of energy seen during 26 | # 27 | # - time(duration) specs: minutes for this band in 'mm' -OR- 'hh:mm' 28 | # - # detections specs: 999 29 | # - range specs: 999999-999999 30 | 31 | 32 | # storm_early_duration = hh:mm 33 | storm_early_duration = 0:15 34 | # storm_early_strikes = # [0-n] 35 | storm_early_strikes = 12 36 | # storm_early_energy = range [0-300000] 37 | storm_early_energy = 0-100000 38 | 39 | # storm_middle_duration = hh:mm 40 | storm_middle_duration = 0:08 41 | # storm_middle_strikes = # [0-n] 42 | storm_middle_strikes = 20 43 | # storm_middle_energy = range [0-300000] 44 | storm_middle_energy = 120000-280000 45 | 46 | # storm_late_duration = hh:mm 47 | storm_late_duration = 0:20 48 | # storm_late_strikes = # [0-n] 49 | storm_late_strikes = 8 50 | # storm_late_energy = range [0-300000] 51 | storm_late_energy = 0-140000 52 | 53 | -------------------------------------------------------------------------------- /TEST/storm_config.ini.dist: -------------------------------------------------------------------------------- 1 | # Configuration file for testGenStorm.py 2 | # Source: https://github.com/ironsheep/lightning-detector-MQTT2HA-Daemon 3 | # 4 | # Uncomment and adapt all settings as needed. 5 | # Some settings can be configured by environment variables. 6 | # If an env variable is set, it takes precedence over settings in this file 7 | 8 | # define the path of the storm it passes [nearby | overhead] 9 | 10 | # percentage 1-100 - closet the storm will be (% of total time of storm) 11 | # storm_closest_from = %-of-storm-duration 12 | #storm_closest_from = 20 13 | # storm_closest_to = %-of-storm-duration 14 | #storm_closest_to = 30 15 | 16 | # where will the stom be relative to overhead(0km) our location 17 | # storm_min_distance = km [overhead = 0, non-zero = nearby] 18 | #storm_min_distance = 0 19 | # storm_max_distance = km [def = out-of-range] 20 | #storm_max_distance = 63 21 | 22 | ### Three bands of storm (just for argument sake) [early|middle|late] 23 | # describe each band in terms of = time(duration), # detections during, range of energy seen during 24 | # 25 | # - time(duration) specs: minutes for this band in 'mm' -OR- 'hh:mm' 26 | # - # detections specs: 999 27 | # - range specs: 999999-999999 28 | 29 | 30 | # storm_early_duration = hh:mm 31 | #storm_early_duration = 0:15 32 | # storm_early_strikes = # [0-n] 33 | #storm_early_strikes = 12 34 | # storm_early_energy = range [0-300000] 35 | #storm_early_energy = 0-100000 36 | 37 | # storm_middle_duration = hh:mm 38 | #storm_middle_duration = 0:08 39 | # storm_middle_strikes = # [0-n] 40 | #storm_middle_strikes = 20 41 | # storm_middle_energy = range [0-300000] 42 | #storm_middle_energy = 120000-280000 43 | 44 | # storm_late_duration = hh:mm 45 | #storm_late_duration = 0:20 46 | # storm_late_strikes = # [0-n] 47 | #storm_late_strikes = 5 48 | # storm_late_energy = range [0-300000] 49 | #storm_late_energy = 0-140000 50 | 51 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # yeah, don't version our finder stash either 7 | .DS_Store 8 | 9 | # yeah, don't set my custom file 10 | config.ini 11 | 12 | # C extensions 13 | *.so 14 | 15 | # Distribution / packaging 16 | .Python 17 | build/ 18 | develop-eggs/ 19 | dist/ 20 | downloads/ 21 | eggs/ 22 | .eggs/ 23 | lib/ 24 | lib64/ 25 | parts/ 26 | sdist/ 27 | var/ 28 | wheels/ 29 | pip-wheel-metadata/ 30 | share/python-wheels/ 31 | *.egg-info/ 32 | .installed.cfg 33 | *.egg 34 | MANIFEST 35 | 36 | # PyInstaller 37 | # Usually these files are written by a python script from a template 38 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 39 | *.manifest 40 | *.spec 41 | 42 | # Installer logs 43 | pip-log.txt 44 | pip-delete-this-directory.txt 45 | 46 | # Unit test / coverage reports 47 | htmlcov/ 48 | .tox/ 49 | .nox/ 50 | .coverage 51 | .coverage.* 52 | .cache 53 | nosetests.xml 54 | coverage.xml 55 | *.cover 56 | *.py,cover 57 | .hypothesis/ 58 | .pytest_cache/ 59 | 60 | # Translations 61 | *.mo 62 | *.pot 63 | 64 | # Django stuff: 65 | *.log 66 | local_settings.py 67 | db.sqlite3 68 | db.sqlite3-journal 69 | 70 | # Flask stuff: 71 | instance/ 72 | .webassets-cache 73 | 74 | # Scrapy stuff: 75 | .scrapy 76 | 77 | # Sphinx documentation 78 | docs/_build/ 79 | 80 | # PyBuilder 81 | target/ 82 | 83 | # Jupyter Notebook 84 | .ipynb_checkpoints 85 | 86 | # IPython 87 | profile_default/ 88 | ipython_config.py 89 | 90 | # pyenv 91 | .python-version 92 | 93 | # pipenv 94 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 95 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 96 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 97 | # install all needed dependencies. 98 | #Pipfile.lock 99 | 100 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 101 | __pypackages__/ 102 | 103 | # Celery stuff 104 | celerybeat-schedule 105 | celerybeat.pid 106 | 107 | # SageMath parsed files 108 | *.sage.py 109 | 110 | # Environments 111 | .env 112 | .venv 113 | env/ 114 | venv/ 115 | ENV/ 116 | env.bak/ 117 | venv.bak/ 118 | 119 | # Spyder project settings 120 | .spyderproject 121 | .spyproject 122 | 123 | # Rope project settings 124 | .ropeproject 125 | 126 | # mkdocs documentation 127 | /site 128 | 129 | # mypy 130 | .mypy_cache/ 131 | .dmypy.json 132 | dmypy.json 133 | 134 | # Pyre type checker 135 | .pyre/ 136 | -------------------------------------------------------------------------------- /config.ini.dist: -------------------------------------------------------------------------------- 1 | # Configuration file for lightning-detector-MQTT2HA-Daemon 2 | # Source: https://github.com/ironsheep/lightning-detector-MQTT2HA-Daemon 3 | # 4 | # Uncomment and adapt all settings as needed. 5 | # Some settings can be configured by environment variables. 6 | # If an env variable is set, it takes precedence over settings in this file 7 | 8 | [General] 9 | 10 | 11 | [Daemon] 12 | 13 | # Enable or Disable an endless execution loop (Default: true) 14 | #enabled = true 15 | 16 | 17 | [MQTT] 18 | 19 | # The hostname or IP address of the MQTT broker to connect to (Default: localhost) 20 | # Also read from the MQTT_HOSTNAME environment variable 21 | #hostname = localhost 22 | 23 | # The TCP port the MQTT broker is listening on (Default: 1883) 24 | # Also read from the MQTT_PORT environment variable 25 | #port = 1883 26 | 27 | # Maximum period in seconds between ping messages to the broker. (Default: 60) 28 | #keepalive = 60 29 | 30 | 31 | # NOTE: The MQTT topic used for this device is constructed as: 32 | # {base_topic}/{sensor_name} 33 | # 34 | # The MQTT base topic to publish the Lightning detector sensor data topics under. 35 | #base_topic = home/nodes 36 | 37 | # The MQTT name for this Lightning detector sensor 38 | #sensor_name = lightningdetector 39 | 40 | 41 | # The MQTT broker authentification credentials (Default: no authentication) 42 | # Will also read from MQTT_USERNAME and MQTT_PASSWORD environment variables 43 | #username = user 44 | #password = pwd123 45 | 46 | # Enable TLS/SSL on the connection 47 | #tls = false 48 | 49 | # Path to CA Certificate file to verify host 50 | #tls_ca_cert = 51 | 52 | # Path to TLS client auth key file 53 | #tls_keyfile = 54 | 55 | # Path to TLS client auth certificate file 56 | #tls_certfile = 57 | 58 | # Broker connection-failure recovery 59 | # Rety connection attempts [default 5] 60 | #retry_count = 5 61 | 62 | # Retry after waiting N seconds [default 30] 63 | #retry_wait_in_seconds = 30 64 | 65 | [Behavior] 66 | 67 | # This script accumulates detections into buckets (rings if you will) for this period of time [2-10] in minutes [Default: 5] 68 | #period_in_minutes = 5 69 | 70 | # This script accumulates values into [3-7] rings [Default: 5] 71 | #number_of_rings = 5 72 | 73 | # This script can report distances in miles or kilometers (mi, km) [Default: km] 74 | #distance_as = km 75 | 76 | # This script determines that a storm has ended after this period of time [10-60] in minutes [Default: 30] 77 | #end_storm_after_minutes = 30 78 | 79 | [Sensor] 80 | 81 | # decribe how your sensor is hooked up to your RPi 82 | # use values 'I2C' or 'SPI' - default is 'I2C' 83 | #sensor_attached = I2C 84 | 85 | # GPIO pin used for interrupts 86 | #intr_pin = 17 87 | 88 | # The SPI bus and device numbers come from the device file being used. 89 | # e.g., /dev/spidev0.0 would be bus=0, device=0 90 | # The defaults are 0 and 0 (SPI0 which appears at the GPIO 40pin header) 91 | #spi_bus = 0 92 | #spi_device = 0 93 | 94 | # Rev. 1 Raspberry Pis should leave bus set at 0, while rev. 2 Pis should set 95 | # bus equal to 1. The address should be changed to match the address of the 96 | # sensor. 97 | #i2c_bus = 1 98 | #i2c_address = 0x03 99 | 100 | # Value to use for your board 101 | # Internal Tuning Capacitors (from 0 to 120pF in steps of 8pf) - A value of [0-15] 102 | # run the script with a --tune paramater to determine value for your board 103 | # NOTE: this runs for 3 minutes so be patient! Then record your best value here. 104 | #tuning_capacitor = 0x1 105 | 106 | # Indoors (True) = more sensitive (can miss very strong lightnings) 107 | # Outdoors (False) = less sensitive (can miss far away lightnings) 108 | #detector_afr_gain_indoor = True 109 | 110 | #detector_noise_floor = 1 111 | 112 | # Prevent single isolated strikes from being logged => interrupts begin after 113 | # this number of strikes (def: 5, value 1,5,9,16), then are fired normally. 114 | #detector_min_strikes = 5 115 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /THEOPS.md: -------------------------------------------------------------------------------- 1 | # Theory of Operations: 2 | ## lightning-detector-MQTT2HA-Daemon 3 | 4 | ![Project Maintenance][maintenance-shield] 5 | 6 | The ISP-lightning-mqtt-daemon.py script starts up by: 7 | 8 | * Loading the set up information from the config.ini (D1) 9 | * Setting up communication with the MQTT Broker 10 | * Sends LWT details to the MQTT Broker 11 | * Sends the Home Assistant MQTT Discovery information to the Broker 12 | * Configures a keep-alive timer so it knows when to tell the broker it's still running 13 | * Configures the AS3935 Detector 14 | 15 | Lastly, it sits, forever, waiting for interrupts from the detector. Here's a rough diagram of our system: 16 | 17 | ![Our operational context](Docs/images/Context.png) 18 | 19 | Let's start by understanding a tiny bit about our dectector. (*All the way to the left of our diagram.*) 20 | 21 | --- 22 | ### The AS3935 23 | 24 | This sensor, in simple terms, listens for detections and then reports them as each is heard. It reports only a **relative strength** of the detection and **an estimate of distance** to the detection. 25 | 26 | **NOTE: there is NO directional information privided by the AS3935 sensor.** 27 | 28 | --- 29 | ### How we get to "Rings" 30 | 31 | Since we don't have direction for a given detection, we only know that it happend say 12km away from us. This could be any direction from our position which is why we think in terms of rings. 32 | 33 | This detector reports distances as one of 16 possible values: overhead, >40km away, or any of 14 possible distances between the two and these are not quite evenly spaced apart. 34 | 35 | 16 bands (rings) would be hard to show on a card and equally hard would be showing the dissimilar ring widths for each, so we decided that a user configurable number of equal-width rings would be shown on our **lovelace lightning detector card**. In the **config.ini** you'll find: 36 | 37 | ``` 38 | [Behavior] 39 | number_of_rings = { 3-7, Default: 5 } 40 | ``` 41 | --- 42 | ### A "Moving window" 43 | 44 | We also made a simplifying assumption that the most useful information to see would be, say, the most recent period of detections. So as each detection is "heard", we "remember" it. We also then "forget" any detections older than this period and we forward this new remaining set of detections via the MQTT broker to our card. Here's the setting for this window size as seen in our **config.ini**: 45 | 46 | ``` 47 | [Behavior] 48 | period_in_minutes = { 2-10, Default: 5 } 49 | ``` 50 | 51 | --- 52 | ### What about the whole storm? 53 | 54 | Yes we think the duration of the whole storm is also something useful to see on our card. The beginning of the storm is easy, this is the date/time of our first detection after we haven't seen a storm for a while. 55 | 56 | The end of the storm is a little softer, however. So we added another user-configurable setting to our **config.ini**: 57 | 58 | ``` 59 | [Behavior] 60 | end_storm_after_minutes = { 10-60, Default: 30 } 61 | ``` 62 | 63 | This script then has a timer to locate the end of the storm which we start setting when we first have a full period of no detections. Then if a detection is heard we stop the timer and start waiting for nothing again. Eventually we'll reach the end of storm timeout and we'll report that the "storm ended" to our card. 64 | 65 | --- 66 | ### Detection Accumulation 67 | 68 | Now let's look at what we do with each the detections: How do we determine storage based on user configured rings? How do we store a detection in a ring? and lastly how do we report this to our card? 69 | 70 | Our Ring Accumulator (D2 in our diagram, above) is setup at runtime once we know how many rings we have. Then we runtime-configure a lookup table for which of the 16 distances reported by the AS3935 gets put into which ring. 71 | 72 | Finally as each detection happens, we get the current time and we save the detection distance, power and timestamp into the bucket for the ring indicated by the distance. We then scan to see if there are any old detections and remove them from any bucket they are in and lastly we send all the detection data to the card via MQTT. Here's what that JSON payload looks like: 73 | 74 | ```json 75 | { 76 | "crings": { 77 | "timestamp": "2020-07-18T14:23:30-06:00", 78 | "last": "2020-07-18T14:23:30-06:00", 79 | "first": "2020-07-18T14:23:30-06:00", 80 | "storm_last": "2020-07-18T14:23:30-06:00", 81 | "storm_first": "2020-07-18T14:23:30-06:00", 82 | "end_minutes": 30, 83 | "period_minutes": 5, 84 | "units": "km", 85 | "out_of_range": 1, 86 | "ring_count": 5, 87 | "ring_width_km": 7, 88 | "ring0": { 89 | "count": 0, 90 | "distance_km": 0, 91 | "from_units": 0, 92 | "to_units": 4.9, 93 | "energy": 0 94 | }, 95 | "ring1": { 96 | "count": 0, 97 | "distance_km": 5, 98 | "from_units": 5, 99 | "to_units": 11.9, 100 | "energy": 0 101 | }, 102 | "ring2": { 103 | "count": 0, 104 | "distance_km": 12, 105 | "from_units": 12, 106 | "to_units": 18.9, 107 | "energy": 0 108 | }, 109 | "ring3": { 110 | "count": 0, 111 | "distance_km": 19, 112 | "from_units": 19, 113 | "to_units": 25.9, 114 | "energy": 0 115 | }, 116 | "ring4": { 117 | "count": 0, 118 | "distance_km": 26, 119 | "from_units": 26, 120 | "to_units": 32.9, 121 | "energy": 0 122 | }, 123 | "ring5": { 124 | "count": 0, 125 | "distance_km": 33, 126 | "from_units": 33, 127 | "to_units": 40, 128 | "energy": 0 129 | } 130 | } 131 | } 132 | ``` 133 | 134 | What are we looing at here? It's all pretty easy. For the entire ring-set we have: 135 | 136 | | key | meaning | 137 | |----------------|-------------| 138 | | `timestamp` | time when this ring-set was sent | 139 | | `last` | most recent detection in this ring-set | 140 | | `first` | oldest detection in this ring-set| 141 | | `storm_last` | most recent detection of this storm | 142 | | `storm_first` | first detection of this storm | 143 | | `end_minutes` | user configured no-detection period which will end the storm | 144 | | `period_minutes` | user configured period | 145 | | `units` | are we showing distances in 'km' or 'mi' (miles) | 146 | | `out_of_range` | # detections in this period that are beyond 40km | 147 | | `ring_count` | user configured number of rings to display | 148 | | `ring_width_km` | calculated rough width in km of each ring | 149 | 150 | Then for each ring we have: 151 | 152 | | key | meaning | 153 | |----------------|-------------| 154 | | `count` | the number of strikes in this ring | 155 | | `distance_km` | inner edge of ring distance (ignored by card) | 156 | | `from_units ` | distance of inner edge of ring (used in card label) | 157 | | `to_units ` | distance of outer edge of ring: (used in card label) | 158 | | `energy ` | average value of strikes in this ring (or did I use median value? hmmm...) | 159 | 160 | Notice that we are feeding value to the card so it doesn't have to calculate them? Yes, this is by design simply to reduce the possibilty of the two this script and the card getting out of sync with each other. 161 | 162 | --- 163 | ### Current ring-set and Past ring-set 164 | 165 | You just saw that that payload has a wrapping key called `crings`. This stands for **current ring set**. There is also the **past ring set** or `prings` reported at the and of each period. This is simply a snapshot of the crings state at the end of the 5 minute period. This is provided in case there is some interest in the ending display of the prior period of strikes for this storm. Just add a 2nd lightning detector card to your view and set the entity to the `prings` sensor and now you see both sets of rings with the new one only updating at the end of each period! These are each sent on their own MQTT Topic so let's go over what topics are maintained by this script. 166 | 167 | --- 168 | ### Topics 169 | 170 | This script posts data at various times to the following topics: 171 | 172 | | Name | Description | 173 | |-----------------|-------------| 174 | | `{base_topic}/{sensorName}/detect` | details of the latest detection | 175 | | `{base_topic}/{sensorName}/settings` | detector settings along with script settings | 176 | | `{base_topic}/{sensorName}/crings` | live status of the current period | 177 | | `{base_topic}/{sensorName}/prings` | status of the preceeding full period, updated at the end of each period. | 178 | 179 | Please refer to the [README](README.md) for the json payload examples for `~/detect` and `~/settings` topics. 180 | 181 | **NOTE:** the Lovelace lightning detector card only listens to one of `crings` or `prings` the other two topics are not used by the card. The `~/settings` topic is provided so one can easily go to `configuration -> devices -> lightning detector` and tap on the `~settings` sensor to see the currently configured settings values, all within Home Assistant. 182 | 183 | --- 184 | 185 | # Wait, there's a storm generator in here? 186 | 187 | Why yes, there is. When building this card I needed to replay a storm over, and over, and over... to get the coloring to look right to get the storm-end detection to work right, etc. 188 | 189 | In order to do this I need data that looked reasonable so i created parameterized storm generator. Create a storm .ini file with values you want, run the generator script and viola! you now have a randomized list of storm detections you can feed to this script! 190 | 191 | Refer to the [TEST](./TEST) folder in this Repo. where the script, example storm configurations and the generated files live. 192 | 193 | OK, but why did I mention this? Because in the next section you'll be wanting to feed your own data to this script to be reported to the card and that is exacly what the test subsytem of this .py script does. There is a pattern here you'll be able to use. 194 | 195 | 196 | 197 | # Thoughts about adaptation to your own detector 198 | ## (or network feed, or ...) 199 | 200 | It would be pretty easy to disable the AS3935 detector parts of this code and enable your own code that provides detections to the accumulating and reporting parts of this script. In essence you replace the front-end source of data with your own and this script will then take care of getting your data to the card in the correct format. 201 | 202 | For each detection you'd want to specify **a relative power value** to take advantage of the card ring coloring and you'd wnat to identify **the distance of the detection** as well. You'll also want to filter your detection distances so that they stay within the 40km limit of this mechanism oh, and lastly, you'll want to add a one-liner lookup to convert your distance to one of the legal sensor values since this script validates that! But again, don't worry, all of this is already shown working in the testing side of this script. The test mechanism had to do all of these same things. 203 | 204 | Lastly, feed your "detections" to the interrupt handler as if it were test data and you are good to go. 205 | 206 | --- 207 | 208 | *If you have any questions about what I've written here, file an issue and I'll respond with edits to this doc to attempt to make things more clear.* 209 | 210 | Thanks for Reading, following along. I look forward to seeing what adaptations you come up with. Please let me know when you do! 211 | 212 | ``` 213 | Stephen M. Moraco 214 | Lead developer 215 | Iron Sheep Productions, LLC. 216 | ``` 217 | 218 | If you find this kind of written explanation useful, helpful I would be honored by your helping me out for a couple of :coffee:'s or :pizza: slices! 219 | 220 | [![coffee](https://www.buymeacoffee.com/assets/img/custom_images/black_img.png)](https://www.buymeacoffee.com/ironsheep) 221 | 222 | --- 223 | 224 | Last Updated: 02 Aug 2020, 02:02 MST 225 | 226 | [maintenance-shield]: https://img.shields.io/badge/maintainer-S%20M%20Moraco%20%40ironsheepbiz-blue.svg?style=for-the-badge 227 | -------------------------------------------------------------------------------- /README-SPI.md: -------------------------------------------------------------------------------- 1 | # lightning-detector-MQTT2HA-Daemon 2 | 3 | ![Project Maintenance][maintenance-shield] 4 | 5 | [![GitHub Activity][commits-shield]][commits] 6 | 7 | [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) 8 | 9 | [![GitHub Release][releases-shield]][releases] 10 | 11 | A simple Linux python script to monitor the AS3935 Lightning Detector attached to the Raspberry Pi on which it is running and report information from the detector via MQTT to your Home Assistant installation. 12 | 13 | With this new sensor and a new **Lovelace card** (links below) you can monitor lightning presence in your local area. 14 | 15 | When this script/daemon is run it will broadcast discovery topics via MQTT decribing this new sensor to home assistant. If you have MQTT Discovery enabled then this new sensor will appear as a new device in Home Assistant: (where the "Firmware: v...." will be the version number of this script that you've just set up.) 16 | 17 | ![Discovered by Home Assistant](Docs/images/DiscoveryV2.0.png) 18 | 19 | This script can be configured to be run in **daemon mode** continously in the background as a systemd service. 20 | 21 | ## I2C or SPI 22 | 23 | **NOTE:** if you are using an I2C version of the AS3935 sensor board, please refer to [README.md](README.md) instead of this page! 24 | 25 | If you choose to use SPI, make sure that SPI is enabled on your Raspberry Pi: 26 | 27 | ```shell 28 | sudo raspi-config 29 | ``` 30 | 31 | Then go to Interfacing Options -> SPI -> Yes -> Ok. 32 | 33 | *Upon saving these changes your RPi will reboot* 34 | 35 | --- 36 | 37 | Hey, I will always appreciate your helping me out for a couple of :coffee:'s or :pizza: slices! 38 | 39 | [![coffee](https://www.buymeacoffee.com/assets/img/custom_images/black_img.png)](https://www.buymeacoffee.com/ironsheep) 40 | 41 | ## Features 42 | 43 | * Tested on Raspberry Pi's 3 & 4 with Buster - but really should work on any. 44 | * Tested with Home Assistant v0.111.0 45 | * Tested with Mosquitto broker v5.1 46 | * Data is published via MQTT 47 | * MQTT discovery messages are sent so the detector is automatically registered with Home Assistant (if MQTT discovery is enabled in your installation) 48 | * MQTT authentication support 49 | * Supports MQTT LWT so you can tell when the script is running (or if for some reason it has stopped running) 50 | * No special/root privileges are required by this mechanism 51 | * Linux daemon / systemd service, sd\_notify messages generated 52 | 53 | ## Lightning Detector Device 54 | 55 | The AS3935 Lightning Detector monitored by this script is reported as: 56 | 57 | | Name | Description | 58 | |-----------------|-------------| 59 | | `Manufacturer` | (Austria Micro Systems) ams AG | 60 | | `Model` | AS3935 | 61 | | `Name` | (fqdn) e.g., "mypi.home" | 62 | | `sofware ver` | Script Version (e.g., v1.0.0) | 63 | | `mac addr` | mac: 00:00:00:00:00:00 | 64 | | `IP addr` | eth0: 00.00.00.00 -OR- wlan0: 00.00.00.00| 65 | 66 | 67 | (The addreseses reported are those of the Raspberry Pi running this script.) 68 | 69 | ### Readings 70 | 71 | This Lightning Detector as a sensor provides the following readings: 72 | 73 | | Name | Description | 74 | |-----------------|-------------| 75 | | `timestamp` | date/time of report | 76 | | `energy` | "energy" for this report * | 77 | | `distance` | distance to storm front | 78 | | `count` | # detections since last report | 79 | 80 | \* (*from the datasheet*: If the received signal is classified as lightning, the energy is calculated. *This value is just a pure number and has no physical meaning*.) 81 | 82 | ## Prerequisites 83 | 84 | ### Detector Board 85 | 86 | You'll need an inexpensive lightning detector sensor (based on the AS3925 integrated circuit.) I picked up my [AS3925 integrated circuit on a small circuit board from Sparkfun](https://www.sparkfun.com/products/15441), but a [similar board also avail. from Amazon](https://www.amazon.com/Gravity-Lightning-Intensity-Thunderstorm-Photography/dp/B07N2M3L51?ref_=ast_sto_dp) 87 | 88 | **A NOTE of Caution!** Please watch your prices... you should be able to get one for under $30 USD*. People are trying to sell them at much higher prices. Shop around for your best price. 89 | 90 | ### MQTT Broker and Home Assistant 91 | 92 | An MQTT broker is needed as the counterpart for this daemon. 93 | 94 | MQTT is huge help in connecting different parts of your smart home and setting up of a broker is quick and easy. In many cases you've already set one up when you installed Home Assistant. 95 | 96 | You'll need to know the hostname (or IP address) of the machine where the MQTT broker is running as well as the port it is listening to. This is typically the default MQTT port (1883). 97 | *You will add this information to the config.ini for this script, as described below.* 98 | 99 | ## Connecting the AS3935 to your Raspberry Pi 100 | 101 | You'll need the AS3935 Lightning sensor to be connected via SPI to your RPi. It is possible that your model RPi supports more than one SPI bus (numbered SPI0, SPI1, SPI2, etc.) The SPI0 device is exposed on our 40pin GPIO header. Here's the pinout I use: (chose pins close together to make easy to wire up) 102 | 103 | | AS3935 Pin | Module Pin | Raspberry Pi: SPI0 | 104 | |-----------------|-------------|------------------| 105 | | 4 (GND) | GND | 25 (Ground) | 106 | | 5 (VDD) | 3V3 | 17 (3.3v) | 107 | | 8 (CS) | /CS | 24 (CE0) | 108 | | 10 (IRQ) | INT | 22 (GPIO 25) | 109 | | 11 (SCL) | SCK | 23 (SCLK) | 110 | | 12 (MISO) | MISO | 21 (MISO) | 111 | | 13 (MOSI) | MOSI | 19 (MOSI) | 112 | 113 | Make sure to change your config.ini:**sensor_attached = SPI** 114 | 115 | (You can use a different GPIO pin for the IRQ, but remember to change your config.ini:**intr_pin = 25** value to the GPIO # you choose.) 116 | 117 | ## Installation 118 | 119 | On a modern Linux system just a few steps are needed to get the daemon working. 120 | The following example shows the installation on Debian/Raspbian below the `/opt` directory: 121 | 122 | ```shell 123 | sudo apt install git python3 python3-pip python3-pigpio pigpio 124 | 125 | sudo git clone https://github.com/ironsheep/lightning-detector-MQTT2HA-Daemon /opt/ISP-lightning-mqtt-daemon 126 | 127 | cd /opt/ISP-lightning-mqtt-daemon 128 | sudo pip3 install -r requirements.txt 129 | ``` 130 | 131 | ## Configuration 132 | 133 | To match personal needs, all operational details can be configured by modifying entries within the file [`config.ini`](config.ini.dist). 134 | The file needs to be created first: 135 | 136 | ```shell 137 | cp /opt/ISP-lightning-mqtt-daemon/config.{ini.dist,ini} 138 | vim /ISP-lightning-mqtt-daemon/config.ini 139 | ``` 140 | 141 | ## Execution 142 | 143 | When you are ready to test your adjustments to the config.ini file you can start an MQTT monitor tool to see what your newly adjusted script will do. (I use [MQTTBox](http://workswithweb.com/mqttbox.html) to monitor all my MQTT testing.) 144 | 145 | Once you are ready to test, start the PiGPIOd service 146 | 147 | ```shell 148 | sudo systemctl start pigpiod.service 149 | ``` 150 | 151 | Then a test run is as easy as: 152 | 153 | ```shell 154 | python3 /opt/ISP-lightning-mqtt-daemon/ISP-lightning-mqtt-daemon.py 155 | ``` 156 | 157 | Using the command line argument `--config`, a directory where to read the config.ini file from can be specified, e.g. 158 | 159 | ```shell 160 | python3 /opt/ISP-lightning-mqtt-daemon/ISP-lightning-mqtt-daemon.py --config /opt/ISP-lightning-mqtt-daemon 161 | ``` 162 | ## Antenna Fine Tuning 163 | 164 | The AS3935 has a fine tuning adjustment setting for the 500KHz antenna. Our script has a special option we can use to determine the fine-tuning value our board needs. After running the script we then record the value in our config.ini. 165 | 166 | Run the fine tuning option using: 167 | 168 | ```shell 169 | python3 /opt/ISP-lightning-mqtt-daemon/ISP-lightning-mqtt-daemon.py --calc_tuning_cap 170 | ``` 171 | 172 | the output will look something like (yours will be different!): 173 | 174 | ```shell 175 | * Please allow a long time for this function to stop. It should take a little over 3 minutes to check test the 16 values 176 | For tuning 0x0: average frequency of 511695.239310 Hz (diff: +731.0) 177 | For tuning 0x1: average frequency of 511706.015761 Hz (diff: +731.6) 178 | For tuning 0x2: average frequency of 507383.793496 Hz (diff: +461.5) 179 | For tuning 0x3: average frequency of 507158.814087 Hz (diff: +447.4) 180 | For tuning 0x4: average frequency of 503960.562001 Hz (diff: +247.5) 181 | For tuning 0x5: average frequency of 504470.100857 Hz (diff: +279.4) 182 | For tuning 0x6: average frequency of 502103.026784 Hz (diff: +131.4) 183 | For tuning 0x7: average frequency of 500849.485221 Hz (diff: +53.1) 184 | For tuning 0x8: average frequency of 498205.778733 Hz (diff: +112.1) 185 | For tuning 0x9: average frequency of 495721.390191 Hz (diff: +267.4) 186 | For tuning 0xa: average frequency of 497672.497232 Hz (diff: +145.5) 187 | For tuning 0xb: average frequency of 494356.500465 Hz (diff: +352.7) 188 | For tuning 0xc: average frequency of 490485.394396 Hz (diff: +594.7) 189 | For tuning 0xd: average frequency of 491429.095599 Hz (diff: +535.7) 190 | For tuning 0xe: average frequency of 489151.314855 Hz (diff: +678.0) 191 | For tuning 0xf: average frequency of 490377.098284 Hz (diff: +601.4) 192 | - Your best tuning capacitor value is 0x7: which is off by +53.1 193 | ``` 194 | 195 | now you need to add the 0x7 from the last line (above) to the config.ini. Look for the **[Sensor]** section and in there add a line: 196 | 197 | ```shell 198 | tuning_capacitor = 0x7 199 | ``` 200 | 201 | (*If you have qeustions about this take a look at the `config.ini.dist` file as it shows where the new entry should be.*) 202 | 203 | Save the file, and do a quick test again to make sure the script is ok with your config change. 204 | 205 | 206 | Now you are ready to enable the detector script. 207 | 208 | ## Run as Daemon / Service 209 | 210 | You probably want to execute this script **continuously in the background**. 211 | 212 | This can be done by running it as a daemon via the Systemd service - on systemd managed systems (the **recommended** option) 213 | 214 | **NOTE:** Daemon mode must be enabled in the configuration file (default). 215 | 216 | By default the **isp-lightning.service** file indicates that the script should be run as user:group **daemon:daemon**. As this script requires access to SPI and gpio you'll want to add access to them for the daemon user as follows: 217 | 218 | ```shell 219 | # list current groups 220 | groups daemon 221 | $ daemon : daemon 222 | 223 | # add SPI, gpio if not present 224 | sudo usermod daemon -a -G spi,gpio 225 | 226 | # list current groups 227 | groups daemon 228 | $ daemon : daemon spi gpio 229 | # ^^^^^^^^ now they are present 230 | ``` 231 | 232 | Now that the 'daemon' user is configured to allow access the hardware you can setup the script to be run as a system service as follows: 233 | 234 | ```shell 235 | sudo ln -s /opt/ISP-lightning-mqtt-daemon/isp-lightning.service /etc/systemd/system/isp-lightning.service 236 | 237 | sudo systemctl daemon-reload 238 | 239 | # configure services so they start on reboot 240 | sudo systemctl enable pigpiod.service 241 | sudo systemctl enable isp-lightning.service 242 | 243 | # start services now 244 | sudo systemctl start pigpiod.service 245 | sudo systemctl start isp-lightning.service 246 | 247 | # see if services are running (ensure no start errors) 248 | sudo systemctl status pigpiod.service 249 | sudo systemctl status isp-lightning.service 250 | ``` 251 | 252 | *NOTE: we use a symbolic link 'ln -s' so that when you list the files in /etc/systemd/system the link will point back to where your project in installed. You'll see that many other packages installed on your system already do this.* 253 | 254 | ## Integration with MQTT and Home Assistant 255 | 256 | Detection values will be published to the (configurable) MQTT broker topic "`{base_topic}/{sensorName}/detect`" (e.g. `home/nodes/lightning01/detect`). 257 | 258 | An example: 259 | 260 | ```json 261 | { 262 | "last": "2020-06-19T17:26:22-06:00", 263 | "energy": 96098, 264 | "distance": 1, 265 | "count": 1 266 | } 267 | ``` 268 | 269 | This data can then be subscribed to and processed by your home assistant installation. 270 | 271 | Additionally, the detector settings along with script settings are written to: "`{base_topic}/{sensorName}/settings`" with the following fields: 272 | 273 | ```json 274 | { 275 | "settings": { 276 | "timestamp": "2020-07-10T12:52:07-06:00", 277 | "hardware": { 278 | "min_strikes": 5, 279 | "afe_inside": true, 280 | "disp_lco": false, 281 | "noise_floor": 1 282 | }, 283 | "script": { 284 | "period_in_minutes": 5, 285 | "end_storm_minutes": 30, 286 | "number_of_rings": 5, 287 | "distance_units": "km" 288 | } 289 | } 290 | } 291 | ``` 292 | 293 | Lastly, there are two additional topics published which are used to drive our new **Lovelace card**. These are: 294 | 295 | - "`{base_topic}/{sensorName}/crings`" - which posts the live status of current period, updated at each new strike 296 | 297 | - "`{base_topic}/{sensorName}/prings`" - which posts the status of the preceeding full period, updated at the end of a period 298 | 299 | ## Lovelace Card for Home Assistant 300 | 301 | Want to go further? There is a [Lovelace Lightning Detector Card](https://github.com/ironsheep/lovelace-lightning-detector-card) built specifically for visualizing this lightning data. 302 | 303 | ## Credits 304 | 305 | Thank you to "Hexalyse" for providing the starting logic for this effort. His project which i had tweeting (yes, in french) locally here in Colorado when i was first bringing up my hardware is [LightningTweeter](https://github.com/Hexalyse/LightningTweeter) 306 | 307 | Thank you to also Thomas Dietrich for providing a wonderful pattern for this project. His project, which I use and heartily recommend, is [miflora-mqtt-deamon](https://github.com/ThomDietrich/miflora-mqtt-daemon) 308 | 309 | Thank you to Eloi Codina for providing the I2C source for AS3935 I2C access [AS3935 v0.1.4](https://pypi.org/project/as3935/) 310 | 311 | ## Disclaimer and Legal 312 | 313 | ---- 314 | > *Raspberry Pi* is registered trademark of *Raspberry Pi (Trading) Ltd.* 315 | > 316 | > This project is a community project not for commercial use. 317 | > The authors will not be held responsible in the event of device failure or failure to detect any potentially damaging lightning. 318 | > 319 | > This project is in no way affiliated with, authorized, maintained, sponsored or endorsed by *Raspberry Pi (Trading) Ltd.* or any of its affiliates or subsidiaries. 320 | > 321 | > This project is also in no way affiliated with, authorized, maintained, sponsored or endorsed by *Austria Micro Systems - ams AG*, makers of the AS3935 Lightning Sensor. 322 | 323 | ---- 324 | 325 | ## License 326 | 327 | Copyright © 2020 Iron Sheep Productions, LLC. All rights reserved.
328 | Licensed under the GPL 3 License.
329 |
330 | Follow these links for more information: 331 | 332 | ### [Copyright](copyright) | [License](LICENSE) 333 | 334 | 335 | [commits-shield]: https://img.shields.io/github/commit-activity/y/ironsheep/lightning-detector-MQTT2HA-Daemon.svg?style=for-the-badge 336 | [commits]: https://github.com/ironsheep/lightning-detector-MQTT2HA-Daemon/commits/master 337 | 338 | [license-shield]: https://img.shields.io/github/license/ironsheep/lightning-detector-MQTT2HA-Daemon.svg?style=for-the-badge 339 | 340 | [maintenance-shield]: https://img.shields.io/badge/maintainer-S%20M%20Moraco%20%40ironsheepbiz-blue.svg?style=for-the-badge 341 | 342 | [releases-shield]: https://img.shields.io/github/release/ironsheep/lightning-detector-MQTT2HA-Daemon.svg?style=for-the-badge 343 | [releases]: https://github.com/ironsheep/lightning-detector-MQTT2HA-Daemon/releases 344 | 345 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # lightning-detector-MQTT2HA-Daemon 2 | 3 | ![Project Maintenance][maintenance-shield] 4 | 5 | [![GitHub Activity][commits-shield]][commits] 6 | 7 | [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) 8 | 9 | [![GitHub Release][releases-shield]][releases] 10 | 11 | A simple Linux python script to monitor the AS3935 Lightning Detector attached to the Raspberry Pi on which it is running and report information from the detector via MQTT to your Home Assistant installation. 12 | 13 | With this new sensor and a new **Lovelace card** (links below) you can monitor lightning presence in your local area. 14 | 15 | When this script/daemon is run it will broadcast discovery topics via MQTT decribing this new sensor to home assistant. If you have MQTT Discovery enabled then this new sensor will appear as a new device in Home Assistant: (where the "Firmware: v...." will be the version number of this script that you've just set up.) 16 | 17 | ![Discovered by Home Assistant](Docs/images/DiscoveryV2.0.png) 18 | 19 | This script can be configured to be run in **daemon mode** continously in the background as a systemd service. 20 | 21 | ## I2C or SPI 22 | 23 | **NOTE:** if you are using an SPI version of the AS3935 sensor board, please refer to [README-SPI.md](README-SPI.md) instead of this page! 24 | 25 | If you choose to use I2C, make sure that I2C is enabled on your Raspberry Pi: 26 | 27 | ```shell 28 | sudo raspi-config 29 | ``` 30 | 31 | Then go to Interfacing Options -> I2C -> Yes -> Ok. 32 | 33 | *Upon saving these changes your RPi will reboot* 34 | 35 | ---- 36 | 37 | If you like my work and/or this has helped you in some way then feel free to help me out for a couple of :coffee:'s or :pizza: slices! 38 | 39 | [![coffee](https://www.buymeacoffee.com/assets/img/custom_images/black_img.png)](https://www.buymeacoffee.com/ironsheep) 40 | 41 | ---- 42 | 43 | ## Features 44 | 45 | * Tested on Raspberry Pi's 3 & 4 with Buster - but really should work on any. 46 | * Tested with Home Assistant v0.111.0 47 | * Tested with Mosquitto broker v5.1 48 | * Data is published via MQTT 49 | * MQTT discovery messages are sent so the detector is automatically registered with Home Assistant (if MQTT discovery is enabled in your installation) 50 | * MQTT authentication support 51 | * Supports MQTT LWT so you can tell when the script is running (or if for some reason it has stopped running) 52 | * No special/root privileges are required by this mechanism 53 | * Linux daemon / systemd service, sd\_notify messages generated 54 | 55 | ## Lightning Detector Device 56 | 57 | The AS3935 Lightning Detector monitored by this script is reported as: 58 | 59 | | Name | Description | 60 | |-----------------|-------------| 61 | | `Manufacturer` | (Austria Micro Systems) ams AG | 62 | | `Model` | AS3935 | 63 | | `Name` | (fqdn) e.g., "mypi.home" | 64 | | `sofware ver` | Script Version (e.g., v1.0.0) | 65 | | `mac addr` | mac: 00:00:00:00:00:00 | 66 | | `IP addr` | eth0: 00.00.00.00 -OR- wlan0: 00.00.00.00| 67 | 68 | 69 | (The addreseses reported are those of the Raspberry Pi running this script.) 70 | 71 | ### Readings 72 | 73 | This Lightning Detector as a sensor provides the following readings: 74 | 75 | | Name | Description | 76 | |-----------------|-------------| 77 | | `timestamp` | date/time of report | 78 | | `energy` | "energy" for this report * | 79 | | `distance` | distance to storm front | 80 | | `count` | # detections since last report | 81 | 82 | 83 | 84 | \* (*from the datasheet*: If the received signal is classified as lightning, the energy is calculated. *This value is just a pure number and has no physical meaning*.) 85 | 86 | ## Prerequisites 87 | 88 | ### Detector Board 89 | 90 | You'll need an inexpensive lightning detector sensor (based on the AS3925 integrated circuit.) I picked up my [AS3925 integrated circuit on a small circuit board from Sparkfun](https://www.sparkfun.com/products/15441), but a [similar board also avail. from Amazon](https://www.amazon.com/Gravity-Lightning-Intensity-Thunderstorm-Photography/dp/B07N2M3L51?ref_=ast_sto_dp) 91 | 92 | **A NOTE of Caution!** Please watch your prices... you should be able to get one for under $30 USD*. People are trying to sell them at much higher prices. Shop around for your best price. 93 | 94 | ### MQTT Broker and Home Assistant 95 | 96 | An MQTT broker is needed as the counterpart for this daemon. 97 | 98 | MQTT is huge help in connecting different parts of your smart home and setting up of a broker is quick and easy. In many cases you've already set one up when you installed Home Assistant. 99 | 100 | You'll need to know the hostname (or IP address) of the machine where the MQTT broker is running as well as the port it is listening to. This is typically the default MQTT port (1883). 101 | *You will add this information to the config.ini for this script, as described below.* 102 | 103 | ## Connecting the AS3935 to your Raspberry Pi 104 | 105 | You'll need the AS3935 Lightning sensor to be connected (via I2C for now) to your RPi. It is possible that your model RPi supports more than one I2C bus (numbered I2C0, I2C1, I2C2, etc.) The I2C1 device is exposed on our 40pin GPIO header for general use while I2C0 is generally used for a piHat EEPROM. Here's the pinout I use: (chose pins close together to make easy to wire up) 106 | 107 | 108 | | AS3935 Pin | Module Pin | Raspberry Pi: I2C1 | 109 | |-----------------|------------|------------------| 110 | | 4 (GND) | GND | 9 (Ground) | 111 | | 5 (VDD) | 3V3 | 1 (3.3v) | 112 | | 10 (IRQ) | INT | 11 (GPIO 17) | 113 | | 11 (I2CL) | SCL | 5 (SCL) | 114 | | 13 (I2CD) | SDA / MOSI | 3 (SDA) | 115 | 116 | Make sure that if **sensor_attached = ...** in your config.ini is uncommented that it is set to I2C! If it is commented out this script defaults to I2C. 117 | 118 | (You can use a different GPIO pin for the IRQ, but remember to change your config.ini:**intr_pin = 17** value to the GPIO # you choose.) 119 | 120 | ## Installation 121 | 122 | On a modern Linux system just a few steps are needed to get the daemon working. 123 | The following example shows the installation on Debian/Raspbian below the `/opt` directory: 124 | 125 | ```shell 126 | sudo apt install git python3 python3-pip python3-pigpio pigpio 127 | 128 | sudo git clone https://github.com/ironsheep/lightning-detector-MQTT2HA-Daemon /opt/ISP-lightning-mqtt-daemon 129 | 130 | cd /opt/ISP-lightning-mqtt-daemon 131 | sudo pip3 install -r requirements.txt 132 | ``` 133 | 134 | ## Configuration 135 | 136 | To match personal needs, all operational details can be configured by modifying entries within the file [`config.ini`](config.ini.dist). 137 | The file needs to be created first: 138 | 139 | ```shell 140 | cp /opt/ISP-lightning-mqtt-daemon/config.{ini.dist,ini} 141 | vim /ISP-lightning-mqtt-daemon/config.ini 142 | ``` 143 | 144 | ## Execution 145 | 146 | When you are ready to test your adjustments to the config.ini file you can start an MQTT monitor tool to see what your newly adjusted script will do. (I use [MQTTBox](http://workswithweb.com/mqttbox.html) to monitor all my MQTT testing.) 147 | 148 | Once you are ready to test, start the PiGPIOd service 149 | 150 | ```shell 151 | sudo systemctl start pigpiod.service 152 | ``` 153 | 154 | Then a test run is as easy as: 155 | 156 | ```shell 157 | python3 /opt/ISP-lightning-mqtt-daemon/ISP-lightning-mqtt-daemon.py 158 | ``` 159 | 160 | Using the command line argument `--config`, a directory where to read the config.ini file from can be specified, e.g. 161 | 162 | ```shell 163 | python3 /opt/ISP-lightning-mqtt-daemon/ISP-lightning-mqtt-daemon.py --config /opt/ISP-lightning-mqtt-daemon 164 | ``` 165 | 166 | ## Antenna Fine Tuning 167 | 168 | The AS3935 has a fine tuning adjustment setting for the 500KHz antenna. Our script has a special option we can use to determine the fine-tuning value our board needs. After running the script we then record the value in our config.ini. 169 | 170 | Run the fine tuning option using: 171 | 172 | ```shell 173 | python3 /opt/ISP-lightning-mqtt-daemon/ISP-lightning-mqtt-daemon.py --calc_tuning_cap 174 | ``` 175 | 176 | the output will look something like (yours will be different!): 177 | 178 | ```shell 179 | * Please allow a long time for this function to stop. It should take a little over 3 minutes to check test the 16 values 180 | For tuning 0x0: average frequency of 511695.239310 Hz (diff: +731.0) 181 | For tuning 0x1: average frequency of 511706.015761 Hz (diff: +731.6) 182 | For tuning 0x2: average frequency of 507383.793496 Hz (diff: +461.5) 183 | For tuning 0x3: average frequency of 507158.814087 Hz (diff: +447.4) 184 | For tuning 0x4: average frequency of 503960.562001 Hz (diff: +247.5) 185 | For tuning 0x5: average frequency of 504470.100857 Hz (diff: +279.4) 186 | For tuning 0x6: average frequency of 502103.026784 Hz (diff: +131.4) 187 | For tuning 0x7: average frequency of 500849.485221 Hz (diff: +53.1) 188 | For tuning 0x8: average frequency of 498205.778733 Hz (diff: +112.1) 189 | For tuning 0x9: average frequency of 495721.390191 Hz (diff: +267.4) 190 | For tuning 0xa: average frequency of 497672.497232 Hz (diff: +145.5) 191 | For tuning 0xb: average frequency of 494356.500465 Hz (diff: +352.7) 192 | For tuning 0xc: average frequency of 490485.394396 Hz (diff: +594.7) 193 | For tuning 0xd: average frequency of 491429.095599 Hz (diff: +535.7) 194 | For tuning 0xe: average frequency of 489151.314855 Hz (diff: +678.0) 195 | For tuning 0xf: average frequency of 490377.098284 Hz (diff: +601.4) 196 | - Your best tuning capacitor value is 0x7: which is off by +53.1 197 | ``` 198 | 199 | now you need to add the 0x7 from the last line (above) to the config.ini. Look for the [Sensor] section and in there add a line: 200 | 201 | ```shell 202 | tuning_capacitor = 0x7 203 | ``` 204 | 205 | (*If you have qeustions about this take a look at the `config.ini.dist` file as it shows where the new entry should be.*) 206 | 207 | Save the file, and do a quick test again to make sure the script is ok with your config change. 208 | 209 | 210 | Now you are ready to enable the detector script. 211 | 212 | ## Run as Daemon / Service 213 | 214 | You probably want to execute this script **continuously in the background**. 215 | 216 | This can be done by running it as a daemon via the Systemd service - on systemd managed systems (the **recommended** option) 217 | 218 | **NOTE:** Daemon mode must be enabled in the configuration file (default). 219 | 220 | By default the **isp-lightning.service** file indicates that the script should be run as user:group **daemon:daemon**. As this script requires access to i2c and gpio you'll want to add access to them for the daemon user as follows: 221 | 222 | ```shell 223 | # list current groups 224 | groups daemon 225 | $ daemon : daemon 226 | 227 | # add i2c, gpio if not present 228 | sudo usermod daemon -a -G i2c,gpio 229 | 230 | # list current groups 231 | groups daemon 232 | $ daemon : daemon i2c gpio 233 | # ^^^^^^^^ now they are present 234 | ``` 235 | 236 | Now that the 'daemon' user is configured to allow access the hardware you can setup the script to be run as a system service as follows: 237 | 238 | ```shell 239 | sudo ln -s /opt/ISP-lightning-mqtt-daemon/isp-lightning.service /etc/systemd/system/isp-lightning.service 240 | 241 | sudo systemctl daemon-reload 242 | 243 | # configure services so they start on reboot 244 | sudo systemctl enable pigpiod.service 245 | sudo systemctl enable isp-lightning.service 246 | 247 | # start services now 248 | sudo systemctl start pigpiod.service 249 | sudo systemctl start isp-lightning.service 250 | 251 | # see if services are running (ensure no start errors) 252 | sudo systemctl start pigpiod.service 253 | sudo systemctl status isp-lightning.service 254 | ``` 255 | 256 | *NOTE: we use a symbolic link 'ln -s' so that when you list the files in /etc/systemd/system the link will point back to where your project in installed. You'll see that many other packages installed on your system already do this.* 257 | 258 | ## Integration with MQTT and Home Assistant 259 | 260 | Detection values will be published to the (configurable) MQTT broker topic "`{base_topic}/{sensorName}/detect`" (e.g. `home/nodes/lightning01/detect`). 261 | 262 | An example: 263 | 264 | ```json 265 | { 266 | "last": "2020-06-19T17:26:22-06:00", 267 | "energy": 96098, 268 | "distance": 1, 269 | "count": 1 270 | } 271 | ``` 272 | 273 | This data can then be subscribed to and processed by your home assistant installation. 274 | 275 | Additionally, the detector settings along with script settings are written to: "`{base_topic}/{sensorName}/settings`" with the following fields: 276 | 277 | ```json 278 | { 279 | "settings": { 280 | "timestamp": "2020-07-10T12:52:07-06:00", 281 | "hardware": { 282 | "min_strikes": 5, 283 | "afe_inside": true, 284 | "disp_lco": false, 285 | "noise_floor": 1 286 | }, 287 | "script": { 288 | "period_in_minutes": 5, 289 | "end_storm_minutes": 30, 290 | "number_of_rings": 5, 291 | "distance_units": "km" 292 | } 293 | } 294 | } 295 | ``` 296 | 297 | Lastly, there are two additional topics published which are used to drive our new **Lovelace card**. These are: 298 | 299 | - "`{base_topic}/{sensorName}/crings`" - which posts the live status of current period, updated at each new strike 300 | - "`{base_topic}/{sensorName}/prings`" - which posts the status of the preceeding full period, updated at the end of a period 301 | 302 | ## Lovelace Card for Home Assistant 303 | 304 | Want to go further? There is a [Lovelace Lightning Detector Card](https://github.com/ironsheep/lovelace-lightning-detector-card) built specifically for visualizing this lightning data. 305 | 306 | ## Credits 307 | 308 | Thank you to "Hexalyse" for providing the starting logic for this effort. His project which i had tweeting (yes, in french) locally here in Colorado when i was first bringing up my hardware is [LightningTweeter](https://github.com/Hexalyse/LightningTweeter) 309 | 310 | Thank you to also Thomas Dietrich for providing a wonderful pattern for this project. His project, which I use and heartily recommend, is [miflora-mqtt-deamon](https://github.com/ThomDietrich/miflora-mqtt-daemon) 311 | 312 | Thank you to Eloi Codina for providing the I2C source for AS3935 I2C access [AS3935 v0.1.4](https://pypi.org/project/as3935/) 313 | 314 | ## Disclaimer and Legal 315 | 316 | ---- 317 | 318 | > *Raspberry Pi* is registered trademark of *Raspberry Pi (Trading) Ltd.* 319 | > 320 | > This project is a community project not for commercial use. 321 | > The authors will not be held responsible in the event of device failure or failure to detect any potentially damaging lightning. 322 | > 323 | > This project is in no way affiliated with, authorized, maintained, sponsored or endorsed by *Raspberry Pi (Trading) Ltd.* or any of its affiliates or subsidiaries. 324 | > 325 | > This project is also in no way affiliated with, authorized, maintained, sponsored or endorsed by *Austria Micro Systems - ams AG*, makers of the AS3935 Lightning Sensor. 326 | 327 | ---- 328 | 329 | ## License 330 | 331 | Copyright © 2020 Iron Sheep Productions, LLC. All rights reserved.
332 | Licensed under the GPL 3 License.
333 |
334 | Follow these links for more information: 335 | 336 | ### [Copyright](copyright) | [License](LICENSE) 337 | 338 | 339 | [commits-shield]: https://img.shields.io/github/commit-activity/y/ironsheep/lightning-detector-MQTT2HA-Daemon.svg?style=for-the-badge 340 | [commits]: https://github.com/ironsheep/lightning-detector-MQTT2HA-Daemon/commits/master 341 | 342 | [license-shield]: https://img.shields.io/github/license/ironsheep/lightning-detector-MQTT2HA-Daemon.svg?style=for-the-badge 343 | 344 | [maintenance-shield]: https://img.shields.io/badge/maintainer-S%20M%20Moraco%20%40ironsheepbiz-blue.svg?style=for-the-badge 345 | 346 | [releases-shield]: https://img.shields.io/github/release/ironsheep/lightning-detector-MQTT2HA-Daemon.svg?style=for-the-badge 347 | [releases]: https://github.com/ironsheep/lightning-detector-MQTT2HA-Daemon/releases 348 | 349 | -------------------------------------------------------------------------------- /THEOPS-SPI.md: -------------------------------------------------------------------------------- 1 | # Researching SPI support for AS3935 2 | ## lightning-detector-MQTT2HA-Daemon 3 | 4 | ![Project Maintenance][maintenance-shield] 5 | 6 | This project supports both I2C and SPI forms of communication with the ASE935 Lightning Detector chip. While there is good Python library support for I2C, interacting with a SPI peripheral is more of a "roll-your-own" effort. This is why I'm writing this "*here's what I needed do to interact with the AS3935 via SPI*" document. 7 | 8 | I'll try to keep this short, presenting essential elements to understanding. 9 | 10 | ## Preparing to SPI 11 | 12 | To interact iwth a SPI attached device you'll have to do some learning about the device itself. 13 | 14 | You'll need to find out first about our AS3935: 15 | 16 | | AS3935 SPI Questions | 17 | | ---------------------| 18 | | Maximum SPI Clock rate of the device 19 | | Polarity of the SCLK signal 20 | | Which edge [rising/falling] of the Clock the data is sampled 21 | | Number of bits in the SPI word (8 for most of the devices) 22 | | Style of Write transaction(s) the device wants/supports 23 | | Style of Read transaction(s) the device wants/supports 24 | 25 | ...and then about about our RPi: 26 | 27 | | Raspberry Pi (RPi) SPI Questions | 28 | | ---------------------| 29 | | Maximum SPI Clock rate of our RPi hardware 30 | | How do we get to the SPI0 device on the RPi 31 | 32 | 33 | I'll go into what we learned for each of this items in this Document. The last two of the AS3935 items are where you'll be deciding how you will need to use the underlying SPIDEV library to get reads/writes to work. 34 | 35 | ## Reading the AS3935 Datasheet with intent 36 | 37 | The [AS3935 Datasheet](https://cdn.sparkfun.com/assets/learn_tutorials/9/2/1/AS3935_Datasheet_EN_v2.pdf) is where we find our SPI configuration specifics. When you are starting work with a new device it is good practice to read through the datasheet for the device before you start. This will give you an overall feel for how the device works and for what information you have at hand. You will often find suggestions for best practices to use when interacting with the device. Ok, enough general info., let's get to finding what we need. 38 | 39 | Since we are looking for how to configure our SPI bus let's go strait to the section entitled "**Serial Peripheral Interface (SPI)**" (*middle of Pg 20 in the PDF linked above.*) 40 | 41 | The first thing we find is that our AS3935 Maximum clock freq. is 2Mhz. So we need to make sure we stay at 2Mhz or something lower. *NOTE* also that there's a warning about frequencies around the 500kHz resonant frequency of our detector antenna so we should probably stay well above this frequency as well. 42 | 43 | In the next section entitled "**SPI Command Structure**" we start learning about our commands. but as we are getting to that, we see something significant! 44 | 45 | ``` 46 | An SPI command consists of two bytes in series with the data being sampled on 47 | the falling edge of SCLK (CPHA=1) 48 | ``` 49 | 50 | We then find out that this device supports two types of commands: Read and Write. This is pretty logical. They also call out a specific form of write called a "Direct Write" which we'll learn more about later in this section. 51 | 52 | The device registers are numbered from 0x00 to 0x3B. 53 | 54 | The AS3935 SPI write can be seen in "**Figure 28: SPI Page Write**" (*bottom of Pg 22 in the PDF linked above.*) We see here that this is a simple consecutive write of N bytes with the first byte specifying the starting address to be written with subsequent bytes being written to the start+0, start+1, start+2, ... locations. 55 | 56 | Next, we see the AS3935 SPI read in "**Figure 29: SPI Read Byte**" (*middle of Pg 23 in the PDF linked above.*) Here we see that we are to write a byte and then read a byte which shows up immediately after our write. This is where our spidev documentation kind of breaks down as we are trying to learn how to code this. But we'll address how to handle this shortly. 57 | 58 | Lastly, in the next section entitled "**Send Direct Command Byte**" (*still on page 23*) we meet the aforementioned "Direct Write" command. Really all this amounts to is that we are writing a special fixed value to one of two specific registers to cause special device functions to occur. This will fold into our earlier write command without really doing anything special. Noted. 59 | 60 | Well, we've reached the end of the SPI section of our datasheet so let's fill in what we know: 61 | 62 | Here's our updated list so far: 63 | 64 | | AS3935 SPI Questions | What we've Learned | 65 | | ---------------------|---------------------| 66 | | Maximum SPI Clock rate of the device | 2MHz 67 | | -> Special note: We should avoid 500kHz | 500KHz < (our SCLK value) < 2MHz 68 | | Polarity of the SCLK signal | not given, use default: (CPOL=0) 69 | | Which edge [rising/falling] of the Clock the data is sampled| Falling edge: (CPHA=1) 70 | | Number of bits in the SPI word | not given, use default: 8-bits 71 | | Style of Write transaction(s) the device wants/supports | write {value(s)} starting at {address} 72 | | Style of Read transaction(s) the device wants/supports | read {value(s)} starting from {address} 73 | 74 | Let's move on to studying the RPi. 75 | 76 | 77 | ## Researching our Host (the RPi) 78 | 79 | Now we need to learn about the SPI subsytem of the RPi. For this let's refer to the [SPI section](https://www.raspberrypi.org/documentation/hardware/raspberrypi/spi/README.md) of the Official Doumentation. By reading this page we learn that SPI is not enabled by default and the preferred way to enable it is to run `sudo raspi-config` and enable the SPI hardware. We then see that once enabled, our SPI device will show up as `/dev/spidev0.0`. 80 | 81 | In the section entitled "**Hardware**" we learn that the Standard Master mode is enabled by default. Good, this is what we'll need. 82 | 83 | Then, further down we find the section entitled "**Chip Select** but this appears to be for a DMA mode so doesn't appear to help us. We know our device requires that CS be driven low, but we've no info in the docs that inform us, so far. 84 | 85 | So let's move to the section below here entitled "**Speed**" *(this is the 2nd of two sections with this title!).* 86 | 87 | Here is where we find what we are looking for. The maximum speed supported by the driver is 125.0 MHz! 88 | 89 | Let's review what we've learned about our RPi: 90 | 91 | | Raspberry Pi (RPi) SPI Questions | What we've Learned | 92 | | ---------------------|---------------------| 93 | | Maximum SPI Clock rate of our RPi hardware | 125.0 MHz (*well above our chip limit of 2MHz*) 94 | | How do we get to the SPI0 device on the RPi | SPI0 is found at `/dev/spidev0.0` 95 | 96 | This completes our hardware fact-finding, now we need to figure out how we'll need to interact with the spidev API. 97 | 98 | ## Interpreting our need vs. the spidev API 99 | 100 | The spidev python library interface info is found as [spidev - PyPl](https://pypi.org/project/spidev/) We seems to offer a lot of setup specifics but we need to figure out reads and writes! 101 | 102 | Spidev reads and writes are: 103 | 104 | | spidev method | Description | 105 | | ---------------------|---------------------| 106 | | readbytes(n) | Read n bytes from SPI device. | 107 | | writebytes(list of values) | Writes a list of values to SPI device. | 108 | | writebytes2(list of values) | Similar to writebytes but accepts arbitrary large lists | 109 | | xfer(list of values [, speed_hz, delay_usec, bits_per_word]) | Performs an SPI transaction. Chip-select should be released and reactivated between blocks. Delay specifies the delay in usec between blocks. | 110 | | xfer2(list of values [, speed_hz, delay_usec, bits_per_word]) | Performs an SPI transaction. Chip-select should be held active between blocks. | 111 | | xfer3(list of values [, speed_hz, delay_usec, bits_per_word]) | Similar to xfer2 but accepts arbitrary large lists. | 112 | 113 | Geez, oddly enough we are missing a key piece of data on this page. So i had to do more research. New search term "**spidev documents**" - and i ran accross this seemingly platform specific doc. [SpiDev Documentation](https://www.sigmdel.ca/michel/ha/rpi/dnld/draft_spidev_doc.pdf) that had the clue I needed. I found that the xfer(), xfer2() and xfer3() methods have a return value! 114 | 115 | And there's one more fact to remember with SPI devices. The master provides the clock so the slave device can complete its work! This means that for our AS3935 which provides bytes after we send the address from which to read that we must supply clocks for each of the bits of the data bytes so the slave can write the values for the master to read! To state this another way we need to send pad bytes (we don't care about their value) within the xfer-write so that the slave can return the desired values! 116 | 117 | So, now writing read/write is going to be fairly easy, well... sortof: 118 | 119 | | method need | in terms of spidev API | 120 | | ---------------------|---------------------| 121 | | write {value(s)} starting at {address} | writebytes([address, value]) | 122 | | read {value(s)} starting from {address} | bytesRead = xfer(address, {place-holder-bytes}) 123 | 124 | Ok this is our plan. But what does it all look like in python? 125 | 126 | 127 | ## What we've learned - realized as spidev API calls 128 | 129 | I'll pull exerpts from the underlying class objects this project uses. 130 | 131 | Here's the configuration code I use: 132 | 133 | ```python 134 | from AS3935.AS3935_i2c_spi import AS3935_SPI 135 | 136 | # note: spi_device=0, spi_bus=0 matching /dev/spidev0.0 137 | 138 | detector = AS3935_SPI(interrupt_pin, spi_device, spi_bus) 139 | detector.max_speed_hz(1250000) # 1,250,000 Hz (1.25 MHz) 140 | detector.mode(0b01) # [CPOL=0|CPHA=1] per AS3935 doc. 141 | ``` 142 | 143 | In this example you see the selection of spi device and bus matching so the code selects the SPI0 device. You see me selecting 1.25Mhz as the SCLK which is > 500KHz and < our 2MHz upper limit. You also see CPOL set to 0 and CPHA set to 1. 144 | 145 | ...looking deeper into `AS3935.AS3935_i2c_spi`, we see the underlying class constructor method: 146 | 147 | ```python 148 | def __init__(self, irq, bus=0, device=0x00): 149 | """ 150 | Configure the main parameters of AS3935. 151 | 152 | :param irq: (int) GPIO pin number the IRQ is connected at (BCM number) 153 | :param bus: (int, optional) the bus the AS3935 is connected at. Default = 0 154 | :param device: (int, optional) the device number of the AS3935 spi device file. Default = 0x00 155 | """ 156 | self.device = device 157 | self.bus = bus 158 | self.irq = irq 159 | self.pi = pigpio.pi() 160 | self.bitsPerWord = 8 161 | # configure spidev device 162 | self.spi_device = spidev.SpiDev() 163 | self.spi_device.open(bus, device) 164 | self.spi_device.lsbfirst = False 165 | ``` 166 | 167 | ...followed by configuration methods: 168 | 169 | ```python 170 | def max_speed_hz(self, speedInHz): 171 | """ 172 | Configures the SPI clock frequency 173 | 174 | :param speedInHz: (int) desired SCLK freq. in Hz 175 | """ 176 | self.speedInHz = speedInHz 177 | # configure spidev device 178 | self.spi_device.max_speed_hz = speedInHz 179 | ``` 180 | 181 | ```python 182 | def mode(self, modeBits): 183 | """ 184 | Configures SPI signal polarities 185 | 186 | :param modeBits: (int) SPI mode as two bit pattern of clock polarity and phase [CPOL|CPHA], min: 0b00 = 0, max: 0b11 = 3 187 | """ 188 | self.spi_mode = modeBits 189 | # configure spidev device 190 | self.spi_device.mode = modeBits 191 | ``` 192 | 193 | 194 | Next, let's look into `AS3935.AS3935_i2c_spi` implementation of the reads and write: 195 | 196 | ```python 197 | 198 | def read_bytes(self, address, count=1): 199 | """ 200 | Returns the byte values read from starting address. 201 | 202 | :param address: (int) the address to read from (between 0x00 and 0x3F) 203 | :param count: (int) the number of bytes to be read (between 0x00 and 0x3F) 204 | :return: (list) byte values read the address (values between 0x00 and 0xFF) 205 | """ 206 | if not 0 <= address <= 63: 207 | raise ValueError("The address must be between 0x00 and 0x3F") 208 | read_cmd = [ address & 0x3f | self.BITS_A7A6_READ ] + [ 0x0 ] * count 209 | bytesRead = self.spi_device.xfer(read_cmd) 210 | if not len(bytesRead) == count + 1: 211 | raise AssertionError('Failed to read {} byte(s) from SPI device (got {})!'.format(count, len(bytesRead))) 212 | bytesRequested = bytesRead[1:] 213 | if not len(bytesRequested) == count: 214 | raise AssertionError('Failed to read {} byte(s) from SPI device (got {})!'.format(count, len(bytesRequested))) 215 | return bytesRequested 216 | ``` 217 | 218 | This is our many value read. (we mostly do single value reads until we need to read the detection strength then we read values from 3 consectutive registers. (*read starting at for length of 3*) 219 | 220 | Next, we have a simplifying method for single byte reads: 221 | 222 | ```python 223 | def read_byte(self, address): 224 | """ 225 | Returns the value of the byte read from address. 226 | 227 | :param address: (int) the address to read from (between 0x00 and 0x3F) 228 | :return: (int) byte value read from the address (value between 0x00 and 0xFF) 229 | """ 230 | # a simple alias of our base read so code reads better 231 | bytesRead = self.read_bytes(address, 1) 232 | if not len(bytesRead) > 0: 233 | raise AssertionError('At least 1 byte should have been returned from SPI device!') 234 | return bytesRead[0] 235 | ``` 236 | 237 | I added this simply because there are so many times we want to just read 1 byte from an address so pulling the single-byte value from the list in one place just made sense. 238 | 239 | Lastly here's our write: 240 | 241 | ```python 242 | def write_byte(self, address, value): 243 | """ 244 | Writes value at address. 245 | 246 | :param address: (int) the address to write to (between 0x00 and 0x3F) 247 | :param value: (int) the byte value (between 0x00 and 0xFF) 248 | """ 249 | if not 0 <= address <= 63: 250 | raise ValueError("The address must be between 0x00 and 0x3F") 251 | if not 0 <= value <= 255: 252 | raise ValueError("The value must be between 0x00 and 0xFF") 253 | 254 | write_cmd = [ address & 0x3f | self.BITS_A7A6_WRITE, value ] 255 | self.spi_device.writebytes(write_cmd) 256 | ``` 257 | 258 | Most of our writes are single byte writes so this is all we needed to implement. 259 | 260 | ## Sometimes you just have to try 261 | 262 | I tried to show how and where I found the facts to guide our implementation. We found a good bit! But there were just some things we couldn't figure out in advance. 263 | 264 | **Clock Polarity** wasn't specified so I played with 1 and 0 and the 0 value worked! It was pretty telling. With the wrong SCLK polarity the device didn't respond. With correct polarity it responded. We call this a light-bulb test! 265 | 266 | **Control of /CS lines** wasn't identified in the RPi docs. So I wired it up and verified the behavior with a Logic Analyzer and it just worked. (See Blue CS trace in Analyzer screen shots below.) I'll call it a good day any day I don't have to research further how something has to be controlled! 267 | 268 | ## Measured Results - The Proof 269 | 270 | When writing code to drive hardware you have to measure the signals passed between the devices to verify their communication. Here's my test setup: 271 | 272 | ![Test Hardware](Docs/images/test-hardware.jpg) 273 | 274 | The colored probes you see (above) are connected to my [SQ200 from ikalogic.com](https://www.ikalogic.com/sq-logic-analyzer-pattern-generator/) an inexpensive ~$175 Logic Analyzer / Pattern Generator. It comes with ScanaStudio software which automatically decodes most protocols I use in my play/work efforts. (*Yes, it even decodes the SPI protocol!*) 275 | 276 | Here is the picture I took of the scanstudio screen recording the proof of our SPI clock setup, polarities and showing that the AS3935 actually responding! 277 | 278 | ![Measured Clocks](Docs/images/spi-clocks-verified.jpg) 279 | 280 | This image shows our write to register 2 along with a pad byte of 0x00 so that we can read the response from the AS3935. 281 | 282 | Now lets look at a few more transactions: 283 | 284 | ![More Transactions](Docs/images/spi-transactions.jpg) 285 | 286 | Here we see: 287 | 288 | * a read of Register 0x02 - AS3925 answers with 0x10 289 | * a read of Register 0x00 - AS3925 answers with 0x24 290 | * a read of Register 0x08 - AS3925 answers with 0x01 291 | * a read of Register 0x01 - AS3925 answers with 0x10 292 | 293 | **Exercise for the reader**: review the register map in the AS3935 datasheet to see what registers were being read and what the returned values mean! 294 | 295 | 296 | Ok, that's all I have for this document. I hope what I have written here has helped you to understand a little more about how to research SPI for a specific device and then how to write code to interact with that device. 297 | 298 | --- 299 | 300 | *If you have any questions about what I've written here, file an issue and I'll respond with edits to this doc to attempt to make things more clear.* 301 | 302 | Thanks for Reading, following along. 303 | 304 | ``` 305 | Stephen M. Moraco 306 | Lead developer 307 | Iron Sheep Productions, LLC. 308 | ``` 309 | 310 | If you find this kind of written explanation useful, helpful I would be honored by your helping me out for a couple of :coffee:'s or :pizza: slices! 311 | 312 | [![coffee](https://www.buymeacoffee.com/assets/img/custom_images/black_img.png)](https://www.buymeacoffee.com/ironsheep) 313 | 314 | --- 315 | 316 | Last Updated: 02 Sep 2020, 02:26 MST 317 | 318 | [maintenance-shield]: https://img.shields.io/badge/maintainer-S%20M%20Moraco%20%40ironsheepbiz-blue.svg?style=for-the-badge 319 | -------------------------------------------------------------------------------- /AS3935/AS3935_i2c_spi.py: -------------------------------------------------------------------------------- 1 | """ 2 | Original work 'AS3935' (C) 2019 Eloi Codina Torras 3 | 4 | AS3935_Base, AS3935_I2C, and AS3935_SPI built from AS3935 by Stephen M. Moraco, Sep 1, 2020 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | """ 19 | import pigpio 20 | import time 21 | 22 | 23 | INT_NH = 0b0001 24 | INT_D = 0b0100 25 | INT_L = 0b1000 26 | 27 | class AS3935_Base: 28 | REG_01 = 0x01 29 | REG_02 = 0x02 30 | REG_03 = 0x03 31 | REG_04 = 0x04 32 | REG_05 = 0x05 33 | def __init__(self, irq, bus=1, address=0x03): 34 | """ 35 | Configure the main parameters of AS3935. 36 | 37 | :param irq: (int) GPIO pin number the IRQ is connected at (BCM number) 38 | :param bus: (int, optional) the bus the AS3935 is connected at. Default = 1 39 | :param address: (int, optional) the address of the AS3935. Default = 0x03 40 | """ 41 | self.address = address 42 | self.bus = bus 43 | self.irq = irq 44 | self.pi = pigpio.pi() 45 | self.device = None 46 | self.debug = False 47 | # Let our derived classes handle this! 48 | #self.i2c_device = self.pi.i2c_open(bus, address) 49 | 50 | def close(self): 51 | """ 52 | Release the /dev/???? device! 53 | """ 54 | # Let our derived classes handle this! 55 | #self.pi.i2c_close() 56 | #self.i2c_device = None 57 | self.device = None 58 | 59 | def setDebug(self, enableState=True): 60 | self.debug = enableState 61 | 62 | def print_line(self, text, className='AS3935_Base', error=False, warning=False, info=False, verbose=False, debug=False): 63 | if debug: 64 | if self.debug: 65 | print('[{}] - (DBG): {}'.format(className, text)) 66 | 67 | # ------ CONFIGURE FUNCTIONS ------ # 68 | 69 | def max_speed_hz(self, speedInHz): 70 | """ 71 | NOTHING this is only used in SPI 72 | """ 73 | 74 | def mode(self, modeBits): 75 | """ 76 | NOTHING this is only used in SPI 77 | """ 78 | 79 | # ------ CROSS FUNCTIONS ------ # 80 | 81 | def read_byte(self, address): 82 | """ 83 | Returns the value of the byte stored at address. 84 | 85 | :param address: (int) the address to read from 86 | :return: (int) the value of the address 87 | """ 88 | # Let our derived classes handle this! 89 | #return self.pi.i2c_read_byte_data(self.i2c_device, address) 90 | raise AssertionError('The read_byte() method must be overridden by the derived class, base should not be called!') 91 | pass 92 | 93 | def write_byte(self, address, value): 94 | """ 95 | Writes value at address. Raises ValueError if the value is not correct. 96 | It sleeps for 2 ms after writing the value 97 | 98 | :param address: (int) the address to write to 99 | :param value: (int) the byte value (between 0x00 and 0xFF) 100 | """ 101 | # Let our derived classes handle this! 102 | # if not 0 <= value <= 255: 103 | # raise ValueError("The value should be between 0x00 and 0xFF") 104 | # self.pi.i2c_write_byte_data(self.i2c_device, address, value) 105 | # time.sleep(0.002) 106 | raise AssertionError('The write_byte() method must be overridden by the derived class, base should not be called!') 107 | 108 | def full_calibration(self, tuning_cap): 109 | """ 110 | Performs a full calibration: antenna and RCO 111 | 112 | :param tuning_cap: int: tuning number for the antenna. Can be calculated with self.calculate_tuning_cap() 113 | """ 114 | self.set_tune_antenna(tuning_cap) 115 | self.calibrate_trco() 116 | 117 | # ------ 8.2- OPERATING MODES ------ # 118 | 119 | def power_down_mode(self): 120 | """ 121 | Sets the AS3935 on power down mode (PWD) 122 | """ 123 | self.write_byte(0x00, self.read_byte(0x00) | 0x01) 124 | 125 | def listening_mode(self): 126 | """ 127 | Sets the AS3935 on listening mode (PWD) 128 | """ 129 | self.write_byte(0x00, self.read_byte(0x00) & 0b11111110) 130 | 131 | # ------------- 8.5- I2C ------------ # 132 | # ------ 8.5.3- DIRECT COMMAND ------ # 133 | 134 | def set_default_values(self): 135 | """ 136 | Sends a direct command to 0x3C to reset to default values. 137 | """ 138 | self.print_line('++ reset chip to default values', debug=True) 139 | self.write_byte(0x3C, 0x96) 140 | 141 | def calibrate_rco(self): 142 | """ 143 | Sends a direct command to 0x3D to calibrate the RCO (CALIB_RCO) 144 | """ 145 | self.print_line('++ calibrate RC Osc.', debug=True) 146 | self.write_byte(0x3D, 0x96) 147 | 148 | # ------------- 8.7- AFE AND WATCHDOG ------------ # 149 | 150 | def get_indoors(self): 151 | """ 152 | Checks whether the device is configured to be run indoors. (AFE_GB) 153 | 154 | :return: (bool) whether the device is configured to be run indoors 155 | """ 156 | return self.read_byte(0x00) & 0b100000 == 0b100000 157 | 158 | def set_indoors(self, indoors): 159 | """ 160 | Configures the device to be run indoors or outdoors. (AFE_GB) 161 | 162 | :param indoors: (bool) configure the AS3935 to be run indoors 163 | """ 164 | current_value = self.read_byte(0x00) 165 | if indoors: 166 | write_value = (current_value & 0b11000001) | 0b100100 167 | else: 168 | write_value = (current_value & 0b11000001) | 0b11100 169 | self.write_byte(0x00, write_value) 170 | 171 | def get_watchdog_threshold(self): 172 | """ 173 | Returns the watchdog threshold (WDTH) 174 | 175 | :return: (int) the current watchdog threshold 176 | """ 177 | return self.read_byte(0x01) & 0b00001111 178 | 179 | def set_watchdog_threshold(self, value=0b0001): 180 | """ 181 | Sets the watchdog threshold to value (WDTH). If called without parameters, 182 | it sets it to the default configuration. 183 | Can raise a ValueError if not 0 <= value <= 0b1111 184 | 185 | :param value: (int, optional) The value to be set. From 0b0000 to 0b1111. Default=0b0001 186 | """ 187 | if not 0 <= value <= 0b1111: 188 | raise ValueError("Value should be from 0b0010 to 0b1111") 189 | self.write_byte(0x01, (self.read_byte(0x01) & 0x11110000) | value) 190 | 191 | # ------------- 8.8- NOISE FLOOR GENERATOR ------------ # 192 | 193 | def get_noise_floor(self): 194 | """ 195 | Checks the current noise floor threshold (NF_LEV). 196 | 197 | :return: (int) the current noise floor threshold 198 | """ 199 | return (self.read_byte(0x01) & 0b1110000) >> 4 200 | 201 | def set_noise_floor(self, noise_floor=0b010): 202 | """ 203 | Sets a new noise floor threshold (NF_LEV). If called without parameters, it sets it to the default configuration. 204 | Can raise a ValueError if not 0 <= noise_floor <= 0b111 205 | 206 | :param noise_floor: (int, optional) The value to be set. From 0b000 to 0b111 207 | """ 208 | if not 0 <= noise_floor <= 0b111: 209 | raise ValueError("noise_floor should be from 0b000 to 0b111") 210 | self.write_byte(0x01, (self.read_byte(0x01) & 0b10001111) + ((noise_floor & 0x07) << 4)) 211 | 212 | def lower_noise_floor(self, min_noise=0b000): 213 | """ 214 | Lowers the noise floor threshold by one step (subtracts 1 to the current NF_LEV) 215 | if it is currently higher than min_noise. 216 | Can raise a ValueError if not 0 <= min_noise <= 0b111 217 | 218 | :param min_noise: (int, optional) the minimum NF_LEV the device should be set at. Default = 0b000 219 | :return: (int) the new noise floor threshold 220 | """ 221 | if not 0 <= min_noise <= 0b111: 222 | raise ValueError("min_noise should be from 0b000 to 0b111") 223 | floor = self.get_noise_floor() 224 | if floor > min_noise: 225 | floor = floor - 1 226 | self.set_noise_floor(floor) 227 | return floor 228 | 229 | def raise_noise_floor(self, max_noise=0b111): 230 | """ 231 | Raises the noise floor threshold by one step (adds 1 to the current NF_LEV) 232 | if it is currently lower than max_noise 233 | Can raise a ValueError if not 0 <= max_noise <= 0b111 234 | 235 | :param max_noise: (int, optional) the maximum NF_LEV the device should be set at. Default 0b111 236 | :return: (int) the new noise floor threshold 237 | """ 238 | if not 0 <= max_noise <= 0b111: 239 | raise ValueError("max_noise should be from 0b000 to 0b111") 240 | floor = self.get_noise_floor() 241 | if floor < max_noise: 242 | floor = floor + 1 243 | self.set_noise_floor(floor) 244 | return floor 245 | 246 | # ------------- 8.9- LIGHTNING ALGORITHM ------------ # 247 | # ------------- 8.9.1- SIGNAL VALIDATION ------------ # 248 | 249 | def get_spike_rejection(self): 250 | """ 251 | Checks the current spike rejection settings (SREJ) 252 | 253 | :return: (int) the current spike rejection setting (SREJ) 254 | """ 255 | return self.read_byte(0x02) & 0b00001111 256 | 257 | def set_spike_rejection(self, value=0b0010): 258 | """ 259 | Sets a new setting for the spike rejection algorithm (SREJ). If the function is called without any parameter, 260 | it sets it to the default value of 0b0010 261 | Can raise a ValueError if not 0 <= value <= 0b1111 262 | 263 | :param value: (int, optional) the value to set SREJ. Default = 0b0010 264 | """ 265 | if not 0 <= value <= 0b1111: 266 | raise ValueError("Value should be from 0b0000 to 0b1111") 267 | clean_byte = self.read_byte(0x02) & 0b11110000 268 | self.write_byte(0x02, clean_byte | value) 269 | 270 | # ------------- 8.9.2- ENERGY CALCULATION ------------ # 271 | 272 | def get_energy(self): 273 | """ 274 | Checks the last lightning strike's energy calculation. It does not have any physical meaning. 275 | (Energy of the Single Lightning *SBYTE) 276 | 277 | :return: (int) last strike's energy 278 | """ 279 | return ((self.read_byte(0x06) & 0x1F) << 16) | (self.read_byte(0x05) << 8) | self.read_byte(0x04) 280 | 281 | # ------------- 8.9.3- DISTANCE ESTIMATION ------------ # 282 | 283 | def get_distance(self): 284 | """ 285 | Checks the estimation of the last lightning strike's distance in km (DISTANCE). 286 | 287 | :return: (int/None) last strike's distance in km. None if out of range, 0 if overhead 288 | """ 289 | dist = self.read_byte(0x07) & 0b00111111 290 | distInterp = dist 291 | if dist == 0b111111: 292 | distInterp = None 293 | if distInterp != dist: 294 | self.print_line('++ returning [{}] for [{}]'.format(distInterp, dist), debug=True) 295 | return distInterp 296 | 297 | # ------------- 8.9.4- INTERRUPTION MANAGEMENT ------------ # 298 | 299 | def get_interrupt(self): 300 | """ 301 | Checks the reason of the interruption (INT). To know what it is, use the constants: 302 | INT_NH: noise level too high 303 | INT_D: disturber detected 304 | INT_L: lightning strike detected 305 | 306 | It sleeps for 2 ms before retrieving the value, as specified at the datasheet. 307 | 308 | :return: (int) the interruption reason 309 | """ 310 | time.sleep(0.002) 311 | return self.read_byte(0x03) & 0x0F 312 | 313 | def set_mask_disturber(self, mask_dist): 314 | """ 315 | Sets whether disturbers should be masked (MASK_DIST). 316 | 317 | :param mask_dist: (bool) whether disturbers should be masked 318 | """ 319 | if mask_dist: 320 | self.write_byte(0x03, self.read_byte(0x03) | 0b100000) 321 | else: 322 | self.write_byte(0x03, self.read_byte(0x03) & 0b11011111) 323 | 324 | def get_mask_disturber(self): 325 | """ 326 | Checks whether disturbers are currently masked (MASK_DIST). 327 | 328 | :return: (bool) whether disturbers are currently masked 329 | """ 330 | return self.read_byte(0x03) & 0b100000 == 0b100000 331 | 332 | def get_min_strikes(self): 333 | """ 334 | Checks the current configuration of how many strikes AS3935 has to detect in 15 minutes to issue an interrupt 335 | (MIN_NUM_LIG). 336 | In case of an error, it raises a LookupError 337 | 338 | :return: (int) number of strikes. Possible values: 1, 5, 9, 16 339 | """ 340 | bin_min = self.read_byte(0x02) & 0b00110000 341 | if bin_min == 0b00000000: 342 | return 1 343 | elif bin_min == 0b00010000: 344 | return 5 345 | elif bin_min == 0b00100000: 346 | return 9 347 | elif bin_min == 0b00110000: 348 | return 16 349 | raise LookupError("Could not get MIN_NUM_LIGH") 350 | 351 | def set_min_strikes(self, min_strikes): 352 | """ 353 | Sets the minumum number of lightning strikes the AS3935 has to detect in 15 minutes to issue an interrupt 354 | (MIN_NUM_LIG). 355 | Can raise a ValueError if min_strikes is not an accepted value. 356 | 357 | :param min_strikes: (int) min number of strikes to issue an interrupt. Possible values: 1, 5, 9, 16 358 | """ 359 | if min_strikes == 1: 360 | bin_min = 0b00000000 361 | elif min_strikes == 5: 362 | bin_min = 0b00010000 363 | elif min_strikes == 9: 364 | bin_min = 0b00100000 365 | elif min_strikes == 16: 366 | bin_min = 0b00110000 367 | else: 368 | raise ValueError("Allowed values for min_strikes: 1, 5, 9, 16.") 369 | self.write_byte(0x02, (self.read_byte(0x02) & 0b11001111) | bin_min) 370 | 371 | def clear_lightning_stats(self): 372 | """ 373 | Clears the statistics built up by the lightning distance estimation algorithm (CL_STAT) 374 | """ 375 | original_byte = self.read_byte(0x02) 376 | self.write_byte(0x02, original_byte & 0b10111111) 377 | time.sleep(0.001) 378 | self.write_byte(0x02, original_byte) 379 | 380 | # ------------- 8.10- ANTENNA TUNNING ------------ # 381 | 382 | def get_display_lco(self): 383 | """ 384 | Checks whether the antenna resonance frequency is currently displayed on the IRQ pin (DISP_LCO) 385 | 386 | :return: (bool) whether the antenna resonance frequency is currently displayed 387 | """ 388 | return self.read_byte(0x08) & 0b10000000 == 0b100000000 389 | 390 | def set_display_lco(self, display_lco): 391 | """ 392 | Sets whether the antenna resonance frequency should be displayed on the IRQ pin(DISP_LCO). 393 | 394 | :param display_lco: (bool) whether the antenna resonance frequency should be displayed 395 | """ 396 | current_value = self.read_byte(0x08) 397 | if display_lco: 398 | self.write_byte(0x08, (current_value | 0x80)) 399 | else: 400 | self.write_byte(0x08, (current_value & 0x7F)) 401 | 402 | def set_tune_antenna(self, tuning_cap): 403 | """ 404 | Sets the antenna calibration. It adds or removes internal capacitors according to tuning_cap (TUN_CAP). 405 | If tuning_cap is unknown, this could be calculated by calculate_tuning_cap(self, frequency_divisor, tries_frequency) 406 | Can raise a ValueError if not 0 <= tuning_cap <= 15 407 | 408 | :param tuning_cap: (int) the number to calibrate the antenna 409 | """ 410 | if not 0 <= tuning_cap <= 15: 411 | raise ValueError("The value of the tuning_cap should be less than 15.") 412 | self.write_byte(0x08, (self.read_byte(0x08) & 0b11110000) | tuning_cap) 413 | 414 | def calculate_tuning_cap(self, frequency_divisor=16, tries_frequency=3, seconds_try=4): 415 | """ 416 | Measures the frequency of the LC resonator for every possible tuning_cap and returns the best value. 417 | If possible, use the default values for frequency_divisor, tries_frequency and seconds_try. 418 | This function takes a long time. It should take about tries_frequency*seconds_try*16 seconds given that 419 | there are 16 tuning possibilities. 420 | 421 | The ideal frequency is of 500 kHz 422 | 423 | Can raise ValueError if frequency_divisor is not a valid number. 424 | 425 | :param frequency_divisor: (int) the divisor the AS3935 uses to divide the frequency before displaying it on the IRQ 426 | :param tries_frequency: (int) number of times the current frequency is calculated during *seconds_try* seconds 427 | to calculate an average 428 | :param seconds_try: (float) seconds during which pulses on IRQ will be counted to calculate the internal frequency 429 | :return: (int) a tuning number between 0 and 15 430 | """ 431 | #print("* Please allow a long time for this function to stop. It should take 16*seconds_try*tries_frequency seconds") 432 | print("* Please allow a long time for this function to stop. It should take a little over 3 minutes to test the 16 values") 433 | 434 | self.set_frequency_division_ratio(frequency_divisor) 435 | frequency_target = 500000 / frequency_divisor 436 | best_tuner = 0 437 | best_diff = 500000000 438 | for current_tuner in range(0b0, 0b10000): 439 | self.set_tune_antenna(current_tuner) 440 | freqs = [] 441 | for i in range(tries_frequency): 442 | freqs.append(self.calculate_resonance_frequency(seconds_try)) 443 | freq = sum(freqs)/tries_frequency 444 | diff = abs(frequency_target - freq) 445 | print("For tuning {tun}: average frequency of {freq:.6f} Hz (diff: {diff:+.1f})".format(tun=hex(current_tuner), 446 | freq=freq*frequency_divisor, diff=diff)) 447 | if diff < best_diff: 448 | best_tuner = current_tuner 449 | best_diff = diff 450 | self.set_tune_antenna(best_tuner) 451 | print("- Your best tuning capacitor value is {tun}: which is off by {diff:+.1f}".format(tun=hex(best_tuner), diff=best_diff)) 452 | return best_tuner 453 | 454 | def calculate_resonance_frequency(self, seconds): 455 | """ 456 | Sets the AS3935 to display the antenna resonance frequency on the IRQ during *seconds* and counts the number 457 | of pulses in this time to calculate the internal frequency. 458 | To get the real frequency multiply this value by the frequency divisor ratio. 459 | 460 | :param seconds: (int) number of seconds while it should count spikes 461 | :return: (int) internal frequency 462 | """ 463 | cb = self.pi.callback(self.irq) 464 | 465 | # Count pulses 466 | self.set_display_lco(True) 467 | start = time.time() 468 | time.sleep(seconds) 469 | self.set_display_lco(False) 470 | end = time.time() 471 | 472 | # Calculate the frequency. Not with seconds, because it is not exact 473 | freq = cb.tally() / (end-start) 474 | cb.cancel() 475 | return freq 476 | 477 | def get_frequency_division_ratio(self): 478 | """ 479 | Gets the current frequency division ratio. Number by which the real antenna resonance frequency is divided to 480 | display on the IRQ pin (LCO_FDIV). 481 | Can raise a LookupError if there is an error checkig the configuration. 482 | 483 | :return: (int) frequency division ratio. Possible numbers: 16, 32, 64, 128 484 | """ 485 | lco_fdiv = self.read_byte(0x03) & 0b11000000 486 | if lco_fdiv == 0: 487 | return 16 488 | elif lco_fdiv == 64: 489 | return 32 490 | elif lco_fdiv == 128: 491 | return 64 492 | elif lco_fdiv == 192: 493 | return 128 494 | raise LookupError("Could not get the LCO_FDIV value.") 495 | 496 | def set_frequency_division_ratio(self, divisor=16): 497 | """ 498 | Sets a new frequency division ration by which the antenna resonance frequency is divided to display on the IRQ pin 499 | (LCO_FDIV).If called with no parameter, it defaults to 16. 500 | Can raise a ValueError if *divisor* is not an accepted number. 501 | 502 | :param divisor: (int, optional) frequency divisor ratio. Accepted values = (16, 32, 64, 128). Default = 16 503 | """ 504 | values = {16: 0b0, 32: 0b01000000, 64: 0b10000000, 128: 0b11000000} 505 | if divisor not in values: 506 | raise ValueError("Accepted values: 16, 32, 64, 128") 507 | new_lco_fdiv = (self.read_byte(0x03) & 0b00111111) | values[divisor] 508 | self.write_byte(0x03, new_lco_fdiv) 509 | 510 | # ------------- 8.11- CLOCK GENERATION ------------ # 511 | 512 | def get_display_srco(self): 513 | """ 514 | Checks whether the SRCO frequency is being displayed on the IRQ pin. 515 | 516 | :return: (bool) whether the SRCO frequency is currently displayed 517 | """ 518 | return self.read_byte(0x08) & 0b01000000 == 0b01000000 519 | 520 | def set_display_srco(self, display_srco): 521 | """ 522 | Sets whether the SRCO frequency should be displayed on the IRQ pin. 523 | 524 | :param display_srco: (bool) whether the SRCO frequency should be displayed 525 | """ 526 | current_value = self.read_byte(0x08) 527 | if display_srco: 528 | self.write_byte(0x08, (current_value | 0b1000000)) 529 | else: 530 | self.write_byte(0x08, (current_value & 0b10111111)) 531 | 532 | def get_display_trco(self): 533 | """ 534 | Checks' whether the TRCO frequency is being displayed on the IRQ pin. 535 | 536 | :return: (bool) whether the TRCO frequency is currently displayed 537 | """ 538 | return self.read_byte(0x08) & 0b00100000 == 0b00100000 539 | 540 | def set_display_trco(self, display_trco): 541 | """ 542 | Sets whether the TRCO frequency should be displayed on the IRQ pin. 543 | 544 | :param display_srco: (bool) whether the TRCO frequency should be displayed 545 | """ 546 | current_value = self.read_byte(0x08) 547 | if display_trco: 548 | self.write_byte(0x08, (current_value | 0b00100000)) 549 | else: 550 | self.write_byte(0x08, (current_value & 0b11011111)) 551 | 552 | def calibrate_trco(self): 553 | """ 554 | Calibrates the TRCO by sending the direct command CALIB_RCO and toggling the DIS_TRCO bit (low-high-low) 555 | """ 556 | self.listening_mode() 557 | self.calibrate_rco() 558 | self.set_display_trco(True) 559 | time.sleep(0.002) 560 | self.set_display_trco(False) 561 | 562 | """ 563 | This class overrides the base adding all the I2C specifics 564 | """ 565 | class AS3935_I2C(AS3935_Base): 566 | def __init__(self, irq, bus=1, address=0x03): 567 | AS3935_Base.__init__(self, irq=irq, bus=bus, address=address) 568 | """ 569 | Configure the main parameters of AS3935. 570 | 571 | :param irq: (int) GPIO pin number the IRQ is connected at (BCM number) 572 | :param bus: (int, optional) the bus the AS3935 is connected at. Default = 1 573 | :param address: (int, optional) the address of the AS3935. Default = 0x03 574 | """ 575 | self.device = self.pi.i2c_open(bus, address) 576 | 577 | def close(self): 578 | """ 579 | Release the /dev/i2c-1 device! 580 | """ 581 | self.pi.i2c_close() 582 | self.device = None 583 | 584 | # ------ CROSS FUNCTIONS ------ # 585 | 586 | def read_byte(self, address): 587 | """ 588 | Returns the value of the byte stored at address. 589 | 590 | :param address: (int) the address to read from 591 | :return: (int) the value of the address 592 | """ 593 | value = self.pi.i2c_read_byte_data(self.device, address) 594 | self.print_line('---:: addr({}): ({:08b})'.format(hex(address), value), debug=True) 595 | return value 596 | 597 | def write_byte(self, address, value): 598 | """ 599 | Writes value at address. Raises ValueError if the value is not correct. 600 | It sleeps for 2 ms after writing the value 601 | 602 | :param address: (int) the address to write to 603 | :param value: (int) the byte value (between 0x00 and 0xFF) 604 | """ 605 | if not 0 <= value <= 255: 606 | raise ValueError("The value should be between 0x00 and 0xFF") 607 | self.pi.i2c_write_byte_data(self.device, address, value) 608 | self.print_line('---:: addr({}) <= ({:08b})'.format(hex(address), value), debug=True) 609 | time.sleep(0.002) 610 | 611 | def print_line(self, text, className='AS3935_I2C', error=False, warning=False, info=False, verbose=False, debug=False): 612 | super().print_line(text, className=className, error=error, warning=warning, info=info, verbose=verbose, debug=debug) 613 | 614 | """ 615 | This class overrides the base adding all the SPI specifics 616 | """ 617 | import spidev 618 | 619 | class AS3935_SPI(AS3935_Base): 620 | def __init__(self, irq, bus=0, device=0x00): 621 | AS3935_Base.__init__(self, irq=irq, bus=bus, address=device) 622 | """ 623 | Configure the main parameters of AS3935. 624 | 625 | :param irq: (int) GPIO pin number the IRQ is connected at (BCM number) 626 | :param bus: (int, optional) the bus the AS3935 is connected at. Default = 0 627 | :param device: (int, optional) the device number of the AS3935 spi device file. Default = 0x00 628 | """ 629 | self.speedInHz = 1000000 # default 630 | self.spi_mode = 0b00 # default 631 | # configure spidev device 632 | self.device = spidev.SpiDev() 633 | self.device.open(bus, device) 634 | self.device.lsbfirst = False 635 | 636 | def close(self): 637 | """ 638 | Release the /dev/spidev0.0 device! 639 | """ 640 | self.device.close() 641 | 642 | # ------ CONFIGURE FUNCTIONS ------ # 643 | 644 | def max_speed_hz(self, speedInHz): 645 | """ 646 | Configures the SPI clock frequency 647 | 648 | :param speedInHz: (int) desired SCLK freq. in Hz 649 | """ 650 | self.speedInHz = speedInHz 651 | self.device.max_speed_hz = speedInHz 652 | 653 | def mode(self, modeBits): 654 | """ 655 | Configures SPI signal polarities 656 | 657 | :param modeBits: (int) SPI mode as two bit pattern of clock polarity and phase [CPOL|CPHA], min: 0b00 = 0, max: 0b11 = 3 658 | """ 659 | self.spi_mode = modeBits 660 | self.device.mode = modeBits 661 | 662 | # ------ CROSS FUNCTIONS ------ # 663 | BITS_A7A6_READ = 0x40 664 | BITS_A7A6_WRITE = 0x00 665 | 666 | def read_bytes(self, address, count=1): 667 | """ 668 | Returns the byte values read from starting address. 669 | 670 | :param address: (int) the address to read from (between 0x00 and 0x3F) 671 | :param count: (int) the number of bytes to be read (between 0x00 and 0x3F) 672 | :return: (list) byte values read the address (values between 0x00 and 0xFF) 673 | """ 674 | if not 0 <= address <= 63: 675 | raise ValueError("The address must be between 0x00 and 0x3F") 676 | read_cmd = [ address & 0x3f | self.BITS_A7A6_READ ] + [ 0x0 ] * count 677 | bytesRead = self.device.xfer(read_cmd) 678 | if not len(bytesRead) == count + 1: 679 | raise AssertionError('Failed to read {} byte(s) from SPI device (got {})!'.format(count, len(bytesRead))) 680 | bytesRequested = bytesRead[1:] 681 | if not len(bytesRequested) == count: 682 | raise AssertionError('Failed to read {} byte(s) from SPI device (got {})!'.format(count, len(bytesRequested))) 683 | return bytesRequested 684 | 685 | def read_byte(self, address): 686 | """ 687 | Returns the value of the byte read from address. 688 | 689 | :param address: (int) the address to read from (between 0x00 and 0x3F) 690 | :return: (int) byte value read from the address (value between 0x00 and 0xFF) 691 | """ 692 | # a simple alias of our base read so code reads better 693 | bytesRead = self.read_bytes(address, 1) 694 | if not len(bytesRead) > 0: 695 | raise AssertionError('At least 1 byte should have been returned from SPI device!') 696 | self.print_line('---:: addr({}): ({:08b})'.format(hex(address), bytesRead[0]), debug=True) 697 | return bytesRead[0] 698 | 699 | def write_byte(self, address, value): 700 | """ 701 | Writes value at address. Raises ValueError if the value is not correct. 702 | It sleeps for 2 ms after writing the value 703 | 704 | :param address: (int) the address to write to (between 0x00 and 0x3F) 705 | :param value: (int) the byte value (between 0x00 and 0xFF) 706 | """ 707 | if not 0 <= address <= 63: 708 | raise ValueError("The address must be between 0x00 and 0x3F") 709 | if not 0 <= value <= 255: 710 | raise ValueError("The value must be between 0x00 and 0xFF") 711 | 712 | write_cmd = [ address & 0x3f | self.BITS_A7A6_WRITE, value ] 713 | self.device.writebytes(write_cmd) 714 | self.print_line('---:: addr({}) <= ({:08b})'.format(hex(address), value), debug=True) 715 | time.sleep(0.002) 716 | 717 | def print_line(self, text, className='AS3935_SPI', error=False, warning=False, info=False, verbose=False, debug=False): 718 | super().print_line(text, className=className, error=error, warning=warning, info=info, verbose=verbose, debug=debug) 719 | -------------------------------------------------------------------------------- /TEST/testGenStorm.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import _thread 4 | from datetime import datetime 5 | import threading 6 | import os 7 | import sys 8 | import re 9 | import os.path 10 | import argparse 11 | from time import time, sleep, localtime, strftime 12 | from collections import OrderedDict 13 | from configparser import ConfigParser 14 | from colorama import init as colorama_init 15 | from colorama import Fore, Back, Style 16 | import random 17 | from signal import signal, SIGPIPE, SIG_DFL 18 | signal(SIGPIPE,SIG_DFL) 19 | 20 | # 21 | # read config from storm_comfig.ini 22 | # the follow guidance to generate list of detections to output file (or stdout) 23 | # where each detection is 24 | # hh:mm distance energy 25 | 26 | script_version = "1.0.0" 27 | script_name = 'testGenStorm.py' 28 | 29 | script_info = '{} v{}'.format(script_name, script_version) 30 | project_info= '{}: Lightning Detections Generator'.format(script_info) 31 | project_url = 'https://github.com/ironsheep/lightning-detector-MQTT2HA-Daemon' 32 | 33 | if False: 34 | # will be caught by python 2.7 to be illegal syntax 35 | print('Sorry, this script requires a python3 runtime environment.', file=sys.stderr) 36 | 37 | opt_debug = False 38 | opt_verbose = False 39 | opt_write_file = False 40 | out_file = sys.stdout 41 | output_line_count = 0 42 | 43 | # Logging function 44 | def print_line(text, error=False, warning=False, info=False, debug=False, write=False, console=True): 45 | timestamp = strftime('%Y-%m-%d %H:%M:%S', localtime()) 46 | if console: 47 | if error: 48 | print(Fore.RED + Style.BRIGHT + '[{}] '.format(timestamp) + Style.RESET_ALL + '{}'.format(text) + Style.RESET_ALL, file=sys.stderr) 49 | elif warning: 50 | print(Fore.YELLOW + '[{}] '.format(timestamp) + Style.RESET_ALL + '{}'.format(text) + Style.RESET_ALL) 51 | elif info: 52 | if opt_verbose: 53 | print(Fore.GREEN + '[{}] '.format(timestamp) + Fore.YELLOW + '- ' + '{}'.format(text) + Style.RESET_ALL) 54 | elif debug: 55 | if opt_debug: 56 | print(Fore.CYAN + '[{}] '.format(timestamp) + '- (DBG): ' + '{}'.format(text) + Style.RESET_ALL) 57 | else: 58 | print(Fore.GREEN + '[{}] '.format(timestamp) + Style.RESET_ALL + '{}'.format(text) + Style.RESET_ALL) 59 | else: 60 | if write: 61 | print('{}'.format(text), file=out_file) 62 | #output_line_count += 1 63 | # Argparse 64 | default_output_filename = 'storm.dat' 65 | default_config_filename = 'storm_config.ini' 66 | parser = argparse.ArgumentParser(description=project_info, epilog='For further details see: ' + project_url) 67 | parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true") 68 | parser.add_argument("-d", "--debug", help="show debug output", action="store_true") 69 | parser.add_argument("-w", "--write_output", help="write output to file", action="store_true") 70 | parser.add_argument('--config_dir', help='directory where storm_config.ini is located', default=sys.path[0]) 71 | parser.add_argument("-i", '--config_file', help='name of config file to use instead of storm_config.ini', default=default_config_filename) 72 | parser.add_argument("-o", '--output_file', help='name of file to be written', default=default_output_filename) 73 | parse_args = parser.parse_args() 74 | 75 | 76 | config_dir = parse_args.config_dir 77 | config_filename = parse_args.config_file 78 | output_filename = parse_args.output_file 79 | opt_debug = parse_args.debug 80 | opt_verbose = parse_args.verbose 81 | opt_write_file = parse_args.write_output 82 | 83 | print_line(script_info, info=True) 84 | print_line('Generating detections according to {} placing output in {}'.format(config_filename, output_filename), info=True) 85 | if opt_verbose: 86 | print_line('Verbose enabled', info=True) 87 | if opt_debug: 88 | print_line('Debug enabled', debug=True) 89 | 90 | 91 | if opt_write_file and len(output_filename) > 0: 92 | out_file = open(output_filename, "wt") 93 | 94 | # Load configuration file 95 | config = ConfigParser(delimiters=('=', ), inline_comment_prefixes=('#')) 96 | config.optionxform = str 97 | try: 98 | with open(os.path.join(config_dir, config_filename)) as config_file: 99 | config.read_file(config_file) 100 | except IOError: 101 | print_line('- No configuration file "{config_filename}"'.format(), error=True) 102 | sys.exit(1) 103 | 104 | # Script storm settings 105 | 106 | 107 | 108 | default_none = 0 # no default 109 | 110 | min_percent = 1 111 | max_percent = 100 112 | # percentage 1-100 - closet the storm will be (% of total time of storm) 113 | storm_closest_from = config['Storm'].get('storm_closest_from', default_none) 114 | storm_closest_to = config['Storm'].get('storm_closest_to', default_none) 115 | 116 | # where will the stom be relative to overhead(0km) our location 117 | default_min_distance = 0 118 | default_max_distance = 63 119 | storm_min_distance = config['Storm'].getint('storm_min_distance', default_min_distance) 120 | storm_max_distance = config['Storm'].getint('storm_max_distance', default_max_distance) 121 | 122 | # duration specs: minutes for this band in 'mm' -OR- 'hh:mm' 123 | storm_early_duration = config['Storm'].get('storm_early_duration', default_none) 124 | storm_middle_duration = config['Storm'].get('storm_middle_duration', default_none) 125 | storm_late_duration = config['Storm'].get('storm_late_duration', default_none) 126 | 127 | storm_early_strikes = config['Storm'].getint('storm_early_strikes', default_none) 128 | storm_middle_strikes = config['Storm'].getint('storm_middle_strikes', default_none) 129 | storm_late_strikes = config['Storm'].getint('storm_late_strikes', default_none) 130 | 131 | # range specs '{min_km}-{max_km}' 132 | storm_early_energy = config['Storm'].get('storm_early_energy', default_none) 133 | storm_middle_energy = config['Storm'].get('storm_middle_energy', default_none) 134 | storm_late_energy = config['Storm'].get('storm_late_energy', default_none) 135 | 136 | # parsers 137 | def floatFromPercentSpec(percentSpec): 138 | desiredPercent = -1 139 | testPercent = float(percentSpec) / 100.0 140 | if testPercent >= 0 and testPercent <= 1: 141 | desiredPercent = testPercent 142 | return desiredPercent 143 | 144 | def minutesFromHourSpec(hourSpec): 145 | desiredMinutes = -1 146 | partsAr = hourSpec.split(':') 147 | if len(partsAr) == 2: 148 | desiredMinutes = int(partsAr[0]) * 60 149 | desiredMinutes += int(partsAr[1]) 150 | elif len(partsAr) == 1: 151 | desiredMinutes = int(partsAr[0]) 152 | return desiredMinutes 153 | 154 | def tupleFromRangeSpec(rangeSpec): 155 | desiredTuple = (-1) 156 | partsAr = rangeSpec.split('-') 157 | if len(partsAr) == 2: 158 | desiredTuple = ( int(partsAr[0]), int(partsAr[1]) ) 159 | #else 160 | # parse error.... just let (-1) tuple be returned 161 | return desiredTuple 162 | 163 | # Check configuration 164 | # 165 | 166 | have_enough_params = True 167 | 168 | if (storm_min_distance < default_min_distance) or (storm_min_distance > default_max_distance): 169 | print_line('ERROR: Invalid "storm_min_distance" found in configuration file: "storm_config.ini"! Must be [{}-{}] Fix and try again... Aborting'.format(default_min_distance, default_max_distance), error=True) 170 | have_enough_params = False 171 | 172 | if (storm_max_distance < default_min_distance) or (storm_max_distance > default_max_distance): 173 | print_line('ERROR: Invalid "storm_max_distance" found in configuration file: "storm_config.ini"! Must be [{}-{}] Fix and try again... Aborting'.format(default_min_distance, default_max_distance), error=True) 174 | have_enough_params = False 175 | 176 | storm_early_duration_minutes = minutesFromHourSpec(storm_early_duration) 177 | if (storm_early_duration_minutes < 0): 178 | print_line('ERROR: Invalid "storm_early_duration" found in configuration file: "storm_config.ini"! Invalid hh:mm [{}] Fix and try again... Aborting'.format(storm_early_duration), error=True) 179 | have_enough_params = False 180 | 181 | storm_middle_duration_minutes = minutesFromHourSpec(storm_middle_duration) 182 | if (storm_early_duration_minutes < 0): 183 | print_line('ERROR: Invalid "storm_middle_duration" found in configuration file: "storm_config.ini"! Invalid hh:mm [{}] Fix and try again... Aborting'.format(storm_middle_duration), error=True) 184 | have_enough_params = False 185 | 186 | storm_late_duration_minutes = minutesFromHourSpec(storm_late_duration) 187 | if (storm_early_duration_minutes < 0): 188 | print_line('ERROR: Invalid "storm_late_duration" found in configuration file: "storm_config.ini"! Invalid hh:mm [{}] Fix and try again... Aborting'.format(storm_late_duration), error=True) 189 | have_enough_params = False 190 | 191 | storm_early_energy_range = tupleFromRangeSpec(storm_early_energy) 192 | if storm_early_energy_range[0] == -1: 193 | print_line('ERROR: Invalid "storm_early_energy" found in configuration file: "storm_config.ini"! Invalid 999-999 [{}] Fix and try again... Aborting'.format(storm_early_energy), error=True) 194 | have_enough_params = False 195 | 196 | storm_middle_energy_range = tupleFromRangeSpec(storm_middle_energy) 197 | if storm_middle_energy_range[0] == -1: 198 | print_line('ERROR: Invalid "storm_middle_energy" found in configuration file: "storm_config.ini"! Invalid 999-999 [{}] Fix and try again... Aborting'.format(storm_middle_energy), error=True) 199 | have_enough_params = False 200 | 201 | storm_late_energy_range = tupleFromRangeSpec(storm_late_energy) 202 | if storm_late_energy_range[0] == -1: 203 | print_line('ERROR: Invalid "storm_late_energy" found in configuration file: "storm_config.ini"! Invalid 999-999 [{}] Fix and try again... Aborting'.format(storm_late_energy), error=True) 204 | have_enough_params = False 205 | 206 | storm_closest_from_percent = floatFromPercentSpec(storm_closest_from) 207 | if (storm_closest_from_percent == -1): 208 | print_line('ERROR: Invalid "storm_closest_from" found in configuration file: "storm_config.ini"! Must be [{}-{}] Fix and try again... Aborting'.format(min_percent, max_percent), error=True) 209 | have_enough_params = False 210 | 211 | storm_closest_to_percent = floatFromPercentSpec(storm_closest_to) 212 | if (storm_closest_to_percent == -1): 213 | print_line('ERROR: Invalid "storm_closest_to" found in configuration file: "storm_config.ini"! Must be [{}-{}] Fix and try again... Aborting'.format(min_percent, max_percent), error=True) 214 | have_enough_params = False 215 | 216 | if have_enough_params == False: 217 | # things not good, we're outta here... 218 | sys.exit(1) 219 | 220 | 221 | print_line('Configuration accepted', info=True) 222 | 223 | total_minutes = storm_early_duration_minutes + storm_middle_duration_minutes + storm_late_duration_minutes 224 | 225 | early_start_seconds = 0 226 | middle_start_seconds = (60 * storm_early_duration_minutes) 227 | late_start_seconds = 60 * (storm_early_duration_minutes + storm_middle_duration_minutes) 228 | 229 | total_hours = int(total_minutes / 60) 230 | total_rem_minutes = total_minutes - (total_hours * 60) 231 | 232 | minutes_before_closest = total_minutes * storm_closest_from_percent 233 | minutes_while_closest = (storm_closest_to_percent - storm_closest_from_percent) * total_minutes 234 | minutes_after_closest = total_minutes * (1 - storm_closest_to_percent) 235 | minutes_until_leave_closest = total_minutes - minutes_after_closest 236 | 237 | print_line('- minutes_before_closest {}'.format(round(minutes_before_closest,1))) 238 | print_line('- total_minutes {} [{}:{}]'.format(total_minutes, total_hours, total_rem_minutes)) 239 | print_line('- minutes_while_closest {}'.format(round(minutes_while_closest,1))) 240 | print_line('- minutes_until_leave_closest {}'.format(round(minutes_until_leave_closest,1))) 241 | print_line('- minutes_after_closest {}'.format(round(minutes_after_closest,1))) 242 | 243 | def timeHMSfromSeconds(timeSeconds): 244 | desiredhours = int(timeSeconds / 3600) 245 | seconds_remaining = timeSeconds - (desiredhours * 3600) 246 | desiredMinutes = int(seconds_remaining / 60) 247 | seconds_remaining -= (desiredMinutes * 60) 248 | return ( desiredhours, desiredMinutes, round(seconds_remaining)) 249 | 250 | def stringTimeSecondsInHMS(curr_time_in_seconds): 251 | time_hms = timeHMSfromSeconds(curr_time_in_seconds) 252 | desired_interp = '{:02d}:{:02d}:{:02d}'.format(time_hms[0], time_hms[1], time_hms[2]) 253 | return desired_interp 254 | 255 | 256 | close_start_hms = stringTimeSecondsInHMS((minutes_before_closest * 60) + 1) 257 | close_end_hms = stringTimeSecondsInHMS(((minutes_before_closest + minutes_while_closest) * 60) - 1) 258 | 259 | close_minutes = round(minutes_before_closest + minutes_while_closest) 260 | close_end_hours = int(close_minutes / 60) 261 | close_end_rem_minutes = close_minutes - (close_end_hours * 60) 262 | 263 | print_line('- close {} - {}'.format(close_start_hms, close_end_hms)) 264 | 265 | early_hours = int(storm_early_duration_minutes / 60) 266 | early_rem_minutes = int(storm_early_duration_minutes - (early_hours * 60)) 267 | early_rem_seconds = storm_early_duration_minutes - ((early_hours * 3600) + (early_rem_minutes * 60)) 268 | 269 | 270 | 271 | early_start_hms = stringTimeSecondsInHMS(0) 272 | early_end_hms = stringTimeSecondsInHMS(0 + (60 * (storm_early_duration_minutes - 1/60))) 273 | 274 | middle_start_hms = stringTimeSecondsInHMS(middle_start_seconds) 275 | middle_end_hms = stringTimeSecondsInHMS(middle_start_seconds + (60 * (storm_middle_duration_minutes - 1/60))) 276 | 277 | late_start_hms = stringTimeSecondsInHMS(late_start_seconds) 278 | late_end_hms = stringTimeSecondsInHMS(late_start_seconds + (60 * (storm_late_duration_minutes - 1/60))) 279 | 280 | 281 | early_middle_minutes = storm_early_duration_minutes + storm_middle_duration_minutes 282 | minutes_so_far = early_middle_minutes 283 | middle_hours = int(minutes_so_far / 60) 284 | middle_rem_minutes = minutes_so_far - (middle_hours * 60) 285 | 286 | minutes_so_far = total_minutes 287 | late_hours = int(minutes_so_far / 60) 288 | late_rem_minutes = minutes_so_far - (late_hours * 60) 289 | 290 | print_line('- early {} - {}'.format(early_start_hms, early_end_hms)) 291 | print_line('- mid {} - {}'.format(middle_start_hms, middle_end_hms)) 292 | print_line('- late {} - {}'.format(late_start_hms, late_end_hms)) 293 | 294 | close_early = False 295 | close_middle = False 296 | close_late = False 297 | if minutes_before_closest > storm_early_duration_minutes: 298 | if minutes_before_closest > early_middle_minutes: 299 | print_line('Close during late!', debug=True) 300 | close_late = True 301 | else: 302 | print_line('Close during middle!', debug=True) 303 | close_middle = True 304 | else: 305 | print_line('Close during early!', debug=True) 306 | close_early = True 307 | 308 | if close_minutes < storm_early_duration_minutes: 309 | print_line('Leave Close during early!', debug=True) 310 | else: 311 | if close_minutes > early_middle_minutes: 312 | print_line('Leave Close during late!', debug=True) 313 | if close_early: 314 | close_middle = True 315 | close_late = True 316 | else: 317 | print_line('Leave Close during middle!', debug=True) 318 | close_middle = True 319 | 320 | if close_early: 321 | print_line('Close EARLY', info=True) 322 | if close_middle: 323 | print_line('Close MIDDLE', info=True) 324 | if close_late: 325 | print_line('Close LATE', info=True) 326 | # distance calcs 327 | # - storm moves from farthest to closest from 00:00 to 'minutes_before_closest' 328 | # - stays close until 'close_minutes' 329 | # - moves from closest to farthest from 'minutes_until_leave_closest' to 'total_minutes' 330 | # rate of travel 331 | # - distance: max km - min_distance 332 | # - entry-rate km/min = distance / 'minutes_before_closest' 333 | # - rate of 0 until 'minutes_until_leave_closest' 334 | # - exit-rate km/min = distance / ('total_minutes' - 'minutes_until_leave_closest') 335 | distance_traveled = storm_max_distance - storm_min_distance 336 | entry_rate = round(0 - (distance_traveled / minutes_before_closest),1) 337 | exit_rate = round(distance_traveled / (total_minutes - minutes_until_leave_closest), 1) 338 | print_line('- distance_traveled {} km (twice: arrive then leave)'.format(distance_traveled)) 339 | print_line('- storm arrives @ {} km/min'.format(round(entry_rate,1))) 340 | print_line('- storm departs @ {} km/min'.format(round(exit_rate,1))) 341 | 342 | # generate detections for early then middle then late 343 | # watch for overlap with CLOSE/OVERHEAD 344 | # 345 | # generate 'storm_early_strikes' of 'storm_early_energy' within 'storm_early_duration' 346 | # generate 'storm_middle_strikes' of 'storm_middle_energy' within 'storm_middle_duration' 347 | # generate 'storm_late_strikes' of 'storm_late_energy' within 'storm_late_duration' 348 | 349 | # table LATE - MIDDLE - EARLY 350 | # 0 0 0 >> can't happen << 351 | # 0 0 1 contained 352 | # 0 1 0 contained 353 | # 0 1 1 SPANs 354 | # 1 0 0 contained 355 | # 1 0 1 >> can't happen << 356 | # 1 1 0 SPANs 357 | # 1 1 1 SPANs 358 | # 359 | normal_early = False 360 | normal_middle = False 361 | normal_late = False 362 | split_early = False 363 | split_middle = False 364 | split_late = False 365 | close_only_middle = False 366 | middle_is_exit_rate = False 367 | 368 | if close_early == False and close_middle == False and close_late == False: 369 | # ERROR must have a close somewhere 370 | print_line('ERROR[CODE]??: Missing CLOSE spec... Aborting', error=True) 371 | sys.exit(1) 372 | 373 | elif close_early == True and close_middle == False and close_late == True: 374 | # ERROR close is over early and late but not middle, 375 | # can't happen 376 | print_line('ERROR[CODE]??: close is NOT over middle... Aborting', error=True) 377 | sys.exit(1) 378 | 379 | elif close_early == True and close_middle == False and close_late == False: 380 | # close contained in EARLY section 381 | # 2 or 3 early sections 382 | split_early = True 383 | # 1 middle section 384 | normal_middle = True 385 | middle_is_exit_rate = True 386 | # 1 late section 387 | normal_late = True 388 | 389 | elif close_early == False and close_middle == True and close_late == False: 390 | # close contained in MIDDLE section 391 | # 1 early section 392 | normal_early = True 393 | # 2 or 3 middle sections 394 | split_middle = True 395 | # 1 late section 396 | normal_late = True 397 | 398 | elif close_early == True and close_middle == True and close_late == False: 399 | # close SPANs EARLY and MIDDLE sections 400 | # 1 or 2 early sections 401 | split_early = True 402 | # 1 or 2 middle sections 403 | split_middle = True 404 | # 1 late section 405 | normal_late = True 406 | 407 | elif close_early == False and close_middle == False and close_late == True: 408 | # close contained in LATE section 409 | # 1 early section 410 | normal_early = True 411 | # 1 middle section 412 | normal_middle = True 413 | middle_is_exit_rate = False 414 | # 2 or 3 late sections 415 | split_late = True 416 | 417 | elif close_early == False and close_middle == True and close_late == True: 418 | # close SPANs LATE and MIDDLE sections 419 | # 1 early section 420 | normal_early = True 421 | # 1 or 2 middle sections 422 | split_middle = True 423 | # 1 or 2 late sections 424 | split_late = True 425 | else: 426 | # close SPANs LATE, MIDDLE and EARLY sections 427 | # 1 or 2 early sections 428 | split_early = True 429 | # 1 middle sections (all close) 430 | close_only_middle = True 431 | # 1 or 2 late sections 432 | split_late = True 433 | 434 | # emit our generator control tuples 435 | # where each tuple is (distance rate change +/-, # detections, energy range, duration ) 436 | generatorSets = [] 437 | # ----------------------------------------------------- 438 | # EARLY 439 | minutes_close_so_far = 0 440 | curr_distance = storm_max_distance 441 | if normal_early == True: 442 | generatorSets.append( ( 'earlyOnly', entry_rate, storm_early_strikes, storm_early_energy_range, storm_early_duration_minutes ) ) 443 | 444 | elif split_early == True: 445 | # hmm need to spread strikes across all parts 446 | rem_minutes_early = storm_early_duration_minutes 447 | rem_early_strikes = storm_early_strikes 448 | 449 | if minutes_before_closest > 0: 450 | # have early before CLOSE 451 | percent_early = minutes_before_closest / storm_early_duration_minutes 452 | before_strikes = round(storm_early_strikes * percent_early) 453 | generatorSets.append( ( 'earlyBefore', entry_rate, before_strikes, storm_early_energy_range, round(minutes_before_closest,3) ) ) 454 | rem_minutes_early -= minutes_before_closest 455 | rem_early_strikes -= before_strikes 456 | 457 | if minutes_until_leave_closest < storm_early_duration_minutes: 458 | # generate CLOSE part 459 | percent_close = minutes_while_closest / rem_minutes_early 460 | close_strikes = round(rem_early_strikes * percent_close) 461 | generatorSets.append( ( 'earlyClose', 0, close_strikes, storm_early_energy_range, round(minutes_while_closest,3) ) ) 462 | rem_minutes_early -= minutes_while_closest 463 | rem_early_strikes -= close_strikes 464 | minutes_close_so_far = minutes_while_closest 465 | # generate trailing EARLY-NOT_CLOSE part 466 | generatorSets.append( ( 'earlyAfter', exit_rate, rem_early_strikes, storm_early_energy_range, round(rem_minutes_early,3) ) ) 467 | else: 468 | # end with CLOSE part 469 | generatorSets.append( ( 'earlyClose', 0, storm_early_strikes, storm_early_energy_range, round(rem_minutes_early,3) ) ) 470 | minutes_close_so_far = rem_minutes_early 471 | 472 | # ----------------------------------------------------- 473 | # MIDDLE 474 | if normal_middle == True: 475 | desired_rate = entry_rate 476 | if middle_is_exit_rate: 477 | desired_rate = exit_rate 478 | generatorSets.append( ( 'middleOnly', desired_rate, storm_middle_strikes, storm_middle_energy_range, round(storm_middle_duration_minutes,3) ) ) 479 | 480 | elif close_only_middle == True: 481 | generatorSets.append( ( 'middleCloseOnly', 0, storm_middle_strikes, storm_middle_energy_range, round(storm_middle_duration_minutes,3) ) ) 482 | minutes_close_so_far += storm_middle_duration_minutes 483 | 484 | elif split_middle == True: 485 | # hmm need to spread strikes across all parts 486 | rem_minutes_middle = storm_middle_duration_minutes 487 | rem_middle_strikes = storm_middle_strikes 488 | start_of_middle = storm_early_duration_minutes 489 | rem_close_minutes = minutes_while_closest - minutes_close_so_far 490 | 491 | if minutes_before_closest > start_of_middle: 492 | # have middle before CLOSE 493 | minutes_before = minutes_before_closest - start_of_middle 494 | percent_middle = minutes_before_closest / storm_middle_duration_minutes 495 | before_strikes = int(storm_middle_strikes * percent_middle) 496 | generatorSets.append( ( 'middleBefore', entry_rate, before_strikes, storm_middle_energy_range, round(minutes_before,3) ) ) 497 | rem_minutes_middle -= minutes_before 498 | rem_middle_strikes -= before_strikes 499 | 500 | if rem_close_minutes < rem_minutes_middle: 501 | # generate CLOSE part 502 | percent_close = rem_close_minutes / rem_minutes_middle 503 | close_strikes = int(rem_middle_strikes * percent_close) 504 | generatorSets.append( ( 'middleClose', 0, close_strikes, storm_middle_energy_range, round(rem_close_minutes,3) ) ) 505 | rem_minutes_middle -= rem_close_minutes 506 | rem_middle_strikes -= close_strikes 507 | minutes_close_so_far += rem_close_minutes 508 | # generate trailing MIDDLE-NOT-CLOSE part 509 | generatorSets.append( ( 'middleAfter', exit_rate, rem_middle_strikes, storm_middle_energy_range, round(rem_minutes_middle,3) ) ) 510 | else: 511 | # end with CLOSE part 512 | generatorSets.append( ( 'middleEndClose', 0, rem_middle_strikes, storm_middle_energy_range, round(rem_minutes_middle,3) ) ) 513 | minutes_close_so_far += rem_minutes_middle 514 | 515 | # ----------------------------------------------------- 516 | # LATE 517 | if normal_late == True: 518 | generatorSets.append( ( 'lateOnly', exit_rate, storm_late_strikes, storm_late_energy_range, round(storm_late_duration_minutes,3) ) ) 519 | 520 | elif split_late == True: 521 | # hmm need to spread strikes across all parts 522 | rem_minutes_late = storm_late_duration_minutes 523 | rem_late_strikes = storm_late_strikes 524 | start_of_late = storm_early_duration_minutes + storm_middle_duration_minutes 525 | rem_close_minutes = minutes_while_closest - minutes_close_so_far 526 | 527 | if minutes_before_closest > start_of_late: 528 | # have late before CLOSE 529 | minutes_before = minutes_before_closest - start_of_late 530 | percent_late = minutes_before_closest / storm_late_duration_minutes 531 | before_strikes = int(storm_late_strikes * percent_late) 532 | generatorSets.append( ( 'lateBefore', entry_rate, before_strikes, storm_late_energy_range, round(minutes_before,3) ) ) 533 | rem_minutes_late -= minutes_before 534 | rem_late_strikes -= before_strikes 535 | 536 | if rem_close_minutes < rem_minutes_late: 537 | # generate CLOSE 538 | percent_close = rem_close_minutes / rem_minutes_late 539 | close_strikes = int(rem_late_strikes * percent_close) 540 | generatorSets.append( ( 'lateClose', 0, close_strikes, storm_late_energy_range, round(rem_close_minutes,3) ) ) 541 | rem_minutes_late -= rem_close_minutes 542 | rem_late_strikes -= close_strikes 543 | minutes_close_so_far += rem_close_minutes 544 | # generate trailing LATE-NOT-CLOSE part 545 | generatorSets.append( ( 'lateAfter', exit_rate, rem_late_strikes, storm_late_energy_range, round(rem_minutes_late,3) ) ) 546 | else: 547 | # end with CLOSE part 548 | generatorSets.append( ( 'lateEndClose', 0, rem_late_strikes, storm_late_energy_range, round(rem_minutes_late,3) ) ) 549 | minutes_close_so_far += rem_minutes_late 550 | 551 | set_time_in_seconds = 0 552 | for currSet in generatorSets: 553 | start_time_hms = stringTimeSecondsInHMS(set_time_in_seconds) 554 | set_time_in_seconds += (currSet[4] * 60) 555 | end_time_hms = stringTimeSecondsInHMS(set_time_in_seconds - 1) 556 | tupleString = '{}'.format(currSet) 557 | print_line('generator set --- {:>45} --- {} - {}'.format(tupleString, start_time_hms, end_time_hms), debug=True) 558 | 559 | 560 | # ----------------------------------------------------- 561 | # Let's generate us some lightning! 562 | # 563 | # number of distance values 564 | MAX_DISTANCE_VALUES = 14 565 | OUT_OF_RANGE = 43 566 | OUT_OF_RANGE_ACTUAL = 63 567 | 568 | # adjusted table replacing 63 w/41 to make more sensical outcome 569 | distanceValueToIndexList = list(( 1, 5, 6, 8, 10, 12, 14, 17, 20, 24, 27, 31, 34, 37, 40, OUT_OF_RANGE )) 570 | if len(distanceValueToIndexList) != 1 + MAX_DISTANCE_VALUES + 1: 571 | raise TypeError("[CODE] the distanceValueToIndexList must have 16 entries!! Aborting!") 572 | 573 | curr_distance = storm_max_distance 574 | curr_time_in_seconds = 0 575 | 576 | def byTime(e): 577 | return e[0] 578 | 579 | def detectorValueFromDistance(distance_km): 580 | desired_value = 63 581 | prior_Value = 1 582 | #print_line('- distance_km={}'.format(distance_km), debug=True) 583 | for distanceIndex in range(len(distanceValueToIndexList)): # 0-15 584 | curr_Value = distanceValueToIndexList[distanceIndex] 585 | #print_line(' -- curr_Value={}'.format(curr_Value), debug=True) 586 | if curr_Value > distance_km: 587 | desired_value = prior_Value 588 | #print_line(' -- desired_value={}'.format(desired_value), debug=True) 589 | break 590 | else: 591 | prior_Value = curr_Value 592 | #print_line(' -- prior_Value={}'.format(prior_Value), debug=True) 593 | continue 594 | if desired_value == OUT_OF_RANGE: 595 | desired_value = OUT_OF_RANGE_ACTUAL 596 | #print_line(' -- desired_value={}'.format(desired_value), debug=True) 597 | return desired_value 598 | 599 | if opt_write_file: 600 | print_line('Writing file: {}'.format(output_filename), info=True) 601 | output_line_count = 0 602 | 603 | print_line('{}'.format('# record-nbr, time-seconds, dist_km, energy'), console=False, write=True) 604 | line_number = 1 605 | for currSet in generatorSets: 606 | curr_time_hmsstr = stringTimeSecondsInHMS(curr_time_in_seconds) 607 | print_line('start {} from {} km'.format(curr_time_hmsstr, curr_distance)) 608 | print_line('# start {} from {} km'.format(curr_time_hmsstr, curr_distance), console=False, write=True) 609 | # generate lightning for set... 610 | # ( name, travel-rate, count, energy(min-max), duration_in_minutes ) 611 | print_line('- set {}'.format(currSet[0]), debug=True) 612 | print_line(' -- rate={}'.format(currSet[1]), debug=True) 613 | print_line(' -- ct={}'.format(currSet[2]), debug=True) 614 | print_line(' -- energy={}'.format(currSet[3]), debug=True) 615 | print_line(' -- minutes={}'.format(currSet[4]), debug=True) 616 | 617 | # hh:mm distance energy 618 | detections = [] 619 | scale = 100 # handle 9.99 format float 620 | for i in range(currSet[2]): 621 | when = random.randrange(0, currSet[4] * scale) 622 | if when > 0: 623 | when /= scale 624 | time_in_seconds = round(((when * 60) + curr_time_in_seconds),1) 625 | energy_range = currSet[3] 626 | #print_line(' -- energy_range={}'.format(energy_range), debug=True) 627 | energy = random.randrange(energy_range[0], energy_range[1]) 628 | raw_distance_km = (when * currSet[1]) + curr_distance 629 | distance_km = detectorValueFromDistance(raw_distance_km) 630 | print_line('using {} for {}'.format(distance_km, raw_distance_km), debug=True) 631 | detections.append( (time_in_seconds, distance_km, energy) ) 632 | 633 | 634 | for detection in sorted(detections, key=byTime): 635 | curr_time_hmsstr = stringTimeSecondsInHMS(detection[0]) 636 | print_line(' -- detection={} {}'.format(curr_time_hmsstr, detection), debug=True) 637 | print_line('{}, {}, {}, {}'.format(line_number, detection[0], detection[1], detection[2]), console=False, write=True) 638 | line_number += 1 639 | 640 | curr_time_in_seconds += currSet[4] * 60 641 | curr_distance = round((currSet[4] * currSet[1]) + curr_distance,1) 642 | 643 | if opt_write_file: 644 | print_line('Write {} lines to file: {}'.format(output_line_count, output_filename), info=True) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------