#include "SH_stream_tcp.h"

#define PACKET_SIGN ushort(0xFED0)


SHStreamTCP::SHStreamTCP(PIIODevice * dev): PIStreamPacker(dev) {
	createCryptKey("SHS_tcp");
	//setPacketSign(0xAFBD);
	//setCryptFragmentationEnabled(true);
	id = last_counter = send_counter = last_rid = 0;
	check_hdr = was_error = false;
}


void SHStreamTCP::send(const PIByteArray & data) {
	if (data.isEmpty()) return;
	PIByteArray ba;
	ba << PACKET_SIGN << id << ++send_counter;
	ba.append(data);
	PIStreamPacker::send(ba);
}


void SHStreamTCP::packetReceived(PIByteArray data) {
	if (data.size() < 10) return;
	//piCoutObj << "packetReceived";
	ushort sign = 0;
	uint rcounter = 0;
	last_rid = 0;
	data >> sign >> last_rid >> rcounter;
	if (sign != PACKET_SIGN) return;
	if (check_hdr) {
		if ((last_rid != id) || (rcounter != (last_counter + 1))) {
			was_error = true;
			return;
		}
	}
	last_counter = rcounter;
	packetReceivedSH(data);
}
