repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
zap
github_2023
zigzap
c
fio_tls_trust
int FIO_TLS_WEAK fio_tls_trust(fio_tls_s *tls, const char *public_cert_file) { REQUIRE_LIBRARY(); trust_s c = { .pem = FIO_STR_INIT, }; if (!public_cert_file) return 0; if (fio_str_readfile(&c.pem, public_cert_file, 0, 0).data == NULL) goto file_missing; trust_ary_push(&tls->trust, c); fio_tls_trust_destroy(&c); fio_tls_build_context(tls); return 0; file_missing: FIO_LOG_FATAL("TLS certificate file missing for %s ", public_cert_file); return -1; // CoalNova's suggestion. Was: -1 }
/** * Adds a certificate to the "trust" list, which automatically adds a peer * verification requirement. * * fio_tls_trust(tls, "google-ca.pem" ); */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/tls/fio_tls_openssl.c#L944-L960
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
fio_tls_accept
void FIO_TLS_WEAK fio_tls_accept(intptr_t uuid, fio_tls_s *tls, void *udata) { REQUIRE_LIBRARY(); fio_tls_attach2uuid(uuid, tls, udata, 1); }
/** * Establishes an SSL/TLS connection as an SSL/TLS Server, using the specified * context / settings object. * * The `uuid` should be a socket UUID that is already connected to a peer * (i.e., the result of `fio_accept`). * * The `udata` is an opaque user data pointer that is passed along to the * protocol selected (if any protocols were added using `fio_tls_alpn_add`). */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/tls/fio_tls_openssl.c#L972-L975
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
fio_tls_connect
void FIO_TLS_WEAK fio_tls_connect(intptr_t uuid, fio_tls_s *tls, void *udata) { REQUIRE_LIBRARY(); fio_tls_attach2uuid(uuid, tls, udata, 0); }
/** * Establishes an SSL/TLS connection as an SSL/TLS Client, using the specified * context / settings object. * * The `uuid` should be a socket UUID that is already connected to a peer * (i.e., one received by a `fio_connect` specified callback `on_connect`). * * The `udata` is an opaque user data pointer that is passed along to the * protocol selected (if any protocols were added using `fio_tls_alpn_add`). */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/tls/fio_tls_openssl.c#L987-L990
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
fio_tls_dup
void FIO_TLS_WEAK fio_tls_dup(fio_tls_s *tls) { fio_atomic_add(&tls->ref, 1); }
/** * Increase the reference count for the TLS object. * * Decrease with `fio_tls_destroy`. */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/tls/fio_tls_openssl.c#L997-L997
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
fio_tls_destroy
void FIO_TLS_WEAK fio_tls_destroy(fio_tls_s *tls) { if (!tls) return; REQUIRE_LIBRARY(); if (fio_atomic_sub(&tls->ref, 1)) return; fio_tls_destroy_context(tls); alpn_list_free(&tls->alpn); cert_ary_free(&tls->sni); trust_ary_free(&tls->trust); free(tls); }
/** * Destroys the SSL/TLS context / settings object and frees any related * resources / memory. */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/tls/fio_tls_openssl.c#L1003-L1014
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
initialize_cli
static void initialize_cli(int argc, char const *argv[]) { fio_cli_start( argc, argv, 0, 0, "This is a Hash algorythm collision test program. It accepts the " "following arguments:", FIO_CLI_STRING( "-test -t test only the specified algorithm. Options include:"), FIO_CLI_PRINT("\t\tsiphash13"), FIO_CLI_PRINT("\t\tsiphash24"), FIO_CLI_PRINT("\t\tsha1"), FIO_CLI_PRINT("\t\trisky (fio_str_hash_risky)"), FIO_CLI_PRINT("\t\trisky2 (fio_str_hash_risky alternative)"), // FIO_CLI_PRINT("\t\txor (xor all bytes and length)"), FIO_CLI_STRING( "-dictionary -d a text file containing words separated by an " "EOL marker."), FIO_CLI_BOOL("-v make output more verbouse (debug mode)")); if (fio_cli_get_bool("-v")) FIO_LOG_LEVEL = FIO_LOG_LEVEL_DEBUG; FIO_LOG_DEBUG("initialized CLI."); }
/* ***************************************************************************** CLI ***************************************************************************** */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/collisions.c#L97-L116
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
cleanup
static void cleanup(void) { print_flag = 0; hash_name_free(&hash_names); words_free(&words); }
/* ***************************************************************************** Cleanup ***************************************************************************** */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/collisions.c#L174-L178
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
siphash13
static uintptr_t siphash13(char *data, size_t len) { return fio_siphash13(data, len, 0, 0); }
/* ***************************************************************************** Hash functions ***************************************************************************** */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/collisions.c#L184-L186
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
inverse64_test
static uint64_t inverse64_test(uint64_t n, uint64_t inv) { uint64_t result = inv * (2 - (n * inv)); return result; }
/* ***************************************************************************** Finsing a mod64 inverse See: https://lemire.me/blog/2017/09/18/computing-the-inverse-of-odd-integers/ ***************************************************************************** */ /* will return `inv` if `inv` is inverse of `n` */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/collisions.c#L393-L396
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
attack_xxhash2
FIO_FUNC void attack_xxhash2(void) { /* POC - forcing XXHash to return seed only data (here, seed = 0) */ const uint64_t PRIME64_1 = 11400714785074694791ULL; const uint64_t PRIME64_2 = 14029467366897019727ULL; // const uint64_t PRIME64_3 = 1609587929392839161ULL; // const uint64_t PRIME64_4 = 9650029242287828579ULL; // const uint64_t PRIME64_5 = 2870177450012600261ULL; const uint64_t PRIME64_1_INV = inverse64(PRIME64_1); const uint64_t PRIME64_2_INV = inverse64(PRIME64_2); // const uint64_t PRIME64_3_INV = inverse64(PRIME64_3); // const uint64_t PRIME64_4_INV = inverse64(PRIME64_4); // const uint64_t PRIME64_5_INV = inverse64(PRIME64_5); const uint64_t seed_manipulation[4] = {PRIME64_1 + PRIME64_2, PRIME64_2, 0, -PRIME64_1}; uint64_t v[4] = {0, 0, 0, 0}; /* attack v *= PRIME64_1 */ v[0] = v[0] * PRIME64_1_INV; v[1] = v[1] * PRIME64_1_INV; v[2] = v[2] * PRIME64_1_INV; v[3] = v[3] * PRIME64_1_INV; /* attack v = XXH_rotl64(v, 31) */ v[0] = (v[0] >> 31) | (v[0] << (64 - 31)); v[1] = (v[1] >> 31) | (v[1] << (64 - 31)); v[2] = (v[2] >> 31) | (v[2] << (64 - 31)); v[3] = (v[3] >> 31) | (v[3] << (64 - 31)); /* attack seed manipulation */ v[0] = v[0] - seed_manipulation[0]; v[1] = v[1] - seed_manipulation[1]; v[2] = v[2] - seed_manipulation[2]; v[3] = v[3] - seed_manipulation[3]; /* attack v += XXH_get64bits(p) * PRIME64_2 */ v[0] = v[0] * PRIME64_2_INV; v[1] = v[1] * PRIME64_2_INV; v[2] = v[2] * PRIME64_2_INV; v[3] = v[3] * PRIME64_2_INV; uint64_t seed_data = XXH64(v, 32, 0); if (seed_data == 0) fprintf(stderr, "XXHash seed data extracted for seed == 0!\n"); else fprintf(stderr, "Seed extraction failed %llu\n", seed_data); }
/* ***************************************************************************** Hash Breaking Word Workshop ***************************************************************************** */ /** * Attacking 8 byte words, which follow this code path: * h64 = seed + PRIME64_5; * h64 += len; // len == 8 * if (p + 4 <= bEnd) { * h64 ^= (U64)(XXH_get32bits(p)) * PRIME64_1; * h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3; * p += 4; * } * * while (p < bEnd) { * h64 ^= (*p) * PRIME64_5; * h64 = XXH_rotl64(h64, 11) * PRIME64_1; * p++; * } * * h64 ^= h64 >> 33; * h64 *= PRIME64_2; * h64 ^= h64 >> 29; * h64 *= PRIME64_3; * h64 ^= h64 >> 32; */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/collisions.c#L446-L486
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
add_bad4xxhash
FIO_FUNC void add_bad4xxhash(void) { attack_xxhash(); const uint64_t PRIME64_1 = 11400714785074694791ULL; const uint64_t PRIME64_2 = 14029467366897019727ULL; const uint64_t PRIME64_1_INV = inverse64(PRIME64_1); const uint64_t PRIME64_2_INV = inverse64(PRIME64_2); const uint64_t seed_manipulation[4] = {PRIME64_1 + PRIME64_2, PRIME64_2, 0, -PRIME64_1}; uint64_t rotating[4] = {0x1, 0x20, 0x300, 0x4000}; uint8_t results[32][16] = {{0}}; uint8_t results_count = 0; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { if (i == j) /* all 4 rotating words must be present */ continue; /* mix rotating word order */ uint64_t v[4] = {rotating[i], rotating[j], rotating[3 - i], rotating[3 - j]}; /* prepare vector against h64 = XXH_rotl64... */ v[0] = (v[0] >> 1) | (v[0] << (64 - 1)); v[1] = (v[1] >> 7) | (v[1] << (64 - 7)); v[2] = (v[2] >> 12) | (v[2] << (64 - 12)); v[3] = (v[3] >> 18) | (v[3] << (64 - 18)); /* attack v *= PRIME64_1 */ v[0] = v[0] * PRIME64_1_INV; v[1] = v[1] * PRIME64_1_INV; v[2] = v[2] * PRIME64_1_INV; v[3] = v[3] * PRIME64_1_INV; /* attack v = XXH_rotl64(v, 31) */ v[0] = (v[0] >> 31) | (v[0] << (64 - 31)); v[1] = (v[1] >> 31) | (v[1] << (64 - 31)); v[2] = (v[2] >> 31) | (v[2] << (64 - 31)); v[3] = (v[3] >> 31) | (v[3] << (64 - 31)); /* attack seed manipulation */ v[0] = v[0] - seed_manipulation[0]; v[1] = v[1] - seed_manipulation[1]; v[2] = v[2] - seed_manipulation[2]; v[3] = v[3] - seed_manipulation[3]; /* attack v += XXH_get64bits(p) * PRIME64_2 */ v[0] = v[0] * PRIME64_2_INV; v[1] = v[1] * PRIME64_2_INV; v[2] = v[2] * PRIME64_2_INV; v[3] = v[3] * PRIME64_2_INV; /* copy to results, if unique */ uint8_t unique = 1; for (int t = 0; t < results_count; ++t) { if (!memcmp(&results[0][t], v, 32)) unique = 0; } if (unique) { memcpy(&results[0][results_count], v, 32); ++results_count; } } } if (results_count) { fprintf(stderr, "Created %u vectors, now testing...\n", results_count); uint64_t origin = XXH64(&results[0][0], 32, 0); for (int i = 0; i < results_count; ++i) { words_push(&words, FIO_STR_INIT_STATIC2(&results[0][i], 32)); if (i && origin == XXH64(&results[0][i], 32, 0)) fprintf(stderr, "Possible collision [%d]\n", i); } fprintf(stderr, "Done testing.\n"); } }
/** * Attacking 64 byte messages where the last 32 bytes are the same and the first * 32 bytes use rotating 8 byte words. This is attcking the following part in * the code: * * U64 v1 = seed + PRIME64_1 + PRIME64_2; * U64 v2 = seed + PRIME64_2; * U64 v3 = seed + 0; * U64 v4 = seed - PRIME64_1; * * do { * v1 += XXH_get64bits(p) * PRIME64_2; * p += 8; * v1 = XXH_rotl64(v1, 31); * v1 *= PRIME64_1; * //... v2, v3, v4 same; * } while (p <= limit); * * h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + * XXH_rotl64(v4, 18); */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/collisions.c#L574-L640
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
fio_risky_hash2
static inline uintptr_t fio_risky_hash2(const void *data_, size_t len, uint64_t seed) { /* The primes used by Risky Hash */ const uint64_t primes[] = { 0xFBBA3FA15B22113B, // 1111101110111010001111111010000101011011001000100001000100111011 0xAB137439982B86C9, // 1010101100010011011101000011100110011000001010111000011011001001 }; /* The consumption vectors initialized state */ uint64_t v[4] = { seed ^ primes[1], ~seed + primes[1], fio_lrot64(seed, 17) ^ (primes[1] + primes[0]), fio_lrot64(seed, 33) + (~primes[1]), }; /* reading position */ const uint8_t *data = (uint8_t *)data_; /* consume 256bit blocks */ for (size_t i = len >> 5; i; --i) { fio_risky_consume(v[0], fio_str2u64(data)); fio_risky_consume(v[1], fio_str2u64(data + 8)); fio_risky_consume(v[2], fio_str2u64(data + 16)); fio_risky_consume(v[3], fio_str2u64(data + 24)); data += 32; } /* Consume any remaining 64 bit words. */ switch (len & 24) { case 24: fio_risky_consume(v[2], fio_str2u64(data + 16)); case 16: /* overflow */ fio_risky_consume(v[1], fio_str2u64(data + 8)); case 8: /* overflow */ fio_risky_consume(v[0], fio_str2u64(data)); data += len & 24; } uint64_t tmp = 0; /* consume leftover bytes, if any */ switch ((len & 7)) { case 7: /* overflow */ tmp |= ((uint64_t)data[6]) << 8; case 6: /* overflow */ tmp |= ((uint64_t)data[5]) << 16; case 5: /* overflow */ tmp |= ((uint64_t)data[4]) << 24; case 4: /* overflow */ tmp |= ((uint64_t)data[3]) << 32; case 3: /* overflow */ tmp |= ((uint64_t)data[2]) << 40; case 2: /* overflow */ tmp |= ((uint64_t)data[1]) << 48; case 1: /* overflow */ tmp |= ((uint64_t)data[0]) << 56; /* ((len & 24) >> 3) is a 0-3 value representing the next state vector */ /* `switch` allows v[i] to be a register without a memory address */ /* using v[(len & 24) >> 3] forces implementation to use memory */ switch ((len & 24) >> 3) { case 3: fio_risky_consume(v[3], tmp); break; case 2: fio_risky_consume(v[2], tmp); break; case 1: fio_risky_consume(v[1], tmp); break; case 0: fio_risky_consume(v[0], tmp); break; } } /* merge and mix */ uint64_t result = fio_lrot64(v[0], 17) + fio_lrot64(v[1], 13) + fio_lrot64(v[2], 47) + fio_lrot64(v[3], 57); result += len; result += v[0] * primes[1]; result ^= fio_lrot64(result, 13); result += v[1] * primes[1]; result ^= fio_lrot64(result, 29); result += v[2] * primes[1]; result ^= fio_lrot64(result, 33); result += v[3] * primes[1]; result ^= fio_lrot64(result, 51); /* irreversible avalanche... I think */ result ^= (result >> 29) * primes[0]; return result; }
/* Computes a facil.io Risky Hash. */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/collisions.c#L692-L781
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
seek3
static inline int seek3(uint8_t **buffer, register uint8_t *const limit, const uint8_t c) { if (**buffer == c) return 1; #if !__x86_64__ && !__aarch64__ /* too short for this mess */ if ((uintptr_t)limit <= 16 + ((uintptr_t)*buffer & (~(uintptr_t)7))) goto finish; /* align memory */ { const uint8_t *alignment = (uint8_t *)(((uintptr_t)(*buffer) & (~(uintptr_t)7)) + 8); if (limit >= alignment) { while (*buffer < alignment) { if (**buffer == c) return 1; *buffer += 1; } } } const uint8_t *limit64 = (uint8_t *)((uintptr_t)limit & (~(uintptr_t)7)); #else const uint8_t *limit64 = (uint8_t *)limit - 7; #endif uint64_t wanted1 = 0x0101010101010101ULL * c; for (; *buffer < limit64; *buffer += 8) { const uint64_t eq1 = ~((*((uint64_t *)*buffer)) ^ wanted1); const uint64_t t0 = (eq1 & 0x7f7f7f7f7f7f7f7fllu) + 0x0101010101010101llu; const uint64_t t1 = (eq1 & 0x8080808080808080llu); if ((t0 & t1)) { break; } } #if !__x86_64__ && !__aarch64__ finish: #endif while (*buffer < limit) { if (**buffer == c) return 1; (*buffer)++; } return 0; }
/** * This seems to be faster on some systems, especially for smaller distances. * * On newer systems, `memchr` should be faster. */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/memchr_speed.c#L38-L83
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
pco_scale
static double pco_scale(double x, double n) { if (x >= 1.0 || x <= 0.0) return x; /* This is the result we want: return 1.0 - pow(1.0 - x, n); except the important cases are with x very small so this method gives better accuracy. */ return -expm1(log1p(-x) * n); }
/* Probability that the smallest of n numbers in [0..1) is <= x . */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/random.c#L248-L257
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
get_count
static inline int get_count(uint32_t cs) { return cs >> SUM_BITS; }
/* The idea of the test is based around Hamming weights. We calculate the average number of bits per BITS-bit word and how it depends on the weights of the previous DIM words. There are SIZE different categories for the previous words. For each one accumulate number of samples (get_count(cs[j]) and count_sum[j].c) and number of bits per sample (get_sum(cs[j]) and count_sum[j].s) . To increase cache hits, we pack a 13-bit unsigned counter (upper bits) and a and a 19-bit unsigned sum of Hamming weights (lower bits) into a uint32_t. It would make sense to use bitfields, but in this way update_cs() can update both fields with a single sum. */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/random.c#L271-L271
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
update_cs
static inline void update_cs(int bc, uint32_t *p) { *p += bc + (1 << SUM_BITS); }
/* We add bc to the sum field of *p then add 1 to the count field. */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/random.c#L276-L278
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
desat
static void desat(const int64_t next_batch_size) { int64_t c = 0, s = 0; for (int i = 0; i < SIZE; i++) { const int32_t st = cs[i]; const int count = get_count(st); const int sum = get_sum(st); c += count; s += sum; count_sum[i].c += count; /* In cs[] the total Hamming weight is stored as actual weight. In count_sum, it is stored as difference from expected average Hamming weight, hence (BITS/2) * count */ count_sum[i].s += sum - (HWD_BITS / 2) * count; cs[i] = 0; } if (c != next_batch_size || s != tot_sums) { fprintf(stderr, "Counters or values overflowed. Seriously non-random.\n"); printf("p = %.3g\n", 1e-100); exit(0); } }
/* Copy accumulated numbers out of cs[] into count_sum, then zero the ones in cs[]. We have to check explicitly that values do not overflow. */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/random.c#L310-L335
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
desat
static void desat(const int64_t next_batch_size) { int64_t c = 0; for (uint64_t i = 0; i < SIZE; i++) { const int32_t st = cs[i]; const int count = get_count(st); c += count; count_sum[i].c += count; /* In cs[] the total Hamming weight is stored as actual weight. In count_sum, it is stored as difference from expected average Hamming weight, hence (BITS/2) * ct */ count_sum[i].s += get_sum(st) - (HWD_BITS / 2) * count; cs[i] = 0; } if (c != next_batch_size) { fprintf(stderr, "Counters overflowed. Seriously non-random.\n"); printf("p = %.3g\n", 1e-100); exit(0); } }
/* Copy accumulated numbers out of cs[] into count_sum, then zero the ones in cs[]. Note it is impossible for totals to overflow unless counts do. */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/random.c#L342-L364
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
print_sig
static void print_sig(uint32_t sig) { for (uint64_t i = DIM; i > 0; i--) { putchar(sig % 3 + '0'); sig /= 3; } }
/* Now we're out of the the accumulate phase, which is the inside loop. Next is analysis. */ /* Mostly a debugging printf, though it can tell you a bit about the structure of a prng when it fails. Print sig out in base 3, least significant digits first. This means the most recent trit is the rightmost. */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/random.c#L488-L493
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
mix3
static void mix3(double *ct, int sig) { double *p1 = ct + sig, *p2 = p1 + sig; double a, b, c; for (int i = 0; i < sig; i++) { a = ct[i]; b = p1[i]; c = p2[i]; ct[i] = (a + b + c) * CORRECT3; p1[i] = (a - c) * M_SQRT1_2; p2[i] = (2 * b - a - c) * CORRECT6; } sig = DIV3(sig); if (sig) { mix3(ct, sig); mix3(p1, sig); mix3(p2, sig); } }
/* This is a transform similar in spirit to the Walsh-Hadamard transform (see the paper). It's ortho-normal. So with independent normal distribution mean 0 standard deviation 1 in, we get independent normal distribution mean 0 standard deviation 1 out, except maybe for element 0. And of course, for certain kinds of bad prngs when the null hypthosis is false, some of these numbers will get extreme. */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/random.c#L511-L530
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
cat
static int cat(uint32_t sig) { int r = 0; while (sig) { r += (sig % 3) != 0; sig /= 3; } return (r >= NUMCATS ? NUMCATS : r) - 1; }
/* categorise sig based on nonzero ternary digits. */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/random.c#L533-L542
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
analyze
static void analyze(int64_t pos, bool trans, bool final) { if (pos < 2 * pow(2.0 / (1.0 - P), DIM)) printf("WARNING: p-values are unreliable, you have to wait (insufficient " "data for meaningful answer)\n"); const double pvalue = compute_pvalue(trans); const time_t tm = time(0); printf("processed %.3g bytes in %.3g seconds (%.4g GB/s, %.4g TB/h). %s\n", (double)pos, (double)(tm - tstart), pos * 1E-9 / (double)(tm - tstart), pos * (3600 * 1E-12) / (double)(tm - tstart), ctime(&tm)); if (final) printf("final\n"); printf("p = %.3g\n", pvalue); if (pvalue < low_pvalue) exit(0); if (!final) printf("------\n\n"); }
/* This is the call made when we want to print some analysis. This will be done multiple times if --progress is used. */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/random.c#L623-L645
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
prep_msg
static void prep_msg(void) { ASSERT_COND(strlen(address) < 512, "host name too long"); if (USE_PIPELINING) { MSG_LEN = strlen(HTTP_REQUEST_HEAD) + strlen(address) + 4; REQ_PER_MSG = 1; memcpy(MSG_OUTPUT, HTTP_REQUEST_HEAD, strlen(HTTP_REQUEST_HEAD)); memcpy(MSG_OUTPUT + strlen(HTTP_REQUEST_HEAD), address, strlen(address)); MSG_OUTPUT[MSG_LEN - 4] = '\r'; MSG_OUTPUT[MSG_LEN - 3] = '\n'; MSG_OUTPUT[MSG_LEN - 2] = '\r'; MSG_OUTPUT[MSG_LEN - 1] = '\n'; } else { memcpy(MSG_OUTPUT, HTTP_REQUEST_HEAD, strlen(HTTP_REQUEST_HEAD)); memcpy(MSG_OUTPUT + strlen(HTTP_REQUEST_HEAD), address, strlen(address)); MSG_LEN = strlen(HTTP_REQUEST_HEAD) + strlen(address) + 4; REQ_PER_MSG = MTU_LIMIT / MSG_LEN; MSG_OUTPUT[MSG_LEN - 4] = '\r'; MSG_OUTPUT[MSG_LEN - 3] = '\n'; MSG_OUTPUT[MSG_LEN - 2] = '\r'; MSG_OUTPUT[MSG_LEN - 1] = '\n'; if (!REQ_PER_MSG) REQ_PER_MSG = 1; for (size_t i = 1; i < REQ_PER_MSG; ++i) { memcpy(MSG_OUTPUT + (i * MSG_LEN), MSG_OUTPUT, MSG_LEN); } MSG_LEN *= REQ_PER_MSG; } }
/* copies an HTTP request to the internal buffer */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/slowloris.c#L92-L119
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
sig_int_handler
static void sig_int_handler(int sig) { signal(SIGINT, SIG_DFL); switch (sig) { case SIGINT: /* fallthrough */ case SIGTERM: /* fallthrough */ flag = 0; break; default: break; } }
/* handles the SIGUSR1, SIGINT and SIGTERM signals. */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/slowloris.c#L122-L132
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
main
int main(int argc, char const *argv[]) { int result = 0; ASSERT_COND(argc == 3 || argc == 4, "\nTo test HTTP/1.1 server against Slowloris, " "use: %s addr port [attackers]\ni.e.:\n\t\t%s example.com 80" "\n\t\t%s localhost 3000 24", argv[0], argv[0], argv[0]); /* initialize stuff */ signal(SIGPIPE, SIG_IGN); signal(SIGINT, sig_int_handler); signal(SIGTERM, sig_int_handler); if (argc == 4 && atol(argv[3]) > 0) ATTACKERS = atol(argv[3]); address = argv[1]; port = argv[2]; prep_msg(); switch (test_server(5)) { case SERVER_OK: fprintf(stderr, "* PASSED sanity test.\n"); break; case OPENFILE_LIMIT: ASSERT_COND(0, "FAILED to connect to %s:%s - no open files available?", address, port); break; case CONNECTION_FAILED: ASSERT_COND(0, "FAILED to connect to %s:%s", address, port); break; case REQUEST_FAILED: ASSERT_COND(0, "FAILED to send request to %s:%s", address, port); break; case RESPONSE_TIMEOUT: ASSERT_COND(0, "FAILED, response timed out for %s:%s", address, port); break; } fprintf(stderr, "* Starting %zu attack loops, with %zu bytes per request.\n", ATTACKERS, MSG_LEN / REQ_PER_MSG); size_t thread_count = 0; pthread_t *threads = calloc(sizeof(*threads), ATTACKERS + 1); ASSERT_COND(threads, "couldn't allocate memoryt for thread data store"); time_t start = 0; time(&start); for (size_t i = 0; i < ATTACKERS; ++i) { if (pthread_create(threads + thread_count, NULL, attack_server_task, NULL) == 0) ++thread_count; } if (pthread_create(threads + thread_count, NULL, test_server_task, NULL) == 0) ++thread_count; if (!thread_count) { attack_server(); test_server_task(NULL); } else if (TEST_TIME) { for (int i = 0; i < TEST_TIME && flag; ++i) { const struct timespec tm = {.tv_sec = 1}; nanosleep(&tm, NULL); } flag = 0; fprintf(stderr, "* Stopping test...\n"); } while (thread_count) { --thread_count; pthread_join(threads[thread_count], NULL); } time_t end = 0; time(&end); fprintf(stderr, "Stats:\n" "\tTest length: %zu seconds\n" "\tConcurrent attackers: %zu\n" "\tRequests sent: %zu\n" "\tBytes sent: %zu\n" "\tBytes received: %zu\n" "\tSucceful requests: %zu / %zu\n" "\tDisconnections: %zu\n" "\tEOF on attempted read: %zu\n" "\tSlowest test cycle: %zu\n", end - start, ATTACKERS, total_requests, (total_requests * (MSG_LEN / REQ_PER_MSG)), total_reads, total_success, total_attempts, total_disconnections, total_eof, max_wait); if (max_wait > 5 || total_attempts != total_success) { result = RESULT_FAILED; fprintf(stderr, "FAILED! the server experienced DoS at least once or " "took more than 10 seconds to respond.\n"); } else if ((max_wait > 1 || ((total_disconnections / 2) / (end - start) == 0)) && !total_eof) { result = RESULT_UNKNOWN; fprintf(stderr, "Unknown. Server may have been partially effected.\n"); } else { result = RESULT_PASSED; fprintf(stderr, "PASSED.\n"); } return result; }
/* ***************************************************************************** Main attack function ***************************************************************************** */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/slowloris.c#L163-L264
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
set_non_block
static int set_non_block(int fd) { /* If they have O_NONBLOCK, use the Posix way to do it */ #if defined(O_NONBLOCK) /* Fixme: O_NONBLOCK is defined but broken on SunOS 4.1.x and AIX 3.2.5. */ int flags; if (-1 == (flags = fcntl(fd, F_GETFL, 0))) flags = 0; // printf("flags initial value was %d\n", flags); return fcntl(fd, F_SETFL, flags | O_NONBLOCK | O_CLOEXEC); #elif defined(FIONBIO) /* Otherwise, use the old way of doing it */ static int flags = 1; return ioctl(fd, FIONBIO, &flags); #else #error No functions / argumnet macros for non-blocking sockets. #endif }
/* ***************************************************************************** IO Helpers ***************************************************************************** */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/slowloris.c#L290-L306
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
connect2tcp
static int __attribute__((unused)) connect2tcp(const char *a, const char *p) { /* TCP/IP socket */ struct addrinfo hints = {0}; struct addrinfo *addrinfo; // will point to the results memset(&hints, 0, sizeof hints); // make sure the struct is empty hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6 hints.ai_socktype = SOCK_STREAM; // TCP stream sockets hints.ai_flags = AI_PASSIVE; // fill in my IP for me if (getaddrinfo(a, p, &hints, &addrinfo)) { // perror("addr err"); return -1; } // get the file descriptor int fd = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol); if (fd == -1 || set_non_block(fd) < 0) { freeaddrinfo(addrinfo); return -1; } int one = 1; setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); errno = 0; for (struct addrinfo *i = addrinfo; i; i = i->ai_next) { if (connect(fd, i->ai_addr, i->ai_addrlen) == 0 || errno == EINPROGRESS) goto socket_okay; perror("Connect failed..."); } freeaddrinfo(addrinfo); close(fd); return -1; socket_okay: freeaddrinfo(addrinfo); return fd; }
/** Opens a TCP/IP connection using a blocking IO socket */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/slowloris.c#L309-L343
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
wait__internal
static inline int wait__internal(int fd, uint16_t events) { errno = 0; int i = 0; if (fd == -1) goto badfd; struct pollfd ls = {.fd = fd, .events = events}; i = poll(&ls, 1, 1000); if (i > 0) { if ((ls.revents & POLLHUP) || (ls.revents & POLLERR) || (ls.revents & POLLNVAL)) goto badfd; return 0; } switch (errno) { case EFAULT: /* overflow */ case EINVAL: /* overflow */ case ENOMEM: /* overflow */ return -1; } errno = EWOULDBLOCK; return -1; badfd: errno = EBADF; return -1; }
/* ***************************************************************************** Polling Helpers ***************************************************************************** */ /** Waits for socket to become available for either reading or writing */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/slowloris.c#L350-L374
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
wait4fd
static __attribute__((unused)) int wait4fd(int fd) { return wait__internal(fd, POLLIN | POLLOUT); }
/** Waits for socket to become available for either reading or writing */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/slowloris.c#L377-L379
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
wait4read
static __attribute__((unused)) int wait4read(int fd) { return wait__internal(fd, POLLIN); }
/** Waits for socket to become available for reading */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/slowloris.c#L381-L383
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
wait4write
static __attribute__((unused)) int wait4write(int fd) { return wait__internal(fd, POLLOUT); }
/** Waits for socket to become available for reading */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/slowloris.c#L385-L387
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
test_server
static test_err_en test_server(size_t timeout) { int fd = connect2tcp(address, port); if (fd == -1) { if (errno == EMFILE || errno == ENFILE || errno == ENOMEM) return OPENFILE_LIMIT; return CONNECTION_FAILED; } time_t start = 0; time(&start); size_t blocks = 0; while (wait4write(fd) < 0) { if (errno != EWOULDBLOCK || ++blocks >= timeout || !flag) { /* timeout / error / stop */ close(fd); if (!flag) return SERVER_OK; return CONNECTION_FAILED; } } // fprintf(stderr, "* TEST: connected to %s:%s\n", address, port); if (write(fd, MSG_OUTPUT, MSG_LEN / REQ_PER_MSG) != (ssize_t)(MSG_LEN / REQ_PER_MSG)) { /* a new connection and the buffer is full? no... */ close(fd); // fprintf(stderr, "* TEST: couldn't send rerquest to %s:%s\n", address, // port); return REQUEST_FAILED; } blocks = 0; while (wait4read(fd) < 0) { if (errno != EWOULDBLOCK || ++blocks >= timeout || !flag) { /* timeout / error */ close(fd); if (!flag) return SERVER_OK; return RESPONSE_TIMEOUT; } } char buffer[4096]; if (read(fd, buffer, 1024) < 12) { close(fd); return RESPONSE_TIMEOUT; } close(fd); // fprintf(stderr, "* TEST: received response from %s:%s\n", address, port); time_t end = 0; time(&end); if (max_wait < (size_t)(end - start)) { /* non-atomic... but who cares. */ max_wait = end - start; } return SERVER_OK; }
/* ***************************************************************************** Test ***************************************************************************** */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/slowloris.c#L393-L451
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
zap
github_2023
zigzap
c
attack_server
static void attack_server(void) { int fd = connect2tcp(address, port); size_t offset = 0; uint8_t read_once = 0; while (flag) { if (wait4write(fd) == 0) { ssize_t w = write(fd, MSG_OUTPUT + offset, MSG_LEN - offset); if (w < 0) { /* error... waiting? */ if (errno != EWOULDBLOCK && errno != EAGAIN && errno != EINTR) { break; } } else { offset += w; if (offset >= MSG_LEN) { offset = 0; atomic_add(&total_requests, REQ_PER_MSG); } } } else if (errno != EWOULDBLOCK && errno != EAGAIN) { break; } if (wait4read(fd) == 0) { size_t buf; ssize_t r = read(fd, &buf, sizeof(buf)); if (r < 0) break; /* read a few bytes at a time */ if (!r) { atomic_add(&total_eof, 1); } else { atomic_add(&total_reads, r); read_once = 1; } } else if (errno == EWOULDBLOCK || errno == EAGAIN) { if (read_once) { atomic_add(&total_eof, 1); break; } } else { if (read_once) break; } } if (flag) atomic_add(&total_disconnections, 1); close(fd); return; }
/* ***************************************************************************** Attack ***************************************************************************** */
https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/tests/slowloris.c#L457-L505
675c65b509d48c21a8d1fa4c5ec53fc407643a3b
flipper-zero-tutorials
github_2023
jamisonderek
c
i2c_find_device
static uint8_t i2c_find_device() { uint8_t addr = 0; furi_hal_i2c_acquire(i2c_bus); for(uint8_t try_addr = 0x20; try_addr != 0xff; try_addr++) { if(furi_hal_i2c_is_device_ready(i2c_bus, try_addr, 10)) { addr = try_addr; FURI_LOG_D(TAG, "Found device at %02x", addr); break; } } if(addr == 0) { FURI_LOG_D(TAG, "Failed to find device."); } furi_hal_i2c_release(i2c_bus); return addr; }
/** * @brief Find an I2C device on the external bus. * @details This function scans the external I2C bus to find a device. * Ideally only a MCP4725 would be connected. It returns the first address of any device found. * @return The address of the device, or 0 if not found. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/dac/app.c#L75-L90
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
i2c_set_voltage
static void i2c_set_voltage(VoltageModel* voltage_model, uint16_t amount) { furi_assert(voltage_model != NULL); if(amount > 4095) { amount = 4095; } uint32_t timeout = 100; uint8_t buffer[3] = {0x0}; // We use the 3-bytes to transfer data. // There is also a 2-byte transfer which should be able to send the data slightly quicker? buffer[0] = 0; /// PD1/PD0 = Normal Mode. buffer[0] |= 0b01000000; // Write DAC register. if(voltage_model->write_eeprom) { // If you set this, the voltage will be set at power up. buffer[0] |= 0b01100000; // Write DAC register + EEPROM. } buffer[1] = amount >> 4; buffer[2] = amount << 4; // If we don't know the address, we need to find it. if(voltage_model->i2c_address == 0) { uint8_t addr = i2c_find_device(); if(addr == 0) { FURI_LOG_E(TAG, "Device not ready."); return; } voltage_model->i2c_address = addr; } furi_hal_i2c_acquire(i2c_bus); furi_hal_i2c_tx(i2c_bus, voltage_model->i2c_address, buffer, COUNT_OF(buffer), timeout); // If we need to confirm the DAC is ready, we wait for ready bit to get set. if(voltage_model->confirm_i2c_ready) { for(int i = 0; i < 20; i++) { furi_hal_i2c_rx(i2c_bus, voltage_model->i2c_address, buffer, 2, timeout); if(buffer[0] & 0x80) { // DAC ready bit. break; } FURI_LOG_D(TAG, "Waiting for DAC to be ready. %02x %02x", buffer[0], buffer[1]); } } furi_hal_i2c_release(i2c_bus); }
/** * @brief Set the voltage on the MCP4725. * @details This function sets the voltage on the MCP4725. It writes the value to the DAC register. * @param voltage_model The voltage model object. * @param amount The amount to set the voltage register to (0 to 4095). */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/dac/app.c#L98-L144
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
navigation_exit_callback
static uint32_t navigation_exit_callback(void* _context) { UNUSED(_context); return VIEW_NONE; }
/** * @brief Callback for exiting the application. * @details Return VIEW_NONE to indicate that we want to exit the application. * @param _context The context - unused * @return next view id (VIEW_NONE) */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/dac/app.c#L152-L155
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
navigation_submenu_callback
static uint32_t navigation_submenu_callback(void* _context) { UNUSED(_context); return DacViewSubmenu; }
/** * @brief Callback for returning to submenu. * @details This function is called when user press back button. We return DacViewSubmenu to * indicate that we want to navigate to the submenu. * @param _context The context - unused * @return next view id (DacViewSubmenu) */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/dac/app.c#L164-L167
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
submenu_selection_callback
static void submenu_selection_callback(void* context, uint32_t index) { DacApp* app = (DacApp*)context; switch(index) { case DacSubmenuIndexVoltage: view_dispatcher_switch_to_view(app->view_dispatcher, DacViewVoltage); break; case DacSubmenuIndexAbout: view_dispatcher_switch_to_view(app->view_dispatcher, DacViewAbout); break; default: break; } }
/** * @brief Handle submenu item selection. * @details This function is called when user selects an item from the submenu. * @param context The context - DacApp object. * @param index The SubmenuIndex item that was clicked. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/dac/app.c#L175-L187
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
voltage_view_draw_callback
static void voltage_view_draw_callback(Canvas* canvas, void* model) { VoltageModel* my_model = (VoltageModel*)model; canvas_set_font(canvas, FontPrimary); canvas_draw_str_aligned(canvas, 10, 1, AlignLeft, AlignTop, "Voltage"); canvas_set_font(canvas, FontSecondary); FuriString* str = furi_string_alloc(); furi_string_printf(str, "PWM Freq: %u Hz", my_model->pwm_frequency); canvas_draw_str_aligned(canvas, 10, 15, AlignLeft, AlignTop, furi_string_get_cstr(str)); furi_string_printf(str, "PWM Duty: %u %%", my_model->pwm_duty); canvas_draw_str_aligned(canvas, 10, 25, AlignLeft, AlignTop, furi_string_get_cstr(str)); furi_string_printf( str, "MCP4725: %u (%u %%)", my_model->mcp_4725_value, my_model->mcp_4725_value * 100 / 4095); canvas_draw_str_aligned(canvas, 10, 35, AlignLeft, AlignTop, furi_string_get_cstr(str)); furi_string_printf(str, "ADC Input: %1.3f V", (double)(my_model->adc_value / 1000.0f)); canvas_draw_str_aligned(canvas, 10, 45, AlignLeft, AlignTop, furi_string_get_cstr(str)); // canvas_draw_str_aligned(canvas, 10, 57, AlignLeft, AlignTop, "CAPS STATUS MESSAGE!!!"); canvas_draw_str_aligned(canvas, 1, 15 + (10 * my_model->item), AlignLeft, AlignTop, ">"); furi_string_free(str); }
/** * @brief Callback for drawing the voltage screen. * @details This function is called when the screen needs to be redrawn, like when the model gets updated. * @param canvas The canvas to draw on. * @param model The model - MyModel object. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/dac/app.c#L195-L224
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
dac_timer_callback
static void dac_timer_callback(void* context) { DacApp* app = (DacApp*)context; view_dispatcher_send_custom_event(app->view_dispatcher, DacEventIdSampleAdc); }
/** * @brief Callback for timer elapsed. * @details This function is called when the timer is elapsed. We use this to queue a redraw event. * @param context The context - DacApp object. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/dac/app.c#L231-L234
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
voltage_view_enter_callback
static void voltage_view_enter_callback(void* context) { uint32_t period = furi_ms_to_ticks(200); DacApp* app = (DacApp*)context; furi_assert(app->timer == NULL); app->timer = furi_timer_alloc(dac_timer_callback, FuriTimerTypePeriodic, context); furi_timer_start(app->timer, period); view_dispatcher_send_custom_event(app->view_dispatcher, DacEventIdUpdatePWM); view_dispatcher_send_custom_event(app->view_dispatcher, DacEventIdUpdateMcp4725); }
/** * @brief Callback when the user starts the voltage screen. * @details This function is called when the user enters the voltage screen. We start a timer to * redraw the screen periodically (so the random number is refreshed). * @param context The context - DacApp object. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/dac/app.c#L242-L250
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
voltage_view_exit_callback
static void voltage_view_exit_callback(void* context) { DacApp* app = (DacApp*)context; furi_timer_stop(app->timer); furi_timer_free(app->timer); app->timer = NULL; }
/** * @brief Callback when the user exits the voltage screen. * @details This function is called when the user exits the voltage screen. We stop the timer. * @param context The context - DacApp object. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/dac/app.c#L257-L262
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
voltage_view_custom_event_callback
static bool voltage_view_custom_event_callback(uint32_t event, void* context) { DacApp* app = (DacApp*)context; bool redraw = false; switch(event) { case DacEventIdSampleAdc: // Read a new ADC voltage value. { redraw = true; with_view_model( app->view_voltage, VoltageModel * model, { uint16_t adc_value = furi_hal_adc_read(model->adc_handle, adc_input_channel); model->adc_value = furi_hal_adc_convert_to_voltage(model->adc_handle, adc_value); }, redraw); return true; } case DacEventIdUpdatePWM: { with_view_model( app->view_voltage, VoltageModel * model, { furi_hal_pwm_set_params(channel_pwm, model->pwm_frequency, model->pwm_duty); }, redraw); return true; } case DacEventIdUpdateMcp4725: { with_view_model( app->view_voltage, VoltageModel * model, { i2c_set_voltage(model, model->mcp_4725_value); }, redraw); return true; } default: return false; } }
/** * @brief Callback for custom events. * @details This function is called when a custom event is sent to the view dispatcher. * @param event The event id - DacEventId value. * @param context The context - DacApp object. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/dac/app.c#L270-L309
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
voltage_view_input_callback
static bool voltage_view_input_callback(InputEvent* event, void* context) { DacApp* app = (DacApp*)context; if(event->type == InputTypeShort) { bool redraw = true; if(event->key == InputKeyLeft) { // Left button clicked, reduce x coordinate. with_view_model( app->view_voltage, VoltageModel * model, { switch(model->item) { case DacVoltageItemFreq: model->pwm_frequency = model->pwm_frequency / 1.5; if(model->pwm_frequency < 1) { model->pwm_frequency = 1; } view_dispatcher_send_custom_event( app->view_dispatcher, DacEventIdUpdatePWM); break; case DacVoltageItemDuty: if(model->pwm_duty <= 1) { model->pwm_duty = 1; } else if(model->pwm_duty < 10) { model->pwm_duty = model->pwm_duty - 1; } else { model->pwm_duty = model->pwm_duty - 5; } view_dispatcher_send_custom_event( app->view_dispatcher, DacEventIdUpdatePWM); break; case DacVoltageItemMcp4725: if(model->mcp_4725_value <= 0) { model->mcp_4725_value = 0; } else if(model->mcp_4725_value < 20) { model->mcp_4725_value = model->mcp_4725_value - 1; } else if(model->mcp_4725_value < 200) { model->mcp_4725_value = model->mcp_4725_value - 10; } else { model->mcp_4725_value -= 100; } view_dispatcher_send_custom_event( app->view_dispatcher, DacEventIdUpdateMcp4725); break; default: break; } }, redraw); } else if(event->key == InputKeyRight) { // Right button clicked, increase x coordinate. with_view_model( app->view_voltage, VoltageModel * model, { switch(model->item) { case DacVoltageItemFreq: if(model->pwm_frequency > 40000) { model->pwm_frequency = 65535; } else { model->pwm_frequency = model->pwm_frequency * 1.5; } view_dispatcher_send_custom_event( app->view_dispatcher, DacEventIdUpdatePWM); break; case DacVoltageItemDuty: if((model->pwm_duty >= 90) || ((model->pwm_duty >= 30 && model->pwm_duty <= 55))) { model->pwm_duty = model->pwm_duty + 1; } else { model->pwm_duty = model->pwm_duty + 5; } if(model->pwm_duty >= 100) { model->pwm_duty = 100; } view_dispatcher_send_custom_event( app->view_dispatcher, DacEventIdUpdatePWM); break; case DacVoltageItemMcp4725: if(model->mcp_4725_value >= 4095) { model->mcp_4725_value = 4095; } else if( (model->mcp_4725_value < 20) || (model->mcp_4725_value > 4095 - 20) || (model->mcp_4725_value > 2048 - 20 && model->mcp_4725_value < 2048 + 20)) { model->mcp_4725_value = model->mcp_4725_value + 1; } else if( (model->mcp_4725_value < 200) || (model->mcp_4725_value > 4095 - 200) || (model->mcp_4725_value > 2048 - 200 && model->mcp_4725_value < 2048 + 200)) { model->mcp_4725_value = model->mcp_4725_value + 10; } else { model->mcp_4725_value += 100; } if(model->mcp_4725_value >= 4095) { model->mcp_4725_value = 4095; } view_dispatcher_send_custom_event( app->view_dispatcher, DacEventIdUpdateMcp4725); break; default: break; } }, redraw); } else if(event->key == InputKeyUp) { // Choose previous item. with_view_model( app->view_voltage, VoltageModel * _model, { if(_model->item > 0) { _model->item--; } }, redraw); } else if(event->key == InputKeyDown) { // Choose next item. with_view_model( app->view_voltage, VoltageModel * _model, { if(_model->item < DacVoltageItemCount - 1) { _model->item++; } }, redraw); } } return false; }
/** * @brief Callback for voltage screen input. * @details This function is called when the user presses a button while on the voltage screen. * @param event The event - InputEvent object. * @param context The context - DacApp object. * @return true if the event was handled, false otherwise. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/dac/app.c#L318-L449
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
dac_app_free
static void dac_app_free(DacApp* app) { with_view_model( app->view_voltage, VoltageModel * model, { furi_hal_adc_release(model->adc_handle); }, false); furi_hal_pwm_stop(channel_pwm); view_dispatcher_remove_view(app->view_dispatcher, DacViewAbout); widget_free(app->widget_about); view_dispatcher_remove_view(app->view_dispatcher, DacViewVoltage); view_free(app->view_voltage); view_dispatcher_remove_view(app->view_dispatcher, DacViewSubmenu); submenu_free(app->submenu); view_dispatcher_free(app->view_dispatcher); furi_record_close(RECORD_GUI); free(app); }
/** * @brief Free the dac application. * @details This function frees the dac application resources. * @param app The dac application object. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/dac/app.c#L554-L572
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
attempt_enable_5v
static bool attempt_enable_5v() { bool enabled_5v = false; if(furi_hal_power_is_otg_enabled() || furi_hal_power_is_charging()) { enabled_5v = false; } else { // Some other apps make multiple attempts, so we retry too. uint8_t attempts = 5; while(--attempts > 0) { if(furi_hal_power_enable_otg()) { enabled_5v = true; break; } } } return enabled_5v; }
/** * @brief Attempt to enable +5 Volt GPIO pin #1. * @details This function attempts to enable 5V power. It will return true if not already enabled and it was successful. * @return true if 5V was enabled, false otherwise. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/dac/app.c#L579-L594
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
analog_output_app
int32_t analog_output_app(void* _p) { UNUSED(_p); DacApp* app = dac_app_alloc(); bool app_enabled_5v = attempt_enable_5v(); view_dispatcher_run(app->view_dispatcher); dac_app_free(app); if(app_enabled_5v) { furi_hal_power_disable_otg(); } return 0; }
/** * @brief Main function for application. * @details This function is the entry point for the application. It should be defined in * application.fam as the entry_point setting. * @param _p Input parameter - unused * @return 0 - Success */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/dac/app.c#L603-L613
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
gpio_7segment_input_callback
static void gpio_7segment_input_callback(InputEvent* input_event, FuriMessageQueue* queue) { furi_assert(queue); GpioEvent event = {.type = GpioEventTypeKey, .input = *input_event}; furi_message_queue_put(queue, &event, FuriWaitForever); }
// Invoked when input (button press) is detected. Queues message and returns to caller. // @param input_event the input event that caused the callback to be invoked. // @param queue the message queue for queueing key event.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/gpio_7segment/gpio_7segment_app.c#L104-L108
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
gpio_7segment_render_callback
static void gpio_7segment_render_callback(Canvas* canvas, void* ctx) { // Attempt to aquire context, so we can read the data. GpioContext* context = ctx; if(furi_mutex_acquire(context->mutex, 200) != FuriStatusOk) { return; } GpioData* data = context->data; // Title canvas_set_font(canvas, FontPrimary); canvas_draw_str_aligned(canvas, 5, 0, AlignLeft, AlignTop, "GPIO 7-Segment LED"); // Draw two boxes (7-segment LEDs) canvas_draw_frame(canvas, 45, 22, 20, 16); canvas_draw_frame(canvas, 45, 37, 20, 16); // Draw the labels (use CAPS if LED should be glowing.) int index = 7 * data->digit; canvas_draw_str_aligned(canvas, 50, 39, AlignLeft, AlignTop, digits[index++] ? "A7" : "a7"); canvas_draw_str_aligned(canvas, 66, 39, AlignLeft, AlignTop, digits[index++] ? "A6" : "a6"); canvas_draw_str_aligned(canvas, 50, 54, AlignLeft, AlignTop, digits[index++] ? "A4" : "a4"); canvas_draw_str_aligned(canvas, 32, 39, AlignLeft, AlignTop, digits[index++] ? "B3" : "b3"); canvas_draw_str_aligned(canvas, 32, 26, AlignLeft, AlignTop, digits[index++] ? "B2" : "b2"); canvas_draw_str_aligned(canvas, 50, 13, AlignLeft, AlignTop, digits[index++] ? "C3" : "c3"); canvas_draw_str_aligned(canvas, 66, 26, AlignLeft, AlignTop, digits[index++] ? "C1" : "c1"); // Tell user if GPIO pins are GND or 3.3v to glow. canvas_draw_str_aligned(canvas, 90, 40, AlignLeft, AlignTop, data->invert?"GND":"3.3v"); // Display the current number. furi_string_printf(data->buffer, "Digit: %d", data->digit); canvas_draw_str_aligned(canvas, 90, 50, AlignLeft, AlignTop, furi_string_get_cstr(data->buffer)); // Release the context, so other threads can update the data. furi_mutex_release(context->mutex); }
// Invoked by the draw callback to render the screen. // @param canvas surface to draw on. // @param ctx a pointer to the application GpioContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/gpio_7segment/gpio_7segment_app.c#L113-L149
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
gpio_7segment_show
void gpio_7segment_show(int digit, bool invert) { // There are 7 segments per digit. int index = 7 * digit; furi_hal_gpio_write(&gpio_ext_pa7, digits[index++] ^ invert); furi_hal_gpio_write(&gpio_ext_pa6, digits[index++] ^ invert); furi_hal_gpio_write(&gpio_ext_pa4, digits[index++] ^ invert); furi_hal_gpio_write(&gpio_ext_pb3, digits[index++] ^ invert); furi_hal_gpio_write(&gpio_ext_pb2, digits[index++] ^ invert); furi_hal_gpio_write(&gpio_ext_pc3, digits[index++] ^ invert); furi_hal_gpio_write(&gpio_ext_pc1, digits[index++] ^ invert); }
// Sets the GPIO pin output to display a number. // @param digit a value between 0-9 to display. // @param invert use true if your 7-segment LED display is common anode // (and all the output pins go to cathode side of LEDs). use false if // your display is common cathode.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/gpio_7segment/gpio_7segment_app.c#L156-L167
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
gpio_7segment_disconnect_pin
void gpio_7segment_disconnect_pin(const GpioPin* pin) { furi_hal_gpio_init(pin, GpioModeOutputOpenDrain, GpioPullNo, GpioSpeedLow); furi_hal_gpio_write(pin, true); }
// Disconnects a GpioPin via OutputOpenDrive, PushPullNo, output true. // @pin pointer to GpioPin to disconnect.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/gpio_7segment/gpio_7segment_app.c#L171-L174
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
gpio_7segment_app
int32_t gpio_7segment_app(void* p) { UNUSED(p); // Configure our initial data. GpioContext* context = malloc(sizeof(GpioContext)); context->mutex = furi_mutex_alloc(FuriMutexTypeNormal); context->data = malloc(sizeof(GpioData)); context->data->buffer = furi_string_alloc(); context->data->digit = 8; context->data->invert = false; // Queue for events (input) context->queue = furi_message_queue_alloc(8, sizeof(GpioEvent)); // Set ViewPort callbacks ViewPort* view_port = view_port_alloc(); view_port_draw_callback_set(view_port, gpio_7segment_render_callback, context); view_port_input_callback_set(view_port, gpio_7segment_input_callback, context->queue); // Set our 7 GPIO external pins to output (push-pull). // NOTE: For common anode LED, we *could* use GpioModeOutputOpenDrain. furi_hal_gpio_init_simple(&gpio_ext_pa7, GpioModeOutputPushPull); furi_hal_gpio_init_simple(&gpio_ext_pa6, GpioModeOutputPushPull); furi_hal_gpio_init_simple(&gpio_ext_pa4, GpioModeOutputPushPull); furi_hal_gpio_init_simple(&gpio_ext_pb3, GpioModeOutputPushPull); furi_hal_gpio_init_simple(&gpio_ext_pb2, GpioModeOutputPushPull); furi_hal_gpio_init_simple(&gpio_ext_pc3, GpioModeOutputPushPull); furi_hal_gpio_init_simple(&gpio_ext_pc1, GpioModeOutputPushPull); // Display the number (this should light all 7 of the LED segments) gpio_7segment_show(context->data->digit, context->data->invert); // Open GUI and register view_port Gui* gui = furi_record_open(RECORD_GUI); gui_add_view_port(gui, view_port, GuiLayerFullscreen); // Main loop GpioEvent event; bool processing = true; do { if (furi_message_queue_get(context->queue, &event, FuriWaitForever) == FuriStatusOk) { FURI_LOG_T(TAG, "Got event type: %d", event.type); switch (event.type) { case GpioEventTypeKey: // Short press of back button exits the program. if (event.input.type == InputTypeShort && event.input.key == InputKeyBack) { FURI_LOG_I(TAG, "Short-Back pressed. Exiting program."); processing = false; } else if (event.input.type == InputTypeShort && event.input.key == InputKeyOk) { FURI_LOG_I(TAG, "OK pressed."); if (furi_mutex_acquire(context->mutex, FuriWaitForever) == FuriStatusOk) { // Pick a random number between 1 and 6... context->data->digit = (furi_hal_random_get() % 6) + 1; gpio_7segment_show(context->data->digit, context->data->invert); furi_mutex_release(context->mutex); } } else if (event.input.type == InputTypeShort && event.input.key == InputKeyUp) { FURI_LOG_I(TAG, "UP pressed."); if (furi_mutex_acquire(context->mutex, FuriWaitForever) == FuriStatusOk) { // Invert our output (switch between common anode/cathode 7-segment LEDs) context->data->invert = !context->data->invert; gpio_7segment_show(context->data->digit, context->data->invert); furi_mutex_release(context->mutex); } } break; default: break; } // Send signal to update the screen (callback will get invoked at some point later.) view_port_update(view_port); } else { // We had an issue getting message from the queue, so exit application. processing = false; } } while (processing); // Disconnect the GPIO pins. gpio_7segment_disconnect_pin(&gpio_ext_pa7); gpio_7segment_disconnect_pin(&gpio_ext_pa6); gpio_7segment_disconnect_pin(&gpio_ext_pa4); gpio_7segment_disconnect_pin(&gpio_ext_pb3); gpio_7segment_disconnect_pin(&gpio_ext_pb2); gpio_7segment_disconnect_pin(&gpio_ext_pc3); gpio_7segment_disconnect_pin(&gpio_ext_pc1); // Free resources view_port_enabled_set(view_port, false); gui_remove_view_port(gui, view_port); view_port_free(view_port); furi_record_close(RECORD_GUI); furi_message_queue_free(context->queue); furi_mutex_free(context->mutex); furi_string_free(context->data->buffer); free(context->data); free(context); return 0; }
// This is the entry point to our application.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/gpio_7segment/gpio_7segment_app.c#L177-L277
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
demo_input_callback
static void demo_input_callback(InputEvent* input_event, FuriMessageQueue* queue) { furi_assert(queue); DemoEvent event = {.type = DemoEventTypeKey, .input = *input_event}; furi_message_queue_put(queue, &event, FuriWaitForever); }
// The LED at the time of GPIO interrupt (or 0 if none). // Invoked when input (button press) is detected. // We queue a message and then return to the caller. // @input_event the button that triggered the callback. // @queue our message queue.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/gpio_interrupt_demo/gpio_interrupt_demo_app.c#L67-L71
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
demo_tick
static void demo_tick(void* ctx) { furi_assert(ctx); FuriMessageQueue* queue = ctx; DemoEvent event = {.type = DemoEventTypeTick}; furi_message_queue_put(queue, &event, 0); }
// Invoked from our timer. We queue a message and then return to the caller. // @ctx our message queue.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/gpio_interrupt_demo/gpio_interrupt_demo_app.c#L75-L80
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
demo_gpio_fall_callback
static void demo_gpio_fall_callback(void* ctx) { UNUSED(ctx); selectedLed = currentLed; }
// Invoked when our GPIO pin transitions from VCC to GND. // @ctx unused for this method.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/gpio_interrupt_demo/gpio_interrupt_demo_app.c#L84-L87
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
demo_render_callback
static void demo_render_callback(Canvas* canvas, void* ctx) { // Attempt to aquire context, so we can read the data. DemoContext* demo_context = ctx; if(furi_mutex_acquire(demo_context->mutex, 200) != FuriStatusOk) { return; } DemoData* data = demo_context->data; if(selectedLed) { furi_string_printf(data->buffer, "Stopped on LED %d.", selectedLed); } else { furi_string_printf(data->buffer, "GND pin C3 to stop."); } canvas_set_font(canvas, FontPrimary); canvas_draw_str_aligned( canvas, 10, 20, AlignLeft, AlignTop, furi_string_get_cstr(data->buffer)); // Release the context, so other threads can update the data. furi_mutex_release(demo_context->mutex); }
// Invoked by the draw callback to render the screen. // We render our UI on the callback thread. // @canvas the surface to render our UI // @ctx a pointer to a DemoContext object.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/gpio_interrupt_demo/gpio_interrupt_demo_app.c#L93-L113
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
update_led
void update_led(uint8_t led) { if(led == 1 || led == 3) { // Pin A7 is 3.3 volts for LED 1 & 3. furi_hal_gpio_init(&gpio_ext_pa7, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow); furi_hal_gpio_write(&gpio_ext_pa7, true); } else { furi_hal_gpio_init(&gpio_ext_pa7, GpioModeOutputOpenDrain, GpioPullNo, GpioSpeedLow); // Pin A7 is GND (false) for LED 2 & 4. furi_hal_gpio_write(&gpio_ext_pa7, !(led == 2 || led == 4)); } if(led == 2 || led == 5) { // Pin A6 is 3.3 volts for LED 2 & 5. furi_hal_gpio_init(&gpio_ext_pa6, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow); furi_hal_gpio_write(&gpio_ext_pa6, true); } else { furi_hal_gpio_init(&gpio_ext_pa6, GpioModeOutputOpenDrain, GpioPullNo, GpioSpeedLow); // Pin A6 is GND (false) for LED 1 & 6. furi_hal_gpio_write(&gpio_ext_pa6, !(led == 1 || led == 6)); } if(led == 4 || led == 6) { // Pin A4 is 3.3 volts for LED 4 & 6. furi_hal_gpio_init(&gpio_ext_pa4, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow); furi_hal_gpio_write(&gpio_ext_pa4, true); } else { furi_hal_gpio_init(&gpio_ext_pa4, GpioModeOutputOpenDrain, GpioPullNo, GpioSpeedLow); // Pin A4 is GND (false) for LED 3 & 5. furi_hal_gpio_write(&gpio_ext_pa4, !(led == 3 || led == 5)); } }
// Turns on one of the LEDs. // @pin the LED to turn on (value of 1-6)
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/gpio_interrupt_demo/gpio_interrupt_demo_app.c#L117-L147
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
disconnect_pin
void disconnect_pin(const GpioPin* pin) { furi_hal_gpio_init(pin, GpioModeOutputOpenDrain, GpioPullNo, GpioSpeedLow); furi_hal_gpio_write(pin, true); }
// Disconnects a GpioPin via OutputOpenDrive, PushPullNo, output true. // @pin pointer to GpioPin to disconnect.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/gpio_interrupt_demo/gpio_interrupt_demo_app.c#L151-L154
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
gpio_interrupt_demo_app
int32_t gpio_interrupt_demo_app(void* p) { UNUSED(p); // Configure our initial data. DemoContext* demo_context = malloc(sizeof(DemoContext)); demo_context->mutex = furi_mutex_alloc(FuriMutexTypeNormal); demo_context->data = malloc(sizeof(DemoData)); demo_context->data->buffer = furi_string_alloc(); // Queue for events (tick or input) demo_context->queue = furi_message_queue_alloc(8, sizeof(DemoEvent)); // LEDs connected on GPIO output pins (A7, A6, A4) via 220 ohm resistors. currentLed = 1; selectedLed = 0; update_led(currentLed); // GPIO pin (C3) is pull-up to VCC. Add switch to ground for change in value. // I use 220ohm resistor from switch to C3 (but optional if you are SURE // the pin is in input/interrupt mode). // // GpioModeInterruptRiseFall means callback invoked when going from VCC (from our // pull-up resistor) to GND. // // NOTE: You can use GpioModeInterruptRise for invoking on a GND->VCC and // GpioModeInterruptRiseFall for invoking on both transitions. // furi_hal_gpio_init(&gpio_ext_pc3, GpioModeInterruptFall, GpioPullUp, GpioSpeedVeryHigh); // NOTE: "add_int_callback" does "enable_int_callback" automatically. // For the 3rd parameter, you can pass any object that you want to be passed // to your callback method. furi_hal_gpio_add_int_callback(&gpio_ext_pc3, demo_gpio_fall_callback, NULL); // Timer triggers every 70ms (incrementing our current LED). FuriTimer* timer = furi_timer_alloc(demo_tick, FuriTimerTypePeriodic, demo_context->queue); furi_timer_start(timer, 70); // Set ViewPort callbacks ViewPort* view_port = view_port_alloc(); view_port_draw_callback_set(view_port, demo_render_callback, demo_context); view_port_input_callback_set(view_port, demo_input_callback, demo_context->queue); // Open GUI and register view_port Gui* gui = furi_record_open(RECORD_GUI); gui_add_view_port(gui, view_port, GuiLayerFullscreen); // Main loop DemoEvent event; bool processing = true; do { if(furi_message_queue_get(demo_context->queue, &event, 1000) == FuriStatusOk) { FURI_LOG_T(TAG, "Got event type: %d", event.type); switch(event.type) { case DemoEventTypeKey: // Short press of back button exits the program. if(event.input.type == InputTypeShort && event.input.key == InputKeyBack) { FURI_LOG_I(TAG, "Short-Back pressed. Exiting program."); processing = false; } else if(event.input.type == InputTypeShort && event.input.key == InputKeyDown) { // Clear our LED stop value. selectedLed = 0; } break; case DemoEventTypeTick: if(selectedLed == 0) { if(++currentLed > 6) { currentLed = 1; } update_led(currentLed); } break; default: break; } // Send signal to update the screen (callback will get invoked at some point later.) view_port_update(view_port); } } while(processing); // Free resources furi_hal_gpio_remove_int_callback(&gpio_ext_pc3); furi_timer_free(timer); // Pull all pins open. disconnect_pin(&gpio_ext_pc3); disconnect_pin(&gpio_ext_pa7); disconnect_pin(&gpio_ext_pa6); disconnect_pin(&gpio_ext_pa4); view_port_enabled_set(view_port, false); gui_remove_view_port(gui, view_port); view_port_free(view_port); furi_record_close(RECORD_GUI); furi_message_queue_free(demo_context->queue); furi_mutex_free(demo_context->mutex); furi_string_free(demo_context->data->buffer); free(demo_context->data); free(demo_context); return 0; }
// Program entry point
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/gpio_interrupt_demo/gpio_interrupt_demo_app.c#L157-L260
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
gpio_polling_demo_input_callback
static void gpio_polling_demo_input_callback(InputEvent* input_event, FuriMessageQueue* queue) { furi_assert(queue); DemoEvent event = {.type = DemoEventTypeKey, .input = *input_event}; furi_message_queue_put(queue, &event, FuriWaitForever); }
// This is the pin used for our GPIO demo. // Invoked when input (button press) is detected. We queue a message and then return to the caller.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/gpio_polling_demo/gpio_polling_demo_app.c#L46-L50
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
gpio_polling_demo_tick
static void gpio_polling_demo_tick(void* ctx) { furi_assert(ctx); FuriMessageQueue* queue = ctx; DemoEvent event = {.type = DemoEventTypeTick}; // It's OK to loose this event if system overloaded (so we don't pass a wait value for 3rd parameter.) furi_message_queue_put(queue, &event, 0); }
// Invoked by the timer on every tick. We queue a message and then return to the caller.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/gpio_polling_demo/gpio_polling_demo_app.c#L53-L59
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
gpio_polling_demo_render_callback
static void gpio_polling_demo_render_callback(Canvas* canvas, void* ctx) { // Attempt to aquire context, so we can read the data. DemoContext* demo_context = ctx; if(furi_mutex_acquire(demo_context->mutex, 200) != FuriStatusOk) { return; } DemoData* data = demo_context->data; bool show_hello = !data->pin_grounded; int counter = data->counter; bool even_counter = (counter & 1) == 0; // If the lowest bit is 0, then counter is even. // Other fonts are FontPrimary, FontSecondary, FontKeyboard, FontBigNumbers, canvas_set_font(canvas, FontPrimary); canvas_draw_str_aligned(canvas, 64, 31, AlignLeft, AlignCenter, (show_hello ? "HELLO" : "WORLD")); // Put the lowest 4 digits of counter value into the buffer, then concatenate the text "Even" or "Odd". furi_string_printf(data->buffer, "%04u", (counter % 10000)); furi_string_cat_printf(data->buffer, " %s", (even_counter) ? ("Even") : ("Odd")); canvas_set_font(canvas, FontSecondary); canvas_draw_str_aligned(canvas, 64, 42, AlignCenter, AlignTop, furi_string_get_cstr(data->buffer)); // Release the context, so other threads can update the data. furi_mutex_release(demo_context->mutex); // Make tones if the speaker is available. if (furi_hal_speaker_acquire(1000)) { float freq = 100.0f + (counter*4.0); float volume = 1.0f; furi_hal_speaker_start(freq, volume); furi_delay_ms(100); furi_hal_speaker_stop(); furi_hal_speaker_release(); } }
// Invoked by the draw callback to render the screen. We render our UI on the callback thread.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/gpio_polling_demo/gpio_polling_demo_app.c#L62-L97
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
gpio_polling_demo_update_pin_status
static void gpio_polling_demo_update_pin_status(void* ctx) { DemoContext* demo_context = ctx; DemoData* data = demo_context->data; data->counter++; // read returns true for VCC and false for ground, so invert answer. data->pin_grounded = !furi_hal_gpio_read(&demo_message_pin); }
// Our main loop invokes this method after acquiring the mutex, so we can safely access the protected data. // We increment a counter and update if the GPIO pin is grounded.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/gpio_polling_demo/gpio_polling_demo_app.c#L101-L108
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
input_callback
static void input_callback(InputEvent* input_event, FuriMessageQueue* queue) { furi_assert(queue); DemoEvent event = {.type = DemoEventTypeKey, .input = *input_event}; furi_message_queue_put(queue, &event, FuriWaitForever); }
// Invoked when input (button press) is detected. We queue a message and then return to the caller.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/i2c_demo/i2c_demo_app.c#L57-L61
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
tick_callback
static void tick_callback(void* ctx) { furi_assert(ctx); FuriMessageQueue* queue = ctx; DemoEvent event = {.type = DemoEventTypeTick}; // It's OK to loose this event if system overloaded (so we don't pass a wait value for 3rd parameter.) furi_message_queue_put(queue, &event, 0); }
// Invoked by the timer on every tick. We queue a message and then return to the caller.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/i2c_demo/i2c_demo_app.c#L64-L70
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
render_callback
static void render_callback(Canvas* canvas, void* ctx) { // Attempt to aquire context, so we can read the data. DemoContext* demo_context = ctx; if(furi_mutex_acquire(demo_context->mutex, 200) != FuriStatusOk) { return; } DemoData* data = demo_context->data; canvas_set_font(canvas, FontPrimary); if(data->address) { canvas_draw_str_aligned(canvas, 64, 20, AlignCenter, AlignCenter, "FOUND I2C DEVICE"); furi_string_printf(data->buffer, "Address 0x%02x", (data->address)); canvas_draw_str_aligned( canvas, 64, 30, AlignCenter, AlignCenter, furi_string_get_cstr(data->buffer)); if(data->state == I2cDemoStateWriteSuccess) { canvas_draw_str_aligned(canvas, 64, 40, AlignCenter, AlignCenter, "WRITE SUCCESS"); } else if(data->state == I2cDemoStateReadSuccess) { canvas_draw_str_aligned(canvas, 64, 40, AlignCenter, AlignCenter, "READ SUCCESS"); } else if(data->state == I2cDemoStateFound) { canvas_draw_str_aligned(canvas, 64, 40, AlignCenter, AlignCenter, "FOUND DEVICE"); } else if(data->state == I2cDemoStateWriteReadSuccess) { canvas_draw_str_aligned( canvas, 64, 40, AlignCenter, AlignCenter, "WRITE/READ SUCCESS"); } furi_string_printf(data->buffer, "value %d", (data->value)); canvas_draw_str_aligned( canvas, 64, 50, AlignCenter, AlignCenter, furi_string_get_cstr(data->buffer)); } else { canvas_draw_str_aligned(canvas, 64, 20, AlignCenter, AlignCenter, "I2C NOT FOUND"); canvas_draw_str_aligned(canvas, 64, 30, AlignCenter, AlignCenter, "pin15=SDA. pin16=SCL"); canvas_draw_str_aligned(canvas, 64, 40, AlignCenter, AlignCenter, "pin9=VCC. pin18=GND"); } // Release the context, so other threads can update the data. furi_mutex_release(demo_context->mutex); }
// Invoked by the draw callback to render the screen. We render our UI on the callback thread.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/i2c_demo/i2c_demo_app.c#L73-L110
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
update_i2c_status
static void update_i2c_status(void* ctx) { DemoContext* demo_context = ctx; DemoData* data = demo_context->data; uint8_t addr = 0; addr = demo_i2c_find_device(); if(addr) { data->state = I2cDemoStateFound; if(demo_i2c_init_bh1750(addr)) { data->state = I2cDemoStateWriteSuccess; if(demo_i2c_write_one_time_h_res_mode_bh1750(addr)) { data->state = I2cDemoStateWriteSuccess; if(demo_i2c_read_one_time_h_res_mode_bh1750(addr, &data->value)) { data->state = I2cDemoStateReadSuccess; if(demo_i2c_write_read_bh1750(addr, &data->value)) { data->state = I2cDemoStateWriteReadSuccess; } } } } } data->address = addr; }
// Our main loop invokes this method after acquiring the mutex, so we can safely access the protected data.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/i2c_demo/i2c_demo_app.c#L226-L254
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
input_callback
static void input_callback(InputEvent* input_event, FuriMessageQueue* queue) { furi_assert(queue); DemoEvent event = {.type = DemoEventTypeKey, .input = *input_event}; furi_message_queue_put(queue, &event, FuriWaitForever); }
// Invoked when input (button press) is detected. // We queue a message and then return to the caller. // @input_event the button that triggered the callback. // @queue our message queue.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/memsic_2125/memsic_2125_app.c#L65-L69
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
pulse_callback
void pulse_callback(void* data) { // Get the current time from high-resolution timer. FuriHalCortexTimer timer = furi_hal_cortex_timer_get(0); uint32_t now = timer.start; // Our parameter is a pointer to the axis data. furi_assert(data); AxisData* d = (AxisData*)data; // Get the current state of the pin (true = 3.3volts, false = GND) bool state = furi_hal_gpio_read(d->pin); if(state) { // state=true, so we are in GND->3v3 transition. // See if we have timings for both the high & low transitions. if((d->high != 0) && (d->low != 0) && (d->high < d->low) && !d->reading) { uint32_t durationCycle = now - d->high; uint32_t durationLow = d->low - d->high; // Update the value of the axis to reflect the duty cycle. d->value = (100.0f * durationLow) / durationCycle; } // Store the current time that the rise transition happened. d->high = timer.start; } else { // Store the current time that the fall transition happened. d->low = timer.start; } }
// Invoked whenever the monitored pin changes state. // @data pointer to an AxisData.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/memsic_2125/memsic_2125_app.c#L73-L103
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
render_callback
static void render_callback(Canvas* canvas, void* ctx) { // Attempt to aquire context, so we can read the data. DemoContext* demo_context = ctx; DemoData* data = demo_context->data; canvas_set_font(canvas, FontPrimary); canvas_draw_str_aligned(canvas, 1, 1, AlignLeft, AlignTop, "Memsic 2125 C1:X C0:Y"); data->xData->reading = true; data->yData->reading = true; furi_string_printf( data->buffer, "%0.3f %0.3f", (double)data->xData->value, (double)data->yData->value); data->xData->reading = false; data->yData->reading = false; canvas_draw_str_aligned( canvas, 30, 55, AlignLeft, AlignTop, furi_string_get_cstr(data->buffer)); // Draw a circle based on the xData & yData information. data->xData->reading = true; uint8_t x = (0.5f + ((50.0f - data->xData->value) / 12.0f)) * 128; data->xData->reading = false; x = MAX(0, MIN(x, 127)); data->yData->reading = true; uint8_t y = (0.5f + (((float)data->yData->value - 50.0f) / 12.0f)) * 64; data->yData->reading = false; y = MAX(0, MIN(y, 63)); canvas_draw_circle(canvas, x, y, 2); }
// Invoked by the draw callback to render the screen. // We render our UI on the callback thread. // @canvas the surface to render our UI // @ctx a pointer to a DemoContext object.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/memsic_2125/memsic_2125_app.c#L109-L136
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
memsic_2125_app
int32_t memsic_2125_app(void* p) { UNUSED(p); // Configure our initial data. DemoContext* demo_context = malloc(sizeof(DemoContext)); demo_context->data = malloc(sizeof(DemoData)); demo_context->data->buffer = furi_string_alloc(); AxisData* xData = malloc(sizeof(AxisData)); xData->pin = &gpio_ext_pc1; xData->high = 0; xData->low = 0; xData->reading = false; xData->value = 0; demo_context->data->xData = xData; AxisData* yData = malloc(sizeof(AxisData)); yData->pin = &gpio_ext_pc0; yData->high = 0; yData->low = 0; yData->reading = false; yData->value = 0; demo_context->data->yData = yData; // Queue for events (tick or input) demo_context->queue = furi_message_queue_alloc(8, sizeof(DemoEvent)); // x-axis is a 100Hz pulse, with variable duty-cycle (which we need to measure). // Invoke the pulse_callback method passing the xData structure whenever the pin // transitions (Rise GND->3v3 or Fall 3v3->GND). furi_hal_gpio_init(xData->pin, GpioModeInterruptRiseFall, GpioPullNo, GpioSpeedVeryHigh); furi_hal_gpio_add_int_callback(xData->pin, pulse_callback, xData); // y-axis is a 100Hz pulse, with variable duty-cycle (which we need to measure). // Invoke the pulse_callback method passing the xData structure whenever the pin // transitions (Rise GND->3v3 or Fall 3v3->GND). furi_hal_gpio_init(yData->pin, GpioModeInterruptRiseFall, GpioPullNo, GpioSpeedVeryHigh); furi_hal_gpio_add_int_callback(yData->pin, pulse_callback, yData); // Set ViewPort callbacks ViewPort* view_port = view_port_alloc(); view_port_draw_callback_set(view_port, render_callback, demo_context); view_port_input_callback_set(view_port, input_callback, demo_context->queue); // Open GUI and register view_port Gui* gui = furi_record_open(RECORD_GUI); gui_add_view_port(gui, view_port, GuiLayerFullscreen); // Main loop DemoEvent event; bool processing = true; do { if(furi_message_queue_get(demo_context->queue, &event, FuriWaitForever) == FuriStatusOk) { FURI_LOG_T(TAG, "Got event type: %d", event.type); switch(event.type) { case DemoEventTypeKey: // Short press of back button exits the program. if(event.input.type == InputTypeShort && event.input.key == InputKeyBack) { FURI_LOG_I(TAG, "Short-Back pressed. Exiting program."); processing = false; } break; default: break; } // Send signal to update the screen (callback will get invoked at some point later.) view_port_update(view_port); } else { // We had an issue getting message from the queue, so exit application. processing = false; } } while(processing); // Free resources furi_hal_gpio_remove_int_callback(yData->pin); furi_hal_gpio_remove_int_callback(xData->pin); view_port_enabled_set(view_port, false); gui_remove_view_port(gui, view_port); view_port_free(view_port); furi_record_close(RECORD_GUI); furi_message_queue_free(demo_context->queue); furi_string_free(demo_context->data->buffer); free(demo_context->data); free(demo_context); return 0; }
// Program entry point
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/memsic_2125/memsic_2125_app.c#L139-L226
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
uart_demo_submenu_add_default_entries
static void uart_demo_submenu_add_default_entries(Submenu* submenu, void* context) { UartDemoApp* app = context; submenu_reset(submenu); submenu_add_item(submenu, "Clear", 0, uart_demo_submenu_item_callback, context); submenu_add_item(submenu, "Send Msg 1", 1, uart_demo_submenu_item_callback, context); submenu_add_item(submenu, "Send Msg 2", 2, uart_demo_submenu_item_callback, context); app->index = 3; }
/** * Adds the default submenu entries. * * @param submenu The submenu. * @param context The context to pass to the submenu item callback function. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/uart_demo/uart_demo.c#L49-L57
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
uart_helper_received_byte_callback
static void uart_helper_received_byte_callback( FuriHalSerialHandle* handle, FuriHalSerialRxEvent event, void* context) { UartHelper* helper = context; if(event == FuriHalSerialRxEventData) { uint8_t data = furi_hal_serial_async_rx(handle); furi_stream_buffer_send(helper->rx_stream, (void*)&data, 1, 0); furi_thread_flags_set(furi_thread_get_id(helper->worker_thread), WorkerEventDataWaiting); } }
/** * Invoked when a byte of data is received on the UART bus. This function * adds the byte to the stream buffer and sets the WorkerEventDataWaiting flag. * * @param handle Serial handle * @param event FuriHalSerialRxEvent * @param context UartHelper instance */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/uart_demo/uart_helper.c#L60-L71
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
uart_helper_worker
static int32_t uart_helper_worker(void* context) { UartHelper* helper = context; FuriString* line = furi_string_alloc(); uint32_t events; do { events = furi_thread_flags_wait( WorkerEventDataWaiting | WorkerEventExiting, FuriFlagWaitAny, FuriWaitForever); if(events & WorkerEventDataWaiting) { size_t length_read = 0; do { // We will read out of the stream into this temporary read_buffer in chunks // of up to 32 bytes. A tricker implementation would be to read directly // into our ring_buffer, avoiding the extra copy. uint8_t read_buffer[32]; size_t available = ring_buffer_available(helper->ring_buffer); if(available == 0) { // In our case, the buffer is large enough to hold the entire response, // so we should never hit this case & data loss is fine in the // exceptional case. // If loosing data is unacceptable, you could transfer the buffer into // a string and prepend that to the response, or you could increase the // size of the buffer. // Buffer is full, so data loss will happen at beginning of string! // We read one byte (hopefully the delimiter). available = 1; } // We will read up to 32 bytes, but no more than the available space in the // ring buffer. size_t request_bytes = available < COUNT_OF(read_buffer) ? available : COUNT_OF(read_buffer); // hasDelim will be true if at least one delimiter was found in the data. bool hasDelim = false; // Read up to 32 bytes from the stream buffer into our temporary read_buffer. length_read = furi_stream_buffer_receive(helper->rx_stream, read_buffer, request_bytes, 0); // Add the data to the ring buffer, check for delimiters, and process lines. if(length_read > 0) { // Add the data to the ring buffer. If at least one delimiter is found, // hasDelim will be true. hasDelim = ring_buffer_add(helper->ring_buffer, read_buffer, length_read); if(hasDelim) { size_t index; do { // Find the next delimiter in the ring buffer. index = ring_buffer_find_delim(helper->ring_buffer); // If a delimiter was found, extract the line and process it. if(index != FURI_STRING_FAILURE) { // Extract the line from the ring buffer, advancing the read // pointer to the next byte after the delimiter. ring_buffer_extract_line(helper->ring_buffer, index, line); // Invoke the callback to process the line. if(helper->process_line) { helper->process_line(line, helper->context); } } } while(index != FURI_STRING_FAILURE); } } // Keep reading until we have read all of the data from the stream buffer. } while(length_read > 0); } // Keep processing data until the WorkerEventExiting flag is set. } while((events & WorkerEventExiting) != WorkerEventExiting); furi_string_free(line); return 0; }
/** * Worker thread that dequeues data from the stream buffer and processes it. When * a delimiter is found in the data, the line is extracted and the process_line callback * is invoked. This thread will exit when the WorkerEventExiting flag is set. * * @param context UartHelper instance * @return 0 */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/uart_demo/uart_helper.c#L81-L160
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
wiegand_menu_callback
void wiegand_menu_callback(void* context, uint32_t index) { App* app = context; WiegandMainMenuEvent event = WiegandMainMenuUnknownEvent; switch(index) { case WiegandMainMenuInstructions: event = WiegandMainMenuInstructionsEvent; break; case WiegandMainMenuRead: event = WiegandMainMenuReadEvent; break; case WiegandMainMenuScan: event = WiegandMainMenuScanEvent; break; case WiegandMainMenuLoad: event = WiegandMainMenuLoadEvent; break; } if(event != WiegandMainMenuUnknownEvent) { scene_manager_handle_custom_event(app->scene_manager, event); } }
/* Triggers a custom event that is handled in the main menu on_scene handler. @param context Pointer to the application context. @param index Index of the selected menu item to map to custom event. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/wiegand/scenes/wiegand_main_menu.c#L8-L29
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
wiegand_main_menu_scene_on_enter
void wiegand_main_menu_scene_on_enter(void* context) { App* app = context; submenu_reset(app->submenu); submenu_set_header(app->submenu, "Wiegand"); submenu_add_item( app->submenu, "Instructions", WiegandMainMenuInstructions, wiegand_menu_callback, app); submenu_add_item(app->submenu, "Read", WiegandMainMenuRead, wiegand_menu_callback, app); submenu_add_item( app->submenu, "Scan w/AutoSave", WiegandMainMenuScan, wiegand_menu_callback, app); submenu_add_item(app->submenu, "Load", WiegandMainMenuLoad, wiegand_menu_callback, app); view_dispatcher_switch_to_view(app->view_dispatcher, WiegandSubmenuView); }
/* Displays the main menu. @param context Pointer to the application context. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/wiegand/scenes/wiegand_main_menu.c#L35-L46
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_tester_navigation_exit_callback
static uint32_t led_tester_navigation_exit_callback(void* _context) { UNUSED(_context); return VIEW_NONE; }
/** * @brief Callback for exiting the application. * @details This function is called when user press back button. We return VIEW_NONE to * indicate that we want to exit the application. * @param _context The context - unused * @return next view id */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/ws2812b_tester/app.c#L68-L71
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_tester_navigation_submenu_callback
static uint32_t led_tester_navigation_submenu_callback(void* _context) { UNUSED(_context); return LedTesterViewSubmenu; }
/** * @brief Callback for the application's menu. * @details This function is called when user press back button. We return LedTesterViewSubmenu to * indicate that we want to return to the application menu. * @param _context The context - unused * @return next view id */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/ws2812b_tester/app.c#L80-L83
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_tester_submenu_callback
static void led_tester_submenu_callback(void* context, uint32_t index) { LedTesterApp* app = (LedTesterApp*)context; switch(index) { case LedTesterSubmenuIndexLeds: view_dispatcher_switch_to_view(app->view_dispatcher, LedTesterViewLeds); break; case LedTesterSubmenuIndexAbout: view_dispatcher_switch_to_view(app->view_dispatcher, LedTesterViewAbout); break; default: break; } }
/** * @brief Handle submenu item selection. * @details This function is called when user selects an item from the submenu. * @param context The context - LedTesterApp object. * @param index The LedTesterSubmenuIndex item that was clicked. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/ws2812b_tester/app.c#L91-L103
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_tester_timer_callback
static void led_tester_timer_callback(void* context) { LedTesterApp* app = (LedTesterApp*)context; view_dispatcher_send_custom_event(app->view_dispatcher, LedTesterEventTimer); }
/** * @brief Callback for timer elapsed. * @details This function is called when the timer is elapsed. * @param context The context - LedTesterApp object. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/ws2812b_tester/app.c#L110-L113
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_tester_settings_updated
static void led_tester_settings_updated(LedTesterApp* app) { view_dispatcher_send_custom_event(app->view_dispatcher, LedTesterEventConfigChange); }
/** * @brief Callback for when the LED configuration settings are updated. * @details This function is called when the LED configuration settings are changed by the user. * @param context The context - LedTesterApp object. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/ws2812b_tester/app.c#L120-L122
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_tester_item_clicked
static void led_tester_item_clicked(void* context, uint32_t index) { UNUSED(index); LedTesterApp* app = (LedTesterApp*)context; view_dispatcher_send_custom_event(app->view_dispatcher, LedTesterEventClicked); }
/** * @brief Callback for when the LED configuration settings are clicked. * @details This function is called when the user presses OK button while in the LED configuration settings. * @param context The context - LedTesterApp object. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/ws2812b_tester/app.c#L129-L133
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_tester_5v_power_on
static void led_tester_5v_power_on() { uint8_t attempts = 5; while(--attempts > 0) { if(furi_hal_power_enable_otg()) break; } }
/** * @brief Enable 5V power. * @details This function enables the 5V power output on pin 1. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/ws2812b_tester/app.c#L139-L144
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_tester_5v_power_off
static void led_tester_5v_power_off() { if(furi_hal_power_is_otg_enabled()) { furi_hal_power_disable_otg(); } }
/** * @brief Disable 5V power. * @details This function disables the 5V power output on pin 1. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/ws2812b_tester/app.c#L150-L154
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_tester_setting_led_count_change
static void led_tester_setting_led_count_change(VariableItem* item) { LedTesterApp* app = variable_item_get_context(item); LedTesterModel* model = app->model; uint8_t index = variable_item_get_current_value_index(item); variable_item_set_current_value_text(item, setting_led_count_names[index]); model->led_count = setting_led_count_values[index]; led_tester_settings_updated(app); }
// 4 LEDs
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/ws2812b_tester/app.c#L175-L182
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_tester_custom_event_callback
static bool led_tester_custom_event_callback(void* context, uint32_t event) { LedTesterApp* app = (LedTesterApp*)context; const GpioPin* pin = setting_led_pin_values[app->model->led_pin_index]; if(!app->led_driver) { FURI_LOG_E(TAG, "led_driver is NULL. Custom event %lu ignored.", event); return false; } if(event == LedTesterEventTimer) { app->model->timer_counter++; } uint8_t offset = (app->model->led_divisor == -1) ? 0 : (app->model->timer_counter / app->model->led_divisor) & 0x3; uint32_t rgb[4] = {0}; switch(app->model->led_pattern_index) { case 0: // RED for(size_t i = 0; i < COUNT_OF(rgb); i++) { rgb[i] = 0xFF0000; } break; case 1: // GREEN for(size_t i = 0; i < COUNT_OF(rgb); i++) { rgb[i] = 0x00FF00; } break; case 2: // BLUE for(size_t i = 0; i < COUNT_OF(rgb); i++) { rgb[i] = 0x0000FF; } break; case 3: // WHITE for(size_t i = 0; i < COUNT_OF(rgb); i++) { rgb[i] = 0xFFFFFF; } break; case 4: // RGBW rgb[0] = 0xFF0000; rgb[1] = 0x00FF00; rgb[2] = 0x0000FF; rgb[3] = 0xFFFFFF; break; case 5: // GBWR rgb[3] = 0xFF0000; rgb[0] = 0x00FF00; rgb[1] = 0x0000FF; rgb[2] = 0xFFFFFF; break; case 6: // BWRG rgb[2] = 0xFF0000; rgb[3] = 0x00FF00; rgb[0] = 0x0000FF; rgb[1] = 0xFFFFFF; break; case 7: // WRGB rgb[0] = 0xFFFFFF; rgb[1] = 0xFF0000; rgb[2] = 0x00FF00; rgb[3] = 0x0000FF; break; default: break; } // Rotate the pattern for(size_t i = 0; i < offset; i++) { uint32_t tmp = rgb[0]; for(size_t j = 0; j < COUNT_OF(rgb) - 1; j++) { rgb[j] = rgb[j + 1]; } rgb[COUNT_OF(rgb) - 1] = tmp; } // If deinit, turn off the LEDs if(event == LedTesterEventDeinit) { for(size_t i = 0; i < COUNT_OF(rgb); i++) { rgb[i] = 0; } } // Scale the brightness for(size_t i = 0; i < COUNT_OF(rgb); i++) { rgb[i] = (((rgb[i] >> 16) & 0xFF) * app->model->led_max_brightness / 100) << 16 | (((rgb[i] >> 8) & 0xFF) * app->model->led_max_brightness / 100) << 8 | ((rgb[i] & 0xFF) * app->model->led_max_brightness / 100); // rgb[i] = (rgb[i] & 0x0F0F0F); // For Debugging, just use lower 4-bits. } led_driver_set_pin(app->led_driver, pin); // Set the LEDs to the pattern for(size_t i = 0; i < app->model->led_count; i++) { led_driver_set_led(app->led_driver, i, rgb[i % COUNT_OF(rgb)]); } // Turn off any remaining LEDs for(size_t i = app->model->led_count; i < MAX_LED_COUNT; i++) { led_driver_set_led(app->led_driver, i, 0); } led_driver_transmit(app->led_driver, true); if(event == LedTesterEventDeinit) { led_driver_free(app->led_driver); app->led_driver = NULL; } return true; }
/** * @brief Callback for custom events. * @details This function is called when a custom event is sent to the view dispatcher. * @param context The context - LedTesterApp object. * @param event The event id - LedTesterEventId value. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/ws2812b_tester/app.c#L247-L357
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_tester_enter_leds_callback
void led_tester_enter_leds_callback(void* _context) { // _context is variable_item_list, but it doesn't expose the item, so we can't get the context. UNUSED(_context); // Hack, we use a global to access the app object. LedTesterApp* app = (LedTesterApp*)global_app; app->timer = furi_timer_alloc(led_tester_timer_callback, FuriTimerTypePeriodic, app); furi_timer_start(app->timer, 250); view_dispatcher_send_custom_event(app->view_dispatcher, LedTesterEventInitialized); app->led_driver = led_driver_alloc(MAX_LED_COUNT, setting_led_pin_values[app->model->led_pin_index]); }
/** * @brief Callback for entering the LED configuration settings. * @details This function is called when the user enters the LED configuration settings. We * start the periodic timer to update the LEDs & we signal initialized so the LEDs * turn on to their default state. * @param _context The context - unused */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/ws2812b_tester/app.c#L366-L376
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_tester_exit_leds_callback
void led_tester_exit_leds_callback(void* _context) { // _context is variable_item_list, but it doesn't expose the item, so we can't get the context. UNUSED(_context); // Hack, we use a global to access the app object. LedTesterApp* app = (LedTesterApp*)global_app; furi_timer_stop(app->timer); furi_timer_free(app->timer); app->timer = NULL; view_dispatcher_send_custom_event(app->view_dispatcher, LedTesterEventDeinit); }
/** * @brief Callback for exiting the LED configuration settings. * @details This function is called when the user exits the LED configuration settings. We * stop the periodic timer to update the LEDs. * @param _context The context - unused */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/ws2812b_tester/app.c#L384-L393
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_tester_app_free
static void led_tester_app_free(LedTesterApp* app) { view_dispatcher_remove_view(app->view_dispatcher, LedTesterViewAbout); widget_free(app->widget_about); view_dispatcher_remove_view(app->view_dispatcher, LedTesterViewLeds); variable_item_list_free(app->variable_item_list); view_dispatcher_remove_view(app->view_dispatcher, LedTesterViewSubmenu); submenu_free(app->submenu); view_dispatcher_free(app->view_dispatcher); furi_record_close(RECORD_GUI); free(app); }
/** * @brief Free the led tester application. * @details This function frees the led tester application resources. * @param app The led tester application object. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/ws2812b_tester/app.c#L541-L551
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
ws2812b_led_tester_app
int32_t ws2812b_led_tester_app(void* _p) { UNUSED(_p); LedTesterApp* app = led_tester_app_alloc(); view_dispatcher_run(app->view_dispatcher); led_tester_app_free(app); return 0; }
/** * @brief Main function for led tester application. * @details This function is the entry point for the led tester application. It should be defined in * application.fam as the entry_point setting. * @param _p Input parameter - unused * @return 0 - Success */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/gpio/ws2812b_tester/app.c#L560-L566
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
hid_cc_update_timer
static void hid_cc_update_timer(HidCC* hid_cc, HidCCModel* model) { furi_assert(hid_cc); furi_assert(model); if(model->timer_click_enabled) { furi_timer_start(hid_cc->timer, model->timer_duration); } else { furi_timer_stop(hid_cc->timer); } }
// Add a new method to update the timer.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/hid/hid_app/final_files/views/hid_cc.c#L112-L121
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
hid_cc_tick_callback
static void hid_cc_tick_callback(void* context) { furi_assert(context); HidCC* hid_cc = context; with_view_model( hid_cc->view, HidCCModel * model, { if(model->timer_click_enabled) { hid_hal_mouse_press(hid_cc->hid, HID_MOUSE_BTN_LEFT); furi_delay_ms(10); hid_hal_mouse_release(hid_cc->hid, HID_MOUSE_BTN_LEFT); } }, true); }
// Add new method on tick callback that clicks button if click_enabled...
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/hid/hid_app/final_files/views/hid_cc.c#L124-L139
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_driver_init_dma_gpio_update
static void led_driver_init_dma_gpio_update(LedDriver* led_driver, const GpioPin* gpio) { led_driver->gpio = gpio; // Memory to Peripheral led_driver->dma_gpio_update.Direction = LL_DMA_DIRECTION_MEMORY_TO_PERIPH; // Peripheral (GPIO - We populate GPIO port's BSRR register) led_driver->dma_gpio_update.PeriphOrM2MSrcAddress = (uint32_t)&gpio->port->BSRR; led_driver->dma_gpio_update.PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT; led_driver->dma_gpio_update.PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_WORD; // Memory (State to set GPIO) led_driver->dma_gpio_update.MemoryOrM2MDstAddress = (uint32_t)led_driver->gpio_buf; led_driver->dma_gpio_update.MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT; led_driver->dma_gpio_update.MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_WORD; // Data led_driver->dma_gpio_update.Mode = LL_DMA_MODE_CIRCULAR; led_driver->dma_gpio_update.NbData = 2; // We cycle between two (HIGH/LOW)values // When to perform data exchange led_driver->dma_gpio_update.PeriphRequest = LL_DMAMUX_REQ_TIM2_UP; led_driver->dma_gpio_update.Priority = LL_DMA_PRIORITY_VERYHIGH; }
/** * @brief Initializes the DMA for GPIO pin toggle via BSRR. * @param led_driver The led driver to initialize. * @param gpio The GPIO pin to toggle. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/js-old/flipboard/modules/js_rgbleds/led_driver.c#L25-L44
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_driver_init_dma_led_transition_timer
static void led_driver_init_dma_led_transition_timer(LedDriver* led_driver) { // Timer that triggers based on user data. led_driver->dma_led_transition_timer.Direction = LL_DMA_DIRECTION_MEMORY_TO_PERIPH; // Peripheral (Timer - We populate TIM2's ARR register) led_driver->dma_led_transition_timer.PeriphOrM2MSrcAddress = (uint32_t)&TIM2->ARR; led_driver->dma_led_transition_timer.PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT; led_driver->dma_led_transition_timer.PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_WORD; // Memory (Timings) led_driver->dma_led_transition_timer.MemoryOrM2MDstAddress = (uint32_t)led_driver->timer_buffer; led_driver->dma_led_transition_timer.MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT; led_driver->dma_led_transition_timer.MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_HALFWORD; // Data led_driver->dma_led_transition_timer.Mode = LL_DMA_MODE_NORMAL; led_driver->dma_led_transition_timer.NbData = LED_DRIVER_BUFFER_SIZE; // When to perform data exchange led_driver->dma_led_transition_timer.PeriphRequest = LL_DMAMUX_REQ_TIM2_UP; led_driver->dma_led_transition_timer.Priority = LL_DMA_PRIORITY_HIGH; }
/** * @brief Initializes the DMA for the LED timings via ARR. * @param led_driver The led driver to initialize. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/js-old/flipboard/modules/js_rgbleds/led_driver.c#L50-L68
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_driver_free
void led_driver_free(LedDriver* led_driver) { furi_assert(led_driver); furi_hal_gpio_init_simple(led_driver->gpio, GpioModeAnalog); free(led_driver->led_data); free(led_driver); }
/** * @brief Frees a led driver. * @details Frees a led driver. * @param led_driver The led driver to free. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/js-old/flipboard/modules/js_rgbleds/led_driver.c#L94-L100
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_driver_set_led
uint32_t led_driver_set_led(LedDriver* led_driver, uint32_t index, uint32_t rrggbb) { furi_assert(led_driver); if(index >= led_driver->count_leds) { return 0xFFFFFFFF; } uint32_t previous = led_driver->led_data[index]; led_driver->led_data[index] = rrggbb; return previous; }
/** * @brief Sets the LED at the given index to the given color. * @note You must still call led_driver_transmit to actually update the LEDs. * @param led_driver The led driver to use. * @param index The index of the LED to set. * @param rrggbb The color to set the LED to (0xrrggbb format). * @return The previous color of the LED (0xrrggbb format). */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/js-old/flipboard/modules/js_rgbleds/led_driver.c#L110-L119
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_driver_get_led
uint32_t led_driver_get_led(LedDriver* led_driver, uint32_t index) { furi_assert(led_driver); if(index >= led_driver->count_leds) { return 0xFFFFFFFF; } return led_driver->led_data[index]; }
/** * @brief Gets the LED at the given index. * @param led_driver The led driver to use. * @param index The index of the LED to get. * @return The color of the LED (0xrrggbb format). */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/js-old/flipboard/modules/js_rgbleds/led_driver.c#L127-L134
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_driver_start_dma
static void led_driver_start_dma(LedDriver* led_driver) { furi_assert(led_driver); LL_DMA_Init(DMA1, LL_DMA_CHANNEL_1, &led_driver->dma_gpio_update); LL_DMA_Init(DMA1, LL_DMA_CHANNEL_2, &led_driver->dma_led_transition_timer); LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_1); LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_2); }
/** * @brief Initializes the DMA for GPIO pin toggle and led transititions. * @param led_driver The led driver to initialize. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/js-old/flipboard/modules/js_rgbleds/led_driver.c#L140-L148
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_driver_stop_dma
static void led_driver_stop_dma() { LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_1); LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_2); LL_DMA_ClearFlag_TC1(DMA1); LL_DMA_ClearFlag_TC2(DMA1); }
/** * @brief Stops the DMA for GPIO pin toggle and led transititions. * @param led_driver The led driver to initialize. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/js-old/flipboard/modules/js_rgbleds/led_driver.c#L154-L159
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
led_driver_start_timer
static void led_driver_start_timer() { furi_hal_bus_enable(FuriHalBusTIM2); LL_TIM_SetCounterMode(TIM2, LL_TIM_COUNTERMODE_UP); LL_TIM_SetClockDivision(TIM2, LL_TIM_CLOCKDIVISION_DIV1); LL_TIM_SetPrescaler(TIM2, 0); // Updated by led_driver->dma_led_transition_timer.PeriphOrM2MSrcAddress LL_TIM_SetAutoReload(TIM2, LED_DRIVER_TIMER_SETINEL); LL_TIM_SetCounter(TIM2, 0); LL_TIM_EnableCounter(TIM2); LL_TIM_EnableUpdateEvent(TIM2); LL_TIM_EnableDMAReq_UPDATE(TIM2); LL_TIM_GenerateEvent_UPDATE(TIM2); }
/** * @brief Starts the timer for led transitions. * @param led_driver The led driver to initialize. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/js-old/flipboard/modules/js_rgbleds/led_driver.c#L165-L179
89716a9b00eacce7055a75fddb5a3adde93f265f