1 /*
2  * Copyright (c) 2019 Manivannan Sadhasivam
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/device.h>
8 #include <zephyr/drivers/lora.h>
9 #include <errno.h>
10 #include <zephyr/sys/util.h>
11 #include <zephyr/kernel.h>
12 
13 #define DEFAULT_RADIO_NODE DT_ALIAS(lora0)
14 BUILD_ASSERT(DT_NODE_HAS_STATUS_OKAY(DEFAULT_RADIO_NODE),
15 	     "No default LoRa radio specified in DT");
16 
17 #define MAX_DATA_LEN 255
18 
19 #define LOG_LEVEL CONFIG_LOG_DEFAULT_LEVEL
20 #include <zephyr/logging/log.h>
21 LOG_MODULE_REGISTER(lora_receive);
22 
lora_receive_cb(const struct device * dev,uint8_t * data,uint16_t size,int16_t rssi,int8_t snr,void * user_data)23 void lora_receive_cb(const struct device *dev, uint8_t *data, uint16_t size,
24 		     int16_t rssi, int8_t snr, void *user_data)
25 {
26 	static int cnt;
27 
28 	ARG_UNUSED(dev);
29 	ARG_UNUSED(size);
30 	ARG_UNUSED(user_data);
31 
32 	LOG_INF("LoRa RX RSSI: %d dBm, SNR: %d dB", rssi, snr);
33 	LOG_HEXDUMP_INF(data, size, "LoRa RX payload");
34 
35 	/* Stop receiving after 10 packets */
36 	if (++cnt == 10) {
37 		LOG_INF("Stopping packet receptions");
38 		lora_recv_async(dev, NULL, NULL);
39 	}
40 }
41 
main(void)42 int main(void)
43 {
44 	const struct device *const lora_dev = DEVICE_DT_GET(DEFAULT_RADIO_NODE);
45 	struct lora_modem_config config;
46 	int ret, len;
47 	uint8_t data[MAX_DATA_LEN] = {0};
48 	int16_t rssi;
49 	int8_t snr;
50 
51 	if (!device_is_ready(lora_dev)) {
52 		LOG_ERR("%s Device not ready", lora_dev->name);
53 		return 0;
54 	}
55 
56 	config.frequency = 865100000;
57 	config.bandwidth = BW_125_KHZ;
58 	config.datarate = SF_10;
59 	config.preamble_len = 8;
60 	config.coding_rate = CR_4_5;
61 	config.iq_inverted = false;
62 	config.public_network = false;
63 	config.tx_power = 14;
64 	config.tx = false;
65 
66 	ret = lora_config(lora_dev, &config);
67 	if (ret < 0) {
68 		LOG_ERR("LoRa config failed");
69 		return 0;
70 	}
71 
72 	/* Receive 4 packets synchronously */
73 	LOG_INF("Synchronous reception");
74 	for (int i = 0; i < 4; i++) {
75 		/* Block until data arrives */
76 		len = lora_recv(lora_dev, data, MAX_DATA_LEN, K_FOREVER,
77 				&rssi, &snr);
78 		if (len < 0) {
79 			LOG_ERR("LoRa receive failed");
80 			return 0;
81 		}
82 
83 		LOG_INF("LoRa RX RSSI: %d dBm, SNR: %d dB", rssi, snr);
84 		LOG_HEXDUMP_INF(data, len, "LoRa RX payload");
85 	}
86 
87 	/* Enable asynchronous reception */
88 	LOG_INF("Asynchronous reception");
89 	lora_recv_async(lora_dev, lora_receive_cb, NULL);
90 	k_sleep(K_FOREVER);
91 	return 0;
92 }
93