diff --git a/consumerir/consumerir.c b/consumerir/consumerir.c index a4bfed7..5192462 100644 --- a/consumerir/consumerir.c +++ b/consumerir/consumerir.c @@ -15,6 +15,9 @@ */ #define LOG_TAG "ConsumerIrHal" +#include +#include +#include #include #include #include @@ -34,18 +37,62 @@ static const consumerir_freq_range_t consumerir_freqs[] = { {.min = 56000, .max = 56000}, }; +static bool +try_append_number(char *buffer, int *len, int size, int number) +{ + int stored; + + stored = snprintf(&buffer[*len], size - *len, "%d,", number); + + if (stored < 0 || stored >= size - *len) { + return false; + } + + *len += stored; + return true; +} + +static bool +grow_buffer(char **buffer, int *size) +{ + char *new_buffer; + + *size *= 2; + if ((new_buffer = realloc(*buffer, *size)) == NULL) { + return false; + } + *buffer = new_buffer; + return true; +} + +static bool +append_number(char **buffer, int *len, int *size, int number) +{ + if (! try_append_number(*buffer, len, *size, number)) { + if (! grow_buffer(buffer, size)) return false; + return try_append_number(*buffer, len, *size, number); + } else { + return true; + } +} + int fd = 0; static int consumerir_transmit(struct consumerir_device *dev, int carrier_freq, int pattern[], int pattern_len) { - int strlen; + int buffer_len = 0; + int buffer_size = 128; int i; - char buffer[2048]; + char *buffer; - memset(buffer, 0, 2048); + if ((buffer = malloc(buffer_size)) == NULL) { + return -ENOMEM; + } /* write the header */ - strlen = sprintf(buffer, "%d,", carrier_freq); + if (! append_number(&buffer, &buffer_len, &buffer_size, carrier_freq)) { + goto error; + } /* calculate factor of conversion from microseconds to pulses */ float factor = 1000000 / carrier_freq; @@ -53,14 +100,21 @@ static int consumerir_transmit(struct consumerir_device *dev, /* write out the timing pattern */ for (i = 0; i < pattern_len; i++) { - strlen += sprintf(buffer + strlen, "%d,", (int) (pattern[i]/factor)); + if (! append_number(&buffer, &buffer_len, &buffer_size, (int) (pattern[i]/factor))) { + goto error; + } } - buffer[strlen - 1] = 0; + buffer[buffer_len - 1] = 0; + write(fd, buffer, buffer_len - 1); - write(fd, buffer, strlen - 1); + free(buffer); return 0; + +error: + free(buffer); + return -ENOMEM; } static int consumerir_get_num_carrier_freqs(struct consumerir_device *dev)