id
int64
4
16.3M
file_name
stringlengths
3
68
file_path
stringlengths
14
181
content
stringlengths
39
9.06M
size
int64
39
9.06M
language
stringclasses
1 value
extension
stringclasses
2 values
total_lines
int64
1
711k
avg_line_length
float64
3.18
138
max_line_length
int64
10
140
alphanum_fraction
float64
0.02
0.93
repo_name
stringlengths
7
69
repo_stars
int64
2
61.6k
repo_forks
int64
12
7.81k
repo_open_issues
int64
0
1.13k
repo_license
stringclasses
10 values
repo_extraction_date
stringclasses
657 values
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
1 class
exact_duplicates_redpajama
bool
1 class
exact_duplicates_githubcode
bool
2 classes
near_duplicates_stackv2
bool
1 class
near_duplicates_stackv1
bool
1 class
near_duplicates_redpajama
bool
1 class
near_duplicates_githubcode
bool
2 classes
6,295
secplus_v2.h
DarkFlippers_unleashed-firmware/lib/subghz/protocols/secplus_v2.h
#pragma once #include "base.h" #include "public_api.h" #define SUBGHZ_PROTOCOL_SECPLUS_V2_NAME "Security+ 2.0" typedef struct SubGhzProtocolDecoderSecPlus_v2 SubGhzProtocolDecoderSecPlus_v2; typedef struct SubGhzProtocolEncoderSecPlus_v2 SubGhzProtocolEncoderSecPlus_v2; extern const SubGhzProtocolDecoder subghz_protocol_secplus_v2_decoder; extern const SubGhzProtocolEncoder subghz_protocol_secplus_v2_encoder; extern const SubGhzProtocol subghz_protocol_secplus_v2; /** * Allocate SubGhzProtocolEncoderSecPlus_v2. * @param environment Pointer to a SubGhzEnvironment instance * @return SubGhzProtocolEncoderSecPlus_v2* pointer to a SubGhzProtocolEncoderSecPlus_v2 instance */ void* subghz_protocol_encoder_secplus_v2_alloc(SubGhzEnvironment* environment); /** * Free SubGhzProtocolEncoderSecPlus_v2. * @param context Pointer to a SubGhzProtocolEncoderSecPlus_v2 instance */ void subghz_protocol_encoder_secplus_v2_free(void* context); /** * Deserialize and generating an upload to send. * @param context Pointer to a SubGhzProtocolEncoderSecPlus_v2 instance * @param flipper_format Pointer to a FlipperFormat instance * @return status */ SubGhzProtocolStatus subghz_protocol_encoder_secplus_v2_deserialize(void* context, FlipperFormat* flipper_format); /** * Forced transmission stop. * @param context Pointer to a SubGhzProtocolEncoderSecPlus_v2 instance */ void subghz_protocol_encoder_secplus_v2_stop(void* context); /** * Getting the level and duration of the upload to be loaded into DMA. * @param context Pointer to a SubGhzProtocolEncoderSecPlus_v2 instance * @return LevelDuration */ LevelDuration subghz_protocol_encoder_secplus_v2_yield(void* context); /** * Allocate SubGhzProtocolDecoderSecPlus_v2. * @param environment Pointer to a SubGhzEnvironment instance * @return SubGhzProtocolDecoderSecPlus_v2* pointer to a SubGhzProtocolDecoderSecPlus_v2 instance */ void* subghz_protocol_decoder_secplus_v2_alloc(SubGhzEnvironment* environment); /** * Free SubGhzProtocolDecoderSecPlus_v2. * @param context Pointer to a SubGhzProtocolDecoderSecPlus_v2 instance */ void subghz_protocol_decoder_secplus_v2_free(void* context); /** * Reset decoder SubGhzProtocolDecoderSecPlus_v2. * @param context Pointer to a SubGhzProtocolDecoderSecPlus_v2 instance */ void subghz_protocol_decoder_secplus_v2_reset(void* context); /** * Parse a raw sequence of levels and durations received from the air. * @param context Pointer to a SubGhzProtocolDecoderSecPlus_v2 instance * @param level Signal level true-high false-low * @param duration Duration of this level in, us */ void subghz_protocol_decoder_secplus_v2_feed(void* context, bool level, uint32_t duration); /** * Getting the hash sum of the last randomly received parcel. * @param context Pointer to a SubGhzProtocolDecoderSecPlus_v2 instance * @return hash Hash sum */ uint8_t subghz_protocol_decoder_secplus_v2_get_hash_data(void* context); /** * Serialize data SubGhzProtocolDecoderSecPlus_v2. * @param context Pointer to a SubGhzProtocolDecoderSecPlus_v2 instance * @param flipper_format Pointer to a FlipperFormat instance * @param preset The modulation on which the signal was received, SubGhzRadioPreset * @return status */ SubGhzProtocolStatus subghz_protocol_decoder_secplus_v2_serialize( void* context, FlipperFormat* flipper_format, SubGhzRadioPreset* preset); /** * Deserialize data SubGhzProtocolDecoderSecPlus_v2. * @param context Pointer to a SubGhzProtocolDecoderSecPlus_v2 instance * @param flipper_format Pointer to a FlipperFormat instance * @return status */ SubGhzProtocolStatus subghz_protocol_decoder_secplus_v2_deserialize(void* context, FlipperFormat* flipper_format); /** * Getting a textual representation of the received data. * @param context Pointer to a SubGhzProtocolDecoderSecPlus_v2 instance * @param output Resulting text */ void subghz_protocol_decoder_secplus_v2_get_string(void* context, FuriString* output);
3,989
C
.c
93
40.913978
97
0.81387
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,296
marantec.c
DarkFlippers_unleashed-firmware/lib/subghz/protocols/marantec.c
#include "marantec.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" #define TAG "SubGhzProtocolMarantec" static const SubGhzBlockConst subghz_protocol_marantec_const = { .te_short = 1000, .te_long = 2000, .te_delta = 200, .min_count_bit_for_found = 49, }; struct SubGhzProtocolDecoderMarantec { SubGhzProtocolDecoderBase base; SubGhzBlockDecoder decoder; SubGhzBlockGeneric generic; ManchesterState manchester_saved_state; uint16_t header_count; }; struct SubGhzProtocolEncoderMarantec { SubGhzProtocolEncoderBase base; SubGhzProtocolBlockEncoder encoder; SubGhzBlockGeneric generic; }; typedef enum { MarantecDecoderStepReset = 0, MarantecDecoderFoundHeader, MarantecDecoderStepDecoderData, } MarantecDecoderStep; const SubGhzProtocolDecoder subghz_protocol_marantec_decoder = { .alloc = subghz_protocol_decoder_marantec_alloc, .free = subghz_protocol_decoder_marantec_free, .feed = subghz_protocol_decoder_marantec_feed, .reset = subghz_protocol_decoder_marantec_reset, .get_hash_data = subghz_protocol_decoder_marantec_get_hash_data, .serialize = subghz_protocol_decoder_marantec_serialize, .deserialize = subghz_protocol_decoder_marantec_deserialize, .get_string = subghz_protocol_decoder_marantec_get_string, }; const SubGhzProtocolEncoder subghz_protocol_marantec_encoder = { .alloc = subghz_protocol_encoder_marantec_alloc, .free = subghz_protocol_encoder_marantec_free, .deserialize = subghz_protocol_encoder_marantec_deserialize, .stop = subghz_protocol_encoder_marantec_stop, .yield = subghz_protocol_encoder_marantec_yield, }; const SubGhzProtocol subghz_protocol_marantec = { .name = SUBGHZ_PROTOCOL_MARANTEC_NAME, .type = SubGhzProtocolTypeStatic, .flag = SubGhzProtocolFlag_433 | SubGhzProtocolFlag_AM | SubGhzProtocolFlag_Decodable | SubGhzProtocolFlag_Load | SubGhzProtocolFlag_Save | SubGhzProtocolFlag_Send, .decoder = &subghz_protocol_marantec_decoder, .encoder = &subghz_protocol_marantec_encoder, }; void* subghz_protocol_encoder_marantec_alloc(SubGhzEnvironment* environment) { UNUSED(environment); SubGhzProtocolEncoderMarantec* instance = malloc(sizeof(SubGhzProtocolEncoderMarantec)); instance->base.protocol = &subghz_protocol_marantec; 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_running = false; return instance; } void subghz_protocol_encoder_marantec_free(void* context) { furi_assert(context); SubGhzProtocolEncoderMarantec* instance = context; free(instance->encoder.upload); free(instance); } static LevelDuration subghz_protocol_encoder_marantec_add_duration_to_upload(ManchesterEncoderResult result) { LevelDuration data = {.duration = 0, .level = 0}; switch(result) { case ManchesterEncoderResultShortLow: data.duration = subghz_protocol_marantec_const.te_short; data.level = false; break; case ManchesterEncoderResultLongLow: data.duration = subghz_protocol_marantec_const.te_long; data.level = false; break; case ManchesterEncoderResultLongHigh: data.duration = subghz_protocol_marantec_const.te_long; data.level = true; break; case ManchesterEncoderResultShortHigh: data.duration = subghz_protocol_marantec_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 SubGhzProtocolEncoderMarantec instance */ static void subghz_protocol_encoder_marantec_get_upload(SubGhzProtocolEncoderMarantec* instance) { furi_assert(instance); size_t index = 0; ManchesterEncoderState enc_state; manchester_encoder_reset(&enc_state); ManchesterEncoderResult result; if(!manchester_encoder_advance( &enc_state, bit_read(instance->generic.data, instance->generic.data_count_bit - 1), &result)) { instance->encoder.upload[index++] = subghz_protocol_encoder_marantec_add_duration_to_upload(result); manchester_encoder_advance( &enc_state, bit_read(instance->generic.data, instance->generic.data_count_bit - 1), &result); } instance->encoder.upload[index++] = level_duration_make(false, (uint32_t)subghz_protocol_marantec_const.te_long * 5); for(uint8_t i = instance->generic.data_count_bit - 1; i > 0; i--) { if(!manchester_encoder_advance( &enc_state, bit_read(instance->generic.data, i - 1), &result)) { instance->encoder.upload[index++] = subghz_protocol_encoder_marantec_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_marantec_add_duration_to_upload(result); } instance->encoder.upload[index] = subghz_protocol_encoder_marantec_add_duration_to_upload( manchester_encoder_finish(&enc_state)); if(level_duration_get_level(instance->encoder.upload[index])) { index++; } instance->encoder.size_upload = index; } uint8_t subghz_protocol_marantec_crc8(uint8_t* data, size_t len) { uint8_t crc = 0x08; size_t i, j; for(i = 0; i < len; i++) { crc ^= data[i]; for(j = 0; j < 8; j++) { if((crc & 0x80) != 0) crc = (uint8_t)((crc << 1) ^ 0x1D); else crc <<= 1; } } return crc; } /** * Analysis of received data * @param instance Pointer to a SubGhzBlockGeneric* instance */ static void subghz_protocol_marantec_remote_controller(SubGhzBlockGeneric* instance) { instance->btn = (instance->data >> 16) & 0xF; instance->serial = ((instance->data >> 12) & 0xFFFFFF00) | ((instance->data >> 8) & 0xFF); } SubGhzProtocolStatus subghz_protocol_encoder_marantec_deserialize(void* context, FlipperFormat* flipper_format) { furi_assert(context); SubGhzProtocolEncoderMarantec* instance = context; SubGhzProtocolStatus ret = SubGhzProtocolStatusError; do { ret = subghz_block_generic_deserialize_check_count_bit( &instance->generic, flipper_format, subghz_protocol_marantec_const.min_count_bit_for_found); if(ret != SubGhzProtocolStatusOk) { break; } //optional parameter parameter flipper_format_read_uint32( flipper_format, "Repeat", (uint32_t*)&instance->encoder.repeat, 1); subghz_protocol_marantec_remote_controller(&instance->generic); subghz_protocol_encoder_marantec_get_upload(instance); instance->encoder.is_running = true; } while(false); return ret; } void subghz_protocol_encoder_marantec_stop(void* context) { SubGhzProtocolEncoderMarantec* instance = context; instance->encoder.is_running = false; } LevelDuration subghz_protocol_encoder_marantec_yield(void* context) { SubGhzProtocolEncoderMarantec* instance = context; if(instance->encoder.repeat == 0 || !instance->encoder.is_running) { instance->encoder.is_running = 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; } void* subghz_protocol_decoder_marantec_alloc(SubGhzEnvironment* environment) { UNUSED(environment); SubGhzProtocolDecoderMarantec* instance = malloc(sizeof(SubGhzProtocolDecoderMarantec)); instance->base.protocol = &subghz_protocol_marantec; instance->generic.protocol_name = instance->base.protocol->name; return instance; } void subghz_protocol_decoder_marantec_free(void* context) { furi_assert(context); SubGhzProtocolDecoderMarantec* instance = context; free(instance); } void subghz_protocol_decoder_marantec_reset(void* context) { furi_assert(context); SubGhzProtocolDecoderMarantec* instance = context; manchester_advance( instance->manchester_saved_state, ManchesterEventReset, &instance->manchester_saved_state, NULL); } void subghz_protocol_decoder_marantec_feed(void* context, bool level, volatile uint32_t duration) { furi_assert(context); SubGhzProtocolDecoderMarantec* instance = context; ManchesterEvent event = ManchesterEventReset; switch(instance->decoder.parser_step) { case MarantecDecoderStepReset: if((!level) && (DURATION_DIFF(duration, subghz_protocol_marantec_const.te_long * 5) < subghz_protocol_marantec_const.te_delta * 8)) { //Found header marantec instance->decoder.parser_step = MarantecDecoderStepDecoderData; instance->decoder.decode_data = 1; instance->decoder.decode_count_bit = 1; manchester_advance( instance->manchester_saved_state, ManchesterEventReset, &instance->manchester_saved_state, NULL); } break; case MarantecDecoderStepDecoderData: if(!level) { if(DURATION_DIFF(duration, subghz_protocol_marantec_const.te_short) < subghz_protocol_marantec_const.te_delta) { event = ManchesterEventShortLow; } else if( DURATION_DIFF(duration, subghz_protocol_marantec_const.te_long) < subghz_protocol_marantec_const.te_delta) { event = ManchesterEventLongLow; } else if( duration >= ((uint32_t)subghz_protocol_marantec_const.te_long * 2 + subghz_protocol_marantec_const.te_delta)) { if(instance->decoder.decode_count_bit == subghz_protocol_marantec_const.min_count_bit_for_found) { instance->generic.data = instance->decoder.decode_data; instance->generic.data_count_bit = instance->decoder.decode_count_bit; if(instance->base.callback) instance->base.callback(&instance->base, instance->base.context); } instance->decoder.decode_data = 1; instance->decoder.decode_count_bit = 1; manchester_advance( instance->manchester_saved_state, ManchesterEventReset, &instance->manchester_saved_state, NULL); } else { instance->decoder.parser_step = MarantecDecoderStepReset; } } else { if(DURATION_DIFF(duration, subghz_protocol_marantec_const.te_short) < subghz_protocol_marantec_const.te_delta) { event = ManchesterEventShortHigh; } else if( DURATION_DIFF(duration, subghz_protocol_marantec_const.te_long) < subghz_protocol_marantec_const.te_delta) { event = ManchesterEventLongHigh; } else { instance->decoder.parser_step = MarantecDecoderStepReset; } } 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_marantec_get_hash_data(void* context) { furi_assert(context); SubGhzProtocolDecoderMarantec* instance = context; return subghz_protocol_blocks_get_hash_data( &instance->decoder, (instance->decoder.decode_count_bit / 8) + 1); } SubGhzProtocolStatus subghz_protocol_decoder_marantec_serialize( void* context, FlipperFormat* flipper_format, SubGhzRadioPreset* preset) { furi_assert(context); SubGhzProtocolDecoderMarantec* instance = context; return subghz_block_generic_serialize(&instance->generic, flipper_format, preset); } SubGhzProtocolStatus subghz_protocol_decoder_marantec_deserialize(void* context, FlipperFormat* flipper_format) { furi_assert(context); SubGhzProtocolDecoderMarantec* instance = context; return subghz_block_generic_deserialize_check_count_bit( &instance->generic, flipper_format, subghz_protocol_marantec_const.min_count_bit_for_found); } void subghz_protocol_decoder_marantec_get_string(void* context, FuriString* output) { furi_assert(context); SubGhzProtocolDecoderMarantec* instance = context; subghz_protocol_marantec_remote_controller(&instance->generic); furi_string_cat_printf( output, "%s %db\r\n" "Key:0x%lX%08lX\r\n" "Sn:0x%07lX \r\n" "Btn:%X\r\n", instance->generic.protocol_name, instance->generic.data_count_bit, (uint32_t)(instance->generic.data >> 32), (uint32_t)(instance->generic.data & 0xFFFFFFFF), instance->generic.serial, instance->generic.btn); }
13,951
C
.c
335
33.99403
99
0.674405
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,297
came_twee.c
DarkFlippers_unleashed-firmware/lib/subghz/protocols/came_twee.c
#include "came_twee.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://phreakerclub.com/forum/showthread.php?t=635&highlight=came+twin * */ #define TAG "SubGhzProtocolCameTwee" #define DIP_PATTERN "%c%c%c%c%c%c%c%c%c%c" #define CNT_TO_DIP(dip) \ (dip & 0x0200 ? '1' : '0'), (dip & 0x0100 ? '1' : '0'), (dip & 0x0080 ? '1' : '0'), \ (dip & 0x0040 ? '1' : '0'), (dip & 0x0020 ? '1' : '0'), (dip & 0x0010 ? '1' : '0'), \ (dip & 0x0008 ? '1' : '0'), (dip & 0x0004 ? '1' : '0'), (dip & 0x0002 ? '1' : '0'), \ (dip & 0x0001 ? '1' : '0') /** * Rainbow table Came Twee. */ static const uint32_t came_twee_magic_numbers_xor[15] = { 0x0E0E0E00, 0x1D1D1D11, 0x2C2C2C22, 0x3B3B3B33, 0x4A4A4A44, 0x59595955, 0x68686866, 0x77777777, 0x86868688, 0x95959599, 0xA4A4A4AA, 0xB3B3B3BB, 0xC2C2C2CC, 0xD1D1D1DD, 0xE0E0E0EE, }; static const SubGhzBlockConst subghz_protocol_came_twee_const = { .te_short = 500, .te_long = 1000, .te_delta = 250, .min_count_bit_for_found = 54, }; struct SubGhzProtocolDecoderCameTwee { SubGhzProtocolDecoderBase base; SubGhzBlockDecoder decoder; SubGhzBlockGeneric generic; ManchesterState manchester_saved_state; }; struct SubGhzProtocolEncoderCameTwee { SubGhzProtocolEncoderBase base; SubGhzProtocolBlockEncoder encoder; SubGhzBlockGeneric generic; }; typedef enum { CameTweeDecoderStepReset = 0, CameTweeDecoderStepDecoderData, } CameTweeDecoderStep; const SubGhzProtocolDecoder subghz_protocol_came_twee_decoder = { .alloc = subghz_protocol_decoder_came_twee_alloc, .free = subghz_protocol_decoder_came_twee_free, .feed = subghz_protocol_decoder_came_twee_feed, .reset = subghz_protocol_decoder_came_twee_reset, .get_hash_data = subghz_protocol_decoder_came_twee_get_hash_data, .serialize = subghz_protocol_decoder_came_twee_serialize, .deserialize = subghz_protocol_decoder_came_twee_deserialize, .get_string = subghz_protocol_decoder_came_twee_get_string, }; const SubGhzProtocolEncoder subghz_protocol_came_twee_encoder = { .alloc = subghz_protocol_encoder_came_twee_alloc, .free = subghz_protocol_encoder_came_twee_free, .deserialize = subghz_protocol_encoder_came_twee_deserialize, .stop = subghz_protocol_encoder_came_twee_stop, .yield = subghz_protocol_encoder_came_twee_yield, }; const SubGhzProtocol subghz_protocol_came_twee = { .name = SUBGHZ_PROTOCOL_CAME_TWEE_NAME, .type = SubGhzProtocolTypeStatic, .flag = SubGhzProtocolFlag_433 | SubGhzProtocolFlag_AM | SubGhzProtocolFlag_Decodable | SubGhzProtocolFlag_Load | SubGhzProtocolFlag_Save | SubGhzProtocolFlag_Send, .decoder = &subghz_protocol_came_twee_decoder, .encoder = &subghz_protocol_came_twee_encoder, }; void* subghz_protocol_encoder_came_twee_alloc(SubGhzEnvironment* environment) { UNUSED(environment); SubGhzProtocolEncoderCameTwee* instance = malloc(sizeof(SubGhzProtocolEncoderCameTwee)); instance->base.protocol = &subghz_protocol_came_twee; instance->generic.protocol_name = instance->base.protocol->name; instance->encoder.repeat = 10; instance->encoder.size_upload = 1536; //max upload 92*14 = 1288 !!!! instance->encoder.upload = malloc(instance->encoder.size_upload * sizeof(LevelDuration)); instance->encoder.is_running = false; return instance; } void subghz_protocol_encoder_came_twee_free(void* context) { furi_assert(context); SubGhzProtocolEncoderCameTwee* instance = context; free(instance->encoder.upload); free(instance); } static LevelDuration subghz_protocol_encoder_came_twee_add_duration_to_upload(ManchesterEncoderResult result) { LevelDuration data = {.duration = 0, .level = 0}; switch(result) { case ManchesterEncoderResultShortLow: data.duration = subghz_protocol_came_twee_const.te_short; data.level = false; break; case ManchesterEncoderResultLongLow: data.duration = subghz_protocol_came_twee_const.te_long; data.level = false; break; case ManchesterEncoderResultLongHigh: data.duration = subghz_protocol_came_twee_const.te_long; data.level = true; break; case ManchesterEncoderResultShortHigh: data.duration = subghz_protocol_came_twee_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 SubGhzProtocolEncoderCameTwee instance */ static void subghz_protocol_encoder_came_twee_get_upload(SubGhzProtocolEncoderCameTwee* instance) { furi_assert(instance); size_t index = 0; ManchesterEncoderState enc_state; manchester_encoder_reset(&enc_state); ManchesterEncoderResult result; uint64_t temp_parcel = 0x003FFF7200000000; //parcel mask for(int i = 14; i >= 0; i--) { temp_parcel = (temp_parcel & 0xFFFFFFFF00000000) | (instance->generic.serial ^ came_twee_magic_numbers_xor[i]); for(uint8_t i = instance->generic.data_count_bit; i > 0; i--) { if(!manchester_encoder_advance(&enc_state, !bit_read(temp_parcel, i - 1), &result)) { instance->encoder.upload[index++] = subghz_protocol_encoder_came_twee_add_duration_to_upload(result); manchester_encoder_advance(&enc_state, !bit_read(temp_parcel, i - 1), &result); } instance->encoder.upload[index++] = subghz_protocol_encoder_came_twee_add_duration_to_upload(result); } instance->encoder.upload[index] = subghz_protocol_encoder_came_twee_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_came_twee_const.te_long * 51); } instance->encoder.size_upload = index; } /** * Analysis of received data * @param instance Pointer to a SubGhzBlockGeneric* instance */ static void subghz_protocol_came_twee_remote_controller(SubGhzBlockGeneric* instance) { /* Came Twee 54 bit, rolling code 15 parcels with * a decreasing counter from 0xE to 0x0 * with originally coded dip switches on the console 10 bit code * * 0x003FFF72E04A6FEE * 0x003FFF72D17B5EDD * 0x003FFF72C2684DCC * 0x003FFF72B3193CBB * 0x003FFF72A40E2BAA * 0x003FFF72953F1A99 * 0x003FFF72862C0988 * 0x003FFF7277DDF877 * 0x003FFF7268C2E766 * 0x003FFF7259F3D655 * 0x003FFF724AE0C544 * 0x003FFF723B91B433 * 0x003FFF722C86A322 * 0x003FFF721DB79211 * 0x003FFF720EA48100 * * decryption * the last 32 bits, do XOR by the desired number, divide the result by 4, * convert the first 16 bits of the resulting 32-bit number to bin and do * bit-by-bit mirroring, adding up to 10 bits * * Example * Step 1. 0x003FFF721DB79211 => 0x1DB79211 * Step 4. 0x1DB79211 xor 0x1D1D1D11 => 0x00AA8F00 * Step 4. 0x00AA8F00 / 4 => 0x002AA3C0 * Step 5. 0x002AA3C0 => 0x002A * Step 6. 0x002A bin => b101010 * Step 7. b101010 => b0101010000 * Step 8. b0101010000 => (Dip) Off ON Off ON Off ON Off Off Off Off */ uint8_t cnt_parcel = (uint8_t)(instance->data & 0xF); uint32_t data = (uint32_t)(instance->data & 0x0FFFFFFFF); data = (data ^ came_twee_magic_numbers_xor[cnt_parcel]); instance->serial = data; data /= 4; instance->btn = (data >> 4) & 0x0F; data >>= 16; data = (uint16_t)subghz_protocol_blocks_reverse_key(data, 16); instance->cnt = data >> 6; } SubGhzProtocolStatus subghz_protocol_encoder_came_twee_deserialize(void* context, FlipperFormat* flipper_format) { furi_assert(context); SubGhzProtocolEncoderCameTwee* instance = context; SubGhzProtocolStatus res = SubGhzProtocolStatusError; do { res = subghz_block_generic_deserialize_check_count_bit( &instance->generic, flipper_format, subghz_protocol_came_twee_const.min_count_bit_for_found); if(res != SubGhzProtocolStatusOk) { break; } //optional parameter parameter flipper_format_read_uint32( flipper_format, "Repeat", (uint32_t*)&instance->encoder.repeat, 1); subghz_protocol_came_twee_remote_controller(&instance->generic); subghz_protocol_encoder_came_twee_get_upload(instance); instance->encoder.is_running = true; } while(false); return res; } void subghz_protocol_encoder_came_twee_stop(void* context) { SubGhzProtocolEncoderCameTwee* instance = context; instance->encoder.is_running = false; } LevelDuration subghz_protocol_encoder_came_twee_yield(void* context) { SubGhzProtocolEncoderCameTwee* instance = context; if(instance->encoder.repeat == 0 || !instance->encoder.is_running) { instance->encoder.is_running = 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; } void* subghz_protocol_decoder_came_twee_alloc(SubGhzEnvironment* environment) { UNUSED(environment); SubGhzProtocolDecoderCameTwee* instance = malloc(sizeof(SubGhzProtocolDecoderCameTwee)); instance->base.protocol = &subghz_protocol_came_twee; instance->generic.protocol_name = instance->base.protocol->name; return instance; } void subghz_protocol_decoder_came_twee_free(void* context) { furi_assert(context); SubGhzProtocolDecoderCameTwee* instance = context; free(instance); } void subghz_protocol_decoder_came_twee_reset(void* context) { furi_assert(context); SubGhzProtocolDecoderCameTwee* instance = context; instance->decoder.parser_step = CameTweeDecoderStepReset; manchester_advance( instance->manchester_saved_state, ManchesterEventReset, &instance->manchester_saved_state, NULL); } void subghz_protocol_decoder_came_twee_feed(void* context, bool level, uint32_t duration) { furi_assert(context); SubGhzProtocolDecoderCameTwee* instance = context; ManchesterEvent event = ManchesterEventReset; switch(instance->decoder.parser_step) { case CameTweeDecoderStepReset: if((!level) && (DURATION_DIFF(duration, subghz_protocol_came_twee_const.te_long * 51) < subghz_protocol_came_twee_const.te_delta * 20)) { //Found header CAME instance->decoder.parser_step = CameTweeDecoderStepDecoderData; instance->decoder.decode_data = 0; instance->decoder.decode_count_bit = 0; manchester_advance( instance->manchester_saved_state, ManchesterEventLongLow, &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 CameTweeDecoderStepDecoderData: if(!level) { if(DURATION_DIFF(duration, subghz_protocol_came_twee_const.te_short) < subghz_protocol_came_twee_const.te_delta) { event = ManchesterEventShortLow; } else if( DURATION_DIFF(duration, subghz_protocol_came_twee_const.te_long) < subghz_protocol_came_twee_const.te_delta) { event = ManchesterEventLongLow; } else if( duration >= ((uint32_t)subghz_protocol_came_twee_const.te_long * 2 + subghz_protocol_came_twee_const.te_delta)) { if(instance->decoder.decode_count_bit == subghz_protocol_came_twee_const.min_count_bit_for_found) { instance->generic.data = instance->decoder.decode_data; instance->generic.data_count_bit = instance->decoder.decode_count_bit; if(instance->base.callback) instance->base.callback(&instance->base, instance->base.context); } instance->decoder.decode_data = 0; instance->decoder.decode_count_bit = 0; manchester_advance( instance->manchester_saved_state, ManchesterEventLongLow, &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 = CameTweeDecoderStepReset; } } else { if(DURATION_DIFF(duration, subghz_protocol_came_twee_const.te_short) < subghz_protocol_came_twee_const.te_delta) { event = ManchesterEventShortHigh; } else if( DURATION_DIFF(duration, subghz_protocol_came_twee_const.te_long) < subghz_protocol_came_twee_const.te_delta) { event = ManchesterEventLongHigh; } else { instance->decoder.parser_step = CameTweeDecoderStepReset; } } 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_came_twee_get_hash_data(void* context) { furi_assert(context); SubGhzProtocolDecoderCameTwee* instance = context; return subghz_protocol_blocks_get_hash_data( &instance->decoder, (instance->decoder.decode_count_bit / 8) + 1); } SubGhzProtocolStatus subghz_protocol_decoder_came_twee_serialize( void* context, FlipperFormat* flipper_format, SubGhzRadioPreset* preset) { furi_assert(context); SubGhzProtocolDecoderCameTwee* instance = context; return subghz_block_generic_serialize(&instance->generic, flipper_format, preset); } SubGhzProtocolStatus subghz_protocol_decoder_came_twee_deserialize(void* context, FlipperFormat* flipper_format) { furi_assert(context); SubGhzProtocolDecoderCameTwee* instance = context; return subghz_block_generic_deserialize_check_count_bit( &instance->generic, flipper_format, subghz_protocol_came_twee_const.min_count_bit_for_found); } void subghz_protocol_decoder_came_twee_get_string(void* context, FuriString* output) { furi_assert(context); SubGhzProtocolDecoderCameTwee* instance = context; subghz_protocol_came_twee_remote_controller(&instance->generic); uint32_t code_found_hi = instance->generic.data >> 32; uint32_t code_found_lo = instance->generic.data & 0x00000000ffffffff; furi_string_cat_printf( output, "%s %db\r\n" "Key:0x%lX%08lX\r\n" "Btn:%X\r\n" "DIP:" DIP_PATTERN "\r\n", instance->generic.protocol_name, instance->generic.data_count_bit, code_found_hi, code_found_lo, instance->generic.btn, CNT_TO_DIP(instance->generic.cnt)); }
16,760
C
.c
406
33.600985
99
0.654849
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,298
smc5326.c
DarkFlippers_unleashed-firmware/lib/subghz/protocols/smc5326.c
#include "smc5326.h" #include "../blocks/const.h" #include "../blocks/decoder.h" #include "../blocks/encoder.h" #include "../blocks/generic.h" #include "../blocks/math.h" /* * Help * https://datasheetspdf.com/pdf-file/532079/Aslic/AX5326-4/1 * */ #define TAG "SubGhzProtocolSmc5326" #define DIP_P 0b11 //(+) #define DIP_O 0b10 //(0) #define DIP_N 0b00 //(-) #define DIP_PATTERN "%c%c%c%c%c%c%c%c" #define SHOW_DIP_P(dip, check_dip) \ ((((dip >> 0xE) & 0x3) == check_dip) ? '*' : '_'), \ ((((dip >> 0xC) & 0x3) == check_dip) ? '*' : '_'), \ ((((dip >> 0xA) & 0x3) == check_dip) ? '*' : '_'), \ ((((dip >> 0x8) & 0x3) == check_dip) ? '*' : '_'), \ ((((dip >> 0x6) & 0x3) == check_dip) ? '*' : '_'), \ ((((dip >> 0x4) & 0x3) == check_dip) ? '*' : '_'), \ ((((dip >> 0x2) & 0x3) == check_dip) ? '*' : '_'), \ ((((dip >> 0x0) & 0x3) == check_dip) ? '*' : '_') static const SubGhzBlockConst subghz_protocol_smc5326_const = { .te_short = 300, .te_long = 900, .te_delta = 200, .min_count_bit_for_found = 25, }; struct SubGhzProtocolDecoderSMC5326 { SubGhzProtocolDecoderBase base; SubGhzBlockDecoder decoder; SubGhzBlockGeneric generic; uint32_t te; uint32_t last_data; }; struct SubGhzProtocolEncoderSMC5326 { SubGhzProtocolEncoderBase base; SubGhzProtocolBlockEncoder encoder; SubGhzBlockGeneric generic; uint32_t te; }; typedef enum { SMC5326DecoderStepReset = 0, SMC5326DecoderStepSaveDuration, SMC5326DecoderStepCheckDuration, } SMC5326DecoderStep; const SubGhzProtocolDecoder subghz_protocol_smc5326_decoder = { .alloc = subghz_protocol_decoder_smc5326_alloc, .free = subghz_protocol_decoder_smc5326_free, .feed = subghz_protocol_decoder_smc5326_feed, .reset = subghz_protocol_decoder_smc5326_reset, .get_hash_data = subghz_protocol_decoder_smc5326_get_hash_data, .serialize = subghz_protocol_decoder_smc5326_serialize, .deserialize = subghz_protocol_decoder_smc5326_deserialize, .get_string = subghz_protocol_decoder_smc5326_get_string, }; const SubGhzProtocolEncoder subghz_protocol_smc5326_encoder = { .alloc = subghz_protocol_encoder_smc5326_alloc, .free = subghz_protocol_encoder_smc5326_free, .deserialize = subghz_protocol_encoder_smc5326_deserialize, .stop = subghz_protocol_encoder_smc5326_stop, .yield = subghz_protocol_encoder_smc5326_yield, }; const SubGhzProtocol subghz_protocol_smc5326 = { .name = SUBGHZ_PROTOCOL_SMC5326_NAME, .type = SubGhzProtocolTypeStatic, .flag = SubGhzProtocolFlag_433 | SubGhzProtocolFlag_868 | SubGhzProtocolFlag_315 | SubGhzProtocolFlag_AM | SubGhzProtocolFlag_Decodable | SubGhzProtocolFlag_Load | SubGhzProtocolFlag_Save | SubGhzProtocolFlag_Send, .decoder = &subghz_protocol_smc5326_decoder, .encoder = &subghz_protocol_smc5326_encoder, }; void* subghz_protocol_encoder_smc5326_alloc(SubGhzEnvironment* environment) { UNUSED(environment); SubGhzProtocolEncoderSMC5326* instance = malloc(sizeof(SubGhzProtocolEncoderSMC5326)); instance->base.protocol = &subghz_protocol_smc5326; instance->generic.protocol_name = instance->base.protocol->name; instance->encoder.repeat = 10; instance->encoder.size_upload = 128; instance->encoder.upload = malloc(instance->encoder.size_upload * sizeof(LevelDuration)); instance->encoder.is_running = false; return instance; } void subghz_protocol_encoder_smc5326_free(void* context) { furi_assert(context); SubGhzProtocolEncoderSMC5326* instance = context; free(instance->encoder.upload); free(instance); } /** * Generating an upload from data. * @param instance Pointer to a SubGhzProtocolEncoderSMC5326 instance * @return true On success */ static bool subghz_protocol_encoder_smc5326_get_upload(SubGhzProtocolEncoderSMC5326* instance) { furi_assert(instance); size_t index = 0; size_t size_upload = (instance->generic.data_count_bit * 2) + 2; if(size_upload > instance->encoder.size_upload) { FURI_LOG_E(TAG, "Size upload exceeds allocated encoder buffer."); return false; } else { instance->encoder.size_upload = size_upload; } //Send key data for(uint8_t i = instance->generic.data_count_bit; i > 0; i--) { if(bit_read(instance->generic.data, i - 1)) { //send bit 1 instance->encoder.upload[index++] = level_duration_make(true, (uint32_t)instance->te * 3); instance->encoder.upload[index++] = level_duration_make(false, (uint32_t)instance->te); } else { //send bit 0 instance->encoder.upload[index++] = level_duration_make(true, (uint32_t)instance->te); instance->encoder.upload[index++] = level_duration_make(false, (uint32_t)instance->te * 3); } } //Send Stop bit instance->encoder.upload[index++] = level_duration_make(true, (uint32_t)instance->te); //Send PT_GUARD instance->encoder.upload[index++] = level_duration_make(false, (uint32_t)instance->te * 25); return true; } SubGhzProtocolStatus subghz_protocol_encoder_smc5326_deserialize(void* context, FlipperFormat* flipper_format) { furi_assert(context); SubGhzProtocolEncoderSMC5326* instance = context; SubGhzProtocolStatus ret = SubGhzProtocolStatusError; do { ret = subghz_block_generic_deserialize_check_count_bit( &instance->generic, flipper_format, subghz_protocol_smc5326_const.min_count_bit_for_found); if(ret != SubGhzProtocolStatusOk) { break; } if(!flipper_format_rewind(flipper_format)) { FURI_LOG_E(TAG, "Rewind error"); ret = SubGhzProtocolStatusErrorParserOthers; break; } if(!flipper_format_read_uint32(flipper_format, "TE", (uint32_t*)&instance->te, 1)) { FURI_LOG_E(TAG, "Missing TE"); ret = SubGhzProtocolStatusErrorParserTe; break; } //optional parameter parameter flipper_format_read_uint32( flipper_format, "Repeat", (uint32_t*)&instance->encoder.repeat, 1); if(!subghz_protocol_encoder_smc5326_get_upload(instance)) { ret = SubGhzProtocolStatusErrorEncoderGetUpload; break; } instance->encoder.is_running = true; } while(false); return ret; } void subghz_protocol_encoder_smc5326_stop(void* context) { SubGhzProtocolEncoderSMC5326* instance = context; instance->encoder.is_running = false; } LevelDuration subghz_protocol_encoder_smc5326_yield(void* context) { SubGhzProtocolEncoderSMC5326* instance = context; if(instance->encoder.repeat == 0 || !instance->encoder.is_running) { instance->encoder.is_running = 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; } void* subghz_protocol_decoder_smc5326_alloc(SubGhzEnvironment* environment) { UNUSED(environment); SubGhzProtocolDecoderSMC5326* instance = malloc(sizeof(SubGhzProtocolDecoderSMC5326)); instance->base.protocol = &subghz_protocol_smc5326; instance->generic.protocol_name = instance->base.protocol->name; return instance; } void subghz_protocol_decoder_smc5326_free(void* context) { furi_assert(context); SubGhzProtocolDecoderSMC5326* instance = context; free(instance); } void subghz_protocol_decoder_smc5326_reset(void* context) { furi_assert(context); SubGhzProtocolDecoderSMC5326* instance = context; instance->decoder.parser_step = SMC5326DecoderStepReset; instance->last_data = 0; } void subghz_protocol_decoder_smc5326_feed(void* context, bool level, uint32_t duration) { furi_assert(context); SubGhzProtocolDecoderSMC5326* instance = context; switch(instance->decoder.parser_step) { case SMC5326DecoderStepReset: if((!level) && (DURATION_DIFF(duration, subghz_protocol_smc5326_const.te_short * 24) < subghz_protocol_smc5326_const.te_delta * 12)) { //Found Preambula instance->decoder.parser_step = SMC5326DecoderStepSaveDuration; instance->decoder.decode_data = 0; instance->decoder.decode_count_bit = 0; instance->te = 0; } break; case SMC5326DecoderStepSaveDuration: //save duration if(level) { instance->decoder.te_last = duration; instance->te += duration; instance->decoder.parser_step = SMC5326DecoderStepCheckDuration; } break; case SMC5326DecoderStepCheckDuration: if(!level) { if(duration >= ((uint32_t)subghz_protocol_smc5326_const.te_long * 2)) { instance->decoder.parser_step = SMC5326DecoderStepSaveDuration; if(instance->decoder.decode_count_bit == subghz_protocol_smc5326_const.min_count_bit_for_found) { if((instance->last_data == instance->decoder.decode_data) && instance->last_data) { instance->te /= (instance->decoder.decode_count_bit * 4 + 1); instance->generic.data = instance->decoder.decode_data; instance->generic.data_count_bit = instance->decoder.decode_count_bit; if(instance->base.callback) instance->base.callback(&instance->base, instance->base.context); } instance->last_data = instance->decoder.decode_data; } instance->decoder.decode_data = 0; instance->decoder.decode_count_bit = 0; instance->te = 0; break; } instance->te += duration; if((DURATION_DIFF(instance->decoder.te_last, subghz_protocol_smc5326_const.te_short) < subghz_protocol_smc5326_const.te_delta) && (DURATION_DIFF(duration, subghz_protocol_smc5326_const.te_long) < subghz_protocol_smc5326_const.te_delta * 3)) { subghz_protocol_blocks_add_bit(&instance->decoder, 0); instance->decoder.parser_step = SMC5326DecoderStepSaveDuration; } else if( (DURATION_DIFF(instance->decoder.te_last, subghz_protocol_smc5326_const.te_long) < subghz_protocol_smc5326_const.te_delta * 3) && (DURATION_DIFF(duration, subghz_protocol_smc5326_const.te_short) < subghz_protocol_smc5326_const.te_delta)) { subghz_protocol_blocks_add_bit(&instance->decoder, 1); instance->decoder.parser_step = SMC5326DecoderStepSaveDuration; } else { instance->decoder.parser_step = SMC5326DecoderStepReset; } } else { instance->decoder.parser_step = SMC5326DecoderStepReset; } break; } } uint8_t subghz_protocol_decoder_smc5326_get_hash_data(void* context) { furi_assert(context); SubGhzProtocolDecoderSMC5326* instance = context; return subghz_protocol_blocks_get_hash_data( &instance->decoder, (instance->decoder.decode_count_bit / 8) + 1); } SubGhzProtocolStatus subghz_protocol_decoder_smc5326_serialize( void* context, FlipperFormat* flipper_format, SubGhzRadioPreset* preset) { furi_assert(context); SubGhzProtocolDecoderSMC5326* instance = context; SubGhzProtocolStatus ret = subghz_block_generic_serialize(&instance->generic, flipper_format, preset); if((ret == SubGhzProtocolStatusOk) && !flipper_format_write_uint32(flipper_format, "TE", &instance->te, 1)) { FURI_LOG_E(TAG, "Unable to add TE"); ret = SubGhzProtocolStatusErrorParserTe; } return ret; } SubGhzProtocolStatus subghz_protocol_decoder_smc5326_deserialize(void* context, FlipperFormat* flipper_format) { furi_assert(context); SubGhzProtocolDecoderSMC5326* instance = context; SubGhzProtocolStatus ret = SubGhzProtocolStatusError; do { ret = subghz_block_generic_deserialize_check_count_bit( &instance->generic, flipper_format, subghz_protocol_smc5326_const.min_count_bit_for_found); if(ret != SubGhzProtocolStatusOk) { break; } if(!flipper_format_rewind(flipper_format)) { FURI_LOG_E(TAG, "Rewind error"); ret = SubGhzProtocolStatusErrorParserOthers; break; } if(!flipper_format_read_uint32(flipper_format, "TE", (uint32_t*)&instance->te, 1)) { FURI_LOG_E(TAG, "Missing TE"); ret = SubGhzProtocolStatusErrorParserTe; break; } } while(false); return ret; } static void subghz_protocol_smc5326_get_event_serialize(uint8_t event, FuriString* output) { furi_string_cat_printf( output, "%s%s%s%s\r\n", (((event >> 6) & 0x3) == 0x3 ? "B1 " : ""), (((event >> 4) & 0x3) == 0x3 ? "B2 " : ""), (((event >> 2) & 0x3) == 0x3 ? "B3 " : ""), (((event >> 0) & 0x3) == 0x3 ? "B4 " : "")); } void subghz_protocol_decoder_smc5326_get_string(void* context, FuriString* output) { furi_assert(context); SubGhzProtocolDecoderSMC5326* instance = context; uint32_t data = (uint32_t)((instance->generic.data >> 9) & 0xFFFF); furi_string_cat_printf( output, "%s %ubit\r\n" "Key:%07lX Te:%luus\r\n" " +: " DIP_PATTERN "\r\n" " o: " DIP_PATTERN " ", instance->generic.protocol_name, instance->generic.data_count_bit, (uint32_t)(instance->generic.data & 0x1FFFFFF), instance->te, SHOW_DIP_P(data, DIP_P), SHOW_DIP_P(data, DIP_O)); subghz_protocol_smc5326_get_event_serialize(instance->generic.data >> 1, output); furi_string_cat_printf(output, " -: " DIP_PATTERN "\r\n", SHOW_DIP_P(data, DIP_N)); }
14,337
C
.c
337
34.848665
99
0.643697
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,299
came_atomo.c
DarkFlippers_unleashed-firmware/lib/subghz/protocols/came_atomo.c
#include "came_atomo.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" #include "../blocks/custom_btn_i.h" #define TAG "SubGhzProtocoCameAtomo" static const SubGhzBlockConst subghz_protocol_came_atomo_const = { .te_short = 600, .te_long = 1200, .te_delta = 250, .min_count_bit_for_found = 62, }; struct SubGhzProtocolDecoderCameAtomo { SubGhzProtocolDecoderBase base; SubGhzBlockDecoder decoder; SubGhzBlockGeneric generic; ManchesterState manchester_saved_state; }; struct SubGhzProtocolEncoderCameAtomo { SubGhzProtocolEncoderBase base; SubGhzProtocolBlockEncoder encoder; SubGhzBlockGeneric generic; }; typedef enum { CameAtomoDecoderStepReset = 0, CameAtomoDecoderStepDecoderData, } CameAtomoDecoderStep; const SubGhzProtocolDecoder subghz_protocol_came_atomo_decoder = { .alloc = subghz_protocol_decoder_came_atomo_alloc, .free = subghz_protocol_decoder_came_atomo_free, .feed = subghz_protocol_decoder_came_atomo_feed, .reset = subghz_protocol_decoder_came_atomo_reset, .get_hash_data = subghz_protocol_decoder_came_atomo_get_hash_data, .serialize = subghz_protocol_decoder_came_atomo_serialize, .deserialize = subghz_protocol_decoder_came_atomo_deserialize, .get_string = subghz_protocol_decoder_came_atomo_get_string, }; const SubGhzProtocolEncoder subghz_protocol_came_atomo_encoder = { .alloc = subghz_protocol_encoder_came_atomo_alloc, .free = subghz_protocol_encoder_came_atomo_free, .deserialize = subghz_protocol_encoder_came_atomo_deserialize, .stop = subghz_protocol_encoder_came_atomo_stop, .yield = subghz_protocol_encoder_came_atomo_yield, }; const SubGhzProtocol subghz_protocol_came_atomo = { .name = SUBGHZ_PROTOCOL_CAME_ATOMO_NAME, .type = SubGhzProtocolTypeDynamic, .flag = SubGhzProtocolFlag_433 | SubGhzProtocolFlag_AM | SubGhzProtocolFlag_Decodable | SubGhzProtocolFlag_Load | SubGhzProtocolFlag_Save | SubGhzProtocolFlag_Send, .decoder = &subghz_protocol_came_atomo_decoder, .encoder = &subghz_protocol_came_atomo_encoder, }; static void subghz_protocol_came_atomo_remote_controller(SubGhzBlockGeneric* instance); /** * Defines the button value for the current btn_id * Basic set | 0x0 | 0x2 | 0x4 | 0x6 | * @return Button code */ static uint8_t subghz_protocol_came_atomo_get_btn_code(void); void* subghz_protocol_encoder_came_atomo_alloc(SubGhzEnvironment* environment) { UNUSED(environment); SubGhzProtocolEncoderCameAtomo* instance = malloc(sizeof(SubGhzProtocolEncoderCameAtomo)); instance->base.protocol = &subghz_protocol_came_atomo; instance->generic.protocol_name = instance->base.protocol->name; instance->encoder.repeat = 10; instance->encoder.size_upload = 900; //actual size 766+ instance->encoder.upload = malloc(instance->encoder.size_upload * sizeof(LevelDuration)); instance->encoder.is_running = false; return instance; } void subghz_protocol_encoder_came_atomo_free(void* context) { furi_assert(context); SubGhzProtocolEncoderCameAtomo* instance = context; free(instance->encoder.upload); free(instance); } static LevelDuration subghz_protocol_encoder_came_atomo_add_duration_to_upload(ManchesterEncoderResult result) { LevelDuration data = {.duration = 0, .level = 0}; switch(result) { case ManchesterEncoderResultShortLow: data.duration = subghz_protocol_came_atomo_const.te_short; data.level = false; break; case ManchesterEncoderResultLongLow: data.duration = subghz_protocol_came_atomo_const.te_long; data.level = false; break; case ManchesterEncoderResultLongHigh: data.duration = subghz_protocol_came_atomo_const.te_long; data.level = true; break; case ManchesterEncoderResultShortHigh: data.duration = subghz_protocol_came_atomo_const.te_short; data.level = true; break; default: FURI_LOG_E(TAG, "SubGhz: ManchesterEncoderResult is incorrect."); break; } return level_duration_make(data.level, data.duration); } bool subghz_protocol_came_atomo_create_data( void* context, FlipperFormat* flipper_format, uint32_t serial, uint16_t cnt, SubGhzRadioPreset* preset) { furi_assert(context); SubGhzProtocolEncoderCameAtomo* instance = context; instance->generic.btn = 0x1; instance->generic.serial = serial; instance->generic.cnt = cnt; instance->generic.cnt_2 = 0x7e; instance->generic.data_count_bit = 62; instance->generic.data_2 = ((uint64_t)0x7e << 56 | (uint64_t)cnt << 40 | (uint64_t)serial << 8); uint8_t pack[8] = {}; pack[0] = (instance->generic.cnt_2); pack[1] = (instance->generic.cnt >> 8); pack[2] = (instance->generic.cnt & 0xFF); pack[3] = ((instance->generic.data_2 >> 32) & 0xFF); pack[4] = ((instance->generic.data_2 >> 24) & 0xFF); pack[5] = ((instance->generic.data_2 >> 16) & 0xFF); pack[6] = ((instance->generic.data_2 >> 8) & 0xFF); pack[7] = (instance->generic.data_2 & 0xFF); atomo_encrypt(pack); uint32_t hi = pack[0] << 24 | pack[1] << 16 | pack[2] << 8 | pack[3]; uint32_t lo = pack[4] << 24 | pack[5] << 16 | pack[6] << 8 | pack[7]; instance->generic.data = (uint64_t)hi << 32 | lo; instance->generic.data ^= 0xFFFFFFFFFFFFFFFF; instance->generic.data >>= 4; instance->generic.data &= 0xFFFFFFFFFFFFFFF; return SubGhzProtocolStatusOk == subghz_block_generic_serialize(&instance->generic, flipper_format, preset); } /** * Generating an upload from data. * @param instance Pointer to a SubGhzProtocolEncoderCameAtomo instance */ static void subghz_protocol_encoder_came_atomo_get_upload( SubGhzProtocolEncoderCameAtomo* instance, uint8_t btn) { furi_assert(instance); size_t index = 0; ManchesterEncoderState enc_state; manchester_encoder_reset(&enc_state); ManchesterEncoderResult result; uint8_t pack[8] = {}; if(instance->generic.cnt < 0xFFFF) { if((instance->generic.cnt + furi_hal_subghz_get_rolling_counter_mult()) > 0xFFFF) { instance->generic.cnt = 0; } else { instance->generic.cnt += furi_hal_subghz_get_rolling_counter_mult(); } } else if(instance->generic.cnt >= 0xFFFF) { instance->generic.cnt = 0; } // Save original button for later use if(subghz_custom_btn_get_original() == 0) { subghz_custom_btn_set_original(btn); } btn = subghz_protocol_came_atomo_get_btn_code(); if(btn == 0x1) { btn = 0x0; } else if(btn == 0x2) { btn = 0x2; } else if(btn == 0x3) { btn = 0x4; } else if(btn == 0x4) { btn = 0x6; } //Send header instance->encoder.upload[index++] = level_duration_make(true, (uint32_t)subghz_protocol_came_atomo_const.te_long * 15); instance->encoder.upload[index++] = level_duration_make(false, (uint32_t)subghz_protocol_came_atomo_const.te_long * 60); for(uint8_t i = 0; i < 8; i++) { pack[0] = (instance->generic.data_2 >> 56); pack[1] = (instance->generic.cnt >> 8); pack[2] = (instance->generic.cnt & 0xFF); pack[3] = ((instance->generic.data_2 >> 32) & 0xFF); pack[4] = ((instance->generic.data_2 >> 24) & 0xFF); pack[5] = ((instance->generic.data_2 >> 16) & 0xFF); pack[6] = ((instance->generic.data_2 >> 8) & 0xFF); pack[7] = (btn << 4); if(pack[0] == 0x7F) { pack[0] = 0; } else { pack[0] += (i + 1); } atomo_encrypt(pack); uint32_t hi = pack[0] << 24 | pack[1] << 16 | pack[2] << 8 | pack[3]; uint32_t lo = pack[4] << 24 | pack[5] << 16 | pack[6] << 8 | pack[7]; instance->generic.data = (uint64_t)hi << 32 | lo; instance->generic.data ^= 0xFFFFFFFFFFFFFFFF; instance->generic.data >>= 4; instance->generic.data &= 0xFFFFFFFFFFFFFFF; instance->encoder.upload[index++] = level_duration_make(true, (uint32_t)subghz_protocol_came_atomo_const.te_long); instance->encoder.upload[index++] = level_duration_make(false, (uint32_t)subghz_protocol_came_atomo_const.te_short); for(uint8_t i = (instance->generic.data_count_bit - 2); i > 0; i--) { if(!manchester_encoder_advance( &enc_state, !bit_read(instance->generic.data, i - 1), &result)) { instance->encoder.upload[index++] = subghz_protocol_encoder_came_atomo_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_came_atomo_add_duration_to_upload(result); } instance->encoder.upload[index] = subghz_protocol_encoder_came_atomo_add_duration_to_upload( manchester_encoder_finish(&enc_state)); if(level_duration_get_level(instance->encoder.upload[index])) { index++; } //Send pause instance->encoder.upload[index++] = level_duration_make(false, (uint32_t)subghz_protocol_came_atomo_const.te_delta * 272); } instance->encoder.size_upload = index; instance->generic.cnt_2++; pack[0] = (instance->generic.cnt_2); pack[1] = (instance->generic.cnt >> 8); pack[2] = (instance->generic.cnt & 0xFF); pack[3] = ((instance->generic.data_2 >> 32) & 0xFF); pack[4] = ((instance->generic.data_2 >> 24) & 0xFF); pack[5] = ((instance->generic.data_2 >> 16) & 0xFF); pack[6] = ((instance->generic.data_2 >> 8) & 0xFF); pack[7] = (btn << 4); atomo_encrypt(pack); uint32_t hi = pack[0] << 24 | pack[1] << 16 | pack[2] << 8 | pack[3]; uint32_t lo = pack[4] << 24 | pack[5] << 16 | pack[6] << 8 | pack[7]; instance->generic.data = (uint64_t)hi << 32 | lo; instance->generic.data ^= 0xFFFFFFFFFFFFFFFF; instance->generic.data >>= 4; instance->generic.data &= 0xFFFFFFFFFFFFFFF; } SubGhzProtocolStatus subghz_protocol_encoder_came_atomo_deserialize(void* context, FlipperFormat* flipper_format) { furi_assert(context); SubGhzProtocolEncoderCameAtomo* instance = context; SubGhzProtocolStatus res = SubGhzProtocolStatusError; do { if(SubGhzProtocolStatusOk != subghz_block_generic_deserialize(&instance->generic, flipper_format)) { FURI_LOG_E(TAG, "Deserialize error"); break; } //optional parameter parameter flipper_format_read_uint32( flipper_format, "Repeat", (uint32_t*)&instance->encoder.repeat, 1); subghz_protocol_came_atomo_remote_controller(&instance->generic); subghz_protocol_encoder_came_atomo_get_upload(instance, instance->generic.btn); if(!flipper_format_rewind(flipper_format)) { FURI_LOG_E(TAG, "Rewind error"); break; } 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->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; } instance->encoder.is_running = true; res = SubGhzProtocolStatusOk; } while(false); return res; } void subghz_protocol_encoder_came_atomo_stop(void* context) { SubGhzProtocolEncoderCameAtomo* instance = context; instance->encoder.is_running = false; } LevelDuration subghz_protocol_encoder_came_atomo_yield(void* context) { SubGhzProtocolEncoderCameAtomo* instance = context; if(instance->encoder.repeat == 0 || !instance->encoder.is_running) { instance->encoder.is_running = 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; } void* subghz_protocol_decoder_came_atomo_alloc(SubGhzEnvironment* environment) { UNUSED(environment); SubGhzProtocolDecoderCameAtomo* instance = malloc(sizeof(SubGhzProtocolDecoderCameAtomo)); instance->base.protocol = &subghz_protocol_came_atomo; instance->generic.protocol_name = instance->base.protocol->name; return instance; } void subghz_protocol_decoder_came_atomo_free(void* context) { furi_assert(context); SubGhzProtocolDecoderCameAtomo* instance = context; free(instance); } void subghz_protocol_decoder_came_atomo_reset(void* context) { furi_assert(context); SubGhzProtocolDecoderCameAtomo* instance = context; instance->decoder.parser_step = CameAtomoDecoderStepReset; manchester_advance( instance->manchester_saved_state, ManchesterEventReset, &instance->manchester_saved_state, NULL); } void subghz_protocol_decoder_came_atomo_feed(void* context, bool level, uint32_t duration) { furi_assert(context); SubGhzProtocolDecoderCameAtomo* instance = context; ManchesterEvent event = ManchesterEventReset; switch(instance->decoder.parser_step) { case CameAtomoDecoderStepReset: if((!level) && (DURATION_DIFF(duration, subghz_protocol_came_atomo_const.te_long * 60) < subghz_protocol_came_atomo_const.te_delta * 40)) { //Found header CAME instance->decoder.parser_step = CameAtomoDecoderStepDecoderData; instance->decoder.decode_data = 0; instance->decoder.decode_count_bit = 1; manchester_advance( instance->manchester_saved_state, ManchesterEventReset, &instance->manchester_saved_state, NULL); manchester_advance( instance->manchester_saved_state, ManchesterEventShortLow, &instance->manchester_saved_state, NULL); } break; case CameAtomoDecoderStepDecoderData: if(!level) { if(DURATION_DIFF(duration, subghz_protocol_came_atomo_const.te_short) < subghz_protocol_came_atomo_const.te_delta) { event = ManchesterEventShortLow; } else if( DURATION_DIFF(duration, subghz_protocol_came_atomo_const.te_long) < subghz_protocol_came_atomo_const.te_delta) { event = ManchesterEventLongLow; } else if( duration >= ((uint32_t)subghz_protocol_came_atomo_const.te_long * 2 + subghz_protocol_came_atomo_const.te_delta)) { if(instance->decoder.decode_count_bit == subghz_protocol_came_atomo_const.min_count_bit_for_found) { instance->generic.data = instance->decoder.decode_data; instance->generic.data_count_bit = instance->decoder.decode_count_bit; if(instance->base.callback) instance->base.callback(&instance->base, instance->base.context); } instance->decoder.decode_data = 0; instance->decoder.decode_count_bit = 1; manchester_advance( instance->manchester_saved_state, ManchesterEventReset, &instance->manchester_saved_state, NULL); manchester_advance( instance->manchester_saved_state, ManchesterEventShortLow, &instance->manchester_saved_state, NULL); } else { instance->decoder.parser_step = CameAtomoDecoderStepReset; } } else { if(DURATION_DIFF(duration, subghz_protocol_came_atomo_const.te_short) < subghz_protocol_came_atomo_const.te_delta) { event = ManchesterEventShortHigh; } else if( DURATION_DIFF(duration, subghz_protocol_came_atomo_const.te_long) < subghz_protocol_came_atomo_const.te_delta) { event = ManchesterEventLongHigh; } else { instance->decoder.parser_step = CameAtomoDecoderStepReset; } } 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; } } /** * Analysis of received data * @param instance Pointer to a SubGhzBlockGeneric* instance * @param file_name Full path to rainbow table the file */ static void subghz_protocol_came_atomo_remote_controller(SubGhzBlockGeneric* instance) { /* * ***SkorP ver.*** * 0x1fafef3ed0f7d9ef * 0x185fcc1531ee86e7 * 0x184fa96912c567ff * 0x187f8a42f3dc38f7 * 0x186f63915492a5cd * 0x181f40bab58bfac5 * 0x180f25c696a01bdd * 0x183f06ed77b944d5 * 0x182ef661d83d21a9 * 0x18ded54a39247ea1 * 0x18ceb0361a0f9fb9 * 0x18fe931dfb16c0b1 * 0x18ee7ace5c585d8b * ........ * transmission consists of 99 parcels with increasing counter while holding down the button * with each new press, the counter in the encrypted part increases * * 0x1FAFF13ED0F7D9EF * 0x1FAFF11ED0F7D9EF * 0x1FAFF10ED0F7D9EF * 0x1FAFF0FED0F7D9EF * 0x1FAFF0EED0F7D9EF * 0x1FAFF0DED0F7D9EF * 0x1FAFF0CED0F7D9EF * 0x1FAFF0BED0F7D9EF * 0x1FAFF0AED0F7D9EF * * where 0x1FAF - parcel counter, 0хF0A - button press counter, * 0xED0F7D9E - serial number, 0хF - key * 0x1FAF parcel counter - 1 in the parcel queue ^ 0x185F = 0x07F0 * 0x185f ^ 0x185F = 0x0000 * 0x184f ^ 0x185F = 0x0010 * 0x187f ^ 0x185F = 0x0020 * ..... * 0x182e ^ 0x185F = 0x0071 * 0x18de ^ 0x185F = 0x0081 * ..... * 0x1e43 ^ 0x185F = 0x061C * where the last nibble is incremented every 8 samples * * Decode * * 0x1cf6931dfb16c0b1 => 0x1cf6 * 0x1cf6 ^ 0x185F = 0x04A9 * 0x04A9 => 0x04A = 74 (dec) * 74+1 % 32(atomo_magic_xor) = 11 * GET atomo_magic_xor[11] = 0xXXXXXXXXXXXXXXXX * 0x931dfb16c0b1 ^ 0xXXXXXXXXXXXXXXXX = 0xEF3ED0F7D9EF * 0xEF3 ED0F7D9E F => 0xEF3 - CNT, 0xED0F7D9E - SN, 0xF - key * * ***Eng1n33r ver. (actual)*** * 0x1FF08D9924984115 - received data * 0x00F7266DB67BEEA0 - inverted data * 0x0501FD0000A08300 - decrypted data, * where: 0x05 - Button hold-cycle counter (8-bit, from 0 to 0x7F) * 0x01FD - Parcel counter (normal 16-bit counter) * 0x0000A083 - Serial number (32-bit) * 0x0 - Button code (4-bit, 0x0 - #1 left-up; 0x2 - #2 right-up; 0x4 - #3 left-down; 0x6 - #4 right-down) * 0x0 - Last zero nibble * */ instance->data ^= 0xFFFFFFFFFFFFFFFF; instance->data <<= 4; uint8_t pack[8] = {}; pack[0] = (instance->data >> 56); pack[1] = ((instance->data >> 48) & 0xFF); pack[2] = ((instance->data >> 40) & 0xFF); pack[3] = ((instance->data >> 32) & 0xFF); pack[4] = ((instance->data >> 24) & 0xFF); pack[5] = ((instance->data >> 16) & 0xFF); pack[6] = ((instance->data >> 8) & 0xFF); pack[7] = (instance->data & 0xFF); atomo_decrypt(pack); instance->cnt_2 = pack[0]; instance->cnt = (uint16_t)pack[1] << 8 | pack[2]; instance->serial = (uint32_t)(pack[3]) << 24 | pack[4] << 16 | pack[5] << 8 | pack[6]; uint8_t btn_decode = (pack[7] >> 4); if(btn_decode == 0x0) { instance->btn = 0x1; } else if(btn_decode == 0x2) { instance->btn = 0x2; } else if(btn_decode == 0x4) { instance->btn = 0x3; } else if(btn_decode == 0x6) { instance->btn = 0x4; } uint32_t hi = pack[0] << 24 | pack[1] << 16 | pack[2] << 8 | pack[3]; uint32_t lo = pack[4] << 24 | pack[5] << 16 | pack[6] << 8 | pack[7]; instance->data_2 = (uint64_t)hi << 32 | lo; // Save original button for later use if(subghz_custom_btn_get_original() == 0) { subghz_custom_btn_set_original(instance->btn); } subghz_custom_btn_set_max(3); } void atomo_encrypt(uint8_t* buff) { uint8_t tmpB = (~buff[0] + 1) & 0x7F; uint8_t bitCnt = 8; while(bitCnt < 59) { if((tmpB & 0x18) && (((tmpB / 8) & 3) != 3)) { tmpB = ((tmpB << 1) & 0xFF) | 1; } else { tmpB = (tmpB << 1) & 0xFF; } if(tmpB & 0x80) { buff[bitCnt / 8] ^= (0x80 >> (bitCnt & 7)); } bitCnt++; } buff[0] = (buff[0] ^ 5) & 0x7F; } void atomo_decrypt(uint8_t* buff) { buff[0] = (buff[0] ^ 5) & 0x7F; uint8_t tmpB = (-buff[0]) & 0x7F; uint8_t bitCnt = 8; while(bitCnt < 59) { if((tmpB & 0x18) && (((tmpB / 8) & 3) != 3)) { tmpB = ((tmpB << 1) & 0xFF) | 1; } else { tmpB = (tmpB << 1) & 0xFF; } if(tmpB & 0x80) { buff[bitCnt / 8] ^= (0x80 >> (bitCnt & 7)); } bitCnt++; } } static uint8_t subghz_protocol_came_atomo_get_btn_code(void) { uint8_t custom_btn_id = subghz_custom_btn_get(); uint8_t original_btn_code = subghz_custom_btn_get_original(); uint8_t btn = original_btn_code; // Set custom button if((custom_btn_id == SUBGHZ_CUSTOM_BTN_OK) && (original_btn_code != 0)) { // Restore original button code btn = original_btn_code; } else if(custom_btn_id == SUBGHZ_CUSTOM_BTN_UP) { switch(original_btn_code) { case 0x1: btn = 0x2; break; case 0x2: btn = 0x1; break; case 0x3: btn = 0x1; break; case 0x4: btn = 0x1; break; default: break; } } else if(custom_btn_id == SUBGHZ_CUSTOM_BTN_DOWN) { switch(original_btn_code) { case 0x1: btn = 0x3; break; case 0x2: btn = 0x3; break; case 0x3: btn = 0x2; break; case 0x4: btn = 0x2; break; default: break; } } else if(custom_btn_id == SUBGHZ_CUSTOM_BTN_LEFT) { switch(original_btn_code) { case 0x1: btn = 0x4; break; case 0x2: btn = 0x4; break; case 0x3: btn = 0x4; break; case 0x4: btn = 0x3; break; default: break; } } return btn; } uint8_t subghz_protocol_decoder_came_atomo_get_hash_data(void* context) { furi_assert(context); SubGhzProtocolDecoderCameAtomo* instance = context; return subghz_protocol_blocks_get_hash_data( &instance->decoder, (instance->decoder.decode_count_bit / 8) + 1); } SubGhzProtocolStatus subghz_protocol_decoder_came_atomo_serialize( void* context, FlipperFormat* flipper_format, SubGhzRadioPreset* preset) { furi_assert(context); SubGhzProtocolDecoderCameAtomo* instance = context; return subghz_block_generic_serialize(&instance->generic, flipper_format, preset); } SubGhzProtocolStatus subghz_protocol_decoder_came_atomo_deserialize(void* context, FlipperFormat* flipper_format) { furi_assert(context); SubGhzProtocolDecoderCameAtomo* instance = context; return subghz_block_generic_deserialize_check_count_bit( &instance->generic, flipper_format, subghz_protocol_came_atomo_const.min_count_bit_for_found); } void subghz_protocol_decoder_came_atomo_get_string(void* context, FuriString* output) { furi_assert(context); SubGhzProtocolDecoderCameAtomo* instance = context; subghz_protocol_came_atomo_remote_controller(&instance->generic); uint32_t code_found_hi = instance->generic.data >> 32; uint32_t code_found_lo = instance->generic.data & 0x00000000ffffffff; furi_string_cat_printf( output, "%s %db\r\n" "Key:%08lX%08lX\r\n" "Sn:0x%08lX Btn:%01X\r\n" "Pcl_Cnt:0x%04lX\r\n" "Btn_Cnt:0x%02X", instance->generic.protocol_name, instance->generic.data_count_bit, code_found_hi, code_found_lo, instance->generic.serial, instance->generic.btn, instance->generic.cnt, instance->generic.cnt_2); }
25,280
C
.c
640
31.88125
117
0.620763
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,300
mastercode.h
DarkFlippers_unleashed-firmware/lib/subghz/protocols/mastercode.h
#pragma once #include "base.h" #define SUBGHZ_PROTOCOL_MASTERCODE_NAME "Mastercode" typedef struct SubGhzProtocolDecoderMastercode SubGhzProtocolDecoderMastercode; typedef struct SubGhzProtocolEncoderMastercode SubGhzProtocolEncoderMastercode; extern const SubGhzProtocolDecoder subghz_protocol_mastercode_decoder; extern const SubGhzProtocolEncoder subghz_protocol_mastercode_encoder; extern const SubGhzProtocol subghz_protocol_mastercode; /** * Allocate SubGhzProtocolEncoderMastercode. * @param environment Pointer to a SubGhzEnvironment instance * @return SubGhzProtocolEncoderMastercode* pointer to a SubGhzProtocolEncoderMastercode instance */ void* subghz_protocol_encoder_mastercode_alloc(SubGhzEnvironment* environment); /** * Free SubGhzProtocolEncoderMastercode. * @param context Pointer to a SubGhzProtocolEncoderMastercode instance */ void subghz_protocol_encoder_mastercode_free(void* context); /** * Deserialize and generating an upload to send. * @param context Pointer to a SubGhzProtocolEncoderMastercode instance * @param flipper_format Pointer to a FlipperFormat instance * @return status */ SubGhzProtocolStatus subghz_protocol_encoder_mastercode_deserialize(void* context, FlipperFormat* flipper_format); /** * Forced transmission stop. * @param context Pointer to a SubGhzProtocolEncoderMastercode instance */ void subghz_protocol_encoder_mastercode_stop(void* context); /** * Getting the level and duration of the upload to be loaded into DMA. * @param context Pointer to a SubGhzProtocolEncoderMastercode instance * @return LevelDuration */ LevelDuration subghz_protocol_encoder_mastercode_yield(void* context); /** * Allocate SubGhzProtocolDecoderMastercode. * @param environment Pointer to a SubGhzEnvironment instance * @return SubGhzProtocolDecoderMastercode* pointer to a SubGhzProtocolDecoderMastercode instance */ void* subghz_protocol_decoder_mastercode_alloc(SubGhzEnvironment* environment); /** * Free SubGhzProtocolDecoderMastercode. * @param context Pointer to a SubGhzProtocolDecoderMastercode instance */ void subghz_protocol_decoder_mastercode_free(void* context); /** * Reset decoder SubGhzProtocolDecoderMastercode. * @param context Pointer to a SubGhzProtocolDecoderMastercode instance */ void subghz_protocol_decoder_mastercode_reset(void* context); /** * Parse a raw sequence of levels and durations received from the air. * @param context Pointer to a SubGhzProtocolDecoderMastercode instance * @param level Signal level true-high false-low * @param duration Duration of this level in, us */ void subghz_protocol_decoder_mastercode_feed(void* context, bool level, uint32_t duration); /** * Getting the hash sum of the last randomly received parcel. * @param context Pointer to a SubGhzProtocolDecoderMastercode instance * @return hash Hash sum */ uint8_t subghz_protocol_decoder_mastercode_get_hash_data(void* context); /** * Serialize data SubGhzProtocolDecoderMastercode. * @param context Pointer to a SubGhzProtocolDecoderMastercode instance * @param flipper_format Pointer to a FlipperFormat instance * @param preset The modulation on which the signal was received, SubGhzRadioPreset * @return status */ SubGhzProtocolStatus subghz_protocol_decoder_mastercode_serialize( void* context, FlipperFormat* flipper_format, SubGhzRadioPreset* preset); /** * Deserialize data SubGhzProtocolDecoderMastercode. * @param context Pointer to a SubGhzProtocolDecoderMastercode instance * @param flipper_format Pointer to a FlipperFormat instance * @return status */ SubGhzProtocolStatus subghz_protocol_decoder_mastercode_deserialize(void* context, FlipperFormat* flipper_format); /** * Getting a textual representation of the received data. * @param context Pointer to a SubGhzProtocolDecoderMastercode instance * @param output Resulting text */ void subghz_protocol_decoder_mastercode_get_string(void* context, FuriString* output);
3,962
C
.c
92
41.076087
97
0.82611
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,301
chamberlain_code.h
DarkFlippers_unleashed-firmware/lib/subghz/protocols/chamberlain_code.h
#pragma once #include "base.h" #define SUBGHZ_PROTOCOL_CHAMB_CODE_NAME "Cham_Code" typedef struct SubGhzProtocolDecoderChamb_Code SubGhzProtocolDecoderChamb_Code; typedef struct SubGhzProtocolEncoderChamb_Code SubGhzProtocolEncoderChamb_Code; extern const SubGhzProtocolDecoder subghz_protocol_chamb_code_decoder; extern const SubGhzProtocolEncoder subghz_protocol_chamb_code_encoder; extern const SubGhzProtocol subghz_protocol_chamb_code; /** * Allocate SubGhzProtocolEncoderChamb_Code. * @param environment Pointer to a SubGhzEnvironment instance * @return SubGhzProtocolEncoderChamb_Code* pointer to a SubGhzProtocolEncoderChamb_Code instance */ void* subghz_protocol_encoder_chamb_code_alloc(SubGhzEnvironment* environment); /** * Free SubGhzProtocolEncoderChamb_Code. * @param context Pointer to a SubGhzProtocolEncoderChamb_Code instance */ void subghz_protocol_encoder_chamb_code_free(void* context); /** * Deserialize and generating an upload to send. * @param context Pointer to a SubGhzProtocolEncoderChamb_Code instance * @param flipper_format Pointer to a FlipperFormat instance * @return status */ SubGhzProtocolStatus subghz_protocol_encoder_chamb_code_deserialize(void* context, FlipperFormat* flipper_format); /** * Forced transmission stop. * @param context Pointer to a SubGhzProtocolEncoderChamb_Code instance */ void subghz_protocol_encoder_chamb_code_stop(void* context); /** * Getting the level and duration of the upload to be loaded into DMA. * @param context Pointer to a SubGhzProtocolEncoderChamb_Code instance * @return LevelDuration */ LevelDuration subghz_protocol_encoder_chamb_code_yield(void* context); /** * Allocate SubGhzProtocolDecoderChamb_Code. * @param environment Pointer to a SubGhzEnvironment instance * @return SubGhzProtocolDecoderChamb_Code* pointer to a SubGhzProtocolDecoderChamb_Code instance */ void* subghz_protocol_decoder_chamb_code_alloc(SubGhzEnvironment* environment); /** * Free SubGhzProtocolDecoderChamb_Code. * @param context Pointer to a SubGhzProtocolDecoderChamb_Code instance */ void subghz_protocol_decoder_chamb_code_free(void* context); /** * Reset decoder SubGhzProtocolDecoderChamb_Code. * @param context Pointer to a SubGhzProtocolDecoderChamb_Code instance */ void subghz_protocol_decoder_chamb_code_reset(void* context); /** * Parse a raw sequence of levels and durations received from the air. * @param context Pointer to a SubGhzProtocolDecoderChamb_Code instance * @param level Signal level true-high false-low * @param duration Duration of this level in, us */ void subghz_protocol_decoder_chamb_code_feed(void* context, bool level, uint32_t duration); /** * Getting the hash sum of the last randomly received parcel. * @param context Pointer to a SubGhzProtocolDecoderChamb_Code instance * @return hash Hash sum */ uint8_t subghz_protocol_decoder_chamb_code_get_hash_data(void* context); /** * Serialize data SubGhzProtocolDecoderChamb_Code. * @param context Pointer to a SubGhzProtocolDecoderChamb_Code instance * @param flipper_format Pointer to a FlipperFormat instance * @param preset The modulation on which the signal was received, SubGhzRadioPreset * @return status */ SubGhzProtocolStatus subghz_protocol_decoder_chamb_code_serialize( void* context, FlipperFormat* flipper_format, SubGhzRadioPreset* preset); /** * Deserialize data SubGhzProtocolDecoderChamb_Code. * @param context Pointer to a SubGhzProtocolDecoderChamb_Code instance * @param flipper_format Pointer to a FlipperFormat instance * @return status */ SubGhzProtocolStatus subghz_protocol_decoder_chamb_code_deserialize(void* context, FlipperFormat* flipper_format); /** * Getting a textual representation of the received data. * @param context Pointer to a SubGhzProtocolDecoderChamb_Code instance * @param output Resulting text */ void subghz_protocol_decoder_chamb_code_get_string(void* context, FuriString* output);
3,961
C
.c
92
41.065217
97
0.814642
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,302
smc5326.h
DarkFlippers_unleashed-firmware/lib/subghz/protocols/smc5326.h
#pragma once #include "base.h" #define SUBGHZ_PROTOCOL_SMC5326_NAME "SMC5326" typedef struct SubGhzProtocolDecoderSMC5326 SubGhzProtocolDecoderSMC5326; typedef struct SubGhzProtocolEncoderSMC5326 SubGhzProtocolEncoderSMC5326; extern const SubGhzProtocolDecoder subghz_protocol_smc5326_decoder; extern const SubGhzProtocolEncoder subghz_protocol_smc5326_encoder; extern const SubGhzProtocol subghz_protocol_smc5326; /** * Allocate SubGhzProtocolEncoderSMC5326. * @param environment Pointer to a SubGhzEnvironment instance * @return SubGhzProtocolEncoderSMC5326* pointer to a SubGhzProtocolEncoderSMC5326 instance */ void* subghz_protocol_encoder_smc5326_alloc(SubGhzEnvironment* environment); /** * Free SubGhzProtocolEncoderSMC5326. * @param context Pointer to a SubGhzProtocolEncoderSMC5326 instance */ void subghz_protocol_encoder_smc5326_free(void* context); /** * Deserialize and generating an upload to send. * @param context Pointer to a SubGhzProtocolEncoderSMC5326 instance * @param flipper_format Pointer to a FlipperFormat instance * @return status */ SubGhzProtocolStatus subghz_protocol_encoder_smc5326_deserialize(void* context, FlipperFormat* flipper_format); /** * Forced transmission stop. * @param context Pointer to a SubGhzProtocolEncoderSMC5326 instance */ void subghz_protocol_encoder_smc5326_stop(void* context); /** * Getting the level and duration of the upload to be loaded into DMA. * @param context Pointer to a SubGhzProtocolEncoderSMC5326 instance * @return LevelDuration */ LevelDuration subghz_protocol_encoder_smc5326_yield(void* context); /** * Allocate SubGhzProtocolDecoderSMC5326. * @param environment Pointer to a SubGhzEnvironment instance * @return SubGhzProtocolDecoderSMC5326* pointer to a SubGhzProtocolDecoderSMC5326 instance */ void* subghz_protocol_decoder_smc5326_alloc(SubGhzEnvironment* environment); /** * Free SubGhzProtocolDecoderSMC5326. * @param context Pointer to a SubGhzProtocolDecoderSMC5326 instance */ void subghz_protocol_decoder_smc5326_free(void* context); /** * Reset decoder SubGhzProtocolDecoderSMC5326. * @param context Pointer to a SubGhzProtocolDecoderSMC5326 instance */ void subghz_protocol_decoder_smc5326_reset(void* context); /** * Parse a raw sequence of levels and durations received from the air. * @param context Pointer to a SubGhzProtocolDecoderSMC5326 instance * @param level Signal level true-high false-low * @param duration Duration of this level in, us */ void subghz_protocol_decoder_smc5326_feed(void* context, bool level, uint32_t duration); /** * Getting the hash sum of the last randomly received parcel. * @param context Pointer to a SubGhzProtocolDecoderSMC5326 instance * @return hash Hash sum */ uint8_t subghz_protocol_decoder_smc5326_get_hash_data(void* context); /** * Serialize data SubGhzProtocolDecoderSMC5326. * @param context Pointer to a SubGhzProtocolDecoderSMC5326 instance * @param flipper_format Pointer to a FlipperFormat instance * @param preset The modulation on which the signal was received, SubGhzRadioPreset * @return status */ SubGhzProtocolStatus subghz_protocol_decoder_smc5326_serialize( void* context, FlipperFormat* flipper_format, SubGhzRadioPreset* preset); /** * Deserialize data SubGhzProtocolDecoderSMC5326. * @param context Pointer to a SubGhzProtocolDecoderSMC5326 instance * @param flipper_format Pointer to a FlipperFormat instance * @return status */ SubGhzProtocolStatus subghz_protocol_decoder_smc5326_deserialize(void* context, FlipperFormat* flipper_format); /** * Getting a textual representation of the received data. * @param context Pointer to a SubGhzProtocolDecoderSMC5326 instance * @param output Resulting text */ void subghz_protocol_decoder_smc5326_get_string(void* context, FuriString* output);
3,830
C
.c
92
39.641304
94
0.819941
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,303
nero_sketch.c
DarkFlippers_unleashed-firmware/lib/subghz/protocols/nero_sketch.c
#include "nero_sketch.h" #include "../blocks/const.h" #include "../blocks/decoder.h" #include "../blocks/encoder.h" #include "../blocks/generic.h" #include "../blocks/math.h" #define TAG "SubGhzProtocolNeroSketch" static const SubGhzBlockConst subghz_protocol_nero_sketch_const = { .te_short = 330, .te_long = 660, .te_delta = 150, .min_count_bit_for_found = 40, }; struct SubGhzProtocolDecoderNeroSketch { SubGhzProtocolDecoderBase base; SubGhzBlockDecoder decoder; SubGhzBlockGeneric generic; uint16_t header_count; }; struct SubGhzProtocolEncoderNeroSketch { SubGhzProtocolEncoderBase base; SubGhzProtocolBlockEncoder encoder; SubGhzBlockGeneric generic; }; typedef enum { NeroSketchDecoderStepReset = 0, NeroSketchDecoderStepCheckPreambula, NeroSketchDecoderStepSaveDuration, NeroSketchDecoderStepCheckDuration, } NeroSketchDecoderStep; const SubGhzProtocolDecoder subghz_protocol_nero_sketch_decoder = { .alloc = subghz_protocol_decoder_nero_sketch_alloc, .free = subghz_protocol_decoder_nero_sketch_free, .feed = subghz_protocol_decoder_nero_sketch_feed, .reset = subghz_protocol_decoder_nero_sketch_reset, .get_hash_data = subghz_protocol_decoder_nero_sketch_get_hash_data, .serialize = subghz_protocol_decoder_nero_sketch_serialize, .deserialize = subghz_protocol_decoder_nero_sketch_deserialize, .get_string = subghz_protocol_decoder_nero_sketch_get_string, }; const SubGhzProtocolEncoder subghz_protocol_nero_sketch_encoder = { .alloc = subghz_protocol_encoder_nero_sketch_alloc, .free = subghz_protocol_encoder_nero_sketch_free, .deserialize = subghz_protocol_encoder_nero_sketch_deserialize, .stop = subghz_protocol_encoder_nero_sketch_stop, .yield = subghz_protocol_encoder_nero_sketch_yield, }; const SubGhzProtocol subghz_protocol_nero_sketch = { .name = SUBGHZ_PROTOCOL_NERO_SKETCH_NAME, .type = SubGhzProtocolTypeStatic, .flag = SubGhzProtocolFlag_433 | SubGhzProtocolFlag_AM | SubGhzProtocolFlag_Decodable | SubGhzProtocolFlag_Load | SubGhzProtocolFlag_Save | SubGhzProtocolFlag_Send, .decoder = &subghz_protocol_nero_sketch_decoder, .encoder = &subghz_protocol_nero_sketch_encoder, }; void* subghz_protocol_encoder_nero_sketch_alloc(SubGhzEnvironment* environment) { UNUSED(environment); SubGhzProtocolEncoderNeroSketch* instance = malloc(sizeof(SubGhzProtocolEncoderNeroSketch)); instance->base.protocol = &subghz_protocol_nero_sketch; 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_running = false; return instance; } void subghz_protocol_encoder_nero_sketch_free(void* context) { furi_assert(context); SubGhzProtocolEncoderNeroSketch* instance = context; free(instance->encoder.upload); free(instance); } /** * Generating an upload from data. * @param instance Pointer to a SubGhzProtocolEncoderNeroSketch instance * @return true On success */ static bool subghz_protocol_encoder_nero_sketch_get_upload(SubGhzProtocolEncoderNeroSketch* instance) { furi_assert(instance); size_t index = 0; size_t size_upload = 47 * 2 + 2 + (instance->generic.data_count_bit * 2) + 2; if(size_upload > instance->encoder.size_upload) { FURI_LOG_E(TAG, "Size upload exceeds allocated encoder buffer."); return false; } else { instance->encoder.size_upload = size_upload; } //Send header for(uint8_t i = 0; i < 47; i++) { instance->encoder.upload[index++] = level_duration_make(true, (uint32_t)subghz_protocol_nero_sketch_const.te_short); instance->encoder.upload[index++] = level_duration_make(false, (uint32_t)subghz_protocol_nero_sketch_const.te_short); } //Send start bit instance->encoder.upload[index++] = level_duration_make(true, (uint32_t)subghz_protocol_nero_sketch_const.te_short * 4); instance->encoder.upload[index++] = level_duration_make(false, (uint32_t)subghz_protocol_nero_sketch_const.te_short); //Send key data for(uint8_t i = instance->generic.data_count_bit; i > 0; i--) { if(bit_read(instance->generic.data, i - 1)) { //send bit 1 instance->encoder.upload[index++] = level_duration_make(true, (uint32_t)subghz_protocol_nero_sketch_const.te_long); instance->encoder.upload[index++] = level_duration_make(false, (uint32_t)subghz_protocol_nero_sketch_const.te_short); } else { //send bit 0 instance->encoder.upload[index++] = level_duration_make(true, (uint32_t)subghz_protocol_nero_sketch_const.te_short); instance->encoder.upload[index++] = level_duration_make(false, (uint32_t)subghz_protocol_nero_sketch_const.te_long); } } //Send stop bit instance->encoder.upload[index++] = level_duration_make(true, (uint32_t)subghz_protocol_nero_sketch_const.te_short * 3); instance->encoder.upload[index++] = level_duration_make(false, (uint32_t)subghz_protocol_nero_sketch_const.te_short); return true; } SubGhzProtocolStatus subghz_protocol_encoder_nero_sketch_deserialize(void* context, FlipperFormat* flipper_format) { furi_assert(context); SubGhzProtocolEncoderNeroSketch* instance = context; SubGhzProtocolStatus ret = SubGhzProtocolStatusError; do { ret = subghz_block_generic_deserialize_check_count_bit( &instance->generic, flipper_format, subghz_protocol_nero_sketch_const.min_count_bit_for_found); if(ret != SubGhzProtocolStatusOk) { break; } //optional parameter parameter flipper_format_read_uint32( flipper_format, "Repeat", (uint32_t*)&instance->encoder.repeat, 1); if(!subghz_protocol_encoder_nero_sketch_get_upload(instance)) { ret = SubGhzProtocolStatusErrorEncoderGetUpload; break; } instance->encoder.is_running = true; } while(false); return ret; } void subghz_protocol_encoder_nero_sketch_stop(void* context) { SubGhzProtocolEncoderNeroSketch* instance = context; instance->encoder.is_running = false; } LevelDuration subghz_protocol_encoder_nero_sketch_yield(void* context) { SubGhzProtocolEncoderNeroSketch* instance = context; if(instance->encoder.repeat == 0 || !instance->encoder.is_running) { instance->encoder.is_running = 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; } void* subghz_protocol_decoder_nero_sketch_alloc(SubGhzEnvironment* environment) { UNUSED(environment); SubGhzProtocolDecoderNeroSketch* instance = malloc(sizeof(SubGhzProtocolDecoderNeroSketch)); instance->base.protocol = &subghz_protocol_nero_sketch; instance->generic.protocol_name = instance->base.protocol->name; return instance; } void subghz_protocol_decoder_nero_sketch_free(void* context) { furi_assert(context); SubGhzProtocolDecoderNeroSketch* instance = context; free(instance); } void subghz_protocol_decoder_nero_sketch_reset(void* context) { furi_assert(context); SubGhzProtocolDecoderNeroSketch* instance = context; instance->decoder.parser_step = NeroSketchDecoderStepReset; } void subghz_protocol_decoder_nero_sketch_feed(void* context, bool level, uint32_t duration) { furi_assert(context); SubGhzProtocolDecoderNeroSketch* instance = context; switch(instance->decoder.parser_step) { case NeroSketchDecoderStepReset: if((level) && (DURATION_DIFF(duration, subghz_protocol_nero_sketch_const.te_short) < subghz_protocol_nero_sketch_const.te_delta)) { instance->decoder.parser_step = NeroSketchDecoderStepCheckPreambula; instance->decoder.te_last = duration; instance->header_count = 0; } break; case NeroSketchDecoderStepCheckPreambula: if(level) { if((DURATION_DIFF(duration, subghz_protocol_nero_sketch_const.te_short) < subghz_protocol_nero_sketch_const.te_delta) || (DURATION_DIFF(duration, subghz_protocol_nero_sketch_const.te_short * 4) < subghz_protocol_nero_sketch_const.te_delta)) { instance->decoder.te_last = duration; } else { instance->decoder.parser_step = NeroSketchDecoderStepReset; } } else if( DURATION_DIFF(duration, subghz_protocol_nero_sketch_const.te_short) < subghz_protocol_nero_sketch_const.te_delta) { if(DURATION_DIFF( instance->decoder.te_last, subghz_protocol_nero_sketch_const.te_short) < subghz_protocol_nero_sketch_const.te_delta) { // Found header instance->header_count++; break; } else if( DURATION_DIFF( instance->decoder.te_last, subghz_protocol_nero_sketch_const.te_short * 4) < subghz_protocol_nero_sketch_const.te_delta) { // Found start bit if(instance->header_count > 40) { instance->decoder.parser_step = NeroSketchDecoderStepSaveDuration; instance->decoder.decode_data = 0; instance->decoder.decode_count_bit = 0; } else { instance->decoder.parser_step = NeroSketchDecoderStepReset; } } else { instance->decoder.parser_step = NeroSketchDecoderStepReset; } } else { instance->decoder.parser_step = NeroSketchDecoderStepReset; } break; case NeroSketchDecoderStepSaveDuration: if(level) { if(duration >= (subghz_protocol_nero_sketch_const.te_short * 2 + subghz_protocol_nero_sketch_const.te_delta * 2)) { //Found stop bit instance->decoder.parser_step = NeroSketchDecoderStepReset; if(instance->decoder.decode_count_bit == subghz_protocol_nero_sketch_const.min_count_bit_for_found) { instance->generic.data = instance->decoder.decode_data; instance->generic.data_count_bit = instance->decoder.decode_count_bit; if(instance->base.callback) instance->base.callback(&instance->base, instance->base.context); } instance->decoder.decode_data = 0; instance->decoder.decode_count_bit = 0; break; } else { instance->decoder.te_last = duration; instance->decoder.parser_step = NeroSketchDecoderStepCheckDuration; } } else { instance->decoder.parser_step = NeroSketchDecoderStepReset; } break; case NeroSketchDecoderStepCheckDuration: if(!level) { if((DURATION_DIFF( instance->decoder.te_last, subghz_protocol_nero_sketch_const.te_short) < subghz_protocol_nero_sketch_const.te_delta) && (DURATION_DIFF(duration, subghz_protocol_nero_sketch_const.te_long) < subghz_protocol_nero_sketch_const.te_delta)) { subghz_protocol_blocks_add_bit(&instance->decoder, 0); instance->decoder.parser_step = NeroSketchDecoderStepSaveDuration; } else if( (DURATION_DIFF( instance->decoder.te_last, subghz_protocol_nero_sketch_const.te_long) < subghz_protocol_nero_sketch_const.te_delta) && (DURATION_DIFF(duration, subghz_protocol_nero_sketch_const.te_short) < subghz_protocol_nero_sketch_const.te_delta)) { subghz_protocol_blocks_add_bit(&instance->decoder, 1); instance->decoder.parser_step = NeroSketchDecoderStepSaveDuration; } else { instance->decoder.parser_step = NeroSketchDecoderStepReset; } } else { instance->decoder.parser_step = NeroSketchDecoderStepReset; } break; } } uint8_t subghz_protocol_decoder_nero_sketch_get_hash_data(void* context) { furi_assert(context); SubGhzProtocolDecoderNeroSketch* instance = context; return subghz_protocol_blocks_get_hash_data( &instance->decoder, (instance->decoder.decode_count_bit / 8) + 1); } SubGhzProtocolStatus subghz_protocol_decoder_nero_sketch_serialize( void* context, FlipperFormat* flipper_format, SubGhzRadioPreset* preset) { furi_assert(context); SubGhzProtocolDecoderNeroSketch* instance = context; return subghz_block_generic_serialize(&instance->generic, flipper_format, preset); } SubGhzProtocolStatus subghz_protocol_decoder_nero_sketch_deserialize(void* context, FlipperFormat* flipper_format) { furi_assert(context); SubGhzProtocolDecoderNeroSketch* instance = context; return subghz_block_generic_deserialize_check_count_bit( &instance->generic, flipper_format, subghz_protocol_nero_sketch_const.min_count_bit_for_found); } void subghz_protocol_decoder_nero_sketch_get_string(void* context, FuriString* output) { furi_assert(context); SubGhzProtocolDecoderNeroSketch* instance = context; uint32_t code_found_hi = instance->generic.data >> 32; uint32_t code_found_lo = instance->generic.data & 0x00000000ffffffff; uint64_t code_found_reverse = subghz_protocol_blocks_reverse_key( instance->generic.data, instance->generic.data_count_bit); uint32_t code_found_reverse_hi = code_found_reverse >> 32; uint32_t code_found_reverse_lo = code_found_reverse & 0x00000000ffffffff; furi_string_cat_printf( output, "%s %dbit\r\n" "Key:0x%lX%08lX\r\n" "Yek:0x%lX%08lX\r\n", instance->generic.protocol_name, instance->generic.data_count_bit, code_found_hi, code_found_lo, code_found_reverse_hi, code_found_reverse_lo); }
14,626
C
.c
325
36.6
99
0.670222
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,304
legrand.c
DarkFlippers_unleashed-firmware/lib/subghz/protocols/legrand.c
#include "legrand.h" #include "../blocks/const.h" #include "../blocks/decoder.h" #include "../blocks/encoder.h" #include "../blocks/generic.h" #include "../blocks/math.h" #define TAG "SubGhzProtocolLegrand" static const SubGhzBlockConst subghz_protocol_legrand_const = { .te_short = 375, .te_long = 1125, .te_delta = 150, .min_count_bit_for_found = 18, }; struct SubGhzProtocolDecoderLegrand { SubGhzProtocolDecoderBase base; SubGhzBlockDecoder decoder; SubGhzBlockGeneric generic; uint32_t te; uint32_t last_data; }; struct SubGhzProtocolEncoderLegrand { SubGhzProtocolEncoderBase base; SubGhzProtocolBlockEncoder encoder; SubGhzBlockGeneric generic; uint32_t te; }; typedef enum { LegrandDecoderStepReset = 0, LegrandDecoderStepFirstBit, LegrandDecoderStepSaveDuration, LegrandDecoderStepCheckDuration, } LegrandDecoderStep; const SubGhzProtocolDecoder subghz_protocol_legrand_decoder = { .alloc = subghz_protocol_decoder_legrand_alloc, .free = subghz_protocol_decoder_legrand_free, .feed = subghz_protocol_decoder_legrand_feed, .reset = subghz_protocol_decoder_legrand_reset, .get_hash_data = subghz_protocol_decoder_legrand_get_hash_data, .serialize = subghz_protocol_decoder_legrand_serialize, .deserialize = subghz_protocol_decoder_legrand_deserialize, .get_string = subghz_protocol_decoder_legrand_get_string, }; const SubGhzProtocolEncoder subghz_protocol_legrand_encoder = { .alloc = subghz_protocol_encoder_legrand_alloc, .free = subghz_protocol_encoder_legrand_free, .deserialize = subghz_protocol_encoder_legrand_deserialize, .stop = subghz_protocol_encoder_legrand_stop, .yield = subghz_protocol_encoder_legrand_yield, }; const SubGhzProtocol subghz_protocol_legrand = { .name = SUBGHZ_PROTOCOL_LEGRAND_NAME, .type = SubGhzProtocolTypeStatic, .flag = SubGhzProtocolFlag_433 | SubGhzProtocolFlag_AM | SubGhzProtocolFlag_Decodable | SubGhzProtocolFlag_Load | SubGhzProtocolFlag_Save | SubGhzProtocolFlag_Send, .decoder = &subghz_protocol_legrand_decoder, .encoder = &subghz_protocol_legrand_encoder, }; void* subghz_protocol_encoder_legrand_alloc(SubGhzEnvironment* environment) { UNUSED(environment); SubGhzProtocolEncoderLegrand* instance = malloc(sizeof(SubGhzProtocolEncoderLegrand)); instance->base.protocol = &subghz_protocol_legrand; instance->generic.protocol_name = instance->base.protocol->name; instance->encoder.repeat = 10; instance->encoder.size_upload = subghz_protocol_legrand_const.min_count_bit_for_found * 2 + 1; instance->encoder.upload = malloc(instance->encoder.size_upload * sizeof(LevelDuration)); instance->encoder.is_running = false; return instance; } void subghz_protocol_encoder_legrand_free(void* context) { furi_assert(context); SubGhzProtocolEncoderLegrand* instance = context; free(instance->encoder.upload); free(instance); } /** * Generating an upload from data. * @param instance Pointer to a SubGhzProtocolEncoderLegrand instance * @return true On success */ static bool subghz_protocol_encoder_legrand_get_upload(SubGhzProtocolEncoderLegrand* instance) { furi_assert(instance); size_t size_upload = (instance->generic.data_count_bit * 2) + 1; if(size_upload != instance->encoder.size_upload) { FURI_LOG_E(TAG, "Invalid data bit count"); return false; } size_t index = 0; // Send sync instance->encoder.upload[index++] = level_duration_make(false, (uint32_t)instance->te * 16); // Send key data for(uint8_t i = instance->generic.data_count_bit; i > 0; i--) { if(bit_read(instance->generic.data, i - 1)) { // send bit 1 instance->encoder.upload[index++] = level_duration_make(false, (uint32_t)instance->te); instance->encoder.upload[index++] = level_duration_make(true, (uint32_t)instance->te * 3); } else { // send bit 0 instance->encoder.upload[index++] = level_duration_make(false, (uint32_t)instance->te * 3); instance->encoder.upload[index++] = level_duration_make(true, (uint32_t)instance->te); } } return true; } SubGhzProtocolStatus subghz_protocol_encoder_legrand_deserialize(void* context, FlipperFormat* flipper_format) { furi_assert(context); SubGhzProtocolEncoderLegrand* instance = context; SubGhzProtocolStatus ret = SubGhzProtocolStatusError; do { ret = subghz_block_generic_deserialize_check_count_bit( &instance->generic, flipper_format, subghz_protocol_legrand_const.min_count_bit_for_found); if(ret != SubGhzProtocolStatusOk) { break; } if(!flipper_format_rewind(flipper_format)) { FURI_LOG_E(TAG, "Rewind error"); ret = SubGhzProtocolStatusErrorParserOthers; break; } if(!flipper_format_read_uint32(flipper_format, "TE", (uint32_t*)&instance->te, 1)) { FURI_LOG_E(TAG, "Missing TE"); ret = SubGhzProtocolStatusErrorParserTe; break; } // optional parameter flipper_format_read_uint32( flipper_format, "Repeat", (uint32_t*)&instance->encoder.repeat, 1); if(!subghz_protocol_encoder_legrand_get_upload(instance)) { ret = SubGhzProtocolStatusErrorEncoderGetUpload; break; } instance->encoder.is_running = true; } while(false); return ret; } void subghz_protocol_encoder_legrand_stop(void* context) { SubGhzProtocolEncoderLegrand* instance = context; instance->encoder.is_running = false; } LevelDuration subghz_protocol_encoder_legrand_yield(void* context) { SubGhzProtocolEncoderLegrand* instance = context; if(instance->encoder.repeat == 0 || !instance->encoder.is_running) { instance->encoder.is_running = 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; } void* subghz_protocol_decoder_legrand_alloc(SubGhzEnvironment* environment) { UNUSED(environment); SubGhzProtocolDecoderLegrand* instance = malloc(sizeof(SubGhzProtocolDecoderLegrand)); instance->base.protocol = &subghz_protocol_legrand; instance->generic.protocol_name = instance->base.protocol->name; return instance; } void subghz_protocol_decoder_legrand_free(void* context) { furi_assert(context); SubGhzProtocolDecoderLegrand* instance = context; free(instance); } void subghz_protocol_decoder_legrand_reset(void* context) { furi_assert(context); SubGhzProtocolDecoderLegrand* instance = context; instance->decoder.parser_step = LegrandDecoderStepReset; instance->last_data = 0; } void subghz_protocol_decoder_legrand_feed(void* context, bool level, uint32_t duration) { furi_assert(context); SubGhzProtocolDecoderLegrand* instance = context; switch(instance->decoder.parser_step) { case LegrandDecoderStepReset: if(!level && DURATION_DIFF(duration, subghz_protocol_legrand_const.te_short * 16) < subghz_protocol_legrand_const.te_delta * 8) { instance->decoder.parser_step = LegrandDecoderStepFirstBit; instance->decoder.decode_data = 0; instance->decoder.decode_count_bit = 0; instance->te = 0; } break; case LegrandDecoderStepFirstBit: if(level) { if(DURATION_DIFF(duration, subghz_protocol_legrand_const.te_short) < subghz_protocol_legrand_const.te_delta) { subghz_protocol_blocks_add_bit(&instance->decoder, 0); instance->te += duration * 4; // long low that is part of sync, then short high } if(DURATION_DIFF(duration, subghz_protocol_legrand_const.te_long) < subghz_protocol_legrand_const.te_delta * 3) { subghz_protocol_blocks_add_bit(&instance->decoder, 1); instance->te += duration / 3 * 4; // short low that is part of sync, then long high } if(instance->decoder.decode_count_bit > 0) { // advance to the next step if either short or long is found instance->decoder.parser_step = LegrandDecoderStepSaveDuration; break; } } instance->decoder.parser_step = LegrandDecoderStepReset; break; case LegrandDecoderStepSaveDuration: if(!level) { instance->decoder.te_last = duration; instance->te += duration; instance->decoder.parser_step = LegrandDecoderStepCheckDuration; break; } instance->decoder.parser_step = LegrandDecoderStepReset; break; case LegrandDecoderStepCheckDuration: if(level) { uint8_t found = 0; if(DURATION_DIFF(instance->decoder.te_last, subghz_protocol_legrand_const.te_long) < subghz_protocol_legrand_const.te_delta * 3 && DURATION_DIFF(duration, subghz_protocol_legrand_const.te_short) < subghz_protocol_legrand_const.te_delta) { found = 1; subghz_protocol_blocks_add_bit(&instance->decoder, 0); } if(DURATION_DIFF(instance->decoder.te_last, subghz_protocol_legrand_const.te_short) < subghz_protocol_legrand_const.te_delta && DURATION_DIFF(duration, subghz_protocol_legrand_const.te_long) < subghz_protocol_legrand_const.te_delta * 3) { found = 1; subghz_protocol_blocks_add_bit(&instance->decoder, 1); } if(found) { instance->te += duration; if(instance->decoder.decode_count_bit < subghz_protocol_legrand_const.min_count_bit_for_found) { instance->decoder.parser_step = LegrandDecoderStepSaveDuration; break; } // enough bits for a packet found, save it only if there was a previous packet // with the same data if(instance->last_data && (instance->last_data == instance->decoder.decode_data)) { instance->te /= instance->decoder.decode_count_bit * 4; instance->generic.data = instance->decoder.decode_data; instance->generic.data_count_bit = instance->decoder.decode_count_bit; if(instance->base.callback) { instance->base.callback(&instance->base, instance->base.context); } } instance->last_data = instance->decoder.decode_data; // fallthrough to reset, the next bit is expected to be a sync // it also takes care of resetting the decoder state } } instance->decoder.parser_step = LegrandDecoderStepReset; break; } } uint8_t subghz_protocol_decoder_legrand_get_hash_data(void* context) { furi_assert(context); SubGhzProtocolDecoderLegrand* instance = context; return subghz_protocol_blocks_get_hash_data( &instance->decoder, (instance->decoder.decode_count_bit / 8) + 1); } SubGhzProtocolStatus subghz_protocol_decoder_legrand_serialize( void* context, FlipperFormat* flipper_format, SubGhzRadioPreset* preset) { furi_assert(context); SubGhzProtocolDecoderLegrand* instance = context; SubGhzProtocolStatus ret = subghz_block_generic_serialize(&instance->generic, flipper_format, preset); if((ret == SubGhzProtocolStatusOk) && !flipper_format_write_uint32(flipper_format, "TE", &instance->te, 1)) { FURI_LOG_E(TAG, "Unable to add TE"); ret = SubGhzProtocolStatusErrorParserTe; } return ret; } SubGhzProtocolStatus subghz_protocol_decoder_legrand_deserialize(void* context, FlipperFormat* flipper_format) { furi_assert(context); SubGhzProtocolDecoderLegrand* instance = context; SubGhzProtocolStatus ret = SubGhzProtocolStatusError; do { ret = subghz_block_generic_deserialize_check_count_bit( &instance->generic, flipper_format, subghz_protocol_legrand_const.min_count_bit_for_found); if(ret != SubGhzProtocolStatusOk) { break; } if(!flipper_format_rewind(flipper_format)) { FURI_LOG_E(TAG, "Rewind error"); ret = SubGhzProtocolStatusErrorParserOthers; break; } if(!flipper_format_read_uint32(flipper_format, "TE", (uint32_t*)&instance->te, 1)) { FURI_LOG_E(TAG, "Missing TE"); ret = SubGhzProtocolStatusErrorParserTe; break; } } while(false); return ret; } void subghz_protocol_decoder_legrand_get_string(void* context, FuriString* output) { furi_assert(context); SubGhzProtocolDecoderLegrand* instance = context; furi_string_cat_printf( output, "%s %dbit\r\n" "Key:0x%05lX\r\n" "Te:%luus\r\n", instance->generic.protocol_name, instance->generic.data_count_bit, (uint32_t)(instance->generic.data & 0xFFFFFF), instance->te); }
13,589
C
.c
319
34.382445
99
0.66104
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,305
devices.c
DarkFlippers_unleashed-firmware/lib/subghz/devices/devices.c
#include "devices.h" #include "registry.h" void subghz_devices_init(void) { furi_check(!subghz_device_registry_is_valid()); subghz_device_registry_init(); } void subghz_devices_deinit(void) { furi_check(subghz_device_registry_is_valid()); subghz_device_registry_deinit(); } const SubGhzDevice* subghz_devices_get_by_name(const char* device_name) { furi_check(subghz_device_registry_is_valid()); const SubGhzDevice* device = subghz_device_registry_get_by_name(device_name); return device; } const char* subghz_devices_get_name(const SubGhzDevice* device) { const char* ret = NULL; if(device) { ret = device->name; } return ret; } bool subghz_devices_begin(const SubGhzDevice* device) { furi_check(device); bool ret = false; if(device->interconnect->begin) { SubGhzDeviceConf conf = { .ver = 1, .extended_range = false, // TODO .amp_and_leds = furi_hal_subghz_get_ext_leds_and_amp(), }; ret = device->interconnect->begin(&conf); } return ret; } void subghz_devices_end(const SubGhzDevice* device) { furi_check(device); if(device->interconnect->end) { device->interconnect->end(); } } bool subghz_devices_is_connect(const SubGhzDevice* device) { furi_check(device); bool ret = false; if(device->interconnect->is_connect) { ret = device->interconnect->is_connect(); } return ret; } void subghz_devices_reset(const SubGhzDevice* device) { furi_check(device); if(device->interconnect->reset) { device->interconnect->reset(); } } void subghz_devices_sleep(const SubGhzDevice* device) { furi_check(device); if(device->interconnect->sleep) { device->interconnect->sleep(); } } void subghz_devices_idle(const SubGhzDevice* device) { furi_check(device); if(device->interconnect->idle) { device->interconnect->idle(); } } void subghz_devices_load_preset( const SubGhzDevice* device, FuriHalSubGhzPreset preset, uint8_t* preset_data) { furi_check(device); if(device->interconnect->load_preset) { device->interconnect->load_preset(preset, preset_data); } } uint32_t subghz_devices_set_frequency(const SubGhzDevice* device, uint32_t frequency) { furi_check(device); uint32_t ret = 0; if(device->interconnect->set_frequency) { ret = device->interconnect->set_frequency(frequency); } return ret; } bool subghz_devices_is_frequency_valid(const SubGhzDevice* device, uint32_t frequency) { bool ret = false; furi_check(device); if(device->interconnect->is_frequency_valid) { ret = device->interconnect->is_frequency_valid(frequency); } return ret; } void subghz_devices_set_async_mirror_pin(const SubGhzDevice* device, const GpioPin* gpio) { furi_check(device); if(device->interconnect->set_async_mirror_pin) { device->interconnect->set_async_mirror_pin(gpio); } } const GpioPin* subghz_devices_get_data_gpio(const SubGhzDevice* device) { furi_check(device); const GpioPin* ret = NULL; if(device->interconnect->get_data_gpio) { ret = device->interconnect->get_data_gpio(); } return ret; } bool subghz_devices_set_tx(const SubGhzDevice* device) { bool ret = 0; furi_check(device); if(device->interconnect->set_tx) { ret = device->interconnect->set_tx(); } return ret; } void subghz_devices_flush_tx(const SubGhzDevice* device) { furi_check(device); if(device->interconnect->flush_tx) { device->interconnect->flush_tx(); } } bool subghz_devices_start_async_tx(const SubGhzDevice* device, void* callback, void* context) { bool ret = false; furi_check(device); if(device->interconnect->start_async_tx) { ret = device->interconnect->start_async_tx(callback, context); } return ret; } bool subghz_devices_is_async_complete_tx(const SubGhzDevice* device) { bool ret = false; furi_check(device); if(device->interconnect->is_async_complete_tx) { ret = device->interconnect->is_async_complete_tx(); } return ret; } void subghz_devices_stop_async_tx(const SubGhzDevice* device) { furi_check(device); if(device->interconnect->stop_async_tx) { device->interconnect->stop_async_tx(); } } void subghz_devices_set_rx(const SubGhzDevice* device) { furi_check(device); if(device->interconnect->set_rx) { device->interconnect->set_rx(); } } void subghz_devices_flush_rx(const SubGhzDevice* device) { furi_check(device); if(device->interconnect->flush_rx) { device->interconnect->flush_rx(); } } void subghz_devices_start_async_rx(const SubGhzDevice* device, void* callback, void* context) { furi_check(device); if(device->interconnect->start_async_rx) { device->interconnect->start_async_rx(callback, context); } } void subghz_devices_stop_async_rx(const SubGhzDevice* device) { furi_check(device); if(device->interconnect->stop_async_rx) { device->interconnect->stop_async_rx(); } } float subghz_devices_get_rssi(const SubGhzDevice* device) { float ret = 0; furi_check(device); if(device->interconnect->get_rssi) { ret = device->interconnect->get_rssi(); } return ret; } uint8_t subghz_devices_get_lqi(const SubGhzDevice* device) { furi_check(device); uint8_t ret = 0; if(device->interconnect->get_lqi) { ret = device->interconnect->get_lqi(); } return ret; } bool subghz_devices_rx_pipe_not_empty(const SubGhzDevice* device) { furi_check(device); bool ret = false; if(device->interconnect->rx_pipe_not_empty) { ret = device->interconnect->rx_pipe_not_empty(); } return ret; } bool subghz_devices_is_rx_data_crc_valid(const SubGhzDevice* device) { bool ret = false; furi_check(device); if(device->interconnect->is_rx_data_crc_valid) { ret = device->interconnect->is_rx_data_crc_valid(); } return ret; } void subghz_devices_read_packet(const SubGhzDevice* device, uint8_t* data, uint8_t* size) { furi_check(device); if(device->interconnect->read_packet) { device->interconnect->read_packet(data, size); } } void subghz_devices_write_packet(const SubGhzDevice* device, const uint8_t* data, uint8_t size) { furi_check(device); if(device->interconnect->write_packet) { device->interconnect->write_packet(data, size); } }
6,543
C
.c
210
26.519048
97
0.680051
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,307
registry.c
DarkFlippers_unleashed-firmware/lib/subghz/devices/registry.c
#include "registry.h" #include "cc1101_int/cc1101_int_interconnect.h" #include <flipper_application/plugins/plugin_manager.h> #include <loader/firmware_api/firmware_api.h> #define TAG "SubGhzDeviceRegistry" struct SubGhzDeviceRegistry { const SubGhzDevice** items; size_t size; PluginManager* manager; }; static SubGhzDeviceRegistry* subghz_device_registry = NULL; void subghz_device_registry_init(void) { SubGhzDeviceRegistry* subghz_device = (SubGhzDeviceRegistry*)malloc(sizeof(SubGhzDeviceRegistry)); subghz_device->manager = plugin_manager_alloc( SUBGHZ_RADIO_DEVICE_PLUGIN_APP_ID, SUBGHZ_RADIO_DEVICE_PLUGIN_API_VERSION, firmware_api_interface); //TODO FL-3556: fix path to plugins //if(plugin_manager_load_all(subghz_device->manager, APP_DATA_PATH("plugins")) != // if(plugin_manager_load_all(subghz_device->manager, EXT_PATH("apps_data/subghz/plugins")) != PluginManagerErrorNone) { FURI_LOG_E(TAG, "Failed to load all libs"); } subghz_device->size = plugin_manager_get_count(subghz_device->manager) + 1; subghz_device->items = (const SubGhzDevice**)malloc(sizeof(SubGhzDevice*) * subghz_device->size); subghz_device->items[0] = &subghz_device_cc1101_int; for(uint32_t i = 1; i < subghz_device->size; i++) { const SubGhzDevice* plugin = plugin_manager_get_ep(subghz_device->manager, i - 1); subghz_device->items[i] = plugin; } FURI_LOG_I(TAG, "Loaded %zu radio device", subghz_device->size); subghz_device_registry = subghz_device; } void subghz_device_registry_deinit(void) { plugin_manager_free(subghz_device_registry->manager); free(subghz_device_registry->items); free(subghz_device_registry); subghz_device_registry = NULL; } bool subghz_device_registry_is_valid(void) { return subghz_device_registry != NULL; } const SubGhzDevice* subghz_device_registry_get_by_name(const char* name) { furi_assert(subghz_device_registry); if(name != NULL) { for(size_t i = 0; i < subghz_device_registry->size; i++) { if(strcmp(name, subghz_device_registry->items[i]->name) == 0) { return subghz_device_registry->items[i]; } } } return NULL; } const SubGhzDevice* subghz_device_registry_get_by_index(size_t index) { furi_assert(subghz_device_registry); if(index < subghz_device_registry->size) { return subghz_device_registry->items[index]; } else { return NULL; } }
2,540
C
.c
64
34.375
95
0.691839
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,311
cc1101_int_interconnect.c
DarkFlippers_unleashed-firmware/lib/subghz/devices/cc1101_int/cc1101_int_interconnect.c
#include "cc1101_int_interconnect.h" #include <furi_hal.h> #include "../cc1101_configs.h" #define TAG "SubGhzDeviceCc1101Int" static bool subghz_device_cc1101_int_interconnect_is_frequency_valid(uint32_t frequency) { bool ret = furi_hal_subghz_is_frequency_valid(frequency); if(!ret) { furi_crash("SubGhz: Incorrect frequency."); } return ret; } static uint32_t subghz_device_cc1101_int_interconnect_set_frequency(uint32_t frequency) { subghz_device_cc1101_int_interconnect_is_frequency_valid(frequency); return furi_hal_subghz_set_frequency_and_path(frequency); } static bool subghz_device_cc1101_int_interconnect_start_async_tx(void* callback, void* context) { return furi_hal_subghz_start_async_tx((FuriHalSubGhzAsyncTxCallback)callback, context); } static void subghz_device_cc1101_int_interconnect_start_async_rx(void* callback, void* context) { furi_hal_subghz_start_async_rx((FuriHalSubGhzCaptureCallback)callback, context); } static void subghz_device_cc1101_int_interconnect_load_preset( FuriHalSubGhzPreset preset, uint8_t* preset_data) { switch(preset) { case FuriHalSubGhzPresetOok650Async: furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_ook_650khz_async_regs); break; case FuriHalSubGhzPresetOok270Async: furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_ook_270khz_async_regs); break; case FuriHalSubGhzPreset2FSKDev238Async: furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_2fsk_dev2_38khz_async_regs); break; case FuriHalSubGhzPreset2FSKDev476Async: furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_2fsk_dev47_6khz_async_regs); break; case FuriHalSubGhzPresetMSK99_97KbAsync: furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_msk_99_97kb_async_regs); break; case FuriHalSubGhzPresetGFSK9_99KbAsync: furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_gfsk_9_99kb_async_regs); break; default: furi_hal_subghz_load_custom_preset(preset_data); } } static bool subghz_device_cc1101_int_interconnect_is_connect(void) { return true; } const SubGhzDeviceInterconnect subghz_device_cc1101_int_interconnect = { .begin = NULL, .end = furi_hal_subghz_shutdown, .is_connect = subghz_device_cc1101_int_interconnect_is_connect, .reset = furi_hal_subghz_reset, .sleep = furi_hal_subghz_sleep, .idle = furi_hal_subghz_idle, .load_preset = subghz_device_cc1101_int_interconnect_load_preset, .set_frequency = subghz_device_cc1101_int_interconnect_set_frequency, .is_frequency_valid = furi_hal_subghz_is_frequency_valid, .set_async_mirror_pin = furi_hal_subghz_set_async_mirror_pin, .get_data_gpio = furi_hal_subghz_get_data_gpio, .set_tx = furi_hal_subghz_tx, .flush_tx = furi_hal_subghz_flush_tx, .start_async_tx = subghz_device_cc1101_int_interconnect_start_async_tx, .is_async_complete_tx = furi_hal_subghz_is_async_tx_complete, .stop_async_tx = furi_hal_subghz_stop_async_tx, .set_rx = furi_hal_subghz_rx, .flush_rx = furi_hal_subghz_flush_rx, .start_async_rx = subghz_device_cc1101_int_interconnect_start_async_rx, .stop_async_rx = furi_hal_subghz_stop_async_rx, .get_rssi = furi_hal_subghz_get_rssi, .get_lqi = furi_hal_subghz_get_lqi, .rx_pipe_not_empty = furi_hal_subghz_rx_pipe_not_empty, .is_rx_data_crc_valid = furi_hal_subghz_is_rx_data_crc_valid, .read_packet = furi_hal_subghz_read_packet, .write_packet = furi_hal_subghz_write_packet, }; const SubGhzDevice subghz_device_cc1101_int = { .name = SUBGHZ_DEVICE_CC1101_INT_NAME, .interconnect = &subghz_device_cc1101_int_interconnect, };
3,796
C
.c
82
41.414634
99
0.738378
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,312
cc1101_int_interconnect.h
DarkFlippers_unleashed-firmware/lib/subghz/devices/cc1101_int/cc1101_int_interconnect.h
#pragma once #include "../types.h" #define SUBGHZ_DEVICE_CC1101_INT_NAME "cc1101_int" typedef struct SubGhzDeviceCC1101Int SubGhzDeviceCC1101Int; extern const SubGhzDevice subghz_device_cc1101_int;
201
C
.c
5
38.6
59
0.839378
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,313
encoder.c
DarkFlippers_unleashed-firmware/lib/subghz/blocks/encoder.c
#include "encoder.h" #include "math.h" #include <core/check.h> #define TAG "SubGhzBlockEncoder" void subghz_protocol_blocks_set_bit_array( bool bit_value, uint8_t data_array[], size_t set_index_bit, size_t max_size_array) { furi_check(set_index_bit < max_size_array * 8); bit_write(data_array[set_index_bit >> 3], 7 - (set_index_bit & 0x7), bit_value); } bool subghz_protocol_blocks_get_bit_array(uint8_t data_array[], size_t read_index_bit) { return bit_read(data_array[read_index_bit >> 3], 7 - (read_index_bit & 0x7)); } size_t subghz_protocol_blocks_get_upload_from_bit_array( uint8_t data_array[], size_t count_bit_data_array, LevelDuration* upload, size_t max_size_upload, uint32_t duration_bit, SubGhzProtocolBlockAlignBit align_bit) { size_t bias_bit = 0; size_t size_upload = 0; uint32_t duration = duration_bit; if(align_bit == SubGhzProtocolBlockAlignBitRight) { if(count_bit_data_array & 0x7) { bias_bit = 8 - (count_bit_data_array & 0x7); } } size_t index_bit = bias_bit; bool last_bit = subghz_protocol_blocks_get_bit_array(data_array, index_bit++); for(size_t i = 1 + bias_bit; i < count_bit_data_array + bias_bit; i++) { if(last_bit == subghz_protocol_blocks_get_bit_array(data_array, index_bit)) { duration += duration_bit; } else { if(size_upload > max_size_upload) { furi_crash("SubGhz: Encoder buffer overflow"); } upload[size_upload++] = level_duration_make( subghz_protocol_blocks_get_bit_array(data_array, index_bit - 1), duration); last_bit = !last_bit; duration = duration_bit; } index_bit++; } upload[size_upload++] = level_duration_make( subghz_protocol_blocks_get_bit_array(data_array, index_bit - 1), duration); return size_upload; }
1,937
C
.c
50
32.26
91
0.632111
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,314
custom_btn.c
DarkFlippers_unleashed-firmware/lib/subghz/blocks/custom_btn.c
#include "custom_btn_i.h" static uint8_t custom_btn_id = SUBGHZ_CUSTOM_BTN_OK; static uint8_t custom_btn_original = 0; static uint8_t custom_btn_max_btns = 0; static uint8_t controller_programming_mode = PROG_MODE_OFF; bool subghz_custom_btn_set(uint8_t btn_id) { if(btn_id > custom_btn_max_btns) { custom_btn_id = SUBGHZ_CUSTOM_BTN_OK; return false; } else { custom_btn_id = btn_id; return true; } } uint8_t subghz_custom_btn_get(void) { return custom_btn_id; } void subghz_custom_btn_set_original(uint8_t btn_code) { custom_btn_original = btn_code; } uint8_t subghz_custom_btn_get_original(void) { return custom_btn_original; } void subghz_custom_btn_set_max(uint8_t b) { custom_btn_max_btns = b; } void subghz_custom_btns_reset(void) { custom_btn_original = 0; custom_btn_max_btns = 0; controller_programming_mode = PROG_MODE_OFF; custom_btn_id = SUBGHZ_CUSTOM_BTN_OK; } bool subghz_custom_btn_is_allowed(void) { return custom_btn_max_btns != 0; } void subghz_custom_btn_set_prog_mode(ProgMode prog_mode) { controller_programming_mode = prog_mode; } ProgMode subghz_custom_btn_get_prog_mode(void) { return controller_programming_mode; }
1,238
C
.c
41
26.804878
59
0.708509
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,316
decoder.c
DarkFlippers_unleashed-firmware/lib/subghz/blocks/decoder.c
#include "decoder.h" #define TAG "SubGhzBlockDecoder" void subghz_protocol_blocks_add_bit(SubGhzBlockDecoder* decoder, uint8_t bit) { decoder->decode_data = decoder->decode_data << 1 | bit; decoder->decode_count_bit++; } void subghz_protocol_blocks_add_to_128_bit( SubGhzBlockDecoder* decoder, uint8_t bit, uint64_t* head_64_bit) { if(++decoder->decode_count_bit > 64) { (*head_64_bit) = ((*head_64_bit) << 1) | (decoder->decode_data >> 63); } decoder->decode_data = decoder->decode_data << 1 | bit; } uint8_t subghz_protocol_blocks_get_hash_data(SubGhzBlockDecoder* decoder, size_t len) { uint8_t hash = 0; uint8_t* p = (uint8_t*)&decoder->decode_data; for(size_t i = 0; i < len; i++) { hash ^= p[i]; } return hash; }
791
C
.c
23
30.26087
87
0.645288
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,317
generic.c
DarkFlippers_unleashed-firmware/lib/subghz/blocks/generic.c
#include "generic.h" #include <lib/toolbox/stream/stream.h> #include <lib/flipper_format/flipper_format_i.h> #define TAG "SubGhzBlockGeneric" void subghz_block_generic_get_preset_name(const char* preset_name, FuriString* preset_str) { const char* preset_name_temp; if(!strcmp(preset_name, "AM270")) { preset_name_temp = "FuriHalSubGhzPresetOok270Async"; } else if(!strcmp(preset_name, "AM650")) { preset_name_temp = "FuriHalSubGhzPresetOok650Async"; } else if(!strcmp(preset_name, "FM238")) { preset_name_temp = "FuriHalSubGhzPreset2FSKDev238Async"; } else if(!strcmp(preset_name, "FM476")) { preset_name_temp = "FuriHalSubGhzPreset2FSKDev476Async"; } else { preset_name_temp = "FuriHalSubGhzPresetCustom"; } furi_string_set(preset_str, preset_name_temp); } SubGhzProtocolStatus subghz_block_generic_serialize( SubGhzBlockGeneric* instance, FlipperFormat* flipper_format, SubGhzRadioPreset* preset) { furi_check(instance); SubGhzProtocolStatus res = SubGhzProtocolStatusError; FuriString* temp_str; temp_str = furi_string_alloc(); do { stream_clean(flipper_format_get_raw_stream(flipper_format)); if(!flipper_format_write_header_cstr( flipper_format, SUBGHZ_KEY_FILE_TYPE, SUBGHZ_KEY_FILE_VERSION)) { FURI_LOG_E(TAG, "Unable to add header"); res = SubGhzProtocolStatusErrorParserHeader; break; } if(!flipper_format_write_uint32(flipper_format, "Frequency", &preset->frequency, 1)) { FURI_LOG_E(TAG, "Unable to add Frequency"); res = SubGhzProtocolStatusErrorParserFrequency; break; } subghz_block_generic_get_preset_name(furi_string_get_cstr(preset->name), temp_str); if(!flipper_format_write_string_cstr( flipper_format, "Preset", furi_string_get_cstr(temp_str))) { FURI_LOG_E(TAG, "Unable to add Preset"); res = SubGhzProtocolStatusErrorParserPreset; break; } if(!strcmp(furi_string_get_cstr(temp_str), "FuriHalSubGhzPresetCustom")) { if(!flipper_format_write_string_cstr( flipper_format, "Custom_preset_module", "CC1101")) { FURI_LOG_E(TAG, "Unable to add Custom_preset_module"); res = SubGhzProtocolStatusErrorParserCustomPreset; break; } if(!flipper_format_write_hex( flipper_format, "Custom_preset_data", preset->data, preset->data_size)) { FURI_LOG_E(TAG, "Unable to add Custom_preset_data"); res = SubGhzProtocolStatusErrorParserCustomPreset; break; } } if(!flipper_format_write_string_cstr(flipper_format, "Protocol", instance->protocol_name)) { FURI_LOG_E(TAG, "Unable to add Protocol"); res = SubGhzProtocolStatusErrorParserProtocolName; break; } uint32_t temp = instance->data_count_bit; if(!flipper_format_write_uint32(flipper_format, "Bit", &temp, 1)) { FURI_LOG_E(TAG, "Unable to add Bit"); res = SubGhzProtocolStatusErrorParserBitCount; break; } 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->data >> (i * 8)) & 0xFF; } if(!flipper_format_write_hex(flipper_format, "Key", key_data, sizeof(uint64_t))) { FURI_LOG_E(TAG, "Unable to add Key"); res = SubGhzProtocolStatusErrorParserKey; break; } // Nice One - Manual adding support if(instance->data_count_bit == 72 && (strcmp(instance->protocol_name, "Nice FloR-S") == 0)) { uint32_t temp = (instance->data_2 >> 4) & 0xFFFFF; if(!flipper_format_write_uint32(flipper_format, "Data", &temp, 1)) { FURI_LOG_E(TAG, "Unable to add Data"); break; } } res = SubGhzProtocolStatusOk; } while(false); furi_string_free(temp_str); return res; } SubGhzProtocolStatus subghz_block_generic_deserialize(SubGhzBlockGeneric* instance, FlipperFormat* flipper_format) { furi_check(instance); SubGhzProtocolStatus res = SubGhzProtocolStatusError; FuriString* temp_str; temp_str = furi_string_alloc(); uint32_t temp_data = 0; do { if(!flipper_format_rewind(flipper_format)) { FURI_LOG_E(TAG, "Rewind error"); res = SubGhzProtocolStatusErrorParserOthers; break; } if(!flipper_format_read_uint32(flipper_format, "Bit", (uint32_t*)&temp_data, 1)) { FURI_LOG_E(TAG, "Missing Bit"); res = SubGhzProtocolStatusErrorParserBitCount; break; } instance->data_count_bit = (uint16_t)temp_data; uint8_t key_data[sizeof(uint64_t)] = {0}; if(!flipper_format_read_hex(flipper_format, "Key", key_data, sizeof(uint64_t))) { FURI_LOG_E(TAG, "Missing Key"); res = SubGhzProtocolStatusErrorParserKey; break; } for(uint8_t i = 0; i < sizeof(uint64_t); i++) { instance->data = instance->data << 8 | key_data[i]; } res = SubGhzProtocolStatusOk; } while(0); furi_string_free(temp_str); return res; } SubGhzProtocolStatus subghz_block_generic_deserialize_check_count_bit( SubGhzBlockGeneric* instance, FlipperFormat* flipper_format, uint16_t count_bit) { furi_check(instance); SubGhzProtocolStatus ret = SubGhzProtocolStatusError; do { ret = subghz_block_generic_deserialize(instance, flipper_format); if(ret != SubGhzProtocolStatusOk) { break; } if(instance->data_count_bit != count_bit) { FURI_LOG_D(TAG, "Wrong number of bits in key"); ret = SubGhzProtocolStatusErrorValueBitCount; break; } } while(false); return ret; }
6,140
C
.c
147
32.530612
100
0.615693
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,320
math.c
DarkFlippers_unleashed-firmware/lib/subghz/blocks/math.c
#include "math.h" uint64_t subghz_protocol_blocks_reverse_key(uint64_t key, uint8_t bit_count) { uint64_t reverse_key = 0; for(uint8_t i = 0; i < bit_count; i++) { reverse_key = reverse_key << 1 | bit_read(key, i); } return reverse_key; } uint8_t subghz_protocol_blocks_get_parity(uint64_t key, uint8_t bit_count) { uint8_t parity = 0; for(uint8_t i = 0; i < bit_count; i++) { parity += bit_read(key, i); } return parity & 0x01; } uint8_t subghz_protocol_blocks_crc4( uint8_t const message[], size_t size, uint8_t polynomial, uint8_t init) { uint8_t remainder = init << 4; // LSBs are unused uint8_t poly = polynomial << 4; uint8_t bit; while(size--) { remainder ^= *message++; for(bit = 0; bit < 8; bit++) { if(remainder & 0x80) { remainder = (remainder << 1) ^ poly; } else { remainder = (remainder << 1); } } } return remainder >> 4 & 0x0f; // discard the LSBs } uint8_t subghz_protocol_blocks_crc7( uint8_t const message[], size_t size, uint8_t polynomial, uint8_t init) { uint8_t remainder = init << 1; // LSB is unused uint8_t poly = polynomial << 1; for(size_t byte = 0; byte < size; ++byte) { remainder ^= message[byte]; for(uint8_t bit = 0; bit < 8; ++bit) { if(remainder & 0x80) { remainder = (remainder << 1) ^ poly; } else { remainder = (remainder << 1); } } } return remainder >> 1 & 0x7f; // discard the LSB } uint8_t subghz_protocol_blocks_crc8( uint8_t const message[], size_t size, uint8_t polynomial, uint8_t init) { uint8_t remainder = init; for(size_t byte = 0; byte < size; ++byte) { remainder ^= message[byte]; for(uint8_t bit = 0; bit < 8; ++bit) { if(remainder & 0x80) { remainder = (remainder << 1) ^ polynomial; } else { remainder = (remainder << 1); } } } return remainder; } uint8_t subghz_protocol_blocks_crc8le( uint8_t const message[], size_t size, uint8_t polynomial, uint8_t init) { uint8_t remainder = subghz_protocol_blocks_reverse_key(init, 8); polynomial = subghz_protocol_blocks_reverse_key(polynomial, 8); for(size_t byte = 0; byte < size; ++byte) { remainder ^= message[byte]; for(uint8_t bit = 0; bit < 8; ++bit) { if(remainder & 1) { remainder = (remainder >> 1) ^ polynomial; } else { remainder = (remainder >> 1); } } } return remainder; } uint16_t subghz_protocol_blocks_crc16lsb( uint8_t const message[], size_t size, uint16_t polynomial, uint16_t init) { uint16_t remainder = init; for(size_t byte = 0; byte < size; ++byte) { remainder ^= message[byte]; for(uint8_t bit = 0; bit < 8; ++bit) { if(remainder & 1) { remainder = (remainder >> 1) ^ polynomial; } else { remainder = (remainder >> 1); } } } return remainder; } uint16_t subghz_protocol_blocks_crc16( uint8_t const message[], size_t size, uint16_t polynomial, uint16_t init) { uint16_t remainder = init; for(size_t byte = 0; byte < size; ++byte) { remainder ^= message[byte] << 8; for(uint8_t bit = 0; bit < 8; ++bit) { if(remainder & 0x8000) { remainder = (remainder << 1) ^ polynomial; } else { remainder = (remainder << 1); } } } return remainder; } uint8_t subghz_protocol_blocks_lfsr_digest8( uint8_t const message[], size_t size, uint8_t gen, uint8_t key) { uint8_t sum = 0; for(size_t byte = 0; byte < size; ++byte) { uint8_t data = message[byte]; for(int i = 7; i >= 0; --i) { // XOR key into sum if data bit is set if((data >> i) & 1) sum ^= key; // roll the key right (actually the LSB is dropped here) // and apply the gen (needs to include the dropped LSB as MSB) if(key & 1) key = (key >> 1) ^ gen; else key = (key >> 1); } } return sum; } uint8_t subghz_protocol_blocks_lfsr_digest8_reflect( uint8_t const message[], size_t size, uint8_t gen, uint8_t key) { uint8_t sum = 0; // Process message from last byte to first byte (reflected) for(int byte = size - 1; byte >= 0; --byte) { uint8_t data = message[byte]; // Process individual bits of each byte (reflected) for(uint8_t i = 0; i < 8; ++i) { // XOR key into sum if data bit is set if((data >> i) & 1) { sum ^= key; } // roll the key left (actually the LSB is dropped here) // and apply the gen (needs to include the dropped lsb as MSB) if(key & 0x80) key = (key << 1) ^ gen; else key = (key << 1); } } return sum; } uint16_t subghz_protocol_blocks_lfsr_digest16( uint8_t const message[], size_t size, uint16_t gen, uint16_t key) { uint16_t sum = 0; for(size_t byte = 0; byte < size; ++byte) { uint8_t data = message[byte]; for(int8_t i = 7; i >= 0; --i) { // if data bit is set then xor with key if((data >> i) & 1) sum ^= key; // roll the key right (actually the LSB is dropped here) // and apply the gen (needs to include the dropped LSB as MSB) if(key & 1) key = (key >> 1) ^ gen; else key = (key >> 1); } } return sum; } uint8_t subghz_protocol_blocks_add_bytes(uint8_t const message[], size_t size) { uint32_t result = 0; for(size_t i = 0; i < size; ++i) { result += message[i]; } return (uint8_t)result; } uint8_t subghz_protocol_blocks_parity8(uint8_t byte) { byte ^= byte >> 4; byte &= 0xf; return (0x6996 >> byte) & 1; } uint8_t subghz_protocol_blocks_parity_bytes(uint8_t const message[], size_t size) { uint8_t result = 0; for(size_t i = 0; i < size; ++i) { result ^= subghz_protocol_blocks_parity8(message[i]); } return result; } uint8_t subghz_protocol_blocks_xor_bytes(uint8_t const message[], size_t size) { uint8_t result = 0; for(size_t i = 0; i < size; ++i) { result ^= message[i]; } return result; }
6,729
C
.c
220
23.059091
83
0.533231
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,322
bit_lib.c
DarkFlippers_unleashed-firmware/lib/bit_lib/bit_lib.c
#include "bit_lib.h" #include <core/check.h> #include <stdio.h> void bit_lib_push_bit(uint8_t* data, size_t data_size, bool bit) { size_t last_index = data_size - 1; for(size_t i = 0; i < last_index; ++i) { data[i] = (data[i] << 1) | ((data[i + 1] >> 7) & 1); } data[last_index] = (data[last_index] << 1) | bit; } void bit_lib_set_bit(uint8_t* data, size_t position, bool bit) { if(bit) { data[position / 8] |= 1UL << (7 - (position % 8)); } else { data[position / 8] &= ~(1UL << (7 - (position % 8))); } } void bit_lib_set_bits(uint8_t* data, size_t position, uint8_t byte, uint8_t length) { furi_check(length <= 8); furi_check(length > 0); for(uint8_t i = 0; i < length; ++i) { uint8_t shift = (length - 1) - i; bit_lib_set_bit(data, position + i, (byte >> shift) & 1); //-V610 } } bool bit_lib_get_bit(const uint8_t* data, size_t position) { return (data[position / 8] >> (7 - (position % 8))) & 1; } uint8_t bit_lib_get_bits(const uint8_t* data, size_t position, uint8_t length) { uint8_t shift = position % 8; if(shift == 0) { return data[position / 8] >> (8 - length); } else { // TODO FL-3534: fix read out of bounds uint8_t value = (data[position / 8] << (shift)); value |= data[position / 8 + 1] >> (8 - shift); value = value >> (8 - length); return value; } } uint16_t bit_lib_get_bits_16(const uint8_t* data, size_t position, uint8_t length) { uint16_t value = 0; if(length <= 8) { value = bit_lib_get_bits(data, position, length); } else { value = bit_lib_get_bits(data, position, 8) << (length - 8); value |= bit_lib_get_bits(data, position + 8, length - 8); } return value; } uint32_t bit_lib_get_bits_32(const uint8_t* data, size_t position, uint8_t length) { uint32_t value = 0; if(length <= 8) { value = bit_lib_get_bits(data, position, length); } else if(length <= 16) { value = bit_lib_get_bits(data, position, 8) << (length - 8); value |= bit_lib_get_bits(data, position + 8, length - 8); } else if(length <= 24) { value = bit_lib_get_bits(data, position, 8) << (length - 8); value |= bit_lib_get_bits(data, position + 8, 8) << (length - 16); value |= bit_lib_get_bits(data, position + 16, length - 16); } else { value = (uint32_t)bit_lib_get_bits(data, position, 8) << (length - 8); value |= (uint32_t)bit_lib_get_bits(data, position + 8, 8) << (length - 16); value |= (uint32_t)bit_lib_get_bits(data, position + 16, 8) << (length - 24); value |= bit_lib_get_bits(data, position + 24, length - 24); } return value; } uint64_t bit_lib_get_bits_64(const uint8_t* data, size_t position, uint8_t length) { uint64_t value = 0; if(length <= 8) { value = bit_lib_get_bits(data, position, length); } else if(length <= 16) { value = bit_lib_get_bits(data, position, 8) << (length - 8); value |= bit_lib_get_bits(data, position + 8, length - 8); } else if(length <= 24) { value = bit_lib_get_bits(data, position, 8) << (length - 8); value |= bit_lib_get_bits(data, position + 8, 8) << (length - 16); value |= bit_lib_get_bits(data, position + 16, length - 16); } else if(length <= 32) { value = (uint64_t)bit_lib_get_bits(data, position, 8) << (length - 8); value |= (uint64_t)bit_lib_get_bits(data, position + 8, 8) << (length - 16); value |= (uint64_t)bit_lib_get_bits(data, position + 16, 8) << (length - 24); value |= bit_lib_get_bits(data, position + 24, length - 24); } else if(length <= 40) { value = (uint64_t)bit_lib_get_bits(data, position, 8) << (length - 8); value |= (uint64_t)bit_lib_get_bits(data, position + 8, 8) << (length - 16); value |= (uint64_t)bit_lib_get_bits(data, position + 16, 8) << (length - 24); value |= (uint64_t)bit_lib_get_bits(data, position + 24, 8) << (length - 32); value |= bit_lib_get_bits(data, position + 32, length - 32); } else if(length <= 48) { value = (uint64_t)bit_lib_get_bits(data, position, 8) << (length - 8); value |= (uint64_t)bit_lib_get_bits(data, position + 8, 8) << (length - 16); value |= (uint64_t)bit_lib_get_bits(data, position + 16, 8) << (length - 24); value |= (uint64_t)bit_lib_get_bits(data, position + 24, 8) << (length - 32); value |= (uint64_t)bit_lib_get_bits(data, position + 32, 8) << (length - 40); value |= bit_lib_get_bits(data, position + 40, length - 40); } else if(length <= 56) { value = (uint64_t)bit_lib_get_bits(data, position, 8) << (length - 8); value |= (uint64_t)bit_lib_get_bits(data, position + 8, 8) << (length - 16); value |= (uint64_t)bit_lib_get_bits(data, position + 16, 8) << (length - 24); value |= (uint64_t)bit_lib_get_bits(data, position + 24, 8) << (length - 32); value |= (uint64_t)bit_lib_get_bits(data, position + 32, 8) << (length - 40); value |= (uint64_t)bit_lib_get_bits(data, position + 40, 8) << (length - 48); value |= bit_lib_get_bits(data, position + 48, length - 48); } else { value = (uint64_t)bit_lib_get_bits(data, position, 8) << (length - 8); value |= (uint64_t)bit_lib_get_bits(data, position + 8, 8) << (length - 16); value |= (uint64_t)bit_lib_get_bits(data, position + 16, 8) << (length - 24); value |= (uint64_t)bit_lib_get_bits(data, position + 24, 8) << (length - 32); value |= (uint64_t)bit_lib_get_bits(data, position + 32, 8) << (length - 40); value |= (uint64_t)bit_lib_get_bits(data, position + 40, 8) << (length - 48); value |= (uint64_t)bit_lib_get_bits(data, position + 48, 8) << (length - 56); value |= bit_lib_get_bits(data, position + 56, length - 56); } return value; } bool bit_lib_test_parity_32(uint32_t bits, BitLibParity parity) { #if !defined __GNUC__ #error Please, implement parity test for non-GCC compilers #else switch(parity) { case BitLibParityEven: return __builtin_parity(bits); case BitLibParityOdd: return !__builtin_parity(bits); default: furi_crash("Unknown parity"); } #endif } bool bit_lib_test_parity( const uint8_t* bits, size_t position, uint8_t length, BitLibParity parity, uint8_t parity_length) { uint32_t parity_block; bool result = true; const size_t parity_blocks_count = length / parity_length; for(size_t i = 0; i < parity_blocks_count; ++i) { switch(parity) { case BitLibParityEven: case BitLibParityOdd: parity_block = bit_lib_get_bits_32(bits, position + i * parity_length, parity_length); if(!bit_lib_test_parity_32(parity_block, parity)) { result = false; } break; case BitLibParityAlways0: if(bit_lib_get_bit(bits, position + i * parity_length + parity_length - 1)) { result = false; } break; case BitLibParityAlways1: if(!bit_lib_get_bit(bits, position + i * parity_length + parity_length - 1)) { result = false; } break; } if(!result) break; } return result; } size_t bit_lib_add_parity( const uint8_t* data, size_t position, uint8_t* dest, size_t dest_position, uint8_t source_length, uint8_t parity_length, BitLibParity parity) { uint32_t parity_word = 0; size_t j = 0, bit_count = 0; for(int word = 0; word < source_length; word += parity_length - 1) { for(int bit = 0; bit < parity_length - 1; bit++) { parity_word = (parity_word << 1) | bit_lib_get_bit(data, position + word + bit); bit_lib_set_bit( dest, dest_position + j++, bit_lib_get_bit(data, position + word + bit)); } // if parity fails then return 0 switch(parity) { case BitLibParityAlways0: bit_lib_set_bit(dest, dest_position + j++, 0); break; // marker bit which should be a 0 case BitLibParityAlways1: bit_lib_set_bit(dest, dest_position + j++, 1); break; // marker bit which should be a 1 default: bit_lib_set_bit( dest, dest_position + j++, (bit_lib_test_parity_32(parity_word, BitLibParityOdd) ^ parity) ^ 1); break; } bit_count += parity_length; parity_word = 0; } // if we got here then all the parities passed // return bit count return bit_count; } size_t bit_lib_remove_bit_every_nth(uint8_t* data, size_t position, uint8_t length, uint8_t n) { size_t counter = 0; size_t result_counter = 0; uint8_t bit_buffer = 0; uint8_t bit_counter = 0; while(counter < length) { if((counter + 1) % n != 0) { bit_buffer = (bit_buffer << 1) | bit_lib_get_bit(data, position + counter); bit_counter++; } if(bit_counter == 8) { bit_lib_set_bits(data, position + result_counter, bit_buffer, 8); bit_counter = 0; bit_buffer = 0; result_counter += 8; } counter++; } if(bit_counter != 0) { bit_lib_set_bits(data, position + result_counter, bit_buffer, bit_counter); result_counter += bit_counter; } return result_counter; } void bit_lib_copy_bits( uint8_t* data, size_t position, size_t length, const uint8_t* source, size_t source_position) { for(size_t i = 0; i < length; ++i) { bit_lib_set_bit(data, position + i, bit_lib_get_bit(source, source_position + i)); } } void bit_lib_reverse_bits(uint8_t* data, size_t position, uint8_t length) { size_t i = 0; size_t j = length - 1; while(i < j) { bool tmp = bit_lib_get_bit(data, position + i); bit_lib_set_bit(data, position + i, bit_lib_get_bit(data, position + j)); bit_lib_set_bit(data, position + j, tmp); i++; j--; } } uint8_t bit_lib_get_bit_count(uint32_t data) { #if defined __GNUC__ return __builtin_popcountl(data); #else #error Please, implement popcount for non-GCC compilers #endif } void bit_lib_print_bits(const uint8_t* data, size_t length) { for(size_t i = 0; i < length; ++i) { printf("%u", bit_lib_get_bit(data, i)); } } void bit_lib_print_regions( const BitLibRegion* regions, size_t region_count, const uint8_t* data, size_t length) { // print data bit_lib_print_bits(data, length); printf("\r\n"); // print regions for(size_t c = 0; c < length; ++c) { bool print = false; for(size_t i = 0; i < region_count; i++) { if(regions[i].start <= c && c < regions[i].start + regions[i].length) { print = true; printf("%c", regions[i].mark); break; } } if(!print) { printf(" "); } } printf("\r\n"); // print regions data for(size_t c = 0; c < length; ++c) { bool print = false; for(size_t i = 0; i < region_count; i++) { if(regions[i].start <= c && c < regions[i].start + regions[i].length) { print = true; printf("%u", bit_lib_get_bit(data, c)); break; } } if(!print) { printf(" "); } } printf("\r\n"); } uint16_t bit_lib_reverse_16_fast(uint16_t data) { uint16_t result = 0; result |= (data & 0x8000) >> 15; result |= (data & 0x4000) >> 13; result |= (data & 0x2000) >> 11; result |= (data & 0x1000) >> 9; result |= (data & 0x0800) >> 7; result |= (data & 0x0400) >> 5; result |= (data & 0x0200) >> 3; result |= (data & 0x0100) >> 1; result |= (data & 0x0080) << 1; result |= (data & 0x0040) << 3; result |= (data & 0x0020) << 5; result |= (data & 0x0010) << 7; result |= (data & 0x0008) << 9; result |= (data & 0x0004) << 11; result |= (data & 0x0002) << 13; result |= (data & 0x0001) << 15; return result; } uint8_t bit_lib_reverse_8_fast(uint8_t byte) { byte = (byte & 0xF0) >> 4 | (byte & 0x0F) << 4; byte = (byte & 0xCC) >> 2 | (byte & 0x33) << 2; byte = (byte & 0xAA) >> 1 | (byte & 0x55) << 1; return byte; } uint16_t bit_lib_crc8( uint8_t const* data, size_t data_size, uint8_t polynom, uint8_t init, bool ref_in, bool ref_out, uint8_t xor_out) { uint8_t crc = init; for(size_t i = 0; i < data_size; ++i) { uint8_t byte = data[i]; if(ref_in) bit_lib_reverse_bits(&byte, 0, 8); crc ^= byte; for(size_t j = 8; j > 0; --j) { if(crc & TOPBIT(8)) { crc = (crc << 1) ^ polynom; } else { crc = (crc << 1); } } } if(ref_out) bit_lib_reverse_bits(&crc, 0, 8); crc ^= xor_out; return crc; } uint16_t bit_lib_crc16( uint8_t const* data, size_t data_size, uint16_t polynom, uint16_t init, bool ref_in, bool ref_out, uint16_t xor_out) { uint16_t crc = init; for(size_t i = 0; i < data_size; ++i) { uint8_t byte = data[i]; if(ref_in) byte = bit_lib_reverse_16_fast(byte) >> 8; for(size_t j = 0; j < 8; ++j) { bool c15 = (crc >> 15 & 1); bool bit = (byte >> (7 - j) & 1); crc <<= 1; if(c15 ^ bit) crc ^= polynom; } } if(ref_out) crc = bit_lib_reverse_16_fast(crc); crc ^= xor_out; return crc; } void bit_lib_num_to_bytes_be(uint64_t src, uint8_t len, uint8_t* dest) { furi_check(dest); furi_check(len <= 8); while(len--) { dest[len] = (uint8_t)src; src >>= 8; } } void bit_lib_num_to_bytes_le(uint64_t src, uint8_t len, uint8_t* dest) { furi_check(dest); furi_check(len <= 8); for(int i = 0; i < len; i++) { dest[i] = (uint8_t)(src >> (8 * i)); } } uint64_t bit_lib_bytes_to_num_be(const uint8_t* src, uint8_t len) { furi_check(src); furi_check(len <= 8); uint64_t res = 0; while(len--) { res = (res << 8) | (*src); src++; } return res; } uint64_t bit_lib_bytes_to_num_le(const uint8_t* src, uint8_t len) { furi_check(src); furi_check(len <= 8); uint64_t res = 0; uint8_t shift = 0; while(len--) { res |= ((uint64_t)*src) << (8 * shift++); src++; } return res; } uint64_t bit_lib_bytes_to_num_bcd(const uint8_t* src, uint8_t len, bool* is_bcd) { furi_check(src); furi_check(len <= 9); uint64_t res = 0; uint8_t nibble_1, nibble_2; *is_bcd = true; for(uint8_t i = 0; i < len; i++) { nibble_1 = src[i] / 16; nibble_2 = src[i] % 16; if((nibble_1 > 9) || (nibble_2 > 9)) *is_bcd = false; res *= 10; res += nibble_1; res *= 10; res += nibble_2; } return res; }
15,253
C
.c
426
28.948357
98
0.546316
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,324
signal_reader.c
DarkFlippers_unleashed-firmware/lib/signal_reader/signal_reader.c
#include "signal_reader.h" #include <furi.h> #include <furi_hal.h> #include <furi_hal_gpio.h> #include <stm32wbxx_ll_dma.h> #include <stm32wbxx_ll_dmamux.h> #include <stm32wbxx_ll_tim.h> #include <stm32wbxx_ll_exti.h> #include <furi_hal_bus.h> #define SIGNAL_READER_DMA DMA2 #define SIGNAL_READER_CAPTURE_TIM (TIM16) #define SIGNAL_READER_CAPTURE_TIM_CHANNEL LL_TIM_CHANNEL_CH1 #define SIGNAL_READER_DMA_GPIO LL_DMA_CHANNEL_2 #define SIGNAL_READER_DMA_GPIO_IRQ FuriHalInterruptIdDma2Ch2 #define SIGNAL_READER_DMA_GPIO_DEF SIGNAL_READER_DMA, SIGNAL_READER_DMA_GPIO #define SIGNAL_READER_DMA_TRIGGER LL_DMA_CHANNEL_3 #define SIGNAL_READER_DMA_TRIGGER_IRQ FuriHalInterruptIdDma2Ch3 #define SIGNAL_READER_DMA_TRIGGER_DEF SIGNAL_READER_DMA, SIGNAL_READER_DMA_TRIGGER #define SIGNAL_READER_DMA_CNT_SYNC LL_DMA_CHANNEL_5 #define SIGNAL_READER_DMA_CNT_SYNC_IRQ FuriHalInterruptIdDma2Ch5 #define SIGNAL_READER_DMA_CNT_SYNC_DEF SIGNAL_READER_DMA, SIGNAL_READER_DMA_CNT_SYNC struct SignalReader { size_t buffer_size; const GpioPin* pin; GpioPull pull; SignalReaderPolarity polarity; SignalReaderTrigger trigger; uint16_t* gpio_buffer; uint8_t* bitstream_buffer; uint32_t cnt_en; uint32_t tim_cnt_compensation; uint32_t tim_arr; SignalReaderEvent event; SignalReaderEventData event_data; SignalReaderCallback callback; void* context; }; #define GPIO_PIN_MAP(pin, prefix) \ (((pin) == (LL_GPIO_PIN_0)) ? prefix##0 : \ ((pin) == (LL_GPIO_PIN_1)) ? prefix##1 : \ ((pin) == (LL_GPIO_PIN_2)) ? prefix##2 : \ ((pin) == (LL_GPIO_PIN_3)) ? prefix##3 : \ ((pin) == (LL_GPIO_PIN_4)) ? prefix##4 : \ ((pin) == (LL_GPIO_PIN_5)) ? prefix##5 : \ ((pin) == (LL_GPIO_PIN_6)) ? prefix##6 : \ ((pin) == (LL_GPIO_PIN_7)) ? prefix##7 : \ ((pin) == (LL_GPIO_PIN_8)) ? prefix##8 : \ ((pin) == (LL_GPIO_PIN_9)) ? prefix##9 : \ ((pin) == (LL_GPIO_PIN_10)) ? prefix##10 : \ ((pin) == (LL_GPIO_PIN_11)) ? prefix##11 : \ ((pin) == (LL_GPIO_PIN_12)) ? prefix##12 : \ ((pin) == (LL_GPIO_PIN_13)) ? prefix##13 : \ ((pin) == (LL_GPIO_PIN_14)) ? prefix##14 : \ prefix##15) #define GET_DMAMUX_EXTI_LINE(pin) GPIO_PIN_MAP(pin, LL_DMAMUX_REQ_GEN_EXTI_LINE) SignalReader* signal_reader_alloc(const GpioPin* gpio_pin, uint32_t size) { SignalReader* instance = malloc(sizeof(SignalReader)); instance->pin = gpio_pin; instance->pull = GpioPullNo; instance->buffer_size = size; instance->gpio_buffer = malloc(sizeof(uint16_t) * size * 8); instance->bitstream_buffer = malloc(size); instance->event.data = &instance->event_data; return instance; } void signal_reader_free(SignalReader* instance) { furi_check(instance); furi_check(instance->gpio_buffer); furi_check(instance->bitstream_buffer); free(instance->gpio_buffer); free(instance->bitstream_buffer); free(instance); } void signal_reader_set_pull(SignalReader* instance, GpioPull pull) { furi_check(instance); instance->pull = pull; } void signal_reader_set_polarity(SignalReader* instance, SignalReaderPolarity polarity) { furi_check(instance); instance->polarity = polarity; } void signal_reader_set_sample_rate( SignalReader* instance, SignalReaderTimeUnit time_unit, uint32_t time) { furi_check(instance); UNUSED(time_unit); instance->tim_arr = time; } void signal_reader_set_trigger(SignalReader* instance, SignalReaderTrigger trigger) { furi_check(instance); instance->trigger = trigger; } static void furi_hal_sw_digital_pin_dma_rx_isr(void* context) { SignalReader* instance = context; uint16_t* gpio_buff_start = NULL; uint8_t* bitstream_buff_start = NULL; if(LL_DMA_IsActiveFlag_HT2(SIGNAL_READER_DMA)) { LL_DMA_ClearFlag_HT2(SIGNAL_READER_DMA); instance->event.type = SignalReaderEventTypeHalfBufferFilled; gpio_buff_start = instance->gpio_buffer; bitstream_buff_start = instance->bitstream_buffer; if(instance->callback) { furi_assert(gpio_buff_start); furi_assert(bitstream_buff_start); for(size_t i = 0; i < instance->buffer_size * 4; i++) { if((i % 8) == 0) { bitstream_buff_start[i / 8] = 0; } uint8_t bit = 0; if(instance->polarity == SignalReaderPolarityNormal) { bit = (gpio_buff_start[i] & instance->pin->pin) == instance->pin->pin; } else { bit = (gpio_buff_start[i] & instance->pin->pin) == 0; } bitstream_buff_start[i / 8] |= bit << (i % 8); } instance->event_data.data = bitstream_buff_start; instance->event_data.len = instance->buffer_size / 2; instance->callback(instance->event, instance->context); } } if(LL_DMA_IsActiveFlag_TC2(SIGNAL_READER_DMA)) { LL_DMA_ClearFlag_TC2(SIGNAL_READER_DMA); instance->event.type = SignalReaderEventTypeFullBufferFilled; gpio_buff_start = &instance->gpio_buffer[instance->buffer_size * 4]; bitstream_buff_start = &instance->bitstream_buffer[instance->buffer_size / 2]; if(instance->callback) { furi_assert(gpio_buff_start); furi_assert(bitstream_buff_start); for(size_t i = 0; i < instance->buffer_size * 4; i++) { if((i % 8) == 0) { bitstream_buff_start[i / 8] = 0; } uint8_t bit = 0; if(instance->polarity == SignalReaderPolarityNormal) { bit = (gpio_buff_start[i] & instance->pin->pin) == instance->pin->pin; } else { bit = (gpio_buff_start[i] & instance->pin->pin) == 0; } bitstream_buff_start[i / 8] |= bit << (i % 8); } instance->event_data.data = bitstream_buff_start; instance->event_data.len = instance->buffer_size / 2; instance->callback(instance->event, instance->context); } } } void signal_reader_start(SignalReader* instance, SignalReaderCallback callback, void* context) { furi_check(instance); furi_check(callback); instance->callback = callback; instance->context = context; // EXTI delay compensation instance->tim_cnt_compensation = 9; instance->cnt_en = SIGNAL_READER_CAPTURE_TIM->CR1; instance->cnt_en |= TIM_CR1_CEN; furi_hal_bus_enable(FuriHalBusTIM16); // Capture timer config LL_TIM_SetPrescaler(SIGNAL_READER_CAPTURE_TIM, 0); LL_TIM_SetCounterMode(SIGNAL_READER_CAPTURE_TIM, LL_TIM_COUNTERMODE_UP); LL_TIM_SetAutoReload(SIGNAL_READER_CAPTURE_TIM, instance->tim_arr); LL_TIM_SetClockDivision(SIGNAL_READER_CAPTURE_TIM, LL_TIM_CLOCKDIVISION_DIV1); LL_TIM_DisableARRPreload(SIGNAL_READER_CAPTURE_TIM); LL_TIM_SetClockSource(SIGNAL_READER_CAPTURE_TIM, LL_TIM_CLOCKSOURCE_INTERNAL); // Configure TIM channel CC1 LL_TIM_OC_InitTypeDef TIM_OC_InitStruct = {}; TIM_OC_InitStruct.OCMode = LL_TIM_OCMODE_FROZEN; TIM_OC_InitStruct.OCState = LL_TIM_OCSTATE_DISABLE; TIM_OC_InitStruct.OCNState = LL_TIM_OCSTATE_DISABLE; TIM_OC_InitStruct.CompareValue = (instance->tim_arr / 2); TIM_OC_InitStruct.OCPolarity = LL_TIM_OCPOLARITY_HIGH; LL_TIM_OC_Init( SIGNAL_READER_CAPTURE_TIM, SIGNAL_READER_CAPTURE_TIM_CHANNEL, &TIM_OC_InitStruct); LL_TIM_OC_DisableFast(SIGNAL_READER_CAPTURE_TIM, SIGNAL_READER_CAPTURE_TIM_CHANNEL); LL_TIM_SetTriggerOutput(SIGNAL_READER_CAPTURE_TIM, LL_TIM_TRGO_RESET); LL_TIM_DisableMasterSlaveMode(SIGNAL_READER_CAPTURE_TIM); // Start LL_TIM_GenerateEvent_UPDATE(SIGNAL_READER_CAPTURE_TIM); /* We need the EXTI to be configured as interrupt generating line, but no ISR registered */ furi_hal_gpio_init( instance->pin, GpioModeInterruptRiseFall, instance->pull, GpioSpeedVeryHigh); furi_hal_gpio_enable_int_callback(instance->pin); /* Set DMAMUX request generation signal ID on specified DMAMUX channel */ LL_DMAMUX_SetRequestSignalID( DMAMUX1, LL_DMAMUX_REQ_GEN_0, GET_DMAMUX_EXTI_LINE(instance->pin->pin)); /* Set the polarity of the signal on which the DMA request is generated */ LL_DMAMUX_SetRequestGenPolarity(DMAMUX1, LL_DMAMUX_REQ_GEN_0, LL_DMAMUX_REQ_GEN_POL_RISING); /* Set the number of DMA requests that will be authorized after a generation event */ LL_DMAMUX_SetGenRequestNb(DMAMUX1, LL_DMAMUX_REQ_GEN_0, 1); // Configure DMA Sync LL_DMA_SetMemoryAddress( SIGNAL_READER_DMA_CNT_SYNC_DEF, (uint32_t)&instance->tim_cnt_compensation); LL_DMA_SetPeriphAddress( SIGNAL_READER_DMA_CNT_SYNC_DEF, (uint32_t) & (SIGNAL_READER_CAPTURE_TIM->CNT)); LL_DMA_ConfigTransfer( SIGNAL_READER_DMA_CNT_SYNC_DEF, LL_DMA_DIRECTION_MEMORY_TO_PERIPH | LL_DMA_MODE_CIRCULAR | LL_DMA_PERIPH_NOINCREMENT | LL_DMA_MEMORY_NOINCREMENT | LL_DMA_PDATAALIGN_HALFWORD | LL_DMA_MDATAALIGN_HALFWORD | LL_DMA_PRIORITY_VERYHIGH); LL_DMA_SetDataLength(SIGNAL_READER_DMA_CNT_SYNC_DEF, 1); LL_DMA_SetPeriphRequest(SIGNAL_READER_DMA_CNT_SYNC_DEF, LL_DMAMUX_REQ_GENERATOR0); // Configure DMA Sync LL_DMA_SetMemoryAddress(SIGNAL_READER_DMA_TRIGGER_DEF, (uint32_t)&instance->cnt_en); LL_DMA_SetPeriphAddress( SIGNAL_READER_DMA_TRIGGER_DEF, (uint32_t) & (SIGNAL_READER_CAPTURE_TIM->CR1)); LL_DMA_ConfigTransfer( SIGNAL_READER_DMA_TRIGGER_DEF, LL_DMA_DIRECTION_MEMORY_TO_PERIPH | LL_DMA_PERIPH_NOINCREMENT | LL_DMA_MEMORY_NOINCREMENT | LL_DMA_PDATAALIGN_HALFWORD | LL_DMA_MDATAALIGN_HALFWORD | LL_DMA_PRIORITY_VERYHIGH); LL_DMA_SetDataLength(SIGNAL_READER_DMA_TRIGGER_DEF, 1); LL_DMA_SetPeriphRequest(SIGNAL_READER_DMA_TRIGGER_DEF, LL_DMAMUX_REQ_GENERATOR0); // Configure DMA Rx pin LL_DMA_SetMemoryAddress(SIGNAL_READER_DMA_GPIO_DEF, (uint32_t)instance->gpio_buffer); LL_DMA_SetPeriphAddress(SIGNAL_READER_DMA_GPIO_DEF, (uint32_t) & (instance->pin->port->IDR)); LL_DMA_ConfigTransfer( SIGNAL_READER_DMA_GPIO_DEF, LL_DMA_DIRECTION_PERIPH_TO_MEMORY | LL_DMA_MODE_CIRCULAR | LL_DMA_PERIPH_NOINCREMENT | LL_DMA_MEMORY_INCREMENT | LL_DMA_PDATAALIGN_HALFWORD | LL_DMA_MDATAALIGN_HALFWORD | LL_DMA_PRIORITY_HIGH); LL_DMA_SetDataLength(SIGNAL_READER_DMA_GPIO_DEF, instance->buffer_size * 8); LL_DMA_SetPeriphRequest(SIGNAL_READER_DMA_GPIO_DEF, LL_DMAMUX_REQ_TIM16_CH1); // Configure DMA Channel CC1 LL_TIM_EnableDMAReq_CC1(SIGNAL_READER_CAPTURE_TIM); LL_TIM_CC_EnableChannel(SIGNAL_READER_CAPTURE_TIM, SIGNAL_READER_CAPTURE_TIM_CHANNEL); // Start DMA irq, higher priority than normal furi_hal_interrupt_set_isr_ex( SIGNAL_READER_DMA_GPIO_IRQ, FuriHalInterruptPriorityHighest, furi_hal_sw_digital_pin_dma_rx_isr, instance); // Start DMA Sync timer LL_DMA_EnableChannel(SIGNAL_READER_DMA_CNT_SYNC_DEF); // Start DMA Rx pin LL_DMA_EnableChannel(SIGNAL_READER_DMA_GPIO_DEF); // Strat timer LL_TIM_SetCounter(SIGNAL_READER_CAPTURE_TIM, 0); if(instance->trigger == SignalReaderTriggerNone) { LL_TIM_EnableCounter(SIGNAL_READER_CAPTURE_TIM); } else { LL_DMA_EnableChannel(SIGNAL_READER_DMA_TRIGGER_DEF); } LL_DMAMUX_EnableRequestGen(DMAMUX1, LL_DMAMUX_REQ_GEN_0); // Need to clear flags before enabling DMA !!!! if(LL_DMA_IsActiveFlag_TC2(SIGNAL_READER_DMA)) LL_DMA_ClearFlag_TC1(SIGNAL_READER_DMA); if(LL_DMA_IsActiveFlag_TE2(SIGNAL_READER_DMA)) LL_DMA_ClearFlag_TE1(SIGNAL_READER_DMA); LL_DMA_EnableIT_TC(SIGNAL_READER_DMA_GPIO_DEF); LL_DMA_EnableIT_HT(SIGNAL_READER_DMA_GPIO_DEF); } void signal_reader_stop(SignalReader* instance) { furi_check(instance); furi_hal_interrupt_set_isr(SIGNAL_READER_DMA_GPIO_IRQ, NULL, NULL); furi_hal_gpio_disable_int_callback(instance->pin); // Deinit DMA Rx pin LL_DMA_DeInit(SIGNAL_READER_DMA_GPIO_DEF); // Deinit DMA Sync timer LL_DMA_DeInit(SIGNAL_READER_DMA_CNT_SYNC_DEF); // Deinit DMA Trigger timer LL_DMA_DeInit(SIGNAL_READER_DMA_TRIGGER_DEF); furi_hal_bus_disable(FuriHalBusTIM16); }
12,448
C
.c
261
40.89272
99
0.670625
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,325
iso15693_parser.c
DarkFlippers_unleashed-firmware/lib/signal_reader/parsers/iso15693/iso15693_parser.c
#include "iso15693_parser.h" #include <toolbox/bit_buffer.h> #include <furi/furi.h> #define ISO15693_PARSER_SIGNAL_READER_BUFF_SIZE (2) #define ISO15693_PARSER_BITSTREAM_BUFF_SIZE (32) #define ISO15693_PARSER_BITRATE_F64MHZ (603U) #define TAG "Iso15693Parser" typedef enum { Iso15693ParserStateParseSoF, Iso15693ParserStateParseFrame, Iso15693ParserStateFail, } Iso15693ParserState; typedef enum { Iso15693ParserMode1OutOf4, Iso15693ParserMode1OutOf256, Iso15693ParserModeNum, } Iso15693ParserMode; struct Iso15693Parser { Iso15693ParserState state; Iso15693ParserMode mode; bool detect_mode; SignalReader* signal_reader; uint8_t bitstream_buff[ISO15693_PARSER_BITSTREAM_BUFF_SIZE]; size_t bitstream_idx; uint8_t last_byte; bool signal_detected; bool bit_offset_calculated; uint8_t bit_offset; size_t byte_idx; size_t bytes_to_process; uint8_t next_byte; uint16_t next_byte_part; bool zero_found; BitBuffer* parsed_frame; bool eof_received; bool frame_parsed; Iso15693ParserCallback callback; void* context; }; typedef enum { Iso15693ParserCommandProcessed, Iso15693ParserCommandWaitData, Iso15693ParserCommandFail, Iso15693ParserCommandSuccess, } Iso15693ParserCommand; typedef Iso15693ParserCommand (*Iso15693ParserStateHandler)(Iso15693Parser* instance); Iso15693Parser* iso15693_parser_alloc(const GpioPin* pin, size_t max_frame_size) { Iso15693Parser* instance = malloc(sizeof(Iso15693Parser)); instance->detect_mode = true; instance->parsed_frame = bit_buffer_alloc(max_frame_size); instance->signal_reader = signal_reader_alloc(pin, ISO15693_PARSER_SIGNAL_READER_BUFF_SIZE); signal_reader_set_sample_rate( instance->signal_reader, SignalReaderTimeUnit64Mhz, ISO15693_PARSER_BITRATE_F64MHZ); signal_reader_set_pull(instance->signal_reader, GpioPullDown); signal_reader_set_polarity(instance->signal_reader, SignalReaderPolarityNormal); signal_reader_set_trigger(instance->signal_reader, SignalReaderTriggerRisingFallingEdge); return instance; } void iso15693_parser_free(Iso15693Parser* instance) { furi_assert(instance); bit_buffer_free(instance->parsed_frame); signal_reader_free(instance->signal_reader); free(instance); } void iso15693_parser_reset(Iso15693Parser* instance) { furi_assert(instance); instance->state = Iso15693ParserStateParseSoF; if(instance->detect_mode) instance->mode = Iso15693ParserMode1OutOf4; memset(instance->bitstream_buff, 0x00, sizeof(instance->bitstream_buff)); instance->bitstream_idx = 0; instance->next_byte = 0; instance->next_byte_part = 0; instance->bit_offset = 0; instance->byte_idx = 0; instance->bytes_to_process = 0; instance->signal_detected = false; instance->bit_offset_calculated = false; instance->last_byte = 0x00; instance->zero_found = false; instance->eof_received = false; bit_buffer_reset(instance->parsed_frame); instance->frame_parsed = false; } static void signal_reader_callback(SignalReaderEvent event, void* context) { furi_assert(context); furi_assert(event.data->data); furi_assert(event.data->len == ISO15693_PARSER_SIGNAL_READER_BUFF_SIZE / 2); Iso15693Parser* instance = context; furi_assert(instance->callback); const uint8_t sof_1_out_of_4 = 0x21; const uint8_t sof_1_out_of_256 = 0x81; const uint8_t eof_single = 0x01; const uint8_t eof = 0x04; if(instance->state == Iso15693ParserStateParseSoF) { if(event.data->data[0] == sof_1_out_of_4) { if(instance->detect_mode) instance->mode = Iso15693ParserMode1OutOf4; instance->state = Iso15693ParserStateParseFrame; } else if(event.data->data[0] == sof_1_out_of_256) { if(instance->detect_mode) instance->mode = Iso15693ParserMode1OutOf256; instance->state = Iso15693ParserStateParseFrame; } else if(event.data->data[0] == eof_single) { instance->eof_received = true; instance->callback(Iso15693ParserEventDataReceived, instance->context); } else { instance->state = Iso15693ParserStateFail; instance->callback(Iso15693ParserEventDataReceived, instance->context); } } else { if(instance->mode == Iso15693ParserMode1OutOf4) { if(event.data->data[0] == eof) { instance->eof_received = true; instance->callback(Iso15693ParserEventDataReceived, instance->context); } else { instance->bitstream_buff[instance->bytes_to_process] = event.data->data[0]; instance->bytes_to_process++; if(instance->bytes_to_process == ISO15693_PARSER_BITSTREAM_BUFF_SIZE) { instance->callback(Iso15693ParserEventDataReceived, instance->context); } } } else { instance->bitstream_buff[instance->bytes_to_process] = event.data->data[0]; instance->bytes_to_process++; if(instance->bytes_to_process == ISO15693_PARSER_BITSTREAM_BUFF_SIZE) { instance->callback(Iso15693ParserEventDataReceived, instance->context); } } } } static void iso15693_parser_start_signal_reader(Iso15693Parser* instance) { iso15693_parser_reset(instance); signal_reader_start(instance->signal_reader, signal_reader_callback, instance); } void iso15693_parser_start( Iso15693Parser* instance, Iso15693ParserCallback callback, void* context) { furi_assert(instance); furi_assert(callback); instance->callback = callback; instance->context = context; iso15693_parser_start_signal_reader(instance); } void iso15693_parser_stop(Iso15693Parser* instance) { furi_assert(instance); signal_reader_stop(instance->signal_reader); } static Iso15693ParserCommand iso15693_parser_parse_1_out_of_4(Iso15693Parser* instance) { Iso15693ParserCommand command = Iso15693ParserCommandWaitData; const uint8_t bit_patterns_1_out_of_4[] = {0x02, 0x08, 0x20, 0x80}; for(size_t i = 0; i < instance->bytes_to_process; i++) { // Check next pattern size_t j = 0; for(j = 0; j < COUNT_OF(bit_patterns_1_out_of_4); j++) { if(instance->bitstream_buff[i] == bit_patterns_1_out_of_4[j]) { instance->next_byte |= j << (instance->next_byte_part * 2); instance->next_byte_part++; if(instance->next_byte_part == 4) { instance->next_byte_part = 0; bit_buffer_append_byte(instance->parsed_frame, instance->next_byte); instance->next_byte = 0; } break; } } if(j == COUNT_OF(bit_patterns_1_out_of_4)) { command = Iso15693ParserCommandFail; break; } } if(command != Iso15693ParserCommandFail) { if(instance->eof_received) { command = Iso15693ParserCommandSuccess; instance->frame_parsed = true; } } instance->bytes_to_process = 0; return command; } static Iso15693ParserCommand iso15693_parser_parse_1_out_of_256(Iso15693Parser* instance) { Iso15693ParserCommand command = Iso15693ParserCommandWaitData; const uint8_t eof = 0x04; for(size_t i = instance->byte_idx; i < instance->bytes_to_process; i++) { // Check EoF if(instance->next_byte_part == 0) { if(instance->bitstream_buff[i] == eof) { instance->frame_parsed = true; command = Iso15693ParserCommandSuccess; break; } } if(instance->zero_found) { if(instance->bitstream_buff[i] != 0x00) { command = Iso15693ParserCommandFail; break; } } else { if(instance->bitstream_buff[i] != 0x00) { for(size_t j = 0; j < 8; j++) { if(FURI_BIT(instance->bitstream_buff[i], j) == 1) { bit_buffer_append_byte( instance->parsed_frame, instance->next_byte_part * 4 + j / 2); } } } } instance->next_byte_part = (instance->next_byte_part + 1) % 64; } instance->bytes_to_process = 0; instance->byte_idx = 0; return command; } static const Iso15693ParserStateHandler iso15693_parser_state_handlers[Iso15693ParserModeNum] = { [Iso15693ParserMode1OutOf4] = iso15693_parser_parse_1_out_of_4, [Iso15693ParserMode1OutOf256] = iso15693_parser_parse_1_out_of_256, }; bool iso15693_parser_run(Iso15693Parser* instance) { if(instance->state == Iso15693ParserStateFail) { iso15693_parser_stop(instance); iso15693_parser_start_signal_reader(instance); } else if((instance->state == Iso15693ParserStateParseSoF) && (instance->eof_received)) { instance->frame_parsed = true; } else if(instance->bytes_to_process) { Iso15693ParserCommand command = Iso15693ParserCommandProcessed; while(command == Iso15693ParserCommandProcessed) { command = iso15693_parser_state_handlers[instance->mode](instance); } if(command == Iso15693ParserCommandFail) { iso15693_parser_stop(instance); iso15693_parser_start_signal_reader(instance); FURI_LOG_D(TAG, "Frame parse failed"); } } return instance->frame_parsed; } size_t iso15693_parser_get_data_size_bytes(Iso15693Parser* instance) { furi_assert(instance); return bit_buffer_get_size_bytes(instance->parsed_frame); } void iso15693_parser_get_data( Iso15693Parser* instance, uint8_t* buff, size_t buff_size, size_t* data_bits) { furi_assert(instance); furi_assert(buff); furi_assert(data_bits); bit_buffer_write_bytes(instance->parsed_frame, buff, buff_size); *data_bits = bit_buffer_get_size(instance->parsed_frame); } void iso15693_parser_detect_mode(Iso15693Parser* instance) { furi_assert(instance); instance->detect_mode = true; } void iso15693_parser_force_1outof4(Iso15693Parser* instance) { furi_assert(instance); instance->detect_mode = false; instance->mode = Iso15693ParserMode1OutOf4; } void iso15693_parser_force_1outof256(Iso15693Parser* instance) { furi_assert(instance); instance->detect_mode = false; instance->mode = Iso15693ParserMode1OutOf256; }
10,618
C
.c
263
33.053232
97
0.669515
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,326
flipper_format.c
DarkFlippers_unleashed-firmware/lib/flipper_format/flipper_format.c
#include <core/check.h> #include <toolbox/stream/stream.h> #include <toolbox/stream/string_stream.h> #include <toolbox/stream/file_stream.h> #include <toolbox/stream/buffered_file_stream.h> #include "flipper_format.h" #include "flipper_format_i.h" #include "flipper_format_stream.h" #include "flipper_format_stream_i.h" /********************************** Private **********************************/ struct FlipperFormat { Stream* stream; bool strict_mode; }; static const char* const flipper_format_filetype_key = "Filetype"; static const char* const flipper_format_version_key = "Version"; Stream* flipper_format_get_raw_stream(FlipperFormat* flipper_format) { return flipper_format->stream; } /********************************** Public **********************************/ FlipperFormat* flipper_format_string_alloc(void) { FlipperFormat* flipper_format = malloc(sizeof(FlipperFormat)); flipper_format->stream = string_stream_alloc(); flipper_format->strict_mode = false; return flipper_format; } FlipperFormat* flipper_format_file_alloc(Storage* storage) { FlipperFormat* flipper_format = malloc(sizeof(FlipperFormat)); flipper_format->stream = file_stream_alloc(storage); flipper_format->strict_mode = false; return flipper_format; } FlipperFormat* flipper_format_buffered_file_alloc(Storage* storage) { FlipperFormat* flipper_format = malloc(sizeof(FlipperFormat)); flipper_format->stream = buffered_file_stream_alloc(storage); flipper_format->strict_mode = false; return flipper_format; } bool flipper_format_file_open_existing(FlipperFormat* flipper_format, const char* path) { furi_check(flipper_format); return file_stream_open(flipper_format->stream, path, FSAM_READ_WRITE, FSOM_OPEN_EXISTING); } bool flipper_format_buffered_file_open_existing(FlipperFormat* flipper_format, const char* path) { furi_check(flipper_format); return buffered_file_stream_open( flipper_format->stream, path, FSAM_READ_WRITE, FSOM_OPEN_EXISTING); } bool flipper_format_file_open_append(FlipperFormat* flipper_format, const char* path) { furi_check(flipper_format); bool result = file_stream_open(flipper_format->stream, path, FSAM_READ_WRITE, FSOM_OPEN_APPEND); // Add EOL if it is not there if(stream_size(flipper_format->stream) >= 1) { do { char last_char; result = false; if(!stream_seek(flipper_format->stream, -1, StreamOffsetFromEnd)) break; uint16_t bytes_were_read = stream_read(flipper_format->stream, (uint8_t*)&last_char, 1); if(bytes_were_read != 1) break; if(last_char != flipper_format_eoln) { if(!flipper_format_stream_write_eol(flipper_format->stream)) break; } result = true; } while(false); } else { stream_seek(flipper_format->stream, 0, StreamOffsetFromEnd); } return result; } bool flipper_format_file_open_always(FlipperFormat* flipper_format, const char* path) { furi_check(flipper_format); return file_stream_open(flipper_format->stream, path, FSAM_READ_WRITE, FSOM_CREATE_ALWAYS); } bool flipper_format_buffered_file_open_always(FlipperFormat* flipper_format, const char* path) { furi_check(flipper_format); return buffered_file_stream_open( flipper_format->stream, path, FSAM_READ_WRITE, FSOM_CREATE_ALWAYS); } bool flipper_format_file_open_new(FlipperFormat* flipper_format, const char* path) { furi_check(flipper_format); return file_stream_open(flipper_format->stream, path, FSAM_READ_WRITE, FSOM_CREATE_NEW); } bool flipper_format_file_close(FlipperFormat* flipper_format) { furi_check(flipper_format); return file_stream_close(flipper_format->stream); } bool flipper_format_buffered_file_close(FlipperFormat* flipper_format) { furi_check(flipper_format); return buffered_file_stream_close(flipper_format->stream); } void flipper_format_free(FlipperFormat* flipper_format) { furi_check(flipper_format); stream_free(flipper_format->stream); free(flipper_format); } void flipper_format_set_strict_mode(FlipperFormat* flipper_format, bool strict_mode) { flipper_format->strict_mode = strict_mode; } bool flipper_format_rewind(FlipperFormat* flipper_format) { furi_check(flipper_format); return stream_rewind(flipper_format->stream); } bool flipper_format_seek_to_end(FlipperFormat* flipper_format) { furi_check(flipper_format); return stream_seek(flipper_format->stream, 0, StreamOffsetFromEnd); } bool flipper_format_key_exist(FlipperFormat* flipper_format, const char* key) { size_t pos = stream_tell(flipper_format->stream); stream_seek(flipper_format->stream, 0, StreamOffsetFromStart); bool result = flipper_format_stream_seek_to_key(flipper_format->stream, key, false); stream_seek(flipper_format->stream, pos, StreamOffsetFromStart); return result; } bool flipper_format_read_header( FlipperFormat* flipper_format, FuriString* filetype, uint32_t* version) { furi_check(flipper_format); return flipper_format_read_string(flipper_format, flipper_format_filetype_key, filetype) && flipper_format_read_uint32(flipper_format, flipper_format_version_key, version, 1); } bool flipper_format_write_header( FlipperFormat* flipper_format, FuriString* filetype, const uint32_t version) { furi_check(flipper_format); return flipper_format_write_header_cstr( flipper_format, furi_string_get_cstr(filetype), version); } bool flipper_format_write_header_cstr( FlipperFormat* flipper_format, const char* filetype, const uint32_t version) { furi_check(flipper_format); return flipper_format_write_string_cstr( flipper_format, flipper_format_filetype_key, filetype) && flipper_format_write_uint32(flipper_format, flipper_format_version_key, &version, 1); } bool flipper_format_get_value_count( FlipperFormat* flipper_format, const char* key, uint32_t* count) { furi_check(flipper_format); return flipper_format_stream_get_value_count( flipper_format->stream, key, count, flipper_format->strict_mode); } bool flipper_format_read_string(FlipperFormat* flipper_format, const char* key, FuriString* data) { furi_check(flipper_format); return flipper_format_stream_read_value_line( flipper_format->stream, key, FlipperStreamValueStr, data, 1, flipper_format->strict_mode); } bool flipper_format_write_string(FlipperFormat* flipper_format, const char* key, FuriString* data) { furi_check(flipper_format); FlipperStreamWriteData write_data = { .key = key, .type = FlipperStreamValueStr, .data = furi_string_get_cstr(data), .data_size = 1, }; bool result = flipper_format_stream_write_value_line(flipper_format->stream, &write_data); return result; } bool flipper_format_write_string_cstr( FlipperFormat* flipper_format, const char* key, const char* data) { furi_check(flipper_format); FlipperStreamWriteData write_data = { .key = key, .type = FlipperStreamValueStr, .data = data, .data_size = 1, }; bool result = flipper_format_stream_write_value_line(flipper_format->stream, &write_data); return result; } bool flipper_format_read_hex_uint64( FlipperFormat* flipper_format, const char* key, uint64_t* data, const uint16_t data_size) { furi_check(flipper_format); return flipper_format_stream_read_value_line( flipper_format->stream, key, FlipperStreamValueHexUint64, data, data_size, flipper_format->strict_mode); } bool flipper_format_write_hex_uint64( FlipperFormat* flipper_format, const char* key, const uint64_t* data, const uint16_t data_size) { furi_check(flipper_format); FlipperStreamWriteData write_data = { .key = key, .type = FlipperStreamValueHexUint64, .data = data, .data_size = data_size, }; bool result = flipper_format_stream_write_value_line(flipper_format->stream, &write_data); return result; } bool flipper_format_read_uint32( FlipperFormat* flipper_format, const char* key, uint32_t* data, const uint16_t data_size) { furi_check(flipper_format); return flipper_format_stream_read_value_line( flipper_format->stream, key, FlipperStreamValueUint32, data, data_size, flipper_format->strict_mode); } bool flipper_format_write_uint32( FlipperFormat* flipper_format, const char* key, const uint32_t* data, const uint16_t data_size) { furi_check(flipper_format); FlipperStreamWriteData write_data = { .key = key, .type = FlipperStreamValueUint32, .data = data, .data_size = data_size, }; bool result = flipper_format_stream_write_value_line(flipper_format->stream, &write_data); return result; } bool flipper_format_read_int32( FlipperFormat* flipper_format, const char* key, int32_t* data, const uint16_t data_size) { return flipper_format_stream_read_value_line( flipper_format->stream, key, FlipperStreamValueInt32, data, data_size, flipper_format->strict_mode); } bool flipper_format_write_int32( FlipperFormat* flipper_format, const char* key, const int32_t* data, const uint16_t data_size) { furi_check(flipper_format); FlipperStreamWriteData write_data = { .key = key, .type = FlipperStreamValueInt32, .data = data, .data_size = data_size, }; bool result = flipper_format_stream_write_value_line(flipper_format->stream, &write_data); return result; } bool flipper_format_read_bool( FlipperFormat* flipper_format, const char* key, bool* data, const uint16_t data_size) { return flipper_format_stream_read_value_line( flipper_format->stream, key, FlipperStreamValueBool, data, data_size, flipper_format->strict_mode); } bool flipper_format_write_bool( FlipperFormat* flipper_format, const char* key, const bool* data, const uint16_t data_size) { furi_check(flipper_format); FlipperStreamWriteData write_data = { .key = key, .type = FlipperStreamValueBool, .data = data, .data_size = data_size, }; bool result = flipper_format_stream_write_value_line(flipper_format->stream, &write_data); return result; } bool flipper_format_read_float( FlipperFormat* flipper_format, const char* key, float* data, const uint16_t data_size) { return flipper_format_stream_read_value_line( flipper_format->stream, key, FlipperStreamValueFloat, data, data_size, flipper_format->strict_mode); } bool flipper_format_write_float( FlipperFormat* flipper_format, const char* key, const float* data, const uint16_t data_size) { furi_check(flipper_format); FlipperStreamWriteData write_data = { .key = key, .type = FlipperStreamValueFloat, .data = data, .data_size = data_size, }; bool result = flipper_format_stream_write_value_line(flipper_format->stream, &write_data); return result; } bool flipper_format_read_hex( FlipperFormat* flipper_format, const char* key, uint8_t* data, const uint16_t data_size) { return flipper_format_stream_read_value_line( flipper_format->stream, key, FlipperStreamValueHex, data, data_size, flipper_format->strict_mode); } bool flipper_format_write_hex( FlipperFormat* flipper_format, const char* key, const uint8_t* data, const uint16_t data_size) { furi_check(flipper_format); FlipperStreamWriteData write_data = { .key = key, .type = FlipperStreamValueHex, .data = data, .data_size = data_size, }; bool result = flipper_format_stream_write_value_line(flipper_format->stream, &write_data); return result; } bool flipper_format_write_comment(FlipperFormat* flipper_format, FuriString* data) { furi_check(flipper_format); return flipper_format_write_comment_cstr(flipper_format, furi_string_get_cstr(data)); } bool flipper_format_write_comment_cstr(FlipperFormat* flipper_format, const char* data) { furi_check(flipper_format); return flipper_format_stream_write_comment_cstr(flipper_format->stream, data); } bool flipper_format_delete_key(FlipperFormat* flipper_format, const char* key) { furi_check(flipper_format); FlipperStreamWriteData write_data = { .key = key, .type = FlipperStreamValueIgnore, .data = NULL, .data_size = 0, }; bool result = flipper_format_stream_delete_key_and_write( flipper_format->stream, &write_data, flipper_format->strict_mode); return result; } bool flipper_format_update_string(FlipperFormat* flipper_format, const char* key, FuriString* data) { furi_check(flipper_format); FlipperStreamWriteData write_data = { .key = key, .type = FlipperStreamValueStr, .data = furi_string_get_cstr(data), .data_size = 1, }; bool result = flipper_format_stream_delete_key_and_write( flipper_format->stream, &write_data, flipper_format->strict_mode); return result; } bool flipper_format_update_string_cstr( FlipperFormat* flipper_format, const char* key, const char* data) { furi_check(flipper_format); FlipperStreamWriteData write_data = { .key = key, .type = FlipperStreamValueStr, .data = data, .data_size = 1, }; bool result = flipper_format_stream_delete_key_and_write( flipper_format->stream, &write_data, flipper_format->strict_mode); return result; } bool flipper_format_update_uint32( FlipperFormat* flipper_format, const char* key, const uint32_t* data, const uint16_t data_size) { furi_check(flipper_format); FlipperStreamWriteData write_data = { .key = key, .type = FlipperStreamValueUint32, .data = data, .data_size = data_size, }; bool result = flipper_format_stream_delete_key_and_write( flipper_format->stream, &write_data, flipper_format->strict_mode); return result; } bool flipper_format_update_int32( FlipperFormat* flipper_format, const char* key, const int32_t* data, const uint16_t data_size) { FlipperStreamWriteData write_data = { .key = key, .type = FlipperStreamValueInt32, .data = data, .data_size = data_size, }; bool result = flipper_format_stream_delete_key_and_write( flipper_format->stream, &write_data, flipper_format->strict_mode); return result; } bool flipper_format_update_bool( FlipperFormat* flipper_format, const char* key, const bool* data, const uint16_t data_size) { FlipperStreamWriteData write_data = { .key = key, .type = FlipperStreamValueBool, .data = data, .data_size = data_size, }; bool result = flipper_format_stream_delete_key_and_write( flipper_format->stream, &write_data, flipper_format->strict_mode); return result; } bool flipper_format_update_float( FlipperFormat* flipper_format, const char* key, const float* data, const uint16_t data_size) { FlipperStreamWriteData write_data = { .key = key, .type = FlipperStreamValueFloat, .data = data, .data_size = data_size, }; bool result = flipper_format_stream_delete_key_and_write( flipper_format->stream, &write_data, flipper_format->strict_mode); return result; } bool flipper_format_update_hex( FlipperFormat* flipper_format, const char* key, const uint8_t* data, const uint16_t data_size) { FlipperStreamWriteData write_data = { .key = key, .type = FlipperStreamValueHex, .data = data, .data_size = data_size, }; bool result = flipper_format_stream_delete_key_and_write( flipper_format->stream, &write_data, flipper_format->strict_mode); return result; } bool flipper_format_insert_or_update_string( FlipperFormat* flipper_format, const char* key, FuriString* data) { bool result = false; if(!flipper_format_key_exist(flipper_format, key)) { flipper_format_seek_to_end(flipper_format); result = flipper_format_write_string(flipper_format, key, data); } else { result = flipper_format_update_string(flipper_format, key, data); } return result; } bool flipper_format_insert_or_update_string_cstr( FlipperFormat* flipper_format, const char* key, const char* data) { bool result = false; if(!flipper_format_key_exist(flipper_format, key)) { flipper_format_seek_to_end(flipper_format); result = flipper_format_write_string_cstr(flipper_format, key, data); } else { result = flipper_format_update_string_cstr(flipper_format, key, data); } return result; } bool flipper_format_insert_or_update_uint32( FlipperFormat* flipper_format, const char* key, const uint32_t* data, const uint16_t data_size) { bool result = false; if(!flipper_format_key_exist(flipper_format, key)) { flipper_format_seek_to_end(flipper_format); result = flipper_format_write_uint32(flipper_format, key, data, data_size); } else { result = flipper_format_update_uint32(flipper_format, key, data, data_size); } return result; } bool flipper_format_insert_or_update_int32( FlipperFormat* flipper_format, const char* key, const int32_t* data, const uint16_t data_size) { bool result = false; if(!flipper_format_key_exist(flipper_format, key)) { flipper_format_seek_to_end(flipper_format); result = flipper_format_write_int32(flipper_format, key, data, data_size); } else { result = flipper_format_update_int32(flipper_format, key, data, data_size); } return result; } bool flipper_format_insert_or_update_bool( FlipperFormat* flipper_format, const char* key, const bool* data, const uint16_t data_size) { bool result = false; if(!flipper_format_key_exist(flipper_format, key)) { flipper_format_seek_to_end(flipper_format); result = flipper_format_write_bool(flipper_format, key, data, data_size); } else { result = flipper_format_update_bool(flipper_format, key, data, data_size); } return result; } bool flipper_format_insert_or_update_float( FlipperFormat* flipper_format, const char* key, const float* data, const uint16_t data_size) { bool result = false; if(!flipper_format_key_exist(flipper_format, key)) { flipper_format_seek_to_end(flipper_format); result = flipper_format_write_float(flipper_format, key, data, data_size); } else { result = flipper_format_update_float(flipper_format, key, data, data_size); } return result; } bool flipper_format_insert_or_update_hex( FlipperFormat* flipper_format, const char* key, const uint8_t* data, const uint16_t data_size) { bool result = false; if(!flipper_format_key_exist(flipper_format, key)) { flipper_format_seek_to_end(flipper_format); result = flipper_format_write_hex(flipper_format, key, data, data_size); } else { result = flipper_format_update_hex(flipper_format, key, data, data_size); } return result; }
19,809
C
.c
566
29.540636
101
0.683799
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,328
flipper_format_stream.c
DarkFlippers_unleashed-firmware/lib/flipper_format/flipper_format_stream.c
#include <inttypes.h> #include <toolbox/hex.h> #include <toolbox/strint.h> #include <core/check.h> #include "flipper_format_stream.h" #include "flipper_format_stream_i.h" static inline bool flipper_format_stream_is_space(char c) { return c == ' ' || c == '\t' || c == flipper_format_eolr; } static bool flipper_format_stream_write(Stream* stream, const void* data, size_t data_size) { size_t bytes_written = stream_write(stream, data, data_size); return bytes_written == data_size; } static bool flipper_format_stream_write_key(Stream* stream, const char* key) { bool result = false; do { if(!flipper_format_stream_write(stream, key, strlen(key))) break; if(!flipper_format_stream_write(stream, &flipper_format_delimiter, 1)) break; if(!flipper_format_stream_write(stream, " ", 1)) break; result = true; } while(false); return result; } bool flipper_format_stream_write_eol(Stream* stream) { return flipper_format_stream_write(stream, &flipper_format_eoln, 1); } static bool flipper_format_stream_read_valid_key(Stream* stream, FuriString* key) { furi_string_reset(key); const size_t buffer_size = 32; uint8_t buffer[buffer_size]; bool found = false; bool error = false; bool accumulate = true; bool new_line = true; while(true) { size_t was_read = stream_read(stream, buffer, buffer_size); if(was_read == 0) break; for(size_t i = 0; i < was_read; i++) { uint8_t data = buffer[i]; if(data == flipper_format_eoln) { // EOL found, clean data, start accumulating data and set the new_line flag furi_string_reset(key); accumulate = true; new_line = true; } else if(data == flipper_format_eolr) { // ignore } else if(data == flipper_format_comment && new_line) { // if there is a comment character and we are at the beginning of a new line // do not accumulate comment data and reset the new_line flag accumulate = false; new_line = false; } else if(data == flipper_format_delimiter) { if(new_line) { // we are on a "new line" and found the delimiter // this can only be if we have previously found some kind of key, so // clear the data, set the flag that we no longer want to accumulate data // and reset the new_line flag furi_string_reset(key); accumulate = false; new_line = false; } else { // parse the delimiter only if we are accumulating data if(accumulate) { // we found the delimiter, move the rw pointer to the delimiter location // and signal that we have found something if(!stream_seek(stream, i - was_read, StreamOffsetFromCurrent)) { error = true; break; } found = true; break; } } } else { // just new symbol, reset the new_line flag new_line = false; if(accumulate) { // and accumulate data if we want furi_string_push_back(key, data); } } } if(found || error) break; } return found; } bool flipper_format_stream_seek_to_key(Stream* stream, const char* key, bool strict_mode) { bool found = false; FuriString* read_key; read_key = furi_string_alloc(); while(!stream_eof(stream)) { if(flipper_format_stream_read_valid_key(stream, read_key)) { if(furi_string_cmp_str(read_key, key) == 0) { if(!stream_seek(stream, 2, StreamOffsetFromCurrent)) break; found = true; break; } else if(strict_mode) { found = false; break; } } } furi_string_free(read_key); return found; } static bool flipper_format_stream_read_value(Stream* stream, FuriString* value, bool* last) { enum { LeadingSpace, ReadValue, TrailingSpace } state = LeadingSpace; const size_t buffer_size = 32; uint8_t buffer[buffer_size]; bool result = false; bool error = false; furi_string_reset(value); while(true) { size_t was_read = stream_read(stream, buffer, buffer_size); if(was_read == 0) { if(state != LeadingSpace && stream_eof(stream)) { result = true; *last = true; } else { error = true; } } for(uint16_t i = 0; i < was_read; i++) { const uint8_t data = buffer[i]; if(state == LeadingSpace) { if(flipper_format_stream_is_space(data)) { continue; } else if(data == flipper_format_eoln) { stream_seek(stream, i - was_read, StreamOffsetFromCurrent); error = true; break; } else { state = ReadValue; furi_string_push_back(value, data); } } else if(state == ReadValue) { if(flipper_format_stream_is_space(data)) { state = TrailingSpace; } else if(data == flipper_format_eoln) { if(!stream_seek(stream, i - was_read, StreamOffsetFromCurrent)) { error = true; } else { result = true; *last = true; } break; } else { furi_string_push_back(value, data); } } else if(state == TrailingSpace) { if(flipper_format_stream_is_space(data)) { continue; } else if(!stream_seek(stream, i - was_read, StreamOffsetFromCurrent)) { error = true; } else { *last = (data == flipper_format_eoln); result = true; } break; } } if(error || result) break; } return result; } static bool flipper_format_stream_read_line(Stream* stream, FuriString* str_result) { furi_string_reset(str_result); const size_t buffer_size = 32; uint8_t buffer[buffer_size]; do { size_t was_read = stream_read(stream, buffer, buffer_size); if(was_read == 0) break; bool result = false; bool error = false; for(size_t i = 0; i < was_read; i++) { uint8_t data = buffer[i]; if(data == flipper_format_eoln) { if(!stream_seek(stream, i - was_read, StreamOffsetFromCurrent)) { error = true; break; } result = true; break; } else if(data == flipper_format_eolr) { // Ignore } else { furi_string_push_back(str_result, data); } } if(result || error) { break; } } while(true); return furi_string_size(str_result) != 0; } static bool flipper_format_stream_seek_to_next_line(Stream* stream) { const size_t buffer_size = 32; uint8_t buffer[buffer_size]; bool result = false; bool error = false; do { size_t was_read = stream_read(stream, buffer, buffer_size); if(was_read == 0) { if(stream_eof(stream)) { result = true; break; } } for(size_t i = 0; i < was_read; i++) { if(buffer[i] == flipper_format_eoln) { if(!stream_seek(stream, i - was_read, StreamOffsetFromCurrent)) { error = true; break; } result = true; break; } } if(result || error) { break; } } while(true); return result; } bool flipper_format_stream_write_value_line(Stream* stream, FlipperStreamWriteData* write_data) { bool result = false; if(write_data->type == FlipperStreamValueIgnore) { result = true; } else { FuriString* value; value = furi_string_alloc(); do { if(!flipper_format_stream_write_key(stream, write_data->key)) break; if(write_data->type == FlipperStreamValueStr) write_data->data_size = 1; bool cycle_error = false; for(uint16_t i = 0; i < write_data->data_size; i++) { switch(write_data->type) { case FlipperStreamValueStr: { const char* data = write_data->data; furi_string_printf(value, "%s", data); }; break; case FlipperStreamValueHex: { const uint8_t* data = write_data->data; furi_string_printf(value, "%02X", data[i]); }; break; #ifndef FLIPPER_STREAM_LITE case FlipperStreamValueFloat: { const float* data = write_data->data; furi_string_printf(value, "%f", (double)data[i]); }; break; #endif case FlipperStreamValueInt32: { const int32_t* data = write_data->data; furi_string_printf(value, "%" PRIi32, data[i]); }; break; case FlipperStreamValueUint32: { const uint32_t* data = write_data->data; furi_string_printf(value, "%" PRIu32, data[i]); }; break; case FlipperStreamValueHexUint64: { const uint64_t* data = write_data->data; furi_string_printf( value, "%08lX%08lX", (uint32_t)(data[i] >> 32), (uint32_t)data[i]); }; break; case FlipperStreamValueBool: { const bool* data = write_data->data; furi_string_printf(value, data[i] ? "true" : "false"); }; break; default: furi_crash("Unknown FF type"); } if(((size_t)i + 1) < write_data->data_size) { furi_string_cat(value, " "); } if(!flipper_format_stream_write( stream, furi_string_get_cstr(value), furi_string_size(value))) { cycle_error = true; break; } } if(cycle_error) break; if(!flipper_format_stream_write_eol(stream)) break; result = true; } while(false); furi_string_free(value); } return result; } bool flipper_format_stream_read_value_line( Stream* stream, const char* key, FlipperStreamValue type, void* _data, size_t data_size, bool strict_mode) { bool result = false; do { if(!flipper_format_stream_seek_to_key(stream, key, strict_mode)) break; if(type == FlipperStreamValueStr) { FuriString* data = (FuriString*)_data; if(flipper_format_stream_read_line(stream, data)) { result = true; break; } } else { result = true; FuriString* value; value = furi_string_alloc(); for(size_t i = 0; i < data_size; i++) { bool last = false; result = flipper_format_stream_read_value(stream, value, &last); if(result) { int scan_values = 0; switch(type) { case FlipperStreamValueHex: { uint8_t* data = _data; if(furi_string_size(value) >= 2) { // sscanf "%02X" does not work here if(hex_char_to_uint8( furi_string_get_char(value, 0), furi_string_get_char(value, 1), &data[i])) { scan_values = 1; } } }; break; #ifndef FLIPPER_STREAM_LITE case FlipperStreamValueFloat: { float* data = _data; // newlib-nano does not have sscanf for floats // scan_values = sscanf(furi_string_get_cstr(value), "%f", &data[i]); char* end_char; data[i] = strtof(furi_string_get_cstr(value), &end_char); if(*end_char == 0) { // most likely ok scan_values = 1; } }; break; #endif case FlipperStreamValueInt32: { int32_t* data = _data; if(strint_to_int32(furi_string_get_cstr(value), NULL, &data[i], 10) == StrintParseNoError) { scan_values = 1; } }; break; case FlipperStreamValueUint32: { uint32_t* data = _data; if(strint_to_uint32(furi_string_get_cstr(value), NULL, &data[i], 10) == StrintParseNoError) { scan_values = 1; } }; break; case FlipperStreamValueHexUint64: { uint64_t* data = _data; if(furi_string_size(value) >= 16) { if(hex_chars_to_uint64(furi_string_get_cstr(value), &data[i])) { scan_values = 1; } } }; break; case FlipperStreamValueBool: { bool* data = _data; data[i] = !furi_string_cmpi(value, "true"); scan_values = 1; }; break; default: furi_crash("Unknown FF type"); } if(scan_values != 1) { result = false; break; } } else { break; } if(last && ((i + 1) != data_size)) { result = false; break; } } furi_string_free(value); } } while(false); return result; } bool flipper_format_stream_get_value_count( Stream* stream, const char* key, uint32_t* count, bool strict_mode) { bool result = false; bool last = false; FuriString* value; value = furi_string_alloc(); uint32_t position = stream_tell(stream); do { if(!flipper_format_stream_seek_to_key(stream, key, strict_mode)) break; *count = 0; result = true; while(true) { if(!flipper_format_stream_read_value(stream, value, &last)) { result = false; break; } *count = *count + 1; if(last) break; } } while(false); if(!stream_seek(stream, position, StreamOffsetFromStart)) { result = false; } furi_string_free(value); return result; } bool flipper_format_stream_delete_key_and_write( Stream* stream, FlipperStreamWriteData* write_data, bool strict_mode) { bool result = false; do { size_t size = stream_size(stream); if(size == 0) break; if(!stream_rewind(stream)) break; // find key if(!flipper_format_stream_seek_to_key(stream, write_data->key, strict_mode)) break; // get key start position size_t start_position = stream_tell(stream) - strlen(write_data->key); if(start_position >= 2) { start_position -= 2; } else { // something wrong break; } // get value end position if(!flipper_format_stream_seek_to_next_line(stream)) break; size_t end_position = stream_tell(stream); // newline symbol if(end_position < size) { end_position += 1; } if(!stream_seek(stream, start_position, StreamOffsetFromStart)) break; if(!stream_delete_and_insert( stream, end_position - start_position, (StreamWriteCB)flipper_format_stream_write_value_line, write_data)) break; result = true; } while(false); return result; } bool flipper_format_stream_write_comment_cstr(Stream* stream, const char* data) { bool result = false; do { const char comment_buffer[2] = {flipper_format_comment, ' '}; result = flipper_format_stream_write(stream, comment_buffer, sizeof(comment_buffer)); if(!result) break; result = flipper_format_stream_write(stream, data, strlen(data)); if(!result) break; result = flipper_format_stream_write_eol(stream); } while(false); return result; }
17,830
C
.c
468
24.549145
97
0.48649
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,337
music_worker.h
DarkFlippers_unleashed-firmware/lib/music_worker/music_worker.h
#pragma once #include <stdbool.h> #include <stdint.h> typedef void (*MusicWorkerCallback)( uint8_t semitone, uint8_t dots, uint8_t duration, float position, void* context); typedef struct MusicWorker MusicWorker; MusicWorker* music_worker_alloc(void); void music_worker_clear(MusicWorker* instance); void music_worker_free(MusicWorker* instance); bool music_worker_load(MusicWorker* instance, const char* file_path); bool music_worker_load_fmf_from_file(MusicWorker* instance, const char* file_path); bool music_worker_load_rtttl_from_file(MusicWorker* instance, const char* file_path); bool music_worker_load_rtttl_from_string(MusicWorker* instance, const char* string); void music_worker_set_callback(MusicWorker* instance, MusicWorkerCallback callback, void* context); void music_worker_set_volume(MusicWorker* instance, float volume); void music_worker_start(MusicWorker* instance); void music_worker_stop(MusicWorker* instance); bool music_worker_is_playing(MusicWorker* instance);
1,022
C
.c
22
43.863636
99
0.8
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,338
music_worker.c
DarkFlippers_unleashed-firmware/lib/music_worker/music_worker.c
#include "music_worker.h" #include <furi_hal.h> #include <furi.h> #include <storage/storage.h> #include <lib/flipper_format/flipper_format.h> #include <math.h> #include <m-array.h> #define TAG "MusicWorker" #define MUSIC_PLAYER_FILETYPE "Flipper Music Format" #define MUSIC_PLAYER_VERSION 0 #define SEMITONE_PAUSE 0xFF #define NOTE_C4 261.63f #define NOTE_C4_SEMITONE (4.0f * 12.0f) #define TWO_POW_TWELTH_ROOT 1.059463094359f typedef struct { uint8_t semitone; uint8_t duration; uint8_t dots; } NoteBlock; ARRAY_DEF(NoteBlockArray, NoteBlock, M_POD_OPLIST); struct MusicWorker { FuriThread* thread; bool should_work; MusicWorkerCallback callback; void* callback_context; float volume; uint32_t bpm; uint32_t duration; uint32_t octave; NoteBlockArray_t notes; }; static int32_t music_worker_thread_callback(void* context) { furi_assert(context); MusicWorker* instance = context; NoteBlockArray_it_t it; NoteBlockArray_it(it, instance->notes); if(furi_hal_speaker_acquire(1000)) { while(instance->should_work) { if(NoteBlockArray_end_p(it)) { NoteBlockArray_it(it, instance->notes); furi_delay_ms(10); } else { NoteBlock* note_block = NoteBlockArray_ref(it); float note_from_a4 = (float)note_block->semitone - NOTE_C4_SEMITONE; float frequency = NOTE_C4 * powf(TWO_POW_TWELTH_ROOT, note_from_a4); float duration = 60.0 * furi_kernel_get_tick_frequency() * 4 / instance->bpm / note_block->duration; uint32_t dots = note_block->dots; while(dots > 0) { duration += duration / 2; dots--; } uint32_t next_tick = furi_get_tick() + duration; float volume = instance->volume; if(instance->callback) { instance->callback( note_block->semitone, note_block->dots, note_block->duration, 0.0, instance->callback_context); } furi_hal_speaker_stop(); furi_hal_speaker_start(frequency, volume); while(instance->should_work && furi_get_tick() < next_tick) { volume *= 0.9945679; furi_hal_speaker_set_volume(volume); furi_delay_ms(2); } NoteBlockArray_next(it); } } furi_hal_speaker_stop(); furi_hal_speaker_release(); } else { FURI_LOG_E(TAG, "Speaker system is busy with another process."); } return 0; } MusicWorker* music_worker_alloc(void) { MusicWorker* instance = malloc(sizeof(MusicWorker)); NoteBlockArray_init(instance->notes); instance->thread = furi_thread_alloc_ex("MusicWorker", 1024, music_worker_thread_callback, instance); instance->volume = 1.0f; return instance; } void music_worker_clear(MusicWorker* instance) { NoteBlockArray_reset(instance->notes); } void music_worker_free(MusicWorker* instance) { furi_assert(instance); furi_thread_free(instance->thread); NoteBlockArray_clear(instance->notes); free(instance); } static bool is_digit(const char c) { return isdigit(c) != 0; } static bool is_letter(const char c) { return islower(c) != 0 || isupper(c) != 0; } static bool is_space(const char c) { return c == ' ' || c == '\t'; } static size_t extract_number(const char* string, uint32_t* number) { size_t ret = 0; *number = 0; while(is_digit(*string)) { *number *= 10; *number += (*string - '0'); string++; ret++; } return ret; } static size_t extract_dots(const char* string, uint32_t* number) { size_t ret = 0; *number = 0; while(*string == '.') { *number += 1; string++; ret++; } return ret; } static size_t extract_char(const char* string, char* symbol) { if(is_letter(*string)) { *symbol = *string; return 1; } else { return 0; } } static size_t extract_sharp(const char* string, char* symbol) { if(*string == '#' || *string == '_') { *symbol = '#'; return 1; } else { return 0; } } static size_t skip_till(const char* string, const char symbol) { size_t ret = 0; while(*string != '\0' && *string != symbol) { string++; ret++; } if(*string != symbol) { ret = 0; } return ret; } static bool music_worker_add_note(MusicWorker* instance, uint8_t semitone, uint8_t duration, uint8_t dots) { NoteBlock note_block; note_block.semitone = semitone; note_block.duration = duration; note_block.dots = dots; NoteBlockArray_push_back(instance->notes, note_block); return true; } static int8_t note_to_semitone(const char note) { switch(note) { case 'C': return 0; // C# case 'D': return 2; // D# case 'E': return 4; case 'F': return 5; // F# case 'G': return 7; // G# case 'A': return 9; // A# case 'B': return 11; default: return 0; } } static bool music_worker_parse_notes(MusicWorker* instance, const char* string) { const char* cursor = string; bool result = true; while(*cursor != '\0') { if(!is_space(*cursor)) { uint32_t duration = 0; char note_char = '\0'; char sharp_char = '\0'; uint32_t octave = 0; uint32_t dots = 0; // Parsing cursor += extract_number(cursor, &duration); cursor += extract_char(cursor, &note_char); cursor += extract_sharp(cursor, &sharp_char); cursor += extract_number(cursor, &octave); cursor += extract_dots(cursor, &dots); // Post processing note_char = toupper(note_char); if(!duration) { duration = instance->duration; } if(!octave) { octave = instance->octave; } // Validation bool is_valid = true; is_valid &= (duration >= 1 && duration <= 128); is_valid &= ((note_char >= 'A' && note_char <= 'G') || note_char == 'P'); is_valid &= (sharp_char == '#' || sharp_char == '\0'); is_valid &= (octave <= 16); is_valid &= (dots <= 16); if(!is_valid) { FURI_LOG_E( TAG, "Invalid note: %lu%c%c%lu.%lu", duration, note_char == '\0' ? '_' : note_char, sharp_char == '\0' ? '_' : sharp_char, octave, dots); result = false; break; } // Note to semitones uint8_t semitone = 0; if(note_char == 'P') { semitone = SEMITONE_PAUSE; } else { semitone += octave * 12; semitone += note_to_semitone(note_char); semitone += sharp_char == '#' ? 1 : 0; } if(music_worker_add_note(instance, semitone, duration, dots)) { FURI_LOG_D( TAG, "Added note: %c%c%lu.%lu = %u %lu", note_char == '\0' ? '_' : note_char, sharp_char == '\0' ? '_' : sharp_char, octave, dots, semitone, duration); } else { FURI_LOG_E( TAG, "Invalid note: %c%c%lu.%lu = %u %lu", note_char == '\0' ? '_' : note_char, sharp_char == '\0' ? '_' : sharp_char, octave, dots, semitone, duration); } cursor += skip_till(cursor, ','); } if(*cursor != '\0') cursor++; } return result; } bool music_worker_load(MusicWorker* instance, const char* file_path) { furi_assert(instance); furi_assert(file_path); bool ret = false; if(strcasestr(file_path, ".fmf")) { ret = music_worker_load_fmf_from_file(instance, file_path); } else { ret = music_worker_load_rtttl_from_file(instance, file_path); } return ret; } bool music_worker_load_fmf_from_file(MusicWorker* instance, const char* file_path) { furi_assert(instance); furi_assert(file_path); bool result = false; FuriString* temp_str; temp_str = furi_string_alloc(); Storage* storage = furi_record_open(RECORD_STORAGE); FlipperFormat* file = flipper_format_file_alloc(storage); do { if(!flipper_format_file_open_existing(file, file_path)) break; uint32_t version = 0; if(!flipper_format_read_header(file, temp_str, &version)) break; if(furi_string_cmp_str(temp_str, MUSIC_PLAYER_FILETYPE) || (version != MUSIC_PLAYER_VERSION)) { FURI_LOG_E(TAG, "Incorrect file format or version"); break; } if(!flipper_format_read_uint32(file, "BPM", &instance->bpm, 1)) { FURI_LOG_E(TAG, "BPM is missing"); break; } if(!flipper_format_read_uint32(file, "Duration", &instance->duration, 1)) { FURI_LOG_E(TAG, "Duration is missing"); break; } if(!flipper_format_read_uint32(file, "Octave", &instance->octave, 1)) { FURI_LOG_E(TAG, "Octave is missing"); break; } if(!flipper_format_read_string(file, "Notes", temp_str)) { FURI_LOG_E(TAG, "Notes is missing"); break; } if(!music_worker_parse_notes(instance, furi_string_get_cstr(temp_str))) { break; } result = true; } while(false); furi_record_close(RECORD_STORAGE); flipper_format_free(file); furi_string_free(temp_str); return result; } bool music_worker_load_rtttl_from_file(MusicWorker* instance, const char* file_path) { furi_assert(instance); furi_assert(file_path); bool result = false; FuriString* content; content = furi_string_alloc(); Storage* storage = furi_record_open(RECORD_STORAGE); File* file = storage_file_alloc(storage); do { if(!storage_file_open(file, file_path, FSAM_READ, FSOM_OPEN_EXISTING)) { FURI_LOG_E(TAG, "Unable to open file"); break; }; size_t ret = 0; do { uint8_t buffer[65] = {0}; ret = storage_file_read(file, buffer, sizeof(buffer) - 1); for(size_t i = 0; i < ret; i++) { furi_string_push_back(content, buffer[i]); } } while(ret > 0); furi_string_trim(content); if(!furi_string_size(content)) { FURI_LOG_E(TAG, "Empty file"); break; } if(!music_worker_load_rtttl_from_string(instance, furi_string_get_cstr(content))) { FURI_LOG_E(TAG, "Invalid file content"); break; } result = true; } while(0); storage_file_free(file); furi_record_close(RECORD_STORAGE); furi_string_free(content); return result; } bool music_worker_load_rtttl_from_string(MusicWorker* instance, const char* string) { furi_assert(instance); const char* cursor = string; // Skip name cursor += skip_till(cursor, ':'); if(*cursor != ':') { return false; } // Duration cursor += skip_till(cursor, '='); if(*cursor != '=') { return false; } cursor++; cursor += extract_number(cursor, &instance->duration); // Octave cursor += skip_till(cursor, '='); if(*cursor != '=') { return false; } cursor++; cursor += extract_number(cursor, &instance->octave); // BPM cursor += skip_till(cursor, '='); if(*cursor != '=') { return false; } cursor++; cursor += extract_number(cursor, &instance->bpm); // Notes cursor += skip_till(cursor, ':'); if(*cursor != ':') { return false; } cursor++; if(!music_worker_parse_notes(instance, cursor)) { return false; } return true; } void music_worker_set_callback(MusicWorker* instance, MusicWorkerCallback callback, void* context) { furi_assert(instance); instance->callback = callback; instance->callback_context = context; } void music_worker_set_volume(MusicWorker* instance, float volume) { furi_assert(instance); instance->volume = volume; } void music_worker_start(MusicWorker* instance) { furi_assert(instance); furi_assert(instance->should_work == false); instance->should_work = true; furi_thread_start(instance->thread); } void music_worker_stop(MusicWorker* instance) { furi_assert(instance); furi_assert(instance->should_work == true); instance->should_work = false; furi_thread_join(instance->thread); } bool music_worker_is_playing(MusicWorker* instance) { furi_assert(instance); return instance->should_work; }
13,525
C
.c
422
23.445498
100
0.547242
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,340
lfrfid_dict_file.c
DarkFlippers_unleashed-firmware/lib/lfrfid/lfrfid_dict_file.c
#include "lfrfid_dict_file.h" #include <storage/storage.h> #include <flipper_format/flipper_format.h> #include <bit_lib/bit_lib.h> #define LFRFID_DICT_FILETYPE "Flipper RFID key" bool lfrfid_dict_file_save(ProtocolDict* dict, ProtocolId protocol, const char* filename) { furi_check(dict); furi_check(protocol != PROTOCOL_NO); furi_check(filename); Storage* storage = furi_record_open(RECORD_STORAGE); FlipperFormat* file = flipper_format_file_alloc(storage); size_t data_size = protocol_dict_get_data_size(dict, protocol); uint8_t* data = malloc(data_size); bool result = false; do { if(!flipper_format_file_open_always(file, filename)) break; if(!flipper_format_write_header_cstr(file, LFRFID_DICT_FILETYPE, 1)) break; // TODO FL-3517: write comment about protocol types into file if(!flipper_format_write_string_cstr( file, "Key type", protocol_dict_get_name(dict, protocol))) break; // TODO FL-3517: write comment about protocol sizes into file protocol_dict_get_data(dict, protocol, data, data_size); if(!flipper_format_write_hex(file, "Data", data, data_size)) break; result = true; } while(false); flipper_format_free(file); furi_record_close(RECORD_STORAGE); free(data); return result; } static void lfrfid_dict_protocol_indala_data( uint8_t* data, size_t data_size, uint8_t* protocol_data, size_t protocol_data_size) { UNUSED(data_size); memset(protocol_data, 0, protocol_data_size); // fc bit_lib_set_bit(protocol_data, 24, bit_lib_get_bit(data, 0)); bit_lib_set_bit(protocol_data, 16, bit_lib_get_bit(data, 1)); bit_lib_set_bit(protocol_data, 11, bit_lib_get_bit(data, 2)); bit_lib_set_bit(protocol_data, 14, bit_lib_get_bit(data, 3)); bit_lib_set_bit(protocol_data, 15, bit_lib_get_bit(data, 4)); bit_lib_set_bit(protocol_data, 20, bit_lib_get_bit(data, 5)); bit_lib_set_bit(protocol_data, 6, bit_lib_get_bit(data, 6)); bit_lib_set_bit(protocol_data, 25, bit_lib_get_bit(data, 7)); // cn bit_lib_set_bit(protocol_data, 9, bit_lib_get_bit(data, 8 + 0)); bit_lib_set_bit(protocol_data, 12, bit_lib_get_bit(data, 8 + 1)); bit_lib_set_bit(protocol_data, 10, bit_lib_get_bit(data, 8 + 2)); bit_lib_set_bit(protocol_data, 7, bit_lib_get_bit(data, 8 + 3)); bit_lib_set_bit(protocol_data, 19, bit_lib_get_bit(data, 8 + 4)); bit_lib_set_bit(protocol_data, 3, bit_lib_get_bit(data, 8 + 5)); bit_lib_set_bit(protocol_data, 2, bit_lib_get_bit(data, 8 + 6)); bit_lib_set_bit(protocol_data, 18, bit_lib_get_bit(data, 8 + 7)); bit_lib_set_bit(protocol_data, 13, bit_lib_get_bit(data, 8 + 8)); bit_lib_set_bit(protocol_data, 0, bit_lib_get_bit(data, 8 + 9)); bit_lib_set_bit(protocol_data, 4, bit_lib_get_bit(data, 8 + 10)); bit_lib_set_bit(protocol_data, 21, bit_lib_get_bit(data, 8 + 11)); bit_lib_set_bit(protocol_data, 23, bit_lib_get_bit(data, 8 + 12)); bit_lib_set_bit(protocol_data, 26, bit_lib_get_bit(data, 8 + 13)); bit_lib_set_bit(protocol_data, 17, bit_lib_get_bit(data, 8 + 14)); bit_lib_set_bit(protocol_data, 8, bit_lib_get_bit(data, 8 + 15)); const uint32_t fc_and_card = data[0] << 16 | data[1] << 8 | data[2]; // indala checksum uint8_t checksum_sum = 0; checksum_sum += ((fc_and_card >> 14) & 1); checksum_sum += ((fc_and_card >> 12) & 1); checksum_sum += ((fc_and_card >> 9) & 1); checksum_sum += ((fc_and_card >> 8) & 1); checksum_sum += ((fc_and_card >> 6) & 1); checksum_sum += ((fc_and_card >> 5) & 1); checksum_sum += ((fc_and_card >> 2) & 1); checksum_sum += ((fc_and_card >> 0) & 1); checksum_sum = checksum_sum & 0b1; if(checksum_sum) { bit_lib_set_bit(protocol_data, 27, 0); bit_lib_set_bit(protocol_data, 28, 1); } else { bit_lib_set_bit(protocol_data, 27, 1); bit_lib_set_bit(protocol_data, 28, 0); } // wiegand parity uint8_t even_parity_sum = 0; for(int8_t i = 12; i < 24; i++) { if(((fc_and_card >> i) & 1) == 1) { even_parity_sum++; } } bit_lib_set_bit(protocol_data, 1, even_parity_sum % 2); uint8_t odd_parity_sum = 1; for(int8_t i = 0; i < 12; i++) { if(((fc_and_card >> i) & 1) == 1) { odd_parity_sum++; } } bit_lib_set_bit(protocol_data, 5, odd_parity_sum % 2); } static ProtocolId lfrfid_dict_protocol_fallback( ProtocolDict* dict, const char* protocol_name, FlipperFormat* file) { ProtocolId result = PROTOCOL_NO; if(strcmp(protocol_name, "I40134") == 0) { ProtocolId protocol = LFRFIDProtocolIndala26; size_t data_size = 3; size_t protocol_data_size = protocol_dict_get_data_size(dict, protocol); uint8_t* data = malloc(data_size); uint8_t* protocol_data = malloc(protocol_data_size); if(flipper_format_read_hex(file, "Data", data, data_size)) { lfrfid_dict_protocol_indala_data(data, data_size, protocol_data, protocol_data_size); protocol_dict_set_data(dict, protocol, protocol_data, protocol_data_size); result = protocol; } free(protocol_data); free(data); } return result; } ProtocolId lfrfid_dict_file_load(ProtocolDict* dict, const char* filename) { furi_check(dict); furi_check(filename); Storage* storage = furi_record_open(RECORD_STORAGE); FlipperFormat* file = flipper_format_file_alloc(storage); ProtocolId result = PROTOCOL_NO; uint8_t* data = malloc(protocol_dict_get_max_data_size(dict)); FuriString* str_result; str_result = furi_string_alloc(); do { if(!flipper_format_file_open_existing(file, filename)) break; // header uint32_t version; if(!flipper_format_read_header(file, str_result, &version)) break; if(furi_string_cmp_str(str_result, LFRFID_DICT_FILETYPE) != 0) break; if(version != 1) break; // type if(!flipper_format_read_string(file, "Key type", str_result)) break; ProtocolId protocol; protocol = protocol_dict_get_protocol_by_name(dict, furi_string_get_cstr(str_result)); if(protocol == PROTOCOL_NO) { protocol = lfrfid_dict_protocol_fallback(dict, furi_string_get_cstr(str_result), file); if(protocol == PROTOCOL_NO) break; } else { // data size_t data_size = protocol_dict_get_data_size(dict, protocol); if(!flipper_format_read_hex(file, "Data", data, data_size)) break; protocol_dict_set_data(dict, protocol, data, data_size); } result = protocol; } while(false); free(data); furi_string_free(str_result); flipper_format_free(file); furi_record_close(RECORD_STORAGE); return result; }
6,927
C
.c
157
37.579618
99
0.629619
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,341
lfrfid_worker_modes.c
DarkFlippers_unleashed-firmware/lib/lfrfid/lfrfid_worker_modes.c
#include "lfrfid/lfrfid_i.h" #include <furi.h> #include <furi_hal.h> #include "lfrfid_worker_i.h" #include "tools/t5577.h" #include <toolbox/pulse_protocols/pulse_glue.h> #include <toolbox/buffer_stream.h> #include "tools/varint_pair.h" #include <lib/bit_lib/bit_lib.h> #define TAG "LfRfidWorker" /** * if READ_DEBUG_GPIO is defined: * gpio_ext_pa7 will repeat signal coming from the comparator * gpio_ext_pa6 will show load on the decoder */ // #define LFRFID_WORKER_READ_DEBUG_GPIO 1 #ifdef LFRFID_WORKER_READ_DEBUG_GPIO #define LFRFID_WORKER_READ_DEBUG_GPIO_VALUE &gpio_ext_pa7 #define LFRFID_WORKER_READ_DEBUG_GPIO_LOAD &gpio_ext_pa6 #endif #define LFRFID_WORKER_READ_AVERAGE_COUNT 64 #define LFRFID_WORKER_READ_MIN_TIME_US 16 #define LFRFID_WORKER_READ_DROP_TIME_MS 50 #define LFRFID_WORKER_READ_STABILIZE_TIME_MS 450 #define LFRFID_WORKER_READ_SWITCH_TIME_MS 2000 #define LFRFID_WORKER_WRITE_VERIFY_TIME_MS 2000 #define LFRFID_WORKER_WRITE_DROP_TIME_MS 50 #define LFRFID_WORKER_WRITE_TOO_LONG_TIME_MS 10000 #define LFRFID_WORKER_WRITE_MAX_UNSUCCESSFUL_READS 5 #define LFRFID_WORKER_READ_BUFFER_SIZE 512 #define LFRFID_WORKER_READ_BUFFER_COUNT 16 #define LFRFID_WORKER_EMULATE_BUFFER_SIZE 1024 #define LFRFID_WORKER_DELAY_QUANT 50 void lfrfid_worker_delay(LFRFIDWorker* worker, uint32_t milliseconds) { for(uint32_t i = 0; i < (milliseconds / LFRFID_WORKER_DELAY_QUANT); i++) { if(lfrfid_worker_check_for_stop(worker)) break; furi_delay_ms(LFRFID_WORKER_DELAY_QUANT); } } void t5577_trace(LFRFIDT5577 t5577, const char* message) { if(furi_log_get_level() == FuriLogLevelTrace) { FURI_LOG_T(TAG, "%s", message); for(uint8_t i = 0; i < 8; i++) FURI_LOG_T(TAG, "\nBlock %u %08lX", i, t5577.block[i]); FURI_LOG_T(TAG, "Mask: %u", t5577.mask); FURI_LOG_T(TAG, "Blocks to write: %lu", t5577.blocks_to_write); } } /**************************************************************************************************/ /********************************************** READ **********************************************/ /**************************************************************************************************/ typedef struct { BufferStream* stream; VarintPair* pair; bool ignore_next_pulse; } LFRFIDWorkerReadContext; static void lfrfid_worker_read_capture(bool level, uint32_t duration, void* context) { LFRFIDWorkerReadContext* ctx = context; // ignore pulse if last pulse was noise if(ctx->ignore_next_pulse) { ctx->ignore_next_pulse = false; return; } // ignore noise spikes if(duration <= LFRFID_WORKER_READ_MIN_TIME_US) { if(level) { ctx->ignore_next_pulse = true; } varint_pair_reset(ctx->pair); return; } #ifdef LFRFID_WORKER_READ_DEBUG_GPIO furi_hal_gpio_write(LFRFID_WORKER_READ_DEBUG_GPIO_VALUE, level); #endif bool need_to_send = varint_pair_pack(ctx->pair, level, duration); if(need_to_send) { buffer_stream_send_from_isr( ctx->stream, varint_pair_get_data(ctx->pair), varint_pair_get_size(ctx->pair)); varint_pair_reset(ctx->pair); } } typedef enum { LFRFIDWorkerReadOK, LFRFIDWorkerReadExit, LFRFIDWorkerReadTimeout, } LFRFIDWorkerReadState; static LFRFIDWorkerReadState lfrfid_worker_read_internal( LFRFIDWorker* worker, LFRFIDFeature feature, uint32_t timeout, ProtocolId* result_protocol) { LFRFIDWorkerReadState state = LFRFIDWorkerReadTimeout; if(feature & LFRFIDFeatureASK) { furi_hal_rfid_tim_read_start(125000, 0.5); FURI_LOG_D(TAG, "Start ASK"); if(worker->read_cb) { worker->read_cb(LFRFIDWorkerReadStartASK, PROTOCOL_NO, worker->cb_ctx); } } else { furi_hal_rfid_tim_read_start(62500, 0.25); FURI_LOG_D(TAG, "Start PSK"); if(worker->read_cb) { worker->read_cb(LFRFIDWorkerReadStartPSK, PROTOCOL_NO, worker->cb_ctx); } } // stabilize detector lfrfid_worker_delay(worker, LFRFID_WORKER_READ_STABILIZE_TIME_MS); protocol_dict_decoders_start(worker->protocols); #ifdef LFRFID_WORKER_READ_DEBUG_GPIO furi_hal_gpio_init_simple(LFRFID_WORKER_READ_DEBUG_GPIO_VALUE, GpioModeOutputPushPull); furi_hal_gpio_init_simple(LFRFID_WORKER_READ_DEBUG_GPIO_LOAD, GpioModeOutputPushPull); furi_hal_gpio_write(LFRFID_WORKER_READ_DEBUG_GPIO_VALUE, false); furi_hal_gpio_write(LFRFID_WORKER_READ_DEBUG_GPIO_LOAD, false); #endif LFRFIDWorkerReadContext ctx; ctx.pair = varint_pair_alloc(); ctx.stream = buffer_stream_alloc(LFRFID_WORKER_READ_BUFFER_SIZE, LFRFID_WORKER_READ_BUFFER_COUNT); furi_hal_rfid_tim_read_capture_start(lfrfid_worker_read_capture, &ctx); *result_protocol = PROTOCOL_NO; ProtocolId last_protocol = PROTOCOL_NO; size_t last_size = protocol_dict_get_max_data_size(worker->protocols); uint8_t* last_data = malloc(last_size); uint8_t* protocol_data = malloc(last_size); size_t last_read_count = 0; uint32_t switch_os_tick_last = furi_get_tick(); uint32_t average_duration = 0; uint32_t average_pulse = 0; size_t average_index = 0; bool card_detected = false; FURI_LOG_D(TAG, "Read started"); while(true) { if(lfrfid_worker_check_for_stop(worker)) { state = LFRFIDWorkerReadExit; break; } Buffer* buffer = buffer_stream_receive(ctx.stream, 100); #ifdef LFRFID_WORKER_READ_DEBUG_GPIO furi_hal_gpio_write(LFRFID_WORKER_READ_DEBUG_GPIO_LOAD, true); #endif if(buffer_stream_get_overrun_count(ctx.stream) > 0) { FURI_LOG_E(TAG, "Read overrun, recovering"); buffer_stream_reset(ctx.stream); #ifdef LFRFID_WORKER_READ_DEBUG_GPIO furi_hal_gpio_write(LFRFID_WORKER_READ_DEBUG_GPIO_LOAD, false); #endif continue; } if(buffer == NULL) { #ifdef LFRFID_WORKER_READ_DEBUG_GPIO furi_hal_gpio_write(LFRFID_WORKER_READ_DEBUG_GPIO_LOAD, false); #endif continue; } size_t size = buffer_get_size(buffer); uint8_t* data = buffer_get_data(buffer); size_t index = 0; while(index < size) { uint32_t duration; uint32_t pulse; size_t tmp_size; if(!varint_pair_unpack(&data[index], size - index, &pulse, &duration, &tmp_size)) { FURI_LOG_E(TAG, "can't unpack varint pair"); break; } else { index += tmp_size; average_duration += duration; average_pulse += pulse; average_index++; if(average_index >= LFRFID_WORKER_READ_AVERAGE_COUNT) { float average = (float)average_pulse / (float)average_duration; average_pulse = 0; average_duration = 0; average_index = 0; if(worker->read_cb) { if(average > 0.2f && average < 0.8f) { if(!card_detected) { card_detected = true; worker->read_cb( LFRFIDWorkerReadSenseStart, PROTOCOL_NO, worker->cb_ctx); } } else { if(card_detected) { card_detected = false; worker->read_cb( LFRFIDWorkerReadSenseEnd, PROTOCOL_NO, worker->cb_ctx); } } } } ProtocolId protocol = PROTOCOL_NO; protocol = protocol_dict_decoders_feed_by_feature( worker->protocols, feature, true, pulse); if(protocol == PROTOCOL_NO) { protocol = protocol_dict_decoders_feed_by_feature( worker->protocols, feature, false, duration - pulse); } if(protocol != PROTOCOL_NO) { // reset switch timer switch_os_tick_last = furi_get_tick(); size_t protocol_data_size = protocol_dict_get_data_size(worker->protocols, protocol); protocol_dict_get_data( worker->protocols, protocol, protocol_data, protocol_data_size); // validate protocol if(protocol == last_protocol && memcmp(last_data, protocol_data, protocol_data_size) == 0) { last_read_count = last_read_count + 1; size_t validation_count = protocol_dict_get_validate_count(worker->protocols, protocol); if(last_read_count >= validation_count) { state = LFRFIDWorkerReadOK; *result_protocol = protocol; break; } } else { if(last_protocol == PROTOCOL_NO && worker->read_cb) { worker->read_cb( LFRFIDWorkerReadSenseCardStart, protocol, worker->cb_ctx); } last_protocol = protocol; memcpy(last_data, protocol_data, protocol_data_size); last_read_count = 0; } if(furi_log_get_level() >= FuriLogLevelDebug) { FuriString* string_info; string_info = furi_string_alloc(); for(uint8_t i = 0; i < protocol_data_size; i++) { if(i != 0) { furi_string_cat_printf(string_info, " "); } furi_string_cat_printf(string_info, "%02X", protocol_data[i]); } FURI_LOG_D( TAG, "%s, %zu, [%s]", protocol_dict_get_name(worker->protocols, protocol), last_read_count, furi_string_get_cstr(string_info)); furi_string_free(string_info); } protocol_dict_decoders_start(worker->protocols); } } } buffer_reset(buffer); #ifdef LFRFID_WORKER_READ_DEBUG_GPIO furi_hal_gpio_write(LFRFID_WORKER_READ_DEBUG_GPIO_LOAD, false); #endif if(*result_protocol != PROTOCOL_NO) { break; } if((furi_get_tick() - switch_os_tick_last) > timeout) { state = LFRFIDWorkerReadTimeout; break; } } FURI_LOG_D(TAG, "Read stopped"); if(last_protocol != PROTOCOL_NO && worker->read_cb) { worker->read_cb(LFRFIDWorkerReadSenseCardEnd, last_protocol, worker->cb_ctx); } if(card_detected && worker->read_cb) { worker->read_cb(LFRFIDWorkerReadSenseEnd, last_protocol, worker->cb_ctx); } furi_hal_rfid_tim_read_capture_stop(); furi_hal_rfid_tim_read_stop(); furi_hal_rfid_pins_reset(); varint_pair_free(ctx.pair); buffer_stream_free(ctx.stream); free(protocol_data); free(last_data); #ifdef LFRFID_WORKER_READ_DEBUG_GPIO furi_hal_gpio_write(LFRFID_WORKER_READ_DEBUG_GPIO_VALUE, false); furi_hal_gpio_write(LFRFID_WORKER_READ_DEBUG_GPIO_LOAD, false); furi_hal_gpio_init_simple(LFRFID_WORKER_READ_DEBUG_GPIO_VALUE, GpioModeAnalog); furi_hal_gpio_init_simple(LFRFID_WORKER_READ_DEBUG_GPIO_LOAD, GpioModeAnalog); #endif return state; } static void lfrfid_worker_mode_read_process(LFRFIDWorker* worker) { ProtocolId read_result = PROTOCOL_NO; LFRFIDWorkerReadState state; LFRFIDFeature feature; if(worker->read_type == LFRFIDWorkerReadTypePSKOnly) { feature = LFRFIDFeaturePSK; } else { feature = LFRFIDFeatureASK; } if(worker->read_type == LFRFIDWorkerReadTypeAuto) { while(1) { // read for a while state = lfrfid_worker_read_internal( worker, feature, LFRFID_WORKER_READ_SWITCH_TIME_MS, &read_result); if(state == LFRFIDWorkerReadOK || state == LFRFIDWorkerReadExit) { break; } // switch to next feature if(feature == LFRFIDFeatureASK) { feature = LFRFIDFeaturePSK; } else { feature = LFRFIDFeatureASK; } lfrfid_worker_delay(worker, LFRFID_WORKER_READ_DROP_TIME_MS); } } else { while(1) { if(worker->read_type == LFRFIDWorkerReadTypeASKOnly) { state = lfrfid_worker_read_internal(worker, feature, UINT32_MAX, &read_result); } else { state = lfrfid_worker_read_internal( worker, feature, LFRFID_WORKER_READ_SWITCH_TIME_MS, &read_result); } if(state == LFRFIDWorkerReadOK || state == LFRFIDWorkerReadExit) { break; } lfrfid_worker_delay(worker, LFRFID_WORKER_READ_DROP_TIME_MS); } } if(state == LFRFIDWorkerReadOK && worker->read_cb) { worker->read_cb(LFRFIDWorkerReadDone, read_result, worker->cb_ctx); } } /**************************************************************************************************/ /******************************************** EMULATE *********************************************/ /**************************************************************************************************/ typedef struct { uint32_t duration[LFRFID_WORKER_EMULATE_BUFFER_SIZE]; uint32_t pulse[LFRFID_WORKER_EMULATE_BUFFER_SIZE]; } LFRFIDWorkerEmulateBuffer; typedef enum { HalfTransfer, TransferComplete, } LFRFIDWorkerEmulateDMAEvent; static void lfrfid_worker_emulate_dma_isr(bool half, void* context) { FuriStreamBuffer* stream = context; uint32_t flag = half ? HalfTransfer : TransferComplete; furi_stream_buffer_send(stream, &flag, sizeof(uint32_t), 0); } static void lfrfid_worker_mode_emulate_process(LFRFIDWorker* worker) { LFRFIDWorkerEmulateBuffer* buffer = malloc(sizeof(LFRFIDWorkerEmulateBuffer)); FuriStreamBuffer* stream = furi_stream_buffer_alloc(sizeof(uint32_t), sizeof(uint32_t)); LFRFIDProtocol protocol = worker->protocol; PulseGlue* pulse_glue = pulse_glue_alloc(); protocol_dict_encoder_start(worker->protocols, protocol); for(size_t i = 0; i < LFRFID_WORKER_EMULATE_BUFFER_SIZE; i++) { bool pulse_pop = false; while(!pulse_pop) { LevelDuration level_duration = protocol_dict_encoder_yield(worker->protocols, protocol); pulse_pop = pulse_glue_push( pulse_glue, level_duration_get_level(level_duration), level_duration_get_duration(level_duration)); } uint32_t duration, pulse; pulse_glue_pop(pulse_glue, &duration, &pulse); buffer->duration[i] = duration - 1; buffer->pulse[i] = pulse; } #ifdef LFRFID_WORKER_READ_DEBUG_GPIO furi_hal_gpio_init_simple(LFRFID_WORKER_READ_DEBUG_GPIO_LOAD, GpioModeOutputPushPull); #endif furi_hal_rfid_tim_emulate_dma_start( buffer->duration, buffer->pulse, LFRFID_WORKER_EMULATE_BUFFER_SIZE, lfrfid_worker_emulate_dma_isr, stream); while(true) { uint32_t flag = 0; size_t size = furi_stream_buffer_receive(stream, &flag, sizeof(uint32_t), 100); #ifdef LFRFID_WORKER_READ_DEBUG_GPIO furi_hal_gpio_write(LFRFID_WORKER_READ_DEBUG_GPIO_LOAD, true); #endif if(size == sizeof(uint32_t)) { size_t start = 0; if(flag == HalfTransfer) { start = 0; } else if(flag == TransferComplete) { start = (LFRFID_WORKER_EMULATE_BUFFER_SIZE / 2); } for(size_t i = 0; i < (LFRFID_WORKER_EMULATE_BUFFER_SIZE / 2); i++) { bool pulse_pop = false; while(!pulse_pop) { LevelDuration level_duration = protocol_dict_encoder_yield(worker->protocols, protocol); pulse_pop = pulse_glue_push( pulse_glue, level_duration_get_level(level_duration), level_duration_get_duration(level_duration)); } uint32_t duration, pulse; pulse_glue_pop(pulse_glue, &duration, &pulse); buffer->duration[start + i] = duration - 1; buffer->pulse[start + i] = pulse; } } if(lfrfid_worker_check_for_stop(worker)) { break; } #ifdef LFRFID_WORKER_READ_DEBUG_GPIO furi_hal_gpio_write(LFRFID_WORKER_READ_DEBUG_GPIO_LOAD, false); #endif } furi_hal_rfid_tim_emulate_dma_stop(); #ifdef LFRFID_WORKER_READ_DEBUG_GPIO furi_hal_gpio_init_simple(LFRFID_WORKER_READ_DEBUG_GPIO_LOAD, GpioModeAnalog); #endif free(buffer); furi_stream_buffer_free(stream); pulse_glue_free(pulse_glue); } /**************************************************************************************************/ /********************************************* WRITE **********************************************/ /**************************************************************************************************/ static void lfrfid_worker_mode_write_process(LFRFIDWorker* worker) { LFRFIDProtocol protocol = worker->protocol; LFRFIDWriteRequest* request = malloc(sizeof(LFRFIDWriteRequest)); request->write_type = LFRFIDWriteTypeT5577; bool can_be_written = protocol_dict_get_write_data(worker->protocols, protocol, request); uint32_t write_start_time = furi_get_tick(); bool too_long = false; size_t unsuccessful_reads = 0; size_t data_size = protocol_dict_get_data_size(worker->protocols, protocol); uint8_t* verify_data = malloc(data_size); uint8_t* read_data = malloc(data_size); protocol_dict_get_data(worker->protocols, protocol, verify_data, data_size); if(can_be_written) { while(!lfrfid_worker_check_for_stop(worker)) { FURI_LOG_D(TAG, "Data write"); t5577_write(&request->t5577); ProtocolId read_result = PROTOCOL_NO; LFRFIDWorkerReadState state = lfrfid_worker_read_internal( worker, protocol_dict_get_features(worker->protocols, protocol), LFRFID_WORKER_WRITE_VERIFY_TIME_MS, &read_result); if(state == LFRFIDWorkerReadOK) { bool read_success = false; if(read_result == protocol) { protocol_dict_get_data(worker->protocols, protocol, read_data, data_size); if(memcmp(read_data, verify_data, data_size) == 0) { read_success = true; } } if(read_success) { if(worker->write_cb) { worker->write_cb(LFRFIDWorkerWriteOK, worker->cb_ctx); } break; } else { unsuccessful_reads++; if(unsuccessful_reads == LFRFID_WORKER_WRITE_MAX_UNSUCCESSFUL_READS) { if(worker->write_cb) { worker->write_cb(LFRFIDWorkerWriteFobCannotBeWritten, worker->cb_ctx); } } } } else if(state == LFRFIDWorkerReadExit) { break; } if(!too_long && (furi_get_tick() - write_start_time) > LFRFID_WORKER_WRITE_TOO_LONG_TIME_MS) { too_long = true; if(worker->write_cb) { worker->write_cb(LFRFIDWorkerWriteTooLongToWrite, worker->cb_ctx); } } lfrfid_worker_delay(worker, LFRFID_WORKER_WRITE_DROP_TIME_MS); } } else { if(worker->write_cb) { worker->write_cb(LFRFIDWorkerWriteProtocolCannotBeWritten, worker->cb_ctx); } } free(request); free(verify_data); free(read_data); } static void lfrfid_worker_mode_write_and_set_pass_process(LFRFIDWorker* worker) { LFRFIDProtocol protocol = worker->protocol; LFRFIDWriteRequest* request = malloc(sizeof(LFRFIDWriteRequest)); request->write_type = LFRFIDWriteTypeT5577; bool can_be_written = protocol_dict_get_write_data(worker->protocols, protocol, request); uint32_t write_start_time = furi_get_tick(); bool too_long = false; size_t unsuccessful_reads = 0; size_t data_size = protocol_dict_get_data_size(worker->protocols, protocol); uint8_t* verify_data = malloc(data_size); uint8_t* read_data = malloc(data_size); protocol_dict_get_data(worker->protocols, protocol, verify_data, data_size); if(can_be_written) { while(!lfrfid_worker_check_for_stop(worker)) { FURI_LOG_D(TAG, "Data write with pass"); LfRfid* app = worker->cb_ctx; uint32_t pass = bit_lib_bytes_to_num_be(app->password, 4); request->t5577.mask = 0b10000001; for(uint8_t i = 0; i < request->t5577.blocks_to_write; i++) request->t5577.mask |= (1 << i); request->t5577.block[0] |= (1 << 4); request->t5577.block[7] = pass; t5577_trace(request->t5577, "Write with password"); t5577_write_with_mask(&request->t5577, 0, true, 0); ProtocolId read_result = PROTOCOL_NO; LFRFIDWorkerReadState state = lfrfid_worker_read_internal( worker, protocol_dict_get_features(worker->protocols, protocol), LFRFID_WORKER_WRITE_VERIFY_TIME_MS, &read_result); if(state == LFRFIDWorkerReadOK) { bool read_success = false; if(read_result == protocol) { protocol_dict_get_data(worker->protocols, protocol, read_data, data_size); if(memcmp(read_data, verify_data, data_size) == 0) { read_success = true; } } if(read_success) { FURI_LOG_D(TAG, "Write with password %08lX success", pass); if(worker->write_cb) { worker->write_cb(LFRFIDWorkerWriteOK, worker->cb_ctx); } break; } else { unsuccessful_reads++; if(unsuccessful_reads == LFRFID_WORKER_WRITE_MAX_UNSUCCESSFUL_READS) { if(worker->write_cb) { worker->write_cb(LFRFIDWorkerWriteFobCannotBeWritten, worker->cb_ctx); } } } } else if(state == LFRFIDWorkerReadExit) { break; } if(!too_long && (furi_get_tick() - write_start_time) > LFRFID_WORKER_WRITE_TOO_LONG_TIME_MS) { too_long = true; if(worker->write_cb) { worker->write_cb(LFRFIDWorkerWriteTooLongToWrite, worker->cb_ctx); } } lfrfid_worker_delay(worker, LFRFID_WORKER_WRITE_DROP_TIME_MS); } } else { if(worker->write_cb) { worker->write_cb(LFRFIDWorkerWriteProtocolCannotBeWritten, worker->cb_ctx); } } free(request); free(verify_data); free(read_data); } /**************************************************************************************************/ /******************************************* READ RAW *********************************************/ /**************************************************************************************************/ static void lfrfid_worker_mode_read_raw_process(LFRFIDWorker* worker) { LFRFIDRawWorker* raw_worker = lfrfid_raw_worker_alloc(); switch(worker->read_type) { case LFRFIDWorkerReadTypePSKOnly: lfrfid_raw_worker_start_read( raw_worker, worker->raw_filename, 62500, 0.25, worker->read_raw_cb, worker->cb_ctx); break; case LFRFIDWorkerReadTypeASKOnly: lfrfid_raw_worker_start_read( raw_worker, worker->raw_filename, 125000, 0.5, worker->read_raw_cb, worker->cb_ctx); break; default: furi_crash("RAW can be only PSK or ASK"); break; } while(!lfrfid_worker_check_for_stop(worker)) { furi_delay_ms(100); } lfrfid_raw_worker_stop(raw_worker); lfrfid_raw_worker_free(raw_worker); } /**************************************************************************************************/ /***************************************** EMULATE RAW ********************************************/ /**************************************************************************************************/ static void lfrfid_worker_mode_emulate_raw_process(LFRFIDWorker* worker) { LFRFIDRawWorker* raw_worker = lfrfid_raw_worker_alloc(); lfrfid_raw_worker_start_emulate( raw_worker, worker->raw_filename, worker->emulate_raw_cb, worker->cb_ctx); while(!lfrfid_worker_check_for_stop(worker)) { furi_delay_ms(100); } lfrfid_raw_worker_stop(raw_worker); lfrfid_raw_worker_free(raw_worker); } /**************************************************************************************************/ /******************************************** MODES ***********************************************/ /**************************************************************************************************/ const LFRFIDWorkerModeType lfrfid_worker_modes[] = { [LFRFIDWorkerIdle] = {.process = NULL}, [LFRFIDWorkerRead] = {.process = lfrfid_worker_mode_read_process}, [LFRFIDWorkerWrite] = {.process = lfrfid_worker_mode_write_process}, [LFRFIDWorkerWriteAndSetPass] = {.process = lfrfid_worker_mode_write_and_set_pass_process}, [LFRFIDWorkerEmulate] = {.process = lfrfid_worker_mode_emulate_process}, [LFRFIDWorkerReadRaw] = {.process = lfrfid_worker_mode_read_raw_process}, [LFRFIDWorkerEmulateRaw] = {.process = lfrfid_worker_mode_emulate_raw_process}, };
26,822
C
.c
601
33.765391
100
0.546699
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,342
lfrfid_raw_worker.c
DarkFlippers_unleashed-firmware/lib/lfrfid/lfrfid_raw_worker.c
#include <furi_hal_rfid.h> #include <toolbox/stream/file_stream.h> #include <toolbox/buffer_stream.h> #include <toolbox/varint.h> #include "lfrfid_raw_worker.h" #include "lfrfid_raw_file.h" #include "tools/varint_pair.h" #define EMULATE_BUFFER_SIZE 1024 #define RFID_DATA_BUFFER_SIZE 2048 #define READ_DATA_BUFFER_COUNT 4 #define TAG_EMULATE "RawEmulate" // emulate mode typedef struct { size_t overrun_count; FuriStreamBuffer* stream; } RfidEmulateCtx; typedef struct { uint32_t emulate_buffer_arr[EMULATE_BUFFER_SIZE]; uint32_t emulate_buffer_ccr[EMULATE_BUFFER_SIZE]; RfidEmulateCtx ctx; } LFRFIDRawWorkerEmulateData; typedef enum { HalfTransfer, TransferComplete, } LFRFIDRawEmulateDMAEvent; // read mode #define READ_TEMP_DATA_SIZE 10 typedef struct { BufferStream* stream; VarintPair* pair; } LFRFIDRawWorkerReadData; // main worker struct LFRFIDRawWorker { FuriString* file_path; FuriThread* thread; FuriEventFlag* events; LFRFIDWorkerEmulateRawCallback emulate_callback; LFRFIDWorkerReadRawCallback read_callback; void* context; float frequency; float duty_cycle; }; typedef enum { LFRFIDRawWorkerEventStop, } LFRFIDRawWorkerEvent; static int32_t lfrfid_raw_read_worker_thread(void* thread_context); static int32_t lfrfid_raw_emulate_worker_thread(void* thread_context); LFRFIDRawWorker* lfrfid_raw_worker_alloc(void) { LFRFIDRawWorker* worker = malloc(sizeof(LFRFIDRawWorker)); worker->thread = furi_thread_alloc_ex("LfrfidRawWorker", 2048, NULL, worker); worker->events = furi_event_flag_alloc(); worker->file_path = furi_string_alloc(); return worker; } void lfrfid_raw_worker_free(LFRFIDRawWorker* worker) { furi_check(worker); furi_thread_free(worker->thread); furi_event_flag_free(worker->events); furi_string_free(worker->file_path); free(worker); } void lfrfid_raw_worker_start_read( LFRFIDRawWorker* worker, const char* file_path, float freq, float duty_cycle, LFRFIDWorkerReadRawCallback callback, void* context) { furi_check(worker); furi_check(file_path); furi_check(furi_thread_get_state(worker->thread) == FuriThreadStateStopped); furi_string_set(worker->file_path, file_path); worker->frequency = freq; worker->duty_cycle = duty_cycle; worker->read_callback = callback; worker->context = context; furi_thread_set_callback(worker->thread, lfrfid_raw_read_worker_thread); furi_thread_start(worker->thread); } void lfrfid_raw_worker_start_emulate( LFRFIDRawWorker* worker, const char* file_path, LFRFIDWorkerEmulateRawCallback callback, void* context) { furi_check(worker); furi_check(file_path); furi_check(furi_thread_get_state(worker->thread) == FuriThreadStateStopped); furi_string_set(worker->file_path, file_path); worker->emulate_callback = callback; worker->context = context; furi_thread_set_callback(worker->thread, lfrfid_raw_emulate_worker_thread); furi_thread_start(worker->thread); } void lfrfid_raw_worker_stop(LFRFIDRawWorker* worker) { furi_check(worker); worker->emulate_callback = NULL; worker->context = NULL; worker->read_callback = NULL; furi_event_flag_set(worker->events, 1 << LFRFIDRawWorkerEventStop); furi_thread_join(worker->thread); } static void lfrfid_raw_worker_capture(bool level, uint32_t duration, void* context) { LFRFIDRawWorkerReadData* ctx = context; bool need_to_send = varint_pair_pack(ctx->pair, level, duration); if(need_to_send) { buffer_stream_send_from_isr( ctx->stream, varint_pair_get_data(ctx->pair), varint_pair_get_size(ctx->pair)); varint_pair_reset(ctx->pair); } } static int32_t lfrfid_raw_read_worker_thread(void* thread_context) { LFRFIDRawWorker* worker = (LFRFIDRawWorker*)thread_context; Storage* storage = furi_record_open(RECORD_STORAGE); LFRFIDRawFile* file = lfrfid_raw_file_alloc(storage); const char* filename = furi_string_get_cstr(worker->file_path); bool file_valid = lfrfid_raw_file_open_write(file, filename); LFRFIDRawWorkerReadData* data = malloc(sizeof(LFRFIDRawWorkerReadData)); data->stream = buffer_stream_alloc(RFID_DATA_BUFFER_SIZE, READ_DATA_BUFFER_COUNT); data->pair = varint_pair_alloc(); if(file_valid) { // write header file_valid = lfrfid_raw_file_write_header( file, worker->frequency, worker->duty_cycle, RFID_DATA_BUFFER_SIZE); } if(file_valid) { // setup carrier furi_hal_rfid_tim_read_start(worker->frequency, worker->duty_cycle); // stabilize detector furi_delay_ms(1500); // start capture furi_hal_rfid_tim_read_capture_start(lfrfid_raw_worker_capture, data); while(1) { Buffer* buffer = buffer_stream_receive(data->stream, 100); if(buffer != NULL) { file_valid = lfrfid_raw_file_write_buffer( file, buffer_get_data(buffer), buffer_get_size(buffer)); buffer_reset(buffer); } if(!file_valid) { if(worker->read_callback != NULL) { // message file_error to worker worker->read_callback(LFRFIDWorkerReadRawFileError, worker->context); } break; } if(buffer_stream_get_overrun_count(data->stream) > 0 && worker->read_callback != NULL) { // message overrun to worker worker->read_callback(LFRFIDWorkerReadRawOverrun, worker->context); } uint32_t flags = furi_event_flag_get(worker->events); if(FURI_BIT(flags, LFRFIDRawWorkerEventStop)) { break; } } furi_hal_rfid_tim_read_capture_stop(); furi_hal_rfid_tim_read_stop(); } else { if(worker->read_callback != NULL) { // message file_error to worker worker->read_callback(LFRFIDWorkerReadRawFileError, worker->context); } } if(!file_valid) { const uint32_t available_flags = (1 << LFRFIDRawWorkerEventStop); while(true) { uint32_t flags = furi_event_flag_wait( worker->events, available_flags, FuriFlagWaitAny, FuriWaitForever); if(FURI_BIT(flags, LFRFIDRawWorkerEventStop)) { break; } } } varint_pair_free(data->pair); buffer_stream_free(data->stream); lfrfid_raw_file_free(file); furi_record_close(RECORD_STORAGE); free(data); return 0; } static void rfid_emulate_dma_isr(bool half, void* context) { RfidEmulateCtx* ctx = context; uint32_t flag = half ? HalfTransfer : TransferComplete; size_t len = furi_stream_buffer_send(ctx->stream, &flag, sizeof(uint32_t), 0); if(len != sizeof(uint32_t)) { ctx->overrun_count++; } } static int32_t lfrfid_raw_emulate_worker_thread(void* thread_context) { LFRFIDRawWorker* worker = thread_context; bool file_valid = true; LFRFIDRawWorkerEmulateData* data = malloc(sizeof(LFRFIDRawWorkerEmulateData)); Storage* storage = furi_record_open(RECORD_STORAGE); data->ctx.overrun_count = 0; data->ctx.stream = furi_stream_buffer_alloc(sizeof(uint32_t), sizeof(uint32_t)); LFRFIDRawFile* file = lfrfid_raw_file_alloc(storage); do { file_valid = lfrfid_raw_file_open_read(file, furi_string_get_cstr(worker->file_path)); if(!file_valid) break; file_valid = lfrfid_raw_file_read_header(file, &worker->frequency, &worker->duty_cycle); if(!file_valid) break; for(size_t i = 0; i < EMULATE_BUFFER_SIZE; i++) { file_valid = lfrfid_raw_file_read_pair( file, &data->emulate_buffer_arr[i], &data->emulate_buffer_ccr[i], NULL); if(!file_valid) break; data->emulate_buffer_arr[i] /= 8; data->emulate_buffer_arr[i] -= 1; data->emulate_buffer_ccr[i] /= 8; } } while(false); furi_hal_rfid_tim_emulate_dma_start( data->emulate_buffer_arr, data->emulate_buffer_ccr, EMULATE_BUFFER_SIZE, rfid_emulate_dma_isr, &data->ctx); if(!file_valid && worker->emulate_callback != NULL) { // message file_error to worker worker->emulate_callback(LFRFIDWorkerEmulateRawFileError, worker->context); } if(file_valid) { uint32_t flag = 0; while(true) { size_t size = furi_stream_buffer_receive(data->ctx.stream, &flag, sizeof(uint32_t), 100); if(size == sizeof(uint32_t)) { size_t start = 0; if(flag == TransferComplete) { start = (EMULATE_BUFFER_SIZE / 2); } for(size_t i = 0; i < (EMULATE_BUFFER_SIZE / 2); i++) { file_valid = lfrfid_raw_file_read_pair( file, &data->emulate_buffer_arr[start + i], &data->emulate_buffer_ccr[start + i], NULL); if(!file_valid) break; data->emulate_buffer_arr[i] /= 8; data->emulate_buffer_arr[i] -= 1; data->emulate_buffer_ccr[i] /= 8; } } else if(size != 0) { data->ctx.overrun_count++; } if(!file_valid) { if(worker->emulate_callback != NULL) { // message file_error to worker worker->emulate_callback(LFRFIDWorkerEmulateRawFileError, worker->context); } break; } if(data->ctx.overrun_count > 0 && worker->emulate_callback != NULL) { // message overrun to worker worker->emulate_callback(LFRFIDWorkerEmulateRawOverrun, worker->context); } uint32_t flags = furi_event_flag_get(worker->events); if(FURI_BIT(flags, LFRFIDRawWorkerEventStop)) { break; }; } } furi_hal_rfid_tim_emulate_dma_stop(); if(!file_valid) { const uint32_t available_flags = (1 << LFRFIDRawWorkerEventStop); while(true) { uint32_t flags = furi_event_flag_wait( worker->events, available_flags, FuriFlagWaitAny, FuriWaitForever); if(FURI_BIT(flags, LFRFIDRawWorkerEventStop)) { break; }; } } if(data->ctx.overrun_count) { FURI_LOG_E(TAG_EMULATE, "overruns: %zu", data->ctx.overrun_count); } furi_stream_buffer_free(data->ctx.stream); lfrfid_raw_file_free(file); furi_record_close(RECORD_STORAGE); free(data); return 0; }
10,912
C
.c
281
30.590747
96
0.629226
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,343
lfrfid_raw_file.c
DarkFlippers_unleashed-firmware/lib/lfrfid/lfrfid_raw_file.c
#include "lfrfid_raw_file.h" #include "tools/varint_pair.h" #include <toolbox/stream/file_stream.h> #include <toolbox/varint.h> #define LFRFID_RAW_FILE_MAGIC 0x4C464952 #define LFRFID_RAW_FILE_VERSION 1 #define TAG "LfRfidRawFile" typedef struct { uint32_t magic; uint32_t version; float frequency; float duty_cycle; uint32_t max_buffer_size; } LFRFIDRawFileHeader; struct LFRFIDRawFile { Stream* stream; uint32_t max_buffer_size; uint8_t* buffer; uint32_t buffer_size; size_t buffer_counter; }; LFRFIDRawFile* lfrfid_raw_file_alloc(Storage* storage) { furi_check(storage); LFRFIDRawFile* file = malloc(sizeof(LFRFIDRawFile)); file->stream = file_stream_alloc(storage); file->buffer = NULL; return file; } void lfrfid_raw_file_free(LFRFIDRawFile* file) { furi_check(file); if(file->buffer) free(file->buffer); stream_free(file->stream); free(file); } bool lfrfid_raw_file_open_write(LFRFIDRawFile* file, const char* file_path) { furi_check(file); furi_check(file_path); return file_stream_open(file->stream, file_path, FSAM_READ_WRITE, FSOM_CREATE_ALWAYS); } bool lfrfid_raw_file_open_read(LFRFIDRawFile* file, const char* file_path) { furi_check(file); furi_check(file_path); return file_stream_open(file->stream, file_path, FSAM_READ, FSOM_OPEN_EXISTING); } bool lfrfid_raw_file_write_header( LFRFIDRawFile* file, float frequency, float duty_cycle, uint32_t max_buffer_size) { furi_check(file); LFRFIDRawFileHeader header = { .magic = LFRFID_RAW_FILE_MAGIC, .version = LFRFID_RAW_FILE_VERSION, .frequency = frequency, .duty_cycle = duty_cycle, .max_buffer_size = max_buffer_size}; size_t size = stream_write(file->stream, (uint8_t*)&header, sizeof(LFRFIDRawFileHeader)); return size == sizeof(LFRFIDRawFileHeader); } bool lfrfid_raw_file_write_buffer(LFRFIDRawFile* file, uint8_t* buffer_data, size_t buffer_size) { furi_check(file); furi_check(buffer_data); furi_check(buffer_size); size_t size; size = stream_write(file->stream, (uint8_t*)&buffer_size, sizeof(size_t)); if(size != sizeof(size_t)) return false; size = stream_write(file->stream, buffer_data, buffer_size); if(size != buffer_size) return false; return true; } bool lfrfid_raw_file_read_header(LFRFIDRawFile* file, float* frequency, float* duty_cycle) { furi_check(file); furi_check(frequency); furi_check(duty_cycle); LFRFIDRawFileHeader header; size_t size = stream_read(file->stream, (uint8_t*)&header, sizeof(LFRFIDRawFileHeader)); if(size == sizeof(LFRFIDRawFileHeader)) { if(header.magic == LFRFID_RAW_FILE_MAGIC && header.version == LFRFID_RAW_FILE_VERSION) { *frequency = header.frequency; *duty_cycle = header.duty_cycle; file->max_buffer_size = header.max_buffer_size; file->buffer = malloc(file->max_buffer_size); file->buffer_size = 0; file->buffer_counter = 0; return true; } else { return false; } } else { return false; } } bool lfrfid_raw_file_read_pair( LFRFIDRawFile* file, uint32_t* duration, uint32_t* pulse, bool* pass_end) { furi_check(file); furi_check(duration); furi_check(pulse); size_t length = 0; if(file->buffer_counter >= file->buffer_size) { if(stream_eof(file->stream)) { // rewind stream and pass header stream_seek(file->stream, sizeof(LFRFIDRawFileHeader), StreamOffsetFromStart); if(pass_end) *pass_end = true; } length = stream_read(file->stream, (uint8_t*)&file->buffer_size, sizeof(size_t)); if(length != sizeof(size_t)) { FURI_LOG_E(TAG, "read pair: failed to read size"); return false; } if(file->buffer_size > file->max_buffer_size) { FURI_LOG_E(TAG, "read pair: buffer size is too big"); return false; } length = stream_read(file->stream, file->buffer, file->buffer_size); if(length != file->buffer_size) { FURI_LOG_E(TAG, "read pair: failed to read data"); return false; } file->buffer_counter = 0; } size_t size = 0; bool result = varint_pair_unpack( &file->buffer[file->buffer_counter], (size_t)(file->buffer_size - file->buffer_counter), pulse, duration, &size); if(result) { file->buffer_counter += size; } else { FURI_LOG_E(TAG, "read pair: buffer is too small"); return false; } return true; }
4,737
C
.c
138
28.086957
98
0.643608
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,345
lfrfid_worker.c
DarkFlippers_unleashed-firmware/lib/lfrfid/lfrfid_worker.c
#include "lfrfid_worker_i.h" #include <furi.h> #include <furi_hal.h> typedef enum { LFRFIDEventStopThread = (1 << 0), LFRFIDEventStopMode = (1 << 1), LFRFIDEventRead = (1 << 2), LFRFIDEventWrite = (1 << 3), LFRFIDEventWriteAndSetPass = (1 << 4), LFRFIDEventEmulate = (1 << 5), LFRFIDEventReadRaw = (1 << 6), LFRFIDEventEmulateRaw = (1 << 7), LFRFIDEventAll = (LFRFIDEventStopThread | LFRFIDEventStopMode | LFRFIDEventRead | LFRFIDEventWrite | LFRFIDEventWriteAndSetPass | LFRFIDEventEmulate | LFRFIDEventReadRaw | LFRFIDEventEmulateRaw), } LFRFIDEventType; static int32_t lfrfid_worker_thread(void* thread_context); LFRFIDWorker* lfrfid_worker_alloc(ProtocolDict* dict) { furi_check(dict); LFRFIDWorker* worker = malloc(sizeof(LFRFIDWorker)); worker->mode_index = LFRFIDWorkerIdle; worker->read_cb = NULL; worker->write_cb = NULL; worker->cb_ctx = NULL; worker->raw_filename = NULL; worker->mode_storage = NULL; worker->thread = furi_thread_alloc_ex("LfrfidWorker", 2048, lfrfid_worker_thread, worker); worker->protocols = dict; return worker; } void lfrfid_worker_free(LFRFIDWorker* worker) { furi_check(worker); if(worker->raw_filename) { free(worker->raw_filename); } furi_thread_free(worker->thread); free(worker); } void lfrfid_worker_read_start( LFRFIDWorker* worker, LFRFIDWorkerReadType type, LFRFIDWorkerReadCallback callback, void* context) { furi_check(worker); furi_check(worker->mode_index == LFRFIDWorkerIdle); worker->read_type = type; worker->read_cb = callback; worker->cb_ctx = context; furi_thread_flags_set(furi_thread_get_id(worker->thread), LFRFIDEventRead); } void lfrfid_worker_write_start( LFRFIDWorker* worker, LFRFIDProtocol protocol, LFRFIDWorkerWriteCallback callback, void* context) { furi_check(worker->mode_index == LFRFIDWorkerIdle); worker->protocol = protocol; worker->write_cb = callback; worker->cb_ctx = context; furi_thread_flags_set(furi_thread_get_id(worker->thread), LFRFIDEventWrite); } void lfrfid_worker_write_and_set_pass_start( LFRFIDWorker* worker, LFRFIDProtocol protocol, LFRFIDWorkerWriteCallback callback, void* context) { furi_assert(worker->mode_index == LFRFIDWorkerIdle); worker->protocol = protocol; worker->write_cb = callback; worker->cb_ctx = context; furi_thread_flags_set(furi_thread_get_id(worker->thread), LFRFIDEventWriteAndSetPass); } void lfrfid_worker_emulate_start(LFRFIDWorker* worker, LFRFIDProtocol protocol) { furi_check(worker); furi_check(worker->mode_index == LFRFIDWorkerIdle); worker->protocol = protocol; furi_thread_flags_set(furi_thread_get_id(worker->thread), LFRFIDEventEmulate); } void lfrfid_worker_set_filename(LFRFIDWorker* worker, const char* filename) { if(worker->raw_filename) { free(worker->raw_filename); } worker->raw_filename = strdup(filename); } void lfrfid_worker_read_raw_start( LFRFIDWorker* worker, const char* filename, LFRFIDWorkerReadType type, LFRFIDWorkerReadRawCallback callback, void* context) { furi_check(worker); furi_check(worker->mode_index == LFRFIDWorkerIdle); worker->read_type = type; worker->read_raw_cb = callback; worker->cb_ctx = context; lfrfid_worker_set_filename(worker, filename); furi_thread_flags_set(furi_thread_get_id(worker->thread), LFRFIDEventReadRaw); } void lfrfid_worker_emulate_raw_start( LFRFIDWorker* worker, const char* filename, LFRFIDWorkerEmulateRawCallback callback, void* context) { furi_check(worker); furi_check(worker->mode_index == LFRFIDWorkerIdle); lfrfid_worker_set_filename(worker, filename); worker->emulate_raw_cb = callback; worker->cb_ctx = context; furi_thread_flags_set(furi_thread_get_id(worker->thread), LFRFIDEventEmulateRaw); } void lfrfid_worker_stop(LFRFIDWorker* worker) { furi_check(worker); furi_thread_flags_set(furi_thread_get_id(worker->thread), LFRFIDEventStopMode); } void lfrfid_worker_start_thread(LFRFIDWorker* worker) { furi_check(worker); furi_thread_start(worker->thread); } void lfrfid_worker_stop_thread(LFRFIDWorker* worker) { furi_check(worker); furi_thread_flags_set(furi_thread_get_id(worker->thread), LFRFIDEventStopThread); furi_thread_join(worker->thread); } bool lfrfid_worker_check_for_stop(LFRFIDWorker* worker) { UNUSED(worker); uint32_t flags = furi_thread_flags_get(); return flags & LFRFIDEventStopMode; } size_t lfrfid_worker_dict_get_data_size(LFRFIDWorker* worker, LFRFIDProtocol protocol) { furi_assert(worker->mode_index == LFRFIDWorkerIdle); return protocol_dict_get_data_size(worker->protocols, protocol); } static int32_t lfrfid_worker_thread(void* thread_context) { LFRFIDWorker* worker = thread_context; while(true) { uint32_t flags = furi_thread_flags_wait(LFRFIDEventAll, FuriFlagWaitAny, FuriWaitForever); if(flags != (unsigned)FuriFlagErrorTimeout) { // stop thread if(flags & LFRFIDEventStopThread) break; // switch mode if(flags & LFRFIDEventRead) worker->mode_index = LFRFIDWorkerRead; if(flags & LFRFIDEventWrite) worker->mode_index = LFRFIDWorkerWrite; if(flags & LFRFIDEventWriteAndSetPass) worker->mode_index = LFRFIDWorkerWriteAndSetPass; if(flags & LFRFIDEventEmulate) worker->mode_index = LFRFIDWorkerEmulate; if(flags & LFRFIDEventReadRaw) worker->mode_index = LFRFIDWorkerReadRaw; if(flags & LFRFIDEventEmulateRaw) worker->mode_index = LFRFIDWorkerEmulateRaw; // do mode, if it exists if(lfrfid_worker_modes[worker->mode_index].process) { lfrfid_worker_modes[worker->mode_index].process(worker); } // reset mode worker->mode_index = LFRFIDWorkerIdle; } } return 0; }
6,082
C
.c
158
33.094937
98
0.707151
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,347
protocol_paradox.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_paradox.c
#include <furi.h> #include <toolbox/protocols/protocol.h> #include <lfrfid/tools/fsk_demod.h> #include <lfrfid/tools/fsk_osc.h> #include <bit_lib/bit_lib.h> #include "lfrfid_protocols.h" #define JITTER_TIME (20) #define MIN_TIME (64 - JITTER_TIME) #define MAX_TIME (80 + JITTER_TIME) #define PARADOX_DECODED_DATA_SIZE (6) #define PARADOX_PREAMBLE_LENGTH (8) #define PARADOX_ENCODED_BIT_SIZE (96) #define PARADOX_ENCODED_DATA_SIZE (((PARADOX_ENCODED_BIT_SIZE) / 8) + 1) #define PARADOX_ENCODED_DATA_LAST (PARADOX_ENCODED_DATA_SIZE - 1) typedef struct { FSKDemod* fsk_demod; } ProtocolParadoxDecoder; typedef struct { FSKOsc* fsk_osc; uint8_t encoded_index; } ProtocolParadoxEncoder; typedef struct { ProtocolParadoxDecoder decoder; ProtocolParadoxEncoder encoder; uint8_t encoded_data[PARADOX_ENCODED_DATA_SIZE]; uint8_t data[PARADOX_DECODED_DATA_SIZE]; } ProtocolParadox; ProtocolParadox* protocol_paradox_alloc(void) { ProtocolParadox* protocol = malloc(sizeof(ProtocolParadox)); protocol->decoder.fsk_demod = fsk_demod_alloc(MIN_TIME, 6, MAX_TIME, 5); protocol->encoder.fsk_osc = fsk_osc_alloc(8, 10, 50); return protocol; } void protocol_paradox_free(ProtocolParadox* protocol) { fsk_demod_free(protocol->decoder.fsk_demod); fsk_osc_free(protocol->encoder.fsk_osc); free(protocol); } uint8_t* protocol_paradox_get_data(ProtocolParadox* protocol) { return protocol->data; } void protocol_paradox_decoder_start(ProtocolParadox* protocol) { memset(protocol->encoded_data, 0, PARADOX_ENCODED_DATA_SIZE); } static bool protocol_paradox_can_be_decoded(ProtocolParadox* protocol) { // check preamble if(protocol->encoded_data[0] != 0b00001111 || protocol->encoded_data[PARADOX_ENCODED_DATA_LAST] != 0b00001111) return false; for(uint32_t i = PARADOX_PREAMBLE_LENGTH; i < 96; i += 2) { if(bit_lib_get_bit(protocol->encoded_data, i) == bit_lib_get_bit(protocol->encoded_data, i + 1)) { return false; } } return true; } static void protocol_paradox_decode(uint8_t* encoded_data, uint8_t* decoded_data) { for(uint32_t i = PARADOX_PREAMBLE_LENGTH; i < 96; i += 2) { if(bit_lib_get_bits(encoded_data, i, 2) == 0b01) { bit_lib_push_bit(decoded_data, PARADOX_DECODED_DATA_SIZE, 0); } else if(bit_lib_get_bits(encoded_data, i, 2) == 0b10) { bit_lib_push_bit(decoded_data, PARADOX_DECODED_DATA_SIZE, 1); } } bit_lib_push_bit(decoded_data, PARADOX_DECODED_DATA_SIZE, 0); bit_lib_push_bit(decoded_data, PARADOX_DECODED_DATA_SIZE, 0); bit_lib_push_bit(decoded_data, PARADOX_DECODED_DATA_SIZE, 0); bit_lib_push_bit(decoded_data, PARADOX_DECODED_DATA_SIZE, 0); } bool protocol_paradox_decoder_feed(ProtocolParadox* protocol, bool level, uint32_t duration) { bool value; uint32_t count; fsk_demod_feed(protocol->decoder.fsk_demod, level, duration, &value, &count); if(count > 0) { for(size_t i = 0; i < count; i++) { bit_lib_push_bit(protocol->encoded_data, PARADOX_ENCODED_DATA_SIZE, value); if(protocol_paradox_can_be_decoded(protocol)) { protocol_paradox_decode(protocol->encoded_data, protocol->data); return true; } } } return false; } static void protocol_paradox_encode(const uint8_t* decoded_data, uint8_t* encoded_data) { // preamble bit_lib_set_bits(encoded_data, 0, 0b00001111, 8); for(size_t i = 0; i < 44; i++) { if(bit_lib_get_bit(decoded_data, i)) { bit_lib_set_bits(encoded_data, PARADOX_PREAMBLE_LENGTH + i * 2, 0b10, 2); } else { bit_lib_set_bits(encoded_data, PARADOX_PREAMBLE_LENGTH + i * 2, 0b01, 2); } } } bool protocol_paradox_encoder_start(ProtocolParadox* protocol) { protocol_paradox_encode(protocol->data, (uint8_t*)protocol->encoded_data); protocol->encoder.encoded_index = 0; fsk_osc_reset(protocol->encoder.fsk_osc); return true; } LevelDuration protocol_paradox_encoder_yield(ProtocolParadox* protocol) { bool level; uint32_t duration; bool bit = bit_lib_get_bit(protocol->encoded_data, protocol->encoder.encoded_index); bool advance = fsk_osc_next_half(protocol->encoder.fsk_osc, bit, &level, &duration); if(advance) { bit_lib_increment_index(protocol->encoder.encoded_index, PARADOX_ENCODED_BIT_SIZE); } return level_duration_make(level, duration); } static uint8_t protocol_paradox_calculate_checksum(uint8_t fc, uint16_t card_id) { uint8_t card_hi = (card_id >> 8) & 0xff; uint8_t card_lo = card_id & 0xff; uint8_t arr[5] = {0, 0, fc, card_hi, card_lo}; uint8_t manchester[9]; bit_lib_push_bit(manchester, 9, false); bit_lib_push_bit(manchester, 9, false); bit_lib_push_bit(manchester, 9, false); bit_lib_push_bit(manchester, 9, false); for(uint8_t i = 6; i < 40; i += 1) { if(bit_lib_get_bit(arr, i) == 0b1) { bit_lib_push_bit(manchester, 9, true); bit_lib_push_bit(manchester, 9, false); } else { bit_lib_push_bit(manchester, 9, false); bit_lib_push_bit(manchester, 9, true); } } uint8_t output = bit_lib_crc8(manchester, 9, 0x31, 0x00, true, true, 0x06); return output; } void protocol_paradox_render_data(ProtocolParadox* protocol, FuriString* result) { uint8_t* decoded_data = protocol->data; uint8_t fc = bit_lib_get_bits(decoded_data, 10, 8); uint16_t card_id = bit_lib_get_bits_16(decoded_data, 18, 16); uint8_t card_crc = bit_lib_get_bits_16(decoded_data, 34, 8); uint8_t calc_crc = protocol_paradox_calculate_checksum(fc, card_id); furi_string_printf( result, "FC: %hhu\n" "Card: %hu\n" "CRC: %hhu\n" "Calc CRC: %hhu", fc, card_id, card_crc, calc_crc); if(card_crc != calc_crc) { furi_string_cat(result, "\nCRC Mismatch, Invalid Card!"); } } void protocol_paradox_render_brief_data(ProtocolParadox* protocol, FuriString* result) { uint8_t* decoded_data = protocol->data; uint8_t fc = bit_lib_get_bits(decoded_data, 10, 8); uint16_t card_id = bit_lib_get_bits_16(decoded_data, 18, 16); uint8_t card_crc = bit_lib_get_bits_16(decoded_data, 34, 8); uint8_t calc_crc = protocol_paradox_calculate_checksum(fc, card_id); furi_string_printf(result, "FC: %hhu; Card: %hu", fc, card_id); if(calc_crc != card_crc) { furi_string_cat(result, "\nCRC Mismatch, Invalid Card!"); } } bool protocol_paradox_write_data(ProtocolParadox* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; // Correct protocol data by redecoding protocol_paradox_encode(protocol->data, (uint8_t*)protocol->encoded_data); protocol_paradox_decode(protocol->encoded_data, protocol->data); protocol_paradox_encode(protocol->data, (uint8_t*)protocol->encoded_data); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = LFRFID_T5577_MODULATION_FSK2a | LFRFID_T5577_BITRATE_RF_50 | (3 << LFRFID_T5577_MAXBLOCK_SHIFT); request->t5577.block[1] = bit_lib_get_bits_32(protocol->encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->encoded_data, 32, 32); request->t5577.block[3] = bit_lib_get_bits_32(protocol->encoded_data, 64, 32); request->t5577.blocks_to_write = 4; result = true; } return result; } const ProtocolBase protocol_paradox = { .name = "Paradox", .manufacturer = "Paradox", .data_size = PARADOX_DECODED_DATA_SIZE, .features = LFRFIDFeatureASK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_paradox_alloc, .free = (ProtocolFree)protocol_paradox_free, .get_data = (ProtocolGetData)protocol_paradox_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_paradox_decoder_start, .feed = (ProtocolDecoderFeed)protocol_paradox_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_paradox_encoder_start, .yield = (ProtocolEncoderYield)protocol_paradox_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_paradox_render_data, .render_brief_data = (ProtocolRenderData)protocol_paradox_render_brief_data, .write_data = (ProtocolWriteData)protocol_paradox_write_data, };
8,601
C
.c
205
36.078049
94
0.668223
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,348
protocol_awid.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_awid.c
#include <furi.h> #include <toolbox/protocols/protocol.h> #include <lfrfid/tools/fsk_demod.h> #include <lfrfid/tools/fsk_osc.h> #include <bit_lib/bit_lib.h> #include "lfrfid_protocols.h" #define JITTER_TIME (20) #define MIN_TIME (64 - JITTER_TIME) #define MAX_TIME (80 + JITTER_TIME) #define AWID_DECODED_DATA_SIZE (9) #define AWID_ENCODED_BIT_SIZE (96) #define AWID_ENCODED_DATA_SIZE (((AWID_ENCODED_BIT_SIZE) / 8) + 1) #define AWID_ENCODED_DATA_LAST (AWID_ENCODED_DATA_SIZE - 1) typedef struct { FSKDemod* fsk_demod; } ProtocolAwidDecoder; typedef struct { FSKOsc* fsk_osc; uint8_t encoded_index; } ProtocolAwidEncoder; typedef struct { ProtocolAwidDecoder decoder; ProtocolAwidEncoder encoder; uint8_t encoded_data[AWID_ENCODED_DATA_SIZE]; uint8_t data[AWID_DECODED_DATA_SIZE]; } ProtocolAwid; ProtocolAwid* protocol_awid_alloc(void) { ProtocolAwid* protocol = malloc(sizeof(ProtocolAwid)); protocol->decoder.fsk_demod = fsk_demod_alloc(MIN_TIME, 6, MAX_TIME, 5); protocol->encoder.fsk_osc = fsk_osc_alloc(8, 10, 50); return protocol; } void protocol_awid_free(ProtocolAwid* protocol) { fsk_demod_free(protocol->decoder.fsk_demod); fsk_osc_free(protocol->encoder.fsk_osc); free(protocol); } uint8_t* protocol_awid_get_data(ProtocolAwid* protocol) { return protocol->data; } void protocol_awid_decoder_start(ProtocolAwid* protocol) { memset(protocol->encoded_data, 0, AWID_ENCODED_DATA_SIZE); } static bool protocol_awid_can_be_decoded(uint8_t* data) { bool result = false; // Index map // 0 10 20 30 40 50 60 // | | | | | | | // 01234567 890 1 234 5 678 9 012 3 456 7 890 1 234 5 678 9 012 3 456 7 890 1 234 5 678 9 012 3 - to 96 // ----------------------------------------------------------------------------- // 00000001 000 1 110 1 101 1 011 1 101 1 010 0 000 1 000 1 010 0 001 0 110 1 100 0 000 1 000 1 // preamble bbb o bbb o bbw o fff o fff o ffc o ccc o ccc o ccc o ccc o ccc o wxx o xxx o xxx o - to 96 // |---26 bit---| |-----117----||-------------142-------------| // b = format bit len, o = odd parity of last 3 bits // f = facility code, c = card number // w = wiegand parity // (26 bit format shown) do { // check preamble and spacing if(data[0] != 0b00000001 || data[AWID_ENCODED_DATA_LAST] != 0b00000001) break; // check odd parity for every 4 bits starting from the second byte bool parity_error = bit_lib_test_parity(data, 8, 88, BitLibParityOdd, 4); if(parity_error) break; bit_lib_remove_bit_every_nth(data, 8, 88, 4); // Avoid detection for invalid formats uint8_t len = bit_lib_get_bits(data, 8, 8); if(len != 26 && len != 50 && len != 37 && len != 34 && len != 36) break; result = true; } while(false); return result; } static void protocol_awid_decode(uint8_t* encoded_data, uint8_t* decoded_data) { bit_lib_copy_bits(decoded_data, 0, 66, encoded_data, 8); } bool protocol_awid_decoder_feed(ProtocolAwid* protocol, bool level, uint32_t duration) { bool value; uint32_t count; bool result = false; fsk_demod_feed(protocol->decoder.fsk_demod, level, duration, &value, &count); if(count > 0) { for(size_t i = 0; i < count; i++) { bit_lib_push_bit(protocol->encoded_data, AWID_ENCODED_DATA_SIZE, value); if(protocol_awid_can_be_decoded(protocol->encoded_data)) { protocol_awid_decode(protocol->encoded_data, protocol->data); result = true; break; } } } return result; } static void protocol_awid_encode(const uint8_t* decoded_data, uint8_t* encoded_data) { memset(encoded_data, 0, AWID_ENCODED_DATA_SIZE); // preamble bit_lib_set_bits(encoded_data, 0, 0b00000001, 8); for(size_t i = 0; i < 88 / 4; i++) { uint8_t value = bit_lib_get_bits(decoded_data, i * 3, 3) << 1; value |= bit_lib_test_parity_32(value, BitLibParityOdd); bit_lib_set_bits(encoded_data, 8 + i * 4, value, 4); } } bool protocol_awid_encoder_start(ProtocolAwid* protocol) { protocol_awid_encode(protocol->data, (uint8_t*)protocol->encoded_data); protocol->encoder.encoded_index = 0; fsk_osc_reset(protocol->encoder.fsk_osc); return true; } LevelDuration protocol_awid_encoder_yield(ProtocolAwid* protocol) { bool level; uint32_t duration; bool bit = bit_lib_get_bit(protocol->encoded_data, protocol->encoder.encoded_index); bool advance = fsk_osc_next_half(protocol->encoder.fsk_osc, bit, &level, &duration); if(advance) { bit_lib_increment_index(protocol->encoder.encoded_index, AWID_ENCODED_BIT_SIZE); } return level_duration_make(level, duration); } void protocol_awid_render_data(ProtocolAwid* protocol, FuriString* result) { // Index map // 0 10 20 30 40 50 60 // | | | | | | | // 01234567 8 90123456 7890123456789012 3 456789012345678901234567890123456 // ------------------------------------------------------------------------ // 00011010 1 01110101 0000000010001110 1 000000000000000000000000000000000 // bbbbbbbb w ffffffff cccccccccccccccc w xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx // |26 bit| |-117--| |-----142------| // b = format bit len, o = odd parity of last 3 bits // f = facility code, c = card number // w = wiegand parity // (26 bit format shown) uint8_t* decoded_data = protocol->data; uint8_t format_length = decoded_data[0]; furi_string_printf(result, "Format: %hhu\n", format_length); if(format_length == 26) { uint8_t facility; bit_lib_copy_bits(&facility, 0, 8, decoded_data, 9); uint16_t card_id; bit_lib_copy_bits((uint8_t*)&card_id, 8, 8, decoded_data, 17); bit_lib_copy_bits((uint8_t*)&card_id, 0, 8, decoded_data, 25); furi_string_cat_printf( result, "FC: %hhu\n" "Card: %hu", facility, card_id); } else { // print 66 bits as hex furi_string_cat_printf(result, "Data: "); for(size_t i = 0; i < AWID_DECODED_DATA_SIZE; i++) { furi_string_cat_printf(result, "%02hhX", decoded_data[i]); } } } void protocol_awid_render_brief_data(ProtocolAwid* protocol, FuriString* result) { uint8_t* decoded_data = protocol->data; uint8_t format_length = decoded_data[0]; furi_string_printf(result, "Format: %hhu", format_length); if(format_length == 26) { uint8_t facility; bit_lib_copy_bits(&facility, 0, 8, decoded_data, 9); uint16_t card_id; bit_lib_copy_bits((uint8_t*)&card_id, 8, 8, decoded_data, 17); bit_lib_copy_bits((uint8_t*)&card_id, 0, 8, decoded_data, 25); furi_string_cat_printf( result, "; FC: %hhu\n" "Card: %hu", facility, card_id); } else { furi_string_cat(result, "\nData: Unknown"); } } bool protocol_awid_write_data(ProtocolAwid* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; // Fix incorrect length byte if(protocol->data[0] != 26 && protocol->data[0] != 50 && protocol->data[0] != 37 && protocol->data[0] != 34 && protocol->data[0] != 36) { protocol->data[0] = 26; } // Correct protocol data by redecoding protocol_awid_encode(protocol->data, (uint8_t*)protocol->encoded_data); bit_lib_remove_bit_every_nth((uint8_t*)protocol->encoded_data, 8, 88, 4); protocol_awid_decode(protocol->encoded_data, protocol->data); protocol_awid_encode(protocol->data, (uint8_t*)protocol->encoded_data); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = LFRFID_T5577_MODULATION_FSK2a | LFRFID_T5577_BITRATE_RF_50 | (3 << LFRFID_T5577_MAXBLOCK_SHIFT); request->t5577.block[1] = bit_lib_get_bits_32(protocol->encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->encoded_data, 32, 32); request->t5577.block[3] = bit_lib_get_bits_32(protocol->encoded_data, 64, 32); request->t5577.blocks_to_write = 4; result = true; } return result; } const ProtocolBase protocol_awid = { .name = "AWID", .manufacturer = "AWID", .data_size = AWID_DECODED_DATA_SIZE, .features = LFRFIDFeatureASK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_awid_alloc, .free = (ProtocolFree)protocol_awid_free, .get_data = (ProtocolGetData)protocol_awid_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_awid_decoder_start, .feed = (ProtocolDecoderFeed)protocol_awid_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_awid_encoder_start, .yield = (ProtocolEncoderYield)protocol_awid_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_awid_render_data, .render_brief_data = (ProtocolRenderData)protocol_awid_render_brief_data, .write_data = (ProtocolWriteData)protocol_awid_write_data, };
9,510
C
.c
220
37.104545
107
0.613479
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,350
protocol_h10301.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_h10301.c
#include <furi.h> #include <toolbox/protocols/protocol.h> #include <lfrfid/tools/fsk_demod.h> #include <lfrfid/tools/fsk_osc.h> #include "lfrfid_protocols.h" #define JITTER_TIME (20) #define MIN_TIME (64 - JITTER_TIME) #define MAX_TIME (80 + JITTER_TIME) #define H10301_DECODED_DATA_SIZE (3) #define H10301_ENCODED_DATA_SIZE_U32 (3) #define H10301_ENCODED_DATA_SIZE (sizeof(uint32_t) * H10301_ENCODED_DATA_SIZE_U32) #define H10301_BIT_SIZE (sizeof(uint32_t) * 8) #define H10301_BIT_MAX_SIZE (H10301_BIT_SIZE * H10301_DECODED_DATA_SIZE) typedef struct { FSKDemod* fsk_demod; } ProtocolH10301Decoder; typedef struct { FSKOsc* fsk_osc; uint8_t encoded_index; uint32_t pulse; } ProtocolH10301Encoder; typedef struct { ProtocolH10301Decoder decoder; ProtocolH10301Encoder encoder; uint32_t encoded_data[H10301_ENCODED_DATA_SIZE_U32]; uint8_t data[H10301_DECODED_DATA_SIZE]; } ProtocolH10301; ProtocolH10301* protocol_h10301_alloc(void) { ProtocolH10301* protocol = malloc(sizeof(ProtocolH10301)); protocol->decoder.fsk_demod = fsk_demod_alloc(MIN_TIME, 6, MAX_TIME, 5); protocol->encoder.fsk_osc = fsk_osc_alloc(8, 10, 50); return protocol; } void protocol_h10301_free(ProtocolH10301* protocol) { fsk_demod_free(protocol->decoder.fsk_demod); fsk_osc_free(protocol->encoder.fsk_osc); free(protocol); } uint8_t* protocol_h10301_get_data(ProtocolH10301* protocol) { return protocol->data; } void protocol_h10301_decoder_start(ProtocolH10301* protocol) { memset(protocol->encoded_data, 0, sizeof(uint32_t) * 3); } static void protocol_h10301_decoder_store_data(ProtocolH10301* protocol, bool data) { protocol->encoded_data[0] = (protocol->encoded_data[0] << 1) | ((protocol->encoded_data[1] >> 31) & 1); protocol->encoded_data[1] = (protocol->encoded_data[1] << 1) | ((protocol->encoded_data[2] >> 31) & 1); protocol->encoded_data[2] = (protocol->encoded_data[2] << 1) | data; } static bool protocol_h10301_can_be_decoded(const uint32_t* card_data) { const uint8_t* encoded_data = (const uint8_t*)card_data; // packet preamble // raw data if(*(encoded_data + 3) != 0x1D) { return false; } // encoded company/oem // coded with 01 = 0, 10 = 1 transitions // stored in word 0 if((*card_data >> 10 & 0x3FFF) != 0x1556) { return false; } // encoded format/length // coded with 01 = 0, 10 = 1 transitions // stored in word 0 and word 1 if((((*card_data & 0x3FF) << 12) | ((*(card_data + 1) >> 20) & 0xFFF)) != 0x155556) { return false; } // data decoding uint32_t result = 0; // decode from word 1 // coded with 01 = 0, 10 = 1 transitions for(int8_t i = 9; i >= 0; i--) { switch((*(card_data + 1) >> (2 * i)) & 0b11) { case 0b01: result = (result << 1) | 0; break; case 0b10: result = (result << 1) | 1; break; default: return false; break; } } // decode from word 2 // coded with 01 = 0, 10 = 1 transitions for(int8_t i = 15; i >= 0; i--) { switch((*(card_data + 2) >> (2 * i)) & 0b11) { case 0b01: result = (result << 1) | 0; break; case 0b10: result = (result << 1) | 1; break; default: return false; break; } } // trailing parity (odd) test uint8_t parity_sum = 0; for(int8_t i = 0; i < 13; i++) { if(((result >> i) & 1) == 1) { parity_sum++; } } if((parity_sum % 2) != 1) { return false; } // leading parity (even) test parity_sum = 0; for(int8_t i = 13; i < 26; i++) { if(((result >> i) & 1) == 1) { parity_sum++; } } if((parity_sum % 2) == 1) { return false; } return true; } static void protocol_h10301_decode(const uint32_t* card_data, uint8_t* decoded_data) { // data decoding uint32_t result = 0; // decode from word 1 // coded with 01 = 0, 10 = 1 transitions for(int8_t i = 9; i >= 0; i--) { switch((*(card_data + 1) >> (2 * i)) & 0b11) { case 0b01: result = (result << 1) | 0; break; case 0b10: result = (result << 1) | 1; break; default: break; } } // decode from word 2 // coded with 01 = 0, 10 = 1 transitions for(int8_t i = 15; i >= 0; i--) { switch((*(card_data + 2) >> (2 * i)) & 0b11) { case 0b01: result = (result << 1) | 0; break; case 0b10: result = (result << 1) | 1; break; default: break; } } uint8_t data[H10301_DECODED_DATA_SIZE] = { (uint8_t)(result >> 17), (uint8_t)(result >> 9), (uint8_t)(result >> 1)}; memcpy(decoded_data, &data, H10301_DECODED_DATA_SIZE); } bool protocol_h10301_decoder_feed(ProtocolH10301* protocol, bool level, uint32_t duration) { bool value; uint32_t count; bool result = false; fsk_demod_feed(protocol->decoder.fsk_demod, level, duration, &value, &count); if(count > 0) { for(size_t i = 0; i < count; i++) { protocol_h10301_decoder_store_data(protocol, value); if(protocol_h10301_can_be_decoded(protocol->encoded_data)) { protocol_h10301_decode(protocol->encoded_data, protocol->data); result = true; break; } } } return result; } static void protocol_h10301_write_raw_bit(bool bit, uint8_t position, uint32_t* card_data) { if(bit) { card_data[position / H10301_BIT_SIZE] |= 1UL << (H10301_BIT_SIZE - (position % H10301_BIT_SIZE) - 1); } else { card_data[position / H10301_BIT_SIZE] &= ~(1UL << (H10301_BIT_SIZE - (position % H10301_BIT_SIZE) - 1)); } } static void protocol_h10301_write_bit(bool bit, uint8_t position, uint32_t* card_data) { protocol_h10301_write_raw_bit(bit, position + 0, card_data); protocol_h10301_write_raw_bit(!bit, position + 1, card_data); } void protocol_h10301_encode(const uint8_t* decoded_data, uint8_t* encoded_data) { uint32_t card_data[H10301_DECODED_DATA_SIZE] = {0, 0, 0}; uint32_t fc_cn = (decoded_data[0] << 16) | (decoded_data[1] << 8) | decoded_data[2]; // even parity sum calculation (high 12 bits of data) uint8_t even_parity_sum = 0; for(int8_t i = 12; i < 24; i++) { if(((fc_cn >> i) & 1) == 1) { even_parity_sum++; } } // odd parity sum calculation (low 12 bits of data) uint8_t odd_parity_sum = 1; for(int8_t i = 0; i < 12; i++) { if(((fc_cn >> i) & 1) == 1) { odd_parity_sum++; } } // 0x1D preamble protocol_h10301_write_raw_bit(0, 0, card_data); protocol_h10301_write_raw_bit(0, 1, card_data); protocol_h10301_write_raw_bit(0, 2, card_data); protocol_h10301_write_raw_bit(1, 3, card_data); protocol_h10301_write_raw_bit(1, 4, card_data); protocol_h10301_write_raw_bit(1, 5, card_data); protocol_h10301_write_raw_bit(0, 6, card_data); protocol_h10301_write_raw_bit(1, 7, card_data); // company / OEM code 1 protocol_h10301_write_bit(0, 8, card_data); protocol_h10301_write_bit(0, 10, card_data); protocol_h10301_write_bit(0, 12, card_data); protocol_h10301_write_bit(0, 14, card_data); protocol_h10301_write_bit(0, 16, card_data); protocol_h10301_write_bit(0, 18, card_data); protocol_h10301_write_bit(1, 20, card_data); // card format / length 1 protocol_h10301_write_bit(0, 22, card_data); protocol_h10301_write_bit(0, 24, card_data); protocol_h10301_write_bit(0, 26, card_data); protocol_h10301_write_bit(0, 28, card_data); protocol_h10301_write_bit(0, 30, card_data); protocol_h10301_write_bit(0, 32, card_data); protocol_h10301_write_bit(0, 34, card_data); protocol_h10301_write_bit(0, 36, card_data); protocol_h10301_write_bit(0, 38, card_data); protocol_h10301_write_bit(0, 40, card_data); protocol_h10301_write_bit(1, 42, card_data); // even parity bit protocol_h10301_write_bit((even_parity_sum % 2), 44, card_data); // data for(uint8_t i = 0; i < 24; i++) { protocol_h10301_write_bit((fc_cn >> (23 - i)) & 1, 46 + (i * 2), card_data); } // odd parity bit protocol_h10301_write_bit((odd_parity_sum % 2), 94, card_data); memcpy(encoded_data, &card_data, H10301_ENCODED_DATA_SIZE); } bool protocol_h10301_encoder_start(ProtocolH10301* protocol) { protocol_h10301_encode(protocol->data, (uint8_t*)protocol->encoded_data); protocol->encoder.encoded_index = 0; protocol->encoder.pulse = 0; return true; } LevelDuration protocol_h10301_encoder_yield(ProtocolH10301* protocol) { bool level = 0; uint32_t duration = 0; // if pulse is zero, we need to output high, otherwise we need to output low if(protocol->encoder.pulse == 0) { // get bit uint8_t bit = (protocol->encoded_data[protocol->encoder.encoded_index / H10301_BIT_SIZE] >> ((H10301_BIT_SIZE - 1) - (protocol->encoder.encoded_index % H10301_BIT_SIZE))) & 1; // get pulse from oscillator bool advance = fsk_osc_next(protocol->encoder.fsk_osc, bit, &duration); if(advance) { protocol->encoder.encoded_index++; if(protocol->encoder.encoded_index >= (H10301_BIT_MAX_SIZE)) { protocol->encoder.encoded_index = 0; } } // duration diveded by 2 because we need to output high and low duration = duration / 2; protocol->encoder.pulse = duration; level = true; } else { // output low half and reset pulse duration = protocol->encoder.pulse; protocol->encoder.pulse = 0; level = false; } return level_duration_make(level, duration); } bool protocol_h10301_write_data(ProtocolH10301* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; // Correct protocol data by redecoding protocol_h10301_encoder_start(protocol); protocol_h10301_decode(protocol->encoded_data, protocol->data); protocol_h10301_encoder_start(protocol); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = LFRFID_T5577_MODULATION_FSK2a | LFRFID_T5577_BITRATE_RF_50 | (3 << LFRFID_T5577_MAXBLOCK_SHIFT); request->t5577.block[1] = protocol->encoded_data[0]; request->t5577.block[2] = protocol->encoded_data[1]; request->t5577.block[3] = protocol->encoded_data[2]; request->t5577.blocks_to_write = 4; result = true; } return result; } void protocol_h10301_render_data(ProtocolH10301* protocol, FuriString* result) { uint8_t* data = protocol->data; furi_string_printf( result, "FC: %hhu\n" "Card: %hu", data[0], (uint16_t)((data[1] << 8) | (data[2]))); } const ProtocolBase protocol_h10301 = { .name = "H10301", .manufacturer = "HID", .data_size = H10301_DECODED_DATA_SIZE, .features = LFRFIDFeatureASK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_h10301_alloc, .free = (ProtocolFree)protocol_h10301_free, .get_data = (ProtocolGetData)protocol_h10301_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_h10301_decoder_start, .feed = (ProtocolDecoderFeed)protocol_h10301_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_h10301_encoder_start, .yield = (ProtocolEncoderYield)protocol_h10301_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_h10301_render_data, .render_brief_data = (ProtocolRenderData)protocol_h10301_render_data, .write_data = (ProtocolWriteData)protocol_h10301_write_data, };
12,252
C
.c
331
30.232628
94
0.604451
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,351
protocol_gproxii.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_gproxii.c
#include <furi.h> #include "toolbox/level_duration.h" #include "protocol_gproxii.h" #include <toolbox/manchester_decoder.h> #include <bit_lib/bit_lib.h> #include "lfrfid_protocols.h" #define GPROXII_PREAMBLE_BIT_SIZE (6) #define GPROXII_ENCODED_BIT_SIZE (90) #define GPROXII_ENCODED_BYTE_FULL_SIZE \ (((GPROXII_PREAMBLE_BIT_SIZE + GPROXII_ENCODED_BIT_SIZE) / 8)) #define GPROXII_DATA_SIZE (12) #define GPROXII_SHORT_TIME (256) #define GPROXII_LONG_TIME (512) #define GPROXII_JITTER_TIME (120) #define GPROXII_SHORT_TIME_LOW (GPROXII_SHORT_TIME - GPROXII_JITTER_TIME) #define GPROXII_SHORT_TIME_HIGH (GPROXII_SHORT_TIME + GPROXII_JITTER_TIME) #define GPROXII_LONG_TIME_LOW (GPROXII_LONG_TIME - GPROXII_JITTER_TIME) #define GPROXII_LONG_TIME_HIGH (GPROXII_LONG_TIME + GPROXII_JITTER_TIME) typedef struct { bool last_short; bool last_level; size_t encoded_index; uint8_t decoded_data[GPROXII_ENCODED_BYTE_FULL_SIZE]; uint8_t data[GPROXII_ENCODED_BYTE_FULL_SIZE]; } ProtocolGProxII; ProtocolGProxII* protocol_gproxii_alloc(void) { ProtocolGProxII* protocol = malloc(sizeof(ProtocolGProxII)); return protocol; } void protocol_gproxii_free(ProtocolGProxII* protocol) { free(protocol); } uint8_t* protocol_gproxii_get_data(ProtocolGProxII* protocol) { return protocol->data; } bool wiegand_check(uint64_t fc_and_card, bool even_parity, bool odd_parity, int card_len) { uint8_t even_parity_sum = 0; uint8_t odd_parity_sum = 1; switch(card_len) { case 26: for(int8_t i = 12; i < 24; i++) { if(((fc_and_card >> i) & 1) == 1) { even_parity_sum++; } } if(even_parity_sum % 2 != even_parity) return false; for(int8_t i = 0; i < 12; i++) { if(((fc_and_card >> i) & 1) == 1) { odd_parity_sum++; } } if(odd_parity_sum % 2 != odd_parity) return false; break; case 36: for(int8_t i = 17; i < 34; i++) { if(((fc_and_card >> i) & 1) == 1) { even_parity_sum++; } } if(even_parity_sum % 2 != even_parity) return false; for(int8_t i = 0; i < 17; i++) { if(((fc_and_card >> i) & 1) == 1) { odd_parity_sum++; } } if(odd_parity_sum % 2 != odd_parity) return false; break; default: furi_crash(); } return true; } void protocol_gproxii_decoder_start(ProtocolGProxII* protocol) { memset(protocol->data, 0, GPROXII_ENCODED_BYTE_FULL_SIZE); memset(protocol->decoded_data, 0, GPROXII_DATA_SIZE); protocol->last_short = false; } static bool protocol_gproxii_can_be_decoded(ProtocolGProxII* protocol) { // 96 bit with 5 bit zero parity // 0 10 20 30 40 50 60 70 80 90 // | | | | | | | | | | // 012345 6789 0 1234 5 6789 0 1234 5 6789 0 1234 5 6789 0 1234 5 6789 0 1234 5 6789 0 1234 5 6789 0 1234 5 6789 0 1234 5 6789 0 1234 5 // ------------------------------------------------------------------------------------------------------------------------------------ // 111110 0000 0 1001 0 1101 0 1111 0 1000 0 1001 0 0000 0 1001 0 0000 0 1001 0 0000 0 1001 0 0000 0 1001 0 0000 0 1000 0 0000 0 1001 0 // Remove header and reverse bytes on the remaining 72 bits // // 0 10 20 30 40 50 60 70 // | | | | | | | | // 01234567 89012345 67890123 45678901 23456789 01234567 89012345 67890123 45678901 // -------------------------------------------------------------------------------- // 00001001 11011111 10001001 00001001 00001001 00001001 00001001 00001000 00001001 - Without parity // 10010000 11111011 10010001 10010000 10010000 10010000 10010000 00010000 10010000 - Reversed // 10010000 01101011 00000001 00000000 00000000 00000000 00000000 10000000 00000000 - XOR all bytes from 1 using byte 0 // 72 Bit Guardall/Verex/Chubb GProx II 26 bit key with 16 bit profile // 0 10 20 30 40 50 60 70 // | | | | | | | | // 01234567 890123 45 6789012345678901 2 34567890 1234567890123456 7 89012345678901 // -------------------------------------------------------------------------------- // XORVALUE LLLLLL DD PPPPPPPPPPPPPPPP E FFFFFFFF CCCCCCCCCCCCCCCC O UUUUUUUUUUUUUU // 10010000 011010 11 0000000100000000 0 00000000 0000000000000001 0 00000000000000 - Profile: 256 FC: 0 Card: 1 // 72 Bit Guardall/Verex/Chubb GProx II 36 bit key with 16 bit profile // 0 10 20 30 40 50 60 70 // | | | | | | | | // 01234567 890123 45 67890123 45678901 2 34567890123456 78901234567890123456 7 8901 // -------------------------------------------------------------------------------- // XORVALUE LLLLLL DD PPPPPPPP PPPPPPPP E UUUUUUFFFFFFFF UUUUCCCCCCCCCCCCCCCC O UUUU // 10111000 100100 10 00000001 00000000 0 00000000010100 00001000100010111000 1 0000 - Profile: 256 FC: 20 Card: 35000 // X = XOR Key, L = Message length, D = 2 bit check digits, P = Profile, E = Wiegand leading even parity // F = Faclity code, C = Card number, O = Wiegand trailing odd parity, U = Unused bits // Check 6 bits preamble 111110 if(bit_lib_get_bits(protocol->data, 0, 6) != 0b111110) return false; // Check always 0 parity on every 5th bit after preamble if(!bit_lib_test_parity(protocol->data, 6, GPROXII_ENCODED_BIT_SIZE, BitLibParityAlways0, 5)) { return false; } // Start GProx II decode bit_lib_copy_bits(protocol->decoded_data, 0, GPROXII_ENCODED_BIT_SIZE, protocol->data, 6); // Remove parity bit_lib_remove_bit_every_nth(protocol->decoded_data, 0, GPROXII_ENCODED_BIT_SIZE, 5); // Reverse bytes for(int i = 0; i < 9; i++) { protocol->decoded_data[i] = bit_lib_reverse_8_fast(protocol->decoded_data[i]); } // DeXOR from byte 1 using byte 0 for(int i = 1; i < 9; i++) { protocol->decoded_data[i] = protocol->decoded_data[0] ^ protocol->decoded_data[i]; } // Check card length is either 26 or 36 int card_len = bit_lib_get_bits(protocol->decoded_data, 8, 6); // wiegand parity if(card_len == 26) { uint64_t fc_and_card = bit_lib_get_bits_64(protocol->decoded_data, 33, 24); bool even_parity = bit_lib_get_bits(protocol->decoded_data, 32, 1); bool odd_parity = bit_lib_get_bits(protocol->decoded_data, 57, 1); if(!wiegand_check(fc_and_card, even_parity, odd_parity, card_len)) return false; } else if(card_len == 36) { uint64_t fc_and_card = bit_lib_get_bits_64(protocol->decoded_data, 33, 34); uint8_t even_parity = bit_lib_get_bits(protocol->decoded_data, 32, 1); uint8_t odd_parity = bit_lib_get_bits(protocol->decoded_data, 67, 1); if(!wiegand_check(fc_and_card, even_parity, odd_parity, card_len)) return false; } else { return false; // If we don't get a 26 or 36 it's not a known card type } return true; } bool protocol_gproxii_decoder_feed(ProtocolGProxII* protocol, bool level, uint32_t duration) { UNUSED(level); bool pushed = false; // Bi-Phase Manchester decoding inverse. Short = 1, Long = 0 if(duration >= GPROXII_SHORT_TIME_LOW && duration <= GPROXII_SHORT_TIME_HIGH) { if(protocol->last_short == false) { protocol->last_short = true; } else { pushed = true; bit_lib_push_bit(protocol->data, GPROXII_ENCODED_BYTE_FULL_SIZE, true); protocol->last_short = false; } } else if(duration >= GPROXII_LONG_TIME_LOW && duration <= GPROXII_LONG_TIME_HIGH) { if(protocol->last_short == false) { pushed = true; bit_lib_push_bit(protocol->data, GPROXII_ENCODED_BYTE_FULL_SIZE, false); } else { // reset protocol->last_short = false; } } else { // reset protocol->last_short = false; } if(pushed && protocol_gproxii_can_be_decoded(protocol)) { return true; } return false; } bool protocol_gproxii_encoder_start(ProtocolGProxII* protocol) { protocol->encoded_index = 0; protocol->last_short = false; protocol->last_level = false; return true; } LevelDuration protocol_gproxii_encoder_yield(ProtocolGProxII* protocol) { uint32_t duration; protocol->last_level = !protocol->last_level; bool bit = bit_lib_get_bit(protocol->data, protocol->encoded_index); // Bi-Phase Manchester encoder inverted if(bit) { // two short pulses for 1 duration = GPROXII_SHORT_TIME / 8; if(protocol->last_short) { bit_lib_increment_index(protocol->encoded_index, 96); protocol->last_short = false; } else { protocol->last_short = true; } } else { // one long pulse for 0 duration = GPROXII_LONG_TIME / 8; bit_lib_increment_index(protocol->encoded_index, 96); } return level_duration_make(protocol->last_level, duration); } void protocol_gproxii_render_data(ProtocolGProxII* protocol, FuriString* result) { protocol_gproxii_can_be_decoded(protocol); int xor_code = bit_lib_get_bits(protocol->decoded_data, 0, 8); int card_len = bit_lib_get_bits(protocol->decoded_data, 8, 6); int crc_code = bit_lib_get_bits(protocol->decoded_data, 14, 2); if(card_len == 26) { // 26 Bit card // Print FC, Card and Length furi_string_cat_printf( result, "FC: %u Card: %u LEN: %hhu\n", bit_lib_get_bits(protocol->decoded_data, 33, 8), bit_lib_get_bits_16(protocol->decoded_data, 41, 16), card_len); // XOR Key, CRC and Profile furi_string_cat_printf( result, "XOR: %hhu CRC: %hhu P: %04hX", xor_code, crc_code, bit_lib_get_bits_16(protocol->decoded_data, 16, 16)); } else if(card_len == 36) { // 36 Bit card // Print FC, Card and Length furi_string_cat_printf( result, "FC: %u Card: %u LEN: %hhu\n", bit_lib_get_bits_16(protocol->decoded_data, 33, 14), bit_lib_get_bits_16(protocol->decoded_data, 51, 16), card_len); // XOR Key, CRC and Profile furi_string_cat_printf( result, "XOR: %hhu CRC: %hhu P: %04hX", xor_code, crc_code, bit_lib_get_bits_16(protocol->decoded_data, 16, 16)); } else { furi_string_cat_printf(result, "Read Error\n"); } } bool protocol_gproxii_write_data(ProtocolGProxII* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = LFRFID_T5577_MODULATION_BIPHASE | LFRFID_T5577_BITRATE_RF_64 | (3 << LFRFID_T5577_MAXBLOCK_SHIFT); request->t5577.block[1] = bit_lib_get_bits_32(protocol->data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->data, 32, 32); request->t5577.block[3] = bit_lib_get_bits_32(protocol->data, 64, 32); request->t5577.blocks_to_write = 4; result = true; } return result; } const ProtocolBase protocol_gproxii = { .name = "GProxII", .manufacturer = "Guardall", .data_size = GPROXII_DATA_SIZE, .features = LFRFIDFeatureASK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_gproxii_alloc, .free = (ProtocolFree)protocol_gproxii_free, .get_data = (ProtocolGetData)protocol_gproxii_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_gproxii_decoder_start, .feed = (ProtocolDecoderFeed)protocol_gproxii_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_gproxii_encoder_start, .yield = (ProtocolEncoderYield)protocol_gproxii_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_gproxii_render_data, .render_brief_data = (ProtocolRenderData)protocol_gproxii_render_data, .write_data = (ProtocolWriteData)protocol_gproxii_write_data, };
12,768
C
.c
277
39.140794
139
0.587215
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,352
protocol_keri.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_keri.c
#include <furi.h> #include <toolbox/protocols/protocol.h> #include <bit_lib/bit_lib.h> #include "lfrfid_protocols.h" #define KERI_PREAMBLE_BIT_SIZE (33) #define KERI_PREAMBLE_DATA_SIZE (5) #define KERI_ENCODED_BIT_SIZE (64) #define KERI_ENCODED_DATA_SIZE (((KERI_ENCODED_BIT_SIZE) / 8) + KERI_PREAMBLE_DATA_SIZE) #define KERI_ENCODED_DATA_LAST ((KERI_ENCODED_BIT_SIZE) / 8) #define KERI_DECODED_BIT_SIZE (28) #define KERI_DECODED_DATA_SIZE (4) #define KERI_US_PER_BIT (255) #define KERI_ENCODER_PULSES_PER_BIT (16) typedef struct { uint8_t data_index; uint8_t bit_clock_index; bool last_bit; bool current_polarity; bool pulse_phase; } ProtocolKeriEncoder; typedef struct { uint8_t encoded_data[KERI_ENCODED_DATA_SIZE]; uint8_t negative_encoded_data[KERI_ENCODED_DATA_SIZE]; uint8_t corrupted_encoded_data[KERI_ENCODED_DATA_SIZE]; uint8_t corrupted_negative_encoded_data[KERI_ENCODED_DATA_SIZE]; uint8_t data[KERI_DECODED_DATA_SIZE]; ProtocolKeriEncoder encoder; } ProtocolKeri; ProtocolKeri* protocol_keri_alloc(void) { ProtocolKeri* protocol = malloc(sizeof(ProtocolKeri)); return protocol; } void protocol_keri_free(ProtocolKeri* protocol) { free(protocol); } uint8_t* protocol_keri_get_data(ProtocolKeri* protocol) { return protocol->data; } void protocol_keri_decoder_start(ProtocolKeri* protocol) { memset(protocol->encoded_data, 0, KERI_ENCODED_DATA_SIZE); memset(protocol->negative_encoded_data, 0, KERI_ENCODED_DATA_SIZE); memset(protocol->corrupted_encoded_data, 0, KERI_ENCODED_DATA_SIZE); memset(protocol->corrupted_negative_encoded_data, 0, KERI_ENCODED_DATA_SIZE); } static bool protocol_keri_check_preamble(uint8_t* data, size_t bit_index) { // Preamble 11100000 00000000 00000000 00000000 1 if(*(uint32_t*)&data[bit_index / 8] != 0b00000000000000000000000011100000) return false; if(bit_lib_get_bit(data, bit_index + 32) != 1) return false; return true; } static bool protocol_keri_can_be_decoded(uint8_t* data) { if(!protocol_keri_check_preamble(data, 0)) return false; if(!protocol_keri_check_preamble(data, 64)) return false; ///if(bit_lib_get_bit(data, 61) != 0) return false; //if(bit_lib_get_bit(data, 60) != 0) return false; return true; } static bool protocol_keri_decoder_feed_internal(bool polarity, uint32_t time, uint8_t* data) { time += (KERI_US_PER_BIT / 2); size_t bit_count = (time / KERI_US_PER_BIT); bool result = false; if(bit_count < KERI_ENCODED_BIT_SIZE) { for(size_t i = 0; i < bit_count; i++) { bit_lib_push_bit(data, KERI_ENCODED_DATA_SIZE, polarity); if(protocol_keri_can_be_decoded(data)) { result = true; break; } } } return result; } static void protocol_keri_descramble(uint32_t* fc, uint32_t* cn, uint32_t* internal_id) { const uint8_t card_to_id[] = {255, 255, 255, 255, 13, 12, 20, 5, 16, 6, 21, 17, 8, 255, 0, 7, 10, 15, 255, 11, 4, 1, 255, 18, 255, 19, 2, 14, 3, 9, 255, 255}; const uint8_t card_to_fc[] = {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 255, 255, 255, 255, 2, 255, 255, 255, 3, 255, 4, 255, 255, 255, 255, 255, 1, 255}; *fc = 0; *cn = 0; for(uint8_t card_idx = 0; card_idx < 32; card_idx++) { bool bit = (*internal_id >> card_idx) & 1; // Card ID if(card_to_id[card_idx] < 32) { *cn = *cn | (bit << card_to_id[card_idx]); } // Card FC if(card_to_fc[card_idx] < 32) { *fc = *fc | (bit << card_to_fc[card_idx]); } } } static void protocol_keri_decoder_save(uint8_t* data_to, const uint8_t* data_from) { uint32_t id = bit_lib_get_bits_32(data_from, 32, 32); data_to[3] = (uint8_t)id; data_to[2] = (uint8_t)(id >>= 8); data_to[1] = (uint8_t)(id >>= 8); data_to[0] = (uint8_t)(id >>= 8); } bool protocol_keri_decoder_feed(ProtocolKeri* protocol, bool level, uint32_t duration) { bool result = false; if(duration > (KERI_US_PER_BIT / 2)) { if(protocol_keri_decoder_feed_internal(level, duration, protocol->encoded_data)) { protocol_keri_decoder_save(protocol->data, protocol->encoded_data); result = true; return result; } if(protocol_keri_decoder_feed_internal(!level, duration, protocol->negative_encoded_data)) { protocol_keri_decoder_save(protocol->data, protocol->negative_encoded_data); result = true; return result; } } if(duration > (KERI_US_PER_BIT / 4)) { // Try to decode wrong phase synced data if(level) { duration += 120; } else { if(duration > 120) { duration -= 120; } } if(protocol_keri_decoder_feed_internal(level, duration, protocol->corrupted_encoded_data)) { protocol_keri_decoder_save(protocol->data, protocol->corrupted_encoded_data); result = true; return result; } if(protocol_keri_decoder_feed_internal( !level, duration, protocol->corrupted_negative_encoded_data)) { protocol_keri_decoder_save(protocol->data, protocol->corrupted_negative_encoded_data); result = true; return result; } } return result; } bool protocol_keri_encoder_start(ProtocolKeri* protocol) { memset(protocol->encoded_data, 0, KERI_ENCODED_DATA_SIZE); *(uint32_t*)&protocol->encoded_data[0] = 0b00000000000000000000000011100000; bit_lib_copy_bits(protocol->encoded_data, 32, 32, protocol->data, 0); bit_lib_set_bits(protocol->encoded_data, 32, 1, 1); protocol->encoder.last_bit = bit_lib_get_bit(protocol->encoded_data, KERI_ENCODED_BIT_SIZE - 1); protocol->encoder.data_index = 0; protocol->encoder.current_polarity = true; protocol->encoder.pulse_phase = true; protocol->encoder.bit_clock_index = 0; return true; } LevelDuration protocol_keri_encoder_yield(ProtocolKeri* protocol) { LevelDuration level_duration; ProtocolKeriEncoder* encoder = &protocol->encoder; if(encoder->pulse_phase) { level_duration = level_duration_make(encoder->current_polarity, 1); encoder->pulse_phase = false; } else { level_duration = level_duration_make(!encoder->current_polarity, 1); encoder->pulse_phase = true; encoder->bit_clock_index++; if(encoder->bit_clock_index >= KERI_ENCODER_PULSES_PER_BIT) { encoder->bit_clock_index = 0; bool current_bit = bit_lib_get_bit(protocol->encoded_data, encoder->data_index); if(current_bit != encoder->last_bit) { encoder->current_polarity = !encoder->current_polarity; } encoder->last_bit = current_bit; bit_lib_increment_index(encoder->data_index, KERI_ENCODED_BIT_SIZE); } } return level_duration; } static void protocol_keri_render_data_internal(ProtocolKeri* protocol, FuriString* result, bool brief) { uint32_t data = bit_lib_get_bits_32(protocol->data, 0, 32); uint32_t internal_id = data & 0x7FFFFFFF; uint32_t fc = 0; uint32_t cn = 0; protocol_keri_descramble(&fc, &cn, &data); if(brief) { furi_string_printf( result, "Internal ID: %lu\n" "FC: %lu; Card: %lu", internal_id, fc, cn); } else { furi_string_printf( result, "Internal ID: %lu\n" "FC: %lu\n" "Card: %lu", internal_id, fc, cn); } } void protocol_keri_render_data(ProtocolKeri* protocol, FuriString* result) { protocol_keri_render_data_internal(protocol, result, false); } void protocol_keri_render_brief_data(ProtocolKeri* protocol, FuriString* result) { protocol_keri_render_data_internal(protocol, result, true); } bool protocol_keri_write_data(ProtocolKeri* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; // Start bit should be always set protocol->data[0] |= (1 << 7); protocol_keri_encoder_start(protocol); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = LFRFID_T5577_TESTMODE_DISABLED | LFRFID_T5577_X_MODE | LFRFID_T5577_MODULATION_PSK1 | LFRFID_T5577_PSKCF_RF_2 | (2 << LFRFID_T5577_MAXBLOCK_SHIFT); request->t5577.block[0] |= 0xF << 18; request->t5577.block[1] = bit_lib_get_bits_32(protocol->encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->encoded_data, 32, 32); request->t5577.blocks_to_write = 3; result = true; } return result; } const ProtocolBase protocol_keri = { .name = "Keri", .manufacturer = "Keri", .data_size = KERI_DECODED_DATA_SIZE, .features = LFRFIDFeaturePSK, .validate_count = 6, .alloc = (ProtocolAlloc)protocol_keri_alloc, .free = (ProtocolFree)protocol_keri_free, .get_data = (ProtocolGetData)protocol_keri_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_keri_decoder_start, .feed = (ProtocolDecoderFeed)protocol_keri_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_keri_encoder_start, .yield = (ProtocolEncoderYield)protocol_keri_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_keri_render_data, .render_brief_data = (ProtocolRenderData)protocol_keri_render_brief_data, .write_data = (ProtocolWriteData)protocol_keri_write_data, };
10,016
C
.c
245
33.465306
100
0.626209
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,353
protocol_fdx_b.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_fdx_b.c
#include <furi.h> #include "toolbox/level_duration.h" #include "protocol_fdx_b.h" #include <toolbox/manchester_decoder.h> #include <bit_lib/bit_lib.h> #include "lfrfid_protocols.h" #include <furi_hal_rtc.h> #define FDX_B_ENCODED_BIT_SIZE (128) #define FDX_B_ENCODED_BYTE_SIZE (((FDX_B_ENCODED_BIT_SIZE) / 8)) #define FDX_B_PREAMBLE_BIT_SIZE (11) #define FDX_B_PREAMBLE_BYTE_SIZE (2) #define FDX_B_ENCODED_BYTE_FULL_SIZE (FDX_B_ENCODED_BYTE_SIZE + FDX_B_PREAMBLE_BYTE_SIZE) #define FDXB_DECODED_DATA_SIZE (11) #define FDX_B_SHORT_TIME (128) #define FDX_B_LONG_TIME (256) #define FDX_B_JITTER_TIME (60) #define FDX_B_SHORT_TIME_LOW (FDX_B_SHORT_TIME - FDX_B_JITTER_TIME) #define FDX_B_SHORT_TIME_HIGH (FDX_B_SHORT_TIME + FDX_B_JITTER_TIME) #define FDX_B_LONG_TIME_LOW (FDX_B_LONG_TIME - FDX_B_JITTER_TIME) #define FDX_B_LONG_TIME_HIGH (FDX_B_LONG_TIME + FDX_B_JITTER_TIME) typedef struct { bool last_short; bool last_level; size_t encoded_index; uint8_t encoded_data[FDX_B_ENCODED_BYTE_FULL_SIZE]; uint8_t data[FDXB_DECODED_DATA_SIZE]; } ProtocolFDXB; ProtocolFDXB* protocol_fdx_b_alloc(void) { ProtocolFDXB* protocol = malloc(sizeof(ProtocolFDXB)); return protocol; } void protocol_fdx_b_free(ProtocolFDXB* protocol) { free(protocol); } uint8_t* protocol_fdx_b_get_data(ProtocolFDXB* proto) { return proto->data; } void protocol_fdx_b_decoder_start(ProtocolFDXB* protocol) { memset(protocol->encoded_data, 0, FDX_B_ENCODED_BYTE_FULL_SIZE); protocol->last_short = false; } static bool protocol_fdx_b_can_be_decoded(ProtocolFDXB* protocol) { bool result = false; /* msb lsb 0 10000000000 Header pattern. 11 bits. 11 1nnnnnnnn 20 1nnnnnnnn 38 bit (12 digit) National code. 29 1nnnnnnnn eg. 000000001008 (decimal). 38 1nnnnnnnn 47 1nnnnnncc 10 bit (3 digit) Country code. 56 1cccccccc eg. 999 (decimal). 65 1s------- 1 bit data block status flag. 74 1-------a 1 bit animal application indicator. 83 1xxxxxxxx 16 bit checksum. 92 1xxxxxxxx 101 1eeeeeeee 24 bits of extra data if present. 110 1eeeeeeee eg. $123456. 119 1eeeeeeee */ do { // check 11 bits preamble if(bit_lib_get_bits_16(protocol->encoded_data, 0, 11) != 0b10000000000) break; // check next 11 bits preamble if(bit_lib_get_bits_16(protocol->encoded_data, 128, 11) != 0b10000000000) break; // check control bits if(!bit_lib_test_parity(protocol->encoded_data, 3, 13 * 9, BitLibParityAlways1, 9)) break; // compute checksum uint8_t crc_data[8]; for(size_t i = 0; i < 8; i++) { bit_lib_copy_bits(crc_data, i * 8, 8, protocol->encoded_data, 12 + 9 * i); } uint16_t crc_res = bit_lib_crc16(crc_data, 8, 0x1021, 0x0000, false, false, 0x0000); // read checksum uint16_t crc_ex = 0; bit_lib_copy_bits((uint8_t*)&crc_ex, 8, 8, protocol->encoded_data, 84); bit_lib_copy_bits((uint8_t*)&crc_ex, 0, 8, protocol->encoded_data, 93); // compare checksum if(crc_res != crc_ex) break; result = true; } while(false); return result; } void protocol_fdx_b_decode(ProtocolFDXB* protocol) { // remove parity bit_lib_remove_bit_every_nth(protocol->encoded_data, 3, 14 * 9, 9); // remove header pattern for(size_t i = 0; i < 11; i++) bit_lib_push_bit(protocol->encoded_data, FDX_B_ENCODED_BYTE_FULL_SIZE, 0); // 0 nnnnnnnn // 8 nnnnnnnn 38 bit (12 digit) National code. // 16 nnnnnnnn eg. 000000001008 (decimal). // 24 nnnnnnnn // 32 nnnnnncc 10 bit (3 digit) Country code. // 40 cccccccc eg. 999 (decimal). // 48 s------- 1 bit data block status flag. // 56 -------a 1 bit animal application indicator. // 64 xxxxxxxx 16 bit checksum. // 72 xxxxxxxx // 80 eeeeeeee 24 bits of extra data if present. // 88 eeeeeeee eg. $123456. // 96 eeeeeeee // copy data without checksum bit_lib_copy_bits(protocol->data, 0, 64, protocol->encoded_data, 0); bit_lib_copy_bits(protocol->data, 64, 24, protocol->encoded_data, 80); // const BitLibRegion regions_encoded[] = { // {'n', 0, 38}, // {'c', 38, 10}, // {'b', 48, 16}, // {'x', 64, 16}, // {'e', 80, 24}, // }; // bit_lib_print_regions(regions_encoded, 5, protocol->encoded_data, FDX_B_ENCODED_BIT_SIZE); // const BitLibRegion regions_decoded[] = { // {'n', 0, 38}, // {'c', 38, 10}, // {'b', 48, 16}, // {'e', 64, 24}, // }; // bit_lib_print_regions(regions_decoded, 4, protocol->data, FDXB_DECODED_DATA_SIZE * 8); } bool protocol_fdx_b_decoder_feed(ProtocolFDXB* protocol, bool level, uint32_t duration) { bool result = false; UNUSED(level); bool pushed = false; // Bi-Phase Manchester decoding if(duration >= FDX_B_SHORT_TIME_LOW && duration <= FDX_B_SHORT_TIME_HIGH) { if(protocol->last_short == false) { protocol->last_short = true; } else { pushed = true; bit_lib_push_bit(protocol->encoded_data, FDX_B_ENCODED_BYTE_FULL_SIZE, false); protocol->last_short = false; } } else if(duration >= FDX_B_LONG_TIME_LOW && duration <= FDX_B_LONG_TIME_HIGH) { if(protocol->last_short == false) { pushed = true; bit_lib_push_bit(protocol->encoded_data, FDX_B_ENCODED_BYTE_FULL_SIZE, true); } else { // reset protocol->last_short = false; } } else { // reset protocol->last_short = false; } if(pushed && protocol_fdx_b_can_be_decoded(protocol)) { protocol_fdx_b_decode(protocol); result = true; } return result; } bool protocol_fdx_b_encoder_start(ProtocolFDXB* protocol) { memset(protocol->encoded_data, 0, FDX_B_ENCODED_BYTE_FULL_SIZE); bit_lib_set_bit(protocol->encoded_data, 0, 1); for(size_t i = 0; i < 13; i++) { bit_lib_set_bit(protocol->encoded_data, 11 + 9 * i, 1); if(i == 8 || i == 9) continue; if(i < 8) { bit_lib_copy_bits(protocol->encoded_data, 12 + 9 * i, 8, protocol->data, i * 8); } else { bit_lib_copy_bits(protocol->encoded_data, 12 + 9 * i, 8, protocol->data, (i - 2) * 8); } } uint16_t crc_res = bit_lib_crc16(protocol->data, 8, 0x1021, 0x0000, false, false, 0x0000); bit_lib_copy_bits(protocol->encoded_data, 84, 8, (uint8_t*)&crc_res, 8); bit_lib_copy_bits(protocol->encoded_data, 93, 8, (uint8_t*)&crc_res, 0); protocol->encoded_index = 0; protocol->last_short = false; protocol->last_level = false; return true; } LevelDuration protocol_fdx_b_encoder_yield(ProtocolFDXB* protocol) { uint32_t duration; protocol->last_level = !protocol->last_level; bool bit = bit_lib_get_bit(protocol->encoded_data, protocol->encoded_index); // Bi-Phase Manchester encoder if(bit) { // one long pulse for 1 duration = FDX_B_LONG_TIME / 8; bit_lib_increment_index(protocol->encoded_index, FDX_B_ENCODED_BIT_SIZE); } else { // two short pulses for 0 duration = FDX_B_SHORT_TIME / 8; if(protocol->last_short) { bit_lib_increment_index(protocol->encoded_index, FDX_B_ENCODED_BIT_SIZE); protocol->last_short = false; } else { protocol->last_short = true; } } return level_duration_make(protocol->last_level, duration); } // 0 nnnnnnnn // 8 nnnnnnnn 38 bit (12 digit) National code. // 16 nnnnnnnn eg. 000000001008 (decimal). // 24 nnnnnnnn // 32 nnnnnnnn 10 bit (3 digit) Country code. // 40 cccccccc eg. 999 (decimal). // 48 s------- 1 bit data block status flag. // 56 -------a 1 bit animal application indicator. // 64 eeeeeeee 24 bits of extra data if present. // 72 eeeeeeee eg. $123456. // 80 eeeeeeee static uint64_t protocol_fdx_b_get_national_code(const uint8_t* data) { uint64_t national_code = bit_lib_get_bits_32(data, 0, 32); national_code = national_code << 32; national_code |= (uint64_t)bit_lib_get_bits_32(data, 32, 6) << (32 - 6); bit_lib_reverse_bits((uint8_t*)&national_code, 0, 64); return national_code; } static uint16_t protocol_fdx_b_get_country_code(const uint8_t* data) { uint16_t country_code = bit_lib_get_bits_16(data, 38, 10) << 6; bit_lib_reverse_bits((uint8_t*)&country_code, 0, 16); return country_code; } static bool protocol_fdx_b_get_temp(const uint8_t* data, float* temp) { uint32_t extended = bit_lib_get_bits_32(data, 64, 24) << 8; bit_lib_reverse_bits((uint8_t*)&extended, 0, 32); uint8_t ex_parity = (extended & 0x100) >> 8; uint8_t ex_temperature = extended & 0xff; uint8_t ex_calc_parity = bit_lib_test_parity_32(ex_temperature, BitLibParityOdd); bool ex_temperature_present = (ex_calc_parity == ex_parity) && !(extended & 0xe00); if(ex_temperature_present) { float temperature_f = 74 + ex_temperature * 0.2; *temp = temperature_f; return true; } else { return false; } } void protocol_fdx_b_render_data(ProtocolFDXB* protocol, FuriString* result) { // 38 bits of national code uint64_t national_code = protocol_fdx_b_get_national_code(protocol->data); // 10 bit of country code uint16_t country_code = protocol_fdx_b_get_country_code(protocol->data); bool block_status = bit_lib_get_bit(protocol->data, 48); bool rudi_bit = bit_lib_get_bit(protocol->data, 49); uint8_t reserved = bit_lib_get_bits(protocol->data, 50, 5); uint8_t user_info = bit_lib_get_bits(protocol->data, 55, 5); uint8_t replacement_number = bit_lib_get_bits(protocol->data, 60, 3); bool animal_flag = bit_lib_get_bit(protocol->data, 63); furi_string_printf( result, "ID: %03hu-%012llu\n" "Country Code: %hu\n" "Temperature: ", country_code, national_code, country_code); float temperature; if(protocol_fdx_b_get_temp(protocol->data, &temperature)) { if(furi_hal_rtc_get_locale_units() == FuriHalRtcLocaleUnitsMetric) { float temperature_c = (temperature - 32.0f) / 1.8f; furi_string_cat_printf(result, "%.2fC", (double)temperature_c); } else { furi_string_cat_printf(result, "%.2fF", (double)temperature); } } else { furi_string_cat(result, "---"); } furi_string_cat_printf( result, "\n" "Animal: %s\n" "Bits: %hhX-%hhX-%hhX-%hhX-%hhX", animal_flag ? "Yes" : "No", block_status, rudi_bit, reserved, user_info, replacement_number); } void protocol_fdx_b_render_brief_data(ProtocolFDXB* protocol, FuriString* result) { // 38 bits of national code uint64_t national_code = protocol_fdx_b_get_national_code(protocol->data); // 10 bit of country code uint16_t country_code = protocol_fdx_b_get_country_code(protocol->data); furi_string_printf( result, "ID: %03hu-%012llu\n" "Country: %hu; Temp.: ", country_code, national_code, country_code); float temperature; if(protocol_fdx_b_get_temp(protocol->data, &temperature)) { if(furi_hal_rtc_get_locale_units() == FuriHalRtcLocaleUnitsMetric) { float temperature_c = (temperature - 32.0f) / 1.8f; furi_string_cat_printf(result, "%.2fC", (double)temperature_c); } else { furi_string_cat_printf(result, "%.2fF", (double)temperature); } } else { furi_string_cat(result, "---"); } } bool protocol_fdx_b_write_data(ProtocolFDXB* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; // Correct protocol data by redecoding protocol_fdx_b_encoder_start(protocol); protocol_fdx_b_decode(protocol); protocol_fdx_b_encoder_start(protocol); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = LFRFID_T5577_MODULATION_DIPHASE | LFRFID_T5577_BITRATE_RF_32 | (4 << LFRFID_T5577_MAXBLOCK_SHIFT); request->t5577.block[1] = bit_lib_get_bits_32(protocol->encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->encoded_data, 32, 32); request->t5577.block[3] = bit_lib_get_bits_32(protocol->encoded_data, 64, 32); request->t5577.block[4] = bit_lib_get_bits_32(protocol->encoded_data, 96, 32); request->t5577.blocks_to_write = 5; result = true; } return result; } const ProtocolBase protocol_fdx_b = { .name = "FDX-B", .manufacturer = "ISO", .data_size = FDXB_DECODED_DATA_SIZE, .features = LFRFIDFeatureASK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_fdx_b_alloc, .free = (ProtocolFree)protocol_fdx_b_free, .get_data = (ProtocolGetData)protocol_fdx_b_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_fdx_b_decoder_start, .feed = (ProtocolDecoderFeed)protocol_fdx_b_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_fdx_b_encoder_start, .yield = (ProtocolEncoderYield)protocol_fdx_b_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_fdx_b_render_data, .render_brief_data = (ProtocolRenderData)protocol_fdx_b_render_brief_data, .write_data = (ProtocolWriteData)protocol_fdx_b_write_data, };
13,742
C
.c
339
34.424779
98
0.627773
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,354
protocol_hid_ex_generic.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_hid_ex_generic.c
#include <furi.h> #include <toolbox/protocols/protocol.h> #include <lfrfid/tools/fsk_demod.h> #include <lfrfid/tools/fsk_osc.h> #include "lfrfid_protocols.h" #include <bit_lib/bit_lib.h> #define JITTER_TIME (20) #define MIN_TIME (64 - JITTER_TIME) #define MAX_TIME (80 + JITTER_TIME) #define HID_DATA_SIZE 23 #define HID_PREAMBLE_SIZE 1 #define HID_ENCODED_DATA_SIZE (HID_PREAMBLE_SIZE + HID_DATA_SIZE + HID_PREAMBLE_SIZE) #define HID_ENCODED_BIT_SIZE ((HID_PREAMBLE_SIZE + HID_DATA_SIZE) * 8) #define HID_DECODED_DATA_SIZE (12) #define HID_DECODED_BIT_SIZE ((HID_ENCODED_BIT_SIZE - HID_PREAMBLE_SIZE * 8) / 2) #define HID_PREAMBLE 0x1D typedef struct { FSKDemod* fsk_demod; } ProtocolHIDExDecoder; typedef struct { FSKOsc* fsk_osc; uint8_t encoded_index; uint32_t pulse; } ProtocolHIDExEncoder; typedef struct { ProtocolHIDExDecoder decoder; ProtocolHIDExEncoder encoder; uint8_t encoded_data[HID_ENCODED_DATA_SIZE]; uint8_t data[HID_DECODED_DATA_SIZE]; size_t protocol_size; } ProtocolHIDEx; ProtocolHIDEx* protocol_hid_ex_generic_alloc(void) { ProtocolHIDEx* protocol = malloc(sizeof(ProtocolHIDEx)); protocol->decoder.fsk_demod = fsk_demod_alloc(MIN_TIME, 6, MAX_TIME, 5); protocol->encoder.fsk_osc = fsk_osc_alloc(8, 10, 50); return protocol; } void protocol_hid_ex_generic_free(ProtocolHIDEx* protocol) { fsk_demod_free(protocol->decoder.fsk_demod); fsk_osc_free(protocol->encoder.fsk_osc); free(protocol); } uint8_t* protocol_hid_ex_generic_get_data(ProtocolHIDEx* protocol) { return protocol->data; } void protocol_hid_ex_generic_decoder_start(ProtocolHIDEx* protocol) { memset(protocol->encoded_data, 0, HID_ENCODED_DATA_SIZE); } static bool protocol_hid_ex_generic_can_be_decoded(const uint8_t* data) { // check preamble if(data[0] != HID_PREAMBLE || data[HID_PREAMBLE_SIZE + HID_DATA_SIZE] != HID_PREAMBLE) { return false; } // check for manchester encoding for(size_t i = HID_PREAMBLE_SIZE; i < (HID_PREAMBLE_SIZE + HID_DATA_SIZE); i++) { for(size_t n = 0; n < 4; n++) { uint8_t bit_pair = (data[i] >> (n * 2)) & 0b11; if(bit_pair == 0b11 || bit_pair == 0b00) { return false; } } } return true; } static void protocol_hid_ex_generic_decode(const uint8_t* from, uint8_t* to) { size_t bit_index = 0; for(size_t i = HID_PREAMBLE_SIZE; i < (HID_PREAMBLE_SIZE + HID_DATA_SIZE); i++) { for(size_t n = 0; n < 4; n++) { uint8_t bit_pair = (from[i] >> (6 - (n * 2))) & 0b11; if(bit_pair == 0b01) { bit_lib_set_bit(to, bit_index, 0); } else if(bit_pair == 0b10) { bit_lib_set_bit(to, bit_index, 1); } bit_index++; } } } bool protocol_hid_ex_generic_decoder_feed(ProtocolHIDEx* protocol, bool level, uint32_t duration) { bool value; uint32_t count; bool result = false; fsk_demod_feed(protocol->decoder.fsk_demod, level, duration, &value, &count); if(count > 0) { for(size_t i = 0; i < count; i++) { bit_lib_push_bit(protocol->encoded_data, HID_ENCODED_DATA_SIZE, value); if(protocol_hid_ex_generic_can_be_decoded(protocol->encoded_data)) { protocol_hid_ex_generic_decode(protocol->encoded_data, protocol->data); result = true; } } } return result; } static void protocol_hid_ex_generic_encode(ProtocolHIDEx* protocol) { protocol->encoded_data[0] = HID_PREAMBLE; size_t bit_index = 0; for(size_t i = 0; i < HID_DECODED_BIT_SIZE; i++) { bool bit = bit_lib_get_bit(protocol->data, i); if(bit) { bit_lib_set_bit(protocol->encoded_data, 8 + bit_index, 1); bit_lib_set_bit(protocol->encoded_data, 8 + bit_index + 1, 0); } else { bit_lib_set_bit(protocol->encoded_data, 8 + bit_index, 0); bit_lib_set_bit(protocol->encoded_data, 8 + bit_index + 1, 1); } bit_index += 2; } } bool protocol_hid_ex_generic_encoder_start(ProtocolHIDEx* protocol) { protocol->encoder.encoded_index = 0; protocol->encoder.pulse = 0; protocol_hid_ex_generic_encode(protocol); return true; } LevelDuration protocol_hid_ex_generic_encoder_yield(ProtocolHIDEx* protocol) { bool level = 0; uint32_t duration = 0; // if pulse is zero, we need to output high, otherwise we need to output low if(protocol->encoder.pulse == 0) { // get bit uint8_t bit = bit_lib_get_bit(protocol->encoded_data, protocol->encoder.encoded_index); // get pulse from oscillator bool advance = fsk_osc_next(protocol->encoder.fsk_osc, bit, &duration); if(advance) { bit_lib_increment_index(protocol->encoder.encoded_index, HID_ENCODED_BIT_SIZE); } // duration diveded by 2 because we need to output high and low duration = duration / 2; protocol->encoder.pulse = duration; level = true; } else { // output low half and reset pulse duration = protocol->encoder.pulse; protocol->encoder.pulse = 0; level = false; } return level_duration_make(level, duration); } bool protocol_hid_ex_generic_write_data(ProtocolHIDEx* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; // Correct protocol data by redecoding protocol_hid_ex_generic_encoder_start(protocol); protocol_hid_ex_generic_decode(protocol->encoded_data, protocol->data); protocol_hid_ex_generic_encoder_start(protocol); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = LFRFID_T5577_MODULATION_FSK2a | LFRFID_T5577_BITRATE_RF_50 | (6 << LFRFID_T5577_MAXBLOCK_SHIFT); request->t5577.block[1] = bit_lib_get_bits_32(protocol->encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->encoded_data, 32, 32); request->t5577.block[3] = bit_lib_get_bits_32(protocol->encoded_data, 64, 32); request->t5577.block[4] = bit_lib_get_bits_32(protocol->encoded_data, 96, 32); request->t5577.block[5] = bit_lib_get_bits_32(protocol->encoded_data, 128, 32); request->t5577.block[6] = bit_lib_get_bits_32(protocol->encoded_data, 160, 32); request->t5577.blocks_to_write = 7; result = true; } return result; } void protocol_hid_ex_generic_render_data(ProtocolHIDEx* protocol, FuriString* result) { UNUSED(protocol); // TODO FL-3518: parser and render functions furi_string_set( result, "Type: Generic HID Extended\n" "Data: Unknown"); } const ProtocolBase protocol_hid_ex_generic = { .name = "HIDExt", .manufacturer = "Generic", .data_size = HID_DECODED_DATA_SIZE, .features = LFRFIDFeatureASK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_hid_ex_generic_alloc, .free = (ProtocolFree)protocol_hid_ex_generic_free, .get_data = (ProtocolGetData)protocol_hid_ex_generic_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_hid_ex_generic_decoder_start, .feed = (ProtocolDecoderFeed)protocol_hid_ex_generic_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_hid_ex_generic_encoder_start, .yield = (ProtocolEncoderYield)protocol_hid_ex_generic_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_hid_ex_generic_render_data, .render_brief_data = (ProtocolRenderData)protocol_hid_ex_generic_render_data, .write_data = (ProtocolWriteData)protocol_hid_ex_generic_write_data, };
7,829
C
.c
191
34.617801
99
0.650881
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,355
protocol_gallagher.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_gallagher.c
#include <furi.h> #include <toolbox/protocols/protocol.h> #include <toolbox/manchester_decoder.h> #include <bit_lib/bit_lib.h> #include "lfrfid_protocols.h" #define GALLAGHER_CLOCK_PER_BIT (32) #define GALLAGHER_ENCODED_BIT_SIZE (96) #define GALLAGHER_ENCODED_BYTE_SIZE ((GALLAGHER_ENCODED_BIT_SIZE) / 8) #define GALLAGHER_PREAMBLE_BIT_SIZE (16) #define GALLAGHER_PREAMBLE_BYTE_SIZE ((GALLAGHER_PREAMBLE_BIT_SIZE) / 8) #define GALLAGHER_ENCODED_BYTE_FULL_SIZE \ (GALLAGHER_ENCODED_BYTE_SIZE + GALLAGHER_PREAMBLE_BYTE_SIZE) #define GALLAGHER_DECODED_DATA_SIZE 8 #define GALLAGHER_READ_SHORT_TIME (128) #define GALLAGHER_READ_LONG_TIME (256) #define GALLAGHER_READ_JITTER_TIME (60) #define GALLAGHER_READ_SHORT_TIME_LOW (GALLAGHER_READ_SHORT_TIME - GALLAGHER_READ_JITTER_TIME) #define GALLAGHER_READ_SHORT_TIME_HIGH (GALLAGHER_READ_SHORT_TIME + GALLAGHER_READ_JITTER_TIME) #define GALLAGHER_READ_LONG_TIME_LOW (GALLAGHER_READ_LONG_TIME - GALLAGHER_READ_JITTER_TIME) #define GALLAGHER_READ_LONG_TIME_HIGH (GALLAGHER_READ_LONG_TIME + GALLAGHER_READ_JITTER_TIME) typedef struct { uint8_t data[GALLAGHER_DECODED_DATA_SIZE]; uint8_t encoded_data[GALLAGHER_ENCODED_BYTE_FULL_SIZE]; uint8_t encoded_data_index; bool encoded_polarity; ManchesterState decoder_manchester_state; } ProtocolGallagher; ProtocolGallagher* protocol_gallagher_alloc(void) { ProtocolGallagher* proto = malloc(sizeof(ProtocolGallagher)); return (void*)proto; } void protocol_gallagher_free(ProtocolGallagher* protocol) { free(protocol); } uint8_t* protocol_gallagher_get_data(ProtocolGallagher* protocol) { return protocol->data; } static void protocol_gallagher_scramble(uint8_t* data, size_t length) { const uint8_t lut[] = { 0xa3, 0xb0, 0x80, 0xc6, 0xb2, 0xf4, 0x5c, 0x6c, 0x81, 0xf1, 0xbb, 0xeb, 0x55, 0x67, 0x3c, 0x05, 0x1a, 0x0e, 0x61, 0xf6, 0x22, 0xce, 0xaa, 0x8f, 0xbd, 0x3b, 0x1f, 0x5e, 0x44, 0x04, 0x51, 0x2e, 0x4d, 0x9a, 0x84, 0xea, 0xf8, 0x66, 0x74, 0x29, 0x7f, 0x70, 0xd8, 0x31, 0x7a, 0x6d, 0xa4, 0x00, 0x82, 0xb9, 0x5f, 0xb4, 0x16, 0xab, 0xff, 0xc2, 0x39, 0xdc, 0x19, 0x65, 0x57, 0x7c, 0x20, 0xfa, 0x5a, 0x49, 0x13, 0xd0, 0xfb, 0xa8, 0x91, 0x73, 0xb1, 0x33, 0x18, 0xbe, 0x21, 0x72, 0x48, 0xb6, 0xdb, 0xa0, 0x5d, 0xcc, 0xe6, 0x17, 0x27, 0xe5, 0xd4, 0x53, 0x42, 0xf3, 0xdd, 0x7b, 0x24, 0xac, 0x2b, 0x58, 0x1e, 0xa7, 0xe7, 0x86, 0x40, 0xd3, 0x98, 0x97, 0x71, 0xcb, 0x3a, 0x0f, 0x01, 0x9b, 0x6e, 0x1b, 0xfc, 0x34, 0xa6, 0xda, 0x07, 0x0c, 0xae, 0x37, 0xca, 0x54, 0xfd, 0x26, 0xfe, 0x0a, 0x45, 0xa2, 0x2a, 0xc4, 0x12, 0x0d, 0xf5, 0x4f, 0x69, 0xe0, 0x8a, 0x77, 0x60, 0x3f, 0x99, 0x95, 0xd2, 0x38, 0x36, 0x62, 0xb7, 0x32, 0x7e, 0x79, 0xc0, 0x46, 0x93, 0x2f, 0xa5, 0xba, 0x5b, 0xaf, 0x52, 0x1d, 0xc3, 0x75, 0xcf, 0xd6, 0x4c, 0x83, 0xe8, 0x3d, 0x30, 0x4e, 0xbc, 0x08, 0x2d, 0x09, 0x06, 0xd9, 0x25, 0x9e, 0x89, 0xf2, 0x96, 0x88, 0xc1, 0x8c, 0x94, 0x0b, 0x28, 0xf0, 0x47, 0x63, 0xd5, 0xb3, 0x68, 0x56, 0x9c, 0xf9, 0x6f, 0x41, 0x50, 0x85, 0x8b, 0x9d, 0x59, 0xbf, 0x9f, 0xe2, 0x8e, 0x6a, 0x11, 0x23, 0xa1, 0xcd, 0xb5, 0x7d, 0xc7, 0xa9, 0xc8, 0xef, 0xdf, 0x02, 0xb8, 0x03, 0x6b, 0x35, 0x3e, 0x2c, 0x76, 0xc9, 0xde, 0x1c, 0x4b, 0xd1, 0xed, 0x14, 0xc5, 0xad, 0xe9, 0x64, 0x4a, 0xec, 0x8d, 0xf7, 0x10, 0x43, 0x78, 0x15, 0x87, 0xe4, 0xd7, 0x92, 0xe1, 0xee, 0xe3, 0x90}; for(size_t i = 0; i < length; i++) { data[i] = lut[data[i]]; } } static void protocol_gallagher_descramble(uint8_t* data, size_t length) { const uint8_t lut[] = { 0x2f, 0x6e, 0xdd, 0xdf, 0x1d, 0x0f, 0xb0, 0x76, 0xad, 0xaf, 0x7f, 0xbb, 0x77, 0x85, 0x11, 0x6d, 0xf4, 0xd2, 0x84, 0x42, 0xeb, 0xf7, 0x34, 0x55, 0x4a, 0x3a, 0x10, 0x71, 0xe7, 0xa1, 0x62, 0x1a, 0x3e, 0x4c, 0x14, 0xd3, 0x5e, 0xb2, 0x7d, 0x56, 0xbc, 0x27, 0x82, 0x60, 0xe3, 0xae, 0x1f, 0x9b, 0xaa, 0x2b, 0x95, 0x49, 0x73, 0xe1, 0x92, 0x79, 0x91, 0x38, 0x6c, 0x19, 0x0e, 0xa9, 0xe2, 0x8d, 0x66, 0xc7, 0x5a, 0xf5, 0x1c, 0x80, 0x99, 0xbe, 0x4e, 0x41, 0xf0, 0xe8, 0xa6, 0x20, 0xab, 0x87, 0xc8, 0x1e, 0xa0, 0x59, 0x7b, 0x0c, 0xc3, 0x3c, 0x61, 0xcc, 0x40, 0x9e, 0x06, 0x52, 0x1b, 0x32, 0x8c, 0x12, 0x93, 0xbf, 0xef, 0x3b, 0x25, 0x0d, 0xc2, 0x88, 0xd1, 0xe0, 0x07, 0x2d, 0x70, 0xc6, 0x29, 0x6a, 0x4d, 0x47, 0x26, 0xa3, 0xe4, 0x8b, 0xf6, 0x97, 0x2c, 0x5d, 0x3d, 0xd7, 0x96, 0x28, 0x02, 0x08, 0x30, 0xa7, 0x22, 0xc9, 0x65, 0xf8, 0xb7, 0xb4, 0x8a, 0xca, 0xb9, 0xf2, 0xd0, 0x17, 0xff, 0x46, 0xfb, 0x9a, 0xba, 0x8f, 0xb6, 0x69, 0x68, 0x8e, 0x21, 0x6f, 0xc4, 0xcb, 0xb3, 0xce, 0x51, 0xd4, 0x81, 0x00, 0x2e, 0x9c, 0x74, 0x63, 0x45, 0xd9, 0x16, 0x35, 0x5f, 0xed, 0x78, 0x9f, 0x01, 0x48, 0x04, 0xc1, 0x33, 0xd6, 0x4f, 0x94, 0xde, 0x31, 0x9d, 0x0a, 0xac, 0x18, 0x4b, 0xcd, 0x98, 0xb8, 0x37, 0xa2, 0x83, 0xec, 0x03, 0xd8, 0xda, 0xe5, 0x7a, 0x6b, 0x53, 0xd5, 0x15, 0xa4, 0x43, 0xe9, 0x90, 0x67, 0x58, 0xc0, 0xa5, 0xfa, 0x2a, 0xb1, 0x75, 0x50, 0x39, 0x5c, 0xe6, 0xdc, 0x89, 0xfc, 0xcf, 0xfe, 0xf9, 0x57, 0x54, 0x64, 0xa8, 0xee, 0x23, 0x0b, 0xf1, 0xea, 0xfd, 0xdb, 0xbd, 0x09, 0xb5, 0x5b, 0x05, 0x86, 0x13, 0xf3, 0x24, 0xc5, 0x3f, 0x44, 0x72, 0x7c, 0x7e, 0x36}; for(size_t i = 0; i < length; i++) { data[i] = lut[data[i]]; } } static void protocol_gallagher_decode(ProtocolGallagher* protocol) { bit_lib_remove_bit_every_nth(protocol->encoded_data, 16, 9 * 8, 9); protocol_gallagher_descramble(protocol->encoded_data + 2, 8); // Region code bit_lib_set_bits(protocol->data, 0, (protocol->encoded_data[5] & 0x1E) >> 1, 4); // Issue Level bit_lib_set_bits(protocol->data, 4, (protocol->encoded_data[9] & 0x0F), 4); // Facility Code uint32_t fc = (protocol->encoded_data[7] & 0x0F) << 12 | protocol->encoded_data[3] << 4 | ((protocol->encoded_data[9] >> 4) & 0x0F); protocol->data[3] = (uint8_t)fc; protocol->data[2] = (uint8_t)(fc >>= 8); protocol->data[1] = (uint8_t)(fc >>= 8); // Card Number uint32_t card = protocol->encoded_data[2] << 16 | (protocol->encoded_data[6] & 0x1F) << 11 | protocol->encoded_data[4] << 3 | (protocol->encoded_data[5] & 0xE0) >> 5; protocol->data[7] = (uint8_t)card; protocol->data[6] = (uint8_t)(card >>= 8); protocol->data[5] = (uint8_t)(card >>= 8); protocol->data[4] = (uint8_t)(card >>= 8); } static bool protocol_gallagher_can_be_decoded(ProtocolGallagher* protocol) { // check 16 bits preamble if(bit_lib_get_bits_16(protocol->encoded_data, 0, 16) != 0b0111111111101010) return false; // check next 16 bits preamble if(bit_lib_get_bits_16(protocol->encoded_data, 96, 16) != 0b0111111111101010) return false; uint8_t checksum_arr[8] = {0}; for(int i = 0, pos = 0; i < 8; i++) { // Following the preamble, every 9th bit is a checksum-bit for the preceding byte pos = 16 + (9 * i); checksum_arr[i] = bit_lib_get_bits(protocol->encoded_data, pos, 8); } uint8_t crc = bit_lib_get_bits(protocol->encoded_data, 16 + (9 * 8), 8); uint8_t calc_crc = bit_lib_crc8(checksum_arr, 8, 0x7, 0x2c, false, false, 0x00); // crc if(crc != calc_crc) return false; return true; } void protocol_gallagher_decoder_start(ProtocolGallagher* protocol) { memset(protocol->encoded_data, 0, GALLAGHER_ENCODED_BYTE_FULL_SIZE); manchester_advance( protocol->decoder_manchester_state, ManchesterEventReset, &protocol->decoder_manchester_state, NULL); } bool protocol_gallagher_decoder_feed(ProtocolGallagher* protocol, bool level, uint32_t duration) { bool result = false; ManchesterEvent event = ManchesterEventReset; if(duration > GALLAGHER_READ_SHORT_TIME_LOW && duration < GALLAGHER_READ_SHORT_TIME_HIGH) { if(!level) { event = ManchesterEventShortHigh; } else { event = ManchesterEventShortLow; } } else if(duration > GALLAGHER_READ_LONG_TIME_LOW && duration < GALLAGHER_READ_LONG_TIME_HIGH) { if(!level) { event = ManchesterEventLongHigh; } else { event = ManchesterEventLongLow; } } if(event != ManchesterEventReset) { bool data; bool data_ok = manchester_advance( protocol->decoder_manchester_state, event, &protocol->decoder_manchester_state, &data); if(data_ok) { bit_lib_push_bit(protocol->encoded_data, GALLAGHER_ENCODED_BYTE_FULL_SIZE, data); if(protocol_gallagher_can_be_decoded(protocol)) { protocol_gallagher_decode(protocol); result = true; } } } return result; } bool protocol_gallagher_encoder_start(ProtocolGallagher* protocol) { // Preamble bit_lib_set_bits(protocol->encoded_data, 0, 0b01111111, 8); bit_lib_set_bits(protocol->encoded_data, 8, 0b11101010, 8); uint8_t rc = bit_lib_get_bits(protocol->data, 0, 4); uint8_t il = bit_lib_get_bits(protocol->data, 4, 4); uint32_t fc = bit_lib_get_bits_32(protocol->data, 8, 24); uint32_t cn = bit_lib_get_bits_32(protocol->data, 32, 32); uint8_t payload[8] = {0}; payload[0] = (cn & 0xffffff) >> 16; payload[1] = (fc & 0xfff) >> 4; payload[2] = (cn & 0x7ff) >> 3; payload[3] = (cn & 0x7) << 5 | (rc & 0xf) << 1; payload[4] = (cn & 0xffff) >> 11; payload[5] = (fc & 0xffff) >> 12; payload[6] = 0; payload[7] = (fc & 0xf) << 4 | (il & 0xf); // Gallagher scramble protocol_gallagher_scramble(payload, 8); for(int i = 0; i < 8; i++) { // data byte bit_lib_set_bits(protocol->encoded_data, 16 + (i * 9), payload[i], 8); // every byte is followed by a bit which is the inverse of the last bit bit_lib_set_bit(protocol->encoded_data, 16 + (i * 9) + 8, !(payload[i] & 0x1)); } // checksum uint8_t crc = bit_lib_crc8(payload, 8, 0x7, 0x2c, false, false, 0x00); bit_lib_set_bits(protocol->encoded_data, 16 + (9 * 8), crc, 8); return true; } LevelDuration protocol_gallagher_encoder_yield(ProtocolGallagher* protocol) { bool level = bit_lib_get_bit(protocol->encoded_data, protocol->encoded_data_index); uint32_t duration = GALLAGHER_CLOCK_PER_BIT / 2; if(protocol->encoded_polarity) { protocol->encoded_polarity = false; } else { level = !level; protocol->encoded_polarity = true; bit_lib_increment_index(protocol->encoded_data_index, GALLAGHER_ENCODED_BIT_SIZE); } return level_duration_make(level, duration); } bool protocol_gallagher_write_data(ProtocolGallagher* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; // Correct protocol data by redecoding protocol_gallagher_encoder_start(protocol); protocol_gallagher_decode(protocol); protocol_gallagher_encoder_start(protocol); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = (LFRFID_T5577_MODULATION_MANCHESTER | LFRFID_T5577_BITRATE_RF_32 | (3 << LFRFID_T5577_MAXBLOCK_SHIFT)); request->t5577.block[1] = bit_lib_get_bits_32(protocol->encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->encoded_data, 32, 32); request->t5577.block[3] = bit_lib_get_bits_32(protocol->encoded_data, 64, 32); request->t5577.blocks_to_write = 4; result = true; } return result; } static void protocol_gallagher_render_data_internal( ProtocolGallagher* protocol, FuriString* result, bool brief) { uint8_t region = bit_lib_get_bits(protocol->data, 0, 4); uint8_t issue_level = bit_lib_get_bits(protocol->data, 4, 4); uint32_t fc = bit_lib_get_bits_32(protocol->data, 8, 24); uint32_t card_id = bit_lib_get_bits_32(protocol->data, 32, 32); if(brief) { furi_string_printf( result, "FC: %lu\n" "Card: %lu", fc, card_id); } else { furi_string_printf( result, "FC: %lu\n" "Card: %lu\n" "Region: %u\n" "Issue Level: %u", fc, card_id, region, issue_level); } } void protocol_gallagher_render_data(ProtocolGallagher* protocol, FuriString* result) { protocol_gallagher_render_data_internal(protocol, result, false); } void protocol_gallagher_render_brief_data(ProtocolGallagher* protocol, FuriString* result) { protocol_gallagher_render_data_internal(protocol, result, true); } const ProtocolBase protocol_gallagher = { .name = "Gallagher", .manufacturer = "Gallagher", .data_size = GALLAGHER_DECODED_DATA_SIZE, .features = LFRFIDFeatureASK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_gallagher_alloc, .free = (ProtocolFree)protocol_gallagher_free, .get_data = (ProtocolGetData)protocol_gallagher_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_gallagher_decoder_start, .feed = (ProtocolDecoderFeed)protocol_gallagher_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_gallagher_encoder_start, .yield = (ProtocolEncoderYield)protocol_gallagher_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_gallagher_render_data, .render_brief_data = (ProtocolRenderData)protocol_gallagher_render_brief_data, .write_data = (ProtocolWriteData)protocol_gallagher_write_data, };
13,721
C
.c
279
42.677419
100
0.646826
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,356
protocol_em4100.h
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_em4100.h
#pragma once #include <toolbox/protocols/protocol.h> extern const ProtocolBase protocol_em4100; extern const ProtocolBase protocol_em4100_32; extern const ProtocolBase protocol_em4100_16;
191
C
.c
5
36.6
45
0.857923
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,357
protocol_viking.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_viking.c
#include <furi.h> #include <toolbox/protocols/protocol.h> #include <toolbox/manchester_decoder.h> #include <bit_lib/bit_lib.h> #include "lfrfid_protocols.h" #define VIKING_CLOCK_PER_BIT (32) #define VIKING_ENCODED_BIT_SIZE (64) #define VIKING_ENCODED_BYTE_SIZE (((VIKING_ENCODED_BIT_SIZE) / 8)) #define VIKING_PREAMBLE_BIT_SIZE (24) #define VIKING_PREAMBLE_BYTE_SIZE (3) #define VIKING_ENCODED_BYTE_FULL_SIZE (VIKING_ENCODED_BYTE_SIZE + VIKING_PREAMBLE_BYTE_SIZE) #define VIKING_DECODED_DATA_SIZE 4 #define VIKING_READ_SHORT_TIME (128) #define VIKING_READ_LONG_TIME (256) #define VIKING_READ_JITTER_TIME (60) #define VIKING_READ_SHORT_TIME_LOW (VIKING_READ_SHORT_TIME - VIKING_READ_JITTER_TIME) #define VIKING_READ_SHORT_TIME_HIGH (VIKING_READ_SHORT_TIME + VIKING_READ_JITTER_TIME) #define VIKING_READ_LONG_TIME_LOW (VIKING_READ_LONG_TIME - VIKING_READ_JITTER_TIME) #define VIKING_READ_LONG_TIME_HIGH (VIKING_READ_LONG_TIME + VIKING_READ_JITTER_TIME) typedef struct { uint8_t data[VIKING_DECODED_DATA_SIZE]; uint8_t encoded_data[VIKING_ENCODED_BYTE_FULL_SIZE]; uint8_t encoded_data_index; bool encoded_polarity; ManchesterState decoder_manchester_state; } ProtocolViking; ProtocolViking* protocol_viking_alloc(void) { ProtocolViking* proto = malloc(sizeof(ProtocolViking)); return (void*)proto; } void protocol_viking_free(ProtocolViking* protocol) { free(protocol); } uint8_t* protocol_viking_get_data(ProtocolViking* protocol) { return protocol->data; } static void protocol_viking_decode(ProtocolViking* protocol) { // Copy Card ID bit_lib_copy_bits(protocol->data, 0, 32, protocol->encoded_data, 24); } static bool protocol_viking_can_be_decoded(ProtocolViking* protocol) { // check 24 bits preamble if(bit_lib_get_bits_16(protocol->encoded_data, 0, 16) != 0b1111001000000000) return false; if(bit_lib_get_bits(protocol->encoded_data, 16, 8) != 0b00000000) return false; // check next 24 bits preamble if(bit_lib_get_bits_16(protocol->encoded_data, 64, 16) != 0b1111001000000000) return false; if(bit_lib_get_bits(protocol->encoded_data, 80, 8) != 0b00000000) return false; // Checksum uint32_t checksum = bit_lib_get_bits(protocol->encoded_data, 0, 8) ^ bit_lib_get_bits(protocol->encoded_data, 8, 8) ^ bit_lib_get_bits(protocol->encoded_data, 16, 8) ^ bit_lib_get_bits(protocol->encoded_data, 24, 8) ^ bit_lib_get_bits(protocol->encoded_data, 32, 8) ^ bit_lib_get_bits(protocol->encoded_data, 40, 8) ^ bit_lib_get_bits(protocol->encoded_data, 48, 8) ^ bit_lib_get_bits(protocol->encoded_data, 56, 8) ^ 0xA8; if(checksum != 0) return false; return true; } void protocol_viking_decoder_start(ProtocolViking* protocol) { memset(protocol->encoded_data, 0, VIKING_ENCODED_BYTE_FULL_SIZE); manchester_advance( protocol->decoder_manchester_state, ManchesterEventReset, &protocol->decoder_manchester_state, NULL); } bool protocol_viking_decoder_feed(ProtocolViking* protocol, bool level, uint32_t duration) { bool result = false; ManchesterEvent event = ManchesterEventReset; if(duration > VIKING_READ_SHORT_TIME_LOW && duration < VIKING_READ_SHORT_TIME_HIGH) { if(!level) { event = ManchesterEventShortHigh; } else { event = ManchesterEventShortLow; } } else if(duration > VIKING_READ_LONG_TIME_LOW && duration < VIKING_READ_LONG_TIME_HIGH) { if(!level) { event = ManchesterEventLongHigh; } else { event = ManchesterEventLongLow; } } if(event != ManchesterEventReset) { bool data; bool data_ok = manchester_advance( protocol->decoder_manchester_state, event, &protocol->decoder_manchester_state, &data); if(data_ok) { bit_lib_push_bit(protocol->encoded_data, VIKING_ENCODED_BYTE_FULL_SIZE, data); if(protocol_viking_can_be_decoded(protocol)) { protocol_viking_decode(protocol); result = true; } } } return result; } bool protocol_viking_encoder_start(ProtocolViking* protocol) { // Preamble bit_lib_set_bits(protocol->encoded_data, 0, 0b11110010, 8); bit_lib_set_bits(protocol->encoded_data, 8, 0b00000000, 8); bit_lib_set_bits(protocol->encoded_data, 16, 0b00000000, 8); // Card Id bit_lib_copy_bits(protocol->encoded_data, 24, 32, protocol->data, 0); // Checksum uint32_t id = bit_lib_get_bits_32(protocol->data, 0, 32); uint8_t checksum = ((id >> 24) & 0xFF) ^ ((id >> 16) & 0xFF) ^ ((id >> 8) & 0xFF) ^ (id & 0xFF) ^ 0xF2 ^ 0xA8; bit_lib_set_bits(protocol->encoded_data, 56, checksum, 8); return true; } LevelDuration protocol_viking_encoder_yield(ProtocolViking* protocol) { bool level = bit_lib_get_bit(protocol->encoded_data, protocol->encoded_data_index); uint32_t duration = VIKING_CLOCK_PER_BIT / 2; if(protocol->encoded_polarity) { protocol->encoded_polarity = false; } else { level = !level; protocol->encoded_polarity = true; bit_lib_increment_index(protocol->encoded_data_index, VIKING_ENCODED_BIT_SIZE); } return level_duration_make(level, duration); } bool protocol_viking_write_data(ProtocolViking* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; // Correct protocol data by redecoding protocol_viking_encoder_start(protocol); protocol_viking_decode(protocol); protocol_viking_encoder_start(protocol); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = (LFRFID_T5577_MODULATION_MANCHESTER | LFRFID_T5577_BITRATE_RF_32 | (2 << LFRFID_T5577_MAXBLOCK_SHIFT)); request->t5577.block[1] = bit_lib_get_bits_32(protocol->encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->encoded_data, 32, 32); request->t5577.blocks_to_write = 3; result = true; } return result; } void protocol_viking_render_data(ProtocolViking* protocol, FuriString* result) { furi_string_printf(result, "ID: %08lX", bit_lib_get_bits_32(protocol->data, 0, 32)); } const ProtocolBase protocol_viking = { .name = "Viking", .manufacturer = "Viking", .data_size = VIKING_DECODED_DATA_SIZE, .features = LFRFIDFeatureASK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_viking_alloc, .free = (ProtocolFree)protocol_viking_free, .get_data = (ProtocolGetData)protocol_viking_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_viking_decoder_start, .feed = (ProtocolDecoderFeed)protocol_viking_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_viking_encoder_start, .yield = (ProtocolEncoderYield)protocol_viking_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_viking_render_data, .render_brief_data = (ProtocolRenderData)protocol_viking_render_data, .write_data = (ProtocolWriteData)protocol_viking_write_data, };
7,402
C
.c
167
37.760479
99
0.67227
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,358
protocol_idteck.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_idteck.c
#include <furi.h> #include <toolbox/protocols/protocol.h> #include <bit_lib/bit_lib.h> #include "lfrfid_protocols.h" // Example: 4944544B 351FBE4B // 01001001 01000100 01010100 01001011 00110101 00011111 10111110 01001011 // 4 9 4 4 5 4 4 B 3 5 1 F B E 4 B // 0100 1001 0100 0100 0101 0100 0100 1011 0011 0101 0001 1111 1011 1110 0100 1011 #define IDTECK_PREAMBLE_BIT_SIZE (32) #define IDTECK_PREAMBLE_DATA_SIZE (8) #define IDTECK_ENCODED_BIT_SIZE (64) #define IDTECK_ENCODED_DATA_SIZE (((IDTECK_ENCODED_BIT_SIZE) / 8) + IDTECK_PREAMBLE_DATA_SIZE) #define IDTECK_ENCODED_DATA_LAST ((IDTECK_ENCODED_BIT_SIZE) / 8) #define IDTECK_DECODED_BIT_SIZE (64) #define IDTECK_DECODED_DATA_SIZE (8) #define IDTECK_US_PER_BIT (255) #define IDTECK_ENCODER_PULSES_PER_BIT (16) typedef struct { uint8_t data_index; uint8_t bit_clock_index; bool last_bit; bool current_polarity; bool pulse_phase; } ProtocolIdteckEncoder; typedef struct { uint8_t encoded_data[IDTECK_ENCODED_DATA_SIZE]; uint8_t negative_encoded_data[IDTECK_ENCODED_DATA_SIZE]; uint8_t corrupted_encoded_data[IDTECK_ENCODED_DATA_SIZE]; uint8_t corrupted_negative_encoded_data[IDTECK_ENCODED_DATA_SIZE]; uint8_t data[IDTECK_DECODED_DATA_SIZE]; ProtocolIdteckEncoder encoder; } ProtocolIdteck; ProtocolIdteck* protocol_idteck_alloc(void) { ProtocolIdteck* protocol = malloc(sizeof(ProtocolIdteck)); return protocol; } void protocol_idteck_free(ProtocolIdteck* protocol) { free(protocol); } uint8_t* protocol_idteck_get_data(ProtocolIdteck* protocol) { return protocol->data; } void protocol_idteck_decoder_start(ProtocolIdteck* protocol) { memset(protocol->encoded_data, 0, IDTECK_ENCODED_DATA_SIZE); memset(protocol->negative_encoded_data, 0, IDTECK_ENCODED_DATA_SIZE); memset(protocol->corrupted_encoded_data, 0, IDTECK_ENCODED_DATA_SIZE); memset(protocol->corrupted_negative_encoded_data, 0, IDTECK_ENCODED_DATA_SIZE); } static bool protocol_idteck_check_preamble(uint8_t* data, size_t bit_index) { // Preamble 01001001 01000100 01010100 01001011 if(*(uint32_t*)&data[bit_index / 8] != 0b01001011010101000100010001001001) return false; return true; } static bool protocol_idteck_can_be_decoded(uint8_t* data) { if(!protocol_idteck_check_preamble(data, 0)) return false; return true; } static bool protocol_idteck_decoder_feed_internal(bool polarity, uint32_t time, uint8_t* data) { time += (IDTECK_US_PER_BIT / 2); size_t bit_count = (time / IDTECK_US_PER_BIT); bool result = false; if(bit_count < IDTECK_ENCODED_BIT_SIZE) { for(size_t i = 0; i < bit_count; i++) { bit_lib_push_bit(data, IDTECK_ENCODED_DATA_SIZE, polarity); if(protocol_idteck_can_be_decoded(data)) { result = true; break; } } } return result; } static void protocol_idteck_decoder_save(uint8_t* data_to, const uint8_t* data_from) { bit_lib_copy_bits(data_to, 0, 64, data_from, 0); } bool protocol_idteck_decoder_feed(ProtocolIdteck* protocol, bool level, uint32_t duration) { bool result = false; if(duration > (IDTECK_US_PER_BIT / 2)) { if(protocol_idteck_decoder_feed_internal(level, duration, protocol->encoded_data)) { protocol_idteck_decoder_save(protocol->data, protocol->encoded_data); FURI_LOG_D("Idteck", "Positive"); result = true; return result; } if(protocol_idteck_decoder_feed_internal( !level, duration, protocol->negative_encoded_data)) { protocol_idteck_decoder_save(protocol->data, protocol->negative_encoded_data); FURI_LOG_D("Idteck", "Negative"); result = true; return result; } } if(duration > (IDTECK_US_PER_BIT / 4)) { // Try to decode wrong phase synced data if(level) { duration += 120; } else { if(duration > 120) { duration -= 120; } } if(protocol_idteck_decoder_feed_internal( level, duration, protocol->corrupted_encoded_data)) { protocol_idteck_decoder_save(protocol->data, protocol->corrupted_encoded_data); FURI_LOG_D("Idteck", "Positive Corrupted"); result = true; return result; } if(protocol_idteck_decoder_feed_internal( !level, duration, protocol->corrupted_negative_encoded_data)) { protocol_idteck_decoder_save( protocol->data, protocol->corrupted_negative_encoded_data); FURI_LOG_D("Idteck", "Negative Corrupted"); result = true; return result; } } return result; } bool protocol_idteck_encoder_start(ProtocolIdteck* protocol) { memset(protocol->encoded_data, 0, IDTECK_ENCODED_DATA_SIZE); *(uint32_t*)&protocol->encoded_data[0] = 0b01001011010101000100010001001001; bit_lib_copy_bits(protocol->encoded_data, 32, 32, protocol->data, 32); protocol->encoder.last_bit = bit_lib_get_bit(protocol->encoded_data, IDTECK_ENCODED_BIT_SIZE - 1); protocol->encoder.data_index = 0; protocol->encoder.current_polarity = true; protocol->encoder.pulse_phase = true; protocol->encoder.bit_clock_index = 0; return true; } LevelDuration protocol_idteck_encoder_yield(ProtocolIdteck* protocol) { LevelDuration level_duration; ProtocolIdteckEncoder* encoder = &protocol->encoder; if(encoder->pulse_phase) { level_duration = level_duration_make(encoder->current_polarity, 1); encoder->pulse_phase = false; } else { level_duration = level_duration_make(!encoder->current_polarity, 1); encoder->pulse_phase = true; encoder->bit_clock_index++; if(encoder->bit_clock_index >= IDTECK_ENCODER_PULSES_PER_BIT) { encoder->bit_clock_index = 0; bool current_bit = bit_lib_get_bit(protocol->encoded_data, encoder->data_index); if(current_bit != encoder->last_bit) { encoder->current_polarity = !encoder->current_polarity; } encoder->last_bit = current_bit; bit_lib_increment_index(encoder->data_index, IDTECK_ENCODED_BIT_SIZE); } } return level_duration; } // factory code static uint32_t get_fc(const uint8_t* data) { uint32_t fc = 0; fc = bit_lib_get_bits_32(data, 0, 32); return fc; } // card number static uint32_t get_card(const uint8_t* data) { uint32_t cn = 0; cn = bit_lib_get_bits_32(data, 32, 32); return cn; } void protocol_idteck_render_data(ProtocolIdteck* protocol, FuriString* result) { const uint32_t fc = get_fc(protocol->data); const uint32_t card = get_card(protocol->data); furi_string_printf( result, "FC: %08lX\n" "Card: %08lX", fc, card); } bool protocol_idteck_write_data(ProtocolIdteck* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; protocol_idteck_encoder_start(protocol); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = LFRFID_T5577_BITRATE_RF_32 | LFRFID_T5577_MODULATION_PSK1 | (2 << LFRFID_T5577_MAXBLOCK_SHIFT); request->t5577.block[1] = bit_lib_get_bits_32(protocol->encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->encoded_data, 32, 32); request->t5577.blocks_to_write = 3; result = true; } return result; } const ProtocolBase protocol_idteck = { .name = "Idteck", .manufacturer = "IDTECK", .data_size = IDTECK_DECODED_DATA_SIZE, .features = LFRFIDFeaturePSK, .validate_count = 6, .alloc = (ProtocolAlloc)protocol_idteck_alloc, .free = (ProtocolFree)protocol_idteck_free, .get_data = (ProtocolGetData)protocol_idteck_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_idteck_decoder_start, .feed = (ProtocolDecoderFeed)protocol_idteck_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_idteck_encoder_start, .yield = (ProtocolEncoderYield)protocol_idteck_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_idteck_render_data, .render_brief_data = (ProtocolRenderData)protocol_idteck_render_data, .write_data = (ProtocolWriteData)protocol_idteck_write_data, };
8,644
C
.c
212
34.122642
96
0.660584
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,359
protocol_hid_generic.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_hid_generic.c
#include <furi.h> #include <toolbox/protocols/protocol.h> #include <lfrfid/tools/fsk_demod.h> #include <lfrfid/tools/fsk_osc.h> #include "lfrfid_protocols.h" #include <bit_lib/bit_lib.h> #define JITTER_TIME (20) #define MIN_TIME (64 - JITTER_TIME) #define MAX_TIME (80 + JITTER_TIME) #define HID_DATA_SIZE 11 #define HID_PREAMBLE_SIZE 1 #define HID_PROTOCOL_SIZE_UNKNOWN 0 #define HID_ENCODED_DATA_SIZE (HID_PREAMBLE_SIZE + HID_DATA_SIZE + HID_PREAMBLE_SIZE) #define HID_ENCODED_BIT_SIZE ((HID_PREAMBLE_SIZE + HID_DATA_SIZE) * 8) #define HID_DECODED_DATA_SIZE (6) #define HID_DECODED_BIT_SIZE ((HID_ENCODED_BIT_SIZE - HID_PREAMBLE_SIZE * 8) / 2) #define HID_PREAMBLE 0x1D typedef struct { FSKDemod* fsk_demod; } ProtocolHIDDecoder; typedef struct { FSKOsc* fsk_osc; uint8_t encoded_index; uint32_t pulse; } ProtocolHIDEncoder; typedef struct { ProtocolHIDDecoder decoder; ProtocolHIDEncoder encoder; uint8_t encoded_data[HID_ENCODED_DATA_SIZE]; uint8_t data[HID_DECODED_DATA_SIZE]; } ProtocolHID; ProtocolHID* protocol_hid_generic_alloc(void) { ProtocolHID* protocol = malloc(sizeof(ProtocolHID)); protocol->decoder.fsk_demod = fsk_demod_alloc(MIN_TIME, 6, MAX_TIME, 5); protocol->encoder.fsk_osc = fsk_osc_alloc(8, 10, 50); return protocol; } void protocol_hid_generic_free(ProtocolHID* protocol) { fsk_demod_free(protocol->decoder.fsk_demod); fsk_osc_free(protocol->encoder.fsk_osc); free(protocol); } uint8_t* protocol_hid_generic_get_data(ProtocolHID* protocol) { return protocol->data; } void protocol_hid_generic_decoder_start(ProtocolHID* protocol) { memset(protocol->encoded_data, 0, HID_ENCODED_DATA_SIZE); } static bool protocol_hid_generic_can_be_decoded(const uint8_t* data) { // check preamble if(data[0] != HID_PREAMBLE || data[HID_PREAMBLE_SIZE + HID_DATA_SIZE] != HID_PREAMBLE) { return false; } // check for manchester encoding for(size_t i = HID_PREAMBLE_SIZE; i < (HID_PREAMBLE_SIZE + HID_DATA_SIZE); i++) { for(size_t n = 0; n < 4; n++) { uint8_t bit_pair = (data[i] >> (n * 2)) & 0b11; if(bit_pair == 0b11 || bit_pair == 0b00) { return false; } } } return true; } static void protocol_hid_generic_decode(const uint8_t* from, uint8_t* to) { size_t bit_index = 0; for(size_t i = HID_PREAMBLE_SIZE; i < (HID_PREAMBLE_SIZE + HID_DATA_SIZE); i++) { for(size_t n = 0; n < 4; n++) { uint8_t bit_pair = (from[i] >> (6 - (n * 2))) & 0b11; if(bit_pair == 0b01) { bit_lib_set_bit(to, bit_index, 0); } else if(bit_pair == 0b10) { bit_lib_set_bit(to, bit_index, 1); } bit_index++; } } } /** * Decodes size from the HID Proximity header: * - If any of the first six bits is 1, the key is composed of the bits * following the first 1 * - Otherwise, if the first six bits are 0: * - If the seventh bit is 0, the key is composed of the remaining 37 bits. * - If the seventh bit is 1, the size header continues until the next 1 bit, * and the key is composed of however many bits remain. * * HID Proximity keys are 26 bits at minimum. If the header implies a key size * under 26 bits, this function returns HID_PROTOCOL_SIZE_UNKNOWN. */ static uint8_t protocol_hid_generic_decode_protocol_size(ProtocolHID* protocol) { for(size_t bit_index = 0; bit_index < 6; bit_index++) { if(bit_lib_get_bit(protocol->data, bit_index)) { return HID_DECODED_BIT_SIZE - bit_index - 1; } } if(!bit_lib_get_bit(protocol->data, 6)) { return 37; } size_t bit_index = 7; uint8_t size = 36; while(!bit_lib_get_bit(protocol->data, bit_index) && size >= 26) { size--; bit_index++; } return size < 26 ? HID_PROTOCOL_SIZE_UNKNOWN : size; } bool protocol_hid_generic_decoder_feed(ProtocolHID* protocol, bool level, uint32_t duration) { bool value; uint32_t count; bool result = false; fsk_demod_feed(protocol->decoder.fsk_demod, level, duration, &value, &count); if(count > 0) { for(size_t i = 0; i < count; i++) { bit_lib_push_bit(protocol->encoded_data, HID_ENCODED_DATA_SIZE, value); if(protocol_hid_generic_can_be_decoded(protocol->encoded_data)) { protocol_hid_generic_decode(protocol->encoded_data, protocol->data); result = true; } } } return result; } static void protocol_hid_generic_encode(ProtocolHID* protocol) { protocol->encoded_data[0] = HID_PREAMBLE; size_t bit_index = 0; for(size_t i = 0; i < HID_DECODED_BIT_SIZE; i++) { bool bit = bit_lib_get_bit(protocol->data, i); if(bit) { bit_lib_set_bit(protocol->encoded_data, 8 + bit_index, 1); bit_lib_set_bit(protocol->encoded_data, 8 + bit_index + 1, 0); } else { bit_lib_set_bit(protocol->encoded_data, 8 + bit_index, 0); bit_lib_set_bit(protocol->encoded_data, 8 + bit_index + 1, 1); } bit_index += 2; } } bool protocol_hid_generic_encoder_start(ProtocolHID* protocol) { protocol->encoder.encoded_index = 0; protocol->encoder.pulse = 0; protocol_hid_generic_encode(protocol); return true; } LevelDuration protocol_hid_generic_encoder_yield(ProtocolHID* protocol) { bool level = 0; uint32_t duration = 0; // if pulse is zero, we need to output high, otherwise we need to output low if(protocol->encoder.pulse == 0) { // get bit uint8_t bit = bit_lib_get_bit(protocol->encoded_data, protocol->encoder.encoded_index); // get pulse from oscillator bool advance = fsk_osc_next(protocol->encoder.fsk_osc, bit, &duration); if(advance) { bit_lib_increment_index(protocol->encoder.encoded_index, HID_ENCODED_BIT_SIZE); } // duration diveded by 2 because we need to output high and low duration = duration / 2; protocol->encoder.pulse = duration; level = true; } else { // output low half and reset pulse duration = protocol->encoder.pulse; protocol->encoder.pulse = 0; level = false; } return level_duration_make(level, duration); } bool protocol_hid_generic_write_data(ProtocolHID* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; // Correct protocol data by redecoding protocol_hid_generic_encoder_start(protocol); protocol_hid_generic_decode(protocol->encoded_data, protocol->data); protocol_hid_generic_encoder_start(protocol); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = LFRFID_T5577_MODULATION_FSK2a | LFRFID_T5577_BITRATE_RF_50 | (3 << LFRFID_T5577_MAXBLOCK_SHIFT); request->t5577.block[1] = bit_lib_get_bits_32(protocol->encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->encoded_data, 32, 32); request->t5577.block[3] = bit_lib_get_bits_32(protocol->encoded_data, 64, 32); request->t5577.blocks_to_write = 4; result = true; } return result; } static void protocol_hid_generic_string_cat_protocol_bits( ProtocolHID* protocol, uint8_t protocol_size, FuriString* result) { // round up to the nearest nibble const uint8_t hex_character_count = (protocol_size + 3) / 4; const uint8_t protocol_bit_index = HID_DECODED_BIT_SIZE - protocol_size; for(size_t i = 0; i < hex_character_count; i++) { uint8_t nibble = i == 0 ? bit_lib_get_bits( protocol->data, protocol_bit_index, protocol_size % 4 == 0 ? 4 : protocol_size % 4) : bit_lib_get_bits(protocol->data, protocol_bit_index + i * 4, 4); furi_string_cat_printf(result, "%X", nibble & 0xF); } } void protocol_hid_generic_render_data(ProtocolHID* protocol, FuriString* result) { const uint8_t protocol_size = protocol_hid_generic_decode_protocol_size(protocol); if(protocol_size == HID_PROTOCOL_SIZE_UNKNOWN) { furi_string_printf( result, "Generic HID Proximity\n" "Data: %02X%02X%02X%02X%02X%X", protocol->data[0], protocol->data[1], protocol->data[2], protocol->data[3], protocol->data[4], protocol->data[5] >> 4); } else { furi_string_printf( result, "%hhu-bit HID Proximity\n" "Data: ", protocol_size); protocol_hid_generic_string_cat_protocol_bits(protocol, protocol_size, result); } } const ProtocolBase protocol_hid_generic = { .name = "HIDProx", .manufacturer = "Generic", .data_size = HID_DECODED_DATA_SIZE, .features = LFRFIDFeatureASK, .validate_count = 6, .alloc = (ProtocolAlloc)protocol_hid_generic_alloc, .free = (ProtocolFree)protocol_hid_generic_free, .get_data = (ProtocolGetData)protocol_hid_generic_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_hid_generic_decoder_start, .feed = (ProtocolDecoderFeed)protocol_hid_generic_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_hid_generic_encoder_start, .yield = (ProtocolEncoderYield)protocol_hid_generic_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_hid_generic_render_data, .render_brief_data = (ProtocolRenderData)protocol_hid_generic_render_data, .write_data = (ProtocolWriteData)protocol_hid_generic_write_data, };
9,932
C
.c
247
33.307692
98
0.632725
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,360
protocol_indala26.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_indala26.c
#include <furi.h> #include <toolbox/protocols/protocol.h> #include <bit_lib/bit_lib.h> #include "lfrfid_protocols.h" #define INDALA26_PREAMBLE_BIT_SIZE (33) #define INDALA26_PREAMBLE_DATA_SIZE (5) #define INDALA26_ENCODED_BIT_SIZE (64) #define INDALA26_ENCODED_DATA_SIZE \ (((INDALA26_ENCODED_BIT_SIZE) / 8) + INDALA26_PREAMBLE_DATA_SIZE) #define INDALA26_ENCODED_DATA_LAST ((INDALA26_ENCODED_BIT_SIZE) / 8) #define INDALA26_DECODED_BIT_SIZE (28) #define INDALA26_DECODED_DATA_SIZE (4) #define INDALA26_US_PER_BIT (255) #define INDALA26_ENCODER_PULSES_PER_BIT (16) typedef struct { uint8_t data_index; uint8_t bit_clock_index; bool last_bit; bool current_polarity; bool pulse_phase; } ProtocolIndalaEncoder; typedef struct { uint8_t encoded_data[INDALA26_ENCODED_DATA_SIZE]; uint8_t negative_encoded_data[INDALA26_ENCODED_DATA_SIZE]; uint8_t corrupted_encoded_data[INDALA26_ENCODED_DATA_SIZE]; uint8_t corrupted_negative_encoded_data[INDALA26_ENCODED_DATA_SIZE]; uint8_t data[INDALA26_DECODED_DATA_SIZE]; ProtocolIndalaEncoder encoder; } ProtocolIndala; ProtocolIndala* protocol_indala26_alloc(void) { ProtocolIndala* protocol = malloc(sizeof(ProtocolIndala)); return protocol; } void protocol_indala26_free(ProtocolIndala* protocol) { free(protocol); } uint8_t* protocol_indala26_get_data(ProtocolIndala* protocol) { return protocol->data; } void protocol_indala26_decoder_start(ProtocolIndala* protocol) { memset(protocol->encoded_data, 0, INDALA26_ENCODED_DATA_SIZE); memset(protocol->negative_encoded_data, 0, INDALA26_ENCODED_DATA_SIZE); memset(protocol->corrupted_encoded_data, 0, INDALA26_ENCODED_DATA_SIZE); memset(protocol->corrupted_negative_encoded_data, 0, INDALA26_ENCODED_DATA_SIZE); } static bool protocol_indala26_check_preamble(uint8_t* data, size_t bit_index) { // Preamble 10100000 00000000 00000000 00000000 1 if(*(uint32_t*)&data[bit_index / 8] != 0b00000000000000000000000010100000) return false; if(bit_lib_get_bit(data, bit_index + 32) != 1) return false; return true; } static bool protocol_indala26_can_be_decoded(uint8_t* data) { if(!protocol_indala26_check_preamble(data, 0)) return false; if(!protocol_indala26_check_preamble(data, 64)) return false; if(bit_lib_get_bit(data, 61) != 0) return false; if(bit_lib_get_bit(data, 60) != 0) return false; return true; } static bool protocol_indala26_decoder_feed_internal(bool polarity, uint32_t time, uint8_t* data) { time += (INDALA26_US_PER_BIT / 2); size_t bit_count = (time / INDALA26_US_PER_BIT); bool result = false; if(bit_count < INDALA26_ENCODED_BIT_SIZE) { for(size_t i = 0; i < bit_count; i++) { bit_lib_push_bit(data, INDALA26_ENCODED_DATA_SIZE, polarity); if(protocol_indala26_can_be_decoded(data)) { result = true; break; } } } return result; } static void protocol_indala26_decoder_save(uint8_t* data_to, const uint8_t* data_from) { bit_lib_copy_bits(data_to, 0, 22, data_from, 33); bit_lib_copy_bits(data_to, 22, 5, data_from, 55); bit_lib_copy_bits(data_to, 27, 2, data_from, 62); } bool protocol_indala26_decoder_feed(ProtocolIndala* protocol, bool level, uint32_t duration) { bool result = false; if(duration > (INDALA26_US_PER_BIT / 2)) { if(protocol_indala26_decoder_feed_internal(level, duration, protocol->encoded_data)) { protocol_indala26_decoder_save(protocol->data, protocol->encoded_data); FURI_LOG_D("Indala26", "Positive"); result = true; return result; } if(protocol_indala26_decoder_feed_internal( !level, duration, protocol->negative_encoded_data)) { protocol_indala26_decoder_save(protocol->data, protocol->negative_encoded_data); FURI_LOG_D("Indala26", "Negative"); result = true; return result; } } if(duration > (INDALA26_US_PER_BIT / 4)) { // Try to decode wrong phase synced data if(level) { duration += 120; } else { if(duration > 120) { duration -= 120; } } if(protocol_indala26_decoder_feed_internal( level, duration, protocol->corrupted_encoded_data)) { protocol_indala26_decoder_save(protocol->data, protocol->corrupted_encoded_data); FURI_LOG_D("Indala26", "Positive Corrupted"); result = true; return result; } if(protocol_indala26_decoder_feed_internal( !level, duration, protocol->corrupted_negative_encoded_data)) { protocol_indala26_decoder_save( protocol->data, protocol->corrupted_negative_encoded_data); FURI_LOG_D("Indala26", "Negative Corrupted"); result = true; return result; } } return result; } bool protocol_indala26_encoder_start(ProtocolIndala* protocol) { memset(protocol->encoded_data, 0, INDALA26_ENCODED_DATA_SIZE); *(uint32_t*)&protocol->encoded_data[0] = 0b00000000000000000000000010100000; bit_lib_set_bit(protocol->encoded_data, 32, 1); bit_lib_copy_bits(protocol->encoded_data, 33, 22, protocol->data, 0); bit_lib_copy_bits(protocol->encoded_data, 55, 5, protocol->data, 22); bit_lib_copy_bits(protocol->encoded_data, 62, 2, protocol->data, 27); protocol->encoder.last_bit = bit_lib_get_bit(protocol->encoded_data, INDALA26_ENCODED_BIT_SIZE - 1); protocol->encoder.data_index = 0; protocol->encoder.current_polarity = true; protocol->encoder.pulse_phase = true; protocol->encoder.bit_clock_index = 0; return true; } LevelDuration protocol_indala26_encoder_yield(ProtocolIndala* protocol) { LevelDuration level_duration; ProtocolIndalaEncoder* encoder = &protocol->encoder; if(encoder->pulse_phase) { level_duration = level_duration_make(encoder->current_polarity, 1); encoder->pulse_phase = false; } else { level_duration = level_duration_make(!encoder->current_polarity, 1); encoder->pulse_phase = true; encoder->bit_clock_index++; if(encoder->bit_clock_index >= INDALA26_ENCODER_PULSES_PER_BIT) { encoder->bit_clock_index = 0; bool current_bit = bit_lib_get_bit(protocol->encoded_data, encoder->data_index); if(current_bit != encoder->last_bit) { encoder->current_polarity = !encoder->current_polarity; } encoder->last_bit = current_bit; bit_lib_increment_index(encoder->data_index, INDALA26_ENCODED_BIT_SIZE); } } return level_duration; } // factory code static uint8_t get_fc(const uint8_t* data) { uint8_t fc = 0; fc = fc << 1 | bit_lib_get_bit(data, 24); fc = fc << 1 | bit_lib_get_bit(data, 16); fc = fc << 1 | bit_lib_get_bit(data, 11); fc = fc << 1 | bit_lib_get_bit(data, 14); fc = fc << 1 | bit_lib_get_bit(data, 15); fc = fc << 1 | bit_lib_get_bit(data, 20); fc = fc << 1 | bit_lib_get_bit(data, 6); fc = fc << 1 | bit_lib_get_bit(data, 25); return fc; } // card number static uint16_t get_cn(const uint8_t* data) { uint16_t cn = 0; cn = cn << 1 | bit_lib_get_bit(data, 9); cn = cn << 1 | bit_lib_get_bit(data, 12); cn = cn << 1 | bit_lib_get_bit(data, 10); cn = cn << 1 | bit_lib_get_bit(data, 7); cn = cn << 1 | bit_lib_get_bit(data, 19); cn = cn << 1 | bit_lib_get_bit(data, 3); cn = cn << 1 | bit_lib_get_bit(data, 2); cn = cn << 1 | bit_lib_get_bit(data, 18); cn = cn << 1 | bit_lib_get_bit(data, 13); cn = cn << 1 | bit_lib_get_bit(data, 0); cn = cn << 1 | bit_lib_get_bit(data, 4); cn = cn << 1 | bit_lib_get_bit(data, 21); cn = cn << 1 | bit_lib_get_bit(data, 23); cn = cn << 1 | bit_lib_get_bit(data, 26); cn = cn << 1 | bit_lib_get_bit(data, 17); cn = cn << 1 | bit_lib_get_bit(data, 8); return cn; } void protocol_indala26_render_data_internal( ProtocolIndala* protocol, FuriString* result, bool brief) { bool wiegand_correct = true; bool checksum_correct = true; const uint8_t fc = get_fc(protocol->data); const uint16_t card = get_cn(protocol->data); const uint32_t fc_and_card = fc << 16 | card; const uint8_t checksum = bit_lib_get_bit(protocol->data, 27) << 1 | bit_lib_get_bit(protocol->data, 28); const bool even_parity = bit_lib_get_bit(protocol->data, 1); const bool odd_parity = bit_lib_get_bit(protocol->data, 5); // indala checksum uint8_t checksum_sum = 0; checksum_sum += ((fc_and_card >> 14) & 1); checksum_sum += ((fc_and_card >> 12) & 1); checksum_sum += ((fc_and_card >> 9) & 1); checksum_sum += ((fc_and_card >> 8) & 1); checksum_sum += ((fc_and_card >> 6) & 1); checksum_sum += ((fc_and_card >> 5) & 1); checksum_sum += ((fc_and_card >> 2) & 1); checksum_sum += ((fc_and_card >> 0) & 1); checksum_sum = checksum_sum & 0b1; if(checksum_sum == 1 && checksum == 0b01) { } else if(checksum_sum == 0 && checksum == 0b10) { } else { checksum_correct = false; } // wiegand parity uint8_t even_parity_sum = 0; for(int8_t i = 12; i < 24; i++) { if(((fc_and_card >> i) & 1) == 1) { even_parity_sum++; } } if(even_parity_sum % 2 != even_parity) wiegand_correct = false; uint8_t odd_parity_sum = 1; for(int8_t i = 0; i < 12; i++) { if(((fc_and_card >> i) & 1) == 1) { odd_parity_sum++; } } if(odd_parity_sum % 2 != odd_parity) wiegand_correct = false; if(brief) { furi_string_printf( result, "FC: %u\n" "Card: %u", fc, card); } else { furi_string_printf( result, "FC: %u\n" "Card: %u\n" "Parity: %c\n" "Checksum: %c", fc, card, (wiegand_correct ? '+' : '-'), (checksum_correct ? '+' : '-')); } } void protocol_indala26_render_data(ProtocolIndala* protocol, FuriString* result) { protocol_indala26_render_data_internal(protocol, result, false); } void protocol_indala26_render_brief_data(ProtocolIndala* protocol, FuriString* result) { protocol_indala26_render_data_internal(protocol, result, true); } bool protocol_indala26_write_data(ProtocolIndala* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; protocol_indala26_encoder_start(protocol); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = LFRFID_T5577_BITRATE_RF_32 | LFRFID_T5577_MODULATION_PSK1 | (2 << LFRFID_T5577_MAXBLOCK_SHIFT); request->t5577.block[1] = bit_lib_get_bits_32(protocol->encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->encoded_data, 32, 32); request->t5577.blocks_to_write = 3; result = true; } return result; } const ProtocolBase protocol_indala26 = { .name = "Indala26", .manufacturer = "Motorola", .data_size = INDALA26_DECODED_DATA_SIZE, .features = LFRFIDFeaturePSK, .validate_count = 6, .alloc = (ProtocolAlloc)protocol_indala26_alloc, .free = (ProtocolFree)protocol_indala26_free, .get_data = (ProtocolGetData)protocol_indala26_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_indala26_decoder_start, .feed = (ProtocolDecoderFeed)protocol_indala26_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_indala26_encoder_start, .yield = (ProtocolEncoderYield)protocol_indala26_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_indala26_render_data, .render_brief_data = (ProtocolRenderData)protocol_indala26_render_brief_data, .write_data = (ProtocolWriteData)protocol_indala26_write_data, };
12,232
C
.c
300
34.043333
98
0.630294
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,361
protocol_jablotron.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_jablotron.c
#include <furi.h> #include "toolbox/level_duration.h" #include "protocol_jablotron.h" #include <toolbox/manchester_decoder.h> #include <bit_lib/bit_lib.h> #include "lfrfid_protocols.h" #define JABLOTRON_ENCODED_BIT_SIZE (64) #define JABLOTRON_ENCODED_BYTE_SIZE (((JABLOTRON_ENCODED_BIT_SIZE) / 8)) #define JABLOTRON_PREAMBLE_BIT_SIZE (16) #define JABLOTRON_PREAMBLE_BYTE_SIZE (2) #define JABLOTRON_ENCODED_BYTE_FULL_SIZE \ (JABLOTRON_ENCODED_BYTE_SIZE + JABLOTRON_PREAMBLE_BYTE_SIZE) #define JABLOTRON_DECODED_DATA_SIZE (5) #define JABLOTRON_SHORT_TIME (256) #define JABLOTRON_LONG_TIME (512) #define JABLOTRON_JITTER_TIME (120) #define JABLOTRON_SHORT_TIME_LOW (JABLOTRON_SHORT_TIME - JABLOTRON_JITTER_TIME) #define JABLOTRON_SHORT_TIME_HIGH (JABLOTRON_SHORT_TIME + JABLOTRON_JITTER_TIME) #define JABLOTRON_LONG_TIME_LOW (JABLOTRON_LONG_TIME - JABLOTRON_JITTER_TIME) #define JABLOTRON_LONG_TIME_HIGH (JABLOTRON_LONG_TIME + JABLOTRON_JITTER_TIME) typedef struct { bool last_short; bool last_level; size_t encoded_index; uint8_t encoded_data[JABLOTRON_ENCODED_BYTE_FULL_SIZE]; uint8_t data[JABLOTRON_DECODED_DATA_SIZE]; } ProtocolJablotron; ProtocolJablotron* protocol_jablotron_alloc(void) { ProtocolJablotron* protocol = malloc(sizeof(ProtocolJablotron)); return protocol; } void protocol_jablotron_free(ProtocolJablotron* protocol) { free(protocol); } uint8_t* protocol_jablotron_get_data(ProtocolJablotron* proto) { return proto->data; } void protocol_jablotron_decoder_start(ProtocolJablotron* protocol) { memset(protocol->encoded_data, 0, JABLOTRON_ENCODED_BYTE_FULL_SIZE); protocol->last_short = false; } uint8_t protocol_jablotron_checksum(uint8_t* bits) { uint8_t chksum = 0; for(uint8_t i = 16; i < 56; i += 8) { chksum += bit_lib_get_bits(bits, i, 8); } chksum ^= 0x3A; return chksum; } uint64_t protocol_jablotron_card_id(uint8_t* bytes) { uint64_t id = 0; for(int i = 0; i < 5; i++) { id *= 100; id += ((bytes[i] & 0xF0) >> 4) * 10 + (bytes[i] & 0x0F); } return id; } static bool protocol_jablotron_can_be_decoded(ProtocolJablotron* protocol) { // check 11 bits preamble if(bit_lib_get_bits_16(protocol->encoded_data, 0, 16) != 0b1111111111111111) return false; // check next 11 bits preamble if(bit_lib_get_bits_16(protocol->encoded_data, 64, 16) != 0b1111111111111111) return false; uint8_t checksum = bit_lib_get_bits(protocol->encoded_data, 56, 8); if(checksum != protocol_jablotron_checksum(protocol->encoded_data)) return false; return true; } void protocol_jablotron_decode(ProtocolJablotron* protocol) { bit_lib_copy_bits(protocol->data, 0, 40, protocol->encoded_data, 16); } bool protocol_jablotron_decoder_feed(ProtocolJablotron* protocol, bool level, uint32_t duration) { UNUSED(level); bool pushed = false; // Bi-Phase Manchester decoding if(duration >= JABLOTRON_SHORT_TIME_LOW && duration <= JABLOTRON_SHORT_TIME_HIGH) { if(protocol->last_short == false) { protocol->last_short = true; } else { pushed = true; bit_lib_push_bit(protocol->encoded_data, JABLOTRON_ENCODED_BYTE_FULL_SIZE, false); protocol->last_short = false; } } else if(duration >= JABLOTRON_LONG_TIME_LOW && duration <= JABLOTRON_LONG_TIME_HIGH) { if(protocol->last_short == false) { pushed = true; bit_lib_push_bit(protocol->encoded_data, JABLOTRON_ENCODED_BYTE_FULL_SIZE, true); } else { // reset protocol->last_short = false; } } else { // reset protocol->last_short = false; } if(pushed && protocol_jablotron_can_be_decoded(protocol)) { protocol_jablotron_decode(protocol); return true; } return false; } bool protocol_jablotron_encoder_start(ProtocolJablotron* protocol) { // preamble bit_lib_set_bits(protocol->encoded_data, 0, 0b11111111, 8); bit_lib_set_bits(protocol->encoded_data, 8, 0b11111111, 8); // Full code bit_lib_copy_bits(protocol->encoded_data, 16, 40, protocol->data, 0); // Checksum bit_lib_set_bits( protocol->encoded_data, 56, protocol_jablotron_checksum(protocol->encoded_data), 8); protocol->encoded_index = 0; protocol->last_short = false; protocol->last_level = false; return true; } LevelDuration protocol_jablotron_encoder_yield(ProtocolJablotron* protocol) { uint32_t duration; protocol->last_level = !protocol->last_level; bool bit = bit_lib_get_bit(protocol->encoded_data, protocol->encoded_index); // Bi-Phase Manchester encoder if(bit) { // one long pulse for 1 duration = JABLOTRON_LONG_TIME / 8; bit_lib_increment_index(protocol->encoded_index, JABLOTRON_ENCODED_BIT_SIZE); } else { // two short pulses for 0 duration = JABLOTRON_SHORT_TIME / 8; if(protocol->last_short) { bit_lib_increment_index(protocol->encoded_index, JABLOTRON_ENCODED_BIT_SIZE); protocol->last_short = false; } else { protocol->last_short = true; } } return level_duration_make(protocol->last_level, duration); } void protocol_jablotron_render_data(ProtocolJablotron* protocol, FuriString* result) { uint64_t id = protocol_jablotron_card_id(protocol->data); furi_string_printf(result, "Card: %llX", id); } bool protocol_jablotron_write_data(ProtocolJablotron* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; // Correct protocol data by redecoding protocol_jablotron_encoder_start(protocol); protocol_jablotron_decode(protocol); protocol_jablotron_encoder_start(protocol); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = LFRFID_T5577_MODULATION_DIPHASE | LFRFID_T5577_BITRATE_RF_64 | (2 << LFRFID_T5577_MAXBLOCK_SHIFT); request->t5577.block[1] = bit_lib_get_bits_32(protocol->encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->encoded_data, 32, 32); request->t5577.blocks_to_write = 3; result = true; } return result; } const ProtocolBase protocol_jablotron = { .name = "Jablotron", .manufacturer = "Jablotron", .data_size = JABLOTRON_DECODED_DATA_SIZE, .features = LFRFIDFeatureASK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_jablotron_alloc, .free = (ProtocolFree)protocol_jablotron_free, .get_data = (ProtocolGetData)protocol_jablotron_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_jablotron_decoder_start, .feed = (ProtocolDecoderFeed)protocol_jablotron_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_jablotron_encoder_start, .yield = (ProtocolEncoderYield)protocol_jablotron_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_jablotron_render_data, .render_brief_data = (ProtocolRenderData)protocol_jablotron_render_data, .write_data = (ProtocolWriteData)protocol_jablotron_write_data, };
7,299
C
.c
178
35.382022
98
0.687218
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,362
protocol_em4100.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_em4100.c
#include <furi.h> #include <toolbox/protocols/protocol.h> #include <toolbox/manchester_decoder.h> #include "lfrfid_protocols.h" typedef uint64_t EM4100DecodedData; typedef uint64_t EM4100Epilogue; #define EM_HEADER_POS (55) #define EM_HEADER_MASK (0x1FFLLU << EM_HEADER_POS) #define EM_FIRST_ROW_POS (50) #define EM_ROW_COUNT (10) #define EM_COLUMN_COUNT (4) #define EM_BITS_PER_ROW_COUNT (EM_COLUMN_COUNT + 1) #define EM_COLUMN_POS (4) #define EM_STOP_POS (0) #define EM_STOP_MASK (0x1LLU << EM_STOP_POS) #define EM_HEADER_AND_STOP_MASK (EM_HEADER_MASK | EM_STOP_MASK) #define EM_HEADER_AND_STOP_DATA (EM_HEADER_MASK) #define EM4100_DECODED_DATA_SIZE (5) #define EM4100_ENCODED_DATA_SIZE (sizeof(EM4100DecodedData)) #define EM_READ_SHORT_TIME_BASE (256) #define EM_READ_LONG_TIME_BASE (512) #define EM_READ_JITTER_TIME_BASE (100) #define EM_ENCODED_DATA_HEADER (0xFF80000000000000ULL) typedef struct { uint8_t data[EM4100_DECODED_DATA_SIZE]; EM4100DecodedData encoded_data; EM4100Epilogue encoded_epilogue; uint8_t encoded_data_index; bool encoded_polarity; ManchesterState decoder_manchester_state; uint8_t clock_per_bit; } ProtocolEM4100; uint16_t protocol_em4100_get_time_divisor(ProtocolEM4100* proto) { switch(proto->clock_per_bit) { case 64: return 1; case 32: return 2; case 16: return 4; default: return 1; } } uint32_t protocol_em4100_get_t5577_bitrate(ProtocolEM4100* proto) { switch(proto->clock_per_bit) { case 64: return LFRFID_T5577_BITRATE_RF_64; case 32: return LFRFID_T5577_BITRATE_RF_32; case 16: return LFRFID_T5577_BITRATE_RF_16; default: return LFRFID_T5577_BITRATE_RF_64; } } uint16_t protocol_em4100_get_short_time_low(ProtocolEM4100* proto) { return EM_READ_SHORT_TIME_BASE / protocol_em4100_get_time_divisor(proto) - EM_READ_JITTER_TIME_BASE / protocol_em4100_get_time_divisor(proto); } uint16_t protocol_em4100_get_short_time_high(ProtocolEM4100* proto) { return EM_READ_SHORT_TIME_BASE / protocol_em4100_get_time_divisor(proto) + EM_READ_JITTER_TIME_BASE / protocol_em4100_get_time_divisor(proto); } uint16_t protocol_em4100_get_long_time_low(ProtocolEM4100* proto) { return EM_READ_LONG_TIME_BASE / protocol_em4100_get_time_divisor(proto) - EM_READ_JITTER_TIME_BASE / protocol_em4100_get_time_divisor(proto); } uint16_t protocol_em4100_get_long_time_high(ProtocolEM4100* proto) { return EM_READ_LONG_TIME_BASE / protocol_em4100_get_time_divisor(proto) + EM_READ_JITTER_TIME_BASE / protocol_em4100_get_time_divisor(proto); } ProtocolEM4100* protocol_em4100_alloc(void) { ProtocolEM4100* proto = malloc(sizeof(ProtocolEM4100)); proto->clock_per_bit = 64; return (void*)proto; } ProtocolEM4100* protocol_em4100_16_alloc(void) { ProtocolEM4100* proto = malloc(sizeof(ProtocolEM4100)); proto->clock_per_bit = 16; return (void*)proto; } ProtocolEM4100* protocol_em4100_32_alloc(void) { ProtocolEM4100* proto = malloc(sizeof(ProtocolEM4100)); proto->clock_per_bit = 32; return (void*)proto; } void protocol_em4100_free(ProtocolEM4100* proto) { free(proto); } uint8_t* protocol_em4100_get_data(ProtocolEM4100* proto) { return proto->data; } static void em4100_decode( const uint8_t* encoded_data, const uint8_t encoded_data_size, uint8_t* decoded_data, const uint8_t decoded_data_size) { furi_check(decoded_data_size >= EM4100_DECODED_DATA_SIZE); furi_check(encoded_data_size >= EM4100_ENCODED_DATA_SIZE); uint8_t decoded_data_index = 0; EM4100DecodedData card_data = *((EM4100DecodedData*)(encoded_data)); // clean result memset(decoded_data, 0, decoded_data_size); // header for(uint8_t i = 0; i < 9; i++) { card_data = card_data << 1; } // nibbles uint8_t value = 0; for(uint8_t r = 0; r < EM_ROW_COUNT; r++) { uint8_t nibble = 0; for(uint8_t i = 0; i < 5; i++) { if(i < 4) nibble = (nibble << 1) | (card_data & (1LLU << 63) ? 1 : 0); card_data = card_data << 1; } value = (value << 4) | nibble; if(r % 2) { decoded_data[decoded_data_index] |= value; decoded_data_index++; value = 0; } } } static bool em4100_can_be_decoded( const uint8_t* encoded_data, const uint8_t encoded_data_size, const uint8_t* encoded_epilogue) { furi_check(encoded_data_size >= EM4100_ENCODED_DATA_SIZE); const EM4100DecodedData* card_data = (EM4100DecodedData*)encoded_data; const EM4100Epilogue* epilogue = (EM4100Epilogue*)encoded_epilogue; // check first 9 bytes on epilogue (to prevent conflict with Electra protocol) if((*epilogue & EM_ENCODED_DATA_HEADER) != EM_ENCODED_DATA_HEADER) return false; // check header and stop bit if((*card_data & EM_HEADER_AND_STOP_MASK) != EM_HEADER_AND_STOP_DATA) return false; // check row parity for(uint8_t i = 0; i < EM_ROW_COUNT; i++) { uint8_t parity_sum = 0; for(uint8_t j = 0; j < EM_BITS_PER_ROW_COUNT; j++) { parity_sum += (*card_data >> (EM_FIRST_ROW_POS - i * EM_BITS_PER_ROW_COUNT + j)) & 1; } if(parity_sum % 2) { return false; } } // check columns parity for(uint8_t i = 0; i < EM_COLUMN_COUNT; i++) { uint8_t parity_sum = 0; for(uint8_t j = 0; j < EM_ROW_COUNT + 1; j++) { parity_sum += (*card_data >> (EM_COLUMN_POS - i + j * EM_BITS_PER_ROW_COUNT)) & 1; } if(parity_sum % 2) { return false; } } return true; } void protocol_em4100_decoder_start(ProtocolEM4100* proto) { memset(proto->data, 0, EM4100_DECODED_DATA_SIZE); proto->encoded_data = 0; manchester_advance( proto->decoder_manchester_state, ManchesterEventReset, &proto->decoder_manchester_state, NULL); } bool protocol_em4100_decoder_feed(ProtocolEM4100* proto, bool level, uint32_t duration) { bool result = false; ManchesterEvent event = ManchesterEventReset; if(duration > protocol_em4100_get_short_time_low(proto) && duration < protocol_em4100_get_short_time_high(proto)) { if(!level) { event = ManchesterEventShortHigh; } else { event = ManchesterEventShortLow; } } else if( duration > protocol_em4100_get_long_time_low(proto) && duration < protocol_em4100_get_long_time_high(proto)) { if(!level) { event = ManchesterEventLongHigh; } else { event = ManchesterEventLongLow; } } if(event != ManchesterEventReset) { bool data; bool data_ok = manchester_advance( proto->decoder_manchester_state, event, &proto->decoder_manchester_state, &data); if(data_ok) { bool carry = proto->encoded_epilogue >> 63 & 0b1; proto->encoded_data = (proto->encoded_data << 1) | carry; proto->encoded_epilogue = (proto->encoded_epilogue << 1) | data; if(em4100_can_be_decoded( (uint8_t*)&proto->encoded_data, sizeof(EM4100DecodedData), (uint8_t*)&proto->encoded_epilogue)) { em4100_decode( (uint8_t*)&proto->encoded_data, sizeof(EM4100DecodedData), proto->data, EM4100_DECODED_DATA_SIZE); result = true; } } } return result; } static void em4100_write_nibble(bool low_nibble, uint8_t data, EM4100DecodedData* encoded_data) { uint8_t parity_sum = 0; uint8_t start = 0; if(!low_nibble) start = 4; for(int8_t i = (start + 3); i >= start; i--) { parity_sum += (data >> i) & 1; *encoded_data = (*encoded_data << 1) | ((data >> i) & 1); } *encoded_data = (*encoded_data << 1) | ((parity_sum % 2) & 1); } bool protocol_em4100_encoder_start(ProtocolEM4100* proto) { // header proto->encoded_data = 0b111111111; // data for(uint8_t i = 0; i < EM4100_DECODED_DATA_SIZE; i++) { em4100_write_nibble(false, proto->data[i], &proto->encoded_data); em4100_write_nibble(true, proto->data[i], &proto->encoded_data); } // column parity and stop bit uint8_t parity_sum; for(uint8_t c = 0; c < EM_COLUMN_COUNT; c++) { parity_sum = 0; for(uint8_t i = 1; i <= EM_ROW_COUNT; i++) { uint8_t parity_bit = (proto->encoded_data >> (i * EM_BITS_PER_ROW_COUNT - 1)) & 1; parity_sum += parity_bit; } proto->encoded_data = (proto->encoded_data << 1) | ((parity_sum % 2) & 1); } // stop bit proto->encoded_data = (proto->encoded_data << 1) | 0; proto->encoded_data_index = 0; proto->encoded_polarity = true; return true; } LevelDuration protocol_em4100_encoder_yield(ProtocolEM4100* proto) { bool level = (proto->encoded_data >> (63 - proto->encoded_data_index)) & 1; uint32_t duration = proto->clock_per_bit / 2; if(proto->encoded_polarity) { proto->encoded_polarity = false; } else { level = !level; proto->encoded_polarity = true; proto->encoded_data_index++; if(proto->encoded_data_index >= 64) { proto->encoded_data_index = 0; } } return level_duration_make(level, duration); } bool protocol_em4100_write_data(ProtocolEM4100* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; // Correct protocol data by redecoding protocol_em4100_encoder_start(protocol); em4100_decode( (uint8_t*)&protocol->encoded_data, sizeof(EM4100DecodedData), protocol->data, EM4100_DECODED_DATA_SIZE); protocol_em4100_encoder_start(protocol); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = (LFRFID_T5577_MODULATION_MANCHESTER | protocol_em4100_get_t5577_bitrate(protocol) | (2 << LFRFID_T5577_MAXBLOCK_SHIFT)); request->t5577.block[1] = protocol->encoded_data >> 32; request->t5577.block[2] = protocol->encoded_data; request->t5577.blocks_to_write = 3; result = true; } return result; } void protocol_em4100_render_data(ProtocolEM4100* protocol, FuriString* result) { uint8_t* data = protocol->data; furi_string_printf( result, "FC: %03u Card: %05hu CL:%hhu\n" "DEZ 8: %08lu", data[2], (uint16_t)((data[3] << 8) | (data[4])), protocol->clock_per_bit, (uint32_t)((data[2] << 16) | (data[3] << 8) | (data[4]))); } const ProtocolBase protocol_em4100 = { .name = "EM4100", .manufacturer = "EM-Micro", .data_size = EM4100_DECODED_DATA_SIZE, .features = LFRFIDFeatureASK | LFRFIDFeaturePSK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_em4100_alloc, .free = (ProtocolFree)protocol_em4100_free, .get_data = (ProtocolGetData)protocol_em4100_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_em4100_decoder_start, .feed = (ProtocolDecoderFeed)protocol_em4100_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_em4100_encoder_start, .yield = (ProtocolEncoderYield)protocol_em4100_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_em4100_render_data, .render_brief_data = (ProtocolRenderData)protocol_em4100_render_data, .write_data = (ProtocolWriteData)protocol_em4100_write_data, }; const ProtocolBase protocol_em4100_32 = { .name = "EM4100/32", .manufacturer = "EM-Micro", .data_size = EM4100_DECODED_DATA_SIZE, .features = LFRFIDFeatureASK | LFRFIDFeaturePSK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_em4100_32_alloc, .free = (ProtocolFree)protocol_em4100_free, .get_data = (ProtocolGetData)protocol_em4100_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_em4100_decoder_start, .feed = (ProtocolDecoderFeed)protocol_em4100_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_em4100_encoder_start, .yield = (ProtocolEncoderYield)protocol_em4100_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_em4100_render_data, .render_brief_data = (ProtocolRenderData)protocol_em4100_render_data, .write_data = (ProtocolWriteData)protocol_em4100_write_data, }; const ProtocolBase protocol_em4100_16 = { .name = "EM4100/16", .manufacturer = "EM-Micro", .data_size = EM4100_DECODED_DATA_SIZE, .features = LFRFIDFeatureASK | LFRFIDFeaturePSK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_em4100_16_alloc, .free = (ProtocolFree)protocol_em4100_free, .get_data = (ProtocolGetData)protocol_em4100_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_em4100_decoder_start, .feed = (ProtocolDecoderFeed)protocol_em4100_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_em4100_encoder_start, .yield = (ProtocolEncoderYield)protocol_em4100_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_em4100_render_data, .render_brief_data = (ProtocolRenderData)protocol_em4100_render_data, .write_data = (ProtocolWriteData)protocol_em4100_write_data, };
13,727
C
.c
359
31.649025
97
0.641101
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,363
lfrfid_protocols.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/lfrfid_protocols.c
#include "lfrfid_protocols.h" #include "protocol_em4100.h" #include "protocol_electra.h" #include "protocol_h10301.h" #include "protocol_idteck.h" #include "protocol_indala26.h" #include "protocol_io_prox_xsf.h" #include "protocol_awid.h" #include "protocol_fdx_a.h" #include "protocol_fdx_b.h" #include "protocol_hid_generic.h" #include "protocol_hid_ex_generic.h" #include "protocol_pyramid.h" #include "protocol_viking.h" #include "protocol_jablotron.h" #include "protocol_paradox.h" #include "protocol_pac_stanley.h" #include "protocol_keri.h" #include "protocol_gallagher.h" #include "protocol_nexwatch.h" #include "protocol_securakey.h" #include "protocol_gproxii.h" const ProtocolBase* lfrfid_protocols[] = { [LFRFIDProtocolEM4100] = &protocol_em4100, [LFRFIDProtocolEM4100_32] = &protocol_em4100_32, [LFRFIDProtocolEM4100_16] = &protocol_em4100_16, [LFRFIDProtocolElectra] = &protocol_electra, [LFRFIDProtocolH10301] = &protocol_h10301, [LFRFIDProtocolIdteck] = &protocol_idteck, [LFRFIDProtocolIndala26] = &protocol_indala26, [LFRFIDProtocolIOProxXSF] = &protocol_io_prox_xsf, [LFRFIDProtocolAwid] = &protocol_awid, [LFRFIDProtocolFDXA] = &protocol_fdx_a, [LFRFIDProtocolFDXB] = &protocol_fdx_b, [LFRFIDProtocolHidGeneric] = &protocol_hid_generic, [LFRFIDProtocolHidExGeneric] = &protocol_hid_ex_generic, [LFRFIDProtocolPyramid] = &protocol_pyramid, [LFRFIDProtocolViking] = &protocol_viking, [LFRFIDProtocolJablotron] = &protocol_jablotron, [LFRFIDProtocolParadox] = &protocol_paradox, [LFRFIDProtocolPACStanley] = &protocol_pac_stanley, [LFRFIDProtocolKeri] = &protocol_keri, [LFRFIDProtocolGallagher] = &protocol_gallagher, [LFRFIDProtocolNexwatch] = &protocol_nexwatch, [LFRFIDProtocolSecurakey] = &protocol_securakey, [LFRFIDProtocolGProxII] = &protocol_gproxii, };
1,873
C
.c
47
36.87234
60
0.758904
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,364
lfrfid_protocols.h
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/lfrfid_protocols.h
#pragma once #include <toolbox/protocols/protocol.h> #include "../tools/t5577.h" typedef enum { LFRFIDFeatureASK = 1 << 0, /** ASK Demodulation */ LFRFIDFeaturePSK = 1 << 1, /** PSK Demodulation */ } LFRFIDFeature; typedef enum { LFRFIDProtocolEM4100, LFRFIDProtocolEM4100_32, LFRFIDProtocolEM4100_16, LFRFIDProtocolElectra, LFRFIDProtocolH10301, LFRFIDProtocolIdteck, LFRFIDProtocolIndala26, LFRFIDProtocolIOProxXSF, LFRFIDProtocolAwid, LFRFIDProtocolFDXA, LFRFIDProtocolFDXB, LFRFIDProtocolHidGeneric, LFRFIDProtocolHidExGeneric, LFRFIDProtocolPyramid, LFRFIDProtocolViking, LFRFIDProtocolJablotron, LFRFIDProtocolParadox, LFRFIDProtocolPACStanley, LFRFIDProtocolKeri, LFRFIDProtocolGallagher, LFRFIDProtocolNexwatch, LFRFIDProtocolSecurakey, LFRFIDProtocolGProxII, LFRFIDProtocolMax, } LFRFIDProtocol; extern const ProtocolBase* lfrfid_protocols[]; typedef enum { LFRFIDWriteTypeT5577, } LFRFIDWriteType; typedef struct { LFRFIDWriteType write_type; union { LFRFIDT5577 t5577; }; } LFRFIDWriteRequest;
1,138
C
.c
43
22.372093
54
0.772477
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,365
protocol_securakey.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_securakey.c
// The timing parameters and data structure used in this file // are based on the knowledge found in Proxmark3's firmware: // https://github.com/RfidResearchGroup/proxmark3/blob/1c52152d30f7744c0336633317ea6640dbcdc796/client/src/cmdlfsecurakey.c // PM3's repo has mentioned the existence of non-26-or-32-bit formats. // Those are not supported here for preventing false positives. #include <furi.h> #include <toolbox/protocols/protocol.h> #include <toolbox/hex.h> #include <bit_lib/bit_lib.h> #include "lfrfid_protocols.h" #include <toolbox/manchester_decoder.h> #define TAG "SECURAKEY" #define SECURAKEY_RKKT_ENCODED_FULL_SIZE_BITS (96) #define SECURAKEY_RKKT_ENCODED_FULL_SIZE_BYTE (12) #define SECURAKEY_RKKTH_ENCODED_FULL_SIZE_BITS (64) #define SECURAKEY_RKKTH_ENCODED_FULL_SIZE_BYTE (8) #define SECURAKEY_DECODED_DATA_SIZE_BITS (48) // RKKT: 16-bit for facility code/number, 16-bit for card number, 16-bit for two checksum // RKKTH: 16-bit zero padding, 32-bit card number #define SECURAKEY_DECODED_DATA_SIZE_BYTES (SECURAKEY_DECODED_DATA_SIZE_BITS / 8) #define LFRFID_FREQUENCY (125000) #define SECURAKEY_CLOCK_PER_BIT (40) // RF/40 #define SECURAKEY_READ_LONG_TIME \ (1000000 / (LFRFID_FREQUENCY / SECURAKEY_CLOCK_PER_BIT)) // 1000000 micro sec / sec #define SECURAKEY_READ_SHORT_TIME (SECURAKEY_READ_LONG_TIME / 2) #define SECURAKEY_READ_JITTER_TIME (SECURAKEY_READ_SHORT_TIME * 40 / 100) // 40% jitter tolerance #define SECURAKEY_READ_SHORT_TIME_LOW \ (SECURAKEY_READ_SHORT_TIME - \ SECURAKEY_READ_JITTER_TIME) // these are used for manchester decoding #define SECURAKEY_READ_SHORT_TIME_HIGH (SECURAKEY_READ_SHORT_TIME + SECURAKEY_READ_JITTER_TIME) #define SECURAKEY_READ_LONG_TIME_LOW (SECURAKEY_READ_LONG_TIME - SECURAKEY_READ_JITTER_TIME) #define SECURAKEY_READ_LONG_TIME_HIGH (SECURAKEY_READ_LONG_TIME + SECURAKEY_READ_JITTER_TIME) typedef struct { uint8_t data[SECURAKEY_DECODED_DATA_SIZE_BYTES]; uint8_t RKKT_encoded_data[SECURAKEY_RKKT_ENCODED_FULL_SIZE_BYTE]; uint8_t RKKTH_encoded_data[SECURAKEY_RKKTH_ENCODED_FULL_SIZE_BYTE]; uint8_t encoded_data_index; bool encoded_polarity; ManchesterState decoder_manchester_state; uint8_t bit_format; } ProtocolSecurakey; ProtocolSecurakey* protocol_securakey_alloc(void) { ProtocolSecurakey* protocol = malloc(sizeof(ProtocolSecurakey)); return (void*)protocol; } void protocol_securakey_free(ProtocolSecurakey* protocol) { free(protocol); } uint8_t* protocol_securakey_get_data(ProtocolSecurakey* protocol) { return protocol->data; } static bool protocol_securakey_can_be_decoded(ProtocolSecurakey* protocol) { // check 19 bits preamble + format flag if(bit_lib_get_bits_32(protocol->RKKT_encoded_data, 0, 19) == 0b0111111111000000000) { protocol->bit_format = 0; return true; } else if(bit_lib_get_bits_32(protocol->RKKT_encoded_data, 0, 19) == 0b0111111111001011010) { protocol->bit_format = 26; return true; } else if(bit_lib_get_bits_32(protocol->RKKT_encoded_data, 0, 19) == 0b0111111111001100000) { protocol->bit_format = 32; return true; } else { return false; } } static void protocol_securakey_decode(ProtocolSecurakey* protocol) { memset(protocol->data, 0, SECURAKEY_DECODED_DATA_SIZE_BYTES); // RKKT_encoded_data looks like this (citation: pm3 repo): // 26-bit format (1-bit even parity bit, 8-bit facility number, 16-bit card number, 1-bit odd parity bit) // preamble ??bitlen reserved EPf fffffffc cccccccc cccccccOP CS? CS2? // 0111111111 0 01011010 0 00000000 0 00000010 0 00110110 0 00111110 0 01100010 0 00001111 0 01100000 0 00000000 0 0000 // 32-bit format (1-bit even parity bit, 14-bit facility number, 16-bit card number, 1-bit odd parity bit) // preamble ??bitlen reserved EPfffffff fffffffc cccccccc cccccccOP CS? CS2? // 0111111111 0 01100000 0 00000000 0 10000100 0 11001010 0 01011011 0 01010110 0 00010110 0 11100000 0 00000000 0 0000 // RKKTH-02 encoded data sometimes look like this // plaintext format (preamble and 32-bit? card number) // preamble unknown unknown cccccccc cccccccc cccccccc cccccccc // 0 1 2 3 4 5 6 // 0123456789 0 12345678 9 01234567 8 90123456 7 89012345 6 78901234 5 67890123 // 0111111111 0 00000000 0 00000000 0 00000000 0 00011101 0 00000100 0 01001010 if(bit_lib_get_bits(protocol->RKKT_encoded_data, 13, 6) == 0) { FURI_LOG_D(TAG, "Plaintext RKKTH detected"); protocol->bit_format = 0; // get card number (c) bit_lib_copy_bits(protocol->data, 16, 8, protocol->RKKT_encoded_data, 29); // skip spacers (0s) bit_lib_copy_bits(protocol->data, 24, 8, protocol->RKKT_encoded_data, 38); bit_lib_copy_bits(protocol->data, 32, 8, protocol->RKKT_encoded_data, 47); bit_lib_copy_bits(protocol->data, 40, 8, protocol->RKKT_encoded_data, 56); } else { if(bit_lib_get_bits(protocol->RKKT_encoded_data, 13, 6) == 26) { FURI_LOG_D(TAG, "26-bit RKKT detected"); protocol->bit_format = 26; // left two 0 paddings in the beginning for easier parsing (00011010 = 011010) // get facility number (f) bit_lib_copy_bits(protocol->data, 8, 1, protocol->RKKT_encoded_data, 36); // have to skip one spacer bit_lib_copy_bits(protocol->data, 9, 7, protocol->RKKT_encoded_data, 38); } else if(bit_lib_get_bits(protocol->RKKT_encoded_data, 13, 6) == 32) { FURI_LOG_D(TAG, "32-bit RKKT detected"); protocol->bit_format = 32; // same two 0 paddings here, otherwise should be bit_lib_copy_bits(protocol->data, 8, 7, protocol->RKKT_encoded_data, 30); bit_lib_copy_bits(protocol->data, 2, 7, protocol->RKKT_encoded_data, 30); // have to skip one spacer bit_lib_copy_bits(protocol->data, 9, 7, protocol->RKKT_encoded_data, 38); } // get card number (c) bit_lib_copy_bits(protocol->data, 16, 1, protocol->RKKT_encoded_data, 45); // same skips here bit_lib_copy_bits(protocol->data, 17, 8, protocol->RKKT_encoded_data, 47); bit_lib_copy_bits(protocol->data, 25, 7, protocol->RKKT_encoded_data, 56); // unsure about CS yet, might as well just save it // CS1 bit_lib_copy_bits(protocol->data, 32, 8, protocol->RKKT_encoded_data, 65); // CS2 bit_lib_copy_bits(protocol->data, 40, 8, protocol->RKKT_encoded_data, 74); } // (decoded) data looks like this (pp are zero paddings): // 26-bit format (1-bit EP, 8-bit facility number, 16-bit card number, 1-bit OP) // pppppppp ffffffff cccccccc cccccccc CS1 CS2 // 00000000 00011011 00011111 00110001 00001111 01100000 // 32-bit format (1-bit EP, 14-bit facility number, 16-bit card number, 1-bit OP) // ppffffff ffffffff cccccccc cccccccc CS1 CS2 // 00000010 01100101 00101101 10101011 00010110 11100000 // plaintext format (preamble and 32-bit? card number) // pppppppp pppppppp cccccccc cccccccc cccccccc cccccccc // 00000000 00000000 00101011 00011101 00000100 01001010 } void protocol_securakey_decoder_start(ProtocolSecurakey* protocol) { // always takes in encoded data as RKKT for simplicity // this part is feeding decoder which will delineate the format anyway memset(protocol->RKKT_encoded_data, 0, SECURAKEY_RKKT_ENCODED_FULL_SIZE_BYTE); manchester_advance( protocol->decoder_manchester_state, ManchesterEventReset, &protocol->decoder_manchester_state, NULL); } bool protocol_securakey_decoder_feed(ProtocolSecurakey* protocol, bool level, uint32_t duration) { bool result = false; // this is where we do manchester demodulation on already ASK-demoded data ManchesterEvent event = ManchesterEventReset; if(duration > SECURAKEY_READ_SHORT_TIME_LOW && duration < SECURAKEY_READ_SHORT_TIME_HIGH) { if(!level) { event = ManchesterEventShortHigh; } else { event = ManchesterEventShortLow; } } else if(duration > SECURAKEY_READ_LONG_TIME_LOW && duration < SECURAKEY_READ_LONG_TIME_HIGH) { if(!level) { event = ManchesterEventLongHigh; } else { event = ManchesterEventLongLow; } } // append a new bit to the encoded bit stream if(event != ManchesterEventReset) { bool data; bool data_ok = manchester_advance( protocol->decoder_manchester_state, event, &protocol->decoder_manchester_state, &data); if(data_ok) { bit_lib_push_bit( protocol->RKKT_encoded_data, SECURAKEY_RKKT_ENCODED_FULL_SIZE_BYTE, data); if(protocol_securakey_can_be_decoded(protocol)) { protocol_securakey_decode(protocol); result = true; } } } return result; } void protocol_securakey_render_data(ProtocolSecurakey* protocol, FuriString* result) { if(bit_lib_get_bits_16(protocol->data, 0, 16) == 0) { protocol->bit_format = 0; furi_string_printf( result, "RKKTH Plaintext format\nCard number: %llu", bit_lib_get_bits_64(protocol->data, 0, 48)); } else { if(bit_lib_get_bits(protocol->data, 0, 8) == 0) { protocol->bit_format = 26; } else { protocol->bit_format = 32; } furi_string_printf( result, "RKKT %u-bit format\nFacility code: %u\nCard number: %u", protocol->bit_format, bit_lib_get_bits_16(protocol->data, 0, 16), bit_lib_get_bits_16(protocol->data, 16, 16)); } } bool protocol_securakey_encoder_start(ProtocolSecurakey* protocol) { // set all of our encoded_data bits to zeros. memset(protocol->RKKTH_encoded_data, 0, SECURAKEY_RKKTH_ENCODED_FULL_SIZE_BYTE); memset(protocol->RKKT_encoded_data, 0, SECURAKEY_RKKT_ENCODED_FULL_SIZE_BYTE); if(bit_lib_get_bits_16(protocol->data, 0, 16) == 0) { // write the preamble to the beginning of the RKKT_encoded_data bit_lib_set_bits(protocol->RKKTH_encoded_data, 0, 0b01111111, 8); bit_lib_set_bits(protocol->RKKTH_encoded_data, 8, 0b110, 3); //preamble cont. // write card number (c) bit_lib_copy_bits(protocol->RKKTH_encoded_data, 29, 8, protocol->data, 16); // skip spacers (they are zero already by memset) bit_lib_copy_bits(protocol->RKKTH_encoded_data, 38, 8, protocol->data, 24); bit_lib_copy_bits(protocol->RKKTH_encoded_data, 47, 8, protocol->data, 32); bit_lib_copy_bits(protocol->RKKTH_encoded_data, 56, 8, protocol->data, 40); } else { // write the preamble to the beginning of the RKKT_encoded_data bit_lib_set_bits(protocol->RKKT_encoded_data, 0, 0b01111111, 8); bit_lib_set_bits(protocol->RKKT_encoded_data, 8, 0b11001, 5); //preamble cont. if(bit_lib_get_bits(protocol->data, 0, 8) == 0) { protocol->bit_format = 26; // set bit length bit_lib_set_bits(protocol->RKKT_encoded_data, 13, protocol->bit_format, 6); // set even parity & odd parity if(!bit_lib_test_parity(protocol->data, 8, 12, BitLibParityOdd, 12)) { bit_lib_set_bit(protocol->RKKT_encoded_data, 35, 1); } if(bit_lib_test_parity(protocol->data, 20, 12, BitLibParityOdd, 12)) { bit_lib_set_bit(protocol->RKKT_encoded_data, 63, 1); } // write facility number (f) bit_lib_copy_bits(protocol->RKKT_encoded_data, 36, 1, protocol->data, 8); // have to skip one spacer bit_lib_copy_bits(protocol->RKKT_encoded_data, 38, 7, protocol->data, 9); } else { protocol->bit_format = 32; // set bit length bit_lib_set_bits(protocol->RKKT_encoded_data, 13, protocol->bit_format, 6); // set EP & OP if(!bit_lib_test_parity(protocol->data, 2, 15, BitLibParityOdd, 15)) { bit_lib_set_bit(protocol->RKKT_encoded_data, 29, 1); } if(bit_lib_test_parity(protocol->data, 17, 15, BitLibParityOdd, 15)) { bit_lib_set_bit(protocol->RKKT_encoded_data, 63, 1); } // write facility number (f) bit_lib_copy_bits(protocol->RKKT_encoded_data, 30, 7, protocol->data, 2); // have to skip one spacer bit_lib_copy_bits(protocol->RKKT_encoded_data, 38, 7, protocol->data, 3); } // write card number (c) bit_lib_copy_bits(protocol->RKKT_encoded_data, 45, 1, protocol->data, 16); // same skips here bit_lib_copy_bits(protocol->RKKT_encoded_data, 47, 8, protocol->data, 17); bit_lib_copy_bits(protocol->RKKT_encoded_data, 56, 7, protocol->data, 25); // unsure about CS yet might as well just copy it from saved // CS1 bit_lib_copy_bits(protocol->RKKT_encoded_data, 65, 8, protocol->data, 32); // CS2 bit_lib_copy_bits(protocol->RKKT_encoded_data, 74, 8, protocol->data, 40); } // for sending we start at bit 0. protocol->encoded_data_index = 0; protocol->encoded_polarity = true; return true; } LevelDuration protocol_securakey_encoder_yield(ProtocolSecurakey* protocol) { if(bit_lib_get_bits_16(protocol->data, 0, 16) == 0) { bool level = bit_lib_get_bit(protocol->RKKTH_encoded_data, protocol->encoded_data_index); uint32_t duration = SECURAKEY_CLOCK_PER_BIT / 2; if(protocol->encoded_polarity) { protocol->encoded_polarity = false; } else { level = !level; protocol->encoded_polarity = true; bit_lib_increment_index( protocol->encoded_data_index, SECURAKEY_RKKTH_ENCODED_FULL_SIZE_BITS); } return level_duration_make(level, duration); } else { bool level = bit_lib_get_bit(protocol->RKKT_encoded_data, protocol->encoded_data_index); uint32_t duration = SECURAKEY_CLOCK_PER_BIT / 2; if(protocol->encoded_polarity) { protocol->encoded_polarity = false; } else { level = !level; protocol->encoded_polarity = true; bit_lib_increment_index( protocol->encoded_data_index, SECURAKEY_RKKT_ENCODED_FULL_SIZE_BITS); } return level_duration_make(level, duration); } } bool protocol_securakey_write_data(ProtocolSecurakey* protocol, void* data) { protocol_securakey_encoder_start(protocol); LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; // Write T5577 if(bit_lib_get_bits_16(protocol->data, 0, 16) == 0) { if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = (LFRFID_T5577_MODULATION_MANCHESTER | LFRFID_T5577_BITRATE_RF_40 | (2 << LFRFID_T5577_MAXBLOCK_SHIFT)); // we only need 2 32-bit blocks for our 64-bit encoded data request->t5577.block[1] = bit_lib_get_bits_32(protocol->RKKTH_encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->RKKTH_encoded_data, 32, 32); request->t5577.blocks_to_write = 3; result = true; } } else { if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = (LFRFID_T5577_MODULATION_MANCHESTER | LFRFID_T5577_BITRATE_RF_40 | (3 << LFRFID_T5577_MAXBLOCK_SHIFT)); // we only need 3 32-bit blocks for our 96-bit encoded data request->t5577.block[1] = bit_lib_get_bits_32(protocol->RKKT_encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->RKKT_encoded_data, 32, 32); request->t5577.block[3] = bit_lib_get_bits_32(protocol->RKKT_encoded_data, 64, 32); request->t5577.blocks_to_write = 4; result = true; } } return result; } const ProtocolBase protocol_securakey = { .name = "Radio Key", .manufacturer = "Securakey", .data_size = SECURAKEY_DECODED_DATA_SIZE_BYTES, .features = LFRFIDFeatureASK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_securakey_alloc, .free = (ProtocolFree)protocol_securakey_free, .get_data = (ProtocolGetData)protocol_securakey_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_securakey_decoder_start, .feed = (ProtocolDecoderFeed)protocol_securakey_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_securakey_encoder_start, .yield = (ProtocolEncoderYield)protocol_securakey_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_securakey_render_data, .render_brief_data = (ProtocolRenderData)protocol_securakey_render_data, .write_data = (ProtocolWriteData)protocol_securakey_write_data, };
17,301
C
.c
339
43.117994
134
0.650213
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,366
protocol_io_prox_xsf.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_io_prox_xsf.c
#include <furi.h> #include <toolbox/protocols/protocol.h> #include <lfrfid/tools/fsk_demod.h> #include <lfrfid/tools/fsk_osc.h> #include <bit_lib/bit_lib.h> #include "lfrfid_protocols.h" #define JITTER_TIME (20) #define MIN_TIME (64 - JITTER_TIME) #define MAX_TIME (80 + JITTER_TIME) #define IOPROXXSF_DECODED_DATA_SIZE (4) #define IOPROXXSF_ENCODED_DATA_SIZE (8) #define IOPROXXSF_BIT_SIZE (8) #define IOPROXXSF_BIT_MAX_SIZE (IOPROXXSF_BIT_SIZE * IOPROXXSF_ENCODED_DATA_SIZE) typedef struct { FSKDemod* fsk_demod; } ProtocolIOProxXSFDecoder; typedef struct { FSKOsc* fsk_osc; uint8_t encoded_index; } ProtocolIOProxXSFEncoder; typedef struct { ProtocolIOProxXSFEncoder encoder; ProtocolIOProxXSFDecoder decoder; uint8_t encoded_data[IOPROXXSF_ENCODED_DATA_SIZE]; uint8_t data[IOPROXXSF_DECODED_DATA_SIZE]; } ProtocolIOProxXSF; ProtocolIOProxXSF* protocol_io_prox_xsf_alloc(void) { ProtocolIOProxXSF* protocol = malloc(sizeof(ProtocolIOProxXSF)); protocol->decoder.fsk_demod = fsk_demod_alloc(MIN_TIME, 8, MAX_TIME, 6); protocol->encoder.fsk_osc = fsk_osc_alloc(8, 10, 64); return protocol; } void protocol_io_prox_xsf_free(ProtocolIOProxXSF* protocol) { fsk_demod_free(protocol->decoder.fsk_demod); fsk_osc_free(protocol->encoder.fsk_osc); free(protocol); } uint8_t* protocol_io_prox_xsf_get_data(ProtocolIOProxXSF* protocol) { return protocol->data; } void protocol_io_prox_xsf_decoder_start(ProtocolIOProxXSF* protocol) { memset(protocol->encoded_data, 0, IOPROXXSF_ENCODED_DATA_SIZE); } static uint8_t protocol_io_prox_xsf_compute_checksum(const uint8_t* data) { // Packet structure: // //0 1 2 3 4 5 6 7 //v v v v v v v v //01234567 8 9ABCDEF0 1 23456789 A BCDEF012 3 456789AB C DEF01234 5 6789ABCD EF //00000000 0 VVVVVVVV 1 WWWWWWWW 1 XXXXXXXX 1 YYYYYYYY 1 ZZZZZZZZ 1 CHECKSUM 11 // // algorithm as observed by the proxmark3 folks // CHECKSUM == 0xFF - (V + W + X + Y + Z) uint8_t checksum = 0; for(size_t i = 1; i <= 5; i++) { checksum += bit_lib_get_bits(data, 9 * i, 8); } return 0xFF - checksum; } static bool protocol_io_prox_xsf_can_be_decoded(const uint8_t* encoded_data) { // Packet framing // //0 1 2 3 4 5 6 7 //v v v v v v v v //01234567 89ABCDEF 01234567 89ABCDEF 01234567 89ABCDEF 01234567 89ABCDEF //----------------------------------------------------------------------- //00000000 01______ _1______ __1_____ ___1____ ____1___ _____1XX XXXXXX11 // // _ = variable data // 0 = preamble 0 // 1 = framing 1 // X = checksum // Validate the packet preamble is there... if(encoded_data[0] != 0b00000000) { return false; } if((encoded_data[1] >> 6) != 0b01) { return false; } // ... check for known ones... if(bit_lib_bit_is_not_set(encoded_data[2], 6)) { return false; } if(bit_lib_bit_is_not_set(encoded_data[3], 5)) { return false; } if(bit_lib_bit_is_not_set(encoded_data[4], 4)) { return false; } if(bit_lib_bit_is_not_set(encoded_data[5], 3)) { return false; } if(bit_lib_bit_is_not_set(encoded_data[6], 2)) { return false; } if(bit_lib_bit_is_not_set(encoded_data[7], 1)) { return false; } if(bit_lib_bit_is_not_set(encoded_data[7], 0)) { return false; } // ... and validate our checksums. uint8_t checksum = protocol_io_prox_xsf_compute_checksum(encoded_data); uint8_t checkval = bit_lib_get_bits(encoded_data, 54, 8); if(checksum != checkval) { return false; } return true; } void protocol_io_prox_xsf_decode(const uint8_t* encoded_data, uint8_t* decoded_data) { // Packet structure: // (Note: the second word seems fixed; but this may not be a guarantee; // it currently has no meaning.) // //0 1 2 3 4 5 6 7 //v v v v v v v v //01234567 89ABCDEF 01234567 89ABCDEF 01234567 89ABCDEF 01234567 89ABCDEF //----------------------------------------------------------------------- //00000000 01111000 01FFFFFF FF1VVVVV VVV1CCCC CCCC1CCC CCCCC1XX XXXXXX11 // // F = facility code // V = version // C = code // X = checksum // Facility code decoded_data[0] = bit_lib_get_bits(encoded_data, 18, 8); // Version code. decoded_data[1] = bit_lib_get_bits(encoded_data, 27, 8); // Code bytes. decoded_data[2] = bit_lib_get_bits(encoded_data, 36, 8); decoded_data[3] = bit_lib_get_bits(encoded_data, 45, 8); } bool protocol_io_prox_xsf_decoder_feed(ProtocolIOProxXSF* protocol, bool level, uint32_t duration) { bool result = false; uint32_t count; bool value; fsk_demod_feed(protocol->decoder.fsk_demod, level, duration, &value, &count); for(size_t i = 0; i < count; i++) { bit_lib_push_bit(protocol->encoded_data, IOPROXXSF_ENCODED_DATA_SIZE, value); if(protocol_io_prox_xsf_can_be_decoded(protocol->encoded_data)) { protocol_io_prox_xsf_decode(protocol->encoded_data, protocol->data); result = true; break; } } return result; } static void protocol_io_prox_xsf_encode(const uint8_t* decoded_data, uint8_t* encoded_data) { // Packet to transmit: // // 0 10 20 30 40 50 60 // v v v v v v v // 01234567 8 90123456 7 89012345 6 78901234 5 67890123 4 56789012 3 45678901 23 // ----------------------------------------------------------------------------- // 00000000 0 11110000 1 facility 1 version_ 1 code-one 1 code-two 1 checksum 11 // Preamble. bit_lib_set_bits(encoded_data, 0, 0b00000000, 8); bit_lib_set_bit(encoded_data, 8, 0); bit_lib_set_bits(encoded_data, 9, 0b11110000, 8); bit_lib_set_bit(encoded_data, 17, 1); // Facility code. bit_lib_set_bits(encoded_data, 18, decoded_data[0], 8); bit_lib_set_bit(encoded_data, 26, 1); // Version bit_lib_set_bits(encoded_data, 27, decoded_data[1], 8); bit_lib_set_bit(encoded_data, 35, 1); // Code one bit_lib_set_bits(encoded_data, 36, decoded_data[2], 8); bit_lib_set_bit(encoded_data, 44, 1); // Code two bit_lib_set_bits(encoded_data, 45, decoded_data[3], 8); bit_lib_set_bit(encoded_data, 53, 1); // Checksum bit_lib_set_bits(encoded_data, 54, protocol_io_prox_xsf_compute_checksum(encoded_data), 8); bit_lib_set_bit(encoded_data, 62, 1); bit_lib_set_bit(encoded_data, 63, 1); } bool protocol_io_prox_xsf_encoder_start(ProtocolIOProxXSF* protocol) { protocol_io_prox_xsf_encode(protocol->data, protocol->encoded_data); protocol->encoder.encoded_index = 0; fsk_osc_reset(protocol->encoder.fsk_osc); return true; } LevelDuration protocol_io_prox_xsf_encoder_yield(ProtocolIOProxXSF* protocol) { bool level; uint32_t duration; bool bit = bit_lib_get_bit(protocol->encoded_data, protocol->encoder.encoded_index); bool advance = fsk_osc_next_half(protocol->encoder.fsk_osc, bit, &level, &duration); if(advance) { bit_lib_increment_index(protocol->encoder.encoded_index, IOPROXXSF_BIT_MAX_SIZE); } return level_duration_make(level, duration); } void protocol_io_prox_xsf_render_data(ProtocolIOProxXSF* protocol, FuriString* result) { uint8_t* data = protocol->data; furi_string_printf( result, "FC: %hhu\n" "V: %hhu\n" "Card: %hu", data[0], data[1], (uint16_t)((data[2] << 8) | (data[3]))); } void protocol_io_prox_xsf_render_brief_data(ProtocolIOProxXSF* protocol, FuriString* result) { uint8_t* data = protocol->data; furi_string_printf( result, "FC: %hhu, V: %hhu\n" "Card: %hu", data[0], data[1], (uint16_t)((data[2] << 8) | (data[3]))); } bool protocol_io_prox_xsf_write_data(ProtocolIOProxXSF* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; // Correct protocol data by redecoding protocol_io_prox_xsf_encode(protocol->data, protocol->encoded_data); protocol_io_prox_xsf_decode(protocol->encoded_data, protocol->data); protocol_io_prox_xsf_encode(protocol->data, protocol->encoded_data); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = LFRFID_T5577_MODULATION_FSK2a | LFRFID_T5577_BITRATE_RF_64 | (2 << LFRFID_T5577_MAXBLOCK_SHIFT); request->t5577.block[1] = bit_lib_get_bits_32(protocol->encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->encoded_data, 32, 32); request->t5577.blocks_to_write = 3; result = true; } return result; } const ProtocolBase protocol_io_prox_xsf = { .name = "IoProxXSF", .manufacturer = "Kantech", .data_size = IOPROXXSF_DECODED_DATA_SIZE, .features = LFRFIDFeatureASK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_io_prox_xsf_alloc, .free = (ProtocolFree)protocol_io_prox_xsf_free, .get_data = (ProtocolGetData)protocol_io_prox_xsf_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_io_prox_xsf_decoder_start, .feed = (ProtocolDecoderFeed)protocol_io_prox_xsf_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_io_prox_xsf_encoder_start, .yield = (ProtocolEncoderYield)protocol_io_prox_xsf_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_io_prox_xsf_render_data, .render_brief_data = (ProtocolRenderData)protocol_io_prox_xsf_render_brief_data, .write_data = (ProtocolWriteData)protocol_io_prox_xsf_write_data, };
10,198
C
.c
254
34.814961
100
0.615237
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,367
protocol_pyramid.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_pyramid.c
#include <furi.h> #include <toolbox/protocols/protocol.h> #include <lfrfid/tools/fsk_demod.h> #include <lfrfid/tools/fsk_osc.h> #include "lfrfid_protocols.h" #include <bit_lib/bit_lib.h> #define JITTER_TIME (20) #define MIN_TIME (64 - JITTER_TIME) #define MAX_TIME (80 + JITTER_TIME) #define PYRAMID_DATA_SIZE 13 #define PYRAMID_PREAMBLE_SIZE 3 #define PYRAMID_ENCODED_DATA_SIZE \ (PYRAMID_PREAMBLE_SIZE + PYRAMID_DATA_SIZE + PYRAMID_PREAMBLE_SIZE) #define PYRAMID_ENCODED_BIT_SIZE ((PYRAMID_PREAMBLE_SIZE + PYRAMID_DATA_SIZE) * 8) #define PYRAMID_DECODED_DATA_SIZE (4) #define PYRAMID_DECODED_BIT_SIZE ((PYRAMID_ENCODED_BIT_SIZE - PYRAMID_PREAMBLE_SIZE * 8) / 2) typedef struct { FSKDemod* fsk_demod; } ProtocolPyramidDecoder; typedef struct { FSKOsc* fsk_osc; uint8_t encoded_index; uint32_t pulse; } ProtocolPyramidEncoder; typedef struct { ProtocolPyramidDecoder decoder; ProtocolPyramidEncoder encoder; uint8_t encoded_data[PYRAMID_ENCODED_DATA_SIZE]; uint8_t data[PYRAMID_DECODED_DATA_SIZE]; } ProtocolPyramid; ProtocolPyramid* protocol_pyramid_alloc(void) { ProtocolPyramid* protocol = malloc(sizeof(ProtocolPyramid)); protocol->decoder.fsk_demod = fsk_demod_alloc(MIN_TIME, 6, MAX_TIME, 5); protocol->encoder.fsk_osc = fsk_osc_alloc(8, 10, 50); return protocol; } void protocol_pyramid_free(ProtocolPyramid* protocol) { fsk_demod_free(protocol->decoder.fsk_demod); fsk_osc_free(protocol->encoder.fsk_osc); free(protocol); } uint8_t* protocol_pyramid_get_data(ProtocolPyramid* protocol) { return protocol->data; } void protocol_pyramid_decoder_start(ProtocolPyramid* protocol) { memset(protocol->encoded_data, 0, PYRAMID_ENCODED_DATA_SIZE); } static bool protocol_pyramid_can_be_decoded(uint8_t* data) { // check preamble if(bit_lib_get_bits_16(data, 0, 16) != 0b0000000000000001 || bit_lib_get_bits(data, 16, 8) != 0b00000001) { return false; } if(bit_lib_get_bits_16(data, 128, 16) != 0b0000000000000001 || bit_lib_get_bits(data, 136, 8) != 0b00000001) { return false; } uint8_t checksum = bit_lib_get_bits(data, 120, 8); uint8_t checksum_data[13] = {0x00}; for(uint8_t i = 0; i < 13; i++) { checksum_data[i] = bit_lib_get_bits(data, 16 + (i * 8), 8); } uint8_t calc_checksum = bit_lib_crc8(checksum_data, 13, 0x31, 0x00, true, true, 0x00); if(checksum != calc_checksum) return false; // Remove parity bit_lib_remove_bit_every_nth(data, 8, 15 * 8, 8); // Determine Startbit and format int j; for(j = 0; j < 105; ++j) { if(bit_lib_get_bit(data, j)) break; } uint8_t fmt_len = 105 - j; // Only support 26bit format for now if(fmt_len != 26) return false; return true; } static void protocol_pyramid_decode(ProtocolPyramid* protocol) { // Format bit_lib_set_bits(protocol->data, 0, 26, 8); // Facility Code bit_lib_copy_bits(protocol->data, 8, 8, protocol->encoded_data, 73 + 8); // Card Number bit_lib_copy_bits(protocol->data, 16, 16, protocol->encoded_data, 81 + 8); } bool protocol_pyramid_decoder_feed(ProtocolPyramid* protocol, bool level, uint32_t duration) { bool value; uint32_t count; bool result = false; fsk_demod_feed(protocol->decoder.fsk_demod, level, duration, &value, &count); if(count > 0) { for(size_t i = 0; i < count; i++) { bit_lib_push_bit(protocol->encoded_data, PYRAMID_ENCODED_DATA_SIZE, value); if(protocol_pyramid_can_be_decoded(protocol->encoded_data)) { protocol_pyramid_decode(protocol); result = true; } } } return result; } bool protocol_pyramid_get_parity(const uint8_t* bits, uint8_t type, int length) { int x; for(x = 0; length > 0; --length) x += bit_lib_get_bit(bits, length - 1); x %= 2; return x ^ type; } void protocol_pyramid_add_wiegand_parity( uint8_t* target, uint8_t target_position, uint8_t* source, uint8_t length) { bit_lib_set_bit( target, target_position, protocol_pyramid_get_parity(source, 0 /* even */, length / 2)); bit_lib_copy_bits(target, target_position + 1, length, source, 0); bit_lib_set_bit( target, target_position + length + 1, protocol_pyramid_get_parity(source + length / 2, 1 /* odd */, length / 2)); } static void protocol_pyramid_encode(ProtocolPyramid* protocol) { memset(protocol->encoded_data, 0, sizeof(protocol->encoded_data)); uint8_t pre[16]; memset(pre, 0, sizeof(pre)); // Format start bit bit_lib_set_bit(pre, 79, 1); uint8_t wiegand[3]; memset(wiegand, 0, sizeof(wiegand)); // FC bit_lib_copy_bits(wiegand, 0, 8, protocol->data, 8); // CardNum bit_lib_copy_bits(wiegand, 8, 16, protocol->data, 16); // Wiegand parity protocol_pyramid_add_wiegand_parity(pre, 80, wiegand, 24); bit_lib_add_parity(pre, 8, protocol->encoded_data, 8, 102, 8, 1); // Add checksum uint8_t checksum_buffer[13]; for(uint8_t i = 0; i < 13; i++) checksum_buffer[i] = bit_lib_get_bits(protocol->encoded_data, 16 + (i * 8), 8); uint8_t crc = bit_lib_crc8(checksum_buffer, 13, 0x31, 0x00, true, true, 0x00); bit_lib_set_bits(protocol->encoded_data, 120, crc, 8); } bool protocol_pyramid_encoder_start(ProtocolPyramid* protocol) { protocol->encoder.encoded_index = 0; protocol->encoder.pulse = 0; protocol_pyramid_encode(protocol); return true; } LevelDuration protocol_pyramid_encoder_yield(ProtocolPyramid* protocol) { bool level = 0; uint32_t duration = 0; // if pulse is zero, we need to output high, otherwise we need to output low if(protocol->encoder.pulse == 0) { // get bit uint8_t bit = bit_lib_get_bit(protocol->encoded_data, protocol->encoder.encoded_index); // get pulse from oscillator bool advance = fsk_osc_next(protocol->encoder.fsk_osc, bit, &duration); if(advance) { bit_lib_increment_index(protocol->encoder.encoded_index, PYRAMID_ENCODED_BIT_SIZE); } // duration diveded by 2 because we need to output high and low duration = duration / 2; protocol->encoder.pulse = duration; level = true; } else { // output low half and reset pulse duration = protocol->encoder.pulse; protocol->encoder.pulse = 0; level = false; } return level_duration_make(level, duration); } bool protocol_pyramid_write_data(ProtocolPyramid* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; // Correct protocol data by redecoding protocol_pyramid_encode(protocol); bit_lib_remove_bit_every_nth(protocol->encoded_data, 8, 15 * 8, 8); protocol_pyramid_decode(protocol); protocol_pyramid_encoder_start(protocol); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = LFRFID_T5577_MODULATION_FSK2a | LFRFID_T5577_BITRATE_RF_50 | (4 << LFRFID_T5577_MAXBLOCK_SHIFT); request->t5577.block[1] = bit_lib_get_bits_32(protocol->encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->encoded_data, 32, 32); request->t5577.block[3] = bit_lib_get_bits_32(protocol->encoded_data, 64, 32); request->t5577.block[4] = bit_lib_get_bits_32(protocol->encoded_data, 96, 32); request->t5577.blocks_to_write = 5; result = true; } return result; } void protocol_pyramid_render_data(ProtocolPyramid* protocol, FuriString* result) { uint8_t* decoded_data = protocol->data; uint8_t format_length = decoded_data[0]; furi_string_printf(result, "Format: %hhu\n", format_length); if(format_length == 26) { uint8_t facility; bit_lib_copy_bits(&facility, 0, 8, decoded_data, 8); uint16_t card_id; bit_lib_copy_bits((uint8_t*)&card_id, 8, 8, decoded_data, 16); bit_lib_copy_bits((uint8_t*)&card_id, 0, 8, decoded_data, 24); furi_string_cat_printf(result, "FC: %03hhu; Card: %05hu", facility, card_id); } else { furi_string_cat_printf(result, "Data: Unknown"); } } const ProtocolBase protocol_pyramid = { .name = "Pyramid", .manufacturer = "Farpointe", .data_size = PYRAMID_DECODED_DATA_SIZE, .features = LFRFIDFeatureASK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_pyramid_alloc, .free = (ProtocolFree)protocol_pyramid_free, .get_data = (ProtocolGetData)protocol_pyramid_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_pyramid_decoder_start, .feed = (ProtocolDecoderFeed)protocol_pyramid_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_pyramid_encoder_start, .yield = (ProtocolEncoderYield)protocol_pyramid_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_pyramid_render_data, .render_brief_data = (ProtocolRenderData)protocol_pyramid_render_data, .write_data = (ProtocolWriteData)protocol_pyramid_write_data, };
9,266
C
.c
230
34.63913
96
0.6647
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,368
protocol_pac_stanley.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_pac_stanley.c
#include <furi.h> #include <math.h> #include <toolbox/protocols/protocol.h> #include <toolbox/hex.h> #include <bit_lib/bit_lib.h> #include "lfrfid_protocols.h" #define PAC_STANLEY_ENCODED_BIT_SIZE (128) #define PAC_STANLEY_ENCODED_BYTE_SIZE (((PAC_STANLEY_ENCODED_BIT_SIZE) / 8)) #define PAC_STANLEY_PREAMBLE_BIT_SIZE (8) #define PAC_STANLEY_PREAMBLE_BYTE_SIZE (1) #define PAC_STANLEY_ENCODED_BYTE_FULL_SIZE \ (PAC_STANLEY_ENCODED_BYTE_SIZE + PAC_STANLEY_PREAMBLE_BYTE_SIZE) #define PAC_STANLEY_BYTE_LENGTH (10) // start bit, 7 data bits, parity bit, stop bit #define PAC_STANLEY_DATA_START_INDEX (8 + (3 * PAC_STANLEY_BYTE_LENGTH) + 1) #define PAC_STANLEY_DECODED_DATA_SIZE (4) #define PAC_STANLEY_ENCODED_DATA_SIZE (sizeof(ProtocolPACStanley)) #define PAC_STANLEY_CLOCKS_IN_US (32) #define PAC_STANLEY_CYCLE_LENGTH (256) #define PAC_STANLEY_MIN_TIME (60) #define PAC_STANLEY_MAX_TIME (4000) typedef struct { bool inverted; bool got_preamble; size_t encoded_index; uint8_t encoded_data[PAC_STANLEY_ENCODED_BYTE_FULL_SIZE]; uint8_t data[PAC_STANLEY_DECODED_DATA_SIZE]; } ProtocolPACStanley; ProtocolPACStanley* protocol_pac_stanley_alloc(void) { ProtocolPACStanley* protocol = malloc(sizeof(ProtocolPACStanley)); return (void*)protocol; } void protocol_pac_stanley_free(ProtocolPACStanley* protocol) { free(protocol); } uint8_t* protocol_pac_stanley_get_data(ProtocolPACStanley* protocol) { return protocol->data; } static void protocol_pac_stanley_decode(ProtocolPACStanley* protocol) { uint8_t asciiCardId[8]; for(size_t idx = 0; idx < 8; idx++) { uint8_t byte = bit_lib_reverse_8_fast(bit_lib_get_bits( protocol->encoded_data, PAC_STANLEY_DATA_START_INDEX + (PAC_STANLEY_BYTE_LENGTH * idx), 8)); asciiCardId[idx] = byte & 0x7F; // discard the parity bit } hex_chars_to_uint8((char*)asciiCardId, protocol->data); } static bool protocol_pac_stanley_can_be_decoded(ProtocolPACStanley* protocol) { // Check preamble if(bit_lib_get_bits(protocol->encoded_data, 0, 8) != 0b11111111) return false; if(bit_lib_get_bit(protocol->encoded_data, 8) != 0) return false; if(bit_lib_get_bit(protocol->encoded_data, 9) != 0) return false; if(bit_lib_get_bit(protocol->encoded_data, 10) != 1) return false; if(bit_lib_get_bits(protocol->encoded_data, 11, 8) != 0b00000010) return false; // Check next preamble if(bit_lib_get_bits(protocol->encoded_data, 128, 8) != 0b11111111) return false; // Checksum uint8_t checksum = 0; uint8_t stripped_byte; for(size_t idx = 0; idx < 9; idx++) { uint8_t byte = bit_lib_reverse_8_fast(bit_lib_get_bits( protocol->encoded_data, PAC_STANLEY_DATA_START_INDEX + (PAC_STANLEY_BYTE_LENGTH * idx), 8)); stripped_byte = byte & 0x7F; // discard the parity bit if(bit_lib_test_parity_32(stripped_byte, BitLibParityOdd) != (byte & 0x80) >> 7) { return false; } if(idx < 8) checksum ^= stripped_byte; } if(stripped_byte != checksum) return false; return true; } void protocol_pac_stanley_decoder_start(ProtocolPACStanley* protocol) { memset(protocol->data, 0, PAC_STANLEY_DECODED_DATA_SIZE); protocol->inverted = false; protocol->got_preamble = false; } bool protocol_pac_stanley_decoder_feed(ProtocolPACStanley* protocol, bool level, uint32_t duration) { bool pushed = false; if(duration > PAC_STANLEY_MAX_TIME) return false; uint8_t pulses = (uint8_t)roundf((float)duration / PAC_STANLEY_CYCLE_LENGTH); // Handle last stopbit & preamble (1 sb, 8 bit preamble) if(pulses >= 9 && !protocol->got_preamble) { pulses = 8; protocol->got_preamble = true; protocol->inverted = !level; } else if(pulses >= 9 && protocol->got_preamble) { protocol->got_preamble = false; } else if(pulses == 0 && duration > PAC_STANLEY_MIN_TIME) { pulses = 1; } if(pulses) { for(uint8_t i = 0; i < pulses; i++) { bit_lib_push_bit( protocol->encoded_data, PAC_STANLEY_ENCODED_BYTE_FULL_SIZE, level ^ protocol->inverted); } pushed = true; } if(pushed && protocol_pac_stanley_can_be_decoded(protocol)) { protocol_pac_stanley_decode(protocol); return true; } return false; } bool protocol_pac_stanley_encoder_start(ProtocolPACStanley* protocol) { memset(protocol->encoded_data, 0, sizeof(protocol->encoded_data)); uint8_t idbytes[10]; idbytes[0] = '2'; idbytes[1] = '0'; uint8_to_hex_chars(protocol->data, &idbytes[2], 8); // insert start and stop bits for(size_t i = 0; i < 16; i++) protocol->encoded_data[i] = 0x40 >> ((i + 3) % 5 * 2); protocol->encoded_data[0] = 0xFF; // mark + stop protocol->encoded_data[1] = 0x20; // start + reflect8(STX) uint8_t checksum = 0; for(size_t i = 2; i < 13; i++) { uint8_t shift = 7 - (i + 3) % 4 * 2; uint8_t index = i + (i - 1) / 4; uint16_t pattern; if(i < 12) { pattern = bit_lib_reverse_8_fast(idbytes[i - 2]); pattern |= bit_lib_test_parity_32(pattern, BitLibParityOdd); if(i > 3) checksum ^= idbytes[i - 2]; } else { pattern = (bit_lib_reverse_8_fast(checksum) & 0xFE) | (bit_lib_test_parity_32(checksum, BitLibParityOdd)); } pattern <<= shift; protocol->encoded_data[index] |= pattern >> 8 & 0xFF; protocol->encoded_data[index + 1] |= pattern & 0xFF; } protocol->encoded_index = 0; return true; } LevelDuration protocol_pac_stanley_encoder_yield(ProtocolPACStanley* protocol) { uint16_t length = PAC_STANLEY_CLOCKS_IN_US; bool bit = bit_lib_get_bit(protocol->encoded_data, protocol->encoded_index); bit_lib_increment_index(protocol->encoded_index, PAC_STANLEY_ENCODED_BIT_SIZE); while(bit_lib_get_bit(protocol->encoded_data, protocol->encoded_index) == bit) { length += PAC_STANLEY_CLOCKS_IN_US; bit_lib_increment_index(protocol->encoded_index, PAC_STANLEY_ENCODED_BIT_SIZE); } return level_duration_make(bit, length); } bool protocol_pac_stanley_write_data(ProtocolPACStanley* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; // Correct protocol data by redecoding protocol_pac_stanley_encoder_start(protocol); protocol_pac_stanley_decode(protocol); protocol_pac_stanley_encoder_start(protocol); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = LFRFID_T5577_MODULATION_DIRECT | LFRFID_T5577_BITRATE_RF_32 | (4 << LFRFID_T5577_MAXBLOCK_SHIFT); request->t5577.block[1] = bit_lib_get_bits_32(protocol->encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->encoded_data, 32, 32); request->t5577.block[3] = bit_lib_get_bits_32(protocol->encoded_data, 64, 32); request->t5577.block[4] = bit_lib_get_bits_32(protocol->encoded_data, 96, 32); request->t5577.blocks_to_write = 5; result = true; } return result; } void protocol_pac_stanley_render_data(ProtocolPACStanley* protocol, FuriString* result) { furi_string_printf(result, "CIN: %08lX", bit_lib_get_bits_32(protocol->data, 0, 32)); } const ProtocolBase protocol_pac_stanley = { .name = "PAC/Stanley", .manufacturer = "N/A", .data_size = PAC_STANLEY_DECODED_DATA_SIZE, .features = LFRFIDFeatureASK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_pac_stanley_alloc, .free = (ProtocolFree)protocol_pac_stanley_free, .get_data = (ProtocolGetData)protocol_pac_stanley_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_pac_stanley_decoder_start, .feed = (ProtocolDecoderFeed)protocol_pac_stanley_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_pac_stanley_encoder_start, .yield = (ProtocolEncoderYield)protocol_pac_stanley_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_pac_stanley_render_data, .render_brief_data = (ProtocolRenderData)protocol_pac_stanley_render_data, .write_data = (ProtocolWriteData)protocol_pac_stanley_write_data, };
8,493
C
.c
194
37.597938
101
0.66122
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,369
protocol_nexwatch.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_nexwatch.c
#include <furi.h> #include <toolbox/protocols/protocol.h> #include <bit_lib/bit_lib.h> #include "lfrfid_protocols.h" #define NEXWATCH_PREAMBLE_BIT_SIZE (8) #define NEXWATCH_PREAMBLE_DATA_SIZE (1) #define NEXWATCH_ENCODED_BIT_SIZE (96) #define NEXWATCH_ENCODED_DATA_SIZE ((NEXWATCH_ENCODED_BIT_SIZE) / 8) #define NEXWATCH_DECODED_BIT_SIZE (NEXWATCH_DECODED_DATA_SIZE * 8) #define NEXWATCH_DECODED_DATA_SIZE (8) #define NEXWATCH_US_PER_BIT (255) #define NEXWATCH_ENCODER_PULSES_PER_BIT (16) typedef struct { uint8_t magic; char desc[13]; uint8_t chk; } ProtocolNexwatchMagic; ProtocolNexwatchMagic magic_items[] = { {0xBE, "Quadrakey", 0}, {0x88, "Nexkey", 0}, {0x86, "Honeywell", 0}}; typedef struct { uint8_t data_index; uint8_t bit_clock_index; bool last_bit; bool current_polarity; bool pulse_phase; } ProtocolNexwatchEncoder; typedef struct { uint8_t encoded_data[NEXWATCH_ENCODED_DATA_SIZE]; uint8_t negative_encoded_data[NEXWATCH_ENCODED_DATA_SIZE]; uint8_t corrupted_encoded_data[NEXWATCH_ENCODED_DATA_SIZE]; uint8_t corrupted_negative_encoded_data[NEXWATCH_ENCODED_DATA_SIZE]; uint8_t data[NEXWATCH_DECODED_DATA_SIZE]; ProtocolNexwatchEncoder encoder; } ProtocolNexwatch; ProtocolNexwatch* protocol_nexwatch_alloc(void) { ProtocolNexwatch* protocol = malloc(sizeof(ProtocolNexwatch)); return protocol; } void protocol_nexwatch_free(ProtocolNexwatch* protocol) { free(protocol); } uint8_t* protocol_nexwatch_get_data(ProtocolNexwatch* protocol) { return protocol->data; } void protocol_nexwatch_decoder_start(ProtocolNexwatch* protocol) { memset(protocol->encoded_data, 0, NEXWATCH_ENCODED_DATA_SIZE); memset(protocol->negative_encoded_data, 0, NEXWATCH_ENCODED_DATA_SIZE); memset(protocol->corrupted_encoded_data, 0, NEXWATCH_ENCODED_DATA_SIZE); memset(protocol->corrupted_negative_encoded_data, 0, NEXWATCH_ENCODED_DATA_SIZE); } static bool protocol_nexwatch_check_preamble(uint8_t* data, size_t bit_index) { // 01010110 if(bit_lib_get_bits(data, bit_index, 8) != 0b01010110) return false; return true; } static uint8_t protocol_nexwatch_parity_swap(uint8_t parity) { uint8_t a = ((parity >> 3) & 1); a |= (((parity >> 1) & 1) << 1); a |= (((parity >> 2) & 1) << 2); a |= ((parity & 1) << 3); return a; } static uint8_t protocol_nexwatch_parity(const uint8_t hexid[5]) { uint8_t p = 0; for(uint8_t i = 0; i < 5; i++) { p ^= ((hexid[i]) & 0xF0) >> 4; p ^= ((hexid[i]) & 0x0F); } return protocol_nexwatch_parity_swap(p); } static uint8_t protocol_nexwatch_checksum(uint8_t magic, uint32_t id, uint8_t parity) { uint8_t a = ((id >> 24) & 0xFF); a -= ((id >> 16) & 0xFF); a -= ((id >> 8) & 0xFF); a -= (id & 0xFF); a -= magic; a -= (bit_lib_reverse_8_fast(parity) >> 4); return bit_lib_reverse_8_fast(a); } static bool protocol_nexwatch_can_be_decoded(uint8_t* data) { if(!protocol_nexwatch_check_preamble(data, 0)) return false; // Check for reserved word (32-bit) if(bit_lib_get_bits_32(data, 8, 32) != 0) { return false; } uint8_t parity = bit_lib_get_bits(data, 76, 4); // parity check // from 32b hex id, 4b mode uint8_t hex[5] = {0}; for(uint8_t i = 0; i < 5; i++) { hex[i] = bit_lib_get_bits(data, 40 + (i * 8), 8); } //mode is only 4 bits. hex[4] &= 0xf0; uint8_t calc_parity = protocol_nexwatch_parity(hex); if(calc_parity != parity) { return false; } return true; } static bool protocol_nexwatch_decoder_feed_internal(bool polarity, uint32_t time, uint8_t* data) { time += (NEXWATCH_US_PER_BIT / 2); size_t bit_count = (time / NEXWATCH_US_PER_BIT); bool result = false; if(bit_count < NEXWATCH_ENCODED_BIT_SIZE) { for(size_t i = 0; i < bit_count; i++) { bit_lib_push_bit(data, NEXWATCH_ENCODED_DATA_SIZE, polarity); if(protocol_nexwatch_can_be_decoded(data)) { result = true; break; } } } return result; } static void protocol_nexwatch_descramble(uint32_t* id, uint32_t* scrambled) { // 255 = Not used/Unknown other values are the bit offset in the ID/FC values const uint8_t hex_2_id[] = {31, 27, 23, 19, 15, 11, 7, 3, 30, 26, 22, 18, 14, 10, 6, 2, 29, 25, 21, 17, 13, 9, 5, 1, 28, 24, 20, 16, 12, 8, 4, 0}; *id = 0; for(uint8_t idx = 0; idx < 32; idx++) { bool bit_state = (*scrambled >> hex_2_id[idx]) & 1; *id |= (bit_state << (31 - idx)); } } static void protocol_nexwatch_decoder_save(uint8_t* data_to, const uint8_t* data_from) { uint32_t id = bit_lib_get_bits_32(data_from, 40, 32); data_to[4] = (uint8_t)id; data_to[3] = (uint8_t)(id >>= 8); data_to[2] = (uint8_t)(id >>= 8); data_to[1] = (uint8_t)(id >>= 8); data_to[0] = (uint8_t)(id >>= 8); uint32_t check = bit_lib_get_bits_32(data_from, 72, 24); data_to[7] = (uint8_t)check; data_to[6] = (uint8_t)(check >>= 8); data_to[5] = (uint8_t)(check >>= 8); } bool protocol_nexwatch_decoder_feed(ProtocolNexwatch* protocol, bool level, uint32_t duration) { bool result = false; if(duration > (NEXWATCH_US_PER_BIT / 2)) { if(protocol_nexwatch_decoder_feed_internal(level, duration, protocol->encoded_data)) { protocol_nexwatch_decoder_save(protocol->data, protocol->encoded_data); result = true; return result; } if(protocol_nexwatch_decoder_feed_internal( !level, duration, protocol->negative_encoded_data)) { protocol_nexwatch_decoder_save(protocol->data, protocol->negative_encoded_data); result = true; return result; } } if(duration > (NEXWATCH_US_PER_BIT / 4)) { // Try to decode wrong phase synced data if(level) { duration += 120; } else { if(duration > 120) { duration -= 120; } } if(protocol_nexwatch_decoder_feed_internal( level, duration, protocol->corrupted_encoded_data)) { protocol_nexwatch_decoder_save(protocol->data, protocol->corrupted_encoded_data); result = true; return result; } if(protocol_nexwatch_decoder_feed_internal( !level, duration, protocol->corrupted_negative_encoded_data)) { protocol_nexwatch_decoder_save( protocol->data, protocol->corrupted_negative_encoded_data); result = true; return result; } } return result; } bool protocol_nexwatch_encoder_start(ProtocolNexwatch* protocol) { memset(protocol->encoded_data, 0, NEXWATCH_ENCODED_DATA_SIZE); *(uint32_t*)&protocol->encoded_data[0] = 0b00000000000000000000000001010110; bit_lib_copy_bits(protocol->encoded_data, 32, 32, protocol->data, 0); bit_lib_copy_bits(protocol->encoded_data, 64, 32, protocol->data, 32); protocol->encoder.last_bit = bit_lib_get_bit(protocol->encoded_data, NEXWATCH_ENCODED_BIT_SIZE - 1); protocol->encoder.data_index = 0; protocol->encoder.current_polarity = true; protocol->encoder.pulse_phase = true; protocol->encoder.bit_clock_index = 0; return true; } LevelDuration protocol_nexwatch_encoder_yield(ProtocolNexwatch* protocol) { LevelDuration level_duration; ProtocolNexwatchEncoder* encoder = &protocol->encoder; if(encoder->pulse_phase) { level_duration = level_duration_make(encoder->current_polarity, 1); encoder->pulse_phase = false; } else { level_duration = level_duration_make(!encoder->current_polarity, 1); encoder->pulse_phase = true; encoder->bit_clock_index++; if(encoder->bit_clock_index >= NEXWATCH_ENCODER_PULSES_PER_BIT) { encoder->bit_clock_index = 0; bool current_bit = bit_lib_get_bit(protocol->encoded_data, encoder->data_index); if(current_bit != encoder->last_bit) { encoder->current_polarity = !encoder->current_polarity; } encoder->last_bit = current_bit; bit_lib_increment_index(encoder->data_index, NEXWATCH_ENCODED_BIT_SIZE); } } return level_duration; } static void protocol_nexwatch_render_data_internal( ProtocolNexwatch* protocol, FuriString* result, bool brief) { uint32_t id = 0; uint32_t scrambled = bit_lib_get_bits_32(protocol->data, 8, 32); protocol_nexwatch_descramble(&id, &scrambled); uint8_t m_idx; uint8_t mode = bit_lib_get_bits(protocol->data, 40, 4); uint8_t parity = bit_lib_get_bits(protocol->data, 44, 4); uint8_t chk = bit_lib_get_bits(protocol->data, 48, 8); for(m_idx = 0; m_idx < COUNT_OF(magic_items); m_idx++) { magic_items[m_idx].chk = protocol_nexwatch_checksum(magic_items[m_idx].magic, id, parity); if(magic_items[m_idx].chk == chk) { break; } } const char* type = m_idx < COUNT_OF(magic_items) ? magic_items[m_idx].desc : "Unknown"; if(brief) { furi_string_printf( result, "ID: %lu\n" "Mode: %hhu; Type: %s", id, mode, type); } else { furi_string_printf( result, "ID: %lu\n" "Mode: %hhu\n" "Type: %s", id, mode, type); } } void protocol_nexwatch_render_data(ProtocolNexwatch* protocol, FuriString* result) { protocol_nexwatch_render_data_internal(protocol, result, false); } void protocol_nexwatch_render_brief_data(ProtocolNexwatch* protocol, FuriString* result) { protocol_nexwatch_render_data_internal(protocol, result, true); } bool protocol_nexwatch_write_data(ProtocolNexwatch* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; protocol_nexwatch_encoder_start(protocol); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = LFRFID_T5577_MODULATION_PSK1 | LFRFID_T5577_BITRATE_RF_32 | (3 << LFRFID_T5577_MAXBLOCK_SHIFT); request->t5577.block[1] = bit_lib_get_bits_32(protocol->encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->encoded_data, 32, 32); request->t5577.block[3] = bit_lib_get_bits_32(protocol->encoded_data, 64, 32); request->t5577.blocks_to_write = 4; result = true; } return result; } const ProtocolBase protocol_nexwatch = { .name = "Nexwatch", .manufacturer = "Honeywell", .data_size = NEXWATCH_DECODED_DATA_SIZE, .features = LFRFIDFeaturePSK, .validate_count = 6, .alloc = (ProtocolAlloc)protocol_nexwatch_alloc, .free = (ProtocolFree)protocol_nexwatch_free, .get_data = (ProtocolGetData)protocol_nexwatch_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_nexwatch_decoder_start, .feed = (ProtocolDecoderFeed)protocol_nexwatch_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_nexwatch_encoder_start, .yield = (ProtocolEncoderYield)protocol_nexwatch_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_nexwatch_render_data, .render_brief_data = (ProtocolRenderData)protocol_nexwatch_render_brief_data, .write_data = (ProtocolWriteData)protocol_nexwatch_write_data, };
11,666
C
.c
295
32.894915
98
0.634603
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,370
protocol_fdx_a.c
DarkFlippers_unleashed-firmware/lib/lfrfid/protocols/protocol_fdx_a.c
#include <furi.h> #include <toolbox/protocols/protocol.h> #include <lfrfid/tools/fsk_demod.h> #include <lfrfid/tools/fsk_osc.h> #include "lfrfid_protocols.h" #include <bit_lib/bit_lib.h> #define JITTER_TIME (20) #define MIN_TIME (64 - JITTER_TIME) #define MAX_TIME (80 + JITTER_TIME) #define FDXA_DATA_SIZE 10 #define FDXA_PREAMBLE_SIZE 2 #define FDXA_ENCODED_DATA_SIZE (FDXA_PREAMBLE_SIZE + FDXA_DATA_SIZE + FDXA_PREAMBLE_SIZE) #define FDXA_ENCODED_BIT_SIZE ((FDXA_PREAMBLE_SIZE + FDXA_DATA_SIZE) * 8) #define FDXA_DECODED_DATA_SIZE (5) #define FDXA_DECODED_BIT_SIZE ((FDXA_ENCODED_BIT_SIZE - FDXA_PREAMBLE_SIZE * 8) / 2) #define FDXA_PREAMBLE_0 0x55 #define FDXA_PREAMBLE_1 0x1D typedef struct { FSKDemod* fsk_demod; } ProtocolFDXADecoder; typedef struct { FSKOsc* fsk_osc; uint8_t encoded_index; uint32_t pulse; } ProtocolFDXAEncoder; typedef struct { ProtocolFDXADecoder decoder; ProtocolFDXAEncoder encoder; uint8_t encoded_data[FDXA_ENCODED_DATA_SIZE]; uint8_t data[FDXA_DECODED_DATA_SIZE]; size_t protocol_size; } ProtocolFDXA; ProtocolFDXA* protocol_fdx_a_alloc(void) { ProtocolFDXA* protocol = malloc(sizeof(ProtocolFDXA)); protocol->decoder.fsk_demod = fsk_demod_alloc(MIN_TIME, 6, MAX_TIME, 5); protocol->encoder.fsk_osc = fsk_osc_alloc(8, 10, 50); return protocol; } void protocol_fdx_a_free(ProtocolFDXA* protocol) { fsk_demod_free(protocol->decoder.fsk_demod); fsk_osc_free(protocol->encoder.fsk_osc); free(protocol); } uint8_t* protocol_fdx_a_get_data(ProtocolFDXA* protocol) { return protocol->data; } void protocol_fdx_a_decoder_start(ProtocolFDXA* protocol) { memset(protocol->encoded_data, 0, FDXA_ENCODED_DATA_SIZE); } static bool protocol_fdx_a_decode(const uint8_t* from, uint8_t* to) { size_t bit_index = 0; for(size_t i = FDXA_PREAMBLE_SIZE; i < (FDXA_PREAMBLE_SIZE + FDXA_DATA_SIZE); i++) { for(size_t n = 0; n < 4; n++) { uint8_t bit_pair = (from[i] >> (6 - (n * 2))) & 0b11; if(bit_pair == 0b01) { bit_lib_set_bit(to, bit_index, 0); } else if(bit_pair == 0b10) { bit_lib_set_bit(to, bit_index, 1); } else { return false; } bit_index++; } } return true; } static void protocol_fdx_a_fix_parity(ProtocolFDXA* protocol) { for(size_t i = 0; i < FDXA_DECODED_DATA_SIZE; i++) { if(bit_lib_test_parity_32(protocol->data[i], BitLibParityOdd)) { protocol->data[i] ^= (1 << 7); } } } static bool protocol_fdx_a_can_be_decoded(const uint8_t* data) { // check preamble if(data[0] != FDXA_PREAMBLE_0 || data[1] != FDXA_PREAMBLE_1 || data[12] != FDXA_PREAMBLE_0 || data[13] != FDXA_PREAMBLE_1) { return false; } // check for manchester encoding uint8_t decoded_data[FDXA_DECODED_DATA_SIZE]; if(!protocol_fdx_a_decode(data, decoded_data)) return false; uint8_t parity_sum = 0; for(size_t i = 0; i < FDXA_DECODED_DATA_SIZE; i++) { parity_sum += bit_lib_test_parity_32(decoded_data[i], BitLibParityOdd); decoded_data[i] &= 0x7F; } return parity_sum == 0; } bool protocol_fdx_a_decoder_feed(ProtocolFDXA* protocol, bool level, uint32_t duration) { bool value; uint32_t count; bool result = false; fsk_demod_feed(protocol->decoder.fsk_demod, level, duration, &value, &count); if(count > 0) { for(size_t i = 0; i < count; i++) { bit_lib_push_bit(protocol->encoded_data, FDXA_ENCODED_DATA_SIZE, value); if(protocol_fdx_a_can_be_decoded(protocol->encoded_data)) { protocol_fdx_a_decode(protocol->encoded_data, protocol->data); result = true; } } } return result; } static void protocol_fdx_a_encode(ProtocolFDXA* protocol) { protocol->encoded_data[0] = FDXA_PREAMBLE_0; protocol->encoded_data[1] = FDXA_PREAMBLE_1; size_t bit_index = 0; for(size_t i = 0; i < FDXA_DECODED_BIT_SIZE; i++) { bool bit = bit_lib_get_bit(protocol->data, i); if(bit) { bit_lib_set_bit(protocol->encoded_data, 16 + bit_index, 1); bit_lib_set_bit(protocol->encoded_data, 16 + bit_index + 1, 0); } else { bit_lib_set_bit(protocol->encoded_data, 16 + bit_index, 0); bit_lib_set_bit(protocol->encoded_data, 16 + bit_index + 1, 1); } bit_index += 2; } } bool protocol_fdx_a_encoder_start(ProtocolFDXA* protocol) { protocol->encoder.encoded_index = 0; protocol->encoder.pulse = 0; protocol_fdx_a_encode(protocol); return true; } LevelDuration protocol_fdx_a_encoder_yield(ProtocolFDXA* protocol) { bool level = 0; uint32_t duration = 0; // if pulse is zero, we need to output high, otherwise we need to output low if(protocol->encoder.pulse == 0) { // get bit uint8_t bit = bit_lib_get_bit(protocol->encoded_data, protocol->encoder.encoded_index); // get pulse from oscillator bool advance = fsk_osc_next(protocol->encoder.fsk_osc, bit, &duration); if(advance) { bit_lib_increment_index(protocol->encoder.encoded_index, FDXA_ENCODED_BIT_SIZE); } // duration diveded by 2 because we need to output high and low duration = duration / 2; protocol->encoder.pulse = duration; level = true; } else { // output low half and reset pulse duration = protocol->encoder.pulse; protocol->encoder.pulse = 0; level = false; } return level_duration_make(level, duration); } bool protocol_fdx_a_write_data(ProtocolFDXA* protocol, void* data) { LFRFIDWriteRequest* request = (LFRFIDWriteRequest*)data; bool result = false; // Correct protocol data by redecoding protocol_fdx_a_fix_parity(protocol); protocol_fdx_a_encoder_start(protocol); protocol_fdx_a_decode(protocol->encoded_data, protocol->data); protocol_fdx_a_encoder_start(protocol); if(request->write_type == LFRFIDWriteTypeT5577) { request->t5577.block[0] = LFRFID_T5577_MODULATION_FSK2a | LFRFID_T5577_BITRATE_RF_50 | (3 << LFRFID_T5577_MAXBLOCK_SHIFT); request->t5577.block[1] = bit_lib_get_bits_32(protocol->encoded_data, 0, 32); request->t5577.block[2] = bit_lib_get_bits_32(protocol->encoded_data, 32, 32); request->t5577.block[3] = bit_lib_get_bits_32(protocol->encoded_data, 64, 32); request->t5577.blocks_to_write = 4; result = true; } return result; } void protocol_fdx_a_render_data(ProtocolFDXA* protocol, FuriString* result) { uint8_t data[FDXA_DECODED_DATA_SIZE]; memcpy(data, protocol->data, FDXA_DECODED_DATA_SIZE); uint8_t parity_sum = 0; for(size_t i = 0; i < FDXA_DECODED_DATA_SIZE; i++) { parity_sum += bit_lib_test_parity_32(data[i], BitLibParityOdd); data[i] &= 0x7F; } furi_string_printf( result, "ID: %010llX\n" "Parity: %c", bit_lib_get_bits_64(data, 0, 40), parity_sum == 0 ? '+' : '-'); } const ProtocolBase protocol_fdx_a = { .name = "FDX-A", .manufacturer = "FECAVA", .data_size = FDXA_DECODED_DATA_SIZE, .features = LFRFIDFeatureASK, .validate_count = 3, .alloc = (ProtocolAlloc)protocol_fdx_a_alloc, .free = (ProtocolFree)protocol_fdx_a_free, .get_data = (ProtocolGetData)protocol_fdx_a_get_data, .decoder = { .start = (ProtocolDecoderStart)protocol_fdx_a_decoder_start, .feed = (ProtocolDecoderFeed)protocol_fdx_a_decoder_feed, }, .encoder = { .start = (ProtocolEncoderStart)protocol_fdx_a_encoder_start, .yield = (ProtocolEncoderYield)protocol_fdx_a_encoder_yield, }, .render_data = (ProtocolRenderData)protocol_fdx_a_render_data, .render_brief_data = (ProtocolRenderData)protocol_fdx_a_render_data, .write_data = (ProtocolWriteData)protocol_fdx_a_write_data, };
8,117
C
.c
208
32.769231
97
0.641886
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,372
t5577.c
DarkFlippers_unleashed-firmware/lib/lfrfid/tools/t5577.c
#include "t5577.h" #include <furi.h> #include <furi_hal_rfid.h> #include <stddef.h> #define T5577_TIMING_WAIT_TIME 400 #define T5577_TIMING_START_GAP 30 #define T5577_TIMING_WRITE_GAP 18 #define T5577_TIMING_DATA_0 24 #define T5577_TIMING_DATA_1 56 #define T5577_TIMING_PROGRAM 700 #define T5577_OPCODE_PAGE_0 0b10 #define T5577_OPCODE_PAGE_1 0b11 #define T5577_OPCODE_RESET 0b00 static void t5577_start(void) { furi_hal_rfid_tim_read_start(125000, 0.5); // do not ground the antenna furi_hal_rfid_pin_pull_release(); } static void t5577_stop(void) { furi_hal_rfid_tim_read_stop(); furi_hal_rfid_pins_reset(); } static void t5577_write_gap(uint32_t gap_time) { furi_hal_rfid_tim_read_pause(); furi_delay_us(gap_time * 8); furi_hal_rfid_tim_read_continue(); } static void t5577_write_bit(bool value) { if(value) { furi_delay_us(T5577_TIMING_DATA_1 * 8); } else { furi_delay_us(T5577_TIMING_DATA_0 * 8); } t5577_write_gap(T5577_TIMING_WRITE_GAP); } static void t5577_write_opcode(uint8_t value) { t5577_write_bit((value >> 1) & 1); t5577_write_bit((value >> 0) & 1); } static void t5577_write_reset(void) { t5577_write_gap(T5577_TIMING_START_GAP); t5577_write_bit(1); t5577_write_bit(0); } static void t5577_write_block_pass( uint8_t page, uint8_t block, bool lock_bit, uint32_t data, bool with_pass, uint32_t password) { furi_delay_us(T5577_TIMING_WAIT_TIME * 8); // start gap t5577_write_gap(T5577_TIMING_START_GAP); // opcode for page t5577_write_opcode((page == 1) ? T5577_OPCODE_PAGE_1 : T5577_OPCODE_PAGE_0); // password if(with_pass) { for(uint8_t i = 0; i < 32; i++) { t5577_write_bit((password >> (31 - i)) & 1); } } // lock bit t5577_write_bit(lock_bit); // data for(uint8_t i = 0; i < 32; i++) { t5577_write_bit((data >> (31 - i)) & 1); } // block address t5577_write_bit((block >> 2) & 1); t5577_write_bit((block >> 1) & 1); t5577_write_bit((block >> 0) & 1); furi_delay_us(T5577_TIMING_PROGRAM * 8); furi_delay_us(T5577_TIMING_WAIT_TIME * 8); t5577_write_reset(); } static void t5577_write_block_simple(uint8_t block, bool lock_bit, uint32_t data) { t5577_write_block_pass(0, block, lock_bit, data, false, 0); } void t5577_write(LFRFIDT5577* data) { t5577_start(); FURI_CRITICAL_ENTER(); for(size_t i = 0; i < data->blocks_to_write; i++) { t5577_write_block_simple(i, false, data->block[i]); } t5577_write_reset(); FURI_CRITICAL_EXIT(); t5577_stop(); } void t5577_write_with_pass(LFRFIDT5577* data, uint32_t password) { t5577_start(); FURI_CRITICAL_ENTER(); for(size_t i = 0; i < data->blocks_to_write; i++) { t5577_write_block_pass(0, i, false, data->block[i], true, password); } t5577_write_reset(); FURI_CRITICAL_EXIT(); t5577_stop(); } void t5577_write_with_mask(LFRFIDT5577* data, uint8_t page, bool with_pass, uint32_t password) { t5577_start(); FURI_CRITICAL_ENTER(); uint8_t mask = data->mask; size_t pages_total = (page == 0) ? T5577_BLOCKS_IN_PAGE_0 : T5577_BLOCKS_IN_PAGE_1; for(size_t i = 0; i < pages_total; i++) { bool need_to_write = mask & 1; mask >>= 1; if(!need_to_write) continue; t5577_write_block_pass(page, i, false, data->block[i], with_pass, password); } t5577_write_reset(); FURI_CRITICAL_EXIT(); t5577_stop(); }
3,551
C
.c
114
26.701754
96
0.636577
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,373
varint_pair.c
DarkFlippers_unleashed-firmware/lib/lfrfid/tools/varint_pair.c
#include "varint_pair.h" #include <toolbox/varint.h> #define VARINT_PAIR_SIZE 10 struct VarintPair { size_t data_length; uint8_t data[VARINT_PAIR_SIZE]; }; VarintPair* varint_pair_alloc(void) { VarintPair* pair = malloc(sizeof(VarintPair)); pair->data_length = 0; return pair; } void varint_pair_free(VarintPair* pair) { free(pair); } bool varint_pair_pack(VarintPair* pair, bool first, uint32_t value) { bool result = false; if(first) { if(pair->data_length == 0) { pair->data_length = varint_uint32_pack(value, pair->data); } else { pair->data_length = 0; } } else { if(pair->data_length != 0) { pair->data_length += varint_uint32_pack(value, pair->data + pair->data_length); result = true; } } return result; } bool varint_pair_unpack( uint8_t* data, size_t data_length, uint32_t* value_1, uint32_t* value_2, size_t* length) { size_t size = 0; uint32_t tmp_value_1; uint32_t tmp_value_2; size += varint_uint32_unpack(&tmp_value_1, &data[size], data_length); if(size >= data_length) { return false; } size += varint_uint32_unpack(&tmp_value_2, &data[size], (size_t)(data_length - size)); *value_1 = tmp_value_1; *value_2 = tmp_value_2; *length = size; return true; } uint8_t* varint_pair_get_data(VarintPair* pair) { return pair->data; } size_t varint_pair_get_size(VarintPair* pair) { return pair->data_length; } void varint_pair_reset(VarintPair* pair) { pair->data_length = 0; }
1,616
C
.c
59
22.457627
91
0.624919
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,374
fsk_demod.c
DarkFlippers_unleashed-firmware/lib/lfrfid/tools/fsk_demod.c
#include <furi.h> #include "fsk_demod.h" struct FSKDemod { uint32_t low_time; uint32_t low_pulses; uint32_t hi_time; uint32_t hi_pulses; bool invert; uint32_t mid_time; uint32_t time; uint32_t count; bool last_pulse; }; FSKDemod* fsk_demod_alloc(uint32_t low_time, uint32_t low_pulses, uint32_t hi_time, uint32_t hi_pulses) { FSKDemod* demod = malloc(sizeof(FSKDemod)); demod->invert = false; if(low_time > hi_time) { uint32_t tmp; tmp = hi_time; hi_time = low_time; low_time = tmp; tmp = hi_pulses; hi_pulses = low_pulses; low_pulses = tmp; demod->invert = true; } demod->low_time = low_time; demod->low_pulses = low_pulses; demod->hi_time = hi_time; demod->hi_pulses = hi_pulses; demod->mid_time = (hi_time - low_time) / 2 + low_time; demod->time = 0; demod->count = 0; demod->last_pulse = false; return demod; } void fsk_demod_free(FSKDemod* demod) { free(demod); } void fsk_demod_feed(FSKDemod* demod, bool polarity, uint32_t time, bool* value, uint32_t* count) { *count = 0; if(polarity) { // accumulate time demod->time = time; } else { demod->time += time; // check for valid pulse if(demod->time >= demod->low_time && demod->time < demod->hi_time) { bool pulse; if(demod->time < demod->mid_time) { pulse = false; } else { pulse = true; } demod->count++; // check for edge transition if(demod->last_pulse != pulse) { uint32_t data_count = demod->count + 1; if(demod->last_pulse) { data_count /= demod->hi_pulses; *value = !demod->invert; } else { data_count /= demod->low_pulses; *value = demod->invert; } *count = data_count; demod->count = 0; demod->last_pulse = pulse; } } else { demod->count = 0; } } }
2,196
C
.c
75
20.52
99
0.516881
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,375
fsk_ocs.c
DarkFlippers_unleashed-firmware/lib/lfrfid/tools/fsk_ocs.c
#include "fsk_osc.h" #include <stdlib.h> struct FSKOsc { uint16_t freq[2]; uint16_t osc_phase_max; int32_t osc_phase_current; uint32_t pulse; }; FSKOsc* fsk_osc_alloc(uint32_t freq_low, uint32_t freq_hi, uint32_t osc_phase_max) { FSKOsc* osc = malloc(sizeof(FSKOsc)); osc->freq[0] = freq_low; osc->freq[1] = freq_hi; osc->osc_phase_max = osc_phase_max; osc->osc_phase_current = 0; osc->pulse = 0; return osc; } void fsk_osc_free(FSKOsc* osc) { free(osc); } void fsk_osc_reset(FSKOsc* osc) { osc->osc_phase_current = 0; osc->pulse = 0; } bool fsk_osc_next(FSKOsc* osc, bool bit, uint32_t* period) { bool advance = false; *period = osc->freq[bit]; osc->osc_phase_current += *period; if(osc->osc_phase_current > osc->osc_phase_max) { advance = true; osc->osc_phase_current -= osc->osc_phase_max; } return advance; } bool fsk_osc_next_half(FSKOsc* osc, bool bit, bool* level, uint32_t* duration) { bool advance = false; // if pulse is zero, we need to output high, otherwise we need to output low if(osc->pulse == 0) { uint32_t length; advance = fsk_osc_next(osc, bit, &length); *duration = length / 2; osc->pulse = *duration; *level = true; } else { // output low half and reset pulse *duration = osc->pulse; osc->pulse = 0; *level = false; } return advance; }
1,461
C
.c
51
23.666667
84
0.611866
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,402
u8g2_glue.c
DarkFlippers_unleashed-firmware/lib/u8g2/u8g2_glue.c
#include "u8g2_glue.h" #include <furi_hal.h> #define CONTRAST_ERC 32 #define CONTRAST_MGG 28 uint8_t u8g2_gpio_and_delay_stm32(u8x8_t* u8x8, uint8_t msg, uint8_t arg_int, void* arg_ptr) { UNUSED(u8x8); UNUSED(arg_ptr); switch(msg) { case U8X8_MSG_GPIO_AND_DELAY_INIT: /* HAL initialization contains all what we need so we can skip this part. */ break; case U8X8_MSG_DELAY_MILLI: furi_delay_ms(arg_int); break; case U8X8_MSG_DELAY_10MICRO: furi_delay_us(10); break; case U8X8_MSG_DELAY_100NANO: asm("nop"); break; case U8X8_MSG_GPIO_RESET: furi_hal_gpio_write(&gpio_display_rst_n, arg_int); break; default: return 0; } return 1; } uint8_t u8x8_hw_spi_stm32(u8x8_t* u8x8, uint8_t msg, uint8_t arg_int, void* arg_ptr) { UNUSED(u8x8); switch(msg) { case U8X8_MSG_BYTE_SEND: furi_hal_spi_bus_tx(&furi_hal_spi_bus_handle_display, (uint8_t*)arg_ptr, arg_int, 10000); break; case U8X8_MSG_BYTE_SET_DC: furi_hal_gpio_write(&gpio_display_di, arg_int); break; case U8X8_MSG_BYTE_INIT: break; case U8X8_MSG_BYTE_START_TRANSFER: furi_hal_spi_acquire(&furi_hal_spi_bus_handle_display); break; case U8X8_MSG_BYTE_END_TRANSFER: furi_hal_spi_release(&furi_hal_spi_bus_handle_display); break; default: return 0; } return 1; } #define ST756X_CMD_ON_OFF 0b10101110 /**< 0:0 Switch Display ON/OFF: last bit */ #define ST756X_CMD_SET_LINE 0b01000000 /**< 0:0 Set Start Line: last 6 bits */ #define ST756X_CMD_SET_PAGE 0b10110000 /**< 0:0 Set Page address: last 4 bits */ #define ST756X_CMD_SET_COLUMN_MSB 0b00010000 /**< 0:0 Set Column MSB: last 4 bits */ #define ST756X_CMD_SET_COLUMN_LSB 0b00000000 /**< 0:0 Set Column LSB: last 4 bits */ #define ST756X_CMD_SEG_DIRECTION 0b10100000 /**< 0:0 Reverse scan direction of SEG: last bit */ #define ST756X_CMD_INVERSE_DISPLAY 0b10100110 /**< 0:0 Invert display: last bit */ #define ST756X_CMD_ALL_PIXEL_ON 0b10100100 /**< 0:0 Set all pixel on: last bit */ #define ST756X_CMD_BIAS_SELECT 0b10100010 /**< 0:0 Select 1/9(0) or 1/7(1) bias: last bit */ #define ST756X_CMD_R_M_W 0b11100000 /**< 0:0 Enter Read Modify Write mode: read+0, write+1 */ #define ST756X_CMD_END 0b11101110 /**< 0:0 Exit Read Modify Write mode */ #define ST756X_CMD_RESET 0b11100010 /**< 0:0 Software Reset */ #define ST756X_CMD_COM_DIRECTION 0b11000000 /**< 0:0 Com direction reverse: +0b1000 */ #define ST756X_CMD_POWER_CONTROL 0b00101000 /**< 0:0 Power control: last 3 bits VB:VR:VF */ #define ST756X_CMD_REGULATION_RATIO 0b00100000 /**< 0:0 Regulation resistor ration: last 3bits */ #define ST756X_CMD_SET_EV 0b10000001 /**< 0:0 Set electronic volume: 5 bits in next byte */ #define ST756X_CMD_SET_BOOSTER \ 0b11111000 /**< 0:0 Set Booster level, 4X(0) or 5X(1): last bit in next byte */ #define ST756X_CMD_NOP 0b11100011 /**< 0:0 No operation */ static const uint8_t u8x8_d_st756x_powersave0_seq[] = { U8X8_START_TRANSFER(), /* enable chip, delay is part of the transfer start */ U8X8_C(ST756X_CMD_ALL_PIXEL_ON | 0b0), /* all pixel off */ U8X8_C(ST756X_CMD_ON_OFF | 0b1), /* display on */ U8X8_END_TRANSFER(), /* disable chip */ U8X8_END() /* end of sequence */ }; static const uint8_t u8x8_d_st756x_powersave1_seq[] = { U8X8_START_TRANSFER(), /* enable chip, delay is part of the transfer start */ U8X8_C(ST756X_CMD_ON_OFF | 0b0), /* display off */ U8X8_C(ST756X_CMD_ALL_PIXEL_ON | 0b1), /* all pixel on */ U8X8_END_TRANSFER(), /* disable chip */ U8X8_END() /* end of sequence */ }; static const uint8_t u8x8_d_st756x_flip0_seq[] = { U8X8_START_TRANSFER(), /* enable chip, delay is part of the transfer start */ U8X8_C(0x0a1), /* segment remap a0/a1*/ U8X8_C(0x0c0), /* c0: scan dir normal, c8: reverse */ U8X8_END_TRANSFER(), /* disable chip */ U8X8_END() /* end of sequence */ }; static const uint8_t u8x8_d_st756x_flip1_seq[] = { U8X8_START_TRANSFER(), /* enable chip, delay is part of the transfer start */ U8X8_C(0x0a0), /* segment remap a0/a1*/ U8X8_C(0x0c8), /* c0: scan dir normal, c8: reverse */ U8X8_END_TRANSFER(), /* disable chip */ U8X8_END() /* end of sequence */ }; static const u8x8_display_info_t u8x8_st756x_128x64_display_info = { .chip_enable_level = 0, .chip_disable_level = 1, .post_chip_enable_wait_ns = 150, /* st7565 datasheet, table 26, tcsh */ .pre_chip_disable_wait_ns = 50, /* st7565 datasheet, table 26, tcss */ .reset_pulse_width_ms = 1, .post_reset_wait_ms = 1, .sda_setup_time_ns = 50, /* st7565 datasheet, table 26, tsds */ .sck_pulse_width_ns = 120, /* half of cycle time (100ns according to datasheet), AVR: below 70: 8 MHz, >= 70 --> 4MHz clock */ .sck_clock_hz = 4000000UL, /* since Arduino 1.6.0, the SPI bus speed in Hz. Should be 1000000000/sck_pulse_width_ns */ .spi_mode = 0, /* active high, rising edge */ .i2c_bus_clock_100kHz = 4, .data_setup_time_ns = 40, /* st7565 datasheet, table 24, tds8 */ .write_pulse_width_ns = 80, /* st7565 datasheet, table 24, tcclw */ .tile_width = 16, /* width of 16*8=128 pixel */ .tile_height = 8, .default_x_offset = 0, .flipmode_x_offset = 4, .pixel_width = 128, .pixel_height = 64}; uint8_t u8x8_d_st756x_common(u8x8_t* u8x8, uint8_t msg, uint8_t arg_int, void* arg_ptr) { uint8_t x, c; uint8_t* ptr; switch(msg) { case U8X8_MSG_DISPLAY_DRAW_TILE: u8x8_cad_StartTransfer(u8x8); x = ((u8x8_tile_t*)arg_ptr)->x_pos; x *= 8; x += u8x8->x_offset; u8x8_cad_SendCmd(u8x8, 0x010 | (x >> 4)); u8x8_cad_SendCmd(u8x8, 0x000 | (x & 15)); u8x8_cad_SendCmd(u8x8, 0x0b0 | (((u8x8_tile_t*)arg_ptr)->y_pos)); c = ((u8x8_tile_t*)arg_ptr)->cnt; c *= 8; ptr = ((u8x8_tile_t*)arg_ptr)->tile_ptr; /* The following if condition checks the hardware limits of the st7565 controller: It is not allowed to write beyond the display limits. This is in fact an issue within flip mode. */ if(c + x > 132u) { c = 132u; c -= x; } do { u8x8_cad_SendData( u8x8, c, ptr); /* note: SendData can not handle more than 255 bytes */ arg_int--; } while(arg_int > 0); u8x8_cad_EndTransfer(u8x8); break; case U8X8_MSG_DISPLAY_SET_POWER_SAVE: if(arg_int == 0) u8x8_cad_SendSequence(u8x8, u8x8_d_st756x_powersave0_seq); else u8x8_cad_SendSequence(u8x8, u8x8_d_st756x_powersave1_seq); break; #ifdef U8X8_WITH_SET_CONTRAST case U8X8_MSG_DISPLAY_SET_CONTRAST: u8x8_cad_StartTransfer(u8x8); u8x8_cad_SendCmd(u8x8, ST756X_CMD_SET_EV); u8x8_cad_SendArg(u8x8, arg_int >> 2); /* st7565 has range from 0 to 63 */ u8x8_cad_EndTransfer(u8x8); break; #endif default: return 0; } return 1; } void u8x8_d_st756x_init(u8x8_t* u8x8, uint8_t contrast, uint8_t regulation_ratio, bool bias) { contrast = contrast & 0b00111111; regulation_ratio = regulation_ratio & 0b111; u8x8_cad_StartTransfer(u8x8); // Reset u8x8_cad_SendCmd(u8x8, ST756X_CMD_RESET); // Bias: 1/7(0b1) or 1/9(0b0) u8x8_cad_SendCmd(u8x8, ST756X_CMD_BIAS_SELECT | bias); // Page, Line and Segment config u8x8_cad_SendCmd(u8x8, ST756X_CMD_SEG_DIRECTION); u8x8_cad_SendCmd(u8x8, ST756X_CMD_COM_DIRECTION | 0b1000); u8x8_cad_SendCmd(u8x8, ST756X_CMD_SET_LINE); // Set Regulation Ratio u8x8_cad_SendCmd(u8x8, ST756X_CMD_REGULATION_RATIO | regulation_ratio); // Set EV u8x8_cad_SendCmd(u8x8, ST756X_CMD_SET_EV); u8x8_cad_SendArg(u8x8, contrast); // Enable power u8x8_cad_SendCmd(u8x8, ST756X_CMD_POWER_CONTROL | 0b111); u8x8_cad_EndTransfer(u8x8); } void u8x8_d_st756x_set_contrast(u8x8_t* u8x8, int8_t contrast_offset) { uint8_t contrast = (furi_hal_version_get_hw_display() == FuriHalVersionDisplayMgg) ? CONTRAST_MGG : CONTRAST_ERC; contrast += contrast_offset; contrast = contrast & 0b00111111; u8x8_cad_StartTransfer(u8x8); u8x8_cad_SendCmd(u8x8, ST756X_CMD_SET_EV); u8x8_cad_SendArg(u8x8, contrast); u8x8_cad_EndTransfer(u8x8); } uint8_t u8x8_d_st756x_flipper(u8x8_t* u8x8, uint8_t msg, uint8_t arg_int, void* arg_ptr) { /* call common procedure first and handle messages there */ if(u8x8_d_st756x_common(u8x8, msg, arg_int, arg_ptr) == 0) { /* msg not handled, then try here */ switch(msg) { case U8X8_MSG_DISPLAY_SETUP_MEMORY: u8x8_d_helper_display_setup_memory(u8x8, &u8x8_st756x_128x64_display_info); break; case U8X8_MSG_DISPLAY_INIT: u8x8_d_helper_display_init(u8x8); FuriHalVersionDisplay display = furi_hal_version_get_hw_display(); if(display == FuriHalVersionDisplayMgg) { /* MGG v0+(ST7567) * EV = 32 * RR = V0 / ((1 - (63 - EV) / 162) * 2.1) * RR = 10 / ((1 - (63 - 32) / 162) * 2.1) ~= 5.88 is 6 (0b110) * Bias = 1/9 (false) */ u8x8_d_st756x_init(u8x8, CONTRAST_MGG, 0b110, false); } else { /* ERC v1(ST7565) and v2(ST7567) * EV = 33 * RR = V0 / ((1 - (63 - EV) / 162) * 2.1) * RR = 9.3 / ((1 - (63 - 32) / 162) * 2.1) ~= 5.47 is 5.5 (0b101) * Bias = 1/9 (false) */ u8x8_d_st756x_init(u8x8, CONTRAST_ERC, 0b101, false); } break; case U8X8_MSG_DISPLAY_SET_FLIP_MODE: if(arg_int == 0) { u8x8_cad_SendSequence(u8x8, u8x8_d_st756x_flip1_seq); u8x8->x_offset = u8x8->display_info->default_x_offset; } else { u8x8_cad_SendSequence(u8x8, u8x8_d_st756x_flip0_seq); u8x8->x_offset = u8x8->display_info->flipmode_x_offset; } break; default: /* msg unknown */ return 0; } } return 1; } void u8g2_Setup_st756x_flipper( u8g2_t* u8g2, const u8g2_cb_t* rotation, u8x8_msg_cb byte_cb, u8x8_msg_cb gpio_and_delay_cb) { uint8_t tile_buf_height; uint8_t* buf; u8g2_SetupDisplay(u8g2, u8x8_d_st756x_flipper, u8x8_cad_001, byte_cb, gpio_and_delay_cb); buf = u8g2_m_16_8_f(&tile_buf_height); u8g2_SetupBuffer(u8g2, buf, tile_buf_height, u8g2_ll_hvline_vertical_top_lsb, rotation); }
10,934
C
.c
257
35.400778
112
0.60552
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,406
one_wire_host.c
DarkFlippers_unleashed-firmware/lib/one_wire/one_wire_host.c
#include <furi.h> /** * Timings based on Application Note 126: * https://www.analog.com/media/en/technical-documentation/tech-articles/1wire-communication-through-software--maxim-integrated.pdf */ #include "one_wire_host.h" typedef struct { uint16_t a; uint16_t b; uint16_t c; uint16_t d; uint16_t e; uint16_t f; uint16_t g; uint16_t h; uint16_t i; uint16_t j; } OneWireHostTimings; static const OneWireHostTimings onewire_host_timings_normal = { .a = 9, .b = 64, .c = 64, .d = 14, .e = 9, .f = 55, .g = 0, .h = 480, .i = 70, .j = 410, }; static const OneWireHostTimings onewire_host_timings_overdrive = { .a = 1, .b = 8, .c = 8, .d = 3, .e = 1, .f = 7, .g = 3, .h = 70, .i = 9, .j = 40, }; struct OneWireHost { const GpioPin* gpio_pin; const OneWireHostTimings* timings; unsigned char saved_rom[8]; /** < global search state */ uint8_t last_discrepancy; uint8_t last_family_discrepancy; bool last_device_flag; }; OneWireHost* onewire_host_alloc(const GpioPin* gpio_pin) { furi_check(gpio_pin); OneWireHost* host = malloc(sizeof(OneWireHost)); host->gpio_pin = gpio_pin; onewire_host_reset_search(host); onewire_host_set_overdrive(host, false); return host; } void onewire_host_free(OneWireHost* host) { furi_check(host); onewire_host_stop(host); free(host); } bool onewire_host_reset(OneWireHost* host) { furi_check(host); uint8_t r; uint8_t retries = 125; const OneWireHostTimings* timings = host->timings; // wait until the gpio is high furi_hal_gpio_write(host->gpio_pin, true); do { if(--retries == 0) return 0; furi_delay_us(2); } while(!furi_hal_gpio_read(host->gpio_pin)); // pre delay furi_delay_us(timings->g); // drive low furi_hal_gpio_write(host->gpio_pin, false); furi_delay_us(timings->h); // release furi_hal_gpio_write(host->gpio_pin, true); furi_delay_us(timings->i); // read and post delay r = !furi_hal_gpio_read(host->gpio_pin); furi_delay_us(timings->j); return r; } bool onewire_host_read_bit(OneWireHost* host) { furi_check(host); bool result; const OneWireHostTimings* timings = host->timings; // drive low furi_hal_gpio_write(host->gpio_pin, false); furi_delay_us(timings->a); // release furi_hal_gpio_write(host->gpio_pin, true); furi_delay_us(timings->e); // read and post delay result = furi_hal_gpio_read(host->gpio_pin); furi_delay_us(timings->f); return result; } uint8_t onewire_host_read(OneWireHost* host) { furi_check(host); uint8_t result = 0; for(uint8_t bitMask = 0x01; bitMask; bitMask <<= 1) { if(onewire_host_read_bit(host)) { result |= bitMask; } } return result; } void onewire_host_read_bytes(OneWireHost* host, uint8_t* buffer, uint16_t count) { furi_check(host); furi_check(buffer); for(uint16_t i = 0; i < count; i++) { buffer[i] = onewire_host_read(host); } } void onewire_host_write_bit(OneWireHost* host, bool value) { furi_check(host); const OneWireHostTimings* timings = host->timings; if(value) { // drive low furi_hal_gpio_write(host->gpio_pin, false); furi_delay_us(timings->a); // release furi_hal_gpio_write(host->gpio_pin, true); furi_delay_us(timings->b); } else { // drive low furi_hal_gpio_write(host->gpio_pin, false); furi_delay_us(timings->c); // release furi_hal_gpio_write(host->gpio_pin, true); furi_delay_us(timings->d); } } void onewire_host_write(OneWireHost* host, uint8_t value) { furi_check(host); uint8_t bitMask; for(bitMask = 0x01; bitMask; bitMask <<= 1) { onewire_host_write_bit(host, (bitMask & value) ? 1 : 0); } } void onewire_host_write_bytes(OneWireHost* host, const uint8_t* buffer, uint16_t count) { furi_check(host); furi_check(buffer); for(uint16_t i = 0; i < count; ++i) { onewire_host_write(host, buffer[i]); } } void onewire_host_start(OneWireHost* host) { furi_check(host); furi_hal_gpio_write(host->gpio_pin, true); furi_hal_gpio_init(host->gpio_pin, GpioModeOutputOpenDrain, GpioPullNo, GpioSpeedLow); } void onewire_host_stop(OneWireHost* host) { furi_check(host); furi_hal_gpio_write(host->gpio_pin, true); furi_hal_gpio_init(host->gpio_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); } void onewire_host_reset_search(OneWireHost* host) { furi_check(host); host->last_discrepancy = 0; host->last_device_flag = false; host->last_family_discrepancy = 0; for(int i = 7;; i--) { host->saved_rom[i] = 0; if(i == 0) break; } } void onewire_host_target_search(OneWireHost* host, uint8_t family_code) { furi_check(host); host->saved_rom[0] = family_code; for(uint8_t i = 1; i < 8; i++) host->saved_rom[i] = 0; host->last_discrepancy = 64; host->last_family_discrepancy = 0; host->last_device_flag = false; } bool onewire_host_search(OneWireHost* host, uint8_t* new_addr, OneWireHostSearchMode mode) { furi_check(host); uint8_t id_bit_number; uint8_t last_zero, rom_byte_number, search_result; uint8_t id_bit, cmp_id_bit; unsigned char rom_byte_mask, search_direction; // initialize for search id_bit_number = 1; last_zero = 0; rom_byte_number = 0; rom_byte_mask = 1; search_result = 0; // if the last call was not the last one if(!host->last_device_flag) { // 1-Wire reset if(!onewire_host_reset(host)) { // reset the search host->last_discrepancy = 0; host->last_device_flag = false; host->last_family_discrepancy = 0; return false; } // issue the search command switch(mode) { case OneWireHostSearchModeConditional: onewire_host_write(host, 0xEC); break; case OneWireHostSearchModeNormal: onewire_host_write(host, 0xF0); break; } // loop to do the search do { // read a bit and its complement id_bit = onewire_host_read_bit(host); cmp_id_bit = onewire_host_read_bit(host); // check for no devices on 1-wire if((id_bit == 1) && (cmp_id_bit == 1)) break; else { // all devices coupled have 0 or 1 if(id_bit != cmp_id_bit) search_direction = id_bit; // bit write value for search else { // if this discrepancy if before the Last Discrepancy // on a previous next then pick the same as last time if(id_bit_number < host->last_discrepancy) search_direction = ((host->saved_rom[rom_byte_number] & rom_byte_mask) > 0); else // if equal to last pick 1, if not then pick 0 search_direction = (id_bit_number == host->last_discrepancy); // if 0 was picked then record its position in LastZero if(search_direction == 0) { last_zero = id_bit_number; // check for Last discrepancy in family if(last_zero < 9) host->last_family_discrepancy = last_zero; } } // set or clear the bit in the ROM byte rom_byte_number // with mask rom_byte_mask if(search_direction == 1) host->saved_rom[rom_byte_number] |= rom_byte_mask; else host->saved_rom[rom_byte_number] &= ~rom_byte_mask; // serial number search direction write bit onewire_host_write_bit(host, search_direction); // increment the byte counter id_bit_number // and shift the mask rom_byte_mask id_bit_number++; rom_byte_mask <<= 1; // if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask if(rom_byte_mask == 0) { rom_byte_number++; rom_byte_mask = 1; } } } while(rom_byte_number < 8); // loop until through all ROM bytes 0-7 // if the search was successful then if(!(id_bit_number < 65)) { // search successful so set last_Discrepancy, last_device_flag, search_result host->last_discrepancy = last_zero; // check for last device if(host->last_discrepancy == 0) host->last_device_flag = true; search_result = true; } } // if no device found then reset counters so next 'search' will be like a first if(!search_result || !host->saved_rom[0]) { host->last_discrepancy = 0; host->last_device_flag = false; host->last_family_discrepancy = 0; search_result = false; } else { for(int i = 0; i < 8; i++) new_addr[i] = host->saved_rom[i]; } return search_result; } void onewire_host_set_overdrive(OneWireHost* host, bool set) { furi_check(host); host->timings = set ? &onewire_host_timings_overdrive : &onewire_host_timings_normal; }
9,612
C
.c
284
26.03169
131
0.58589
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,408
one_wire_slave.c
DarkFlippers_unleashed-firmware/lib/one_wire/one_wire_slave.c
#include "one_wire_slave.h" #include <furi.h> #include <furi_hal.h> #define TH_TIMEOUT_MAX 15000 /* Maximum time before general timeout */ typedef enum { OneWireSlaveErrorNone = 0, OneWireSlaveErrorResetInProgress, OneWireSlaveErrorPresenceConflict, OneWireSlaveErrorInvalidCommand, OneWireSlaveErrorTimeout, } OneWireSlaveError; typedef struct { uint16_t trstl_min; /* Minimum Reset Low time */ uint16_t trstl_max; /* Maximum Reset Low time */ uint16_t tpdh_typ; /* Typical Presence Detect High time */ uint16_t tpdl_min; /* Minimum Presence Detect Low time */ uint16_t tpdl_max; /* Maximum Presence Detect Low time */ uint16_t tslot_min; /* Minimum Read/Write Slot time */ uint16_t tslot_max; /* Maximum Read/Write Slot time */ uint16_t tw1l_max; /* Maximum Master Write 1 time */ uint16_t trl_tmsr_max; /* Maximum Master Read Low + Read Sample time */ } OneWireSlaveTimings; struct OneWireSlave { const GpioPin* gpio_pin; const OneWireSlaveTimings* timings; OneWireSlaveError error; bool is_first_reset; bool is_short_reset; OneWireSlaveResetCallback reset_callback; OneWireSlaveCommandCallback command_callback; OneWireSlaveResultCallback result_callback; void* reset_callback_context; void* result_callback_context; void* command_callback_context; }; static const OneWireSlaveTimings onewire_slave_timings_normal = { .trstl_min = 270, .trstl_max = 1200, .tpdh_typ = 20, .tpdl_min = 100, .tpdl_max = 480, .tslot_min = 60, .tslot_max = 135, .tw1l_max = 20, .trl_tmsr_max = 30, }; static const OneWireSlaveTimings onewire_slave_timings_overdrive = { .trstl_min = 48, .trstl_max = 80, .tpdh_typ = 0, .tpdl_min = 8, .tpdl_max = 24, .tslot_min = 6, .tslot_max = 16, .tw1l_max = 2, .trl_tmsr_max = 3, }; /*********************** PRIVATE ***********************/ static bool onewire_slave_wait_while_gpio_is(OneWireSlave* bus, uint32_t time_us, const bool pin_value) { const uint32_t time_start = DWT->CYCCNT; const uint32_t time_ticks = time_us * furi_hal_cortex_instructions_per_microsecond(); uint32_t time_elapsed; do { //-V1044 time_elapsed = DWT->CYCCNT - time_start; if(furi_hal_gpio_read(bus->gpio_pin) != pin_value) { return time_ticks >= time_elapsed; } } while(time_elapsed < time_ticks); return false; } static inline bool onewire_slave_show_presence(OneWireSlave* bus) { const OneWireSlaveTimings* timings = bus->timings; // wait until the bus is high (might return immediately) onewire_slave_wait_while_gpio_is(bus, timings->trstl_max, false); // wait while master delay presence check furi_delay_us(timings->tpdh_typ); // show presence furi_hal_gpio_write(bus->gpio_pin, false); furi_delay_us(timings->tpdl_min); furi_hal_gpio_write(bus->gpio_pin, true); // somebody also can show presence const uint32_t wait_low_time = timings->tpdl_max - timings->tpdl_min; // so we will wait if(!onewire_slave_wait_while_gpio_is(bus, wait_low_time, false)) { bus->error = OneWireSlaveErrorPresenceConflict; return false; } return true; } static inline bool onewire_slave_receive_and_process_command(OneWireSlave* bus) { /* Reset condition detected, send a presence pulse and reset protocol state */ if(bus->error == OneWireSlaveErrorResetInProgress) { if(!bus->is_first_reset) { /* Guess the reset type */ bus->is_short_reset = onewire_slave_wait_while_gpio_is( bus, onewire_slave_timings_overdrive.trstl_max - onewire_slave_timings_overdrive.tslot_max, false); } else { bus->is_first_reset = false; } furi_assert(bus->reset_callback); if(bus->reset_callback(bus->is_short_reset, bus->reset_callback_context)) { if(onewire_slave_show_presence(bus)) { bus->error = OneWireSlaveErrorNone; return true; } } } else if(bus->error == OneWireSlaveErrorNone) { uint8_t command; if(onewire_slave_receive(bus, &command, sizeof(command))) { furi_assert(bus->command_callback); if(bus->command_callback(command, bus->command_callback_context)) { return true; } } return bus->error == OneWireSlaveErrorResetInProgress; } return false; } static inline bool onewire_slave_bus_start(OneWireSlave* bus) { FURI_CRITICAL_ENTER(); furi_hal_gpio_disable_int_callback(bus->gpio_pin); furi_hal_gpio_init(bus->gpio_pin, GpioModeOutputOpenDrain, GpioPullNo, GpioSpeedLow); while(onewire_slave_receive_and_process_command(bus)) ; const bool result = (bus->error == OneWireSlaveErrorNone); furi_hal_gpio_init(bus->gpio_pin, GpioModeInterruptRiseFall, GpioPullNo, GpioSpeedLow); furi_hal_gpio_enable_int_callback(bus->gpio_pin); FURI_CRITICAL_EXIT(); return result; } static void onewire_slave_exti_callback(void* context) { OneWireSlave* bus = context; const volatile bool input_state = furi_hal_gpio_read(bus->gpio_pin); static uint32_t pulse_start = 0; if(input_state) { const uint32_t pulse_length = (DWT->CYCCNT - pulse_start) / furi_hal_cortex_instructions_per_microsecond(); if((pulse_length >= onewire_slave_timings_overdrive.trstl_min) && (pulse_length <= onewire_slave_timings_normal.trstl_max)) { /* Start in reset state in order to send a presence pulse immediately */ bus->error = OneWireSlaveErrorResetInProgress; /* Determine reset type (chooses speed mode if supported by the emulated device) */ bus->is_short_reset = pulse_length <= onewire_slave_timings_overdrive.trstl_max; /* Initial reset allows going directly into overdrive mode */ bus->is_first_reset = true; const bool result = onewire_slave_bus_start(bus); if(result && bus->result_callback != NULL) { bus->result_callback(bus->result_callback_context); } } } else { pulse_start = DWT->CYCCNT; } } /*********************** PUBLIC ***********************/ OneWireSlave* onewire_slave_alloc(const GpioPin* gpio_pin) { furi_check(gpio_pin); OneWireSlave* bus = malloc(sizeof(OneWireSlave)); bus->gpio_pin = gpio_pin; bus->timings = &onewire_slave_timings_normal; bus->error = OneWireSlaveErrorNone; return bus; } void onewire_slave_free(OneWireSlave* bus) { furi_check(bus); onewire_slave_stop(bus); free(bus); } void onewire_slave_start(OneWireSlave* bus) { furi_check(bus); furi_hal_gpio_add_int_callback(bus->gpio_pin, onewire_slave_exti_callback, bus); furi_hal_gpio_write(bus->gpio_pin, true); furi_hal_gpio_init(bus->gpio_pin, GpioModeInterruptRiseFall, GpioPullNo, GpioSpeedLow); } void onewire_slave_stop(OneWireSlave* bus) { furi_check(bus); furi_hal_gpio_write(bus->gpio_pin, true); furi_hal_gpio_init(bus->gpio_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); furi_hal_gpio_remove_int_callback(bus->gpio_pin); } void onewire_slave_set_reset_callback( OneWireSlave* bus, OneWireSlaveResetCallback callback, void* context) { furi_check(bus); bus->reset_callback = callback; bus->reset_callback_context = context; } void onewire_slave_set_command_callback( OneWireSlave* bus, OneWireSlaveCommandCallback callback, void* context) { furi_check(bus); bus->command_callback = callback; bus->command_callback_context = context; } void onewire_slave_set_result_callback( OneWireSlave* bus, OneWireSlaveResultCallback result_cb, void* context) { furi_check(bus); bus->result_callback = result_cb; bus->result_callback_context = context; } bool onewire_slave_receive_bit(OneWireSlave* bus) { furi_check(bus); const OneWireSlaveTimings* timings = bus->timings; // wait while bus is low if(!onewire_slave_wait_while_gpio_is(bus, timings->tslot_max, false)) { bus->error = OneWireSlaveErrorResetInProgress; return false; } // wait while bus is high if(!onewire_slave_wait_while_gpio_is(bus, TH_TIMEOUT_MAX, true)) { bus->error = OneWireSlaveErrorTimeout; return false; } // wait a time of zero return onewire_slave_wait_while_gpio_is(bus, timings->tw1l_max, false); } bool onewire_slave_send_bit(OneWireSlave* bus, bool value) { furi_check(bus); const OneWireSlaveTimings* timings = bus->timings; // wait while bus is low if(!onewire_slave_wait_while_gpio_is(bus, timings->tslot_max, false)) { bus->error = OneWireSlaveErrorResetInProgress; return false; } // wait while bus is high if(!onewire_slave_wait_while_gpio_is(bus, TH_TIMEOUT_MAX, true)) { bus->error = OneWireSlaveErrorTimeout; return false; } // choose write time uint32_t time; if(!value) { furi_hal_gpio_write(bus->gpio_pin, false); time = timings->trl_tmsr_max; } else { time = timings->tslot_min; } // hold line for ZERO or ONE time furi_delay_us(time); furi_hal_gpio_write(bus->gpio_pin, true); return true; } bool onewire_slave_send(OneWireSlave* bus, const uint8_t* data, size_t data_size) { furi_check(bus); furi_hal_gpio_write(bus->gpio_pin, true); size_t bytes_sent = 0; // bytes loop for(; bytes_sent < data_size; ++bytes_sent) { const uint8_t data_byte = data[bytes_sent]; // bit loop for(uint8_t bit_mask = 0x01; bit_mask != 0; bit_mask <<= 1) { if(!onewire_slave_send_bit(bus, bit_mask & data_byte)) { return false; } } } return true; } bool onewire_slave_receive(OneWireSlave* bus, uint8_t* data, size_t data_size) { furi_check(bus); furi_hal_gpio_write(bus->gpio_pin, true); size_t bytes_received = 0; for(; bytes_received < data_size; ++bytes_received) { uint8_t value = 0; for(uint8_t bit_mask = 0x01; bit_mask != 0; bit_mask <<= 1) { if(onewire_slave_receive_bit(bus)) { value |= bit_mask; } if(bus->error != OneWireSlaveErrorNone) { return false; } } data[bytes_received] = value; } return true; } void onewire_slave_set_overdrive(OneWireSlave* bus, bool set) { furi_check(bus); const OneWireSlaveTimings* new_timings = set ? &onewire_slave_timings_overdrive : &onewire_slave_timings_normal; if(bus->timings != new_timings) { /* Prevent erroneous reset by waiting for the previous time slot to finish */ onewire_slave_wait_while_gpio_is(bus, bus->timings->tslot_max, false); bus->timings = new_timings; } }
11,150
C
.c
294
31.411565
97
0.651314
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,410
maxim_crc.c
DarkFlippers_unleashed-firmware/lib/one_wire/maxim_crc.c
#include "maxim_crc.h" #include <furi.h> uint8_t maxim_crc8(const uint8_t* data, const uint8_t data_size, const uint8_t crc_init) { furi_check(data); uint8_t crc = crc_init; for(uint8_t index = 0; index < data_size; ++index) { uint8_t input_byte = data[index]; for(uint8_t bit_position = 0; bit_position < 8; ++bit_position) { const uint8_t mix = (crc ^ input_byte) & (uint8_t)(0x01); crc >>= 1; if(mix != 0) crc ^= 0x8C; input_byte >>= 1; } } return crc; }
553
C
.c
16
27.625
90
0.55618
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,413
int_backup.c
DarkFlippers_unleashed-firmware/lib/update_util/int_backup.c
#include "int_backup.h" #include <toolbox/tar/tar_archive.h> #include <bt/bt_settings_filename.h> #include <bt/bt_service/bt_keys_filename.h> #include <dolphin/helpers/dolphin_state_filename.h> #include <desktop/helpers/slideshow_filename.h> #include <desktop/desktop_settings_filename.h> #include <notification/notification_settings_filename.h> #define INT_BACKUP_DEFAULT_LOCATION EXT_PATH(INT_BACKUP_DEFAULT_FILENAME) static void backup_name_converter(FuriString* filename) { if(furi_string_empty(filename) || (furi_string_get_char(filename, 0) == '.')) { return; } /* Filenames are already prefixed with '.' */ const char* const names[] = { BT_SETTINGS_FILE_NAME, BT_KEYS_STORAGE_FILE_NAME, DESKTOP_SETTINGS_FILE_NAME, NOTIFICATION_SETTINGS_FILE_NAME, SLIDESHOW_FILE_NAME, DOLPHIN_STATE_FILE_NAME, }; for(size_t i = 0; i < COUNT_OF(names); i++) { if(furi_string_equal(filename, &names[i][1])) { furi_string_set(filename, names[i]); return; } } } bool int_backup_create(Storage* storage, const char* destination) { const char* final_destination = destination && strlen(destination) ? destination : INT_BACKUP_DEFAULT_LOCATION; return storage_int_backup(storage, final_destination) == FSE_OK; } bool int_backup_exists(Storage* storage, const char* source) { const char* final_source = source && strlen(source) ? source : INT_BACKUP_DEFAULT_LOCATION; return storage_common_stat(storage, final_source, NULL) == FSE_OK; } bool int_backup_unpack(Storage* storage, const char* source) { const char* final_source = source && strlen(source) ? source : INT_BACKUP_DEFAULT_LOCATION; return storage_int_restore(storage, final_source, backup_name_converter) == FSE_OK; }
1,826
C
.c
42
38.547619
95
0.699718
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,414
update_operation.c
DarkFlippers_unleashed-firmware/lib/update_util/update_operation.c
#include "update_operation.h" #include "update_manifest.h" #include <furi.h> #include <furi_hal.h> #include <loader/loader.h> #include <lib/toolbox/path.h> #include <lib/toolbox/crc32_calc.h> #define UPDATE_ROOT_DIR EXT_PATH("update") /* Need at least 4 free LFS pages before update */ #define UPDATE_MIN_INT_FREE_SPACE (2 * 4 * 1024) static const char* update_prepare_result_descr[] = { [UpdatePrepareResultOK] = "OK", [UpdatePrepareResultManifestPathInvalid] = "Invalid manifest name or location", [UpdatePrepareResultManifestFolderNotFound] = "Update folder not found", [UpdatePrepareResultManifestInvalid] = "Invalid manifest data", [UpdatePrepareResultStageMissing] = "Missing Stage2 loader", [UpdatePrepareResultStageIntegrityError] = "Corrupted Stage2 loader", [UpdatePrepareResultManifestPointerCreateError] = "Failed to create update pointer file", [UpdatePrepareResultManifestPointerCheckError] = "Update pointer file error (corrupted FS?)", [UpdatePrepareResultTargetMismatch] = "Hardware target mismatch", [UpdatePrepareResultOutdatedManifestVersion] = "Update package is too old", [UpdatePrepareResultIntFull] = "Need more free space in internal storage", [UpdatePrepareResultUnspecifiedError] = "Unknown error", }; const char* update_operation_describe_preparation_result(const UpdatePrepareResult value) { if(value >= COUNT_OF(update_prepare_result_descr)) { return "..."; } else { return update_prepare_result_descr[value]; } } static bool update_operation_get_current_package_path_rtc(Storage* storage, FuriString* out_path) { const uint32_t update_index = furi_hal_rtc_get_register(FuriHalRtcRegisterUpdateFolderFSIndex); furi_string_set(out_path, UPDATE_ROOT_DIR); if(update_index == UPDATE_OPERATION_ROOT_DIR_PACKAGE_MAGIC) { return true; } bool found = false; uint32_t iter_index = 0; File* dir = storage_file_alloc(storage); FileInfo fi = {0}; char* name_buffer = malloc(UPDATE_OPERATION_MAX_MANIFEST_PATH_LEN); do { if(!storage_dir_open(dir, UPDATE_ROOT_DIR)) { break; } while(storage_dir_read(dir, &fi, name_buffer, UPDATE_OPERATION_MAX_MANIFEST_PATH_LEN)) { if(++iter_index == update_index) { found = true; path_append(out_path, name_buffer); break; } } } while(false); free(name_buffer); storage_file_free(dir); if(!found) { furi_string_reset(out_path); } return found; } #define UPDATE_FILE_POINTER_FN EXT_PATH(UPDATE_MANIFEST_POINTER_FILE_NAME) #define UPDATE_MANIFEST_MAX_PATH_LEN 256u bool update_operation_get_current_package_manifest_path(Storage* storage, FuriString* out_path) { furi_string_reset(out_path); if(storage_common_stat(storage, UPDATE_FILE_POINTER_FN, NULL) == FSE_OK) { char* manifest_name_buffer = malloc(UPDATE_MANIFEST_MAX_PATH_LEN); File* upd_file = NULL; do { upd_file = storage_file_alloc(storage); if(!storage_file_open( upd_file, UPDATE_FILE_POINTER_FN, FSAM_READ, FSOM_OPEN_EXISTING)) { break; } size_t bytes_read = storage_file_read(upd_file, manifest_name_buffer, UPDATE_MANIFEST_MAX_PATH_LEN); if((bytes_read == 0) || (bytes_read == UPDATE_MANIFEST_MAX_PATH_LEN)) { break; } if(storage_common_stat(storage, manifest_name_buffer, NULL) != FSE_OK) { break; } furi_string_set(out_path, manifest_name_buffer); } while(0); free(manifest_name_buffer); storage_file_free(upd_file); } else { /* legacy, will be deprecated */ FuriString* rtcpath; rtcpath = furi_string_alloc(); do { if(!update_operation_get_current_package_path_rtc(storage, rtcpath)) { break; } path_concat(furi_string_get_cstr(rtcpath), UPDATE_MANIFEST_DEFAULT_NAME, out_path); } while(0); furi_string_free(rtcpath); } return !furi_string_empty(out_path); } static bool update_operation_persist_manifest_path(Storage* storage, const char* manifest_path) { const size_t manifest_path_len = strlen(manifest_path); furi_check(manifest_path && manifest_path_len); bool success = false; File* file = storage_file_alloc(storage); do { if(manifest_path_len >= UPDATE_OPERATION_MAX_MANIFEST_PATH_LEN) { break; } if(!storage_file_open(file, UPDATE_FILE_POINTER_FN, FSAM_WRITE, FSOM_CREATE_ALWAYS)) { break; } if(storage_file_write(file, manifest_path, manifest_path_len) != manifest_path_len) { break; } success = true; } while(0); storage_file_free(file); return success; } UpdatePrepareResult update_operation_prepare(const char* manifest_file_path) { UpdatePrepareResult result = UpdatePrepareResultIntFull; Storage* storage = furi_record_open(RECORD_STORAGE); UpdateManifest* manifest = update_manifest_alloc(); File* file = storage_file_alloc(storage); uint64_t free_int_space; FuriString* stage_path = furi_string_alloc(); FuriString* manifest_path_check = furi_string_alloc(); do { if((storage_common_fs_info(storage, STORAGE_INT_PATH_PREFIX, NULL, &free_int_space) != FSE_OK) || (free_int_space < UPDATE_MIN_INT_FREE_SPACE)) { break; } if(storage_common_stat(storage, manifest_file_path, NULL) != FSE_OK) { result = UpdatePrepareResultManifestFolderNotFound; break; } if(!update_manifest_init(manifest, manifest_file_path)) { result = UpdatePrepareResultManifestInvalid; break; } if(manifest->manifest_version < UPDATE_OPERATION_MIN_MANIFEST_VERSION) { result = UpdatePrepareResultOutdatedManifestVersion; break; } /* Only compare hardware target if it is set - pre-production devices accept any firmware*/ if(furi_hal_version_get_hw_target() && (furi_hal_version_get_hw_target() != manifest->target)) { result = UpdatePrepareResultTargetMismatch; break; } path_extract_dirname(manifest_file_path, stage_path); path_append(stage_path, furi_string_get_cstr(manifest->staged_loader_file)); if(!storage_file_open( file, furi_string_get_cstr(stage_path), FSAM_READ, FSOM_OPEN_EXISTING)) { result = UpdatePrepareResultStageMissing; break; } uint32_t crc = crc32_calc_file(file, NULL, NULL); if(crc != manifest->staged_loader_crc) { result = UpdatePrepareResultStageIntegrityError; break; } if(!update_operation_persist_manifest_path(storage, manifest_file_path)) { result = UpdatePrepareResultManifestPointerCreateError; break; } if(!update_operation_get_current_package_manifest_path(storage, manifest_path_check) || (furi_string_cmpi_str(manifest_path_check, manifest_file_path) != 0)) { FURI_LOG_E( "update", "Manifest pointer check failed: '%s' != '%s'", furi_string_get_cstr(manifest_path_check), manifest_file_path); result = UpdatePrepareResultManifestPointerCheckError; break; } result = UpdatePrepareResultOK; furi_hal_rtc_set_boot_mode(FuriHalRtcBootModePreUpdate); } while(false); furi_string_free(stage_path); furi_string_free(manifest_path_check); storage_file_free(file); update_manifest_free(manifest); furi_record_close(RECORD_STORAGE); return result; } bool update_operation_is_armed(void) { FuriHalRtcBootMode boot_mode = furi_hal_rtc_get_boot_mode(); const uint32_t rtc_upd_index = furi_hal_rtc_get_register(FuriHalRtcRegisterUpdateFolderFSIndex); Storage* storage = furi_record_open(RECORD_STORAGE); const bool upd_fn_ptr_exists = (storage_common_stat(storage, UPDATE_FILE_POINTER_FN, NULL) == FSE_OK); furi_record_close(RECORD_STORAGE); return (boot_mode >= FuriHalRtcBootModePreUpdate) && (boot_mode <= FuriHalRtcBootModePostUpdate) && ((rtc_upd_index != INT_MAX) || upd_fn_ptr_exists); } void update_operation_disarm(void) { furi_hal_rtc_set_boot_mode(FuriHalRtcBootModeNormal); furi_hal_rtc_set_register(FuriHalRtcRegisterUpdateFolderFSIndex, INT_MAX); Storage* storage = furi_record_open(RECORD_STORAGE); storage_simply_remove(storage, UPDATE_FILE_POINTER_FN); furi_record_close(RECORD_STORAGE); }
8,904
C
.c
207
34.951691
99
0.654201
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,415
dfu_file.c
DarkFlippers_unleashed-firmware/lib/update_util/dfu_file.c
#include "dfu_file.h" #include <furi_hal.h> #include <toolbox/crc32_calc.h> #define VALID_WHOLE_FILE_CRC 0xFFFFFFFF #define DFU_SUFFIX_VERSION 0x011A #define DFU_SIGNATURE "DfuSe" bool dfu_file_validate_crc(File* dfuf, const DfuPageTaskProgressCb progress_cb, void* context) { uint32_t file_crc = crc32_calc_file(dfuf, progress_cb, context); /* Last 4 bytes of DFU file = CRC of previous file contents, inverted * If we calculate whole file CRC32, incl. embedded CRC, * that should give us 0xFFFFFFFF */ return file_crc == VALID_WHOLE_FILE_CRC; } uint8_t dfu_file_validate_headers(File* dfuf, const DfuValidationParams* reference_params) { furi_assert(reference_params); DfuPrefix dfu_prefix = {0}; DfuSuffix dfu_suffix = {0}; size_t bytes_read = 0; if(!storage_file_is_open(dfuf) || !storage_file_seek(dfuf, 0, true)) { return 0; } const uint32_t dfu_suffix_offset = storage_file_size(dfuf) - sizeof(DfuSuffix); bytes_read = storage_file_read(dfuf, &dfu_prefix, sizeof(DfuPrefix)); if(bytes_read != sizeof(DfuPrefix)) { return 0; } if(memcmp(dfu_prefix.szSignature, DFU_SIGNATURE, sizeof(dfu_prefix.szSignature)) != 0) { return 0; } if((dfu_prefix.bVersion != 1) || (dfu_prefix.DFUImageSize != dfu_suffix_offset)) { return 0; } if(!storage_file_seek(dfuf, dfu_suffix_offset, true)) { return 0; } bytes_read = storage_file_read(dfuf, &dfu_suffix, sizeof(DfuSuffix)); if(bytes_read != sizeof(DfuSuffix)) { return 0; } if((dfu_suffix.bLength != sizeof(DfuSuffix)) || (dfu_suffix.bcdDFU != DFU_SUFFIX_VERSION)) { return 0; } /* TODO FL-3561: check DfuSignature?.. */ if((dfu_suffix.idVendor != reference_params->vendor) || (dfu_suffix.idProduct != reference_params->product) || (dfu_suffix.bcdDevice != reference_params->device)) { return 0; } return dfu_prefix.bTargets; } /* Assumes file is open, valid and read pointer is set at the start of image data */ static DfuUpdateBlockResult dfu_file_perform_task_for_update_pages( const DfuUpdateTask* task, File* dfuf, const ImageElementHeader* header) { furi_assert(task); furi_assert(header); task->progress_cb(0, task->context); const size_t FLASH_PAGE_SIZE = furi_hal_flash_get_page_size(); const size_t FLASH_PAGE_ALIGNMENT_MASK = FLASH_PAGE_SIZE - 1; if((header->dwElementAddress & FLASH_PAGE_ALIGNMENT_MASK) != 0) { /* start address is not aligned by page boundary -- we don't support that. Yet. */ return UpdateBlockResult_Failed; } if(task->address_cb && (!task->address_cb(header->dwElementAddress) || !task->address_cb(header->dwElementAddress + header->dwElementSize))) { storage_file_seek(dfuf, header->dwElementSize, false); task->progress_cb(100, task->context); return UpdateBlockResult_Skipped; } uint8_t* fw_block = malloc(FLASH_PAGE_SIZE); size_t bytes_read = 0; uint32_t element_offs = 0; while(element_offs < header->dwElementSize) { uint32_t n_bytes_to_read = FLASH_PAGE_SIZE; if((element_offs + n_bytes_to_read) > header->dwElementSize) { n_bytes_to_read = header->dwElementSize - element_offs; } bytes_read = storage_file_read(dfuf, fw_block, n_bytes_to_read); if(bytes_read == 0) { break; } int16_t i_page = furi_hal_flash_get_page_number(header->dwElementAddress + element_offs); if(i_page < 0) { break; } if(!task->task_cb(i_page, fw_block, bytes_read)) { break; } element_offs += bytes_read; task->progress_cb(element_offs * 100 / header->dwElementSize, task->context); } free(fw_block); return (element_offs == header->dwElementSize) ? UpdateBlockResult_OK : UpdateBlockResult_Failed; } bool dfu_file_process_targets(const DfuUpdateTask* task, File* dfuf, const uint8_t n_targets) { TargetPrefix target_prefix = {0}; ImageElementHeader image_element = {0}; size_t bytes_read = 0; if(!storage_file_seek(dfuf, sizeof(DfuPrefix), true)) { return UpdateBlockResult_Failed; }; for(uint8_t i_target = 0; i_target < n_targets; ++i_target) { bytes_read = storage_file_read(dfuf, &target_prefix, sizeof(TargetPrefix)); if(bytes_read != sizeof(TargetPrefix)) { return UpdateBlockResult_Failed; } /* TODO FL-3562: look into TargetPrefix and validate/filter?.. */ for(uint32_t i_element = 0; i_element < target_prefix.dwNbElements; ++i_element) { bytes_read = storage_file_read(dfuf, &image_element, sizeof(ImageElementHeader)); if(bytes_read != sizeof(ImageElementHeader)) { return UpdateBlockResult_Failed; } if(dfu_file_perform_task_for_update_pages(task, dfuf, &image_element) == UpdateBlockResult_Failed) { return false; } } } return true; }
5,211
C
.c
124
34.620968
99
0.636669
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,417
update_manifest.c
DarkFlippers_unleashed-firmware/lib/update_util/update_manifest.c
#include "update_manifest.h" #include <storage/storage.h> #include <flipper_format/flipper_format.h> #include <flipper_format/flipper_format_i.h> #define MANIFEST_KEY_INFO "Info" #define MANIFEST_KEY_TARGET "Target" #define MANIFEST_KEY_LOADER_FILE "Loader" #define MANIFEST_KEY_LOADER_CRC "Loader CRC" #define MANIFEST_KEY_DFU_FILE "Firmware" #define MANIFEST_KEY_RADIO_FILE "Radio" #define MANIFEST_KEY_RADIO_ADDRESS "Radio address" #define MANIFEST_KEY_RADIO_VERSION "Radio version" #define MANIFEST_KEY_RADIO_CRC "Radio CRC" #define MANIFEST_KEY_ASSETS_FILE "Resources" #define MANIFEST_KEY_OB_REFERENCE "OB reference" #define MANIFEST_KEY_OB_MASK "OB mask" #define MANIFEST_KEY_OB_WRITE_MASK "OB write mask" #define MANIFEST_KEY_SPLASH_FILE "Splashscreen" UpdateManifest* update_manifest_alloc(void) { UpdateManifest* update_manifest = malloc(sizeof(UpdateManifest)); update_manifest->version = furi_string_alloc(); update_manifest->firmware_dfu_image = furi_string_alloc(); update_manifest->radio_image = furi_string_alloc(); update_manifest->staged_loader_file = furi_string_alloc(); update_manifest->resource_bundle = furi_string_alloc(); update_manifest->splash_file = furi_string_alloc(); update_manifest->target = 0; update_manifest->manifest_version = 0; memset(update_manifest->ob_reference.bytes, 0, FURI_HAL_FLASH_OB_RAW_SIZE_BYTES); memset(update_manifest->ob_compare_mask.bytes, 0, FURI_HAL_FLASH_OB_RAW_SIZE_BYTES); memset(update_manifest->ob_write_mask.bytes, 0, FURI_HAL_FLASH_OB_RAW_SIZE_BYTES); update_manifest->valid = false; return update_manifest; } void update_manifest_free(UpdateManifest* update_manifest) { furi_assert(update_manifest); furi_string_free(update_manifest->version); furi_string_free(update_manifest->firmware_dfu_image); furi_string_free(update_manifest->radio_image); furi_string_free(update_manifest->staged_loader_file); furi_string_free(update_manifest->resource_bundle); furi_string_free(update_manifest->splash_file); free(update_manifest); } static bool update_manifest_init_from_ff(UpdateManifest* update_manifest, FlipperFormat* flipper_file) { furi_assert(update_manifest); furi_assert(flipper_file); FuriString* filetype; filetype = furi_string_alloc(); update_manifest->valid = flipper_format_read_header(flipper_file, filetype, &update_manifest->manifest_version) && furi_string_cmp_str(filetype, "Flipper firmware upgrade configuration") == 0 && flipper_format_read_string(flipper_file, MANIFEST_KEY_INFO, update_manifest->version) && flipper_format_read_uint32( flipper_file, MANIFEST_KEY_TARGET, &update_manifest->target, 1) && flipper_format_read_string( flipper_file, MANIFEST_KEY_LOADER_FILE, update_manifest->staged_loader_file) && flipper_format_read_hex( flipper_file, MANIFEST_KEY_LOADER_CRC, (uint8_t*)&update_manifest->staged_loader_crc, sizeof(uint32_t)); furi_string_free(filetype); if(update_manifest->valid) { /* Optional fields - we can have dfu, radio, resources, or any combination */ flipper_format_read_string( flipper_file, MANIFEST_KEY_DFU_FILE, update_manifest->firmware_dfu_image); flipper_format_read_string( flipper_file, MANIFEST_KEY_RADIO_FILE, update_manifest->radio_image); flipper_format_read_hex( flipper_file, MANIFEST_KEY_RADIO_ADDRESS, (uint8_t*)&update_manifest->radio_address, sizeof(uint32_t)); flipper_format_read_hex( flipper_file, MANIFEST_KEY_RADIO_VERSION, update_manifest->radio_version.raw, sizeof(UpdateManifestRadioVersion)); flipper_format_read_hex( flipper_file, MANIFEST_KEY_RADIO_CRC, (uint8_t*)&update_manifest->radio_crc, sizeof(uint32_t)); flipper_format_read_string( flipper_file, MANIFEST_KEY_ASSETS_FILE, update_manifest->resource_bundle); flipper_format_read_hex( flipper_file, MANIFEST_KEY_OB_REFERENCE, update_manifest->ob_reference.bytes, FURI_HAL_FLASH_OB_RAW_SIZE_BYTES); flipper_format_read_hex( flipper_file, MANIFEST_KEY_OB_MASK, update_manifest->ob_compare_mask.bytes, FURI_HAL_FLASH_OB_RAW_SIZE_BYTES); flipper_format_read_hex( flipper_file, MANIFEST_KEY_OB_WRITE_MASK, update_manifest->ob_write_mask.bytes, FURI_HAL_FLASH_OB_RAW_SIZE_BYTES); flipper_format_read_string( flipper_file, MANIFEST_KEY_SPLASH_FILE, update_manifest->splash_file); update_manifest->valid = (!furi_string_empty(update_manifest->firmware_dfu_image) || !furi_string_empty(update_manifest->radio_image) || !furi_string_empty(update_manifest->resource_bundle)); } return update_manifest->valid; } // Verifies that mask values are same for adjacent words (value & inverted) static bool ob_data_check_mask_valid(const FuriHalFlashRawOptionByteData* mask) { bool mask_valid = true; for(size_t idx = 0; mask_valid && (idx < FURI_HAL_FLASH_OB_TOTAL_VALUES); ++idx) { mask_valid &= mask->obs[idx].values.base == mask->obs[idx].values.complementary_value; } return mask_valid; } // Verifies that all reference values have no unmasked bits static bool ob_data_check_masked_values_valid( const FuriHalFlashRawOptionByteData* data, const FuriHalFlashRawOptionByteData* mask) { bool valid = true; for(size_t idx = 0; valid && (idx < FURI_HAL_FLASH_OB_TOTAL_VALUES); ++idx) { valid &= (data->obs[idx].dword & mask->obs[idx].dword) == data->obs[idx].dword; } return valid; } bool update_manifest_has_obdata(UpdateManifest* update_manifest) { bool ob_data_valid = false; // do we have at least 1 value? for(size_t idx = 0; !ob_data_valid && (idx < FURI_HAL_FLASH_OB_RAW_SIZE_BYTES); ++idx) { ob_data_valid |= update_manifest->ob_reference.bytes[idx] != 0; } // sanity checks ob_data_valid &= ob_data_check_mask_valid(&update_manifest->ob_write_mask); ob_data_valid &= ob_data_check_mask_valid(&update_manifest->ob_compare_mask); ob_data_valid &= ob_data_check_masked_values_valid( &update_manifest->ob_reference, &update_manifest->ob_compare_mask); return ob_data_valid; } bool update_manifest_init(UpdateManifest* update_manifest, const char* manifest_filename) { Storage* storage = furi_record_open(RECORD_STORAGE); FlipperFormat* flipper_file = flipper_format_file_alloc(storage); if(flipper_format_file_open_existing(flipper_file, manifest_filename)) { update_manifest_init_from_ff(update_manifest, flipper_file); } flipper_format_free(flipper_file); furi_record_close(RECORD_STORAGE); return update_manifest->valid; } bool update_manifest_init_mem( UpdateManifest* update_manifest, const uint8_t* manifest_data, const uint16_t length) { FlipperFormat* flipper_file = flipper_format_string_alloc(); Stream* sstream = flipper_format_get_raw_stream(flipper_file); stream_write(sstream, manifest_data, length); stream_seek(sstream, 0, StreamOffsetFromStart); update_manifest_init_from_ff(update_manifest, flipper_file); flipper_format_free(flipper_file); return update_manifest->valid; }
7,642
C
.c
164
39.957317
97
0.688531
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,418
manifest.c
DarkFlippers_unleashed-firmware/lib/update_util/resources/manifest.c
#include "manifest.h" #include <toolbox/stream/buffered_file_stream.h> #include <toolbox/strint.h> #include <toolbox/hex.h> struct ResourceManifestReader { Storage* storage; Stream* stream; FuriString* linebuf; ResourceManifestEntry entry; }; ResourceManifestReader* resource_manifest_reader_alloc(Storage* storage) { ResourceManifestReader* resource_manifest = (ResourceManifestReader*)malloc(sizeof(ResourceManifestReader)); resource_manifest->storage = storage; resource_manifest->stream = buffered_file_stream_alloc(resource_manifest->storage); memset(&resource_manifest->entry, 0, sizeof(ResourceManifestEntry)); resource_manifest->entry.name = furi_string_alloc(); resource_manifest->linebuf = furi_string_alloc(); return resource_manifest; } void resource_manifest_reader_free(ResourceManifestReader* resource_manifest) { furi_assert(resource_manifest); furi_string_free(resource_manifest->linebuf); furi_string_free(resource_manifest->entry.name); buffered_file_stream_close(resource_manifest->stream); stream_free(resource_manifest->stream); free(resource_manifest); } bool resource_manifest_reader_open(ResourceManifestReader* resource_manifest, const char* filename) { furi_assert(resource_manifest); return buffered_file_stream_open( resource_manifest->stream, filename, FSAM_READ, FSOM_OPEN_EXISTING); } /* Read entries in format of * F:<hash>:<size>:<name> * D:<name> */ ResourceManifestEntry* resource_manifest_reader_next(ResourceManifestReader* resource_manifest) { furi_assert(resource_manifest); furi_string_reset(resource_manifest->entry.name); resource_manifest->entry.type = ResourceManifestEntryTypeUnknown; resource_manifest->entry.size = 0; memset(resource_manifest->entry.hash, 0, sizeof(resource_manifest->entry.hash)); do { if(!stream_read_line(resource_manifest->stream, resource_manifest->linebuf)) { return NULL; } /* Trim end of line */ furi_string_trim(resource_manifest->linebuf); char type_code = furi_string_get_char(resource_manifest->linebuf, 0); switch(type_code) { case 'V': resource_manifest->entry.type = ResourceManifestEntryTypeVersion; break; case 'T': resource_manifest->entry.type = ResourceManifestEntryTypeTimestamp; break; case 'F': resource_manifest->entry.type = ResourceManifestEntryTypeFile; break; case 'D': resource_manifest->entry.type = ResourceManifestEntryTypeDirectory; break; default: /* Skip other entries - version, timestamp, etc */ continue; }; if(resource_manifest->entry.type == ResourceManifestEntryTypeFile) { /* Parse file entry F:<hash>:<size>:<name> */ /* Remove entry type code */ furi_string_right(resource_manifest->linebuf, 2); if(furi_string_search_char(resource_manifest->linebuf, ':') != sizeof(resource_manifest->entry.hash) * 2) { /* Invalid hash */ continue; } /* Read hash */ hex_chars_to_uint8( furi_string_get_cstr(resource_manifest->linebuf), resource_manifest->entry.hash); /* Remove hash */ furi_string_right( resource_manifest->linebuf, sizeof(resource_manifest->entry.hash) * 2 + 1); if(strint_to_uint32( furi_string_get_cstr(resource_manifest->linebuf), NULL, &resource_manifest->entry.size, 10) != StrintParseNoError) break; /* Remove size */ size_t offs = furi_string_search_char(resource_manifest->linebuf, ':'); furi_string_right(resource_manifest->linebuf, offs + 1); furi_string_set(resource_manifest->entry.name, resource_manifest->linebuf); } else { //-V547 /* Everything else is plain key value. Parse version, timestamp or directory entry <Type>:<Value> */ /* Remove entry type code */ furi_string_right(resource_manifest->linebuf, 2); furi_string_set(resource_manifest->entry.name, resource_manifest->linebuf); } return &resource_manifest->entry; } while(true); return NULL; } ResourceManifestEntry* resource_manifest_reader_previous(ResourceManifestReader* resource_manifest) { furi_assert(resource_manifest); // Snapshot position for rollback const size_t previous_position = stream_tell(resource_manifest->stream); // We need to jump 2 lines back size_t jumps = 2; // Special case: end of the file. const bool was_eof = stream_eof(resource_manifest->stream); if(was_eof) { jumps = 1; } while(jumps) { if(!stream_seek_to_char(resource_manifest->stream, '\n', StreamDirectionBackward)) { break; } if(stream_tell(resource_manifest->stream) < (previous_position - 1)) { jumps--; } } // Special case: first line. Force seek to zero if(jumps == 1) { jumps = 0; stream_seek(resource_manifest->stream, 0, StreamOffsetFromStart); } if(jumps == 0) { ResourceManifestEntry* entry = resource_manifest_reader_next(resource_manifest); // Special case: was end of the file, prevent loop if(was_eof) { stream_seek(resource_manifest->stream, -1, StreamOffsetFromCurrent); } return entry; } else { stream_seek(resource_manifest->stream, previous_position, StreamOffsetFromStart); return NULL; } } bool resource_manifest_rewind(ResourceManifestReader* resource_manifest) { furi_assert(resource_manifest); return stream_seek(resource_manifest->stream, 0, StreamOffsetFromStart); }
6,018
C
.c
144
33.493056
101
0.652233
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,419
pulse_reader.c
DarkFlippers_unleashed-firmware/lib/pulse_reader/pulse_reader.c
#include "pulse_reader.h" #include <furi.h> #include <furi_hal.h> #include <furi_hal_gpio.h> #include <stm32wbxx_ll_dma.h> #include <stm32wbxx_ll_dmamux.h> #include <stm32wbxx_ll_tim.h> #include <stm32wbxx_ll_exti.h> struct PulseReader { uint32_t* timer_buffer; uint32_t* gpio_buffer; uint32_t size; uint32_t pos; uint32_t timer_value; uint32_t gpio_value; uint32_t gpio_mask; uint32_t unit_multiplier; uint32_t unit_divider; uint32_t bit_time; uint32_t dma_channel; const GpioPin* gpio; GpioPull pull; LL_DMA_InitTypeDef dma_config_timer; LL_DMA_InitTypeDef dma_config_gpio; }; #define GPIO_PIN_MAP(pin, prefix) \ (((pin) == (LL_GPIO_PIN_0)) ? prefix##0 : \ ((pin) == (LL_GPIO_PIN_1)) ? prefix##1 : \ ((pin) == (LL_GPIO_PIN_2)) ? prefix##2 : \ ((pin) == (LL_GPIO_PIN_3)) ? prefix##3 : \ ((pin) == (LL_GPIO_PIN_4)) ? prefix##4 : \ ((pin) == (LL_GPIO_PIN_5)) ? prefix##5 : \ ((pin) == (LL_GPIO_PIN_6)) ? prefix##6 : \ ((pin) == (LL_GPIO_PIN_7)) ? prefix##7 : \ ((pin) == (LL_GPIO_PIN_8)) ? prefix##8 : \ ((pin) == (LL_GPIO_PIN_9)) ? prefix##9 : \ ((pin) == (LL_GPIO_PIN_10)) ? prefix##10 : \ ((pin) == (LL_GPIO_PIN_11)) ? prefix##11 : \ ((pin) == (LL_GPIO_PIN_12)) ? prefix##12 : \ ((pin) == (LL_GPIO_PIN_13)) ? prefix##13 : \ ((pin) == (LL_GPIO_PIN_14)) ? prefix##14 : \ prefix##15) #define GET_DMAMUX_EXTI_LINE(pin) GPIO_PIN_MAP(pin, LL_DMAMUX_REQ_GEN_EXTI_LINE) PulseReader* pulse_reader_alloc(const GpioPin* gpio, uint32_t size) { PulseReader* signal = malloc(sizeof(PulseReader)); signal->timer_buffer = malloc(size * sizeof(uint32_t)); signal->gpio_buffer = malloc(size * sizeof(uint32_t)); signal->dma_channel = LL_DMA_CHANNEL_4; signal->gpio = gpio; signal->pull = GpioPullNo; signal->size = size; signal->timer_value = 0; signal->pos = 0; pulse_reader_set_timebase(signal, PulseReaderUnit64MHz); pulse_reader_set_bittime(signal, 1); signal->dma_config_timer.Direction = LL_DMA_DIRECTION_PERIPH_TO_MEMORY; signal->dma_config_timer.PeriphOrM2MSrcAddress = (uint32_t) & (TIM2->CNT); signal->dma_config_timer.PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT; signal->dma_config_timer.PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_WORD; signal->dma_config_timer.MemoryOrM2MDstAddress = (uint32_t)signal->timer_buffer; signal->dma_config_timer.MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT; signal->dma_config_timer.MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_WORD; signal->dma_config_timer.Mode = LL_DMA_MODE_CIRCULAR; signal->dma_config_timer.PeriphRequest = LL_DMAMUX_REQ_GENERATOR0; /* executes LL_DMA_SetPeriphRequest */ signal->dma_config_timer.Priority = LL_DMA_PRIORITY_VERYHIGH; signal->dma_config_gpio.Direction = LL_DMA_DIRECTION_PERIPH_TO_MEMORY; signal->dma_config_gpio.PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT; signal->dma_config_gpio.PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_WORD; signal->dma_config_gpio.MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT; signal->dma_config_gpio.MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_WORD; signal->dma_config_gpio.Mode = LL_DMA_MODE_CIRCULAR; signal->dma_config_gpio.PeriphRequest = LL_DMAMUX_REQ_GENERATOR0; /* executes LL_DMA_SetPeriphRequest */ signal->dma_config_gpio.Priority = LL_DMA_PRIORITY_VERYHIGH; return signal; } void pulse_reader_set_timebase(PulseReader* signal, PulseReaderUnit unit) { switch(unit) { case PulseReaderUnit64MHz: signal->unit_multiplier = 1; signal->unit_divider = 1; break; case PulseReaderUnitPicosecond: signal->unit_multiplier = 15625; signal->unit_divider = 1; break; case PulseReaderUnitNanosecond: signal->unit_multiplier = 15625; signal->unit_divider = 1000; break; case PulseReaderUnitMicrosecond: signal->unit_multiplier = 15625; signal->unit_divider = 1000000; break; } } void pulse_reader_set_bittime(PulseReader* signal, uint32_t bit_time) { signal->bit_time = bit_time; } void pulse_reader_set_pull(PulseReader* signal, GpioPull pull) { signal->pull = pull; } void pulse_reader_free(PulseReader* signal) { furi_assert(signal); free(signal->timer_buffer); free(signal->gpio_buffer); free(signal); } uint32_t pulse_reader_samples(PulseReader* signal) { uint32_t dma_pos = signal->size - (uint32_t)LL_DMA_GetDataLength(DMA1, signal->dma_channel); return ((signal->pos + signal->size) - dma_pos) % signal->size; } void pulse_reader_stop(PulseReader* signal) { LL_DMA_DisableChannel(DMA1, signal->dma_channel); LL_DMA_DisableChannel(DMA1, signal->dma_channel + 1); LL_DMAMUX_DisableRequestGen(NULL, LL_DMAMUX_REQ_GEN_0); LL_TIM_DisableCounter(TIM2); furi_hal_bus_disable(FuriHalBusTIM2); furi_hal_gpio_init_simple(signal->gpio, GpioModeAnalog); } void pulse_reader_start(PulseReader* signal) { /* configure DMA to read from a timer peripheral */ signal->dma_config_timer.NbData = signal->size; signal->dma_config_gpio.PeriphOrM2MSrcAddress = (uint32_t) & (signal->gpio->port->IDR); signal->dma_config_gpio.MemoryOrM2MDstAddress = (uint32_t)signal->gpio_buffer; signal->dma_config_gpio.NbData = signal->size; furi_hal_bus_enable(FuriHalBusTIM2); /* start counter */ LL_TIM_SetCounterMode(TIM2, LL_TIM_COUNTERMODE_UP); LL_TIM_SetClockDivision(TIM2, LL_TIM_CLOCKDIVISION_DIV1); LL_TIM_SetPrescaler(TIM2, 0); LL_TIM_SetAutoReload(TIM2, 0xFFFFFFFF); LL_TIM_SetCounter(TIM2, 0); LL_TIM_EnableCounter(TIM2); /* generator 0 gets fed by EXTI_LINEn */ LL_DMAMUX_SetRequestSignalID( NULL, LL_DMAMUX_REQ_GEN_0, GET_DMAMUX_EXTI_LINE(signal->gpio->pin)); /* trigger on rising edge of the interrupt */ LL_DMAMUX_SetRequestGenPolarity(NULL, LL_DMAMUX_REQ_GEN_0, LL_DMAMUX_REQ_GEN_POL_RISING); /* now enable request generation again */ LL_DMAMUX_EnableRequestGen(NULL, LL_DMAMUX_REQ_GEN_0); /* we need the EXTI to be configured as interrupt generating line, but no ISR registered */ furi_hal_gpio_init_ex( signal->gpio, GpioModeInterruptRiseFall, signal->pull, GpioSpeedVeryHigh, GpioAltFnUnused); /* capture current timer */ signal->pos = 0; signal->timer_value = TIM2->CNT; signal->gpio_mask = signal->gpio->pin; signal->gpio_value = signal->gpio->port->IDR & signal->gpio_mask; /* now set up DMA with these settings */ LL_DMA_Init(DMA1, signal->dma_channel, &signal->dma_config_timer); LL_DMA_Init(DMA1, signal->dma_channel + 1, &signal->dma_config_gpio); LL_DMA_EnableChannel(DMA1, signal->dma_channel); LL_DMA_EnableChannel(DMA1, signal->dma_channel + 1); } uint32_t pulse_reader_receive(PulseReader* signal, int timeout_us) { uint32_t start_time = DWT->CYCCNT; uint32_t timeout_ticks = timeout_us * (F_TIM2 / 1000000); do { /* get the DMA's next write position by reading "remaining length" register */ uint32_t dma_pos = signal->size - (uint32_t)LL_DMA_GetDataLength(DMA1, signal->dma_channel); /* the DMA has advanced in the ringbuffer */ if(dma_pos != signal->pos) { uint32_t delta = signal->timer_buffer[signal->pos] - signal->timer_value; uint32_t last_gpio_value = signal->gpio_value; signal->gpio_value = signal->gpio_buffer[signal->pos]; /* check if the GPIO really toggled. if not, we lost an edge :( */ if(((last_gpio_value ^ signal->gpio_value) & signal->gpio_mask) != signal->gpio_mask) { signal->gpio_value ^= signal->gpio_mask; return PULSE_READER_LOST_EDGE; } signal->timer_value = signal->timer_buffer[signal->pos]; signal->pos++; signal->pos %= signal->size; uint32_t delta_unit = 0; /* probably larger values, so choose a wider data type */ if(signal->unit_divider > 1) { delta_unit = (uint32_t)((uint64_t)delta * (uint64_t)signal->unit_multiplier / signal->unit_divider); } else { delta_unit = delta * signal->unit_multiplier; } /* if to be scaled to bit times, save a few instructions. should be faster */ if(signal->bit_time > 1) { return (delta_unit + signal->bit_time / 2) / signal->bit_time; } return delta_unit; } /* check for timeout */ uint32_t elapsed = DWT->CYCCNT - start_time; if(elapsed > timeout_ticks) { return PULSE_READER_NO_EDGE; } } while(true); }
8,920
C
.c
197
38.659898
99
0.649856
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,422
datetime.c
DarkFlippers_unleashed-firmware/lib/datetime/datetime.c
#include "datetime.h" #include <furi.h> #define TAG "DateTime" #define SECONDS_PER_MINUTE 60 #define SECONDS_PER_HOUR (SECONDS_PER_MINUTE * 60) #define SECONDS_PER_DAY (SECONDS_PER_HOUR * 24) #define MONTHS_COUNT 12 #define EPOCH_START_YEAR 1970 static const uint8_t datetime_days_per_month[2][MONTHS_COUNT] = { {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}}; static const uint16_t datetime_days_per_year[] = {365, 366}; bool datetime_validate_datetime(DateTime* datetime) { bool invalid = false; invalid |= (datetime->second > 59); invalid |= (datetime->minute > 59); invalid |= (datetime->hour > 23); invalid |= (datetime->year < 2000); invalid |= (datetime->year > 2099); invalid |= (datetime->month == 0); invalid |= (datetime->month > 12); invalid |= (datetime->day == 0); invalid |= (datetime->day > 31); invalid |= (datetime->weekday == 0); invalid |= (datetime->weekday > 7); return !invalid; } uint32_t datetime_datetime_to_timestamp(DateTime* datetime) { furi_check(datetime); uint32_t timestamp = 0; uint8_t years = 0; uint8_t leap_years = 0; for(uint16_t y = EPOCH_START_YEAR; y < datetime->year; y++) { if(datetime_is_leap_year(y)) { leap_years++; } else { years++; } } timestamp += ((years * datetime_days_per_year[0]) + (leap_years * datetime_days_per_year[1])) * SECONDS_PER_DAY; bool leap_year = datetime_is_leap_year(datetime->year); for(uint8_t m = 1; m < datetime->month; m++) { timestamp += datetime_get_days_per_month(leap_year, m) * SECONDS_PER_DAY; } timestamp += (datetime->day - 1) * SECONDS_PER_DAY; timestamp += datetime->hour * SECONDS_PER_HOUR; timestamp += datetime->minute * SECONDS_PER_MINUTE; timestamp += datetime->second; return timestamp; } void datetime_timestamp_to_datetime(uint32_t timestamp, DateTime* datetime) { furi_check(datetime); uint32_t days = timestamp / SECONDS_PER_DAY; uint32_t seconds_in_day = timestamp % SECONDS_PER_DAY; datetime->year = EPOCH_START_YEAR; datetime->weekday = ((days + 3) % 7) + 1; while(days >= datetime_get_days_per_year(datetime->year)) { days -= datetime_get_days_per_year(datetime->year); (datetime->year)++; } datetime->month = 1; while(days >= datetime_get_days_per_month(datetime_is_leap_year(datetime->year), datetime->month)) { days -= datetime_get_days_per_month(datetime_is_leap_year(datetime->year), datetime->month); (datetime->month)++; } datetime->day = days + 1; datetime->hour = seconds_in_day / SECONDS_PER_HOUR; datetime->minute = (seconds_in_day % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE; datetime->second = seconds_in_day % SECONDS_PER_MINUTE; } uint16_t datetime_get_days_per_year(uint16_t year) { return datetime_days_per_year[datetime_is_leap_year(year) ? 1 : 0]; } bool datetime_is_leap_year(uint16_t year) { return (((year) % 4 == 0) && ((year) % 100 != 0)) || ((year) % 400 == 0); } uint8_t datetime_get_days_per_month(bool leap_year, uint8_t month) { return datetime_days_per_month[leap_year ? 1 : 0][month - 1]; }
3,324
C
.c
82
35.365854
99
0.633281
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,423
mjs_array_buf.c
DarkFlippers_unleashed-firmware/lib/mjs/mjs_array_buf.c
#include "mjs_array_buf.h" #include "common/cs_varint.h" #include "common/mg_str.h" #include "mjs_core.h" #include "mjs_internal.h" #include "mjs_primitive.h" #include "mjs_object.h" #include "mjs_array.h" #include "mjs_util.h" #include "mjs_exec_public.h" #ifndef MJS_ARRAY_BUF_RESERVE #define MJS_ARRAY_BUF_RESERVE 100 #endif #define IS_SIGNED(type) \ (type == MJS_DATAVIEW_I8 || type == MJS_DATAVIEW_I16 || type == MJS_DATAVIEW_I32) int mjs_is_array_buf(mjs_val_t v) { return (v & MJS_TAG_MASK) == MJS_TAG_ARRAY_BUF; } int mjs_is_data_view(mjs_val_t v) { return (v & MJS_TAG_MASK) == MJS_TAG_ARRAY_BUF_VIEW; } int mjs_is_typed_array(mjs_val_t v) { return ((v & MJS_TAG_MASK) == MJS_TAG_ARRAY_BUF) || ((v & MJS_TAG_MASK) == MJS_TAG_ARRAY_BUF_VIEW); } char* mjs_array_buf_get_ptr(struct mjs* mjs, mjs_val_t buf, size_t* bytelen) { struct mbuf* m = &mjs->array_buffers; size_t offset = buf & ~MJS_TAG_MASK; char* ptr = m->buf + offset; uint64_t len = 0; size_t header_len = 0; if(offset < m->len && cs_varint_decode((uint8_t*)ptr, m->len - offset, &len, &header_len)) { if(bytelen) { *bytelen = len; } return ptr + header_len; } return NULL; } static size_t mjs_dataview_get_element_len(mjs_dataview_type_t type) { size_t len = 1; switch(type) { case MJS_DATAVIEW_U8: case MJS_DATAVIEW_I8: len = 1; break; case MJS_DATAVIEW_U16: case MJS_DATAVIEW_I16: len = 2; break; case MJS_DATAVIEW_U32: case MJS_DATAVIEW_I32: len = 4; break; default: break; } return len; } static int64_t get_value(char* buf, mjs_dataview_type_t type) { int64_t value = 0; switch(type) { case MJS_DATAVIEW_U8: value = *(uint8_t*)buf; break; case MJS_DATAVIEW_I8: value = *(int8_t*)buf; break; case MJS_DATAVIEW_U16: value = *(uint16_t*)buf; break; case MJS_DATAVIEW_I16: value = *(int16_t*)buf; break; case MJS_DATAVIEW_U32: value = *(uint32_t*)buf; break; case MJS_DATAVIEW_I32: value = *(int32_t*)buf; break; default: break; } return value; } static void set_value(char* buf, int64_t value, mjs_dataview_type_t type) { switch(type) { case MJS_DATAVIEW_U8: *(uint8_t*)buf = (uint8_t)value; break; case MJS_DATAVIEW_I8: *(int8_t*)buf = (int8_t)value; break; case MJS_DATAVIEW_U16: *(uint16_t*)buf = (uint16_t)value; break; case MJS_DATAVIEW_I16: *(int16_t*)buf = (int16_t)value; break; case MJS_DATAVIEW_U32: *(uint32_t*)buf = (uint32_t)value; break; case MJS_DATAVIEW_I32: *(int32_t*)buf = (int32_t)value; break; default: break; } } static mjs_val_t mjs_dataview_get(struct mjs* mjs, mjs_val_t obj, size_t index) { mjs_val_t buf_obj = mjs_get(mjs, obj, "buffer", -1); size_t byte_len = 0; char* buf = mjs_array_buf_get_ptr(mjs, buf_obj, &byte_len); mjs_dataview_type_t type = mjs_get_int(mjs, mjs_get(mjs, obj, "_t", -1)); if((mjs_dataview_get_element_len(type) * (index + 1)) > byte_len) { return MJS_UNDEFINED; } buf += mjs_dataview_get_element_len(type) * index; int64_t value = get_value(buf, type); return mjs_mk_number(mjs, value); } static mjs_err_t mjs_dataview_set(struct mjs* mjs, mjs_val_t obj, size_t index, int64_t value) { mjs_val_t buf_obj = mjs_get(mjs, obj, "buffer", -1); size_t byte_len = 0; char* buf = mjs_array_buf_get_ptr(mjs, buf_obj, &byte_len); mjs_dataview_type_t type = mjs_get_int(mjs, mjs_get(mjs, obj, "_t", -1)); if((mjs_dataview_get_element_len(type) * (index + 1)) > byte_len) { return MJS_TYPE_ERROR; } buf += mjs_dataview_get_element_len(type) * index; set_value(buf, value, type); return MJS_OK; } mjs_val_t mjs_dataview_get_prop(struct mjs* mjs, mjs_val_t obj, mjs_val_t key) { if(!mjs_is_number(key)) { return MJS_UNDEFINED; } int index = mjs_get_int(mjs, key); return mjs_dataview_get(mjs, obj, index); } mjs_err_t mjs_dataview_set_prop(struct mjs* mjs, mjs_val_t obj, mjs_val_t key, mjs_val_t val) { if(!mjs_is_number(key)) { return MJS_TYPE_ERROR; } int index = mjs_get_int(mjs, key); int64_t value = 0; if(mjs_is_number(val)) { value = mjs_get_double(mjs, val); } else if(mjs_is_boolean(val)) { value = mjs_get_bool(mjs, val) ? (1) : (0); } return mjs_dataview_set(mjs, obj, index, value); } mjs_val_t mjs_dataview_get_buf(struct mjs* mjs, mjs_val_t obj) { return mjs_get(mjs, obj, "buffer", -1); } mjs_val_t mjs_dataview_get_len(struct mjs* mjs, mjs_val_t obj) { size_t bytelen = 0; mjs_array_buf_get_ptr(mjs, mjs_dataview_get_buf(mjs, obj), &bytelen); mjs_dataview_type_t type = mjs_get_int(mjs, mjs_get(mjs, obj, "_t", -1)); size_t element_len = mjs_dataview_get_element_len(type); return mjs_mk_number(mjs, bytelen / element_len); } mjs_val_t mjs_mk_array_buf(struct mjs* mjs, char* data, size_t buf_len) { struct mbuf* m = &mjs->array_buffers; if((m->len + buf_len) > m->size) { char* prev_buf = m->buf; mbuf_resize(m, m->len + buf_len + MJS_ARRAY_BUF_RESERVE); if(data >= prev_buf && data < (prev_buf + m->len)) { data += m->buf - prev_buf; } } size_t offset = m->len; char* prev_buf = m->buf; size_t header_len = cs_varint_llen(buf_len); mbuf_insert(m, offset, NULL, header_len + buf_len); if(data >= prev_buf && data < (prev_buf + m->len)) { data += m->buf - prev_buf; } cs_varint_encode(buf_len, (unsigned char*)m->buf + offset, header_len); if(data != NULL) { memcpy(m->buf + offset + header_len, data, buf_len); } else { memset(m->buf + offset + header_len, 0, buf_len); } return (offset & ~MJS_TAG_MASK) | MJS_TAG_ARRAY_BUF; } void mjs_array_buf_slice(struct mjs* mjs) { size_t nargs = mjs_nargs(mjs); mjs_val_t src = mjs_get_this(mjs); size_t start = 0; size_t end = 0; char* src_buf = NULL; size_t src_len = 0; bool args_correct = false; do { if(!mjs_is_array_buf(src)) { break; } src_buf = mjs_array_buf_get_ptr(mjs, src, &src_len); if((nargs == 0) || (nargs > 2)) { break; } mjs_val_t start_obj = mjs_arg(mjs, 0); if(!mjs_is_number(start_obj)) { break; } start = mjs_get_int32(mjs, start_obj); if(nargs == 2) { mjs_val_t end_obj = mjs_arg(mjs, 1); if(!mjs_is_number(end_obj)) { break; } end = mjs_get_int32(mjs, end_obj); } else { end = src_len - 1; } if((start >= src_len) || (end >= src_len) || (start >= end)) { break; } args_correct = true; } while(0); if(!args_correct) { mjs_prepend_errorf(mjs, MJS_BAD_ARGS_ERROR, ""); mjs_return(mjs, MJS_UNDEFINED); return; } src_buf += start; mjs_return(mjs, mjs_mk_array_buf(mjs, src_buf, end - start)); } static mjs_val_t mjs_mk_dataview_from_buf(struct mjs* mjs, mjs_val_t buf, mjs_dataview_type_t type) { size_t len = 0; mjs_array_buf_get_ptr(mjs, buf, &len); if(len % mjs_dataview_get_element_len(type) != 0) { mjs_prepend_errorf( mjs, MJS_BAD_ARGS_ERROR, "Buffer len is not a multiple of element size"); return MJS_UNDEFINED; } mjs_val_t view_obj = mjs_mk_object(mjs); mjs_set(mjs, view_obj, "_t", ~0, mjs_mk_number(mjs, (double)type)); mjs_set(mjs, view_obj, "buffer", ~0, buf); view_obj &= ~MJS_TAG_MASK; view_obj |= MJS_TAG_ARRAY_BUF_VIEW; mjs_dataview_get(mjs, view_obj, 0); return view_obj; } static mjs_val_t mjs_mk_dataview(struct mjs* mjs, size_t len, mjs_val_t arr, mjs_dataview_type_t type) { size_t elements_nb = 0; if(mjs_is_array(arr)) { if(!mjs_is_number(mjs_array_get(mjs, arr, 0))) { return MJS_UNDEFINED; } elements_nb = mjs_array_length(mjs, arr); } else { elements_nb = len; } size_t element_len = mjs_dataview_get_element_len(type); mjs_val_t buf_obj = mjs_mk_array_buf(mjs, NULL, element_len * elements_nb); if(mjs_is_array(arr)) { char* buf_ptr = mjs_array_buf_get_ptr(mjs, buf_obj, NULL); for(uint8_t i = 0; i < elements_nb; i++) { int64_t value = mjs_get_double(mjs, mjs_array_get(mjs, arr, i)); set_value(buf_ptr, value, type); buf_ptr += element_len; } } return mjs_mk_dataview_from_buf(mjs, buf_obj, type); } static void mjs_array_buf_new(struct mjs* mjs) { mjs_val_t len_arg = mjs_arg(mjs, 0); mjs_val_t buf_obj = MJS_UNDEFINED; if(!mjs_is_number(len_arg)) { mjs_prepend_errorf(mjs, MJS_BAD_ARGS_ERROR, ""); } else { int len = mjs_get_int(mjs, len_arg); buf_obj = mjs_mk_array_buf(mjs, NULL, len); } mjs_return(mjs, buf_obj); } static void mjs_dataview_new(struct mjs* mjs, mjs_dataview_type_t type) { mjs_val_t view_arg = mjs_arg(mjs, 0); mjs_val_t view_obj = MJS_UNDEFINED; if(mjs_is_array_buf(view_arg)) { // Create a view of existing ArrayBuf view_obj = mjs_mk_dataview_from_buf(mjs, view_arg, type); } else if(mjs_is_number(view_arg)) { // Create new typed array int len = mjs_get_int(mjs, view_arg); view_obj = mjs_mk_dataview(mjs, len, MJS_UNDEFINED, type); } else if(mjs_is_array(view_arg)) { // Create new typed array from array view_obj = mjs_mk_dataview(mjs, 0, view_arg, type); } else { mjs_prepend_errorf(mjs, MJS_BAD_ARGS_ERROR, ""); } mjs_return(mjs, view_obj); } static void mjs_new_u8_array(struct mjs* mjs) { mjs_dataview_new(mjs, MJS_DATAVIEW_U8); } static void mjs_new_i8_array(struct mjs* mjs) { mjs_dataview_new(mjs, MJS_DATAVIEW_I8); } static void mjs_new_u16_array(struct mjs* mjs) { mjs_dataview_new(mjs, MJS_DATAVIEW_U16); } static void mjs_new_i16_array(struct mjs* mjs) { mjs_dataview_new(mjs, MJS_DATAVIEW_I16); } static void mjs_new_u32_array(struct mjs* mjs) { mjs_dataview_new(mjs, MJS_DATAVIEW_U32); } static void mjs_new_i32_array(struct mjs* mjs) { mjs_dataview_new(mjs, MJS_DATAVIEW_I32); } void mjs_init_builtin_array_buf(struct mjs* mjs, mjs_val_t obj) { mjs_set(mjs, obj, "ArrayBuffer", ~0, MJS_MK_FN(mjs_array_buf_new)); mjs_set(mjs, obj, "Uint8Array", ~0, MJS_MK_FN(mjs_new_u8_array)); mjs_set(mjs, obj, "Int8Array", ~0, MJS_MK_FN(mjs_new_i8_array)); mjs_set(mjs, obj, "Uint16Array", ~0, MJS_MK_FN(mjs_new_u16_array)); mjs_set(mjs, obj, "Int16Array", ~0, MJS_MK_FN(mjs_new_i16_array)); mjs_set(mjs, obj, "Uint32Array", ~0, MJS_MK_FN(mjs_new_u32_array)); mjs_set(mjs, obj, "Int32Array", ~0, MJS_MK_FN(mjs_new_i32_array)); }
11,146
C
.c
323
28.637771
96
0.595948
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,428
mjs_dataview.c
DarkFlippers_unleashed-firmware/lib/mjs/mjs_dataview.c
/* * Copyright (c) 2017 Cesanta Software Limited * All rights reserved */ #include "mjs_exec_public.h" #include "mjs_internal.h" #include "mjs_object.h" #include "mjs_primitive.h" #include "mjs_util.h" void* mjs_mem_to_ptr(unsigned val) { return (void*)(uintptr_t)val; } void* mjs_mem_get_ptr(void* base, int offset) { return (char*)base + offset; } void mjs_mem_set_ptr(void* ptr, void* val) { *(void**)ptr = val; } double mjs_mem_get_dbl(void* ptr) { double v; memcpy(&v, ptr, sizeof(v)); return v; } void mjs_mem_set_dbl(void* ptr, double val) { memcpy(ptr, &val, sizeof(val)); } /* * TODO(dfrank): add support for unsigned ints to ffi and use * unsigned int here */ double mjs_mem_get_uint(void* ptr, int size, int bigendian) { uint8_t* p = (uint8_t*)ptr; int i, inc = bigendian ? 1 : -1; unsigned int res = 0; p += bigendian ? 0 : size - 1; for(i = 0; i < size; i++, p += inc) { res <<= 8; res |= *p; } return res; } /* * TODO(dfrank): add support for unsigned ints to ffi and use * unsigned int here */ double mjs_mem_get_int(void* ptr, int size, int bigendian) { uint8_t* p = (uint8_t*)ptr; int i, inc = bigendian ? 1 : -1; int res = 0; p += bigendian ? 0 : size - 1; for(i = 0; i < size; i++, p += inc) { res <<= 8; res |= *p; } /* sign-extend */ { int extra = sizeof(res) - size; for(i = 0; i < extra; i++) res <<= 8; for(i = 0; i < extra; i++) res >>= 8; } return res; } void mjs_mem_set_uint(void* ptr, unsigned int val, int size, int bigendian) { uint8_t* p = (uint8_t*)ptr + (bigendian ? size - 1 : 0); int i, inc = bigendian ? -1 : 1; for(i = 0; i < size; i++, p += inc) { *p = val & 0xff; val >>= 8; } } void mjs_mem_set_int(void* ptr, int val, int size, int bigendian) { mjs_mem_set_uint(ptr, val, size, bigendian); }
1,944
C
.c
73
22.753425
77
0.574273
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,436
mjs_builtin.c
DarkFlippers_unleashed-firmware/lib/mjs/mjs_builtin.c
/* * Copyright (c) 2017 Cesanta Software Limited * All rights reserved */ #include "mjs_bcode.h" #include "mjs_core.h" #include "mjs_dataview.h" #include "mjs_exec.h" #include "mjs_gc.h" #include "mjs_internal.h" #include "mjs_json.h" #include "mjs_object.h" #include "mjs_primitive.h" #include "mjs_string.h" #include "mjs_util.h" #include "mjs_array_buf.h" /* * If the file with the given filename was already loaded, returns the * corresponding bcode part; otherwise returns NULL. */ static struct mjs_bcode_part* mjs_get_loaded_file_bcode(struct mjs* mjs, const char* filename) { int parts_cnt = mjs_bcode_parts_cnt(mjs); int i; if(filename == NULL) { return 0; } for(i = 0; i < parts_cnt; i++) { struct mjs_bcode_part* bp = mjs_bcode_part_get(mjs, i); const char* cur_fn = mjs_get_bcode_filename(mjs, bp); if(strcmp(filename, cur_fn) == 0) { return bp; } } return NULL; } static void mjs_load(struct mjs* mjs) { mjs_val_t res = MJS_UNDEFINED; mjs_val_t arg0 = mjs_arg(mjs, 0); mjs_val_t arg1 = mjs_arg(mjs, 1); int custom_global = 0; /* whether the custom global object was provided */ if(mjs_is_string(arg0)) { const char* path = mjs_get_cstring(mjs, &arg0); struct mjs_bcode_part* bp = NULL; mjs_err_t ret; if(mjs_is_object(arg1)) { custom_global = 1; push_mjs_val(&mjs->scopes, arg1); } bp = mjs_get_loaded_file_bcode(mjs, path); if(bp == NULL) { /* File was not loaded before, so, load */ ret = mjs_exec_file(mjs, path, &res); } else { /* * File was already loaded before, so if it was evaluated successfully, * then skip the evaluation at all (and assume MJS_OK); otherwise * re-evaluate it again. * * However, if the custom global object was provided, then reevaluate * the file in any case. */ if(bp->exec_res != MJS_OK || custom_global) { ret = mjs_execute(mjs, bp->start_idx, &res); } else { ret = MJS_OK; } } if(ret != MJS_OK) { /* * arg0 and path might be invalidated by executing a file, so refresh * them */ arg0 = mjs_arg(mjs, 0); path = mjs_get_cstring(mjs, &arg0); mjs_prepend_errorf(mjs, ret, "failed to exec file \"%s\"", path); goto clean; } clean: if(custom_global) { mjs_pop_val(&mjs->scopes); } } mjs_return(mjs, res); } static void mjs_get_mjs(struct mjs* mjs) { mjs_return(mjs, mjs_mk_foreign(mjs, mjs)); } static void mjs_chr(struct mjs* mjs) { mjs_val_t arg0 = mjs_arg(mjs, 0), res = MJS_NULL; int n = mjs_get_int(mjs, arg0); if(mjs_is_number(arg0) && n >= 0 && n <= 255) { uint8_t s = n; res = mjs_mk_string(mjs, (const char*)&s, sizeof(s), 1); } mjs_return(mjs, res); } static void mjs_do_gc(struct mjs* mjs) { mjs_val_t arg0 = mjs_arg(mjs, 0); mjs_gc(mjs, mjs_is_boolean(arg0) ? mjs_get_bool(mjs, arg0) : 0); mjs_return(mjs, arg0); } static void mjs_s2o(struct mjs* mjs) { mjs_return( mjs, mjs_struct_to_obj( mjs, mjs_get_ptr(mjs, mjs_arg(mjs, 0)), (const struct mjs_c_struct_member*)mjs_get_ptr(mjs, mjs_arg(mjs, 1)))); } void mjs_init_builtin(struct mjs* mjs, mjs_val_t obj) { mjs_val_t v; mjs_set(mjs, obj, "global", ~0, obj); mjs_set(mjs, obj, "load", ~0, mjs_mk_foreign_func(mjs, (mjs_func_ptr_t)mjs_load)); mjs_set(mjs, obj, "ffi", ~0, mjs_mk_foreign_func(mjs, (mjs_func_ptr_t)mjs_ffi_call)); mjs_set( mjs, obj, "ffi_cb_free", ~0, mjs_mk_foreign_func(mjs, (mjs_func_ptr_t)mjs_ffi_cb_free)); mjs_set(mjs, obj, "mkstr", ~0, mjs_mk_foreign_func(mjs, (mjs_func_ptr_t)mjs_mkstr)); mjs_set(mjs, obj, "getMJS", ~0, mjs_mk_foreign_func(mjs, (mjs_func_ptr_t)mjs_get_mjs)); mjs_set(mjs, obj, "die", ~0, mjs_mk_foreign_func(mjs, (mjs_func_ptr_t)mjs_die)); mjs_set(mjs, obj, "gc", ~0, mjs_mk_foreign_func(mjs, (mjs_func_ptr_t)mjs_do_gc)); mjs_set(mjs, obj, "chr", ~0, mjs_mk_foreign_func(mjs, (mjs_func_ptr_t)mjs_chr)); mjs_set(mjs, obj, "s2o", ~0, mjs_mk_foreign_func(mjs, (mjs_func_ptr_t)mjs_s2o)); /* * Populate JSON.parse() and JSON.stringify() */ // v = mjs_mk_object(mjs); // mjs_set( // mjs, v, "stringify", ~0, mjs_mk_foreign_func(mjs, (mjs_func_ptr_t)mjs_op_json_stringify)); // mjs_set(mjs, v, "parse", ~0, mjs_mk_foreign_func(mjs, (mjs_func_ptr_t)mjs_op_json_parse)); // mjs_set(mjs, obj, "JSON", ~0, v); /* * Populate Object */ v = mjs_mk_object(mjs); mjs_set(mjs, v, "create", ~0, mjs_mk_foreign_func(mjs, (mjs_func_ptr_t)mjs_op_create_object)); mjs_set( mjs, v, "defineProperty", ~0, mjs_mk_foreign_func( mjs, (mjs_func_ptr_t)mjs_op_object_define_property)); // stub, do not use mjs_set(mjs, obj, "Object", ~0, v); /* * Populate numeric stuff */ mjs_set(mjs, obj, "NaN", ~0, MJS_TAG_NAN); mjs_set(mjs, obj, "isNaN", ~0, mjs_mk_foreign_func(mjs, (mjs_func_ptr_t)mjs_op_isnan)); mjs_init_builtin_array_buf(mjs, obj); }
5,370
C
.c
150
29.42
101
0.579696
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,464
platform_flipper.c
DarkFlippers_unleashed-firmware/lib/mjs/common/platforms/platform_flipper.c
#include <furi.h> #include <toolbox/stream/file_stream.h> #include "../cs_dbg.h" #include "../frozen/frozen.h" char* cs_read_file(const char* path, size_t* size) { Storage* storage = furi_record_open(RECORD_STORAGE); Stream* stream = file_stream_alloc(storage); char* data = NULL; if(!file_stream_open(stream, path, FSAM_READ, FSOM_OPEN_EXISTING)) { } else { *size = stream_size(stream); data = (char*)malloc(*size + 1); if(data != NULL) { stream_rewind(stream); if(stream_read(stream, (uint8_t*)data, *size) != *size) { file_stream_close(stream); furi_record_close(RECORD_STORAGE); stream_free(stream); free(data); return NULL; } data[*size] = '\0'; } } file_stream_close(stream); furi_record_close(RECORD_STORAGE); stream_free(stream); return data; } char* json_fread(const char* path) { UNUSED(path); return NULL; } int json_vfprintf(const char* file_name, const char* fmt, va_list ap) { UNUSED(file_name); UNUSED(fmt); UNUSED(ap); return 0; } int json_prettify_file(const char* file_name) { UNUSED(file_name); return 0; } int json_printer_file(struct json_out* out, const char* buf, size_t len) { UNUSED(out); UNUSED(buf); UNUSED(len); return 0; } int cs_log_print_prefix(enum cs_log_level level, const char* file, int ln) { (void)level; (void)file; (void)ln; return 0; } void cs_log_printf(const char* fmt, ...) { (void)fmt; }
1,607
C
.c
58
21.965517
76
0.599222
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,466
ffi.c
DarkFlippers_unleashed-firmware/lib/mjs/ffi/ffi.c
/* * Copyright (c) 2016 Cesanta Software Limited * All rights reserved */ #include "ffi.h" #define IS_W(arg) ((arg).ctype == FFI_CTYPE_WORD) #define IS_D(arg) ((arg).ctype == FFI_CTYPE_DOUBLE) #define IS_F(arg) ((arg).ctype == FFI_CTYPE_FLOAT) #define W(arg) ((ffi_word_t)(arg).v.i) #define D(arg) ((arg).v.d) #define F(arg) ((arg).v.f) void ffi_set_word(struct ffi_arg* arg, ffi_word_t v) { arg->ctype = FFI_CTYPE_WORD; arg->v.i = v; } void ffi_set_bool(struct ffi_arg* arg, bool v) { arg->ctype = FFI_CTYPE_BOOL; arg->v.i = v; } void ffi_set_ptr(struct ffi_arg* arg, void* v) { ffi_set_word(arg, (ffi_word_t)v); } void ffi_set_double(struct ffi_arg* arg, double v) { arg->ctype = FFI_CTYPE_DOUBLE; arg->v.d = v; } void ffi_set_float(struct ffi_arg* arg, float v) { arg->ctype = FFI_CTYPE_FLOAT; arg->v.f = v; } /* * The ARM ABI uses only 4 32-bit registers for paramter passing. * Xtensa call0 calling-convention (as used by Espressif) has 6. * * Focusing only on implementing FFI with registers means we can simplify a lot. * * ARM has some quasi-alignment rules when mixing double and integers as * arguments. Only: * a) double, int32_t, int32_t * b) int32_t, double * would fit in 4 registers. (the same goes for uint64_t). * * In order to simplify further, when a double-width argument is present, we * allow only two arguments. */ /* * We need to support x86_64 in order to support local tests. * x86_64 has more and wider registers, but unlike the two main * embedded platforms we target it has a separate register file for * integer values and for floating point values (both for passing args and * return values). E.g. if a double value is passed as a second argument * it gets passed in the first available floating point register. * * I.e, the compiler generates exactly the same code for: * * void foo(int a, double b) {...} * * and * * void foo(double b, int a) {...} * * */ typedef ffi_word_t (*w4w_t)(ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t); typedef ffi_word_t (*w5w_t)(ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t); typedef ffi_word_t (*w6w_t)(ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t); typedef ffi_word_t (*wdw_t)(double, ffi_word_t); typedef ffi_word_t (*wwd_t)(ffi_word_t, double); typedef ffi_word_t (*wdd_t)(double, double); typedef ffi_word_t (*wwwd_t)(ffi_word_t, ffi_word_t, double); typedef ffi_word_t (*wwdw_t)(ffi_word_t, double, ffi_word_t); typedef ffi_word_t (*wwdd_t)(ffi_word_t, double, double); typedef ffi_word_t (*wdww_t)(double, ffi_word_t, ffi_word_t); typedef ffi_word_t (*wdwd_t)(double, ffi_word_t, double); typedef ffi_word_t (*wddw_t)(double, double, ffi_word_t); typedef ffi_word_t (*wddd_t)(double, double, double); typedef ffi_word_t (*wfw_t)(float, ffi_word_t); typedef ffi_word_t (*wwf_t)(ffi_word_t, float); typedef ffi_word_t (*wff_t)(float, float); typedef ffi_word_t (*wwwf_t)(ffi_word_t, ffi_word_t, float); typedef ffi_word_t (*wwfw_t)(ffi_word_t, float, ffi_word_t); typedef ffi_word_t (*wwff_t)(ffi_word_t, float, float); typedef ffi_word_t (*wfww_t)(float, ffi_word_t, ffi_word_t); typedef ffi_word_t (*wfwf_t)(float, ffi_word_t, float); typedef ffi_word_t (*wffw_t)(float, float, ffi_word_t); typedef ffi_word_t (*wfff_t)(float, float, float); typedef bool (*b4w_t)(ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t); typedef bool (*b5w_t)(ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t); typedef bool (*b6w_t)(ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t); typedef bool (*bdw_t)(double, ffi_word_t); typedef bool (*bwd_t)(ffi_word_t, double); typedef bool (*bdd_t)(double, double); typedef bool (*bwwd_t)(ffi_word_t, ffi_word_t, double); typedef bool (*bwdw_t)(ffi_word_t, double, ffi_word_t); typedef bool (*bwdd_t)(ffi_word_t, double, double); typedef bool (*bdww_t)(double, ffi_word_t, ffi_word_t); typedef bool (*bdwd_t)(double, ffi_word_t, double); typedef bool (*bddw_t)(double, double, ffi_word_t); typedef bool (*bddd_t)(double, double, double); typedef bool (*bfw_t)(float, ffi_word_t); typedef bool (*bwf_t)(ffi_word_t, float); typedef bool (*bff_t)(float, float); typedef bool (*bwwf_t)(ffi_word_t, ffi_word_t, float); typedef bool (*bwfw_t)(ffi_word_t, float, ffi_word_t); typedef bool (*bwff_t)(ffi_word_t, float, float); typedef bool (*bfww_t)(float, ffi_word_t, ffi_word_t); typedef bool (*bfwf_t)(float, ffi_word_t, float); typedef bool (*bffw_t)(float, float, ffi_word_t); typedef bool (*bfff_t)(float, float, float); typedef double (*d4w_t)(ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t); typedef double (*d5w_t)(ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t); typedef double (*d6w_t)(ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t); typedef double (*ddw_t)(double, ffi_word_t); typedef double (*dwd_t)(ffi_word_t, double); typedef double (*ddd_t)(double, double); typedef double (*dwwd_t)(ffi_word_t, ffi_word_t, double); typedef double (*dwdw_t)(ffi_word_t, double, ffi_word_t); typedef double (*dwdd_t)(ffi_word_t, double, double); typedef double (*ddww_t)(double, ffi_word_t, ffi_word_t); typedef double (*ddwd_t)(double, ffi_word_t, double); typedef double (*dddw_t)(double, double, ffi_word_t); typedef double (*dddd_t)(double, double, double); typedef float (*f4w_t)(ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t); typedef float (*f5w_t)(ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t); typedef float (*f6w_t)(ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t, ffi_word_t); typedef float (*ffw_t)(float, ffi_word_t); typedef float (*fwf_t)(ffi_word_t, float); typedef float (*fff_t)(float, float); typedef float (*fwwf_t)(ffi_word_t, ffi_word_t, float); typedef float (*fwfw_t)(ffi_word_t, float, ffi_word_t); typedef float (*fwff_t)(ffi_word_t, float, float); typedef float (*ffww_t)(float, ffi_word_t, ffi_word_t); typedef float (*ffwf_t)(float, ffi_word_t, float); typedef float (*fffw_t)(float, float, ffi_word_t); typedef float (*ffff_t)(float, float, float); int ffi_call_mjs(ffi_fn_t* func, int nargs, struct ffi_arg* res, struct ffi_arg* args) { int i, doubles = 0, floats = 0; if(nargs > 6) return -1; for(i = 0; i < nargs; i++) { doubles += (IS_D(args[i])); floats += (IS_F(args[i])); } /* Doubles and floats are not supported together atm */ if(doubles > 0 && floats > 0) { return -1; } switch(res->ctype) { case FFI_CTYPE_WORD: { /* {{{ */ ffi_word_t r; if(doubles == 0) { if(floats == 0) { /* * No double and no float args: we currently support up to 6 * word-sized arguments */ if(nargs <= 4) { w4w_t f = (w4w_t)func; r = f(W(args[0]), W(args[1]), W(args[2]), W(args[3])); } else if(nargs == 5) { w5w_t f = (w5w_t)func; r = f(W(args[0]), W(args[1]), W(args[2]), W(args[3]), W(args[4])); } else if(nargs == 6) { w6w_t f = (w6w_t)func; r = f(W(args[0]), W(args[1]), W(args[2]), W(args[3]), W(args[4]), W(args[5])); } else { abort(); } } else { /* There are some floats */ switch(nargs) { case 0: case 1: case 2: if(IS_F(args[0]) && IS_F(args[1])) { wff_t f = (wff_t)func; r = f(F(args[0]), F(args[1])); } else if(IS_F(args[0])) { wfw_t f = (wfw_t)func; r = f(F(args[0]), W(args[1])); } else { wwf_t f = (wwf_t)func; r = f(W(args[0]), F(args[1])); } break; case 3: if(IS_W(args[0]) && IS_W(args[1]) && IS_F(args[2])) { wwwf_t f = (wwwf_t)func; r = f(W(args[0]), W(args[1]), F(args[2])); } else if(IS_W(args[0]) && IS_F(args[1]) && IS_W(args[2])) { wwfw_t f = (wwfw_t)func; r = f(W(args[0]), F(args[1]), W(args[2])); } else if(IS_W(args[0]) && IS_F(args[1]) && IS_F(args[2])) { wwff_t f = (wwff_t)func; r = f(W(args[0]), F(args[1]), F(args[2])); } else if(IS_F(args[0]) && IS_W(args[1]) && IS_W(args[2])) { wfww_t f = (wfww_t)func; r = f(F(args[0]), W(args[1]), W(args[2])); } else if(IS_F(args[0]) && IS_W(args[1]) && IS_F(args[2])) { wfwf_t f = (wfwf_t)func; r = f(F(args[0]), W(args[1]), F(args[2])); } else if(IS_F(args[0]) && IS_F(args[1]) && IS_W(args[2])) { wffw_t f = (wffw_t)func; r = f(F(args[0]), F(args[1]), W(args[2])); } else if(IS_F(args[0]) && IS_F(args[1]) && IS_F(args[2])) { wfff_t f = (wfff_t)func; r = f(F(args[0]), F(args[1]), F(args[2])); } else { // The above checks should be exhaustive abort(); } break; default: return -1; } } } else { /* There are some doubles */ switch(nargs) { case 0: case 1: case 2: if(IS_D(args[0]) && IS_D(args[1])) { wdd_t f = (wdd_t)func; r = f(D(args[0]), D(args[1])); } else if(IS_D(args[0])) { wdw_t f = (wdw_t)func; r = f(D(args[0]), W(args[1])); } else { wwd_t f = (wwd_t)func; r = f(W(args[0]), D(args[1])); } break; case 3: if(IS_W(args[0]) && IS_W(args[1]) && IS_D(args[2])) { wwwd_t f = (wwwd_t)func; r = f(W(args[0]), W(args[1]), D(args[2])); } else if(IS_W(args[0]) && IS_D(args[1]) && IS_W(args[2])) { wwdw_t f = (wwdw_t)func; r = f(W(args[0]), D(args[1]), W(args[2])); } else if(IS_W(args[0]) && IS_D(args[1]) && IS_D(args[2])) { wwdd_t f = (wwdd_t)func; r = f(W(args[0]), D(args[1]), D(args[2])); } else if(IS_D(args[0]) && IS_W(args[1]) && IS_W(args[2])) { wdww_t f = (wdww_t)func; r = f(D(args[0]), W(args[1]), W(args[2])); } else if(IS_D(args[0]) && IS_W(args[1]) && IS_D(args[2])) { wdwd_t f = (wdwd_t)func; r = f(D(args[0]), W(args[1]), D(args[2])); } else if(IS_D(args[0]) && IS_D(args[1]) && IS_W(args[2])) { wddw_t f = (wddw_t)func; r = f(D(args[0]), D(args[1]), W(args[2])); } else if(IS_D(args[0]) && IS_D(args[1]) && IS_D(args[2])) { wddd_t f = (wddd_t)func; r = f(D(args[0]), D(args[1]), D(args[2])); } else { // The above checks should be exhaustive abort(); } break; default: return -1; } } res->v.i = (uint64_t)r; } break; /* }}} */ case FFI_CTYPE_BOOL: { /* {{{ */ ffi_word_t r; if(doubles == 0) { if(floats == 0) { /* * No double and no float args: we currently support up to 6 * word-sized arguments */ if(nargs <= 4) { b4w_t f = (b4w_t)func; r = f(W(args[0]), W(args[1]), W(args[2]), W(args[3])); } else if(nargs == 5) { b5w_t f = (b5w_t)func; r = f(W(args[0]), W(args[1]), W(args[2]), W(args[3]), W(args[4])); } else if(nargs == 6) { b6w_t f = (b6w_t)func; r = f(W(args[0]), W(args[1]), W(args[2]), W(args[3]), W(args[4]), W(args[5])); } else { abort(); } } else { /* There are some floats */ switch(nargs) { case 0: case 1: case 2: if(IS_F(args[0]) && IS_F(args[1])) { bff_t f = (bff_t)func; r = f(F(args[0]), F(args[1])); } else if(IS_F(args[0])) { bfw_t f = (bfw_t)func; r = f(F(args[0]), W(args[1])); } else { bwf_t f = (bwf_t)func; r = f(W(args[0]), F(args[1])); } break; case 3: if(IS_W(args[0]) && IS_W(args[1]) && IS_F(args[2])) { bwwf_t f = (bwwf_t)func; r = f(W(args[0]), W(args[1]), F(args[2])); } else if(IS_W(args[0]) && IS_F(args[1]) && IS_W(args[2])) { bwfw_t f = (bwfw_t)func; r = f(W(args[0]), F(args[1]), W(args[2])); } else if(IS_W(args[0]) && IS_F(args[1]) && IS_F(args[2])) { bwff_t f = (bwff_t)func; r = f(W(args[0]), F(args[1]), F(args[2])); } else if(IS_F(args[0]) && IS_W(args[1]) && IS_W(args[2])) { bfww_t f = (bfww_t)func; r = f(F(args[0]), W(args[1]), W(args[2])); } else if(IS_F(args[0]) && IS_W(args[1]) && IS_F(args[2])) { bfwf_t f = (bfwf_t)func; r = f(F(args[0]), W(args[1]), F(args[2])); } else if(IS_F(args[0]) && IS_F(args[1]) && IS_W(args[2])) { bffw_t f = (bffw_t)func; r = f(F(args[0]), F(args[1]), W(args[2])); } else if(IS_F(args[0]) && IS_F(args[1]) && IS_F(args[2])) { bfff_t f = (bfff_t)func; r = f(F(args[0]), F(args[1]), F(args[2])); } else { // The above checks should be exhaustive abort(); } break; default: return -1; } } } else { /* There are some doubles */ switch(nargs) { case 0: case 1: case 2: if(IS_D(args[0]) && IS_D(args[1])) { bdd_t f = (bdd_t)func; r = f(D(args[0]), D(args[1])); } else if(IS_D(args[0])) { bdw_t f = (bdw_t)func; r = f(D(args[0]), W(args[1])); } else { bwd_t f = (bwd_t)func; r = f(W(args[0]), D(args[1])); } break; case 3: if(IS_W(args[0]) && IS_W(args[1]) && IS_D(args[2])) { bwwd_t f = (bwwd_t)func; r = f(W(args[0]), W(args[1]), D(args[2])); } else if(IS_W(args[0]) && IS_D(args[1]) && IS_W(args[2])) { bwdw_t f = (bwdw_t)func; r = f(W(args[0]), D(args[1]), W(args[2])); } else if(IS_W(args[0]) && IS_D(args[1]) && IS_D(args[2])) { bwdd_t f = (bwdd_t)func; r = f(W(args[0]), D(args[1]), D(args[2])); } else if(IS_D(args[0]) && IS_W(args[1]) && IS_W(args[2])) { bdww_t f = (bdww_t)func; r = f(D(args[0]), W(args[1]), W(args[2])); } else if(IS_D(args[0]) && IS_W(args[1]) && IS_D(args[2])) { bdwd_t f = (bdwd_t)func; r = f(D(args[0]), W(args[1]), D(args[2])); } else if(IS_D(args[0]) && IS_D(args[1]) && IS_W(args[2])) { bddw_t f = (bddw_t)func; r = f(D(args[0]), D(args[1]), W(args[2])); } else if(IS_D(args[0]) && IS_D(args[1]) && IS_D(args[2])) { bddd_t f = (bddd_t)func; r = f(D(args[0]), D(args[1]), D(args[2])); } else { // The above checks should be exhaustive abort(); } break; default: return -1; } } res->v.i = (uint64_t)r; } break; /* }}} */ case FFI_CTYPE_DOUBLE: { /* {{{ */ double r; if(doubles == 0) { /* No double args: we currently support up to 6 word-sized arguments */ if(nargs <= 4) { d4w_t f = (d4w_t)func; r = f(W(args[0]), W(args[1]), W(args[2]), W(args[3])); } else if(nargs == 5) { d5w_t f = (d5w_t)func; r = f(W(args[0]), W(args[1]), W(args[2]), W(args[3]), W(args[4])); } else if(nargs == 6) { d6w_t f = (d6w_t)func; r = f(W(args[0]), W(args[1]), W(args[2]), W(args[3]), W(args[4]), W(args[5])); } else { abort(); } } else { switch(nargs) { case 0: case 1: case 2: if(IS_D(args[0]) && IS_D(args[1])) { ddd_t f = (ddd_t)func; r = f(D(args[0]), D(args[1])); } else if(IS_D(args[0])) { ddw_t f = (ddw_t)func; r = f(D(args[0]), W(args[1])); } else { dwd_t f = (dwd_t)func; r = f(W(args[0]), D(args[1])); } break; case 3: if(IS_W(args[0]) && IS_W(args[1]) && IS_D(args[2])) { dwwd_t f = (dwwd_t)func; r = f(W(args[0]), W(args[1]), D(args[2])); } else if(IS_W(args[0]) && IS_D(args[1]) && IS_W(args[2])) { dwdw_t f = (dwdw_t)func; r = f(W(args[0]), D(args[1]), W(args[2])); } else if(IS_W(args[0]) && IS_D(args[1]) && IS_D(args[2])) { dwdd_t f = (dwdd_t)func; r = f(W(args[0]), D(args[1]), D(args[2])); } else if(IS_D(args[0]) && IS_W(args[1]) && IS_W(args[2])) { ddww_t f = (ddww_t)func; r = f(D(args[0]), W(args[1]), W(args[2])); } else if(IS_D(args[0]) && IS_W(args[1]) && IS_D(args[2])) { ddwd_t f = (ddwd_t)func; r = f(D(args[0]), W(args[1]), D(args[2])); } else if(IS_D(args[0]) && IS_D(args[1]) && IS_W(args[2])) { dddw_t f = (dddw_t)func; r = f(D(args[0]), D(args[1]), W(args[2])); } else if(IS_D(args[0]) && IS_D(args[1]) && IS_D(args[2])) { dddd_t f = (dddd_t)func; r = f(D(args[0]), D(args[1]), D(args[2])); } else { // The above checks should be exhaustive abort(); } break; default: return -1; } } res->v.d = r; } break; /* }}} */ case FFI_CTYPE_FLOAT: { /* {{{ */ double r; if(floats == 0) { /* No float args: we currently support up to 6 word-sized arguments */ if(nargs <= 4) { f4w_t f = (f4w_t)func; r = f(W(args[0]), W(args[1]), W(args[2]), W(args[3])); } else if(nargs == 5) { f5w_t f = (f5w_t)func; r = f(W(args[0]), W(args[1]), W(args[2]), W(args[3]), W(args[4])); } else if(nargs == 6) { f6w_t f = (f6w_t)func; r = f(W(args[0]), W(args[1]), W(args[2]), W(args[3]), W(args[4]), W(args[5])); } else { abort(); } } else { /* There are some float args */ switch(nargs) { case 0: case 1: case 2: if(IS_F(args[0]) && IS_F(args[1])) { fff_t f = (fff_t)func; r = f(F(args[0]), F(args[1])); } else if(IS_F(args[0])) { ffw_t f = (ffw_t)func; r = f(F(args[0]), W(args[1])); } else { fwf_t f = (fwf_t)func; r = f(W(args[0]), F(args[1])); } break; case 3: if(IS_W(args[0]) && IS_W(args[1]) && IS_F(args[2])) { fwwf_t f = (fwwf_t)func; r = f(W(args[0]), W(args[1]), F(args[2])); } else if(IS_W(args[0]) && IS_F(args[1]) && IS_W(args[2])) { fwfw_t f = (fwfw_t)func; r = f(W(args[0]), F(args[1]), W(args[2])); } else if(IS_W(args[0]) && IS_F(args[1]) && IS_F(args[2])) { fwff_t f = (fwff_t)func; r = f(W(args[0]), F(args[1]), F(args[2])); } else if(IS_F(args[0]) && IS_W(args[1]) && IS_W(args[2])) { ffww_t f = (ffww_t)func; r = f(F(args[0]), W(args[1]), W(args[2])); } else if(IS_F(args[0]) && IS_W(args[1]) && IS_F(args[2])) { ffwf_t f = (ffwf_t)func; r = f(F(args[0]), W(args[1]), F(args[2])); } else if(IS_F(args[0]) && IS_F(args[1]) && IS_W(args[2])) { fffw_t f = (fffw_t)func; r = f(F(args[0]), F(args[1]), W(args[2])); } else if(IS_F(args[0]) && IS_F(args[1]) && IS_F(args[2])) { ffff_t f = (ffff_t)func; r = f(F(args[0]), F(args[1]), F(args[2])); } else { // The above checks should be exhaustive abort(); } break; default: return -1; } } res->v.f = r; } break; /* }}} */ } return 0; }
22,899
C
.c
519
30.666667
100
0.428265
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,469
application_assets.c
DarkFlippers_unleashed-firmware/lib/flipper_application/application_assets.c
#include "application_assets.h" #include <toolbox/path.h> #include <storage/storage_i.h> // #define ELF_ASSETS_DEBUG_LOG 1 #ifndef ELF_ASSETS_DEBUG_LOG #undef FURI_LOG_D #define FURI_LOG_D(...) #undef FURI_LOG_E #define FURI_LOG_E(...) #endif #define FLIPPER_APPLICATION_ASSETS_MAGIC 0x4F4C5A44 #define FLIPPER_APPLICATION_ASSETS_VERSION 1 #define FLIPPER_APPLICATION_ASSETS_SIGNATURE_FILENAME ".assets.signature" #define BUFFER_SIZE 512 #define TAG "FapAssets" typedef struct FURI_PACKED { uint32_t magic; uint32_t version; uint32_t dirs_count; uint32_t files_count; } FlipperApplicationAssetsHeader; typedef enum { AssetsSignatureResultEqual, AssetsSignatureResultNotEqual, AssetsSignatureResultError, } AssetsSignatureResult; static FuriString* flipper_application_assets_alloc_app_full_path(FuriString* app_name) { furi_assert(app_name); FuriString* full_path = furi_string_alloc_set(APPS_ASSETS_PATH "/"); furi_string_cat(full_path, app_name); return full_path; } static FuriString* flipper_application_assets_alloc_signature_file_path(FuriString* app_name) { furi_assert(app_name); FuriString* signature_file_path = flipper_application_assets_alloc_app_full_path(app_name); furi_string_cat(signature_file_path, "/" FLIPPER_APPLICATION_ASSETS_SIGNATURE_FILENAME); return signature_file_path; } static uint8_t* flipper_application_assets_alloc_and_load_data(File* file, size_t* size) { furi_assert(file); uint8_t* data = NULL; uint32_t length = 0; // read data length if(storage_file_read(file, &length, sizeof(length)) != sizeof(length)) { return NULL; } data = malloc(length); // read data if(storage_file_read(file, (void*)data, length) != length) { free((void*)data); return NULL; } if(size != NULL) { *size = length; } return data; } static bool flipper_application_assets_process_files( Storage* storage, File* file, FuriString* app_name, uint32_t files_count) { furi_assert(storage); furi_assert(file); furi_assert(app_name); UNUSED(storage); bool success = false; uint32_t length = 0; char* path = NULL; FuriString* file_path = furi_string_alloc(); File* destination = storage_file_alloc(storage); FuriString* full_path = flipper_application_assets_alloc_app_full_path(app_name); for(uint32_t i = 0; i < files_count; i++) { path = (char*)flipper_application_assets_alloc_and_load_data(file, NULL); if(path == NULL) { break; } // read file size if(storage_file_read(file, &length, sizeof(length)) != sizeof(length)) { break; } furi_string_set(file_path, full_path); furi_string_cat(file_path, "/"); furi_string_cat(file_path, path); if(!storage_file_open( destination, furi_string_get_cstr(file_path), FSAM_WRITE, FSOM_CREATE_ALWAYS)) { FURI_LOG_E(TAG, "Can't create file: %s", furi_string_get_cstr(file_path)); break; } // copy data to file if(!storage_file_copy_to_file(file, destination, length)) { FURI_LOG_E(TAG, "Can't copy data to file: %s", furi_string_get_cstr(file_path)); break; } storage_file_close(destination); free(path); path = NULL; if(i == files_count - 1) { success = true; } } if(path != NULL) { free(path); } storage_file_free(destination); furi_string_free(file_path); return success; } static bool flipper_application_assets_process_dirs( Storage* storage, File* file, FuriString* app_name, uint32_t dirs_count) { furi_assert(storage); furi_assert(file); furi_assert(app_name); bool success = false; FuriString* full_path = flipper_application_assets_alloc_app_full_path(app_name); do { FuriString* dir_path = furi_string_alloc(); char* path = NULL; for(uint32_t i = 0; i < dirs_count; i++) { path = (char*)flipper_application_assets_alloc_and_load_data(file, NULL); if(path == NULL) { break; } furi_string_set(dir_path, full_path); furi_string_cat(dir_path, "/"); furi_string_cat(dir_path, path); if(!storage_simply_mkdir(storage, furi_string_get_cstr(dir_path))) { FURI_LOG_E(TAG, "Can't create directory: %s", furi_string_get_cstr(dir_path)); break; } free(path); path = NULL; if(i == dirs_count - 1) { success = true; } } if(path != NULL) { free(path); } furi_string_free(dir_path); } while(false); furi_string_free(full_path); return success; } static AssetsSignatureResult flipper_application_assets_process_signature( Storage* storage, File* file, FuriString* app_name, uint8_t** signature_data, size_t* signature_data_size) { furi_assert(storage); furi_assert(file); furi_assert(app_name); furi_assert(signature_data); furi_assert(signature_data_size); AssetsSignatureResult result = AssetsSignatureResultError; File* signature_file = storage_file_alloc(storage); FuriString* signature_file_path = flipper_application_assets_alloc_signature_file_path(app_name); do { // read signature *signature_data = flipper_application_assets_alloc_and_load_data(file, signature_data_size); if(*signature_data == NULL) { //-V547 FURI_LOG_E(TAG, "Can't read signature"); break; } result = AssetsSignatureResultNotEqual; if(!storage_file_open( signature_file, furi_string_get_cstr(signature_file_path), FSAM_READ_WRITE, FSOM_OPEN_EXISTING)) { FURI_LOG_E(TAG, "Can't open signature file"); break; } size_t signature_size = storage_file_size(signature_file); uint8_t* signature_file_data = malloc(signature_size); if(storage_file_read(signature_file, signature_file_data, signature_size) != signature_size) { FURI_LOG_E(TAG, "Can't read signature file"); free(signature_file_data); break; } if(memcmp(*signature_data, signature_file_data, signature_size) == 0) { FURI_LOG_D(TAG, "Assets signature is equal"); result = AssetsSignatureResultEqual; } free(signature_file_data); } while(0); storage_file_free(signature_file); furi_string_free(signature_file_path); return result; } bool flipper_application_assets_load(File* file, const char* elf_path, size_t offset, size_t size) { UNUSED(size); furi_assert(file); furi_assert(elf_path); FlipperApplicationAssetsHeader header; bool result = false; Storage* storage = furi_record_open(RECORD_STORAGE); uint8_t* signature_data = NULL; size_t signature_data_size = 0; FuriString* app_name = furi_string_alloc(); path_extract_filename_no_ext(elf_path, app_name); FURI_LOG_D(TAG, "Loading assets for %s", furi_string_get_cstr(app_name)); FuriString* full_path = flipper_application_assets_alloc_app_full_path(app_name); do { if(!storage_file_seek(file, offset, true)) { break; } // read header if(storage_file_read(file, &header, sizeof(header)) != sizeof(header)) { break; } if(header.magic != FLIPPER_APPLICATION_ASSETS_MAGIC) { break; } if(header.version != FLIPPER_APPLICATION_ASSETS_VERSION) { break; } // process signature AssetsSignatureResult signature_result = flipper_application_assets_process_signature( storage, file, app_name, &signature_data, &signature_data_size); if(signature_result == AssetsSignatureResultError) { FURI_LOG_E(TAG, "Assets signature error"); break; } else if(signature_result == AssetsSignatureResultEqual) { FURI_LOG_D(TAG, "Assets signature equal, skip loading"); result = true; break; } else { FURI_LOG_D(TAG, "Assets signature not equal, loading"); // remove old assets FuriString* full_path = flipper_application_assets_alloc_app_full_path(app_name); storage_simply_remove_recursive(storage, furi_string_get_cstr(full_path)); furi_string_free(full_path); FURI_LOG_D(TAG, "Assets removed"); } if(!storage_simply_mkdir(storage, APPS_ASSETS_PATH)) { break; } if(!storage_simply_mkdir(storage, furi_string_get_cstr(full_path))) { break; } // process directories if(header.dirs_count && !flipper_application_assets_process_dirs(storage, file, app_name, header.dirs_count)) { break; } // process files if(header.files_count && !flipper_application_assets_process_files( storage, file, app_name, header.files_count)) { break; } // write signature FuriString* signature_file_path = flipper_application_assets_alloc_signature_file_path(app_name); File* signature_file = storage_file_alloc(storage); if(storage_file_open( signature_file, furi_string_get_cstr(signature_file_path), FSAM_WRITE, FSOM_CREATE_ALWAYS)) { storage_file_write(signature_file, signature_data, signature_data_size); } storage_file_free(signature_file); furi_string_free(signature_file_path); result = true; } while(false); if(signature_data != NULL) { free(signature_data); } furi_record_close(RECORD_STORAGE); furi_string_free(full_path); furi_string_free(app_name); FURI_LOG_D(TAG, "Assets loading %s", result ? "success" : "failed"); return result; }
10,329
C
.c
282
28.51773
100
0.620285
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,470
application_manifest.c
DarkFlippers_unleashed-firmware/lib/flipper_application/application_manifest.c
#include "application_manifest.h" #include <furi_hal_version.h> #include <furi.h> bool flipper_application_manifest_is_valid(const FlipperApplicationManifest* manifest) { furi_check(manifest); if((manifest->base.manifest_magic != FAP_MANIFEST_MAGIC) || (manifest->base.manifest_version != FAP_MANIFEST_SUPPORTED_VERSION)) { return false; } return true; } bool flipper_application_manifest_is_too_old( const FlipperApplicationManifest* manifest, const ElfApiInterface* api_interface) { furi_check(manifest); furi_check(api_interface); if(manifest->base.api_version.major < api_interface->api_version_major /* || manifest->base.api_version.minor > app->api_interface->api_version_minor */) { return false; } return true; } bool flipper_application_manifest_is_too_new( const FlipperApplicationManifest* manifest, const ElfApiInterface* api_interface) { furi_check(manifest); furi_check(api_interface); if(manifest->base.api_version.major > api_interface->api_version_major /* || manifest->base.api_version.minor > app->api_interface->api_version_minor */) { return false; } return true; } bool flipper_application_manifest_is_target_compatible(const FlipperApplicationManifest* manifest) { furi_check(manifest); const Version* version = furi_hal_version_get_firmware_version(); return version_get_target(version) == manifest->base.hardware_target_id; }
1,491
C
.c
38
34.552632
100
0.725381
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,478
elf_api_interface.h
DarkFlippers_unleashed-firmware/lib/flipper_application/elf/elf_api_interface.h
#pragma once #include <elf.h> #include <stdbool.h> /** * @brief Interface for ELF loader to resolve symbols */ typedef struct ElfApiInterface { uint16_t api_version_major; uint16_t api_version_minor; bool (*resolver_callback)( const struct ElfApiInterface* interface, uint32_t hash, Elf32_Addr* address); } ElfApiInterface;
364
C
.c
14
22.142857
53
0.70977
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,480
infrared_transmit.c
DarkFlippers_unleashed-firmware/lib/infrared/worker/infrared_transmit.c
#include "infrared.h" #include <stdint.h> #include <stdbool.h> #include <stddef.h> #include <furi.h> #include <furi_hal_infrared.h> static uint32_t infrared_tx_number_of_transmissions = 0; static uint32_t infrared_tx_raw_timings_index = 0; static uint32_t infrared_tx_raw_timings_number = 0; static uint32_t infrared_tx_raw_start_from_mark = 0; static bool infrared_tx_raw_add_silence = false; FuriHalInfraredTxGetDataState infrared_get_raw_data_callback(void* context, uint32_t* duration, bool* level) { furi_assert(duration); furi_assert(level); furi_assert(context); FuriHalInfraredTxGetDataState state = FuriHalInfraredTxGetDataStateOk; const uint32_t* timings = context; if(infrared_tx_raw_add_silence && (infrared_tx_raw_timings_index == 0)) { infrared_tx_raw_add_silence = false; *level = false; *duration = INFRARED_RAW_TX_TIMING_DELAY_US; } else { *level = infrared_tx_raw_start_from_mark ^ (infrared_tx_raw_timings_index % 2); *duration = timings[infrared_tx_raw_timings_index++]; } if(infrared_tx_raw_timings_number == infrared_tx_raw_timings_index) { state = FuriHalInfraredTxGetDataStateLastDone; } return state; } void infrared_send_raw_ext( const uint32_t timings[], uint32_t timings_cnt, bool start_from_mark, uint32_t frequency, float duty_cycle) { furi_check(timings); infrared_tx_raw_start_from_mark = start_from_mark; infrared_tx_raw_timings_index = 0; infrared_tx_raw_timings_number = timings_cnt; infrared_tx_raw_add_silence = start_from_mark; furi_hal_infrared_async_tx_set_data_isr_callback( infrared_get_raw_data_callback, (void*)timings); furi_hal_infrared_async_tx_start(frequency, duty_cycle); furi_hal_infrared_async_tx_wait_termination(); furi_check(!furi_hal_infrared_is_busy()); } void infrared_send_raw(const uint32_t timings[], uint32_t timings_cnt, bool start_from_mark) { infrared_send_raw_ext( timings, timings_cnt, start_from_mark, INFRARED_COMMON_CARRIER_FREQUENCY, INFRARED_COMMON_DUTY_CYCLE); } FuriHalInfraredTxGetDataState infrared_get_data_callback(void* context, uint32_t* duration, bool* level) { FuriHalInfraredTxGetDataState state; InfraredEncoderHandler* handler = context; InfraredStatus status = InfraredStatusError; if(infrared_tx_number_of_transmissions > 0) { status = infrared_encode(handler, duration, level); } if(status == InfraredStatusError) { state = FuriHalInfraredTxGetDataStateLastDone; *duration = 0; *level = 0; } else if(status == InfraredStatusOk) { state = FuriHalInfraredTxGetDataStateOk; } else if(status == InfraredStatusDone) { if(--infrared_tx_number_of_transmissions == 0) { state = FuriHalInfraredTxGetDataStateLastDone; } else { state = FuriHalInfraredTxGetDataStateDone; } } else { furi_crash(); } return state; } void infrared_send(const InfraredMessage* message, int times) { furi_check(message); furi_check(times); furi_check(infrared_is_protocol_valid(message->protocol)); InfraredEncoderHandler* handler = infrared_alloc_encoder(); infrared_reset_encoder(handler, message); infrared_tx_number_of_transmissions = MAX((int)infrared_get_protocol_min_repeat_count(message->protocol), times); uint32_t frequency = infrared_get_protocol_frequency(message->protocol); float duty_cycle = infrared_get_protocol_duty_cycle(message->protocol); furi_hal_infrared_async_tx_set_data_isr_callback(infrared_get_data_callback, handler); furi_hal_infrared_async_tx_start(frequency, duty_cycle); furi_hal_infrared_async_tx_wait_termination(); infrared_free_encoder(handler); furi_check(!furi_hal_infrared_is_busy()); }
3,911
C
.c
97
34.907216
94
0.709541
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,481
infrared_worker.c
DarkFlippers_unleashed-firmware/lib/infrared/worker/infrared_worker.c
#include "infrared_worker.h" #include <furi_hal_infrared.h> #include <float_tools.h> #include <core/check.h> #include <core/common_defines.h> #include <notification/notification_messages.h> #define INFRARED_WORKER_RX_TIMEOUT INFRARED_RAW_RX_TIMING_DELAY_US #define INFRARED_WORKER_RX_RECEIVED 0x01 #define INFRARED_WORKER_RX_TIMEOUT_RECEIVED 0x02 #define INFRARED_WORKER_OVERRUN 0x04 #define INFRARED_WORKER_EXIT 0x08 #define INFRARED_WORKER_TX_FILL_BUFFER 0x10 #define INFRARED_WORKER_TX_MESSAGE_SENT 0x20 #define INFRARED_WORKER_ALL_RX_EVENTS \ (INFRARED_WORKER_RX_RECEIVED | INFRARED_WORKER_RX_TIMEOUT_RECEIVED | \ INFRARED_WORKER_OVERRUN | INFRARED_WORKER_EXIT) #define INFRARED_WORKER_ALL_TX_EVENTS \ (INFRARED_WORKER_TX_FILL_BUFFER | INFRARED_WORKER_TX_MESSAGE_SENT | INFRARED_WORKER_EXIT) #define INFRARED_WORKER_ALL_EVENTS (INFRARED_WORKER_ALL_RX_EVENTS | INFRARED_WORKER_ALL_TX_EVENTS) typedef enum { InfraredWorkerStateIdle, InfraredWorkerStateRunRx, InfraredWorkerStateRunTx, InfraredWorkerStateWaitTxEnd, InfraredWorkerStateStopTx, InfraredWorkerStateStartTx, } InfraredWorkerState; struct InfraredWorkerSignal { bool decoded; size_t timings_cnt; union { InfraredMessage message; struct { /* +1 is for pause we add at the beginning */ uint32_t timings[MAX_TIMINGS_AMOUNT + 1]; uint32_t frequency; float duty_cycle; } raw; }; }; struct InfraredWorker { FuriThread* thread; FuriStreamBuffer* stream; InfraredWorkerSignal signal; InfraredWorkerState state; InfraredEncoderHandler* infrared_encoder; InfraredDecoderHandler* infrared_decoder; NotificationApp* notification; bool blink_enable; bool decode_enable; union { struct { InfraredWorkerGetSignalCallback get_signal_callback; InfraredWorkerMessageSentCallback message_sent_callback; void* get_signal_context; void* message_sent_context; uint32_t frequency; float duty_cycle; uint32_t tx_raw_cnt; bool need_reinitialization; bool steady_signal_sent; } tx; struct { InfraredWorkerReceivedSignalCallback received_signal_callback; void* received_signal_context; bool overrun; } rx; }; }; typedef struct { uint32_t duration; bool level; FuriHalInfraredTxGetDataState state; } InfraredWorkerTiming; static int32_t infrared_worker_tx_thread(void* context); static FuriHalInfraredTxGetDataState infrared_worker_furi_hal_data_isr_callback(void* context, uint32_t* duration, bool* level); static void infrared_worker_furi_hal_message_sent_isr_callback(void* context); static void infrared_worker_rx_timeout_callback(void* context) { InfraredWorker* instance = context; uint32_t flags_set = furi_thread_flags_set( furi_thread_get_id(instance->thread), INFRARED_WORKER_RX_TIMEOUT_RECEIVED); furi_check(flags_set & INFRARED_WORKER_RX_TIMEOUT_RECEIVED); } static void infrared_worker_rx_callback(void* context, bool level, uint32_t duration) { InfraredWorker* instance = context; furi_assert(duration != 0); LevelDuration level_duration = level_duration_make(level, duration); size_t ret = furi_stream_buffer_send(instance->stream, &level_duration, sizeof(LevelDuration), 0); uint32_t events = (ret == sizeof(LevelDuration)) ? INFRARED_WORKER_RX_RECEIVED : INFRARED_WORKER_OVERRUN; uint32_t flags_set = furi_thread_flags_set(furi_thread_get_id(instance->thread), events); furi_check(flags_set & events); } static void infrared_worker_process_timeout(InfraredWorker* instance) { if(instance->signal.timings_cnt < 2) return; const InfraredMessage* message_decoded = infrared_check_decoder_ready(instance->infrared_decoder); if(message_decoded) { instance->signal.message = *message_decoded; instance->signal.timings_cnt = 0; instance->signal.decoded = true; } else { instance->signal.decoded = false; } if(instance->rx.received_signal_callback) instance->rx.received_signal_callback( instance->rx.received_signal_context, &instance->signal); } static void infrared_worker_process_timings(InfraredWorker* instance, uint32_t duration, bool level) { const InfraredMessage* message_decoded = instance->decode_enable ? infrared_decode(instance->infrared_decoder, level, duration) : NULL; if(message_decoded) { instance->signal.message = *message_decoded; instance->signal.timings_cnt = 0; instance->signal.decoded = true; if(instance->rx.received_signal_callback) instance->rx.received_signal_callback( instance->rx.received_signal_context, &instance->signal); } else { /* Skip first timing if it starts from Space */ if((instance->signal.timings_cnt == 0) && !level) { return; } if(instance->signal.timings_cnt < MAX_TIMINGS_AMOUNT) { instance->signal.raw.timings[instance->signal.timings_cnt] = duration; ++instance->signal.timings_cnt; } else { uint32_t flags_set = furi_thread_flags_set( furi_thread_get_id(instance->thread), INFRARED_WORKER_OVERRUN); furi_check(flags_set & INFRARED_WORKER_OVERRUN); instance->rx.overrun = true; } } } static int32_t infrared_worker_rx_thread(void* thread_context) { InfraredWorker* instance = thread_context; uint32_t events = 0; LevelDuration level_duration; uint32_t last_blink_time = 0; while(1) { events = furi_thread_flags_wait(INFRARED_WORKER_ALL_RX_EVENTS, 0, FuriWaitForever); furi_check(events & INFRARED_WORKER_ALL_RX_EVENTS); /* at least one caught */ if(events & INFRARED_WORKER_RX_RECEIVED) { if(!instance->rx.overrun && instance->blink_enable && ((furi_get_tick() - last_blink_time) > 80)) { last_blink_time = furi_get_tick(); notification_message(instance->notification, &sequence_blink_blue_10); } if(instance->signal.timings_cnt == 0) notification_message(instance->notification, &sequence_display_backlight_on); while(sizeof(LevelDuration) == furi_stream_buffer_receive( instance->stream, &level_duration, sizeof(LevelDuration), 0)) { if(!instance->rx.overrun) { bool level = level_duration_get_level(level_duration); uint32_t duration = level_duration_get_duration(level_duration); infrared_worker_process_timings(instance, duration, level); } } } if(events & INFRARED_WORKER_OVERRUN) { printf("#"); infrared_reset_decoder(instance->infrared_decoder); instance->signal.timings_cnt = 0; if(instance->blink_enable) notification_message(instance->notification, &sequence_set_red_255); } if(events & INFRARED_WORKER_RX_TIMEOUT_RECEIVED) { if(instance->rx.overrun) { printf("\nOVERRUN, max samples: %d\n", MAX_TIMINGS_AMOUNT); instance->rx.overrun = false; if(instance->blink_enable) notification_message(instance->notification, &sequence_reset_red); } else { infrared_worker_process_timeout(instance); } instance->signal.timings_cnt = 0; } if(events & INFRARED_WORKER_EXIT) break; } return 0; } void infrared_worker_rx_set_received_signal_callback( InfraredWorker* instance, InfraredWorkerReceivedSignalCallback callback, void* context) { furi_check(instance); instance->rx.received_signal_callback = callback; instance->rx.received_signal_context = context; } InfraredWorker* infrared_worker_alloc(void) { InfraredWorker* instance = malloc(sizeof(InfraredWorker)); instance->thread = furi_thread_alloc_ex("InfraredWorker", 2048, NULL, instance); size_t buffer_size = MAX(sizeof(InfraredWorkerTiming) * (MAX_TIMINGS_AMOUNT + 1), sizeof(LevelDuration) * MAX_TIMINGS_AMOUNT); instance->stream = furi_stream_buffer_alloc(buffer_size, sizeof(InfraredWorkerTiming)); instance->infrared_decoder = infrared_alloc_decoder(); instance->infrared_encoder = infrared_alloc_encoder(); instance->blink_enable = false; instance->decode_enable = true; instance->notification = furi_record_open(RECORD_NOTIFICATION); instance->state = InfraredWorkerStateIdle; return instance; } void infrared_worker_free(InfraredWorker* instance) { furi_check(instance); furi_check(instance->state == InfraredWorkerStateIdle); furi_record_close(RECORD_NOTIFICATION); infrared_free_decoder(instance->infrared_decoder); infrared_free_encoder(instance->infrared_encoder); furi_stream_buffer_free(instance->stream); furi_thread_free(instance->thread); free(instance); } void infrared_worker_rx_start(InfraredWorker* instance) { furi_check(instance); furi_check(instance->state == InfraredWorkerStateIdle); furi_stream_set_trigger_level(instance->stream, sizeof(LevelDuration)); furi_thread_set_callback(instance->thread, infrared_worker_rx_thread); furi_thread_start(instance->thread); furi_hal_infrared_async_rx_set_capture_isr_callback(infrared_worker_rx_callback, instance); furi_hal_infrared_async_rx_set_timeout_isr_callback( infrared_worker_rx_timeout_callback, instance); furi_hal_infrared_async_rx_start(); furi_hal_infrared_async_rx_set_timeout(INFRARED_WORKER_RX_TIMEOUT); instance->rx.overrun = false; instance->state = InfraredWorkerStateRunRx; } void infrared_worker_rx_stop(InfraredWorker* instance) { furi_check(instance); furi_check(instance->state == InfraredWorkerStateRunRx); furi_hal_infrared_async_rx_set_timeout_isr_callback(NULL, NULL); furi_hal_infrared_async_rx_set_capture_isr_callback(NULL, NULL); furi_hal_infrared_async_rx_stop(); furi_thread_flags_set(furi_thread_get_id(instance->thread), INFRARED_WORKER_EXIT); furi_thread_join(instance->thread); furi_check(furi_stream_buffer_reset(instance->stream) == FuriStatusOk); instance->state = InfraredWorkerStateIdle; } bool infrared_worker_signal_is_decoded(const InfraredWorkerSignal* signal) { furi_check(signal); return signal->decoded; } void infrared_worker_get_raw_signal( const InfraredWorkerSignal* signal, const uint32_t** timings, size_t* timings_cnt) { furi_check(signal); furi_check(timings); furi_check(timings_cnt); *timings = signal->raw.timings; *timings_cnt = signal->timings_cnt; } const InfraredMessage* infrared_worker_get_decoded_signal(const InfraredWorkerSignal* signal) { furi_check(signal); return &signal->message; } void infrared_worker_rx_enable_blink_on_receiving(InfraredWorker* instance, bool enable) { furi_check(instance); instance->blink_enable = enable; } void infrared_worker_rx_enable_signal_decoding(InfraredWorker* instance, bool enable) { furi_check(instance); instance->decode_enable = enable; } void infrared_worker_tx_start(InfraredWorker* instance) { furi_check(instance); furi_check(instance->state == InfraredWorkerStateIdle); furi_check(instance->tx.get_signal_callback); // size have to be greater than api hal infrared async tx buffer size furi_stream_set_trigger_level(instance->stream, sizeof(InfraredWorkerTiming)); furi_thread_set_callback(instance->thread, infrared_worker_tx_thread); instance->tx.steady_signal_sent = false; instance->tx.need_reinitialization = false; furi_hal_infrared_async_tx_set_data_isr_callback( infrared_worker_furi_hal_data_isr_callback, instance); furi_hal_infrared_async_tx_set_signal_sent_isr_callback( infrared_worker_furi_hal_message_sent_isr_callback, instance); instance->state = InfraredWorkerStateStartTx; furi_thread_start(instance->thread); } static void infrared_worker_furi_hal_message_sent_isr_callback(void* context) { InfraredWorker* instance = context; uint32_t flags_set = furi_thread_flags_set( furi_thread_get_id(instance->thread), INFRARED_WORKER_TX_MESSAGE_SENT); furi_check(flags_set & INFRARED_WORKER_TX_MESSAGE_SENT); } static FuriHalInfraredTxGetDataState infrared_worker_furi_hal_data_isr_callback(void* context, uint32_t* duration, bool* level) { furi_assert(context); furi_assert(duration); furi_assert(level); InfraredWorker* instance = context; InfraredWorkerTiming timing; FuriHalInfraredTxGetDataState state; if(sizeof(InfraredWorkerTiming) == furi_stream_buffer_receive(instance->stream, &timing, sizeof(InfraredWorkerTiming), 0)) { *level = timing.level; *duration = timing.duration; state = timing.state; } else { // Why bother if we crash anyway?.. *level = 0; *duration = 100; state = FuriHalInfraredTxGetDataStateDone; furi_crash(); } uint32_t flags_set = furi_thread_flags_set( furi_thread_get_id(instance->thread), INFRARED_WORKER_TX_FILL_BUFFER); furi_check(flags_set & INFRARED_WORKER_TX_FILL_BUFFER); return state; } static bool infrared_get_new_signal(InfraredWorker* instance) { bool new_signal_obtained = false; InfraredWorkerGetSignalResponse response = instance->tx.get_signal_callback(instance->tx.get_signal_context, instance); if(response == InfraredWorkerGetSignalResponseNew) { uint32_t new_tx_frequency = 0; float new_tx_duty_cycle = 0; if(instance->signal.decoded) { new_tx_frequency = infrared_get_protocol_frequency(instance->signal.message.protocol); new_tx_duty_cycle = infrared_get_protocol_duty_cycle(instance->signal.message.protocol); } else { furi_assert(instance->signal.timings_cnt > 1); new_tx_frequency = instance->signal.raw.frequency; new_tx_duty_cycle = instance->signal.raw.duty_cycle; } instance->tx.tx_raw_cnt = 0; instance->tx.need_reinitialization = (new_tx_frequency != instance->tx.frequency) || !float_is_equal(new_tx_duty_cycle, instance->tx.duty_cycle); instance->tx.frequency = new_tx_frequency; instance->tx.duty_cycle = new_tx_duty_cycle; if(instance->signal.decoded) { infrared_reset_encoder(instance->infrared_encoder, &instance->signal.message); } new_signal_obtained = true; } else if(response == InfraredWorkerGetSignalResponseSame) { new_signal_obtained = true; /* no need to reinit */ } else if(response == InfraredWorkerGetSignalResponseStop) { new_signal_obtained = false; } else { furi_crash(); } return new_signal_obtained; } static bool infrared_worker_tx_fill_buffer(InfraredWorker* instance) { bool new_data_available = true; InfraredWorkerTiming timing; InfraredStatus status = InfraredStatusError; while(!furi_stream_buffer_is_full(instance->stream) && !instance->tx.need_reinitialization && new_data_available) { if(instance->signal.decoded) { status = infrared_encode(instance->infrared_encoder, &timing.duration, &timing.level); } else { timing.duration = instance->signal.raw.timings[instance->tx.tx_raw_cnt]; /* raw always starts from Mark, but we fill it with space delay at start */ timing.level = (instance->tx.tx_raw_cnt % 2); ++instance->tx.tx_raw_cnt; if(instance->tx.tx_raw_cnt >= instance->signal.timings_cnt) { instance->tx.tx_raw_cnt = 0; status = InfraredStatusDone; } else { status = InfraredStatusOk; } } if(status == InfraredStatusError) { new_data_available = false; furi_crash(); } else if(status == InfraredStatusOk) { timing.state = FuriHalInfraredTxGetDataStateOk; } else if(status == InfraredStatusDone) { timing.state = FuriHalInfraredTxGetDataStateDone; new_data_available = infrared_get_new_signal(instance); if(instance->tx.need_reinitialization || !new_data_available) { timing.state = FuriHalInfraredTxGetDataStateLastDone; } } else { furi_crash(); } uint32_t written_size = furi_stream_buffer_send(instance->stream, &timing, sizeof(InfraredWorkerTiming), 0); furi_assert(sizeof(InfraredWorkerTiming) == written_size); (void)written_size; } return new_data_available; } static int32_t infrared_worker_tx_thread(void* thread_context) { InfraredWorker* instance = thread_context; furi_assert(instance->state == InfraredWorkerStateStartTx); furi_assert(thread_context); size_t repeats_left = instance->signal.decoded ? infrared_get_protocol_min_repeat_count(instance->signal.message.protocol) : 1; uint32_t events = 0; bool exit_pending = false; bool running = infrared_get_new_signal(instance); furi_assert(running); while(running) { switch(instance->state) { case InfraredWorkerStateStartTx: --repeats_left; /* The first message does not result in TX_MESSAGE_SENT event for some reason */ instance->tx.need_reinitialization = false; const bool new_data_available = infrared_worker_tx_fill_buffer(instance); furi_hal_infrared_async_tx_start(instance->tx.frequency, instance->tx.duty_cycle); if(!new_data_available) { instance->state = InfraredWorkerStateStopTx; } else if(instance->tx.need_reinitialization) { instance->state = InfraredWorkerStateWaitTxEnd; } else { instance->state = InfraredWorkerStateRunTx; } break; case InfraredWorkerStateStopTx: furi_hal_infrared_async_tx_stop(); running = false; break; case InfraredWorkerStateWaitTxEnd: furi_hal_infrared_async_tx_wait_termination(); instance->state = InfraredWorkerStateStartTx; events = furi_thread_flags_get(); if(events & INFRARED_WORKER_EXIT) { running = false; break; } break; case InfraredWorkerStateRunTx: events = furi_thread_flags_wait( INFRARED_WORKER_ALL_TX_EVENTS, FuriFlagWaitAny, FuriWaitForever); furi_check(events & INFRARED_WORKER_ALL_TX_EVENTS); /* at least one caught */ if(events & INFRARED_WORKER_EXIT) { exit_pending = true; } if(events & INFRARED_WORKER_TX_FILL_BUFFER) { infrared_worker_tx_fill_buffer(instance); if(instance->tx.need_reinitialization) { instance->state = InfraredWorkerStateWaitTxEnd; } } if(events & INFRARED_WORKER_TX_MESSAGE_SENT) { if(repeats_left > 0) { --repeats_left; } if(instance->tx.message_sent_callback) { instance->tx.message_sent_callback(instance->tx.message_sent_context); } } if(exit_pending && repeats_left == 0) { instance->state = InfraredWorkerStateStopTx; } break; default: furi_crash(); break; } } return 0; } void infrared_worker_tx_set_get_signal_callback( InfraredWorker* instance, InfraredWorkerGetSignalCallback callback, void* context) { furi_check(instance); instance->tx.get_signal_callback = callback; instance->tx.get_signal_context = context; } void infrared_worker_tx_set_signal_sent_callback( InfraredWorker* instance, InfraredWorkerMessageSentCallback callback, void* context) { furi_check(instance); instance->tx.message_sent_callback = callback; instance->tx.message_sent_context = context; } void infrared_worker_tx_stop(InfraredWorker* instance) { furi_check(instance); furi_check(instance->state != InfraredWorkerStateRunRx); furi_thread_flags_set(furi_thread_get_id(instance->thread), INFRARED_WORKER_EXIT); furi_thread_join(instance->thread); furi_hal_infrared_async_tx_set_data_isr_callback(NULL, NULL); furi_hal_infrared_async_tx_set_signal_sent_isr_callback(NULL, NULL); instance->signal.timings_cnt = 0; furi_check(furi_stream_buffer_reset(instance->stream) == FuriStatusOk); instance->state = InfraredWorkerStateIdle; } void infrared_worker_set_decoded_signal(InfraredWorker* instance, const InfraredMessage* message) { furi_check(instance); furi_check(message); instance->signal.decoded = true; instance->signal.message = *message; } void infrared_worker_set_raw_signal( InfraredWorker* instance, const uint32_t* timings, size_t timings_cnt, uint32_t frequency, float duty_cycle) { furi_check(instance); furi_check(timings); furi_check(timings_cnt > 0); furi_check((frequency <= INFRARED_MAX_FREQUENCY) && (frequency >= INFRARED_MIN_FREQUENCY)); furi_check((duty_cycle <= 1.0f) && (duty_cycle > 0.0f)); size_t max_copy_num = COUNT_OF(instance->signal.raw.timings) - 1; furi_check(timings_cnt <= max_copy_num); instance->signal.raw.frequency = frequency; instance->signal.raw.duty_cycle = duty_cycle; instance->signal.raw.timings[0] = INFRARED_RAW_TX_TIMING_DELAY_US; memcpy(&instance->signal.raw.timings[1], timings, timings_cnt * sizeof(uint32_t)); instance->signal.decoded = false; instance->signal.timings_cnt = timings_cnt + 1; } InfraredWorkerGetSignalResponse infrared_worker_tx_get_signal_steady_callback(void* context, InfraredWorker* instance) { UNUSED(context); furi_check(instance); InfraredWorkerGetSignalResponse response = instance->tx.steady_signal_sent ? InfraredWorkerGetSignalResponseSame : InfraredWorkerGetSignalResponseNew; instance->tx.steady_signal_sent = true; return response; }
23,014
C
.c
529
35.448015
108
0.667456
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,482
infrared.c
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/infrared.c
#include "infrared.h" #include <stdlib.h> #include <string.h> #include <core/check.h> #include <core/common_defines.h> #include "nec/infrared_protocol_nec.h" #include "samsung/infrared_protocol_samsung.h" #include "rc5/infrared_protocol_rc5.h" #include "rc6/infrared_protocol_rc6.h" #include "sirc/infrared_protocol_sirc.h" #include "kaseikyo/infrared_protocol_kaseikyo.h" #include "rca/infrared_protocol_rca.h" #include "pioneer/infrared_protocol_pioneer.h" typedef struct { InfraredAlloc alloc; InfraredDecode decode; InfraredDecoderReset reset; InfraredFree free; InfraredDecoderCheckReady check_ready; } InfraredDecoders; typedef struct { InfraredAlloc alloc; InfraredEncode encode; InfraredEncoderReset reset; InfraredFree free; } InfraredEncoders; struct InfraredDecoderHandler { void** ctx; }; struct InfraredEncoderHandler { void* handler; const InfraredEncoders* encoder; }; typedef struct { InfraredEncoders encoder; InfraredDecoders decoder; InfraredGetProtocolVariant get_protocol_variant; } InfraredEncoderDecoder; static const InfraredEncoderDecoder infrared_encoder_decoder[] = { { .decoder = {.alloc = infrared_decoder_nec_alloc, .decode = infrared_decoder_nec_decode, .reset = infrared_decoder_nec_reset, .check_ready = infrared_decoder_nec_check_ready, .free = infrared_decoder_nec_free}, .encoder = {.alloc = infrared_encoder_nec_alloc, .encode = infrared_encoder_nec_encode, .reset = infrared_encoder_nec_reset, .free = infrared_encoder_nec_free}, .get_protocol_variant = infrared_protocol_nec_get_variant, }, { .decoder = {.alloc = infrared_decoder_samsung32_alloc, .decode = infrared_decoder_samsung32_decode, .reset = infrared_decoder_samsung32_reset, .check_ready = infrared_decoder_samsung32_check_ready, .free = infrared_decoder_samsung32_free}, .encoder = {.alloc = infrared_encoder_samsung32_alloc, .encode = infrared_encoder_samsung32_encode, .reset = infrared_encoder_samsung32_reset, .free = infrared_encoder_samsung32_free}, .get_protocol_variant = infrared_protocol_samsung32_get_variant, }, { .decoder = {.alloc = infrared_decoder_rc5_alloc, .decode = infrared_decoder_rc5_decode, .reset = infrared_decoder_rc5_reset, .check_ready = infrared_decoder_rc5_check_ready, .free = infrared_decoder_rc5_free}, .encoder = {.alloc = infrared_encoder_rc5_alloc, .encode = infrared_encoder_rc5_encode, .reset = infrared_encoder_rc5_reset, .free = infrared_encoder_rc5_free}, .get_protocol_variant = infrared_protocol_rc5_get_variant, }, { .decoder = {.alloc = infrared_decoder_rc6_alloc, .decode = infrared_decoder_rc6_decode, .reset = infrared_decoder_rc6_reset, .check_ready = infrared_decoder_rc6_check_ready, .free = infrared_decoder_rc6_free}, .encoder = {.alloc = infrared_encoder_rc6_alloc, .encode = infrared_encoder_rc6_encode, .reset = infrared_encoder_rc6_reset, .free = infrared_encoder_rc6_free}, .get_protocol_variant = infrared_protocol_rc6_get_variant, }, { .decoder = {.alloc = infrared_decoder_sirc_alloc, .decode = infrared_decoder_sirc_decode, .reset = infrared_decoder_sirc_reset, .check_ready = infrared_decoder_sirc_check_ready, .free = infrared_decoder_sirc_free}, .encoder = {.alloc = infrared_encoder_sirc_alloc, .encode = infrared_encoder_sirc_encode, .reset = infrared_encoder_sirc_reset, .free = infrared_encoder_sirc_free}, .get_protocol_variant = infrared_protocol_sirc_get_variant, }, { .decoder = {.alloc = infrared_decoder_pioneer_alloc, .decode = infrared_decoder_pioneer_decode, .reset = infrared_decoder_pioneer_reset, .check_ready = infrared_decoder_pioneer_check_ready, .free = infrared_decoder_pioneer_free}, .encoder = {.alloc = infrared_encoder_pioneer_alloc, .encode = infrared_encoder_pioneer_encode, .reset = infrared_encoder_pioneer_reset, .free = infrared_encoder_pioneer_free}, .get_protocol_variant = infrared_protocol_pioneer_get_variant, }, { .decoder = {.alloc = infrared_decoder_kaseikyo_alloc, .decode = infrared_decoder_kaseikyo_decode, .reset = infrared_decoder_kaseikyo_reset, .check_ready = infrared_decoder_kaseikyo_check_ready, .free = infrared_decoder_kaseikyo_free}, .encoder = {.alloc = infrared_encoder_kaseikyo_alloc, .encode = infrared_encoder_kaseikyo_encode, .reset = infrared_encoder_kaseikyo_reset, .free = infrared_encoder_kaseikyo_free}, .get_protocol_variant = infrared_protocol_kaseikyo_get_variant, }, { .decoder = {.alloc = infrared_decoder_rca_alloc, .decode = infrared_decoder_rca_decode, .reset = infrared_decoder_rca_reset, .check_ready = infrared_decoder_rca_check_ready, .free = infrared_decoder_rca_free}, .encoder = {.alloc = infrared_encoder_rca_alloc, .encode = infrared_encoder_rca_encode, .reset = infrared_encoder_rca_reset, .free = infrared_encoder_rca_free}, .get_protocol_variant = infrared_protocol_rca_get_variant, }, }; static int infrared_find_index_by_protocol(InfraredProtocol protocol); static const InfraredProtocolVariant* infrared_get_variant_by_protocol(InfraredProtocol protocol); const InfraredMessage* infrared_decode(InfraredDecoderHandler* handler, bool level, uint32_t duration) { furi_check(handler); InfraredMessage* message = NULL; InfraredMessage* result = NULL; for(size_t i = 0; i < COUNT_OF(infrared_encoder_decoder); ++i) { if(infrared_encoder_decoder[i].decoder.decode) { message = infrared_encoder_decoder[i].decoder.decode(handler->ctx[i], level, duration); if(!result && message) { result = message; } } } return result; } InfraredDecoderHandler* infrared_alloc_decoder(void) { InfraredDecoderHandler* handler = malloc(sizeof(InfraredDecoderHandler)); handler->ctx = malloc(sizeof(void*) * COUNT_OF(infrared_encoder_decoder)); for(size_t i = 0; i < COUNT_OF(infrared_encoder_decoder); ++i) { handler->ctx[i] = 0; if(infrared_encoder_decoder[i].decoder.alloc) handler->ctx[i] = infrared_encoder_decoder[i].decoder.alloc(); } infrared_reset_decoder(handler); return handler; } void infrared_free_decoder(InfraredDecoderHandler* handler) { furi_check(handler); furi_check(handler->ctx); for(size_t i = 0; i < COUNT_OF(infrared_encoder_decoder); ++i) { if(infrared_encoder_decoder[i].decoder.free) infrared_encoder_decoder[i].decoder.free(handler->ctx[i]); } free(handler->ctx); free(handler); } void infrared_reset_decoder(InfraredDecoderHandler* handler) { furi_check(handler); for(size_t i = 0; i < COUNT_OF(infrared_encoder_decoder); ++i) { if(infrared_encoder_decoder[i].decoder.reset) infrared_encoder_decoder[i].decoder.reset(handler->ctx[i]); } } const InfraredMessage* infrared_check_decoder_ready(InfraredDecoderHandler* handler) { furi_check(handler); InfraredMessage* message = NULL; InfraredMessage* result = NULL; for(size_t i = 0; i < COUNT_OF(infrared_encoder_decoder); ++i) { if(infrared_encoder_decoder[i].decoder.check_ready) { message = infrared_encoder_decoder[i].decoder.check_ready(handler->ctx[i]); if(!result && message) { result = message; } } } return result; } InfraredEncoderHandler* infrared_alloc_encoder(void) { InfraredEncoderHandler* handler = malloc(sizeof(InfraredEncoderHandler)); handler->handler = NULL; handler->encoder = NULL; return handler; } void infrared_free_encoder(InfraredEncoderHandler* handler) { furi_check(handler); const InfraredEncoders* encoder = handler->encoder; if(encoder || handler->handler) { furi_check(encoder); furi_check(handler->handler); furi_check(encoder->free); encoder->free(handler->handler); } free(handler); } static int infrared_find_index_by_protocol(InfraredProtocol protocol) { for(size_t i = 0; i < COUNT_OF(infrared_encoder_decoder); ++i) { if(infrared_encoder_decoder[i].get_protocol_variant(protocol)) { return i; } } return -1; } void infrared_reset_encoder(InfraredEncoderHandler* handler, const InfraredMessage* message) { furi_check(handler); furi_check(message); int index = infrared_find_index_by_protocol(message->protocol); furi_check(index >= 0); const InfraredEncoders* required_encoder = &infrared_encoder_decoder[index].encoder; furi_check(required_encoder); furi_check(required_encoder->reset); furi_check(required_encoder->alloc); /* Realloc encoder if different protocol set */ if(required_encoder != handler->encoder) { if(handler->handler != NULL) { furi_check(handler->encoder->free); handler->encoder->free(handler->handler); } handler->encoder = required_encoder; handler->handler = handler->encoder->alloc(); } handler->encoder->reset(handler->handler, message); } InfraredStatus infrared_encode(InfraredEncoderHandler* handler, uint32_t* duration, bool* level) { furi_check(handler); furi_check(duration); furi_check(level); const InfraredEncoders* encoder = handler->encoder; furi_check(encoder); furi_check(encoder->encode); InfraredStatus status = encoder->encode(handler->handler, duration, level); furi_check(status != InfraredStatusError); return status; } bool infrared_is_protocol_valid(InfraredProtocol protocol) { return infrared_find_index_by_protocol(protocol) >= 0; } InfraredProtocol infrared_get_protocol_by_name(const char* protocol_name) { furi_check(protocol_name); for(InfraredProtocol protocol = 0; protocol < InfraredProtocolMAX; ++protocol) { const char* name = infrared_get_protocol_name(protocol); if(!strcmp(name, protocol_name)) return protocol; } return InfraredProtocolUnknown; } static const InfraredProtocolVariant* infrared_get_variant_by_protocol(InfraredProtocol protocol) { int index = infrared_find_index_by_protocol(protocol); const InfraredProtocolVariant* variant = NULL; if(index >= 0) { variant = infrared_encoder_decoder[index].get_protocol_variant(protocol); } furi_check(variant); return variant; } const char* infrared_get_protocol_name(InfraredProtocol protocol) { return infrared_get_variant_by_protocol(protocol)->name; } uint8_t infrared_get_protocol_address_length(InfraredProtocol protocol) { return infrared_get_variant_by_protocol(protocol)->address_length; } uint8_t infrared_get_protocol_command_length(InfraredProtocol protocol) { return infrared_get_variant_by_protocol(protocol)->command_length; } uint32_t infrared_get_protocol_frequency(InfraredProtocol protocol) { return infrared_get_variant_by_protocol(protocol)->frequency; } float infrared_get_protocol_duty_cycle(InfraredProtocol protocol) { return infrared_get_variant_by_protocol(protocol)->duty_cycle; } size_t infrared_get_protocol_min_repeat_count(InfraredProtocol protocol) { return infrared_get_variant_by_protocol(protocol)->repeat_count; }
12,251
C
.c
305
32.8
99
0.666863
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,483
infrared_protocol_pioneer.c
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/pioneer/infrared_protocol_pioneer.c
#include "infrared_protocol_pioneer_i.h" const InfraredCommonProtocolSpec infrared_protocol_pioneer = { .timings = { .preamble_mark = INFRARED_PIONEER_PREAMBLE_MARK, .preamble_space = INFRARED_PIONEER_PREAMBLE_SPACE, .bit1_mark = INFRARED_PIONEER_BIT1_MARK, .bit1_space = INFRARED_PIONEER_BIT1_SPACE, .bit0_mark = INFRARED_PIONEER_BIT0_MARK, .bit0_space = INFRARED_PIONEER_BIT0_SPACE, .preamble_tolerance = INFRARED_PIONEER_PREAMBLE_TOLERANCE, .bit_tolerance = INFRARED_PIONEER_BIT_TOLERANCE, .silence_time = INFRARED_PIONEER_SILENCE, .min_split_time = INFRARED_PIONEER_MIN_SPLIT_TIME, }, .databit_len[0] = 33, .databit_len[1] = 32, .decode = infrared_common_decode_pdwm, .encode = infrared_common_encode_pdwm, .interpret = infrared_decoder_pioneer_interpret, .decode_repeat = NULL, .encode_repeat = infrared_encoder_pioneer_encode_repeat, }; static const InfraredProtocolVariant infrared_protocol_variant_pioneer = { .name = "Pioneer", .address_length = 8, .command_length = 8, .frequency = INFRARED_PIONEER_CARRIER_FREQUENCY, .duty_cycle = INFRARED_PIONEER_DUTY_CYCLE, .repeat_count = INFRARED_PIONEER_REPEAT_COUNT_MIN, }; const InfraredProtocolVariant* infrared_protocol_pioneer_get_variant(InfraredProtocol protocol) { if(protocol == InfraredProtocolPioneer) return &infrared_protocol_variant_pioneer; else return NULL; }
1,545
C
.c
37
34.837838
97
0.686379
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,484
infrared_protocol_pioneer.h
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/pioneer/infrared_protocol_pioneer.h
#pragma once #include "../infrared_i.h" /*************************************************************************************************** * Pioneer SR protocol description * http://www.adrian-kingston.com/IRFormatPioneer.htm **************************************************************************************************** * Preamble Preamble Pulse Width Modulation Pause Entirely repeat * mark space up to period message.. * * 8500 4250 33 bits (500, 1500) ...26000 8500 4250 * __________ _ _ _ _ _ _ _ _ _ _ _ _ _ __________ _ _ * ____ __________ _ _ _ __ __ __ _ _ __ __ _ _ ____________________ __________ _ * * In 33 bits of data there is: * - 8 bits address * - 8 bits address inverse * - 8 bits command * - 8 bits command inverse * - 1 stop bit ***************************************************************************************************/ void* infrared_decoder_pioneer_alloc(void); void infrared_decoder_pioneer_reset(void* decoder); InfraredMessage* infrared_decoder_pioneer_check_ready(void* decoder); void infrared_decoder_pioneer_free(void* decoder); InfraredMessage* infrared_decoder_pioneer_decode(void* decoder, bool level, uint32_t duration); void* infrared_encoder_pioneer_alloc(void); void infrared_encoder_pioneer_reset(void* encoder_ptr, const InfraredMessage* message); void infrared_encoder_pioneer_free(void* decoder); InfraredStatus infrared_encoder_pioneer_encode(void* encoder_ptr, uint32_t* duration, bool* polarity); const InfraredProtocolVariant* infrared_protocol_pioneer_get_variant(InfraredProtocol protocol);
1,766
C
.c
31
55.677419
100
0.504624
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,485
infrared_protocol_pioneer_i.h
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/pioneer/infrared_protocol_pioneer_i.h
#pragma once #include "../common/infrared_common_i.h" #define INFRARED_PIONEER_CARRIER_FREQUENCY 40000 #define INFRARED_PIONEER_DUTY_CYCLE 0.33 #define INFRARED_PIONEER_PREAMBLE_MARK 8500 #define INFRARED_PIONEER_PREAMBLE_SPACE 4225 #define INFRARED_PIONEER_BIT1_MARK 500 #define INFRARED_PIONEER_BIT1_SPACE 1500 #define INFRARED_PIONEER_BIT0_MARK 500 #define INFRARED_PIONEER_BIT0_SPACE 500 #define INFRARED_PIONEER_PREAMBLE_TOLERANCE 200 // us #define INFRARED_PIONEER_BIT_TOLERANCE 120 // us #define INFRARED_PIONEER_SILENCE 26000 #define INFRARED_PIONEER_MIN_SPLIT_TIME (INFRARED_PIONEER_SILENCE) #define INFRARED_PIONEER_REPEAT_COUNT_MIN 2 extern const InfraredCommonProtocolSpec infrared_protocol_pioneer; bool infrared_decoder_pioneer_interpret(InfraredCommonDecoder* decoder); InfraredStatus infrared_encoder_pioneer_encode_repeat( InfraredCommonEncoder* encoder, uint32_t* duration, bool* level);
996
C
.c
21
45.666667
72
0.77034
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,486
infrared_encoder_pioneer.c
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/pioneer/infrared_encoder_pioneer.c
#include "infrared_protocol_pioneer_i.h" #include <core/check.h> void infrared_encoder_pioneer_reset(void* encoder_ptr, const InfraredMessage* message) { furi_assert(encoder_ptr); furi_assert(message); InfraredCommonEncoder* encoder = encoder_ptr; infrared_common_encoder_reset(encoder); uint8_t* data = encoder->data; if(message->protocol == InfraredProtocolPioneer) { data[0] = message->address & 0xFF; data[1] = ~(message->address & 0xFF); data[2] = message->command & 0xFF; data[3] = ~(message->command & 0xFF); data[4] = 0; encoder->bits_to_encode = encoder->protocol->databit_len[0]; } else { furi_crash(); } } void* infrared_encoder_pioneer_alloc(void) { return infrared_common_encoder_alloc(&infrared_protocol_pioneer); } void infrared_encoder_pioneer_free(void* encoder_ptr) { infrared_common_encoder_free(encoder_ptr); } InfraredStatus infrared_encoder_pioneer_encode_repeat( InfraredCommonEncoder* encoder, uint32_t* duration, bool* level) { furi_assert(encoder); *duration = INFRARED_PIONEER_SILENCE; *level = false; encoder->timings_sum = 0; encoder->timings_encoded = 1; encoder->bits_encoded = 0; encoder->state = InfraredCommonEncoderStatePreamble; return InfraredStatusOk; } InfraredStatus infrared_encoder_pioneer_encode(void* encoder_ptr, uint32_t* duration, bool* level) { InfraredCommonEncoder* encoder = encoder_ptr; InfraredStatus status = infrared_common_encode(encoder, duration, level); if((status == InfraredStatusOk) && (encoder->bits_encoded == encoder->bits_to_encode)) { furi_assert(!*level); status = InfraredStatusDone; encoder->state = InfraredCommonEncoderStateEncodeRepeat; } return status; }
1,829
C
.c
49
32.244898
92
0.700792
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,487
infrared_decoder_pioneer.c
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/pioneer/infrared_decoder_pioneer.c
#include "infrared_protocol_pioneer_i.h" #include <core/check.h> InfraredMessage* infrared_decoder_pioneer_check_ready(void* ctx) { return infrared_common_decoder_check_ready(ctx); } bool infrared_decoder_pioneer_interpret(InfraredCommonDecoder* decoder) { furi_assert(decoder); uint32_t* data = (void*)&decoder->data[0]; uint8_t address = 0; uint8_t command = 0; InfraredProtocol protocol = InfraredProtocolUnknown; if(decoder->databit_cnt == decoder->protocol->databit_len[0] || decoder->databit_cnt == decoder->protocol->databit_len[1]) { address = *data & 0xFF; uint8_t real_address_checksum = ~address; uint8_t address_checksum = (*data >> 8) & 0xFF; command = (*data >> 16) & 0xFF; uint8_t real_command_checksum = ~command; uint8_t command_checksum = (*data >> 24) & 0xFF; if(address_checksum != real_address_checksum) { return false; } if(command_checksum != real_command_checksum) { return false; } protocol = InfraredProtocolPioneer; } else { return false; } decoder->message.protocol = protocol; decoder->message.address = address; decoder->message.command = command; decoder->message.repeat = false; return true; } void* infrared_decoder_pioneer_alloc(void) { return infrared_common_decoder_alloc(&infrared_protocol_pioneer); } InfraredMessage* infrared_decoder_pioneer_decode(void* decoder, bool level, uint32_t duration) { return infrared_common_decode(decoder, level, duration); } void infrared_decoder_pioneer_free(void* decoder) { infrared_common_decoder_free(decoder); } void infrared_decoder_pioneer_reset(void* decoder) { infrared_common_decoder_reset(decoder); }
1,792
C
.c
47
32.680851
96
0.687608
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,488
infrared_protocol_sirc.c
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/sirc/infrared_protocol_sirc.c
#include "infrared_protocol_sirc_i.h" const InfraredCommonProtocolSpec infrared_protocol_sirc = { .timings = { .preamble_mark = INFRARED_SIRC_PREAMBLE_MARK, .preamble_space = INFRARED_SIRC_PREAMBLE_SPACE, .bit1_mark = INFRARED_SIRC_BIT1_MARK, .bit1_space = INFRARED_SIRC_BIT1_SPACE, .bit0_mark = INFRARED_SIRC_BIT0_MARK, .bit0_space = INFRARED_SIRC_BIT0_SPACE, .preamble_tolerance = INFRARED_SIRC_PREAMBLE_TOLERANCE, .bit_tolerance = INFRARED_SIRC_BIT_TOLERANCE, .silence_time = INFRARED_SIRC_SILENCE, .min_split_time = INFRARED_SIRC_MIN_SPLIT_TIME, }, .databit_len[0] = 20, .databit_len[1] = 15, .databit_len[2] = 12, .decode = infrared_common_decode_pdwm, .encode = infrared_common_encode_pdwm, .interpret = infrared_decoder_sirc_interpret, .decode_repeat = NULL, .encode_repeat = infrared_encoder_sirc_encode_repeat, }; static const InfraredProtocolVariant infrared_protocol_variant_sirc = { .name = "SIRC", .address_length = 5, .command_length = 7, .frequency = INFRARED_SIRC_CARRIER_FREQUENCY, .duty_cycle = INFRARED_SIRC_DUTY_CYCLE, .repeat_count = INFRARED_SIRC_REPEAT_COUNT_MIN, }; static const InfraredProtocolVariant infrared_protocol_variant_sirc15 = { .name = "SIRC15", .address_length = 8, .command_length = 7, .frequency = INFRARED_SIRC_CARRIER_FREQUENCY, .duty_cycle = INFRARED_SIRC_DUTY_CYCLE, .repeat_count = INFRARED_SIRC_REPEAT_COUNT_MIN, }; static const InfraredProtocolVariant infrared_protocol_variant_sirc20 = { .name = "SIRC20", .address_length = 13, .command_length = 7, .frequency = INFRARED_SIRC_CARRIER_FREQUENCY, .duty_cycle = INFRARED_SIRC_DUTY_CYCLE, .repeat_count = INFRARED_SIRC_REPEAT_COUNT_MIN, }; const InfraredProtocolVariant* infrared_protocol_sirc_get_variant(InfraredProtocol protocol) { if(protocol == InfraredProtocolSIRC) return &infrared_protocol_variant_sirc; else if(protocol == InfraredProtocolSIRC15) return &infrared_protocol_variant_sirc15; else if(protocol == InfraredProtocolSIRC20) return &infrared_protocol_variant_sirc20; else return NULL; }
2,294
C
.c
58
33.431034
94
0.687136
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,489
infrared_encoder_sirc.c
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/sirc/infrared_encoder_sirc.c
#include "infrared_protocol_sirc_i.h" #include <core/check.h> void infrared_encoder_sirc_reset(void* encoder_ptr, const InfraredMessage* message) { furi_assert(encoder_ptr); furi_assert(message); InfraredCommonEncoder* encoder = encoder_ptr; infrared_common_encoder_reset(encoder); uint32_t* data = (void*)encoder->data; if(message->protocol == InfraredProtocolSIRC) { *data = (message->command & 0x7F); *data |= (message->address & 0x1F) << 7; encoder->bits_to_encode = 12; } else if(message->protocol == InfraredProtocolSIRC15) { *data = (message->command & 0x7F); *data |= (message->address & 0xFF) << 7; encoder->bits_to_encode = 15; } else if(message->protocol == InfraredProtocolSIRC20) { *data = (message->command & 0x7F); *data |= (message->address & 0x1FFF) << 7; encoder->bits_to_encode = 20; } else { furi_crash(); } } InfraredStatus infrared_encoder_sirc_encode_repeat( InfraredCommonEncoder* encoder, uint32_t* duration, bool* level) { furi_assert(encoder); furi_assert(encoder->timings_encoded == (1u + 2 + encoder->bits_to_encode * 2 - 1)); furi_assert(encoder->timings_sum < INFRARED_SIRC_REPEAT_PERIOD); *duration = INFRARED_SIRC_REPEAT_PERIOD - encoder->timings_sum; *level = false; encoder->timings_sum = 0; encoder->timings_encoded = 1; encoder->bits_encoded = 0; encoder->state = InfraredCommonEncoderStatePreamble; return InfraredStatusOk; } void* infrared_encoder_sirc_alloc(void) { return infrared_common_encoder_alloc(&infrared_protocol_sirc); } void infrared_encoder_sirc_free(void* encoder_ptr) { infrared_common_encoder_free(encoder_ptr); } InfraredStatus infrared_encoder_sirc_encode(void* encoder_ptr, uint32_t* duration, bool* level) { InfraredCommonEncoder* encoder = encoder_ptr; InfraredStatus status = infrared_common_encode(encoder, duration, level); if((status == InfraredStatusOk) && (encoder->bits_encoded == encoder->bits_to_encode)) { furi_assert(!*level); status = InfraredStatusDone; encoder->state = InfraredCommonEncoderStateEncodeRepeat; } return status; }
2,240
C
.c
55
35.418182
97
0.685083
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,490
infrared_protocol_sirc_i.h
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/sirc/infrared_protocol_sirc_i.h
#pragma once #include "../common/infrared_common_i.h" #define INFRARED_SIRC_CARRIER_FREQUENCY 40000 #define INFRARED_SIRC_DUTY_CYCLE 0.33 #define INFRARED_SIRC_PREAMBLE_MARK 2400 #define INFRARED_SIRC_PREAMBLE_SPACE 600 #define INFRARED_SIRC_BIT1_MARK 1200 #define INFRARED_SIRC_BIT1_SPACE 600 #define INFRARED_SIRC_BIT0_MARK 600 #define INFRARED_SIRC_BIT0_SPACE 600 #define INFRARED_SIRC_PREAMBLE_TOLERANCE 200 // us #define INFRARED_SIRC_BIT_TOLERANCE 120 // us #define INFRARED_SIRC_SILENCE 10000 #define INFRARED_SIRC_MIN_SPLIT_TIME (INFRARED_SIRC_SILENCE - 1000) #define INFRARED_SIRC_REPEAT_PERIOD 45000 #define INFRARED_SIRC_REPEAT_COUNT_MIN 3 extern const InfraredCommonProtocolSpec infrared_protocol_sirc; bool infrared_decoder_sirc_interpret(InfraredCommonDecoder* decoder); InfraredStatus infrared_encoder_sirc_encode_repeat( InfraredCommonEncoder* encoder, uint32_t* duration, bool* level);
998
C
.c
22
43.636364
71
0.756173
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,491
infrared_decoder_sirc.c
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/sirc/infrared_decoder_sirc.c
#include "infrared_protocol_sirc_i.h" #include <core/check.h> InfraredMessage* infrared_decoder_sirc_check_ready(void* ctx) { return infrared_common_decoder_check_ready(ctx); } bool infrared_decoder_sirc_interpret(InfraredCommonDecoder* decoder) { furi_assert(decoder); uint32_t* data = (void*)&decoder->data[0]; uint16_t address = 0; uint8_t command = 0; InfraredProtocol protocol = InfraredProtocolUnknown; if(decoder->databit_cnt == 12) { address = (*data >> 7) & 0x1F; command = *data & 0x7F; protocol = InfraredProtocolSIRC; } else if(decoder->databit_cnt == 15) { address = (*data >> 7) & 0xFF; command = *data & 0x7F; protocol = InfraredProtocolSIRC15; } else if(decoder->databit_cnt == 20) { address = (*data >> 7) & 0x1FFF; command = *data & 0x7F; protocol = InfraredProtocolSIRC20; } else { return false; } decoder->message.protocol = protocol; decoder->message.address = address; decoder->message.command = command; /* SIRC doesn't specify repeat detection */ decoder->message.repeat = false; return true; } void* infrared_decoder_sirc_alloc(void) { return infrared_common_decoder_alloc(&infrared_protocol_sirc); } InfraredMessage* infrared_decoder_sirc_decode(void* decoder, bool level, uint32_t duration) { return infrared_common_decode(decoder, level, duration); } void infrared_decoder_sirc_free(void* decoder) { infrared_common_decoder_free(decoder); } void infrared_decoder_sirc_reset(void* decoder) { infrared_common_decoder_reset(decoder); }
1,635
C
.c
45
31.466667
93
0.687342
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,492
infrared_protocol_sirc.h
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/sirc/infrared_protocol_sirc.h
#pragma once #include "../infrared_i.h" /*************************************************************************************************** * Sony SIRC protocol description * https://www.sbprojects.net/knowledge/ir/sirc.php * http://picprojects.org.uk/ **************************************************************************************************** * Preamble Preamble Pulse Width Modulation Pause Entirely repeat * mark space up to period message.. * * 2400 600 12/15/20 bits (600,1200) ...45000 2400 600 * __________ _ _ _ _ _ _ _ _ _ _ _ _ _ __________ _ _ * ____ __________ _ _ _ __ __ __ _ _ __ __ _ _ ____________________ __________ _ * | command | address | * SIRC | 7b LSB | 5b LSB | * SIRC15 | 7b LSB | 8b LSB | * SIRC20 | 7b LSB | 13b LSB | * * No way to determine either next message is repeat or not, * so recognize only fact message received. Sony remotes always send at least 3 messages. * Assume 8 last extended bits for SIRC20 are address bits. ***************************************************************************************************/ void* infrared_decoder_sirc_alloc(void); void infrared_decoder_sirc_reset(void* decoder); InfraredMessage* infrared_decoder_sirc_check_ready(void* decoder); void infrared_decoder_sirc_free(void* decoder); InfraredMessage* infrared_decoder_sirc_decode(void* decoder, bool level, uint32_t duration); void* infrared_encoder_sirc_alloc(void); void infrared_encoder_sirc_reset(void* encoder_ptr, const InfraredMessage* message); void infrared_encoder_sirc_free(void* decoder); InfraredStatus infrared_encoder_sirc_encode(void* encoder_ptr, uint32_t* duration, bool* polarity); const InfraredProtocolVariant* infrared_protocol_sirc_get_variant(InfraredProtocol protocol);
2,061
C
.c
32
63.25
100
0.491107
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,493
infrared_protocol_rc5_i.h
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/rc5/infrared_protocol_rc5_i.h
#pragma once #include "../common/infrared_common_i.h" #define INFRARED_RC5_CARRIER_FREQUENCY 36000 #define INFRARED_RC5_DUTY_CYCLE 0.33 #define INFRARED_RC5_PREAMBLE_MARK 0 #define INFRARED_RC5_PREAMBLE_SPACE 0 #define INFRARED_RC5_BIT 888 // half of time-quant for 1 bit #define INFRARED_RC5_PREAMBLE_TOLERANCE 200 // us #define INFRARED_RC5_BIT_TOLERANCE 120 // us /* protocol allows 2700 silence, but it is hard to send 1 message without repeat */ #define INFRARED_RC5_SILENCE (2700 * 10) #define INFRARED_RC5_MIN_SPLIT_TIME 2700 #define INFRARED_RC5_REPEAT_COUNT_MIN 1 extern const InfraredCommonProtocolSpec infrared_protocol_rc5; bool infrared_decoder_rc5_interpret(InfraredCommonDecoder* decoder);
763
C
.c
15
49.533333
83
0.751009
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,494
infrared_protocol_rc5.c
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/rc5/infrared_protocol_rc5.c
#include "infrared_protocol_rc5_i.h" const InfraredCommonProtocolSpec infrared_protocol_rc5 = { .timings = { .preamble_mark = 0, .preamble_space = 0, .bit1_mark = INFRARED_RC5_BIT, .preamble_tolerance = 0, .bit_tolerance = INFRARED_RC5_BIT_TOLERANCE, .silence_time = INFRARED_RC5_SILENCE, .min_split_time = INFRARED_RC5_MIN_SPLIT_TIME, }, .databit_len[0] = 1 + 1 + 1 + 5 + 6, // start_bit + start_bit/command_bit + toggle_bit + 5 address + 6 command .manchester_start_from_space = true, .decode = infrared_common_decode_manchester, .encode = infrared_common_encode_manchester, .interpret = infrared_decoder_rc5_interpret, .decode_repeat = NULL, .encode_repeat = NULL, }; static const InfraredProtocolVariant infrared_protocol_variant_rc5 = { .name = "RC5", .address_length = 5, .command_length = 6, .frequency = INFRARED_RC5_CARRIER_FREQUENCY, .duty_cycle = INFRARED_RC5_DUTY_CYCLE, .repeat_count = INFRARED_RC5_REPEAT_COUNT_MIN, }; static const InfraredProtocolVariant infrared_protocol_variant_rc5x = { .name = "RC5X", .address_length = 5, .command_length = 7, .frequency = INFRARED_RC5_CARRIER_FREQUENCY, .duty_cycle = INFRARED_RC5_DUTY_CYCLE, .repeat_count = INFRARED_RC5_REPEAT_COUNT_MIN, }; const InfraredProtocolVariant* infrared_protocol_rc5_get_variant(InfraredProtocol protocol) { if(protocol == InfraredProtocolRC5) return &infrared_protocol_variant_rc5; else if(protocol == InfraredProtocolRC5X) return &infrared_protocol_variant_rc5x; else return NULL; }
1,710
C
.c
45
31.622222
98
0.664058
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,495
infrared_encoder_rc5.c
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/rc5/infrared_encoder_rc5.c
#include "infrared_protocol_rc5_i.h" #include <stdlib.h> #include <core/check.h> typedef struct InfraredEncoderRC5 { InfraredCommonEncoder* common_encoder; bool toggle_bit; } InfraredEncoderRC5; void infrared_encoder_rc5_reset(void* encoder_ptr, const InfraredMessage* message) { furi_assert(encoder_ptr); InfraredEncoderRC5* encoder = encoder_ptr; InfraredCommonEncoder* common_encoder = encoder->common_encoder; infrared_common_encoder_reset(common_encoder); uint32_t* data = (void*)common_encoder->data; /* RC5 */ *data |= 0x01; // start bit if(message->protocol == InfraredProtocolRC5) { *data |= 0x02; // start bit } *data |= encoder->toggle_bit ? 0x04 : 0; *data |= (reverse(message->address) >> 3) << 3; /* address 5 bit */ *data |= (reverse(message->command) >> 2) << 8; /* command 6 bit */ common_encoder->data[0] = ~common_encoder->data[0]; common_encoder->data[1] = ~common_encoder->data[1]; common_encoder->bits_to_encode = common_encoder->protocol->databit_len[0]; encoder->toggle_bit ^= 1; } InfraredStatus infrared_encoder_rc5_encode(void* encoder_ptr, uint32_t* duration, bool* level) { InfraredEncoderRC5* encoder = encoder_ptr; return infrared_common_encode(encoder->common_encoder, duration, level); } void* infrared_encoder_rc5_alloc(void) { InfraredEncoderRC5* encoder = malloc(sizeof(InfraredEncoderRC5)); encoder->common_encoder = infrared_common_encoder_alloc(&infrared_protocol_rc5); encoder->toggle_bit = false; return encoder; } void infrared_encoder_rc5_free(void* encoder_ptr) { furi_assert(encoder_ptr); InfraredEncoderRC5* encoder = encoder_ptr; free(encoder->common_encoder); free(encoder); }
1,756
C
.c
42
37.690476
96
0.708162
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,496
infrared_decoder_rc5.c
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/rc5/infrared_decoder_rc5.c
#include "infrared_protocol_rc5_i.h" #include <stdlib.h> #include <core/check.h> typedef struct { InfraredCommonDecoder* common_decoder; bool toggle; } InfraredRc5Decoder; InfraredMessage* infrared_decoder_rc5_check_ready(void* ctx) { InfraredRc5Decoder* decoder = ctx; return infrared_common_decoder_check_ready(decoder->common_decoder); } bool infrared_decoder_rc5_interpret(InfraredCommonDecoder* decoder) { furi_assert(decoder); bool result = false; uint32_t* data = (void*)&decoder->data[0]; /* Manchester (inverse): * 0->1 : 1 * 1->0 : 0 */ decoder->data[0] = ~decoder->data[0]; decoder->data[1] = ~decoder->data[1]; // MSB first uint8_t address = reverse((uint8_t)decoder->data[0]) & 0x1F; uint8_t command = (reverse((uint8_t)decoder->data[1]) >> 2) & 0x3F; bool start_bit1 = *data & 0x01; bool start_bit2 = *data & 0x02; bool toggle = !!(*data & 0x04); if(start_bit1 == 1) { InfraredProtocol protocol = start_bit2 ? InfraredProtocolRC5 : InfraredProtocolRC5X; InfraredMessage* message = &decoder->message; InfraredRc5Decoder* rc5_decoder = decoder->context; bool* prev_toggle = &rc5_decoder->toggle; if((message->address == address) && (message->command == command) && (message->protocol == protocol)) { message->repeat = (toggle == *prev_toggle); } else { message->repeat = false; } *prev_toggle = toggle; message->command = command; message->address = address; message->protocol = protocol; result = true; } return result; } void* infrared_decoder_rc5_alloc(void) { InfraredRc5Decoder* decoder = malloc(sizeof(InfraredRc5Decoder)); decoder->toggle = false; decoder->common_decoder = infrared_common_decoder_alloc(&infrared_protocol_rc5); decoder->common_decoder->context = decoder; return decoder; } InfraredMessage* infrared_decoder_rc5_decode(void* decoder, bool level, uint32_t duration) { InfraredRc5Decoder* decoder_rc5 = decoder; return infrared_common_decode(decoder_rc5->common_decoder, level, duration); } void infrared_decoder_rc5_free(void* decoder) { InfraredRc5Decoder* decoder_rc5 = decoder; infrared_common_decoder_free(decoder_rc5->common_decoder); free(decoder_rc5); } void infrared_decoder_rc5_reset(void* decoder) { InfraredRc5Decoder* decoder_rc5 = decoder; infrared_common_decoder_reset(decoder_rc5->common_decoder); }
2,543
C
.c
66
33.242424
92
0.676542
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,497
infrared_protocol_rc5.h
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/rc5/infrared_protocol_rc5.h
#pragma once #include "../infrared_i.h" /*************************************************************************************************** * RC5 protocol description * https://www.mikrocontroller.net/articles/IRMP_-_english#RC5_.2B_RC5X **************************************************************************************************** * Manchester/biphase * Modulation * * 888/1776 - bit (x2 for toggle bit) * * __ ____ __ __ __ __ __ __ __ __ * __ __ ____ __ __ __ __ __ __ __ _ * | 1 | 1 | 0 | ... | ... | * s si T address (MSB) command (MSB) * * Note: manchester starts from space timing, so it have to be handled properly * s - start bit (always 1) * si - RC5: start bit (always 1), RC5X - 7-th bit of address (in our case always 0) * T - toggle bit, change it's value every button press * address - 5 bit * command - 6/7 bit ***************************************************************************************************/ void* infrared_decoder_rc5_alloc(void); void infrared_decoder_rc5_reset(void* decoder); void infrared_decoder_rc5_free(void* decoder); InfraredMessage* infrared_decoder_rc5_check_ready(void* ctx); InfraredMessage* infrared_decoder_rc5_decode(void* decoder, bool level, uint32_t duration); void* infrared_encoder_rc5_alloc(void); void infrared_encoder_rc5_reset(void* encoder_ptr, const InfraredMessage* message); void infrared_encoder_rc5_free(void* decoder); InfraredStatus infrared_encoder_rc5_encode(void* encoder_ptr, uint32_t* duration, bool* polarity); const InfraredProtocolVariant* infrared_protocol_rc5_get_variant(InfraredProtocol protocol);
1,874
C
.c
33
55.636364
100
0.49183
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,498
infrared_protocol_samsung.c
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/samsung/infrared_protocol_samsung.c
#include "infrared_protocol_samsung_i.h" const InfraredCommonProtocolSpec infrared_protocol_samsung32 = { .timings = { .preamble_mark = INFRARED_SAMSUNG_PREAMBLE_MARK, .preamble_space = INFRARED_SAMSUNG_PREAMBLE_SPACE, .bit1_mark = INFRARED_SAMSUNG_BIT1_MARK, .bit1_space = INFRARED_SAMSUNG_BIT1_SPACE, .bit0_mark = INFRARED_SAMSUNG_BIT0_MARK, .bit0_space = INFRARED_SAMSUNG_BIT0_SPACE, .preamble_tolerance = INFRARED_SAMSUNG_PREAMBLE_TOLERANCE, .bit_tolerance = INFRARED_SAMSUNG_BIT_TOLERANCE, .silence_time = INFRARED_SAMSUNG_SILENCE, .min_split_time = INFRARED_SAMSUNG_MIN_SPLIT_TIME, }, .databit_len[0] = 32, .decode = infrared_common_decode_pdwm, .encode = infrared_common_encode_pdwm, .interpret = infrared_decoder_samsung32_interpret, .decode_repeat = infrared_decoder_samsung32_decode_repeat, .encode_repeat = infrared_encoder_samsung32_encode_repeat, }; static const InfraredProtocolVariant infrared_protocol_variant_samsung32 = { .name = "Samsung32", .address_length = 8, .command_length = 8, .frequency = INFRARED_COMMON_CARRIER_FREQUENCY, .duty_cycle = INFRARED_COMMON_DUTY_CYCLE, .repeat_count = INFRARED_SAMSUNG_REPEAT_COUNT_MIN, }; const InfraredProtocolVariant* infrared_protocol_samsung32_get_variant(InfraredProtocol protocol) { if(protocol == InfraredProtocolSamsung32) return &infrared_protocol_variant_samsung32; else return NULL; }
1,569
C
.c
36
36.611111
99
0.696732
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,499
infrared_protocol_samsung.h
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/samsung/infrared_protocol_samsung.h
#pragma once #include "../infrared_i.h" /*************************************************************************************************** * SAMSUNG32 protocol description * https://www.mikrocontroller.net/articles/IRMP_-_english#SAMSUNG **************************************************************************************************** * Preamble Preamble Pulse Distance/Width Pause Preamble Preamble Bit1 Stop * mark space Modulation repeat repeat bit * mark space * * 4500 4500 32 bit + stop bit 40000/100000 4500 4500 * __________ _ _ _ _ _ _ _ _ _ _ _ ___________ _ _ * _ __________ __ _ __ __ __ _ _ __ __ _ ________________ ____________ ____ ___ * ***************************************************************************************************/ void* infrared_decoder_samsung32_alloc(void); void infrared_decoder_samsung32_reset(void* decoder); void infrared_decoder_samsung32_free(void* decoder); InfraredMessage* infrared_decoder_samsung32_check_ready(void* ctx); InfraredMessage* infrared_decoder_samsung32_decode(void* decoder, bool level, uint32_t duration); InfraredStatus infrared_encoder_samsung32_encode(void* encoder_ptr, uint32_t* duration, bool* level); void infrared_encoder_samsung32_reset(void* encoder_ptr, const InfraredMessage* message); void* infrared_encoder_samsung32_alloc(void); void infrared_encoder_samsung32_free(void* encoder_ptr); const InfraredProtocolVariant* infrared_protocol_samsung32_get_variant(InfraredProtocol protocol);
1,736
C
.c
26
65.423077
100
0.491496
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,500
infrared_decoder_samsung.c
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/samsung/infrared_decoder_samsung.c
#include "infrared_protocol_samsung_i.h" #include <core/check.h> InfraredMessage* infrared_decoder_samsung32_check_ready(void* ctx) { return infrared_common_decoder_check_ready(ctx); } bool infrared_decoder_samsung32_interpret(InfraredCommonDecoder* decoder) { furi_assert(decoder); bool result = false; uint8_t address1 = decoder->data[0]; uint8_t address2 = decoder->data[1]; uint8_t command = decoder->data[2]; uint8_t command_inverse = decoder->data[3]; uint8_t inverse_command_inverse = (uint8_t)~command_inverse; if((address1 == address2) && (command == inverse_command_inverse)) { decoder->message.command = command; decoder->message.address = address1; decoder->message.protocol = InfraredProtocolSamsung32; decoder->message.repeat = false; result = true; } return result; } // timings start from Space (delay between message and repeat) InfraredStatus infrared_decoder_samsung32_decode_repeat(InfraredCommonDecoder* decoder) { furi_assert(decoder); float preamble_tolerance = decoder->protocol->timings.preamble_tolerance; uint32_t bit_tolerance = decoder->protocol->timings.bit_tolerance; InfraredStatus status = InfraredStatusError; if(decoder->timings_cnt < 6) return InfraredStatusOk; if((decoder->timings[0] > INFRARED_SAMSUNG_REPEAT_PAUSE_MIN) && (decoder->timings[0] < INFRARED_SAMSUNG_REPEAT_PAUSE_MAX) && MATCH_TIMING(decoder->timings[1], INFRARED_SAMSUNG_REPEAT_MARK, preamble_tolerance) && MATCH_TIMING(decoder->timings[2], INFRARED_SAMSUNG_REPEAT_SPACE, preamble_tolerance) && MATCH_TIMING(decoder->timings[3], decoder->protocol->timings.bit1_mark, bit_tolerance) && MATCH_TIMING(decoder->timings[4], decoder->protocol->timings.bit1_space, bit_tolerance) && MATCH_TIMING(decoder->timings[5], decoder->protocol->timings.bit1_mark, bit_tolerance)) { status = InfraredStatusReady; decoder->timings_cnt = 0; } else { status = InfraredStatusError; } return status; } void* infrared_decoder_samsung32_alloc(void) { return infrared_common_decoder_alloc(&infrared_protocol_samsung32); } InfraredMessage* infrared_decoder_samsung32_decode(void* decoder, bool level, uint32_t duration) { return infrared_common_decode(decoder, level, duration); } void infrared_decoder_samsung32_free(void* decoder) { infrared_common_decoder_free(decoder); } void infrared_decoder_samsung32_reset(void* decoder) { infrared_common_decoder_reset(decoder); }
2,566
C
.c
55
41.727273
98
0.729676
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,501
infrared_encoder_samsung.c
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/samsung/infrared_encoder_samsung.c
#include "infrared_protocol_samsung_i.h" #include <core/check.h> #include <core/common_defines.h> static const uint32_t repeat_timings[] = { INFRARED_SAMSUNG_REPEAT_PAUSE2, INFRARED_SAMSUNG_REPEAT_MARK, INFRARED_SAMSUNG_REPEAT_SPACE, INFRARED_SAMSUNG_BIT1_MARK, INFRARED_SAMSUNG_BIT1_SPACE, INFRARED_SAMSUNG_BIT1_MARK, }; void infrared_encoder_samsung32_reset(void* encoder_ptr, const InfraredMessage* message) { furi_assert(encoder_ptr); InfraredCommonEncoder* encoder = encoder_ptr; infrared_common_encoder_reset(encoder); uint8_t address = message->address; uint8_t command = message->command; uint8_t command_inverse = ~command; uint32_t* data = (void*)encoder->data; *data |= address; *data |= address << 8; *data |= command << 16; *data |= command_inverse << 24; encoder->bits_to_encode = encoder->protocol->databit_len[0]; } InfraredStatus infrared_encoder_samsung32_encode_repeat( InfraredCommonEncoder* encoder, uint32_t* duration, bool* level) { furi_assert(encoder); /* space + 2 timings preambule + payload + stop bit */ uint32_t timings_encoded_up_to_repeat = 1 + 2 + encoder->bits_encoded * 2 + 1; uint32_t repeat_cnt = encoder->timings_encoded - timings_encoded_up_to_repeat; furi_assert(encoder->timings_encoded >= timings_encoded_up_to_repeat); if(repeat_cnt > 0) *duration = repeat_timings[repeat_cnt % COUNT_OF(repeat_timings)]; else *duration = INFRARED_SAMSUNG_REPEAT_PAUSE1; *level = repeat_cnt % 2; ++encoder->timings_encoded; bool done = (!((repeat_cnt + 1) % COUNT_OF(repeat_timings))); return done ? InfraredStatusDone : InfraredStatusOk; } void* infrared_encoder_samsung32_alloc(void) { return infrared_common_encoder_alloc(&infrared_protocol_samsung32); } void infrared_encoder_samsung32_free(void* encoder_ptr) { infrared_common_encoder_free(encoder_ptr); } InfraredStatus infrared_encoder_samsung32_encode(void* encoder_ptr, uint32_t* duration, bool* level) { return infrared_common_encode(encoder_ptr, duration, level); }
2,129
C
.c
53
35.849057
91
0.716019
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,502
infrared_protocol_samsung_i.h
DarkFlippers_unleashed-firmware/lib/infrared/encoder_decoder/samsung/infrared_protocol_samsung_i.h
#pragma once #include "../common/infrared_common_i.h" #define INFRARED_SAMSUNG_PREAMBLE_MARK 4500 #define INFRARED_SAMSUNG_PREAMBLE_SPACE 4500 #define INFRARED_SAMSUNG_BIT1_MARK 550 #define INFRARED_SAMSUNG_BIT1_SPACE 1650 #define INFRARED_SAMSUNG_BIT0_MARK 550 #define INFRARED_SAMSUNG_BIT0_SPACE 550 #define INFRARED_SAMSUNG_REPEAT_PAUSE_MIN 30000 #define INFRARED_SAMSUNG_REPEAT_PAUSE_MAX 140000 #define INFRARED_SAMSUNG_REPEAT_PAUSE1 46000 #define INFRARED_SAMSUNG_REPEAT_PAUSE2 97000 #define INFRARED_SAMSUNG_REPEAT_COUNT_MIN 1 /* Samsung silence have to be greater than REPEAT MAX * otherwise there can be problems during unit tests parsing * of some data. Real tolerances we don't know, but in real life * silence time should be greater than max repeat time. This is * because of similar preambule timings for repeat and first messages. */ #define INFRARED_SAMSUNG_MIN_SPLIT_TIME 5000 #define INFRARED_SAMSUNG_SILENCE 145000 #define INFRARED_SAMSUNG_REPEAT_MARK 4500 #define INFRARED_SAMSUNG_REPEAT_SPACE 4500 #define INFRARED_SAMSUNG_PREAMBLE_TOLERANCE 200 // us #define INFRARED_SAMSUNG_BIT_TOLERANCE 120 // us bool infrared_decoder_samsung32_interpret(InfraredCommonDecoder* decoder); InfraredStatus infrared_decoder_samsung32_decode_repeat(InfraredCommonDecoder* decoder); InfraredStatus infrared_encoder_samsung32_encode_repeat( InfraredCommonEncoder* encoder, uint32_t* duration, bool* level); extern const InfraredCommonProtocolSpec infrared_protocol_samsung32;
1,588
C
.c
31
49.580645
88
0.780425
DarkFlippers/unleashed-firmware
16,875
1,409
86
GPL-3.0
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false