DJMFix.cpp
author František Kučera <franta-hg@frantovo.cz>
Sat, 06 Sep 2025 23:49:23 +0200
branchv_0
changeset 22 de678a266ab8
parent 19 4ed672cecc25
permissions -rw-r--r--
improved sendKeepAlive logic
franta-hg@0
     1
/**
franta-hg@0
     2
 * DJM-Fix
franta-hg@16
     3
 * Copyright © 2025 František Kučera (Frantovo.cz, GlobalCode.info)
franta-hg@0
     4
 *
franta-hg@0
     5
 * This program is free software: you can redistribute it and/or modify
franta-hg@0
     6
 * it under the terms of the GNU General Public License as published by
franta-hg@0
     7
 * the Free Software Foundation, version 3 of the License.
franta-hg@0
     8
 *
franta-hg@0
     9
 * This program is distributed in the hope that it will be useful,
franta-hg@0
    10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
franta-hg@0
    11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
franta-hg@0
    12
 * GNU General Public License for more details.
franta-hg@0
    13
 *
franta-hg@0
    14
 * You should have received a copy of the GNU General Public License
franta-hg@0
    15
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
franta-hg@0
    16
 */
franta-hg@1
    17
#include <iostream>
franta-hg@12
    18
#include <sstream>
franta-hg@5
    19
#include <iomanip>
franta-hg@2
    20
#include <thread>
franta-hg@6
    21
#include <mutex>
franta-hg@5
    22
#include <atomic>
franta-hg@2
    23
#include <chrono>
franta-hg@2
    24
#include <stdexcept>
franta-hg@6
    25
#include <vector>
franta-hg@18
    26
#include <regex>
franta-hg@1
    27
franta-hg@1
    28
#include "DJMFix.h"
franta-hg@18
    29
#include "MessageCodec.h"
franta-hg@1
    30
franta-hg@1
    31
namespace djmfix {
franta-hg@1
    32
franta-hg@12
    33
using L = djmfix::logging::Level;
franta-hg@6
    34
using Bytes = std::vector<uint8_t>;
franta-hg@16
    35
namespace chro = std::chrono;
franta-hg@6
    36
franta-hg@1
    37
class DJMFixImpl : public DJMFix {
franta-hg@1
    38
private:
franta-hg@2
    39
	MidiSender* midiSender;
franta-hg@12
    40
	djmfix::logging::Logger* logger;
franta-hg@18
    41
	MessageCodec codec;
franta-hg@13
    42
	const int keepAliveInterval = 200;
franta-hg@13
    43
	int keepAliveCounter = 0;
franta-hg@2
    44
	std::thread keepAliveThread;
franta-hg@6
    45
	std::recursive_mutex midiMutex;
franta-hg@5
    46
	std::atomic<bool> running{false};
franta-hg@5
    47
	std::atomic<bool> stopped{false};
franta-hg@8
    48
	std::atomic<bool> sendKeepAlive{false};
franta-hg@18
    49
	/**
franta-hg@18
    50
	 * Device (V10) may send multiple greeting messages.
franta-hg@18
    51
	 * It works even if we respond multiple times. But one response is enough.
franta-hg@18
    52
	 */
franta-hg@18
    53
	std::atomic<bool> greetingReceived{false};
franta-hg@18
    54
franta-hg@18
    55
	Bytes seed0 = {0x68, 0x01, 0x31, 0xFB};
franta-hg@18
    56
	Bytes seed1 = {0x29, 0x00, 0x00, 0x00, 0x23, 0x48, 0x00, 0x00};
franta-hg@8
    57
	Bytes seed2;
franta-hg@18
    58
	Bytes seed3;
franta-hg@18
    59
franta-hg@18
    60
	Bytes name1 = {0x50, 0x69, 0x6f, 0x6e, 0x65, 0x65, 0x72, 0x44, 0x4a};
franta-hg@18
    61
	Bytes name2 = {0x72, 0x65, 0x6b, 0x6f, 0x72, 0x64, 0x62, 0x6f, 0x78};
franta-hg@18
    62
franta-hg@18
    63
	Bytes hash1;
franta-hg@18
    64
	Bytes hash2;
franta-hg@18
    65
franta-hg@19
    66
	uint8_t model = 0x17;
franta-hg@2
    67
franta-hg@2
    68
	void run() {
franta-hg@2
    69
		while (!stopped) {
franta-hg@12
    70
			logger->log(L::FINE, "DJMFixImpl::run()");
franta-hg@22
    71
			if (sendKeepAlive) {
franta-hg@22
    72
				send({
franta-hg@16
    73
					0xf0, 0x00, 0x40, 0x05,
franta-hg@19
    74
					0x00, 0x00, 0x00, model,
franta-hg@16
    75
					0x00, 0x50, 0x01, 0xf7
franta-hg@16
    76
				});
franta-hg@22
    77
				keepAliveCounter++;
franta-hg@22
    78
				if (keepAliveCounter % (60 * 1000 / keepAliveInterval) == 0)
franta-hg@22
    79
					logger->log(L::INFO,
franta-hg@22
    80
						"Still sending periodic keep-alive messages "
franta-hg@22
    81
						"(each " + std::to_string(keepAliveInterval) + " ms).");
franta-hg@22
    82
			}
franta-hg@16
    83
			std::this_thread::sleep_for(chro::milliseconds(keepAliveInterval));
franta-hg@2
    84
		}
franta-hg@2
    85
	}
franta-hg@2
    86
franta-hg@18
    87
	void send(const Message& msg) {
franta-hg@18
    88
		logger->log(L::FINE, "<!-- Sent message: -->" + msg.toString());
franta-hg@18
    89
		send(codec.encode(msg));
franta-hg@18
    90
	}
franta-hg@18
    91
franta-hg@6
    92
	void send(const MidiMessage& midiMessage) {
franta-hg@6
    93
		std::lock_guard<std::recursive_mutex> lock(midiMutex);
franta-hg@6
    94
		midiSender->send(midiMessage);
franta-hg@6
    95
	}
franta-hg@6
    96
franta-hg@6
    97
	std::string toString(const Bytes& midiMessage) {
franta-hg@5
    98
		std::stringstream result;
franta-hg@16
    99
		for (uint8_t b : midiMessage)
franta-hg@16
   100
			result << std::hex << std::setw(2) << std::setfill('0') << (int) b;
franta-hg@5
   101
		return result.str();
franta-hg@5
   102
	}
franta-hg@5
   103
franta-hg@6
   104
	Bytes normalize(const Bytes& data) {
franta-hg@16
   105
		if (data.size() % 2) throw std::invalid_argument(
franta-hg@16
   106
				"Data before normalization must have even number of bytes.");
franta-hg@6
   107
		Bytes result;
franta-hg@6
   108
		result.reserve(data.size() / 2);
franta-hg@16
   109
		for (size_t i = 0; i < data.size() / 2; i++) result.push_back(
franta-hg@16
   110
				(data[i * 2] & 0x0F) << 4 | (data[i * 2 + 1] & 0x0F));
franta-hg@6
   111
		return result;
franta-hg@6
   112
	}
franta-hg@6
   113
franta-hg@8
   114
	Bytes denormalize(const Bytes& data) {
franta-hg@8
   115
		Bytes result;
franta-hg@8
   116
		result.reserve(data.size()*2);
franta-hg@8
   117
		for (size_t i = 0; i < data.size(); i++) {
franta-hg@8
   118
			result.push_back(data[i] >> 4);
franta-hg@8
   119
			result.push_back(data[i] & 0x0F);
franta-hg@8
   120
		}
franta-hg@8
   121
		return result;
franta-hg@8
   122
	}
franta-hg@8
   123
franta-hg@6
   124
	uint32_t fnv32hash(const Bytes& buff) {
franta-hg@6
   125
		uint32_t hash = 0x811c9dc5;
franta-hg@6
   126
		for (uint8_t b : buff) hash = ((b^hash) * 0x1000193);
franta-hg@6
   127
		return hash;
franta-hg@6
   128
	}
franta-hg@6
   129
franta-hg@6
   130
	Bytes toBytes(const uint32_t value) {
franta-hg@6
   131
		Bytes result;
franta-hg@6
   132
		result.reserve(4);
franta-hg@6
   133
		result.push_back(value >> 24);
franta-hg@6
   134
		result.push_back(value >> 16);
franta-hg@6
   135
		result.push_back(value >> 8);
franta-hg@6
   136
		result.push_back(value >> 0);
franta-hg@6
   137
		return result;
franta-hg@6
   138
	}
franta-hg@6
   139
franta-hg@6
   140
	bool equals(Bytes a, Bytes b) {
franta-hg@6
   141
		if (a.size() != b.size()) return false;
franta-hg@6
   142
		for (size_t i = 0; i < a.size(); i++) if (a[i] != b[i]) return false;
franta-hg@6
   143
		return true;
franta-hg@6
   144
	}
franta-hg@6
   145
franta-hg@16
   146
	template<typename T> std::vector<T> concat(
franta-hg@16
   147
			const std::vector<T>& a,
franta-hg@16
   148
			const std::vector<T>& b,
franta-hg@16
   149
			const std::vector<T>& c = {}) //
franta-hg@16
   150
	{
franta-hg@6
   151
		std::vector<T> result;
franta-hg@6
   152
		result.reserve(a.size() + b.size() + c.size());
franta-hg@6
   153
		for (size_t i = 0; i < a.size(); i++) result.push_back(a[i]);
franta-hg@6
   154
		for (size_t i = 0; i < b.size(); i++) result.push_back(b[i]);
franta-hg@6
   155
		for (size_t i = 0; i < c.size(); i++) result.push_back(c[i]);
franta-hg@6
   156
		return result;
franta-hg@6
   157
	}
franta-hg@6
   158
franta-hg@16
   159
	template<typename T>
franta-hg@16
   160
	std::vector<T> xOR(const std::vector<T>& a, const std::vector<T>& b) {
franta-hg@16
   161
		if (a.size() != b.size()) throw std::invalid_argument(
franta-hg@16
   162
				"Both must be the same length when doing XOR.");
franta-hg@6
   163
		std::vector<T> result;
franta-hg@6
   164
		result.reserve(a.size());
franta-hg@6
   165
		for (size_t i = 0; i < a.size(); i++) result.push_back(a[i] ^ b[i]);
franta-hg@6
   166
		return result;
franta-hg@6
   167
	}
franta-hg@6
   168
franta-hg@1
   169
public:
franta-hg@1
   170
franta-hg@16
   171
	DJMFixImpl(djmfix::logging::Logger* logger)
franta-hg@16
   172
	: logger(logger ? logger : djmfix::logging::blackhole()) {
franta-hg@12
   173
	}
franta-hg@12
   174
franta-hg@1
   175
	virtual ~DJMFixImpl() override {
franta-hg@13
   176
		logger->log(L::FINER, "~DJMFixImpl()");
franta-hg@2
   177
		if (running) stop();
franta-hg@2
   178
	}
franta-hg@2
   179
franta-hg@18
   180
	void setDeviceName(std::string name) override {
franta-hg@18
   181
		logger->log(L::FINE, "DJMFixImpl::setDeviceName(" + name + ")");
franta-hg@18
   182
franta-hg@18
   183
		std::regex djm250pattern("Pioneer DJ Corporation DJM-250MK2.*");
franta-hg@19
   184
		std::regex djm450pattern("Pioneer DJ Corporation DJM-450.*");
franta-hg@18
   185
franta-hg@18
   186
		if (std::regex_match(name, djm250pattern)) {
franta-hg@18
   187
			// DJM-250MK2:
franta-hg@19
   188
			model = 0x17;
franta-hg@18
   189
			seed3 = {
franta-hg@18
   190
				0x59, 0xb5, 0x4b, 0xfe, 0xe4,
franta-hg@18
   191
				0x4a, 0x5a, 0xc8, 0xe4, 0xc5
franta-hg@18
   192
			};
franta-hg@18
   193
			logger->log(L::FINE, "Switched to DJM-250MK2 mode");
franta-hg@18
   194
		} else if (std::regex_match(name, djm450pattern)) {
franta-hg@18
   195
			// DJM-450:
franta-hg@18
   196
			// DJM-450 - not tested yet:
franta-hg@19
   197
			model = 0x13;
franta-hg@18
   198
			seed3 = {
franta-hg@22
   199
				0x99, 0xd5, 0x55, 0x43, 0x2c,
franta-hg@22
   200
				0x70, 0x53, 0x7a, 0x6f, 0x02
franta-hg@18
   201
			};
franta-hg@18
   202
			logger->log(L::FINE, "Switched to DJM-450 mode");
franta-hg@18
   203
		} else {
franta-hg@18
   204
			// DJM-V10:
franta-hg@19
   205
			model = 0x34;
franta-hg@18
   206
			seed3 = {
franta-hg@18
   207
				0x70, 0x01, 0x4d, 0x05, 0xbe,
franta-hg@18
   208
				0xf2, 0xe4, 0xde, 0x60, 0xd6
franta-hg@18
   209
			};
franta-hg@18
   210
			logger->log(L::FINE, "Switched to DJM-V10 mode");
franta-hg@18
   211
		}
franta-hg@18
   212
	}
franta-hg@18
   213
franta-hg@18
   214
	void setMidiSender(MidiSender* midiSender) override {
franta-hg@13
   215
		logger->log(L::FINER, "DJMFixImpl::setMidiSender()");
franta-hg@2
   216
		this->midiSender = midiSender;
franta-hg@1
   217
	}
franta-hg@1
   218
franta-hg@16
   219
	virtual void receive(const MidiMessage& msg) override {
franta-hg@18
   220
		// TODO: remove try/catch - there should be no unknown messages
franta-hg@18
   221
		try {
franta-hg@18
   222
			receive0(msg);
franta-hg@18
   223
		} catch (const std::exception& e) {
franta-hg@18
   224
			logger->log(L::SEVERE,
franta-hg@18
   225
					std::string("Message receiving failed: ") + e.what());
franta-hg@18
   226
		}
franta-hg@18
   227
	}
franta-hg@18
   228
franta-hg@18
   229
	virtual void receive0(const MidiMessage& msg) {
franta-hg@16
   230
		logger->log(L::FINE, "Received a message: "
franta-hg@16
   231
				"size = " + std::to_string(msg.size()) + " "
franta-hg@16
   232
				"data = " + toString(msg));
franta-hg@6
   233
		std::lock_guard<std::recursive_mutex> lock(midiMutex);
franta-hg@18
   234
		Message msgIn = codec.decode(msg);
franta-hg@5
   235
franta-hg@18
   236
		logger->log(L::FINE, "<!-- Received message: -->" + msgIn.toString());
franta-hg@7
   237
franta-hg@18
   238
		if (msgIn.type == MessageType::D11_GREETING && !greetingReceived) {
franta-hg@13
   239
			logger->log(L::INFO, "Received greeting message.");
franta-hg@19
   240
			Message msgOut(MessageType::H12_SEED1, model,{
franta-hg@18
   241
				{FieldType::F01, name1},
franta-hg@18
   242
				{FieldType::F02, name2},
franta-hg@18
   243
				{FieldType::F03, denormalize(seed1)}
franta-hg@16
   244
			});
franta-hg@18
   245
			send(msgOut);
franta-hg@18
   246
			greetingReceived = true;
franta-hg@13
   247
			logger->log(L::INFO, "Sent message with seed1.");
franta-hg@18
   248
		} else if (msgIn.type == MessageType::D13_HASH1_SEED2) {
franta-hg@18
   249
			std::vector<Field> hash1F = msgIn.findFields(FieldType::F04);
franta-hg@18
   250
			std::vector<Field> seed2F = msgIn.findFields(FieldType::F03);
franta-hg@18
   251
franta-hg@18
   252
			if (hash1F.empty()) throw std::logic_error("hash1 not found");
franta-hg@18
   253
			if (seed2F.empty()) throw std::logic_error("seed2 not found");
franta-hg@18
   254
franta-hg@18
   255
			hash1 = normalize(hash1F[0].data);
franta-hg@18
   256
			seed2 = normalize(seed2F[0].data);
franta-hg@18
   257
franta-hg@16
   258
			logger->log(L::INFO, "Received message with "
franta-hg@16
   259
					"hash1 = " + toString(hash1) + " and "
franta-hg@16
   260
					"seed2 = " + toString(seed2));
franta-hg@6
   261
franta-hg@16
   262
			Bytes hash1check =
franta-hg@16
   263
					toBytes(fnv32hash(concat(seed1, xOR(seed0, seed2))));
franta-hg@6
   264
franta-hg@6
   265
			if (equals(hash1, hash1check)) {
franta-hg@13
   266
				logger->log(L::INFO, "Verification of hash1 was successful.");
franta-hg@18
   267
				hash2 = toBytes(fnv32hash(concat(seed2, xOR(seed0, seed2))));
franta-hg@18
   268
franta-hg@19
   269
				Message msgOut(MessageType::H14_HASH2, model,{
franta-hg@18
   270
					{FieldType::F01, name1},
franta-hg@18
   271
					{FieldType::F02, name2},
franta-hg@18
   272
					{FieldType::F04, denormalize(hash2)},
franta-hg@18
   273
					{FieldType::F05, denormalize(seed3)}
franta-hg@18
   274
				});
franta-hg@18
   275
				send(msgOut);
franta-hg@13
   276
				logger->log(L::INFO, "Sent message with hash2.");
franta-hg@6
   277
			} else {
franta-hg@12
   278
				std::stringstream logMessage;
franta-hg@12
   279
				logMessage
franta-hg@13
   280
						<< "Verification of hash1 failed: "
franta-hg@16
   281
						<< " midiMessage = " << toString(msg)
franta-hg@8
   282
						<< " seed0 = " << toString(seed0)
franta-hg@8
   283
						<< " seed1 = " << toString(seed1)
franta-hg@8
   284
						<< " seed2 = " << toString(seed2)
franta-hg@8
   285
						<< " hash1 = " << toString(hash1)
franta-hg@12
   286
						<< " hash1check = " << toString(hash1check);
franta-hg@12
   287
				logger->log(L::SEVERE, logMessage.str());
franta-hg@8
   288
				// TODO: graceful death
franta-hg@6
   289
			}
franta-hg@18
   290
		} else if (msgIn.type == MessageType::D15_CONFIRMATION) {
franta-hg@8
   291
			sendKeepAlive = true;
franta-hg@16
   292
			logger->log(L::INFO, "Received acknowledgment message. "
franta-hg@16
   293
					"Started sending keep-alive messages. "
franta-hg@16
   294
					"LINE/PHONO channels should work now.");
franta-hg@18
   295
		} else {
franta-hg@18
   296
			logger->log(L::SEVERE, "Received unexpected message type.");
franta-hg@5
   297
		}
franta-hg@5
   298
franta-hg@1
   299
	}
franta-hg@1
   300
franta-hg@1
   301
	void start() override {
franta-hg@12
   302
		logger->log(L::FINE, "DJMFixImpl::start()");
franta-hg@16
   303
		if (midiSender == nullptr)
franta-hg@16
   304
			throw std::logic_error("Need a midiSender when starting DJMFix");
franta-hg@5
   305
franta-hg@16
   306
		send({
franta-hg@16
   307
			0xf0, 0x00, 0x40, 0x05,
franta-hg@19
   308
			0x00, 0x00, 0x00, model,
franta-hg@16
   309
			0x00, 0x50, 0x01, 0xf7
franta-hg@16
   310
		});
franta-hg@18
   311
franta-hg@18
   312
		// TODO: check whether this second message is neccessary for V10:
franta-hg@18
   313
		send({
franta-hg@18
   314
			0xf0, 0x00, 0x40, 0x05,
franta-hg@19
   315
			0x00, 0x00, 0x00, model,
franta-hg@18
   316
			0x00, 0x03, 0x01, 0xf7
franta-hg@18
   317
		});
franta-hg@13
   318
		logger->log(L::INFO, "Sent greeting message.");
franta-hg@2
   319
franta-hg@2
   320
		keepAliveThread = std::thread(&DJMFixImpl::run, this);
franta-hg@2
   321
		running = true;
franta-hg@2
   322
franta-hg@1
   323
	}
franta-hg@1
   324
franta-hg@1
   325
	void stop() override {
franta-hg@2
   326
		stopped = true;
franta-hg@2
   327
		keepAliveThread.join();
franta-hg@2
   328
		running = false;
franta-hg@12
   329
		logger->log(L::FINE, "DJMFixImpl::stop()");
franta-hg@1
   330
	}
franta-hg@1
   331
};
franta-hg@1
   332
franta-hg@12
   333
DJMFix* create(djmfix::logging::Logger* logger) {
franta-hg@12
   334
	return new DJMFixImpl(logger);
franta-hg@1
   335
}
franta-hg@1
   336
franta-hg@1
   337
}