raspikeyer/src/morse.cpp

91 lines
No EOL
3.3 KiB
C++

#include <algorithm>
#include <map>
#include <regex>
#include "morse.h"
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>
{'k', "-.--."}, // k == <KN>
{'s', "...-.-"}, // s == <SK>
{'+', ".-.-."}, // + == <AR>
{'a', "-.-.-"}, // a == <KA>
};
std::string refurbishMessage(const std::string &msg)
{
std::string msgRefurb;
msgRefurb.resize(msg.length());
// Make the message all upper case
std::transform(msg.cbegin(), msg.cend(), msgRefurb.begin(), [](unsigned char c) { return std::toupper(c); });
// Encode the special characters as we like it
msgRefurb = std::regex_replace(msgRefurb, std::regex("<BT>"), "=");
msgRefurb = std::regex_replace(msgRefurb, std::regex("<KN>"), "k");
msgRefurb = std::regex_replace(msgRefurb, std::regex("<SK>"), "s");
msgRefurb = std::regex_replace(msgRefurb, std::regex("<AR>"), "+");
msgRefurb = std::regex_replace(msgRefurb, std::regex("<KA>"), "a");
// Remove all other unknown characters
msgRefurb.erase(remove_if(msgRefurb.begin(), msgRefurb.end(),
[](const char &c) { return c != ' ' && morseCode.find(c) == morseCode.end(); }),
msgRefurb.end());
// Remove spaces, if there are too many of them
msgRefurb = std::regex_replace(msgRefurb, std::regex("(\\s+)"), " ");
return msgRefurb;
}
std::string messageToMorse(const std::string &msg)
{
std::string refMsg = refurbishMessage(msg);
std::string morseString;
for (unsigned int i = 0; i < refMsg.length(); i++) {
auto c = refMsg[i];
if (c == ' ') {
// morseString.append(" ");
morseString += '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++) {
auto m = morseCode[c][j];
if (j == 0 && i > 0 && refMsg[i - 1] != ' ') {
// morseString.append(" ");
morseString += 'c';
}
morseString += m;
if (j < morseCode[c].length() - 1) {
// morseString.append(" ");
morseString += 'i';
}
}
}
// Append word space if last char was not a blank
if (refMsg.back() != ' ') {
// morseString.append(" ");
morseString += 'w';
}
return morseString;
}