formatting

This commit is contained in:
DashyFox 2024-03-15 16:08:06 +03:00
parent 3e3601e009
commit 8d0f45ddf1
7 changed files with 689 additions and 468 deletions

View File

@ -22,7 +22,7 @@
IR_Decoder decForward(2, 555); IR_Decoder decForward(2, 555);
IR_Decoder decBackward(3, 777); IR_Decoder decBackward(3, 777);
IR_Encoder encForward(42, &decBackward); IR_Encoder encForward(42/* , &decBackward */);
// IR_Encoder encBackward(321, encBackward_PIN); // IR_Encoder encBackward(321, encBackward_PIN);
// IR_Encoder encTree(325, A2); // IR_Encoder encTree(325, A2);
@ -32,9 +32,9 @@ void decForwardISR() {
decForward.isr(); decForward.isr();
} }
void decBackwardISR() { // void decBackwardISR() {
decBackward.isr(); // decBackward.isr();
} // }
static uint8_t* portOut; static uint8_t* portOut;
ISR(TIMER2_COMPA_vect) { ISR(TIMER2_COMPA_vect) {
@ -57,7 +57,7 @@ uint8_t data3 [] = { 42 , 127, 137 };
uint8_t data4 [] = { 42 , 127, 137, 255 }; uint8_t data4 [] = { 42 , 127, 137, 255 };
uint32_t loopTimer; uint32_t loopTimer;
uint8_t sig = 255; uint8_t sig = 0;
uint16_t targetAddr = IR_Broadcast; uint16_t targetAddr = IR_Broadcast;
Timer t1(500, millis, []() { Timer t1(500, millis, []() {
@ -177,12 +177,12 @@ void setup() {
IR_DecoderRaw* blindFromForward [] { &decForward, &decBackward }; // IR_DecoderRaw* blindFromForward [] { &decForward, &decBackward };
encForward.setBlindDecoders(blindFromForward, sizeof(blindFromForward) / sizeof(IR_DecoderRaw*)); // encForward.setBlindDecoders(blindFromForward, sizeof(blindFromForward) / sizeof(IR_DecoderRaw*));
attachInterrupt(0, decForwardISR, CHANGE); // D2 attachInterrupt(0, decForwardISR, CHANGE); // D2
attachInterrupt(1, decBackwardISR, CHANGE); // D3 // attachInterrupt(1, decBackwardISR, CHANGE); // D3
} }
void loop() { void loop() {
@ -193,7 +193,7 @@ void loop() {
decBackward.tick(); decBackward.tick();
status(decForward); status(decForward);
status(decBackward); // status(decBackward);
// Serial.println(micros() - loopTimer); // Serial.println(micros() - loopTimer);

View File

@ -3,7 +3,8 @@
#include "PacketTypes.h" #include "PacketTypes.h"
#include "IR_Encoder.h" #include "IR_Encoder.h"
class IR_Decoder : public IR_DecoderRaw { class IR_Decoder : public IR_DecoderRaw
{
uint32_t acceptSendTimer; uint32_t acceptSendTimer;
bool isWaitingAcceptSend; bool isWaitingAcceptSend;
uint16_t addrAcceptSendTo; uint16_t addrAcceptSendTo;
@ -12,23 +13,25 @@ class IR_Decoder : public IR_DecoderRaw {
uint8_t acceptCustomByte; uint8_t acceptCustomByte;
public: public:
PacketTypes::Data gotData; PacketTypes::Data gotData;
PacketTypes::DataBack gotBackData; PacketTypes::DataBack gotBackData;
PacketTypes::Accept gotAccept; PacketTypes::Accept gotAccept;
PacketTypes::Request gotRequest; PacketTypes::Request gotRequest;
PacketTypes::BasePack gotRaw; PacketTypes::BasePack gotRaw;
IR_Decoder(const uint8_t isrPin, uint16_t addr, IR_Encoder* encPair = nullptr) : IR_DecoderRaw(isrPin, addr, encPair) {} IR_Decoder(const uint8_t isrPin, uint16_t addr, IR_Encoder *encPair = nullptr) : IR_DecoderRaw(isrPin, addr, encPair) {}
void tick() { void tick()
{
IR_DecoderRaw::tick(); IR_DecoderRaw::tick();
if (availableRaw()) { if (availableRaw())
#ifdef IRDEBUG_INFO {
#ifdef IRDEBUG_INFO
Serial.println("PARSING RAW DATA"); Serial.println("PARSING RAW DATA");
#endif #endif
isWaitingAcceptSend = false; isWaitingAcceptSend = false;
switch (packInfo.buffer[0] >> 5 & IR_MASK_MSG_TYPE) { switch (packInfo.buffer[0] >> 5 & IR_MASK_MSG_TYPE)
{
case IR_MSG_DATA_ACCEPT: case IR_MSG_DATA_ACCEPT:
case IR_MSG_DATA_NOACCEPT: case IR_MSG_DATA_NOACCEPT:
gotData.set(&packInfo, id); gotData.set(&packInfo, id);
@ -47,24 +50,29 @@ public:
default: default:
break; break;
} }
if (gotData.isAvailable && (gotData.getMsgType() == IR_MSG_DATA_ACCEPT)) { if (gotData.isAvailable && (gotData.getMsgType() == IR_MSG_DATA_ACCEPT))
{
acceptSendTimer = millis(); acceptSendTimer = millis();
addrAcceptSendTo = gotData.getAddrFrom(); addrAcceptSendTo = gotData.getAddrFrom();
acceptCustomByte = crc8(gotData.getDataPrt(), 0, gotData.getDataSize(), poly1); acceptCustomByte = crc8(gotData.getDataPrt(), 0, gotData.getDataSize(), poly1);
if (addrAcceptSendTo && addrAcceptSendTo < IR_Broadcast) isWaitingAcceptSend = true; if (addrAcceptSendTo && addrAcceptSendTo < IR_Broadcast)
isWaitingAcceptSend = true;
} }
gotRaw.set(&packInfo, id); gotRaw.set(&packInfo, id);
} }
if (isWaitingAcceptSend && millis() - acceptSendTimer > 75) { if (isWaitingAcceptSend && millis() - acceptSendTimer > 75)
{
encoder->sendAccept(addrAcceptSendTo, acceptCustomByte); encoder->sendAccept(addrAcceptSendTo, acceptCustomByte);
isWaitingAcceptSend = false; isWaitingAcceptSend = false;
} }
} }
void setAcceptDelay(uint16_t acceptDelay) { void setAcceptDelay(uint16_t acceptDelay)
{
this->acceptDelay = acceptDelay; this->acceptDelay = acceptDelay;
} }
uint16_t getAcceptDelay() { uint16_t getAcceptDelay()
{
return this->acceptDelay; return this->acceptDelay;
} }
}; };

View File

@ -1,43 +1,53 @@
#include "IR_DecoderRaw.h" #include "IR_DecoderRaw.h"
#include "IR_Encoder.h" #include "IR_Encoder.h"
IR_DecoderRaw::IR_DecoderRaw(const uint8_t isrPin, uint16_t addr, IR_Encoder *encPair = nullptr) : isrPin(isrPin), encoder(encPair)
IR_DecoderRaw::IR_DecoderRaw(const uint8_t isrPin, uint16_t addr, IR_Encoder* encPair = nullptr) : isrPin(isrPin), encoder(encPair) { {
id = addr; id = addr;
prevRise = prevFall = prevPrevFall = prevPrevRise = 0; prevRise = prevFall = prevPrevFall = prevPrevRise = 0;
if (encPair != nullptr) { if (encPair != nullptr)
{
encPair->decPair = this; encPair->decPair = this;
} }
} }
//////////////////////////////////// isr /////////////////////////////////////////// //////////////////////////////////// isr ///////////////////////////////////////////
void IR_DecoderRaw::isr() { void IR_DecoderRaw::isr()
if (isPairSending) return; {
if (isPairSending)
return;
subBuffer[currentSubBufferIndex].next = nullptr; subBuffer[currentSubBufferIndex].next = nullptr;
subBuffer[currentSubBufferIndex].dir = (PIND >> isrPin) & 1; subBuffer[currentSubBufferIndex].dir = (PIND >> isrPin) & 1;
subBuffer[currentSubBufferIndex].time = micros(); subBuffer[currentSubBufferIndex].time = micros();
if (firstUnHandledFront == nullptr) { if (firstUnHandledFront == nullptr)
{
firstUnHandledFront = &subBuffer[currentSubBufferIndex]; // Если нет необработанных данных - добавляем их firstUnHandledFront = &subBuffer[currentSubBufferIndex]; // Если нет необработанных данных - добавляем их
isSubBufferOverflow = false; isSubBufferOverflow = false;
} else { }
if (firstUnHandledFront == &subBuffer[currentSubBufferIndex]) { // Если контроллер не успел обработать новый сигнал, принудительно пропускаем его else
{
if (firstUnHandledFront == &subBuffer[currentSubBufferIndex])
{ // Если контроллер не успел обработать новый сигнал, принудительно пропускаем его
firstUnHandledFront = firstUnHandledFront->next; firstUnHandledFront = firstUnHandledFront->next;
isSubBufferOverflow = true; isSubBufferOverflow = true;
#ifdef IRDEBUG_INFO #ifdef IRDEBUG_INFO
// Serial.println(); // Serial.println();
Serial.println(" ISR BUFFER OVERFLOW "); Serial.println(" ISR BUFFER OVERFLOW ");
// Serial.println(); // Serial.println();
#endif #endif
} }
} }
if (lastFront == nullptr) { if (lastFront == nullptr)
{
lastFront = &subBuffer[currentSubBufferIndex]; lastFront = &subBuffer[currentSubBufferIndex];
} else { }
else
{
lastFront->next = &subBuffer[currentSubBufferIndex]; lastFront->next = &subBuffer[currentSubBufferIndex];
lastFront = &subBuffer[currentSubBufferIndex]; lastFront = &subBuffer[currentSubBufferIndex];
} }
@ -47,11 +57,12 @@ void IR_DecoderRaw::isr() {
//////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////
void IR_DecoderRaw::firstRX() { void IR_DecoderRaw::firstRX()
{
#ifdef IRDEBUG_INFO #ifdef IRDEBUG_INFO
Serial.print("\nRX>"); Serial.print("\nRX>");
#endif #endif
errors.reset(); errors.reset();
packSize = 0; packSize = 0;
@ -71,64 +82,92 @@ void IR_DecoderRaw::firstRX() {
memset(dataBuffer, 0x00, dataByteSizeMax); memset(dataBuffer, 0x00, dataByteSizeMax);
} }
void IR_DecoderRaw::listenStart() { void IR_DecoderRaw::listenStart()
if (isRecive && ((micros() - prevRise) > IR_timeout * 2)) { {
if (isRecive && ((micros() - prevRise) > IR_timeout * 2))
{
// Serial.print("\nlis>"); // Serial.print("\nlis>");
isRecive = false; isRecive = false;
firstRX(); firstRX();
} }
} }
void IR_DecoderRaw::tick() { void IR_DecoderRaw::tick()
{
FrontStorage currentFront; FrontStorage currentFront;
uint8_t oldSREG = SREG; uint8_t oldSREG = SREG;
cli(); cli();
listenStart(); listenStart();
if (firstUnHandledFront == nullptr) { isSubBufferOverflow = false; SREG = oldSREG; return; } //Если данных нет - ничего не делаем if (firstUnHandledFront == nullptr)
currentFront = *((FrontStorage*)firstUnHandledFront); //найти следующий необработанный фронт/спад {
isSubBufferOverflow = false;
SREG = oldSREG; SREG = oldSREG;
if (currentFront.next == nullptr) { isRecive = false; return; } return;
} // Если данных нет - ничего не делаем
currentFront = *((FrontStorage *)firstUnHandledFront); // найти следующий необработанный фронт/спад
SREG = oldSREG;
if (currentFront.next == nullptr)
{
isRecive = false;
return;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (currentFront.time > prevRise && currentFront.time - prevRise > IR_timeout * 2 && !isRecive) { // первый if (currentFront.time > prevRise && currentFront.time - prevRise > IR_timeout * 2 && !isRecive)
{ // первый
preambFrontCounter = preambFronts - 1U; preambFrontCounter = preambFronts - 1U;
if (!currentFront.dir)
if (!currentFront.dir) { {
#ifdef IRDEBUG_INFO #ifdef IRDEBUG_INFO
// Serial.print(" currentFront.time: "); Serial.print(currentFront.time); // Serial.print(" currentFront.time: "); Serial.print(currentFront.time);
// Serial.print(" currentFront.dir: "); Serial.print(currentFront.dir ? "UP" : "DOWN"); // Serial.print(" currentFront.dir: "); Serial.print(currentFront.dir ? "UP" : "DOWN");
// Serial.print(" next: "); Serial.print(currentFront.next == nullptr); // Serial.print(" next: "); Serial.print(currentFront.next == nullptr);
// Serial.print(" prevRise: "); Serial.print(prevRise); // Serial.print(" prevRise: "); Serial.print(prevRise);
// Serial.print(" SUB: "); Serial.println(currentFront.time - prevRise); // Serial.print(" SUB: "); Serial.println(currentFront.time - prevRise);
#endif #endif
isRecive = true; isRecive = true;
isWrongPack = false; isWrongPack = false;
} }
} }
if (preambFrontCounter) { // в преамбуле if (preambFrontCounter)
{ // в преамбуле
uint32_t risePeriod; uint32_t risePeriod;
risePeriod = currentFront.time - prevRise; risePeriod = currentFront.time - prevRise;
if (currentFront.dir && risePeriod < IR_timeout) { // __/``` ↑ и мы в внутри пакета if (currentFront.dir && risePeriod < IR_timeout)
{ // __/``` ↑ и мы в внутри пакета
if (risePeriod < riseTimeMin << 1) { // fix рваной единицы if (risePeriod < riseTimeMin << 1)
{ // fix рваной единицы
preambFrontCounter += 2; preambFrontCounter += 2;
errors.other++; errors.other++;
} else {
if (freeFrec) { riseSyncTime = (riseSyncTime + risePeriod / 2) / 2; } // tuner
} }
} else { /* riseSyncTime = bitTime; */ } // сброс тюнера else
{
if (freeFrec)
{
riseSyncTime = (riseSyncTime + risePeriod / 2) / 2;
} // tuner
}
}
else
{ /* riseSyncTime = bitTime; */
} // сброс тюнера
preambFrontCounter--; preambFrontCounter--;
// Serial.print("preambFrontCounter: "); Serial.println(preambFrontCounter); // Serial.print("preambFrontCounter: "); Serial.println(preambFrontCounter);
} else { }
if (isPreamb) {// первый фронт после else
{
if (isPreamb)
{ // первый фронт после
// gotTune.set(riseSyncTime); // gotTune.set(riseSyncTime);
} }
isPreamb = false; isPreamb = false;
} }
// определить направление фронта // определить направление фронта
if (currentFront.dir) { // Если __/``` ↑ if (currentFront.dir)
{ // Если __/``` ↑
uint16_t risePeriod = currentFront.time - prevRise; uint16_t risePeriod = currentFront.time - prevRise;
uint16_t highTime = currentFront.time - prevFall; uint16_t highTime = currentFront.time - prevFall;
@ -139,176 +178,214 @@ void IR_DecoderRaw::tick() {
int8_t allCount = 0; int8_t allCount = 0;
bool invertErr = false; bool invertErr = false;
if (!isPreamb) { if (!isPreamb)
if (risePeriod < IR_timeout && !isBufferOverflow && risePeriod > riseTimeMin && !isWrongPack) { {
if (risePeriod < IR_timeout && !isBufferOverflow && risePeriod > riseTimeMin && !isWrongPack)
{
// Мы в пределах таймаута и буффер не переполнен и fix дроблёных единиц // Мы в пределах таймаута и буффер не переполнен и fix дроблёных единиц
if (aroundRise(risePeriod)) { // тактирование есть, сигнал хороший - без ошибок(?) if (aroundRise(risePeriod))
{ // тактирование есть, сигнал хороший - без ошибок(?)
if (highTime > riseTimeMin >> 1) { // 1 if (highTime > riseTimeMin >> 1)
#ifdef IRDEBUG { // 1
#ifdef IRDEBUG
digitalWrite(wrHigh, 1); digitalWrite(wrHigh, 1);
#endif #endif
writeToBuffer(HIGH); writeToBuffer(HIGH);
} else { // 0 }
#ifdef IRDEBUG else
{ // 0
#ifdef IRDEBUG
digitalWrite(wrLow, 1); digitalWrite(wrLow, 1);
#endif #endif
writeToBuffer(LOW); writeToBuffer(LOW);
} }
}
} else { // пропущены такты! сигнал средний // ошибка пропуска else
{ // пропущены такты! сигнал средний // ошибка пропуска
highCount = ceil_div(highTime, riseTime); // предполагаемое колличество HIGH битов highCount = ceil_div(highTime, riseTime); // предполагаемое колличество HIGH битов
lowCount = ceil_div(lowTime, riseTime); // предполагаемое колличество LOW битов lowCount = ceil_div(lowTime, riseTime); // предполагаемое колличество LOW битов
allCount = ceil_div(risePeriod, riseTime); // предполагаемое колличество всего битов allCount = ceil_div(risePeriod, riseTime); // предполагаемое колличество всего битов
if (highCount == 0 && highTime > riseTime / 3) { // fix короткой единицы (?)после пропуска нулей(?) if (highCount == 0 && highTime > riseTime / 3)
{ // fix короткой единицы (?)после пропуска нулей(?)
highCount++; highCount++;
errors.other++; errors.other++;
#ifdef IRDEBUG #ifdef IRDEBUG
errPulse(errOut, 2); errPulse(errOut, 2);
#endif #endif
} }
if (lowCount + highCount > allCount) { // fix ошибочных сдвигов if (lowCount + highCount > allCount)
if (lowCount > highCount) { // Лишние нули { // fix ошибочных сдвигов
if (lowCount > highCount)
{ // Лишние нули
lowCount = allCount - highCount; lowCount = allCount - highCount;
errors.lowSignal += lowCount; errors.lowSignal += lowCount;
#ifdef IRDEBUG #ifdef IRDEBUG
errPulse(errOut, 3); errPulse(errOut, 3);
#endif #endif
} else if (lowCount < highCount) { // Лишние единицы }
else if (lowCount < highCount)
{ // Лишние единицы
highCount = allCount - lowCount; highCount = allCount - lowCount;
errors.highSignal += highCount; errors.highSignal += highCount;
#ifdef IRDEBUG #ifdef IRDEBUG
errPulse(errOut, 4); errPulse(errOut, 4);
#endif #endif
// неизвестный случай Инверсит след бит или соседние // неизвестный случай Инверсит след бит или соседние
// Очень редко // Очень редко
// TODO: Отловить проверить // TODO: Отловить проверить
} else if (lowCount == highCount) { }
else if (lowCount == highCount)
{
invertErr = true; invertErr = true;
// Serial.print("..."); // Serial.print("...");
errors.other += allCount; errors.other += allCount;
} }
// errorCounter += allCount; // errorCounter += allCount;
} }
// errorCounter += allCount; // errorCounter += allCount;
// errors.other+=allCount; // errors.other+=allCount;
if (lowCount < highCount) { if (lowCount < highCount)
{
errors.highSignal += highCount; errors.highSignal += highCount;
} else { }
else
{
errors.lowSignal += lowCount; errors.lowSignal += lowCount;
} }
#ifdef IRDEBUG #ifdef IRDEBUG
errPulse(errOut, 1); errPulse(errOut, 1);
#endif #endif
for (int8_t i = 0; i < lowCount && 8 - i; i++) { // отправка LOW битов, если есть for (int8_t i = 0; i < lowCount && 8 - i; i++)
if (i == lowCount - 1 && invertErr) { { // отправка LOW битов, если есть
if (i == lowCount - 1 && invertErr)
{
invertErr = false; invertErr = false;
writeToBuffer(!LOW); writeToBuffer(!LOW);
#ifdef IRDEBUG #ifdef IRDEBUG
digitalWrite(wrLow, 1); digitalWrite(wrLow, 1);
#endif #endif
} else { }
else
{
writeToBuffer(LOW); writeToBuffer(LOW);
#ifdef IRDEBUG #ifdef IRDEBUG
digitalWrite(wrLow, 1); digitalWrite(wrLow, 1);
#endif #endif
} }
} }
for (int8_t i = 0; i < highCount && 8 - i; i++) { // отправка HIGH битов, если есть for (int8_t i = 0; i < highCount && 8 - i; i++)
if (i == highCount - 1 && invertErr) { { // отправка HIGH битов, если есть
if (i == highCount - 1 && invertErr)
{
invertErr = false; invertErr = false;
writeToBuffer(!HIGH); writeToBuffer(!HIGH);
#ifdef IRDEBUG #ifdef IRDEBUG
digitalWrite(wrLow, 1); digitalWrite(wrLow, 1);
#endif #endif
} else { }
else
{
writeToBuffer(HIGH); writeToBuffer(HIGH);
#ifdef IRDEBUG #ifdef IRDEBUG
digitalWrite(wrHigh, 1); digitalWrite(wrHigh, 1);
#endif #endif
} }
} }
} }
#ifdef IRDEBUG #ifdef IRDEBUG
digitalWrite(wrHigh, 0); digitalWrite(wrHigh, 0);
digitalWrite(wrLow, 0); digitalWrite(wrLow, 0);
#endif #endif
} }
} }
if (risePeriod > riseTimeMax / 2 || highCount || lowCount) { // комплексный фикс рваной единицы if (risePeriod > riseTimeMax / 2 || highCount || lowCount)
{ // комплексный фикс рваной единицы
prevPrevRise = prevRise; prevPrevRise = prevRise;
prevRise = currentFront.time; prevRise = currentFront.time;
} else {
errors.other++;
#ifdef IRDEBUG
errPulse(errOut, 5);
#endif
} }
else
{
errors.other++;
#ifdef IRDEBUG
errPulse(errOut, 5);
#endif
}
}
else
{ // Если ```\__ ↓
} else { // Если ```\__ ↓ if (currentFront.time - prevFall > riseTimeMin)
{
if (currentFront.time - prevFall > riseTimeMin) {
prevPrevFall = prevFall; prevPrevFall = prevFall;
prevFall = currentFront.time; prevFall = currentFront.time;
} else { }
#ifdef IRDEBUG else
//errPulse(errOut, 5); {
#endif #ifdef IRDEBUG
// errPulse(errOut, 5);
#endif
} }
} }
if (isPreamb && preambFrontCounter <= 0) { if (isPreamb && preambFrontCounter <= 0)
{
prevRise = currentFront.time + riseTime; prevRise = currentFront.time + riseTime;
} }
#ifdef IRDEBUG #ifdef IRDEBUG
digitalWrite(writeOp, isPreamb); digitalWrite(writeOp, isPreamb);
#endif #endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////
oldSREG = SREG; oldSREG = SREG;
cli(); cli();
if (firstUnHandledFront != nullptr) { if (firstUnHandledFront != nullptr)
firstUnHandledFront = firstUnHandledFront->next; //переместить флаг на следующий элемент для обработки (next or nullptr) {
firstUnHandledFront = firstUnHandledFront->next; // переместить флаг на следующий элемент для обработки (next or nullptr)
} }
SREG = oldSREG; SREG = oldSREG;
} }
void IR_DecoderRaw::writeToBuffer(bool bit) { void IR_DecoderRaw::writeToBuffer(bool bit)
if (i_dataBuffer > dataByteSizeMax * 8) {// проверка переполнения {
//TODO: Буффер переполнен! if (i_dataBuffer > dataByteSizeMax * 8)
#ifdef IRDEBUG_INFO { // проверка переполнения
// TODO: Буффер переполнен!
#ifdef IRDEBUG_INFO
Serial.println("OverBuf"); Serial.println("OverBuf");
#endif #endif
isBufferOverflow = true; isBufferOverflow = true;
} }
if (isBufferOverflow || isPreamb || isWrongPack) { if (isBufferOverflow || isPreamb || isWrongPack)
{
isRecive = false; isRecive = false;
return; return;
} }
// Переключение флага, data или syncBit // Переключение флага, data или syncBit
if (bufBitPos == nextControlBit) { if (bufBitPos == nextControlBit)
{
nextControlBit += (isData ? syncBits : bitPerByte); // маркер следующего переключения nextControlBit += (isData ? syncBits : bitPerByte); // маркер следующего переключения
isData = !isData; isData = !isData;
i_syncBit = 0; // сброс счетчика битов синхронизации i_syncBit = 0; // сброс счетчика битов синхронизации
err_syncBit = 0; // сброс счетчика ошибок синхронизации err_syncBit = 0; // сброс счетчика ошибок синхронизации
#ifdef IRDEBUG_INFO #ifdef IRDEBUG_INFO
Serial.print(" "); Serial.print(" ");
#endif #endif
} }
if (isData) { // Запись битов в dataBuffer if (isData)
#ifdef IRDEBUG_INFO { // Запись битов в dataBuffer
#ifdef IRDEBUG_INFO
Serial.print(bit); Serial.print(bit);
#endif #endif
// if (i_dataBuffer % 8 == 7) { // if (i_dataBuffer % 8 == 7) {
// // Serial.print("+"); // // Serial.print("+");
@ -317,15 +394,21 @@ void IR_DecoderRaw::writeToBuffer(bool bit) {
dataBuffer[(i_dataBuffer / 8)] |= bit << (7 - i_dataBuffer % 8); // Запись в буффер dataBuffer[(i_dataBuffer / 8)] |= bit << (7 - i_dataBuffer % 8); // Запись в буффер
i_dataBuffer++; i_dataBuffer++;
bufBitPos++; bufBitPos++;
} else { }
else
{
//********************************* Проверка контрольных sync битов*******************************// //********************************* Проверка контрольных sync битов*******************************//
////////////////////// Исправление лишнего нуля /////////////////////// ////////////////////// Исправление лишнего нуля ///////////////////////
if (i_syncBit == 0) { // Первый бит синхронизации if (i_syncBit == 0)
{ // Первый бит синхронизации
// Serial.print("~"); // Serial.print("~");
if (bit != (dataBuffer[((i_dataBuffer - 1) / 8)] >> (7 - (i_dataBuffer - 1) % 8) & 1)) { if (bit != (dataBuffer[((i_dataBuffer - 1) / 8)] >> (7 - (i_dataBuffer - 1) % 8) & 1))
{
bufBitPos++; bufBitPos++;
i_syncBit++; i_syncBit++;
} else { }
else
{
i_syncBit = 0; i_syncBit = 0;
errors.other++; errors.other++;
// Serial.print("E"); // Serial.print("E");
@ -333,50 +416,71 @@ void IR_DecoderRaw::writeToBuffer(bool bit) {
// Serial.print("bit: "); Serial.println(bit); // Serial.print("bit: "); Serial.println(bit);
// Serial.print("dataBuffer: "); Serial.println(dataBuffer[((i_dataBuffer - 1) / 8)] & 1 << (7 - ((i_dataBuffer - 1) & ~(~0 << 3)))); // Serial.print("dataBuffer: "); Serial.println(dataBuffer[((i_dataBuffer - 1) / 8)] & 1 << (7 - ((i_dataBuffer - 1) & ~(~0 << 3))));
} }
} else { // Последующие биты синхронизации }
else
{ // Последующие биты синхронизации
// Serial.print("`"); // Serial.print("`");
bufBitPos++; bufBitPos++;
i_syncBit++; i_syncBit++;
} }
////////////////////// Проверка наличия битов синхранизации ////////////////////// ////////////////////// Проверка наличия битов синхранизации //////////////////////
if (isWrongPack = (err_syncBit >= syncBits)) { if (isWrongPack = (err_syncBit >= syncBits))
#ifdef IRDEBUG_INFO {
#ifdef IRDEBUG_INFO
Serial.print("****************"); Serial.print("****************");
#endif #endif
}; };
}//**************************************************************************************************// } //**************************************************************************************************//
// Serial.print(bit); // Serial.print(bit);
#ifdef IRDEBUG #ifdef IRDEBUG
bit ? infoPulse(writeOp, 2) : infoPulse(writeOp, 1); bit ? infoPulse(writeOp, 2) : infoPulse(writeOp, 1);
#endif #endif
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifdef IRDEBUG_INFO #ifdef IRDEBUG_INFO
if (isData) { if (isData)
if (i_dataBuffer == ((msgBytes)*bitPerByte)) { Serial.print(" -> "); Serial.print(dataBuffer[0] & IR_MASK_MSG_INFO); Serial.print(" ->"); } {
if (i_dataBuffer == ((msgBytes + addrBytes) * bitPerByte)) { Serial.print(" |"); } if (i_dataBuffer == ((msgBytes)*bitPerByte))
if (i_dataBuffer == ((msgBytes + addrBytes + addrBytes) * bitPerByte)) { Serial.print(" ->"); } {
if (i_dataBuffer == (((dataBuffer[0] & IR_MASK_MSG_INFO) - 2) * bitPerByte)) { Serial.print(" <-"); } Serial.print(" -> ");
Serial.print(dataBuffer[0] & IR_MASK_MSG_INFO);
Serial.print(" ->");
} }
#endif if (i_dataBuffer == ((msgBytes + addrBytes) * bitPerByte))
{
Serial.print(" |");
}
if (i_dataBuffer == ((msgBytes + addrBytes + addrBytes) * bitPerByte))
{
Serial.print(" ->");
}
if (i_dataBuffer == (((dataBuffer[0] & IR_MASK_MSG_INFO) - 2) * bitPerByte))
{
Serial.print(" <-");
}
}
#endif
if (!isAvailable && isData && !isWrongPack) { if (!isAvailable && isData && !isWrongPack)
if (i_dataBuffer == 8 * msgBytes) {// Ппервый байт {
if (i_dataBuffer == 8 * msgBytes)
{ // Ппервый байт
packSize = dataBuffer[0] & IR_MASK_MSG_INFO; packSize = dataBuffer[0] & IR_MASK_MSG_INFO;
#ifdef IRDEBUG_INFO #ifdef IRDEBUG_INFO
Serial.print(" ["); Serial.print(packSize); Serial.print("] "); Serial.print(" [");
#endif Serial.print(packSize);
Serial.print("] ");
#endif
} }
if (packSize && (i_dataBuffer == packSize * bitPerByte)) { // Конец if (packSize && (i_dataBuffer == packSize * bitPerByte))
#ifdef IRDEBUG_INFO { // Конец
#ifdef IRDEBUG_INFO
Serial.print(" END DATA "); Serial.print(" END DATA ");
#endif #endif
packInfo.buffer = dataBuffer; packInfo.buffer = dataBuffer;
packInfo.crc = crcValue; packInfo.crc = crcValue;
@ -392,7 +496,8 @@ void IR_DecoderRaw::writeToBuffer(bool bit) {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
} }
bool IR_DecoderRaw::crcCheck(uint8_t len, crc_t& crc) { bool IR_DecoderRaw::crcCheck(uint8_t len, crc_t &crc)
{
bool crcOK = false; bool crcOK = false;
crc = 0; crc = 0;
@ -402,42 +507,44 @@ bool IR_DecoderRaw::crcCheck(uint8_t len, crc_t& crc) {
if ( if (
crc && crc &&
dataBuffer[len] == (crc >> 8) & 0xFF && dataBuffer[len] == (crc >> 8) & 0xFF &&
dataBuffer[len + 1] == (crc & 0xFF) dataBuffer[len + 1] == (crc & 0xFF))
) { {
crcOK = true; crcOK = true;
} else { }
else
{
crcOK = false; crcOK = false;
} }
return crcOK; return crcOK;
} }
uint16_t IR_DecoderRaw::ceil_div(uint16_t val, uint16_t divider) { uint16_t IR_DecoderRaw::ceil_div(uint16_t val, uint16_t divider)
{
int ret = val / divider; int ret = val / divider;
if ((val << 4) / divider - (ret << 4) >= 8) if ((val << 4) / divider - (ret << 4) >= 8)
ret++; ret++;
return ret; return ret;
} }
// IRDEBUG FUNC // IRDEBUG FUNC
#ifdef IRDEBUG #ifdef IRDEBUG
inline void IR_DecoderRaw::errPulse(uint8_t pin, uint8_t count) { inline void IR_DecoderRaw::errPulse(uint8_t pin, uint8_t count)
for (size_t i = 0; i < count; i++) { {
for (size_t i = 0; i < count; i++)
{
digitalWrite(pin, 1); digitalWrite(pin, 1);
digitalWrite(pin, 0); digitalWrite(pin, 0);
} }
digitalWrite(pin, 0); digitalWrite(pin, 0);
} }
inline void IR_DecoderRaw::infoPulse(uint8_t pin, uint8_t count) { inline void IR_DecoderRaw::infoPulse(uint8_t pin, uint8_t count)
for (size_t i = 0; i < count; i++) { {
for (size_t i = 0; i < count; i++)
{
digitalWrite(pin, 1); digitalWrite(pin, 1);
digitalWrite(pin, 0); digitalWrite(pin, 0);
} }
} }
#endif #endif

View File

@ -1,7 +1,7 @@
#pragma once #pragma once
#include "IR_config.h" #include "IR_config.h"
//#define IRDEBUG // #define IRDEBUG
#ifdef IRDEBUG #ifdef IRDEBUG
#define wrHigh A3 // Запись HIGH инициирована // green #define wrHigh A3 // Запись HIGH инициирована // green
@ -19,16 +19,29 @@
#define riseTimeMax (riseTime + riseTolerance) #define riseTimeMax (riseTime + riseTolerance)
#define riseTimeMin (riseTime - riseTolerance) #define riseTimeMin (riseTime - riseTolerance)
#define aroundRise(t) (riseTimeMin < t && t < riseTimeMax) #define aroundRise(t) (riseTimeMin < t && t < riseTimeMax)
#define IR_timeout (riseTimeMax * (8 + syncBits +1)) // us // таймаут в 8 data + 3 sync + 1 #define IR_timeout (riseTimeMax * (8 + syncBits + 1)) // us // таймаут в 8 data + 3 sync + 1
class IR_Encoder; class IR_Encoder;
class IR_DecoderRaw : virtual public IR_FOX { class IR_DecoderRaw : virtual public IR_FOX
{
friend IR_Encoder; friend IR_Encoder;
protected: protected:
PackInfo packInfo; PackInfo packInfo;
IR_Encoder* encoder; // Указатель на парный передатчик IR_Encoder *encoder; // Указатель на парный передатчик
bool availableRaw() { if (isAvailable) { isAvailable = false; return true; } else { return false; } }; bool availableRaw()
{
if (isAvailable)
{
isAvailable = false;
return true;
}
else
{
return false;
}
};
public: public:
const uint8_t isrPin; // Пин прерывания const uint8_t isrPin; // Пин прерывания
@ -37,13 +50,14 @@ public:
/// @param isrPin Номер вывода прерывания/данных от приёмника (2 или 3 для atmega 328p) /// @param isrPin Номер вывода прерывания/данных от приёмника (2 или 3 для atmega 328p)
/// @param addr Адрес приёмника /// @param addr Адрес приёмника
/// @param encPair Указатель на передатчик, работающий в паре /// @param encPair Указатель на передатчик, работающий в паре
IR_DecoderRaw(const uint8_t isrPin, uint16_t addr, IR_Encoder* encPair = nullptr); IR_DecoderRaw(const uint8_t isrPin, uint16_t addr, IR_Encoder *encPair = nullptr);
void isr(); // Функция прерывания void isr(); // Функция прерывания
void tick(); // Обработка приёмника, необходима для работы void tick(); // Обработка приёмника, необходима для работы
bool isOverflow() { return isBufferOverflow; }; // Буффер переполнился bool isOverflow() { return isBufferOverflow; }; // Буффер переполнился
bool isSubOverflow() { bool isSubOverflow()
{
uint8_t oldSREG = SREG; uint8_t oldSREG = SREG;
cli(); cli();
volatile bool ret = isSubBufferOverflow; volatile bool ret = isSubBufferOverflow;
@ -70,16 +84,17 @@ private:
//////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////
volatile uint8_t currentSubBufferIndex; // Счетчик текущей позиции во вспомогательном буфере фронтов/спадов volatile uint8_t currentSubBufferIndex; // Счетчик текущей позиции во вспомогательном буфере фронтов/спадов
struct FrontStorage { // Структура для хранения времени и направления фронта/спада struct FrontStorage
{ // Структура для хранения времени и направления фронта/спада
volatile uint32_t time = 0; // Время volatile uint32_t time = 0; // Время
volatile bool dir = false; // Направление (true = ↑; false = ↓) volatile bool dir = false; // Направление (true = ↑; false = ↓)
volatile FrontStorage* next = nullptr; // Указатель на следующий связанный фронт/спад, или nullptr если конец volatile FrontStorage *next = nullptr; // Указатель на следующий связанный фронт/спад, или nullptr если конец
}; };
volatile FrontStorage* lastFront = nullptr; // Указатель последнего фронта/спада volatile FrontStorage *lastFront = nullptr; // Указатель последнего фронта/спада
volatile FrontStorage* firstUnHandledFront = nullptr; // Указатель первого необработанного фронта/спада volatile FrontStorage *firstUnHandledFront = nullptr; // Указатель первого необработанного фронта/спада
volatile FrontStorage subBuffer[subBufferSize]; // вспомогательный буфер для хранения необработанных фронтов/спадов volatile FrontStorage subBuffer[subBufferSize]; // вспомогательный буфер для хранения необработанных фронтов/спадов
//////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////
uint8_t dataBuffer[dataByteSizeMax] { 0 }; // Буффер данных uint8_t dataBuffer[dataByteSizeMax]{0}; // Буффер данных
uint32_t prevRise, prevPrevRise, prevFall, prevPrevFall; // Время предыдущих фронтов/спадов uint32_t prevRise, prevPrevRise, prevFall, prevPrevFall; // Время предыдущих фронтов/спадов
uint16_t errorCounter = 0; // Счётчик ошибок uint16_t errorCounter = 0; // Счётчик ошибок
int8_t preambFrontCounter = 0; // Счётчик __/``` ↑ преамбулы int8_t preambFrontCounter = 0; // Счётчик __/``` ↑ преамбулы
@ -92,7 +107,7 @@ private:
/// @param len Длина в байтах проверяемых данных /// @param len Длина в байтах проверяемых данных
/// @param crc Результат рассчёта crc (Выходной параметр) /// @param crc Результат рассчёта crc (Выходной параметр)
/// @return true если crc верно /// @return true если crc верно
bool crcCheck(uint8_t len, uint16_t& crc); bool crcCheck(uint8_t len, uint16_t &crc);
//////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////
bool isData = true; // Флаг относится ли бит к данным, или битам синхронизации bool isData = true; // Флаг относится ли бит к данным, или битам синхронизации
@ -106,7 +121,6 @@ private:
void writeToBuffer(bool); void writeToBuffer(bool);
//////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////
void firstRX(); /// @brief Установка и сброс начальных значений и флагов в готовность к приёму данных void firstRX(); /// @brief Установка и сброс начальных значений и флагов в готовность к приёму данных
/// @brief Целочисленное деление с округлением вверх /// @brief Целочисленное деление с округлением вверх
@ -115,10 +129,8 @@ private:
/// @return Результат /// @return Результат
uint16_t ceil_div(uint16_t val, uint16_t divider); uint16_t ceil_div(uint16_t val, uint16_t divider);
#ifdef IRDEBUG #ifdef IRDEBUG
inline void errPulse(uint8_t pin, uint8_t count); inline void errPulse(uint8_t pin, uint8_t count);
inline void infoPulse(uint8_t pin, uint8_t count); inline void infoPulse(uint8_t pin, uint8_t count);
#endif #endif
}; };

View File

@ -5,43 +5,55 @@
#define ISR_Out 10 #define ISR_Out 10
#define TestOut 13 #define TestOut 13
IR_Encoder::IR_Encoder(uint16_t addr, IR_DecoderRaw* decPair = nullptr) { IR_Encoder::IR_Encoder(uint16_t addr, IR_DecoderRaw *decPair = nullptr)
{
id = addr; id = addr;
this->decPair = decPair; this->decPair = decPair;
signal = noSignal; signal = noSignal;
isSending = false; isSending = false;
#if disablePairDec #if disablePairDec
if (decPair != nullptr) { if (decPair != nullptr)
blindDecoders = new IR_DecoderRaw * [1] {decPair}; {
blindDecoders = new IR_DecoderRaw *[1]
{ decPair };
decodersCount = 1; decodersCount = 1;
} }
#endif #endif
if (decPair != nullptr) { if (decPair != nullptr)
{
decPair->encoder = this; decPair->encoder = this;
} }
}; };
void IR_Encoder::setBlindDecoders(IR_DecoderRaw* decoders [], uint8_t count) { void IR_Encoder::setBlindDecoders(IR_DecoderRaw *decoders[], uint8_t count)
#if disablePairDec {
if (blindDecoders != nullptr) delete [] blindDecoders; #if disablePairDec
#endif if (blindDecoders != nullptr)
delete[] blindDecoders;
#endif
decodersCount = count; decodersCount = count;
blindDecoders = decoders; blindDecoders = decoders;
} }
IR_Encoder::~IR_Encoder() { IR_Encoder::~IR_Encoder()
delete [] bitLow; {
delete [] bitHigh; delete[] bitLow;
delete[] bitHigh;
}; };
void IR_Encoder::sendData(uint16_t addrTo, uint8_t dataByte, bool needAccept = false) { void IR_Encoder::sendData(uint16_t addrTo, uint8_t dataByte, bool needAccept = false)
uint8_t* dataPtr = new uint8_t[1]; {
uint8_t *dataPtr = new uint8_t[1];
dataPtr[0] = dataByte; dataPtr[0] = dataByte;
sendData(addrTo, dataPtr, 1, needAccept); sendData(addrTo, dataPtr, 1, needAccept);
delete[] dataPtr; delete[] dataPtr;
} }
void IR_Encoder::sendData(uint16_t addrTo, uint8_t* data = nullptr, uint8_t len = 0, bool needAccept = false) { void IR_Encoder::sendData(uint16_t addrTo, uint8_t *data = nullptr, uint8_t len = 0, bool needAccept = false)
if (len > bytePerPack) { return; } {
if (len > bytePerPack)
{
return;
}
constexpr uint8_t dataStart = msgBytes + addrBytes + addrBytes; constexpr uint8_t dataStart = msgBytes + addrBytes + addrBytes;
memset(sendBuffer, 0x00, dataByteSizeMax); memset(sendBuffer, 0x00, dataByteSizeMax);
uint8_t packSize = msgBytes + addrBytes + addrBytes + len + crcBytes; uint8_t packSize = msgBytes + addrBytes + addrBytes + len + crcBytes;
@ -60,8 +72,9 @@ void IR_Encoder::sendData(uint16_t addrTo, uint8_t* data = nullptr, uint8_t len
sendBuffer[3] = addrTo >> 8 & 0xFF; sendBuffer[3] = addrTo >> 8 & 0xFF;
sendBuffer[4] = addrTo & 0xFF; sendBuffer[4] = addrTo & 0xFF;
for (uint16_t i = dataStart; (i < dataStart + len) && (data != nullptr); i++) { for (uint16_t i = dataStart; (i < dataStart + len) && (data != nullptr); i++)
sendBuffer[i] = ((uint8_t*)data)[i - dataStart]; {
sendBuffer[i] = ((uint8_t *)data)[i - dataStart];
} }
// data crc // data crc
@ -79,7 +92,8 @@ void IR_Encoder::sendData(uint16_t addrTo, uint8_t* data = nullptr, uint8_t len
rawSend(sendBuffer, packSize); rawSend(sendBuffer, packSize);
} }
void IR_Encoder::sendAccept(uint16_t addrTo, uint8_t customByte = 0) { void IR_Encoder::sendAccept(uint16_t addrTo, uint8_t customByte = 0)
{
constexpr uint8_t packsize = msgBytes + addrBytes + 1U + crcBytes; constexpr uint8_t packsize = msgBytes + addrBytes + 1U + crcBytes;
memset(sendBuffer, 0x00, dataByteSizeMax); memset(sendBuffer, 0x00, dataByteSizeMax);
sendBuffer[0] = IR_MSG_ACCEPT << 5; sendBuffer[0] = IR_MSG_ACCEPT << 5;
@ -101,7 +115,8 @@ void IR_Encoder::sendAccept(uint16_t addrTo, uint8_t customByte = 0) {
rawSend(sendBuffer, packsize); rawSend(sendBuffer, packsize);
} }
void IR_Encoder::sendRequest(uint16_t addrTo) { void IR_Encoder::sendRequest(uint16_t addrTo)
{
constexpr uint8_t packsize = msgBytes + addrBytes + addrBytes + crcBytes; constexpr uint8_t packsize = msgBytes + addrBytes + addrBytes + crcBytes;
memset(sendBuffer, 0x00, dataByteSizeMax); memset(sendBuffer, 0x00, dataByteSizeMax);
sendBuffer[0] = IR_MSG_REQUEST << 5; sendBuffer[0] = IR_MSG_REQUEST << 5;
@ -111,7 +126,7 @@ void IR_Encoder::sendRequest(uint16_t addrTo) {
sendBuffer[1] = id >> 8 & 0xFF; sendBuffer[1] = id >> 8 & 0xFF;
sendBuffer[2] = id & 0xFF; sendBuffer[2] = id & 0xFF;
//addr_to // addr_to
sendBuffer[3] = addrTo >> 8 & 0xFF; sendBuffer[3] = addrTo >> 8 & 0xFF;
sendBuffer[4] = addrTo & 0xFF; sendBuffer[4] = addrTo & 0xFF;
@ -122,16 +137,22 @@ void IR_Encoder::sendRequest(uint16_t addrTo) {
rawSend(sendBuffer, packsize); rawSend(sendBuffer, packsize);
} }
void IR_Encoder::sendBack(uint8_t* data = nullptr, uint8_t len = 0) { void IR_Encoder::sendBack(uint8_t *data = nullptr, uint8_t len = 0)
{
_sendBack(false, 0, data, len); _sendBack(false, 0, data, len);
} }
void IR_Encoder::sendBackTo(uint16_t addrTo, uint8_t* data = nullptr, uint8_t len = 0) { void IR_Encoder::sendBackTo(uint16_t addrTo, uint8_t *data = nullptr, uint8_t len = 0)
{
_sendBack(true, addrTo, data, len); _sendBack(true, addrTo, data, len);
} }
void IR_Encoder::_sendBack(bool isAdressed, uint16_t addrTo, uint8_t* data, uint8_t len) { void IR_Encoder::_sendBack(bool isAdressed, uint16_t addrTo, uint8_t *data, uint8_t len)
if (len > bytePerPack) { return; } {
if (len > bytePerPack)
{
return;
}
memset(sendBuffer, 0x00, dataByteSizeMax); memset(sendBuffer, 0x00, dataByteSizeMax);
uint8_t dataStart = msgBytes + addrBytes + (isAdressed ? addrBytes : 0); uint8_t dataStart = msgBytes + addrBytes + (isAdressed ? addrBytes : 0);
@ -151,8 +172,9 @@ void IR_Encoder::_sendBack(bool isAdressed, uint16_t addrTo, uint8_t* data, uint
sendBuffer[3] = addrTo >> 8 & 0xFF; sendBuffer[3] = addrTo >> 8 & 0xFF;
sendBuffer[4] = addrTo & 0xFF; sendBuffer[4] = addrTo & 0xFF;
for (uint16_t i = dataStart; i < dataStart + len; i++) { for (uint16_t i = dataStart; i < dataStart + len; i++)
sendBuffer[i] = ((uint8_t*)data)[i - dataStart]; {
sendBuffer[i] = ((uint8_t *)data)[i - dataStart];
} }
// data crc // data crc
@ -163,18 +185,22 @@ void IR_Encoder::_sendBack(bool isAdressed, uint16_t addrTo, uint8_t* data, uint
rawSend(sendBuffer, packSize); rawSend(sendBuffer, packSize);
} }
void IR_Encoder::setDecoder_isSending() { void IR_Encoder::setDecoder_isSending()
if (decodersCount) { {
for (uint8_t i = 0; i < decodersCount; i++) { if (decodersCount)
{
for (uint8_t i = 0; i < decodersCount; i++)
{
blindDecoders[i]->isPairSending ^= id; blindDecoders[i]->isPairSending ^= id;
} }
} }
} }
void IR_Encoder::rawSend(uint8_t* ptr, uint8_t len) { void IR_Encoder::rawSend(uint8_t *ptr, uint8_t len)
if (isSending) { {
//TODO: Обработка повторной отправки if (isSending)
{
// TODO: Обработка повторной отправки
return; return;
} }
@ -200,18 +226,22 @@ void IR_Encoder::rawSend(uint8_t* ptr, uint8_t len) {
sei(); sei();
} }
void IR_Encoder::isr()
{
void IR_Encoder::isr() { if (!isSending)
if (!isSending) return; return;
ir_out_virtual = !ir_out_virtual && state; ir_out_virtual = !ir_out_virtual && state;
if (toggleCounter) { if (toggleCounter)
{
toggleCounter--; toggleCounter--;
} else { }
else
{
IsrStart: IsrStart:
switch (signal) { switch (signal)
{
case noSignal: case noSignal:
signal = preamb; signal = preamb;
// сброс счетчиков // сброс счетчиков
@ -222,10 +252,13 @@ void IR_Encoder::isr() {
break; break;
case preamb: case preamb:
if (preambFrontCounter) { if (preambFrontCounter)
{
preambFrontCounter--; preambFrontCounter--;
toggleCounter = preambToggle; // Вторая и последующие генерации для этого signal toggleCounter = preambToggle; // Вторая и последующие генерации для этого signal
} else {// Конец преамбулы, переход на следующий signal }
else
{ // Конец преамбулы, переход на следующий signal
signal = data; signal = data;
state = !LOW; // Инверсное состояние первой генерации следующего signal state = !LOW; // Инверсное состояние первой генерации следующего signal
goto IsrStart; // Применение новых параметров в этй же итерации прерывания goto IsrStart; // Применение новых параметров в этй же итерации прерывания
@ -234,14 +267,18 @@ void IR_Encoder::isr() {
break; break;
case data: case data:
if (dataSequenceCounter) { if (dataSequenceCounter)
if (!(dataSequenceCounter & 1U)) { // если чётный - смена бита {
if (!(dataSequenceCounter & 1U))
{ // если чётный - смена бита
currentBitSequence = ((sendBuffer[dataByteCounter] >> dataBitCounter) & 1U) ? bitHigh : bitLow; // определение текущего бита currentBitSequence = ((sendBuffer[dataByteCounter] >> dataBitCounter) & 1U) ? bitHigh : bitLow; // определение текущего бита
dataBitCounter--; dataBitCounter--;
} }
toggleCounter = currentBitSequence[!state]; toggleCounter = currentBitSequence[!state];
dataSequenceCounter--; dataSequenceCounter--;
} else { // Конец data, переход на следующий signal }
else
{ // Конец data, переход на следующий signal
syncLastBit = ((sendBuffer[dataByteCounter]) & 1U); syncLastBit = ((sendBuffer[dataByteCounter]) & 1U);
dataByteCounter++; dataByteCounter++;
dataBitCounter = bitPerByte - 1; dataBitCounter = bitPerByte - 1;
@ -252,22 +289,30 @@ void IR_Encoder::isr() {
break; break;
case sync: case sync:
if (syncSequenceCounter) { if (syncSequenceCounter)
if (!(syncSequenceCounter & 1U)) { // если чётный - смена бита {
if (syncSequenceCounter == 2) { // Если последний бит if (!(syncSequenceCounter & 1U))
{ // если чётный - смена бита
if (syncSequenceCounter == 2)
{ // Если последний бит
currentBitSequence = ((sendBuffer[dataByteCounter]) & 0b10000000) ? bitLow : bitHigh; currentBitSequence = ((sendBuffer[dataByteCounter]) & 0b10000000) ? bitLow : bitHigh;
} else { }
else
{
currentBitSequence = syncLastBit ? bitLow : bitHigh; // определение текущего бита currentBitSequence = syncLastBit ? bitLow : bitHigh; // определение текущего бита
syncLastBit = !syncLastBit; syncLastBit = !syncLastBit;
} }
} }
toggleCounter = currentBitSequence[!state]; toggleCounter = currentBitSequence[!state];
syncSequenceCounter--; syncSequenceCounter--;
} else { // Конец sync, переход на следующий signal }
else
{ // Конец sync, переход на следующий signal
signal = data; signal = data;
syncSequenceCounter = syncBits * 2; syncSequenceCounter = syncBits * 2;
if (dataByteCounter >= sendLen) { // определение конца данных if (dataByteCounter >= sendLen)
{ // определение конца данных
signal = noSignal; signal = noSignal;
} }
goto IsrStart; // Применение новых параметров в этй же итерации прерывания goto IsrStart; // Применение новых параметров в этй же итерации прерывания
@ -283,11 +328,8 @@ void IR_Encoder::isr() {
} }
} }
void old()
{ ///////////////////////////////////////////////////////
void old() {///////////////////////////////////////////////////////
// void IR_Encoder::rawSend(uint8_t* ptr, uint8_t len) { // void IR_Encoder::rawSend(uint8_t* ptr, uint8_t len) {
// /*tmp*/bool LOW_FIRST = false;/*tmp*/ // /*tmp*/bool LOW_FIRST = false;/*tmp*/
@ -312,12 +354,14 @@ void old() {///////////////////////////////////////////////////////
// } // }
} }
void IR_Encoder::sendByte(uint8_t byte, bool* prev, bool LOW_FIRST) { void IR_Encoder::sendByte(uint8_t byte, bool *prev, bool LOW_FIRST)
{
uint8_t mask = LOW_FIRST ? 0b00000001 : 0b10000000; uint8_t mask = LOW_FIRST ? 0b00000001 : 0b10000000;
for (uint8_t bitShift = 8; bitShift; bitShift--) { for (uint8_t bitShift = 8; bitShift; bitShift--)
{
// digitalWrite(9, HIGH); // digitalWrite(9, HIGH);
// digitalWrite(9, LOW); // digitalWrite(9, LOW);
byte& mask ? send_HIGH(prev) : send_LOW(); byte &mask ? send_HIGH(prev) : send_LOW();
*prev = byte & mask; *prev = byte & mask;
LOW_FIRST ? mask <<= 1 : mask >>= 1; LOW_FIRST ? mask <<= 1 : mask >>= 1;
// digitalWrite(9, HIGH); // digitalWrite(9, HIGH);
@ -325,15 +369,19 @@ void IR_Encoder::sendByte(uint8_t byte, bool* prev, bool LOW_FIRST) {
} }
} }
void IR_Encoder::addSync(bool* prev, bool* next) { void IR_Encoder::addSync(bool *prev, bool *next)
switch (syncBits) { {
case 0: break; switch (syncBits)
{
case 0:
break;
case 1: case 1:
*prev ? send_LOW() : send_HIGH(); *prev ? send_LOW() : send_HIGH();
*prev = !*prev; *prev = !*prev;
break; break;
default: default:
for (int16_t i = 0; i < syncBits - 1; i++) { for (int16_t i = 0; i < syncBits - 1; i++)
{
*prev ? send_LOW() : send_HIGH(); *prev ? send_LOW() : send_HIGH();
*prev = !*prev; *prev = !*prev;
} }
@ -343,7 +391,8 @@ void IR_Encoder::addSync(bool* prev, bool* next) {
} }
} }
void IR_Encoder::send_HIGH(bool prevBite = 1) { void IR_Encoder::send_HIGH(bool prevBite = 1)
{
// if (/* prevBite */1) { // if (/* prevBite */1) {
// meanderBlock(bitPauseTakts * 2, halfPeriod, LOW); // meanderBlock(bitPauseTakts * 2, halfPeriod, LOW);
@ -352,21 +401,20 @@ void IR_Encoder::send_HIGH(bool prevBite = 1) {
// meanderBlock(bitTakts - (bitActiveTakts - bitPauseTakts), halfPeriod, LOW); // meanderBlock(bitTakts - (bitActiveTakts - bitPauseTakts), halfPeriod, LOW);
// meanderBlock(bitActiveTakts - bitPauseTakts, halfPeriod, HIGH); // meanderBlock(bitActiveTakts - bitPauseTakts, halfPeriod, HIGH);
// } // }
} }
void IR_Encoder::send_LOW() { void IR_Encoder::send_LOW()
{
// meanderBlock(bitPauseTakts, halfPeriod, LOW); // meanderBlock(bitPauseTakts, halfPeriod, LOW);
// meanderBlock(bitActiveTakts, halfPeriod, LOW); // meanderBlock(bitActiveTakts, halfPeriod, LOW);
// meanderBlock(bitPauseTakts, halfPeriod, HIGH); // meanderBlock(bitPauseTakts, halfPeriod, HIGH);
} }
void IR_Encoder::send_EMPTY(uint8_t count) { void IR_Encoder::send_EMPTY(uint8_t count)
{
// for (size_t i = 0; i < count * 2; i++) { // for (size_t i = 0; i < count * 2; i++) {
// meanderBlock((bitPauseTakts * 2 + bitActiveTakts), halfPeriod, prevPreambBit); // meanderBlock((bitPauseTakts * 2 + bitActiveTakts), halfPeriod, prevPreambBit);
// prevPreambBit = !prevPreambBit; // prevPreambBit = !prevPreambBit;
// } // }
// meanderBlock(bitPauseTakts * 2 + bitActiveTakts, halfPeriod, 0); //TODO: Отодвинуть преамбулу // meanderBlock(bitPauseTakts * 2 + bitActiveTakts, halfPeriod, 0); //TODO: Отодвинуть преамбулу
} }

View File

@ -1,26 +1,27 @@
#pragma once #pragma once
#include "IR_config.h" #include "IR_config.h"
//TODO: Отложенная передача после завершения приема // TODO: Отложенная передача после завершения приема
class IR_DecoderRaw; class IR_DecoderRaw;
class IR_Encoder : IR_FOX { class IR_Encoder : IR_FOX
{
friend IR_DecoderRaw; friend IR_DecoderRaw;
public:
public:
private: private:
uint16_t id; /// @brief Адрес передатчика uint16_t id; /// @brief Адрес передатчика
public: public:
/// @brief Класс передатчика /// @brief Класс передатчика
/// @param addr Адрес передатчика /// @param addr Адрес передатчика
/// @param pin Вывод передатчика /// @param pin Вывод передатчика
/// @param tune Подстройка несущей частоты /// @param tune Подстройка несущей частоты
/// @param decPair Приёмник, для которого отключается приём в момент передачи передатчиком /// @param decPair Приёмник, для которого отключается приём в момент передачи передатчиком
IR_Encoder(uint16_t addr, IR_DecoderRaw* decPair = nullptr); IR_Encoder(uint16_t addr, IR_DecoderRaw *decPair = nullptr);
static void timerSetup() { static void timerSetup()
{
// TIMER2 Ini // TIMER2 Ini
uint8_t oldSREG = SREG; // Save global interupts settings uint8_t oldSREG = SREG; // Save global interupts settings
cli(); cli();
@ -34,53 +35,55 @@ public:
TCCR2B |= (1 << CS20); // Предделитель 1 TCCR2B |= (1 << CS20); // Предделитель 1
TIMSK2 |= (1 << OCIE2A); // Прерывание по совпадению TIMSK2 |= (1 << OCIE2A); // Прерывание по совпадению
OCR2A = /* 465 */((F_CPU / (38000 * 2)) - 2); //38кГц OCR2A = /* 465 */ ((F_CPU / (38000 * 2)) - 2); // 38кГц
SREG = oldSREG; // Return interrupt settings SREG = oldSREG; // Return interrupt settings
} }
static void timerOFFSetup(){ static void timerOFFSetup()
{
TIMSK2 &= ~(1 << OCIE2A); // Прерывание по совпадению выкл TIMSK2 &= ~(1 << OCIE2A); // Прерывание по совпадению выкл
} }
void IR_Encoder::setBlindDecoders(IR_DecoderRaw* decoders [], uint8_t count); void IR_Encoder::setBlindDecoders(IR_DecoderRaw *decoders[], uint8_t count);
void rawSend(uint8_t* ptr, uint8_t len); void rawSend(uint8_t *ptr, uint8_t len);
void sendData(uint16_t addrTo, uint8_t dataByte, bool needAccept = false); void sendData(uint16_t addrTo, uint8_t dataByte, bool needAccept = false);
void sendData(uint16_t addrTo, uint8_t* data = nullptr, uint8_t len = 0, bool needAccept = false); void sendData(uint16_t addrTo, uint8_t *data = nullptr, uint8_t len = 0, bool needAccept = false);
void sendAccept(uint16_t addrTo, uint8_t customByte = 0); void sendAccept(uint16_t addrTo, uint8_t customByte = 0);
void sendRequest(uint16_t addrTo); void sendRequest(uint16_t addrTo);
void sendBack(uint8_t* data = nullptr, uint8_t len = 0); void sendBack(uint8_t *data = nullptr, uint8_t len = 0);
void sendBackTo(uint16_t addrTo, uint8_t* data = nullptr, uint8_t len = 0); void sendBackTo(uint16_t addrTo, uint8_t *data = nullptr, uint8_t len = 0);
void isr(); void isr();
~IR_Encoder(); ~IR_Encoder();
volatile bool ir_out_virtual; volatile bool ir_out_virtual;
private: private:
void IR_Encoder::_sendBack(bool isAdressed, uint16_t addrTo, uint8_t* data, uint8_t len); void IR_Encoder::_sendBack(bool isAdressed, uint16_t addrTo, uint8_t *data, uint8_t len);
void IR_Encoder::setDecoder_isSending(); void IR_Encoder::setDecoder_isSending();
void sendByte(uint8_t byte, bool* prev, bool LOW_FIRST); void sendByte(uint8_t byte, bool *prev, bool LOW_FIRST);
void addSync(bool* prev, bool* next); void addSync(bool *prev, bool *next);
void send_HIGH(bool = 1); void send_HIGH(bool = 1);
void send_LOW(); void send_LOW();
void send_EMPTY(uint8_t count); void send_EMPTY(uint8_t count);
enum SignalPart : uint8_t { enum SignalPart : uint8_t
{
noSignal = 0, noSignal = 0,
preamb = 1, preamb = 1,
data = 2, data = 2,
sync = 3 sync = 3
}; };
IR_DecoderRaw* decPair; IR_DecoderRaw *decPair;
IR_DecoderRaw** blindDecoders; IR_DecoderRaw **blindDecoders;
uint8_t decodersCount; uint8_t decodersCount;
uint8_t sendLen; uint8_t sendLen;
uint8_t sendBuffer[dataByteSizeMax] { 0 }; /// @brief Буффер данных для отправки uint8_t sendBuffer[dataByteSizeMax]{0}; /// @brief Буффер данных для отправки
volatile bool isSending; volatile bool isSending;
volatile bool state; /// @brief Текущий уровень генерации volatile bool state; /// @brief Текущий уровень генерации
@ -95,23 +98,17 @@ private:
volatile uint8_t syncSequenceCounter; volatile uint8_t syncSequenceCounter;
volatile bool syncLastBit; volatile bool syncLastBit;
struct BitSequence { struct BitSequence
{
uint8_t low; uint8_t low;
uint8_t high; uint8_t high;
}; };
static inline uint8_t* bitHigh = new uint8_t[2] { static inline uint8_t *bitHigh = new uint8_t[2]{
(bitPauseTakts * 2) * 2 - 1, (bitPauseTakts * 2) * 2 - 1,
(bitActiveTakts) * 2 - 1 (bitActiveTakts) * 2 - 1};
}; static inline uint8_t *bitLow = new uint8_t[2]{
static inline uint8_t* bitLow = new uint8_t[2] {
(bitPauseTakts + bitActiveTakts) * 2 - 1, (bitPauseTakts + bitActiveTakts) * 2 - 1,
(bitPauseTakts) * 2 - 1 (bitPauseTakts) * 2 - 1};
}; uint8_t *currentBitSequence = bitLow;
uint8_t* currentBitSequence = bitLow;
volatile SignalPart signal; volatile SignalPart signal;
}; };

View File

@ -2,9 +2,12 @@
#include "IR_config.h" #include "IR_config.h"
class IR_Decoder; class IR_Decoder;
namespace PacketTypes { namespace PacketTypes
class BasePack { {
class BasePack
{
friend IR_Decoder; friend IR_Decoder;
protected: protected:
bool isAvailable; bool isAvailable;
bool isRawAvailable; bool isRawAvailable;
@ -15,49 +18,80 @@ namespace PacketTypes {
uint8_t addressToOffset; uint8_t addressToOffset;
uint8_t DataOffset; uint8_t DataOffset;
IR_FOX::PackInfo* packInfo; IR_FOX::PackInfo *packInfo;
uint16_t id; uint16_t id;
virtual bool checkAddress(){return true;}; virtual bool checkAddress() { return true; };
void set(IR_FOX::PackInfo* packInfo, uint16_t id) { void set(IR_FOX::PackInfo *packInfo, uint16_t id)
{
this->packInfo = packInfo; this->packInfo = packInfo;
this->id = id; this->id = id;
if (checkAddress()) { if (checkAddress())
{
isAvailable = true; isAvailable = true;
isRawAvailable = true; isRawAvailable = true;
#ifdef IRDEBUG_INFO #ifdef IRDEBUG_INFO
Serial.print(" OK "); Serial.print(" OK ");
#endif #endif
} else { }
else
{
isRawAvailable = true; isRawAvailable = true;
#ifdef IRDEBUG_INFO #ifdef IRDEBUG_INFO
Serial.print(" NOT-OK "); Serial.print(" NOT-OK ");
#endif #endif
} }
} }
static uint16_t _getAddrFrom(BasePack *obj)
static uint16_t _getAddrFrom(BasePack* obj) { {
return (obj->packInfo->buffer[obj->addressFromOffset] << 8) | obj->packInfo->buffer[obj->addressFromOffset + 1]; return (obj->packInfo->buffer[obj->addressFromOffset] << 8) | obj->packInfo->buffer[obj->addressFromOffset + 1];
}; };
static uint16_t _getAddrTo(BasePack* obj) { static uint16_t _getAddrTo(BasePack *obj)
{
return (obj->packInfo->buffer[obj->addressToOffset] << 8) | obj->packInfo->buffer[obj->addressToOffset + 1]; return (obj->packInfo->buffer[obj->addressToOffset] << 8) | obj->packInfo->buffer[obj->addressToOffset + 1];
}; };
static uint8_t _getDataSize(BasePack* obj) { static uint8_t _getDataSize(BasePack *obj)
{
return obj->packInfo->packSize - crcBytes - obj->DataOffset; return obj->packInfo->packSize - crcBytes - obj->DataOffset;
}; };
static uint8_t* _getDataPrt(BasePack* obj) { static uint8_t *_getDataPrt(BasePack *obj)
{
return obj->packInfo->buffer + obj->DataOffset; return obj->packInfo->buffer + obj->DataOffset;
}; };
static uint8_t _getDataRawSize(BasePack* obj) { static uint8_t _getDataRawSize(BasePack *obj)
{
return obj->packInfo->packSize; return obj->packInfo->packSize;
}; };
public: public:
bool available() { if (isAvailable) { isAvailable = false; isRawAvailable = false; return true; } else { return false; } }; bool available()
bool availableRaw() { if (isRawAvailable) { isRawAvailable = false; return true; } else { return false; } }; {
if (isAvailable)
{
isAvailable = false;
isRawAvailable = false;
return true;
}
else
{
return false;
}
};
bool availableRaw()
{
if (isRawAvailable)
{
isRawAvailable = false;
return true;
}
else
{
return false;
}
};
uint8_t getMsgInfo() { return packInfo->buffer[0] & IR_MASK_MSG_INFO; }; uint8_t getMsgInfo() { return packInfo->buffer[0] & IR_MASK_MSG_INFO; };
uint8_t getMsgType() { return (packInfo->buffer[0] >> 5) & IR_MASK_MSG_TYPE; }; uint8_t getMsgType() { return (packInfo->buffer[0] >> 5) & IR_MASK_MSG_TYPE; };
uint8_t getMsgRAW() { return packInfo->buffer[0]; }; uint8_t getMsgRAW() { return packInfo->buffer[0]; };
@ -66,13 +100,14 @@ namespace PacketTypes {
uint8_t getErrorHighSignal() { return packInfo->err.highSignal; }; uint8_t getErrorHighSignal() { return packInfo->err.highSignal; };
uint8_t getErrorOther() { return packInfo->err.other; }; uint8_t getErrorOther() { return packInfo->err.other; };
uint16_t getTunerTime() { return packInfo->rTime; }; uint16_t getTunerTime() { return packInfo->rTime; };
uint8_t* getDataRawPtr() { return packInfo->buffer; }; uint8_t *getDataRawPtr() { return packInfo->buffer; };
}; };
class Data : public BasePack
class Data : public BasePack { {
public: public:
Data() { Data()
{
msgOffset = 0; msgOffset = 0;
addressFromOffset = 1; addressFromOffset = 1;
addressToOffset = 3; addressToOffset = 3;
@ -83,20 +118,23 @@ namespace PacketTypes {
uint16_t getAddrTo() { return _getAddrTo(this); }; uint16_t getAddrTo() { return _getAddrTo(this); };
uint8_t getDataSize() { return _getDataSize(this); }; uint8_t getDataSize() { return _getDataSize(this); };
uint8_t* getDataPrt() { return _getDataPrt(this); }; uint8_t *getDataPrt() { return _getDataPrt(this); };
uint8_t getDataRawSize() { return _getDataRawSize(this); }; uint8_t getDataRawSize() { return _getDataRawSize(this); };
private: private:
bool checkAddress() override { bool checkAddress() override
{
bool ret; bool ret;
IR_FOX::checkAddressRuleApply(getAddrTo(), this->id, ret); IR_FOX::checkAddressRuleApply(getAddrTo(), this->id, ret);
return ret; return ret;
} }
}; };
class DataBack : public BasePack { class DataBack : public BasePack
{
public: public:
DataBack() { DataBack()
{
msgOffset = 0; msgOffset = 0;
addressFromOffset = 1; addressFromOffset = 1;
addressToOffset = 3; addressToOffset = 3;
@ -107,15 +145,20 @@ namespace PacketTypes {
uint16_t getAddrTo() { return _getAddrTo(this); }; uint16_t getAddrTo() { return _getAddrTo(this); };
uint8_t getDataSize() { return _getDataSize(this); }; uint8_t getDataSize() { return _getDataSize(this); };
uint8_t* getDataPrt() { return _getDataPrt(this); }; uint8_t *getDataPrt() { return _getDataPrt(this); };
uint8_t getDataRawSize() { return _getDataRawSize(this); }; uint8_t getDataRawSize() { return _getDataRawSize(this); };
private: private:
bool checkAddress() override { bool checkAddress() override
{
bool ret; bool ret;
if (getMsgType() == IR_MSG_BACK_TO) { if (getMsgType() == IR_MSG_BACK_TO)
{
DataOffset = 5; DataOffset = 5;
IR_FOX::checkAddressRuleApply((packInfo->buffer[addressToOffset] << 8) | packInfo->buffer[addressToOffset + 1], this->id, ret); IR_FOX::checkAddressRuleApply((packInfo->buffer[addressToOffset] << 8) | packInfo->buffer[addressToOffset + 1], this->id, ret);
} else { }
else
{
DataOffset = 3; DataOffset = 3;
ret = true; ret = true;
} }
@ -123,9 +166,11 @@ namespace PacketTypes {
} }
}; };
class Accept : public BasePack { class Accept : public BasePack
{
public: public:
Accept() { Accept()
{
msgOffset = 0; msgOffset = 0;
addressFromOffset = 1; addressFromOffset = 1;
DataOffset = 3; DataOffset = 3;
@ -133,13 +178,16 @@ namespace PacketTypes {
uint16_t getAddrFrom() { return _getAddrFrom(this); }; uint16_t getAddrFrom() { return _getAddrFrom(this); };
uint8_t getCustomByte() { return packInfo->buffer[DataOffset]; }; uint8_t getCustomByte() { return packInfo->buffer[DataOffset]; };
private: private:
bool checkAddress() override { return true; } bool checkAddress() override { return true; }
}; };
class Request : public BasePack { class Request : public BasePack
{
public: public:
Request() { Request()
{
msgOffset = 0; msgOffset = 0;
addressFromOffset = 1; addressFromOffset = 1;
addressToOffset = 3; addressToOffset = 3;
@ -150,7 +198,8 @@ namespace PacketTypes {
uint16_t getAddrTo() { return _getAddrTo(this); }; uint16_t getAddrTo() { return _getAddrTo(this); };
private: private:
bool checkAddress() override { bool checkAddress() override
{
bool ret; bool ret;
IR_FOX::checkAddressRuleApply(getAddrTo(), this->id, ret); IR_FOX::checkAddressRuleApply(getAddrTo(), this->id, ret);
return ret; return ret;