DJMFix.cpp
author František Kučera <franta-hg@frantovo.cz>
Mon, 04 Jan 2021 17:11:57 +0100
branchv_0
changeset 13 334b727f7516
parent 12 15d87fdd6e6c
permissions -rw-r--r--
improved logging and error messages
     1 /**
     2  * DJM-Fix
     3  * Copyright © 2020 František Kučera (Frantovo.cz, GlobalCode.info)
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, version 3 of the License.
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. If not, see <http://www.gnu.org/licenses/>.
    16  */
    17 #include <iostream>
    18 #include <sstream>
    19 #include <iomanip>
    20 #include <thread>
    21 #include <mutex>
    22 #include <atomic>
    23 #include <chrono>
    24 #include <stdexcept>
    25 #include <vector>
    26 
    27 #include "DJMFix.h"
    28 
    29 namespace djmfix {
    30 
    31 using L = djmfix::logging::Level;
    32 using Bytes = std::vector<uint8_t>;
    33 
    34 class DJMFixImpl : public DJMFix {
    35 private:
    36 	MidiSender* midiSender;
    37 	djmfix::logging::Logger* logger;
    38 	const int keepAliveInterval = 200;
    39 	int keepAliveCounter = 0;
    40 	std::thread keepAliveThread;
    41 	std::recursive_mutex midiMutex;
    42 	std::atomic<bool> running{false};
    43 	std::atomic<bool> stopped{false};
    44 	std::atomic<bool> sendKeepAlive{false};
    45 	Bytes seed2;
    46 
    47 	void run() {
    48 		while (!stopped) {
    49 			logger->log(L::FINE, "DJMFixImpl::run()");
    50 			if (sendKeepAlive) send({0xf0, 0x00, 0x40, 0x05, 0x00, 0x00, 0x00, 0x17, 0x00, 0x50, 0x01, 0xf7});
    51 			std::this_thread::sleep_for(std::chrono::milliseconds(keepAliveInterval));
    52 			keepAliveCounter++;
    53 			if (keepAliveCounter % (60 * 1000 / keepAliveInterval) == 0) logger->log(L::INFO, "Still sending periodic keep-alive messages (each " + std::to_string(keepAliveInterval) + " ms).");
    54 		}
    55 	}
    56 
    57 	void send(const MidiMessage& midiMessage) {
    58 		std::lock_guard<std::recursive_mutex> lock(midiMutex);
    59 		midiSender->send(midiMessage);
    60 	}
    61 
    62 	std::string toString(const Bytes& midiMessage) {
    63 		std::stringstream result;
    64 		for (uint8_t b : midiMessage) result << std::hex << std::setw(2) << std::setfill('0') << (int) b;
    65 		return result.str();
    66 	}
    67 
    68 	Bytes normalize(const Bytes& data) {
    69 		if (data.size() % 2) throw std::invalid_argument("Data before normalization must have even number of bytes.");
    70 		Bytes result;
    71 		result.reserve(data.size() / 2);
    72 		for (size_t i = 0; i < data.size() / 2; i++) result.push_back((data[i * 2] & 0x0F) << 4 | (data[i * 2 + 1] & 0x0F));
    73 		return result;
    74 	}
    75 
    76 	Bytes denormalize(const Bytes& data) {
    77 		Bytes result;
    78 		result.reserve(data.size()*2);
    79 		for (size_t i = 0; i < data.size(); i++) {
    80 			result.push_back(data[i] >> 4);
    81 			result.push_back(data[i] & 0x0F);
    82 		}
    83 		return result;
    84 	}
    85 
    86 	uint32_t fnv32hash(const Bytes& buff) {
    87 		uint32_t hash = 0x811c9dc5;
    88 		for (uint8_t b : buff) hash = ((b^hash) * 0x1000193);
    89 		return hash;
    90 	}
    91 
    92 	Bytes toBytes(const uint32_t value) {
    93 		Bytes result;
    94 		result.reserve(4);
    95 		result.push_back(value >> 24);
    96 		result.push_back(value >> 16);
    97 		result.push_back(value >> 8);
    98 		result.push_back(value >> 0);
    99 		return result;
   100 	}
   101 
   102 	bool equals(Bytes a, Bytes b) {
   103 		if (a.size() != b.size()) return false;
   104 		for (size_t i = 0; i < a.size(); i++) if (a[i] != b[i]) return false;
   105 		return true;
   106 	}
   107 
   108 	template<typename T> std::vector<T> concat(const std::vector<T>& a, const std::vector<T>& b, const std::vector<T>& c = {}) {
   109 		std::vector<T> result;
   110 		result.reserve(a.size() + b.size() + c.size());
   111 		for (size_t i = 0; i < a.size(); i++) result.push_back(a[i]);
   112 		for (size_t i = 0; i < b.size(); i++) result.push_back(b[i]);
   113 		for (size_t i = 0; i < c.size(); i++) result.push_back(c[i]);
   114 		return result;
   115 	}
   116 
   117 	template<typename T> std::vector<T> xOR(const std::vector<T>& a, const std::vector<T>& b) {
   118 		if (a.size() != b.size()) throw std::invalid_argument("Both must be the same length when doing XOR.");
   119 		std::vector<T> result;
   120 		result.reserve(a.size());
   121 		for (size_t i = 0; i < a.size(); i++) result.push_back(a[i] ^ b[i]);
   122 		return result;
   123 	}
   124 
   125 public:
   126 
   127 	DJMFixImpl(djmfix::logging::Logger* logger) : logger(logger ? logger : djmfix::logging::blackhole()) {
   128 	}
   129 
   130 	virtual ~DJMFixImpl() override {
   131 		logger->log(L::FINER, "~DJMFixImpl()");
   132 		if (running) stop();
   133 	}
   134 
   135 	void setMidiSender(MidiSender* midiSender) {
   136 		logger->log(L::FINER, "DJMFixImpl::setMidiSender()");
   137 		this->midiSender = midiSender;
   138 	}
   139 
   140 	virtual void receive(const MidiMessage& midiMessage) override {
   141 		logger->log(L::FINE, "Received a message: size = " + std::to_string(midiMessage.size()) + " data = " + toString(midiMessage));
   142 		std::lock_guard<std::recursive_mutex> lock(midiMutex);
   143 
   144 
   145 		if (midiMessage.size() == 12 && midiMessage[9] == 0x11) {
   146 			logger->log(L::INFO, "Received greeting message.");
   147 			send({0xf0, 0x00, 0x40, 0x05, 0x00, 0x00, 0x00, 0x17, 0x00, 0x12, 0x2a, 0x01, 0x0b, 0x50, 0x69, 0x6f, 0x6e, 0x65, 0x65, 0x72, 0x44, 0x4a, 0x02, 0x0b, 0x72, 0x65, 0x6b, 0x6f, 0x72, 0x64, 0x62, 0x6f, 0x78, 0x03, 0x12, 0x02, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03, 0x04, 0x08, 0x00, 0x00, 0x00, 0x00, 0xf7});
   148 			logger->log(L::INFO, "Sent message with seed1.");
   149 		} else if (midiMessage.size() == 54 && midiMessage[9] == 0x13 && midiMessage[33] == 0x04 && midiMessage[43] == 0x03) {
   150 			Bytes hash1(midiMessage.begin() + 35, midiMessage.begin() + 35 + 8);
   151 			seed2 = Bytes(midiMessage.begin() + 45, midiMessage.begin() + 45 + 8);
   152 			hash1 = normalize(hash1);
   153 			seed2 = normalize(seed2);
   154 			logger->log(L::INFO, "Received message with hash1 = " + toString(hash1) + " and seed2 = " + toString(seed2));
   155 
   156 			Bytes seed0 = {0x68, 0x01, 0x31, 0xFB};
   157 			Bytes seed1 = {0x29, 0x00, 0x00, 0x00, 0x23, 0x48, 0x00, 0x00};
   158 
   159 			Bytes hash1check = toBytes(fnv32hash(concat(seed1, xOR(seed0, seed2))));
   160 
   161 			if (equals(hash1, hash1check)) {
   162 				logger->log(L::INFO, "Verification of hash1 was successful.");
   163 				Bytes hash2 = toBytes(fnv32hash(concat(seed2, xOR(seed0, seed2))));
   164 				send(concat({0xf0, 0x00, 0x40, 0x05, 0x00, 0x00, 0x00, 0x17, 0x00, 0x14, 0x38, 0x01, 0x0b, 0x50, 0x69, 0x6f, 0x6e, 0x65, 0x65, 0x72, 0x44, 0x4a, 0x02, 0x0b, 0x72, 0x65, 0x6b, 0x6f, 0x72, 0x64, 0x62, 0x6f, 0x78, 0x04, 0x0a}, concat(denormalize(hash2),{0x05, 0x16, 0x05, 0x09, 0x0b, 0x05, 0x04, 0x0b, 0x0f, 0x0e, 0x0e, 0x04, 0x04, 0x0a, 0x05, 0x0a, 0x0c, 0x08, 0x0e, 0x04, 0x0c, 0x05, 0xf7})));
   165 				logger->log(L::INFO, "Sent message with hash2.");
   166 			} else {
   167 				std::stringstream logMessage;
   168 				logMessage
   169 						<< "Verification of hash1 failed: "
   170 						<< " midiMessage = " << toString(midiMessage)
   171 						<< " seed0 = " << toString(seed0)
   172 						<< " seed1 = " << toString(seed1)
   173 						<< " seed2 = " << toString(seed2)
   174 						<< " hash1 = " << toString(hash1)
   175 						<< " hash1check = " << toString(hash1check);
   176 				logger->log(L::SEVERE, logMessage.str());
   177 				// TODO: graceful death
   178 			}
   179 		} else if (midiMessage.size() == 12 && midiMessage[9] == 0x15) {
   180 			sendKeepAlive = true;
   181 			logger->log(L::INFO, "Received acknowledgment message. Started sending keep-alive messages. LINE/PHONO channels should work now.");
   182 		}
   183 
   184 	}
   185 
   186 	void start() override {
   187 		logger->log(L::FINE, "DJMFixImpl::start()");
   188 		if (midiSender == nullptr) throw std::logic_error("Need a midiSender when starting DJMFix");
   189 
   190 		// TODO: methods for parsing and constructing messages from parts (TLV)
   191 		send({0xf0, 0x00, 0x40, 0x05, 0x00, 0x00, 0x00, 0x17, 0x00, 0x50, 0x01, 0xf7});
   192 		logger->log(L::INFO, "Sent greeting message.");
   193 
   194 		keepAliveThread = std::thread(&DJMFixImpl::run, this);
   195 		running = true;
   196 
   197 	}
   198 
   199 	void stop() override {
   200 		stopped = true;
   201 		keepAliveThread.join();
   202 		running = false;
   203 		logger->log(L::FINE, "DJMFixImpl::stop()");
   204 	}
   205 };
   206 
   207 DJMFix* create(djmfix::logging::Logger* logger) {
   208 	return new DJMFixImpl(logger);
   209 }
   210 
   211 }