/*
 * s433Server.cpp
 *
 *  Created on: 2024年4月30日
 *      Author: m
 */

#include "s433Server.h"

#include <string>
#include <unistd.h>
#include "service/BusinessConfig.h"
#include "uart/ProtocolSender.h"
#include "base/strings.hpp"

void sendAck(std::string tid) {
	Json::Value sendAck;
	sendAck["s433Type"] = S433Type::ACK;
	if (tid != "") {
		sendAck["tid"] = tid;
	}
	else {
		sendAck["tid"] = base::format("t%d",TimeHelper::getCurrentTime());
	}

    Json::FastWriter writer;
    const std::string jsonStr = writer.write(sendAck);

//    sendProtocolTo(UART_TTYS1, jsonStr);
    s433Send(jsonStr, 1, 1);
}

void s433MsgSend(S433Msg model){
	//0.5秒后再发
	std::string sendMsg = model.msg;
	if (model.route == 1) {
		sendProtocolTo(UART_TTYS1, sendMsg);
	}
	else if (model.route == 2) {
		sendProtocolTo(UART_TTYS1, (byte*)(sendMsg.c_str()), strlen(sendMsg.c_str()));
	}
	model.count = model.count - 1;
	if (model.count > 0){
		//发送次数循环
		s433MsgSend(model);
	}
}

void threadS433Send() {
	std::thread backend([](){
		S433Msg model = getS433Msg();
		if (model.count>0){
			s433MsgSend(model);

			usleep(1000 * 1000);
			//多个消息时排队循环
			threadS433Send();
		}
	});
	backend.detach();
	return;
}


void s433Send(const std::string msg, int count, int route) {
	bool _isS433Empty = isS433Empty();

	addS433Msg(msg, count, route);
	if (_isS433Empty) {
		threadS433Send();
	}
}


