Welcome to mirror list, hosted at ThFree Co, Russian Federation.

secplus_v2.c « protocols « subghz « lib - github.com/ClusterM/flipperzero-firmware.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 837b263870a73774b94fbd755667a65735341213 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
#include "secplus_v2.h"
#include <lib/toolbox/manchester_decoder.h>
#include <lib/toolbox/manchester_encoder.h>
#include "../blocks/const.h"
#include "../blocks/decoder.h"
#include "../blocks/encoder.h"
#include "../blocks/generic.h"
#include "../blocks/math.h"

/*
* Help
* https://github.com/argilo/secplus
* https://github.com/merbanan/rtl_433/blob/master/src/devices/secplus_v2.c
*/

#define TAG "SubGhzProtocoSecPlus_v2"

#define SECPLUS_V2_HEADER 0x3C0000000000
#define SECPLUS_V2_HEADER_MASK 0xFFFF3C0000000000
#define SECPLUS_V2_PACKET_1 0x000000000000
#define SECPLUS_V2_PACKET_2 0x010000000000
#define SECPLUS_V2_PACKET_MASK 0x30000000000

static const SubGhzBlockConst subghz_protocol_secplus_v2_const = {
    .te_short = 250,
    .te_long = 500,
    .te_delta = 110,
    .min_count_bit_for_found = 62,
};

struct SubGhzProtocolDecoderSecPlus_v2 {
    SubGhzProtocolDecoderBase base;

    SubGhzBlockDecoder decoder;
    SubGhzBlockGeneric generic;

    ManchesterState manchester_saved_state;
    uint64_t secplus_packet_1;
};

struct SubGhzProtocolEncoderSecPlus_v2 {
    SubGhzProtocolEncoderBase base;

    SubGhzProtocolBlockEncoder encoder;
    SubGhzBlockGeneric generic;
    uint64_t secplus_packet_1;
};

typedef enum {
    SecPlus_v2DecoderStepReset = 0,
    SecPlus_v2DecoderStepDecoderData,
} SecPlus_v2DecoderStep;

const SubGhzProtocolDecoder subghz_protocol_secplus_v2_decoder = {
    .alloc = subghz_protocol_decoder_secplus_v2_alloc,
    .free = subghz_protocol_decoder_secplus_v2_free,

    .feed = subghz_protocol_decoder_secplus_v2_feed,
    .reset = subghz_protocol_decoder_secplus_v2_reset,

    .get_hash_data = subghz_protocol_decoder_secplus_v2_get_hash_data,
    .serialize = subghz_protocol_decoder_secplus_v2_serialize,
    .deserialize = subghz_protocol_decoder_secplus_v2_deserialize,
    .get_string = subghz_protocol_decoder_secplus_v2_get_string,
};

const SubGhzProtocolEncoder subghz_protocol_secplus_v2_encoder = {
    .alloc = subghz_protocol_encoder_secplus_v2_alloc,
    .free = subghz_protocol_encoder_secplus_v2_free,

    .deserialize = subghz_protocol_encoder_secplus_v2_deserialize,
    .stop = subghz_protocol_encoder_secplus_v2_stop,
    .yield = subghz_protocol_encoder_secplus_v2_yield,
};

const SubGhzProtocol subghz_protocol_secplus_v2 = {
    .name = SUBGHZ_PROTOCOL_SECPLUS_V2_NAME,
    .type = SubGhzProtocolTypeDynamic,
    .flag = SubGhzProtocolFlag_315 | SubGhzProtocolFlag_AM | SubGhzProtocolFlag_Decodable |
            SubGhzProtocolFlag_Load | SubGhzProtocolFlag_Send,

    .decoder = &subghz_protocol_secplus_v2_decoder,
    .encoder = &subghz_protocol_secplus_v2_encoder,
};

void* subghz_protocol_encoder_secplus_v2_alloc(SubGhzEnvironment* environment) {
    UNUSED(environment);
    SubGhzProtocolEncoderSecPlus_v2* instance = malloc(sizeof(SubGhzProtocolEncoderSecPlus_v2));

    instance->base.protocol = &subghz_protocol_secplus_v2;
    instance->generic.protocol_name = instance->base.protocol->name;

    instance->encoder.repeat = 10;
    instance->encoder.size_upload = 256;
    instance->encoder.upload = malloc(instance->encoder.size_upload * sizeof(LevelDuration));
    instance->encoder.is_runing = false;
    return instance;
}

void subghz_protocol_encoder_secplus_v2_free(void* context) {
    furi_assert(context);
    SubGhzProtocolEncoderSecPlus_v2* instance = context;
    free(instance->encoder.upload);
    free(instance);
}

static bool subghz_protocol_secplus_v2_mix_invet(uint8_t invert, uint16_t p[]) {
    // selectively invert buffers
    switch(invert) {
    case 0x00: // 0b0000 (True, True, False),
        p[0] = ~p[0] & 0x03FF;
        p[1] = ~p[1] & 0x03FF;
        break;
    case 0x01: // 0b0001 (False, True, False),
        p[1] = ~p[1] & 0x03FF;
        break;
    case 0x02: // 0b0010 (False, False, True),
        p[2] = ~p[2] & 0x03FF;
        break;
    case 0x04: // 0b0100 (True, True, True),
        p[0] = ~p[0] & 0x03FF;
        p[1] = ~p[1] & 0x03FF;
        p[2] = ~p[2] & 0x03FF;
        break;
    case 0x05: // 0b0101 (True, False, True),
    case 0x0a: // 0b1010 (True, False, True),
        p[0] = ~p[0] & 0x03FF;
        p[2] = ~p[2] & 0x03FF;
        break;
    case 0x06: // 0b0110 (False, True, True),
        p[1] = ~p[1] & 0x03FF;
        p[2] = ~p[2] & 0x03FF;
        break;
    case 0x08: // 0b1000 (True, False, False),
        p[0] = ~p[0] & 0x03FF;
        break;
    case 0x09: // 0b1001 (False, False, False),
        break;
    default:
        FURI_LOG_E(TAG, "Invert FAIL");
        return false;
    }
    return true;
}

static bool subghz_protocol_secplus_v2_mix_order_decode(uint8_t order, uint16_t p[]) {
    uint16_t a = p[0], b = p[1], c = p[2];

    // selectively reorder buffers
    switch(order) {
    case 0x06: // 0b0110  2, 1, 0],
    case 0x09: // 0b1001  2, 1, 0],
        p[2] = a;
        p[1] = b;
        p[0] = c;
        break;
    case 0x08: // 0b1000  1, 2, 0],
    case 0x04: // 0b0100  1, 2, 0],
        p[1] = a;
        p[2] = b;
        p[0] = c;
        break;
    case 0x01: // 0b0001 2, 0, 1],
        p[2] = a;
        p[0] = b;
        p[1] = c;
        break;
    case 0x00: // 0b0000  0, 2, 1],
        p[0] = a;
        p[2] = b;
        p[1] = c;
        break;
    case 0x05: // 0b0101 1, 0, 2],
        p[1] = a;
        p[0] = b;
        p[2] = c;
        break;
    case 0x02: // 0b0010 0, 1, 2],
    case 0x0A: // 0b1010 0, 1, 2],
        p[0] = a;
        p[1] = b;
        p[2] = c;
        break;
    default:
        FURI_LOG_E(TAG, "Order FAIL");
        return false;
    }
    return true;
}

static bool subghz_protocol_secplus_v2_mix_order_encode(uint8_t order, uint16_t p[]) {
    uint16_t a, b, c;

    // selectively reorder buffers
    switch(order) {
    case 0x06: // 0b0110  2, 1, 0],
    case 0x09: // 0b1001  2, 1, 0],
        a = p[2];
        b = p[1];
        c = p[0];
        break;
    case 0x08: // 0b1000  1, 2, 0],
    case 0x04: // 0b0100  1, 2, 0],
        a = p[1];
        b = p[2];
        c = p[0];
        break;
    case 0x01: // 0b0001 2, 0, 1],
        a = p[2];
        b = p[0];
        c = p[1];
        break;
    case 0x00: // 0b0000  0, 2, 1],
        a = p[0];
        b = p[2];
        c = p[1];
        break;
    case 0x05: // 0b0101 1, 0, 2],
        a = p[1];
        b = p[0];
        c = p[2];
        break;
    case 0x02: // 0b0010 0, 1, 2],
    case 0x0A: // 0b1010 0, 1, 2],
        a = p[0];
        b = p[1];
        c = p[2];
        break;
    default:
        FURI_LOG_E(TAG, "Order FAIL");
        return false;
    }

    p[0] = a;
    p[1] = b;
    p[2] = c;
    return true;
}

/** 
 * Security+ 2.0 half-message decoding
 * @param data data 
 * @param roll_array[] return roll_array part
 * @param fixed[] return fixed part
 * @return true On success
 */

static bool
    subghz_protocol_secplus_v2_decode_half(uint64_t data, uint8_t roll_array[], uint32_t* fixed) {
    uint8_t order = (data >> 34) & 0x0f;
    uint8_t invert = (data >> 30) & 0x0f;
    uint16_t p[3] = {0};

    for(int i = 29; i >= 0; i -= 3) {
        p[0] = p[0] << 1 | bit_read(data, i);
        p[1] = p[1] << 1 | bit_read(data, i - 1);
        p[2] = p[2] << 1 | bit_read(data, i - 2);
    }

    if(!subghz_protocol_secplus_v2_mix_invet(invert, p)) return false;
    if(!subghz_protocol_secplus_v2_mix_order_decode(order, p)) return false;

    data = order << 4 | invert;
    int k = 0;
    for(int i = 6; i >= 0; i -= 2) {
        roll_array[k++] = (data >> i) & 0x03;
        if(roll_array[k] == 3) {
            FURI_LOG_E(TAG, "Roll_Array FAIL");
            return false;
        }
    }

    for(int i = 8; i >= 0; i -= 2) {
        roll_array[k++] = (p[2] >> i) & 0x03;
        if(roll_array[k] == 3) {
            FURI_LOG_E(TAG, "Roll_Array FAIL");
            return false;
        }
    }

    fixed[0] = p[0] << 10 | p[1];
    return true;
}

/** 
 * Analysis of received data
 * @param instance Pointer to a SubGhzBlockGeneric* instance
 * @param packet_1 first part of the message
 */
static void
    subghz_protocol_secplus_v2_remote_controller(SubGhzBlockGeneric* instance, uint64_t packet_1) {
    uint32_t fixed_1[1];
    uint8_t roll_1[9] = {0};
    uint32_t fixed_2[1];
    uint8_t roll_2[9] = {0};
    uint8_t rolling_digits[18] = {0};

    if(subghz_protocol_secplus_v2_decode_half(packet_1, roll_1, fixed_1) &&
       subghz_protocol_secplus_v2_decode_half(instance->data, roll_2, fixed_2)) {
        rolling_digits[0] = roll_2[8];
        rolling_digits[1] = roll_1[8];

        rolling_digits[2] = roll_2[4];
        rolling_digits[3] = roll_2[5];
        rolling_digits[4] = roll_2[6];
        rolling_digits[5] = roll_2[7];

        rolling_digits[6] = roll_1[4];
        rolling_digits[7] = roll_1[5];
        rolling_digits[8] = roll_1[6];
        rolling_digits[9] = roll_1[7];

        rolling_digits[10] = roll_2[0];
        rolling_digits[11] = roll_2[1];
        rolling_digits[12] = roll_2[2];
        rolling_digits[13] = roll_2[3];

        rolling_digits[14] = roll_1[0];
        rolling_digits[15] = roll_1[1];
        rolling_digits[16] = roll_1[2];
        rolling_digits[17] = roll_1[3];

        uint32_t rolling = 0;
        for(int i = 0; i < 18; i++) {
            rolling = (rolling * 3) + rolling_digits[i];
        }
        // Max value = 2^28 (268435456)
        if(rolling >= 0x10000000) {
            FURI_LOG_E(TAG, "Rolling FAIL");
            instance->cnt = 0;
            instance->btn = 0;
            instance->serial = 0;
        } else {
            instance->cnt = subghz_protocol_blocks_reverse_key(rolling, 28);
            instance->btn = fixed_1[0] >> 12;
            instance->serial = fixed_1[0] << 20 | fixed_2[0];
        }
    } else {
        instance->cnt = 0;
        instance->btn = 0;
        instance->serial = 0;
    }
}

/** 
 * Security+ 2.0 half-message encoding
 * @param roll_array[] roll_array part
 * @param fixed[] fixed part
 * @return return data 
 */

static uint64_t subghz_protocol_secplus_v2_encode_half(uint8_t roll_array[], uint32_t fixed) {
    uint64_t data = 0;
    uint16_t p[3] = {(fixed >> 10) & 0x3FF, fixed & 0x3FF, 0};
    uint8_t order = roll_array[0] << 2 | roll_array[1];
    uint8_t invert = roll_array[2] << 2 | roll_array[3];
    p[2] = (uint16_t)roll_array[4] << 8 | roll_array[5] << 6 | roll_array[6] << 4 |
           roll_array[7] << 2 | roll_array[8];

    if(!subghz_protocol_secplus_v2_mix_order_encode(order, p)) return 0;
    if(!subghz_protocol_secplus_v2_mix_invet(invert, p)) return 0;

    for(int i = 0; i < 10; i++) {
        data <<= 3;
        data |= bit_read(p[0], 9 - i) << 2 | bit_read(p[1], 9 - i) << 1 | bit_read(p[2], 9 - i);
    }
    data |= ((uint64_t)order) << 34 | ((uint64_t)invert) << 30;

    return data;
}

/** 
 * Security+ 2.0 message encoding
 * @param instance SubGhzProtocolEncoderSecPlus_v2* 
 */

static void subghz_protocol_secplus_v2_encode(SubGhzProtocolEncoderSecPlus_v2* instance) {
    uint32_t fixed_1[1] = {instance->generic.btn << 12 | instance->generic.serial >> 20};
    uint32_t fixed_2[1] = {instance->generic.serial & 0xFFFFF};
    uint8_t rolling_digits[18] = {0};
    uint8_t roll_1[9] = {0};
    uint8_t roll_2[9] = {0};

    instance->generic.cnt++;
    //ToDo it is not known what value the counter starts
    if(instance->generic.cnt > 0xFFFFFFF) instance->generic.cnt = 0xE500000;
    uint32_t rolling = subghz_protocol_blocks_reverse_key(instance->generic.cnt, 28);

    for(int8_t i = 17; i > -1; i--) {
        rolling_digits[i] = rolling % 3;
        rolling /= 3;
    }

    roll_2[8] = rolling_digits[0];
    roll_1[8] = rolling_digits[1];

    roll_2[4] = rolling_digits[2];
    roll_2[5] = rolling_digits[3];
    roll_2[6] = rolling_digits[4];
    roll_2[7] = rolling_digits[5];

    roll_1[4] = rolling_digits[6];
    roll_1[5] = rolling_digits[7];
    roll_1[6] = rolling_digits[8];
    roll_1[7] = rolling_digits[9];

    roll_2[0] = rolling_digits[10];
    roll_2[1] = rolling_digits[11];
    roll_2[2] = rolling_digits[12];
    roll_2[3] = rolling_digits[13];

    roll_1[0] = rolling_digits[14];
    roll_1[1] = rolling_digits[15];
    roll_1[2] = rolling_digits[16];
    roll_1[3] = rolling_digits[17];

    instance->secplus_packet_1 = SECPLUS_V2_HEADER | SECPLUS_V2_PACKET_1 |
                                 subghz_protocol_secplus_v2_encode_half(roll_1, fixed_1[0]);
    instance->generic.data = SECPLUS_V2_HEADER | SECPLUS_V2_PACKET_2 |
                             subghz_protocol_secplus_v2_encode_half(roll_2, fixed_2[0]);
}

static LevelDuration
    subghz_protocol_encoder_secplus_v2_add_duration_to_upload(ManchesterEncoderResult result) {
    LevelDuration data = {.duration = 0, .level = 0};
    switch(result) {
    case ManchesterEncoderResultShortLow:
        data.duration = subghz_protocol_secplus_v2_const.te_short;
        data.level = false;
        break;
    case ManchesterEncoderResultLongLow:
        data.duration = subghz_protocol_secplus_v2_const.te_long;
        data.level = false;
        break;
    case ManchesterEncoderResultLongHigh:
        data.duration = subghz_protocol_secplus_v2_const.te_long;
        data.level = true;
        break;
    case ManchesterEncoderResultShortHigh:
        data.duration = subghz_protocol_secplus_v2_const.te_short;
        data.level = true;
        break;

    default:
        furi_crash("SubGhz: ManchesterEncoderResult is incorrect.");
        break;
    }
    return level_duration_make(data.level, data.duration);
}

/**
 * Generating an upload from data.
 * @param instance Pointer to a SubGhzProtocolEncoderSecPlus_v2 instance
 */
static void
    subghz_protocol_encoder_secplus_v2_get_upload(SubGhzProtocolEncoderSecPlus_v2* instance) {
    furi_assert(instance);
    size_t index = 0;

    ManchesterEncoderState enc_state;
    manchester_encoder_reset(&enc_state);
    ManchesterEncoderResult result;

    //Send data packet 1
    for(uint8_t i = instance->generic.data_count_bit; i > 0; i--) {
        if(!manchester_encoder_advance(
               &enc_state, bit_read(instance->secplus_packet_1, i - 1), &result)) {
            instance->encoder.upload[index++] =
                subghz_protocol_encoder_secplus_v2_add_duration_to_upload(result);
            manchester_encoder_advance(
                &enc_state, bit_read(instance->secplus_packet_1, i - 1), &result);
        }
        instance->encoder.upload[index++] =
            subghz_protocol_encoder_secplus_v2_add_duration_to_upload(result);
    }
    instance->encoder.upload[index] = subghz_protocol_encoder_secplus_v2_add_duration_to_upload(
        manchester_encoder_finish(&enc_state));
    if(level_duration_get_level(instance->encoder.upload[index])) {
        index++;
    }
    instance->encoder.upload[index++] =
        level_duration_make(false, (uint32_t)subghz_protocol_secplus_v2_const.te_long * 136);

    //Send data packet 2
    manchester_encoder_reset(&enc_state);
    for(uint8_t i = instance->generic.data_count_bit; i > 0; i--) {
        if(!manchester_encoder_advance(
               &enc_state, bit_read(instance->generic.data, i - 1), &result)) {
            instance->encoder.upload[index++] =
                subghz_protocol_encoder_secplus_v2_add_duration_to_upload(result);
            manchester_encoder_advance(
                &enc_state, bit_read(instance->generic.data, i - 1), &result);
        }
        instance->encoder.upload[index++] =
            subghz_protocol_encoder_secplus_v2_add_duration_to_upload(result);
    }
    instance->encoder.upload[index] = subghz_protocol_encoder_secplus_v2_add_duration_to_upload(
        manchester_encoder_finish(&enc_state));
    if(level_duration_get_level(instance->encoder.upload[index])) {
        index++;
    }
    instance->encoder.upload[index++] =
        level_duration_make(false, (uint32_t)subghz_protocol_secplus_v2_const.te_long * 136);

    instance->encoder.size_upload = index;
}

bool subghz_protocol_encoder_secplus_v2_deserialize(void* context, FlipperFormat* flipper_format) {
    furi_assert(context);
    SubGhzProtocolEncoderSecPlus_v2* instance = context;
    bool res = false;
    do {
        if(!subghz_block_generic_deserialize(&instance->generic, flipper_format)) {
            FURI_LOG_E(TAG, "Deserialize error");
            break;
        }

        uint8_t key_data[sizeof(uint64_t)] = {0};
        if(!flipper_format_read_hex(
               flipper_format, "Secplus_packet_1", key_data, sizeof(uint64_t))) {
            FURI_LOG_E(TAG, "Secplus_packet_1");
            break;
        }
        for(uint8_t i = 0; i < sizeof(uint64_t); i++) {
            instance->secplus_packet_1 = instance->secplus_packet_1 << 8 | key_data[i];
        }

        subghz_protocol_secplus_v2_remote_controller(
            &instance->generic, instance->secplus_packet_1);
        subghz_protocol_secplus_v2_encode(instance);
        //optional parameter parameter
        flipper_format_read_uint32(
            flipper_format, "Repeat", (uint32_t*)&instance->encoder.repeat, 1);
        subghz_protocol_encoder_secplus_v2_get_upload(instance);

        //update data
        for(size_t i = 0; i < sizeof(uint64_t); i++) {
            key_data[sizeof(uint64_t) - i - 1] = (instance->generic.data >> i * 8) & 0xFF;
        }
        if(!flipper_format_update_hex(flipper_format, "Key", key_data, sizeof(uint64_t))) {
            FURI_LOG_E(TAG, "Unable to add Key");
            break;
        }

        for(size_t i = 0; i < sizeof(uint64_t); i++) {
            key_data[sizeof(uint64_t) - i - 1] = (instance->secplus_packet_1 >> i * 8) & 0xFF;
        }
        if(!flipper_format_update_hex(
               flipper_format, "Secplus_packet_1", key_data, sizeof(uint64_t))) {
            FURI_LOG_E(TAG, "Unable to add Secplus_packet_1");
            break;
        }

        instance->encoder.is_runing = true;

        res = true;
    } while(false);

    return res;
}

void subghz_protocol_encoder_secplus_v2_stop(void* context) {
    SubGhzProtocolEncoderSecPlus_v2* instance = context;
    instance->encoder.is_runing = false;
}

LevelDuration subghz_protocol_encoder_secplus_v2_yield(void* context) {
    SubGhzProtocolEncoderSecPlus_v2* instance = context;

    if(instance->encoder.repeat == 0 || !instance->encoder.is_runing) {
        instance->encoder.is_runing = false;
        return level_duration_reset();
    }

    LevelDuration ret = instance->encoder.upload[instance->encoder.front];

    if(++instance->encoder.front == instance->encoder.size_upload) {
        instance->encoder.repeat--;
        instance->encoder.front = 0;
    }

    return ret;
}

bool subghz_protocol_secplus_v2_create_data(
    void* context,
    FlipperFormat* flipper_format,
    uint32_t serial,
    uint8_t btn,
    uint32_t cnt,
    SubGhzPesetDefinition* preset) {
    furi_assert(context);
    SubGhzProtocolEncoderSecPlus_v2* instance = context;
    instance->generic.serial = serial;
    instance->generic.cnt = cnt;
    instance->generic.btn = btn;
    instance->generic.data_count_bit =
        (uint8_t)subghz_protocol_secplus_v2_const.min_count_bit_for_found;
    subghz_protocol_secplus_v2_encode(instance);
    bool res = subghz_block_generic_serialize(&instance->generic, flipper_format, preset);

    uint8_t key_data[sizeof(uint64_t)] = {0};
    for(size_t i = 0; i < sizeof(uint64_t); i++) {
        key_data[sizeof(uint64_t) - i - 1] = (instance->secplus_packet_1 >> i * 8) & 0xFF;
    }

    if(res &&
       !flipper_format_write_hex(flipper_format, "Secplus_packet_1", key_data, sizeof(uint64_t))) {
        FURI_LOG_E(TAG, "Unable to add Secplus_packet_1");
        res = false;
    }
    return res;
}

void* subghz_protocol_decoder_secplus_v2_alloc(SubGhzEnvironment* environment) {
    UNUSED(environment);
    SubGhzProtocolDecoderSecPlus_v2* instance = malloc(sizeof(SubGhzProtocolDecoderSecPlus_v2));
    instance->base.protocol = &subghz_protocol_secplus_v2;
    instance->generic.protocol_name = instance->base.protocol->name;

    return instance;
}

void subghz_protocol_decoder_secplus_v2_free(void* context) {
    furi_assert(context);
    SubGhzProtocolDecoderSecPlus_v2* instance = context;
    free(instance);
}

void subghz_protocol_decoder_secplus_v2_reset(void* context) {
    furi_assert(context);
    // SubGhzProtocolDecoderSecPlus_v2* instance = context;
    // does not reset the decoder because you need to get 2 parts of the package
}

static bool subghz_protocol_secplus_v2_check_packet(SubGhzProtocolDecoderSecPlus_v2* instance) {
    if((instance->decoder.decode_data & SECPLUS_V2_HEADER_MASK) == SECPLUS_V2_HEADER) {
        if((instance->decoder.decode_data & SECPLUS_V2_PACKET_MASK) == SECPLUS_V2_PACKET_1) {
            instance->secplus_packet_1 = instance->decoder.decode_data;
        } else if(
            ((instance->decoder.decode_data & SECPLUS_V2_PACKET_MASK) == SECPLUS_V2_PACKET_2) &&
            (instance->secplus_packet_1)) {
            return true;
        }
    }
    return false;
}

void subghz_protocol_decoder_secplus_v2_feed(void* context, bool level, uint32_t duration) {
    furi_assert(context);
    SubGhzProtocolDecoderSecPlus_v2* instance = context;

    ManchesterEvent event = ManchesterEventReset;
    switch(instance->decoder.parser_step) {
    case SecPlus_v2DecoderStepReset:
        if((!level) && (DURATION_DIFF(duration, subghz_protocol_secplus_v2_const.te_long * 130) <
                        subghz_protocol_secplus_v2_const.te_delta * 100)) {
            //Found header Security+ 2.0
            instance->decoder.parser_step = SecPlus_v2DecoderStepDecoderData;
            instance->decoder.decode_data = 0;
            instance->decoder.decode_count_bit = 0;
            instance->secplus_packet_1 = 0;
            manchester_advance(
                instance->manchester_saved_state,
                ManchesterEventReset,
                &instance->manchester_saved_state,
                NULL);
            manchester_advance(
                instance->manchester_saved_state,
                ManchesterEventLongHigh,
                &instance->manchester_saved_state,
                NULL);
            manchester_advance(
                instance->manchester_saved_state,
                ManchesterEventShortLow,
                &instance->manchester_saved_state,
                NULL);
        }
        break;
    case SecPlus_v2DecoderStepDecoderData:
        if(!level) {
            if(DURATION_DIFF(duration, subghz_protocol_secplus_v2_const.te_short) <
               subghz_protocol_secplus_v2_const.te_delta) {
                event = ManchesterEventShortLow;
            } else if(
                DURATION_DIFF(duration, subghz_protocol_secplus_v2_const.te_long) <
                subghz_protocol_secplus_v2_const.te_delta) {
                event = ManchesterEventLongLow;
            } else if(
                duration >= (uint32_t)(subghz_protocol_secplus_v2_const.te_long * 2 +
                             subghz_protocol_secplus_v2_const.te_delta)) {
                if(instance->decoder.decode_count_bit >=
                   subghz_protocol_secplus_v2_const.min_count_bit_for_found) {
                    instance->generic.data = instance->decoder.decode_data;
                    instance->generic.data_count_bit = instance->decoder.decode_count_bit;
                    if(subghz_protocol_secplus_v2_check_packet(instance)) {
                        if(instance->base.callback)
                            instance->base.callback(&instance->base, instance->base.context);
                        instance->decoder.parser_step = SecPlus_v2DecoderStepReset;
                    }
                }
                instance->decoder.decode_data = 0;
                instance->decoder.decode_count_bit = 0;
                manchester_advance(
                    instance->manchester_saved_state,
                    ManchesterEventReset,
                    &instance->manchester_saved_state,
                    NULL);
                manchester_advance(
                    instance->manchester_saved_state,
                    ManchesterEventLongHigh,
                    &instance->manchester_saved_state,
                    NULL);
                manchester_advance(
                    instance->manchester_saved_state,
                    ManchesterEventShortLow,
                    &instance->manchester_saved_state,
                    NULL);
            } else {
                instance->decoder.parser_step = SecPlus_v2DecoderStepReset;
            }
        } else {
            if(DURATION_DIFF(duration, subghz_protocol_secplus_v2_const.te_short) <
               subghz_protocol_secplus_v2_const.te_delta) {
                event = ManchesterEventShortHigh;
            } else if(
                DURATION_DIFF(duration, subghz_protocol_secplus_v2_const.te_long) <
                subghz_protocol_secplus_v2_const.te_delta) {
                event = ManchesterEventLongHigh;
            } else {
                instance->decoder.parser_step = SecPlus_v2DecoderStepReset;
            }
        }
        if(event != ManchesterEventReset) {
            bool data;
            bool data_ok = manchester_advance(
                instance->manchester_saved_state, event, &instance->manchester_saved_state, &data);

            if(data_ok) {
                instance->decoder.decode_data = (instance->decoder.decode_data << 1) | data;
                instance->decoder.decode_count_bit++;
            }
        }
        break;
    }
}

uint8_t subghz_protocol_decoder_secplus_v2_get_hash_data(void* context) {
    furi_assert(context);
    SubGhzProtocolDecoderSecPlus_v2* instance = context;
    return subghz_protocol_blocks_get_hash_data(
        &instance->decoder, (instance->decoder.decode_count_bit / 8) + 1);
}

bool subghz_protocol_decoder_secplus_v2_serialize(
    void* context,
    FlipperFormat* flipper_format,
    SubGhzPesetDefinition* preset) {
    furi_assert(context);
    SubGhzProtocolDecoderSecPlus_v2* instance = context;
    bool res = subghz_block_generic_serialize(&instance->generic, flipper_format, preset);

    uint8_t key_data[sizeof(uint64_t)] = {0};
    for(size_t i = 0; i < sizeof(uint64_t); i++) {
        key_data[sizeof(uint64_t) - i - 1] = (instance->secplus_packet_1 >> i * 8) & 0xFF;
    }

    if(res &&
       !flipper_format_write_hex(flipper_format, "Secplus_packet_1", key_data, sizeof(uint64_t))) {
        FURI_LOG_E(TAG, "Unable to add Secplus_packet_1");
        res = false;
    }
    return res;
}

bool subghz_protocol_decoder_secplus_v2_deserialize(void* context, FlipperFormat* flipper_format) {
    furi_assert(context);
    SubGhzProtocolDecoderSecPlus_v2* instance = context;
    bool res = false;
    do {
        if(!subghz_block_generic_deserialize(&instance->generic, flipper_format)) {
            FURI_LOG_E(TAG, "Deserialize error");
            break;
        }
        if(!flipper_format_rewind(flipper_format)) {
            FURI_LOG_E(TAG, "Rewind error");
            break;
        }
        uint8_t key_data[sizeof(uint64_t)] = {0};
        if(!flipper_format_read_hex(
               flipper_format, "Secplus_packet_1", key_data, sizeof(uint64_t))) {
            FURI_LOG_E(TAG, "Missing Secplus_packet_1");
            break;
        }
        for(uint8_t i = 0; i < sizeof(uint64_t); i++) {
            instance->secplus_packet_1 = instance->secplus_packet_1 << 8 | key_data[i];
        }
        res = true;
    } while(false);

    return res;
}

void subghz_protocol_decoder_secplus_v2_get_string(void* context, string_t output) {
    furi_assert(context);
    SubGhzProtocolDecoderSecPlus_v2* instance = context;
    subghz_protocol_secplus_v2_remote_controller(&instance->generic, instance->secplus_packet_1);

    string_cat_printf(
        output,
        "%s %db\r\n"
        "Pk1:0x%lX%08lX\r\n"
        "Pk2:0x%lX%08lX\r\n"
        "Sn:0x%08lX  Btn:0x%01X\r\n"
        "Cnt:0x%03X\r\n",

        instance->generic.protocol_name,
        instance->generic.data_count_bit,
        (uint32_t)(instance->secplus_packet_1 >> 32),
        (uint32_t)instance->secplus_packet_1,
        (uint32_t)(instance->generic.data >> 32),
        (uint32_t)instance->generic.data,
        instance->generic.serial,
        instance->generic.btn,
        instance->generic.cnt);
}