first commit

This commit is contained in:
lewishe
2023-04-11 11:27:36 +08:00
commit daa54b6448
2146 changed files with 915567 additions and 0 deletions
+37
View File
@@ -0,0 +1,37 @@
#include "AFSK.h"
#if !defined(RADIOLIB_EXCLUDE_AFSK)
AFSKClient::AFSKClient(PhysicalLayer* phy, RADIOLIB_PIN_TYPE pin): _pin(pin) {
_phy = phy;
}
int16_t AFSKClient::begin() {
return(_phy->startDirect());
}
int16_t AFSKClient::tone(uint16_t freq, bool autoStart) {
if(freq == 0) {
return(RADIOLIB_ERR_INVALID_FREQUENCY);
}
if(autoStart) {
int16_t state = _phy->transmitDirect();
RADIOLIB_ASSERT(state);
}
Module* mod = _phy->getMod();
mod->tone(_pin, freq);
return(RADIOLIB_ERR_NONE);
}
int16_t AFSKClient::noTone(bool keepOn) {
Module* mod = _phy->getMod();
mod->noTone(_pin);
if(keepOn) {
return(0);
}
return(_phy->standby());
}
#endif
+72
View File
@@ -0,0 +1,72 @@
#if !defined(_RADIOLIB_AFSK_H)
#define _RADIOLIB_AFSK_H
#include "../../TypeDef.h"
#if !defined(RADIOLIB_EXCLUDE_AFSK)
#include "../../Module.h"
#include "../PhysicalLayer/PhysicalLayer.h"
/*!
\class AFSKClient
\brief Client for audio-based transmissions. Requires Arduino tone() function, and a module capable of direct mode transmission using DIO pins.
*/
class AFSKClient {
public:
/*!
\brief Default contructor.
\param phy Pointer to the wireless module providing PhysicalLayer communication.
\param pin The pin that will be used for audio output.
*/
AFSKClient(PhysicalLayer* phy, RADIOLIB_PIN_TYPE pin);
/*!
\brief Initialization method.
\returns \ref status_codes
*/
int16_t begin();
/*!
\brief Start transmitting audio tone.
\param freq Frequency of the tone in Hz.
\param autoStart Whether to automatically enter transmission mode. Defaults to true.
\returns \ref status_codes
*/
int16_t tone(uint16_t freq, bool autoStart = true);
/*!
\brief Stops transmitting audio tone.
\param freq Keep transmitter on - this may limit noise when switching transmitter on or off.
\returns \ref status_codes
*/
int16_t noTone(bool keepOn = false);
#if !defined(RADIOLIB_GODMODE)
private:
#endif
PhysicalLayer* _phy;
RADIOLIB_PIN_TYPE _pin;
// allow specific classes access the private PhysicalLayer pointer
friend class RTTYClient;
friend class MorseClient;
friend class HellClient;
friend class SSTVClient;
friend class AX25Client;
friend class FSK4Client;
};
#endif
#endif
+227
View File
@@ -0,0 +1,227 @@
#include "APRS.h"
APRSClient::APRSClient(AX25Client* ax) {
_ax = ax;
}
int16_t APRSClient::begin(char symbol, bool alt) {
RADIOLIB_CHECK_RANGE(symbol, ' ', '}', RADIOLIB_ERR_INVALID_SYMBOL);
_symbol = symbol;
if(alt) {
_table = '\\';
} else {
_table = '/';
}
return(RADIOLIB_ERR_NONE);
}
int16_t APRSClient::sendPosition(char* destCallsign, uint8_t destSSID, char* lat, char* lon, char* msg, char* time) {
#if !defined(RADIOLIB_STATIC_ONLY)
size_t len = 1 + strlen(lat) + 1 + strlen(lon);
if(msg != NULL) {
len += 1 + strlen(msg);
}
if(time != NULL) {
len += strlen(time);
}
char* info = new char[len];
#else
char info[RADIOLIB_STATIC_ARRAY_SIZE];
#endif
// build the info field
if((msg == NULL) && (time == NULL)) {
// no message, no timestamp
sprintf(info, RADIOLIB_APRS_DATA_TYPE_POSITION_NO_TIME_NO_MSG "%s%c%s%c", lat, _table, lon, _symbol);
} else if((msg != NULL) && (time == NULL)) {
// message, no timestamp
sprintf(info, RADIOLIB_APRS_DATA_TYPE_POSITION_NO_TIME_MSG "%s%c%s%c%s", lat, _table, lon, _symbol, msg);
} else if((msg == NULL) && (time != NULL)) {
// timestamp, no message
sprintf(info, RADIOLIB_APRS_DATA_TYPE_POSITION_TIME_NO_MSG "%s%s%c%s%c", time, lat, _table, lon, _symbol);
} else {
// timestamp and message
sprintf(info, RADIOLIB_APRS_DATA_TYPE_POSITION_TIME_MSG "%s%s%c%s%c%s", time, lat, _table, lon, _symbol, msg);
}
// send the frame
int16_t state = sendFrame(destCallsign, destSSID, info);
#if !defined(RADIOLIB_STATIC_ONLY)
delete[] info;
#endif
return(state);
}
int16_t APRSClient::sendMicE(float lat, float lon, uint16_t heading, uint16_t speed, uint8_t type, uint8_t* telem, size_t telemLen, char* grid, char* status, int32_t alt) {
// sanity checks first
if(((telemLen == 0) && (telem != NULL)) || ((telemLen != 0) && (telem == NULL))) {
return(RADIOLIB_ERR_INVALID_MIC_E_TELEMETRY);
}
if((telemLen != 0) && (telemLen != 2) && (telemLen != 5)) {
return(RADIOLIB_ERR_INVALID_MIC_E_TELEMETRY_LENGTH);
}
if((telemLen > 0) && ((grid != NULL) || (status != NULL) || (alt != RADIOLIB_APRS_MIC_E_ALTITUDE_UNUSED))) {
// can't have both telemetry and status
return(RADIOLIB_ERR_MIC_E_TELEMETRY_STATUS);
}
// prepare buffers
char destCallsign[7];
#if !defined(RADIOLIB_STATIC_ONLY)
size_t infoLen = 10;
if(telemLen > 0) {
infoLen += 1 + telemLen;
} else {
if(grid != NULL) {
infoLen += strlen(grid) + 2;
}
if(status != NULL) {
infoLen += strlen(status);
}
if(alt > RADIOLIB_APRS_MIC_E_ALTITUDE_UNUSED) {
infoLen += 4;
}
}
char* info = new char[infoLen];
#else
char info[RADIOLIB_STATIC_ARRAY_SIZE];
#endif
size_t infoPos = 0;
// the following is based on APRS Mic-E implementation by https://github.com/omegat
// as discussed in https://github.com/jgromes/RadioLib/issues/430
// latitude first, because that is in the destination field
float lat_abs = abs(lat);
int lat_deg = (int)lat_abs;
int lat_min = (lat_abs - (float)lat_deg) * 60.0f;
int lat_hun = (((lat_abs - (float)lat_deg) * 60.0f) - lat_min) * 100.0f;
destCallsign[0] = lat_deg/10;
destCallsign[1] = lat_deg%10;
destCallsign[2] = lat_min/10;
destCallsign[3] = lat_min%10;
destCallsign[4] = lat_hun/10;
destCallsign[5] = lat_hun%10;
// next, add the extra bits
if(type & 0x04) { destCallsign[0] += RADIOLIB_APRS_MIC_E_DEST_BIT_OFFSET; }
if(type & 0x02) { destCallsign[1] += RADIOLIB_APRS_MIC_E_DEST_BIT_OFFSET; }
if(type & 0x01) { destCallsign[2] += RADIOLIB_APRS_MIC_E_DEST_BIT_OFFSET; }
if(lat >= 0) { destCallsign[3] += RADIOLIB_APRS_MIC_E_DEST_BIT_OFFSET; }
if(lon >= 100 || lon <= -100) { destCallsign[4] += RADIOLIB_APRS_MIC_E_DEST_BIT_OFFSET; }
if(lon < 0) { destCallsign[5] += RADIOLIB_APRS_MIC_E_DEST_BIT_OFFSET; }
destCallsign[6] = '\0';
// now convert to Mic-E characters to get the "callsign"
for(uint8_t i = 0; i < 6; i++) {
if(destCallsign[i] <= 9) {
destCallsign[i] += '0';
} else {
destCallsign[i] += ('A' - 10);
}
}
// setup the information field
info[infoPos++] = RADIOLIB_APRS_MIC_E_GPS_DATA_CURRENT;
// encode the longtitude
float lon_abs = abs(lon);
int32_t lon_deg = (int32_t)lon_abs;
int32_t lon_min = (lon_abs - (float)lon_deg) * 60.0f;
int32_t lon_hun = (((lon_abs - (float)lon_deg) * 60.0f) - lon_min) * 100.0f;
if(lon_deg <= 9) {
info[infoPos++] = lon_deg + 118;
} else if(lon_deg <= 99) {
info[infoPos++] = lon_deg + 28;
} else if(lon_deg <= 109) {
info[infoPos++] = lon_deg + 8;
} else {
info[infoPos++] = lon_deg - 72;
}
if(lon_min <= 9){
info[infoPos++] = lon_min + 88;
} else {
info[infoPos++] = lon_min + 28;
}
info[infoPos++] = lon_hun + 28;
// now the speed and heading - this gets really weird
int32_t speed_hun_ten = speed/10;
int32_t speed_uni = speed%10;
int32_t head_hun = heading/100;
int32_t head_ten_uni = heading%100;
if(speed <= 199) {
info[infoPos++] = speed_hun_ten + 'l';
} else {
info[infoPos++] = speed_hun_ten + '0';
}
info[infoPos++] = speed_uni*10 + head_hun + 32;
info[infoPos++] = head_ten_uni + 28;
info[infoPos++] = _symbol;
info[infoPos++] = _table;
// onto the optional stuff - check telemetry first
if(telemLen > 0) {
if(telemLen == 2) {
info[infoPos++] = RADIOLIB_APRS_MIC_E_TELEMETRY_LEN_2;
} else {
info[infoPos++] = RADIOLIB_APRS_MIC_E_TELEMETRY_LEN_5;
}
for(uint8_t i = 0; i < telemLen; i++) {
sprintf(&(info[infoPos]), "%02X", telem[i]);
infoPos += 2;
}
} else {
if(grid != NULL) {
memcpy(&(info[infoPos]), grid, strlen(grid));
infoPos += strlen(grid);
info[infoPos++] = '/';
info[infoPos++] = 'G';
}
if(status != NULL) {
info[infoPos++] = ' ';
memcpy(&(info[infoPos]), status, strlen(status));
infoPos += strlen(status);
}
if(alt > RADIOLIB_APRS_MIC_E_ALTITUDE_UNUSED) {
// altitude is offset by -10 km
int32_t alt_val = alt + 10000;
// ... and encoded in base 91 for some reason
info[infoPos++] = (alt_val / 8281) + 33;
info[infoPos++] = ((alt_val % 8281) / 91) + 33;
info[infoPos++] = ((alt_val % 8281) % 91) + 33;
info[infoPos++] = '}';
}
}
info[infoPos++] = '\0';
// send the frame
int16_t state = sendFrame(destCallsign, 0, info);
#if !defined(RADIOLIB_STATIC_ONLY)
delete[] info;
#endif
return(state);
}
int16_t APRSClient::sendFrame(char* destCallsign, uint8_t destSSID, char* info) {
// get AX.25 callsign
char srcCallsign[RADIOLIB_AX25_MAX_CALLSIGN_LEN + 1];
_ax->getCallsign(srcCallsign);
AX25Frame frameUI(destCallsign, destSSID, srcCallsign, _ax->getSSID(), RADIOLIB_AX25_CONTROL_U_UNNUMBERED_INFORMATION |
RADIOLIB_AX25_CONTROL_POLL_FINAL_DISABLED | RADIOLIB_AX25_CONTROL_UNNUMBERED_FRAME,
RADIOLIB_AX25_PID_NO_LAYER_3, (const char*)info);
return(_ax->sendFrame(&frameUI));
}
+157
View File
@@ -0,0 +1,157 @@
#if !defined(_RADIOLIB_RADIOLIB_APRS_H)
#define _RADIOLIB_RADIOLIB_APRS_H
#include "../../TypeDef.h"
#if !defined(RADIOLIB_EXCLUDE_APRS)
#include "../PhysicalLayer/PhysicalLayer.h"
#include "../AX25/AX25.h"
// APRS data type identifiers
#define RADIOLIB_APRS_DATA_TYPE_POSITION_NO_TIME_NO_MSG "!"
#define RADIOLIB_APRS_DATA_TYPE_GPS_RAW "$"
#define RADIOLIB_APRS_DATA_TYPE_ITEM ")"
#define RADIOLIB_APRS_DATA_TYPE_TEST ","
#define RADIOLIB_APRS_DATA_TYPE_POSITION_TIME_NO_MSG "/"
#define RADIOLIB_APRS_DATA_TYPE_MSG ":"
#define RADIOLIB_APRS_DATA_TYPE_OBJECT ";"
#define RADIOLIB_APRS_DATA_TYPE_STATION_CAPABILITES "<"
#define RADIOLIB_APRS_DATA_TYPE_POSITION_NO_TIME_MSG "="
#define RADIOLIB_APRS_DATA_TYPE_STATUS ">"
#define RADIOLIB_APRS_DATA_TYPE_QUERY "?"
#define RADIOLIB_APRS_DATA_TYPE_POSITION_TIME_MSG "@"
#define RADIOLIB_APRS_DATA_TYPE_TELEMETRY "T"
#define RADIOLIB_APRS_DATA_TYPE_MAIDENHEAD_BEACON "["
#define RADIOLIB_APRS_DATA_TYPE_WEATHER_REPORT "_"
#define RADIOLIB_APRS_DATA_TYPE_USER_DEFINED "{"
#define RADIOLIB_APRS_DATA_TYPE_THIRD_PARTY "}"
/*!
\defgroup mic_e_message_types Mic-E message types.
\{
*/
#define RADIOLIB_APRS_MIC_E_TYPE_OFF_DUTY 0b00000111
#define RADIOLIB_APRS_MIC_E_TYPE_EN_ROUTE 0b00000110
#define RADIOLIB_APRS_MIC_E_TYPE_IN_SERVICE 0b00000101
#define RADIOLIB_APRS_MIC_E_TYPE_RETURNING 0b00000100
#define RADIOLIB_APRS_MIC_E_TYPE_COMMITTED 0b00000011
#define RADIOLIB_APRS_MIC_E_TYPE_SPECIAL 0b00000010
#define RADIOLIB_APRS_MIC_E_TYPE_PRIORITY 0b00000001
#define RADIOLIB_APRS_MIC_E_TYPE_EMERGENCY 0b00000000
/*!
\}
*/
// magic offset applied to encode extra bits in the Mic-E destination field
#define RADIOLIB_APRS_MIC_E_DEST_BIT_OFFSET 25
// Mic-E data types
#define RADIOLIB_APRS_MIC_E_GPS_DATA_CURRENT '`'
#define RADIOLIB_APRS_MIC_E_GPS_DATA_OLD '\''
// Mic-E telemetry flags
#define RADIOLIB_APRS_MIC_E_TELEMETRY_LEN_2 '`'
#define RADIOLIB_APRS_MIC_E_TELEMETRY_LEN_5 '\''
// alias for unused altitude in Mic-E
#define RADIOLIB_APRS_MIC_E_ALTITUDE_UNUSED -1000000
/*!
\class APRSClient
\brief Client for APRS communication.
*/
class APRSClient {
public:
/*!
\brief Default constructor.
\param ax Pointer to the instance of AX25Client to be used for APRS.
*/
explicit APRSClient(AX25Client* ax);
// basic methods
/*!
\brief Initialization method.
\param symbol APRS symbol to be displayed.
\param alt Whether to use the primary (false) or alternate (true) symbol table. Defaults to primary table.
\returns \ref status_codes
*/
int16_t begin(char symbol, bool alt = false);
/*!
\brief Transmit position.
\param destCallsign Destination station callsign.
\param destSSID Destination station SSID.
\param lat Latitude as a null-terminated string.
\param long Longitude as a null-terminated string.
\param msg Message to be transmitted. Defaults to NULL (no message).
\param msg Position timestamp. Defaults to NULL (no timestamp).
\returns \ref status_codes
*/
int16_t sendPosition(char* destCallsign, uint8_t destSSID, char* lat, char* lon, char* msg = NULL, char* time = NULL);
/*
\brief Transmit position using Mic-E encoding.
\param lat Geographical latitude, positive for north, negative for south.
\param lon Geographical longitude, positive for east, negative for west.
\param heading Heading in degrees.
\param speed Speed in knots.
\param type Mic-E message type - see \ref mic_e_message_types.
\param telem Pointer to telemetry array (either 2 or 5 bytes long). NULL when telemetry is not used.
\param telemLen Telemetry length, 2 or 5. 0 when telemetry is not used.
\param grid Maidenhead grid locator. NULL when not used.
\param status Status message to send. NULL when not used.
\param alt Altitude to send. RADIOLIB_APRS_MIC_E_ALTITUDE_UNUSED when not used.
*/
int16_t sendMicE(float lat, float lon, uint16_t heading, uint16_t speed, uint8_t type, uint8_t* telem = NULL, size_t telemLen = 0, char* grid = NULL, char* status = NULL, int32_t alt = RADIOLIB_APRS_MIC_E_ALTITUDE_UNUSED);
/*!
\brief Transmit generic APRS frame.
\param destCallsign Destination station callsign.
\param destSSID Destination station SSID.
\param info AX.25 info field contents.
\returns \ref status_codes
*/
int16_t sendFrame(char* destCallsign, uint8_t destSSID, char* info);
#if !defined(RADIOLIB_GODMODE)
private:
#endif
AX25Client* _ax;
// default APRS symbol (car)
char _symbol = '>';
char _table = '/';
};
#endif
#endif
+465
View File
@@ -0,0 +1,465 @@
#include "AX25.h"
#if !defined(RADIOLIB_EXCLUDE_AX25)
AX25Frame::AX25Frame(const char* destCallsign, uint8_t destSSID, const char* srcCallsign, uint8_t srcSSID, uint8_t control)
: AX25Frame(destCallsign, destSSID, srcCallsign, srcSSID, control, 0, NULL, 0) {
}
AX25Frame::AX25Frame(const char* destCallsign, uint8_t destSSID, const char* srcCallsign, uint8_t srcSSID, uint8_t control, uint8_t protocolID, const char* info)
: AX25Frame(destCallsign, destSSID, srcCallsign, srcSSID, control, protocolID, (uint8_t*)info, strlen(info)) {
}
AX25Frame::AX25Frame(const char* destCallsign, uint8_t destSSID, const char* srcCallsign, uint8_t srcSSID, uint8_t control, uint8_t protocolID, uint8_t* info, uint16_t infoLen) {
// destination callsign/SSID
memcpy(this->destCallsign, destCallsign, strlen(destCallsign));
this->destCallsign[strlen(destCallsign)] = '\0';
this->destSSID = destSSID;
// source callsign/SSID
memcpy(this->srcCallsign, srcCallsign, strlen(srcCallsign));
this->srcCallsign[strlen(srcCallsign)] = '\0';
this->srcSSID = srcSSID;
// set repeaters
this->numRepeaters = 0;
#if !defined(RADIOLIB_STATIC_ONLY)
this->repeaterCallsigns = NULL;
this->repeaterSSIDs = NULL;
#endif
// control field
this->control = control;
// sequence numbers
this->rcvSeqNumber = 0;
this->sendSeqNumber = 0;
// PID field
this->protocolID = protocolID;
// info field
this->infoLen = infoLen;
if(infoLen > 0) {
#if !defined(RADIOLIB_STATIC_ONLY)
this->info = new uint8_t[infoLen];
#endif
memcpy(this->info, info, infoLen);
}
}
AX25Frame::AX25Frame(const AX25Frame& frame) {
*this = frame;
}
AX25Frame::~AX25Frame() {
#if !defined(RADIOLIB_STATIC_ONLY)
// deallocate info field
if(infoLen > 0) {
delete[] this->info;
}
// deallocate repeaters
if(this->numRepeaters > 0) {
for(uint8_t i = 0; i < this->numRepeaters; i++) {
delete[] this->repeaterCallsigns[i];
}
delete[] this->repeaterCallsigns;
delete[] this->repeaterSSIDs;
}
#endif
}
AX25Frame& AX25Frame::operator=(const AX25Frame& frame) {
// destination callsign/SSID
memcpy(this->destCallsign, frame.destCallsign, strlen(frame.destCallsign));
this->destCallsign[strlen(frame.destCallsign)] = '\0';
this->destSSID = frame.destSSID;
// source callsign/SSID
memcpy(this->srcCallsign, frame.srcCallsign, strlen(frame.srcCallsign));
this->srcCallsign[strlen(frame.srcCallsign)] = '\0';
this->srcSSID = frame.srcSSID;
// repeaters
this->numRepeaters = frame.numRepeaters;
for(uint8_t i = 0; i < this->numRepeaters; i++) {
memcpy(this->repeaterCallsigns[i], frame.repeaterCallsigns[i], strlen(frame.repeaterCallsigns[i]));
}
memcpy(this->repeaterSSIDs, frame.repeaterSSIDs, this->numRepeaters);
// control field
this->control = frame.control;
// sequence numbers
this->rcvSeqNumber = frame.rcvSeqNumber;
this->sendSeqNumber = frame.sendSeqNumber;
// PID field
this->protocolID = frame.protocolID;
// info field
this->infoLen = frame.infoLen;
memcpy(this->info, frame.info, this->infoLen);
return(*this);
}
int16_t AX25Frame::setRepeaters(char** repeaterCallsigns, uint8_t* repeaterSSIDs, uint8_t numRepeaters) {
// check number of repeaters
if((numRepeaters < 1) || (numRepeaters > 8)) {
return(RADIOLIB_ERR_INVALID_NUM_REPEATERS);
}
// check repeater configuration
if((repeaterCallsigns == NULL) || (repeaterSSIDs == NULL)) {
return(RADIOLIB_ERR_INVALID_NUM_REPEATERS);
}
for(uint16_t i = 0; i < numRepeaters; i++) {
if(strlen(repeaterCallsigns[i]) > RADIOLIB_AX25_MAX_CALLSIGN_LEN) {
return(RADIOLIB_ERR_INVALID_REPEATER_CALLSIGN);
}
}
// create buffers
#if !defined(RADIOLIB_STATIC_ONLY)
this->repeaterCallsigns = new char*[numRepeaters];
for(uint8_t i = 0; i < numRepeaters; i++) {
this->repeaterCallsigns[i] = new char[strlen(repeaterCallsigns[i]) + 1];
}
this->repeaterSSIDs = new uint8_t[numRepeaters];
#endif
// copy data
this->numRepeaters = numRepeaters;
for(uint8_t i = 0; i < numRepeaters; i++) {
memcpy(this->repeaterCallsigns[i], repeaterCallsigns[i], strlen(repeaterCallsigns[i]));
this->repeaterCallsigns[i][strlen(repeaterCallsigns[i])] = '\0';
}
memcpy(this->repeaterSSIDs, repeaterSSIDs, numRepeaters);
return(RADIOLIB_ERR_NONE);
}
void AX25Frame::setRecvSequence(uint8_t seqNumber) {
this->rcvSeqNumber = seqNumber;
}
void AX25Frame::setSendSequence(uint8_t seqNumber) {
this->sendSeqNumber = seqNumber;
}
AX25Client::AX25Client(PhysicalLayer* phy) {
_phy = phy;
#if !defined(RADIOLIB_EXCLUDE_AFSK)
_audio = nullptr;
#endif
}
#if !defined(RADIOLIB_EXCLUDE_AFSK)
AX25Client::AX25Client(AFSKClient* audio) {
_phy = audio->_phy;
_audio = audio;
_afskMark = RADIOLIB_AX25_AFSK_MARK;
_afskSpace = RADIOLIB_AX25_AFSK_SPACE;
}
int16_t AX25Client::setCorrection(int16_t mark, int16_t space) {
_afskMark = RADIOLIB_AX25_AFSK_MARK + mark;
_afskSpace = RADIOLIB_AX25_AFSK_SPACE + space;
return(RADIOLIB_ERR_NONE);
}
#endif
int16_t AX25Client::begin(const char* srcCallsign, uint8_t srcSSID, uint8_t preambleLen) {
// set source SSID
_srcSSID = srcSSID;
// check source callsign length (6 characters max)
if(strlen(srcCallsign) > RADIOLIB_AX25_MAX_CALLSIGN_LEN) {
return(RADIOLIB_ERR_INVALID_CALLSIGN);
}
// copy callsign
memcpy(_srcCallsign, srcCallsign, strlen(srcCallsign));
_srcCallsign[strlen(srcCallsign)] = '\0';
// save preamble length
_preambleLen = preambleLen;
// configure for direct mode
return(_phy->startDirect());
}
int16_t AX25Client::transmit(const char* str, const char* destCallsign, uint8_t destSSID) {
// create control field
uint8_t controlField = RADIOLIB_AX25_CONTROL_U_UNNUMBERED_INFORMATION | RADIOLIB_AX25_CONTROL_POLL_FINAL_DISABLED | RADIOLIB_AX25_CONTROL_UNNUMBERED_FRAME;
// build the frame
AX25Frame frame(destCallsign, destSSID, _srcCallsign, _srcSSID, controlField, RADIOLIB_AX25_PID_NO_LAYER_3, (uint8_t*)str, strlen(str));
// send Unnumbered Information frame
return(sendFrame(&frame));
}
int16_t AX25Client::sendFrame(AX25Frame* frame) {
// check destination callsign length (6 characters max)
if(strlen(frame->destCallsign) > RADIOLIB_AX25_MAX_CALLSIGN_LEN) {
return(RADIOLIB_ERR_INVALID_CALLSIGN);
}
// check repeater configuration
#if !defined(RADIOLIB_STATIC_ONLY)
if(!(((frame->repeaterCallsigns == NULL) && (frame->repeaterSSIDs == NULL) && (frame->numRepeaters == 0)) ||
((frame->repeaterCallsigns != NULL) && (frame->repeaterSSIDs != NULL) && (frame->numRepeaters != 0)))) {
return(RADIOLIB_ERR_INVALID_NUM_REPEATERS);
}
for(uint16_t i = 0; i < frame->numRepeaters; i++) {
if(strlen(frame->repeaterCallsigns[i]) > RADIOLIB_AX25_MAX_CALLSIGN_LEN) {
return(RADIOLIB_ERR_INVALID_REPEATER_CALLSIGN);
}
}
#endif
// calculate frame length without FCS (destination address, source address, repeater addresses, control, PID, info)
size_t frameBuffLen = ((2 + frame->numRepeaters)*(RADIOLIB_AX25_MAX_CALLSIGN_LEN + 1)) + 1 + 1 + frame->infoLen;
// create frame buffer without preamble, start or stop flags
#if !defined(RADIOLIB_STATIC_ONLY)
uint8_t* frameBuff = new uint8_t[frameBuffLen + 2];
#else
uint8_t frameBuff[RADIOLIB_STATIC_ARRAY_SIZE];
#endif
uint8_t* frameBuffPtr = frameBuff;
// set destination callsign - all address field bytes are shifted by one bit to make room for HDLC address extension bit
memset(frameBuffPtr, ' ' << 1, RADIOLIB_AX25_MAX_CALLSIGN_LEN);
for(size_t i = 0; i < strlen(frame->destCallsign); i++) {
*(frameBuffPtr + i) = frame->destCallsign[i] << 1;
}
frameBuffPtr += RADIOLIB_AX25_MAX_CALLSIGN_LEN;
// set destination SSID
*(frameBuffPtr++) = RADIOLIB_AX25_SSID_RESPONSE_DEST | RADIOLIB_AX25_SSID_RESERVED_BITS | (frame->destSSID & 0x0F) << 1 | RADIOLIB_AX25_SSID_HDLC_EXTENSION_CONTINUE;
// set source callsign - all address field bytes are shifted by one bit to make room for HDLC address extension bit
memset(frameBuffPtr, ' ' << 1, RADIOLIB_AX25_MAX_CALLSIGN_LEN);
for(size_t i = 0; i < strlen(frame->srcCallsign); i++) {
*(frameBuffPtr + i) = frame->srcCallsign[i] << 1;
}
frameBuffPtr += RADIOLIB_AX25_MAX_CALLSIGN_LEN;
// set source SSID
*(frameBuffPtr++) = RADIOLIB_AX25_SSID_COMMAND_SOURCE | RADIOLIB_AX25_SSID_RESERVED_BITS | (frame->srcSSID & 0x0F) << 1 | RADIOLIB_AX25_SSID_HDLC_EXTENSION_CONTINUE;
// set repeater callsigns
for(uint16_t i = 0; i < frame->numRepeaters; i++) {
memset(frameBuffPtr, ' ' << 1, RADIOLIB_AX25_MAX_CALLSIGN_LEN);
for(size_t j = 0; j < strlen(frame->repeaterCallsigns[i]); j++) {
*(frameBuffPtr + j) = frame->repeaterCallsigns[i][j] << 1;
}
frameBuffPtr += RADIOLIB_AX25_MAX_CALLSIGN_LEN;
*(frameBuffPtr++) = RADIOLIB_AX25_SSID_HAS_NOT_BEEN_REPEATED | RADIOLIB_AX25_SSID_RESERVED_BITS | (frame->repeaterSSIDs[i] & 0x0F) << 1 | RADIOLIB_AX25_SSID_HDLC_EXTENSION_CONTINUE;
}
// set HDLC extension end bit
*(frameBuffPtr - 1) |= RADIOLIB_AX25_SSID_HDLC_EXTENSION_END;
// set sequence numbers of the frames that have it
uint8_t controlField = frame->control;
if((frame->control & 0x01) == 0) {
// information frame, set both sequence numbers
controlField |= frame->rcvSeqNumber << 5;
controlField |= frame->sendSeqNumber << 1;
} else if((frame->control & 0x02) == 0) {
// supervisory frame, set only receive sequence number
controlField |= frame->rcvSeqNumber << 5;
}
// set control field
*(frameBuffPtr++) = controlField;
// set PID field of the frames that have it
if(frame->protocolID != 0x00) {
*(frameBuffPtr++) = frame->protocolID;
}
// set info field of the frames that have it
if(frame->infoLen > 0) {
memcpy(frameBuffPtr, frame->info, frame->infoLen);
frameBuffPtr += frame->infoLen;
}
// flip bit order
for(size_t i = 0; i < frameBuffLen; i++) {
frameBuff[i] = Module::flipBits(frameBuff[i]);
}
// calculate FCS
uint16_t fcs = getFrameCheckSequence(frameBuff, frameBuffLen);
*(frameBuffPtr++) = (uint8_t)((fcs >> 8) & 0xFF);
*(frameBuffPtr++) = (uint8_t)(fcs & 0xFF);
// prepare buffer for the final frame (stuffed, with added preamble + flags and NRZI-encoded)
#if !defined(RADIOLIB_STATIC_ONLY)
// worst-case scenario: sequence of 1s, will have 120% of the original length, stuffed frame also includes both flags
uint8_t* stuffedFrameBuff = new uint8_t[_preambleLen + 1 + (6*frameBuffLen)/5 + 2];
#else
uint8_t stuffedFrameBuff[RADIOLIB_STATIC_ARRAY_SIZE];
#endif
// initialize buffer to all zeros
memset(stuffedFrameBuff, 0x00, _preambleLen + 1 + (6*frameBuffLen)/5 + 2);
// stuff bits (skip preamble and both flags)
uint16_t stuffedFrameBuffLenBits = 8*(_preambleLen + 1);
uint8_t count = 0;
for(size_t i = 0; i < frameBuffLen + 2; i++) {
for(int8_t shift = 7; shift >= 0; shift--) {
uint16_t stuffedFrameBuffPos = stuffedFrameBuffLenBits + 7 - 2*(stuffedFrameBuffLenBits%8);
if((frameBuff[i] >> shift) & 0x01) {
// copy 1 and increment counter
SET_BIT_IN_ARRAY(stuffedFrameBuff, stuffedFrameBuffPos);
stuffedFrameBuffLenBits++;
count++;
// check 5 consecutive 1s
if(count == 5) {
// get the new position in stuffed frame
stuffedFrameBuffPos = stuffedFrameBuffLenBits + 7 - 2*(stuffedFrameBuffLenBits%8);
// insert 0 and reset counter
CLEAR_BIT_IN_ARRAY(stuffedFrameBuff, stuffedFrameBuffPos);
stuffedFrameBuffLenBits++;
count = 0;
}
} else {
// copy 0 and reset counter
CLEAR_BIT_IN_ARRAY(stuffedFrameBuff, stuffedFrameBuffPos);
stuffedFrameBuffLenBits++;
count = 0;
}
}
}
// deallocate memory
#if !defined(RADIOLIB_STATIC_ONLY)
delete[] frameBuff;
#endif
// set preamble bytes and start flag field
for(uint16_t i = 0; i < _preambleLen + 1; i++) {
stuffedFrameBuff[i] = RADIOLIB_AX25_FLAG;
}
// get stuffed frame length in bytes
size_t stuffedFrameBuffLen = stuffedFrameBuffLenBits/8 + 1;
uint8_t trailingLen = stuffedFrameBuffLenBits % 8;
// set end flag field (may be split into two bytes due to misalignment caused by extra stuffing bits)
if(trailingLen != 0) {
stuffedFrameBuffLen++;
stuffedFrameBuff[stuffedFrameBuffLen - 2] |= RADIOLIB_AX25_FLAG >> trailingLen;
stuffedFrameBuff[stuffedFrameBuffLen - 1] = RADIOLIB_AX25_FLAG << (8 - trailingLen);
} else {
stuffedFrameBuff[stuffedFrameBuffLen - 1] = RADIOLIB_AX25_FLAG;
}
// convert to NRZI
for(size_t i = _preambleLen + 1; i < stuffedFrameBuffLen*8; i++) {
size_t currBitPos = i + 7 - 2*(i%8);
size_t prevBitPos = (i - 1) + 7 - 2*((i - 1)%8);
if(TEST_BIT_IN_ARRAY(stuffedFrameBuff, currBitPos)) {
// bit is 1, no change, copy previous bit
if(TEST_BIT_IN_ARRAY(stuffedFrameBuff, prevBitPos)) {
SET_BIT_IN_ARRAY(stuffedFrameBuff, currBitPos);
} else {
CLEAR_BIT_IN_ARRAY(stuffedFrameBuff, currBitPos);
}
} else {
// bit is 0, transition, copy inversion of the previous bit
if(TEST_BIT_IN_ARRAY(stuffedFrameBuff, prevBitPos)) {
CLEAR_BIT_IN_ARRAY(stuffedFrameBuff, currBitPos);
} else {
SET_BIT_IN_ARRAY(stuffedFrameBuff, currBitPos);
}
}
}
// transmit
int16_t state = RADIOLIB_ERR_NONE;
#if !defined(RADIOLIB_EXCLUDE_AFSK)
if(_audio != nullptr) {
Module* mod = _phy->getMod();
_phy->transmitDirect();
// iterate over all bytes in the buffer
for(uint32_t i = 0; i < stuffedFrameBuffLen; i++) {
// check each bit
for(uint16_t mask = 0x80; mask >= 0x01; mask >>= 1) {
uint32_t start = mod->micros();
if(stuffedFrameBuff[i] & mask) {
_audio->tone(_afskMark, false);
} else {
_audio->tone(_afskSpace, false);
}
while(mod->micros() - start < RADIOLIB_AX25_AFSK_TONE_DURATION) {
mod->yield();
}
}
}
_audio->noTone();
} else {
#endif
state = _phy->transmit(stuffedFrameBuff, stuffedFrameBuffLen);
#if !defined(RADIOLIB_EXCLUDE_AFSK)
}
#endif
// deallocate memory
#if !defined(RADIOLIB_STATIC_ONLY)
delete[] stuffedFrameBuff;
#endif
return(state);
}
void AX25Client::getCallsign(char* buff) {
strncpy(buff, _srcCallsign, RADIOLIB_AX25_MAX_CALLSIGN_LEN);
}
uint8_t AX25Client::getSSID() {
return(_srcSSID);
}
/*
CCITT CRC implementation based on https://github.com/kicksat/ax25
Licensed under Creative Commons Attribution-ShareAlike 4.0 International
https://creativecommons.org/licenses/by-sa/4.0/
*/
uint16_t AX25Client::getFrameCheckSequence(uint8_t* buff, size_t len) {
uint8_t outBit;
uint16_t mask;
uint16_t shiftReg = CRC_CCITT_INIT;
for(size_t i = 0; i < len; i++) {
for(uint8_t b = 0x80; b > 0x00; b /= 2) {
outBit = (shiftReg & 0x01) ? 0x01 : 0x00;
shiftReg >>= 1;
mask = XOR((buff[i] & b), outBit) ? CRC_CCITT_POLY_REVERSED : 0x0000;
shiftReg ^= mask;
}
}
return(Module::flipBits16(~shiftReg));
}
#endif
+369
View File
@@ -0,0 +1,369 @@
#if !defined(_RADIOLIB_RADIOLIB_AX25_H)
#define _RADIOLIB_RADIOLIB_AX25_H
#include "../../TypeDef.h"
#if !defined(RADIOLIB_EXCLUDE_AX25)
#include "../PhysicalLayer/PhysicalLayer.h"
#include "../AFSK/AFSK.h"
// macros to access bits in byte array, from http://www.mathcs.emory.edu/~cheung/Courses/255/Syllabus/1-C-intro/bit-array.html
#define SET_BIT_IN_ARRAY(A, k) ( A[(k/8)] |= (1 << (k%8)) )
#define CLEAR_BIT_IN_ARRAY(A, k) ( A[(k/8)] &= ~(1 << (k%8)) )
#define TEST_BIT_IN_ARRAY(A, k) ( A[(k/8)] & (1 << (k%8)) )
#define GET_BIT_IN_ARRAY(A, k) ( (A[(k/8)] & (1 << (k%8))) ? 1 : 0 )
// CRC-CCITT calculation macros
#define XOR(A, B) ( ((A) || (B)) && !((A) && (B)) )
#define CRC_CCITT_POLY 0x1021 // generator polynomial
#define CRC_CCITT_POLY_REVERSED 0x8408 // CRC_CCITT_POLY in reversed bit order
#define CRC_CCITT_INIT 0xFFFF // initial value
// maximum callsign length in bytes
#define RADIOLIB_AX25_MAX_CALLSIGN_LEN 6
// flag field MSB LSB DESCRIPTION
#define RADIOLIB_AX25_FLAG 0b01111110 // 7 0 AX.25 frame start/end flag
// address field
#define RADIOLIB_AX25_SSID_COMMAND_DEST 0b10000000 // 7 7 frame type: command (set in destination SSID)
#define RADIOLIB_AX25_SSID_COMMAND_SOURCE 0b00000000 // 7 7 command (set in source SSID)
#define RADIOLIB_AX25_SSID_RESPONSE_DEST 0b00000000 // 7 7 response (set in destination SSID)
#define RADIOLIB_AX25_SSID_RESPONSE_SOURCE 0b10000000 // 7 7 response (set in source SSID)
#define RADIOLIB_AX25_SSID_HAS_NOT_BEEN_REPEATED 0b00000000 // 7 7 not repeated yet (set in repeater SSID)
#define RADIOLIB_AX25_SSID_HAS_BEEN_REPEATED 0b10000000 // 7 7 repeated (set in repeater SSID)
#define RADIOLIB_AX25_SSID_RESERVED_BITS 0b01100000 // 6 5 reserved bits in SSID
#define RADIOLIB_AX25_SSID_HDLC_EXTENSION_CONTINUE 0b00000000 // 0 0 HDLC extension bit: next octet contains more address information
#define RADIOLIB_AX25_SSID_HDLC_EXTENSION_END 0b00000001 // 0 0 address field end
// control field
#define RADIOLIB_AX25_CONTROL_U_SET_ASYNC_BAL_MODE 0b01101100 // 7 2 U frame type: set asynchronous balanced mode (connect request)
#define RADIOLIB_AX25_CONTROL_U_SET_ASYNC_BAL_MODE_EXT 0b00101100 // 7 2 set asynchronous balanced mode extended (connect request with module 128)
#define RADIOLIB_AX25_CONTROL_U_DISCONNECT 0b01000000 // 7 2 disconnect request
#define RADIOLIB_AX25_CONTROL_U_DISCONNECT_MODE 0b00001100 // 7 2 disconnect mode (system busy or disconnected)
#define RADIOLIB_AX25_CONTROL_U_UNNUMBERED_ACK 0b01100000 // 7 2 unnumbered acknowledge
#define RADIOLIB_AX25_CONTROL_U_FRAME_REJECT 0b10000100 // 7 2 frame reject
#define RADIOLIB_AX25_CONTROL_U_UNNUMBERED_INFORMATION 0b00000000 // 7 2 unnumbered information
#define RADIOLIB_AX25_CONTROL_U_EXHANGE_IDENTIFICATION 0b10101100 // 7 2 exchange ID
#define RADIOLIB_AX25_CONTROL_U_TEST 0b11100000 // 7 2 test
#define RADIOLIB_AX25_CONTROL_POLL_FINAL_ENABLED 0b00010000 // 4 4 control field poll/final bit: enabled
#define RADIOLIB_AX25_CONTROL_POLL_FINAL_DISABLED 0b00000000 // 4 4 disabled
#define RADIOLIB_AX25_CONTROL_S_RECEIVE_READY 0b00000000 // 3 2 S frame type: receive ready (system ready to receive)
#define RADIOLIB_AX25_CONTROL_S_RECEIVE_NOT_READY 0b00000100 // 3 2 receive not ready (TNC buffer full)
#define RADIOLIB_AX25_CONTROL_S_REJECT 0b00001000 // 3 2 reject (out of sequence or duplicate)
#define RADIOLIB_AX25_CONTROL_S_SELECTIVE_REJECT 0b00001100 // 3 2 selective reject (single frame repeat request)
#define RADIOLIB_AX25_CONTROL_INFORMATION_FRAME 0b00000000 // 0 0 frame type: information (I frame)
#define RADIOLIB_AX25_CONTROL_SUPERVISORY_FRAME 0b00000001 // 1 0 supervisory (S frame)
#define RADIOLIB_AX25_CONTROL_UNNUMBERED_FRAME 0b00000011 // 1 0 unnumbered (U frame)
// protocol identifier field
#define RADIOLIB_AX25_PID_ISO_8208 0x01
#define RADIOLIB_AX25_PID_TCP_IP_COMPRESSED 0x06
#define RADIOLIB_AX25_PID_TCP_IP_UNCOMPRESSED 0x07
#define RADIOLIB_AX25_PID_SEGMENTATION_FRAGMENT 0x08
#define RADIOLIB_AX25_PID_TEXNET_DATAGRAM_PROTOCOL 0xC3
#define RADIOLIB_AX25_PID_LINK_QUALITY_PROTOCOL 0xC4
#define RADIOLIB_AX25_PID_APPLETALK 0xCA
#define RADIOLIB_AX25_PID_APPLETALK_ARP 0xCB
#define RADIOLIB_AX25_PID_ARPA_INTERNET_PROTOCOL 0xCC
#define RADIOLIB_AX25_PID_ARPA_ADDRESS_RESOLUTION 0xCD
#define RADIOLIB_AX25_PID_FLEXNET 0xCE
#define RADIOLIB_AX25_PID_NET_ROM 0xCF
#define RADIOLIB_AX25_PID_NO_LAYER_3 0xF0
#define RADIOLIB_AX25_PID_ESCAPE_CHARACTER 0xFF
// AFSK tones in Hz
#define RADIOLIB_AX25_AFSK_MARK 1200
#define RADIOLIB_AX25_AFSK_SPACE 2200
// tone duration in us (for 1200 baud AFSK)
#define RADIOLIB_AX25_AFSK_TONE_DURATION 833
/*!
\class AX25Frame
\brief Abstraction of AX.25 frame format.
*/
class AX25Frame {
public:
/*!
\brief Callsign of the destination station.
*/
char destCallsign[RADIOLIB_AX25_MAX_CALLSIGN_LEN + 1];
/*!
\brief SSID of the destination station.
*/
uint8_t destSSID;
/*!
\brief Callsign of the source station.
*/
char srcCallsign[RADIOLIB_AX25_MAX_CALLSIGN_LEN + 1];
/*!
\brief SSID of the source station.
*/
uint8_t srcSSID;
/*!
\brief Number of repeaters to be used.
*/
uint8_t numRepeaters;
/*!
\brief The control field.
*/
uint8_t control;
/*!
\brief The protocol identifier (PID) field.
*/
uint8_t protocolID;
/*!
\brief Number of bytes in the information field.
*/
uint16_t infoLen;
/*!
\brief Receive sequence number.
*/
uint8_t rcvSeqNumber;
/*!
\brief Send sequence number.
*/
uint16_t sendSeqNumber;
#if !defined(RADIOLIB_STATIC_ONLY)
/*!
\brief The info field.
*/
uint8_t* info;
/*!
\brief Array of repeater callsigns.
*/
char** repeaterCallsigns;
/*!
\brief Array of repeater SSIDs.
*/
uint8_t* repeaterSSIDs;
#else
/*!
\brief The info field.
*/
uint8_t info[RADIOLIB_STATIC_ARRAY_SIZE];
/*!
\brief Array of repeater callsigns.
*/
char repeaterCallsigns[8][RADIOLIB_AX25_MAX_CALLSIGN_LEN + 1];
/*!
\brief Array of repeater SSIDs.
*/
uint8_t repeaterSSIDs[8];
#endif
/*!
\brief Overloaded constructor, for frames without info field.
\param destCallsign Callsign of the destination station.
\param destSSID SSID of the destination station.
\param srcCallsign Callsign of the source station.
\param srcSSID SSID of the source station.
\param control The control field.
*/
AX25Frame(const char* destCallsign, uint8_t destSSID, const char* srcCallsign, uint8_t srcSSID, uint8_t control);
/*!
\brief Overloaded constructor, for frames with C-string info field.
\param destCallsign Callsign of the destination station.
\param destSSID SSID of the destination station.
\param srcCallsign Callsign of the source station.
\param srcSSID SSID of the source station.
\param control The control field.
\param protocolID The protocol identifier (PID) field. Set to zero if the frame doesn't have this field.
\param info Information field, in the form of null-terminated C-string.
*/
AX25Frame(const char* destCallsign, uint8_t destSSID, const char* srcCallsign, uint8_t srcSSID, uint8_t control, uint8_t protocolID, const char* info);
/*!
\brief Default constructor.
\param destCallsign Callsign of the destination station.
\param destSSID SSID of the destination station.
\param srcCallsign Callsign of the source station.
\param srcSSID SSID of the source station.
\param control The control field.
\param protocolID The protocol identifier (PID) field. Set to zero if the frame doesn't have this field.
\param info Information field, in the form of arbitrary binary buffer.
\param infoLen Number of bytes in the information field.
*/
AX25Frame(const char* destCallsign, uint8_t destSSID, const char* srcCallsign, uint8_t srcSSID, uint8_t control, uint8_t protocolID, uint8_t* info, uint16_t infoLen);
/*!
\brief Copy constructor.
\param frame AX25Frame instance to copy.
*/
AX25Frame(const AX25Frame& frame);
/*!
\brief Default destructor.
*/
~AX25Frame();
/*!
\brief Overload for assignment operator.
\param frame rvalue AX25Frame.
*/
AX25Frame& operator=(const AX25Frame& frame);
/*!
\brief Method to set the repeater callsigns and SSIDs.
\param repeaterCallsigns Array of repeater callsigns in the form of null-terminated C-strings.
\param repeaterSSIDs Array of repeater SSIDs.
\param numRepeaters Number of repeaters, maximum is 8.
\returns \ref status_codes
*/
int16_t setRepeaters(char** repeaterCallsigns, uint8_t* repeaterSSIDs, uint8_t numRepeaters);
/*!
\brief Method to set receive sequence number.
\param seqNumber Sequence number to set, 0 to 7.
*/
void setRecvSequence(uint8_t seqNumber);
/*!
\brief Method to set send sequence number.
\param seqNumber Sequence number to set, 0 to 7.
*/
void setSendSequence(uint8_t seqNumber);
};
/*!
\class AX25Client
\brief Client for AX25 communication.
*/
class AX25Client {
public:
/*!
\brief Constructor for 2-FSK mode.
\param phy Pointer to the wireless module providing PhysicalLayer communication.
*/
explicit AX25Client(PhysicalLayer* phy);
#if !defined(RADIOLIB_EXCLUDE_AFSK)
/*!
\brief Constructor for AFSK mode.
\param audio Pointer to the AFSK instance providing audio.
*/
explicit AX25Client(AFSKClient* audio);
/*!
\brief Set AFSK tone correction offset. On some platforms, this is required to get the audio produced by the setup to match the expected 1200/2200 Hz tones.
\param mark Positive or negative correction offset for mark audio frequency in Hz.
\param space Positive or negative correction offset for space audio frequency in Hz.
\returns \ref status_codes
*/
int16_t setCorrection(int16_t mark, int16_t space);
#endif
// basic methods
/*!
\brief Initialization method.
\param srcCallsign Callsign of the source station.
\param srcSSID 4-bit SSID of the source station (in case there are more stations with the same callsign). Defaults to 0.
\param preambleLen Number of "preamble" bytes (RADIOLIB_AX25_FLAG) sent ahead of the actual AX.25 frame. Does not include the first RADIOLIB_AX25_FLAG byte, which is considered part of the frame. Defaults to 8.
\returns \ref status_codes
*/
int16_t begin(const char* srcCallsign, uint8_t srcSSID = 0x00, uint8_t preambleLen = 8);
/*!
\brief Transmit unnumbered information (UI) frame.
\param str Data to be sent.
\param destCallsign Callsign of the destination station.
\param destSSID 4-bit SSID of the destination station (in case there are more stations with the same callsign). Defaults to 0.
\returns \ref status_codes
*/
int16_t transmit(const char* str, const char* destCallsign, uint8_t destSSID = 0x00);
/*!
\brief Transmit arbitrary AX.25 frame.
\param frame Frame to be sent.
\returns \ref status_codes
*/
int16_t sendFrame(AX25Frame* frame);
#if !defined(RADIOLIB_GODMODE)
private:
#endif
friend class APRSClient;
PhysicalLayer* _phy;
#if !defined(RADIOLIB_EXCLUDE_AFSK)
AFSKClient* _audio;
uint32_t _afskMark;
uint32_t _afskSpace;
#endif
char _srcCallsign[RADIOLIB_AX25_MAX_CALLSIGN_LEN + 1] = {0, 0, 0, 0, 0, 0, 0};
uint8_t _srcSSID = 0;
uint16_t _preambleLen = 0;
static uint16_t getFrameCheckSequence(uint8_t* buff, size_t len);
void getCallsign(char* buff);
uint8_t getSSID();
};
#endif
#endif
+116
View File
@@ -0,0 +1,116 @@
#include "FSK4.h"
#if !defined(RADIOLIB_EXCLUDE_FSK4)
FSK4Client::FSK4Client(PhysicalLayer* phy) {
_phy = phy;
#if !defined(RADIOLIB_EXCLUDE_AFSK)
_audio = nullptr;
#endif
}
#if !defined(RADIOLIB_EXCLUDE_AFSK)
FSK4Client::FSK4Client(AFSKClient* audio) {
_phy = audio->_phy;
_audio = audio;
}
#endif
int16_t FSK4Client::begin(float base, uint32_t shift, uint16_t rate) {
// save configuration
_baseHz = base;
_shiftHz = shift;
// calculate duration of 1 bit
_bitDuration = (uint32_t)1000000/rate;
// calculate module carrier frequency resolution
uint32_t step = round(_phy->getFreqStep());
// check minimum shift value
if(shift < step / 2) {
return(RADIOLIB_ERR_INVALID_RTTY_SHIFT);
}
// round shift to multiples of frequency step size
if(shift % step < (step / 2)) {
_shift = shift / step;
} else {
_shift = (shift / step) + 1;
}
// Write resultant tones into arrays for quick lookup when modulating.
_tones[0] = 0;
_tones[1] = _shift;
_tones[2] = _shift*2;
_tones[3] = _shift*3;
_tonesHz[0] = 0;
_tonesHz[1] = _shiftHz;
_tonesHz[2] = _shiftHz*2;
_tonesHz[3] = _shiftHz*3;
// calculate 24-bit frequency
_base = (base * 1000000.0) / _phy->getFreqStep();
// configure for direct mode
return(_phy->startDirect());
}
void FSK4Client::idle() {
// Idle at Tone 0.
tone(0);
}
size_t FSK4Client::write(uint8_t* buff, size_t len) {
size_t n = 0;
for(size_t i = 0; i < len; i++) {
n += FSK4Client::write(buff[i]);
}
FSK4Client::standby();
return(n);
}
size_t FSK4Client::write(uint8_t b) {
// send symbols MSB first
for(uint8_t i = 0; i < 4; i++) {
// Extract 4FSK symbol (2 bits)
uint8_t symbol = (b & 0xC0) >> 6;
// Modulate
FSK4Client::tone(symbol);
// Shift to next symbol
b = b << 2;
}
return(1);
}
void FSK4Client::tone(uint8_t i) {
Module* mod = _phy->getMod();
uint32_t start = mod->micros();
transmitDirect(_base + _tones[i], _baseHz + _tonesHz[i]);
while(mod->micros() - start < _bitDuration) {
mod->yield();
}
}
int16_t FSK4Client::transmitDirect(uint32_t freq, uint32_t freqHz) {
#if !defined(RADIOLIB_EXCLUDE_AFSK)
if(_audio != nullptr) {
return(_audio->tone(freqHz));
}
#endif
return(_phy->transmitDirect(freq));
}
int16_t FSK4Client::standby() {
#if !defined(RADIOLIB_EXCLUDE_AFSK)
if(_audio != nullptr) {
return(_audio->noTone());
}
#endif
return(_phy->standby());
}
#endif
+81
View File
@@ -0,0 +1,81 @@
#if !defined(_RADIOLIB_FSK4_H)
#define _RADIOLIB_FSK4_H
#include "../../TypeDef.h"
#if !defined(RADIOLIB_EXCLUDE_FSK4)
#include "../PhysicalLayer/PhysicalLayer.h"
#include "../AFSK/AFSK.h"
/*!
\class FSK4Client
\brief Client for FSK-4 communication. The public interface is the same as Arduino Serial.
*/
class FSK4Client {
public:
/*!
\brief Constructor for FSK-4 mode.
\param phy Pointer to the wireless module providing PhysicalLayer communication.
*/
explicit FSK4Client(PhysicalLayer* phy);
#if !defined(RADIOLIB_EXCLUDE_AFSK)
/*!
\brief Constructor for AFSK mode.
\param audio Pointer to the AFSK instance providing audio.
*/
explicit FSK4Client(AFSKClient* audio);
#endif
// basic methods
/*!
\brief Initialization method.
\param base Base (space) frequency to be used in MHz (in FSK-4 mode), or the space tone frequency in Hz (in AFSK mode)
\param shift Frequency shift between each tone in Hz.
\param rate Baud rate to be used during transmission.
\returns \ref status_codes
*/
int16_t begin(float base, uint32_t shift, uint16_t rate);
/*!
\brief Send out idle condition (RF tone at mark frequency).
*/
void idle();
size_t write(uint8_t* buff, size_t len);
size_t write(uint8_t b);
#if !defined(RADIOLIB_GODMODE)
private:
#endif
PhysicalLayer* _phy;
#if !defined(RADIOLIB_EXCLUDE_AFSK)
AFSKClient* _audio;
#endif
uint32_t _base = 0, _baseHz = 0;
uint32_t _shift = 0, _shiftHz = 0;
uint32_t _bitDuration = 0;
uint32_t _tones[4];
uint32_t _tonesHz[4];
void tone(uint8_t i);
int16_t transmitDirect(uint32_t freq = 0, uint32_t freqHz = 0);
int16_t standby();
};
#endif
#endif
@@ -0,0 +1,308 @@
#include "Hellschreiber.h"
#if !defined(RADIOLIB_EXCLUDE_HELLSCHREIBER)
HellClient::HellClient(PhysicalLayer* phy) {
_phy = phy;
#if !defined(RADIOLIB_EXCLUDE_AFSK)
_audio = nullptr;
#endif
}
#if !defined(RADIOLIB_EXCLUDE_AFSK)
HellClient::HellClient(AFSKClient* audio) {
_phy = audio->_phy;
_audio = audio;
}
#endif
int16_t HellClient::begin(float base, float rate) {
// calculate 24-bit frequency
_baseHz = base;
_base = (base * 1000000.0) / _phy->getFreqStep();
// calculate "pixel" duration
_pixelDuration = 1000000.0/rate;
// configure for direct mode
return(_phy->startDirect());
}
size_t HellClient::printGlyph(uint8_t* buff) {
// print the character
Module* mod = _phy->getMod();
for(uint8_t mask = 0x40; mask >= 0x01; mask >>= 1) {
for(int8_t i = RADIOLIB_HELL_FONT_HEIGHT - 1; i >= 0; i--) {
uint32_t start = mod->micros();
if(buff[i] & mask) {
transmitDirect(_base, _baseHz);
} else {
standby();
}
while(mod->micros() - start < _pixelDuration);
}
}
// make sure transmitter is off
standby();
return(1);
}
void HellClient::setInversion(bool invert) {
_inv = invert;
}
size_t HellClient::write(const char* str) {
if(str == NULL) {
return(0);
}
return(HellClient::write((uint8_t *)str, strlen(str)));
}
size_t HellClient::write(uint8_t* buff, size_t len) {
size_t n = 0;
for(size_t i = 0; i < len; i++) {
n += HellClient::write(buff[i]);
}
return(n);
}
size_t HellClient::write(uint8_t b) {
// convert to position in font buffer
uint8_t pos = b;
if((pos >= ' ') && (pos <= '_')) {
pos -= ' ';
} else if((pos >= 'a') && (pos <= 'z')) {
pos -= (2*' ');
} else {
return(0);
}
// fetch character from flash
uint8_t buff[RADIOLIB_HELL_FONT_WIDTH];
buff[0] = 0x00;
for(uint8_t i = 0; i < RADIOLIB_HELL_FONT_WIDTH - 2; i++) {
buff[i + 1] = RADIOLIB_NONVOLATILE_READ_BYTE(&HellFont[pos][i]);
}
buff[RADIOLIB_HELL_FONT_WIDTH - 1] = 0x00;
// print the character
return(printGlyph(buff));
}
size_t HellClient::print(__FlashStringHelper* fstr) {
PGM_P p = reinterpret_cast<PGM_P>(fstr);
size_t n = 0;
while(true) {
char c = RADIOLIB_NONVOLATILE_READ_BYTE(p++);
if(c == '\0') {
break;
}
n += HellClient::write(c);
}
return n;
}
size_t HellClient::print(const String& str) {
return(HellClient::write((uint8_t*)str.c_str(), str.length()));
}
size_t HellClient::print(const char* str) {
return(HellClient::write((uint8_t*)str, strlen(str)));
}
size_t HellClient::print(char c) {
return(HellClient::write(c));
}
size_t HellClient::print(unsigned char b, int base) {
return(HellClient::print((unsigned long)b, base));
}
size_t HellClient::print(int n, int base) {
return(HellClient::print((long)n, base));
}
size_t HellClient::print(unsigned int n, int base) {
return(HellClient::print((unsigned long)n, base));
}
size_t HellClient::print(long n, int base) {
if(base == 0) {
return(HellClient::write(n));
} else if(base == DEC) {
if (n < 0) {
int t = HellClient::print('-');
n = -n;
return(HellClient::printNumber(n, DEC) + t);
}
return(HellClient::printNumber(n, DEC));
} else {
return(HellClient::printNumber(n, base));
}
}
size_t HellClient::print(unsigned long n, int base) {
if(base == 0) {
return(HellClient::write(n));
} else {
return(HellClient::printNumber(n, base));
}
}
size_t HellClient::print(double n, int digits) {
return(HellClient::printFloat(n, digits));
}
size_t HellClient::println(void) {
// Hellschreiber has no concept of "line ending", print one space instead
return(HellClient::print(' '));
}
size_t HellClient::println(__FlashStringHelper* fstr) {
size_t n = HellClient::print(fstr);
n += HellClient::println();
return(n);
}
size_t HellClient::println(const String& str) {
size_t n = HellClient::print(str);
n += HellClient::println();
return(n);
}
size_t HellClient::println(const char* str) {
size_t n = HellClient::print(str);
n += HellClient::println();
return(n);
}
size_t HellClient::println(char c) {
size_t n = HellClient::print(c);
n += HellClient::println();
return(n);
}
size_t HellClient::println(unsigned char b, int base) {
size_t n = HellClient::print(b, base);
n += HellClient::println();
return(n);
}
size_t HellClient::println(int num, int base) {
size_t n = HellClient::print(num, base);
n += HellClient::println();
return(n);
}
size_t HellClient::println(unsigned int num, int base) {
size_t n = HellClient::print(num, base);
n += HellClient::println();
return(n);
}
size_t HellClient::println(long num, int base) {
size_t n = HellClient::print(num, base);
n += HellClient::println();
return(n);
}
size_t HellClient::println(unsigned long num, int base) {
size_t n = HellClient::print(num, base);
n += HellClient::println();
return(n);
}
size_t HellClient::println(double d, int digits) {
size_t n = HellClient::print(d, digits);
n += HellClient::println();
return(n);
}
size_t HellClient::printNumber(unsigned long n, uint8_t base) {
char buf[8 * sizeof(long) + 1];
char *str = &buf[sizeof(buf) - 1];
*str = '\0';
if(base < 2) {
base = 10;
}
do {
char c = n % base;
n /= base;
*--str = c < 10 ? c + '0' : c + 'A' - 10;
} while(n);
return(HellClient::write(str));
}
size_t HellClient::printFloat(double number, uint8_t digits) {
size_t n = 0;
char code[] = {0x00, 0x00, 0x00, 0x00};
if (isnan(number)) strcpy(code, "nan");
if (isinf(number)) strcpy(code, "inf");
if (number > 4294967040.0) strcpy(code, "ovf"); // constant determined empirically
if (number <-4294967040.0) strcpy(code, "ovf"); // constant determined empirically
if(code[0] != 0x00) {
return(HellClient::write(code));
}
// Handle negative numbers
if (number < 0.0) {
n += HellClient::print('-');
number = -number;
}
// Round correctly so that print(1.999, 2) prints as "2.00"
double rounding = 0.5;
for(uint8_t i = 0; i < digits; ++i) {
rounding /= 10.0;
}
number += rounding;
// Extract the integer part of the number and print it
unsigned long int_part = (unsigned long)number;
double remainder = number - (double)int_part;
n += HellClient::print(int_part);
// Print the decimal point, but only if there are digits beyond
if(digits > 0) {
n += HellClient::print('.');
}
// Extract digits from the remainder one at a time
while(digits-- > 0) {
remainder *= 10.0;
unsigned int toPrint = (unsigned int)(remainder);
n += HellClient::print(toPrint);
remainder -= toPrint;
}
return n;
}
int16_t HellClient::transmitDirect(uint32_t freq, uint32_t freqHz) {
#if !defined(RADIOLIB_EXCLUDE_AFSK)
if(_audio != nullptr) {
return(_audio->tone(freqHz));
}
#endif
return(_phy->transmitDirect(freq));
}
int16_t HellClient::standby() {
#if !defined(RADIOLIB_EXCLUDE_AFSK)
if(_audio != nullptr) {
return(_audio->noTone(_inv));
}
#endif
return(_phy->standby());
}
#endif
@@ -0,0 +1,182 @@
#if !defined(_RADIOLIB_HELLSCHREIBER_H)
#define _RADIOLIB_HELLSCHREIBER_H
#include "../../TypeDef.h"
#if !defined(RADIOLIB_EXCLUDE_HELLSCHREIBER)
#include "../PhysicalLayer/PhysicalLayer.h"
#include "../AFSK/AFSK.h"
#define RADIOLIB_HELL_FONT_WIDTH 7
#define RADIOLIB_HELL_FONT_HEIGHT 7
// font definition: characters are stored in rows,
// least significant byte of each character is the first row
// Hellschreiber use 7x7 characters, but this simplified font uses only 5x5 - the extra bytes aren't stored
static const uint8_t HellFont[64][RADIOLIB_HELL_FONT_WIDTH - 2] RADIOLIB_NONVOLATILE = {
{ 0b0000000, 0b0000000, 0b0000000, 0b0000000, 0b0000000 }, // space
{ 0b0001000, 0b0001000, 0b0001000, 0b0000000, 0b0001000 }, // !
{ 0b0010100, 0b0010100, 0b0000000, 0b0000000, 0b0000000 }, // "
{ 0b0010100, 0b0111110, 0b0010100, 0b0111110, 0b0010100 }, // #
{ 0b0111110, 0b0101000, 0b0111110, 0b0001010, 0b0111110 }, // $
{ 0b0110010, 0b0110100, 0b0001000, 0b0010110, 0b0100110 }, // %
{ 0b0010000, 0b0101000, 0b0010000, 0b0101000, 0b0110100 }, // &
{ 0b0001000, 0b0001000, 0b0000000, 0b0000000, 0b0000000 }, // '
{ 0b0000100, 0b0001000, 0b0001000, 0b0001000, 0b0000100 }, // (
{ 0b0010000, 0b0001000, 0b0001000, 0b0001000, 0b0010000 }, // )
{ 0b0010100, 0b0001000, 0b0010100, 0b0000000, 0b0000000 }, // *
{ 0b0001000, 0b0001000, 0b0111110, 0b0001000, 0b0001000 }, // +
{ 0b0000000, 0b0000000, 0b0000000, 0b0001000, 0b0010000 }, // ,
{ 0b0000000, 0b0000000, 0b0111110, 0b0000000, 0b0000000 }, // -
{ 0b0000000, 0b0000000, 0b0000000, 0b0000000, 0b0001000 }, // .
{ 0b0000010, 0b0000100, 0b0001000, 0b0010000, 0b0100000 }, // /
{ 0b0011100, 0b0100110, 0b0101010, 0b0110010, 0b0011100 }, // 0
{ 0b0011000, 0b0001000, 0b0001000, 0b0001000, 0b0001000 }, // 1
{ 0b0011000, 0b0100100, 0b0001000, 0b0010000, 0b0111100 }, // 2
{ 0b0111100, 0b0000100, 0b0011100, 0b0000100, 0b0111100 }, // 3
{ 0b0100100, 0b0100100, 0b0111100, 0b0000100, 0b0000100 }, // 4
{ 0b0011100, 0b0100000, 0b0111100, 0b0000100, 0b0111100 }, // 5
{ 0b0111100, 0b0100000, 0b0111100, 0b0100100, 0b0111100 }, // 6
{ 0b0111100, 0b0000100, 0b0001000, 0b0010000, 0b0100000 }, // 7
{ 0b0111100, 0b0100100, 0b0011000, 0b0100100, 0b0111100 }, // 8
{ 0b0111100, 0b0100100, 0b0111100, 0b0000100, 0b0111100 }, // 9
{ 0b0000000, 0b0001000, 0b0000000, 0b0000000, 0b0001000 }, // :
{ 0b0000000, 0b0001000, 0b0000000, 0b0001000, 0b0001000 }, // ;
{ 0b0000100, 0b0001000, 0b0010000, 0b0001000, 0b0000100 }, // <
{ 0b0000000, 0b0111110, 0b0000000, 0b0111110, 0b0000000 }, // =
{ 0b0010000, 0b0001000, 0b0000100, 0b0001000, 0b0010000 }, // >
{ 0b0011100, 0b0000100, 0b0001000, 0b0000000, 0b0001000 }, // ?
{ 0b0011100, 0b0100010, 0b0101110, 0b0101010, 0b0001100 }, // @
{ 0b0111110, 0b0100010, 0b0111110, 0b0100010, 0b0100010 }, // A
{ 0b0111100, 0b0010010, 0b0011110, 0b0010010, 0b0111100 }, // B
{ 0b0011110, 0b0110000, 0b0100000, 0b0110000, 0b0011110 }, // C
{ 0b0111100, 0b0100010, 0b0100010, 0b0100010, 0b0111100 }, // D
{ 0b0111110, 0b0100000, 0b0111100, 0b0100000, 0b0111110 }, // E
{ 0b0111110, 0b0100000, 0b0111100, 0b0100000, 0b0100000 }, // F
{ 0b0111110, 0b0100000, 0b0101110, 0b0100010, 0b0111110 }, // G
{ 0b0100010, 0b0100010, 0b0111110, 0b0100010, 0b0100010 }, // H
{ 0b0011100, 0b0001000, 0b0001000, 0b0001000, 0b0011100 }, // I
{ 0b0111100, 0b0001000, 0b0001000, 0b0101000, 0b0111000 }, // J
{ 0b0100100, 0b0101000, 0b0110000, 0b0101000, 0b0100100 }, // K
{ 0b0100000, 0b0100000, 0b0100000, 0b0100000, 0b0111100 }, // L
{ 0b0100010, 0b0110110, 0b0101010, 0b0100010, 0b0100010 }, // M
{ 0b0100010, 0b0110010, 0b0101010, 0b0100110, 0b0100010 }, // N
{ 0b0011100, 0b0100010, 0b0100010, 0b0100010, 0b0011100 }, // O
{ 0b0111110, 0b0100010, 0b0111110, 0b0100000, 0b0100000 }, // P
{ 0b0111110, 0b0100010, 0b0100010, 0b0100110, 0b0111110 }, // Q
{ 0b0111110, 0b0100010, 0b0111110, 0b0100100, 0b0100010 }, // R
{ 0b0111110, 0b0100000, 0b0111110, 0b0000010, 0b0111110 }, // S
{ 0b0111110, 0b0001000, 0b0001000, 0b0001000, 0b0001000 }, // T
{ 0b0100010, 0b0100010, 0b0100010, 0b0100010, 0b0111110 }, // U
{ 0b0100010, 0b0100010, 0b0010100, 0b0010100, 0b0001000 }, // V
{ 0b0100010, 0b0100010, 0b0101010, 0b0110110, 0b0100010 }, // W
{ 0b0100010, 0b0010100, 0b0001000, 0b0010100, 0b0100010 }, // X
{ 0b0100010, 0b0010100, 0b0001000, 0b0001000, 0b0001000 }, // Y
{ 0b0111110, 0b0000100, 0b0001000, 0b0010000, 0b0111110 }, // Z
{ 0b0001100, 0b0001000, 0b0001000, 0b0001000, 0b0001100 }, // [
{ 0b0100000, 0b0010000, 0b0001000, 0b0000100, 0b0000010 }, // backslash
{ 0b0011000, 0b0001000, 0b0001000, 0b0001000, 0b0011000 }, // ]
{ 0b0001000, 0b0010100, 0b0000000, 0b0000000, 0b0000000 }, // ^
{ 0b0000000, 0b0000000, 0b0000000, 0b0000000, 0b0111110 } // _
};
/*!
\class HellClient
\brief Client for Hellschreiber transmissions.
*/
class HellClient {
public:
/*!
\brief Constructor for 2-FSK mode.
\param phy Pointer to the wireless module providing PhysicalLayer communication.
*/
explicit HellClient(PhysicalLayer* phy);
#if !defined(RADIOLIB_EXCLUDE_AFSK)
/*!
\brief Constructor for AFSK mode.
\param audio Pointer to the AFSK instance providing audio.
*/
explicit HellClient(AFSKClient* audio);
#endif
// basic methods
/*!
\brief Initialization method.
\param base Base RF frequency to be used in MHz (in 2-FSK mode), or the tone frequency in Hz (in AFSK mode).
\param rate Baud rate to be used during transmission. Defaults to 122.5 ("Feld Hell")
*/
int16_t begin(float base, float rate = 122.5);
/*!
\brief Method to "print" a buffer of pixels, this is exposed to allow users to send custom characters.
\param buff Buffer of pixels to send, in a 7x7 pixel array.
\returns Always returns the number of printed glyphs (1).
*/
size_t printGlyph(uint8_t* buff);
/*!
\brief Invert text color.
\param invert Whether to enable color inversion (white text on black background), or not (black text on white background)
*/
void setInversion(bool invert);
size_t write(const char* str);
size_t write(uint8_t* buff, size_t len);
size_t write(uint8_t b);
size_t print(__FlashStringHelper*);
size_t print(const String &);
size_t print(const char[]);
size_t print(char);
size_t print(unsigned char, int = DEC);
size_t print(int, int = DEC);
size_t print(unsigned int, int = DEC);
size_t print(long, int = DEC);
size_t print(unsigned long, int = DEC);
size_t print(double, int = 2);
size_t println(void);
size_t println(__FlashStringHelper*);
size_t println(const String &);
size_t println(const char[]);
size_t println(char);
size_t println(unsigned char, int = DEC);
size_t println(int, int = DEC);
size_t println(unsigned int, int = DEC);
size_t println(long, int = DEC);
size_t println(unsigned long, int = DEC);
size_t println(double, int = 2);
#if !defined(RADIOLIB_GODMODE)
private:
#endif
PhysicalLayer* _phy;
#if !defined(RADIOLIB_EXCLUDE_AFSK)
AFSKClient* _audio;
#endif
uint32_t _base = 0, _baseHz = 0;
uint32_t _pixelDuration = 0;
bool _inv = false;
size_t printNumber(unsigned long, uint8_t);
size_t printFloat(double, uint8_t);
int16_t transmitDirect(uint32_t freq = 0, uint32_t freqHz = 0);
int16_t standby();
};
#endif
#endif
+395
View File
@@ -0,0 +1,395 @@
#include "Morse.h"
#if !defined(RADIOLIB_EXCLUDE_MORSE)
MorseClient::MorseClient(PhysicalLayer* phy) {
_phy = phy;
#if !defined(RADIOLIB_EXCLUDE_AFSK)
_audio = nullptr;
#endif
}
#if !defined(RADIOLIB_EXCLUDE_AFSK)
MorseClient::MorseClient(AFSKClient* audio) {
_phy = audio->_phy;
_audio = audio;
}
#endif
int16_t MorseClient::begin(float base, uint8_t speed) {
// calculate 24-bit frequency
_baseHz = base;
_base = (base * 1000000.0) / _phy->getFreqStep();
// calculate tone period for decoding
_basePeriod = (1000000.0f/base)/2.0f;
// calculate symbol lengths (assumes PARIS as typical word)
_dotLength = 1200 / speed;
_dashLength = 3*_dotLength;
_letterSpace = 3*_dotLength;
_wordSpace = 4*_dotLength;
// configure for direct mode
return(_phy->startDirect());
}
size_t MorseClient::startSignal() {
return(MorseClient::write('_'));
}
char MorseClient::decode(uint8_t symbol, uint8_t len) {
// add the guard bit
symbol |= (RADIOLIB_MORSE_DASH << len);
// iterate over the table
for(uint8_t i = 0; i < sizeof(MorseTable); i++) {
uint8_t code = RADIOLIB_NONVOLATILE_READ_BYTE(&MorseTable[i]);
if(code == symbol) {
// match, return the index + ASCII offset
return((char)(i + RADIOLIB_MORSE_ASCII_OFFSET));
}
}
// nothing found
return(RADIOLIB_MORSE_UNSUPORTED);
}
#if !defined(RADIOLIB_EXCLUDE_AFSK)
int MorseClient::read(byte* symbol, byte* len, float low, float high) {
Module* mod = _phy->getMod();
// measure pulse duration in us
uint32_t duration = mod->pulseIn(_audio->_pin, LOW, 4*_basePeriod);
// decide if this is a signal, or pause
if((duration > low*_basePeriod) && (duration < high*_basePeriod)) {
// this is a signal
signalCounter++;
} else if(duration == 0) {
// this is a pause
pauseCounter++;
}
// update everything
if((pauseCounter > 0) && (signalCounter == 1)) {
// start of dot or dash
pauseCounter = 0;
signalStart = mod->millis();
uint32_t pauseLen = mod->millis() - pauseStart;
if((pauseLen >= low*(float)_letterSpace) && (pauseLen <= high*(float)_letterSpace)) {
return(RADIOLIB_MORSE_CHAR_COMPLETE);
} else if(pauseLen > _wordSpace) {
RADIOLIB_DEBUG_PRINTLN("\n<space>");
return(RADIOLIB_MORSE_WORD_COMPLETE);
}
} else if((signalCounter > 0) && (pauseCounter == 1)) {
// end of dot or dash
signalCounter = 0;
pauseStart = mod->millis();
uint32_t signalLen = mod->millis() - signalStart;
if((signalLen >= low*(float)_dotLength) && (signalLen <= high*(float)_dotLength)) {
RADIOLIB_DEBUG_PRINT('.');
(*symbol) |= (RADIOLIB_MORSE_DOT << (*len));
(*len)++;
} else if((signalLen >= low*(float)_dashLength) && (signalLen <= high*(float)_dashLength)) {
RADIOLIB_DEBUG_PRINT('-');
(*symbol) |= (RADIOLIB_MORSE_DASH << (*len));
(*len)++;
} else {
RADIOLIB_DEBUG_PRINT("<len=");
RADIOLIB_DEBUG_PRINT(signalLen);
RADIOLIB_DEBUG_PRINTLN("ms>");
}
}
return(RADIOLIB_MORSE_INTER_SYMBOL);
}
#endif
size_t MorseClient::write(const char* str) {
if(str == NULL) {
return(0);
}
return(MorseClient::write((uint8_t*)str, strlen(str)));
}
size_t MorseClient::write(uint8_t* buff, size_t len) {
size_t n = 0;
for(size_t i = 0; i < len; i++) {
n += MorseClient::write(buff[i]);
}
return(n);
}
size_t MorseClient::write(uint8_t b) {
Module* mod = _phy->getMod();
// check unprintable ASCII characters and boundaries
if((b < ' ') || (b == 0x60) || (b > 'z')) {
return(0);
}
// inter-word pause (space)
if(b == ' ') {
RADIOLIB_DEBUG_PRINTLN(F("space"));
standby();
mod->delay(_wordSpace);
return(1);
}
// get morse code from lookup table
uint8_t code = RADIOLIB_NONVOLATILE_READ_BYTE(&MorseTable[(uint8_t)(toupper(b) - RADIOLIB_MORSE_ASCII_OFFSET)]);
// check unsupported characters
if(code == RADIOLIB_MORSE_UNSUPORTED) {
return(0);
}
// iterate through codeword until guard bit is reached
while(code > RADIOLIB_MORSE_GUARDBIT) {
// send dot or dash
if (code & RADIOLIB_MORSE_DASH) {
RADIOLIB_DEBUG_PRINT('-');
transmitDirect(_base, _baseHz);
mod->delay(_dashLength);
} else {
RADIOLIB_DEBUG_PRINT('.');
transmitDirect(_base, _baseHz);
mod->delay(_dotLength);
}
// symbol space
standby();
mod->delay(_dotLength);
// move onto the next bit
code >>= 1;
}
// letter space
standby();
mod->delay(_letterSpace - _dotLength);
RADIOLIB_DEBUG_PRINTLN();
return(1);
}
size_t MorseClient::print(__FlashStringHelper* fstr) {
PGM_P p = reinterpret_cast<PGM_P>(fstr);
size_t n = 0;
while(true) {
char c = RADIOLIB_NONVOLATILE_READ_BYTE(p++);
if(c == '\0') {
break;
}
n += MorseClient::write(c);
}
return n;
}
size_t MorseClient::print(const String& str) {
return(MorseClient::write((uint8_t*)str.c_str(), str.length()));
}
size_t MorseClient::print(const char* str) {
return(MorseClient::write((uint8_t*)str, strlen(str)));
}
size_t MorseClient::print(char c) {
return(MorseClient::write(c));
}
size_t MorseClient::print(unsigned char b, int base) {
return(MorseClient::print((unsigned long)b, base));
}
size_t MorseClient::print(int n, int base) {
return(MorseClient::print((long)n, base));
}
size_t MorseClient::print(unsigned int n, int base) {
return(MorseClient::print((unsigned long)n, base));
}
size_t MorseClient::print(long n, int base) {
if(base == 0) {
return(MorseClient::write(n));
} else if(base == DEC) {
if (n < 0) {
int t = MorseClient::print('-');
n = -n;
return(MorseClient::printNumber(n, DEC) + t);
}
return(MorseClient::printNumber(n, DEC));
} else {
return(MorseClient::printNumber(n, base));
}
}
size_t MorseClient::print(unsigned long n, int base) {
if(base == 0) {
return(MorseClient::write(n));
} else {
return(MorseClient::printNumber(n, base));
}
}
size_t MorseClient::print(double n, int digits) {
return(MorseClient::printFloat(n, digits));
}
size_t MorseClient::println(void) {
return(MorseClient::write('^'));
}
size_t MorseClient::println(__FlashStringHelper* fstr) {
size_t n = MorseClient::print(fstr);
n += MorseClient::println();
return(n);
}
size_t MorseClient::println(const String& str) {
size_t n = MorseClient::print(str);
n += MorseClient::println();
return(n);
}
size_t MorseClient::println(const char* str) {
size_t n = MorseClient::print(str);
n += MorseClient::println();
return(n);
}
size_t MorseClient::println(char c) {
size_t n = MorseClient::print(c);
n += MorseClient::println();
return(n);
}
size_t MorseClient::println(unsigned char b, int base) {
size_t n = MorseClient::print(b, base);
n += MorseClient::println();
return(n);
}
size_t MorseClient::println(int num, int base) {
size_t n = MorseClient::print(num, base);
n += MorseClient::println();
return(n);
}
size_t MorseClient::println(unsigned int num, int base) {
size_t n = MorseClient::print(num, base);
n += MorseClient::println();
return(n);
}
size_t MorseClient::println(long num, int base) {
size_t n = MorseClient::print(num, base);
n += MorseClient::println();
return(n);
}
size_t MorseClient::println(unsigned long num, int base) {
size_t n = MorseClient::print(num, base);
n += MorseClient::println();
return(n);
}
size_t MorseClient::println(double d, int digits) {
size_t n = MorseClient::print(d, digits);
n += MorseClient::println();
return(n);
}
size_t MorseClient::printNumber(unsigned long n, uint8_t base) {
char buf[8 * sizeof(long) + 1];
char *str = &buf[sizeof(buf) - 1];
*str = '\0';
if(base < 2) {
base = 10;
}
do {
char c = n % base;
n /= base;
*--str = c < 10 ? c + '0' : c + 'A' - 10;
} while(n);
return(MorseClient::write(str));
}
size_t MorseClient::printFloat(double number, uint8_t digits) {
size_t n = 0;
char code[] = {0x00, 0x00, 0x00, 0x00};
if (isnan(number)) strcpy(code, "nan");
if (isinf(number)) strcpy(code, "inf");
if (number > 4294967040.0) strcpy(code, "ovf"); // constant determined empirically
if (number <-4294967040.0) strcpy(code, "ovf"); // constant determined empirically
if(code[0] != 0x00) {
return(MorseClient::write(code));
}
// Handle negative numbers
if (number < 0.0) {
n += MorseClient::print('-');
number = -number;
}
// Round correctly so that print(1.999, 2) prints as "2.00"
double rounding = 0.5;
for(uint8_t i = 0; i < digits; ++i) {
rounding /= 10.0;
}
number += rounding;
// Extract the integer part of the number and print it
unsigned long int_part = (unsigned long)number;
double remainder = number - (double)int_part;
n += MorseClient::print(int_part);
// Print the decimal point, but only if there are digits beyond
if(digits > 0) {
n += MorseClient::print('.');
}
// Extract digits from the remainder one at a time
while(digits-- > 0) {
remainder *= 10.0;
unsigned int toPrint = (unsigned int)(remainder);
n += MorseClient::print(toPrint);
remainder -= toPrint;
}
return n;
}
int16_t MorseClient::transmitDirect(uint32_t freq, uint32_t freqHz) {
#if !defined(RADIOLIB_EXCLUDE_AFSK)
if(_audio != nullptr) {
return(_audio->tone(freqHz));
}
#endif
return(_phy->transmitDirect(freq));
}
int16_t MorseClient::standby() {
#if !defined(RADIOLIB_EXCLUDE_AFSK)
if(_audio != nullptr) {
return(_audio->noTone(true));
}
#endif
return(_phy->standby());
}
#endif
+214
View File
@@ -0,0 +1,214 @@
#if !defined(_RADIOLIB_RADIOLIB_MORSE_H) && !defined(RADIOLIB_EXCLUDE_MORSE)
#define _RADIOLIB_RADIOLIB_MORSE_H
#include "../../TypeDef.h"
#include "../PhysicalLayer/PhysicalLayer.h"
#include "../AFSK/AFSK.h"
#define RADIOLIB_MORSE_DOT 0b0
#define RADIOLIB_MORSE_DASH 0b1
#define RADIOLIB_MORSE_GUARDBIT 0b1
#define RADIOLIB_MORSE_UNSUPORTED 0xFF
#define RADIOLIB_MORSE_ASCII_OFFSET 32
#define RADIOLIB_MORSE_INTER_SYMBOL 0x00
#define RADIOLIB_MORSE_CHAR_COMPLETE 0x01
#define RADIOLIB_MORSE_WORD_COMPLETE 0x02
// Morse character table: - using codes defined in ITU-R M.1677-1
// - Morse code representation is saved LSb first, using additional bit as guard
// - position in array corresponds ASCII code minus RADIOLIB_MORSE_ASCII_OFFSET
// - ASCII characters marked RADIOLIB_MORSE_UNSUPORTED do not have ITU-R M.1677-1 equivalent
static const uint8_t MorseTable[] RADIOLIB_NONVOLATILE = {
0b00, // space
0b110101, // ! (unsupported)
0b1010010, // "
RADIOLIB_MORSE_UNSUPORTED, // # (unsupported)
RADIOLIB_MORSE_UNSUPORTED, // $ (unsupported)
RADIOLIB_MORSE_UNSUPORTED, // % (unsupported)
RADIOLIB_MORSE_UNSUPORTED, // & (unsupported)
0b1011110, // '
0b101101, // (
0b1101101, // )
RADIOLIB_MORSE_UNSUPORTED, // * (unsupported)
0b101010, // +
0b1110011, // ,
0b1100001, // -
0b1101010, // .
0b101001, // /
0b111111, // 0
0b111110, // 1
0b111100, // 2
0b111000, // 3
0b110000, // 4
0b100000, // 5
0b100001, // 6
0b100011, // 7
0b100111, // 8
0b101111, // 9
0b1000111, // :
RADIOLIB_MORSE_UNSUPORTED, // ; (unsupported)
RADIOLIB_MORSE_UNSUPORTED, // < (unsupported)
0b110001, // =
RADIOLIB_MORSE_UNSUPORTED, // > (unsupported)
0b1001100, // ?
0b1010110, // @
0b110, // A
0b10001, // B
0b10101, // C
0b1001, // D
0b10, // E
0b10100, // F
0b1011, // G
0b10000, // H
0b100, // I
0b11110, // J
0b1101, // K
0b10010, // L
0b111, // M
0b101, // N
0b1111, // O
0b10110, // P
0b11011, // Q
0b1010, // R
0b1000, // S
0b11, // T
0b1100, // U
0b11000, // V
0b1110, // W
0b11001, // X
0b11101, // Y
0b10011, // Z
RADIOLIB_MORSE_UNSUPORTED, // [ (unsupported)
RADIOLIB_MORSE_UNSUPORTED, // \ (unsupported)
RADIOLIB_MORSE_UNSUPORTED, // ] (unsupported)
0b1101000, // ^ (unsupported, used as alias for end of work)
0b110101 // _ (unsupported, used as alias for starting signal)
};
/*!
\class MorseClient
\brief Client for Morse Code communication. The public interface is the same as Arduino Serial.
*/
class MorseClient {
public:
/*!
\brief Constructor for 2-FSK mode.
\param phy Pointer to the wireless module providing PhysicalLayer communication.
*/
explicit MorseClient(PhysicalLayer* phy);
#if !defined(RADIOLIB_EXCLUDE_AFSK)
/*!
\brief Constructor for AFSK mode.
\param audio Pointer to the AFSK instance providing audio.
*/
explicit MorseClient(AFSKClient* audio);
#endif
// basic methods
/*!
\brief Initialization method.
\param base Base RF frequency to be used in MHz (in 2-FSK mode), or the tone frequency in Hz (in AFSK mode)
\param speed Coding speed in words per minute.
\returns \ref status_codes
*/
int16_t begin(float base, uint8_t speed = 20);
/*!
\brief Send start signal.
\returns Number of bytes sent (always 0).
*/
size_t startSignal();
/*!
\brief Decode Morse symbol to ASCII.
\param symbol Morse code symbol, respresented as outlined in MorseTable.
\param len Symbol length (number of dots and dashes).
\returns ASCII character matching the symbol, or 0xFF if no match is found.
*/
static char decode(uint8_t symbol, uint8_t len);
/*!
\brief Read Morse tone on input pin.
\param symbol Pointer to the symbol buffer.
\param len Pointer to the length counter.
\param low Low threshold for decision limit (dot length, pause length etc.), defaults to 0.75.
\param high High threshold for decision limit (dot length, pause length etc.), defaults to 1.25.
\returns 0 if not enough symbols were decoded, 1 if inter-character space was detected, 2 if inter-word space was detected.
*/
#if !defined(RADIOLIB_EXCLUDE_AFSK)
int read(byte* symbol, byte* len, float low = 0.75f, float high = 1.25f);
#endif
size_t write(const char* str);
size_t write(uint8_t* buff, size_t len);
size_t write(uint8_t b);
size_t print(__FlashStringHelper*);
size_t print(const String &);
size_t print(const char[]);
size_t print(char);
size_t print(unsigned char, int = DEC);
size_t print(int, int = DEC);
size_t print(unsigned int, int = DEC);
size_t print(long, int = DEC);
size_t print(unsigned long, int = DEC);
size_t print(double, int = 2);
size_t println(void);
size_t println(__FlashStringHelper*);
size_t println(const String &);
size_t println(const char[]);
size_t println(char);
size_t println(unsigned char, int = DEC);
size_t println(int, int = DEC);
size_t println(unsigned int, int = DEC);
size_t println(long, int = DEC);
size_t println(unsigned long, int = DEC);
size_t println(double, int = 2);
#if !defined(RADIOLIB_GODMODE)
private:
#endif
PhysicalLayer* _phy;
#if !defined(RADIOLIB_EXCLUDE_AFSK)
AFSKClient* _audio;
#endif
uint32_t _base = 0, _baseHz = 0;
float _basePeriod = 0.0f;
uint16_t _dotLength = 0;
uint16_t _dashLength = 0;
uint16_t _letterSpace = 0;
uint16_t _wordSpace = 0;
// variables to keep decoding state
uint32_t signalCounter = 0;
uint32_t signalStart = 0;
uint32_t pauseCounter = 0;
uint32_t pauseStart = 0;
size_t printNumber(unsigned long, uint8_t);
size_t printFloat(double, uint8_t);
int16_t transmitDirect(uint32_t freq = 0, uint32_t freqHz = 0);
int16_t standby();
};
#endif
@@ -0,0 +1,256 @@
#include "PhysicalLayer.h"
PhysicalLayer::PhysicalLayer(float freqStep, size_t maxPacketLength) {
_freqStep = freqStep;
_maxPacketLength = maxPacketLength;
#if !defined(RADIOLIB_EXCLUDE_DIRECT_RECEIVE)
_bufferBitPos = 0;
_bufferWritePos = 0;
#endif
}
int16_t PhysicalLayer::transmit(__FlashStringHelper* fstr, uint8_t addr) {
// read flash string length
size_t len = 0;
PGM_P p = reinterpret_cast<PGM_P>(fstr);
while(true) {
char c = RADIOLIB_NONVOLATILE_READ_BYTE(p++);
len++;
if(c == '\0') {
break;
}
}
// dynamically allocate memory
#if defined(RADIOLIB_STATIC_ONLY)
char str[RADIOLIB_STATIC_ARRAY_SIZE];
#else
char* str = new char[len];
#endif
// copy string from flash
p = reinterpret_cast<PGM_P>(fstr);
for(size_t i = 0; i < len; i++) {
str[i] = RADIOLIB_NONVOLATILE_READ_BYTE(p + i);
}
// transmit string
int16_t state = transmit(str, addr);
#if !defined(RADIOLIB_STATIC_ONLY)
delete[] str;
#endif
return(state);
}
int16_t PhysicalLayer::transmit(String& str, uint8_t addr) {
return(transmit(str.c_str(), addr));
}
int16_t PhysicalLayer::transmit(const char* str, uint8_t addr) {
return(transmit((uint8_t*)str, strlen(str), addr));
}
int16_t PhysicalLayer::startTransmit(String& str, uint8_t addr) {
return(startTransmit(str.c_str(), addr));
}
int16_t PhysicalLayer::startTransmit(const char* str, uint8_t addr) {
return(startTransmit((uint8_t*)str, strlen(str), addr));
}
int16_t PhysicalLayer::readData(String& str, size_t len) {
int16_t state = RADIOLIB_ERR_NONE;
// read the number of actually received bytes
size_t length = getPacketLength();
if((len < length) && (len != 0)) {
// user requested less bytes than were received, this is allowed (but frowned upon)
// requests for more data than were received will only return the number of actually received bytes (unlike PhysicalLayer::receive())
length = len;
}
// build a temporary buffer
#if defined(RADIOLIB_STATIC_ONLY)
uint8_t data[RADIOLIB_STATIC_ARRAY_SIZE + 1];
#else
uint8_t* data = new uint8_t[length + 1];
if(!data) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
#endif
// read the received data
state = readData(data, length);
if(state == RADIOLIB_ERR_NONE) {
// add null terminator
data[length] = 0;
// initialize Arduino String class
str = String((char*)data);
}
// deallocate temporary buffer
#if !defined(RADIOLIB_STATIC_ONLY)
delete[] data;
#endif
return(state);
}
int16_t PhysicalLayer::receive(String& str, size_t len) {
int16_t state = RADIOLIB_ERR_NONE;
// user can override the length of data to read
size_t length = len;
// build a temporary buffer
#if defined(RADIOLIB_STATIC_ONLY)
uint8_t data[RADIOLIB_STATIC_ARRAY_SIZE + 1];
#else
uint8_t* data = NULL;
if(length == 0) {
data = new uint8_t[_maxPacketLength + 1];
} else {
data = new uint8_t[length + 1];
}
if(!data) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
#endif
// attempt packet reception
state = receive(data, length);
if(state == RADIOLIB_ERR_NONE) {
// read the number of actually received bytes (for unknown packets)
if(len == 0) {
length = getPacketLength(false);
}
// add null terminator
data[length] = 0;
// initialize Arduino String class
str = String((char*)data);
}
// deallocate temporary buffer
#if !defined(RADIOLIB_STATIC_ONLY)
delete[] data;
#endif
return(state);
}
float PhysicalLayer::getFreqStep() const {
return(_freqStep);
}
int32_t PhysicalLayer::random(int32_t max) {
if(max == 0) {
return(0);
}
// get random bytes from the radio
uint8_t randBuff[4];
for(uint8_t i = 0; i < 4; i++) {
randBuff[i] = randomByte();
}
// create 32-bit TRNG number
int32_t randNum = ((int32_t)randBuff[0] << 24) | ((int32_t)randBuff[1] << 16) | ((int32_t)randBuff[2] << 8) | ((int32_t)randBuff[3]);
if(randNum < 0) {
randNum *= -1;
}
RADIOLIB_DEBUG_PRINTLN(randNum);
return(randNum % max);
}
int32_t PhysicalLayer::random(int32_t min, int32_t max) {
if(min >= max) {
return(min);
}
return(PhysicalLayer::random(max - min) + min);
}
int16_t PhysicalLayer::startDirect() {
// disable encodings
int16_t state = setEncoding(RADIOLIB_ENCODING_NRZ);
RADIOLIB_ASSERT(state);
// disable shaping
state = setDataShaping(RADIOLIB_SHAPING_NONE);
RADIOLIB_ASSERT(state);
// set frequency deviation to the lowest possible value
state = setFrequencyDeviation(-1);
return(state);
}
#if !defined(RADIOLIB_EXCLUDE_DIRECT_RECEIVE)
int16_t PhysicalLayer::available() {
return(_bufferWritePos);
}
uint8_t PhysicalLayer::read() {
if(_directSyncWordLen > 0) {
_gotSync = false;
_syncBuffer = 0;
}
_bufferWritePos--;
return(_buffer[_bufferReadPos++]);
}
int16_t PhysicalLayer::setDirectSyncWord(uint32_t syncWord, uint8_t len) {
if(len > 32) {
return(RADIOLIB_ERR_INVALID_SYNC_WORD);
}
_directSyncWordMask = 0xFFFFFFFF >> (32 - len);
_directSyncWordLen = len;
_directSyncWord = syncWord;
// override sync word matching when length is set to 0
if(_directSyncWordLen == 0) {
_gotSync = true;
}
return(RADIOLIB_ERR_NONE);
}
void PhysicalLayer::updateDirectBuffer(uint8_t bit) {
// check sync word
if(!_gotSync) {
_syncBuffer <<= 1;
_syncBuffer |= bit;
if((_syncBuffer & _directSyncWordMask) == _directSyncWord) {
_gotSync = true;
_bufferWritePos = 0;
_bufferReadPos = 0;
_bufferBitPos = 0;
}
} else {
// save the bit
if(bit) {
_buffer[_bufferWritePos] |= 0x01 << _bufferBitPos;
} else {
_buffer[_bufferWritePos] &= ~(0x01 << _bufferBitPos);
}
_bufferBitPos++;
// check complete byte
if(_bufferBitPos == 8) {
_buffer[_bufferWritePos] = Module::flipBits(_buffer[_bufferWritePos]);
_bufferWritePos++;
_bufferBitPos = 0;
}
}
}
#endif
int16_t PhysicalLayer::setDIOMapping(RADIOLIB_PIN_TYPE pin, uint8_t value) {
return(RADIOLIB_ERR_UNSUPPORTED);
}
@@ -0,0 +1,351 @@
#if !defined(_RADIOLIB_PHYSICAL_LAYER_H)
#define _RADIOLIB_PHYSICAL_LAYER_H
#include "../../TypeDef.h"
#include "../../Module.h"
/*!
\class PhysicalLayer
\brief Provides common interface for protocols that run on %LoRa/FSK modules, such as RTTY or LoRaWAN. Also extracts some common
module-independent methods. Using this interface class allows to use the protocols on various modules without much code duplicity.
Because this class is used mainly as interface, all of its virtual members must be implemented in the module class.
*/
class PhysicalLayer {
public:
// constructor
/*!
\brief Default constructor.
\param freqStep Frequency step of the synthesizer in Hz.
\param maxPacketLength Maximum length of packet that can be received by the module.
*/
PhysicalLayer(float freqStep, size_t maxPacketLength);
// basic methods
/*!
\brief Arduino Flash String transmit method.
\param str Pointer to Arduino Flash String that will be transmitted.
\param addr Node address to transmit the packet to. Only used in FSK mode.
\returns \ref status_codes
*/
int16_t transmit(__FlashStringHelper* fstr, uint8_t addr = 0);
/*!
\brief Arduino String transmit method.
\param str Address of Arduino string that will be transmitted.
\param addr Node address to transmit the packet to. Only used in FSK mode.
\returns \ref status_codes
*/
int16_t transmit(String& str, uint8_t addr = 0);
/*!
\brief C-string transmit method.
\param str C-string that will be transmitted.
\param addr Node address to transmit the packet to. Only used in FSK mode.
\returns \ref status_codes
*/
int16_t transmit(const char* str, uint8_t addr = 0);
/*!
\brief Binary transmit method. Must be implemented in module class.
\param data Binary data that will be transmitted.
\param len Length of binary data to transmit (in bytes).
\param addr Node address to transmit the packet to. Only used in FSK mode.
\returns \ref status_codes
*/
virtual int16_t transmit(uint8_t* data, size_t len, uint8_t addr = 0) = 0;
/*!
\brief Arduino String receive method.
\param str Address of Arduino String to save the received data.
\param len Expected number of characters in the message. Leave as 0 if expecting a unknown size packet
\returns \ref status_codes
*/
int16_t receive(String& str, size_t len = 0);
/*!
\brief Sets module to standby.
\returns \ref status_codes
*/
virtual int16_t standby() = 0;
/*!
\brief Binary receive method. Must be implemented in module class.
\param data Pointer to array to save the received binary data.
\param len Number of bytes that will be received. Must be known in advance for binary transmissions.
\returns \ref status_codes
*/
virtual int16_t receive(uint8_t* data, size_t len) = 0;
/*!
\brief Interrupt-driven Arduino String transmit method. Unlike the standard transmit method, this one is non-blocking.
Interrupt pin will be activated when transmission finishes.
\param str Address of Arduino String that will be transmitted.
\param addr Node address to transmit the packet to. Only used in FSK mode.
\returns \ref status_codes
*/
int16_t startTransmit(String& str, uint8_t addr = 0);
/*!
\brief Interrupt-driven Arduino String transmit method. Unlike the standard transmit method, this one is non-blocking.
Interrupt pin will be activated when transmission finishes.
\param str C-string that will be transmitted.
\param addr Node address to transmit the packet to. Only used in FSK mode.
\returns \ref status_codes
*/
int16_t startTransmit(const char* str, uint8_t addr = 0);
/*!
\brief Interrupt-driven binary transmit method.
\param data Binary data that will be transmitted.
\param len Length of binary data to transmit (in bytes).
\param addr Node address to transmit the packet to. Only used in FSK mode.
\returns \ref status_codes
*/
virtual int16_t startTransmit(uint8_t* data, size_t len, uint8_t addr = 0) = 0;
/*!
\brief Reads data that was received after calling startReceive method.
\param str Address of Arduino String to save the received data.
\param len Expected number of characters in the message. When set to 0, the packet length will be retreived automatically.
When more bytes than received are requested, only the number of bytes requested will be returned.
\returns \ref status_codes
*/
int16_t readData(String& str, size_t len = 0);
/*!
\brief Reads data that was received after calling startReceive method.
\param data Pointer to array to save the received binary data.
\param len Number of bytes that will be read. When set to 0, the packet length will be retreived automatically.
When more bytes than received are requested, only the number of bytes requested will be returned.
\returns \ref status_codes
*/
virtual int16_t readData(uint8_t* data, size_t len) = 0;
/*!
\brief Enables direct transmission mode on pins DIO1 (clock) and DIO2 (data). Must be implemented in module class.
While in direct mode, the module will not be able to transmit or receive packets. Can only be activated in FSK mode.
\param frf 24-bit raw frequency value to start transmitting at. Required for quick frequency shifts in RTTY.
\returns \ref status_codes
*/
virtual int16_t transmitDirect(uint32_t frf = 0) = 0;
/*!
\brief Enables direct reception mode on pins DIO1 (clock) and DIO2 (data). Must be implemented in module class.
While in direct mode, the module will not be able to transmit or receive packets. Can only be activated in FSK mode.
\returns \ref status_codes
*/
virtual int16_t receiveDirect() = 0;
// configuration methods
/*!
\brief Sets FSK frequency deviation from carrier frequency. Allowed values depend on bit rate setting and must be lower than 200 kHz.
Only available in FSK mode. Must be implemented in module class.
\param freqDev Frequency deviation to be set (in kHz).
\returns \ref status_codes
*/
virtual int16_t setFrequencyDeviation(float freqDev) = 0;
/*!
\brief Sets GFSK data shaping. Only available in FSK mode. Must be implemented in module class.
\param sh Shaping to be set. See \ref config_shaping for possible values.
\returns \ref status_codes
*/
virtual int16_t setDataShaping(uint8_t sh) = 0;
/*!
\brief Sets FSK data encoding. Only available in FSK mode. Must be implemented in module class.
\param enc Encoding to be used. See \ref config_encoding for possible values.
\returns \ref status_codes
*/
virtual int16_t setEncoding(uint8_t encoding) = 0;
/*!
\brief Gets the module frequency step size that was set in constructor.
\returns Synthesizer frequency step size in Hz.
*/
float getFreqStep() const;
/*!
\brief Query modem for the packet length of received payload. Must be implemented in module class.
\param update Update received packet length. Will return cached value when set to false.
\returns Length of last received packet in bytes.
*/
virtual size_t getPacketLength(bool update = true) = 0;
/*!
\brief Get truly random number in range 0 - max.
\param max The maximum value of the random number (non-inclusive).
\returns Random number.
*/
int32_t random(int32_t max);
/*!
\brief Get truly random number in range min - max.
\param min The minimum value of the random number (inclusive).
\param max The maximum value of the random number (non-inclusive).
\returns Random number.
*/
int32_t random(int32_t min, int32_t max);
/*!
\brief Get one truly random byte from RSSI noise. Must be implemented in module class.
\returns TRNG byte.
*/
virtual uint8_t randomByte() = 0;
/*!
\brief Configure module parameters for direct modes. Must be called prior to "ham" modes like RTTY or AX.25. Only available in FSK mode.
\returns \ref status_codes
*/
int16_t startDirect();
#if !defined(RADIOLIB_EXCLUDE_DIRECT_RECEIVE)
/*!
\brief Set sync word to be used to determine start of packet in direct reception mode.
\param syncWord Sync word bits.
\param len Sync word length in bits. Set to zero to disable sync word matching.
\returns \ref status_codes
*/
int16_t setDirectSyncWord(uint32_t syncWord, uint8_t len);
/*!
\brief Set interrupt service routine function to call when data bit is receveid in direct mode. Must be implemented in module class.
\param func Pointer to interrupt service routine.
*/
virtual void setDirectAction(void (*func)(void)) = 0;
/*!
\brief Function to read and process data bit in direct reception mode. Must be implemented in module class.
\param pin Pin on which to read.
*/
virtual void readBit(RADIOLIB_PIN_TYPE pin) = 0;
/*!
\brief Get the number of direct mode bytes currently available in buffer.
\returns Number of available bytes.
*/
int16_t available();
/*!
\brief Get data from direct mode buffer.
\returns Byte from direct mode buffer.
*/
uint8_t read();
#endif
/*!
\brief Configure DIO pin mapping to get a given signal on a DIO pin (if available).
\param pin Pin number onto which a signal is to be placed.
\param value The value that indicates which function to place on that pin. See chip datasheet for details.
\returns \ref status_codes
*/
virtual int16_t setDIOMapping(RADIOLIB_PIN_TYPE pin, uint8_t value);
#if !defined(RADIOLIB_EXCLUDE_DIRECT_RECEIVE)
protected:
void updateDirectBuffer(uint8_t bit);
#endif
#if !defined(RADIOLIB_GODMODE)
private:
#endif
float _freqStep;
size_t _maxPacketLength;
#if !defined(RADIOLIB_EXCLUDE_DIRECT_RECEIVE)
uint8_t _bufferBitPos;
uint8_t _bufferWritePos;
uint8_t _bufferReadPos;
uint8_t _buffer[RADIOLIB_STATIC_ARRAY_SIZE];
uint32_t _syncBuffer;
uint32_t _directSyncWord;
uint8_t _directSyncWordLen;
uint32_t _directSyncWordMask;
bool _gotSync;
#endif
virtual Module* getMod() = 0;
// allow specific classes access the private getMod method
friend class AFSKClient;
friend class RTTYClient;
friend class MorseClient;
friend class HellClient;
friend class SSTVClient;
friend class AX25Client;
friend class FSK4Client;
};
#endif
+542
View File
@@ -0,0 +1,542 @@
#include "RTTY.h"
#if !defined(RADIOLIB_EXCLUDE_RTTY)
ITA2String::ITA2String(char c) {
_len = 1;
#if !defined(RADIOLIB_STATIC_ONLY)
_str = new char[1];
#endif
_str[0] = c;
_ita2Len = 0;
}
ITA2String::ITA2String(const char* str) {
_len = strlen(str);
#if !defined(RADIOLIB_STATIC_ONLY)
_str = new char[_len + 1];
#endif
strcpy(_str, str);
_ita2Len = 0;
}
ITA2String::~ITA2String() {
#if !defined(RADIOLIB_STATIC_ONLY)
delete[] _str;
#endif
}
size_t ITA2String::length() {
// length returned by this method is different than the length of ASCII-encoded _str
// ITA2-encoded string length varies based on how many number and characters the string contains
if(_ita2Len == 0) {
// ITA2 length wasn't calculated yet, call byteArr() to calculate it
byteArr();
}
return(_ita2Len);
}
uint8_t* ITA2String::byteArr() {
// create temporary array 2x the string length (figures may be 3 bytes)
#if defined(RADIOLIB_STATIC_ONLY)
uint8_t temp[RADIOLIB_STATIC_ARRAY_SIZE*2 + 1];
#else
uint8_t* temp = new uint8_t[_len*2 + 1];
#endif
size_t arrayLen = 0;
bool flagFigure = false;
for(size_t i = 0; i < _len; i++) {
uint16_t code = getBits(_str[i]);
uint8_t shift = (code >> 5) & 0b11111;
uint8_t character = code & 0b11111;
// check if the code is letter or figure
if(shift == RADIOLIB_ITA2_FIGS) {
// check if this is the first figure in sequence
if(!flagFigure) {
flagFigure = true;
temp[arrayLen++] = RADIOLIB_ITA2_FIGS;
}
// add the character code
temp[arrayLen++] = character & 0b11111;
// check the following character (skip for message end)
if(i < (_len - 1)) {
uint16_t nextCode = getBits(_str[i+1]);
uint8_t nextShift = (nextCode >> 5) & 0b11111;
if(nextShift == RADIOLIB_ITA2_LTRS) {
// next character is a letter, terminate figure shift
temp[arrayLen++] = RADIOLIB_ITA2_LTRS;
flagFigure = false;
}
} else {
// reached the end of the message, terminate figure shift
temp[arrayLen++] = RADIOLIB_ITA2_LTRS;
flagFigure = false;
}
} else {
temp[arrayLen++] = character & 0b11111;
}
}
// save ITA2 string length
_ita2Len = arrayLen;
uint8_t* arr = new uint8_t[arrayLen];
memcpy(arr, temp, arrayLen);
#if !defined(RADIOLIB_STATIC_ONLY)
delete[] temp;
#endif
return(arr);
}
uint16_t ITA2String::getBits(char c) {
// search ITA2 table
uint16_t code = 0x0000;
for(uint8_t i = 0; i < RADIOLIB_ITA2_LENGTH; i++) {
if(RADIOLIB_NONVOLATILE_READ_BYTE(&ITA2Table[i][0]) == c) {
// character is in letter shift
code = (RADIOLIB_ITA2_LTRS << 5) | i;
break;
} else if(RADIOLIB_NONVOLATILE_READ_BYTE(&ITA2Table[i][1]) == c) {
// character is in figures shift
code = (RADIOLIB_ITA2_FIGS << 5) | i;
break;
}
}
return(code);
}
RTTYClient::RTTYClient(PhysicalLayer* phy) {
_phy = phy;
#if !defined(RADIOLIB_EXCLUDE_AFSK)
_audio = nullptr;
#endif
}
#if !defined(RADIOLIB_EXCLUDE_AFSK)
RTTYClient::RTTYClient(AFSKClient* audio) {
_phy = audio->_phy;
_audio = audio;
}
#endif
int16_t RTTYClient::begin(float base, uint32_t shift, uint16_t rate, uint8_t encoding, uint8_t stopBits) {
// save configuration
_encoding = encoding;
_stopBits = stopBits;
_baseHz = base;
_shiftHz = shift;
switch(encoding) {
case RADIOLIB_ASCII:
_dataBits = 7;
break;
case RADIOLIB_ASCII_EXTENDED:
_dataBits = 8;
break;
case RADIOLIB_ITA2:
_dataBits = 5;
break;
default:
return(RADIOLIB_ERR_UNSUPPORTED_ENCODING);
}
// calculate duration of 1 bit
_bitDuration = (uint32_t)1000000/rate;
// calculate module carrier frequency resolution
uint32_t step = round(_phy->getFreqStep());
// check minimum shift value
if(shift < step / 2) {
return(RADIOLIB_ERR_INVALID_RTTY_SHIFT);
}
// round shift to multiples of frequency step size
if(shift % step < (step / 2)) {
_shift = shift / step;
} else {
_shift = (shift / step) + 1;
}
// calculate 24-bit frequency
_base = (base * 1000000.0) / _phy->getFreqStep();
// configure for direct mode
return(_phy->startDirect());
}
void RTTYClient::idle() {
mark();
}
size_t RTTYClient::write(const char* str) {
if(str == NULL) {
return(0);
}
return(RTTYClient::write((uint8_t *)str, strlen(str)));
}
size_t RTTYClient::write(uint8_t* buff, size_t len) {
size_t n = 0;
for(size_t i = 0; i < len; i++) {
n += RTTYClient::write(buff[i]);
}
return(n);
}
size_t RTTYClient::write(uint8_t b) {
space();
uint16_t maxDataMask = 0x01 << (_dataBits - 1);
for(uint16_t mask = 0x01; mask <= maxDataMask; mask <<= 1) {
if(b & mask) {
mark();
} else {
space();
}
}
for(uint8_t i = 0; i < _stopBits; i++) {
mark();
}
return(1);
}
size_t RTTYClient::print(__FlashStringHelper* fstr) {
// read flash string length
size_t len = 0;
PGM_P p = reinterpret_cast<PGM_P>(fstr);
while(true) {
char c = RADIOLIB_NONVOLATILE_READ_BYTE(p++);
len++;
if(c == '\0') {
break;
}
}
// dynamically allocate memory
#if defined(RADIOLIB_STATIC_ONLY)
char str[RADIOLIB_STATIC_ARRAY_SIZE];
#else
char* str = new char[len];
#endif
// copy string from flash
p = reinterpret_cast<PGM_P>(fstr);
for(size_t i = 0; i < len; i++) {
str[i] = RADIOLIB_NONVOLATILE_READ_BYTE(p + i);
}
size_t n = 0;
if(_encoding == RADIOLIB_ITA2) {
ITA2String ita2 = ITA2String(str);
n = RTTYClient::print(ita2);
} else if((_encoding == RADIOLIB_ASCII) || (_encoding == RADIOLIB_ASCII_EXTENDED)) {
n = RTTYClient::write((uint8_t*)str, len);
}
#if !defined(RADIOLIB_STATIC_ONLY)
delete[] str;
#endif
return(n);
}
size_t RTTYClient::print(ITA2String& ita2) {
uint8_t* arr = ita2.byteArr();
size_t n = RTTYClient::write(arr, ita2.length());
delete[] arr;
return(n);
}
size_t RTTYClient::print(const String& str) {
size_t n = 0;
if(_encoding == RADIOLIB_ITA2) {
ITA2String ita2 = ITA2String(str.c_str());
n = RTTYClient::print(ita2);
} else if((_encoding == RADIOLIB_ASCII) || (_encoding == RADIOLIB_ASCII_EXTENDED)) {
n = RTTYClient::write((uint8_t*)str.c_str(), str.length());
}
return(n);
}
size_t RTTYClient::print(const char str[]) {
size_t n = 0;
if(_encoding == RADIOLIB_ITA2) {
ITA2String ita2 = ITA2String(str);
n = RTTYClient::print(ita2);
} else if((_encoding == RADIOLIB_ASCII) || (_encoding == RADIOLIB_ASCII_EXTENDED)) {
n = RTTYClient::write((uint8_t*)str, strlen(str));
}
return(n);
}
size_t RTTYClient::print(char c) {
size_t n = 0;
if(_encoding == RADIOLIB_ITA2) {
ITA2String ita2 = ITA2String(c);
n = RTTYClient::print(ita2);
} else if((_encoding == RADIOLIB_ASCII) || (_encoding == RADIOLIB_ASCII_EXTENDED)) {
n = RTTYClient::write(c);
}
return(n);
}
size_t RTTYClient::print(unsigned char b, int base) {
return(RTTYClient::print((unsigned long)b, base));
}
size_t RTTYClient::print(int n, int base) {
return(RTTYClient::print((long)n, base));
}
size_t RTTYClient::print(unsigned int n, int base) {
return(RTTYClient::print((unsigned long)n, base));
}
size_t RTTYClient::print(long n, int base) {
if(base == 0) {
return(RTTYClient::write(n));
} else if(base == DEC) {
if (n < 0) {
int t = RTTYClient::print('-');
n = -n;
return(RTTYClient::printNumber(n, DEC) + t);
}
return(RTTYClient::printNumber(n, DEC));
} else {
return(RTTYClient::printNumber(n, base));
}
}
size_t RTTYClient::print(unsigned long n, int base) {
if(base == 0) {
return(RTTYClient::write(n));
} else {
return(RTTYClient::printNumber(n, base));
}
}
size_t RTTYClient::print(double n, int digits) {
return(RTTYClient::printFloat(n, digits));
}
size_t RTTYClient::println(void) {
size_t n = 0;
if(_encoding == RADIOLIB_ITA2) {
ITA2String lf = ITA2String("\r\n");
n = RTTYClient::print(lf);
} else if((_encoding == RADIOLIB_ASCII) || (_encoding == RADIOLIB_ASCII_EXTENDED)) {
n = RTTYClient::write("\r\n");
}
return(n);
}
size_t RTTYClient::println(__FlashStringHelper* fstr) {
size_t n = RTTYClient::print(fstr);
n += RTTYClient::println();
return(n);
}
size_t RTTYClient::println(ITA2String& ita2) {
size_t n = RTTYClient::print(ita2);
n += RTTYClient::println();
return(n);
}
size_t RTTYClient::println(const String& str) {
size_t n = RTTYClient::print(str);
n += RTTYClient::println();
return(n);
}
size_t RTTYClient::println(const char* str) {
size_t n = RTTYClient::print(str);
n += RTTYClient::println();
return(n);
}
size_t RTTYClient::println(char c) {
size_t n = RTTYClient::print(c);
n += RTTYClient::println();
return(n);
}
size_t RTTYClient::println(unsigned char b, int base) {
size_t n = RTTYClient::print(b, base);
n += RTTYClient::println();
return(n);
}
size_t RTTYClient::println(int num, int base) {
size_t n = RTTYClient::print(num, base);
n += RTTYClient::println();
return(n);
}
size_t RTTYClient::println(unsigned int num, int base) {
size_t n = RTTYClient::print(num, base);
n += RTTYClient::println();
return(n);
}
size_t RTTYClient::println(long num, int base) {
size_t n = RTTYClient::print(num, base);
n += RTTYClient::println();
return(n);
}
size_t RTTYClient::println(unsigned long num, int base) {
size_t n = RTTYClient::print(num, base);
n += RTTYClient::println();
return(n);
}
size_t RTTYClient::println(double d, int digits) {
size_t n = RTTYClient::print(d, digits);
n += RTTYClient::println();
return(n);
}
void RTTYClient::mark() {
Module* mod = _phy->getMod();
uint32_t start = mod->micros();
transmitDirect(_base + _shift, _baseHz + _shiftHz);
while(mod->micros() - start < _bitDuration) {
mod->yield();
}
}
void RTTYClient::space() {
Module* mod = _phy->getMod();
uint32_t start = mod->micros();
transmitDirect(_base, _baseHz);
while(mod->micros() - start < _bitDuration) {
mod->yield();
}
}
size_t RTTYClient::printNumber(unsigned long n, uint8_t base) {
char buf[8 * sizeof(long) + 1];
char *str = &buf[sizeof(buf) - 1];
*str = '\0';
if(base < 2) {
base = 10;
}
do {
char c = n % base;
n /= base;
*--str = c < 10 ? c + '0' : c + 'A' - 10;
} while(n);
size_t l = 0;
if(_encoding == RADIOLIB_ITA2) {
ITA2String ita2 = ITA2String(str);
uint8_t* arr = ita2.byteArr();
l = RTTYClient::write(arr, ita2.length());
delete[] arr;
} else if((_encoding == RADIOLIB_ASCII) || (_encoding == RADIOLIB_ASCII_EXTENDED)) {
l = RTTYClient::write(str);
}
return(l);
}
/// \todo improve ITA2 float print speed (characters are sent one at a time)
size_t RTTYClient::printFloat(double number, uint8_t digits) {
size_t n = 0;
char code[] = {0x00, 0x00, 0x00, 0x00};
if (isnan(number)) strcpy(code, "nan");
if (isinf(number)) strcpy(code, "inf");
if (number > 4294967040.0) strcpy(code, "ovf"); // constant determined empirically
if (number <-4294967040.0) strcpy(code, "ovf"); // constant determined empirically
if(code[0] != 0x00) {
if(_encoding == RADIOLIB_ITA2) {
ITA2String ita2 = ITA2String(code);
uint8_t* arr = ita2.byteArr();
n = RTTYClient::write(arr, ita2.length());
delete[] arr;
return(n);
} else if((_encoding == RADIOLIB_ASCII) || (_encoding == RADIOLIB_ASCII_EXTENDED)) {
return(RTTYClient::write(code));
}
}
// Handle negative numbers
if (number < 0.0) {
if(_encoding == RADIOLIB_ITA2) {
ITA2String ita2 = ITA2String("-");
uint8_t* arr = ita2.byteArr();
n += RTTYClient::write(arr, ita2.length());
delete[] arr;
} else if((_encoding == RADIOLIB_ASCII) || (_encoding == RADIOLIB_ASCII_EXTENDED)) {
n += RTTYClient::print('-');
}
number = -number;
}
// Round correctly so that print(1.999, 2) prints as "2.00"
double rounding = 0.5;
for(uint8_t i = 0; i < digits; ++i) {
rounding /= 10.0;
}
number += rounding;
// Extract the integer part of the number and print it
unsigned long int_part = (unsigned long)number;
double remainder = number - (double)int_part;
n += RTTYClient::print(int_part);
// Print the decimal point, but only if there are digits beyond
if(digits > 0) {
if(_encoding == RADIOLIB_ITA2) {
ITA2String ita2 = ITA2String(".");
uint8_t* arr = ita2.byteArr();
n += RTTYClient::write(arr, ita2.length());
delete[] arr;
} else if((_encoding == RADIOLIB_ASCII) || (_encoding == RADIOLIB_ASCII_EXTENDED)) {
n += RTTYClient::print('.');
}
}
// Extract digits from the remainder one at a time
while(digits-- > 0) {
remainder *= 10.0;
unsigned int toPrint = (unsigned int)(remainder);
n += RTTYClient::print(toPrint);
remainder -= toPrint;
}
return n;
}
int16_t RTTYClient::transmitDirect(uint32_t freq, uint32_t freqHz) {
#if !defined(RADIOLIB_EXCLUDE_AFSK)
if(_audio != nullptr) {
return(_audio->tone(freqHz));
}
#endif
return(_phy->transmitDirect(freq));
}
int16_t RTTYClient::standby() {
#if !defined(RADIOLIB_EXCLUDE_AFSK)
if(_audio != nullptr) {
return(_audio->noTone());
}
#endif
return(_phy->standby());
}
#endif
+192
View File
@@ -0,0 +1,192 @@
#if !defined(_RADIOLIB_RTTY_H)
#define _RADIOLIB_RTTY_H
#include "../../TypeDef.h"
#if !defined(RADIOLIB_EXCLUDE_RTTY)
#include "../PhysicalLayer/PhysicalLayer.h"
#include "../AFSK/AFSK.h"
#define RADIOLIB_ITA2_FIGS 0x1B
#define RADIOLIB_ITA2_LTRS 0x1F
#define RADIOLIB_ITA2_LENGTH 32
// ITA2 character table: - position in array corresponds to 5-bit ITA2 code
// - characters to the left are in letters shift, characters to the right in figures shift
// - characters marked 0x7F do not have ASCII equivalent
static const char ITA2Table[RADIOLIB_ITA2_LENGTH][2] RADIOLIB_NONVOLATILE = {{'\0', '\0'}, {'E', '3'}, {'\n', '\n'}, {'A', '-'}, {' ', ' '}, {'S', '\''}, {'I', '8'}, {'U', '7'},
{'\r', '\r'}, {'D', 0x05}, {'R', '4'}, {'J', '\a'}, {'N', ','}, {'F', '!'}, {'C', ':'}, {'K', '('},
{'T', '5'}, {'Z', '+'}, {'L', ')'}, {'W', '2'}, {'H', 0x7F}, {'Y', '6'}, {'P', '0'}, {'Q', '1'},
{'O', '9'}, {'B', '?'}, {'G', '&'}, {0x7F, 0x7F}, {'M', '.'}, {'X', '/'}, {'V', ';'}, {0x7F, 0x7F}};
/*!
\class ITA2String
\brief ITA2-encoded string.
*/
class ITA2String {
public:
/*!
\brief Default single-character constructor.
\param c ASCII-encoded character to encode as ITA2.
*/
explicit ITA2String(char c);
/*!
\brief Default string constructor.
\param str ASCII-encoded string to encode as ITA2.
*/
explicit ITA2String(const char* str);
/*!
\brief Default destructor.
*/
~ITA2String();
/*!
\brief Gets the length of the ITA2 string. This number is not the same as the length of ASCII-encoded string!
\returns Length of ITA2-encoded string.
*/
size_t length();
/*!
\brief Gets the ITA2 representation of the ASCII string set in constructor.
\returns Pointer to dynamically allocated array, which contains ITA2-encoded bytes.
It is the caller's responsibility to deallocate this memory!
*/
uint8_t* byteArr();
#if !defined(RADIOLIB_GODMODE)
private:
#endif
#if defined(RADIOLIB_STATIC_ONLY)
char _str[RADIOLIB_STATIC_ARRAY_SIZE];
#else
char* _str;
#endif
size_t _len;
size_t _ita2Len;
static uint16_t getBits(char c);
};
// supported encoding schemes
#define RADIOLIB_ASCII 0
#define RADIOLIB_ASCII_EXTENDED 1
#define RADIOLIB_ITA2 2
/*!
\class RTTYClient
\brief Client for RTTY communication. The public interface is the same as Arduino Serial.
*/
class RTTYClient {
public:
/*!
\brief Constructor for 2-FSK mode.
\param phy Pointer to the wireless module providing PhysicalLayer communication.
*/
explicit RTTYClient(PhysicalLayer* phy);
#if !defined(RADIOLIB_EXCLUDE_AFSK)
/*!
\brief Constructor for AFSK mode.
\param audio Pointer to the AFSK instance providing audio.
*/
explicit RTTYClient(AFSKClient* audio);
#endif
// basic methods
/*!
\brief Initialization method.
\param base Base (space) frequency to be used in MHz (in 2-FSK mode), or the space tone frequency in Hz (in AFSK mode)
\param shift Frequency shift between mark and space in Hz.
\param rate Baud rate to be used during transmission.
\param encoding Encoding to be used. Defaults to ASCII.
\param stopBits Number of stop bits to be used.
\returns \ref status_codes
*/
int16_t begin(float base, uint32_t shift, uint16_t rate, uint8_t encoding = RADIOLIB_ASCII, uint8_t stopBits = 1);
/*!
\brief Send out idle condition (RF tone at mark frequency).
*/
void idle();
/*!
\brief Stops transmitting.
\returns \ref status_codes
*/
int16_t standby();
size_t write(const char* str);
size_t write(uint8_t* buff, size_t len);
size_t write(uint8_t b);
size_t print(__FlashStringHelper*);
size_t print(ITA2String &);
size_t print(const String &);
size_t print(const char[]);
size_t print(char);
size_t print(unsigned char, int = DEC);
size_t print(int, int = DEC);
size_t print(unsigned int, int = DEC);
size_t print(long, int = DEC);
size_t print(unsigned long, int = DEC);
size_t print(double, int = 2);
size_t println(void);
size_t println(__FlashStringHelper*);
size_t println(ITA2String &);
size_t println(const String &);
size_t println(const char[]);
size_t println(char);
size_t println(unsigned char, int = DEC);
size_t println(int, int = DEC);
size_t println(unsigned int, int = DEC);
size_t println(long, int = DEC);
size_t println(unsigned long, int = DEC);
size_t println(double, int = 2);
#if !defined(RADIOLIB_GODMODE)
private:
#endif
PhysicalLayer* _phy;
#if !defined(RADIOLIB_EXCLUDE_AFSK)
AFSKClient* _audio;
#endif
uint8_t _encoding = RADIOLIB_ASCII;
uint32_t _base = 0, _baseHz = 0;
uint32_t _shift = 0, _shiftHz = 0;
uint32_t _bitDuration = 0;
uint8_t _dataBits = 0;
uint8_t _stopBits = 0;
void mark();
void space();
size_t printNumber(unsigned long, uint8_t);
size_t printFloat(double, uint8_t);
int16_t transmitDirect(uint32_t freq = 0, uint32_t freqHz = 0);
};
#endif
#endif
+301
View File
@@ -0,0 +1,301 @@
#include "SSTV.h"
#if !defined(RADIOLIB_EXCLUDE_SSTV)
const SSTVMode_t Scottie1 {
.visCode = RADIOLIB_SSTV_SCOTTIE_1,
.width = 320,
.height = 256,
.scanPixelLen = 432,
.numTones = 7,
.tones = {
{ .type = tone_t::GENERIC, .len = 1500, .freq = 1500 },
{ .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 1500, .freq = 1500 },
{ .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 9000, .freq = 1200 },
{ .type = tone_t::GENERIC, .len = 1500, .freq = 1500 },
{ .type = tone_t::SCAN_RED, .len = 0, .freq = 0 }
}
};
const SSTVMode_t Scottie2 {
.visCode = RADIOLIB_SSTV_SCOTTIE_2,
.width = 320,
.height = 256,
.scanPixelLen = 275,
.numTones = 7,
.tones = {
{ .type = tone_t::GENERIC, .len = 1500, .freq = 1500 },
{ .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 1500, .freq = 1500 },
{ .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 9000, .freq = 1200 },
{ .type = tone_t::GENERIC, .len = 1500, .freq = 1500 },
{ .type = tone_t::SCAN_RED, .len = 0, .freq = 0 }
}
};
const SSTVMode_t ScottieDX {
.visCode = RADIOLIB_SSTV_SCOTTIE_DX,
.width = 320,
.height = 256,
.scanPixelLen = 1080,
.numTones = 7,
.tones = {
{ .type = tone_t::GENERIC, .len = 1500, .freq = 1500 },
{ .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 1500, .freq = 1500 },
{ .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 9000, .freq = 1200 },
{ .type = tone_t::GENERIC, .len = 1500, .freq = 1500 },
{ .type = tone_t::SCAN_RED, .len = 0, .freq = 0 }
}
};
const SSTVMode_t Martin1 {
.visCode = RADIOLIB_SSTV_MARTIN_1,
.width = 320,
.height = 256,
.scanPixelLen = 458,
.numTones = 8,
.tones = {
{ .type = tone_t::GENERIC, .len = 4862, .freq = 1200 },
{ .type = tone_t::GENERIC, .len = 572, .freq = 1500 },
{ .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 572, .freq = 1500 },
{ .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 572, .freq = 1500 },
{ .type = tone_t::SCAN_RED, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 572, .freq = 1500 }
}
};
const SSTVMode_t Martin2 {
.visCode = RADIOLIB_SSTV_MARTIN_2,
.width = 320,
.height = 256,
.scanPixelLen = 229,
.numTones = 8,
.tones = {
{ .type = tone_t::GENERIC, .len = 4862, .freq = 1200 },
{ .type = tone_t::GENERIC, .len = 572, .freq = 1500 },
{ .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 572, .freq = 1500 },
{ .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 572, .freq = 1500 },
{ .type = tone_t::SCAN_RED, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 572, .freq = 1500 }
}
};
const SSTVMode_t Wrasse {
.visCode = RADIOLIB_SSTV_WRASSE_SC2_180,
.width = 320,
.height = 256,
.scanPixelLen = 734,
.numTones = 5,
.tones = {
{ .type = tone_t::GENERIC, .len = 5523, .freq = 1200 },
{ .type = tone_t::GENERIC, .len = 500, .freq = 1500 },
{ .type = tone_t::SCAN_RED, .len = 0, .freq = 0 },
{ .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 },
{ .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 }
}
};
const SSTVMode_t PasokonP3 {
.visCode = RADIOLIB_SSTV_PASOKON_P3,
.width = 640,
.height = 496,
.scanPixelLen = 208,
.numTones = 7,
.tones = {
{ .type = tone_t::GENERIC, .len = 5208, .freq = 1200 },
{ .type = tone_t::GENERIC, .len = 1042, .freq = 1500 },
{ .type = tone_t::SCAN_RED, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 1042, .freq = 1500 },
{ .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 1042, .freq = 1500 },
{ .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 }
}
};
const SSTVMode_t PasokonP5 {
.visCode = RADIOLIB_SSTV_PASOKON_P5,
.width = 640,
.height = 496,
.scanPixelLen = 312,
.numTones = 7,
.tones = {
{ .type = tone_t::GENERIC, .len = 7813, .freq = 1200 },
{ .type = tone_t::GENERIC, .len = 1563, .freq = 1500 },
{ .type = tone_t::SCAN_RED, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 1563, .freq = 1500 },
{ .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 1563, .freq = 1500 },
{ .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 }
}
};
const SSTVMode_t PasokonP7 {
.visCode = RADIOLIB_SSTV_PASOKON_P7,
.width = 640,
.height = 496,
.scanPixelLen = 417,
.numTones = 7,
.tones = {
{ .type = tone_t::GENERIC, .len = 10417, .freq = 1200 },
{ .type = tone_t::GENERIC, .len = 2083, .freq = 1500 },
{ .type = tone_t::SCAN_RED, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 2083, .freq = 1500 },
{ .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 },
{ .type = tone_t::GENERIC, .len = 2083, .freq = 1500 },
{ .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 }
}
};
SSTVClient::SSTVClient(PhysicalLayer* phy) {
_phy = phy;
#if !defined(RADIOLIB_EXCLUDE_AFSK)
_audio = nullptr;
#endif
}
#if !defined(RADIOLIB_EXCLUDE_AFSK)
SSTVClient::SSTVClient(AFSKClient* audio) {
_phy = audio->_phy;
_audio = audio;
}
#endif
#if !defined(RADIOLIB_EXCLUDE_AFSK)
int16_t SSTVClient::begin(const SSTVMode_t& mode, float correction) {
if(_audio == nullptr) {
// this initialization method can only be used in AFSK mode
return(RADIOLIB_ERR_WRONG_MODEM);
}
return(begin(0, mode, correction));
}
#endif
int16_t SSTVClient::begin(float base, const SSTVMode_t& mode, float correction) {
// save mode
_mode = mode;
// apply correction factor to all timings
_mode.scanPixelLen *= correction;
for(uint8_t i = 0; i < _mode.numTones; i++) {
_mode.tones[i].len *= correction;
}
// calculate 24-bit frequency
_base = (base * 1000000.0) / _phy->getFreqStep();
// configure for direct mode
return(_phy->startDirect());
}
void SSTVClient::idle() {
_phy->transmitDirect();
this->tone(RADIOLIB_SSTV_TONE_LEADER);
}
void SSTVClient::sendHeader() {
// save first header flag for Scottie modes
_firstLine = true;
_phy->transmitDirect();
// send the first part of header (leader-break-leader)
this->tone(RADIOLIB_SSTV_TONE_LEADER, RADIOLIB_SSTV_HEADER_LEADER_LENGTH);
this->tone(RADIOLIB_SSTV_TONE_BREAK, RADIOLIB_SSTV_HEADER_BREAK_LENGTH);
this->tone(RADIOLIB_SSTV_TONE_LEADER, RADIOLIB_SSTV_HEADER_LEADER_LENGTH);
// VIS start bit
this->tone(RADIOLIB_SSTV_TONE_BREAK, RADIOLIB_SSTV_HEADER_BIT_LENGTH);
// VIS code
uint8_t parityCount = 0;
for(uint8_t mask = 0x01; mask < 0x80; mask <<= 1) {
if(_mode.visCode & mask) {
this->tone(RADIOLIB_SSTV_TONE_VIS_1, RADIOLIB_SSTV_HEADER_BIT_LENGTH);
parityCount++;
} else {
this->tone(RADIOLIB_SSTV_TONE_VIS_0, RADIOLIB_SSTV_HEADER_BIT_LENGTH);
}
}
// VIS parity
if(parityCount % 2 == 0) {
// even parity
this->tone(RADIOLIB_SSTV_TONE_VIS_0, RADIOLIB_SSTV_HEADER_BIT_LENGTH);
} else {
// odd parity
this->tone(RADIOLIB_SSTV_TONE_VIS_1, RADIOLIB_SSTV_HEADER_BIT_LENGTH);
}
// VIS stop bit
this->tone(RADIOLIB_SSTV_TONE_BREAK, RADIOLIB_SSTV_HEADER_BIT_LENGTH);
}
void SSTVClient::sendLine(uint32_t* imgLine) {
// check first line flag in Scottie modes
if(_firstLine && ((_mode.visCode == RADIOLIB_SSTV_SCOTTIE_1) || (_mode.visCode == RADIOLIB_SSTV_SCOTTIE_2) || (_mode.visCode == RADIOLIB_SSTV_SCOTTIE_DX))) {
_firstLine = false;
// send start sync tone
this->tone(RADIOLIB_SSTV_TONE_BREAK, 9000);
}
// send all tones in sequence
for(uint8_t i = 0; i < _mode.numTones; i++) {
if((_mode.tones[i].type == tone_t::GENERIC) && (_mode.tones[i].len > 0)) {
// sync/porch tones
this->tone(_mode.tones[i].freq, _mode.tones[i].len);
} else {
// scan lines
for(uint16_t j = 0; j < _mode.width; j++) {
uint32_t color = imgLine[j];
switch(_mode.tones[i].type) {
case(tone_t::SCAN_RED):
color &= 0x00FF0000;
color >>= 16;
break;
case(tone_t::SCAN_GREEN):
color &= 0x0000FF00;
color >>= 8;
break;
case(tone_t::SCAN_BLUE):
color &= 0x000000FF;
break;
case(tone_t::GENERIC):
break;
}
this->tone(RADIOLIB_SSTV_TONE_BRIGHTNESS_MIN + ((float)color * 3.1372549), _mode.scanPixelLen);
}
}
}
}
uint16_t SSTVClient::getPictureHeight() const {
return(_mode.height);
}
void SSTVClient::tone(float freq, uint32_t len) {
Module* mod = _phy->getMod();
uint32_t start = mod->micros();
#if !defined(RADIOLIB_EXCLUDE_AFSK)
if(_audio != nullptr) {
_audio->tone(freq, false);
} else {
_phy->transmitDirect(_base + (freq / _phy->getFreqStep()));
}
#else
_phy->transmitDirect(_base + (freq / _phy->getFreqStep()));
#endif
while(mod->micros() - start < len) {
mod->yield();
}
}
#endif
+207
View File
@@ -0,0 +1,207 @@
#if !defined(_RADIOLIB_RADIOLIB_SSTV_H)
#define _RADIOLIB_RADIOLIB_SSTV_H
#include "../../TypeDef.h"
#if !defined(RADIOLIB_EXCLUDE_SSTV)
#include "../PhysicalLayer/PhysicalLayer.h"
#include "../AFSK/AFSK.h"
// the following implementation is based on information from
// http://www.barberdsp.com/downloads/Dayton%20Paper.pdf
// VIS codes
#define RADIOLIB_SSTV_SCOTTIE_1 60
#define RADIOLIB_SSTV_SCOTTIE_2 56
#define RADIOLIB_SSTV_SCOTTIE_DX 76
#define RADIOLIB_SSTV_MARTIN_1 44
#define RADIOLIB_SSTV_MARTIN_2 40
#define RADIOLIB_SSTV_WRASSE_SC2_180 55
#define RADIOLIB_SSTV_PASOKON_P3 113
#define RADIOLIB_SSTV_PASOKON_P5 114
#define RADIOLIB_SSTV_PASOKON_P7 115
// SSTV tones in Hz
#define RADIOLIB_SSTV_TONE_LEADER 1900
#define RADIOLIB_SSTV_TONE_BREAK 1200
#define RADIOLIB_SSTV_TONE_VIS_1 1100
#define RADIOLIB_SSTV_TONE_VIS_0 1300
#define RADIOLIB_SSTV_TONE_BRIGHTNESS_MIN 1500
#define RADIOLIB_SSTV_TONE_BRIGHTNESS_MAX 2300
// calibration header timing in us
#define RADIOLIB_SSTV_HEADER_LEADER_LENGTH 300000
#define RADIOLIB_SSTV_HEADER_BREAK_LENGTH 10000
#define RADIOLIB_SSTV_HEADER_BIT_LENGTH 30000
/*!
\struct tone_t
\brief Structure to save data about tone.
*/
struct tone_t {
/*!
\brief Tone type: GENERIC for sync and porch tones, SCAN_GREEN, SCAN_BLUE and SCAN_RED for scan lines.
*/
enum {
GENERIC = 0,
SCAN_GREEN,
SCAN_BLUE,
SCAN_RED
} type;
/*!
\brief Length of tone in us, set to 0 for picture scan tones.
*/
uint32_t len;
/*!
\brief Frequency of tone in Hz, set to 0 for picture scan tones.
*/
uint16_t freq;
};
/*!
\struct SSTVMode_t
\brief Structure to save data about supported SSTV modes.
*/
struct SSTVMode_t {
/*!
\brief Unique VIS code of the SSTV mode.
*/
uint8_t visCode;
/*!
\brief Picture width in pixels.
*/
uint16_t width;
/*!
\brief Picture height in pixels.
*/
uint16_t height;
/*!
\brief Pixel scan length in us.
*/
uint16_t scanPixelLen;
/*!
\brief Number of tones in each transmission line. Picture scan data is considered single tone.
*/
uint8_t numTones;
/*!
\brief Sequence of tones in each transmission line. This is used to create the correct encoding sequence.
*/
tone_t tones[8];
};
// all currently supported SSTV modes
extern const SSTVMode_t Scottie1;
extern const SSTVMode_t Scottie2;
extern const SSTVMode_t ScottieDX;
extern const SSTVMode_t Martin1;
extern const SSTVMode_t Martin2;
extern const SSTVMode_t Wrasse;
extern const SSTVMode_t PasokonP3;
extern const SSTVMode_t PasokonP5;
extern const SSTVMode_t PasokonP7;
/*!
\class SSTVClient
\brief Client for SSTV transmissions.
*/
class SSTVClient {
public:
/*!
\brief Constructor for 2-FSK mode.
\param phy Pointer to the wireless module providing PhysicalLayer communication.
*/
explicit SSTVClient(PhysicalLayer* phy);
#if !defined(RADIOLIB_EXCLUDE_AFSK)
/*!
\brief Constructor for AFSK mode.
\param audio Pointer to the AFSK instance providing audio.
*/
explicit SSTVClient(AFSKClient* audio);
#endif
// basic methods
/*!
\brief Initialization method for 2-FSK.
\param base Base "0 Hz tone" RF frequency to be used in MHz.
\param mode SSTV mode to be used. Currently supported modes are Scottie1, Scottie2, ScottieDX, Martin1, Martin2, Wrasse, PasokonP3, PasokonP5 and PasokonP7.
\param correction Timing correction factor, used to adjust the length of timing pulses. Less than 1.0 leads to shorter timing pulses, defaults to 1.0 (no correction).
\returns \ref status_codes
*/
int16_t begin(float base, const SSTVMode_t& mode, float correction = 1.0);
#if !defined(RADIOLIB_EXCLUDE_AFSK)
/*!
\brief Initialization method for AFSK.
\param mode SSTV mode to be used. Currently supported modes are Scottie1, Scottie2, ScottieDX, Martin1, Martin2, Wrasse, PasokonP3, PasokonP5 and PasokonP7.
\param correction Timing correction factor, used to adjust the length of timing pulses. Less than 1.0 leads to shorter timing pulses, defaults to 1.0 (no correction).
\returns \ref status_codes
*/
int16_t begin(const SSTVMode_t& mode, float correction = 1.0);
#endif
/*!
\brief Sends out tone at 1900 Hz.
*/
void idle();
/*!
\brief Sends synchronization header for the SSTV mode set in begin method.
*/
void sendHeader();
/*!
\brief Sends single picture line in the currently configured SSTV mode.
\param imgLine Image line to send, in 24-bit RGB. It is up to the user to ensure that imgLine has enough pixels to send it in the current SSTV mode.
*/
void sendLine(uint32_t* imgLine);
/*!
\brief Get picture height of the currently configured SSTV mode.
\returns Picture height of the currently configured SSTV mode in pixels.
*/
uint16_t getPictureHeight() const;
#if !defined(RADIOLIB_GODMODE)
private:
#endif
PhysicalLayer* _phy;
#if !defined(RADIOLIB_EXCLUDE_AFSK)
AFSKClient* _audio;
#endif
uint32_t _base = 0;
SSTVMode_t _mode = Scottie1;
bool _firstLine = true;
void tone(float freq, uint32_t len = 0);
};
#endif
#endif