Quality of life improvements

- IP and port can now be specified for Message Socket Sink
- LoRa PHY header can be omitted from Message Socket Sink output
- Removed deprecated blocks
- More utilities
pull/61/head
Pieter Robyns 2017-09-14 16:20:27 +02:00
rodzic 2714c3f2d3
commit f976dfab8e
26 zmienionych plików z 283 dodań i 1346 usunięć

Wyświetl plik

@ -392,6 +392,14 @@ for better accuracy, but worse performance.</value>
</block>
<block>
<key>lora_message_socket_sink</key>
<param>
<key>loraphy</key>
<value>True</value>
</param>
<param>
<key>loratap</key>
<value>False</value>
</param>
<param>
<key>alias</key>
<value></value>
@ -410,7 +418,7 @@ for better accuracy, but worse performance.</value>
</param>
<param>
<key>_coordinate</key>
<value>(640, 208)</value>
<value>(640, 220)</value>
</param>
<param>
<key>_rotation</key>
@ -420,6 +428,14 @@ for better accuracy, but worse performance.</value>
<key>id</key>
<value>lora_message_socket_sink_0</value>
</param>
<param>
<key>ip</key>
<value>127.0.0.1</value>
</param>
<param>
<key>port</key>
<value>40868</value>
</param>
</block>
<block>
<key>osmosdr_source</key>

Wyświetl plik

@ -3,7 +3,7 @@
##################################################
# GNU Radio Python Flow Graph
# Title: Lora Receive Realtime
# Generated: Thu Sep 7 15:47:58 2017
# Generated: Thu Sep 14 16:24:32 2017
##################################################
if __name__ == '__main__':
@ -80,7 +80,7 @@ class lora_receive_realtime(grc_wxgui.top_block_gui):
self.osmosdr_source_0.set_antenna('', 0)
self.osmosdr_source_0.set_bandwidth(0, 0)
self.lora_message_socket_sink_0 = lora.message_socket_sink()
self.lora_message_socket_sink_0 = lora.message_socket_sink('127.0.0.1', 40868, False, True)
self.lora_lora_receiver_0 = lora.lora_receiver(samp_rate, capture_freq, ([target_freq]), sf, internal_sampling_rate, 0.002)
##################################################

Wyświetl plik

@ -1,6 +1,6 @@
# Test suite: 'decode_long_hackrf'
*Results on 2017-09-08 08:55:44.588268*
*Results on 2017-09-14 14:36:37.348840*
### 868.1 MHz, SF 7, CR 4/8, BW 125 kHz, prlen 8, crc on, implicit off

Wyświetl plik

@ -1,6 +1,6 @@
# Test suite: 'decode_long_rtl-sdr'
*Results on 2017-09-08 08:54:28.651745*
*Results on 2017-09-14 14:35:21.382711*
### 868.1 MHz, SF 7, CR 4/8, BW 125 kHz, prlen 8, crc on, implicit off

Wyświetl plik

@ -1,6 +1,6 @@
# Test suite: 'decode_long_usrp'
*Results on 2017-09-08 08:55:05.243706*
*Results on 2017-09-14 14:35:57.973367*
### 868.1 MHz, SF 7, CR 4/8, BW 125 kHz, prlen 8, crc on, implicit off

Wyświetl plik

@ -1,6 +1,6 @@
# Test suite: 'short_hackrf'
*Results on 2017-09-08 10:55:53.535978*
*Results on 2017-09-14 14:45:53.995797*
### 868.1 MHz, SF 7, CR 4/8, BW 125 kHz, prlen 8, crc on, implicit off

Wyświetl plik

@ -1,6 +1,6 @@
# Test suite: 'short_rtl-sdr'
*Results on 2017-09-08 08:56:21.904351*
*Results on 2017-09-14 14:37:14.668511*
### 868.1 MHz, SF 7, CR 4/8, BW 125 kHz, prlen 8, crc on, implicit off

Wyświetl plik

@ -1,6 +1,6 @@
# Test suite: 'short_usrp'
*Results on 2017-09-08 09:00:25.230843*
*Results on 2017-09-14 14:41:17.943080*
### 868.1 MHz, SF 7, CR 4/8, BW 125 kHz, prlen 8, crc on, implicit off

Wyświetl plik

@ -20,7 +20,6 @@
install(FILES
lora_receiver.xml
lora_message_file_sink.xml
lora_message_wireshark_sink.xml
lora_message_socket_sink.xml DESTINATION share/gnuradio/grc/blocks
)

Wyświetl plik

@ -4,13 +4,36 @@
<key>lora_message_socket_sink</key>
<category>[LoRa]</category>
<import>import lora</import>
<make>lora.message_socket_sink()</make>
<make>lora.message_socket_sink($ip, $port, $loratap, $loraphy)</make>
<param>
<name>IP</name>
<key>ip</key>
<value>127.0.0.1</value>
<type>string</type>
</param>
<param>
<name>Port</name>
<key>port</key>
<value>40868</value>
<type>int</type>
</param>
<param>
<name>Append LoRaTap</name>
<key>loratap</key>
<value>False</value>
<type>bool</type>
</param>
<param>
<name>Append LoRaPHY</name>
<key>loraphy</key>
<value>False</value>
<type>bool</type>
</param>
<!-- Make one 'sink' node per input. Sub-nodes:
* name (an identifier for the GUI)
* type
* vlen
* optional (set to 1 for optional inputs) -->
<sink>
<name>in</name>
<type>message</type>

Wyświetl plik

@ -1,13 +0,0 @@
<?xml version="1.0"?>
<block>
<name>Message Wireshark Sink</name>
<key>lora_message_wireshark_sink</key>
<category>[LoRa]</category>
<import>import lora</import>
<make>lora.message_wireshark_sink()</make>
<sink>
<name>in</name>
<type>message</type>
</sink>
</block>

Wyświetl plik

@ -27,5 +27,8 @@ install(FILES
message_socket_sink.h
channelizer.h
debugger.h
loratap.h
loraphy.h
utilities.h
controller.h DESTINATION include/lora
)

Wyświetl plik

@ -0,0 +1,32 @@
/* -*- c++ -*- */
/*
* Copyright 2017 Pieter Robyns.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include <stdint.h>
typedef enum cr { CR1=1, CR2, CR3, CR4 } cr_t;
typedef struct __attribute__((__packed__)) loraphy_header {
uint8_t length;
uint8_t crc_msn : 4;
uint8_t has_mac_crc : 1;
uint8_t cr : 3;
uint8_t crc_lsn : 4;
uint8_t reserved : 4;
} loraphy_header_t;

Wyświetl plik

@ -0,0 +1,55 @@
/*
This file is part of LoRaTap Copyright (C) 2017 Erik de Jong
LoRaTap is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
LoRaTap is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with LoRaTap. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdint.h>
/*
Values are big-endian
Field details
lt_version LoRaTap header version, current version is 0.
lt_padding Unused, for boundary alignment.
lt_length LoRaTap header length, field used to allow expansion in future versions. Each version can append header parameters.
So, whilst parsing, these parameters can be skipped if not defined for older versions by skipping to the offset of lt_length starting from the beginning of the header.
channel Channel information
rssi RSSI information
sync_word Sync word for received packet, value 0x34 is reserved for LoRaWAN packets
*/
typedef enum sf { SF7=7, SF8, SF9, SF10, SF11, SF12 } sf_t;
typedef struct __attribute__((__packed__)) loratap_channel {
uint32_t frequency; /* LoRa frequency (Hz) */
uint8_t bandwidth; /* Channel bandwidth (KHz) in 125 KHz steps */
uint8_t sf; /* LoRa SF (sf_t) [7, 8, 9, 10, 11, 12] */
} loratap_channel_t;
typedef struct __attribute__((__packed__)) loratap_rssi {
uint8_t packet_rssi; /* LoRa packet RSSI, if snr >= 0 then dBm value is -139 + packet_rssi, otherwise dBm value is -139 + packet_rssi * .25 */
uint8_t max_rssi; /* LoRa receiver max RSSI (dBm value is -139 + rssi) */
uint8_t current_rssi; /* LoRa receiver current RSSI (dBm value is -139 + rssi) */
uint8_t snr; /* LoRa SNR (dB value is (snr[two's complement])/4) */
} loratap_rssi_t;
typedef struct __attribute__((__packed__)) loratap_header {
uint8_t lt_version; /* LoRatap header version */
uint8_t lt_padding;
uint16_t lt_length; /* LoRatap header length */
loratap_channel_t channel;
loratap_rssi_t rssi;
uint8_t sync_word; /* LoRa radio sync word [0x34 = LoRaWAN] */
} loratap_header_t;

Wyświetl plik

@ -701,7 +701,7 @@ namespace gr {
* class. lora::message_socket_sink::make is the public interface for
* creating new instances.
*/
static sptr make();
static sptr make(std::string ip, int port, bool loratap, bool loraphy);
};
} // namespace lora

Wyświetl plik

@ -22,14 +22,19 @@
#define UTILITIES_H
#include <cstdint>
#include <string.h>
#define REV_BITS
#define PHY_HEADER_SIZE 3u
#define MAC_CRC_SIZE 2u
#define SM(value, shift, mask) (((value) << (shift)) & (mask))
#define MS(value, mask, shift) (((value) & (mask)) >> (shift))
namespace gr {
namespace lora {
/**
* \brief Clamp gevin value in the given range.
* \brief Clamp given value in the given range.
*
* \tparam T
* The type of variable to clamp.
@ -59,7 +64,7 @@ namespace gr {
* <BR>e.g. 1 byte given => size = 8
* <BR>e.g. only 6 bits in use => size = 6, and all bits higher than (1 << size-1) will be zeroed.
*/
static inline uint32_t rotl(uint32_t bits, uint32_t count = 1u, const uint32_t size = 8u) {
inline uint32_t rotl(uint32_t bits, uint32_t count = 1u, const uint32_t size = 8u) {
const uint32_t len_mask = (1u << size) - 1u;
count %= size; // Limit bit rotate count to size
@ -79,7 +84,7 @@ namespace gr {
* The length in bits of the given variable `v`.
*/
template <typename T>
std::string to_bin(const T v, const uint32_t bitwidth) {
inline std::string to_bin(const T v, const uint32_t bitwidth) {
#ifdef REV_BITS
const uint64_t maxpow = bitwidth ? (1ull << (bitwidth - 1)) : 0;
uint64_t mask;
@ -155,7 +160,7 @@ namespace gr {
* \param even
* Check for even (`true`) or uneven (`false`) parity.
*/
bool check_parity_string(const std::string& word, const bool even = true) {
inline bool check_parity_string(const std::string& word, const bool even = true) {
size_t count = 0, i = 0;
while(i < 7) {
@ -175,7 +180,7 @@ namespace gr {
* \param even
* Check for even (`true`) or uneven (`false`) parity.
*/
bool check_parity(uint64_t word, const bool even = true) {
inline bool check_parity(uint64_t word, const bool even = true) {
word ^= word >> 1;
word ^= word >> 2;
word = (word & 0x1111111111111111UL) * 0x1111111111111111UL;
@ -193,7 +198,7 @@ namespace gr {
* \param n
* The amount of indices.
*/
uint32_t select_bits(const uint32_t data, const uint8_t *indices, const uint8_t n) {
inline uint32_t select_bits(const uint32_t data, const uint8_t *indices, const uint8_t n) {
uint32_t r = 0u;
for(uint8_t i = 0u; i < n; ++i)
@ -216,7 +221,7 @@ namespace gr {
* \param out_data
* The resulting data words.
*/
void fec_extract_data_only(const uint8_t *in_data, const uint32_t len, const uint8_t *indices, const uint8_t n, uint8_t *out_data) {
inline void fec_extract_data_only(const uint8_t *in_data, const uint32_t len, const uint8_t *indices, const uint8_t n, uint8_t *out_data) {
for (uint32_t i = 0u, out_index = 0u; i < len; i += 2u) {
const uint8_t d2 = (i + 1u < len) ? select_bits(in_data[i + 1u], indices, n) & 0xFF
: 0u;
@ -280,7 +285,7 @@ namespace gr {
* The byte to decode.
* \return Returs a nibble containing the corrected data.
*/
uint8_t hamming_decode_soft_byte(uint8_t v) {
static uint8_t hamming_decode_soft_byte(uint8_t v) {
// Precalculation
// Which bits are covered (including self)?
// p1 10110100
@ -343,7 +348,7 @@ namespace gr {
* \param out_data
* The decoded result words.
*/
void hamming_decode_soft(const uint8_t *words, const uint32_t len, uint8_t *out_data) {
inline void hamming_decode_soft(const uint8_t *words, const uint32_t len, uint8_t *out_data) {
for (uint32_t i = 0u, out_index = 0u; i < len; i += 2u) {
const uint8_t d2 = (i + 1u < len) ? hamming_decode_soft_byte(words[i + 1u])
: 0u;
@ -384,6 +389,18 @@ namespace gr {
out << std::flush;
}
inline uint32_t dissect_packet(const void **header, uint32_t header_size, const uint8_t *buffer, uint32_t offset) {
(*header) = buffer + offset;
return offset + header_size;
}
inline uint32_t build_packet(uint8_t *buffer, uint32_t offset, const void* header, uint32_t header_size) {
memcpy(buffer + offset, header, header_size);
offset += header_size;
return offset;
}
}
}

Wyświetl plik

@ -25,7 +25,7 @@
#include <string.h>
#include <chrono>
#include "utilities.h"
#include <lora/utilities.h>
#define CLAMP_VAL 0.7e6f //1000000.0f //0.7f

Wyświetl plik

@ -27,9 +27,11 @@
#include <liquid/liquid.h>
#include <numeric>
#include <algorithm>
#include <lora/loratap.h>
#include <lora/loraphy.h>
#include <lora/utilities.h>
#include "decoder_impl.h"
#include "tables.h"
#include "utilities.h"
#include "dbugr.hpp"
@ -524,6 +526,10 @@ namespace gr {
// values_to_file("/tmp/after_deshuffle", &d_words_deshuffled[0], d_words_deshuffled.size(), 8);
dewhiten(is_header ? gr::lora::prng_header : d_whitening_sequence);
//if (!is_header)
// values_to_file("/tmp/after_dewhiten", &d_words_dewhitened[0], d_words_dewhitened.size(), 8);
hamming_decode(out_data);
// Print result
@ -537,15 +543,38 @@ namespace gr {
d_data.insert(d_data.end(), out_data, out_data + d_payload_length);
std::cout << result.str() << std::endl;
pmt::pmt_t payload_blob = pmt::make_blob(&d_data[0],
sizeof(uint8_t) * (d_payload_length + 3u));
message_port_pub(pmt::mp("frames"), payload_blob);
msg_lora_frame();
} else {
d_data.insert(d_data.end(), out_data, out_data + 3u);
d_data.insert(d_data.end(), out_data, out_data + PHY_HEADER_SIZE);
std::cout << result.str();
}
}
void decoder_impl::msg_lora_frame(void) {
uint32_t len = sizeof(loratap_header_t) + sizeof(loraphy_header_t) + d_data.size();
uint32_t offset = 0;
uint8_t buffer[len];
loratap_header_t loratap_header;
loraphy_header_t loraphy_header;
memset(buffer, 0, sizeof(uint8_t) * len);
memset(&loratap_header, 0, sizeof(loratap_header));
memset(&loraphy_header, 0, sizeof(loraphy_header));
loraphy_header.has_mac_crc = d_has_mac_crc;
offset = gr::lora::build_packet(buffer, offset, &loratap_header, sizeof(loratap_header_t));
offset = gr::lora::build_packet(buffer, offset, &loraphy_header, sizeof(loraphy_header_t));
offset = gr::lora::build_packet(buffer, offset, &d_data[0], d_data.size());
if(offset != len) {
std::cerr << "decoder_impl::msg_lora_frame: invalid write" << std::endl;
exit(1);
}
pmt::pmt_t payload_blob = pmt::make_blob(buffer, sizeof(uint8_t)*len);
message_port_pub(pmt::mp("frames"), payload_blob);
}
void decoder_impl::deshuffle(const uint8_t *shuffle_pattern, const bool is_header) {
const uint32_t to_decode = is_header ? 5u : d_demodulated.size();
const uint32_t len = sizeof(shuffle_pattern) / sizeof(uint8_t);
@ -656,10 +685,6 @@ namespace gr {
return mult_ifreq[256] / (2.0 * M_PI) * d_samples_per_second;
}
uint8_t decoder_impl::lookup_cr(const uint8_t bytevalue) {
return (bytevalue & 0x0e) >> 1;
}
int decoder_impl::work(int noutput_items,
gr_vector_const_void_star& input_items,
gr_vector_void_star& output_items) {
@ -751,20 +776,22 @@ namespace gr {
d_cr = 4u;
if (demodulate(input, true)) {
uint8_t decoded[3];
uint8_t decoded[PHY_HEADER_SIZE];
// TODO: A bit messy. I think it's better to make an internal decoded std::vector
d_payload_length = 3u;
d_payload_length = PHY_HEADER_SIZE;
decode(decoded, true);
nibble_reverse(decoded, 1u); // TODO: Why? Endianness?
d_payload_length = decoded[0];
d_cr = lookup_cr(decoded[1]);
nibble_reverse(decoded, PHY_HEADER_SIZE);
d_has_mac_crc = MS(decoded[1], 0x10, 4);
d_payload_length = decoded[0] + MAC_CRC_SIZE * d_has_mac_crc;
d_cr = MS(decoded[1], 0xe0, 5);
d_phy_crc = SM(decoded[1], 4, 0xf0) | MS(decoded[2], 0xf0, 4);
// Calculate number of payload symbols needed
uint8_t redundancy = (d_sf > 10 ? 2 : 0);
const int symbols_per_block = d_cr + 4u;
const float bits_needed = float(d_payload_length) * 8.0f + 16.0f;
const float bits_needed = float(d_payload_length) * 8.0f;
const float symbols_needed = bits_needed * (symbols_per_block / 4.0f) / float(d_sf - redundancy);
const int blocks_needed = (int)std::ceil(symbols_needed / symbols_per_block);
d_payload_symbols = blocks_needed * symbols_per_block;

Wyświetl plik

@ -82,6 +82,9 @@ namespace gr {
uint8_t d_sf; ///< The Spreading Factor.
uint32_t d_bw; ///< The receiver bandwidth (fixed to `125kHz`).
uint8_t d_cr; ///< The Coding Rate.
uint8_t d_phy_crc; ///< The PHY CRC.
uint16_t d_mac_crc; ///< The MAC CRC.
uint8_t d_has_mac_crc; ///< Flag to indicate presence of MAC CRC.
double d_bits_per_second; ///< Indicator of how many bits are transferred each second.
uint32_t d_delay_after_sync; ///< The amount of samples to skip in `DecoderState::PAUSE`.
uint32_t d_samples_per_second; ///< The amount of samples taken per second by GNU Radio.
@ -378,12 +381,10 @@ namespace gr {
inline void instantaneous_frequency(const gr_complex *in_samples, float *out_ifreq, const uint32_t window);
/**
* \brief Return the coding rate from the given HDR byte from a LUT.
*
* \param bytevalue
* The LSB nibble to decode.
* \brief TODO
*/
uint8_t lookup_cr(const uint8_t bytevalue);
void msg_lora_frame(void);
public:
/**
* \brief Default constructor.

Wyświetl plik

@ -22,14 +22,17 @@
#include "config.h"
#endif
#include <lora/loratap.h>
#include <lora/loraphy.h>
#include <gnuradio/io_signature.h>
#include <lora/utilities.h>
#include "message_socket_sink_impl.h"
namespace gr {
namespace lora {
message_socket_sink::sptr message_socket_sink::make() {
return gnuradio::get_initial_sptr(new message_socket_sink_impl());
message_socket_sink::sptr message_socket_sink::make(std::string ip, int port, bool loratap, bool loraphy) {
return gnuradio::get_initial_sptr(new message_socket_sink_impl(ip, port, loratap, loraphy));
}
/**
@ -37,16 +40,19 @@ namespace gr {
*
* Create a UDP socket connection to send the data through.
*/
message_socket_sink_impl::message_socket_sink_impl()
: gr::block("message_socket_sink",
gr::io_signature::make(0, 0, 0),
gr::io_signature::make(0, 0, 0)) {
message_socket_sink_impl::message_socket_sink_impl(std::string ip, int port, bool loratap, bool loraphy)
: gr::block("message_socket_sink", gr::io_signature::make(0, 0, 0), gr::io_signature::make(0, 0, 0)),
d_ip(ip),
d_port(port),
d_loratap(loratap),
d_loraphy(loraphy) {
message_port_register_in(pmt::mp("in"));
set_msg_handler(pmt::mp("in"), boost::bind(&message_socket_sink_impl::handle, this, _1));
d_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (d_socket < 0) {
if(d_socket < 0) {
perror("[message_socket_sink] Failed to create socket!");
exit(EXIT_FAILURE);
}
@ -56,17 +62,14 @@ namespace gr {
d_sock_addr->sin_addr.s_addr = htonl(INADDR_ANY);
d_sock_addr->sin_port = htons(0); // Source port: 0 is any
if (bind(d_socket,
(const struct sockaddr*) d_sock_addr,
sizeof(*d_sock_addr))
< 0) {
if(bind(d_socket, (const struct sockaddr*) d_sock_addr, sizeof(*d_sock_addr)) < 0) {
perror("[message_socket_sink] Socket bind failed!");
exit(EXIT_FAILURE);
}
d_sock_addr->sin_port = htons(this->d_port);
// == "127.0.0.1" to int translation
inet_pton(AF_INET, this->d_host.c_str(), &d_sock_addr->sin_addr.s_addr);
d_sock_addr->sin_port = htons(d_port);
// IP string to int conversion
inet_pton(AF_INET, d_ip.c_str(), &d_sock_addr->sin_addr.s_addr);
}
/**
@ -81,22 +84,46 @@ namespace gr {
* \brief Handle a message and send its contents through an UDP packet to the loopback interface.
*/
void message_socket_sink_impl::handle(pmt::pmt_t msg) {
uint8_t *data = (uint8_t*) pmt::blob_data(msg);
uint8_t* data = (uint8_t*)pmt::blob_data(msg);
uint32_t offset = 0;
size_t size = pmt::blob_length(msg);
loratap_header_t *loratap_header;
loraphy_header_t *loraphy_header;
uint8_t *payload;
/*
#ifdef DEBUG
printf("Received message:\n\t");
offset = gr::lora::dissect_packet((const void **)&loratap_header, sizeof(loratap_header_t), data, offset);
offset = gr::lora::dissect_packet((const void **)&loraphy_header, sizeof(loraphy_header_t), data, offset);
uint32_t length = size - sizeof(loratap_header_t) - sizeof(loraphy_header_t);
offset = gr::lora::dissect_packet((const void **)&payload, sizeof(uint8_t)*length, data, offset);
if(offset != size) {
std::cerr << "message_socket_sink_impl::handle: invalid read: " << offset << " != " << size << std::endl;
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < size; ++i)
printf("%02x ", data[i]);
if(d_loratap == false) {
msg_send_udp(loraphy_header, payload, length); // Send message over UDP socket
} else {
//msg_send_loratap(); // Send message over raw LoRa socket
std::cerr << "message_socket_sink_impl::handle: LoRaTap is not supported yet." << std::endl;
return;
}
}
putchar('\n');
#endif
*/
void message_socket_sink_impl::msg_send_udp(const loraphy_header_t* loraphy_header, const uint8_t* payload, const uint32_t length) {
bool error = false;
if (sendto(d_socket, data, size, 0, (const struct sockaddr*)d_sock_addr, sizeof(*d_sock_addr)) != (ssize_t)size) {
perror("[message_socket_sink] Mismatch in number of bytes sent");
if(d_loraphy) {
int32_t msg_len = length;
if (sendto(d_socket, payload, msg_len, 0, (const struct sockaddr*)d_sock_addr, sizeof(*d_sock_addr)) != msg_len)
error = true;
} else {
int32_t msg_len = length-(PHY_HEADER_SIZE+(MAC_CRC_SIZE * loraphy_header->has_mac_crc)); // User did not request PHY header
if (sendto(d_socket, payload+PHY_HEADER_SIZE, msg_len, 0, (const struct sockaddr*)d_sock_addr, sizeof(*d_sock_addr)) != msg_len)
error = true;
}
if(error) {
perror("message_socket_sink_impl::handle: mismatch in number of bytes sent");
exit(EXIT_FAILURE);
}
}

Wyświetl plik

@ -31,8 +31,10 @@ namespace gr {
class message_socket_sink_impl : public message_socket_sink {
private:
const std::string d_host = "127.0.0.1";
const int d_port = 40868;
std::string d_ip = "127.0.0.1";
int d_port = 40868;
bool d_loratap;
bool d_loraphy;
// socket
struct sockaddr_in *d_sock_addr;
@ -41,9 +43,11 @@ namespace gr {
void handle(pmt::pmt_t msg);
public:
message_socket_sink_impl();
message_socket_sink_impl(std::string ip, int port, bool loratap, bool loraphy);
~message_socket_sink_impl();
private:
void msg_send_udp(const loraphy_header_t* loraphy_header, const uint8_t* payload, const uint32_t length);
};
} // namespace lora

Wyświetl plik

@ -31,10 +31,8 @@ endif()
GR_PYTHON_INSTALL(
FILES
__init__.py
lora_decoder.py
lora_receiver.py
loraconfig.py
message_wireshark_sink.py DESTINATION ${GR_PYTHON_DIR}/lora
loraconfig.py DESTINATION ${GR_PYTHON_DIR}/lora
)
if(HAS_MONGODB)

Wyświetl plik

@ -31,9 +31,7 @@ except ImportError:
pass
# import any pure python here
from lora_decoder import lora_decoder
from lora_receiver import lora_receiver
from message_wireshark_sink import message_wireshark_sink
#
# import optional blocks

Wyświetl plik

@ -1,527 +0,0 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# Copyright 2016 Pieter Robyns.
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
# Notes from EP2763321A1, see https://www.google.com/patents/EP2763321A1
# General
# One chirp is one symbol
# The phase stays the same during a chirp, but can change between symbols (modulated chirps)
# Chirp duration may vary
# SF: 12 = N
# CR: 4/5
# BW: 125
# Modulation
# The value of the cyclic shift can be coded over log2 N bits, noted PPM.
# When a reduced set is used (N is small), the Gray mapper sets the least significant bits to zero. For a reduced set in which two bits are set to zero, hence using only one quarter of the available symbols, we have PPM = log2 N - 2, for example.
# The errors of ± 1 in the demodulated position have a much higher probability of occurring. Hence, there is a higher error probability for least significant bits: bit0 sees twice as much errors as bit1, which sees twice as much as bit2, and so on.
# See https://patentimages.storage.googleapis.com/EP2763321A1/imgf0002.png
# Each symbol is a chirp, and a number represents a codeword. M is one modulated bit (cycle shift)
# Sync
# In the example shown, the receiver looks for the presence of 3 consecutive symbols: unmodulated, modulated with first value, modulated with second value (for example a first chirp with a modulation value of 4, and a second one with the opposite modulation N - 4). Since the reception errors are mostly ± 1 offsets, it would not be advisable choosing these values for the frame synchronisation symbols. Modulation values are predetermined.
# According to another aspect of the invention, the preamble includes preferably frequency synchronisation symbols 413 that consist in one or more, preferably two chirps that are complex-conjugate of the base unmodulated chirp. One can regard these in the baseband representation as down-chirps
# Interesting remark in [0045]
# To let the receiver align in time, a silence 420 is inserted after the symbols 413.
# Finetuning described in [0050]
# PHDR
# The header part of the frame is a data field 415 that describes how to decode the information bits. The header content determines the decoding of large sections of the message and, therefore, it is preferably modulated with a reduced set of cyclic shifts, for example one possible position every four positions, i.e. PPM = log(N)-2. Since the most likely demodulation errors are ± 1 modulation position offset, this reduces significantly the probability that the header is not correctly decoded. Different reduction factors are also possible and included in the scope of the invention. A reduced set which is one third of the total set is also feasible, but this would not give an integer number of bits per symbol when the symbol size is, as it is usually a power of two. This technique of encoding part of the chirps with a reduced set of cyclic shifts can be used in other sensitive part of the transmitted data, whenever the likelihood of decoding errors is needed to be reduced.
# Preferably, the header 415 is encoded using the lowest coding rate, RDD=4, so as to give best protection, and comprises a header CRC to check header data integrity.
# The header 415 can include all sort of data useful to decode the payload. According to a possible implementation of the invention, the header fields are coding rate, enable of payload CRC, payload length, CRC, a burst mode indication, a compressed mode indication, some reserved bits, and a ranging bit. When the ranging bit is set, the header data has different meaning except header CRC.
# Pilot symbols
# According to an aspect of the invention, with an aim of improving the robustness without sacrificing the data rate, the payload includes "pilot symbols" as illustrated in Figure 7. These are symbols which use reduced modulation set, within the payload. In the represented example, in which the coding rate is
# 4/5, symbols form coding groups 512 containing 5 adjacent symbols (see next). One every 4 such groups can be encoded with a reduced modulation set 511, i.e. 5 symbols every 20 symbols. This is enough for a simple receiver to track timing, without compromising data rate. The repetition rate of such pilot symbols is a configuration known by both receiver and transmitter and is, for example, made known to the receiver by an appropriate field in the header.
import numpy
import struct
from gnuradio import gr
from scipy import signal
DELAY_AFTER_SYNC = 268 # Delay window after two downchirps in the LoRa signal
EPSILON = 0.001
VERBOSITY = 1
# Conditional print
def printd(string, level=2):
if VERBOSITY >= level:
print(string)
# Convert Gray code to binary
def ungray(gray):
code_len = len(gray)
gray = int(gray, 2)
mask = gray >> 1
binary = gray
while mask != 0:
binary = binary ^ mask
mask = mask >> 1
binary_str = bin(binary)[2:]
return "0" * (code_len - len(binary_str)) + binary_str
# XOR binary number with PRNG byte and return binary
def xor_byte(number, prng): # "number" should be a binary string, prng an integer from 0 - 255
number_int = int(number, 2)
binary = number_int ^ prng
binary_str = bin(binary)[2:]
return "0" * (8 - len(binary_str)) + binary_str
# xor_byte for a bitstring
def xor_string(string, prng):
t = ""
count = 0
for i in range(0, len(string), 8):
t += xor_byte(string[i:i+8], prng[count])
count += 1
return t
# Binary to Gray code
def gray(gray):
code_len = len(gray)
gray = int(gray, 2)
binary = (gray >> 1) ^ gray
binary_str = bin(binary)[2:]
return "0" * (code_len - len(binary_str)) + binary_str
# Binary string to bytes
def bin_to_bytes(bin_str):
result = b""
for i in range(0, len(bin_str), 8):
result += bytes(bytearray([int(bin_str[i:i+8], 2)]))
return result
# Bytes to binary string
def bytes_to_bin(byte_str):
result = ''
binary_str = ''
for elem in byte_str:
binary_str = bin(elem)[2:]
binary_str = "0" * (8 - len(binary_str)) + binary_str
result += binary_str
return result
# Binary string to hex string
def bin_to_hex(bin_str, manchester=False):
str_len = len(bin_str)
if str_len % 8 != 0:
printd("Padding string of len " + str(str_len))
#bin_str = ("0" * (str_len % 8)) + bin_str # Pad at begin
bin_str = bin_str + ("0" * (str_len % 8)) # Pad at end
if manchester:
t = ""
for i in range(0, str_len, 2):
substr = bin_str[i:i+2]
if substr == "10":
t += "1"
elif substr == "01":
t += "0"
else:
print("Warning: not Manchester. Decoded value will be wrong")
bin_str = t
result = ""
for i in range(0, str_len, 8):
substr = bin_str[i:i+8]
hchr = hex(int(substr, 2)).split('0x')[1]
if len(hchr) == 1:
hchr = "0" + hchr
result += hchr + " "
return result.strip()
# Hamming helper functions
def _check_parity(word, even=True):
count = 0
for i in range(0, len(word)):
if word[i] == "1":
count += 1
if even:
return ((count % 2) == 0)
else:
return (((count+1) % 2) == 0)
def _flip(bit):
if bit == "0":
return "1"
else:
return "0"
def hamming_onlydata(string, indices):
result = ""
for i in range(0, len(string)):
if i in indices:
result += string[i]
return result
def hamming_decode(word, powers_of_two_pos=[0, 1, 3], even=True):
error = 0
for i in powers_of_two_pos:
j = i
to_check = ""
while j < len(word): # j: position after skip. k: position to append
k = j
while k < j+i+1 and k < len(word):
to_check += word[k]
k += 1
j += ((i+1)*2)
#print("Checking p%d: %s" % (i+1, str(to_check)))
if not _check_parity(to_check, even):
#print("Found incorrect parity at %d" % i)
error += (i+1)
# Correct errors here
if error > 0:
index = error - 1
printd("Error at index %d" % index)
word = word[:index] + _flip(word[index]) + word[index+1:]
data = ""
for i in range(0, len(word)):
bit = word[i]
if not i in powers_of_two_pos:
data += bit
return data, error
def shuffled_hamming(coded, prng):
bit_order = (7, 6, 3, 4, 2, 1, 0, 5) # Reverse engineered permutation
# Deshuffle
deshuffle = ""
for bit in bit_order:
deshuffle += coded[bit]
printd("S: " + str(deshuffle))
# Dewhiten
dewhiten = xor_byte(deshuffle, prng)
printd("W: " + str(dewhiten))
# Decode
decode, error = hamming_decode(dewhiten[:-1], powers_of_two_pos=[0, 1, 3], even=True)
return decode, error
# State machine states
class LoRaState:
FIND_SYNC = 0
VERIFY_SYNC = 1
DECODE_HDR = 2
DECODE_PAYLOAD = 3
# GNURadio block
class lora_decoder(gr.basic_block):
"""
docstring for block lora_decoder
"""
def __init__(self):
gr.basic_block.__init__(self,
name="lora_decoder",
in_sig=[numpy.float32, numpy.complex64],
out_sig=[numpy.float32, numpy.float32])
self.last_sample = 0.0
self.sync_buffer = []
self.downchirp = []
self.window_size = 0
self.sample_buffer = []
self.sf = 7 # Seems to only affect PHY radio send?
self.bw = 125000.0
self.cr = 4
self.state = 0
self.bits_per_second = self.sf * 1 / ((2**self.sf) / self.bw)
self.samples_per_second = 1000000
self.symbols_per_second = self.bw / (2**self.sf)
self.bits_per_symbol = int(self.bits_per_second / self.symbols_per_second)
self.samples_per_symbol = int(self.samples_per_second / self.symbols_per_second)
self.number_of_bins = int('0b' + '1' * self.sf, 2) + 1
self.number_of_bins_hdr = self.number_of_bins / 4
self.compression = 8
self.payload_symbols = 0
print("Bits per symbol: " + str(self.bits_per_symbol))
print("Bins per symbol: " + str(self.number_of_bins))
print("Header bins per symbol: " + str(self.number_of_bins_hdr))
print("Samples per symbol: " + str(self.samples_per_symbol))
self.words = []
self.demodulated = ""
# Generate ideal downchirp
t = numpy.arange(self.samples_per_symbol) / float(self.samples_per_second)
beta = -1 * (self.bw / (t[-1] - t[0]))
alpha = (self.bw / 2.0) + 0
self.downchirp = numpy.exp(2.0 * numpy.pi * 1j * (alpha * t + 0.5 * beta * t**2)).astype(numpy.complex64)
def deinterleave(self, words, ppm):
bits_per_word = len(words)
result = []
offset_start = 0
for i in range(0, ppm):
d = ""
offset_diag = offset_start
for j in range(0, bits_per_word):
d += words[j][offset_diag]
offset_diag = (offset_diag + 1) % ppm
offset_start += 1
result.append(d)
return result
def forecast(self, noutput_items, ninput_items_required):
ninput_items_required[0] = noutput_items
def compress(self, samples, amt):
return numpy.mean(samples.reshape(-1, amt), axis=1)
def gradient(self, samples):
instantaneous_phase = numpy.unwrap(numpy.angle(samples))
instantaneous_frequency = (numpy.diff(instantaneous_phase) / (2.0*numpy.pi) * self.samples_per_second)
c_freq = self.compress(instantaneous_frequency, self.compression)
gradient = numpy.gradient(c_freq)
return numpy.abs(gradient)
def nibble_reverse(self, data):
result = ""
for i in range(0, len(data), 8):
result += data[i+4:i+8]
result += data[i+0:i+4]
return result
# 1. Find min and max values of cyclic shift
# 2. Apply Gray code to index of the transient of the change in instantaneous frequency
# 3. Read 4 + RDD (redundancy bits) symbols
# 4. Deinterleave
# 5. De-whiten
# 6. Hamming decode
def demodulate(self, samples, is_hdr, out, out_w):
# Possibility 1: convolve in freq domain
#mult = numpy.convolve(...)
# Possibility 2: multiply and FFT
#mult = numpy.multiply(samples, self.downchirp)
#xx = numpy.array(samples)
#xx.tofile("/tmp/in1")
#self.downchirp.tofile("/tmp/downchirp")
#mult.tofile("/tmp/mult")
#mult = numpy.fft.fft(mult, self.window_size)
#mult = numpy.abs(mult)
# Possibility 3: just use gradient of upchirp (faster?)
gradient_mag = self.gradient(samples)
result = (int(numpy.argmax(gradient_mag)) / (8 / self.compression)) # TODO scale according to bins e.g. 128 = divide by 8 / compression, i.e. divide by header bins per symbol!
# Header bins
if is_hdr == True:
result /= 4
# Convert argmax to binary
result_binary = bin(result)[2:]
# 5+3 coding for header
if is_hdr == True:
result_binary = "0" * (self.sf - 2 - len(result_binary)) + result_binary # -2 to cut off LSB of gray code
else:
result_binary = "0" * (self.sf - len(result_binary)) + result_binary
# Convert TO Gray
result_binary = gray(result_binary)
# Debug info for Audacity
printd(str(result) + " " + result_binary)
for i in range(0, self.window_size):
out[i] = gradient_mag[i/self.compression] / numpy.max(gradient_mag) * 100.0 # FFT of convolution result
if is_hdr == True:
out_w[i] = (float(result) / self.number_of_bins_hdr) * 100.0 # Resulting bin scaled
else:
out_w[i] = (float(result) / self.number_of_bins) * 100.0 # Resulting bin scaled
#out_w[i] = numpy.abs(in1[i] * 2+2j) # Real data
self.words.append(result_binary)
# Look for 4+cr symbols and stop
if len(self.words) == (4 + self.cr):
printd(self.words)
# Deinterleave
if is_hdr == True:
deinterleaved = self.deinterleave(self.words, self.sf - 2)
else:
deinterleaved = self.deinterleave(self.words, self.sf)
deinterleaved.reverse() # Words are transmitted in reverse order. TODO is this because I missed something in an earlier stage?
deinterleaved = ''.join(deinterleaved)
printd("D: " + deinterleaved)
self.words = []
self.demodulated += deinterleaved
return deinterleaved
return None
def decode(self, is_hdr):
printd("DEMO: " + self.demodulated)
data = ""
if is_hdr:
prng = [0x44, 0x88, 0x00, 0x00, 0x00] # TODO: Last 3 bytes still unknown
else:
# TODO: Probably not 100% correct towards the end, because of clock drift. Needs to be corrected
prng = [0xfb, 0xf7, 0xd, 0xef, 0x79, 0xbf, 0x63, 0xfb, 0x8, 0xdf, 0xc2, 0x2c, 0x15, 0xfa, 0x4f, 0xe9, 0x46, 0x10, 0x1f, 0x92, 0x7d, 0x51, 0x25, 0x6b, 0x68, 0x67, 0xa1, 0x9c, 0xd6, 0xf7, 0xa7, 0x3d, 0xcd, 0x38, 0x28, 0xe5, 0xbc, 0xf2, 0x89, 0x86, 0xa1, 0x4e, 0x4, 0xa2, 0x20, 0xa4, 0x1, 0xd8, 0x82, 0xe5, 0xda, 0x20, 0x45, 0x1, 0xd9, 0x82, 0xe5, 0x8, 0xf2, 0xc2, 0x86, 0x15, 0x9c, 0x9d, 0x25, 0xc1, 0x68, 0xd3, 0xa1, 0x5, 0xd6, 0x16, 0x75, 0x3d, 0x98, 0x38, 0xb1, 0xe5, 0x5d, 0xf2, 0x5b, 0x54, 0x26, 0x1b, 0x1a, 0x3b, 0xd, 0x45, 0x79, 0xb, 0x63, 0x62, 0x8, 0x3e, 0x10, 0x2c, 0x40, 0xfa, 0xd6, 0xe9, 0xa7, 0x10, 0xcd, 0x40, 0xfa, 0x4, 0x3b, 0xf2, 0x45, 0x86, 0xd9, 0x4e, 0x37, 0x70, 0x75, 0x23, 0x98, 0x15, 0xb1, 0x9d, 0x8f, 0x13, 0xdc, 0x54, 0xea, 0x1b, 0x62, 0x3b, 0x3e, 0x97, 0x2c, 0x8c, 0xfa, 0xae, 0x3b, 0x46, 0x45, 0x1f, 0xd9, 0xaf, 0xe5, 0x70, 0x20, 0x3, 0x1, 0x15, 0x50, 0x9d, 0x5d, 0xc5, 0x5b, 0x1, 0xf4, 0xc2, 0x4f, 0x9e, 0x46, 0x45, 0xcd, 0xb, 0x28, 0xb0, 0x6e, 0x69, 0xd4, 0x77, 0xeb, 0x4e, 0xb0, 0x22, 0x69, 0x7e, 0x77, 0x8d, 0xe, 0xee, 0xf4, 0x9c, 0x3, 0x4a, 0x14, 0xe4, 0xd, 0xc0, 0xce, 0x68, 0xfd, 0x73, 0xfb, 0x93, 0xed, 0x6b, 0x18, 0x67, 0xb3, 0x5e, 0xc2, 0xf2, 0x3e, 0xfd, 0xde, 0x50, 0x7d, 0xd6, 0xa3, 0xa7, 0xba, 0x27, 0x27, 0x3d, 0xda, 0x73, 0x8b, 0x15, 0x67, 0xea, 0xdc, 0x20, 0xf3, 0x65, 0x3d, 0x9b, 0xea, 0xe4, 0xa2, 0x96, 0x67, 0xef, 0x47, 0x6c, 0xdc, 0xee, 0xa7, 0x91, 0xba, 0x62, 0xf4, 0xf4, 0x9e, 0x92, 0xc1, 0x1d, 0xdb, 0xfa, 0x97, 0xa0, 0x11, 0xb8, 0xd9, 0xe0, 0x40, 0x10, 0xd4, 0x99, 0xaf, 0x89, 0xdd, 0xa1, 0x9, 0x6, 0x6e, 0xfe, 0x5c, 0x86, 0x38, 0x3e, 0x77, 0xe3, 0xfa, 0x56, 0x82, 0x8c, 0x9c, 0x7f, 0xf3, 0x41, 0x1d, 0xdb, 0x28, 0x45, 0x35, 0x16, 0xab, 0x6f, 0x3f, 0x7c, 0xef, 0x7e, 0x34, 0x1b, 0x23, 0xb6, 0x47, 0x9d, 0x48, 0x25, 0x5c, 0x40, 0xe0, 0x72, 0x2, 0x40, 0x5d, 0xe0, 0x7b, 0x79, 0x36, 0x63, 0x4a, 0x9e, 0x8a, 0x4d, 0xb5, 0x3a, 0x1b, 0x60, 0x3b, 0xe4, 0xc1, 0xab, 0xf8, 0x66, 0x6f, 0x91, 0xf2, 0x23, 0x64, 0x11, 0x88, 0x1d, 0xbc, 0xc5, 0xa9, 0xdb, 0x60, 0x97, 0x93, 0x47, 0x6b, 0xac, 0x95, 0xc8, 0xc9, 0xb5, 0xb8, 0x75, 0xc9, 0x42, 0x72, 0x6, 0x83, 0xc1, 0x36, 0x80, 0x3c, 0xd9, 0x69, 0xb5, 0x6e, 0xa3, 0xe, 0x7, 0x6d, 0xce, 0x6c, 0xa2, 0x4e, 0x52, 0xcd, 0x5e, 0xea, 0xeb, 0x3f, 0x8a, 0x9f, 0x67, 0x7f, 0x5e, 0x79, 0x70, 0xd, 0x2f, 0x9b, 0xc7, 0xa5, 0x1a, 0x14, 0xd3, 0x4f, 0x3c, 0xbf, 0x69, 0xf9, 0xee, 0x1, 0xe, 0xab, 0x9e, 0x66, 0x79, 0xc1, 0xd7, 0x7, 0x2c, 0xc7, 0x29, 0xca, 0x78, 0x50, 0x89, 0x22, 0x53, 0x4, 0x0, 0xc4, 0xe8, 0xb2, 0x49, 0xf4, 0xf1, 0x4c, 0x8b, 0x14, 0xfc, 0x90, 0xfa, 0x23, 0xb2, 0x5a, 0x63, 0x97, 0xb1, 0xbd, 0x5b, 0x7c, 0xbd, 0x49, 0xe2, 0x3, 0xc6, 0x82, 0xca, 0x1e, 0x50, 0x97, 0xf1, 0x7e, 0x82, 0x69, 0xc, 0x82, 0x60, 0xb5, 0xd6, 0xc9, 0x18, 0xb8, 0x8d, 0x72, 0xab, 0xf4, 0x66, 0x4f, 0x41, 0x4e, 0x80, 0x8f, 0xb, 0x3c, 0x30, 0x73, 0x21, 0x1d, 0x67, 0x39, 0x8c, 0xb7, 0xf1, 0x35, 0xcf, 0x52, 0x6d, 0x37, 0x3c, 0x95, 0x9b, 0xd3, 0x54, 0x51, 0xc9, 0x54, 0xb8, 0x71, 0xa9, 0x90, 0xb0, 0xf1, 0x4, 0x8f, 0x7c, 0x2e, 0x44, 0xbf, 0x5a, 0xfb, 0xbd, 0xdf, 0x9f, 0xee, 0x7f, 0xc2, 0x44, 0x8, 0x30, 0x87, 0x67, 0xca, 0x46]
prng_i = 0
errors = 0
for i in range(0, len(self.demodulated), 8):
d,e = shuffled_hamming(self.demodulated[i:i+8], prng[prng_i])
data += d
errors += e
if prng_i < len(prng) - 1:
prng_i += 1
# Nibbles are reversed
data = self.nibble_reverse(data)
# Remove decoded bits from demodulated data array
self.demodulated = ""
printd("DATA: " + bin_to_hex(data, False) + " (" + str(errors) + ")")
return data, errors
def reset(self):
self.demodulated = ""
self.state = LoRaState.FIND_SYNC
def calc_energy(self, samples):
return numpy.sum(numpy.square(numpy.abs(samples)))
def general_work(self, input_items, output_items):
in0 = input_items[0]
in1 = input_items[1]
out = output_items[0]
out_w = output_items[1]
num_output_items = len(output_items[0])
if self.state == LoRaState.FIND_SYNC:
#if self.calc_energy(in1[0:32]) > 0.08:
# print("Found packet")
smooth_function = numpy.convolve(signal.gaussian(32, std=12), in0, mode='same') / 32.0
for i in range(0, num_output_items):
out[i] = len(self.sync_buffer) / 10
out_w[i] = smooth_function[i] * 100
if smooth_function[i] < self.last_sample + EPSILON:
self.sync_buffer.append(in1[i])
else:
if len(self.sync_buffer) > 900:
self.window_size = self.samples_per_symbol
printd("SYNC %d (%d)" % (self.window_size, len(self.sync_buffer))) # Sync buffer is how long we observed the chirp to be
self.state = LoRaState.VERIFY_SYNC
# Get downchirp from preamble
#for j in range(0, len(self.sync_buffer)):
# self.downchirp.append(self.sync_buffer[j])
self.sync_buffer = []
self.set_output_multiple(self.window_size + DELAY_AFTER_SYNC)
self.consume_each(i+1)
return i+1
# Add sync hits to array
self.sync_buffer = []
self.last_sample = smooth_function[i]
self.consume_each(num_output_items)
return num_output_items
# TODO: Fourier transform to check second sync
elif self.state == LoRaState.VERIFY_SYNC:
#test = signal.correlate(in1[0:self.window_size], self.downchirp, mode='same') # Divide by 10 for visualizing
test = self.gradient(in1[0:self.window_size+1])
for i in range(0, self.window_size):
out[i] = 100
out_w[i] = test[i/self.compression] / 100.0
#xx = numpy.array(in1)
#xx.tofile("/tmp/sync")
#self.downchirp.tofile("/tmp/downchirp")
corr_argmax = numpy.argmax(test)
corr_max = numpy.max(test)
printd("Sync corr:" + str(corr_max) + " " + str(corr_argmax))
if corr_argmax > 2 or numpy.mean(test) > 2250.0:
printd("Lost sync!")
self.state = LoRaState.FIND_SYNC
self.consume_each(self.window_size)
return self.window_size
else:
printd("Decoding")
self.state = LoRaState.DECODE_HDR
for j in range(self.window_size, self.window_size + DELAY_AFTER_SYNC):
out[j] = 80
out_w[j] = 80
self.consume_each(self.window_size + DELAY_AFTER_SYNC)
return self.window_size + DELAY_AFTER_SYNC
# Decode header
elif self.state == LoRaState.DECODE_HDR:
demodulated = self.demodulate(in1[0:self.window_size+1], True, out, out_w)
if not demodulated is None:
header, errors = self.decode(is_hdr=True)
payload_length = int(header[4:8] + header[0:4], 2) # TODO: Why are these nibbles reversed *again*?
# Set new CR for payload
self.cr = 4 # TODO: Get from header instead of hardcode
symbols_per_block = self.cr + 4
bits_needed = ((payload_length * 8) + 16) * (symbols_per_block / 4)
symbols_needed = float(bits_needed) / float(self.sf)
blocks_needed = numpy.ceil(symbols_needed / symbols_per_block)
self.payload_symbols = blocks_needed * symbols_per_block
printd("LEN: " + str(payload_length) + " (" + str(self.payload_symbols) + " symbols)")
self.state = LoRaState.DECODE_PAYLOAD
self.consume_each(self.window_size)
return self.window_size
elif self.state == LoRaState.DECODE_PAYLOAD:
decoded = self.demodulate(in1[0:self.window_size+1], False, out, out_w)
if not decoded is None:
self.payload_symbols -= (4 + self.cr)
if self.payload_symbols <= 0:
payload, errors = self.decode(is_hdr=False)
print(bin_to_hex(payload, False) + " (" + str(errors) + " errors)")
self.reset() # Ready for new packet
self.consume_each(self.window_size)
return self.window_size

Wyświetl plik

@ -1,723 +0,0 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
# Everyone is permitted to copy and distribute verbatim copies
# of this license document, but changing it is not allowed.
#
# Preamble
#
# The GNU General Public License is a free, copyleft license for
# software and other kinds of works.
#
# The licenses for most software and other practical works are designed
# to take away your freedom to share and change the works. By contrast,
# the GNU General Public License is intended to guarantee your freedom to
# share and change all versions of a program--to make sure it remains free
# software for all its users. We, the Free Software Foundation, use the
# GNU General Public License for most of our software; it applies also to
# any other work released this way by its authors. You can apply it to
# your programs, too.
#
# When we speak of free software, we are referring to freedom, not
# price. Our General Public Licenses are designed to make sure that you
# have the freedom to distribute copies of free software (and charge for
# them if you wish), that you receive source code or can get it if you
# want it, that you can change the software or use pieces of it in new
# free programs, and that you know you can do these things.
#
# To protect your rights, we need to prevent others from denying you
# these rights or asking you to surrender the rights. Therefore, you have
# certain responsibilities if you distribute copies of the software, or if
# you modify it: responsibilities to respect the freedom of others.
#
# For example, if you distribute copies of such a program, whether
# gratis or for a fee, you must pass on to the recipients the same
# freedoms that you received. You must make sure that they, too, receive
# or can get the source code. And you must show them these terms so they
# know their rights.
#
# Developers that use the GNU GPL protect your rights with two steps:
# (1) assert copyright on the software, and (2) offer you this License
# giving you legal permission to copy, distribute and/or modify it.
#
# For the developers' and authors' protection, the GPL clearly explains
# that there is no warranty for this free software. For both users' and
# authors' sake, the GPL requires that modified versions be marked as
# changed, so that their problems will not be attributed erroneously to
# authors of previous versions.
#
# Some devices are designed to deny users access to install or run
# modified versions of the software inside them, although the manufacturer
# can do so. This is fundamentally incompatible with the aim of
# protecting users' freedom to change the software. The systematic
# pattern of such abuse occurs in the area of products for individuals to
# use, which is precisely where it is most unacceptable. Therefore, we
# have designed this version of the GPL to prohibit the practice for those
# products. If such problems arise substantially in other domains, we
# stand ready to extend this provision to those domains in future versions
# of the GPL, as needed to protect the freedom of users.
#
# Finally, every program is threatened constantly by software patents.
# States should not allow patents to restrict development and use of
# software on general-purpose computers, but in those that do, we wish to
# avoid the special danger that patents applied to a free program could
# make it effectively proprietary. To prevent this, the GPL assures that
# patents cannot be used to render the program non-free.
#
# The precise terms and conditions for copying, distribution and
# modification follow.
#
# TERMS AND CONDITIONS
#
# 0. Definitions.
#
# "This License" refers to version 3 of the GNU General Public License.
#
# "Copyright" also means copyright-like laws that apply to other kinds of
# works, such as semiconductor masks.
#
# "The Program" refers to any copyrightable work licensed under this
# License. Each licensee is addressed as "you". "Licensees" and
# "recipients" may be individuals or organizations.
#
# To "modify" a work means to copy from or adapt all or part of the work
# in a fashion requiring copyright permission, other than the making of an
# exact copy. The resulting work is called a "modified version" of the
# earlier work or a work "based on" the earlier work.
#
# A "covered work" means either the unmodified Program or a work based
# on the Program.
#
# To "propagate" a work means to do anything with it that, without
# permission, would make you directly or secondarily liable for
# infringement under applicable copyright law, except executing it on a
# computer or modifying a private copy. Propagation includes copying,
# distribution (with or without modification), making available to the
# public, and in some countries other activities as well.
#
# To "convey" a work means any kind of propagation that enables other
# parties to make or receive copies. Mere interaction with a user through
# a computer network, with no transfer of a copy, is not conveying.
#
# An interactive user interface displays "Appropriate Legal Notices"
# to the extent that it includes a convenient and prominently visible
# feature that (1) displays an appropriate copyright notice, and (2)
# tells the user that there is no warranty for the work (except to the
# extent that warranties are provided), that licensees may convey the
# work under this License, and how to view a copy of this License. If
# the interface presents a list of user commands or options, such as a
# menu, a prominent item in the list meets this criterion.
#
# 1. Source Code.
#
# The "source code" for a work means the preferred form of the work
# for making modifications to it. "Object code" means any non-source
# form of a work.
#
# A "Standard Interface" means an interface that either is an official
# standard defined by a recognized standards body, or, in the case of
# interfaces specified for a particular programming language, one that
# is widely used among developers working in that language.
#
# The "System Libraries" of an executable work include anything, other
# than the work as a whole, that (a) is included in the normal form of
# packaging a Major Component, but which is not part of that Major
# Component, and (b) serves only to enable use of the work with that
# Major Component, or to implement a Standard Interface for which an
# implementation is available to the public in source code form. A
# "Major Component", in this context, means a major essential component
# (kernel, window system, and so on) of the specific operating system
# (if any) on which the executable work runs, or a compiler used to
# produce the work, or an object code interpreter used to run it.
#
# The "Corresponding Source" for a work in object code form means all
# the source code needed to generate, install, and (for an executable
# work) run the object code and to modify the work, including scripts to
# control those activities. However, it does not include the work's
# System Libraries, or general-purpose tools or generally available free
# programs which are used unmodified in performing those activities but
# which are not part of the work. For example, Corresponding Source
# includes interface definition files associated with source files for
# the work, and the source code for shared libraries and dynamically
# linked subprograms that the work is specifically designed to require,
# such as by intimate data communication or control flow between those
# subprograms and other parts of the work.
#
# The Corresponding Source need not include anything that users
# can regenerate automatically from other parts of the Corresponding
# Source.
#
# The Corresponding Source for a work in source code form is that
# same work.
#
# 2. Basic Permissions.
#
# All rights granted under this License are granted for the term of
# copyright on the Program, and are irrevocable provided the stated
# conditions are met. This License explicitly affirms your unlimited
# permission to run the unmodified Program. The output from running a
# covered work is covered by this License only if the output, given its
# content, constitutes a covered work. This License acknowledges your
# rights of fair use or other equivalent, as provided by copyright law.
#
# You may make, run and propagate covered works that you do not
# convey, without conditions so long as your license otherwise remains
# in force. You may convey covered works to others for the sole purpose
# of having them make modifications exclusively for you, or provide you
# with facilities for running those works, provided that you comply with
# the terms of this License in conveying all material for which you do
# not control copyright. Those thus making or running the covered works
# for you must do so exclusively on your behalf, under your direction
# and control, on terms that prohibit them from making any copies of
# your copyrighted material outside their relationship with you.
#
# Conveying under any other circumstances is permitted solely under
# the conditions stated below. Sublicensing is not allowed; section 10
# makes it unnecessary.
#
# 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
#
# No covered work shall be deemed part of an effective technological
# measure under any applicable law fulfilling obligations under article
# 11 of the WIPO copyright treaty adopted on 20 December 1996, or
# similar laws prohibiting or restricting circumvention of such
# measures.
#
# When you convey a covered work, you waive any legal power to forbid
# circumvention of technological measures to the extent such circumvention
# is effected by exercising rights under this License with respect to
# the covered work, and you disclaim any intention to limit operation or
# modification of the work as a means of enforcing, against the work's
# users, your or third parties' legal rights to forbid circumvention of
# technological measures.
#
# 4. Conveying Verbatim Copies.
#
# You may convey verbatim copies of the Program's source code as you
# receive it, in any medium, provided that you conspicuously and
# appropriately publish on each copy an appropriate copyright notice;
# keep intact all notices stating that this License and any
# non-permissive terms added in accord with section 7 apply to the code;
# keep intact all notices of the absence of any warranty; and give all
# recipients a copy of this License along with the Program.
#
# You may charge any price or no price for each copy that you convey,
# and you may offer support or warranty protection for a fee.
#
# 5. Conveying Modified Source Versions.
#
# You may convey a work based on the Program, or the modifications to
# produce it from the Program, in the form of source code under the
# terms of section 4, provided that you also meet all of these conditions:
#
# a) The work must carry prominent notices stating that you modified
# it, and giving a relevant date.
#
# b) The work must carry prominent notices stating that it is
# released under this License and any conditions added under section
# 7. This requirement modifies the requirement in section 4 to
# "keep intact all notices".
#
# c) You must license the entire work, as a whole, under this
# License to anyone who comes into possession of a copy. This
# License will therefore apply, along with any applicable section 7
# additional terms, to the whole of the work, and all its parts,
# regardless of how they are packaged. This License gives no
# permission to license the work in any other way, but it does not
# invalidate such permission if you have separately received it.
#
# d) If the work has interactive user interfaces, each must display
# Appropriate Legal Notices; however, if the Program has interactive
# interfaces that do not display Appropriate Legal Notices, your
# work need not make them do so.
#
# A compilation of a covered work with other separate and independent
# works, which are not by their nature extensions of the covered work,
# and which are not combined with it such as to form a larger program,
# in or on a volume of a storage or distribution medium, is called an
# "aggregate" if the compilation and its resulting copyright are not
# used to limit the access or legal rights of the compilation's users
# beyond what the individual works permit. Inclusion of a covered work
# in an aggregate does not cause this License to apply to the other
# parts of the aggregate.
#
# 6. Conveying Non-Source Forms.
#
# You may convey a covered work in object code form under the terms
# of sections 4 and 5, provided that you also convey the
# machine-readable Corresponding Source under the terms of this License,
# in one of these ways:
#
# a) Convey the object code in, or embodied in, a physical product
# (including a physical distribution medium), accompanied by the
# Corresponding Source fixed on a durable physical medium
# customarily used for software interchange.
#
# b) Convey the object code in, or embodied in, a physical product
# (including a physical distribution medium), accompanied by a
# written offer, valid for at least three years and valid for as
# long as you offer spare parts or customer support for that product
# model, to give anyone who possesses the object code either (1) a
# copy of the Corresponding Source for all the software in the
# product that is covered by this License, on a durable physical
# medium customarily used for software interchange, for a price no
# more than your reasonable cost of physically performing this
# conveying of source, or (2) access to copy the
# Corresponding Source from a network server at no charge.
#
# c) Convey individual copies of the object code with a copy of the
# written offer to provide the Corresponding Source. This
# alternative is allowed only occasionally and noncommercially, and
# only if you received the object code with such an offer, in accord
# with subsection 6b.
#
# d) Convey the object code by offering access from a designated
# place (gratis or for a charge), and offer equivalent access to the
# Corresponding Source in the same way through the same place at no
# further charge. You need not require recipients to copy the
# Corresponding Source along with the object code. If the place to
# copy the object code is a network server, the Corresponding Source
# may be on a different server (operated by you or a third party)
# that supports equivalent copying facilities, provided you maintain
# clear directions next to the object code saying where to find the
# Corresponding Source. Regardless of what server hosts the
# Corresponding Source, you remain obligated to ensure that it is
# available for as long as needed to satisfy these requirements.
#
# e) Convey the object code using peer-to-peer transmission, provided
# you inform other peers where the object code and Corresponding
# Source of the work are being offered to the general public at no
# charge under subsection 6d.
#
# A separable portion of the object code, whose source code is excluded
# from the Corresponding Source as a System Library, need not be
# included in conveying the object code work.
#
# A "User Product" is either (1) a "consumer product", which means any
# tangible personal property which is normally used for personal, family,
# or household purposes, or (2) anything designed or sold for incorporation
# into a dwelling. In determining whether a product is a consumer product,
# doubtful cases shall be resolved in favor of coverage. For a particular
# product received by a particular user, "normally used" refers to a
# typical or common use of that class of product, regardless of the status
# of the particular user or of the way in which the particular user
# actually uses, or expects or is expected to use, the product. A product
# is a consumer product regardless of whether the product has substantial
# commercial, industrial or non-consumer uses, unless such uses represent
# the only significant mode of use of the product.
#
# "Installation Information" for a User Product means any methods,
# procedures, authorization keys, or other information required to install
# and execute modified versions of a covered work in that User Product from
# a modified version of its Corresponding Source. The information must
# suffice to ensure that the continued functioning of the modified object
# code is in no case prevented or interfered with solely because
# modification has been made.
#
# If you convey an object code work under this section in, or with, or
# specifically for use in, a User Product, and the conveying occurs as
# part of a transaction in which the right of possession and use of the
# User Product is transferred to the recipient in perpetuity or for a
# fixed term (regardless of how the transaction is characterized), the
# Corresponding Source conveyed under this section must be accompanied
# by the Installation Information. But this requirement does not apply
# if neither you nor any third party retains the ability to install
# modified object code on the User Product (for example, the work has
# been installed in ROM).
#
# The requirement to provide Installation Information does not include a
# requirement to continue to provide support service, warranty, or updates
# for a work that has been modified or installed by the recipient, or for
# the User Product in which it has been modified or installed. Access to a
# network may be denied when the modification itself materially and
# adversely affects the operation of the network or violates the rules and
# protocols for communication across the network.
#
# Corresponding Source conveyed, and Installation Information provided,
# in accord with this section must be in a format that is publicly
# documented (and with an implementation available to the public in
# source code form), and must require no special password or key for
# unpacking, reading or copying.
#
# 7. Additional Terms.
#
# "Additional permissions" are terms that supplement the terms of this
# License by making exceptions from one or more of its conditions.
# Additional permissions that are applicable to the entire Program shall
# be treated as though they were included in this License, to the extent
# that they are valid under applicable law. If additional permissions
# apply only to part of the Program, that part may be used separately
# under those permissions, but the entire Program remains governed by
# this License without regard to the additional permissions.
#
# When you convey a copy of a covered work, you may at your option
# remove any additional permissions from that copy, or from any part of
# it. (Additional permissions may be written to require their own
# removal in certain cases when you modify the work.) You may place
# additional permissions on material, added by you to a covered work,
# for which you have or can give appropriate copyright permission.
#
# Notwithstanding any other provision of this License, for material you
# add to a covered work, you may (if authorized by the copyright holders of
# that material) supplement the terms of this License with terms:
#
# a) Disclaiming warranty or limiting liability differently from the
# terms of sections 15 and 16 of this License; or
#
# b) Requiring preservation of specified reasonable legal notices or
# author attributions in that material or in the Appropriate Legal
# Notices displayed by works containing it; or
#
# c) Prohibiting misrepresentation of the origin of that material, or
# requiring that modified versions of such material be marked in
# reasonable ways as different from the original version; or
#
# d) Limiting the use for publicity purposes of names of licensors or
# authors of the material; or
#
# e) Declining to grant rights under trademark law for use of some
# trade names, trademarks, or service marks; or
#
# f) Requiring indemnification of licensors and authors of that
# material by anyone who conveys the material (or modified versions of
# it) with contractual assumptions of liability to the recipient, for
# any liability that these contractual assumptions directly impose on
# those licensors and authors.
#
# All other non-permissive additional terms are considered "further
# restrictions" within the meaning of section 10. If the Program as you
# received it, or any part of it, contains a notice stating that it is
# governed by this License along with a term that is a further
# restriction, you may remove that term. If a license document contains
# a further restriction but permits relicensing or conveying under this
# License, you may add to a covered work material governed by the terms
# of that license document, provided that the further restriction does
# not survive such relicensing or conveying.
#
# If you add terms to a covered work in accord with this section, you
# must place, in the relevant source files, a statement of the
# additional terms that apply to those files, or a notice indicating
# where to find the applicable terms.
#
# Additional terms, permissive or non-permissive, may be stated in the
# form of a separately written license, or stated as exceptions;
# the above requirements apply either way.
#
# 8. Termination.
#
# You may not propagate or modify a covered work except as expressly
# provided under this License. Any attempt otherwise to propagate or
# modify it is void, and will automatically terminate your rights under
# this License (including any patent licenses granted under the third
# paragraph of section 11).
#
# However, if you cease all violation of this License, then your
# license from a particular copyright holder is reinstated (a)
# provisionally, unless and until the copyright holder explicitly and
# finally terminates your license, and (b) permanently, if the copyright
# holder fails to notify you of the violation by some reasonable means
# prior to 60 days after the cessation.
#
# Moreover, your license from a particular copyright holder is
# reinstated permanently if the copyright holder notifies you of the
# violation by some reasonable means, this is the first time you have
# received notice of violation of this License (for any work) from that
# copyright holder, and you cure the violation prior to 30 days after
# your receipt of the notice.
#
# Termination of your rights under this section does not terminate the
# licenses of parties who have received copies or rights from you under
# this License. If your rights have been terminated and not permanently
# reinstated, you do not qualify to receive new licenses for the same
# material under section 10.
#
# 9. Acceptance Not Required for Having Copies.
#
# You are not required to accept this License in order to receive or
# run a copy of the Program. Ancillary propagation of a covered work
# occurring solely as a consequence of using peer-to-peer transmission
# to receive a copy likewise does not require acceptance. However,
# nothing other than this License grants you permission to propagate or
# modify any covered work. These actions infringe copyright if you do
# not accept this License. Therefore, by modifying or propagating a
# covered work, you indicate your acceptance of this License to do so.
#
# 10. Automatic Licensing of Downstream Recipients.
#
# Each time you convey a covered work, the recipient automatically
# receives a license from the original licensors, to run, modify and
# propagate that work, subject to this License. You are not responsible
# for enforcing compliance by third parties with this License.
#
# An "entity transaction" is a transaction transferring control of an
# organization, or substantially all assets of one, or subdividing an
# organization, or merging organizations. If propagation of a covered
# work results from an entity transaction, each party to that
# transaction who receives a copy of the work also receives whatever
# licenses to the work the party's predecessor in interest had or could
# give under the previous paragraph, plus a right to possession of the
# Corresponding Source of the work from the predecessor in interest, if
# the predecessor has it or can get it with reasonable efforts.
#
# You may not impose any further restrictions on the exercise of the
# rights granted or affirmed under this License. For example, you may
# not impose a license fee, royalty, or other charge for exercise of
# rights granted under this License, and you may not initiate litigation
# (including a cross-claim or counterclaim in a lawsuit) alleging that
# any patent claim is infringed by making, using, selling, offering for
# sale, or importing the Program or any portion of it.
#
# 11. Patents.
#
# A "contributor" is a copyright holder who authorizes use under this
# License of the Program or a work on which the Program is based. The
# work thus licensed is called the contributor's "contributor version".
#
# A contributor's "essential patent claims" are all patent claims
# owned or controlled by the contributor, whether already acquired or
# hereafter acquired, that would be infringed by some manner, permitted
# by this License, of making, using, or selling its contributor version,
# but do not include claims that would be infringed only as a
# consequence of further modification of the contributor version. For
# purposes of this definition, "control" includes the right to grant
# patent sublicenses in a manner consistent with the requirements of
# this License.
#
# Each contributor grants you a non-exclusive, worldwide, royalty-free
# patent license under the contributor's essential patent claims, to
# make, use, sell, offer for sale, import and otherwise run, modify and
# propagate the contents of its contributor version.
#
# In the following three paragraphs, a "patent license" is any express
# agreement or commitment, however denominated, not to enforce a patent
# (such as an express permission to practice a patent or covenant not to
# sue for patent infringement). To "grant" such a patent license to a
# party means to make such an agreement or commitment not to enforce a
# patent against the party.
#
# If you convey a covered work, knowingly relying on a patent license,
# and the Corresponding Source of the work is not available for anyone
# to copy, free of charge and under the terms of this License, through a
# publicly available network server or other readily accessible means,
# then you must either (1) cause the Corresponding Source to be so
# available, or (2) arrange to deprive yourself of the benefit of the
# patent license for this particular work, or (3) arrange, in a manner
# consistent with the requirements of this License, to extend the patent
# license to downstream recipients. "Knowingly relying" means you have
# actual knowledge that, but for the patent license, your conveying the
# covered work in a country, or your recipient's use of the covered work
# in a country, would infringe one or more identifiable patents in that
# country that you have reason to believe are valid.
#
# If, pursuant to or in connection with a single transaction or
# arrangement, you convey, or propagate by procuring conveyance of, a
# covered work, and grant a patent license to some of the parties
# receiving the covered work authorizing them to use, propagate, modify
# or convey a specific copy of the covered work, then the patent license
# you grant is automatically extended to all recipients of the covered
# work and works based on it.
#
# A patent license is "discriminatory" if it does not include within
# the scope of its coverage, prohibits the exercise of, or is
# conditioned on the non-exercise of one or more of the rights that are
# specifically granted under this License. You may not convey a covered
# work if you are a party to an arrangement with a third party that is
# in the business of distributing software, under which you make payment
# to the third party based on the extent of your activity of conveying
# the work, and under which the third party grants, to any of the
# parties who would receive the covered work from you, a discriminatory
# patent license (a) in connection with copies of the covered work
# conveyed by you (or copies made from those copies), or (b) primarily
# for and in connection with specific products or compilations that
# contain the covered work, unless you entered into that arrangement,
# or that patent license was granted, prior to 28 March 2007.
#
# Nothing in this License shall be construed as excluding or limiting
# any implied license or other defenses to infringement that may
# otherwise be available to you under applicable patent law.
#
# 12. No Surrender of Others' Freedom.
#
# If conditions are imposed on you (whether by court order, agreement or
# otherwise) that contradict the conditions of this License, they do not
# excuse you from the conditions of this License. If you cannot convey a
# covered work so as to satisfy simultaneously your obligations under this
# License and any other pertinent obligations, then as a consequence you may
# not convey it at all. For example, if you agree to terms that obligate you
# to collect a royalty for further conveying from those to whom you convey
# the Program, the only way you could satisfy both those terms and this
# License would be to refrain entirely from conveying the Program.
#
# 13. Use with the GNU Affero General Public License.
#
# Notwithstanding any other provision of this License, you have
# permission to link or combine any covered work with a work licensed
# under version 3 of the GNU Affero General Public License into a single
# combined work, and to convey the resulting work. The terms of this
# License will continue to apply to the part which is the covered work,
# but the special requirements of the GNU Affero General Public License,
# section 13, concerning interaction through a network will apply to the
# combination as such.
#
# 14. Revised Versions of this License.
#
# The Free Software Foundation may publish revised and/or new versions of
# the GNU General Public License from time to time. Such new versions will
# be similar in spirit to the present version, but may differ in detail to
# address new problems or concerns.
#
# Each version is given a distinguishing version number. If the
# Program specifies that a certain numbered version of the GNU General
# Public License "or any later version" applies to it, you have the
# option of following the terms and conditions either of that numbered
# version or of any later version published by the Free Software
# Foundation. If the Program does not specify a version number of the
# GNU General Public License, you may choose any version ever published
# by the Free Software Foundation.
#
# If the Program specifies that a proxy can decide which future
# versions of the GNU General Public License can be used, that proxy's
# public statement of acceptance of a version permanently authorizes you
# to choose that version for the Program.
#
# Later license versions may give you additional or different
# permissions. However, no additional obligations are imposed on any
# author or copyright holder as a result of your choosing to follow a
# later version.
#
# 15. Disclaimer of Warranty.
#
# THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
# APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
# HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
# OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
# IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
# ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
#
# 16. Limitation of Liability.
#
# IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
# WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
# THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
# GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
# USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
# DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
# PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
# EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGES.
#
# 17. Interpretation of Sections 15 and 16.
#
# If the disclaimer of warranty and limitation of liability provided
# above cannot be given local legal effect according to their terms,
# reviewing courts shall apply local law that most closely approximates
# an absolute waiver of all civil liability in connection with the
# Program, unless a warranty or assumption of liability accompanies a
# copy of the Program in return for a fee.
#
# END OF TERMS AND CONDITIONS
#
# How to Apply These Terms to Your New Programs
#
# If you develop a new program, and you want it to be of the greatest
# possible use to the public, the best way to achieve this is to make it
# free software which everyone can redistribute and change under these terms.
#
# To do so, attach the following notices to the program. It is safest
# to attach them to the start of each source file to most effectively
# state the exclusion of warranty; and each file should have at least
# the "copyright" line and a pointer to where the full notice is found.
#
# {one line to give the program's name and a brief idea of what it does.}
# Copyright (C) {year} {name of author}
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Also add information on how to contact you by electronic and paper mail.
#
# If the program does terminal interaction, make it output a short
# notice like this when it starts in an interactive mode:
#
# {project} Copyright (C) {year} {fullname}
# This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
# This is free software, and you are welcome to redistribute it
# under certain conditions; type `show c' for details.
#
# The hypothetical commands `show w' and `show c' should show the appropriate
# parts of the General Public License. Of course, your program's commands
# might be different; for a GUI interface, you would use an "about box".
#
# You should also get your employer (if you work as a programmer) or school,
# if any, to sign a "copyright disclaimer" for the program, if necessary.
# For more information on this, and how to apply and follow the GNU GPL, see
# <http://www.gnu.org/licenses/>.
#
# The GNU General Public License does not permit incorporating your program
# into proprietary programs. If your program is a subroutine library, you
# may consider it more useful to permit linking proprietary applications with
# the library. If this is what you want to do, use the GNU Lesser General
# Public License instead of this License. But first, please read
# <http://www.gnu.org/philosophy/why-not-lgpl.html>.
#
import numpy
import pmt
import socket
from gnuradio import gr, blocks
from gnuradio.blocks import socket_pdu
class message_wireshark_sink(gr.basic_block):
"""
docstring for block message_wireshark_sink
"""
def __init__(self):
gr.basic_block.__init__(self,
name="message_wireshark_sink",
in_sig=[],
out_sig=[])
self.message_port_register_in(pmt.intern("in"))
self.set_msg_handler(pmt.intern("in"), self.msg_handler)
# Register system_handler to stop execution when done.
self.message_port_register_in(pmt.intern("system"))
self.set_msg_handler(pmt.intern("system"), self.system_handler)
self.host = "127.0.0.1"
self.port = 40868
###self.server = socket_pdu("UDP_SERVER", self.host, str(self.port))
self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def msg_handler(self, msg):
msg = pmt.to_python(msg)
self.client.sendto(msg, (self.host, self.port))
def system_handler(self, msg):
#### Sends 'done' message, but does NOT end flowchart execution!
#### This is apparently a known bug in the Python connection to the message system.
#### Examples:
#### https://lists.gnu.org/archive/html/discuss-gnuradio/2015-03/msg00223.html
#### https://lists.gnu.org/archive/html/discuss-gnuradio/2015-04/msg00093.html
#### https://lists.gnu.org/archive/html/discuss-gnuradio/2016-07/msg00320.html
#### A GNU Radio block written in C++ works as expected.
#### Workaround by raising exception...
# print msg
print ("End transmission. Press CTRL+C to continue...")
# raise Exception("Continuing...")
exit(0)

Wyświetl plik

@ -187,7 +187,7 @@ class qa_testsuite():
try:
data = self.server.recvfrom(65535)[0]
if data:
total_data.append(binascii.hexlify(data[3:])) # Discard header and convert to hex text
total_data.append(binascii.hexlify(data))
except Exception as e:
print(e)
pass
@ -248,7 +248,7 @@ class qa_testsuite():
file_source = blocks.file_source(gr.sizeof_gr_complex, data_file, False)
lora_receiver = lora.lora_receiver(sample_rate, capture_freq, [868100000], sf, 1000000, 0.002)
throttle = blocks.throttle(gr.sizeof_gr_complex, sample_rate, True)
message_socket_sink = lora.message_socket_sink()
message_socket_sink = lora.message_socket_sink("127.0.0.1", 40868, False, False)
freq_xlating_fir_filter = filter.freq_xlating_fir_filter_ccc(1, (firdes.low_pass(1, sample_rate, 200000, 100000, firdes.WIN_HAMMING, 6.67)), frequency_offset, sample_rate)
# Make connections