* We count all consecutive (allow only one gap between) durations and compute the average. * @return false if more than 2 distinct duration values found */
| 153 | * @return false if more than 2 distinct duration values found |
| 154 | */ |
| 155 | bool aggregateArrayCounts(uint8_t aArray[], uint8_t aMaxIndex, uint8_t *aShortIndex, uint8_t *aLongIndex) { |
| 156 | uint8_t tSum = 0; |
| 157 | uint16_t tWeightedSum = 0; |
| 158 | uint8_t tGapCount = 0; |
| 159 | for (uint_fast8_t i = 0; i <= aMaxIndex; i++) { |
| 160 | uint8_t tCurrentDurations = aArray[i]; |
| 161 | if (tCurrentDurations != 0) { |
| 162 | // Add it to sum and remove array content |
| 163 | tSum += tCurrentDurations; |
| 164 | tWeightedSum += (tCurrentDurations * i); |
| 165 | aArray[i] = 0; |
| 166 | tGapCount = 0; |
| 167 | } else { |
| 168 | tGapCount++; |
| 169 | } |
| 170 | if (tSum != 0 && (i == aMaxIndex || tGapCount > 1)) { |
| 171 | /* |
| 172 | * Here we have a sum AND last element OR more than 1 consecutive gap |
| 173 | */ |
| 174 | uint8_t tAggregateIndex = (tWeightedSum + (tSum / 2)) / tSum; // with rounding |
| 175 | aArray[tAggregateIndex] = tSum; // disabling this line increases code size by 2 - unbelievable! |
| 176 | // store aggregate for later decoding |
| 177 | if (*aShortIndex == 0) { |
| 178 | *aShortIndex = tAggregateIndex; |
| 179 | } else if (*aLongIndex == 0) { |
| 180 | *aLongIndex = tAggregateIndex; |
| 181 | } else { |
| 182 | // we have 3 bins => this is likely no pulse width or distance protocol. e.g. it can be RC5. |
| 183 | return false; |
| 184 | } |
| 185 | // initialize for next aggregation |
| 186 | tSum = 0; |
| 187 | tWeightedSum = 0; |
| 188 | } |
| 189 | } |
| 190 | return true; |
| 191 | } |
| 192 | |
| 193 | /* |
| 194 | * Try to decode a pulse distance or pulse width protocol. |