From e515484e2639832f08b2170d4dfadc7ab2e976a2 Mon Sep 17 00:00:00 2001 From: CARNEIRO--GILLET Alexandre <alexandre.carneiro-gillet@imt-atlantique.net> Date: Tue, 1 Apr 2025 10:38:43 +0200 Subject: [PATCH] =?UTF-8?q?ajout=20PyLoRa=20(m=C3=AAme=20que=20uPyLoRaWAN?= =?UTF-8?q?=20mais=20nettoy=C3=A9)=20+=20gantt=20update?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Autre/gantt.puml | 25 +- GW-custom/PyLoRa/LICENSE | 201 ++++++++ GW-custom/PyLoRa/README.md | 7 + GW-custom/PyLoRa/main.py | 62 +++ GW-custom/PyLoRa/sx127x/__init__.py | 10 + GW-custom/PyLoRa/sx127x/configurations.py | 136 +++++ GW-custom/PyLoRa/sx127x/sx127x.py | 485 ++++++++++++++++++ GW-custom/uPyLoRaWAN/README.md | 11 +- .../{config.sample.py => config.py} | 4 +- 9 files changed, 930 insertions(+), 11 deletions(-) create mode 100644 GW-custom/PyLoRa/LICENSE create mode 100644 GW-custom/PyLoRa/README.md create mode 100644 GW-custom/PyLoRa/main.py create mode 100644 GW-custom/PyLoRa/sx127x/__init__.py create mode 100644 GW-custom/PyLoRa/sx127x/configurations.py create mode 100644 GW-custom/PyLoRa/sx127x/sx127x.py rename GW-custom/uPyLoRaWAN/{config.sample.py => config.py} (95%) diff --git a/Autre/gantt.puml b/Autre/gantt.puml index 0c5abad..8df1a2b 100644 --- a/Autre/gantt.puml +++ b/Autre/gantt.puml @@ -1,12 +1,14 @@ -@startgantt +@startgantt Diagramme de Gantt projet Pronto Language fr hide footbox Project starts 2025-02-04 -today is colored in grey +!$now = %now() +!$today = %date("YYYY-MM-dd", $now) +$today is colored in grey [Capteur V1] as [C1] starts 2025-02-13 and requires 30 days @@ -16,18 +18,27 @@ today is colored in grey [Document de cadrage] happens 2025-02-23 [Capteur autonome suite] as [C2s] starts at [C2]'s end and requires 17 days -[C2s] displays on same row as [C2] +[C2s] displays on same row as [C2] and is 90% completed -[GW V2] starts 2025-02-20 and requires 40 days -[GW custom] starts 2025-02-20 and requires 40 days +[GW V2] starts 2025-02-20 and requires 40 days and is 90% completed +[GW custom] starts 2025-02-20 and requires 40 days and is 40% completed -[Integration] as [I] starts 2025-03-22 and ends 2025-04-12 +[Integration] as [I] starts 2025-03-22 and ends 2025-04-12 and is 5% completed [Revue de projet] happens 2025-03-27 -[Qualifier le système] starts at [I]'s end and requires 2 weeks +[Qualifier le système] starts at [I]'s end and requires 2 weeks and is 0% completed [Recette du projet] happens 2025-05-23 +[Capteur autonome (deadline dépassée)] as [C2sb] starts at [C2s]'s end and ends $today +[C2sb] displays on same row as [C2s] and is colored in IndianRed/DarkRed + +[GW V2 (deadline dépassée)] as [GW2b] starts at [GW V2]'s end and ends $today +[GW2b] displays on same row as [GW V2] and is colored in IndianRed/DarkRed + +[GW custom (deadline dépassée)] as [GWCb] starts at [GW custom]'s end and ends $today +[GWCb] displays on same row as [GW custom] and is colored in IndianRed/DarkRed + @endgantt \ No newline at end of file diff --git a/GW-custom/PyLoRa/LICENSE b/GW-custom/PyLoRa/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/GW-custom/PyLoRa/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/GW-custom/PyLoRa/README.md b/GW-custom/PyLoRa/README.md new file mode 100644 index 0000000..a6a524e --- /dev/null +++ b/GW-custom/PyLoRa/README.md @@ -0,0 +1,7 @@ +# PyLoRa + +A minimal LoRa library for the TTGO LoRa ESP32 based on [lemariva GitHub](https://github.com/lemariva/uPyLoRaWAN). + +[Github](https://github.com/lh70/PyLoRa) + +WIP diff --git a/GW-custom/PyLoRa/main.py b/GW-custom/PyLoRa/main.py new file mode 100644 index 0000000..b998348 --- /dev/null +++ b/GW-custom/PyLoRa/main.py @@ -0,0 +1,62 @@ +from time import sleep +from machine import Pin, SoftSPI +from sx127x import SX127x + + +# ES32 TTGO v1.0 +device_config = { + 'miso':19, + 'mosi':27, + 'ss':18, + 'sck':5, + 'dio_0':26, + 'reset':14, + 'led':2, +} + + +lora_parameters = { + 'frequency': 868E6, + 'tx_power_level': 2, + 'signal_bandwidth': 125E3, + 'spreading_factor': 8, + 'coding_rate': 5, + 'preamble_length': 8, + 'implicit_header': False, + 'sync_word': 0x12, + 'enable_CRC': False, + 'invert_IQ': False, +} + + +device_spi = SoftSPI(baudrate = 10000000, + polarity = 0, phase = 0, bits = 8, firstbit = SoftSPI.MSB, + sck = Pin(device_config['sck'], Pin.OUT, Pin.PULL_DOWN), + mosi = Pin(device_config['mosi'], Pin.OUT, Pin.PULL_UP), + miso = Pin(device_config['miso'], Pin.IN, Pin.PULL_UP)) + +lora = SX127x(device_spi, pins=device_config, parameters=lora_parameters) + +example = 'receiver' # 'sender' 'receiver' + +if __name__ == '__main__': + if example == 'sender': + counter = 0 + print('LoRa Sender') + + while True: + payload = 'Hello ({0})'.format(counter) + print("sending packet: \n{} ...".format(payload), end='') + lora.send(payload.encode()) + print("done\n") + + counter += 1 + sleep(5) + if example == 'receiver': + print('LoRa Receiver') + + while True: + payload = lora.try_receive() + if payload: + lora.blink_led() + print('received packet: \n{}\n'.format(payload.decode())) diff --git a/GW-custom/PyLoRa/sx127x/__init__.py b/GW-custom/PyLoRa/sx127x/__init__.py new file mode 100644 index 0000000..96cb476 --- /dev/null +++ b/GW-custom/PyLoRa/sx127x/__init__.py @@ -0,0 +1,10 @@ +from .sx127x import SX127x +from .configurations import DEVICE_CONFIG_ESP32_TTGO, \ + DEVICE_CONFIG_M5STACK_LORA868, \ + DEVICE_CONFIG_M5STACK_ATOM_MATRIX, \ + LORA_PARAMETERS_DEFAULT, \ + LORA_PARAMETERS_RH_RF95_bw125cr45sf128, \ + LORA_PARAMETERS_RH_RF95_bw125cr45sf2048, \ + LORA_PARAMETERS_RH_RF95_bw125cr48sf4096, \ + LORA_PARAMETERS_RH_RF95_bw31_25cr48sf512, \ + LORA_PARAMETERS_RH_RF95_bw500cr45sf128 diff --git a/GW-custom/PyLoRa/sx127x/configurations.py b/GW-custom/PyLoRa/sx127x/configurations.py new file mode 100644 index 0000000..19a9cfe --- /dev/null +++ b/GW-custom/PyLoRa/sx127x/configurations.py @@ -0,0 +1,136 @@ +# Copyright 2020 LeMaRiva|tech lemariva.com +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + + +# ESP32 TTGO v1.0 +DEVICE_CONFIG_ESP32_TTGO = { + 'miso': 19, + 'mosi': 27, + 'ss': 18, + 'sck': 5, + 'dio_0': 26, + 'reset': 14, + 'led': 2, +} + +# M5Stack ATOM Matrix +DEVICE_CONFIG_M5STACK_ATOM_MATRIX = { + 'miso': 23, + 'mosi': 19, + 'ss': 22, + 'sck': 33, + 'dio_0': 25, + 'reset': 21, + 'led': 12, +} + +# M5Stack & LoRa868 Module +DEVICE_CONFIG_M5STACK_LORA868 = { + 'miso': 19, + 'mosi': 23, + 'ss': 5, + 'sck': 18, + 'dio_0': 26, + 'reset': 36, + 'led': 12, +} + + +LORA_PARAMETERS_DEFAULT = { + 'frequency': 868E6, + 'tx_power_level': 2, + 'signal_bandwidth': 125E3, + 'spreading_factor': 8, # 2^6==64, 2^7==128, 2^8==256, ..., 2^12==4096 + 'coding_rate': 5, # 5==4/5, 6==4/6, 7==4/7, 8==4/8 + 'preamble_length': 8, + 'implicit_header': False, + 'sync_word': 0x12, + 'enable_CRC': False, + 'invert_IQ': False, +} + +""" +LoRa configurations, compatible to rf95modem and RH_RF95 + +https://github.com/gh0st42/rf95modem +https://www.airspayce.com/mikem/arduino/RadioHead/classRH__RF95.html + +todo: check if message format (4 octets HEADER: (TO, FROM, ID, FLAGS)) is non standard +""" +# default medium range configuration +LORA_PARAMETERS_RH_RF95_bw125cr45sf128 = { + 'frequency': 868.1E6, # 868.1E6 or 434E6 + 'tx_power_level': 2, + 'signal_bandwidth': 125E3, + 'spreading_factor': 7, + 'coding_rate': 5, + 'preamble_length': 8, + 'implicit_header': False, + 'sync_word': 0x12, + 'enable_CRC': True, + 'invert_IQ': False, +} +# fast + short range configuration +LORA_PARAMETERS_RH_RF95_bw500cr45sf128 = { + 'frequency': 868.1E6, # 868.1E6 or 434E6 + 'tx_power_level': 2, + 'signal_bandwidth': 500E3, + 'spreading_factor': 7, + 'coding_rate': 5, + 'preamble_length': 8, + 'implicit_header': False, + 'sync_word': 0x12, + 'enable_CRC': True, + 'invert_IQ': False, +} +# slow + long range configuration +LORA_PARAMETERS_RH_RF95_bw31_25cr48sf512 = { + 'frequency': 868.1E6, # 868.1E6 or 434E6 + 'tx_power_level': 2, + 'signal_bandwidth': 31.25E3, + 'spreading_factor': 9, + 'coding_rate': 8, + 'preamble_length': 8, + 'implicit_header': False, + 'sync_word': 0x12, + 'enable_CRC': True, + 'invert_IQ': False, +} +# slow + long range configuration +LORA_PARAMETERS_RH_RF95_bw125cr48sf4096 = { + 'frequency': 868.1E6, # 868.1E6 or 434E6 + 'tx_power_level': 2, + 'signal_bandwidth': 125E3, + 'spreading_factor': 12, + 'coding_rate': 8, + 'preamble_length': 8, + 'implicit_header': False, + 'sync_word': 0x12, + 'enable_CRC': True, + 'invert_IQ': False, +} +# slow + long range configuration +LORA_PARAMETERS_RH_RF95_bw125cr45sf2048 = { + 'frequency': 868.1E6, # 868.1E6 or 434E6 + 'tx_power_level': 2, + 'signal_bandwidth': 125E3, + 'spreading_factor': 11, + 'coding_rate': 5, + 'preamble_length': 8, + 'implicit_header': False, + 'sync_word': 0x12, + 'enable_CRC': True, + 'invert_IQ': False, +} diff --git a/GW-custom/PyLoRa/sx127x/sx127x.py b/GW-custom/PyLoRa/sx127x/sx127x.py new file mode 100644 index 0000000..de0fd36 --- /dev/null +++ b/GW-custom/PyLoRa/sx127x/sx127x.py @@ -0,0 +1,485 @@ +from time import sleep +from typing import Optional + +from machine import Pin + + +PA_OUTPUT_RFO_PIN = 0 +PA_OUTPUT_PA_BOOST_PIN = 1 + +# registers +REG_FIFO = 0x00 +REG_OP_MODE = 0x01 +REG_FRF_MSB = 0x06 +REG_FRF_MID = 0x07 +REG_FRF_LSB = 0x08 +REG_PA_CONFIG = 0x09 +REG_LNA = 0x0c +REG_FIFO_ADDR_PTR = 0x0d + +REG_FIFO_TX_BASE_ADDR = 0x0e +FifoTxBaseAddr = 0x00 +FifoRxBaseAddr = 0x00 + +REG_FIFO_RX_BASE_ADDR = 0x0f +REG_FIFO_RX_CURRENT_ADDR = 0x10 +REG_IRQ_FLAGS_MASK = 0x11 +REG_IRQ_FLAGS = 0x12 +REG_RX_NB_BYTES = 0x13 +REG_PKT_RSSI_VALUE = 0x1a +REG_PKT_SNR_VALUE = 0x1b +REG_MODEM_CONFIG_1 = 0x1d +REG_MODEM_CONFIG_2 = 0x1e +REG_PREAMBLE_MSB = 0x20 +REG_PREAMBLE_LSB = 0x21 +REG_PAYLOAD_LENGTH = 0x22 +REG_FIFO_RX_BYTE_ADDR = 0x25 +REG_MODEM_CONFIG_3 = 0x26 +REG_RSSI_WIDEBAND = 0x2c +REG_DETECTION_OPTIMIZE = 0x31 +REG_DETECTION_THRESHOLD = 0x37 +REG_SYNC_WORD = 0x39 +REG_DIO_MAPPING_1 = 0x40 +REG_VERSION = 0x42 + +# invert IQ +REG_INVERTIQ = 0x33 +RFLR_INVERTIQ_RX_MASK = 0xBF +RFLR_INVERTIQ_RX_OFF = 0x00 +RFLR_INVERTIQ_RX_ON = 0x40 +RFLR_INVERTIQ_TX_MASK = 0xFE +RFLR_INVERTIQ_TX_OFF = 0x01 +RFLR_INVERTIQ_TX_ON = 0x00 + +REG_INVERTIQ2 = 0x3B +RFLR_INVERTIQ2_ON = 0x19 +RFLR_INVERTIQ2_OFF = 0x1D + +# modes +MODE_LONG_RANGE_MODE = 0x80 # bit 7: 1 => LoRa mode +MODE_SLEEP = 0x00 +MODE_STDBY = 0x01 +MODE_TX = 0x03 +MODE_RX_CONTINUOUS = 0x05 +MODE_RX_SINGLE = 0x06 + +# PA config +PA_BOOST = 0x80 + +# IRQ masks +IRQ_TX_DONE_MASK = 0x08 +IRQ_PAYLOAD_CRC_ERROR_MASK = 0x20 +IRQ_RX_DONE_MASK = 0x40 +IRQ_RX_TIME_OUT_MASK = 0x80 + +# Buffer size +MAX_PKT_LENGTH = 255 + +__DEBUG__ = True + + +class SX127x: + + default_parameters = { + 'frequency': 868E6, + 'tx_power_level': 2, + 'signal_bandwidth': 125E3, + 'spreading_factor': 8, + 'coding_rate': 5, + 'preamble_length': 8, + 'implicit_header': False, + 'sync_word': 0x12, + 'enable_CRC': False, + 'invert_IQ': False, + } + + def __init__(self, spi, pins, parameters=default_parameters): + + self._spi = spi + self._pins = pins + self._parameters = parameters + self._lock = False + + # setting pins + if "dio_0" in self._pins: + self._pin_rx_done = Pin(self._pins["dio_0"], Pin.IN) + if "ss" in self._pins: + self._pin_ss = Pin(self._pins["ss"], Pin.OUT) + if "led" in self._pins: + self._led_status = Pin(self._pins["led"], Pin.OUT) + + # check hardware version + re_try = 0 + version = 0 + while re_try < 5: + version = self.read_register(REG_VERSION) + re_try += 1 + if version != 0: + break + + if __DEBUG__: + print("SX version: {}".format(version)) + + if version != 0x12: + raise Exception('Invalid version.') + + # put in LoRa and sleep mode + self.sleep() + + # config + self.set_frequency(self._parameters['frequency']) + self.set_signal_bandwidth(self._parameters['signal_bandwidth']) + + # set LNA boost + self.write_register(REG_LNA, self.read_register(REG_LNA) | 0x03) + + # set auto AGC + self.write_register(REG_MODEM_CONFIG_3, 0x04) + + self.set_tx_power(self._parameters['tx_power_level']) + self._implicit_header_mode = None + self.implicit_header_mode(self._parameters['implicit_header']) + self.set_spreading_factor(self._parameters['spreading_factor']) + self.set_coding_rate(self._parameters['coding_rate']) + self.set_preamble_length(self._parameters['preamble_length']) + self.set_sync_word(self._parameters['sync_word']) + self.enable_crc(self._parameters['enable_CRC']) + self.invert_iq(self._parameters["invert_IQ"]) + + # set LowDataRateOptimize flag if symbol time > 16ms (default disable on reset) + # self.write_register(REG_MODEM_CONFIG_3, self.read_register(REG_MODEM_CONFIG_3) & 0xF7) # default disable on reset + bw_parameter = self._parameters["signal_bandwidth"] + sf_parameter = self._parameters["spreading_factor"] + + if 1000 / (bw_parameter / 2**sf_parameter) > 16: + self.write_register( + REG_MODEM_CONFIG_3, + self.read_register(REG_MODEM_CONFIG_3) | 0x08 + ) + + # set base addresses + self.write_register(REG_FIFO_TX_BASE_ADDR, FifoTxBaseAddr) + self.write_register(REG_FIFO_RX_BASE_ADDR, FifoRxBaseAddr) + + self.standby() + + def begin_packet(self, implicit_header_mode=False): + self.standby() + self.implicit_header_mode(implicit_header_mode) + + # reset FIFO address and payload length + self.write_register(REG_FIFO_ADDR_PTR, FifoTxBaseAddr) + self.write_register(REG_PAYLOAD_LENGTH, 0) + + def end_packet(self): + # put in TX mode + self.write_register(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_TX) + + # wait for TX done, standby automatically on TX_DONE + while self.read_register(REG_IRQ_FLAGS) & IRQ_TX_DONE_MASK == 0: + pass + + # clear IRQ's + self.write_register(REG_IRQ_FLAGS, IRQ_TX_DONE_MASK) + + def write(self, buffer): + current_length = self.read_register(REG_PAYLOAD_LENGTH) + size = len(buffer) + + # check size + size = min(size, (MAX_PKT_LENGTH - FifoTxBaseAddr - current_length)) + + # write data + for i in range(size): + self.write_register(REG_FIFO, buffer[i]) + + # update length + self.write_register(REG_PAYLOAD_LENGTH, current_length + size) + return size + + def set_lock(self, lock=False): + self._lock = lock + + def send(self, message: bytes, implicit_header=False): + self.set_lock(True) # wait until RX_Done, lock and begin writing. + + self.begin_packet(implicit_header) + + self.write(message) + + self.end_packet() + + self.set_lock(False) # unlock when done writing + + def get_irq_flags(self): + irq_flags = self.read_register(REG_IRQ_FLAGS) + self.write_register(REG_IRQ_FLAGS, irq_flags) + return irq_flags + + def packet_rssi(self): + rssi = self.read_register(REG_PKT_RSSI_VALUE) + return rssi - (164 if self._frequency < 868E6 else 157) + + def packet_snr(self): + snr = self.read_register(REG_PKT_SNR_VALUE) + return snr * 0.25 + + def standby(self): + self.write_register(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_STDBY) + + def sleep(self): + self.write_register(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_SLEEP) + + def set_tx_power(self, level, output_pin=PA_OUTPUT_PA_BOOST_PIN): + # todo: add option to use non-boost pin + self._tx_power_level = level + + if output_pin == PA_OUTPUT_RFO_PIN: + # RFO + level = min(max(level, 0), 14) + self.write_register(REG_PA_CONFIG, 0x70 | level) + + else: + # PA BOOST + level = min(max(level, 2), 17) + self.write_register(REG_PA_CONFIG, PA_BOOST | (level - 2)) + + def set_frequency(self, frequency): + self._frequency = frequency + + freq_reg = int(int(int(frequency) << 19) / 32000000) & 0xFFFFFF + + self.write_register(REG_FRF_MSB, (freq_reg & 0xFF0000) >> 16) + self.write_register(REG_FRF_MID, (freq_reg & 0xFF00) >> 8) + self.write_register(REG_FRF_LSB, (freq_reg & 0xFF)) + + def set_spreading_factor(self, sf): + sf = min(max(sf, 6), 12) + self.write_register(REG_DETECTION_OPTIMIZE, 0xc5 if sf == 6 else 0xc3) + self.write_register(REG_DETECTION_THRESHOLD, 0x0c if sf == 6 else 0x0a) + self.write_register( + REG_MODEM_CONFIG_2, + (self.read_register(REG_MODEM_CONFIG_2) & 0x0f) | ((sf << 4) & 0xf0) + ) + + def set_signal_bandwidth(self, sbw): + bins = (7.8E3, 10.4E3, 15.6E3, 20.8E3, 31.25E3, 41.7E3, 62.5E3, 125E3, 250E3) + + bw = 9 + + if sbw < 10: + bw = sbw + else: + for i in range(len(bins)): + if sbw <= bins[i]: + bw = i + break + + self.write_register( + REG_MODEM_CONFIG_1, + (self.read_register(REG_MODEM_CONFIG_1) & 0x0f) | (bw << 4) + ) + + def set_coding_rate(self, denominator): + denominator = min(max(denominator, 5), 8) + cr = denominator - 4 + self.write_register( + REG_MODEM_CONFIG_1, + (self.read_register(REG_MODEM_CONFIG_1) & 0xf1) | (cr << 1) + ) + + def set_preamble_length(self, length): + self.write_register(REG_PREAMBLE_MSB, (length >> 8) & 0xff) + self.write_register(REG_PREAMBLE_LSB, (length >> 0) & 0xff) + + def enable_crc(self, enable_crc=False): + modem_config_2 = self.read_register(REG_MODEM_CONFIG_2) + config = modem_config_2 | 0x04 if enable_crc else modem_config_2 & 0xfb + self.write_register(REG_MODEM_CONFIG_2, config) + + def invert_iq(self, invert_iq): + self._parameters["invertIQ"] = invert_iq + if invert_iq: + self.write_register( + REG_INVERTIQ, + ( + ( + self.read_register(REG_INVERTIQ) + & RFLR_INVERTIQ_TX_MASK + & RFLR_INVERTIQ_RX_MASK + ) + | RFLR_INVERTIQ_RX_ON + | RFLR_INVERTIQ_TX_ON + ), + ) + self.write_register(REG_INVERTIQ2, RFLR_INVERTIQ2_ON) + else: + self.write_register( + REG_INVERTIQ, + ( + ( + self.read_register(REG_INVERTIQ) + & RFLR_INVERTIQ_TX_MASK + & RFLR_INVERTIQ_RX_MASK + ) + | RFLR_INVERTIQ_RX_OFF + | RFLR_INVERTIQ_TX_OFF + ), + ) + self.write_register(REG_INVERTIQ2, RFLR_INVERTIQ2_OFF) + + def set_sync_word(self, sw): + self.write_register(REG_SYNC_WORD, sw) + + def set_channel(self, parameters): + self.standby() + for key in parameters: + if key == "frequency": + self.set_frequency(parameters[key]) + continue + if key == "invert_IQ": + self.invert_iq(parameters[key]) + continue + if key == "tx_power_level": + self.set_tx_power(parameters[key]) + continue + + def dump_registers(self): + for i in range(128): + print("0x{:02X}: {:02X}".format(i, self.read_register(i)), end="") + if (i + 1) % 4 == 0: + print() + else: + print(" | ", end="") + + def implicit_header_mode(self, implicit_header_mode = False): + if self._implicit_header_mode != implicit_header_mode: # set value only if different. + self._implicit_header_mode = implicit_header_mode + modem_config_1 = self.read_register(REG_MODEM_CONFIG_1) + config = (modem_config_1 | 0x01 + if implicit_header_mode else modem_config_1 & 0xfe) + self.write_register(REG_MODEM_CONFIG_1, config) + + def receive(self, size=0): + self.implicit_header_mode(size > 0) + if size > 0: + self.write_register(REG_PAYLOAD_LENGTH, size & 0xff) + + # The last packet always starts at FIFO_RX_CURRENT_ADDR + # no need to reset FIFO_ADDR_PTR + self.write_register( + REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_RX_CONTINUOUS + ) + + def on_receive(self, callback): + self._on_receive = callback + + if self._pin_rx_done: + if callback: + self.write_register(REG_DIO_MAPPING_1, 0x00) + self._pin_rx_done.irq( + trigger=Pin.IRQ_RISING, handler = self.handle_on_receive + ) + else: + self._pin_rx_done.detach_irq() + + def handle_on_receive(self, event_source): + self.set_lock(True) # lock until TX_Done + irq_flags = self.get_irq_flags() + + if irq_flags == IRQ_RX_DONE_MASK: # RX_DONE only, irq_flags should be 0x40 + # automatically standby when RX_DONE + if self._on_receive: + payload = self.read_payload() + self._on_receive(self, payload) + + elif self.read_register(REG_OP_MODE) != ( + MODE_LONG_RANGE_MODE | MODE_RX_SINGLE + ): + # no packet received. + # reset FIFO address / # enter single RX mode + self.write_register(REG_FIFO_ADDR_PTR, FifoRxBaseAddr) + self.write_register( + REG_OP_MODE, + MODE_LONG_RANGE_MODE | MODE_RX_SINGLE + ) + + self.set_lock(False) # unlock in any case. + return True + + def received_packet(self, size = 0): + irq_flags = self.get_irq_flags() + + self.implicit_header_mode(size > 0) + if size > 0: + self.write_register(REG_PAYLOAD_LENGTH, size & 0xff) + + # if (irq_flags & IRQ_RX_DONE_MASK) and \ + # (irq_flags & IRQ_RX_TIME_OUT_MASK == 0) and \ + # (irq_flags & IRQ_PAYLOAD_CRC_ERROR_MASK == 0): + + if irq_flags == IRQ_RX_DONE_MASK: + # RX_DONE only, irq_flags should be 0x40 + # automatically standby when RX_DONE + return True + + elif self.read_register(REG_OP_MODE) != (MODE_LONG_RANGE_MODE | MODE_RX_SINGLE): + # no packet received. + # reset FIFO address / # enter single RX mode + self.write_register(REG_FIFO_ADDR_PTR, FifoRxBaseAddr) + self.write_register( + REG_OP_MODE, + MODE_LONG_RANGE_MODE | MODE_RX_SINGLE + ) + + def read_payload(self) -> bytes: + # set FIFO address to current RX address + # fifo_rx_current_addr = self.read_register(REG_FIFO_RX_CURRENT_ADDR) + self.write_register( + REG_FIFO_ADDR_PTR, + self.read_register(REG_FIFO_RX_CURRENT_ADDR) + ) + + # read packet length + if self._implicit_header_mode: + packet_length = self.read_register(REG_PAYLOAD_LENGTH) + else: + packet_length = self.read_register(REG_RX_NB_BYTES) + + payload = bytearray() + for i in range(packet_length): + payload.append(self.read_register(REG_FIFO)) + + return bytes(payload) + + def read_register(self, address, byteorder='big'): + response = self.transfer(address & 0x7f) + return int.from_bytes(response, byteorder) + + def write_register(self, address, value): + self.transfer(address | 0x80, value) + + def transfer(self, address, value=0x00): + response = bytearray(1) + + self._pin_ss.value(0) + + self._spi.write(bytes([address])) + self._spi.write_readinto(bytes([value]), response) + + self._pin_ss.value(1) + + return response + + def blink_led(self, times=1, on_seconds=0.1, off_seconds=0.1): + for i in range(times): + if self._led_status: + self._led_status.value(True) + sleep(on_seconds) + self._led_status.value(False) + sleep(off_seconds) + + def try_receive(self) -> Optional[bytes]: + if self.received_packet(): + return self.read_payload() + return None diff --git a/GW-custom/uPyLoRaWAN/README.md b/GW-custom/uPyLoRaWAN/README.md index b22db65..ef6553c 100644 --- a/GW-custom/uPyLoRaWAN/README.md +++ b/GW-custom/uPyLoRaWAN/README.md @@ -1,23 +1,30 @@ # uPyLora -ESP32 using MicroPython meets lora. -This repo includes an sx127x micropython driver to communicate between two devices using LoRa. +ESP32 using MicroPython meets LoRa [here](https://github.com/lemariva/uPyLoRaWAN). + +This repo includes an sx127x micropython driver to communicate between two devices using LoRa. For the LoRaWAN repository click on [here](https://github.com/lemariva/uPyLoRaWAN/tree/LoRaWAN). # Setup + Check out these articles for more information: + * [M5Stack Atom Matrix: LoRaWAN node running MicroPython](https://lemariva.com/blog/2020/03/m5stack-atom-lorawan-node-running-micropython) * [Tutorial: ESP32 running MicroPython sends data over LoRaWAN](https://lemariva.com/blog/2020/02/tutorial-micropython-esp32-sends-data-over-lorawan) # Hardware + * [Wemos® TTGO LORA32 868/915Mhz](https://www.banggood.com/2Pcs-Wemos-TTGO-LORA32-868915Mhz-ESP32-LoRa-OLED-0_96-Inch-Blue-Display-p-1239769.html?p=QW0903761303201409LG) board. # Revision + * 0.1 first commit # Licenses + * Apache 2.0 # References + * Basically based on: [Wei1234c GitHub](https://github.com/Wei1234c/SX127x_driver_for_MicroPython_on_ESP8266). The original project was cleaned and made compatible with the [Wemos® TTGO LORA32 868/915Mhz](https://www.banggood.com/2Pcs-Wemos-TTGO-LORA32-868915Mhz-ESP32-LoRa-OLED-0_96-Inch-Blue-Display-p-1239769.html?p=QW0903761303201409LG) board. diff --git a/GW-custom/uPyLoRaWAN/config.sample.py b/GW-custom/uPyLoRaWAN/config.py similarity index 95% rename from GW-custom/uPyLoRaWAN/config.sample.py rename to GW-custom/uPyLoRaWAN/config.py index 56c117d..379c64a 100644 --- a/GW-custom/uPyLoRaWAN/config.sample.py +++ b/GW-custom/uPyLoRaWAN/config.py @@ -67,6 +67,6 @@ lora_parameters = { } wifi_config = { - 'ssid':'', - 'password':'' + 'ssid':'ObjetsConnectes', + 'password':'Pandemie2021' } \ No newline at end of file -- GitLab