raspikeyer/src/morse.cpp

109 lines
No EOL
3.5 KiB
C++

#include <algorithm>
#include <map>
#include <regex>
#include "morse.h"
static std::map<char, std::string> morseCode = {
{'A', ".-"}, {'B', "-..."}, {'C', "-.-."}, {'D', "-.."}, {'E', "."}, {'F', "..-."},
{'G', "--."}, {'H', "...."}, {'I', ".."}, {'J', ".---"}, {'K', "-.-"}, {'L', ".-.."},
{'M', "--"}, {'N', "-."}, {'O', "---"}, {'P', ".--."}, {'Q', "--.-"}, {'R', ".-."},
{'S', "..."}, {'T', "-"}, {'U', "..-"}, {'V', "...-"}, {'W', ".--"}, {'X', "-..-"},
{'Y', "-.--"}, {'Z', "--.."}, {'1', ".----"}, {'2', "..---"}, {'3', "...--"}, {'4', "....-"},
{'5', "....."}, {'6', "-...."}, {'7', "--..."}, {'8', "---.."}, {'9', "----."}, {'0', "-----"},
{',', "--..--"}, {'.', ".-.-.-"}, {'?', "..--.."}, {'/', "-..-."}, {'-', "-....-"}, {':', "---..."},
{'&', ".-..."}, {'\'', ".----."}, {'@', ".--.-."}, {')', "-.--.-"}, {'(', "-.--."}, {'\"', ".-..-."},
{'=', "-...-"}, // '=' == <BT>
{'b', "-...-.-"}, // '=' == <BK>
{'k', "-.--."}, // k == <KN>
{'s', "...-.-"}, // s == <SK>
{'+', ".-.-."}, // + == <AR>
{'a', "-.-.-"}, // a == <KA>
};
void refurbishMessage(std::string &msg)
{
// Make the message all upper case
std::transform(msg.begin(), msg.end(), msg.begin(), ::toupper);
// Encode the special characters as we like it
msg = std::regex_replace(msg, std::regex("<BT>"), "=");
msg = std::regex_replace(msg, std::regex("<BK>"), "b");
msg = std::regex_replace(msg, std::regex("<KN>"), "k");
msg = std::regex_replace(msg, std::regex("<SK>"), "s");
msg = std::regex_replace(msg, std::regex("<AR>"), "+");
msg = std::regex_replace(msg, std::regex("<KA>"), "a");
// Remove all other unknown characters
msg.erase(remove_if(msg.begin(), msg.end(),
[](const char &c) { return c != ' ' && morseCode.find(c) == morseCode.end(); }),
msg.end());
// Remove spaces, if there are too many of them
msg = std::regex_replace(msg, std::regex("(\\s+)"), " ");
}
std::string messageToMorse(std::string &msg)
{
refurbishMessage(msg);
std::string morseString {};
for (unsigned int i = 0; i < msg.length(); i++) {
char c = msg[i];
if (c == ' ') {
morseString.push_back('w');
continue;
}
// Ignore and continue with next char, if not found
auto search = morseCode.find(c);
if (search == morseCode.end()) {
continue;
}
for (unsigned int j = 0; j < morseCode[c].length(); j++) {
char m = morseCode[c][j];
if (j == 0 && i > 0 && msg[i - 1] != ' ') {
morseString.push_back('c');
}
morseString += m;
if (j < morseCode[c].length() - 1) {
morseString.push_back('i');
}
}
}
// Append word space if last char was not a blank
if (msg.back() != ' ') {
morseString.push_back('w');
}
return morseString;
}
std::string charToMorse(char ch) {
std::string morseString {};
if (ch == ' ') {
morseString.push_back('w');
return morseString;
}
for (unsigned int j = 0; j < morseCode[ch].length(); j++) {
char m = morseCode[ch][j];
morseString += m;
if (j < morseCode[ch].length() - 1) {
morseString.push_back('i');
}
}
morseString.push_back('c');
return morseString;
}