repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
RomanKazantsev/image-processing-filters | inc/vessels.h | <gh_stars>1-10
/*
Copyright (c) 2017 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#pragma once
#define _USE_MATH_DEFINES
#include <vector>
#include <float.h>
#include "imageio.h"
#include "gabor.h"
#include "gradient.h"
using namespace std;
int ApplyVesselsFilter(ColorFloatImage const &input_image, GrayscaleFloatImage &output_image, float sigma) {
float lambda = 4.0f;
float psi = 0.0f;
float gamma = 0.5f;
float min_theta = 0;
float max_theta = 180;
const int num_filters = 18;
int rad_x = 0, rad_y = 0;
int width = output_image.Width();
int height = output_image.Height();
// prepare a set of Gabors filters
std::vector<float> kernels[num_filters];
for (int i = 0; i < num_filters; i++) {
float theta = (max_theta - min_theta) / num_filters * i + min_theta;
CreateGaborKernel(sigma, gamma, theta, lambda, psi, kernels[i], rad_x, rad_y);
}
// prepare extrapolated image
ColorFloatImage tmp_image(input_image.Width() + 2 * rad_x, input_image.Height() + 2 * rad_y);
ExtrapolateImage(input_image, tmp_image, rad_x, rad_y);
// apply filters to given image and find maximum response for each pixel
float min_value = FLT_MAX;
float max_value = FLT_MIN;
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
float max_response = -99999.0f;
bool is_negative = false;
output_image(i, j) = 0.0f;
for (int ind_f = 0; ind_f < num_filters; ind_f++) {
vector<float> &kernel = kernels[ind_f];
float sum = 0.0f;
for (int k = 0; k < kernel.size(); k++) {
int ii = k % (2 * rad_x + 1);
int jj = k / (2 * rad_x + 1);
float p = ToGray(tmp_image(i + ii, j + jj));
sum += kernel[k] * p;
}
if (std::fabsf(sum) > max_response) {
max_response = std::fabsf(sum);
if (sum < 0.0f) is_negative = true;
else is_negative = false;
}
}
if(is_negative) output_image(i, j) = max_response;
if (output_image(i, j) < min_value) min_value = output_image(i, j);
if (output_image(i, j) > max_value) max_value = output_image(i, j);
}
}
// normalize values
if ((max_value - min_value) > 0) {
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
output_image(i, j) = (output_image(i, j) - min_value) / (max_value - min_value) * 255.0f;
}
}
}
return 0;
}
|
RomanKazantsev/image-processing-filters | inc/sobel.h | /*
Copyright (c) 2017 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#pragma once
#include "imageio.h"
float ToGray(ColorFloatPixel pixel)
{
return pixel.b * 0.114f + pixel.g * 0.587f + pixel.r * 0.299f;
}
int Sobel(ColorFloatImage const &image, GrayscaleFloatImage &res, int mode) {
if (mode != 1 && mode != 2) return 0;
ColorFloatImage tmp_image(image.Width() + 2, image.Height() + 2);
// prepare temporal image
for (int j = 0; j < image.Height(); j++)
for (int i = 0; i < image.Width(); i++) {
tmp_image(i + 1, j + 1) = image(i, j);
}
for (int j = 0; j < image.Height(); j++) {
tmp_image(0, j + 1) = image(0, j);
tmp_image(image.Width() + 1, j + 1) = image(image.Width() - 1, j);
}
for (int i = 0; i < image.Width(); i++) {
tmp_image(i + 1, 0) = image(i, 0);
tmp_image(i + 1, image.Height() + 1) = image(i, image.Height() - 1);
}
tmp_image(0, 0) = image(0, 0);
tmp_image(0, tmp_image.Height() - 1) = image(0, image.Height() - 1);
tmp_image(tmp_image.Width() - 1, 0) = image(image.Width() - 1, 0);
tmp_image(tmp_image.Width() - 1, tmp_image.Height() - 1) = image(image.Width() - 1, image.Height() - 1);
if (mode == 1) { // horizontal
for (int j = 0; j < res.Height(); j++)
for (int i = 0; i < res.Width(); i++) {
ColorFloatPixel p1 = tmp_image(i + 2, j) + tmp_image(i + 2, j + 1) + tmp_image(i + 2, j + 1) + tmp_image(i + 2, j + 2);
ColorFloatPixel p2 = tmp_image(i, j) + tmp_image(i, j + 1) + tmp_image(i, j + 1) + tmp_image(i, j + 2);
float pp1 = ToGray(p1);
float pp2 = ToGray(p2);
res(i, j) = pp1 - pp2;
}
}
else if (mode == 2) { // vertical
for (int j = 0; j < res.Height(); j++)
for (int i = 0; i < res.Width(); i++) {
ColorFloatPixel p1 = tmp_image(i, j + 2) + tmp_image(i + 1, j + 2) + tmp_image(i + 1, j + 2) + tmp_image(i + 2, j + 2);
ColorFloatPixel p2 = tmp_image(i, j) + tmp_image(i + 1, j) + tmp_image(i + 1, j) + tmp_image(i + 2, j);
float pp1 = ToGray(p1);
float pp2 = ToGray(p2);
res(i, j) = pp1 - pp2;
}
}
return 0;
}
|
RomanKazantsev/image-processing-filters | inc/rotate.h | <gh_stars>1-10
/*
Copyright (c) 2017 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#pragma once
#define _USE_MATH_DEFINES
#include <math.h>
#include "imageio.h"
using namespace std;
static ColorFloatPixel RunBilinearInterpolation(float alpha, float beta,
ColorFloatPixel p11, ColorFloatPixel p12, ColorFloatPixel p21, ColorFloatPixel p22) {
ColorFloatPixel R1 = (1 - alpha) * p11 + alpha * p12;
ColorFloatPixel R2 = (1 - alpha) * p21 + alpha * p22;
return (1 - beta) * R1 + beta * R2;
}
int Rotate(char *inputfilename, char *outputfilename, int angle, int mode) {
typedef struct point {
public:
float x, y;
point(int xx, int yy) : x(float(xx)), y(float(yy)) {}
void rotate(int angle_in) {
float angle = float(angle_in) * float(M_PI) / 180.0f; // angle in radians
float xx = cosf(angle) * x - sinf(angle) * y;
float yy = sinf(angle) * x + cosf(angle) * y;
x = xx;
y = yy;
}
} point_t;
if (mode != 1 && mode != 2) { return 0; }
if (mode == 2) angle = -angle;
ColorFloatImage image = ImageIO::FileToColorFloatImage(inputfilename);
angle = angle % 360;
if (angle < 0) { angle += 360; }
//if (angle != 90 && angle != 180 && angle != 270) {return 0;}
// calculate new width and height of resulted image
int width = image.Width();
int height = image.Height();
point_t edge1(width / 2, height / 2), edge2(width / 2, -height / 2),
edge3(-width / 2, -height / 2), edge4(-width / 2, height / 2);
edge1.rotate(angle);
edge2.rotate(angle);
edge3.rotate(angle);
edge4.rotate(angle);
int width_new = int(2 * max(max(max(edge1.x, edge2.x), edge3.x), edge4.x));
int height_new = int(2 * max(max(max(edge1.y, edge2.y), edge3.y), edge4.y));
ColorFloatImage res(width_new, height_new);
for (int j = 0; j < height_new; j++) {
for (int i = 0; i < width_new; i++) {
point_t some_point(i - width_new / 2, height_new / 2 - j);
some_point.rotate(angle);
float xx = some_point.x + width / 2;
float yy = height / 2 - some_point.y;
if (xx <= (width - 1) && xx >= 0 && yy <= (height - 1) && yy >= 0) {
float xx_int, yy_int;
float alpha = modf(xx, &xx_int);
float beta = modf(yy, &yy_int);
float xx_int_plus1 = xx_int == (width - 1) ? xx_int : (xx_int + 1);
float yy_int_plus1 = yy_int == (height - 1) ? yy_int : (yy_int + 1);
res(i, j) = RunBilinearInterpolation(alpha, beta,
image(int(xx_int), int(yy_int)), image(int(xx_int_plus1), int(yy_int)),
image(int(xx_int), int(yy_int_plus1)), image(int(xx_int_plus1), int(yy_int_plus1)));
}
}
}
// run bilinear interpolation
for (int j = 0; j < height_new; j++) {
for (int i = 0; i < width_new; i++) {
ColorFloatPixel t = i > 0 ? res(i - 1, j) : res(i, j);
ColorFloatPixel b = (i + 1) < width_new ? res(i + 1, j) : res(i, j);
ColorFloatPixel l = j > 0 ? res(i, j - 1) : res(i, j);
ColorFloatPixel r = (j + 1) < height_new ? res(i, j + 1) : res(i, j);
res(i, j).b = (t.b + b.b + l.b + r.b) / 4;
res(i, j).g = (t.g + b.g + l.g + r.g) / 4;
res(i, j).r = (t.r + b.r + l.r + r.r) / 4;
}
}
ImageIO::ImageToFile(res, outputfilename);
return 0;
}
|
jfm92/lv_micropython | ports/microByte/drivers/display/display_HAL/display_HAL.h | /*********************
* INCLUDES
*********************/
#include "lvgl/lvgl.h"
#include "stdint.h"
/*********************
* DEFINES
*********************/
#define BLACK 0x0000
#define WHITE 0xFFFF
/*********************
* FUNCTIONS
*********************/
/*
* Function: display_HAL_init
* --------------------
*
* Initialize the screen
*
* Returns: True if the initialization suceed otherwise false.
*
*/
bool display_HAL_init(void);
/*
* Function: display_HAL_clear
* --------------------
*
* Fill the entire screen in white color.
*
* Returns: Nothing
*
*/
void display_HAL_clear();
/*
* Function: display_HAL_flush
* --------------------
*
* LVGL library function which flush a partial frame of 20 px x 240 px
*
* Arguments:
* - lv_disp_drv_t * drv: Instance to the screen defined on the LVGL initialization.
* - const lv_area_t * area: Screen area information which will be updated.
* - lv_color_t * color_map: Color map of the area to be update.
* Returns: Nothing
*
* Note: This function should not be called from any other part of the code, because
* is called periodically by the LVGL library.
*
*/
void display_HAL_flush(lv_disp_drv_t * drv, const lv_area_t * area, lv_color_t * color_map);
/*
* Function: display_HAL_gb_frame
* --------------------
*
* Process the emulator information to set the color and scale of the frame, and send the
* information to the screen driver.
*
* Arguments:
* - data: Frame data of the GameBoy/GameBoy color emulator.
*
* Returns: Nothing
*
*/
void display_HAL_gb_frame(const uint16_t *data);
/*
* Function: display_HAL_NES_frame
* --------------------
*
* Process the emulator information to set the color and scale of the frame, and send the
* information to the screen driver.
*
* Arguments:
* - data: Frame data of the NES color emulator.
*
* Returns: Nothing
*
*/
void display_HAL_NES_frame(const uint8_t *data);
/*
* Function: display_HAL_SMS_frame
* --------------------
*
* Process the emulator information to set the color and scale of the frame, and send the
* information to the screen driver.
*
* Arguments:
* - data: Frame data of the Sega Master System or Game Gear emulator, without color.
* - color: Color to apply to each frame.
* - GAMEGEAR: Set to true if you want to create a Game Gear frame, otherwise for Master System set to false
*
* Returns: Nothing
*
*/
void display_HAL_SMS_frame(const uint8_t *data, uint16_t color[], bool GAMEGEAR);
/*
* Function: display_HAL_get_buffer
* --------------------
*
* This function return a pointer to use the current display buffer.
*
* Returns: Pointer to the current buffer in use.
*
*/
uint16_t * display_HAL_get_buffer();
/*
* Function: display_HAL_get_buffer_size
* --------------------
*
* Give the actual size of the buffer.
*
* Returns: Size of the buffer
*
*/
size_t display_HAL_get_buffer_size();
/*
* Function: display_HAL_boot_frame
* --------------------
*
* This function receive the pointer of a buffer with the partial boot frame to print
* on the screen and send it to the driver layer.
*
* Arguments:
* -buffer: Pointer rendered buffer.
*
* Returns: Nothing
*
*/
void display_HAL_boot_frame(uint16_t * buffer);
/*
* Function: display_HAL_change_endian
* --------------------
*
* This function is a workaround to solve the issue with little endian and big endian package.
* The boot animation library creates little endian package on the other hand the GUI and the emulators,
* use big endian.
* By default the screen is configured to use little endian, but is necessay to change the endian configuration
* to obtain proper image after the boot screen.
*
*
* Returns: Nothing
*
*/
void display_HAL_change_endian();
void display_HAL_print(uint16_t *buffer, size_t size);
void display_HAL_set_windows(uint16_t x0, uint16_t x1, uint16_t y0, uint16_t y1);
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
QueueHandle_t vidQueue;
QueueHandle_t horizontalQueue; |
jfm92/lv_micropython | ports/microByte/drivers/input/input_HAL/input_HAL.h | <reponame>jfm92/lv_micropython<filename>ports/microByte/drivers/input/input_HAL/input_HAL.h<gh_stars>1-10
/*********************
* FUNCTIONS
*********************/
/*
* Function: input_init
* --------------------
*
* Initialize the mux driver and set the right configuration.
*
* Returns: Nothing
*/
void input_init(void);
/*
* Function: input_read
* --------------------
*
* Gets the value of the buttons attached to the mux and if the menu button is pushed,
* it peforms some special functions such as brightness and volumen set or open the on
* game menu.
*
* Returns: An unsigned interger of 16bit with the status of each button. See the next
* table to know the position of each button.
* Bit position of each button
* - 0 -> Down - 2 -> Up
* - 1 -> Left - 3 -> Right
*
* - 12 -> Select - 11 -> Menu
* - 10 -> Start
*
* - 9 -> B - 8 -> A - 7 -> Y
* - 6 -> X - 5 -> R - 13 -> L
*/
uint16_t input_read(void); |
jfm92/lv_micropython | ports/microByte/drivers/HW_config/hw_config.h | <reponame>jfm92/lv_micropython
/********************************
* Display pin configuration
* ******************************/
#define SCR_MODEL ST7789
#define SCR_WIDTH 240
#define SCR_HEIGHT 240
#define SCR_BUFFER_SIZE 20
#define HSPI_MOSI 13
#define HSPI_CLK 14
#define HSPI_RST 33
#define HSPI_DC 32
#define HSPI_BACKLIGTH 15
#define HSPI_CLK_SPEED 60*1000*1000 // 60Mhz
/********************************
* SD CARD pin configuration
* ******************************/
#define VSPI_MOSI 23
#define VSPI_MISO 19
#define VSPI_CLK 18
#define VSPI_CS0 5
/********************************
* Pin Mux pin configuration
* ******************************/
#define MUX_SDA 21
#define MUX_SCL 22
#define MUX_INT 34
#define I2C_CLK 400*1000 //400Khz
#define I2C_dev_address 0x20
/********************************
* I2S Pin
* ******************************/
#define I2S_BCK 27
#define I2S_WS 26
#define I2S_DATA_O 25
#define I2S_NUM I2S_NUM_0
/********************************
* Notification LED
* ******************************/
#define LED_PIN 2 |
jfm92/lv_micropython | ports/microByte/drivers/GUI/GUI_frontend.h | void GUI_frontend_main(); |
jfm92/lv_micropython | ports/microByte/drivers/display/st7789/st7789.c | <reponame>jfm92/lv_micropython<filename>ports/microByte/drivers/display/st7789/st7789.c<gh_stars>1-10
/*********************
* INCLUDES
*********************/
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/param.h>
#include "st7789.h"
#include "../../HW_config/hw_config.h"
#include "lvgl/lvgl.h"
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
/*********************
* DEFINES
*********************/
#define ST7789_SPI_QUEUE_SIZE 2
/**********************
* VARIABLES
**********************/
static const char *TAG = "ST7789_driver";
/**********************
* STATIC PROTOTYPES
**********************/
static void ST7789_send_cmd(st7789_driver_t *driver, const st7789_command_t *command);
static void ST7789_config(st7789_driver_t *driver);
static void ST7789_pre_cb(spi_transaction_t *transaction);
static void ST7789_queue_empty(st7789_driver_t *driver);
static void ST7789_multi_cmd(st7789_driver_t *driver, const st7789_command_t *sequence);
/**********************
* GLOBAL FUNCTIONS
**********************/
bool ST7789_init(st7789_driver_t *driver){
//Allocate the buffer memory
driver->buffer = (st7789_color_t *)heap_caps_malloc(driver->buffer_size * 2 * sizeof(st7789_color_t), MALLOC_CAP_8BIT | MALLOC_CAP_DMA);
if(driver->buffer == NULL){
ESP_LOGE(TAG, "Display buffer allocation fail");
return false;
}
ESP_LOGI(TAG,"Display buffer allocated with a size of: %i",driver->buffer_size * 2 * sizeof(st7789_color_t));
// Why set buffer, primary and secondary instead,just primary and secondary??
//Set-up the display buffers
driver->buffer_primary = driver->buffer;
driver->buffer_secondary = driver->buffer + driver->buffer_size;
driver->current_buffer = driver->buffer_primary;
driver->queue_fill = 0;
driver->data.driver = driver;
driver->data.data = true;
driver->command.driver = driver;
driver->command.data = false;
// Set the RESET and DC PIN
gpio_pad_select_gpio(HSPI_RST);
gpio_pad_select_gpio(HSPI_DC);
gpio_set_direction(HSPI_RST, GPIO_MODE_OUTPUT);
gpio_set_direction(HSPI_DC, GPIO_MODE_OUTPUT);
ESP_LOGI(TAG,"Set RST pin: %i \n Set DC pin: %i",HSPI_RST,HSPI_DC);
// Set-Up SPI BUS
spi_bus_config_t buscfg = {
.mosi_io_num = HSPI_MOSI,
.miso_io_num = -1,
.sclk_io_num = HSPI_CLK,
.quadwp_io_num = -1,
.quadhd_io_num = -1,
.max_transfer_sz= driver->buffer_size * 2 * sizeof(st7789_color_t), // 2 buffers with 2 bytes for pixel
.flags = SPICOMMON_BUSFLAG_NATIVE_PINS
};
// Configure SPI BUS
spi_device_interface_config_t devcfg = {
.clock_speed_hz = HSPI_CLK_SPEED,
.mode = 3,
.spics_io_num = -1,
.queue_size = ST7789_SPI_QUEUE_SIZE,
.pre_cb = ST7789_pre_cb,
};
if(spi_bus_initialize(HSPI_HOST, &buscfg, 1) != ESP_OK){
ESP_LOGE(TAG,"SPI Bus initialization failed.");
return false;
}
if(spi_bus_add_device(HSPI_HOST, &devcfg,&driver->spi) != ESP_OK){
ESP_LOGE(TAG,"SPI Bus add device failed.");
return false;
}
ESP_LOGI(TAG,"SPI Bus configured correctly.");
// Set the screen configuration
ST7789_reset(driver);
ST7789_config(driver);
ESP_LOGI(TAG,"Display configured and ready to work.");
return true;
}
void ST7789_reset(st7789_driver_t *driver) {
gpio_set_level(HSPI_RST, 0);
vTaskDelay(20 / portTICK_PERIOD_MS);
gpio_set_level(HSPI_RST, 1);
vTaskDelay(130 / portTICK_PERIOD_MS);
}
void ST7789_fill_area(st7789_driver_t *driver, st7789_color_t color, uint16_t start_x, uint16_t start_y, uint16_t width, uint16_t height){
// Fill the buffer with the selected color
for (size_t i = 0; i < driver->buffer_size * 2; ++i) {
driver->buffer[i] = color;
}
// Set the working area on the screen
ST7789_set_window(driver, start_x, start_y, start_x + width - 1, start_y + height - 1);
size_t bytes_to_write = width * height * 2;
size_t transfer_size = driver->buffer_size * 2 * sizeof(st7789_color_t);
spi_transaction_t trans;
spi_transaction_t *rtrans;
memset(&trans, 0, sizeof(trans));
trans.tx_buffer = driver->buffer;
trans.user = &driver->data;
trans.length = transfer_size * 8;
trans.rxlength = 0;
while (bytes_to_write > 0) {
if (driver->queue_fill >= ST7789_SPI_QUEUE_SIZE) {
spi_device_get_trans_result(driver->spi, &rtrans, portMAX_DELAY);
driver->queue_fill--;
}
if (bytes_to_write < transfer_size) {
transfer_size = bytes_to_write;
}
spi_device_queue_trans(driver->spi, &trans, portMAX_DELAY);
driver->queue_fill++;
bytes_to_write -= transfer_size;
}
ST7789_queue_empty(driver);
}
void ST7789_write_pixels(st7789_driver_t *driver, st7789_color_t *pixels, size_t length){
ST7789_queue_empty(driver);
spi_transaction_t *trans = driver->current_buffer == driver->buffer_primary ? &driver->trans_a : &driver->trans_b;
memset(trans, 0, sizeof(&trans));
trans->tx_buffer = driver->current_buffer;
trans->user = &driver->data;
trans->length = length * sizeof(st7789_color_t) * 8;
trans->rxlength = 0;
spi_device_queue_trans(driver->spi, trans, portMAX_DELAY);
driver->queue_fill++;
}
void ST7789_write_lines(st7789_driver_t *driver, int ypos, int xpos, int width, uint16_t *linedata, int lineCount){
// ST7789_set_window(driver,xpos,ypos,240,ypos +20);
int size = width * 2 * 8 * lineCount;
//driver->buffer_secondary = linedata;
//driver->current_buffer = driver->buffer_secondary;
//ST7789_write_pixels(driver, driver->buffer_primary, size);
driver->buffer_size = 240*20;
ST7789_set_window(driver,0,ypos,240,ypos +20);
// ST7789_write_pixels(driver, driver->current_buffer, driver->buffer_size);
ST7789_swap_buffers(driver);
}
void ST7789_swap_buffers(st7789_driver_t *driver){
ST7789_write_pixels(driver, driver->current_buffer, driver->buffer_size);
driver->current_buffer = driver->current_buffer == driver->buffer_primary ? driver->buffer_secondary : driver->buffer_primary;
}
void ST7789_set_window(st7789_driver_t *driver, uint16_t start_x, uint16_t start_y, uint16_t end_x, uint16_t end_y){
uint8_t caset[4];
uint8_t raset[4];
caset[0] = (uint8_t)(start_x >> 8) & 0xFF;
caset[1] = (uint8_t)(start_x & 0xff);
caset[2] = (uint8_t)(end_x >> 8) & 0xFF;
caset[3] = (uint8_t)(end_x & 0xff) ;
raset[0] = (uint8_t)(start_y >> 8) & 0xFF;
raset[1] = (uint8_t)(start_y & 0xff);
raset[2] = (uint8_t)(end_y >> 8) & 0xFF;
raset[3] = (uint8_t)(end_y & 0xff);
st7789_command_t sequence[] = {
{ST7789_CMD_CASET, 0, 4, caset},
{ST7789_CMD_RASET, 0, 4, raset},
{ST7789_CMD_RAMWR, 0, 0, NULL},
{ST7789_CMDLIST_END, 0, 0, NULL},
};
ST7789_multi_cmd(driver, sequence);
}
void ST7789_set_endian(st7789_driver_t *driver){
const st7789_command_t init_sequence2[] = {
{ST7789_CMD_RAMCTRL, 0, 2, (const uint8_t *)"\x00\xc0"},
{ST7789_CMDLIST_END, 0, 0, NULL},
};
ST7789_multi_cmd(driver, init_sequence2);
}
/**********************
* STATIC FUNCTIONS
**********************/
static void ST7789_pre_cb(spi_transaction_t *transaction) {
const st7789_transaction_data_t *data = (st7789_transaction_data_t *)transaction->user;
gpio_set_level(HSPI_DC, data->data);
}
static void ST7789_config(st7789_driver_t *driver){
const uint8_t caset[4] = {
0x00,
0x00,
(driver->display_width - 1) >> 8,
(driver->display_width - 1) & 0xff
};
const uint8_t raset[4] = {
0x00,
0x00,
(driver->display_height - 1) >> 8,
(driver->display_height - 1) & 0xff
};
const st7789_command_t init_sequence[] = {
// Sleep
{ST7789_CMD_SLPIN, 10, 0, NULL}, // Sleep
{ST7789_CMD_SWRESET, 200, 0, NULL}, // Reset
{ST7789_CMD_SLPOUT, 120, 0, NULL}, // Sleep out
{ST7789_CMD_MADCTL, 0, 1, (const uint8_t *)"\x00"}, // Page / column address order
{ST7789_CMD_COLMOD, 0, 1, (const uint8_t *)"\x55"}, // 16 bit RGB
{ST7789_CMD_INVON, 0, 0, NULL}, // Inversion on
{ST7789_CMD_CASET, 0, 4, (const uint8_t *)&caset}, // Set width
{ST7789_CMD_RASET, 0, 4, (const uint8_t *)&raset}, // Set height
// Porch setting
{ST7789_CMD_PORCTRL, 0, 5, (const uint8_t *)"\x0c\x0c\x00\x33\x33"},
// Set VGH to 12.54V and VGL to -9.6V
{ST7789_CMD_GCTRL, 0, 1, (const uint8_t *)"\x14"},
// Set VCOM to 1.475V
{ST7789_CMD_VCOMS, 0, 1, (const uint8_t *)"\x37"},
// Enable VDV/VRH control
{ST7789_CMD_VDVVRHEN, 0, 2, (const uint8_t *)"\x01\xff"},
// VAP(GVDD) = 4.45+(vcom+vcom offset+vdv)
{ST7789_CMD_VRHSET, 0, 1, (const uint8_t *)"\x12"},
// VDV = 0V
{ST7789_CMD_VDVSET, 0, 1, (const uint8_t *)"\x20"},
// AVDD=6.8V, AVCL=-4.8V, VDDS=2.3V
{ST7789_CMD_PWCTRL1, 0, 2, (const uint8_t *)"\xa4\xa1"},
// 60 fps
{ST7789_CMD_FRCTR2, 0, 1, (const uint8_t *)"\x0f"},
// Gama 2.2
{ST7789_CMD_GAMSET, 0, 1, (const uint8_t *)"\x01"},
// Gama curve
{ST7789_CMD_PVGAMCTRL, 0, 14, (const uint8_t *)"\xd0\x08\x11\x08\x0c\x15\x39\x33\x50\x36\x13\x14\x29\x2d"},
{ST7789_CMD_NVGAMCTRL, 0, 14, (const uint8_t *)"\xd0\x08\x10\x08\x06\x06\x39\x44\x51\x0b\x16\x14\x2f\x31"},
// Little endian
{ST7789_CMD_RAMCTRL, 0, 2, (const uint8_t *)"\x00\xc8"},
{ST7789_CMDLIST_END, 0, 0, NULL}, // End of commands
};
ST7789_multi_cmd(driver, init_sequence);
ST7789_fill_area(driver, 0x0000, 0, 0, driver->display_width, driver->display_height);
const st7789_command_t init_sequence2[] = {
{ST7789_CMD_DISPON, 100, 0, NULL}, // Display on
{ST7789_CMD_SLPOUT, 100, 0, NULL}, // Sleep out
{ST7789_CMD_CASET, 0, 4, caset},
{ST7789_CMD_RASET, 0, 4, raset},
{ST7789_CMD_RAMWR, 0, 0, NULL},
{ST7789_CMDLIST_END, 0, 0, NULL}, // End of commands
};
ST7789_multi_cmd(driver, init_sequence2);
}
static void ST7789_send_cmd(st7789_driver_t *driver, const st7789_command_t *command){
spi_transaction_t *return_trans;
spi_transaction_t data_trans;
// Check if the SPI queue is empty
ST7789_queue_empty(driver);
// Send the command
memset(&data_trans, 0, sizeof(data_trans));
data_trans.length = 8; // 8 bits
data_trans.tx_buffer = &command->command;
data_trans.user = &driver->command;
spi_device_queue_trans(driver->spi, &data_trans, portMAX_DELAY);
spi_device_get_trans_result(driver->spi, &return_trans, portMAX_DELAY);
// Send the data if the command has.
if (command->data_size > 0) {
memset(&data_trans, 0, sizeof(data_trans));
data_trans.length = command->data_size * 8;
data_trans.tx_buffer = command->data;
data_trans.user = &driver->data;
spi_device_queue_trans(driver->spi, &data_trans, portMAX_DELAY);
spi_device_get_trans_result(driver->spi, &return_trans, portMAX_DELAY);
}
// Wait the required time
if (command->wait_ms > 0) {
vTaskDelay(command->wait_ms / portTICK_PERIOD_MS);
}
}
static void ST7789_multi_cmd(st7789_driver_t *driver, const st7789_command_t *sequence){
while (sequence->command != ST7789_CMDLIST_END) {
ST7789_send_cmd(driver, sequence);
sequence++;
}
}
static void ST7789_queue_empty(st7789_driver_t *driver){
spi_transaction_t *return_trans;
while (driver->queue_fill > 0) {
spi_device_get_trans_result(driver->spi, &return_trans, portMAX_DELAY);
driver->queue_fill--;
}
}
|
jfm92/lv_micropython | ports/microByte/machine_display.c | #include "py/runtime.h"
#include "py/mphal.h"
#include "drivers/display/display_HAL/display_HAL.h"
#include "modmachine.h"
const mp_obj_type_t machine_display_type;
typedef struct _machine_display_obj_t {
mp_obj_base_t base;
mp_int_t height;
mp_int_t width;
} machine_display_obj_t;
mp_obj_t mp_display_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
machine_display_obj_t *self = m_new_obj_with_finaliser(machine_display_obj_t);
self->base.type = &machine_display_type;
self->height = 240;
self->width = 240;
//display_HAL_init();
return MP_OBJ_FROM_PTR(self);
}
mp_obj_t machine_display_clear(){
printf("Clear\r\n");
display_HAL_clear();
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_display_clear_obj, 1, 2, machine_display_clear);
STATIC mp_obj_t machine_display_flush(size_t n_args, const mp_obj_t *args){
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_display_flush_obj, 1, 2, machine_display_flush);
//uGame releated functions
mp_obj_t machine_display_block(size_t n_args, const mp_obj_t *args){
printf("fooo\r\n");
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_display_block_obj, 5, 5, machine_display_block);
mp_obj_t machine_display_exit(size_t n_args, const mp_obj_t *args){
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_display_exit_obj, 1, 2, machine_display_exit);
mp_obj_t machine_display_enter(size_t n_args, const mp_obj_t *args){
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_display_enter_obj, 1, 2, machine_display_enter);
STATIC const mp_rom_map_elem_t machine_display_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_clear), MP_ROM_PTR(&machine_display_clear_obj) },
{ MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&machine_display_flush_obj) },
{ MP_ROM_QSTR(MP_QSTR_block), MP_ROM_PTR(&machine_display_block_obj) },
{ MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&machine_display_exit_obj) },
{ MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&machine_display_enter_obj) },
{ MP_ROM_QSTR(MP_QSTR_width), MP_ROM_INT(240) }, //TODO: Somenthing temporary
{ MP_ROM_QSTR(MP_QSTR_height), MP_ROM_INT(240) }, //TODO: Somenthing temporary
};
STATIC MP_DEFINE_CONST_DICT(machine_display_locals_dict, machine_display_locals_dict_table);
const mp_obj_type_t machine_display_type = {
{ &mp_type_type },
.name = MP_QSTR_display,
//.print = esp32_pwm_print,
.make_new = mp_display_make_new,
.locals_dict = (mp_obj_dict_t *)&machine_display_locals_dict,
}; |
jfm92/lv_micropython | ports/microByte/drivers/display/st7789/st7789.h | <reponame>jfm92/lv_micropython
#pragma once
#include "driver/spi_master.h"
#include "lvgl/lvgl.h"
/*******************************
* ST7789 Commands
* *****************************/
// System Function Command Table 1
#define ST7789_CMD_NOP 0x00 // No operation
#define ST7789_CMD_SWRESET 0x01 // Software reset
#define ST7789_CMD_RDDID 0x04 // Read display ID
#define ST7789_CMD_RDDST 0x09 // Read display status
#define ST7789_CMD_RDDPM 0x0a // Read display power
#define ST7789_CMD_RDDMADCTL 0x0b // Read display
#define ST7789_CMD_RDDCOLMOD 0x0c // Read display pixel
#define ST7789_CMD_RDDIM 0x0d // Read display image
#define ST7789_CMD_RDDSM 0x0e // Read display signal
#define ST7789_CMD_RDDSDR 0x0f // Read display self-diagnostic result
#define ST7789_CMD_SLPIN 0x10 // Sleep in
#define ST7789_CMD_SLPOUT 0x11 // Sleep out
#define ST7789_CMD_PTLON 0x12 // Partial mode on
#define ST7789_CMD_NORON 0x13 // Partial off (Normal)
#define ST7789_CMD_INVOFF 0x20 // Display inversion off
#define ST7789_CMD_INVON 0x21 // Display inversion on
#define ST7789_CMD_GAMSET 0x26 // Gamma set
#define ST7789_CMD_DISPOFF 0x28 // Display off
#define ST7789_CMD_DISPON 0x29 // Display on
#define ST7789_CMD_CASET 0x2a // Column address set
#define ST7789_CMD_RASET 0x2b // Row address set
#define ST7789_CMD_RAMWR 0x2c // Memory write
#define ST7789_CMD_RAMRD 0x2e // Memory read
#define ST7789_CMD_PTLAR 0x30 // Partial start/end address set
#define ST7789_CMD_VSCRDEF 0x33 // Vertical scrolling definition
#define ST7789_CMD_TEOFF 0x34 // Tearing line effect off
#define ST7789_CMD_TEON 0x35 // Tearing line effect on
#define ST7789_CMD_MADCTL 0x36 // Memory data access control
#define ST7789_CMD_VSCRSADD 0x37 // Vertical address scrolling
#define ST7789_CMD_IDMOFF 0x38 // Idle mode off
#define ST7789_CMD_IDMON 0x39 // Idle mode on
#define ST7789_CMD_COLMOD 0x3a // Interface pixel format
#define ST7789_CMD_RAMWRC 0x3c // Memory write continue
#define ST7789_CMD_RAMRDC 0x3e // Memory read continue
#define ST7789_CMD_TESCAN 0x44 // Set tear scanline
#define ST7789_CMD_RDTESCAN 0x45 // Get scanline
#define ST7789_CMD_WRDISBV 0x51 // Write display brightness
#define ST7789_CMD_RDDISBV 0x52 // Read display brightness value
#define ST7789_CMD_WRCTRLD 0x53 // Write CTRL display
#define ST7789_CMD_RDCTRLD 0x54 // Read CTRL value display
#define ST7789_CMD_WRCACE 0x55 // Write content adaptive brightness control and Color enhancemnet
#define ST7789_CMD_RDCABC 0x56 // Read content adaptive brightness control
#define ST7789_CMD_WRCABCMB 0x5e // Write CABC minimum brightness
#define ST7789_CMD_RDCABCMB 0x5f // Read CABC minimum brightness
#define ST7789_CMD_RDABCSDR 0x68 // Read Automatic Brightness Control Self-Diagnostic Result
#define ST7789_CMD_RDID1 0xda // Read ID1
#define ST7789_CMD_RDID2 0xdb // Read ID2
#define ST7789_CMD_RDID3 0xdc // Read ID3
// System Function Command Table 2
#define ST7789_CMD_RAMCTRL 0xb0 // RAM Control
#define ST7789_CMD_RGBCTRL 0xb1 // RGB Control
#define ST7789_CMD_PORCTRL 0xb2 // Porch control
#define ST7789_CMD_FRCTRL1 0xb3 // Frame Rate Control 1
#define ST7789_CMD_GCTRL 0xb7 // Gate control
#define ST7789_CMD_DGMEN 0xba // Digital Gamma Enable
#define ST7789_CMD_VCOMS 0xbb // VCOM Setting
#define ST7789_CMD_LCMCTRL 0xc0 // LCM Control
#define ST7789_CMD_IDSET 0xc1 // ID Setting
#define ST7789_CMD_VDVVRHEN 0xc2 // VDV and VRH Command enable
#define ST7789_CMD_VRHSET 0xc3 // VRH Set
#define ST7789_CMD_VDVSET 0xc4 // VDV Set
#define ST7789_CMD_VCMOFSET 0xc5 // VCOM Offset Set
#define ST7789_CMD_FRCTR2 0xc6 // FR Control 2
#define ST7789_CMD_CABCCTRL 0xc7 // CABC Control
#define ST7789_CMD_REGSEL1 0xc8 // Register value selection 1
#define ST7789_CMD_REGSEL2 0xca // Register value selection 2
#define ST7789_CMD_PWMFRSEL 0xcc // PWM Frequency Selection
#define ST7789_CMD_PWCTRL1 0xd0 // Power Control 1
#define ST7789_CMD_VAPVANEN 0xd2 // Enable VAP/VAN signal output
#define ST7789_CMD_CMD2EN 0xdf // Command 2 Enable
#define ST7789_CMD_PVGAMCTRL 0xe0 // Positive Voltage Gamma Control
#define ST7789_CMD_NVGAMCTRL 0xe1 // Negative voltage Gamma Control
#define ST7789_CMD_DGMLUTR 0xe2 // Digital Gamma Look-up Table for Red
#define ST7789_CMD_DGMLUTB 0xe3 // Digital Gamma Look-up Table for Blue
#define ST7789_CMD_GATECTRL 0xe4 // Gate control
#define ST7789_CMD_PWCTRL2 0xe8 // Power Control 2
#define ST7789_CMD_EQCTRL 0xe9 // Equalize Time Control
#define ST7789_CMD_PROMCTRL 0xec // Program Control
#define ST7789_CMD_PROMEN 0xfa // Program Mode Enable
#define ST7789_CMD_NVMSET 0xfc // NVM Setting
#define ST7789_CMD_PROMACT 0xfe // Program Action
#define ST7789_CMDLIST_END 0xff // End command (used for command list)
/*******************************
* TYPEDEF
* *****************************/
struct st7789_driver;
typedef struct st7789_transaction_data {
struct st7789_driver *driver;
bool data;
} st7789_transaction_data_t;
typedef uint16_t st7789_color_t;
typedef struct st7789_driver {
int pin_reset;
int pin_dc;
int pin_mosi;
int pin_sclk;
int spi_host;
int dma_chan;
uint8_t queue_fill;
uint16_t display_width;
uint16_t display_height;
spi_device_handle_t spi;
size_t buffer_size;
st7789_transaction_data_t data;
st7789_transaction_data_t command;
st7789_color_t *buffer;
st7789_color_t *buffer_primary;
st7789_color_t *buffer_secondary;
st7789_color_t *current_buffer;
spi_transaction_t trans_a;
spi_transaction_t trans_b;
} st7789_driver_t;
typedef struct st7789_command {
uint8_t command;
uint8_t wait_ms;
uint8_t data_size;
const uint8_t *data;
} st7789_command_t;
/*********************
* FUNCTIONS
*********************/
/*
* Function: ST7789_init
* --------------------
*
* Initialize the SPI peripheral and send the initialization sequence.
*
* Arguments:
* -driver: Screen driver structure.
*
* Returns: True if the initialization suceed otherwise false.
*
*/
bool ST7789_init(st7789_driver_t *driver);
/*
* Function: ST7789_reset
* --------------------
*
* Reset the display
*
* Arguments:
* -driver: Screen driver structure.
*
* Returns: Nothing.
*
*/
void ST7789_reset(st7789_driver_t *driver);
/*
* Function: ST7789_fill_area
* --------------------
*
* Fill a area of the display with a selected color
*
* Arguments:
* -driver: Screen driver structure.
* -color: 16 Bit hexadecimal color to fill the area.
* -start_x: Start point on the X axis.
* -start_y: Start point on the Y axis.
* -width: Width of the area to be fill.
* -height: Height of the area to be fill.
*
* Returns: Nothing.
*
*/
void ST7789_fill_area(st7789_driver_t *driver, st7789_color_t color, uint16_t start_x, uint16_t start_y, uint16_t width, uint16_t height);
/*
* Function: ST7789_write_pixels
* --------------------
*
* WIP
*
* Arguments:
* -driver: Screen driver structure.
*
* Returns: Nothing.
*
*/
void ST7789_write_pixels(st7789_driver_t *driver, st7789_color_t *pixels, size_t length);
/*
* Function: ST7789_write_lines
* --------------------
*
* WIP
*
* Arguments:
* -driver: Screen driver structure.
*
* Returns: Nothing.
*
*/
void ST7789_write_lines(st7789_driver_t *driver, int ypos, int xpos, int width, uint16_t *linedata, int lineCount);
/*
* Function: ST7789_swap_buffers
* --------------------
*
* The driver has two buffer, to allow send and render the image at the same type. This function
* send the data of the actived buffer and change the pointer of current buffer to the next one.
*
* Arguments:
* -driver: Screen driver structure.
*
* Returns: Nothing.
*
*/
void ST7789_swap_buffers(st7789_driver_t *driver);
/*
* Function: ST7789_set_window
* --------------------
*
* This screen allows partial update of the screen, so we can specified which part of the windows is going to change.
*
* Arguments:
* -driver: Screen driver structure.
* -start_x: X axis start point of the refresh zone.
* -start_y: Y axis start point of the refresh zone.
* -end_x: X axis end point of the refresh zone.
* -end_y: Y axis end point of the refresh zone.
* Returns: Nothing.
*
*/
void ST7789_set_window(st7789_driver_t *driver, uint16_t start_x, uint16_t start_y, uint16_t end_x, uint16_t end_y);
/*
* Function: ST7789_set_endian
* --------------------
*
* Depper explanation on the display_HAL.h file, but this function change the screen configuration from,
* little endian message to big endian message.
*
* Arguments:
* -driver: Screen driver structure.
*
* Returns: Nothing.
*
*/
void ST7789_set_endian(st7789_driver_t *driver); |
jfm92/lv_micropython | ports/microByte/drivers/input/TCA9555/TCA9555.h |
/*********************
* FUNCTIONS
*********************/
/*
* Function: TCA955_init
* --------------------
*
* Initialize I2C Bus and check if the TCA955 mux is connected to the bus
*
* Returns: True if the initialization suceed otherwise false.
*
*/
bool TCA955_init(void);
/*
* Function: TCA9555_pinMode
* --------------------
*
* Configure a specific pin to be an input.
* By default all the pins are inputs.
*
* Arguments
* -pin: 0-16 pin number.
*
* Returns: True if the configuration suceed otherwise false.
*
*/
bool TCA9555_pinMode(uint8_t pin);
/*
* Function: TCA9555_readInputs
* --------------------
*
* Get the value of the input pins attached to the driver.
*
*
* Returns: A integer of 16 bits with the value of each pin (Each bit is the value of each input).
*
*/
int16_t TCA9555_readInputs(void); |
jfm92/lv_micropython | ports/microByte/drivers/GUI/GUI_frontend.c | <gh_stars>1-10
/*********************
* LIBRARIES
*********************/
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "lvgl/lvgl.h"
#include "../input/input_HAL/input_HAL.h"
/**********************
* Global Variable
**********************/
bool ctrl_available = true;
bool tab_move_available = false;
uint32_t btn_left_time = 0;
uint32_t btn_right_time = 0;
uint32_t btn_up_time = 0;
uint32_t btn_down_time = 0;
uint32_t btn_a_time = 0;
uint32_t btn_b_time = 0;
uint32_t btn_menu_time = 0;
/**********************
* LVGL groups and objects
**********************/
// Interactive related things
static lv_group_t * group_interact;
static lv_indev_t * kb_indev;
//Static
static bool user_input_task(lv_indev_drv_t * indev_drv, lv_indev_data_t * data);
void GUI_frontend_menu(){
//TODO: Add tittle
//TODO: Add REPL button
/*lv_obj_t * list_py_files = lv_list_create(lv_scr_act(), NULL);
lv_obj_set_size(list_py_files, 210, 130);
lv_obj_align(list_py_files, NULL, LV_ALIGN_CENTER, 0, 10);
lv_group_add_obj(group_interact, list_py_files);*/
//TODO: Get .py files
//TODO: Show .py files on the list
}
void GUI_frontend_main(){
group_interact = lv_group_create();
lv_indev_drv_t kb_drv;
lv_indev_drv_init(&kb_drv);
kb_drv.type = LV_INDEV_TYPE_KEYPAD;
kb_drv.read_cb = user_input_task;
kb_indev = lv_indev_drv_register(&kb_drv);
lv_indev_set_group(kb_indev, group_interact);
lv_obj_t * repl_btn = lv_btn_create(lv_scr_act(), NULL);
lv_obj_align(repl_btn, NULL, LV_ALIGN_CENTER, 0, 10);
lv_group_add_obj(group_interact, repl_btn);
GUI_frontend_menu();
}
void GUI_frontend_ctrl_available(bool _ctrl_available){
}
void GUI_add_interact_group(lv_obj_t * _lv_obj){
lv_group_add_obj(group_interact, _lv_obj);
}
static bool user_input_task(lv_indev_drv_t * indev_drv, lv_indev_data_t * data){
if(ctrl_available){
uint16_t inputs_value = input_read();
if(!((inputs_value >> 0) & 0x01)){
//Down BTN
printf("down\r\n");
uint32_t actual_time= xTaskGetTickCount()/portTICK_PERIOD_MS;
if((actual_time-btn_down_time)>2){
data->state = LV_INDEV_STATE_PR;
data->key = LV_KEY_ENTER;
// Save the actual time to calculate the bounce time.
btn_down_time = actual_time;
}
}
}
return false;
}
|
jfm92/lv_micropython | ports/microByte/drivers/input/TCA9555/TCA9555.c | <filename>ports/microByte/drivers/input/TCA9555/TCA9555.c<gh_stars>1-10
/*********************
* INCLUDES
*********************/
#include "stdbool.h"
#include "esp_log.h"
#include "driver/i2c.h"
//#include "system_configuration.h"
/*********************
* DEFINES
*********************/
#define CONFIG_REG 0x06
#define READ_REG 0x00
#define I2C_dev_address 0x20
/**********************
* STATIC PROTOTYPES
**********************/
static const char *TAG = "TCA9555";
static int8_t TCA955_write(uint8_t I2C_bus, uint8_t data, size_t size){
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, ( I2C_dev_address << 1 ) | I2C_MASTER_WRITE, 0x1);
i2c_master_write(cmd, &data, size, 0x1); // Using &data will give a warning a compilation time, but is necessary to avoid I2C invalid address at running time
i2c_master_stop(cmd);
esp_err_t ret = i2c_master_cmd_begin(0, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
if(ret != ESP_OK){
ESP_LOGE(TAG, "Write error err = %d",ret );
return -1;
}
return 1;
}
static int8_t TCA955_read(uint8_t I2C_bus, uint8_t *data, size_t size){
if (size == 0) {
return ESP_OK;
}
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (I2C_dev_address << 1) | I2C_MASTER_READ, 0x1);
if (size > 1) {
i2c_master_read(cmd, data, size - 1, 0x0);
}
i2c_master_read_byte(cmd, data + size - 1, 0x1);
i2c_master_stop(cmd);
esp_err_t ret = i2c_master_cmd_begin(I2C_bus, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
return ret;
}
/**********************
* GLOBAL FUNCTIONS
**********************/
bool TCA955_init(void){
//Init I2C bus as master
esp_err_t ret;
i2c_config_t conf;
conf.mode = I2C_MODE_MASTER;
conf.sda_io_num = 21;
conf.sda_pullup_en = GPIO_PULLUP_ENABLE;
conf.scl_io_num = 22;
conf.scl_pullup_en = GPIO_PULLUP_ENABLE;
conf.master.clk_speed = 400*1000 ;
i2c_param_config(0, &conf);
ret = i2c_driver_install(0, conf.mode,0,0, 0);
if(ret != ESP_OK){
ESP_LOGE(TAG, "I2C driver initialization fail");
return false;
}
//Check if the device is connected
if(TCA955_write(0,0x00,1) == -1){
ESP_LOGE(TAG,"TCA9555 not detected");
return false;
}
printf("TCA9555 detected\r\n");
return true;
}
int16_t TCA9555_readInputs(void){
uint8_t data[2] = {0xFF,0xFF};
TCA955_write(0, READ_REG, 1);
TCA955_read(0, data, 2);
uint16_t data_out = ((uint16_t)data[1] << 8) | data[0];
return data_out;
}
/**********************
* STATIC FUNCTIONS
**********************/
|
jfm92/lv_micropython | ports/microByte/drivers/input/input_HAL/input_HAL.c | <filename>ports/microByte/drivers/input/input_HAL/input_HAL.c
/*********************
* INCLUDES
*********************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "driver/gpio.h"
#include "../TCA9555/TCA9555.h"
//#include "st7789.h"
//#include "sound_driver.h"
#include "input_HAL.h"
#include "../../HW_config/hw_config.h"
//#include "system_manager.h"
/**********************
* VARIABLES
**********************/
uint32_t menu_btn_time =0;
/**********************
* STATIC
**********************/
static const char *TAG = "user_input";
/**********************
* GLOBAL FUNCTIONS
**********************/
void input_init(void){
// Initalize mux driver
ESP_LOGI(TAG,"Initalization of GPIO mux driver");
TCA955_init();
}
uint16_t input_read(void){
//Get the mux values
uint16_t inputs_value = TCA9555_readInputs();
//Check if the menu button it was pushed
/* if(!((inputs_value >>11) & 0x01)){ //Temporary workaround !((inputs_value >>11) & 0x01) is the real button
struct SYSTEM_MODE management;
//Get the actual time
uint32_t actual_time= xTaskGetTickCount()/portTICK_PERIOD_MS;
// Check if any of the special buttons was pushed
if(!((inputs_value >> 0) & 0x01)){
// Down arrow, volume down
int volume_aux = audio_volume_get();
volume_aux -= 10;
if(volume_aux < 0)volume_aux = 0;
management.mode = MODE_CHANGE_VOLUME;
management.volume_level = volume_aux;
if( xQueueSend( modeQueue,&management, ( TickType_t ) 10) != pdPASS ) ESP_LOGE(TAG, "Queue send failed");
}
else if(!((inputs_value >> 2) & 0x01)){
//UP arrow, volume UP
int volume_aux = audio_volume_get();
volume_aux += 10;
if(volume_aux > 100)volume_aux = 100;
management.mode = MODE_CHANGE_VOLUME;
management.volume_level = volume_aux;
if( xQueueSend( modeQueue,&management, ( TickType_t ) 10) != pdPASS ) ESP_LOGE(TAG, "Queue send failed");
}
else if(!((inputs_value >> 1) & 0x01)){
// Right arrow, brightness up
int brightness_aux = 0;//st7789_backlight_get();
brightness_aux += 10;
if(brightness_aux > 100)brightness_aux = 100;
management.mode = MODE_CHANGE_BRIGHT;
management.volume_level = brightness_aux;
if( xQueueSend( modeQueue,&management, ( TickType_t ) 10) != pdPASS ) ESP_LOGE(TAG, "Queue send failed");
}
else if(!((inputs_value >> 3) & 0x01)){
// Left arrow, brightness down
int brightness_aux = 0;//st7789_backlight_get();
brightness_aux -= 10;
if(brightness_aux < 0 )brightness_aux = 0;
management.mode = MODE_CHANGE_BRIGHT;
management.volume_level = brightness_aux;
if( xQueueSend( modeQueue,&management, ( TickType_t ) 10) != pdPASS ) ESP_LOGE(TAG, "Queue send failed");
}
else{
if((actual_time-menu_btn_time)>25){
printf("Menu\r\n");
management.mode = MODE_GAME;
management.status = 0;
if( xQueueSend( modeQueue,&management, ( TickType_t ) 10) != pdPASS ) ESP_LOGE(TAG, "Queue send failed");
menu_btn_time = actual_time;
}
}
return 0xFFFF;
}
else{*/
return inputs_value;
//}
}
|
jfm92/lv_micropython | ports/microByte/drivers/display/display_HAL/display_HAL.c | /*********************
* INCLUDES
*********************/
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_log.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../st7789/st7789.h"
#include "display_HAL.h"
#include "../../HW_config/hw_config.h"
/*********************
* DEFINES
*********************/
#define LINE_BUFFERS (2)
#define LINE_COUNT (20)
uint16_t *line[LINE_BUFFERS];
extern uint16_t myPalette[];
/**********************
* VARIABLES
**********************/
st7789_driver_t display = {
.pin_reset = HSPI_RST,
.pin_dc = HSPI_DC,
.pin_mosi = HSPI_MOSI,
.pin_sclk = HSPI_CLK,
.spi_host = HSPI_HOST,
.dma_chan = 1,
.display_width = 240,
.display_height = 240,
.buffer_size = 240*20, // 2 buffers with 20 lines
};
static const char *TAG = "Display_HAL";
/**********************
* STATIC PROTOTYPES
**********************/
static void task(void *arg);
/**********************
* GLOBAL FUNCTIONS
**********************/
// Display HAL basic functions.
uint16_t * buffer_secondary;
bool display_HAL_init(void){
vidQueue = xQueueCreate(7, sizeof(uint16_t *));
horizontalQueue = xQueueCreate(7, sizeof(uint8_t));
xTaskCreatePinnedToCore(&task, "videoTask", 1024 * 4, NULL, 1, NULL, 1);
buffer_secondary = (st7789_color_t *)heap_caps_malloc(display.buffer_size * 2 * sizeof(st7789_color_t), MALLOC_CAP_8BIT | MALLOC_CAP_DMA);
return ST7789_init(&display);
}
void display_HAL_clear(){
ST7789_fill_area(&display, WHITE, 0, 0, display.display_width, display.display_height);
}
// Boot Screen Functions
uint16_t * display_HAL_get_buffer(){
return buffer_secondary;
}
size_t display_HAL_get_buffer_size(){
return display.buffer_size;
}
void display_HAL_boot_frame(uint16_t * buffer){
// The boot animation to the buffer
display.current_buffer = buffer;
//Send to the driver layer and change the buffer
ST7789_swap_buffers(&display);
}
void display_HAL_change_endian(){
ST7789_set_endian(&display);
}
// LVGL library releated functions
void display_HAL_flush(lv_disp_drv_t * drv, const lv_area_t * area, lv_color_t * color_map){
uint32_t size = lv_area_get_width(area) * lv_area_get_height(area);
//Set the area to print on the screen
ST7789_set_window(&display,area->x1,area->y1,area->x2 ,area->y2);
//Save the buffer data and the size of the data to send
display.current_buffer = (void *)color_map;
display.buffer_size = size;
//Send it
//ST7789_write_pixels(&display, display.current_buffer, display.buffer_size);
ST7789_swap_buffers(&display);
//Tell to LVGL that is ready to send another frame
lv_disp_flush_ready(drv);
}
void display_HAL_set_windows(uint16_t x0, uint16_t x1, uint16_t y0, uint16_t y1){
//ST7789_set_window(&display, x0, y0, (x1-x0) - 1, (y1-y0)- 1);
ST7789_set_window(&display,x0,y0,x1,y1);
}
void display_HAL_print(uint16_t *buffer, size_t size){
// The boot animation to the buffer
// display.current_buffer = buffer;
memcpy(display.current_buffer,buffer,size*2);
display.buffer_size = size;
//Send to the driver layer and change the buffer
ST7789_swap_buffers(&display);
//ST7789_write_pixels(&display, buffer, size);
}
static void task(void *arg){
uint16_t *param;
uint8_t horizonta;
int y = 0;
while(1){
xQueuePeek(vidQueue, ¶m, portMAX_DELAY);
xQueuePeek(horizontalQueue, &horizonta, portMAX_DELAY);
memcpy(display.current_buffer,param,240*20); //240*20
display.buffer_size = 240*10;
display_HAL_set_windows(0,240,(horizonta-9),horizonta+9);
ST7789_swap_buffers(&display);
xQueueReceive(horizontalQueue, &horizonta, portMAX_DELAY);
xQueueReceive(vidQueue, ¶m, portMAX_DELAY);
}
}
/**********************
* STATIC FUNCTIONS
**********************/
|
jfm92/lv_micropython | ports/microByte/drivers/GUI/GUI.c | #include "stdlib.h"
#include "lvgl/lvgl.h"
#include "../display/display_HAL/display_HAL.h"
#include "../input/input_HAL/input_HAL.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "GUI_frontend.h"
/*********************
* DEFINES
*********************/
#define BUF_SIZE 240*20
#define LV_TICK_PERIOD_MS 10
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_tick_task(void *arg);
static lv_disp_drv_t disp_drv;
static void GUI_task(void *arg);
TaskHandle_t GUI_task_handler;
bool GUI_task_running = false;
/**********************
* GLOBAL FUNCTIONS
**********************/
void GUI_init(){
//Initialize back control thread
xTaskCreatePinnedToCore(GUI_task, "Graphical User Interface", 1024*6, NULL, 1, &GUI_task_handler, 0);
GUI_task_running = true;
}
bool GUI_pause(bool status){
if(GUI_task_running && !status) vTaskSuspend(GUI_task_handler);
else if(!GUI_task_running && status) vTaskResume(&GUI_task_handler);
else{
printf("Error changing GUI task state\r\n");
return false;
}
return true;
}
void GUI_pause_controls(bool status){
}
void GUI_clean(){
}
void GUI_change_move(){
}
/**********************
* STATIC FUNCTIONS
**********************/
static void GUI_task(void *arg){
//it's suppose that the display is already initialize
lv_init();
//Display buffer initialization
static lv_color_t * buf1[BUF_SIZE];
static lv_color_t * buf2[BUF_SIZE];
static lv_disp_buf_t disp_buf;
uint32_t size_in_px = BUF_SIZE;
lv_disp_buf_init(&disp_buf, buf1, buf2, size_in_px);
// Initialize LVGL display and attach the flush function
lv_disp_drv_init(&disp_drv);
disp_drv.flush_cb = display_HAL_flush;
disp_drv.hor_res = 240;
disp_drv.ver_res = 240;
disp_drv.buffer = &disp_buf;
lv_disp_drv_register(&disp_drv);
// Create timer to handle LVGL system tick
const esp_timer_create_args_t periodic_timer_args = {
.callback = &lv_tick_task,
.name = "periodic_gui"
};
esp_timer_handle_t periodic_timer;
ESP_ERROR_CHECK(esp_timer_create(&periodic_timer_args, &periodic_timer));
//On ESP32 it's better to create a periodic task instead of esp_register_freertos_tick_hook
ESP_ERROR_CHECK(esp_timer_start_periodic(periodic_timer, LV_TICK_PERIOD_MS * 1000)); // LV_TICK_PERIOD_MS expressed as microseconds
//GUI_frontend_main();
while(1){
lv_task_handler();
}
}
static void lv_tick_task(void *arg) {
(void) arg;
lv_tick_inc(LV_TICK_PERIOD_MS);
}
|
jfm92/lv_micropython | ports/microByte/drivers/GUI/GUI.h | void GUI_init();
|
jfm92/lv_micropython | ports/microByte/machine_gamepad.c | <gh_stars>1-10
#include "py/runtime.h"
#include "py/mphal.h"
#include "drivers/input/input_HAL/input_HAL.h"
#include "modmachine.h"
typedef enum {
BTN_UP = 0,
BTN_DOWN = 1,
BTN_LEFT = 2,
BTN_RIGHT = 3,
BTN_A = 4,
BTN_B = 5,
BTN_X = 6,
BTN_Y = 7,
BTN_R = 8,
BTN_L = 9,
BTN_START = 10,
BTN_SELECT = 11,
BTN_MENU = 12,
}BTN_num_t;
typedef struct _machine_gamepad_obj_t {
mp_obj_base_t base;
BTN_num_t id;
} machine_gamepad_obj_t;
STATIC const machine_gamepad_obj_t machine_btn_obj[] = {
{{&machine_gamepad_type}, BTN_UP},
{{&machine_gamepad_type}, BTN_DOWN},
{{&machine_gamepad_type}, BTN_LEFT},
{{&machine_gamepad_type}, BTN_RIGHT},
{{&machine_gamepad_type}, BTN_A},
{{&machine_gamepad_type}, BTN_B},
{{&machine_gamepad_type}, BTN_X},
{{&machine_gamepad_type}, BTN_Y},
{{&machine_gamepad_type}, BTN_R},
{{&machine_gamepad_type}, BTN_L},
{{&machine_gamepad_type}, BTN_START},
{{&machine_gamepad_type}, BTN_SELECT},
{{&machine_gamepad_type}, BTN_MENU},
};
mp_obj_t mp_btn_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
const machine_gamepad_obj_t *self = NULL;
int id = mp_obj_get_int(args[0]);
if(id>=0 && id < MP_ARRAY_SIZE(machine_btn_obj)){
self = (machine_gamepad_obj_t*)&machine_btn_obj[id];
}
else{
mp_raise_ValueError(MP_ERROR_TEXT("Invalid ID"));
}
return MP_OBJ_FROM_PTR(self);
}
//TODO: REmove and initialize on the main loop
STATIC mp_obj_t machine_gamepad_init(mp_obj_t self_in){
//TODO: Check if it's already initialize
input_init();
printf("hola\r\n");
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_1(machine_gamepad_init_obj, machine_gamepad_init);
mp_obj_t machine_gamepad_pressed(size_t n_args, const mp_obj_t *args){
machine_gamepad_obj_t *aux = args[0];
uint16_t btn_status = input_read();
if(!((btn_status >> aux->id) & 0x01)){
return mp_obj_new_bool(true);
}
return mp_obj_new_bool(false);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_gamepad_pressed_obj, 1, 2, machine_gamepad_pressed);
//TODO: Improve ID buttons
mp_obj_t machine_gamepad_help(){
printf("Buttons ID:\r\n");
printf("- Button Down: 0\r\n");
printf("- Button Left: 1\r\n");
printf("- Button Up: 2\r\n");
printf("- Button Right: 3\r\n");
printf("- Button Down: 0\r\n");
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_0(machine_gamepad_help_obj, machine_gamepad_help);
STATIC const mp_rom_map_elem_t machine_gamepad_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_gamepad_init_obj) },
{ MP_ROM_QSTR(MP_QSTR_pressed), MP_ROM_PTR(&machine_gamepad_pressed_obj) },
{ MP_ROM_QSTR(MP_QSTR_help), MP_ROM_PTR(&machine_gamepad_help_obj) },
};
STATIC MP_DEFINE_CONST_DICT(machine_gamepad_locals_dict, machine_gamepad_locals_dict_table);
const mp_obj_type_t machine_gamepad_type = {
{ &mp_type_type },
.name = MP_QSTR_gamepad,
//.print = esp32_pwm_print,
.make_new = mp_btn_make_new,
.locals_dict = (mp_obj_dict_t *)&machine_gamepad_locals_dict,
}; |
Gxjasmine/moudleTest | mineMoule/Classes/mineMoule.h | //
// mineMoule.h
// Pods
//
// Created by fuzhongw on 2021/5/6.
//
#ifndef mineMoule_h
#define mineMoule_h
#endif /* mineMoule_h */
|
Gxjasmine/moudleTest | Example/mineMoule/MFAppDelegate.h | //
// MFAppDelegate.h
// mineMoule
//
// Created by <EMAIL> on 04/30/2021.
// Copyright (c) 2021 <EMAIL>. All rights reserved.
//
@import UIKit;
@interface MFAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
Gxjasmine/moudleTest | Example/mineMoule/MFViewController.h | <reponame>Gxjasmine/moudleTest<filename>Example/mineMoule/MFViewController.h<gh_stars>0
//
// MFViewController.h
// mineMoule
//
// Created by <EMAIL> on 04/30/2021.
// Copyright (c) 2021 <EMAIL>. All rights reserved.
//
@import UIKit;
@interface MFViewController : UIViewController
@end
|
Gxjasmine/moudleTest | mineMoule/Classes/Cussasaview.h | //
// Cussasaview.h
// mineMoule
//
// Created by fuzhongw on 2021/5/6.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface Cussasaview : UIView
@end
NS_ASSUME_NONNULL_END
|
Gxjasmine/moudleTest | mineMoule/Classes/saaaaa.h | //
// saaaaa.h
// mineMoule
//
// Created by fuzhongw on 2021/5/6.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface saaaaa : UIView
@property (nonatomic, strong) NSString *name;
@end
NS_ASSUME_NONNULL_END
|
Gxjasmine/moudleTest | Example/Pods/Target Support Files/mineMoule/mineMoule-umbrella.h | <gh_stars>0
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "saaaaa.h"
#import "Cussasaview.h"
FOUNDATION_EXPORT double mineMouleVersionNumber;
FOUNDATION_EXPORT const unsigned char mineMouleVersionString[];
|
gscultho/HuskEOS | huskEOS/OS_CPU_Interface/Header/cpu_os_interface.h | /*************************************************************************/
/* File Name: cpu_os_interface.h */
/* Purpose: Scheduler HW interface. Routines for stack init, critical*/
/* sections, system tick, etc. */
/* Created by: <NAME> on 2/10/2019. */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#ifndef cpu_os_interface_h
#define cpu_os_interface_h
#include "rtos_cfg.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define OS_TICK_PRIORITY (0xC0)
#define PENDSV_PRIORITY (0xE0)
#define OS_INT_NO_MASK (0)
#define CPU_PENDSV_LOAD_MASK (0x10000000)
/*************************************************************************/
/* Macros */
/*************************************************************************/
#define EnableInterrupts(c) __asm("CPSIE i")
#define DisableInterrupts(c) __asm("CPSID i")
/*************************************************************************/
/* Interface with scheduler */
/*************************************************************************/
#define OS_CPU_ENTER_CRITICAL(void) (vd_cpu_disableInterrupts(void))
#define OS_CPU_EXIT_CRITICAL(void) (vd_cpu_enableInterrupts(void))
#define vd_cpu_enableInterruptsOSStart() EnableInterrupts(c)
#define vd_cpu_disableInterruptsOSStart() DisableInterrupts(c)
#define OS_CPU_MASK_SCHEDULER_TICK(c) (u1_cpu_maskInterrupts(OS_TICK_PRIORITY))
#define OS_CPU_UNMASK_SCHEDULER_TICK(c) (vd_cpu_unmaskInterrupts(c))
#define OS_CPU_TRIGGER_DISPATCHER() ((SYS_REG_ICSR_ADDR) |= CPU_PENDSV_LOAD_MASK)
#define vd_OSsch_systemTick_ISR(void) (SysTick_Handler(void))
/*************************************************************************/
/* Data Types */
/*************************************************************************/
/*************************************************************************/
/* Public Functions */
/*************************************************************************/
/*************************************************************************/
/* Function Name: vd_cpu_init */
/* Purpose: Initialize registers for scheduler interrupts. */
/* Arguments: U4 numMs: */
/* Period for scheduler IRQ to be triggered. */
/* Return: N/A */
/*************************************************************************/
void vd_cpu_init(U4 numMs);
/*************************************************************************/
/* Function Name: sp_cpu_taskStackInit */
/* Purpose: Initialize relevant parameters in task stack. */
/* Arguments: void* newTaskFcn: */
/* Function pointer to task routine. */
/* OS_STACK* sp: */
/* Pointer to bottom of task stack (highest mem. */
/* address). */
/* Return: os_t_p_sp: */
/* New stack pointer. */
/*************************************************************************/
OS_STACK* sp_cpu_taskStackInit(void (*newTaskFcn)(void), OS_STACK* sp);
/*************************************************************************/
/* Function Name: vd_cpu_disableInterrupts */
/* Purpose: Enter critical section by disabling interrupts. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
void vd_cpu_disableInterrupts(void);
/*************************************************************************/
/* Function Name: vd_cpu_enableInterrupts */
/* Purpose: Exit critical section by enabling interrupts. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
void vd_cpu_enableInterrupts(void);
/*************************************************************************/
/* Function Name: u1_cpu_maskInterrupts */
/* Purpose: Mask interrupts up to a specified priority. */
/* Arguments: U1 setMask: */
/* Interrupt priority mask. */
/* Return: ut_t_interruptMask: Previous interrupt mask. */
/*************************************************************************/
U1 u1_cpu_maskInterrupts(U1 setMask);
/*************************************************************************/
/* Function Name: vd_cpu_unmaskInterrupts */
/* Purpose: Restore previous interrupt mask. */
/* Arguments: U4 setMask: */
/* Interrupt priority mask. */
/* Return: N/A */
/*************************************************************************/
void vd_cpu_unmaskInterrupts(U1 setMask);
/*************************************************************************/
/* Function Name: u4_cpu_getCurrentMsPeriod */
/* Purpose: Returns current scheduler period in ms. */
/* Arguments: N/A */
/* Return: U4 u4_prev_periodMs */
/*************************************************************************/
U4 u4_cpu_getCurrentMsPeriod(void);
/*************************************************************************/
/* Function Name: vd_cpu_suspendScheduler */
/* Purpose: Turns off scheduler interrupts. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
void vd_cpu_suspendScheduler(void);
/*************************************************************************/
/* Function Name: vd_cpu_setNewSchedPeriod */
/* Purpose: Set scheduler interrupts to new speified period. */
/* Arguments: U4 numMs: */
/* Period for scheduler IRQ to be triggered. */
/* Return: N/A */
/*************************************************************************/
void vd_cpu_setNewSchedPeriod(U4 numMs);
/*************************************************************************/
/* Function Name: u1_cpu_getPercentOfTick */
/* Purpose: Return number of clock cycles done in current tick. */
/* Arguments: N/A */
/* Return: U1: Number of clock cycles. */
/*************************************************************************/
U1 u1_cpu_getPercentOfTick(void);
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
#endif
|
gscultho/HuskEOS | App/Source/app.c | <gh_stars>1-10
/*************************************************************************/
/* Starter app file for OS with three threads set up to run. Include */
/* header files from other OS modules to use them and create new threads */
/* by following the code below for reference. All module design and API */
/* information can be found in documentation in repository. */
/*************************************************************************/
/* OS includes */
#include "sch.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define APP_TICK_MS (1)
#define APP_TASK_STACK_SIZE (200)
#define APP_TASK1_PRIO (0)
#define APP_TASK2_PRIO (1)
#define APP_TASK3_PRIO (2)
#define APP_TASK1_PERIOD (1)
#define APP_TASK2_PERIOD (5)
#define APP_TASK3_PERIOD (10)
/*************************************************************************/
/* Private Function Prototypes */
/*************************************************************************/
static void app_task1(void);
static void app_task2(void);
static void app_task3(void);
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
static OS_STACK u4_taskStack [APP_TASK_STACK_SIZE];
static OS_STACK u4_taskStack2[APP_TASK_STACK_SIZE];
static OS_STACK u4_taskStack3[APP_TASK_STACK_SIZE];
/*************************************************************************/
/*************************************************************************/
/* Function Name: main */
/* Purpose: Control should be handed to RTOS. */
/* at end of function. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
int main()
{
/* Initialize OS with tick period. */
vd_OS_init(APP_TICK_MS);
/* Init task 1. */
u1_OSsch_createTask(&app_task1, /* Pointer to function definition. */
&u4_taskStack[APP_TASK_STACK_SIZE - 1], /* Pointer to highest memory address in stack. */
sizeof(u4_taskStack)/sizeof(OS_STACK), /* Size of stack in terms of OS_STACK. */
APP_TASK1_PRIO, /* Priority of task. */
APP_TASK1_PRIO); /* ID number of task for some API calls. Kept same as priority for simplicity. */
/* Init task 2. */
u1_OSsch_createTask(&app_task2, /* Pointer to function definition. */
&u4_taskStack2[APP_TASK_STACK_SIZE - 1], /* Pointer to highest memory address in stack. */
sizeof(u4_taskStack2)/sizeof(OS_STACK), /* Size of stack in terms of OS_STACK. */
APP_TASK2_PRIO, /* Priority of task. */
APP_TASK2_PRIO); /* ID number of task for some API calls. Kept same as priority for simplicity. */
/* Init task 3. */
u1_OSsch_createTask(&app_task3, /* Pointer to function definition. */
&u4_taskStack3[APP_TASK_STACK_SIZE - 1], /* Pointer to highest memory address in stack. */
sizeof(u4_taskStack3)/sizeof(OS_STACK), /* Size of stack in terms of OS_STACK. */
APP_TASK3_PRIO, /* Priority of task. */
APP_TASK3_PRIO); /* ID number of task for some API calls. Kept same as priority for simplicity. */
/* Hand control to OS, will not return. */
vd_OSsch_start();
}
/*************************************************************************/
/* Function Name: app_task1 */
/* Purpose: */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
static void app_task1(void)
{
U4 u4_t_sleepTime;
u4_t_sleepTime = APP_TASK1_PERIOD;
while(1)
{
//
vd_OSsch_taskSleep(u4_t_sleepTime);
}
}
/*************************************************************************/
/* Function Name: app_task2 */
/* Purpose: */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
static void app_task2(void)
{
U4 u4_t_sleepTime;
u4_t_sleepTime = APP_TASK2_PERIOD;
while(1)
{
//
vd_OSsch_taskSleep(u4_t_sleepTime);
}
}
/*************************************************************************/
/* Function Name: app_task3 */
/* Purpose: */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
static void app_task3(void)
{
U4 u4_t_sleepTime;
u4_t_sleepTime = APP_TASK3_PERIOD;
while(1)
{
//
vd_OSsch_taskSleep(u4_t_sleepTime);
}
}
|
gscultho/HuskEOS | huskEOS/Schedule/Header/sch_internal_IF.h | /*************************************************************************/
/* File Name: sch_internal_IF.h */
/* Purpose: Kernel access definitions and routines for scheduler. */
/* Created by: <NAME> on 5/20/2019 */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#ifndef sch_internal_IF_h
#define sch_internal_IF_h
#include "rtos_cfg.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define SCH_MAX_NUM_TASKS (RTOS_CONFIG_MAX_NUM_TASKS + ONE)
#define SCH_TASK_SLEEP_RESOURCE_MBOX (SCH_TASK_WAKEUP_MBOX_READY)
#define SCH_TASK_SLEEP_RESOURCE_QUEUE (SCH_TASK_WAKEUP_QUEUE_READY)
#define SCH_TASK_SLEEP_RESOURCE_SEMA (SCH_TASK_WAKEUP_SEMA_READY)
#define SCH_TASK_SLEEP_RESOURCE_FLAGS (SCH_TASK_WAKEUP_FLAGS_EVENT)
#define SCH_TASK_SLEEP_RESOURCE_MUTEX (SCH_TASK_WAKEUP_MUTEX_READY)
#define SCH_SET_PRIORITY_FAILED (0)
/*************************************************************************/
/* Data Types */
/*************************************************************************/
struct ListNode; /* Forward declaration. Defined in "listMgr_internal.h" */
typedef struct Sch_Task
{
OS_STACK* stackPtr; /* Task stack pointer must be first entry in struct. */
U1 priority; /* Task priority. */
U1 taskID; /* Task ID. Task can be referenced via this number. */
U1 flags; /* Status flags used for scheduling. */
U4 sleepCntr; /* Sleep counter. Unit is scheduler ticks. */
void* resource; /* If task is blocked on a resource, its address is stored here. */
U1 wakeReason; /* Stores code for reason task was most recently woken up. */
#if(RTOS_CONFIG_ENABLE_STACK_OVERFLOW_DETECT == RTOS_CONFIG_TRUE)
OS_STACK* topOfStack; /* Pointer to stack watermark. Used to detect stack overflow. */
#endif
}
Sch_Task;
#if (RTOS_CONFIG_CALC_TASK_CPU_LOAD == RTOS_CONFIG_TRUE)
/* Used to calculate CPU load. */
typedef struct CPU_IdleCalc
{
U1 CPU_idleAvg;
U4 CPU_idleRunning;
U1 CPU_idlePrevTimestamp;
}
CPU_IdleCalc;
/* More CPU run-time statistics can be added here. */
typedef struct OS_RunTimeStats
{
CPU_IdleCalc CPUIdlePercent;
}
OS_RunTimeStats;
#endif
/*************************************************************************/
/* Public Functions */
/*************************************************************************/
/*************************************************************************/
/* Function Name: vd_OSsch_setReasonForWakeup */
/* Purpose: Set reason for wakeup to resource available. Called */
/* internal to RTOS by other RTOS modules. It is expected*/
/* that OS internal modules will call taskWake() *after* */
/* this function call and maintain their own block lists.*/
/* Arguments: U1 reason: */
/* Identifier code for wakeup reason. */
/* Sch_Task* wakeupTaskTCB: */
/* Pointer to task TCB that is being woken up which */
/* was stored on resource blocked list. */
/* Return: void */
/*************************************************************************/
void vd_OSsch_setReasonForWakeup(U1 reason, struct Sch_Task* wakeupTaskTCB);
/*************************************************************************/
/* Function Name: vd_OSsch_setReasonForSleep */
/* Purpose: Set reason for task sleep according to mask and set */
/* task to sleep state. */
/* Arguments: void* taskSleepResource: */
/* Address of resource task is blocked on. */
/* U1 resourceType: */
/* Code for resource that task is sleeping on. */
/* U4 period: */
/* Period to sleep for. */
/* Return: N/A */
/*************************************************************************/
void vd_OSsch_setReasonForSleep(void* taskSleepResource, U1 resourceType, U4 period);
/*************************************************************************/
/* Function Name: u1_OSsch_setNewPriority */
/* Purpose: Function to change task priority in support of */
/* priority inheritance. Internal use only. Internal */
/* module must ensure that no two active tasks share */
/* the same priority value at any time. */
/* Arguments: Sch_Task* tcb: */
/* Pointer to TCB to have priority changed. */
/* U1 newPriority: */
/* */
/* Return: U1: Previous priority value. */
/*************************************************************************/
U1 u1_OSsch_setNewPriority(struct Sch_Task* tcb, U1 newPriority);
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
extern Sch_Task* tcb_g_p_currentTaskBlock; /* Lets internal modules quickly dereference current task data. Should be used as read-only. */
extern struct ListNode* Node_s_ap_mapTaskIDToTCB[SCH_MAX_NUM_TASKS]; /* Lets internal modules quickly dereference TCB from task ID. */
/* THESE MACROS MUST BE USED AS READ-ONLY. MADE AVAILABLE FOR BLOCK LIST HANDLING BY RESOURCES. */
#define SCH_CURRENT_TCB_ADDR (tcb_g_p_currentTaskBlock) /* Address of current task TCB. */
#define SCH_CURRENT_TASK_ID ((U1)(tcb_g_p_currentTaskBlock->taskID)) /* ID of current task. */
#define SCH_ID_TO_TCB(c) (Node_s_ap_mapTaskIDToTCB[c]->TCB) /* Get TCB address from task ID. */
#define SCH_CURRENT_TASK_PRIO (tcb_g_p_currentTaskBlock->priority) /* Get priority from TCB address. */
#define SCH_ID_TO_PRIO(c) (Node_s_ap_mapTaskIDToTCB[c]->TCB->priority) /* Get priority from task ID. */
#endif
|
gscultho/HuskEOS | huskEOS/OS_CPU_Interface/Source/cpu_os_interface.c | /*************************************************************************/
/* File Name: cpu_os_interface.c */
/* Purpose: APIs for scheduler to interface with hardware. */
/* Compiler: ARM C/C++ Compiler, V5.06 [Build 750] */
/* Created by: <NAME> on 2/12/19. */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
/*************************************************************************/
/* Includes */
/*************************************************************************/
#include "cpu_os_interface.h"
/*************************************************************************/
/* External References */
/*************************************************************************/
extern U1 MaskInterrupt(U1);
extern void UnmaskInterrupt(U1);
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define CPU_FALSE (0)
#define SYSTICK_CONTROL_R (NVIC_ST_CTRL_R)
#define SYSTICK_RELOAD_R (NVIC_ST_RELOAD_R)
#define SYSTICK_CURRENT_COUNT_R (NVIC_ST_CURRENT_R)
#define SYSTICK_CALBIRATION_R (NVIC_ST_CALIBRATE_R)
#define SYSTICK_PRIORITY_SET_R (NVIC_ST_PRIORITY_R)
#define PENDSV_PRIORITY_SET_R (NVIC_PENDSV_PRIORITY_R)
#define TIME_CAL_10_TO_1_MS (10)
#define SYSTICK_DISABLED (0x00000007)
#define SYSTICK_24_BIT_MASK (0x00FFFFFF)
#define INTERRUPT_NEST_COUNT_ZERO (0)
#define SYSTICK_CTRL_EXTERNAL_CLK (0x03)
#define STACK_FRAME_PSR_INIT (0x01000000)
#define END_OF_REG_STACK_FRAME (-16)
#define PSR_REGISTER_SLOT (-1)
#define GENERAL_PURPOSE_REG_START (-2)
/*************************************************************************/
/* Data Types */
/*************************************************************************/
typedef U4 clockReg;
/*************************************************************************/
/* Global Variables, Constants */
/*************************************************************************/
static clockReg reg_s_currentReloadVal;
/*************************************************************************/
/* Private Function Prototypes */
/*************************************************************************/
static void vd_cpu_sysTickSet(U4 numMs);
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
static U4 u4_periodMs;
static U1 u1_intNestCounter;
/*************************************************************************/
/*************************************************************************/
/* Function Name: vd_cpu_init */
/* Purpose: Initialize registers for scheduler interrupts. */
/* Arguments: U4 numMs: */
/* Period for scheduler IRQ to be triggered. */
/* Return: N/A */
/*************************************************************************/
void vd_cpu_init(U4 numMs)
{
u4_periodMs = (U4)ZERO;
u1_intNestCounter = (U1)ZERO;
reg_s_currentReloadVal = (U4)ZERO;
SYSTICK_PRIORITY_SET_R |= (U1)OS_TICK_PRIORITY;
PENDSV_PRIORITY_SET_R |= (U1)PENDSV_PRIORITY;
vd_cpu_disableInterruptsOSStart();
vd_cpu_sysTickSet(numMs);
}
/*************************************************************************/
/* Function Name: sp_cpu_taskStackInit */
/* Purpose: Initialize relevant parameters in task stack. */
/* Arguments: void* newTaskFcn: */
/* Function pointer to task routine. */
/* OS_STACK* sp: */
/* Pointer to bottom of task stack (highest mem. */
/* address). */
/* Return: os_t_p_sp: */
/* New stack pointer. */
/*************************************************************************/
OS_STACK* sp_cpu_taskStackInit(void (*newTaskFcn)(void), OS_STACK* sp)
{
S1 s1_t_index;
OS_STACK *os_t_p_stackFrame;
OS_STACK *os_t_p_sp;
os_t_p_stackFrame = sp;
/* Decrement to move upwards in stack */
os_t_p_stackFrame[ZERO] = (OS_STACK)STACK_FRAME_PSR_INIT;
os_t_p_stackFrame[PSR_REGISTER_SLOT] = (OS_STACK)newTaskFcn;
for(s1_t_index = (S1)GENERAL_PURPOSE_REG_START; s1_t_index > (S1)END_OF_REG_STACK_FRAME; --s1_t_index)
{
os_t_p_stackFrame[s1_t_index] = (OS_STACK)ZERO;
}
os_t_p_sp = &os_t_p_stackFrame[s1_t_index + ONE]; /* index is -16 at this point, want -15 */
return (os_t_p_sp);
}
/*************************************************************************/
/* Function Name: vd_cpu_disableInterrupts */
/* Purpose: Enter critical section by disabling interrupts. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
#pragma push
#pragma O0
#pragma diag_suppress 3731 /* __ldrex and __strex instrinsics deprecated since ARMCC compiler does not guarantee the order of the load/store instructions.
The order is thus preserved by disabling optimization for this section of code and the instrinsics can be safely used. */
void vd_cpu_disableInterrupts(void)
{
U1 u1_t_newIntNestCntr;
do
{
u1_t_newIntNestCntr = __ldrex(&u1_intNestCounter);
}
while(__strex((++u1_t_newIntNestCntr), &u1_intNestCounter));
DisableInterrupts();
}
#pragma pop
/*************************************************************************/
/* Function Name: vd_cpu_enableInterrupts */
/* Purpose: Exit critical section by enabling interrupts. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
#pragma push
#pragma O0
#pragma diag_suppress 3731 /* __ldrex and __strex instrinsics deprecated since ARMCC compiler does not guarantee the order of the load/store instructions.
The order is thus preserved by disabling optimization for this section of code and the instrinsics can be safely used. */
void vd_cpu_enableInterrupts(void)
{
U1 u1_t_newIntNestCntr;
do
{
u1_t_newIntNestCntr = __ldrex(&u1_intNestCounter);
}
while(__strex((--u1_t_newIntNestCntr), &u1_intNestCounter));
if(u1_t_newIntNestCntr == (U1)INTERRUPT_NEST_COUNT_ZERO)
{
EnableInterrupts();
}
}
#pragma pop
/*************************************************************************/
/* Function Name: u1_cpu_maskInterrupts */
/* Purpose: Mask interrupts up to a specified priority. */
/* Arguments: U1 setMask: */
/* Interrupt priority mask. */
/* Return: ut_t_interruptMask: Previous interrupt mask. */
/*************************************************************************/
U1 u1_cpu_maskInterrupts(U1 setMask)
{
U1 ut_t_interruptMask;
vd_cpu_disableInterrupts();
ut_t_interruptMask = MaskInterrupt(setMask);
vd_cpu_enableInterrupts();
return (ut_t_interruptMask);
}
/*************************************************************************/
/* Function Name: vd_cpu_unmaskInterrupts */
/* Purpose: Restore previous interrupt mask. */
/* Arguments: U4 setMask: */
/* Interrupt priority mask. */
/* Return: N/A */
/*************************************************************************/
void vd_cpu_unmaskInterrupts(U1 setMask)
{
vd_cpu_disableInterrupts();
UnmaskInterrupt(setMask);
vd_cpu_enableInterrupts();
}
/*************************************************************************/
/* Function Name: u4_cpu_getCurrentMsPeriod */
/* Purpose: Returns current scheduler period in ms. */
/* Arguments: N/A */
/* Return: U4 u4_prev_periodMs */
/*************************************************************************/
U4 u4_cpu_getCurrentMsPeriod(void)
{
return (u4_periodMs);
}
/*************************************************************************/
/* Function Name: vd_cpu_suspendScheduler */
/* Purpose: Turns off scheduler interrupts. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
void vd_cpu_suspendScheduler(void)
{
SYSTICK_CONTROL_R &= ~(SYSTICK_DISABLED);
}
/*************************************************************************/
/* Function Name: vd_cpu_setNewSchedPeriod */
/* Purpose: Set scheduler interrupts to new speified period. */
/* Arguments: U4 numMs: */
/* Period for scheduler IRQ to be triggered. */
/* Return: N/A */
/*************************************************************************/
void vd_cpu_setNewSchedPeriod(U4 numMs)
{
vd_cpu_sysTickSet(numMs);
}
/*************************************************************************/
/* Function Name: u1_cpu_getPercentOfTick */
/* Purpose: Return number of clock cycles done in current tick. */
/* Arguments: N/A */
/* Return: U1: Number of clock cycles. */
/*************************************************************************/
U1 u1_cpu_getPercentOfTick(void)
{
U4 u4_t_calculation;
if(reg_s_currentReloadVal != (U4)ZERO)
{
u4_t_calculation = (reg_s_currentReloadVal - (SYSTICK_24_BIT_MASK & SYSTICK_CURRENT_COUNT_R))*100;
return(u4_t_calculation/reg_s_currentReloadVal);
}
else return ((U1)ZERO);
}
/*************************************************************************/
/* Function Name: vd_cpu_sysTickSet */
/* Purpose: Configure SysTick registers. */
/* Arguments: U4 numMs: */
/* Period for scheduler IRQ to be triggered. */
/* Return: N/A */
/*************************************************************************/
static void vd_cpu_sysTickSet(U4 numMs)
{
U4 u4_t_scale;
u4_t_scale = SYSTICK_CALBIRATION_R + ONE;
u4_t_scale &= SYSTICK_24_BIT_MASK;
/* Get scale to 1 ms */
u4_t_scale = u4_t_scale/TIME_CAL_10_TO_1_MS;
numMs = numMs*u4_t_scale;
/* SysTick overflow check */
numMs &= (U4)SYSTICK_24_BIT_MASK;
SYSTICK_CONTROL_R &= ~(SYSTICK_DISABLED); /* 1) disable SysTick during setup */
SYSTICK_RELOAD_R = --numMs; /* 2) Reload value */
SYSTICK_CURRENT_COUNT_R = CPU_FALSE; /* 3) any write to CURRENT clears it */
SYSTICK_CONTROL_R |= (U1)SYSTICK_CTRL_EXTERNAL_CLK; /* 4) enable SysTick with core clock */
reg_s_currentReloadVal = numMs;
}
/***********************************************************************************************/
/* History */
/***********************************************************************************************/
/* Version Date Description */
/* */
/* 0.1 3/25/19 Created module to add APIs for handling scheduler interrupt */
/* frequency. Suspend, resume, setNew APIs added. */
/* 0.2 4/1/19 Added APIs to pause and resume SysTick without resetting it. */
/* 0.3 5/29/19 Removed several APIs not needed. */
/* 0.4 5/30/19 Added APIs for handling interrupt enabling/masking */
/* 0.5 6/22/19 API for CPU load calculation support. */
/* */
/* 0.6 5/3/20 Suppressed warnings for __ldrex and strex instrinsics in */
/* ARMCC compiler V5.06. */
/* */
|
gscultho/HuskEOS | huskEOS/List_Manager/Source/listMgr_internal.c | /*************************************************************************/
/* File Name: listMgr_internal.c */
/* Purpose: Routines for managing task lists in scheduler */
/* and wait lists for other RTOS modules. */
/* Created by: <NAME> on 7/17/2019. */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
/*************************************************************************/
/* Includes */
/*************************************************************************/
#include "listMgr_internal.h"
#include "sch_internal_IF.h"
/*************************************************************************/
/* External References */
/*************************************************************************/
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define LIST_NULL_PTR ((void*)ZERO)
/*************************************************************************/
/* Data Structures */
/*************************************************************************/
/*************************************************************************/
/* Global Variables, Constants */
/*************************************************************************/
/*************************************************************************/
/* Private Function Prototypes */
/*************************************************************************/
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/* Function Name: vd_list_addNodeToEnd */
/* Purpose: Add new node to end of specified linked list. */
/* Arguments: ListNode** listHead: */
/* Pointers of head node. */
/* ListNode* newNode: */
/* Node to be added to end of list. */
/* Return: N/A */
/*************************************************************************/
void vd_list_addNodeToEnd(struct ListNode** listHead, struct ListNode* newNode)
{
ListNode* node_t_ptr;
/* List is empty */
if(*listHead == LIST_NULL_PTR)
{
newNode->nextNode = LIST_NULL_PTR;
newNode->previousNode = LIST_NULL_PTR;
*listHead = newNode;
}
/* Add new node to end of list */
else
{
node_t_ptr = *listHead;
while(node_t_ptr->nextNode != LIST_NULL_PTR)
{
node_t_ptr = node_t_ptr->nextNode;
}
node_t_ptr->nextNode = newNode;
newNode->nextNode = LIST_NULL_PTR;
newNode->previousNode = node_t_ptr;
}
}
/*************************************************************************/
/* Function Name: vd_list_addTaskByPrio */
/* Purpose: Add task to a queue by order of priority. */
/* Arguments: ListNode** listHead, newNode: */
/* Pointers to head node and new node. */
/* Return: N/A */
/*************************************************************************/
void vd_list_addTaskByPrio(struct ListNode** listHead, struct ListNode* newNode)
{
ListNode* node_t_tempPtr;
/* List is empty */
if(*listHead == LIST_NULL_PTR)
{
newNode->nextNode = LIST_NULL_PTR;
newNode->previousNode = LIST_NULL_PTR;
*listHead = newNode;
}
/* If new node has higher priority than current highest priority task */
else if(newNode->TCB->priority <= (*listHead)->TCB->priority)
{
/* Insert new node as the new head */
newNode->nextNode = *listHead;
newNode->previousNode = LIST_NULL_PTR;
(*listHead)->previousNode = newNode;
/* Update head pointer of list */
*listHead = newNode;
}
else
{
node_t_tempPtr = (*listHead);
/* Find insertion point */
while(newNode->TCB->priority >= node_t_tempPtr->TCB->priority)
{
node_t_tempPtr = node_t_tempPtr->nextNode;
}
/* Set new node's next node equal to this node */
newNode->nextNode = node_t_tempPtr;
/* Move back one node */
node_t_tempPtr = node_t_tempPtr->previousNode;
/* Set next node's previous pointer to the new node */
(newNode->nextNode)->previousNode = newNode;
/*Set new node's previous pointer equal to the node before it */
newNode->previousNode = node_t_tempPtr;
/* Set previous node's next pointer equal to the new node */
node_t_tempPtr->nextNode = newNode;
}
}
/*************************************************************************/
/* Function Name: vd_list_addNodeToFront */
/* Purpose: Add node to front of linked list. */
/* Arguments: ListNode** listHead: */
/* Pointers to head node and new node. */
/* ListNode* newNode: */
/* Pointer to node to be added to front. */
/* Return: N/A */
/*************************************************************************/
void vd_list_addNodeToFront(struct ListNode** listHead, struct ListNode* newNode)
{
/* List is empty */
if(*listHead == LIST_NULL_PTR)
{
newNode->nextNode = LIST_NULL_PTR;
newNode->previousNode = LIST_NULL_PTR;
*listHead = newNode;
}
else
{
newNode->previousNode = LIST_NULL_PTR;
/* Connect new node with old head node */
newNode->nextNode = (*listHead);
/* Point back to new first node */
newNode->nextNode->previousNode = newNode;
/* Set head pointer to new first node */
*listHead = newNode;
}
}
/*************************************************************************/
/* Function Name: vd_list_removeNode */
/* Purpose: Remove a node from linked list. */
/* Arguments: ListNode** listHead: */
/* Pointer of head node. */
/* ListNode* removeNode: */
/* Pointer to node to remove. */
/* Return: N/A */
/*************************************************************************/
void vd_list_removeNode(struct ListNode** listHead, struct ListNode* removeNode)
{
/* Change links */
if(removeNode->previousNode != LIST_NULL_PTR)
{
removeNode->previousNode->nextNode = removeNode->nextNode;
}
if(removeNode->nextNode != LIST_NULL_PTR)
{
removeNode->nextNode->previousNode = removeNode->previousNode;
}
/* Special case if head was pointing to this node */
if(*listHead == removeNode)
{
if((*listHead)->nextNode != LIST_NULL_PTR)
{
*listHead = (*listHead)->nextNode;
}
else
{
*listHead = LIST_NULL_PTR;
}
}
/* Reset node pointers */
removeNode->nextNode = LIST_NULL_PTR;
removeNode->previousNode = LIST_NULL_PTR;
}
/*************************************************************************/
/* Function Name: node_list_removeFirstNode */
/* Purpose: Remove first node from linked list. */
/* Arguments: ListNode** listHead: */
/* Pointer of head node. */
/* Return: ListNode*: */
/* Pointer to removed node. */
/*************************************************************************/
ListNode* node_list_removeFirstNode(struct ListNode** listHead)
{
ListNode* node_t_tempPtr;
ListNode* node_t_deletedNodePtr;
node_t_deletedNodePtr = LIST_NULL_PTR;
if(*listHead != LIST_NULL_PTR)
{
/* Get address of first node in list */
node_t_deletedNodePtr = *listHead;
/* Move to new head of list */
node_t_tempPtr = (*listHead)->nextNode;
if(node_t_tempPtr != LIST_NULL_PTR)
{
node_t_tempPtr->previousNode = LIST_NULL_PTR;
}
/* Set new head pointer */
*listHead = node_t_tempPtr;
/* Reset deleted node pointers */
node_t_deletedNodePtr->nextNode = LIST_NULL_PTR;
node_t_deletedNodePtr->previousNode = LIST_NULL_PTR;
}
return (node_t_deletedNodePtr);
}
/*************************************************************************/
/* Function Name: node_list_removeNodeByTCB */
/* Purpose: Remove node from linked list that holds specified TCB.*/
/* Arguments: ListNode** listHead: */
/* Pointer to head node. */
/* Sch_Task* taskTCB: */
/* Pointer to TCB to be searched for. */
/* Return: ListNode*: */
/* Pointer to removed node. */
/*************************************************************************/
ListNode* node_list_removeNodeByTCB(struct ListNode** listHead, struct Sch_Task* taskTCB)
{
ListNode* node_t_tempPtr;
node_t_tempPtr = *listHead;
/* Find TCB */
while((node_t_tempPtr->TCB != taskTCB) && (node_t_tempPtr != LIST_NULL_PTR))
{
node_t_tempPtr = node_t_tempPtr->nextNode;
}
if(node_t_tempPtr != LIST_NULL_PTR)
{
vd_list_removeNode(listHead, node_t_tempPtr);
}
return(node_t_tempPtr);
}
/***********************************************************************************************/
/* History */
/***********************************************************************************************/
/* Version Date Description */
/* */
/* 0.1 7/17/19 Added routines to support task queue management for scheduler*/
/* version 2.x. Still in work. */
|
gscultho/HuskEOS | huskEOS/Mutex/Header/mutex_internal_IF.h | /*************************************************************************/
/* File Name: mutex_internal_IF.h */
/* Purpose: Kernel access definitions and routines for mutex. */
/* Created by: <NAME> on 5/23/19 */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#ifndef mutex_internal_IF_h
#if(RTOS_CFG_OS_MUTEX_ENABLED == RTOS_CONFIG_TRUE)
#define mutex_internal_IF_h
#include "rtos_cfg.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define MUTEX_MAX_NUM_BLOCKED (RTOS_CFG_MAX_NUM_BLOCKED_TASKS_MUTEX)
/*************************************************************************/
/* Data Types */
/*************************************************************************/
struct listNode; /* Forward declaration. Defined in "listMgr_internal.h" */
struct Sch_Task; /* Forward declaration. Defined in sch_internal_IF.h" */
/* Handle task blocking on each mutex. */
typedef struct BlockedTasks
{
struct ListNode blockedTasks[MUTEX_MAX_NUM_BLOCKED]; /* Memory allocated for storing blocked task data. */
struct ListNode* blockedListHead; /* Pointer to first blocked task in list (highest priority. */
}
BlockedTasks;
/* Priority management. */
typedef struct PrioInheritance
{
U1 taskRealPrio; /* Real priority of task holding mutex. */
U1 taskInheritedPrio; /* Inherited priority of task holding mutex. */
struct Sch_Task* mutexHolder; /* Pointer to task holding the mutex. */
}
PrioInheritance;
typedef struct Mutex
{
U1 lock; /* Binary lock value (1 is available). */
BlockedTasks blockedTaskList; /* Group for handling blocked tasks. */
PrioInheritance priority; /* Group for handling priority inheritance. */
}
Mutex;
/*************************************************************************/
/* Public Functions */
/*************************************************************************/
/*************************************************************************/
/* Function Name: vd_OSmutex_blockedTimeout */
/* Purpose: API for scheduler to call when sleeping task times out*/
/* Arguments: Mutex* mutex: */
/* Pointer to mutex. */
/* Sch_Task* taskTCB: */
/* Pointer to TCB of blocked task. */
/* Return: N/A */
/*************************************************************************/
void vd_OSmutex_blockedTimeout(struct Mutex* mutex, struct Sch_Task* taskTCB);
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
#endif /* Conditional compile. */
#endif
|
gscultho/HuskEOS | huskEOS/Mutex/Header/mutex.h | /*************************************************************************/
/* File Name: mutex.h */
/* Purpose: Header file for mutex module. */
/* Created by: <NAME> on 3/3/19 */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#ifndef mutex_h
#if(RTOS_CFG_OS_MUTEX_ENABLED == RTOS_CONFIG_TRUE)
#define mutex_h
#include "rtos_cfg.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define MUTEX_SUCCESS (1)
#define MUTEX_AVAILABLE (1)
#define MUTEX_TAKEN (0)
#define MUTEX_NO_OBJECTS_AVAILABLE (0)
#define MUTEX_NOT_HELD_BY_TASK (0)
/*************************************************************************/
/* Data Types */
/*************************************************************************/
typedef struct Mutex OSMutex; /* Forward declaration */
/*************************************************************************/
/* Public Functions */
/*************************************************************************/
/*************************************************************************/
/* Function Name: u1_OSmutex_init */
/* Purpose: Initialize specified mutex. */
/* Arguments: OSMutex** mutex: */
/* Address of mutex object. */
/* U1 initValue: */
/* Initial value for mutex. */
/* Return: U1: MUTEX_SUCCESS OR */
/* MUTEX_NO_OBJECTS_AVAILABLE */
/*************************************************************************/
U1 u1_OSmutex_init(OSMutex** mutex, U1 initValue);
/*************************************************************************/
/* Function Name: u1_OSmutex_lock */
/* Purpose: Claim mutex referenced by pointer. */
/* Arguments: OSMutex* mutex: */
/* Pointer to mutex. */
/* U4 blockPeriod: */
/* Number of time units for task to sleep if blocked. */
/* */
/* Return: U1 MUTEX_TAKEN OR */
/* MUTEX_SUCCESS */
/*************************************************************************/
U1 u1_OSmutex_lock(OSMutex* mutex, U4 blockPeriod);
/*************************************************************************/
/* Function Name: u1_OSmutex_check */
/* Purpose: Check status of mutex. */
/* Arguments: OSMutex* mutex: */
/* Pointer to mutex. */
/* Return: U1 MUTEX_TAKEN OR */
/* MUTEX_SUCCESS */
/*************************************************************************/
U1 u1_OSmutex_check(OSMutex* mutex);
/*************************************************************************/
/* Function Name: u1_OSmutex_unlock */
/* Purpose: Release mutex and manage priority inheritance. */
/* Arguments: OSMutex* mutex: */
/* Pointer to mutex. */
/* Return: U1: MUTEX_SUCCESS OR */
/* MUTEX_ALREADY_RELEASED */
/*************************************************************************/
U1 u1_OSmutex_unlock(OSMutex* mutex);
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
#else
#warning "MUTEX MODULE NOT ENABLED"
#endif /* Conditional compile */
#endif
|
gscultho/HuskEOS | huskEOS/Queue/Header/queue.h | /*************************************************************************/
/* File Name: queue.h */
/* Purpose: Main header file for queue module. */
/* Created by: <NAME> on 3/16/19. */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#ifndef queue_h
#if(RTOS_CFG_OS_QUEUE_ENABLED == RTOS_CONFIG_TRUE)
#define queue_h
#include "rtos_cfg.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define FIFO_MAX_NUM_QUEUES (RTOS_CFG_NUM_FIFO)
#define FIFO_QUEUE_PUT_SUCCESS (1)
#define FIFO_STS_QUEUE_EMPTY (2)
#define FIFO_STS_QUEUE_FULL (3)
#define FIFO_STS_QUEUE_READY (1)
#define FIFO_FAILURE (0)
#define FIFO_SUCCESS (1)
/* API error codes */
#define FIFO_ERR_NO_ERROR (0)
#define FIFO_ERR_QUEUE_OUT_OF_RANGE (255)
#define FIFO_ERR_QUEUE_FULL (1)
#define FIFO_ERR_QUEUE_EMPTY (2)
/*************************************************************************/
/* Data Types */
/*************************************************************************/
typedef struct Queue OSQueue;
/*************************************************************************/
/* Public Functions */
/*************************************************************************/
/*************************************************************************/
/* Function Name: u1_OSqueue_init */
/* Purpose: Initialize FIFO and provide ID number. */
/* Arguments: Q_MEM* queueStart: */
/* Pointer to first address allocated for queue. */
/* U4 queueLength: */
/* Length of queue. Number of Q_MEM entries. */
/* Return: U1: FIFO_FAILURE OR */
/* queue ID number. */
/*************************************************************************/
U1 u1_OSqueue_init(Q_MEM* queueStart, U4 queueLength);
/*************************************************************************/
/* Function Name: u1_OSqueue_flushFifo */
/* Purpose: Clear all values in a queue. */
/* Arguments: U1 u1_queueNum: */
/* ID of queue to be flushed. */
/* U1* error: */
/* Address to write error to. */
/* Return: FIFO_SUCCESS OR */
/* FIFO_FAILURE */
/*************************************************************************/
U1 u1_OSqueue_flushFifo(U1 queueNum, U1* error);
/*************************************************************************/
/* Function Name: data_OSqueue_get */
/* Purpose: Get data from queue. If higher priority task is */
/* waiting to send data, it will preempt this task. */
/* Arguments: U1 queueNum: */
/* Queue index being referenced. */
/* U4 blockPeriod: */
/* Sleep timeout period if task is blocked. */
/* U1* error: */
/* Address to write error to. */
/* Return: Q_MEM FIFO_FAILURE OR */
/* data at head of queue. */
/*************************************************************************/
Q_MEM data_OSqueue_get(U1 queueNum, U4 blockPeriod, U1* error);
/*************************************************************************/
/* Function Name: u1_OSqueue_getSts */
/* Purpose: Check if queue is ready, full, or empty. */
/* Arguments: U1 queueNum: */
/* Queue index being referenced. */
/* U1* error: */
/* Address to write error to. */
/* Return: U1 FIFO_STS_QUEUE_FULL OR */
/* FIFO_FAILURE OR */
/* FIFO_STS_QUEUE_EMPTY OR */
/* FIFO_STS_QUEUE_READY */
/*************************************************************************/
U1 u1_OSqueue_getSts(U1 queueNum, U1* error);
/*************************************************************************/
/* Function Name: u1_OSqueue_put */
/* Purpose: Put data in queue if not full. */
/* Arguments: U1 queueNum: */
/* Queue index being referenced. */
/* U4 blockPeriod: */
/* Sleep timeout period if task is blocked. */
/* U4 message: */
/* Data to be added to queue. */
/* U1* error: */
/* Address to write error to. */
/* Return: U1 FIFO_QUEUE_FULL OR */
/* FIFO_QUEUE_PUT_SUCCESS */
/*************************************************************************/
U1 u1_OSqueue_put(U1 queueNum, U4 blockPeriod, Q_MEM message, U1* error);
/*************************************************************************/
/* Function Name: u4_OSqueue_getNumInFIFO */
/* Purpose: Return number of items in buffer. */
/* Arguments: U1 queueNum: */
/* Queue index being referenced. */
/* U1* error: */
/* Address to write error to. */
/* Return: U4 u4_t_count: */
/* FIFO_FAILURE OR */
/* Number of entries in queue */
/*************************************************************************/
U4 u4_OSqueue_getNumInFIFO(U1 queueNum, U1* error);
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
#else
#warning "QUEUE MODULE NOT ENABLED"
#endif /* Conditional compile */
#endif
|
gscultho/HuskEOS | huskEOS/Semaphore/Source/semaphore.c | <filename>huskEOS/Semaphore/Source/semaphore.c
/*************************************************************************/
/* File Name: semaphore.c */
/* Purpose: Semaphore services for application layer tasks. */
/* Created by: <NAME> on 3/24/19. */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#include "rtos_cfg.h"
#if(RTOS_CFG_OS_SEMAPHORE_ENABLED == RTOS_CONFIG_TRUE)
/*************************************************************************/
/* Includes */
/*************************************************************************/
#include "listMgr_internal.h"
#include "semaphore_internal_IF.h"
#include "semaphore.h"
#include "sch_internal_IF.h"
#include "sch.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define SEMA_NO_BLOCK (0)
#define SEMA_NULL_PTR ((void*)0)
#define SEMA_NO_BLOCKED_TASKS (0)
#define SEMA_NUM_SEMAPHORES (RTOS_CFG_NUM_SEMAPHORES)
/*************************************************************************/
/* Static Global Variables, Constants */
/*************************************************************************/
static Semaphore sema_s_semaList[SEMA_NUM_SEMAPHORES];
/*************************************************************************/
/* Private Function Prototypes */
/*************************************************************************/
static void vd_OSsema_blockTask(OSSemaphore* semaphore);
static void vd_OSsema_unblockTask(OSSemaphore* semaphore);
/*************************************************************************/
/*************************************************************************/
/* Function Name: u1_OSsema_init */
/* Purpose: Initialize specified semaphore. */
/* Arguments: OSSemaphore** semaphore: */
/* Address of semaphore object. */
/* S1 initValue: */
/* Initial value for semsphore. */
/* Return: U1: SEMA_SEMAPHORE_SUCCESS OR */
/* SEMA_NO_SEMA_OBJECTS_AVAILABLE */
/*************************************************************************/
U1 u1_OSsema_init(OSSemaphore** semaphore, S1 initValue)
{
U1 u1_t_index;
U1 u1_t_returnSts;
static U1 u1_s_numSemaAllocated = (U1)ZERO;
u1_t_returnSts = (U1)SEMA_NO_SEMA_OBJECTS_AVAILABLE;
OS_SCH_ENTER_CRITICAL();
/* Have semaphore pointer point to available object */
if(u1_s_numSemaAllocated < (U1)SEMA_NUM_SEMAPHORES)
{
(*semaphore) = &sema_s_semaList[u1_s_numSemaAllocated];
++u1_s_numSemaAllocated;
(*semaphore)->sema = initValue;
(*semaphore)->blockedListHead = SEMA_NULL_PTR;
for(u1_t_index = (U1)ZERO; u1_t_index < (U1)SEMA_MAX_NUM_BLOCKED; u1_t_index++)
{
(*semaphore)->blockedTasks[u1_t_index].nextNode = SEMA_NULL_PTR;
(*semaphore)->blockedTasks[u1_t_index].previousNode = SEMA_NULL_PTR;
(*semaphore)->blockedTasks[u1_t_index].TCB = SEMA_NULL_PTR;
}
u1_t_returnSts = (U1)SEMA_SEMAPHORE_SUCCESS;
}
else
{
}
OS_SCH_EXIT_CRITICAL();
return (u1_t_returnSts);
}
/*************************************************************************/
/* Function Name: u1_OSsema_wait */
/* Purpose: Claim semaphore referenced by pointer. */
/* Arguments: OSSemaphore* semaphore: */
/* Pointer to semaphore. */
/* U4 blockPeriod: */
/* Number of time units for task to sleep if blocked. */
/* */
/* Return: U1 SEMA_SEMAPHORE_TAKEN OR */
/* SEMA_SEMAPHORE_SUCCESS */
/*************************************************************************/
U1 u1_OSsema_wait(OSSemaphore* semaphore, U4 blockPeriod)
{
U1 u1_t_returnSts;
u1_t_returnSts = (U1)SEMA_SEMAPHORE_TAKEN;
OS_SCH_ENTER_CRITICAL();
/* Check if available */
if(semaphore->sema == (U1)ZERO)
{
/* If non-blocking function call, exit critical section and return immediately */
if(blockPeriod == (U4)SEMA_NO_BLOCK)
{
OS_SCH_EXIT_CRITICAL();
}
/* Else block task */
else
{
vd_OSsema_blockTask(semaphore); /* Add task to resource blocked list */
/* Tell scheduler the reason for task block state,
set sleep timer and change task state */
vd_OSsch_setReasonForSleep(semaphore, (U1)SCH_TASK_SLEEP_RESOURCE_SEMA, blockPeriod);
OS_SCH_EXIT_CRITICAL();
/* Check again after task wakes up */
OS_SCH_ENTER_CRITICAL();
if(semaphore->sema) /* If available */
{
--(semaphore->sema);
u1_t_returnSts = (U1)SEMA_SEMAPHORE_SUCCESS;
}
OS_SCH_EXIT_CRITICAL();
}
}
else /* Semaphore is available */
{
--(semaphore->sema);
OS_SCH_EXIT_CRITICAL();
u1_t_returnSts = (U1)SEMA_SEMAPHORE_SUCCESS;
}
return (u1_t_returnSts);
}
/*************************************************************************/
/* Function Name: u1_OSsema_check */
/* Purpose: Check status of semaphore. */
/* Arguments: OSSemaphore* semaphore: */
/* Pointer to semaphore. */
/* Return: U1 SEMA_SEMAPHORE_TAKEN OR */
/* SEMA_SEMAPHORE_SUCCESS */
/*************************************************************************/
U1 u1_OSsema_check(OSSemaphore* semaphore)
{
U1 u1_t_sts;
OS_SCH_ENTER_CRITICAL();
switch (semaphore->sema)
{
case SEMA_SEMAPHORE_TAKEN:
u1_t_sts = (U1)SEMA_SEMAPHORE_TAKEN;
break;
default:
u1_t_sts = (U1)SEMA_SEMAPHORE_SUCCESS;
break;
}
OS_SCH_EXIT_CRITICAL();
return (u1_t_sts);
}
/*************************************************************************/
/* Function Name: vd_OSsema_post */
/* Purpose: Release semaphore */
/* Arguments: OSSemaphore* semaphore: */
/* Pointer to semaphore. */
/* Return: N/A */
/*************************************************************************/
void vd_OSsema_post(OSSemaphore* semaphore)
{
OS_SCH_ENTER_CRITICAL();
++(semaphore->sema);
/* If blocked list is not empty */
if(semaphore->blockedListHead != SEMA_NULL_PTR)
{
vd_OSsema_unblockTask(semaphore);
}
else{}
OS_SCH_EXIT_CRITICAL();
}
/*************************************************************************/
/* Function Name: vd_OSsema_blockedTimeout */
/* Purpose: API for scheduler to call when sleeping task times out*/
/* Arguments: OSSemaphore* semaphore: */
/* Pointer to semaphore. */
/* Sch_Task* taskTCB: */
/* Pointer to TCB of blocked task. */
/* Return: N/A */
/*************************************************************************/
void vd_OSsema_blockedTimeout(OSSemaphore* semaphore, struct Sch_Task* taskTCB)
{
ListNode* node_t_tempPtr;
OS_SCH_ENTER_CRITICAL();
/* Remove node from block list and clear its contents */
node_t_tempPtr = node_list_removeNodeByTCB(&(semaphore->blockedListHead), taskTCB);
node_t_tempPtr->TCB = SEMA_NULL_PTR;
OS_SCH_EXIT_CRITICAL();
}
/*************************************************************************/
/* Function Name: vd_OSsema_blockTask */
/* Purpose: Add task to blocked list of semaphore. */
/* Arguments: OSSemaphore* semaphore: */
/* Pointer to semaphore. */
/* Return: N/A */
/*************************************************************************/
static void vd_OSsema_blockTask(OSSemaphore* semaphore)
{
U1 u1_t_index;
u1_t_index = (U1)ZERO;
/* Find available node to store data */
while((semaphore->blockedTasks[u1_t_index].TCB != SEMA_NULL_PTR) && (u1_t_index < (U1)SEMA_MAX_NUM_BLOCKED))
{
++u1_t_index;
}
/* If node found, then store TCB pointer and add to blocked list */
if(u1_t_index < (U1)SEMA_MAX_NUM_BLOCKED)
{
(semaphore->blockedTasks[u1_t_index].TCB) = SCH_CURRENT_TCB_ADDR;
vd_list_addTaskByPrio(&(semaphore->blockedListHead), &(semaphore->blockedTasks[u1_t_index]));
}
}
/*************************************************************************/
/* Function Name: vd_OSsema_unblockTask */
/* Purpose: Wake up tasks blocked on semaphore. */
/* Arguments: OSSemaphore* semaphore: */
/* Pointer to semaphore. */
/* Return: N/A */
/*************************************************************************/
static void vd_OSsema_unblockTask(OSSemaphore* semaphore)
{
ListNode* node_t_p_highPrioTask;
/* Remove highest priority task */
node_t_p_highPrioTask = node_list_removeFirstNode(&(semaphore->blockedListHead));
/* Notify scheduler the reason that task is going to be woken. */
vd_OSsch_setReasonForWakeup((U1)SCH_TASK_WAKEUP_SEMA_READY, node_t_p_highPrioTask->TCB);
/* Notify scheduler to change task state. If woken task is higher priority than running task, context switch will occur after critical section. */
vd_OSsch_taskWake(node_t_p_highPrioTask->TCB->taskID);
/* Clear TCB pointer. This frees this node for future use. */
node_t_p_highPrioTask->TCB = SEMA_NULL_PTR;
}
#endif /* Conditional compile */
/***********************************************************************************************/
/* History */
/***********************************************************************************************/
/* Version Date Description */
/* */
/* 0.1 3/24/19 Module implemented */
/* */
/* 0.2 5/24/19 Added API for scheduler to use when blocked task times out. */
/* */
/* 1.0 7/26/19 Block list structure changed to utilize list module. */
/* */
|
gscultho/HuskEOS | huskEOS/Queue/Source/queue.c | /*************************************************************************/
/* File Name: queue.c */
/* Purpose: FIFO services for application layer tasks. */
/* Created by: <NAME> on 3/20/19. */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
/* If multiple dequeue tasks are blocked, when data is put into the queue
the task with the highest priority shall receive the data. */
#include "rtos_cfg.h"
#if(RTOS_CFG_OS_QUEUE_ENABLED == RTOS_CONFIG_TRUE)
/*************************************************************************/
/* Includes */
/*************************************************************************/
#include "listMgr_internal.h"
#include "queue_internal_IF.h"
#include "queue.h"
#include "sch_internal_IF.h"
#include "sch.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define QUEUE_MAX_NUM_BLOCKED_TASKS (RTOS_CFG_MAX_NUM_BLOCKED_TASKS_FIFO)
#define QUEUE_GET_PTR_START_INDEX (0)
#define QUEUE_PUT_PTR_START_INDEX (1)
#define QUEUE_BLOCK_PERIOD_NO_BLOCK (0)
#define QUEUE_NULL_PTR ((void*)0)
/*************************************************************************/
/* Global Variables, Constants */
/*************************************************************************/
static Queue queue_queueList[FIFO_MAX_NUM_QUEUES];
/*************************************************************************/
/* Private Function Prototypes */
/*************************************************************************/
static void vd_OSqueue_addTaskToBlocked(U1 queueNum);
static void vd_queue_unblockWaitingTasks(U1 queueNum);
static U1 u1_queue_checkValidFIFO(U1 queueNum);
/*************************************************************************/
/*************************************************************************/
/* Function Name: u1_OSqueue_init */
/* Purpose: Initialize FIFO and provide ID number. */
/* Arguments: Q_MEM* queueStart: */
/* Pointer to first address allocated for queue. */
/* U4 queueLength: */
/* Length of queue. Number of Q_MEM entries. */
/* Return: U1: FIFO_FAILURE OR */
/* queue ID number. */
/*************************************************************************/
U1 u1_OSqueue_init(Q_MEM* queueStart, U4 queueLength)
{
U1 u1_t_index;
U1 u1_t_return;
static U1 u1_s_numQueuesAllocated = (U1)ZERO;
/* Check that there is available overhead for new queue. */
if(u1_s_numQueuesAllocated < (U1)FIFO_MAX_NUM_QUEUES)
{
/* Return queue ID number. */
u1_t_return = u1_s_numQueuesAllocated;
OS_SCH_ENTER_CRITICAL();
queue_queueList[u1_s_numQueuesAllocated].startPtr = queueStart;
queue_queueList[u1_s_numQueuesAllocated].endPtr = queueStart + queueLength - (U1)ONE;
queue_queueList[u1_s_numQueuesAllocated].getPtr = &queue_queueList[u1_s_numQueuesAllocated].startPtr[QUEUE_GET_PTR_START_INDEX]; /* Offset 0 from start. */
queue_queueList[u1_s_numQueuesAllocated].putPtr = &queue_queueList[u1_s_numQueuesAllocated].startPtr[QUEUE_PUT_PTR_START_INDEX]; /* Offset 1 from start. */
queue_queueList[u1_s_numQueuesAllocated].blockedTaskList.blockedListHead = QUEUE_NULL_PTR;
for(u1_t_index = (U1)ZERO; u1_t_index < (U1)RTOS_CFG_MAX_NUM_BLOCKED_TASKS_FIFO; u1_t_index++)
{
queue_queueList[u1_s_numQueuesAllocated].blockedTaskList.blockedTasks[u1_t_index].nextNode = QUEUE_NULL_PTR;
queue_queueList[u1_s_numQueuesAllocated].blockedTaskList.blockedTasks[u1_t_index].previousNode = QUEUE_NULL_PTR;
queue_queueList[u1_s_numQueuesAllocated].blockedTaskList.blockedTasks[u1_t_index].TCB = QUEUE_NULL_PTR;
}
++u1_s_numQueuesAllocated;
OS_SCH_EXIT_CRITICAL();
}
else
{
u1_t_return = (U1)FIFO_FAILURE;
}
return (u1_t_return);
}
/*************************************************************************/
/* Function Name: u1_OSqueue_flushFifo */
/* Purpose: Clear all values in a queue. */
/* Arguments: U1 u1_queueNum: */
/* ID of queue to be flushed. */
/* U1* error: */
/* Address to write error to. */
/* Return: FIFO_SUCCESS OR */
/* FIFO_FAILURE */
/*************************************************************************/
U1 u1_OSqueue_flushFifo(U1 queueNum, U1* error)
{
U1 u1_t_return;
*error = u1_queue_checkValidFIFO(queueNum);
if(*error)
{
u1_t_return = (U1)FIFO_FAILURE;
}
else
{
OS_SCH_ENTER_CRITICAL();
queue_queueList[queueNum].getPtr = &queue_queueList[queueNum].startPtr[QUEUE_GET_PTR_START_INDEX]; /* Offset 0 from start. */
queue_queueList[queueNum].putPtr = &queue_queueList[queueNum].startPtr[QUEUE_PUT_PTR_START_INDEX]; /* Offset 1 from start. */
/* Wake all blocked tasks. */
while(queue_queueList[queueNum].blockedTaskList.blockedListHead != QUEUE_NULL_PTR)
{
vd_queue_unblockWaitingTasks(queueNum);
}
OS_SCH_EXIT_CRITICAL();
u1_t_return = (U1)FIFO_SUCCESS;
}
return (u1_t_return);
}
/*************************************************************************/
/* Function Name: data_OSqueue_get */
/* Purpose: Get data from queue. If higher priority task is */
/* waiting to send data, it will preempt this task. */
/* Arguments: U1 queueNum: */
/* Queue index being referenced. */
/* U4 blockPeriod: */
/* Sleep timeout period if task is blocked. */
/* U1* error: */
/* Address to write error to. */
/* Return: Q_MEM FIFO_FAILURE OR */
/* Q_MEM_t_data */
/*************************************************************************/
Q_MEM data_OSqueue_get(U1 queueNum, U4 blockPeriod, U1* error)
{
Q_MEM* data_t_p_nextGetPtr;
Q_MEM data_t_return;
*error = u1_queue_checkValidFIFO(queueNum);
if(*error)
{
data_t_return = (Q_MEM)FIFO_FAILURE;
}
else
{
OS_SCH_ENTER_CRITICAL();
/* Check space ahead of getPtr */
if(queue_queueList[queueNum].getPtr == queue_queueList[queueNum].endPtr)
{
data_t_p_nextGetPtr = queue_queueList[queueNum].startPtr;
}
else
{
data_t_p_nextGetPtr = queue_queueList[queueNum].getPtr + ONE;
}
/* If queue is empty */
if(data_t_p_nextGetPtr == queue_queueList[queueNum].putPtr)
{
*error = (U1)FIFO_ERR_QUEUE_EMPTY;
/* Block task if blocking enabled */
if(blockPeriod != (U4)QUEUE_BLOCK_PERIOD_NO_BLOCK)
{
vd_OSqueue_addTaskToBlocked(queueNum);
vd_OSsch_setReasonForSleep(&queue_queueList[queueNum], (U1)SCH_TASK_SLEEP_RESOURCE_QUEUE, blockPeriod);
/* Let task enter sleep state. */
OS_SCH_EXIT_CRITICAL();
/* When task wakes back up, check again. */
OS_SCH_ENTER_CRITICAL();
/* If queue is no longer empty. */
if(data_t_p_nextGetPtr != queue_queueList[queueNum].putPtr)
{
*error = (Q_MEM)FIFO_ERR_NO_ERROR;
/* Move pointer */
queue_queueList[queueNum].getPtr = data_t_p_nextGetPtr;
/* Dequeue and clear entry */
data_t_return = *(queue_queueList[queueNum].getPtr);
*(queue_queueList[queueNum].getPtr) = (U1)ZERO;
/* Unblock highest priority task that is blocked. */
if(queue_queueList[queueNum].blockedTaskList.blockedListHead != QUEUE_NULL_PTR)
{
vd_queue_unblockWaitingTasks(queueNum);
}
else
{
}
}
else
{
/* Don't block since task was already blocked. */
data_t_return = (Q_MEM)FIFO_FAILURE;
}
}
else
{
/* Non-blocking. Return to task */
data_t_return = (Q_MEM)FIFO_FAILURE;
}/* blockPeriod != (U4)QUEUE_BLOCK_PERIOD_NO_BLOCK */
}
else
{
/* Else move pointer */
queue_queueList[queueNum].getPtr = data_t_p_nextGetPtr;
/* Dequeue and clear entry */
data_t_return = *(queue_queueList[queueNum].getPtr);
*(queue_queueList[queueNum].getPtr) = (U1)ZERO;
/* Unblock highest priority task that is blocked. */
if(queue_queueList[queueNum].blockedTaskList.blockedListHead != QUEUE_NULL_PTR)
{
vd_queue_unblockWaitingTasks(queueNum);
}
else
{
}
}/* data_t_p_nextGetPtr == queue_queueList[queueNum].putPtr */
OS_SCH_EXIT_CRITICAL();
}/* if(*error) */
return (data_t_return);
}
/*************************************************************************/
/* Function Name: u1_OSqueue_getSts */
/* Purpose: Check if queue is ready, full, or empty. */
/* Arguments: U1 queueNum: */
/* Queue index being referenced. */
/* U1* error: */
/* Address to write error to. */
/* Return: U1 FIFO_STS_QUEUE_FULL OR */
/* FIFO_FAILURE OR */
/* FIFO_STS_QUEUE_EMPTY OR */
/* FIFO_STS_QUEUE_READY */
/*************************************************************************/
U1 u1_OSqueue_getSts(U1 queueNum, U1* error)
{
U1 u1_t_sts;
Q_MEM* Q_MEM_t_p_nextGetPtr;
*error = u1_queue_checkValidFIFO(queueNum);
if(*error)
{
u1_t_sts = (U1)FIFO_FAILURE;
}
else
{
OS_CPU_ENTER_CRITICAL();
/* Check space ahead of getPtr */
if(queue_queueList[queueNum].getPtr == queue_queueList[queueNum].endPtr)
{
Q_MEM_t_p_nextGetPtr = queue_queueList[queueNum].startPtr;
}
else
{
Q_MEM_t_p_nextGetPtr = queue_queueList[queueNum].getPtr + ONE;
}
/* Get status */
if(Q_MEM_t_p_nextGetPtr == queue_queueList[queueNum].putPtr)
{
u1_t_sts = (U1)FIFO_STS_QUEUE_EMPTY;
}
else if(queue_queueList[queueNum].putPtr == (queue_queueList[queueNum].getPtr))
{
u1_t_sts = (U1)FIFO_STS_QUEUE_FULL;
}
else
{
u1_t_sts = (U1)FIFO_STS_QUEUE_READY;
}
OS_CPU_EXIT_CRITICAL();
}
return (u1_t_sts);
}
/*************************************************************************/
/* Function Name: u1_OSqueue_put */
/* Purpose: Put data in queue if not full. */
/* Arguments: U1 queueNum: */
/* Queue index being referenced. */
/* U4 blockPeriod: */
/* Sleep timeout period if task is blocked. */
/* U4 message: */
/* Data to be added to queue. */
/* U1* error: */
/* Address to write error to. */
/* Return: U1 FIFO_QUEUE_FULL OR */
/* FIFO_QUEUE_PUT_SUCCESS */
/*************************************************************************/
U1 u1_OSqueue_put(U1 queueNum, U4 blockPeriod, Q_MEM message, U1* error)
{
U1 u1_t_return;
*error = u1_queue_checkValidFIFO(queueNum);
if(*error)
{
u1_t_return = (U1)FIFO_FAILURE;
}
else
{
OS_SCH_ENTER_CRITICAL();
/* If queue is full */
if(queue_queueList[queueNum].putPtr == (queue_queueList[queueNum].getPtr))
{
*error = (U1)FIFO_ERR_QUEUE_FULL;
/* Block if blocking is enabled */
if(blockPeriod != (U4)QUEUE_BLOCK_PERIOD_NO_BLOCK)
{
vd_OSqueue_addTaskToBlocked(queueNum);
vd_OSsch_setReasonForSleep(&queue_queueList[queueNum], (U1)SCH_TASK_SLEEP_RESOURCE_QUEUE, blockPeriod);
/* Let task enter sleep state. */
OS_SCH_EXIT_CRITICAL();
/* Check if queue is full after task wakes up. */
OS_SCH_ENTER_CRITICAL();
if(queue_queueList[queueNum].putPtr != (queue_queueList[queueNum].getPtr)) /* Spot is available. */
{
*error = (Q_MEM)FIFO_ERR_NO_ERROR;
/* Puts data in queue */
*(queue_queueList[queueNum].putPtr) = message;
/* Shift pointer */
if(queue_queueList[queueNum].putPtr == queue_queueList[queueNum].endPtr)
{
queue_queueList[queueNum].putPtr = queue_queueList[queueNum].startPtr;
}
else
{
++queue_queueList[queueNum].putPtr;
}
/* Check if tasks need to be woken */
if(queue_queueList[queueNum].blockedTaskList.blockedListHead != QUEUE_NULL_PTR)
{
vd_queue_unblockWaitingTasks(queueNum);
}
u1_t_return = (Q_MEM)FIFO_SUCCESS;
}
else
{
/* Don't block again since this is the second check. */
u1_t_return = (U1)FIFO_FAILURE;
}/* queue_queueList[queueNum].putPtr != (queue_queueList[queueNum].getPtr) */
}
else
{
/* API call is non-blocking, don't block. */
u1_t_return = (U1)FIFO_FAILURE;
} /* queue_queueList[queueNum].putPtr != (queue_queueList[queueNum].getPtr) */
}
else
{
u1_t_return = (U1)FIFO_QUEUE_PUT_SUCCESS;
/* Puts data in queue */
*(queue_queueList[queueNum].putPtr) = message;
/* Shift pointer */
if(queue_queueList[queueNum].putPtr == queue_queueList[queueNum].endPtr)
{
queue_queueList[queueNum].putPtr = queue_queueList[queueNum].startPtr;
}
else
{
++queue_queueList[queueNum].putPtr;
}
/* Check if tasks need to be woken */
if(queue_queueList[queueNum].blockedTaskList.blockedListHead != QUEUE_NULL_PTR)
{
vd_queue_unblockWaitingTasks(queueNum);
}
}/* queue_queueList[queueNum].putPtr == (queue_queueList[queueNum].getPtr) */
OS_SCH_EXIT_CRITICAL();
}/* if(*error) */
return (u1_t_return);
}
/*************************************************************************/
/* Function Name: u4_OSqueue_getNumInFIFO */
/* Purpose: Return number of items in buffer. */
/* Arguments: U1 queueNum: */
/* Queue index being referenced. */
/* U1* error: */
/* Address to write error to. */
/* Return: U4 u4_t_count: */
/* FIFO_FAILURE OR */
/* Number of entries in queue */
/*************************************************************************/
U4 u4_OSqueue_getNumInFIFO(U1 queueNum, U1* error)
{
U4 u4_t_count;
*error = u1_queue_checkValidFIFO(queueNum);
if(*error)
{
u4_t_count = (U4)FIFO_FAILURE;
}
else
{
OS_SCH_ENTER_CRITICAL();
if(queue_queueList[queueNum].putPtr > queue_queueList[queueNum].getPtr)
{
u4_t_count = queue_queueList[queueNum].putPtr - queue_queueList[queueNum].getPtr;
}
else
{
u4_t_count = (queue_queueList[queueNum].putPtr - queue_queueList[queueNum].startPtr) + (queue_queueList[queueNum].endPtr - queue_queueList[queueNum].getPtr);
}
OS_SCH_EXIT_CRITICAL();
}
return (u4_t_count);
}
/*************************************************************************/
/* Function Name: vd_OSqueue_blockedTaskTimeout */
/* Purpose: Update block list if a task times out on its block. */
/* Called internally by scheduler. */
/* Arguments: Queue* queueAddr */
/* Address of queue structure. */
/* Sch_Task* taskTCB: */
/* TCB address of blocked task. */
/* Return: N/A */
/*************************************************************************/
void vd_OSqueue_blockedTaskTimeout(Queue* queueAddr, struct Sch_Task* taskTCB)
{
ListNode* node_t_tempPtr;
OS_SCH_ENTER_CRITICAL();
/* Remove node from block list and clear its contents */
node_t_tempPtr = node_list_removeNodeByTCB((&(queueAddr)->blockedTaskList.blockedListHead), taskTCB);
node_t_tempPtr->TCB = QUEUE_NULL_PTR;
OS_SCH_EXIT_CRITICAL();
}
/*************************************************************************/
/* Function Name: u1_queue_checkValidFIFO */
/* Purpose: Return if queue index is valid or invalid. */
/* Arguments: U1 queueNum: */
/* Queue index being referenced. */
/* Return: FIFO_ERR_QUEUE_OUT_OF_RANGE OR */
/* QUEUE_NUM_VALID */
/*************************************************************************/
static U1 u1_queue_checkValidFIFO(U1 queueNum)
{
/* unsigned, check only equal to or above max */
if(queueNum >= (U1)FIFO_MAX_NUM_QUEUES)
{
return ((U1)FIFO_ERR_QUEUE_OUT_OF_RANGE);
}
return((U1)FIFO_ERR_NO_ERROR);
}
/*************************************************************************/
/* Function Name: vd_OSqueue_addTaskToBlocked */
/* Purpose: Add task to block list. */
/* Arguments: U1 queueNum: */
/* Queue index being referenced. */
/* Return: void */
/*************************************************************************/
static void vd_OSqueue_addTaskToBlocked(U1 queueNum)
{
U1 u1_t_index;
u1_t_index = (U1)ZERO;
/* Find available node to store data */
while((queue_queueList[queueNum].blockedTaskList.blockedTasks[u1_t_index].TCB != QUEUE_NULL_PTR) && (u1_t_index < (U1)QUEUE_MAX_NUM_BLOCKED_TASKS))
{
++u1_t_index;
}
/* If node found, then store TCB pointer and add to blocked list */
if(u1_t_index < (U1)QUEUE_MAX_NUM_BLOCKED_TASKS)
{
queue_queueList[queueNum].blockedTaskList.blockedTasks[u1_t_index].TCB = SCH_CURRENT_TCB_ADDR;
vd_list_addTaskByPrio(&(queue_queueList[queueNum].blockedTaskList.blockedListHead), &(queue_queueList[queueNum].blockedTaskList.blockedTasks[u1_t_index]));
}
}
/*************************************************************************/
/* Function Name: vd_queue_unblockWaitingTasks */
/* Purpose: Remove highest priority task from blocked list & wake.*/
/* Arguments: U1 queueNum: */
/* Queue index being referenced. */
/* Return: void */
/*************************************************************************/
static void vd_queue_unblockWaitingTasks(U1 queueNum)
{
ListNode* node_t_p_highPrioTask;
/* If blocked list is not empty */
/* Remove highest priority task */
node_t_p_highPrioTask = node_list_removeFirstNode(&(queue_queueList[queueNum].blockedTaskList.blockedListHead));
/* Notify scheduler the reason that task is going to be woken. */
vd_OSsch_setReasonForWakeup((U1)SCH_TASK_WAKEUP_QUEUE_READY, node_t_p_highPrioTask->TCB);
/* Notify scheduler to change task state. If woken task is higher priority than running task, context switch will occur after critical section. */
vd_OSsch_taskWake(node_t_p_highPrioTask->TCB->taskID);
/* Clear TCB pointer. This frees this node for future use. */
node_t_p_highPrioTask->TCB = QUEUE_NULL_PTR;
}
#endif /* Conditional compile */
/***********************************************************************************************/
/* History */
/***********************************************************************************************/
/* Version Date Description */
/* */
/* 0.1 3/25/19 First implementation of module. */
/* */
/* 1.0 8/5/19 Rewrite to support better flow and blocked task handling. */
/* */
/* 1.1 8/14/19 Some bug fixes. Data being overwritten. */
/* */
/* 1.2 5/12/20 u1_OSqueue_flushFifo() will no longer reset queue entries to */
/* zero as this is unnecessary. */
|
gscultho/HuskEOS | huskEOS/Mailbox/Source/mailbox.c | <filename>huskEOS/Mailbox/Source/mailbox.c<gh_stars>1-10
/*************************************************************************/
/* File Name: mailbox.c */
/* Purpose: Mailbox services for application layer tasks. */
/* Created by: <NAME> on 3/3/19. */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
/* Each created mailbox is to be used between only two tasks
due to the fact that each mailbox structure only has allocated space
for storing one blocked task at a time. Queues should be used for multiple
senders/receivers. */
#include "rtos_cfg.h"
#if(RTOS_CFG_OS_MAILBOX_ENABLED == RTOS_CONFIG_TRUE)
/*************************************************************************/
/* Includes */
/*************************************************************************/
#include "mbox_internal_IF.h"
#include "mailbox.h"
#include "listMgr_internal.h"
#include "sch_internal_IF.h"
#include "sch.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define MBOX_BLOCK_PERIOD_NO_BLOCK (0)
#define MBOX_MAILBOX_EMPTY (0)
#define MBOX_MAILBOX_NUM_VALID (0)
#define MBOX_NO_BLOCKED_TASK (0)
/*************************************************************************/
/* Global Variables, Constants */
/*************************************************************************/
static Mailbox Mbox_MailboxList[MBOX_MAX_NUM_MAILBOX];
/*************************************************************************/
/* Private Function Prototypes */
/*************************************************************************/
static void vd_OSmbox_unblockWaitingTask(U1 mailboxID);
static void vd_OSmbox_blockHandler(U4 blockPeriod, U1 mailboxID);
static U1 u1_OSmbox_checkValidMailbox(U1 mailbox);
/*************************************************************************/
/*************************************************************************/
/* Function Name: vd_OSmbox_init */
/* Purpose: Initialize mailbox module. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
void vd_OSmbox_init(void)
{
U1 u1_t_index;
for(u1_t_index = (U1)ZERO; u1_t_index < (U1)MBOX_MAX_NUM_MAILBOX; u1_t_index++)
{
Mbox_MailboxList[u1_t_index].mail = (MAIL)MBOX_MAILBOX_EMPTY;
Mbox_MailboxList[u1_t_index].blockedTaskID = (U1)MBOX_NO_BLOCKED_TASK;
}
}
/*************************************************************************/
/* Function Name: mail_OSmbox_getMail */
/* Purpose: Get data from specified mailbox. */
/* Arguments: U1 mailbox: */
/* Mailbox identifier. */
/* U4 blockPeriod: */
/* Number of time units for task to sleep if blocked*/
/* U1* errorCode: */
/* Address to write error to. */
/* Return: MAIL MBOX_FAILURE OR */
/* data held in mailbox. */
/*************************************************************************/
MAIL mail_OSmbox_getMail(U1 mailbox, U4 blockPeriod, U1* errorCode)
{
MAIL mail_t_data;
*errorCode = u1_OSmbox_checkValidMailbox(mailbox);
if(*errorCode)
{
mail_t_data = (U1)MBOX_FAILURE;
}
else
{
OS_SCH_ENTER_CRITICAL();
mail_t_data = Mbox_MailboxList[mailbox].mail;
/* Check if mailbox has data ready */
if(mail_t_data != (MAIL)MBOX_MAILBOX_EMPTY)
{
if(Mbox_MailboxList[mailbox].blockedTaskID != (U1)MBOX_NO_BLOCKED_TASK)
{
vd_OSmbox_unblockWaitingTask(mailbox);
}
else
{
}
/* Reset mailbox */
Mbox_MailboxList[mailbox].mail = (MAIL)MBOX_MAILBOX_EMPTY;
}
/* If not, block */
else
{
*errorCode = (U1)MBOX_ERR_MAILBOX_EMPTY;
/* If block period is non-zero, then block task */
if(blockPeriod != (U1)MBOX_BLOCK_PERIOD_NO_BLOCK)
{
vd_OSmbox_blockHandler(blockPeriod, mailbox);
/* Let task go to sleep. */
OS_SCH_EXIT_CRITICAL();
/* When it wakes, check again for mail. There is no blocked task since this was the blocked task. */
OS_SCH_ENTER_CRITICAL();
mail_t_data = Mbox_MailboxList[mailbox].mail;
/* Check if mailbox has data ready */
if(mail_t_data != (MAIL)MBOX_MAILBOX_EMPTY)
{
/* Reset mailbox */
Mbox_MailboxList[mailbox].mail = (MAIL)MBOX_MAILBOX_EMPTY;
*errorCode = (U1)MBOX_NO_ERROR;
}
else
{
/* Non-blocking call, return immediately. */
}
}
}/* mail_t_data != (MAIL)MBOX_MAILBOX_EMPTY */
OS_SCH_EXIT_CRITICAL();
}/* if *errorCode */
return (mail_t_data);
}
/*************************************************************************/
/* Function Name: mail_OSmbox_checkMail */
/* Purpose: Check for data but do not clear it. */
/* Arguments: U1 mailbox: */
/* Mailbox identifier. */
/* U1* errorCode: */
/* Address to write error to. */
/* Return: MAIL: MBOX_FAILURE if invalid or empty OR */
/* data held in mailbox. */
/*************************************************************************/
MAIL mail_OSmbox_checkMail(U1 mailbox, U1* errorCode)
{
MAIL mail_t_data;
*errorCode = u1_OSmbox_checkValidMailbox(mailbox);
if(*errorCode)
{
mail_t_data = (U1)MBOX_FAILURE;
}
else
{
OS_CPU_ENTER_CRITICAL();
if(Mbox_MailboxList[mailbox].mail != (U1)MBOX_MAILBOX_EMPTY)
{
mail_t_data = Mbox_MailboxList[mailbox].mail;
}
else
{
*errorCode = (U1)MBOX_ERR_MAILBOX_EMPTY;
mail_t_data = (U1)MBOX_FAILURE;
}
OS_CPU_EXIT_CRITICAL();
}
return (mail_t_data);
}
/*************************************************************************/
/* Function Name: u1_OSmbox_sendMail */
/* Purpose: Send data to mailbox. */
/* Arguments: U1 mailbox: */
/* Mailbox identifier. */
/* U4 blockPeriod: */
/* Number of time units for task to sleep if blocked.*/
/* MAIL data: */
/* Data to be dropped. */
/* U1* errorCode: */
/* Address to write error to. */
/* */
/* Return: U1 MBOX_SUCCESS OR */
/* MBOX_FAILURE */
/*************************************************************************/
U1 u1_OSmbox_sendMail(U1 mailbox, U4 blockPeriod, MAIL data, U1* errorCode)
{
U1 u1_t_return;
*errorCode = u1_OSmbox_checkValidMailbox(mailbox);
if(*errorCode)
{
u1_t_return = (U1)MBOX_FAILURE;
}
else
{
OS_CPU_ENTER_CRITICAL();
/* Check if mailbox has no data in it */
if((Mbox_MailboxList[mailbox].mail) == (U4)MBOX_MAILBOX_EMPTY)
{
Mbox_MailboxList[mailbox].mail = data;
/* Check if blocked tasks need to be unblocked */
if((Mbox_MailboxList[mailbox].blockedTaskID) != (U1)MBOX_NO_BLOCKED_TASK)
{
vd_OSmbox_unblockWaitingTask(mailbox);
}
else
{
/* No task waiting. */
}
u1_t_return = (U1)MBOX_SUCCESS;
}
/* Mailbox full, check if task needs to be blocked */
else
{
*errorCode = (U1)MBOX_ERR_MAILBOX_FULL;
/* If block period is non-zero, then block task */
if(blockPeriod != (U1)MBOX_BLOCK_PERIOD_NO_BLOCK)
{
vd_OSmbox_blockHandler(blockPeriod, mailbox);
/* Let task sleep. */
OS_CPU_EXIT_CRITICAL();
/* Task wakes up here. Check again if mailbox is available. */
OS_CPU_ENTER_CRITICAL();
if((Mbox_MailboxList[mailbox].mail) == (U4)MBOX_MAILBOX_EMPTY)
{
Mbox_MailboxList[mailbox].mail = data;
*errorCode = (U1)MBOX_NO_ERROR;
u1_t_return = (U1)MBOX_SUCCESS;
}
else
{
/* Don't block task since task woke from block timeout. */
u1_t_return = (U1)MBOX_FAILURE;
}
}
else
{
/* Not a blocking call. */
u1_t_return = (U1)MBOX_FAILURE;
}/* blockPeriod != (U1)MBOX_BLOCK_PERIOD_NO_BLOCK */
}/* (Mbox_MailboxList[mailbox].mail) == (U4)MBOX_MAILBOX_EMPTY */
OS_CPU_EXIT_CRITICAL();
}/* if(*errorCode) */
return ((U1)u1_t_return);
}
/*************************************************************************/
/* Function Name: vd_OSmbox_clearMailbox */
/* Purpose: Clear data and wake task if one is blocked. */
/* Arguments: U1 mailbox: */
/* Mailbox identifier. */
/* */
/* Return: N/A */
/*************************************************************************/
void vd_OSmbox_clearMailbox(U1 mailbox)
{
if(u1_OSmbox_checkValidMailbox(mailbox))
{
}
else
{
OS_CPU_ENTER_CRITICAL();
Mbox_MailboxList[mailbox].mail = (U4)MBOX_MAILBOX_EMPTY;
/* Check if there was a task waiting to send/receive data */
if((Mbox_MailboxList[mailbox].blockedTaskID) != (U1)MBOX_NO_BLOCKED_TASK)
{
vd_OSmbox_unblockWaitingTask(mailbox);
}
else
{
}
OS_CPU_EXIT_CRITICAL();
}
}
/*************************************************************************/
/* Function Name: vd_OSmbox_blockedTaskTimeout */
/* Purpose: Remove blocked task from specified mailbox. */
/* Arguments: void* mbox: */
/* Mailbox address. */
/* */
/* Return: N/A */
/*************************************************************************/
void vd_OSmbox_blockedTaskTimeout(void* mbox)
{
((Mailbox*)(mbox))->blockedTaskID = (U1)MBOX_NO_BLOCKED_TASK;
}
/*************************************************************************/
/* Function Name: u1_OSmbox_checkValidMailbox */
/* Purpose: Return if mailbox number is valid or not. */
/* Arguments: U1 mailbox: */
/* Mailbox identifier. */
/* */
/* Return: U1 MBOX_ERR_MAILBOX_OUT_OF_RANGE OR */
/* MBOX_MAILBOX_NUM_VALID */
/*************************************************************************/
static U1 u1_OSmbox_checkValidMailbox(U1 mailbox)
{
if(mailbox >= (U1)MBOX_MAX_NUM_MAILBOX)
{
return ((U1)MBOX_ERR_MAILBOX_OUT_OF_RANGE);
}
else{}
return ((U1)MBOX_MAILBOX_NUM_VALID);
}
/*************************************************************************/
/* Function Name: vd_OSmbox_blockHandler */
/* Purpose: Handle task blocking if mailbox not available. */
/* Arguments: U4 blockPeriod: */
/* Period for task to sleep for. */
/* mailboxID: */
/* Mailbox identifier, */
/* CALL IN CRITICAL SECTION */
/* Return: N/A */
/*************************************************************************/
static void vd_OSmbox_blockHandler(U4 blockPeriod, U1 mailboxID)
{
/* Do not block if a task is already on block list, per mailbox usage requirement of one blocked task per mailbox. */
if(Mbox_MailboxList[mailboxID].blockedTaskID == (U1)MBOX_NO_BLOCKED_TASK)
{
Mbox_MailboxList[mailboxID].blockedTaskID = SCH_CURRENT_TASK_ID;
}
else
{
}
/* Set task to sleep state and notify scheduler of reason. */
vd_OSsch_setReasonForSleep(&Mbox_MailboxList[mailboxID], (U1)SCH_TASK_SLEEP_RESOURCE_MBOX, blockPeriod);
}
/*************************************************************************/
/* Function Name: vd_OSmbox_unblockWaitingTask */
/* Purpose: Remove task number (offset by one) from list and wake.*/
/* Arguments: U1 mailboxID: */
/* Mailbox identifier. */
/* Return: void */
/*************************************************************************/
static void vd_OSmbox_unblockWaitingTask(U1 mailboxID)
{
U1 u1_t_blockedTask;
u1_t_blockedTask = Mbox_MailboxList[mailboxID].blockedTaskID;
/* Notify scheduler of reason for task wakeup. */
vd_OSsch_setReasonForWakeup((U1)SCH_TASK_SLEEP_RESOURCE_MBOX, SCH_ID_TO_TCB(u1_t_blockedTask));
/* Notify scheduler to change task state. If woken task is higher priority than running task, context switch will occur after critical section. */
vd_OSsch_taskWake(u1_t_blockedTask);
Mbox_MailboxList[mailboxID].blockedTaskID = (U1)MBOX_NO_BLOCKED_TASK;
}
#endif /* Conditional compile */
/***********************************************************************************************/
/* History */
/***********************************************************************************************/
/* Version Date Description */
/* */
/* 0.1 3/4/19 Mailboxes with blocked task implemented. */
/* */
/* 1.0 8/3/19 Updated for better software flow and block handling. */
|
gscultho/HuskEOS | huskEOS/OS_CPU_Interface/Header/cpu_defs.h | /*************************************************************************/
/* File Name: cpu_defs.h */
/* Purpose: Definitions for OS hardware use. */
/* Created by: <NAME> on 2/10/2019. */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#ifndef cpu_defs_h
#define cpu_defs_h
/*************************************************************************/
/* Data Types */
/*************************************************************************/
typedef unsigned char U1;
typedef unsigned short U2;
typedef unsigned int U4;
typedef unsigned long U8;
typedef signed char S1;
typedef short S2;
typedef int S4;
typedef signed long S8;
/*************************************************************************/
/* Definitions */
/*************************************************************************/
/* CPU Information */
#define OS_UWORD U4
#define OS_SWORD S4
#define STACK_DESCENDING (0)
#define STACK_ASCENDING (1)
#define OS_STACK OS_UWORD
#define STACK_GROWTH (STACK_DESCENDING)
/* General */
#define TWO (2)
#define ONE (1)
#define ZERO (0)
#define TEN (10)
#define NULL (0)
#define MAX_VAL_4BYTE ((U4)0xFFFFFFFF)
/* Registers used by OS */
#define SYS_REG_ICSR_ADDR (*((volatile U4 *)0xE000ED04))
#define NVIC_ST_CTRL_R (*((volatile U4 *)0xE000E010))
#define NVIC_ST_RELOAD_R (*((volatile U4 *)0xE000E014))
#define NVIC_ST_CURRENT_R (*((volatile U4 *)0xE000E018))
#define NVIC_ST_CALIBRATE_R (*((volatile U4 *)0xE000E01C))
#define NVIC_ST_PRIORITY_R (*((volatile U1 *)0xE000ED23))
#define NVIC_PENDSV_PRIORITY_R (*((volatile U1 *)0xE000ED22))
/*************************************************************************/
/* Public Functions */
/*************************************************************************/
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
#endif
|
gscultho/HuskEOS | huskEOS/Mailbox/Header/mailbox.h | <reponame>gscultho/HuskEOS<gh_stars>1-10
/*************************************************************************/
/* File Name: mailbox.h */
/* Purpose: Header file for mailbox module. */
/* Created by: <NAME> on 3/3/19 */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#ifndef mailbox_h
#if(RTOS_CFG_OS_MAILBOX_ENABLED == RTOS_CONFIG_TRUE)
#define mailbox_h
#include "rtos_cfg.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define MBOX_MAX_NUM_MAILBOX (RTOS_CFG_NUM_MAILBOX)
#define MBOX_SUCCESS (1)
#define MBOX_FAILURE (0)
/* API error codes */
#define MBOX_NO_ERROR (0)
#define MBOX_ERR_MAILBOX_OUT_OF_RANGE (255)
#define MBOX_ERR_MAILBOX_FULL (1)
#define MBOX_ERR_MAILBOX_EMPTY (1)
#define MBOX_ERR_MAILBOX_IN_USE (2)
/*************************************************************************/
/* Data Types */
/*************************************************************************/
/*************************************************************************/
/* Public Functions */
/*************************************************************************/
/*************************************************************************/
/* Function Name: mail_OSmbox_getMail */
/* Purpose: Get data from specified mailbox. */
/* Arguments: U1 mailbox: */
/* Mailbox identifier. */
/* U4 blockPeriod: */
/* Number of time units for task to sleep if blocked*/
/* U1* errorCode: */
/* Address to write error to. */
/* Return: MAIL MBOX_FAILURE OR */
/* data held in mailbox. */
/*************************************************************************/
MAIL mail_OSmbox_getMail(U1 mailbox, U4 blockPeriod, U1* errorCode);
/*************************************************************************/
/* Function Name: mail_OSmbox_checkMail */
/* Purpose: Check for data but do not clear it. */
/* Arguments: U1 mailbox: */
/* Mailbox identifier. */
/* U1* errorCode: */
/* Address to write error to. */
/* Return: MAIL: MBOX_FAILURE if invalid or empty OR */
/* data held in mailbox. */
/*************************************************************************/
MAIL mail_OSmbox_checkMail(U1 mailbox, U1* errorCode);
/*************************************************************************/
/* Function Name: u1_OSmbox_sendMail */
/* Purpose: Send data to mailbox. */
/* Arguments: U1 mailbox: */
/* Mailbox identifier. */
/* U4 blockPeriod: */
/* Number of time units for task to sleep if blocked.*/
/* MAIL data: */
/* Data to be dropped. */
/* U1* errorCode: */
/* Address to write error to. */
/* */
/* Return: U1 MBOX_SUCCESS OR */
/* MBOX_FAILURE */
/*************************************************************************/
U1 u1_OSmbox_sendMail(U1 mailbox, U4 blockPeriod, MAIL data, U1* errorCode);
/*************************************************************************/
/* Function Name: vd_OSmbox_clearMailbox */
/* Purpose: Clear data and wake task if one is blocked. */
/* Arguments: U1 mailbox: */
/* Mailbox identifier. */
/* */
/* Return: N/A */
/*************************************************************************/
void vd_OSmbox_clearMailbox(U1 mailbox);
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
#else
#warning "MAILBOX MODULE NOT ENABLED"
#endif /* Conditional compile */
#endif
|
gscultho/HuskEOS | huskEOS/Semaphore/Header/semaphore_internal_IF.h | <reponame>gscultho/HuskEOS
/*************************************************************************/
/* File Name: semaphore_internal_IF.h */
/* Purpose: Kernel access definitions and routines for semaphore. */
/* Created by: <NAME> on 5/23/19 */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#ifndef semaphore_internal_IF_h
#define semaphore_internal_IF_h
#include "rtos_cfg.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define SEMA_MAX_NUM_BLOCKED (RTOS_CFG_NUM_BLOCKED_TASKS_SEMA)
/*************************************************************************/
/* Data Types */
/*************************************************************************/
struct listNode; /* Forward declaration. Defined in "listMgr_internal.h" */
typedef struct Semaphore
{
S1 sema;
struct ListNode blockedTasks[SEMA_MAX_NUM_BLOCKED];
struct ListNode* blockedListHead;
}
Semaphore;
/*************************************************************************/
/* Public Functions */
/*************************************************************************/
/*************************************************************************/
/* Function Name: vd_OSsema_blockedTimeout */
/* Purpose: API for scheduler to call when sleeping task times out*/
/* Arguments: OSSemaphore* semaphore: */
/* Pointer to semaphore. */
/* Sch_Task* taskTCB: */
/* Pointer to TCB of blocked task. */
/* Return: N/A */
/*************************************************************************/
void vd_OSsema_blockedTimeout(struct Semaphore* semaphore, struct Sch_Task* taskTCB);
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
#endif
|
gscultho/HuskEOS | huskEOS/Memory/Source/memory.c | <reponame>gscultho/HuskEOS
/*************************************************************************/
/* File Name: memory.c */
/* Purpose: Functions for user-controlled memory management. */
/* Created by: <NAME> on 7/13/19. */
/* Copyright � 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#include <rtos_cfg.h>
#if(RTOS_CFG_OS_MEM_ENABLED == RTOS_CONFIG_TRUE)
/*************************************************************************/
/* Includes */
/*************************************************************************/
#include <memory.h>
#include <memory_internal_IF.h>
#include <sch_internal_IF.h>
#include <sch.h>
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define MEM_WATERMARK_SIZE (2)
#define MEM_WATERMARK_VAL (0xF0)
/*************************************************************************/
/* Global Variables, Constants */
/*************************************************************************/
static OSMemPartition partitionList[MEM_MAX_NUM_PARTITIONS];
static U1 numPartitionsAllocated = 0; // the current number of partitions allocated. Cannot exceed RTOS_CFG_MAX_NUM_MEM_PARTITIONS.
static U1 largestBlockSize = 0; // Largest block size currently managed. Slight runtime improvement to store this variable.
/*************************************************************************/
/* Private Function Prototypes */
/*************************************************************************/
U1 u1_OSMem_findBlockSize(MEMTYPE* blockStart, U1* err);
/*************************************************************************/
/* Public Functions */
/*************************************************************************/
/*************************************************************************/
/* Function Name: u1_OSMem_PartitionInit */
/* Purpose: Add a memory partition to the memory manager. */
/* Arguments: MEMTYPE* partitionMatrix: */
/* Desired memory partition to allocate. */
/* U1 blockSize: */
/* Size of each block (number of matrix columns). */
/* U1 numBlocks: */
/* Number of matrix rows. */
/* U1* err: */
/* Error variable. Can be one of the following: */
/* MEM_ERR_INVALID_SIZE_REQUEST, or */
/* MEM_ERR_HIT_PARTITION_MAX, or */
/* MEM_NO_ERROR */
/* Return: U1 numPartitions - 1 */
/* Index of the newly allocated partition. */
/*************************************************************************/
U1 u1_OSMem_PartitionInit(MEMTYPE* partitionMatrix, U1 blockSize, U1 numBlocks, U1 *err)
{
U1 blockIndex = 0;
U1* tempBlockStart = NULL;
/* cant exceed the maximum block size or maximum number of blocks */
if(blockSize > MEM_MAX_BLOCK_SIZE ||
numBlocks > MEM_MAX_NUM_BLOCKS)
{
*err = MEM_ERR_INVALID_SIZE_REQUEST;
}
/* we have a valid partition, so add its information to the list */
else
{
OS_SCH_ENTER_CRITICAL();
/* can't exceed the maximum number of partitions, needs to be critical because of the global variable */
if(numPartitionsAllocated == MEM_MAX_NUM_PARTITIONS)
{
*err = MEM_ERR_HIT_PARTITION_MAX;
}
else
{
tempBlockStart = partitionMatrix; // capture the matrix start as a temp variable
partitionList[numPartitionsAllocated].start = partitionMatrix;
partitionList[numPartitionsAllocated].blockSize = blockSize;
partitionList[numPartitionsAllocated].numBlocks = numBlocks;
partitionList[numPartitionsAllocated].numActiveBlocks = 0;
/* loop over each row of the matrix, and create a new memory block, and assign default properties */
for(blockIndex = 0; blockIndex < numBlocks; blockIndex++)
{
partitionList[numPartitionsAllocated].blocks[blockIndex].blockSize = blockSize;
partitionList[numPartitionsAllocated].blocks[blockIndex].blockStatus = BLOCK_NOT_IN_USE;
partitionList[numPartitionsAllocated].blocks[blockIndex].start = tempBlockStart;
tempBlockStart += blockSize;
}
numPartitionsAllocated++; // increment the partition tracker to indicate we added a new partition
*err = MEM_NO_ERROR;
/* set the global largestBlockSize, slight runtime improvement later */
if(blockSize > largestBlockSize)
{
largestBlockSize = blockSize;
}
}
OS_SCH_EXIT_CRITICAL();
}
return (numPartitionsAllocated - 1); // return the index of the partition we just added
}
/*************************************************************************/
/* Function Name: data_OSMem_malloc */
/* Purpose: Find and return first available memory block. */
/* Arguments: U1 sizeRequested: */
/* Desired memory amount to allocate. */
/* U1* err: */
/* Error variable. Can be one of the following: */
/* MEM_ERR_INVALID_SIZE_REQUEST, or */
/* MEM_ERR_MALLOC_NO_BLOCKS_AVAIL, or */
/* MEM_NO_ERROR */
/* Return: MEMTYPE* Pointer to the allocated memory block, or */
/* NULL */
/*************************************************************************/
MEMTYPE* data_OSMem_malloc(U1 sizeRequested, U1* err)
{
U1 partitionIndex = 0;
U1 blockIndex = 0;
U1 byteIndex = 0;
/* check to see if the user requested more memory than possible */
if(sizeRequested > largestBlockSize)
{
*err = MEM_ERR_INVALID_SIZE_REQUEST;
return NULL;
}
/* loop over all partitions */
for(partitionIndex = 0; partitionIndex < numPartitionsAllocated; partitionIndex++)
{
/* size requested should be smaller than the block size minus the watermark size */
if(sizeRequested > partitionList[partitionIndex].blockSize - MEM_WATERMARK_SIZE)
{
continue;
}
/* otherwise, valid partition found, so check to see if there are available blocks */
else
{
OS_SCH_ENTER_CRITICAL();
/* if there are no open blocks in this partition, go to the next partition */
if(partitionList[partitionIndex].numActiveBlocks == partitionList[partitionIndex].numBlocks)
{
OS_SCH_EXIT_CRITICAL();
continue;
}
/* otherwise, loop for all blocks in this partition */
else
{
for(blockIndex = 0; blockIndex < partitionList[partitionIndex].numBlocks; blockIndex++)
{
/* if this block is not in use, it meets all the criteria, so return it */
if(partitionList[partitionIndex].blocks[blockIndex].blockStatus != BLOCK_IN_USE)
{
partitionList[partitionIndex].blocks[blockIndex].blockStatus = BLOCK_IN_USE;
/* assign all bytes to the watermark value (garbage) because this isn't calloc */
for(byteIndex = 0; byteIndex < partitionList[partitionIndex].blockSize; byteIndex++)
{
partitionList[partitionIndex].blocks[blockIndex].start[byteIndex] = MEM_WATERMARK_VAL;
}
partitionList[partitionIndex].numActiveBlocks++;
OS_SCH_EXIT_CRITICAL();
*err = MEM_NO_ERROR;
return partitionList[partitionIndex].blocks[blockIndex].start;
}
}
}
}
}
/* if we made it here, there are no blocks available for the given size */
*err = MEM_ERR_MALLOC_NO_BLOCKS_AVAIL;
return NULL;
}
/*************************************************************************/
/* Function Name: data_OSMem_calloc */
/* Purpose: Return first available memory block, filled with 0's. */
/* Arguments: U1 sizeRequested: */
/* Desired memory amount to allocate. */
/* U1* err: */
/* Error variable. Can be one of the following: */
/* MEM_ERR_INVALID_SIZE_REQUEST, or */
/* MEM_ERR_MALLOC_NO_BLOCKS_AVAIL, or */
/* MEM_NO_ERROR */
/* Return: U1* Pointer to the allocated memory block, or */
/* NULL */
/*************************************************************************/
MEMTYPE* data_OSMem_calloc(U1 sizeRequested, U1* err)
{
U1 partitionIndex = 0;
U1 blockIndex = 0;
U1 byteIndex = 0;
/* check to see if the user requested more memory than possible */
if(sizeRequested > largestBlockSize)
{
*err = MEM_ERR_INVALID_SIZE_REQUEST;
return NULL;
}
/* loop over all partitions */
for(partitionIndex = 0; partitionIndex < numPartitionsAllocated; partitionIndex++)
{
/* size requested should be smaller than the block size minus the watermark size */
if(sizeRequested > partitionList[partitionIndex].blockSize - MEM_WATERMARK_SIZE)
{
continue;
}
/* otherwise, valid partition found, so check to see if there are available blocks */
else
{
OS_SCH_ENTER_CRITICAL();
/* if there are no open blocks in this partition, go to the next partition */
if(partitionList[partitionIndex].numActiveBlocks == partitionList[partitionIndex].numBlocks)
{
OS_SCH_EXIT_CRITICAL();
continue;
}
/* loop for all blocks in this partition */
for(blockIndex = 0; blockIndex < partitionList[partitionIndex].numBlocks; blockIndex++)
{
/* if this block is not in use, it meets all the criteria, so return it */
if(partitionList[partitionIndex].blocks[blockIndex].blockStatus != BLOCK_IN_USE)
{
partitionList[partitionIndex].blocks[blockIndex].blockStatus = BLOCK_IN_USE;
/* assign the last two bytes to the watermark value, and the rest to zeroes */
for(byteIndex = 0; byteIndex < partitionList[partitionIndex].blockSize; byteIndex++)
{
if(byteIndex > partitionList[partitionIndex].blockSize - MEM_WATERMARK_SIZE)
{
partitionList[partitionIndex].blocks[blockIndex].start[byteIndex] = MEM_WATERMARK_VAL;
}
else
{
partitionList[partitionIndex].blocks[blockIndex].start[byteIndex] = 0;
}
}
partitionList[partitionIndex].numActiveBlocks++;
OS_SCH_EXIT_CRITICAL();
*err = MEM_NO_ERROR;
return partitionList[partitionIndex].blocks[blockIndex].start;
}
}
}
}
/* no blocks available for the given size */
*err = MEM_ERR_MALLOC_NO_BLOCKS_AVAIL;
return NULL;
}
/*************************************************************************/
/* Function Name: v_OSMem_free */
/* Purpose: Destroy the passed-in pointer and free the memblock. */
/* Arguments: MEMTYPE** memToFree: */
/* Pointer to the memory contained in the */
/* memblock. */
/* U1* err: */
/* Error variable. Can be one of the following: */
/* MEM_ERR_FREE_NOT_FOUND, or */
/* MEM_NO_ERROR */
/* Return: void */
/*************************************************************************/
void v_OSMem_free(MEMTYPE** memToFree, U1* err)
{
U1 foundMemoryBlock = 0;
U1 partitionIndex = 0;
U1 blockIndex = 0;
MEMTYPE* blockStart = NULL;
/* find the block currently in use by the heap */
for(partitionIndex = 0; partitionIndex < numPartitionsAllocated; partitionIndex++)
{
U1 numBlocks = partitionList[partitionIndex].numBlocks;
for(blockIndex = 0; blockIndex < numBlocks; blockIndex++)
{
blockStart = partitionList[partitionIndex].blocks[blockIndex].start;
/* compare the pointer address to see if they are te same */
if(*memToFree == blockStart)
{
OS_SCH_ENTER_CRITICAL();
partitionList[partitionIndex].blocks[blockIndex].blockStatus = BLOCK_NOT_IN_USE;
*memToFree = NULL; // terminate the existing pointer
*err = MEM_NO_ERROR;
foundMemoryBlock = 1;
OS_SCH_EXIT_CRITICAL();
break;
}
}
/* runtime improvement: dont consider other partitions after we already freed the pointer */
if(foundMemoryBlock == 1)
{
break;
}
}
/* set an error if we never found the passed-in pointer */
if(foundMemoryBlock == 0)
{
*err = MEM_ERR_FREE_NOT_FOUND;
}
}
/*************************************************************************/
/* Function Name: data_OSMem_realloc */
/* Purpose: Free the current block and re-allocate a new block. */
/* Arguments: MEMTYPE* oldPointer: */
/* Pointer to memory to reallocate. */
/* U1 newSize: */
/* Desired new size of the memblock. */
/* U1* err: */
/* Error variable. Can be one of the following: */
/* MEM_ERR_INVALID_SIZE_REQUEST, or */
/* MEM_ERR_REALLOC_GEN_FAULT, or */
/* MEM_ERR_FREE_NOT_FOUND, or */
/* MEM_ERR_BLOCK_NOT_FOUND, or */
/* MEM_NO_ERROR */
/* Return: MEMTYPE* Pointer to the allocated memory block, or */
/* NULL */
/*************************************************************************/
MEMTYPE* data_OSMem_realloc(MEMTYPE* oldPointer, U1 newSize, U1* err)
{
U1 localError = 0;
U1 loopLength = 0;
U1 byteIndex = 0;
MEMTYPE* newPointer = NULL;
/* find size of old memory block */
U1 oldBlockSize = u1_OSMem_findBlockSize(oldPointer, &localError);
/* case if the user requests a size zero */
if(newSize == 0)
{
/* free the old pointer and check for error */
v_OSMem_free(&oldPointer, &localError);
if(localError == MEM_NO_ERROR)
{
*err = MEM_NO_ERROR;
}
else
{
*err = localError;
}
return NULL;
}
/* case if the user requests a size outside of the possible range, or the same size as the old block */
else if ( newSize > largestBlockSize
|| newSize == oldBlockSize)
{
/* just return an error, don't do anything to the old pointer */
*err = MEM_ERR_INVALID_SIZE_REQUEST;
return oldPointer;
}
/* case new size is valid */
else
{
/* first we try to allocate a new memory block */
newPointer = data_OSMem_malloc(newSize, &localError);
/* next make sure there are no error codes */
if( localError == MEM_NO_ERROR
&& newPointer != NULL)
{
/* choose the smallest of the two loop lengths */
if(newSize > oldBlockSize)
{
loopLength = oldBlockSize;
}
else
{
loopLength = newSize;
}
OS_SCH_ENTER_CRITICAL();
/* begin transfer of memory from old block to new block */
for(byteIndex = 0; byteIndex < loopLength; byteIndex++)
{
if(byteIndex > (loopLength - MEM_WATERMARK_SIZE))
{
newPointer[byteIndex] = MEM_WATERMARK_VAL;
}
else if (byteIndex > oldBlockSize)
{
newPointer[byteIndex] = MEM_WATERMARK_VAL;
}
else
{
newPointer[byteIndex] = oldPointer[byteIndex];
}
}
OS_SCH_EXIT_CRITICAL();
v_OSMem_free(&oldPointer, &localError);
*err = localError;
return newPointer;
}
else
{
*err = localError;
return NULL;
}
}
}
/*************************************************************************/
/* Private Functions */
/*************************************************************************/
/*************************************************************************/
/* Function Name: u1_OSMem_findBlockSize */
/* Purpose: Find the index of the memory block with the same */
/* passed in start pointer. */
/* Arguments: MEMTYPE* blockStart: */
/* Pointer to find in the partition list. */
/* U1* err: */
/* Error variable. Can be one of the following: */
/* MEM_ERR_INVALID_SIZE_REQUEST, or */
/* MEM_NO_ERROR */
/* Return: U1 Size of the memory block. 255 if error. */
/*************************************************************************/
U1 u1_OSMem_findBlockSize(MEMTYPE* blockStart, U1* err)
{
U1 partitionIndex = 0;
U1 blockIndex = 0;
/* loop through the structure and find the index */
for(partitionIndex = 0; partitionIndex < numPartitionsAllocated; partitionIndex++)
{
OSMemPartition tempPartition = partitionList[partitionIndex];
for(blockIndex = 0; blockIndex < tempPartition.numBlocks; blockIndex++)
{
if(blockStart == tempPartition.blocks[blockIndex].start)
{
*err = MEM_NO_ERROR;
return tempPartition.blockSize - 2;
}
else
{
}
}
}
/* otherwise, set an error code and return 255 */
*err = MEM_ERR_BLOCK_NOT_FOUND;
return 255;
}
/*************************************************************************/
/* Function Name: u1_OSMem_maintenance */
/* Purpose: Check the status of all the memblocks to ensure that */
/* the user hasn't overwritten any of the watermarks. */
/* Arguments: None. */
/* Return: MEM_MAINT_NO_ERROR (0) or */
/* MEM_MAINT_ERROR (1) */
/*************************************************************************/
U1 u1_OSMem_maintenance()
{
/* local variables */
U1 partitionIndex = 0;
U1 blockIndex = 0;
U1 watermarkIndex = 0;
U1 currentBlockSize = 0;
/* iterate through the list of partitions */
for(partitionIndex = 0; partitionIndex < numPartitionsAllocated; partitionIndex++)
{
currentBlockSize = partitionList[partitionIndex].blockSize;
/* iterate through all of the blocks */
for(blockIndex = 0; blockIndex < partitionList[partitionIndex].numBlocks; blockIndex++)
{
if(partitionList[partitionIndex].blocks[blockIndex].blockStatus == BLOCK_IN_USE)
{
OSMemBlock tempBlock = partitionList[partitionIndex].blocks[blockIndex];
for(watermarkIndex = (currentBlockSize - MEM_WATERMARK_SIZE); watermarkIndex < currentBlockSize; watermarkIndex++)
{
if(tempBlock.start[watermarkIndex] != MEM_WATERMARK_VAL)
{
return MEM_MAINT_ERROR;
}
else
{
}
}
}
else
{
}
}
}
return MEM_MAINT_NO_ERROR;
}
#endif /* conditional compile */
/***********************************************************************************************/
/* History */
/***********************************************************************************************/
/* Version Date Description */
/* */
/* 0.1 08/14/19 Initial commit. */
/* */
/* 0.2 08/19/19 Implemented realloc function. */
/* */
/* 0.3 08/24/19 Fixed bugs w/free and init. Added maintenance function. */
/* */
/* 0.4 08/25/19 Fixed bug with realloc where pointer would get destroyed. */
/* */
/* 1.0 08/26/19 Reorganized memory module according to standard. */
/* */
/* 1.1 09/04/19 Fixed warnings at compile time. */
/* */
/* 2.0 02/22/20 Rewrite to remove malloc syscall references. */
/* */
/* 2.1 05/07/20 Small bugfixes with free and realloc functions. */
/* */
/* 2.2 05/07/20 Moved static variables from memory internal to memory.c. */
/* */
/* 2.3 07/12/20 Changed memory module datatype to be user defined. */
|
gscultho/HuskEOS | huskEOS/Mutex/Source/mutex.c | /*************************************************************************/
/* File Name: mutex.c */
/* Purpose: Mutex services for application layer tasks. */
/* Created by: <NAME> on 8/14/19. */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#include "rtos_cfg.h"
#if(RTOS_CFG_OS_MUTEX_ENABLED == RTOS_CONFIG_TRUE)
/*************************************************************************/
/* Includes */
/*************************************************************************/
#include "listMgr_internal.h"
#include "mutex_internal_IF.h"
#include "mutex.h"
#include "sch_internal_IF.h"
#include "sch.h"
/*************************************************************************/
/* External References */
/*************************************************************************/
extern void OSTaskFault(void);
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define MUTEX_NO_BLOCK (0)
#define MUTEX_NULL_PTR ((void*)0)
#define MUTEX_NUM_MUTEXES (RTOS_CFG_MAX_NUM_MUTEX)
#define MUTEX_DEFAULT_PRIO (0xFF)
/*************************************************************************/
/* Static Global Variables, Constants */
/*************************************************************************/
static Mutex mutex_s_mutexList[MUTEX_NUM_MUTEXES];
/*************************************************************************/
/* Private Function Prototypes */
/*************************************************************************/
static void vd_OSmutex_blockTask(struct Mutex* mutex);
static void vd_OSmutex_unblockTask(struct Mutex* mutex);
/*************************************************************************/
/*************************************************************************/
/* Function Name: u1_OSmutex_init */
/* Purpose: Initialize specified mutex. */
/* Arguments: OSMutex** mutex: */
/* Address of mutex object. */
/* U1 initValue: */
/* Initial value for mutex. */
/* Return: U1: MUTEX_SUCCESS OR */
/* MUTEX_NO_OBJECTS_AVAILABLE */
/*************************************************************************/
U1 u1_OSmutex_init(OSMutex** mutex, U1 initValue)
{
U1 u1_t_index;
U1 u1_t_returnSts;
static U1 u1_s_numMutexAllocated = (U1)ZERO;
u1_t_returnSts = (U1)MUTEX_NO_OBJECTS_AVAILABLE;
OS_SCH_ENTER_CRITICAL();
/* Have mutex pointer point to available object */
if(u1_s_numMutexAllocated < (U1)MUTEX_NUM_MUTEXES)
{
(*mutex) = &mutex_s_mutexList[u1_s_numMutexAllocated];
++u1_s_numMutexAllocated;
(*mutex)->lock = initValue%TWO;
(*mutex)->blockedTaskList.blockedListHead = MUTEX_NULL_PTR;
(*mutex)->priority.taskInheritedPrio = (U1)MUTEX_DEFAULT_PRIO;
(*mutex)->priority.taskRealPrio = (U1)MUTEX_DEFAULT_PRIO;
for(u1_t_index = (U1)ZERO; u1_t_index < (U1)MUTEX_MAX_NUM_BLOCKED; u1_t_index++)
{
(*mutex)->blockedTaskList.blockedTasks[u1_t_index].nextNode = MUTEX_NULL_PTR;
(*mutex)->blockedTaskList.blockedTasks[u1_t_index].previousNode = MUTEX_NULL_PTR;
(*mutex)->blockedTaskList.blockedTasks[u1_t_index].TCB = MUTEX_NULL_PTR;
}
u1_t_returnSts = (U1)MUTEX_SUCCESS;
}
else
{
}
OS_SCH_EXIT_CRITICAL();
return (u1_t_returnSts);
}
/*************************************************************************/
/* Function Name: u1_OSmutex_lock */
/* Purpose: Claim mutex referenced by pointer. */
/* Arguments: OSMutex* mutex: */
/* Pointer to mutex. */
/* U4 blockPeriod: */
/* Number of time units for task to sleep if blocked. */
/* */
/* Return: U1 MUTEX_TAKEN OR */
/* MUTEX_SUCCESS */
/*************************************************************************/
U1 u1_OSmutex_lock(OSMutex* mutex, U4 blockPeriod)
{
U1 u1_t_returnSts;
u1_t_returnSts = (U1)MUTEX_TAKEN;
OS_SCH_ENTER_CRITICAL();
/* Check if available */
if(mutex->lock == (U1)ZERO)
{
/* If non-blocking function call, exit critical section and return immediately */
if(blockPeriod == (U4)MUTEX_NO_BLOCK)
{
OS_SCH_EXIT_CRITICAL();
}
/* Else block task */
else
{
/* Per scheduler v2 requirement: No two tasks in active state can share the same priority. */
/* Tell scheduler the reason for task block state,
set sleep timer and change task state. */
vd_OSsch_setReasonForSleep(mutex, (U1)SCH_TASK_SLEEP_RESOURCE_MUTEX, blockPeriod);
vd_OSmutex_blockTask(mutex); /* Add task to resource blocked list */
OS_SCH_EXIT_CRITICAL();
/* Check again after task wakes up */
OS_SCH_ENTER_CRITICAL();
if(mutex->lock == MUTEX_AVAILABLE) /* If available */
{
--(mutex->lock);
mutex->priority.mutexHolder = SCH_CURRENT_TCB_ADDR;
u1_t_returnSts = (U1)MUTEX_SUCCESS;
}
OS_SCH_EXIT_CRITICAL();
}
}
else /* mutex is available */
{
--(mutex->lock);
mutex->priority.mutexHolder = SCH_CURRENT_TCB_ADDR;
OS_SCH_EXIT_CRITICAL();
u1_t_returnSts = (U1)MUTEX_SUCCESS;
}
return (u1_t_returnSts);
}
/*************************************************************************/
/* Function Name: u1_OSmutex_check */
/* Purpose: Check status of mutex. */
/* Arguments: OSMutex* mutex: */
/* Pointer to mutex. */
/* Return: U1 MUTEX_TAKEN OR */
/* MUTEX_SUCCESS */
/*************************************************************************/
U1 u1_OSmutex_check(OSMutex* mutex)
{
U1 u1_t_sts;
u1_t_sts = (U1)MUTEX_TAKEN;
OS_SCH_ENTER_CRITICAL();
switch (mutex->lock)
{
case (U1)MUTEX_TAKEN:
break;
case (U1)MUTEX_SUCCESS:
u1_t_sts = (U1)MUTEX_SUCCESS;
break;
default:
OSTaskFault(); /* This point is only reached if there is a software bug. */
break;
}
OS_SCH_EXIT_CRITICAL();
return (u1_t_sts);
}
/*************************************************************************/
/* Function Name: u1_OSmutex_unlock */
/* Purpose: Release mutex and manage priority inheritance. */
/* Arguments: OSMutex* mutex: */
/* Pointer to mutex. */
/* Return: U1: MUTEX_SUCCESS OR */
/* MUTEX_ALREADY_RELEASED */
/*************************************************************************/
U1 u1_OSmutex_unlock(OSMutex* mutex)
{
U1 u1_t_return;
OS_SCH_ENTER_CRITICAL();
/* Only task that holds mutex can release it. */
if(mutex->priority.mutexHolder == SCH_CURRENT_TCB_ADDR)
{
++(mutex->lock);
/* Unblock highest priority task on wait list and restore priority to normal value. */
if(mutex->blockedTaskList.blockedListHead != MUTEX_NULL_PTR)
{
vd_OSmutex_unblockTask(mutex);
}
else
{
/* No blocked task. */
}
u1_t_return = (U1)MUTEX_SUCCESS;
}
else
{
u1_t_return = (U1)MUTEX_NOT_HELD_BY_TASK;
}
OS_SCH_EXIT_CRITICAL();
return (u1_t_return);
}
/*************************************************************************/
/* Function Name: vd_OSmutex_blockedTimeout */
/* Purpose: API for scheduler to call when sleeping task times out*/
/* Arguments: Mutex* mutex: */
/* Pointer to mutex. */
/* Sch_Task* taskTCB: */
/* Pointer to TCB of blocked task. */
/* Return: N/A */
/*************************************************************************/
void vd_OSmutex_blockedTimeout(struct Mutex* mutex, struct Sch_Task* taskTCB)
{
ListNode* node_t_tempPtr;
U1 u1_t_newMutexHolderPrio;
OS_SCH_ENTER_CRITICAL();
/* Remove node from block list. */
node_t_tempPtr = node_list_removeNodeByTCB(&(mutex->blockedTaskList.blockedListHead), taskTCB);
/* If task with mutex has inherited this task's priority. */
if(node_t_tempPtr->TCB->priority == mutex->priority.taskInheritedPrio)
{
/* If there is no other higher priority task then reset to original priority. */
if(mutex->blockedTaskList.blockedListHead == MUTEX_NULL_PTR)
{
u1_t_newMutexHolderPrio = mutex->priority.taskRealPrio;
/* Reset internal data. */
mutex->priority.taskRealPrio = (U1)MUTEX_DEFAULT_PRIO;
mutex->priority.taskInheritedPrio = (U1)MUTEX_DEFAULT_PRIO;
}
else
{
/* If the new highest prio blocked task priority is greater (numerically lower) than the current inherited priority, update the inherited priority. */
if(mutex->blockedTaskList.blockedListHead->TCB->priority < mutex->priority.taskInheritedPrio)
{
/* Update inherited priority. */
u1_t_newMutexHolderPrio = mutex->blockedTaskList.blockedListHead->TCB->priority;
/* Change internal record as well. */
mutex->priority.taskInheritedPrio = mutex->blockedTaskList.blockedListHead->TCB->priority;
}
else /* No higher priority to inherit. */
{
u1_t_newMutexHolderPrio = mutex->priority.taskRealPrio;
/* Reset internal data. */
mutex->priority.taskRealPrio = (U1)MUTEX_DEFAULT_PRIO;
mutex->priority.taskInheritedPrio = (U1)MUTEX_DEFAULT_PRIO;
}
}
/* Notify scheduler of change. */
(void)u1_OSsch_setNewPriority(mutex->priority.mutexHolder, u1_t_newMutexHolderPrio);
}
else
{
/* No change to mutex holder's priority. */
}/* node_t_tempPtr->TCB->priority == mutex->priority.taskInheritedPrio */
node_t_tempPtr->TCB = MUTEX_NULL_PTR;
OS_SCH_EXIT_CRITICAL();
}
/*************************************************************************/
/* Function Name: vd_OSmutex_blockTask */
/* Purpose: Add task to blocked list of mutex and handle priority */
/* inheritance. */
/* Arguments: OSMutex* mutex: */
/* Pointer to mutex. */
/* Return: N/A */
/*************************************************************************/
static void vd_OSmutex_blockTask(OSMutex* mutex)
{
U1 u1_t_index;
U1 u1_t_priorityOriginal;
u1_t_index = (U1)ZERO;
/* Find available node to store data */
while((mutex->blockedTaskList.blockedTasks[u1_t_index].TCB != MUTEX_NULL_PTR) && (u1_t_index < (U1)MUTEX_MAX_NUM_BLOCKED))
{
++u1_t_index;
}
/* If node found, then store TCB pointer and add to blocked list */
if(u1_t_index < (U1)MUTEX_MAX_NUM_BLOCKED)
{
/* Add task to blocked list. */
(mutex->blockedTaskList.blockedTasks[u1_t_index].TCB) = SCH_CURRENT_TCB_ADDR;
vd_list_addTaskByPrio(&(mutex->blockedTaskList.blockedListHead), &(mutex->blockedTaskList.blockedTasks[u1_t_index]));
/* If the blocking task's priority is greater (numerically lower) than the mutex holder's current priority, update the inherited priority. */
if((mutex->blockedTaskList.blockedListHead->TCB->priority != mutex->priority.taskInheritedPrio)
&& (mutex->blockedTaskList.blockedListHead->TCB->priority < mutex->priority.mutexHolder->priority)
&& (mutex->priority.mutexHolder != MUTEX_NULL_PTR))
{
/* Notify scheduler of change. */
u1_t_priorityOriginal = u1_OSsch_setNewPriority(mutex->priority.mutexHolder, mutex->blockedTaskList.blockedListHead->TCB->priority);
/* Change internal record as well. */
mutex->priority.taskInheritedPrio = mutex->blockedTaskList.blockedListHead->TCB->priority;
/* Check if original priority needs to be stored internally. */
if(mutex->priority.taskRealPrio == (U1)MUTEX_DEFAULT_PRIO)
{
mutex->priority.taskRealPrio = u1_t_priorityOriginal;
}
else
{
/* Original priority is already stored. */
}
}
else
{
}/* (mutex->blockedTaskList.blockedListHead->TCB->priority < mutex->priority.taskInheritedPrio) */
}/* (u1_t_index < (U1)MUTEX_MAX_NUM_BLOCKED) */
}
/*************************************************************************/
/* Function Name: vd_OSmutex_unblockTask */
/* Purpose: Wake up task blocked on mutex, handle priorities. */
/* Arguments: OSMutex* mutex: */
/* Pointer to mutex. */
/* Return: N/A */
/*************************************************************************/
static void vd_OSmutex_unblockTask(OSMutex* mutex)
{
ListNode* node_t_p_highPrioTask;
/* Remove highest priority task */
node_t_p_highPrioTask = node_list_removeFirstNode(&(mutex->blockedTaskList.blockedListHead));
/* If task holding mutex had inherited priority, restore original priority. */
if(mutex->priority.taskInheritedPrio != (U1)MUTEX_DEFAULT_PRIO)
{ //throw away return value
(void)u1_OSsch_setNewPriority(mutex->priority.mutexHolder, mutex->priority.taskRealPrio);
mutex->priority.taskInheritedPrio = (U1)MUTEX_DEFAULT_PRIO;
}
else
{
/* Priority was not inherited. */
}
/* Reset internal data. */
mutex->priority.mutexHolder = MUTEX_NULL_PTR;
mutex->priority.taskRealPrio = (U1)MUTEX_DEFAULT_PRIO;
/* Notify scheduler the reason that task is going to be woken. */
vd_OSsch_setReasonForWakeup((U1)SCH_TASK_WAKEUP_MUTEX_READY, node_t_p_highPrioTask->TCB);
/* Notify scheduler to change task state. If woken task is higher priority than running task, context switch will occur after critical section. */
vd_OSsch_taskWake(node_t_p_highPrioTask->TCB->taskID);
/* Clear TCB pointer. This frees this node for future use. */
node_t_p_highPrioTask->TCB = MUTEX_NULL_PTR;
}
#endif /* Conditional compile */
/***********************************************************************************************/
/* History */
/***********************************************************************************************/
/* Version Date Description */
/* */
/* 0.1 8/19/19 Module implemented for first time. */
/* */
/* 0.2 1/2/2020 Mutex objects being declared twice (by app and by module) */
/* due to leftover behavior of baseline (old sempaphore module).*/
/* */
/* 0.3 5/4/2020 Added extra check before initiating priority inheritance. The*/
/* module now checks that the mutex is held by another task */
/* before making function call to scheduler to raise priority. */
/* Tecnically this is not a bug since it only presents an issue */
/* if the application uses the lock/unlock functions in an */
/* incorrect sequence, or it initializes a mutex to an */
/* unintended value. */
|
gscultho/HuskEOS | huskEOS/Global/Header/rtos_cfg.h | <filename>huskEOS/Global/Header/rtos_cfg.h
/*************************************************************************/
/* File Name: rtos_cfg.h */
/* Purpose: Configuration for RTOS. */
/* Created by: <NAME> on 2/28/2019 */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#ifndef rtos_cfg_h
#define rtos_cfg_h
#include "cpu_defs.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define RTOS_CONFIG_TRUE (1)
#define RTOS_CONFIG_FALSE (0)
/* Application */
#define RTOS_CONFIG_BG_TASK_STACK_SIZE (50) /* Stack size for background task if enabled */
#define RTOS_CONFIG_CALC_TASK_CPU_LOAD (RTOS_CONFIG_FALSE) /* Can only be enabled if RTOS_CONFIG_BG_TASK and RTOS_CONFIG_ENABLE_BACKGROUND_IDLE_SLEEP enabled */
/* Scheduling */
#define RTOS_CONFIG_MAX_NUM_TASKS (3) /* This number of TCBs will be allocated at compile-time, plus any others used by OS */
/* Available priorities are 0 - 0xEF with 0 being highest priority. */
#define RTOS_CONFIG_ENABLE_BACKGROUND_IDLE_SLEEP (RTOS_CONFIG_TRUE) /* CPU goes to sleep when idle. */
#define RTOS_CONFIG_ENABLE_STACK_OVERFLOW_DETECT (RTOS_CONFIG_TRUE) /* Check for stack overflow periodically. */
#define RTOS_CONFIG_PRESLEEP_FUNC (RTOS_CONFIG_FALSE) /* If enabled, hook function app_OSPreSleepFcn() can be defined in application. */
#define RTOS_CONFIG_POSTSLEEP_FUNC (RTOS_CONFIG_FALSE) /* If enabled, hook function app_OSPostSleepFcn() can be defined in application. */
/* Mailbox */
#define RTOS_CFG_OS_MAILBOX_ENABLED (RTOS_CONFIG_FALSE)
#define RTOS_CFG_NUM_MAILBOX (0) /* Number of mailboxes available in run-time. */
#define RTOS_CFG_MBOX_DATA U4 /* Data type for mailbox */
/* Message Queues */
#define RTOS_CFG_OS_QUEUE_ENABLED (RTOS_CONFIG_FALSE)
#define RTOS_CFG_NUM_FIFO (0) /* Number of FIFOs available in run-time. */
#define RTOS_CFG_MAX_NUM_BLOCKED_TASKS_FIFO (0) /* Maximum number of tasks that can block on each FIFO. */
#define RTOS_CFG_BUFFER_DATA U4 /* Type of data used in the buffers. */
/* Semaphores */
#define RTOS_CFG_OS_SEMAPHORE_ENABLED (RTOS_CONFIG_FALSE)
#define RTOS_CFG_NUM_SEMAPHORES (0) /* Number of semaphores available in run-time. */
#define RTOS_CFG_NUM_BLOCKED_TASKS_SEMA (0) /* Maximum number of tasks that can block on each FIFO. */
/* Flags */
#define RTOS_CFG_OS_FLAGS_ENABLED (RTOS_CONFIG_FALSE)
#define RTOS_CFG_NUM_FLAG_OBJECTS (0) /* Number of flag objects available in run-time. */
#define RTOS_CFG_MAX_NUM_TASKS_PEND_FLAGS (0) /* Maximum number of tasks that can pend on flags object. */
/* Mutex */
#define RTOS_CFG_OS_MUTEX_ENABLED (RTOS_CONFIG_FALSE)
#define RTOS_CFG_MAX_NUM_MUTEX (0) /* Number of mutexes available in run-time. */
#define RTOS_CFG_MAX_NUM_BLOCKED_TASKS_MUTEX (0) /* Number of tasks that can block on each mutex. */
/* Memory */
#define RTOS_CFG_OS_MEM_ENABLED (RTOS_CONFIG_FALSE)
#define RTOS_CFG_MAX_NUM_MEM_PARTITIONS (0) /* Maximum number of memory partitions available in run-time. */
#define RTOS_CFG_MAX_NUM_MEM_BLOCKS (0) /* Maximum number of blocks that can be contained within a partition. */
#define RTOS_CFG_MAX_MEM_BLOCK_SIZE (0) /* Maximum memory block size. */
#define RTOS_CFG_MEMORY_TYPE U1 /* Type of data to use in the memory module. */
/* I/O */
#define PART_TM4C123GH6PM 1
/*************************************************************************/
/* Data Types */
/*************************************************************************/
/* Internal - Do not modify */
typedef RTOS_CFG_MBOX_DATA MAIL;
typedef RTOS_CFG_BUFFER_DATA Q_MEM;
typedef RTOS_CFG_MEMORY_TYPE MEMTYPE;
/*************************************************************************/
/* Public Functions */
/*************************************************************************/
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
#endif
|
gscultho/HuskEOS | huskEOS/Flags/Header/flags_internal_IF.h | <filename>huskEOS/Flags/Header/flags_internal_IF.h
/*************************************************************************/
/* File Name: flags_internal_IF.h */
/* Purpose: Kernel access definitions and routines for flags. */
/* Created by: <NAME> on 5/20/19 */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#ifndef flags_internal_IF_h
#define flags_internal_IF_h
#include "rtos_cfg.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define FLAGS_MAX_NUM_TASKS_PENDING (RTOS_CFG_MAX_NUM_TASKS_PEND_FLAGS)
/*************************************************************************/
/* Data Types */
/*************************************************************************/
struct Sch_Task; /* Forward declaration. See definition in sch_internal_IF.h */
typedef struct TasksPending
{
U1 event; /* Event that task is pending on. */
struct Sch_Task* tcb; /* Pointer to pending task TCB. */
U1 eventPendType; /* Type of pend (exact match or just one flag set). */
}
TasksPending;
typedef struct FlagsObj
{
U1 flags; /* Object containing 8 flags. */
TasksPending pendingList[FLAGS_MAX_NUM_TASKS_PENDING]; /* Memory allocated for storing pending task info. */
}
FlagsObj;
/*************************************************************************/
/* Public Functions */
/*************************************************************************/
/*************************************************************************/
/* Function Name: vd_OSflags_pendTimeout */
/* Purpose: Timeout hander for pending task. Called by scheduler. */
/* Arguments: FlagsObj* flags: */
/* Pointer to flags object. */
/* Sch_Task pendingTCB: */
/* Pointer to timed out task's TCB. */
/* Return: N/A */
/*************************************************************************/
void vd_OSflags_pendTimeout(struct FlagsObj* flags, struct Sch_Task* pendingTCB);
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
#endif
|
gscultho/HuskEOS | huskEOS/Schedule/Source/sch.c | <filename>huskEOS/Schedule/Source/sch.c
/*************************************************************************/
/* File Name: sch.c */
/* Purpose: Init and routines for scheduler module and task handling. */
/* Created by: <NAME> on 2/29/19. */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
/*************************************************************************/
/* Includes */
/*************************************************************************/
#include "cpu_defs.h"
#include "rtos_cfg.h"
#include "sch_internal_IF.h"
#include "listMgr_internal.h"
#include "sch.h"
#if(RTOS_CFG_OS_MAILBOX_ENABLED == RTOS_CONFIG_TRUE)
#include "mbox_internal_IF.h"
#endif
#if(RTOS_CFG_OS_QUEUE_ENABLED == RTOS_CONFIG_TRUE)
#include "queue_internal_IF.h"
#endif
#if(RTOS_CFG_OS_SEMAPHORE_ENABLED == RTOS_CONFIG_TRUE)
#include "semaphore_internal_IF.h"
#endif
#if(RTOS_CFG_OS_FLAGS_ENABLED == RTOS_CONFIG_TRUE)
#include "flags_internal_IF.h"
#endif
#if(RTOS_CFG_OS_MUTEX_ENABLED == RTOS_CONFIG_TRUE)
#include "mutex_internal_IF.h"
#endif
#if(RTOS_CFG_OS_MEM_ENABLED == RTOS_CONFIG_TRUE)
#include "memory_internal_IF.h"
#endif
/*************************************************************************/
/* External References */
/*************************************************************************/
extern void WaitForInterrupt(void);
extern void OSTaskFault(void);
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define RTOS_RESOURCES_CONFIGURED (RTOS_CFG_OS_MAILBOX_ENABLED | \
RTOS_CFG_OS_QUEUE_ENABLED | \
RTOS_CFG_OS_SEMAPHORE_ENABLED | \
RTOS_CFG_OS_FLAGS_ENABLED)
#define SCH_NUM_TASKS_ZERO (0)
#define SCH_TRUE (1)
#define SCH_FALSE (0)
#define SCH_TCB_PTR_INIT (NULL)
#define SCH_TASK_FLAG_STS_SLEEP (0x10)
#define SCH_TASK_FLAG_STS_SUSPENDED (0x20)
#define SCH_TASK_FLAG_SLEEP_MBOX (SCH_TASK_WAKEUP_MBOX_READY)
#define SCH_TASK_FLAG_SLEEP_QUEUE (SCH_TASK_WAKEUP_QUEUE_READY)
#define SCH_TASK_FLAG_SLEEP_SEMA (SCH_TASK_WAKEUP_SEMA_READY)
#define SCH_TASK_FLAG_SLEEP_FLAGS (SCH_TASK_WAKEUP_FLAGS_EVENT)
#define SCH_TASK_FLAG_SLEEP_MUTEX (SCH_TASK_WAKEUP_MUTEX_READY)
#define SCH_TASK_FLAG_STS_CHECK (SCH_TASK_FLAG_STS_SLEEP | SCH_TASK_FLAG_STS_SUSPENDED)
#define SCH_TASK_RESOURCE_SLEEP_CHECK_MASK (SCH_TASK_FLAG_SLEEP_MBOX | SCH_TASK_FLAG_SLEEP_QUEUE | SCH_TASK_FLAG_SLEEP_SEMA | SCH_TASK_FLAG_SLEEP_FLAGS)
#define SCH_TOP_OF_STACK_MARK (0xF0F0F0F0)
#define SCH_ONE_HUNDRED_PERCENT (100)
#define SCH_HUNDRED_TICKS (100)
#define SCH_CPU_NOT_SLEEPING (SCH_FALSE)
#define SCH_CPU_SLEEPING (SCH_TRUE)
#define SCH_FIRST_TCB_NODE (ZERO)
#define SCH_TASK_PRIORITY_UNDEFINED (0xFF)
#define SCH_TASK_LOWEST_PRIORITY (0xF0)
#define SCH_INVALID_TASK_ID (0xFF)
#define SCH_BG_TASK_ID (SCH_MAX_NUM_TASKS - 1)
#define SCH_NULL_PTR ((void*)ZERO)
#define SCH_MAX_NUM_TICK (4294967200U)
/*************************************************************************/
/* Global Variables, Constants */
/*************************************************************************/
ListNode* Node_s_ap_mapTaskIDToTCB[SCH_MAX_NUM_TASKS];
/* Note: These global variables are modified by asm routine */
Sch_Task* tcb_g_p_currentTaskBlock;
Sch_Task* tcb_g_p_nextTaskBlock;
/*************************************************************************/
/* Static Global Variables, Constants */
/*************************************************************************/
static U1 u1_s_numTasks;
static U4 u4_s_tickCntr;
#if(RTOS_CONFIG_PRESLEEP_FUNC == RTOS_CONFIG_TRUE || RTOS_CONFIG_POSTSLEEP_FUNC == RTOS_CONFIG_TRUE)
static U1 u1_s_sleepState;
#endif
static ListNode* node_s_p_headOfWaitList;
static ListNode* node_s_p_headOfReadyList;
static OS_STACK u4_backgroundStack[SCH_BG_TASK_STACK_SIZE];
/* Allocate memory for data structures used for TCBs and scheduling queues */
static ListNode Node_s_as_listAllTasks[SCH_MAX_NUM_TASKS];
static Sch_Task SchTask_s_as_taskList[SCH_MAX_NUM_TASKS];
#if (RTOS_CONFIG_CALC_TASK_CPU_LOAD == RTOS_CONFIG_TRUE)
static OS_RunTimeStats OS_s_cpuData;
#endif
/*************************************************************************/
/* Private Function Prototypes */
/*************************************************************************/
static void vd_OSsch_background(void);
#if(RTOS_CONFIG_ENABLE_STACK_OVERFLOW_DETECT == RTOS_CONFIG_TRUE)
static U1 u1_sch_checkStack(U1 taskIndex);
#endif
static void vd_OSsch_setNextReadyTaskToRun(void);
static void vd_OSsch_taskSleepTimeoutHandler(Sch_Task* taskTCB);
static void vd_OSsch_periodicScheduler(void);
/*************************************************************************/
/*************************************************************************/
/* Function Name: vd_OS_init */
/* Purpose: Initialize scheduler module and configured RTOS */
/* modules. */
/* Arguments: U4 numMsPeriod: */
/* Sets scheduler tick rate in milliseconds. */
/* Return: N/A */
/*************************************************************************/
void vd_OS_init(U4 numMsPeriod)
{
U1 u1_t_index;
u1_s_numTasks = (U1)SCH_NUM_TASKS_ZERO;
u4_s_tickCntr = (U1)ZERO;
#if(RTOS_CONFIG_PRESLEEP_FUNC == RTOS_CONFIG_TRUE || RTOS_CONFIG_POSTSLEEP_FUNC == RTOS_CONFIG_TRUE)
u1_s_sleepState = (U1)SCH_CPU_NOT_SLEEPING;
#endif
/* Initialize task and queue data to default values */
for(u1_t_index = (U1)ZERO; u1_t_index < (U1)SCH_MAX_NUM_TASKS; u1_t_index++)
{
SchTask_s_as_taskList[u1_t_index].stackPtr = (OS_STACK*)NULL;
SchTask_s_as_taskList[u1_t_index].flags = (U1)ZERO;
SchTask_s_as_taskList[u1_t_index].sleepCntr = (U4)ZERO;
SchTask_s_as_taskList[u1_t_index].resource = (void*)NULL;
SchTask_s_as_taskList[u1_t_index].wakeReason = (U1)ZERO;
SchTask_s_as_taskList[u1_t_index].priority = (U1)SCH_TASK_PRIORITY_UNDEFINED;
SchTask_s_as_taskList[u1_t_index].taskID = (U1)SCH_INVALID_TASK_ID;
Node_s_ap_mapTaskIDToTCB[u1_t_index] = (ListNode*)NULL;
Node_s_as_listAllTasks[u1_t_index].nextNode = (ListNode*)NULL;
Node_s_as_listAllTasks[u1_t_index].previousNode = (ListNode*)NULL;
Node_s_as_listAllTasks[u1_t_index].TCB = (Sch_Task*)NULL;
}
/* Initialize linked list head pointers */
node_s_p_headOfWaitList = (ListNode*)NULL;
node_s_p_headOfReadyList = (ListNode*)NULL;
/* Initialize running task pointer */
tcb_g_p_currentTaskBlock = (Sch_Task*)SCH_TCB_PTR_INIT;
#if (RTOS_CONFIG_CALC_TASK_CPU_LOAD == RTOS_CONFIG_TRUE)
OS_s_cpuData.CPUIdlePercent.CPU_idleAvg = (U1)ZERO;
OS_s_cpuData.CPUIdlePercent.CPU_idlePrevTimestamp = (U1)ZERO;
OS_s_cpuData.CPUIdlePercent.CPU_idleRunning = (U4)ZERO;
#endif
/* Create background task */
u1_OSsch_createTask(&vd_OSsch_background,
&u4_backgroundStack[SCH_BG_TASK_STACK_SIZE - ONE],
(U4)RTOS_CONFIG_BG_TASK_STACK_SIZE,
(U1)SCH_TASK_LOWEST_PRIORITY,
(U1)SCH_BG_TASK_ID);
/* Mask interrupts until RTOS enters normal operation */
vd_cpu_disableInterruptsOSStart();
vd_cpu_init(numMsPeriod);
#if(RTOS_CFG_OS_MAILBOX_ENABLED == RTOS_CONFIG_TRUE)
vd_OSmbox_init();
#endif
}
/*************************************************************************/
/* Function Name: u1_OSsch_createTask */
/* Purpose: Create new task in list. */
/* Arguments: void* newTaskFcn: */
/* Function pointer to task routine. */
/* void* sp: */
/* Pointer to bottom of task stack (highest mem. */
/* address). */
/* U4 sizeOfStack: */
/* Size of task stack. */
/* U1 priority: */
/* Unique priority level for task. 0 = highest. */
/* U1 taskID: */
/* Task ID to refer to task when using APIs (cannot*/
/* be changed). Value must be between 0 and the */
/* total number of application tasks - 1. */
/* */
/* Return: SCH_TASK_CREATE_SUCCESS OR */
/* SCH_TASK_CREATE_DENIED */
/*************************************************************************/
U1 u1_OSsch_createTask(void (*newTaskFcn)(void), void* sp, U4 sizeOfStack, U1 priority, U1 taskID)
{
U1 u1_t_returnSts;
if(u1_s_numTasks >= (U1)SCH_MAX_NUM_TASKS)
{
u1_t_returnSts = (U1)SCH_TASK_CREATE_DENIED;
}
else if(Node_s_ap_mapTaskIDToTCB[taskID] != (void*)NULL)
{
u1_t_returnSts = (U1)SCH_TASK_CREATE_DENIED;
}
else
{
/* Map user configured task ID to the actual TCB location for later queries by user */
Node_s_ap_mapTaskIDToTCB[taskID] = &Node_s_as_listAllTasks[u1_s_numTasks];
/* Set new task stack pointers */
#if(RTOS_CONFIG_ENABLE_STACK_OVERFLOW_DETECT == RTOS_CONFIG_TRUE)
#if(STACK_GROWTH == STACK_DESCENDING)
SchTask_s_as_taskList[u1_s_numTasks].topOfStack = ((OS_STACK*)sp - sizeOfStack + ONE);
#elif(STACK_GROWTH == STACK_ASCENDING)
SchTask_s_as_taskList[u1_s_numTasks].topOfStack = ((OS_STACK*)sp + sizeOfStack - ONE);
#else
#error "STACK DIRECTION NOT PROPERLY DEFINED"
#endif /* STACK_GROWTH */
*SchTask_s_as_taskList[u1_s_numTasks].topOfStack = (OS_STACK)SCH_TOP_OF_STACK_MARK;
#endif /* RTOS_CONFIG_ENABLE_STACK_OVERFLOW_DETECT */
SchTask_s_as_taskList[u1_s_numTasks].stackPtr = sp_cpu_taskStackInit(newTaskFcn, (OS_STACK*)sp);
/* Set new task priority, ID */
SchTask_s_as_taskList[u1_s_numTasks].priority = priority;
SchTask_s_as_taskList[u1_s_numTasks].taskID = taskID;
/* Set new linked list node content to newly formed TCB */
Node_s_as_listAllTasks[u1_s_numTasks].TCB = &SchTask_s_as_taskList[u1_s_numTasks];
/* Put new task into ready queue sorted by priority */
vd_list_addTaskByPrio(&node_s_p_headOfReadyList, &Node_s_as_listAllTasks[u1_s_numTasks]);
/* Increment number of tasks */
++u1_s_numTasks;
u1_t_returnSts = (U1)SCH_TASK_CREATE_SUCCESS;
}
return (u1_t_returnSts);
}
/*************************************************************************/
/* Function Name: vd_OSsch_start */
/* Purpose: Give control to operating system. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
void vd_OSsch_start(void)
{
/* Start at highest priority task */
tcb_g_p_nextTaskBlock = node_s_p_headOfReadyList->TCB;
OS_CPU_TRIGGER_DISPATCHER();
vd_cpu_enableInterruptsOSStart();
}
/*************************************************************************/
/* Function Name: vd_OSsch_interruptEnter */
/* Purpose: Must be called by ISRs external to OS at entry. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
U1 u1_OSsch_interruptEnter(void)
{
#if(RTOS_CONFIG_PRESLEEP_FUNC == RTOS_CONFIG_TRUE)
if(u1_s_sleepState == (U1)SCH_CPU_SLEEPING)
{
/* Post-sleep hook function defined by application */
app_OSPostSleepFcn();
u1_s_sleepState = (U1)SCH_CPU_NOT_SLEEPING;
}
#endif
return (u1_OSsch_maskInterrupts());
}
/*************************************************************************/
/* Function Name: vd_OSsch_interruptExit */
/* Purpose: Must be called by ISRs external to OS at exit. */
/* Arguments: U1 prioMaskReset: */
/* Priority mask returned by u1_OSsch_interruptEnter()*/
/* Return: N/A */
/*************************************************************************/
void vd_OSsch_interruptExit(U1 prioMaskReset)
{
vd_OSsch_unmaskInterrupts(prioMaskReset);
}
/*************************************************************************/
/* Function Name: u1_OSsch_g_numTasks */
/* Purpose: Return current number of scheduled tasks. */
/* Arguments: N/A */
/* Return: Number of tasks: 0 - SCH_MAX_NUM_TASKS */
/*************************************************************************/
U1 u1_OSsch_g_numTasks(void)
{
return (u1_s_numTasks);
}
/*************************************************************************/
/* Function Name: u4_OSsch_getCurrentTickPeriodMs */
/* Purpose: Get current period in ms for scheduler tick. */
/* Arguments: N/A */
/* Return: Tick rate in milliseconds. */
/*************************************************************************/
U4 u4_OSsch_getCurrentTickPeriodMs(void)
{
return (u4_cpu_getCurrentMsPeriod());
}
/*************************************************************************/
/* Function Name: u1_OSsch_getReasonForWakeup */
/* Purpose: Get most recent reason that current task has woken up.*/
/* Arguments: N/A */
/* Return: SCH_TASK_WAKEUP_SLEEP_TIMEOUT OR */
/* SCH_TASK_NO_WAKEUP_SINCE_LAST_CHECK OR */
/* SCH_TASK_WAKEUP_MBOX_READY OR */
/* SCH_TASK_WAKEUP_QUEUE_READY OR */
/* SCH_TASK_WAKEUP_SEMA_READY OR */
/* SCH_TASK_WAKEUP_FLAGS_EVENT OR */
/* SCH_TASK_WAKEUP_MUTEX_READY OR */
/* OS flags event that triggered wakeup */
/*************************************************************************/
U1 u1_OSsch_getReasonForWakeup(void)
{
U1 u1_t_reason;
/* Don't let scheduler interrupt itself. Ticker keeps ticking. */
OS_CPU_ENTER_CRITICAL();
u1_t_reason = tcb_g_p_currentTaskBlock->wakeReason;
tcb_g_p_currentTaskBlock->wakeReason = (U1)SCH_TASK_NO_WAKEUP_SINCE_LAST_CHECK;
/* Resume tick interrupts and enable context switch interrupt. */
OS_CPU_EXIT_CRITICAL();
return(u1_t_reason);
}
/*************************************************************************/
/* Function Name: u4_OSsch_getTicks */
/* Purpose: Get number of ticks from scheduler. Overflows to zero.*/
/* Arguments: N/A */
/* Return: Number of scheduler ticks. */
/*************************************************************************/
U4 u4_OSsch_getTicks(void)
{
return(u4_s_tickCntr);
}
/*************************************************************************/
/* Function Name: u1_OSsch_getCurrentTaskID */
/* Purpose: Returns current task ID. */
/* Arguments: N/A */
/* Return: U1: Current task ID number. */
/*************************************************************************/
U1 u1_OSsch_getCurrentTaskID(void)
{
return(tcb_g_p_currentTaskBlock->taskID);
}
/*************************************************************************/
/* Function Name: u1_OSsch_getCurrentTaskPrio */
/* Purpose: Returns current task priority. */
/* Arguments: N/A */
/* Return: U1: Current task priority. */
/*************************************************************************/
U1 u1_OSsch_getCurrentTaskPrio(void)
{
return(tcb_g_p_currentTaskBlock->priority);
}
/*************************************************************************/
/* Function Name: u1_OSsch_getCPULoad */
/* Purpose: Returns CPU load averaged over 100 ticks. */
/* Arguments: N/A */
/* Return: U1: CPU load as a percentage. */
/*************************************************************************/
#if (RTOS_CONFIG_CALC_TASK_CPU_LOAD == RTOS_CONFIG_TRUE)
U1 u1_OSsch_getCPULoad(void)
{
return ((U1)SCH_ONE_HUNDRED_PERCENT - OS_s_cpuData.CPUIdlePercent.CPU_idleAvg);
}
#endif
/*************************************************************************/
/* Function Name: vd_OSsch_setNewTickPeriod */
/* Purpose: Set new tick period in milliseconds. */
/* Arguments: U4 numMsReload: */
/* Period of interrupts. */
/* Return: N/A */
/*************************************************************************/
void vd_OSsch_setNewTickPeriod(U4 numMsReload)
{
vd_cpu_setNewSchedPeriod(numMsReload);
}
/*************************************************************************/
/* Function Name: vd_OSsch_setReasonForWakeup */
/* Purpose: Set reason for wakeup to resource available. Called */
/* internal to RTOS by other RTOS modules. It is expected*/
/* that OS internal modules will call taskWake() *after* */
/* this function call and maintain their own block lists.*/
/* Arguments: U1 reason: */
/* Identifier code for wakeup reason. */
/* Sch_Task* wakeupTaskTCB: */
/* Pointer to task TCB that is being woken up which */
/* was stored on resource blocked list. */
/* Return: void */
/*************************************************************************/
void vd_OSsch_setReasonForWakeup(U1 reason, struct Sch_Task* wakeupTaskTCB)
{
OS_CPU_ENTER_CRITICAL();
/* Clear OS resource pointer. */
wakeupTaskTCB->resource = (void*)NULL;
/* Remove sleep reason from flags entry in TCB */
wakeupTaskTCB->flags &= ~((U1)reason);
/* Set the wakeup reason for application to read. */
wakeupTaskTCB->wakeReason = reason;
OS_CPU_EXIT_CRITICAL();
}
/*************************************************************************/
/* Function Name: vd_OSsch_setReasonForSleep */
/* Purpose: Set reason for task sleep according to mask and set */
/* task to sleep state. */
/* Arguments: void* taskSleepResource: */
/* Address of resource task is blocked on. */
/* U1 resourceType: */
/* Code for resource that task is sleeping on. */
/* U4 period: */
/* Period to sleep for. */
/* Return: N/A */
/*************************************************************************/
void vd_OSsch_setReasonForSleep(void* taskSleepResource, U1 resourceType, U4 period)
{
/* Don't let scheduler interrupt itself. Ticker keeps ticking. */
OS_CPU_ENTER_CRITICAL();
tcb_g_p_currentTaskBlock->resource = taskSleepResource;
tcb_g_p_currentTaskBlock->flags |= (U1)resourceType;
tcb_g_p_currentTaskBlock->sleepCntr = period;
tcb_g_p_currentTaskBlock->flags |= (U1)SCH_TASK_FLAG_STS_SLEEP;
/* Switch to an active task */
vd_OSsch_setNextReadyTaskToRun();
OS_CPU_TRIGGER_DISPATCHER();
/* Resume tick interrupts and enable context switch interrupt. */
OS_CPU_EXIT_CRITICAL();
}
/*************************************************************************/
/* Function Name: u1_OSsch_setNewPriority */
/* Purpose: Function to change task priority in support of */
/* priority inheritance. Internal use only. Internal */
/* module must ensure that no two active tasks share */
/* the same priority value at any time. */
/* Arguments: Sch_Task* tcb: */
/* Pointer to TCB to have priority changed. */
/* U1 newPriority: */
/* */
/* Return: U1: Previous priority value. */
/*************************************************************************/
U1 u1_OSsch_setNewPriority(struct Sch_Task* tcb, U1 newPriority)
{
U1 u1_t_prevPrio;
OS_CPU_ENTER_CRITICAL();
/* If task is suspended or sleeping then simply change priority. */
if(tcb->flags & (U1)SCH_TASK_FLAG_STS_CHECK)
{
u1_t_prevPrio = tcb->priority;
tcb->priority = newPriority;
}
else
{
/* Remove node from current position. */
vd_list_removeNode(&node_s_p_headOfReadyList, Node_s_ap_mapTaskIDToTCB[tcb->taskID]);
/* Change priority. */
u1_t_prevPrio = tcb->priority;
tcb->priority = newPriority;
/* Add back into list in order. */
vd_list_addTaskByPrio(&node_s_p_headOfReadyList, Node_s_ap_mapTaskIDToTCB[tcb->taskID]);
/* Is new priority higher priority than current task ? */
if(node_s_p_headOfReadyList->TCB != tcb_g_p_currentTaskBlock)
{
/* Set global task pointer to new task control block */
tcb_g_p_nextTaskBlock = node_s_p_headOfReadyList->TCB;
OS_CPU_TRIGGER_DISPATCHER();
}
else
{
}
}
OS_CPU_EXIT_CRITICAL();
return (u1_t_prevPrio);
}
/*************************************************************************/
/* Function Name: vd_OSsch_taskSleep */
/* Purpose: Suspend current task for a specified amount of time. */
/* Arguments: U4 u4_period: */
/* Time units to suspend for. */
/* Return: N/A */
/*************************************************************************/
void vd_OSsch_taskSleep(U4 period)
{
/* Don't let scheduler interrupt itself. Ticker keeps ticking. */
OS_CPU_ENTER_CRITICAL();
tcb_g_p_currentTaskBlock->sleepCntr = period;
tcb_g_p_currentTaskBlock->flags |= (U1)SCH_TASK_FLAG_STS_SLEEP;
/* Switch to an active task */
vd_OSsch_setNextReadyTaskToRun();
OS_CPU_TRIGGER_DISPATCHER();
/* Resume tick interrupts and enable context switch interrupt. */
OS_CPU_EXIT_CRITICAL();
}
/*************************************************************************/
/* Function Name: u4_OSsch_taskSleepSetFreq */
/* Purpose: Used to set task to sleep such that task will run at a*/
/* set frequency. */
/* Arguments: U4 nextWakeTime: */
/* Time to wake up at (in ticks). */
/* Return: U4 u4_t_wakeTime: */
/* Tick value that task was most recently woken at. */
/*************************************************************************/
U4 u4_OSsch_taskSleepSetFreq(U4 nextWakeTime)
{
/* Don't let scheduler interrupt itself. Ticker keeps ticking. */
OS_CPU_ENTER_CRITICAL();
/* Handle tick roll-over. */
if(nextWakeTime > u4_s_tickCntr)
{
tcb_g_p_currentTaskBlock->sleepCntr = nextWakeTime - u4_s_tickCntr;
}
else
{
tcb_g_p_currentTaskBlock->sleepCntr = ((U4)SCH_MAX_NUM_TICK - u4_s_tickCntr) + nextWakeTime;
}
tcb_g_p_currentTaskBlock->flags |= (U1)SCH_TASK_FLAG_STS_SLEEP;
/* Switch to an active task */
vd_OSsch_setNextReadyTaskToRun();
OS_CPU_TRIGGER_DISPATCHER();
/* Resume tick interrupts and enable context switch interrupt. */
OS_CPU_EXIT_CRITICAL();
return(u4_s_tickCntr);
}
/*************************************************************************/
/* Function Name: vd_OSsch_taskWake */
/* Purpose: Wake specified task from sleep or suspended state. */
/* Arguments: U1 taskID: */
/* Task ID to be woken from sleep or suspend state. */
/* Return: N/A */
/*************************************************************************/
void vd_OSsch_taskWake(U1 taskID)
{
OS_CPU_ENTER_CRITICAL();
/* Check that task is not already in ready state. */
if(Node_s_ap_mapTaskIDToTCB[taskID]->TCB->flags & (U1)SCH_TASK_FLAG_STS_CHECK)
{
/* If task is blocked on resource, then tell resource that task has timed out. */
if(Node_s_ap_mapTaskIDToTCB[taskID]->TCB->resource != SCH_NULL_PTR)
{
vd_OSsch_taskSleepTimeoutHandler(Node_s_ap_mapTaskIDToTCB[taskID]->TCB);
}
else
{
/* Task not blocked on resource. */
}
Node_s_ap_mapTaskIDToTCB[taskID]->TCB->sleepCntr = (U4)ZERO;
Node_s_ap_mapTaskIDToTCB[taskID]->TCB->flags &= ~((U1)(SCH_TASK_FLAG_STS_SLEEP|SCH_TASK_FLAG_STS_SUSPENDED));
#if(RTOS_CONFIG_CALC_TASK_CPU_LOAD == RTOS_CONFIG_TRUE)
/* Check if CPU was previously idle, make calculation if so. */
if(tcb_g_p_currentTaskBlock == (Node_s_ap_mapTaskIDToTCB[SCH_BG_TASK_ID]->TCB))
{
OS_s_cpuData.CPUIdlePercent.CPU_idleRunning += (u1_cpu_getPercentOfTick() - OS_s_cpuData.CPUIdlePercent.CPU_idlePrevTimestamp);
}
else {}
#endif
/* Remove task from wait list */
vd_list_removeNode(&node_s_p_headOfWaitList, Node_s_ap_mapTaskIDToTCB[taskID]);
/* Add woken task to ready queue */
vd_list_addTaskByPrio(&node_s_p_headOfReadyList, Node_s_ap_mapTaskIDToTCB[taskID]);
/* Is woken up task higher priority than current task ? */
if(node_s_p_headOfReadyList->TCB != tcb_g_p_currentTaskBlock)
{
/* Set global task pointer to new task control block */
tcb_g_p_nextTaskBlock = node_s_p_headOfReadyList->TCB;
OS_CPU_TRIGGER_DISPATCHER();
}
else
{
}
}
else
{
/* Task is not in sleep or suspended state. Do nothing. */
}/* Node_s_ap_mapTaskIDToTCB[taskID]->TCB->flags & (U1)SCH_TASK_FLAG_STS_CHECK */
OS_CPU_EXIT_CRITICAL();
}
/*************************************************************************/
/* Function Name: vd_OSsch_taskSuspend */
/* Purpose: Suspend current task for a specified amount of time. */
/* Arguments: U1 taskIndex: */
/* Task ID to be suspended. */
/* Return: N/A */
/*************************************************************************/
void vd_OSsch_taskSuspend(U1 taskIndex)
{
ListNode* node_t_p_suspendTask;
OS_CPU_ENTER_CRITICAL();
node_t_p_suspendTask = Node_s_ap_mapTaskIDToTCB[taskIndex];
if((node_t_p_suspendTask->TCB->flags & (U1)SCH_TASK_FLAG_STS_CHECK) != (U1)SCH_TASK_FLAG_STS_SUSPENDED)
{
Node_s_ap_mapTaskIDToTCB[taskIndex]->TCB->flags |= (U1)SCH_TASK_FLAG_STS_SUSPENDED;
vd_list_removeNode(&node_s_p_headOfReadyList, node_t_p_suspendTask);
vd_list_addNodeToEnd(&node_s_p_headOfWaitList, node_t_p_suspendTask);
}
else{}
/* Is task suspending itself or another task? */
if(node_t_p_suspendTask->TCB == tcb_g_p_currentTaskBlock)
{
/* Switch to an active task */
tcb_g_p_nextTaskBlock = node_s_p_headOfReadyList->TCB;
OS_CPU_TRIGGER_DISPATCHER();
}
else{}
/* Resume tick interrupts and enable context switch interrupt. */
OS_CPU_EXIT_CRITICAL();
}
/*************************************************************************/
/* Function Name: vd_OSsch_suspendScheduler */
/* Purpose: Turn off scheduler interrupts and reset ticker. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
void vd_OSsch_suspendScheduler(void)
{
vd_cpu_suspendScheduler();
}
/*************************************************************************/
/* Function Name: vd_OSsch_systemTick_ISR */
/* Purpose: Handle system tick operations and run scheduler. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
__irq void vd_OSsch_systemTick_ISR(void)
{
U1 u1_t_prioMask;
u1_t_prioMask = u1_OSsch_interruptEnter();
/* Increment ticks but cap at max (0xFFFFFFFF rounded down to nearest 100). */
u4_s_tickCntr = (u4_s_tickCntr + 1) % (U4)SCH_MAX_NUM_TICK;
#if(RTOS_CONFIG_CALC_TASK_CPU_LOAD == RTOS_CONFIG_TRUE)
/* Check if CPU was previously idle, make calculation if so. */
if(tcb_g_p_currentTaskBlock == (Node_s_ap_mapTaskIDToTCB[SCH_BG_TASK_ID]->TCB))
{
OS_s_cpuData.CPUIdlePercent.CPU_idleRunning += ((U1)SCH_ONE_HUNDRED_PERCENT - OS_s_cpuData.CPUIdlePercent.CPU_idlePrevTimestamp);
}
else{}
if((u4_s_tickCntr % (U4)SCH_HUNDRED_TICKS) == (U4)ZERO)
{
OS_s_cpuData.CPUIdlePercent.CPU_idleAvg = (U1)(OS_s_cpuData.CPUIdlePercent.CPU_idleRunning/(U4)SCH_HUNDRED_TICKS);
OS_s_cpuData.CPUIdlePercent.CPU_idleRunning = (U1)ZERO;
}
else{}
OS_s_cpuData.CPUIdlePercent.CPU_idlePrevTimestamp = (U1)ZERO;
#endif
vd_OSsch_periodicScheduler();
/* Resume tick interrupts and enable context switch interrupt. */
vd_OSsch_interruptExit(u1_t_prioMask);
}
/*************************************************************************/
/* Function Name: vd_OSsch_setNextReadyTaskToRun */
/* Purpose: Select next task to run. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
static void vd_OSsch_setNextReadyTaskToRun(void)
{
ListNode* node_t_p_moveToWaitList;
/* Remove node of task that was previously executing */
node_t_p_moveToWaitList = node_list_removeFirstNode(&node_s_p_headOfReadyList);
/* Move previous node to wait list */
vd_list_addNodeToFront(&node_s_p_headOfWaitList, node_t_p_moveToWaitList);
tcb_g_p_nextTaskBlock = node_s_p_headOfReadyList->TCB;
}
/*************************************************************************/
/* Function Name: vd_OSsch_taskSleepTimeoutHandler */
/* Purpose: Tell resources that blocked task has timed out. */
/* Arguments: Sch_Task* taskTCB: */
/* Pointer to task control block. */
/* Return: N/A */
/*************************************************************************/
static void vd_OSsch_taskSleepTimeoutHandler(Sch_Task* taskTCB)
{
/* Task has timed out. Determine if due to manual sleep or resource */
switch(taskTCB->flags & (U1)SCH_TASK_RESOURCE_SLEEP_CHECK_MASK)
{
/* Remove task from resource's blocked list */
#if(RTOS_CFG_OS_MAILBOX_ENABLED == RTOS_CONFIG_TRUE)
case (U1)SCH_TASK_FLAG_SLEEP_MBOX:
vd_OSmbox_blockedTaskTimeout((Mailbox*)taskTCB->resource);
taskTCB->resource = (void*)NULL;
break;
#endif
#if(RTOS_CFG_OS_QUEUE_ENABLED == RTOS_CONFIG_TRUE)
case (U1)SCH_TASK_FLAG_SLEEP_QUEUE:
vd_OSqueue_blockedTaskTimeout((Queue*)taskTCB->resource, taskTCB);
taskTCB->resource = (void*)NULL;
break;
#endif
#if(RTOS_CFG_OS_SEMAPHORE_ENABLED == RTOS_CONFIG_TRUE)
case (U1)SCH_TASK_FLAG_SLEEP_SEMA:
vd_OSsema_blockedTimeout((Semaphore*)taskTCB->resource, taskTCB);
taskTCB->resource = (void*)NULL;
break;
#endif
#if(RTOS_CFG_OS_FLAGS_ENABLED == RTOS_CONFIG_TRUE)
case (U1)SCH_TASK_FLAG_SLEEP_FLAGS:
vd_OSflags_pendTimeout((FlagsObj*)taskTCB->resource, taskTCB);
taskTCB->resource = (void*)NULL;
break;
#endif
#if(RTOS_CFG_OS_MUTEX_ENABLED == RTOS_CONFIG_TRUE)
case (U1)SCH_TASK_FLAG_SLEEP_MUTEX:
vd_OSmutex_blockedTimeout((Mutex*)taskTCB->resource, taskTCB);
taskTCB->resource = (void*)NULL;
break;
#endif
case (U1)ZERO:
/* Manual sleep time out */
break;
default:
OSTaskFault(); /* If code execution reaches this point it is a bug */
break;
}
}
/*************************************************************************/
/* Function Name: vd_OSsch_periodicScheduler */
/* Purpose: Scheduler algorithm called to check if task is ready. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
static void vd_OSsch_periodicScheduler(void)
{
ListNode* node_t_p_check;
ListNode* node_t_p_changeListNode;
Sch_Task* tcb_t_p_currentTCB;
if(node_s_p_headOfWaitList == (ListNode*)NULL)
{
/* No tasks to process. Return immediately. */
}
else
{
node_t_p_check = node_s_p_headOfWaitList;
/* Check each node that is not suspended. Suspended tasks always held at end of waiting list */
while(node_t_p_check != (ListNode*)NULL)
{
tcb_t_p_currentTCB = node_t_p_check->TCB;
if(tcb_t_p_currentTCB->flags & (U1)SCH_TASK_FLAG_STS_SUSPENDED)
{
/* All waiting tasks have been checked */
break;
}
/* Decrement sleep counter and check if zero */
else if((--(tcb_t_p_currentTCB->sleepCntr) == (U1)ZERO))
{
#if(RTOS_RESOURCES_CONFIGURED)
vd_OSsch_taskSleepTimeoutHandler(tcb_t_p_currentTCB);
#endif
/* Update flags and wake reason to TIMEOUT */
tcb_t_p_currentTCB->wakeReason = (U1)SCH_TASK_WAKEUP_SLEEP_TIMEOUT;
tcb_t_p_currentTCB->flags &= ~((U1)(SCH_TASK_FLAG_STS_SLEEP | SCH_TASK_RESOURCE_SLEEP_CHECK_MASK));
/* Save node to be moved to ready list */
node_t_p_changeListNode = node_t_p_check;
/* Move to next node in wait list */
node_t_p_check = node_t_p_check->nextNode;
/* Remove from waiting list and add to ready queue by priority. */
vd_list_removeNode(&node_s_p_headOfWaitList, node_t_p_changeListNode);
vd_list_addTaskByPrio(&node_s_p_headOfReadyList, node_t_p_changeListNode);
}
else
{
/* Move to next node in wait list */
node_t_p_check = node_t_p_check->nextNode;
}
}
/* Is first task in ready queue the same as before tick? */
if(node_s_p_headOfReadyList->TCB == tcb_g_p_currentTaskBlock)
{
/* Do nothing, return to current task. */
}
else
{
/* Set global task pointer to new task control block */
tcb_g_p_nextTaskBlock = node_s_p_headOfReadyList->TCB;
/* Set bit for pendSV to run when CPU is ready */
OS_CPU_TRIGGER_DISPATCHER();
}
} /* node_s_p_headOfWaitList == NULL */
}
/*************************************************************************/
/* Function Name: vd_OSsch_background */
/* Purpose: Background task when no others are scheduled. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
static void vd_OSsch_background(void)
{
U1 u1_t_index;
for(;;)
{
#if(RTOS_CONFIG_ENABLE_STACK_OVERFLOW_DETECT == RTOS_CONFIG_TRUE)
for(u1_t_index = ZERO; u1_t_index < u1_s_numTasks; u1_t_index++)
{
if(u1_sch_checkStack(u1_t_index))
{
OSTaskFault();
}
else{}
}
#endif
#if(RTOS_CFG_OS_MEM_ENABLED == RTOS_CONFIG_TRUE)
if(u1_OSMem_maintenance())
{
OSTaskFault();
}
else{}
#endif
#if (RTOS_CONFIG_CALC_TASK_CPU_LOAD == RTOS_CONFIG_TRUE)
OS_s_cpuData.CPUIdlePercent.CPU_idlePrevTimestamp = u1_cpu_getPercentOfTick();
#endif
#if(RTOS_CONFIG_ENABLE_BACKGROUND_IDLE_SLEEP == RTOS_CONFIG_TRUE)
#if(RTOS_CONFIG_PRESLEEP_FUNC == RTOS_CONFIG_TRUE || RTOS_CONFIG_POSTSLEEP_FUNC == RTOS_CONFIG_TRUE)
u1_s_sleepState = (U1)SCH_CPU_SLEEPING;
#endif
#if(RTOS_CONFIG_PRESLEEP_FUNC == RTOS_CONFIG_TRUE)
/* pre-sleep hook function defined by application */
app_OSPreSleepFcn();
#endif
WaitForInterrupt();
#endif
}
}
/*************************************************************************/
/* Function Name: u1_sch_checkStack */
/* Purpose: Check watermark on task stacks. */
/* Arguments: U1 taskIndex: */
/* Task ID to be checked. */
/* Return: SCH_TRUE or SCH_FALSE */
/*************************************************************************/
#if(RTOS_CONFIG_ENABLE_STACK_OVERFLOW_DETECT == RTOS_CONFIG_TRUE)
static U1 u1_sch_checkStack(U1 taskIndex)
{
return(*SchTask_s_as_taskList[taskIndex].topOfStack != (OS_STACK)SCH_TOP_OF_STACK_MARK);
}
#endif
/***********************************************************************************************/
/* History */
/***********************************************************************************************/
/* Version Date Description */
/* */
/* 0.1 2/9/19 Basic time-sharing functionality implemented. Processes up */
/* to five tasks according to their period and sequence. */
/* */
/* 0.2 2/12/19 Took timer/interrupt operations and combined into */
/* timeHandler module. Has since been migrated into CPU IF mod. */
/* */
/* 1.0 2/28/19 First implementation of pre-emptive scheduler. */
/* */
/* 1.1 3/2/19 Changes to scheduling algorithm. Priority-based instead of */
/* time-based, added blocking and yielding APIs for tasks. */
/* */
/* 1.2 3/25/19 Resolved scheduler bug in which a lower priority task would */
/* not have its sleep timer decremented on a SysTick interrupt */
/* if a higher priority task was ready to run. */
/* */
/* 1.3 5/20/19 Added members to TCB to track which resource task is blocked */
/* on. Scheduler calls APIs to remove task ID from resource */
/* block list. */
/* */
/* 1.4 5/21/19 Added TCB member and public API to track task wakeup reason. */
/* Application can now determine if task woke up due to timeout,*/
/* or a resource became available. */
/* */
/* 1.5 6/9/19 Added stack overflow detection. */
/* */
/* 1.6 6/9/19 Added u4_OSsch_taskSleepSetFreq to support task execution at */
/* set frequencies. */
/* */
/* 1.7 6/22/19 Added API to get CPU load during runtime. */
/* */
/* 1.8 7/13/19 Added hook functions for pre-sleep, post-sleep. */
/* */
/* 2.0 7/20/19 Redesigned scheduler from array-based with static priorities */
/* to using linked-lists and dynamic priorities (user can change*/
/* during runtime). Uses ready queue, waiting list, and an array*/
/* to map task ID (priority) used in APIs --> linked list node. */
/* */
/* 2.1 7/29/19 vd_OSsch_taskWake() call removed from */
/* vd_OSsch_setReasonForWakeup() to save space on call stack. */
/* When vd_OSsch_setReasonForWakeup() is called by an internal */
/* module, it must also now call vd_OSsch_taskWake(). */
/* -Note: These two function calls must occur in the same */
/* critical section. */
/* */
/* Removed getCurrentTCB() and replaced with #define in */
/* sch_internal_F.h */
/* */
/* 2.2 8/19/19 Fixed minor bugs in CPU load calculation. */
/* */
/* 2.3 8/27/19 Integrated memory module. */
/* */
/* 2.4 5/3/20 Changed SCH_BG_TASK_ID from ZERO to (SCH_MAX_NUM_TASKS - 1) */
/* to so that task ID zero is available (to match priorities). */
/* */
/* 2.5 5/4/20 Changing SCH_BG_TASK_ID caused bug in CPU load calculation. */
/* Bug is now resolved. */
|
gscultho/HuskEOS | huskEOS/Queue/Header/queue_internal_IF.h | <gh_stars>1-10
/*************************************************************************/
/* File Name: queue_internal_IF.h */
/* Purpose: Kernel access definitions and routines for FIFO. */
/* Created by: <NAME> on 5/25/19 */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#ifndef queue_internal_IF_h
#define queue_internal_IF_h
#include "rtos_cfg.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
/*************************************************************************/
/* Data Types */
/*************************************************************************/
struct listNode; /* Forward declaration. Defined in "listMgr_internal.h" */
typedef struct BlockedList
{
struct ListNode blockedTasks[RTOS_CFG_MAX_NUM_BLOCKED_TASKS_FIFO];
struct ListNode* blockedListHead;
}
BlockedList;
typedef struct Queue
{
Q_MEM* startPtr; /* First memory address of FIFO. */
Q_MEM* endPtr; /* Last memory address of FIFO. */
Q_MEM* putPtr; /* Next data sent will be put here. */
Q_MEM* getPtr; /* Next get() call will take data from here. */
BlockedList blockedTaskList; /* Structure to track blocked tasks. */
}
Queue;
/*************************************************************************/
/* Public Functions */
/*************************************************************************/
/*************************************************************************/
/* Function Name: vd_OSqueue_blockedTaskTimeout */
/* Purpose: Update block list if a task times out on its block. */
/* Called internally by scheduler. */
/* Arguments: Queue* queueAddr */
/* Address of queue structure. */
/* Sch_Task* taskTCB: */
/* TCB address of blocked task. */
/* Return: N/A */
/*************************************************************************/
void vd_OSqueue_blockedTaskTimeout(Queue* queueAddr, struct Sch_Task* taskTCB);
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
#endif
|
gscultho/HuskEOS | huskEOS/Flags/Source/flags.c | <gh_stars>1-10
/*************************************************************************/
/* File Name: flags.c */
/* Purpose: Flags services for application layer tasks. */
/* Created by: <NAME> on 3/24/19. */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#include "rtos_cfg.h"
#if(RTOS_CFG_OS_FLAGS_ENABLED == RTOS_CONFIG_TRUE)
/*************************************************************************/
/* Includes */
/*************************************************************************/
#include "flags_internal_IF.h"
#include "flags.h"
#include "sch_internal_IF.h"
#include "sch.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define FLAGS_RESET_VALUE (0x00)
#define FLAGS_NULL_PTR ((void*)ZERO)
#define FLAGS_EVENT_TYPE_MIN_VALID (1)
#define FLAGS_EVENT_TYPE_MAX_VALID (2)
/*************************************************************************/
/* External References */
/*************************************************************************/
extern void OSTaskFault(void);
/*************************************************************************/
/* Static Global Variables, Constants */
/*************************************************************************/
static FlagsObj flags_s_flagsList[RTOS_CFG_NUM_FLAG_OBJECTS];
/*************************************************************************/
/* Private Function Prototypes */
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/* Function Name: u1_OSflags_init */
/* Purpose: Initialize flags object. */
/* Arguments: OSFlagsObj** flags: */
/* Address of flags object. */
/* U1 flagInitValues: */
/* Initial values for flags. */
/* Return: U1: FLAGS_NO_OBJ_AVAILABLE OR */
/* FLAGS_INIT_SUCCESS */
/*************************************************************************/
U1 u1_OSflags_init(OSFlagsObj** flags, U1 flagInitValues)
{
U1 u1_t_index;
U1 u1_t_returnSts;
static U1 u1_s_numFlagsAllocated = (U1)ZERO;
u1_t_returnSts = (U1)FLAGS_NO_OBJ_AVAILABLE;
OS_SCH_ENTER_CRITICAL();
/* Have flags pointer point to available object. */
if(u1_s_numFlagsAllocated < (U1)RTOS_CFG_NUM_FLAG_OBJECTS)
{
(*flags) = &flags_s_flagsList[u1_s_numFlagsAllocated];
++u1_s_numFlagsAllocated;
(*flags)->flags = flagInitValues;
for(u1_t_index = (U1)ZERO; u1_t_index < (U1)RTOS_CFG_MAX_NUM_TASKS_PEND_FLAGS; u1_t_index++)
{
(*flags)->pendingList[u1_t_index].event = (U1)ZERO;
(*flags)->pendingList[u1_t_index].tcb = FLAGS_NULL_PTR;
(*flags)->pendingList[u1_t_index].eventPendType = (U1)ZERO;
}
u1_t_returnSts = (U1)FLAGS_INIT_SUCCESS;
}
else
{
}
OS_SCH_EXIT_CRITICAL();
return (u1_t_returnSts);
}
/*************************************************************************/
/* Function Name: u1_OSflags_postFlags */
/* Purpose: Write to flags object as specified. */
/* Arguments: OSFlagsObj* flags: */
/* Pointer to flags object. */
/* U1 flagMask: */
/* Mask to set/clear. */
/* U1 set_clear: */
/* FLAGS_WRITE_SET OR */
/* FLAGS_WRITE_CLEAR */
/* Return: U4 FLAGS_WRITE_COMMAND_INVALID OR */
/* FLAGS_WRITE_SUCCESS */
/*************************************************************************/
U1 u1_OSflags_postFlags(OSFlagsObj* flags, U1 flagMask, U1 set_clear)
{
U1 u1_t_returnSts;
U1 u1_t_index;
OS_CPU_ENTER_CRITICAL();
if(set_clear == (U1)FLAGS_WRITE_SET)
{
flags->flags |= flagMask;
u1_t_returnSts = (U1)FLAGS_WRITE_SUCCESS;
}
else if(set_clear == (U1)FLAGS_WRITE_CLEAR)
{
flags->flags &= ~(flagMask);
u1_t_returnSts = (U1)FLAGS_WRITE_SUCCESS;
}
else
{
/* Default return status */
u1_t_returnSts = (U1)FLAGS_WRITE_COMMAND_INVALID;
}
if(u1_t_returnSts == (U1)FLAGS_WRITE_SUCCESS)
{
/* Check if there is a task waiting on event. */
for(u1_t_index = (U1)ZERO; u1_t_index < (U1)FLAGS_MAX_NUM_TASKS_PENDING; u1_t_index++)
{
if(flags->pendingList[u1_t_index].tcb != FLAGS_NULL_PTR)
{
switch(flags->pendingList[u1_t_index].eventPendType)
{
case (U1)FLAGS_EVENT_ANY:
if((flags->pendingList[u1_t_index].event & flags->flags) != (U1)ZERO)
{
/* Notify scheduler to change task state. If woken task is higher priority than running task, context switch will occur after critical section. */
vd_OSsch_taskWake(flags->pendingList[u1_t_index].tcb->taskID);
/* Wake up task and notify scheduler of reason. */
vd_OSsch_setReasonForWakeup((U1)(flags->flags), (flags->pendingList[u1_t_index].tcb));
/* Clear data in flags object. */
flags->pendingList[u1_t_index].event = (U1)ZERO;
flags->pendingList[u1_t_index].tcb = FLAGS_NULL_PTR;
flags->pendingList[u1_t_index].eventPendType = (U1)ZERO;
}
else
{
}
break;
case (U1)FLAGS_EVENT_EXACT:
if((flags->pendingList[u1_t_index].event & flags->flags) == flags->flags)
{
/* Wake up task and notify scheduler of reason. */
vd_OSsch_setReasonForWakeup((U1)(flags->flags), (flags->pendingList[u1_t_index].tcb));
/* Notify scheduler to change task state. If woken task is higher priority than running task, context switch will occur after critical section. */
vd_OSsch_taskWake(flags->pendingList[u1_t_index].tcb->taskID);
/* Clear data in flags object. */
flags->pendingList[u1_t_index].event = (U1)ZERO;
flags->pendingList[u1_t_index].tcb = FLAGS_NULL_PTR;
flags->pendingList[u1_t_index].eventPendType = (U1)ZERO;
}
else
{
}
break;
default: /* Only occurs if there is data corruption. */
OSTaskFault();
break;
}/* End switch{} */
}
else
{
}/*flags->pendingList[u1_t_index].tcb != FLAGS_NULL_PTR */
}/* End for{} */
}
else
{
}/* u1_t_returnSts = (U1)FLAGS_WRITE_SUCCESS */
OS_CPU_EXIT_CRITICAL();
return (u1_t_returnSts);
}
/*************************************************************************/
/* Function Name: u1_OSflags_pendOnFlags */
/* Purpose: Set task to pend on certain flags. When task is woken,*/
/* it can retrieve the waking event by calling */
/* u1_OSsch_getReasonForWakeup() */
/* */
/* Arguments: OSFlagsObj* flags: */
/* Pointer to flags object. */
/* U1 eventMask: */
/* Event that will cause wakeup. */
/* U4 timeOut: */
/* Maximum wait time. If 0, then wait is indefinite.*/
/* U1 eventType: */
/* Type of event - FLAGS_EVENT_ANY, */
/* FLAGS_EVENT_EXACT */
/* */
/* Return: U1: FLAGS_PEND_LIST_FULL OR */
/* FLAGS_PEND_SUCCESS */
/*************************************************************************/
U1 u1_OSflags_pendOnFlags(OSFlagsObj* flags, U1 eventMask, U4 timeOut, U1 eventType)
{
U1 u1_t_returnSts;
U1 u1_t_index;
u1_t_returnSts = (U1)FLAGS_PEND_LIST_FULL;
if((eventType >= (U1)FLAGS_EVENT_TYPE_MIN_VALID) && (eventType <= (U1)FLAGS_EVENT_TYPE_MAX_VALID))
{
OS_CPU_ENTER_CRITICAL();
/* Check if there is a task waiting on event. */
for(u1_t_index = (U1)ZERO; u1_t_index < (U1)FLAGS_MAX_NUM_TASKS_PENDING; u1_t_index++)
{
if(flags->pendingList[u1_t_index].tcb == FLAGS_NULL_PTR)
{
u1_t_returnSts = (U1)FLAGS_PEND_SUCCESS;
/* Set event conditions */
flags->pendingList[u1_t_index].event = eventMask;
flags->pendingList[u1_t_index].tcb = SCH_CURRENT_TCB_ADDR;
flags->pendingList[u1_t_index].eventPendType = eventType;
/* If indefinite timeout */
if(timeOut == (U4)ZERO)
{
vd_OSsch_taskSuspend(SCH_CURRENT_TASK_ID);
}
/* If defined timeout */
else
{
/* Notify scheduler the reason for sleep state. */
vd_OSsch_setReasonForSleep(flags, (U1)SCH_TASK_SLEEP_RESOURCE_FLAGS, timeOut);
}
break; /* Break loop */
}
else
{
}/* flags->pendingList[u1_t_index].tcb == FLAGS_NULL_PTR */
}/* End for{} */
OS_CPU_EXIT_CRITICAL();
}
else
{
}/* if eventType */
return (u1_t_returnSts);
}
/*************************************************************************/
/* Function Name: vd_OSflags_pendTimeout */
/* Purpose: Timeout hander for pending task. Called by scheduler. */
/* Arguments: FlagsObj* flags: */
/* Pointer to flags object. */
/* Sch_Task pendingTCB: */
/* Pointer to timed out task's TCB. */
/* Return: N/A */
/*************************************************************************/
void vd_OSflags_pendTimeout(FlagsObj* flags, struct Sch_Task* pendingTCB)
{
U1 u1_t_index;
OS_CPU_ENTER_CRITICAL();
/* Check if there is a task waiting on event. */
for(u1_t_index = (U1)ZERO; u1_t_index < (U1)FLAGS_MAX_NUM_TASKS_PENDING; u1_t_index++)
{
if(flags->pendingList[u1_t_index].tcb == pendingTCB)
{
flags->pendingList[u1_t_index].tcb = FLAGS_NULL_PTR;
flags->pendingList[u1_t_index].event = (U1)ZERO;
flags->pendingList[u1_t_index].eventPendType = (U1)ZERO;
}
else
{
}
}/* End for{} */
OS_CPU_EXIT_CRITICAL();
}
/*************************************************************************/
/* Function Name: vd_OSflags_reset */
/* Purpose: Reset flags object to init state. */
/* Arguments: OSFlagsObj* flags: */
/* Pointer to flags object. */
/* Return: N/A */
/*************************************************************************/
void vd_OSflags_reset(OSFlagsObj* flags)
{
U1 u1_t_index;
OS_CPU_ENTER_CRITICAL();
flags->flags = (U1)FLAGS_RESET_VALUE;
/* Check if there is a task waiting on event. Clear the spot if so. */
for(u1_t_index = (U1)ZERO; u1_t_index < (U1)FLAGS_MAX_NUM_TASKS_PENDING; u1_t_index++)
{
if(flags->pendingList[u1_t_index].tcb != FLAGS_NULL_PTR)
{
vd_OSsch_taskWake(flags->pendingList[u1_t_index].tcb->taskID);
vd_OSsch_setReasonForWakeup((U1)SCH_TASK_WAKEUP_FLAGS_EVENT, (flags->pendingList[u1_t_index].tcb));
flags->pendingList[u1_t_index].tcb = FLAGS_NULL_PTR;
flags->pendingList[u1_t_index].event = (U1)ZERO;
flags->pendingList[u1_t_index].eventPendType = (U1)ZERO;
}
else
{
}
}/* End for{} */
OS_CPU_EXIT_CRITICAL();
}
/*************************************************************************/
/* Function Name: vd_OSflags_clearAll */
/* Purpose: Clear all flags. */
/* Arguments: OSFlagsObj* flags: */
/* Pointer to flags object. */
/* Return: N/A */
/*************************************************************************/
void vd_OSflags_clearAll(OSFlagsObj* flags)
{
OS_CPU_ENTER_CRITICAL();
flags->flags = (U1)FLAGS_RESET_VALUE;
OS_CPU_EXIT_CRITICAL();
}
/*************************************************************************/
/* Function Name: u1_flags_checkFlags */
/* Purpose: Check flags but do not modify. */
/* Arguments: OSFlagsObj* flags: */
/* Pointer to flags object. */
/* Return: U1 u1_t_returnVal: */
/* Value of flags at time they were read. */
/*************************************************************************/
U1 u1_OSflags_checkFlags(OSFlagsObj* flags)
{
U1 u1_t_returnVal;
OS_CPU_ENTER_CRITICAL();
u1_t_returnVal = (U1)(flags->flags);
OS_CPU_EXIT_CRITICAL();
return (u1_t_returnVal);
}
#endif /* Conditional compile */
/***********************************************************************************************/
/* History */
/***********************************************************************************************/
/* Version Date Description */
/* */
/* 0.1 3/25/19 Initial implementation of flags module. */
/* */
/* 0.2 5/23/19 Added pend API and necessary handling. */
/* */
/* 1.0 7/29/19 Re-wrote flags module to handle a user-configured number of */
/* tasks that can pend on each flags object. */
|
gscultho/HuskEOS | huskEOS/Flags/Header/flags.h | /*************************************************************************/
/* File Name: flags.h */
/* Purpose: Public header file for flags module. */
/* Created by: <NAME> on 3/24/19 */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#ifndef flags_h
#if(RTOS_CFG_OS_FLAGS_ENABLED == RTOS_CONFIG_TRUE)
#define flags_h
#include "rtos_cfg.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define FLAGS_WRITE_SET (1)
#define FLAGS_WRITE_CLEAR (0)
#define FLAGS_WRITE_COMMAND_INVALID (255)
#define FLAGS_WRITE_SUCCESS (1)
#define FLAGS_NO_OBJ_AVAILABLE (0)
#define FLAGS_INIT_SUCCESS (1)
#define FLAGS_PEND_LIST_FULL (0)
#define FLAGS_PEND_SUCCESS (1)
#define FLAGS_EVENT_ANY (1)
#define FLAGS_EVENT_EXACT (2)
/*************************************************************************/
/* Data Types */
/*************************************************************************/
typedef struct FlagsObj OSFlagsObj;
/*************************************************************************/
/* Public Functions */
/*************************************************************************/
/*************************************************************************/
/* Function Name: u1_OSflags_init */
/* Purpose: Initialize flags object. */
/* Arguments: OSFlagsObj** flags: */
/* Address of flags object. */
/* U1 flagInitValues: */
/* Initial values for flags. */
/* Return: U1: FLAGS_NO_OBJ_AVAILABLE OR */
/* FLAGS_INIT_SUCCESS */
/*************************************************************************/
U1 u1_OSflags_init(OSFlagsObj** flags, U1 flagInitValues);
/*************************************************************************/
/* Function Name: u1_OSflags_postFlags */
/* Purpose: Write to flags object as specified. */
/* Arguments: OSFlagsObj* flags: */
/* Pointer to flags object. */
/* U1 flagMask: */
/* Mask to set/clear. */
/* U1 set_clear: */
/* FLAGS_WRITE_SET OR */
/* FLAGS_WRITE_CLEAR */
/* Return: U4 FLAGS_WRITE_COMMAND_INVALID OR */
/* FLAGS_WRITE_SUCCESS */
/*************************************************************************/
U1 u1_OSflags_postFlags(OSFlagsObj* flags, U1 flagMask, U1 set_clear);
/*************************************************************************/
/* Function Name: u1_OSflags_pendOnFlags */
/* Purpose: Set task to pend on certain flags. When task is woken,*/
/* it can retrieve the waking event by calling */
/* u1_OSsch_getReasonForWakeup() */
/* */
/* Arguments: OSFlagsObj* flags: */
/* Pointer to flags object. */
/* U1 eventMask: */
/* Event that will cause wakeup. */
/* U4 timeOut: */
/* Maximum wait time. If 0, then wait is indefinite.*/
/* U1 eventType: */
/* Type of event - FLAGS_EVENT_ANY, */
/* FLAGS_EVENT_EXACT */
/* */
/* Return: U1: FLAGS_PEND_LIST_FULL OR */
/* FLAGS_PEND_SUCCESS */
/*************************************************************************/
U1 u1_OSflags_pendOnFlags(OSFlagsObj* flags, U1 eventMask, U4 timeOut, U1 eventType);
/*************************************************************************/
/* Function Name: vd_OSflags_reset */
/* Purpose: Reset flags object to init state. */
/* Arguments: OSFlagsObj* flags: */
/* Pointer to flags object. */
/* Return: N/A */
/*************************************************************************/
void vd_OSflags_reset(OSFlagsObj* flags);
/*************************************************************************/
/* Function Name: vd_OSflags_clearAll */
/* Purpose: Clear all flags. */
/* Arguments: OSFlagsObj* flags: */
/* Pointer to flags object. */
/* Return: N/A */
/*************************************************************************/
void vd_OSflags_clearAll(OSFlagsObj* flags);
/*************************************************************************/
/* Function Name: u1_flags_checkFlags */
/* Purpose: Check flags but do not modify. */
/* Arguments: OSFlagsObj* flags: */
/* Pointer to flags object. */
/* Return: U1 u1_t_returnVal: */
/* Value of flags at time they were read. */
/*************************************************************************/
U1 u1_OSflags_checkFlags(OSFlagsObj* flags);
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
#else
#warning "FLAGS MODULE NOT ENABLED"
#endif /* Conditional compile */
#endif
|
gscultho/HuskEOS | huskEOS/Schedule/Header/sch.h | <gh_stars>1-10
/*************************************************************************/
/* File Name: sch.h */
/* Purpose: Header file for scheduler module. */
/* Created by: <NAME> on 2/9/19. */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#ifndef sch_h
#define sch_h
#include "cpu_os_interface.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define SCH_TASK_CREATE_SUCCESS (1)
#define SCH_TASK_CREATE_DENIED (0)
#define SCH_BG_TASK_STACK_SIZE (RTOS_CONFIG_BG_TASK_STACK_SIZE)
/* Task wakeup reasons */
#define SCH_TASK_WAKEUP_SLEEP_TIMEOUT (0x00)
#define SCH_TASK_NO_WAKEUP_SINCE_LAST_CHECK (0xFF)
#define SCH_TASK_WAKEUP_MBOX_READY (0x01)
#define SCH_TASK_WAKEUP_QUEUE_READY (0x02)
#define SCH_TASK_WAKEUP_SEMA_READY (0x03)
#define SCH_TASK_WAKEUP_FLAGS_EVENT (0x04)
#define SCH_TASK_WAKEUP_MUTEX_READY (0x05)
/*************************************************************************/
/* Function Name: OS_SCH_ENTER_CRITICAL */
/* Purpose: Critical section enter. Supports nesting. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
#define OS_SCH_ENTER_CRITICAL(void) (OS_CPU_ENTER_CRITICAL(void))
/*************************************************************************/
/* Function Name: OS_SCH_EXIT_CRITICAL */
/* Purpose: Critical section exit. Supports nesting. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
#define OS_SCH_EXIT_CRITICAL(void) (OS_CPU_EXIT_CRITICAL(void))
/*************************************************************************/
/* Function Name: u1_OSsch_maskInterrupts */
/* Purpose: Masks RTOS interrupts only. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
#define u1_OSsch_maskInterrupts(c) (OS_CPU_MASK_SCHEDULER_TICK(c))
/*************************************************************************/
/* Function Name: vd_OSsch_unmaskInterrupts */
/* Purpose: Unmasks RTOS interrupts and restores previous mask. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
#define vd_OSsch_unmaskInterrupts(c) (OS_CPU_UNMASK_SCHEDULER_TICK(c))
/*************************************************************************/
/* Data Types */
/*************************************************************************/
/*************************************************************************/
/* Public Functions */
/*************************************************************************/
/*************************************************************************/
/* Function Name: vd_OS_init */
/* Purpose: Initialize scheduler module and configured RTOS */
/* modules. */
/* Arguments: U4 numMsPeriod: */
/* Sets scheduler tick rate in milliseconds. */
/* Return: N/A */
/*************************************************************************/
void vd_OS_init(U4 numMsPeriod);
/*************************************************************************/
/* Function Name: u1_OSsch_createTask */
/* Purpose: Create new task in list. */
/* Arguments: void* newTaskFcn: */
/* Function pointer to task routine. */
/* void* sp: */
/* Pointer to bottom of task stack (highest mem. */
/* address). */
/* U4 sizeOfStack: */
/* Size of task stack. */
/* U1 priority: */
/* Unique priority level for task. 0 = highest. */
/* U1 taskID: */
/* Task ID to refer to task when using APIs (cannot*/
/* be changed). Value must be between 0 and the */
/* total number of application tasks - 1. */
/* */
/* Return: SCH_TASK_CREATE_SUCCESS OR */
/* SCH_TASK_CREATE_DENIED */
/*************************************************************************/
U1 u1_OSsch_createTask(void (*newTaskFcn)(void), void* sp, U4 sizeOfStack, U1 priority, U1 taskID);
/*************************************************************************/
/* Function Name: vd_OSsch_start */
/* Purpose: Give control to operating system. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
void vd_OSsch_start(void);
/*************************************************************************/
/* Function Name: vd_OSsch_interruptEnter */
/* Purpose: Must be called by ISRs external to OS at entry. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
U1 u1_OSsch_interruptEnter(void);
/*************************************************************************/
/* Function Name: vd_OSsch_interruptExit */
/* Purpose: Must be called by ISRs external to OS at exit. */
/* Arguments: U1 prioMaskReset: */
/* Priority mask returned by u1_OSsch_interruptEnter()*/
/* Return: N/A */
/*************************************************************************/
void vd_OSsch_interruptExit(U1 prioMaskReset);
/*************************************************************************/
/* Function Name: u1_OSsch_g_numTasks */
/* Purpose: Return current number of scheduled tasks. */
/* Arguments: N/A */
/* Return: Number of tasks: 0 - SCH_MAX_NUM_TASKS */
/*************************************************************************/
U1 u1_OSsch_g_numTasks(void);
/*************************************************************************/
/* Function Name: u4_OSsch_getCurrentTickPeriodMs */
/* Purpose: Get current period in ms for scheduler tick. */
/* Arguments: N/A */
/* Return: Tick rate in milliseconds. */
/*************************************************************************/
U4 u4_OSsch_getCurrentTickPeriodMs(void);
/*************************************************************************/
/* Function Name: u1_OSsch_getReasonForWakeup */
/* Purpose: Get most recent reason that current task has woken up.*/
/* Arguments: N/A */
/* Return: SCH_TASK_WAKEUP_SLEEP_TIMEOUT OR */
/* SCH_TASK_NO_WAKEUP_SINCE_LAST_CHECK OR */
/* SCH_TASK_WAKEUP_MBOX_READY OR */
/* SCH_TASK_WAKEUP_QUEUE_READY OR */
/* SCH_TASK_WAKEUP_SEMA_READY OR */
/* SCH_TASK_WAKEUP_FLAGS_EVENT OR */
/* SCH_TASK_WAKEUP_MUTEX_READY OR */
/* OS flags event that triggered wakeup */
/*************************************************************************/
U1 u1_OSsch_getReasonForWakeup(void);
/*************************************************************************/
/* Function Name: u4_OSsch_getTicks */
/* Purpose: Get number of ticks from scheduler. Overflows to zero.*/
/* Arguments: N/A */
/* Return: Number of scheduler ticks. */
/*************************************************************************/
U4 u4_OSsch_getTicks(void);
/*************************************************************************/
/* Function Name: u1_OSsch_getCurrentTaskID */
/* Purpose: Returns current task ID. */
/* Arguments: N/A */
/* Return: U1: Current task ID number. */
/*************************************************************************/
U1 u1_OSsch_getCurrentTaskID(void);
/*************************************************************************/
/* Function Name: u1_OSsch_getCurrentTaskPrio */
/* Purpose: Returns current task priority. */
/* Arguments: N/A */
/* Return: U1: Current task priority. */
/*************************************************************************/
U1 u1_OSsch_getCurrentTaskPrio(void);
/*************************************************************************/
/* Function Name: u1_OSsch_getCPULoad */
/* Purpose: Returns CPU load averaged over 100 ticks. */
/* Arguments: N/A */
/* Return: U1: CPU load as a percentage. */
/*************************************************************************/
#if (RTOS_CONFIG_CALC_TASK_CPU_LOAD == RTOS_CONFIG_TRUE)
U1 u1_OSsch_getCPULoad(void);
#endif
/*************************************************************************/
/* Function Name: vd_OSsch_setNewTickPeriod */
/* Purpose: Set new tick period in milliseconds. */
/* Arguments: U4 numMsReload: */
/* Period of interrupts. */
/* Return: N/A */
/*************************************************************************/
void vd_OSsch_setNewTickPeriod(U4 numMsReload);
/*************************************************************************/
/* Function Name: vd_OSsch_taskSleep */
/* Purpose: Suspend current task for a specified amount of time. */
/* Arguments: U4 u4_period: */
/* Time units to suspend for. */
/* Return: N/A */
/*************************************************************************/
void vd_OSsch_taskSleep(U4 period);
/*************************************************************************/
/* Function Name: u4_OSsch_taskSleepSetFreq */
/* Purpose: Used to set task to sleep such that task will run at a*/
/* set frequency. */
/* Arguments: U4 nextWakeTime: */
/* Time to wake up at (in ticks). */
/* Return: U4 u4_t_wakeTime: */
/* Tick value that task was most recently woken at. */
/*************************************************************************/
U4 u4_OSsch_taskSleepSetFreq(U4 nextWakeTime);
/*************************************************************************/
/* Function Name: vd_OSsch_taskWake */
/* Purpose: Wake specified task from sleep or suspended state. */
/* Arguments: U1 taskID: */
/* Task ID to be woken from sleep or suspend state. */
/* Return: N/A */
/*************************************************************************/
void vd_OSsch_taskWake(U1 taskID);
/*************************************************************************/
/* Function Name: vd_OSsch_taskSuspend */
/* Purpose: Suspend current task for a specified amount of time. */
/* Arguments: U1 taskIndex: */
/* Task ID to be suspended. */
/* Return: N/A */
/*************************************************************************/
void vd_OSsch_taskSuspend(U1 taskIndex);
/*************************************************************************/
/* Function Name: vd_OSsch_suspendScheduler */
/* Purpose: Turn off scheduler interrupts and reset ticker. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
void vd_OSsch_suspendScheduler(void);
/*************************************************************************/
/* Function Name: app_OSPreSleepFcn */
/* Purpose: Hook function. Will run before CPU put to sleep. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
#if(RTOS_CONFIG_PRESLEEP_FUNC == RTOS_CONFIG_TRUE)
void app_OSPreSleepFcn(void);
#endif
/*************************************************************************/
/* Function Name: app_OSPostSleepFcn */
/* Purpose: Hook function. Will run after CPU woken from sleep. */
/* Arguments: N/A */
/* Return: N/A */
/*************************************************************************/
#if(RTOS_CONFIG_POSTSLEEP_FUNC == RTOS_CONFIG_TRUE)
void app_OSPostSleepFcn(void);
#endif
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
#endif
|
gscultho/HuskEOS | huskEOS/Semaphore/Header/semaphore.h | /*************************************************************************/
/* File Name: semaphore.h */
/* Purpose: Header file for semaphore module. */
/* Created by: <NAME> on 3/3/19 */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#ifndef semaphore_h
#if(RTOS_CFG_OS_SEMAPHORE_ENABLED == RTOS_CONFIG_TRUE)
#define semaphore_h
#include "rtos_cfg.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
#define SEMA_SEMAPHORE_SUCCESS (1)
#define SEMA_SEMAPHORE_TAKEN (0)
#define SEMA_NO_SEMA_OBJECTS_AVAILABLE (0)
/*************************************************************************/
/* Data Types */
/*************************************************************************/
typedef struct Semaphore OSSemaphore; /* Forward declaration */
/*************************************************************************/
/* Public Functions */
/*************************************************************************/
/*************************************************************************/
/* Function Name: u1_OSsema_init */
/* Purpose: Initialize specified semaphore. */
/* Arguments: OSSemaphore** semaphore: */
/* Address of semaphore object. */
/* S1 initValue: */
/* Initial value for semsphore. */
/* Return: U1: SEMA_SEMAPHORE_SUCCESS OR */
/* SEMA_NO_SEMA_OBJECTS_AVAILABLE */
/*************************************************************************/
U1 u1_OSsema_init(OSSemaphore** semaphore, S1 initValue);
/*************************************************************************/
/* Function Name: u1_OSsema_wait */
/* Purpose: Claim semaphore referenced by pointer. */
/* Arguments: OSSemaphore* semaphore: */
/* Pointer to semaphore. */
/* U4 blockPeriod: */
/* Number of time units for task to sleep if blocked. */
/* */
/* Return: U1 SEMA_SEMAPHORE_TAKEN OR */
/* SEMA_SEMAPHORE_SUCCESS */
/*************************************************************************/
U1 u1_OSsema_wait(OSSemaphore* semaphore, U4 blockPeriod);
/*************************************************************************/
/* Function Name: u1_OSsema_check */
/* Purpose: Check status of semaphore. */
/* Arguments: OSSemaphore* semaphore: */
/* Pointer to semaphore. */
/* Return: U1 SEMA_SEMAPHORE_TAKEN OR */
/* SEMA_SEMAPHORE_SUCCESS */
/*************************************************************************/
U1 u1_OSsema_check(OSSemaphore* semaphore);
/*************************************************************************/
/* Function Name: vd_OSsema_post */
/* Purpose: Release semaphore */
/* Arguments: OSSemaphore* semaphore: */
/* Pointer to semaphore. */
/* Return: N/A */
/*************************************************************************/
void vd_OSsema_post(OSSemaphore* semaphore);
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
#else
#warning "SEMAPHORE MODULE NOT ENABLED"
#endif /* Conditional compile */
#endif
|
gscultho/HuskEOS | huskEOS/List_Manager/Header/listMgr_internal.h | <gh_stars>1-10
/*************************************************************************/
/* File Name: listMgr_internal.h */
/* Purpose: Routines for managing task lists in scheduler. */
/* Created by: <NAME> on 7/17/19. */
/* Copyright © 2019 <NAME> and <NAME>. */
/* All rights reserved. */
/*************************************************************************/
#ifndef TaskList_Node_h
#define TaskList_Node_h
#include "cpu_defs.h"
/*************************************************************************/
/* Definitions */
/*************************************************************************/
/*************************************************************************/
/* Data Types */
/*************************************************************************/
struct Sch_Task; /* Forward declaration. See definition in sch_internal_IF.h */
typedef struct ListNode
{
struct ListNode* nextNode; /* Next */
struct ListNode* previousNode; /* Prev */
struct Sch_Task* TCB; /* Data */
}
ListNode;
/*************************************************************************/
/* Public Functions */
/*************************************************************************/
/*************************************************************************/
/* Function Name: vd_list_addNodeToEnd */
/* Purpose: Add new node to end of specified linked list. */
/* Arguments: ListNode** listHead: */
/* Pointers of head node. */
/* ListNode* newNode: */
/* Node to be added to end of list. */
/* Return: N/A */
/*************************************************************************/
void vd_list_addNodeToEnd(struct ListNode** listHead, struct ListNode* newNode);
/*************************************************************************/
/* Function Name: vd_list_addTaskByPrio */
/* Purpose: Add task to a queue by order of priority. */
/* Arguments: ListNode** listHead, newNode: */
/* Pointers to head node and new node. */
/* Return: N/A */
/*************************************************************************/
void vd_list_addTaskByPrio(struct ListNode** listHead, struct ListNode* newNode);
/*************************************************************************/
/* Function Name: vd_list_addNodeToFront */
/* Purpose: Add node to front of linked list. */
/* Arguments: ListNode** listHead: */
/* Pointers to head node and new node. */
/* ListNode* newNode: */
/* Pointer to node to be added to front. */
/* Return: N/A */
/*************************************************************************/
void vd_list_addNodeToFront(struct ListNode** listHead, struct ListNode* newNode);
/*************************************************************************/
/* Function Name: vd_list_removeNode */
/* Purpose: Remove a node from linked list. */
/* Arguments: ListNode** listHead: */
/* Pointer of head node. */
/* ListNode* removeNode: */
/* Pointer to node to remove. */
/* Return: N/A */
/*************************************************************************/
void vd_list_removeNode(struct ListNode** listHead, struct ListNode* removeNode);
/*************************************************************************/
/* Function Name: node_list_removeFirstNode */
/* Purpose: Remove first node from linked list. */
/* Arguments: ListNode** listHead: */
/* Pointer of head node. */
/* Return: ListNode*: */
/* Pointer to removed node. */
/*************************************************************************/
ListNode* node_list_removeFirstNode(struct ListNode** listHead);
/*************************************************************************/
/* Function Name: node_list_removeNodeByTCB */
/* Purpose: Remove node from linked list that holds specified TCB.*/
/* Arguments: ListNode** listHead: */
/* Pointer to head node. */
/* Sch_Task* taskTCB: */
/* Pointer to TCB to be searched for. */
/* Return: ListNode*: */
/* Pointer to removed node. */
/*************************************************************************/
ListNode* node_list_removeNodeByTCB(struct ListNode** listHead, struct Sch_Task* taskTCB);
/*************************************************************************/
/* Global Variables */
/*************************************************************************/
#endif
|
rmorbach/blade | LinBLaDE/src/ProductSearch.h | /*
* ProductSearch.h
*
* Created on: Sep 18, 2012
* Author: kamyon
*/
#ifndef PRODUCTSEARCH_H_
#define PRODUCTSEARCH_H_
#include <string>
#include "ski/types.h"
#include <curl/curl.h>
#include <list>
class ProductSearch
{
protected:
/**
* Constructor
*/
ProductSearch();
public:
/**
* Destructor
* TODO: make protected after implementing the factory method as returning std::unique_ptr
* TODO: pImpl this.
*/
virtual ~ProductSearch();
/**
* Search method
*/
enum Method
{
Google_Product_Search,//!< Google Product Search
Directions_For_Me //!< Directions For Me
};
/**
* Product Information
*/
struct ProductInfo
{
/** Name */
std::string title;
/** Description */
std::string description;
/** Manufacturer */
std::string brand;
/** Combines the information as a single string */
std::string asString() const
{
std::string info;
if (!title.empty())
info += "Title: " + title + "\n";
if (!brand.empty())
info += "Brand: " + brand + "\n";
if (!description.empty())
info += "Description:" + description + "\n";
return info;
};
};
typedef std::list<ProductInfo> ProductList;
static ProductSearch* create(Method method);
/**
* Takes a barcode with identified upc and fills the product information
* @param[in] bc barcode to identify product from
* @return product information
*/
ProductList identify(const std::string &bc);
protected:
/**
* Structure to store intermediate results of http requests
*/
struct HttpResult
{
/** Pointer to actual data */
TUInt8 *data;
/** Size of data */
size_t size;
/** buffersize */
static const size_t BUFSIZE = 100000; //100K buffer
/** Constructor */
HttpResult() : data(new TUInt8[BUFSIZE]), size(0) {};
/** Destructor */
~HttpResult() {if (data != NULL) delete [] data; };
};
/** User agent to mask as */
static const char* USER_AGENT;
/**
* Initializes a cURL easy session, and sets up some common parameters
* @return handle to the initialized easy cURL session.
*/
static CURL* initializeRequest();
/**
* Prepares the cURL request for the specific lookup method
* @param[in] curl cURL session handle
* @param[in] upc upc code to look up
*/
virtual void prepareRequest(CURL* curl, const std::string &upc) = 0;
/**
* Submits a prepared request
* @param[in] curl cURL session handle
* @param[out] page a string containing the returned page that needs to be parsed.
* @return true if request has been successfully submitted, false if an error occurred.
*/
static bool submitRequest(CURL* curl, std::string &page);
/**
* Cleans up after a cURL easy session
* @param[in] cURL session handle to cleanup after
*/
virtual void cleanupAfterRequest(CURL* curl);
/**
* Callback function that saves the returned results webpage
* @param[in] buffer buffer that contains returned result
* @param[in] size size of result in units of size nmemb
* @param[in] nmemb size of each unit returned
* @param[in] pointer to user supplied field to store returned results.
*/
static size_t getReturnedResult(void *buffer, size_t size, size_t nmemb, void *userp);
/**
* Parses returned page to extract product information
* @param[in] page html page to parse
* @return information about the product
*/
virtual ProductList parseProductPage(const std::string &page) = 0;
};
//==========================
// Google Search
//==========================
class GoogleSearch: public ProductSearch
{
public:
GoogleSearch();
protected:
/** API Key*/
static const std::string API_KEY;
/** API Key*/
static const std::string SEARCH_URL;
virtual ~GoogleSearch();
void prepareRequest(CURL* curl, const std::string &upc);
ProductList parseProductPage(const std::string &page);
};
//==========================
// D4M Search
//==========================
class D4MSearch: public ProductSearch
{
public:
/** Constructor */
D4MSearch();
protected:
/** Search address */
static const std::string SEARCH_URL;
/** Referrer */
static const std::string REFERRER;
/** Destructor */
virtual ~D4MSearch();
void prepareRequest(CURL* curl, const std::string &upc);
void cleanupAfterRequest(CURL* curl);
ProductList parseProductPage(const std::string &page);
struct curl_httppost *formpost;
struct curl_httppost *lastptr;
};
#endif /* PRODUCTSEARCH_H_ */
|
rmorbach/blade | include/ski/types.h | /*
Copyright (c) 2012, The Smith-Kettlewell Eye Research Institute
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Smith-Kettlewell Eye Research Institute nor
the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE SMITH-KETTLEWELL EYE RESEARCH INSTITUTE BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file Simple type declarations.
* @author <NAME>
*/
#ifndef SKI_TYPES_H_
#define SKI_TYPES_H_
#define __STDC_CONSTANT_MACROS
#include "stdint.h"
//Simple types
typedef unsigned int TUInt;
typedef int TInt;
typedef uint8_t TUInt8;
typedef int8_t TInt8;
typedef uint16_t TUInt16;
typedef int16_t TInt16;
typedef uint32_t TUInt32;
typedef int32_t TInt32;
typedef uint64_t TUInt64;
typedef int64_t TInt64;
#endif //SKI_TYPES_H_
|
rmorbach/blade | LinBLaDE/src/iohandler.h | <reponame>rmorbach/blade
#ifndef __MAIN_H
#define __MAIN_H
/**
* @file Main class
* @author <NAME>
*/
#include "opts.h"
#include "opencv2/opencv.hpp"
using namespace std;
/**
* Main class
*/
class IOHandler{
public:
/**
* Constructor
*/
IOHandler();
/**
* Destructor
*/
virtual ~IOHandler();
/**
* Starts the processing. Based on the input options, initializes input, starts processing frame(s) and then cleans up afterwards.
* @return exit code (0 is successful, an error code otherwise).
*/
int start();
/**
* Cleanup at the end
*/
void cleanup();
private:
enum EImageMode {EColor = 1, EGray = 0, ENone = -1};
/**
* Initializes the webcam
* @return true if camera is successfully initialized
* @param[in] aCam index of camera to be initialized
*/
void initializeCamera(int aCam=0);
/**
* Initializes images
*/
void initializeImageContainers();
/**
* Releases image containers
* @param[in] isInputReleased true if input image is also to be released [default: false].
*/
void releaseImageContainers(bool isInputReleased=false);
/**
* Reads input image file
* @param[in] aFile input file to read.
* @param[in] image format (EColor, EGray or ENone, denoting as is) [Default=ENone].
* @throw errFileRead if cannot load file.
*/
void loadImage(const string &aFile, EImageMode format=ENone);
/**
* Reads input video file
* @return true if input video is successfully opened
* @param[in] aFile input file to read.
* @throw errFileRead if cannot load file.
*/
void loadVideo(const string &aFile);
/**
* Decodes video codec returned by opencv into a string
* @param aCodec codec value
* @return human-readable string containing codec name
*/
std::string getVideoCodec();
/**
* Camera loop, runs until isRunning_ = false
*/
void loop();
/**
* Gets new frames
* @param[in] image image to populate.
* @return true if frames successfully retrieved, false if reached end of video file.
*/
bool getNewFrame(cv::Mat &image);
/**
* Processes a single frame (camera frame or image file)
*/
void processFrame();
/**
* Saves an image to a file
* @param[in] image image to save.
* @param[in] filename file to save as.
* @param[in] params vector of parameters for image compression (See OpenCV documentation).
* @throw EFileWriteError if a problem occurred.
*/
void saveImage(const cv::Mat &image, const string &filename, const vector<int>& params=vector<int>() );
/**
* Initializes a video writer.
* @param[in] filename file name to save as.
* @param[in] isColor true if input is color frames.
*/
void startVideoWriter(const string &filename, bool isColor=true);
/**
* Saves a video frame to the currently initialized writer.
* @param[in] image to save
* @return error code from cvWriteFrame
*/
void saveFrame(const cv::Mat &image);
/**
* Handles key presses
* @param[in] how long to wait for a key press in ms, if 0, waits until keypress [Default=0].
* @return true is the key causes termination of the program loop
*/
bool checkForKeys(int aTime=0);
/**
* Closes the named window if it exists. If no name given, close all windows [Default=NULL].
* @param[in] name of window to close
*/
void closeWindow(const string &aWindow=string());
//Size of frames
cv::Size iSize_;
/** Image container for input image */
cv::Mat imgRGB;
/** Capture device */
cv::VideoCapture iCapture_;
/** Video writer */
cv::VideoWriter iWriter_;
/** frames/sec of the video */
int fps_;
/** true if paused */
bool isPaused_;
/**
* Raises errors based on exceptions thrown
* @param[in] aException exception
*/
void handleException(const exception &aException);
};
#endif //__MAIN_H
|
rmorbach/blade | BLaDE/src/UPCASymbology.h | <gh_stars>1-10
/*
Copyright (c) 2012, The Smith-Kettlewell Eye Research Institute
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Smith-Kettlewell Eye Research Institute nor
the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE SMITH-KETTLEWELL EYE RESEARCH INSTITUTE BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* UPCASymbology.h
*
* Created on: Jul 16, 2012
* Author: kamyon
*/
#ifndef UPCASYMBOLOGY_H_
#define UPCASYMBOLOGY_H_
#include "ski/BLaDE/Symbology.h"
#include "ski/types.h"
class UpcaSymbology: public BarcodeSymbology
{
public:
/**
* Decoding options
*/
struct Options
{
/** minimum barcode energy margin to pass verification */
double minMargin;
/** maximum barcode energy to pass verification */
double maxEnergy;
/** Constructor */
Options():
minMargin(0.02),
maxEnergy(20) //TODO: remove? doesn't seem to be used currently
{};
};
/**
* Constructor
*/
UpcaSymbology(const Options &opts = Options());
/**
* Destructor
*/
virtual ~UpcaSymbology();
/**
* Returns a convolution pattern to the decoder
* @param[in] digit digit to return the pattern for
* @param[in] fundamental width
* @param[in] whether the pattern is horizontally flipped
* @param[out] pattern pattern to use for convolution.
*/
virtual void getConvolutionPattern(TUInt digit, double x, bool isFlipped, vector<TUInt> &pattern) const;
/**
* Estimates the barcode from the matrix of digit energies for each symbol
* @param[in] energies matrix of digit energies per symbol
* @return a string that is the barcode estimate, empty string if estimate fails verification
*/
string estimate(const TMatEnergy &energies) const;
protected:
/** Decoding options */
Options opts_;
/** Mapping from auxiliary variables to actual digits*/
TMatrixUInt stateDigitMapForOddSymbol_;
/** Mapping from auxiliary variables to actual digits*/
TMatrixUInt stateDigitMapForEvenSymbol_;
/**
* Returns the digit that results in transition from one state to the other for a given symbol
* @param[in] prevState previous state
* @param[in] curState current state
* @param[in] symbol current symbol
*/
inline TUInt getDigitFromStates(TUInt prevState, TUInt curState, TUInt symbol) const;
/** Number of bars in each symbol */
static const TUInt SYMBOL_LENGTH_ = 4;
/** UPC Digit patterns */
static const TUInt digitPatterns_[10][SYMBOL_LENGTH_];
};
#endif /* UPCASYMBOLOGY_H_ */
|
rmorbach/blade | include/ski/type_traits.h | <filename>include/ski/type_traits.h
/*
Copyright (c) 2012, The Smith-Kettlewell Eye Research Institute
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Smith-Kettlewell Eye Research Institute nor
the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE SMITH-KETTLEWELL EYE RESEARCH INSTITUTE BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file Simple type declarations.
* @author <NAME>
*/
#ifndef SKI_TYPE_TRAITS_H_
#define SKI_TYPE_TRAITS_H_
#include "ski/types.h"
#include <limits>
namespace ski
{
//Type traits for promotion
template<typename T1, typename T2>
struct promote
{
//typedef T1 firstArg;
//typedef T2 secondArg;
typedef T2 result;
};
template<> struct promote<TInt8, TInt8> {typedef TInt32 result; };
template<> struct promote<TInt8, TInt16> {typedef TInt32 result; };
template<> struct promote<TInt8, TInt32> {typedef TInt32 result; };
template<> struct promote<TInt8, TInt64> {typedef TInt64 result; };
template<> struct promote<TInt8, TUInt8> {typedef TUInt32 result; };
template<> struct promote<TInt8, TUInt16> {typedef TUInt32 result; };
template<> struct promote<TInt8, TUInt32> {typedef TUInt32 result; };
template<> struct promote<TInt8, TUInt64> {typedef TUInt64 result; };
template<> struct promote<TInt8, float> {typedef float result; };
template<> struct promote<TInt16, TInt8> {typedef TInt32 result; };
template<> struct promote<TInt16, TInt16> {typedef TInt32 result; };
template<> struct promote<TInt16, TInt32> {typedef TInt32 result; };
template<> struct promote<TInt16, TInt64> {typedef TInt64 result; };
template<> struct promote<TInt16, TUInt8> {typedef TUInt32 result; };
template<> struct promote<TInt16, TUInt16>{typedef TUInt32 result; };
template<> struct promote<TInt16, TUInt32>{typedef TUInt32 result; };
template<> struct promote<TInt16, TUInt64>{typedef TUInt64 result; };
template<> struct promote<TInt16, float> {typedef float result; };
template<> struct promote<TInt32, TInt8> {typedef TInt32 result; };
template<> struct promote<TInt32, TInt16> {typedef TInt32 result; };
template<> struct promote<TInt32, TInt32> {typedef TInt32 result; };
template<> struct promote<TInt32, TInt64> {typedef TInt64 result; };
template<> struct promote<TInt32, TUInt> {typedef TInt32 result; };
template<> struct promote<TInt32, TUInt8> {typedef TInt32 result; };
template<> struct promote<TInt32, TUInt16> {typedef TInt32 result; };
template<> struct promote<TInt32, TUInt64> {typedef TUInt64 result; };
template<> struct promote<TInt32, float> {typedef float result; };
template<> struct promote<TInt64, TInt8> {typedef TInt64 result; };
template<> struct promote<TInt64, TInt16> {typedef TInt64 result; };
template<> struct promote<TInt64, TInt32> {typedef TInt64 result; };
template<> struct promote<TInt64, TInt64> {typedef TInt64 result; };
template<> struct promote<TInt64, TUInt8> {typedef TUInt64 result; };
template<> struct promote<TInt64, TUInt16>{typedef TUInt64 result; };
template<> struct promote<TInt64, TUInt32>{typedef TUInt64 result; };
template<> struct promote<TInt64, TUInt64>{typedef TUInt64 result; };
template<> struct promote<TInt64, float> {typedef float result; };
template<> struct promote<TUInt8, TInt8> {typedef TUInt32 result; };
template<> struct promote<TUInt8, TInt16> {typedef TUInt32 result; };
template<> struct promote<TUInt8, TInt32> {typedef TUInt32 result; };
template<> struct promote<TUInt8, TInt64> {typedef TUInt64 result; };
template<> struct promote<TUInt8, TUInt8> {typedef TUInt32 result; };
template<> struct promote<TUInt8, TUInt16>{typedef TUInt32 result; };
template<> struct promote<TUInt8, TUInt32>{typedef TUInt32 result; };
template<> struct promote<TUInt8, TUInt64>{typedef TUInt64 result; };
template<> struct promote<TUInt8, float> {typedef float result; };
template<> struct promote<TUInt16, TInt8> {typedef TUInt32 result; };
template<> struct promote<TUInt16, TInt16> {typedef TUInt32 result; };
template<> struct promote<TUInt16, TInt32> {typedef TUInt32 result; };
template<> struct promote<TUInt16, TInt64> {typedef TUInt64 result; };
template<> struct promote<TUInt16, TUInt8> {typedef TUInt32 result; };
template<> struct promote<TUInt16, TUInt16>{typedef TUInt32 result; };
template<> struct promote<TUInt16, TUInt32>{typedef TUInt32 result; };
template<> struct promote<TUInt16, TUInt64>{typedef TUInt64 result; };
template<> struct promote<TUInt16, float> {typedef float result; };
template<> struct promote<TUInt32, TInt8> {typedef TUInt32 result; };
template<> struct promote<TUInt32, TInt16>{typedef TUInt32 result; };
template<> struct promote<TUInt32, TInt32>{typedef TUInt32 result; };
template<> struct promote<TUInt32, TInt64>{typedef TUInt64 result; };
template<> struct promote<TUInt32, TUInt> {typedef TUInt32 result; };
template<> struct promote<TUInt32, TUInt8>{typedef TUInt32 result; };
template<> struct promote<TUInt32, TUInt16>{typedef TUInt32 result; };
template<> struct promote<TUInt32, TUInt64>{typedef TUInt64 result; };
template<> struct promote<TUInt32, float> {typedef float result; };
template<> struct promote<TUInt64, TInt8> {typedef TUInt64 result; };
template<> struct promote<TUInt64, TInt16>{typedef TUInt64 result; };
template<> struct promote<TUInt64, TInt32>{typedef TUInt64 result; };
template<> struct promote<TUInt64, TInt64>{typedef TUInt64 result; };
template<> struct promote<TUInt64, TUInt8>{typedef TUInt64 result; };
template<> struct promote<TUInt64, TUInt16>{typedef TUInt64 result; };
template<> struct promote<TUInt64, TUInt32>{typedef TUInt64 result; };
template<> struct promote<TUInt64, TUInt64>{typedef TUInt64 result; };
template<> struct promote<TUInt64, float> {typedef float result; };
template<> struct promote<float, TInt8> {typedef float result; };
template<> struct promote<float, TInt16>{typedef float result; };
template<> struct promote<float, TInt32>{typedef float result; };
template<> struct promote<float, TInt64>{typedef float result; };
template<> struct promote<float, TUInt8>{typedef float result; };
template<> struct promote<float, TUInt16>{typedef float result; };
template<> struct promote<float, TUInt32>{typedef float result; };
template<> struct promote<float, TUInt64>{typedef float result; };
template<> struct promote<float, float> {typedef float result; };
template<typename T> struct promote<T, double> {typedef double result; };
template<typename T> struct promote<double, T> {typedef double result; };
template<> struct promote<double, double> {typedef double result; }; //to resolve ambiguity
//Type traits for rounding
/**
* @param T1 type of input
* @param T2 type of output
*/
template<typename T1, typename T2>
struct should_be_rounded
{
/**
* Is true if a cv_type of T1 should be rounded when cast to a cv_type of T2 at compile time.
*/
static const bool value = (!std::numeric_limits<T1>::is_integer) && (std::numeric_limits<T2>::is_integer);
};
//Type traits for some operations
template <class T>
struct implements
{
///Whether the "double T::norm()" function is implemented
static const bool norm = false;
};
//Must be specializations for classes that implement the norm() operator
}; //namespace ski
#endif //SKI_TYPE_TRAITS_H_
|
rmorbach/blade | include/ski/BLaDE/BLaDE.h | /*
Copyright (c) 2012, The Smith-Kettlewell Eye Research Institute
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Smith-Kettlewell Eye Research Institute nor
the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE SMITH-KETTLEWELL EYE RESEARCH INSTITUTE BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file Barcode Location and Decoding Engine
* @author <NAME>
*/
#ifndef BLADE_H_
#define BLADE_H_
#include "ski/types.h"
#include <memory>
#include "ski/BLaDE/Barcode.h"
//Forward declarations
class BarcodeSymbology;
class _BLaDE;
/**
* @class Barcode Location and Decoding Engine High-Level Access
*/
class BLaDE
{
public:
/**
* BLaDE default options
*/
struct Options
{
/** Scale used for the finder */
TUInt scale;
/** Minimum number of cells a barcode needs to contain.*/
TUInt nOrientations;
/**
* Constructor
* @param[in] s scale to work at
* @param[in] n how finely to quantize orientation search
*/
Options(TUInt s=0, TUInt n=18):
scale(s),
nOrientations(n)
{};
};
/**
* BLaDE included symbologies
*/
enum PredefinedSymbology
{
UPCA = 1
};
/**
* Constructor
* @param[in] aImg input image to work on
* @param[in] opts options to use
*/
BLaDE(const TMatrixUInt8 &aImg, const Options &opts=Options());
/**
* Destructor
*/
~BLaDE();
/**
* Returns a list of located barcodes on the image associated with this engine
* @return a list of detected possible barcodes
*/
BarcodeList& locate();
/**
* Add symbology to use for decoding. Symbologies are tried in the order they are added.
* @param[in] aSymbology a symbology to try when attempting to decode
*/
void addSymbology(BarcodeSymbology* aSymbology);
/**
* Adds a pre-defined symbology (with default options) to use for decoding.
* Symbologies are tried in the order they are added.
* @param[in] aSymbology a symbology to try when attempting to decode
*/
void addSymbology(PredefinedSymbology aSymbology);
/**
* Attempt to decode a barcode
* @param[in, out] bc a located barcode returned by getLocator->locate()
* @return true if one of the symbologies has correctly decoded the barcode
*/
bool decode(Barcode &bc);
private:
std::unique_ptr<_BLaDE> blade_;
};
#endif
|
rmorbach/blade | BLaDE/src/Decoder.h | /*
Copyright (c) 2012, The Smith-Kettlewell Eye Research Institute
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Smith-Kettlewell Eye Research Institute nor
the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE SMITH-KETTLEWELL EYE RESEARCH INSTITUTE BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file Barcode Decoding code
* @author <NAME>
*/
#ifndef DECODER_H_
#define DECODER_H_
#include <string>
#include <vector>
#include "ski/BLaDE/Barcode.h"
#include "ski/BLaDE/Symbology.h"
#include <memory>
using namespace std;
/**
* Barcode decoder class.
* Decoder methods are responsible for extracting a matrix of energies for a given symbology, where
* each entry corresponds to the likelihood of a given symbol being a given digit.
* The symbology used by this decoder then uses this information to perform the final decoding,
* such as parity checks or joint decoding.
*/
class BarcodeDecoder
{
public:
/**
* Decoder options
*/
struct Options
{
/** edge threshold for barcode stripe edge detection */
int edgeThresh;
/** Approximate fundamental width of extracted slices */
TUInt fundamentalWidth;
/** Coefficient to use for the "edginess" when calculating the fixed edge locations */
double edgePowerCoefficient;
/** Maximum edge magnitude allowed in the Viterbi*/
int maxEdgeMagnitude;
/** Coefficient to use for the variance of the expected locations of fixed edges */
double edgeFixedLocationVar;
/** Coefficient to use for the variance of the relative locations of fixed edges */
double edgeRelativeLocationVar;
/** Constructor */
Options():
edgeThresh(40),
fundamentalWidth(10),
edgePowerCoefficient(1),
maxEdgeMagnitude(200),
edgeFixedLocationVar(10000),
edgeRelativeLocationVar(1)
{};
};
/** Result of decoding attempt */
enum Result {
CANNOT_DECODE = 0, ///< Means detected barcode is not aligned well enough to attempt decoding
DECODING_FAILED = -1, ///< Means that the decode attempted decoding, but was not successful
DECODING_SUCCESSFUL = 1 ///< Means that decoding was successful
};
/**
* Constructor
* @param[in] img image to use when decoding barcode
* @param[in] symbology to use when decoding. The decoder then takes ownership of the symbology.
* @param[in] opts options to use for decoding
*/
BarcodeDecoder(const TMatrixUInt8& img, BarcodeSymbology* aSymbology, const Options &opts=Options());
/**
* Destructor
*/
~BarcodeDecoder();
/**
* Reads the barcode - main function called for decoding.
* @param[in] bc barcode candidate info returned by the detection stage
* @return result of attempted decoding attempt
*/
Result read(Barcode &bc);
/**
* Name of the symbology used by this decoder
*/
inline string symbology() const {return symbology_->name(); };
private:
/** Decoder options */
Options opts_;
/** Possible sweep directions */
enum SweepDirection {FORWARD = 0, BACKWARD = 1, FINISHED = 2};
/**
* Struct containing information about a detected edge in barcode slice
*/
struct DetectedEdge
{
/** Constructor */
inline DetectedEdge(int p, int loc, int mag, int nPrevPos, int nPrevNeg):
polarity(p), location(loc), magnitude(mag),
nPreviousPositiveEdges(nPrevPos), nPreviousNegativeEdges(nPrevNeg) {};
/** Polarity, must be -1 for a light->dark edge, 1 for dark->light edge */
int polarity;
/** location of the edge in the slice */
int location;
/** magnitude of the detected edge */
int magnitude;
/** number of edges with positive polarity before this edge in the barcode slice */
int nPreviousPositiveEdges;
/** number of edges with negative polarity before this edge in the barcode slice */
int nPreviousNegativeEdges;
/** Index of this edge */
inline int index() const {return nPreviousPositiveEdges + nPreviousNegativeEdges; };
};
/**
* Struct containing information about expected barcode symbol boundaries
*/
struct SymbolBoundary
{
/** Left edge of the symbol */
int leftEdge;
/** Right edge of the symbol */
int rightEdge;
/** Expected width of the symbol in terms of the fundamental width */
TUInt width;
/**
* Constructor
* @param[in] lEdge location of the left edge of the symbol
* @param[in] rEdge location of the right edge of the symbol
* @param[in] w width of the symbol in terms of the fundamental width
*/
SymbolBoundary(int lEdge=0, int rEdge=0, TUInt w=0) : leftEdge(lEdge), rightEdge(rEdge), width(w) {};
/**
* Fundamental width of the symbol
* @return returne the fundamental width of the symbol
*/
inline double fundamentalWidth() const {return ((double) rightEdge - leftEdge) / (double) width; };
};
/** Grayscale image to estimate the barcode from */
const TMatrixUInt8& image_;
/** Symbology used for this detector */
const std::unique_ptr<BarcodeSymbology> symbology_;
/** Number of data symbols */
const TUInt nSymbols_;
/** Integral barcode slice to be used for symbol estimation */
vector<int> slice_;
/**
* Performs tests to see whether we should attempt to decode barcode or not.
* Decoding is not attempted if it is deemed that the barcode is not properly seen in the image.
* @param bc barcode under consideration
* @return true if it is determined that the barcode is visible enough to attempt decoding
*/
bool shouldAttemptDecoding(const Barcode &bc);
/**
* Extracts the barcode image slice from input image and integrates.
* The slice is stretched such that the fundamental width is x.
* The extracted slice extends 2x beyond the detected barcode ends
* @param[in] aImg grayscale image to extract slice from
* @param[in] firstEdge first edge of the barcode candidate.
* @param[in] lastEdge last edge of the barcode candidate.
*/
void extractIntegralSlice(const TMatrixUInt8& aImg, TPointInt firstEdge, TPointInt lastEdge);
/**
* Extracts edges from the barcode slice
* @param[out] extracted edges from the barcode slice
*/
void extractEdges(vector<DetectedEdge> &edges);
/**
* Localizes the fixed edges to get accurate symbol boundaries and fundamental width estimates.
* @param[out] symbolBoundaries localized symbol boundaries
* @return true if an estimate is found, false if not enough edges were determined.
*/
bool localizeFixedEdges(vector<SymbolBoundary> &symbolBoundaries);
/**
* Finds which detected edges can be candidates for the fixed edges of the barcode
* @param[in] detectedEdges detected edges of the barcode stripe
* @param[out] fixedEdgeCandidates fixedEdgeCandidates[i] is a vector of references to the
* detected edges that may be fixed edge [i] in the symbology.
* @return true if all fixed edges can be matched, false if the detected edges cannot be matched to the symbology.
*/
bool getFixedEdgeCandidates(const vector<DetectedEdge> &detectedEdges,
vector<vector<const DetectedEdge*> > &fixedEdgeCandidates);
/**
* Calculates the fixed edge priors - energies due to the difference of fixed edge candidates from expected absolute locations.
* @param[in] fixedEdgeCandidates list of fixed edge candidates as given by getFixedEdgeCandidates()
* @param[in] x estimate of the fundamental width to use
* @param[out] priors vector of priors for each fixed edge in the symbology.
* @param[out] conditionals vector of priors for each fixed edge in the symbology.
*/
void calculateFixedEdgeEnergies(const vector<vector<const DetectedEdge*> > &fixedEdgeCandidates,
double x, vector<vector<TEnergy> > &priors, vector<TMatEnergy> &conditionals);
/**
* Calculate the digit energies
* @param[in] dir direction to convolve (in case of backwards barcode)
* @param[in] boundaries detected boundaries for the symbols
*/
void getDigitEnergies(int dir, const vector<SymbolBoundary> &boundaries);
/**
* Used by convolve(), this function calculates the dot product at a specific place
* @param[in] sgn sign of the initial bit - will flip at every pattern edge
* @param[in] beginning of the data to calculate the dot-product for
* @param[in] pattern pattern to convolve with
* @return result of the convolution
*/
static int dotProduct(int sgn, const int *data, const vector<TUInt> &pattern);
/** Matrix to store digit energies, energies_(digit, symbol)*/
TMatEnergy energies_;
/** Matrix to store digit convolution values, convolutions_(digit, symbol)*/
TMatrixInt convolutions_;
};
#endif // DECODER_H_
|
rmorbach/blade | LinBLaDE/src/AlsaAccess.h | <reponame>rmorbach/blade
/*
Copyright (c) 2012, The Smith-Kettlewell Eye Research Institute
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Smith-Kettlewell Eye Research Institute nor
the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE SMITH-KETTLEWELL EYE RESEARCH INSTITUTE BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* @file AlsaAccess.h
* @author <NAME>
* Created on: Jul 25, 2012
*/
#ifndef ALSAACCESS_H_
#define ALSAACCESS_H_
#include "ski/Sound/SoundManager.h"
#include <list>
#include <string>
#include <stdexcept>
#include <memory>
#include <alsa/asoundlib.h>
class AlsaAccess
{
public:
/** Constructor */
AlsaAccess();
/** Destructor */
virtual ~AlsaAccess();
/** Alsa exception class used by this class for alsa related errors*/
class AlsaException: public std::exception
{
public:
/**
* Constructor
* @param msg msg text for debugging
* @param err alsa error code that caused this exception
*/
explicit AlsaException(const std::string &msg, int err=0):
msg_( std::string("AlsaException:").append(msg).append("\n").append( (err < 0 ? snd_strerror(err) : "") ) )
{};
/** Destructor */
virtual ~AlsaException() throw() {};
virtual const char* what() const throw() {return msg_.c_str(); };
private:
std::string msg_;
};
///Opens audio manager
void open(SoundManager::Parameters ¶ms, bool isSync);
///Closes audio manager
void close();
///Returns currently used audio paramters
inline const SoundManager::Parameters* getParameters() const {return (getStatus() == SoundManager::STATUS_CLOSED ? NULL : ¶ms_);};
///Speaks out loud a text
void speak(const std::string &aText);
///Queues audio data for playback
void play(const SoundManager::TAudioData *data);
///Plays audio data now
void playNow(const SoundManager::TAudioData *data);
///Pauses playback
void pause();
///Resumes playback
void resume();
///Stops playback after emptying queue
void stop();
///Stops playback immediately
void stopNow();
///Returns current status
SoundManager::Status getStatus() const;
protected:
typedef snd_ctl_t* card_handle;
typedef snd_ctl_card_info_t* card_info;
typedef snd_pcm_t* pcm_handle;
typedef snd_pcm_uframes_t TULong;
typedef snd_pcm_sframes_t TLong;
class SoundCard;
/**
* A wave device that is part of a sound card
*/
struct WaveDevice
{
/** Index of this device */
int index;
/** Hardware name of this device */
std::string hwName;
/** Handle to this device */
pcm_handle handle;
/** Hardware Parameters of this device */
snd_pcm_hw_params_t* hwParams;
/** Software Parameters of this device */
snd_pcm_sw_params_t* swParams;
/**
* Constructor
* @param parent sound card that this device resides on
* @param deviceIndex index of this device on the parent card
*/
WaveDevice(const SoundCard &parent, int deviceIndex);
/** Destructor */
~WaveDevice();
/**
* Open device
* @param[in, out] params parameters to use. On return, contains actual parameters that were set.
* @param[in] isSycn if true, device is opened for synchronous playback, if false, it is opened for asynchronous playback
*/
void open(SoundManager::Parameters ¶ms, bool isSync);
/** Close device */
void close();
/** Device handle */
typedef std::unique_ptr<WaveDevice> Handle;
};
static const WaveDevice::Handle nullDevice;
/**
* A sound card installed in the device
*/
struct SoundCard
{
/** Index of this card on device */
int index;
/** Name of this card */
std::string name;
/** Hardware name of this card */
std::string hwName;
/** handle to the card if open */
card_handle handle;
/** Information regarding this card */
card_info info;
/** List of devices on this card */
std::list<WaveDevice::Handle> devices;
/** Constructor */
SoundCard(int cardIndex);
/** Destructor */
~SoundCard();
/** Enumerates devices on this card */
void enumerateDevices();
/** Opens card */
void open();
/** Closes card and releases information structures */
void close();
/** Device handle */
typedef std::unique_ptr<SoundCard> Handle;
};
/** Audio data structure used internally */
struct private_audio_data
{
/** Pointer to the audio data */
const SoundManager::TAudioData* data;
/** Number of channels in the data */
TUInt nChannels;
/** Number of frames in the data. The data is assumed to be one period-length */
TUInt64 size;
};
/** List of cards and devices found */
std::list<SoundCard::Handle> cards_;
/**
* Populates the list of sound cards
*/
void enumerateSoundCards();
//-------------
//Playback stuff
//--------------
/** Playback device */
WaveDevice* playbackDevice_;
/** Playback parameters */
SoundManager::Parameters params_;
/** Playback mode */
bool isPlaybackSync_;
/**
* Writes data to audio buffer
* @param[in] device pcm handle of device to write to
* @param[in] data data to write
*/
static void write(pcm_handle device, const private_audio_data &data);
enum Errors
{
ERROR_RECOVERABLE,
ERROR_UNRECOVERABLE,
ERROR_RETRY,
ERROR_UNHANDLED
};
/**
* Recovers from buffer under/overruns.
* @param[in] aDev handle of device causing the error
* @param[in] err error code that occurred
* @return int error code if error is unhandled;
*/
static Errors recoverFromError(pcm_handle handle, int error);
//Asynchronous playback stuff
/** Asyncronous callback handler structure - we do not access this directly*/
snd_async_handler_t* asyncHandler_;
/** Private audio data to be used for playback*/
private_audio_data privateData_;
/**
* Asynchronous sound callback
* @param[in] aHandler sound callback handler
*/
static void asyncHandleCallback(snd_async_handler_t *aHandler);
};
#endif /* ALSAACCESS_H_ */
|
rmorbach/blade | LinBLaDE/src/BarcodeEngine.h | <filename>LinBLaDE/src/BarcodeEngine.h
/*
* BarcodeEngine.h
*
* Created on: Sep 14, 2012
* Author: kamyon
*/
#ifndef BARCODEENGINE_H_
#define BARCODEENGINE_H_
#include "ski/cv.hpp"
#include "ski/math.h"
#include "ski/BLaDE/Barcode.h"
#include "ski/Sound/SoundManager.h"
#include <cstdio>
#include "ProductSearch.h"
#include "opencv2/opencv.hpp"
#include <memory>
class Opts;
class BLaDE;
/**
* @class Barcode Feedback and BLaDE access wrapper
*/
class BarcodeEngine
{
public:
/**
* Constructor
* @param input image matrix to process
* @param opts options to use
*/
BarcodeEngine(cv::Mat& input, const Opts &opts);
/**
* Processes current frame
* @return true if a barcode is found.
*/
bool process();
/**
* Destructor
*/
~BarcodeEngine();
private:
//=======================
// BLaDE Access
//=======================
/** input matrix reference */
cv::Mat &input_;
/** Grayscale version of input image */
TMatrixUInt8 grayImage_;
/** Handle of the actual localization and decoding engine */
std::unique_ptr<BLaDE> blade_;
//=======================
// FEEDBACK
//=======================
/** Text to output when a barcode is decoded */
static const char* BARCODE_DECODED_TEXT;
/** Text to output when looking up product information */
static const char* LOOKUP_TEXT;
/** Text to output when no product information is found */
static const char* NO_PRODUCT_FOUND_TEXT;
/**
* Outputs a text
* @param aText
*/
void outputText(const std::string &aText);
/**
* Calculates the size score of a barcode, indicating how happy we are with the barcode's size
* @param bc detected barcode
* @param imSize size of image barcode is detected in
* @return a score showing indicating how appropriate the size of the barcode is for attempting decoding
*/
static double calculateSizeScore(const Barcode &bc, const TSizeInt& imSize);
/**
* Calculates the alignment score of a barcode, indicating how happy we are with the barcode's
* alignment in the image frame.
* @param bc detected barcode
* @param imSize size of image barcode is detected in
* @return a score showing indicating how well aligned the barcode is in the image for attempting decoding
*/
static double calculateAlignmentScore(const Barcode &bc, const TSizeInt& imSize);
//-----------------------
//Visual Feedback
//-----------------------
/** True if visual feedback is on */
bool isVisualFeedbackOn_;
//-----------------------
//Audio Feedback
//-----------------------
/** True if audio feedback is on */
bool isAudioFeedbackOn_;
class AudioFeedback
{
private:
/**
* Parameters to use for audio feedback
*/
SoundManager::Parameters soundParams_;
/** Handle of the sound manager used to provide audio feedback */
std::unique_ptr<SoundManager> soundMan_;
/** Number of feedback levels */
static const TUInt N_FEEDBACK_LEVELS = 5;
/** Number of audio channels */
static const TUInt N_CHANNELS = 1;
/** Sampling rate */
static const TUInt RATE = 16000;
/** Audio snippet size */
static const TUInt64 PERIOD_SIZE = 4096;
/** Number of snippets in buffer */
static const TUInt64 N_PERIODS = 4;
/** Approximate audio frequency. Actual frequency may differ slightly due to buffering considerations */
static const TUInt BASE_FREQUENCY = 800;
/// Audio array
typedef SoundManager::TAudioData* TAudioArray;
/** Pre-generated audio samples to play */
cv::Mat_<TAudioArray> sounds_;
/** Pre-generated quiet sound (NULL feedback) */
TAudioArray nullSound_;
public:
/// Constructor
AudioFeedback();
/// Destructor
~AudioFeedback();
/**
* Plays an audio sound if sound feedback is turned on
* @param aSound sound data to play
*/
void play(double sizeScore, double alignmentScore);
/**
* Plays null sound
*/
void playNull();
/**
* Uses text-to-speech to present a text
*/
void say(const std::string &aText);
private:
/**
* Plays a given sound data
* @param aSound sound data to play
*/
void play(const TAudioArray &aSound);
/**
* Generates the sounds
*/
void generateSounds();
};
std::unique_ptr<AudioFeedback> audioFeedback_;
//=======================
// PRODUCT LOOKUP
//=======================
/** Whether product information is looked up online after decoding */
bool isProductSearchOn_;
/**
* Looks up product information based on decoded barcode
* @return product information
*/
ProductSearch::ProductList getProductInfo(const Barcode &aBarcode);
ProductSearch* pSearch_;
};
#endif /* BARCODEENGINE_H_ */
|
rmorbach/blade | include/ski/log.h | <filename>include/ski/log.h
/*
Copyright (c) 2012, The Smith-Kettlewell Eye Research Institute
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Smith-Kettlewell Eye Research Institute nor
the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE SMITH-KETTLEWELL EYE RESEARCH INSTITUTE BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* log.h
* Debugging macros
* Created on: Jul 30, 2012
* Author: kamyon
*/
#ifndef ELOG_H_
#define ELOG_H_
#ifdef __ANDROID__ //if building for android
#include <android/log.h>
const char APP_NAME[] = "SKI APP";
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, APP_NAME, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG , APP_NAME, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO , APP_NAME, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN , APP_NAME, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR , APP_NAME, __VA_ARGS__)
#else // __ANDROID__ not defined -> building for a pc system
#include <cstdio>
#include <cstdarg>
#ifdef DEBUG
#define LOGD(...) {std::fprintf(stderr, __VA_ARGS__);}
#define LOGV(...) {std::fprintf(stdout, __VA_ARGS__);}
#else
#define LOGD(...) {;}
#define LOGV(...) {;}
#endif //DEBUG_
#define LOGE(...) {std::fprintf(stderr, "ERROR: "); std::fprintf(stderr, __VA_ARGS__);}
#define LOGW(...) {std::fprintf(stderr, "WARNING: "); std::fprintf(stderr, __VA_ARGS__);}
#define LOG(...) {std::fprintf(stdout, __VA_ARGS__);}
//Workaround for curses
#ifdef CURSES
extern "C"
{
#undef LOG
#define LOG(...) {printw(__VA_ARGS__);}
#undef LOGD
#define LOGD(...) {printw(__VA_ARGS__);}
#undef LOGV
#define LOGV(...) {printw(__VA_ARGS__);}
#undef LOGE
#define LOGE(...) {printw(__VA_ARGS__);}
}
#endif //CURSES
#endif //__ANDROID__
#endif //ELOG_H_
|
rmorbach/blade | LinBLaDE/src/opts.h | #ifndef __OPTS_H
#define __OPTS_H
/**
* @file options
*/
#include "ski/types.h"
#include <string>
#include <cstdio>
struct Opts
{
/** input mode */
enum InputMode
{
EInputImage, EInputMovie, EInputWebcam
} input;
/** Resolution */
enum CameraResolution
{
EResolutionLow = 1, //320x240
EResolutionMed, //640x480
EResolutionHi //960x720
} resolution;
/** Whether windows should be shown or not */
bool isWindowShown;
/** Product lookup info on/off */
bool isProductLookedUp;
/** Whether audio is enabled */
bool isAudioEnabled;
/** Filename of input (empty if input is webcam).*/
std::string inputFile;
/** index of webcam if input is webcam (0: any, 1: cam 1, 2: cam 2). */
int camera;
/** Scale used for the finder */
TUInt scale;
/** Constructor - also sets default values */
Opts() :
input(EInputWebcam),
resolution(EResolutionMed),
isWindowShown(true),
isProductLookedUp(false), //TODO: after implementing the lookup, change this to true
isAudioEnabled(true),
camera(0),
scale(0)
{
};
};
/**
* Parses the command line arguments and sets the option structure given in the parameter
* @param[in] argc number of arguments.
* @param[in] argv list of agument strings passed. argv[0] is the name of the program itself.
* @param[in] opts structure that on return contains the options updated from the command line
* @return true if program should continue, false if program should quit gracefully
* @throw errParser if parser has encountered an error.
*/
bool parse(int argc, char* argv[], Opts &opts);
#endif //__OPTS_H
|
rmorbach/blade | include/ski/BLaDE/Barcode.h | /*
Copyright (c) 2012, The Smith-Kettlewell Eye Research Institute
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Smith-Kettlewell Eye Research Institute nor
the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE SMITH-KETTLEWELL EYE RESEARCH INSTITUTE BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file Barcode.h
*
* Created on: May 24, 2011
* @author: <NAME>
*/
#ifndef BARCODE_H_
#define BARCODE_H_
#include "ski/cv.hpp"
#include <string>
#include <list>
/**
* Structure containing information about decoded barcode.
*/
struct Barcode
{
/** first edge of this barcode segment */
TPointInt firstEdge;
/** last edge of this barcode segment */
TPointInt lastEdge;
/** Barcode estimate information */
std::string estimate;
/** Type of barcode (determined by the decoder that produces a valid estimate) */
std::string symbology;
/**
* Constructor
* @param[in] pt1 one end of the barcode strip
* @param[in] pt2 other end of the barcode strip
* @param[in] est estimated barcode string
* @param[in] sym symbology used for the estimate
*/
Barcode(const TPointInt &pt1, const TPointInt &pt2) :
firstEdge(pt1),
lastEdge(pt2)
{};
};
typedef std::list<Barcode> BarcodeList;
#endif /* BARCODE_H_ */
|
rmorbach/blade | BLaDE/src/Locator.h | <reponame>rmorbach/blade<gh_stars>1-10
/*
Copyright (c) 2012, The Smith-Kettlewell Eye Research Institute
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Smith-Kettlewell Eye Research Institute nor
the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE SMITH-KETTLEWELL EYE RESEARCH INSTITUTE BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file Locator.h
* Barcode Location Code.
* @author <NAME>
*/
#ifndef BARCODE_LOCATOR_H_
#define BARCODE_LOCATOR_H_
#include <algorithm>
#include <list>
#include "ski/types.h"
#include "algorithms.h"
#include "ski/BLaDE/Barcode.h"
using namespace ski;
/**
* Class that encapsulates the barcode location algorithm.
*/
class BarcodeLocator
{
public:
/**
* Locator options
*/
struct Options
{
/** min gradient magnitude threshold */
TUInt8 gradThresh;
/** Cell size for the locator to use, each cell has one vote on a barcode orientation.*/
TUInt cellSize;
/** Entropy threshold for the barcode verification stage */
double maxEntropy;
/** maximum number of votes allowed per Hough bin - to reduce few strong edges overwhelming hough */
TUInt maxVotesPerBin;
/** minimum number of votes per orientation*/
TUInt minVotesPerOrientation;
/** minimum number of votes per barcode orientation candidate */
TUInt minVotesPerMode;
/** minimum edges to declare a segment a barcode segment */
int minEdgesInBarcode;
/** minimum edge density to declare a segment a barcode segment in edges/pixel */
double minEdgeDensityInBarcode;
/** maximum distance allowed between edges in a barcode */
int maxDistBtwEdges;
/** # of orientations being considered */
TUInt nOrientations;
/** Scale being used */
TUInt scale;
/** Constructor */
Options():
gradThresh(20),
cellSize(16),
maxEntropy(1.5),
maxVotesPerBin(20),
minVotesPerOrientation(300),
minVotesPerMode(50),
minEdgesInBarcode(20),
minEdgeDensityInBarcode(0.2),
maxDistBtwEdges(5),
nOrientations(18),
scale(0)
{};
};
/**
* Constructor.
* @param[in] img grayscale image to work on
* @param[in] opts other locator specific options
*/
BarcodeLocator(const TMatrixUInt8 &img, const Options &opts=Options());
/**
* Destructor
*/
virtual ~BarcodeLocator();
/**
* Function that locates barcodes - main entry TPointInt for the locator class.
* @param[out] list of barcodes found that contains most edges.
*/
void locate(BarcodeList &barcodes);
private:
/** Options used by barcode locator */
const BarcodeLocator::Options opts_;
/**
* @class Structure that holds the images being used, subsamples input if needed, calculates gradients, etc.
* TODO: move to separate file, passing only relevant options
*/
class ImageContainer
{
private:
/** Input image */
const TMatrixUInt8 &original;
/** scale that we are working on */
const TUInt scale;
/** Size of output image */
const TSizeUInt outputSize;
/** Subsampled image if scale is greater than zero */
TMatrixUInt8 scaled;
/** @f\nabla_i I@f */
TMatrixInt dI;
/** @f\nabla_j I@f */
TMatrixInt dJ;
/** @f|\nabla\ I| I@f */
TMatrixUInt8 dMag;
/** @f\angle\nabla\ I@f */
TMatrixUInt8 dAng;
/** Scratch areas for Scharr calculation speedup */
TMatrixInt tmp1, tmp2;
/** Matrix containing lookup tables for the gradient orientation given i and j gradients */
TMatrixUInt8 gradientOrientationMap;
/** Matrix containing lookup tables for the gradient magnitude given i and j gradients */
TMatrixUInt8 gradientMagnitudeMap;
/** Minimum possible value of i gradient */
static const int MIN_GRAD = -255;
/** Maximum possible value if j gradient */
static const int MAX_GRAD = 255;
public:
/**
* Constructor
*/
ImageContainer(const TMatrixUInt8 &input, const Options &opts);
/**
* Calculates the scaled image if needed, recalculates the gradients, etc.
*/
void update();
/**
* Whether image is being subsampled
*/
inline bool isSubsampled() const {return (scale > 0); };
/**
* Size of output images used by the locator
* @return size of gradient images returned by the locator
*/
inline TSizeUInt size() const {return outputSize; };
/**
* Returns a reference to the image used for processing
* @return the image that is being used for gradient calculations
*/
inline const TMatrixUInt8& get() const {return (isSubsampled() ? original : scaled); };
/**
* Magnitude image
* @return image of scaled gradient magnitude
*/
inline const TMatrixUInt8& magnitudes() const {return dMag; };
/**
* Orientation image
* @return image of scaled gradient orientations
*/
inline const TMatrixUInt8& orientations() const {return dAng; };
private:
/**
* Subsamples image if needed
*/
static void subsample(const TMatrixUInt8 &input, TMatrixUInt8 &output, TUInt scale);
/**
* Prepares the lookup tables and containers for the gradient calculations
* @param[in] thresh minimum threshold for a gradient magnitude - anything lower *in magnitude* is suppressed to zero.
* @param[in] nOrientations number of gradient orientations levels to quantize
*/
void prepareGradientCalculator(TUInt8 thresh, TUInt8 nOrientations);
/**
* Calculates rectangular and polar gradients with angles quantized to a given number of bins.
* @param[in] input input to calculate gradients on
*/
void calculateGradients(const TMatrixUInt8& input);
/**
* Calculates rectangular gradients using Sobel or Scharr separable operators.
* @param[in] img image to calculate the gradients on.
* @param[out] iGrad matrix to return i-gradients in.
* @param[out] jGrad matrix to return j-gradients in.
* @param[in] tmp1 temporary scratch area
* @param[in] tmp2 temporary scratch area
*/
static void calculateScharrGradients(const TMatrixUInt8 &img, TMatrixInt &iGrad, TMatrixInt &jGrad, TMatrixInt &tmp1, TMatrixInt &tmp2);
/**
* Calculates polar gradients from rectangular gradients, with orientation quantized to 16 bins.
* @param[in] iGrad matrix of i-gradients in.
* @param[in] jGrad matrix of j-gradients in.
* @param[out] absGrad matrix to return gradient magnitudes in - scaled to fit in an 8 bit unsigned integer.
* @param[out] angGrad matrix to return gradient angles in.
* @param[in] magnitudeLookup lookup map to use to speed up magnitude scaling
* @param[in] orientationLookup lookup map to use to speed up orientation quantization
*/
static void calculatePolarGradients(const TMatrixInt &iGrad, const TMatrixInt &jGrad,
TMatrixUInt8 &absGrad, TMatrixUInt8 &angGrad, const TMatrixUInt8 &magnitudeLookup, const TMatrixUInt8 &orientationLookup);
} image_;
/**
* Structure containing information about barcode candidate segment and decoded barcode.
*/
struct BarcodeCandidate
{
/** # of alternating edges in this candidate */
int nEdges;
/** orientation of this barcode segment */
int orientation;
/** first edge of this barcode segment */
TPointInt firstEdge;
/** last edge of this barcode segment */
TPointInt lastEdge;
/**
* Constructor
* @param[in] o orientation
* @param[in] pt1 one end of the barcode strip
* @param[in] pt2 other end of the barcode strip
*/
BarcodeCandidate(int o = 0, const TPointInt &pt1=TPointInt(), const TPointInt &pt2=TPointInt() ) :
nEdges(0),
orientation(o),
firstEdge(pt1),
lastEdge(pt2)
{};
/**
* returns the width of the barcode segment
* @return width of barcode segment
*/
inline double width() const
{
return norm(lastEdge - firstEdge);
};
/**
* Smaller than operator for sorting
* @return true if this barcode has fewer edges than the one compared to it
* TODO: consider alternative sorting methods using an overall measure including feedback scores?
*/
inline bool operator<(const BarcodeCandidate &bc) const
{
return (nEdges < bc.nEdges);
};
/**
* For a barcode candidate determined in a given scale, returns the barcode at full scale
* @return detected barcode
*/
inline Barcode promote(TUInt scale) const
{
int multiplier = (1 << scale);
return Barcode( firstEdge * multiplier, lastEdge * multiplier);
}
};
typedef std::list<BarcodeCandidate> BarcodeCandidateList;
/** list of detected barcodes */
BarcodeCandidateList barcodeCandidates_;
/**
* An image is divided into cells that are deemed part of a barcode or not based on the number
* of edge pixels and the histogram of orientations of the edge pixels in the cell
*/
class Cell
{
public:
/** boundaries of the cell */
TRectInt box;
/** Histogram of orientations for this cell */
vector<TUInt> orientationHistogram;
/** Histogram of orientations for this cell */
vector<TUInt> weightedOrientationHistogram;
private:
/** Dominant orientation of this cell, value is set by findDominantOrientation(), which must be run before reading. */
int dominantOrientation_;
/** Entropy of this cell, value is set by calculateEntropy(), which must be run before reading. */
double entropy_;
/** Number of pixels voting in the orientation histogram */
TUInt nVoters_;
/** Maximum entropy allowed */
double maxEntropy_;
/** Number of possible orientations */
TUInt nOrientations_;
public:
/**
* Constructor
* @param[in] aBox cell area.
* @param[in] nOrientations number of orientation bins.
* @param[in] maximum entropy allowed
*/
Cell(const TRectInt &aBox, TUInt nOrientations, double maxEntropy);
/**
* Clears the voters the orientation histogram, and the isSet flag.
*/
void reset();
/**
* Adds a new pixel vote
* @param[in] orientation orientation of the pixel
* @param[in] magnitude of this pixel
*/
void addVoter(TUInt8 orientation, TUInt8 magnitude);
/**
* Returns the dominant orientation in this cell and sets the dominantOrientation value.
* @return dominant orientation
*/
int dominantOrientation();
/**
* Calculates the entropy of this cell, and sets the entropy value.
* @return entropy
*/
double entropy();
/**
* Returns true is this cell has low entropy
*/
inline bool hasLowEntropy() {return ( entropy() < maxEntropy_ ); };
/**
* Returns true is this cell has sufficient number of voters
*/
inline bool hasEnoughVoters() const {return ( nVoters_ > ((TUInt) box.area() >> 2) ); };
/**
* True if this cell passes the tests for further consideration
* @return true if the cell has both low entropy and sufficient number of voters
*/
inline bool shouldBeConsidered() {return hasLowEntropy() && hasEnoughVoters(); };
/**
* Returns the number of voting pixels
*/
inline TUInt nVoters() {return nVoters_; };
/**
* Returns the center of the cell
*/
inline TPointInt center() {return (box.tl() + box.br()) * .5; };
};
/**
* Collects votes from each pixel for barcode location/orientation.
* @param[out] modes modes of the orientation histogram.
*/
void getOrientationCandidates(vector<Vote> &modes);
/**
* Calculates the histograms of non-overlapping cells in the image
*/
void calculateCellHistograms();
/**
* Calculates the image orientation histogram from cell histograms.
*/
void calculateOrientationHistogram();
/**
* Calculates the modes of the orientation histogram
* @param[out] modes modes of the orientation histogram.
*/
void findOrientationHistogramModes(vector<Vote> &modes);
/**
* Called by histogram modes, finds the modes using gradient ascent.
*/
void ascendModes(const vector<Vote> &votes, vector<Vote> &modes);
/**
* Finds barcode candidates at given orientation candidates.
* @param[in] modes modes of the orientation histogram.
*/
void getBarcodeCandidates(const vector<Vote> &modes);
/**
* Finds clusters of barcode candidates at a given orientation
* @param[in] theta orientation to look for the candidates in
* @param[out] candidates returns the candidates for barcode centers
*/
void getCandidateCellClusters(double theta, vector<TPointInt> &candidates);
/**
* Scans a segment to see if there is barcode evidence.
* @param[out] aBC barcode to save if the segment is indeed a good candidate
* @param[in] pt TPointInt to start the scan
* @param[in, out] qBegin pointer to where in the scanline we start the scan
* @param[in] qEnd pointer to where in the scanline we end the scan
* The scan starts from pt, proceeds along qBegin .. qEnd unless a barcode segment is found,
* in which case it returns true and qBegin points at the last TPointInt we were in the scanline.
* @return true if a viable barcode segment has been found.
*/
bool scanSegment(BarcodeCandidate &aBC, const TPointInt &pt);
/**
* Prepares the pixel-to-cell lookup table and cell vector
*/
void prepareCells();
/**
* Generates trigonometric lookup tables for the Hough transform
*/
void prepareTrigLookups();
/**
* Prepares the scanlines to follow
*/
void prepareScanLines();
/** matrix of cells from the image */
vector<vector<Cell> > cells_;
/** Mapping from pixels to cell indices to easily find which cell pixel (i,j) belongs to. */
#ifdef USE_OPENCV //When using gcc4.7+, use type-alias
cv::Mat_<Cell*> mapPixelToCell_;
#else
ski::TMatrix<Cell*> mapPixelToCell_;
#endif
/**
* Lookup table for hough votes, cosLookupTable(i)=i*cos(theta)/dr and sinLookupTable(j)=j*sin(theta)/dr
* r(i,j) = cosLookupTable[i] + sinLookupTable[j];
*/
TMatrixInt cosLookupTable_, sinLookupTable_;
/**
* Histogram of hough votes over the orientations (column summation of the Hough matrix)
*/
vector<TUInt> orientationHistogram_;
/** Scan lines to sweep. iScanLines_[o] is a scanline to sweep for orientation o */
vector<vector<TPointInt> > scanLines_;
/** Acceptable angles for a given orientation */
TMatrixBool isAcceptable_;
};
#endif //BARCODE_LOCATOR_H_
|
rmorbach/blade | include/ski/viterbi.h | <filename>include/ski/viterbi.h
/*
Copyright (c) 2012, The Smith-Kettlewell Eye Research Institute
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Smith-Kettlewell Eye Research Institute nor
the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE SMITH-KETTLEWELL EYE RESEARCH INSTITUTE BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* Defines a Viterbi class which can be used to set up and run a Viterbi algorithm.
* @author <NAME>
*/
#ifndef VITERBI_H
#define VITERBI_H
#include <vector>
#undef max
#undef min
#include "ski/math.h"
#include "ski/types.h"
#include <stdexcept>
#include <algorithm>
/*WARNING: If the type is a bounded type (such as int), overflows may give incorrect results.
Thus, it is recommended to use a larger type than strictly necessary (e.g. int instead of int8 etc.);
*/
using namespace std;
//=================================
//Implements the Viterbi algorithm
//=================================
/**
* Class declaration for minimum Energy Viterbi Path detection
*/
template <typename T=double>
class Viterbi
{
public:
/**
* Return type for Viterbi - holds the energy and path of a sequence.
*/
typedef vector<T> TArray_;
#if CAN_USE_TEMPLATE_ALIAS
typedef ski::TMat<T> TMatrix_;
#elif defined USE_OPENCV //TODO: once template aliases are implemented (gcc4.7+), use template aliases in cv.hpp instead
typedef cv::Mat_<T> TMatrix_;
#else
typedef ski::TMatrix<T> TMatrix_;
#endif
struct Solution
{
/** energy of solution */
T energy;
/** sequence of state indices for this solution */
vector<int> sequence;
/**
* Initialization
*/
Solution (): energy((T) 0) {};
/**
* Initialization with the expected path length
* @param[in] n length of path.
*/
Solution (int n): energy((T) 0), sequence(n, 0) {};
};
struct SubState
{
/** energy of this state */
T energy;
/** index of this state */
int index;
/** Path of this state */
int path;
/** Previous state in the path to this state */
const SubState *prevState;
/** Constructor */
SubState(int i, int j=0, T e=((T) 0), SubState *pS=NULL);
/** Copy constructor */
SubState(const SubState &aSubState);
/** For sorting states */
inline bool operator< (const SubState& anotherState) {return energy < anotherState.energy; };
};
struct State
{
/** index */
int index;
/** Number of paths in this state */
int nPaths;
/** substates of this state */
vector<SubState> substates;
/**
* Constructor
* @param[in] i index of the state
* @param[in] n number of contained substates
*/
State(int i, int n=1);
/** Destructor */
~State() {};
/**
* Calculates and assigns energies from priors only
* @param[in] prior prior for this time and state
*/
void calculate(T prior);
/**
* Calculates and assigns energies using energies of previous states, prior and conditionals
* @param[in] prevStates energies of the states at the previous time
* @param[in] prior prior for this time
* @param[in] conditionals vector of conditional energies at this time given the states at the previous time
*/
void calculate(const vector<State> &prevStates, T prior, const TMatrix_ &conditionals);
};
struct Variable
{
/** States of this variable */
vector<State> states;
/**
* Constructor
* @param[in] t index of this variable
* @param[in] n number of states of this variable
*/
Variable(int t, int n);
/** Destructor */
~Variable() {};
/** Index of this variable */
int index;
/** Number of paths to track for each state */
int nPaths;
/**
* Resizes the variable to have n states
* @param[in] n number of states the variable can have
*/
void resize(int n);
/**
* Calculates the state energies from the prior
*/
void calculate(const vector<T> &prior);
/**
* Calculates the state energies from the previous variable, prior and conditions
* @param[in] prevVar previous variable
* @param[in] prior prior energies
* @param[in] conditional conditional energies
*/
void calculate(const Variable &prevVar, const TArray_ prior, const TMatrix_ conditional);
/**
* Finds the best nPaths substates and returns references to them.
* @param[out] beststates references to the best substates
*/
void bestStates(vector<SubState> &beststates);
};
/**
* Constructor
* @param[in] sE singleton energies. sE[t](i) is the energy of state i at time t.
* @param[in] pE pairwise energies. pE[t](i,j) is the energy to move from state i at time t to state j at time t+1.
* @param[in] nPaths number of paths to return.
*
*/
Viterbi(const vector<TArray_> &sE, const vector<TMatrix_> &pE, int nPaths=1);
/**
* Destructor
*/
~Viterbi();
/**
* Solves the Viterbi algorithm.
* @param[in] finalState index of the final state to end. By default, just finds the best state.
* If given a valid index, backtracks from that specific state.
*/
void solve(int finalState=-1);
/** Holds the solutions to the Viterbi, sorted in order of increasing energy*/
vector<Solution> solutions;
private:
/**
* Runs the algorithm
*/
void run();
/**
* backtracks from pseudostate finalState
* @param[in] finalState final state to backtrack from
*/
void backtrack(int finalState);
/**
* Checks the consistency of the inputs and prints errors if there is a problem.
* Also initializes the states.
* @return true if the inputs are of consistent size.
*/
void initialize();
/** Reference to the singleton energies. [t](i) is the prior energy of state i at time t */
const vector<TArray_> &priors_;
/** Reference to the pairwise energies. conditionals_[t](i,j) is the conditional energy from i to j at time t */
const vector<TMatrix_> &conditionals_;
/** sequence length */
int time_;
/** number of paths to track */
int nPaths_;
/**States*/
vector<Variable> vars_;
};
//==================
// Substates
//===================
template <typename T>
Viterbi<T>::SubState::SubState(int i, int j/*=0*/, T e/*=((T) 0)*/, SubState *pS/*=NULL*/):
energy(e),
index(i),
path(j),
prevState(pS)
{
}
template <typename T>
Viterbi<T>::SubState::SubState(const SubState &aSubState):
energy(aSubState.energy),
index(aSubState.index),
path(aSubState.path),
prevState(aSubState.prevState)
{
}
//==================
// States
//===================
template <typename T>
Viterbi<T>::State::State(int i, int n/*=1*/):
index(i),
nPaths(n),
substates(n, SubState(i))
{
}
//==================
// Variables
//===================
template <typename T>
Viterbi<T>::Variable::Variable(int t, int p):
index(t),
nPaths(p)
{
}
template <typename T>
void Viterbi<T>::Variable::resize(int nStates)
{
//Add states if necessary
states.reserve(nStates);
for (int n = states.size(); n < nStates; n++)
states.push_back(State(n, nPaths));
//trim states if too many
states.erase(states.begin() + nStates, states.end());
}
template <typename T>
void Viterbi<T>::Variable::calculate(const TArray_ &prior)
{
resize(prior.size());
typename vector<T>::const_iterator p = prior.begin();
for (typename vector<State>::iterator s = states.begin(); s != states.end(); s++, p++)
{
int path = 0;
for (typename vector<SubState>::iterator ss = s->substates.begin(); ss!= s->substates.end(); ss++)
{
ss->energy = (ss == s->substates.begin() ? *p : ski::MaxValue<T>() / 2);//*p;
ss->path = path++;
}
}
}
template <typename T>
void Viterbi<T>::Variable::calculate(const Variable &prevVar, const TArray_ prior, const TMatrix_ conditional)
{
if (prior.size() != states.size())
resize(prior.size());
if ( (conditional.rows != (int) prevVar.states.size()) || (conditional.cols != (int) states.size()) )
throw logic_error("Viterbi::Variable: Size mismatch.");
//For each state, calculate the min energy paths
static vector<SubState> allPaths;
int nAllPaths = prevVar.states.size() * prevVar.nPaths;
allPaths.resize(nAllPaths, SubState(0));
int n = 0;
for (typename vector<State>::iterator s = states.begin(); s != states.end(); s++, n++)
{
T statePriorEnergy = prior[n];
typename vector<SubState>::iterator p = allPaths.begin();
int pN = 0; //index of previous state
for (typename vector<State>::const_iterator pS = prevVar.states.begin(); pS != prevVar.states.end(); pS++, pN++)
{
T stateTotalEnergy = statePriorEnergy + conditional(pN, n);
for (typename vector<SubState>::const_iterator pSS = pS->substates.begin(); pSS != pS->substates.end(); pSS++, p++)
{
p->prevState = &(*pSS);
p->energy = stateTotalEnergy + pSS->energy;
}
}
partial_sort_copy(allPaths.begin(), allPaths.end(), s->substates.begin(), s->substates.end());
//Fix path numbers
int i = 0;
for (typename vector<SubState>::iterator ss = s->substates.begin(); ss != s->substates.end(); ss++)
{
ss->index = n;
ss->path = i++;
}
}
}
template <typename T>
void Viterbi<T>::Variable::bestStates(vector<SubState> &beststates)
{
//For each state, calculate the min energy paths
int nAllStates= states.size() * nPaths;
beststates.clear();
beststates.reserve(nAllStates);
for (typename vector<State>::iterator s = states.begin(); s != states.end(); s++)
{
for (typename vector<SubState>::iterator ss = s->substates.begin(); ss != s->substates.end(); ss++)
beststates.push_back(*ss);
}
partial_sort(beststates.begin(), beststates.begin() + nPaths, beststates.end());
beststates.resize(nPaths, SubState(-1));
}
//==================
//VITERBI
//===================
template <typename T>
Viterbi<T>::Viterbi(const vector<TArray_ > &priorMat, const vector<TMatrix_> &condMat, int nPaths/*=1*/):
solutions(nPaths),
priors_(priorMat),
conditionals_(condMat),
nPaths_(nPaths)
{
}
template <typename T>
Viterbi<T>::~Viterbi()
{
}
template <typename T>
void Viterbi<T>::initialize()
{
/*Checks that the sizes of the priors and conditionals are consistent with each other.
Also assigns the time_ and nStates_ variables;
Priors_[t] gives the size of nStates_[t],
Conditionals_[t-1] nStates_[t-1] x nStates_[t]
*/
time_ = priors_.size();
//Check lengths:
if ((int) conditionals_.size() != time_-1)
throw logic_error("Viterbi: Time inconsistency!");
//Check that the matrices are compatible
for (int t = 1; t < time_; t++)
{
if ( (conditionals_[t-1].rows != priors_[t-1].size())
|| (conditionals_[t-1].cols != priors_[t].size()) )
throw logic_error("Viterbi: Sizes of the provided matrices are not consistent!");
}
//Add states if need be
vars_.reserve(time_);
for (int t = vars_.size(); t < time_; t++)
vars_.push_back(Variable(t, nPaths_));
vars_.erase(vars_.begin() + time_, vars_.end());
/** Initialize solutions */
for (typename vector<Solution>::iterator s = solutions.begin(); s!= solutions.end(); s++)
{
s->energy = (T) 0;
s->sequence.resize(time_);
}
}
template <typename T>
void Viterbi<T>::solve(int finalState/*=-1*/)
{
/* Returns nPaths best (min energy) Viterbi sequences ending at finalState
* and their corresponding energies. */
//Ensure finalState is valid:
if ( (finalState >= (int) priors_.back().size()) || (finalState < -1) )
throw invalid_argument("Viterbi: Final state not valid.");
try
{
//Initialize states
initialize();
//Run the Viterbi
run();
//Backtrack
backtrack(finalState);
}
catch (exception &aErr)
{
throw aErr;
}
}
template <typename T>
void Viterbi<T>::run()
{
vars_[0].calculate(priors_[0]);
for (int t = 1; t < time_; t++)
vars_[t].calculate(vars_[t-1], priors_[t], conditionals_[t-1]);
}
template <typename T>
void Viterbi<T>::backtrack(int finalState)
{
//Backtracks from the final state given in argument
Variable &lastVar = vars_[time_-1];
vector<SubState> finalStates;
const SubState *aState;
if (finalState == -1)
lastVar.bestStates(finalStates);
else
finalStates.assign(lastVar.states[finalState].substates.begin(), lastVar.states[finalState].substates.end());
for (int n = 0; n < nPaths_; n++)
{
aState = &finalStates[n];
solutions[n].energy = aState->energy;
for (int t = time_-1; t >= 0; t--)
{
solutions[n].sequence[t] = aState->index;
aState = aState->prevState;
}
}
}
#ifdef _LIBTEST
void testViterbi()
{
typedef int curType; //change curType to test different types
int T = 4, nStates = 3;
vector<vector<curType> > prior;
vector<Mat_<curType> > cond;
for (int t = 0; t < T; t++)
prior.push_back(vector<curType>(nStates));
for (int t = 0; t < T - 1; t++)
cond.push_back(Mat_<curType>(nStates, nStates));
cond[0](0,0) = 1;
cond[0](0,1) = 0;
cond[0](0,2) = 1;
cond[0](1,0) = 0;
cond[0](1,1) = 1;
cond[0](1,2) = 2;
cond[0](2,0) = 1;
cond[0](2,1) = 2;
cond[0](2,2) = 1;
cond[1](0,0) = 0;
cond[1](0,1) = 1;
cond[1](0,2) = 1;
cond[1](1,0) = 1;
cond[1](1,1) = 2;
cond[1](1,2) = 1;
cond[1](2,0) = 3;
cond[1](2,1) = 0;
cond[1](2,2) = 1;
cond[2](0,0) = 2;
cond[2](0,1) = 2;
cond[2](0,2) = 1;
cond[2](1,0) = 3;
cond[2](1,1) = 1;
cond[2](1,2) = 0;
cond[2](2,0) = 1;
cond[2](2,1) = 0;
cond[2](2,2) = 2;
prior[0][0] = 1;
prior[0][1] = 1;
prior[0][2] = 2;
prior[1][0] = 2;
prior[1][1] = 1;
prior[1][2] = 0;
prior[2][0] = 1;
prior[2][1] = 1;
prior[2][2] = 2;
prior[3][0] = 0;
prior[3][1] = 1;
prior[3][2] = 1;
int nPaths = 4;
Viterbi<curType> V(prior, cond, nPaths);
V.solve();
for (int p = 0; p < nPaths; p++){
printf("%d'th best path: ",p);
for (int t=0; t<4; t++)
printf("%d,", V.solutions[p].sequence[t]);
printf(" with energy %d.\n", V.solutions[p].energy); //change %d to %f if curType==float etc.
}
int finalState = 1;
V.solve(finalState);
for (int p = 0; p < nPaths; p++){
printf("%d'th best path ending at %d: ", p, finalState);
for (int t=0; t<4; t++)
printf("%d,", V.solutions[p].sequence[t]);
printf(" with energy %d.\n", V.solutions[p].energy); //change %d to %f if curType==float etc.
}
return;
//Correct results for this test:
//V.minEnergy(4);
//[4 5 5 5]
//V.bestSequence(4);
//[0 2 1 2; 0 2 1 1; 1 2 1 2; 2 2 1 2] (sequences are rows)
//V.minEnergy(4,1);
//[5 6 6 6]
//V.bestSequence(4,1);
//P=[0 2 1 1; 0 1 2 1; 1 2 1 1; 0 2 2 1] (sequences are rows)
}
#endif //LIBTEST
#endif // VITERBI_H
|
rmorbach/blade | include/ski/Sound/SoundManager.h | <filename>include/ski/Sound/SoundManager.h
/*
Copyright (c) 2012, The Smith-Kettlewell Eye Research Institute
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Smith-Kettlewell Eye Research Institute nor
the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE SMITH-KETTLEWELL EYE RESEARCH INSTITUTE BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* SoundManager.h
*
* Created on: Jul 30, 2012
* Author: kamyon
*/
#ifndef SOUNDMANAGER_H_
#define SOUNDMANAGER_H_
#include "ski/types.h"
#include <string>
#include <memory>
//Forward declaration of implementation
class AlsaAccess;
/**
* @class Sound manager class
*/
class SoundManager
{
public:
///Audio data is limited to signed 16-bit int.
typedef TInt16 TAudioData;
/** Audio parameters to use. For simplicity, we assume the device supports interleaved signed 16-bit samples
* Thus, for a 2 channel signal, the audio frame byte-pattern should look like:
* L1 L1 R1 R1 L2 L2 R2 R2 ...
* See http://www.alsa-project.org/main/index.php/FramesPeriods for more details
*/
struct Parameters
{
/** Number of channels */
TUInt nChannels;
/** Sampling rate */
TUInt samplingRate;
/** Period size in frames = # of frames per period*/
TUInt64 periodSize;
/** Number of periods the buffer will contain */
TUInt nPeriods;
/** Buffer size in number of frames - this will be auto-set by the hardware*/
TUInt64 bufferSize;
/**
* Default constructor
* @param nC number of channels
* @param aRate sampling rate
* @param aPerSz number of frames per period
* @param nP number of periods in buffer
*/
Parameters(TUInt nC = 2, TUInt aRate=16000, TUInt64 aPerSz=4096, TUInt nP=4);
/** Frame size in bytes */
TUInt frameSizeInBytes() const;
/** Period size in bytes */
TUInt64 periodSizeInBytes() const;
};
enum Status
{
STATUS_CLOSED,
STATUS_READY,
STATUS_SUSPENDED,
STATUS_PAUSED,
STATUS_PLAYING,
STATUS_ERROR
};
//// Constructor
SoundManager();
/// Destructor
~SoundManager();
/**
* Opens an audio device.
* @param[in, out] parameters to try when opening device. The hardware may not allow certain paremeters,
* in which case the actual parameters used to open the device are used.
* @param[in] isSync if true, the device is opened for synchronous play; if false, it is opened for aynschronous play
*/
void open(Parameters ¶ms, bool isSync);
/**
* Closes the audio device.
*/
void close();
/**
* Returns a read-only pointer to the current audio parameters if device is open, null if it is not
* @return audio parameters of the playback device.
*/
const Parameters* getParameters() const;
/**
* Speaks out a piece of text using text to speech.
* @param aText text to speak out.
*/
void speak(const std::string &aText) const;
/**
* Queues a piece of audio to play
* The audio is assumed to contain one period's worth of frames, as given by getParameters();.
* @param audio pointer to audio data to play. One buffer's worth of data will be read from this location.
*/
void play(const TAudioData* audio) const;
/**
* Clears the queue and plays a piece of audio immediately. Any sound currently playing is stopped.
* The audio is assumed to contain one buffer's worth of samples, as given by getParameters();.
* @param audio pointer to audio data to play. One buffer's worth of data will be read from this location.
*/
void playNow(const TAudioData* audio) const;
/**
* Pauses playback without clearing the queue
*/
void pause() const;
/**
* Resumes a paused playback
*/
void resume() const;
/**
* Stops playback, finishing the playback queue first.
*/
void stop() const;
/**
* Stops playback immediately, clearing the playback queue.
*/
void stopNow() const;
/**
* Returns the current status of the playback device
* @return current sattus of the device
*/
Status getStatus() const;
protected:
std::unique_ptr<AlsaAccess> soundMngr_;
};
#endif /* SOUNDMANAGER_H_ */
|
rmorbach/blade | LinBLaDE/src/misc.h | /*
* misc.h
*
* Created on: Jul 25, 2012
* Author: kamyon
*/
#ifndef MISC_H_
#define MISC_H_
#include <cstdio>
#include "ski/log.h"
#include <string>
//#include "ski/cv.hpp"
#include "opencv2/opencv.hpp"
#include "ski/types.h"
namespace Draw
{
typedef struct{
TUInt8 b, g, r;
} TColor;
static const TColor colorRed = {0, 0, 255};
static const TColor colorGreen = {0, 255, 0};
static const TColor colorBlue = {255, 0, 0};
static const TColor colorWhite = {255, 255, 255};
static const TColor colorBlack = {0, 0, 0};
static const TColor colorLightGray= {200, 200, 200};
static const TColor colorDarkGray = {85, 85, 85};
static const TColor colorYellow = {0, 255, 255};
static const TColor colorCyan = {255, 255, 0};
static const TColor colorMagenta = {255, 0, 255};
/**
* Draws a line.
* @param[in] frame image to draw on.
* @param[in] pt1 one end of the line.
* @param[in] pt2 other end of the line.
* @param[in] aColor color of the line.
* @param[in] thickness in pixels.
* @param[in] scale that the coordinates were given in. The result is rendered at scale 0.
*/
void line(cv::Mat &frame, const cv::Point &pt1, const cv::Point &pt2, const TColor &aColor=colorRed, TUInt8 thickness=1, TInt scale=0);
/**
* Draws a line.
* @param[in] frame image to draw on.
* @param[in] pt1 one end of the line.
* @param[in] pt2 other end of the line.
* @param[in] aColor brightness of the line.
* @param[in] thickness in pixels.
* @param[in] scale that the coordinates were given in. The result is rendered at scale 0.
*/
void line(cv::Mat &frame, const cv::Point &pt1, const cv::Point &pt2, TUInt8 aIntensity=0, TUInt8 thickness=1, TInt scale=0);
/**
* Draws a cross.
* @param[in] frame image to draw on.
* @param[in] aRect box to draw a cross in.
* @param[in] aColor color of the cross
* @param[in] thickness in pixels
* @param[in] scale that the coordinates were given in. The result is rendered at scale 0.
*/
void cross(cv::Mat &frame, const cv::Rect &aRect, const TColor &aColor=colorRed, TUInt8 thickness=1, TInt scale=0);
/**
* Draws a frame.
* @param[in] frame image to draw on.
* @param[in] aRect box to draw a frame around.
* corner[0] is connected to corner[1] which is connected to corner[2], which is
* connected to corner[3], which is connected back to corner[0].
* @param[in] aColor color of the frame
* @param[in] thickness in pixels
* @param[in] scale that the coordinates were given in. The result is rendered at scale 0.
*/
void frame(cv::Mat &frame, const cv::Rect &aRect, const TColor& aColor=colorRed, TUInt8 thickness=1, TInt scale=0);
/**
* Draws text.
* @param[in] frame image to draw on.
* @param[in] aPoint anchor point of the text.
* @param[in] aText text to draw.
* @param[in] aColor color of the text.
* @param[in] scale that the coordinates were given in. The result is rendered at scale 0.
*/
void text(cv::Mat &frame, const cv::Point &aPoint, const std::string &aText, const TColor &aColor=colorRed, TInt scale=0);
/**
* Draws text on grayscale images.
* @param[in] frame image to draw on.
* @param[in] aPoint anchor point of the text.
* @param[in] aText text to draw.
* @param[in] aIntensity brightness of the text.
* @param[in] scale that the coordinates were given in. The result is rendered at scale 0.
*/
void text(cv::Mat &frame, const cv::Point &aPoint, const std::string &aText, TUInt8 aIntensity, TInt scale=0);
/**
* Converts a TColor to Scalar.
* @param[in] aColor TColor to convert
* @return resulting Scalar.
*/
cv::Scalar convertColor(const TColor &aColor);
/**
* Converts a Scalar to TColor.
* @param[in] aColor Scalar to convert
* @return resulting TColor.
*/
TColor convertColor(const cv::Scalar &aColor);
} //end namespace Draw
#endif /* MISC_H_ */
|
rmorbach/blade | BLaDE/src/algorithms.h | /*
Copyright (c) 2012, The Smith-Kettlewell Eye Research Institute
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Smith-Kettlewell Eye Research Institute nor
the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE SMITH-KETTLEWELL EYE RESEARCH INSTITUTE BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* Some Algorithms
* @author <NAME>
*/
#ifndef EALGORITHMS_H_
#define EALGORITHMS_H_
#include "ski/math.h"
#include "ski/type_traits.h"
#include "ski/cv.hpp"
#include <vector>
using namespace std;
namespace ski
{
/** @class Vote template for voting algorithms */
template<class T1, class T2>
struct Vote_
{
/** location of the vote */
T1 loc;
/** weight of the vote */
T2 weight;
/**
* Constructor
* @param[in] x location of the vote
* @param[in] w weight of the vote
*/
Vote_(T1 x=T1(), T2 w=T2()): loc(x), weight(w) {};
};
/** Some commonly used vote types */
typedef Vote_<double, double> Vote;
typedef Vote_<TPointInt, double> VoteP;
/** @class Kernel template class */
template<class T>
class Kernel
{
public:
/** Returns the value of the kernel at a given location */
virtual double value(T x) const = 0;
/** Destructor */
virtual ~Kernel() {};
};
/**
* Evaluates the value of a point on a distribution based on weighted kde that wraps around.
* @param[in] p vector of distribution weights, a kde is fitted to each point
* @param[in] x the place to evaluate kde at.
* @param[in] kernel kernel to use in the kde
* @return the evaluated value
*/
template<class T1, class T2>
T2 kde(const vector<Vote_<T1, T2> > &p, const T1 x, const Kernel<T1> &kernel)
{
typedef typename vector<struct Vote_<T1, T2> >::const_iterator VoteIterator;
T2 w = T2();
for (VoteIterator v = p.begin(); v != p.end(); v++)
w += v->weight * kernel.value(v->loc - x);
return w;
};
/**
* Performs mean shift to find mode of distribution p assuming the distribution wraps around
* @param[in] pIn vector of distribution weights and locations, a kde is fitted to each point
* @param[in, out] pOut vector of modes and their weights. Contains the initial locations to perform mean shift on.
* @param[in] kernel kernel to use in the kde
*/
template<class T1, class T2>
void meanShift(const vector<class Vote_<T1, T2> > &pIn, vector<class Vote_<T1, T2> > &pOut, const Kernel<T1> &kernel)
{
TUInt n = pIn.size();
pOut = pIn;
if (n < 2)
return;
//generate weighted vector
vector<Vote_<T1, T1> > pWeighted;
pWeighted.reserve(n);
typedef typename vector<struct Vote_<T1, T2> >::const_iterator VoteConstIterator;
typedef typename vector<struct Vote_<T1, T2> >::iterator VoteIterator;
for (VoteConstIterator x = pIn.begin(); x != pIn.end(); x++)
pWeighted.push_back( Vote_<T1, T1>(x->loc, x->loc * x->weight) );
static const TUInt maxIter = 100;
static const double maxDist = 0.01;
for (TUInt i = 0; i < maxIter; i++)
{
double totDistanceMoved = 0;
for (VoteIterator x = pOut.begin(); x != pOut.end(); x++)
{
x->weight = kde(pIn, x->loc, kernel);
T1 newLoc = kde(pWeighted, x->loc, kernel) * (1 / x->weight);
totDistanceMoved += distance(x->loc, newLoc);
x->loc = newLoc;
}
//check for convergence
if (totDistanceMoved < maxDist)
break;
}
};
/**
* Finds the centers of data that are a certain distance from each other
*/
template <class T1>
void findClusterCenters(const vector<class Vote_<T1, double> > &data, vector<class Vote_<T1, double> > ¢ers, double radius)
{
//ensure output is empty
centers.clear();
bool isMatchFound=false;
typedef typename vector<class Vote_<T1, double> >::const_iterator VoteConstIterator;
typedef typename vector<class Vote_<T1, double> >::iterator VoteIterator;
VoteConstIterator v;
VoteIterator v2;
for (v = data.begin(); v!= data.end(); v++)
{
for (v2 = centers.begin(); v2 != centers.end(); v2++)
{
if ( ( isMatchFound = ( distance(v->loc, v2->loc) < radius ) ) ) //if matches an existing center
break;
}
if (!isMatchFound)
centers.push_back(*v); //no match found, create new cluster center
else
{
//Recalculate center and weight of the matching cluster
double totWeight = v->weight + v2->weight;
v2->loc = v2->loc * (v2->weight / totWeight) + v->loc * (v->weight / totWeight);
v2->weight = totWeight;
}
}
};
/*
* Specializations
*/
/** Gaussian kernel for reals */
class GaussianKernelD: public Kernel<double>
{
public:
/**
* Constructor
* @param[in] var variance of the kernel
*/
GaussianKernelD(double var): z(1 / sqrt(2 * ski::PI * var)), c(-.5 / var) {};
/**
* Returns the value of the kernel
* @param[in] d value to evaluate the kernel at
* @return value of the kernel at d.
*/
inline virtual double value(double d) const {return exp(c * d * d) / z; };
private:
/** Constants for this kernel */
const double z, c;
};
/**
* @class Kernel used in meanshift in 2D space
*/
class GaussianKernelPt: public Kernel<TPointInt>
{
public:
/**
* Constructor
* @param[in] var variance of the kernel
*/
GaussianKernelPt(double var): z(1 / sqrt(2 * PI * var)), c(-.5 / var) {};
/**
* Returns the value of the kernel
* @param[in] d value to evaluate the kernel at
* @return value of the kernel at d.
*/
inline virtual double value(TPointInt d) const { return exp(c * norm(d)) / z; };
private:
/** Constants for this kernel */
const double z, c;
};
/**
* @class Kernel used in kde that takes into account wraparound in 1D space
*/
class GaussianKernelRot: public Kernel<double>
{
public:
/**
* Constructor
* @param[in] var variance of the kernel
* @param[in] maxVal maximum value of the kernel argument
*/
GaussianKernelRot(double var, double maxVal): z(1 / sqrt(2 * PI * var)), c(-.5 / var), lim(maxVal) {};
/**
* Returns the value of the kernel
* @param[in] d value to evaluate the kernel at
* @return value of the kernel at d.
*/
inline virtual double value(double d) const
{
d = abs(d);
if (d > lim)
d = 2*lim-d;
return exp(c * d * d) / z;
};
private:
/** Constants for this kernel */
double z, c, lim;
};
} //end namespace E
#endif // EALGORITHMS_H_
|
rmorbach/blade | include/ski/BLaDE/Symbology.h | /*
Copyright (c) 2012, The Smith-Kettlewell Eye Research Institute
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Smith-Kettlewell Eye Research Institute nor
the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE SMITH-KETTLEWELL EYE RESEARCH INSTITUTE BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file Symbology.h
* @author <NAME>
*
*/
#ifndef SYMBOLOGY_H_
#define SYMBOLOGY_H_
#include <string>
#include <vector>
#include <list>
#include "ski/cv.hpp"
/** Matrix to store digit energies, energies_(digit, symbol)*/
typedef double TEnergy;
typedef TMatrixDouble TMatEnergy;
using namespace std;
/**
* Class for constant-width barcode structures
*/
class BarcodeSymbology
{
public:
/**
* Struct for expected barcode structure edges
*/
struct Edge
{
/**
* Constructor
* @param[in] i index of this edge
* @param[in] loc location of this edge
*/
Edge(int i, int loc) : index(i), location(loc) {};
/** Index of the edge from the beginning */
int index;
/** Location of this edge */
int location;
/**
* Whether this is a fixed edge or not
* @return true if this edge's location is known (this is a fixed edge).
*/
inline bool isFixed() const {return (location != -1); };
/** Polarity of this edge, must be one of -1 for even edges, 1 for odd edges */
inline int polarity() const {return (index % 2 ? 1 : -1); };
/** Number of positive edges before this edge */
inline int nPreviousPositiveEdges() const {return index >> 1; };
/** Number of negative edges before this edge */
inline int nPreviousNegativeEdges() const {return (index % 2 ? (index >> 1) + 1 : index >> 1); };
};
struct Bar
{
/**
* Constructor
* @param[in] left pointer to left edge of this bar.
* @param[in] right pointer to left edge of this bar.
*/
inline Bar(Edge *left, Edge *right) : leftEdge(left), rightEdge(right), index(left->index) {};
/** Polarity of the stripe, 1 for light stripes, -1 for dark stripes */
inline bool isDark() const {return (leftEdge->polarity() == -1); };
/** Left edge*/
Edge *leftEdge;
/** Right edge location */
Edge *rightEdge;
/** Index of the bar starting from the beginning */
int index;
/** Width of this stripe in terms of the fundamental width. -1 means unknown */
inline int width() const { return ( leftEdge->isFixed() && rightEdge->isFixed() ? rightEdge->location - leftEdge->location : -1); };
};
/**
* Class for constant width barcode symbols
*/
struct Symbol
{
/**
* Constructor for a symbol with known pattern, such as guardbands
* @param[in] aWidth width of the symbol in multiples of the fundamental width
* @param[in] dataSymbolIndex index of data symbol. -1 if this is not a data symbol.
* @param[in] aBars vector representing the symbol bars.
*/
Symbol(TUInt aWidth, int dataSymbolIndex, vector<Bar*> aBars);
/** Width of symbol. */
TUInt width;
/** index of this data symbol. -1 if this is a special symbol */
int index;
/** Pattern */
vector<Bar*> bars;
/**
* Left edge of this symbol
* @return pointer to left edge of the first bar of this symbol
*/
inline const Edge* leftEdge() const {return bars.front()->leftEdge; };
/**
* Right edge of this symbol
* @return pointer to right edge of the last bar of this symbol
*/
inline const Edge* rightEdge() const {return bars.back()->rightEdge; };
/** Whether this is a special symbol or a data symbol */
inline bool isDataSymbol() const {return (index != -1); };
};
/**
* Constructor
* @param[in] name of symbology
* TODO: symbologies should only be held through handles -> move this to protected and add static create() method.
*/
BarcodeSymbology(const char name[]) : name_(name), nDataSymbols_(0), nFixedEdges_(0) {};
/**
* Destructor
*/
virtual ~BarcodeSymbology() {};
/**
* Name of symbology
* @return a string that is the symbology name
*/
inline const char* name() const {return name_; };
/**
* Returns a reference to the requested fixed edge
* @param[in] i index of the fixed edge
* @return pointer to the requested fixed edge
*/
const Edge* getFixedEdge(TUInt i) const;
/**
* Returns a reference to the requested data symbol
* @param[in] i index of the data symbol
* @return pointer to the requested symbol.
*/
const Symbol* getDataSymbol(TUInt i) const;
/**
* Number of data symbols in the symbology
*/
inline TUInt nDataSymbols() const { return dataSymbols_.size(); };
/**
* Number of fixed edges in the symbology
*/
inline TUInt nFixedEdges() const {return fixedEdges_.size(); };
/**
* Number of total edges in the symbology
*/
inline TUInt nTotalEdges() const {return edges_.size(); };
/**
* Width of the symbology in terms of the fundamental width
*/
inline TUInt width() const {return edges_.back().location; };
/**
* Will return a convolution pattern for the particular symbology. Must be overwritten by the derived symbology
*/
virtual void getConvolutionPattern(TUInt digit, double x, bool isFlipped, vector<TUInt> &pattern) const;
/**
* Final joint decoding of the barcode from digit energies.
* This method must be overwritten by the specific symbologies.
* @param[in] energy matrix, where energies[s,d] corresponds to the energy of the s'th symbol being digit d
* @return a string that is the barcode estimate, empty string if no verified estimate is made
*/
virtual string estimate(const TMatEnergy &energies) const = 0;
/**
* Convert estimated symbols to a string
* @param[in] aEstimate estimate of most likely symbols from given symbol energies,
* corresponding to the row indices in the energy matrix.
* @return a string that represents the vector of symbols in textual form
*/
virtual string convertEstimateToString(const vector<TUInt> &aEstimate) const;
protected:
//Symbology name
const char *name_;
//Barcode representation:
/** Representation of the barcode as a vector of edges.*/
list<Edge> edges_;
/** Representation of the barcode as a vector of bars.*/
list<Bar> bars_;
/** Representation of the barcode as a vector of symbols.*/
list<Symbol> symbols_;
/** Pointers to the fixed edges of the barcode */
vector<Edge*> fixedEdges_;
/** Pointers to the data symbols of the barcode */
vector<Symbol*> dataSymbols_;
/** Number of data symbols in this symbology */
TUInt nDataSymbols_;
/** Number of fixed edges in this symbology */
TUInt nFixedEdges_;
/**
* Adds a symbol to the barcode symbol representation
* @param[in] width width of the symbol in multiples of the fundamental width
* @param[in] nBars Number of bars+gaps in the symbol
* @param[in] pattern pointer to array representing the symbol pattern. NULL if unknown.
*/
Symbol* addSymbol(TUInt width, TUInt nBars, const TUInt *pattern=NULL);
private:
/**
* Adds a bar to the barcode bar representation
* @param[in] rightEdgeLocation location of the right edge if known, -1 if unknown.
*/
Bar* addBar(int rightEdgeLocation);
/**
* Adds an edge to the barcode edge representation
* @param[in] loc location of the edge.
*/
Edge* addEdge(int loc);
};
#endif /* SYMBOLOGY_H_ */
|
rmorbach/blade | include/ski/math.h | <filename>include/ski/math.h
/*
Copyright (c) 2012, The Smith-Kettlewell Eye Research Institute
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Smith-Kettlewell Eye Research Institute nor
the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE SMITH-KETTLEWELL EYE RESEARCH INSTITUTE BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Math header for general use
* <NAME>
*/
#ifndef SKI_MATH_H_
#define SKI_MATH_H_
#include <cmath>
#include "ski/types.h"
#include "ski/type_traits.h"
#include <stdarg.h>
#undef max
#undef min
#undef MAXINT
#undef MININT
#undef MAXUINT
#include <limits>
#include "ski/log.h"
namespace ski
{
const double PI=(4*atan(1.0));
const double INF = std::numeric_limits<double>::infinity();
const double NEGINF = -INF;
static const int MAXINT = (std::numeric_limits<int>::max)();
static const int MININT = (std::numeric_limits<int>::min)();
static const int MAXUINT = (std::numeric_limits<TUInt>::max)();
static const int VERYLARGE = MAXINT/16; //more formal in future.
/**
* returns the maximum number of a given type.
* @return maximum value of a given type.
*/
template<typename T>
inline T MaxValue() {return (std::numeric_limits<T>::has_infinity ? std::numeric_limits<T>::infinity() : (std::numeric_limits<T>::max)()); };
/**
* returns the minimum number of a given type.
* @return minimum value of a given type.
*/
template<typename T>
inline T MinValue() {return (std::numeric_limits<T>::has_infinity ? -std::numeric_limits<T>::infinity() : (std::numeric_limits<T>::min)() ); };
/**
* Integer power overload
* @param[in] aNumber integer to take power of.
* @param[in] aPow power
* @return aNumber ^ aPow. Note that the number can easily overflow. To avoid overflow, use a float or double version.
*/
inline int pow(int aNumber, int aPow) {return (aPow == 0 ? 1 : aNumber * pow(aNumber, aPow-1) ); };
/**
* Round
* @param[in] a value to round
* @return value rounded towards infinity
*/
inline double round( double value ) {return floor( value + 0.5 ); };
template <bool shouldBeRounded>
struct cast_selector
{
template <typename T1, typename T2>
inline static T2 cast(T1 val) {return (shouldBeRounded ? floor(val + 0.5): val); };
};
template <typename T1, typename T2>
inline T2 cast(T1 val) {return cast_selector<should_be_rounded<T1,T2>::value>::cast(val); };
template <typename T>
inline T cast (T val) { return val; };
///Template class to use the correct method.
template <bool isImplemented>
struct method_selector
{
template <class T>
inline static double norm(const T& obj) {return std::abs(obj); };
template <class T>
inline static double distance(const T& obj1, const T& obj2) {return norm(obj1-obj2); };
};
//Uses the object's norm method if the object is designated as having implemented norm()
template <>
struct method_selector<true>
{
template <class T>
inline static double norm(const T& obj) {return obj.norm(); };
template <class T>
inline static double distance(const T& obj1, const T& obj2) {return obj1.distance(obj2); };
};
template <typename T>
inline double norm(T val) {return std::abs((double) val); };
/*
template <class T>
inline double norm(const T &a)
{
return method_selector<implements<T>::norm>::norm(a);
};
*/
/**
* Distance between two objects
* @param[in] a object 1.
* @param[in] b object 2.
* If T is a complex class, the objects must implement a.norm(), b.norm() and the difference operator.
* @return distance between a and b.
*/
template <class T>
inline double distance(const T &a, const T &b) {return norm(a-b); };
}; //end namespace ski
#endif // SKI_MATH_H_
|
Pilooz/flipdots | arduino/flip_panel_node_client_ino_3rdgeneration/EntireFlipBoard.h | #ifndef ENTIREBOARD
#define ENTIREBOARD
#include <Arduino.h>
#include "FlipBoard.h"
#define DTIME 200 // Temps d'alimentation de la bobine
FlipBoard board1(0x21, 0x20);
/*FlipBoard board2(0x23, 0x22);
FlipBoard board3(0x25, 0x24);*/
class EntireBoard {
public:
void setup() {
Wire.begin(); // wake up I2C bus
board1.setup();
/*board2.setup();
board3.setup();*/
for (int i = 2; i <= 13; i++) {
pinMode(i, OUTPUT);
digitalWrite(i, LOW);
}
//this->clear();
}
void releaseCurrent() {
board1.releaseCurrent();
//board2.releaseCurrent();
//board3.releaseCurrent();
}
void releaseX() {
board1.releaseX();
//board2.releaseX();
//board3.releaseX();
}
void releaseY() {
board1.releaseY();
//board2.releaseY();
//board3.releaseY();
}
void clear() {
/*
for(int j=0; j<16; j++){
for(int i=0; i<28; i++){
this->setPixel(i, j, BLACK);
}
}
delay(100);
for(int j=0; j<16; j++){
for(int i=0; i<28; i++){
this->setPixel(27-i, 15-j, YELLOW);
}
}
*/
for (int i = 0; i < 28; i++) {
for (int j = 0; j < 16; j++) {
this->setPixel(i, j, BLACK);
}
}
for (int i = 0; i < 28; i++) {
for (int j = 0; j < 16; j++) {
this->setPixel(27 - i, 15 - j, YELLOW);
}
}
}
void selectPanel(unsigned char x, unsigned char y) {
if (y >= 0 && y < 16) {
if (x >= 0 && x < 28) {
digitalWrite(4, LOW);
digitalWrite(3, LOW);
digitalWrite(2, LOW);
board1.setEnablePin(true);
}
}
}
void setPixel(unsigned char x, unsigned char y, unsigned char color) {
if (y >= 0 && y < 16) {
unsigned char mask;
unsigned ay = y;
unsigned char ax = x;
board1.releaseX();
if (ay > 7 && ay <= 15) {
mask = 0x80 >> (y - 8);
if (color == YELLOW) {
board1.setLastColor( YELLOW);
board1.setPixel(ax, 15 - ay, YELLOW);
board1.setX();
selectPanel(x, y);
board1.setX();
delayMicroseconds(DTIME);
}
else if (color == BLACK) {
board1.setLastColor( BLACK);
board1.setPixel(ax, 15 - ay, BLACK);
board1.setX();
selectPanel(x, y);
board1.setX();
delayMicroseconds(DTIME);
}
}
else if (ay <= 7 && ay >= 0) {
mask = 0x80 >> y;
if (color == YELLOW) {
board1.setLastColor( YELLOW);
board1.setPixel(ax, 15 - ay, YELLOW);
board1.setX();
selectPanel(x, y);
board1.setX();
delayMicroseconds(DTIME);
}
else if (color == BLACK) {
board1.setLastColor( BLACK);
board1.setPixel(ax, 15 - ay, BLACK);
board1.setX();
selectPanel(x, y);
board1.setX();
delayMicroseconds(DTIME);
}
}
}
digitalWrite(13, LOW);
}
private:
};
#endif
|
Pilooz/flipdots | arduino/flip_panel_node_client_ino_3rdgeneration/FlipBoard.h | #ifndef FLIPBOARD
#define FLIPBOARD
#define BLACK 0
#define YELLOW 1
class FlipBoard {
public:
FlipBoard(unsigned char addrX, unsigned char addrY) {
// Setup the flip board with MCP addresses
this->addrX = addrX;
this->addrY = addrY;
}
void setup() {
// set all I/O to O
Wire.beginTransmission(addrX);
Wire.write(0x00); // IODIRA register
Wire.write(0x00); // set all of port A to outputs
Wire.endTransmission();
Wire.beginTransmission(addrX);
Wire.write(0x01); // IODIRB register
Wire.write(0x00); // set all of port B to outputs
Wire.endTransmission();
Wire.beginTransmission(addrY);
Wire.write(0x00); // IODIRA register
Wire.write(0x00); // set all of port A to outputs
Wire.endTransmission();
Wire.beginTransmission(addrY);
Wire.write(0x01); // IODIRB register
Wire.write(0x00); // set all of port B to outputs
Wire.endTransmission();
}
void releaseCurrent() {
digitalWrite(4, LOW);
digitalWrite(3, LOW);
digitalWrite(2, LOW);
digitalWrite(5, LOW);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
digitalWrite(8, LOW);
digitalWrite(9, LOW);
digitalWrite(10, LOW);
releaseX();
releaseY();
}
void releaseX(){
Wire.beginTransmission(this->addrX);
Wire.write(0x12); // address port A
Wire.write( 0b00111111); // value to send
Wire.endTransmission();
enablePin = 0;
}
void releaseY(){
Wire.beginTransmission(this->addrY);
Wire.write(0x12); // address port A
if(lastColor == YELLOW){
Wire.write( 0xFF );
}
else if(lastColor == BLACK){
Wire.write( 0x00 ); // value to send
}
Wire.endTransmission();
Wire.beginTransmission(this->addrY);
Wire.write(0x13); // address port B
if(lastColor == YELLOW){
Wire.write( 0xFF );
}
else if(lastColor == BLACK){
Wire.write( 0x00 ); // value to send
}
Wire.endTransmission();
}
void setEnablePin(bool aBool) {
if (aBool) {
enablePin = 0b01000000;
}
else {
enablePin = 0;
}
}
void setLastColor(unsigned char aLastColor){
lastColor = aLastColor;
}
void setPixel(unsigned char x, unsigned char y, unsigned char color) {
// y == Masses
unsigned char PORTA_Y;
unsigned char PORTB_Y;
unsigned char PORTA_X;
switch (y) {
case 0: // Mass 1 - GPB0
PORTA_Y = 0b00000000;
PORTB_Y = 0b00000001;
break;
case 1: // Mass 2 - GPB1
PORTA_Y = 0b00000000;
PORTB_Y = 0b00000010;
break;
case 2: // Mass 3 - GPB3
PORTA_Y = 0b00000000;
PORTB_Y = 0b00001000;
break;
case 3: // Mass 4 - GPB2
PORTA_Y = 0b00000000;
PORTB_Y = 0b00000100;
break;
case 4: // Mass 5 - GPB4
PORTA_Y = 0b00000000;
PORTB_Y = 0b00010000;
break;
case 5: // Mass 6 - GPB5
PORTA_Y = 0b00000000;
PORTB_Y = 0b00100000;
break;
case 6: // Mass 7 - GPB7
PORTA_Y = 0b00000000;
PORTB_Y = 0b10000000;
break;
case 7: // Mass 8 - GPB6
PORTA_Y = 0b00000000;
PORTB_Y = 0b01000000;
break;
case 8: // Mass 9 - GPA7
PORTA_Y = 0b10000000;
PORTB_Y = 0b00000000;
break;
case 9: // Mass 10 - GPA6
PORTA_Y = 0b01000000;
PORTB_Y = 0b00000000;
break;
case 10: // Mass 11 - GPA4
PORTA_Y = 0b00010000;
PORTB_Y = 0b00000000;
break;
case 11: // Mass 12 - GPA5
PORTA_Y = 0b00100000;
PORTB_Y = 0b00000000;
break;
case 12: // Mass 13 - GPA3
PORTA_Y = 0b00001000;
PORTB_Y = 0b00000000;
break;
case 13: // Mass 14 - GPA2
PORTA_Y = 0b00000100;
PORTB_Y = 0b00000000;
break;
case 14: // Mass 15 - GPA0
PORTA_Y = 0b00000001;
PORTB_Y = 0b00000000;
break;
case 15: // Mass 16 - GPA1
PORTA_Y = 0b00000010;
PORTB_Y = 0b00000000;
break;
}
// invert value in case of yellow
if (color == YELLOW) {
PORTA_Y = ~PORTA_Y;
PORTB_Y = ~PORTB_Y;
}
if (color == BLACK) {
if (x < 8) {
PORTA_X = 0b00000000 + (x);
lastAddr = PORTA_X;
}
else if (x < 16 && x > 7) {
PORTA_X = 0b00010000 + (x - 8);
lastAddr = PORTA_X;
}
else if (x < 24 && x > 15) {
PORTA_X = 0b00001000 + (x - 16);
lastAddr = PORTA_X;
}
else if (x < 32 && x > 23) {
PORTA_X = 0b00011000 + (x - 24);
lastAddr = PORTA_X;
}
}
if (color == YELLOW) {
if (x < 8) {
PORTA_X = 0b00100000 + (x);
lastAddr = PORTA_X;
}
else if (x < 16 && x > 7) {
PORTA_X = 0b00110000 + (x - 8);
lastAddr = PORTA_X;
}
else if (x < 24 && x > 15) {
PORTA_X = 0b00101000 + (x - 16);
lastAddr = PORTA_X;
}
else if (x < 32 && x > 23) {
PORTA_X = 0b00111000 + (x - 24);
lastAddr = PORTA_X;
}
}
// send Y value
Wire.beginTransmission(this->addrY);
Wire.write(0x12); // address port A
Wire.write( PORTA_Y ); // value to send
Wire.endTransmission();
Wire.beginTransmission(this->addrY);
Wire.write(0x13); // address port B
Wire.write( PORTB_Y ); // value to send
Wire.endTransmission();
}
void setX(){
// send X value
if (enablePin != 0) {
lastAddr += enablePin;
}
Wire.beginTransmission(this->addrX);
Wire.write(0x12); // address port A
Wire.write( lastAddr ); // value to send
Wire.endTransmission();
}
private:
unsigned char addrX;
unsigned char addrY;
unsigned char enablePin = 0;
unsigned char lastColor = BLACK;
unsigned char lastAddr = 0x00;
};
#endif
|
henrythasler/legendary-dashboard | lib/text/wisdom.h | <filename>lib/text/wisdom.h
#if defined(ESP8266) || defined(ESP32)
#include <pgmspace.h>
#else
#include <avr/pgmspace.h>
#endif
// Latin-1 character codes
// ä: "\xe4"
// ü: "\xfc"
// ö: "\xf6"
// Ä: "\xc4"
// Ö: "\xd6"
// Ü: "\xdc"
// ß: "\xdf"
const std::vector<String> wisdomTexts PROGMEM = {
// Bullshit Bingo
"Bingo 1: It works on my Machine!",
"Bingo 2: It worked yesterday!",
"Bingo 3: I've never done that before.",
"Bingo 4: That's weird.",
"Bingo 5: Where were you when the program blew up?",
"Bingo 6: Why do you want to do it that way?",
"Bingo 7: You can't use that version on your System!",
"Bingo 8: Even though it doesn't work how does it feel?",
"Bingo 9: Did you check for a Virus on your System?",
"Bingo 10: Somebody must have changed my code!",
"Bingo 11: It works, but it hasn't been tested.",
"Bingo 12: THIS can't be the source of that!",
"Bingo 13: I can't test everything.",
"Bingo 14: It's just some unlucky coincidence.",
"Bingo 15: You must have the wrong version!",
"Bingo 16: I haven't touched that module in weeks.",
"Bingo 17: There is something funky in your data.",
"Bingo 18: What did you Type in to get it to crash?",
"Bingo 19: It must be a hardware problem.",
"Bingo 20: How is that possible?",
"Bingo 21: That's scheduled to be fixed in the next release.",
"Bingo 22: Yes, we knew that would happen.",
"Bingo 23: Maybe we just don't support that platform.",
"Bingo 24: It's a Feature we just haven't updated the specs.",
"Bingo 25: Surely Nobody is going to use the program like that.",
// Julia
"So m""\xfc""de wie heute, war ich bestimmt seit gestern nicht mehr.",
"Geschenke einpacken. Das r""\xfc""ckw""\xe4""rts einparken der Frauen f""\xfc""r M""\xe4""nner.",
"Je gr""\xf6""ßer der Dachschaden desto besser der Blick auf die Sterne.",
"Ich kann doch nicht alle gl""\xfc""cklich machen oder sehe ich aus wie ein Glas Nutella?!",
"Lass uns lachen, das Leben ist ernst genug.",
"Ich f""\xfc""hle mich, als k""\xf6""nnte ich B""\xe4""ume ausreissen. Also, kleine B""\xe4""ume. Vielleicht Bambus. Oder Blumen. Na gut. Gras. Gras geht.",
"Nat""\xfc""rlich mache ich gerne Sport. Deshalb auch so selten. Soll ja schließlich was Besonderes bleiben.",
"Das Problem will ich nicht, zeig mir das N""\xe4""chste!",
"Fr""\xfc""her war wirklich alles leichter. Zum Beispiel Ich.",
"Als Gott mich schuf, grinste er und dachte: Keine Ahnung was passiert, aber lustig wirds bestimmt!",
"Fahre nie schneller, als dein Schutzengel fliegen kann!",
"Wer Ordnung h""\xe4""lt, ist nur zu faul zum Suchen.",
"Gebildet ist, wer wei""\xdf"", wo er findet, was er nicht wei""\xdf"".",
"I don't know where I'm going but I'm on my way.",
"Humor ist versteckte Weisheit.",
"Schokolade ist Gottes Entschuldigung f""\xfc""r Brokkoli.",
"Wer schwankt hat mehr vom Weg!",
"Da lernt man Dreisatz und Wahrscheinlichkeitsrechnung und steht trotzdem gr""\xfc""belnd vor dem Backofen, welche der vier Schienen nun die Mittlere ist.",
"Ich schlafe im Sommer mit offenem Fenster. 1832 M""\xfc""cken gef""\xe4""llt das.",
"Was ist ein Keks unter einem Baum? Ein schattiges Pl""\xe4""tzchen",
"Nat""\xfc""rlich spreche ich mit mir selbst. Manchmal brauche ich eine kompetente Beratung.",
"Wie, zu Fu""\xdf"" gehen? Hab doch vier gesunde Reifen!",
// <NAME>
"Z""\xe4""hlte bereits 60 Jahre: Amazon-Lagerist bei Inventur verstorben",
"Mag er roh nie: Mann kocht Nudelgericht",
"In G""\xe4""nsef""\xfc""""\xdf""chen gesetzt: Praktikant macht es sich bei 'Arbeit' im Schlachthof bequem",
"""\xe4""tsch, Iran: Versteckte Kamera schickt englischen S""\xe4""nger in den nahen Osten",
"Multibl""\xe4""h-Pers""\xf6""nlichkeit: Psychisch Kranker kann als mehrere Menschen furzen",
"Nur ein paar Brocken: Englisch-Kenntnisse nicht ausreichend um Arzt den Grad der ""\xfc""belkeit zu erkl""\xe4""ren",
"<NAME> gewesen: Merkel spricht nicht gerne ""\xfc""ber ihre Anfangszeit",
"Kann ich mal Ihren Stift haben?: Azubi-Leihvertrag steht kurz vor der Unterzeichnung",
"Ersatzteil aus dem Second-Hand-Laden: Einarmiger Bandit repariert",
"""\xfc""ber Welt tickendes Angebot: Swatch plant kostenlose Riesen-Uhr auf dem Mond",
"Wieder zu Hause aufgetaucht: H""\xe4""ftling gl""\xfc""ckt Flucht durch Kanalisation",
"Das Bett h""\xe4""utet ihm sehr viel: Mann h""\xe4""lt trotz unruhiger N""\xe4""chte an Schlafst""\xe4""tte aus Schlangenleder fest",
"Weltrekordhalter im Kraulen: Schwimmer verw""\xf6""hnt Katze",
"Opa-Hammer-Gau: Rentner f""\xe4""llt bei Passionsspielen Werkzeug auf Fu""\xdf""",
"Essenzzeit: Mann nimmt Gericht aus Konzentraten ein",
"D""\xf6""ner Hebab: Turkish Airlines bietet an Bord nun auch Grillspezialit""\xe4""t an",
"<NAME>: Alternder Callboy wird gefragt, warum er ""\xfc""berhaupt noch arbeitet",
"20 Pfund abgenommen: Dicke Britin hetzt Taschendieb durch die ganze Stadt",
"Autorennlesung: Schriftsteller rezitiert sein Werk ""\xfc""ber Formel 1 Saison am N""\xfc""rburgring",
"2G und SD: Veraltetes Handy h""\xe4""ngt in Baum",
"Beim Bund: General weist Soldaten auf Riss in Hose hin",
"Pfiff dezent: US Rapper bewies als Schiedsrichter kein Durchsetzungsverm""\xf6""gen",
"Tubenarrest: Freche Zahnpasta muss drinnen bleiben",
"Schlimmen R""\xfc""ckfall erlitten: Alkoholiker konnte nicht wieder stehen",
"War nicht ohne: Mann von Safer Sex begeistert",
"Will da auch gar nichts besch""\xf6""nigen: Plastischer Chirurg nimmt Patientin jede Hoffnung",
"Zwei Dijons: Senfhersteller bringt Ex-Freundin Geschenk",
"Hel<NAME>: Getr""\xe4""nkemarktmitarbeiter findet Bier schneller",
"Erwischt: Frau beobachtet ihren Mann beim Tindern",
"Aus dem Bauch heraus: Von Wal verspeister Mann verfasst spontan seine Memoiren",
"Herdzinsangelegenheit: Kunde m""\xf6""chte Ofen liebend gern auf Raten zahlen",
"Rotes Kreuz: Rettungssanit""\xe4""ter klagt ""\xfc""ber R""\xfc""ckenschmerzen nach S/M-Wochenende",
"Tarte ""\xfc"", Tarte A: B""\xe4""cker wegen verr""\xfc""ckter Nummerierung in Psychiatrie eingeliefert",
"Muss neuen aufsetzen: Mann sch""\xfc""ttet sich Kaffee ""\xfc""ber den Hut",
"Springer Steve L.: Neonazi trug beim Suizid seine Lieblingsschuhe",
"Hintergrund unklar: Maler zerst""\xf6""rt Stillleben",
"Im Karsten: Schwulenporno endlich fertig",
"Nur eine Kugel: Revolverheld erschie""\xdf""t knausrigen Eisdielenkunden",
"War noch gr""\xfc""n hinter Tenoren: Fahranf""\xe4""nger rast auf Kreuzung in Tourbus-Heck",
"Speichermedium: Auf Dachboden lebende Frau mit ""\xfc""bernat""\xfc""rlichen F""\xe4""higkeiten findet USB-Stick",
"Thomas' Scotch-Alk: Whisky von Showmaster entwendet",
"Alles au""\xdf""er Kontrolle: T""\xfc""rsteher nahm Job nicht ernst",
"Mittags Sch""\xe4""fchen gehalten: Hirte macht Pause mit Lamm im Arm",
"Tausend Zsa Zsa: Trickreicher Erfinder klont mehrfach Hollywoodlegende",
"Sitzt gut: H""\xe4""ftling mit Kleidung und Schemel zufrieden",
"S""\xe4""uchenschutzgesetz: Kleine Schweine m""\xfc""ssen bei Pandemie als erstes gerettet werden",
"Beh""\xe4""lter f""\xfc""r sich: Betrunkener erkl""\xe4""rt auf Party nicht, warum er Eimer dabei hat",
"Rasch aua: Autobahn""\xfc""berquerung zu Fuß endet im Krankenhaus",
"Da kennt er nix: Vollidiot meldet sich zu Astrophysik-Quiz an",
"Social Diss-Dancing: Waldorfsch""\xfc""ler postet beleidigende Videos auf Facebook",
"Der totale Kn""\xfc""ller: Kopierer bricht Verkaufsrekorde trotz schlechten Papiereinzugs",
"Qual-Lied-Hetz-Management: Nach ISO9001 ist es erlaubt, ""\xfc""ber 'Atemlos durch die Nacht' herzuziehen",
"Steckt in Apache: Winnetou in flagranti mit Liebhaber erwischt",
"Streit ""\xfc""ber fehlende Stra""\xdf""e eskaliert: B""\xfc""rgermeister schickt Erschlie""\xdf""ungskommando",
"Schwamm: SpongeBob besteht Seepferdchen",
"F""\xfc""hrt ein Schattendasein: Von Hand auf Leinwand projiziertes Krokodil",
"<NAME>: Bert erlebt Berufung von Freund zum Orchesterleiter als Dem""\xfc""tigung",
"Wegen Kontaktsperre: Batterie verweigert Dienst",
"Nach dem Stunt teert Inge: Filmdouble muss voraussichtlich Zweitjob im Stra""\xdf""enbau annehmen",
"Geh""\xf6""ren zur Riesigkotgruppe: Dicke leiden unter Klopapiermangel",
"Bekam einen R""\xfc""ffel: Zahnloser muss sich zur Strafe als Elefant verkleiden",
"Hahn-Twerker: Zimmermann macht Potanz-Video im Gockel-Kost""\xfc""m",
"Unterschiedliche Vorstellungen: Kinobesitzerehepaar trennt sich",
"Siel bereisen: Florian macht Deichtour",
"Macht sich nichts vor: Pfleger wei""\xdf"" eigentlich, dass Ansteckungsrisiko ohne Mundschutz gr""\xf6""""\xdf""er ist",
"<NAME>: Schauspieler nutzt Fahrgesch""\xe4""ft",
"Zieht Schlussstrich: Mann trennt sich von Lieblingsstift",
"Prinzessbohnen: K""\xf6""nig r""\xe4""t seinem Sohn zu mehr Gem""\xfc""se",
"K""\xf6""nnte jeden treffen: Mann immun gegen Coronavirus",
"In Skiflagge geraten: Insolventer Quizteilnehmer tr""\xe4""gt Riesenslalomzubeh""\xf6""r als Schal",
"Wegen Best""\xe4""ubungsmitteln: Biene verhaftet",
"Eilegeboten: Kundschafter mahnen H""\xfc""hner zu rechtzeitiger Steigerung der Produktion bis Ostern",
"Verein-Zelt: Sch""\xfc""tzenfest-Pavillon darf nur noch von je einem Mitglied betreten werden",
"Stoff vers""\xe4""umt: N""\xe4""herin muss nach Feierabend noch f""\xfc""r Kurs lernen",
"Stand dort: Wanderer sah auf Umgebungsplan, wo er sich befand",
"In Betrieb genommen: Sexroboter vor Auslieferung getestet",
"Wertpapiere: Banker investiert in Toilettenrollen",
"Musste dem Rechnung tragen: Frau akzeptiert, dass Freund nach Leistenbruch unm""\xf6""glich Kassenzettel heben kann",
"Hat endlich eine Rolle ergattert: Erfolgloser Schauspieler bringt Klopapier nach Hause",
"Stand kurz vor einer L""\xf6""sung: Impfstoffentwickler atmet hochgiftige D""\xe4""mpfe ein",
"<NAME> bellt im Karton: Entertainer hat den Verstand verloren",
"F""\xe4""llt leicht: Neymar auch in Verkleidung unschwer zu erkennen",
"Total vervirt: Coronapatient l""\xe4""uft orientierungslos durch Fu""\xdf""g""\xe4""ngerzone",
"'Wang, w""\xfc""rz mal Widder...richtig so...mehr!': Carrell empfand Hammelfleisch am China-Imbiss als zu fad",
"Brachte nur noch Vieren nach Hause: Familie von schlechtem Sch""\xfc""ler in Quarant""\xe4""ne",
"Dia mit Lungen aufgenommen: Polizei jagt Organfotografen",
"Einrichtungshaus: IKEA mahnt Kunden zur Einhaltung der Laufroute",
"Trampolin: Warschauerin nimmt H""\xfc""pfger""\xe4""t mit in die Stra""\xdf""enbahn",
"Mustafa werden: Muslima will nach Geschlechtsumwandlung dominanter auftreten",
"Das wird sich noch zeigen: Murmeltierexperte streitet mit entt""\xe4""uschten Touristen ""\xfc""ber seine Fachkompetenz",
"'Husten! Wir haben ein Problem.': ISS meldet ersten Corona-Fall",
"Macht jetzt in Antiquit""\xe4""ten: Vasenh""\xe4""ndler findet kein Klo",
"F""\xfc""hrt Ananas-Serum: Arzt t""\xe4""uscht Patienten mit Impfstoff aus Fruchtsaft",
"Immer nur Fish &amp; Ships: Godzilla findet englische K""\xfc""che ""\xf6""de",
"h.c. nicht alle: Uni-Rektor stellt fast nur Dozenten mit Ehrendoktorw""\xfc""rde ein",
"Waren verdorben: Ordin""\xe4""re Marktfrauen boten faules Obst an",
"Eine einzige Schikane: Formel-1-Fahrer ""\xfc""ber schlechten Kurs emp""\xf6""rt",
"File geboten: Datei zu verkaufen",
"Schnappt nach Luft: Hund dreht in Sauna durch",
"'Kiek, Erik, ih!': Berlinerin zeigt ihrem Freund toten Hahn",
"Nicht auszumalen: Kinderbuch mit 10.000 Seiten ver""\xf6""ffentlicht",
"Schlafend gestellt: Einbrecher lag bei Zugriff noch im Bett",
"finnish.net: Homepage in Helsinki f""\xfc""r Hessen unm""\xf6""glich zu erreichen",
"Arbeitet fieberhaft: Immunsystem l""\xe4""uft auf Hochtouren",
"Petryschale: Frauke z""\xfc""chtet Halsw""\xe4""rmer im Labor",
"H<NAME> ist man schlauer: Soldat will nicht an die Front",
"Fellig losgel""\xf6""st: Major Tom startete unrasiert",
"'Sch""\xfc""tt Senf herein!': Jugendlicher stiftet Kumpel an, Schie""\xdf""sport-Club einen Streich zu spielen",
"Leckt ein bisschen: Chemiker untersucht unbekannte Substanz unter Silo",
"Dieb rennt: Fl""\xfc""chtiger Taschenr""\xe4""uber z""\xfc""ndete Opfer an",
"Muss zum K""\xe4""ferorthop""\xe4""den: Insekt hat ""\xfc""berbiss",
"Punk kaut Tomaten: Linker Veganer hebt mehrfach Geld ab",
"Spricht mit gespaltener Zunge: Indianer l""\xfc""gt ""\xfc""ber Unfall mit Jagdmesser",
"Wiesloch: Frau aus Baden-W""\xfc""rttemberg s""\xe4""uft",
"Patienten m""\xfc""ssen mit gr""\xf6""""\xdf""eren Einschnitten rechnen: Chirurgiepraxis spart an feinen Skalpellen",
"Ein sch""\xf6""ner Zug von ihm: Modell-Eisenbahner verschenkt sein liebstes Exemplar",
"Da gibts Gedr""\xe4""nge: Hohes Menschenaufkommen bei hessischem Spirituosenh""\xe4""ndler",
"Arsch reckend: Immer mehr M""\xe4""nner gehen in Yoga-Kurs",
"PDF: Geheimes Dokument offenbart verkehrte Politik der FDP",
"H""\xe4""ufig in Elefantenporno zu sehen: Sto""\xdf""szene",
"Ging ihm dann auch direkt auf: Mann h""\xe4""tte Hosenrei""\xdf""verschluss vor Vorstellungsgespr""\xe4""ch besser repariert",
"Ein einmaliges Erlebnis: Marodes Bungeeunternehmen versucht es mit ehrlicher Werbung",
"Gold richtig: Quizshow-Teilnehmer beantwortet Frage nach Edelmetall",
"Ein Fach nur, d""\xe4""mlich: Merkw""\xfc""rdiger Apothekerschrank floppt",
"Die wichtigsten Wokgabeln: Asiatischer Koch paukt f""\xfc""r Pr""\xfc""fung in Besteckkunde",
"Rote Arme Fraktion: <NAME> und <NAME> haben Sonnenbrand",
"Hat ihn dumm angemacht: Vegetarier von Salat verpr""\xfc""gelt",
"Er ist jetzt an einem besseren Ort: Journalist springt aus dem Fenster der BILD-Redaktion",
"War als erster an der Ziehlinie: Junkie gewinnt Wettrennen um Kokain",
"Aphte: Nazi wegen Mundh""\xf6""hlenentz""\xfc""ndung unf""\xe4""hig, seine Lieblingspartei zu nennen",
"Kann ein Liter Fond singen: Mann wei""\xdf"", wie es ist, beim Tr""\xe4""llern Bratensaft zu produzieren",
"War eiskalt vor dem Tor: Platzwart findet erfrorenen St""\xfc""rmer",
"Will nicht, dass jeder seinen Schwan zieht: Bekleideter Mann bindet Wasservogel an",
"Ein Schlag ins Gesicht: Masochist von entt""\xe4""uschendem Domina-Angebot gekr""\xe4""nkt",
"Serge ade: Bayernspieler muss trotz hervorragender Leistungen den Verein verlassen",
"""\xfc""ber Alf lecken: Masernpatient versucht Krankheit durch Lutschen an Au""\xdf""erirdischem zu lindern",
"Wie die Lehm-Inge: Kinder beim T""\xf6""pfern von Klippe gesprungen",
"'""\xe4""hm, Sie Hemmer!': Rapper als Spa""\xdf""bremse beschimpft",
"Wageneber im Kofferraum: Franzose mit Reifenpanne hatte Schwein",
"Steiffhundfest: Kind behauptet, sein Stofftier habe Geburtstag",
"War am saugen: Ehefrau ""\xfc""berrascht ihren Mann mit neuer Haushaltshilfe",
"Gingen um die Welt: Bilder von Extremdistanz-Wanderern in allen Nachrichten pr""\xe4""sent",
"Bekommt lecker Li: Kampfhund wird mit Chinesen belohnt",
"Oh<NAME>: <NAME> ist nicht lustig",
"Freut sich auf 'at home-Pils': Nuklearphysiker hat Feierabend",
"Zweibr""\xfc""cken: Zahn""\xe4""rztin aus der Pfalz erlebt ruhigen Vormittag",
"Irre summen: Anwohner m""\xfc""ssen f""\xfc""r L""\xe4""rmschutzwand vor Psychiatrie zahlen",
"H""\xf6""ren sich gegenseitig ab: Spionage-Azubis lernen f""\xfc""r ihre Abschlusspr""\xfc""fung",
"Kaviar im Zeugnis: Bayerischer Lehrer belohnt rogens""\xfc""chtigen Sch""\xfc""ler",
"Genfer: Zahnloser Schweizer gibt sich f""\xfc""r ehemaligen deutschen Au""\xdf""enminister aus",
"Lange nicht Font""\xe4""nen geh""\xf6""rt: Meeresanwohner wundert sich, wo Wale geblieben sind"
// Murphys law
"If anything can go wrong, it will.",
"If anything just cannot go wrong, it will anyway.",
"If everything seems to be going well, you have obviously overlooked something",
"Smile . . . tomorrow will be worse.",
"Matter will be damaged in direct proportion to its value.",
"Research supports a specific theory depending on the amount of funds dedicated to it.",
"In nature, nothing is ever right. Therefore, if everything is going right ... something is wrong.",
"It is impossible to make anything foolproof because fools are so ingenious.",
"Everything takes longer than you think.",
"Every solution breeds new problems.",
"The legibility of a copy is inversely proportional to its importance.",
"A falling object will always land where it can do the most damage.",
"A shatterproof object will always fall on the only surface hard enough to crack or break it.",
"The other line always moves faster.",
"In order to get a personal loan, you must first prove you don't need it.",
"Anything you try to fix will take longer and cost you more than you thought.",
"Build a system that even a fool can use, and only a fool will use it.",
"Everyone has a scheme for getting rich that will not work.",
"In any hierarchy, each individual rises to his own level of incompetence, and then remains there.",
"There's never time to do it right, but there's always time to do it over.",
"When in doubt, mumble. When in trouble, delegate.",
"Anything good in life is either illegal, immoral or fattening.",
"Murphy's golden rule: whoever has the gold makes the rules.",
"A Smith & Wesson beats four aces.",
"In case of doubt, make it sound convincing.",
"Never argue with a fool, people might not know the difference.",
"Whatever hits the fan will not be evenly distributed.",
"Where patience fails, force prevails.",
"Just when you think things cannot get any worse, they will.",
"Great ideas are never remembered and dumb statements are never forgotten.",
"When you see light at the end of the tunnel, the tunnel will cave in.",
"Traffic is inversely proportional to how late you are, or are going to be.",
"The probability of being observed is in direct proportion to the stupidity of ones actions.",
"Those who know the least will always know it the loudest.",
"Just because you CAN do something doesn't mean you SHOULD.",
"Chaos always wins, because it's better organized.",
"If at first you don't succeed destroy all evidence that you ever tried.",
"It takes forever to learn the rules and once you've learned them they change again",
"You will find an easy way to do it, after you've finished doing it.",
"Anyone who isn't paranoid simply isn't paying attention.",
"A valuable falling in a hard to reach place will be exactly at the distance of the tip of your fingers.",
"The probability of rain is inversely proportional to the size of the umbrella you carry around with you all day.",
"Nothing is impossible for the man who doesn't have to do it himself.",
"The likelihood of something happening is in inverse proportion to the desirability of it happening.",
"Common Sense Is Not So Common.",
"Power Is Taken... Not Given.",
"Two wrongs don't make a right. It usually takes three or four.",
"The difference between Stupidity and Genius is that Genius has its limits.",
"Those who don't take decisions never make mistakes.",
"Anything that seems right, is putting you into a false sense of security.",
"Its never so bad it couldn't be worse.",
"When saying that things can not possibly get any worse - they will.",
"The person ahead of you in the queue, will have the most complex transaction possible.",
"Logic is a systematic method of coming to the wrong conclusion with confidence.",
"Technology is dominated by those who manage what they do not understand.",
"The opulence of the front office decor varies inversely with the fundamental solvency of the firm.",
"The attention span of a computer is only as long as it electrical cord.",
"Nothing ever gets built on schedule or within budget.",
"The first myth of management is that it exists.",
"A failure will not appear till a unit has passed final inspection.",
"To err is human, but to really foul things up requires a computer.",
"Any sufficiently advanced technology is indistinguishable from magic.",
"Nothing motivates a man more than to see his boss putting in an honest day's work.",
"Some people manage by the book, even though they don't know who wrote the book or even what book.",
"To spot the expert, pick the one who predicts the job will take the longest and cost the most.",
"After all is said and done, a hell of a lot more is said than done.",
"The only perfect science is hind-sight.",
"If an experiment works, something has gone wrong.",
"When all else fails, read the instructions.",
"The degree of technical competence is inversely proportional to the level of management.",
"The remaining work to finish in order to reach your goal increases as the deadline approaches.",
"It is never wise to let a piece of electronic equipment know that you are in a hurry.",
"If you are not thoroughly confused, you have not been thoroughly informed.",
"Standard parts are not.",
"The bolt that is in the most awkward place will always be the one with the tightest thread.",
"In today's fast-moving tech environment, it is a requirement that we forget more than we learn.",
"It is simple to make something complex, and complex to make it simple.",
"If it works in theory, it won't work in practice. If it works in practice it won't work in theory.",
"Any tool dropped will fall where it can cause the most damage.",
"When you finally update to a new technology, is when everyone stop supporting it.",
"If you think you understand science (or computers or women), you're clearly not an expert",
"Technicians are the only ones that don't trust technology.",
"The repairman will have never seen a model quite like yours before.",
"In theory there is no difference between theory and practice, but in practice there is.",
"Never underestimate incompetency.",
"Any given program, when running, is obsolete.",
"Any given program costs more and takes longer each time it is run.",
"If a program is useful, it will have to be changed.",
"If a program is useless, it will have to be documented.",
"Any given program will expand to fill all the available memory.",
"Program complexity grows until it exceeds the capability of the programmer who must maintain it.",
"Adding manpower to a late software project makes it later.",
"No matter how many resources you have, it is never enough.",
"If a program has not crashed yet, it is waiting for a critical moment before it crashes.",
"Software bugs are impossible to detect by anybody except the end user.",
"A failure in a device will never appear until it has passed final inspection.",
"An expert is someone brought in at the last minute to share the blame.",
"A patch is a piece of software which replaces old bugs with new bugs.",
"The chances of a program doing what it's supposed to do is inversely proportional to the number of lines of code used.",
"The longer it takes to download a program the more likely it won't run.",
"It's not a bug, it's an undocumented feature.",
"Bugs mysteriously appear when you say, Watch this!",
"The probability of bugs appearing is directly proportional to the number and importance of people watching.",
"If a project is completed on schedule, it wasn't debugged properly.",
"If it works, it's production. If it doesn't, it's a test.",
"Real programmers don't comment their code. If it was hard to write, it should be hard to understand.",
"A computer that has been on the market for 6 weeks is still usable as a boat anchor.",
"Computers let you waste time efficiently.",
"A pat on the back is only a few inches from a kick in the pants.",
"Don't be irreplaceable, if you can't be replaced, you can't be promoted.",
"It doesn't matter what you do, it only matters what you say you've done and what you say you're going to do.",
"The more crap you put up with, the more crap you are going to get.",
"When the bosses talk about improving productivity, they are never talking about themselves.",
"Mother said there would be days like this, but she never said there would be so many.",
"--> The last person that quit or was fired will be the one held responsible for everything that goes wrong. :-)",
"If it wasn't for the last minute, nothing would get done.",
"The longer the title, the less important the job.",
"If you have a little extra money to blow, something will break, and cost more than that little extra.",
"If the salesperson says, All you have to do is..., you know you're in trouble.",
// general
"When I was a kid my parents moved a lot, but I always found them.",
"Life is short. Smile while you still have teeth.",
"The best way to teach your kids about taxes is by eating 30 percent of their ice cream.",
"I'm writing a book. I've got the page numbers done.",
"I have always wanted to be somebody, but I see now I should have been more specific.",
"Knowledge is like underwear. It is useful to have it, but not necessary to show it off.",
"If a book about failures doesn't sell, is it a success?",
"A lie gets halfway around the world before the truth has a chance to get its pants on.",
"It's okay if you don't like me. Not everyone has good taste.",
"Everything is changing. People are taking the comedians seriously and the politicians as a joke.",
"I like long walks, especially when they are taken by people who annoy me.",
"The only way to keep your health is to eat what you don't want, drink what you don't like, and do what you'd rather not.",
"When nothing is going right, go left.",
"Never miss a good chance to shut up.",
"I'd like to live like a poor man – only with lots of money.",
"My life feels like a test I didn't study for.",
"I don't go crazy. I am crazy. I just go normal from time to time.",
"My bed is a magical place where I suddenly remember everything I forgot to do.",
"I'm actually not funny. I'm just really mean and people think I'm joking.",
"Sometimes I want to go back in time and punch myself in the face.",
"If you are lonely, dim all lights and put on a horror movie. After a while it won't feel like you are alone anymore.",
"Fries or salad? sums up every adult decision you have to make.",
"If we're not meant to have midnight snacks, why is there a light in the fridge.",
"My doctor told me to watch my drinking. Now I drink in front of a mirror.",
"I drive way too fast to worry about cholesterol.",
"As your best friend I'll always pick you up when you fall, after I finish laughing.",
"Some people are like clouds. When they disappear, it's a beautiful day.",
"I'm not arguing. I'm simply explaining why I'm right.",
"No wonder the teacher knows so much; she has the book.",
"The most ineffective workers are systematically moved to the place where they can do the least damage: management.",
"The best way to appreciate your job is to imagine yourself without one.",
"If I had asked people what they wanted, they would have said faster horses. <NAME>",
"The closest a person ever comes to perfection is when he fills out a job application form.",
"Don't yell at your kids! Lean in real close and whisper, it's much scarier.",
"The quickest way for a parent to get a child's attention is to sit down and look comfortable.",
"I don't know what's more exhausting about parenting: the getting up early, or the acting like you know what you're doing.",
"It just occurred to me that the majority of my diet is made up of the foods that my kid didn't finish.",
"When your children are teenagers, it's important to have a dog so that someone in the house is happy to see you.",
"I never know what to say when people ask me what my hobbies are. I mean, I'm a dad.",
"My wife and I were happy for twenty years. Then we met.",
"Marriage... it's not a word, it's a sentence.",
"Marry a man your own age; as your beauty fades, so will his eyesight.",
"Marriage is the triumph of imagination over intelligence. Second marriage is the triumph of hope over experience.",
"The most terrifying thing any woman can say to me is Notice anything different?",
"When a man brings his wife flowers for no reason, there's a reason."
}; |
henrythasler/legendary-dashboard | lib/images/src/gfx.h | <filename>lib/images/src/gfx.h
#ifndef GFX_H
#define GFX_H
#include <images.h>
#include <icons.h>
struct Image{
const uint8_t *color;
const uint8_t *black;
Image(const uint8_t *color, const uint8_t *black)
: color(color), black(black)
{
}
};
struct {
Image bmw = Image(bmwYellow, bmwBlack);
Image bruce = Image(bruceYellow, bruceBlack);
Image yellowScreen = Image(bsodRed, bsodBlack);
Image beer = Image(beerYellow, beerBlack);
Image coffin = Image(coffinYellow, coffinBlack);
Image parking = Image(parkingYellow, parkingBlack);
Image unittest = Image(unittestYellow, unittestBlack);
Image fixing = Image(whiteWall, fixingBlack);
Image employees = Image(whiteWall, employeesBlack);
} images;
struct {
Image gift = Image(giftRed, giftBlack);
Image logo = Image(empty, logoBlack);
Image pressure = Image(empty, pressureBlack);
Image humidity = Image(empty, humidityBlack);
Image temperature = Image(empty, temperatureBlack);
} icons;
#endif
|
henrythasler/legendary-dashboard | lib/chart/src/chart.h | #ifndef CHART_H
#define CHART_H
#include <timeseries.h>
#ifdef ARDUINO
#include <GxEPD.h>
#include <GxGDEW042Z15/GxGDEW042Z15.h> // 4.2" b/w/r
#endif
using namespace std;
class Chart
{
private:
public:
Chart(void);
#ifdef ARDUINO
void lineChart(GxEPD_Class *display,
Timeseries *timeseries,
uint16_t canvasLeft = 0,
uint16_t canvasTop = 0,
uint16_t canvasWidth = 300,
uint16_t canvasHeight = 400,
uint16_t lineColor = 0, // GxEPD_BLACK
bool drawDataPoints = false,
bool yAxisMinAuto = true,
bool yAxisMaxAuto = true,
float yAxisMin = 0,
float yAxisMax = 100);
void signalBars(GxEPD_Class *display,
int strength,
int x,
int y,
int numbars,
int barwidth,
int barheight,
int heightdelta,
int gap,
uint16_t strokeColor = 0, // BLACK
uint16_t signalColor = 0, // WHITE
uint16_t fillColor = 0xFFFF); // WHITE
#endif
};
#endif |
henrythasler/legendary-dashboard | lib/icons/src/icons.h | <reponame>henrythasler/legendary-dashboard<filename>lib/icons/src/icons.h
#ifndef ICONS_H
#define ICONS_H
#if defined(ESP8266) || defined(ESP32)
#include <pgmspace.h>
#else
#include <avr/pgmspace.h>
#endif
const unsigned char empty [] PROGMEM = {};
// 'gift', 120x120px
const unsigned char giftRed [] PROGMEM = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xc1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0x80, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0xff, 0xff, 0xff,
0xff, 0x00, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x7f, 0xff, 0xff, 0xff,
0x14, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x58, 0x3f, 0xff, 0xff, 0xfe, 0x05,
0x43, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe1, 0x4a, 0x3f, 0xff, 0xfc, 0x06, 0x10, 0x21,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc5, 0x50, 0x3f, 0xff, 0xfc, 0x00, 0x85, 0x28, 0x7f,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x12, 0x55, 0x1f, 0xff, 0xf8, 0x00, 0x00, 0x42, 0x3f, 0xff,
0xff, 0xff, 0xff, 0xff, 0xfe, 0x2a, 0x88, 0x1f, 0xff, 0xf2, 0x6a, 0xa8, 0x28, 0x1f, 0xff, 0xff,
0xff, 0xff, 0xff, 0xfc, 0x8a, 0x42, 0x00, 0x3f, 0xf0, 0xb5, 0x45, 0x02, 0x87, 0xff, 0xff, 0xff,
0xff, 0xff, 0xf8, 0x50, 0x88, 0x80, 0x1f, 0xf0, 0x9a, 0xb4, 0xa0, 0x03, 0xff, 0xff, 0xff, 0xff,
0xff, 0xe2, 0x94, 0x42, 0x6d, 0x1f, 0xf1, 0x6d, 0x55, 0x12, 0x41, 0xff, 0xff, 0xff, 0xff, 0xff,
0xc0, 0x20, 0x2a, 0xb4, 0x1f, 0xe0, 0x35, 0xd5, 0xaa, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x85,
0x05, 0x55, 0xb7, 0x8f, 0xe2, 0xdb, 0x55, 0x52, 0x90, 0x3f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x2a,
0xae, 0xda, 0x0f, 0xf0, 0xad, 0x6a, 0xaa, 0xc0, 0x1f, 0xff, 0xff, 0xff, 0xfe, 0x28, 0x8a, 0xb5,
0x6f, 0x4f, 0xe1, 0x55, 0x55, 0x55, 0x58, 0x2f, 0xff, 0xff, 0xff, 0xfc, 0x02, 0xaa, 0xab, 0x5a,
0x8f, 0xe0, 0x6a, 0xaa, 0x95, 0x55, 0x07, 0xff, 0xff, 0xff, 0xfd, 0x0a, 0xaa, 0xaa, 0xdb, 0x4f,
0xe2, 0xad, 0x55, 0x22, 0xaa, 0x47, 0xff, 0xff, 0xff, 0xf0, 0x55, 0x55, 0x55, 0x6d, 0x0f, 0xf0,
0xab, 0x54, 0x90, 0x95, 0x21, 0xff, 0xff, 0xff, 0xf0, 0x2a, 0xaa, 0xad, 0xb7, 0x4f, 0xe2, 0x55,
0x55, 0x04, 0x2a, 0xa0, 0xff, 0xff, 0xff, 0xc5, 0xaa, 0xa5, 0x55, 0x55, 0x07, 0xe0, 0xaa, 0xaa,
0xa0, 0x01, 0x54, 0x7f, 0xff, 0xff, 0x85, 0x55, 0x10, 0x55, 0x6d, 0xc7, 0xe2, 0x55, 0x54, 0x09,
0x04, 0xaa, 0x3f, 0xff, 0xff, 0x2a, 0xa8, 0x45, 0x55, 0x56, 0x07, 0xf0, 0x55, 0x55, 0xa0, 0x40,
0x15, 0x1f, 0xff, 0xfc, 0x2a, 0xa2, 0x20, 0xaa, 0xab, 0xa7, 0xe2, 0xaa, 0xaa, 0x48, 0x00, 0x05,
0x4f, 0xff, 0xf9, 0x55, 0x00, 0x0a, 0x55, 0x6a, 0x47, 0xe0, 0x55, 0x55, 0x25, 0x02, 0x41, 0x47,
0xff, 0xe1, 0x54, 0x12, 0x41, 0x55, 0xab, 0x07, 0xe0, 0x95, 0x55, 0x48, 0x40, 0x00, 0x50, 0x09,
0x45, 0x40, 0x80, 0x14, 0xaa, 0xb4, 0xa7, 0xe8, 0x52, 0x4a, 0xa2, 0x20, 0x54, 0x11, 0xee, 0xf2,
0xa0, 0x00, 0x84, 0xaa, 0xad, 0x07, 0xe0, 0x15, 0x29, 0x54, 0x00, 0x01, 0x03, 0x7b, 0x41, 0x08,
0x24, 0x22, 0x55, 0x55, 0x47, 0xe2, 0x44, 0xa5, 0x25, 0x20, 0x29, 0x51, 0xaa, 0xf0, 0x02, 0x01,
0x11, 0x2a, 0xaa, 0x47, 0xe0, 0x2a, 0x52, 0x90, 0x44, 0x02, 0x22, 0xb7, 0x50, 0xa8, 0x00, 0x44,
0xaa, 0xaa, 0x07, 0xf2, 0x01, 0x0a, 0x56, 0x20, 0x02, 0x91, 0x51, 0x52, 0x81, 0x24, 0x12, 0x55,
0x55, 0x47, 0xe0, 0x54, 0xa1, 0x51, 0x02, 0x10, 0x52, 0xaa, 0xa4, 0x50, 0x01, 0x45, 0x4a, 0xa8,
0x07, 0xf8, 0x04, 0x95, 0x15, 0x50, 0x01, 0x12, 0xa2, 0xa5, 0x0a, 0x20, 0x11, 0x24, 0x95, 0x47,
0xf1, 0x29, 0x20, 0xa8, 0x01, 0x24, 0x41, 0x55, 0x42, 0x50, 0x04, 0x8a, 0xaa, 0x4a, 0x07, 0xf0,
0x08, 0x2a, 0x0a, 0xa8, 0x00, 0x58, 0xa1, 0x55, 0x02, 0x00, 0x40, 0x49, 0x28, 0x87, 0xf0, 0x02,
0x81, 0x52, 0x40, 0x12, 0x12, 0x45, 0x22, 0x50, 0x42, 0x15, 0x24, 0x84, 0x17, 0xf4, 0x90, 0x28,
0x09, 0x55, 0x00, 0x91, 0x20, 0x81, 0x04, 0x10, 0x84, 0xa4, 0xa5, 0x07, 0xf0, 0x05, 0x02, 0xa4,
0x00, 0x00, 0x20, 0x8a, 0x24, 0x40, 0x02, 0x29, 0x12, 0x10, 0x07, 0xf8, 0x00, 0x90, 0x05, 0x54,
0x80, 0x14, 0x42, 0x85, 0x28, 0x81, 0x08, 0x92, 0x95, 0x07, 0xf0, 0x80, 0x04, 0xa0, 0x00, 0x11,
0x21, 0x10, 0x24, 0x40, 0x10, 0x42, 0x00, 0x20, 0x17, 0xf4, 0x24, 0x40, 0x15, 0x55, 0x00, 0x28,
0x81, 0x02, 0x08, 0x00, 0x11, 0x55, 0x04, 0x87, 0xf0, 0x01, 0x04, 0x00, 0x00, 0x40, 0x80, 0x24,
0x10, 0xa1, 0x11, 0x24, 0x00, 0x50, 0x0f, 0xf9, 0x10, 0x22, 0x42, 0xaa, 0x00, 0x04, 0x00, 0x08,
0x00, 0x80, 0x00, 0x92, 0x08, 0x07, 0xf8, 0x00, 0x00, 0x10, 0x00, 0x90, 0xa8, 0x0a, 0x50, 0x10,
0x2a, 0xaa, 0x00, 0x02, 0x4f, 0xfc, 0x44, 0x82, 0x08, 0x57, 0x80, 0x15, 0x40, 0x09, 0x00, 0x00,
0x00, 0x42, 0x40, 0x0f, 0xf8, 0x00, 0x10, 0x85, 0xb4, 0x14, 0xa5, 0x2a, 0xa0, 0x8a, 0x1a, 0x84,
0x10, 0x10, 0x0f, 0xfa, 0x10, 0x80, 0x55, 0x54, 0x11, 0x24, 0x88, 0x28, 0xa0, 0x82, 0xd0, 0x82,
0x04, 0x0f, 0xf8, 0x04, 0x2a, 0xaa, 0xb1, 0x44, 0x82, 0x53, 0x50, 0x14, 0xa3, 0x55, 0x08, 0x81,
0x2f, 0xfe, 0x82, 0x2a, 0xaa, 0xa0, 0x64, 0x82, 0xbf, 0xf4, 0x04, 0x10, 0xaa, 0xa0, 0x40, 0x0f,
0xfc, 0x08, 0x84, 0x55, 0x4a, 0x81, 0x17, 0xff, 0xf9, 0x12, 0x28, 0xaa, 0x94, 0x20, 0x2f, 0xfe,
0x00, 0x52, 0xaa, 0x82, 0xa9, 0x0f, 0xff, 0xf8, 0x82, 0x8a, 0x2a, 0x55, 0x09, 0x1f, 0xfc, 0x2a,
0x95, 0x2a, 0x2a, 0x80, 0x0f, 0xff, 0xfc, 0x21, 0x04, 0x95, 0x24, 0xa4, 0x3f, 0xff, 0x08, 0x91,
0x55, 0x09, 0x44, 0x8f, 0xff, 0xfc, 0x01, 0x62, 0x0a, 0x92, 0x20, 0x1f, 0xfe, 0x44, 0x4a, 0xa8,
0xa5, 0x10, 0x1f, 0xff, 0xfe, 0x90, 0x85, 0x45, 0x49, 0x4a, 0x7f, 0xfe, 0x25, 0x24, 0xa8, 0x29,
0x01, 0x1f, 0xff, 0xfe, 0x00, 0xa0, 0xa1, 0x28, 0x00, 0x3f, 0xff, 0x08, 0x92, 0xa2, 0x94, 0x00,
0x3f, 0xff, 0xfe, 0x48, 0x0a, 0x92, 0x85, 0x55, 0x7f, 0xff, 0x4a, 0x4a, 0xa1, 0x45, 0x12, 0x3f,
0xff, 0xff, 0x00, 0x40, 0xa8, 0x50, 0x00, 0x7f, 0xff, 0x81, 0x24, 0x0a, 0x28, 0x00, 0x7f, 0xff,
0xff, 0x84, 0x10, 0x52, 0x25, 0x50, 0xff, 0xff, 0xd0, 0x00, 0x0a, 0x8a, 0x84, 0x7f, 0xff, 0xff,
0xc1, 0x04, 0x4a, 0x00, 0x01, 0xff, 0xff, 0xf1, 0x05, 0x24, 0x50, 0x10, 0xff, 0xff, 0xff, 0xc0,
0x28, 0x29, 0x20, 0x2b, 0xff, 0xff, 0xff, 0xfe, 0x15, 0x04, 0x00, 0xff, 0xff, 0xff, 0xc8, 0x01,
0x0a, 0x8c, 0x1f, 0xff, 0xff, 0xff, 0xfc, 0xa2, 0x50, 0x85, 0xff, 0xff, 0xff, 0xe1, 0x00, 0x25,
0x2f, 0xff, 0xff, 0xff, 0xff, 0xf8, 0xa9, 0x08, 0x41, 0xff, 0xff, 0xff, 0xe0, 0x20, 0x11, 0x47,
0xff, 0xff, 0xff, 0xff, 0xf2, 0xa4, 0xa0, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x04, 0x0a, 0xa9, 0xff,
0xff, 0xff, 0xff, 0xc2, 0x92, 0x12, 0x07, 0xff, 0xff, 0xff, 0xfc, 0x82, 0x42, 0x28, 0xff, 0xff,
0xff, 0xff, 0x94, 0xa4, 0x80, 0x97, 0xff, 0xff, 0xff, 0xf8, 0x20, 0x15, 0x4a, 0x3f, 0xff, 0xff,
0xfe, 0x0a, 0xa4, 0x90, 0x0f, 0xff, 0xff, 0xff, 0xfc, 0x02, 0x80, 0xaa, 0x8f, 0xff, 0xff, 0xfc,
0xb4, 0x48, 0x02, 0x0f, 0xff, 0xff, 0xff, 0xfc, 0x10, 0x2a, 0x95, 0x23, 0xff, 0xff, 0xe0, 0x95,
0x22, 0xa0, 0x1f, 0xff, 0xff, 0xff, 0xfe, 0x81, 0x00, 0x52, 0xa1, 0xff, 0xff, 0xc5, 0x4a, 0x94,
0x02, 0x3f, 0xff, 0xff, 0xff, 0xff, 0x08, 0x55, 0x29, 0x0b, 0xff, 0xff, 0xc0, 0xa4, 0x41, 0x10,
0x3f, 0xff, 0xff, 0xff, 0xff, 0x82, 0x04, 0x8a, 0xcf, 0xff, 0xff, 0xf5, 0x52, 0x94, 0x01, 0x7f,
0xff, 0xff, 0xff, 0xff, 0x80, 0xa2, 0x55, 0x3f, 0xff, 0xff, 0xfc, 0x48, 0x82, 0x40, 0xff, 0xff,
0xff, 0xff, 0xff, 0xc8, 0x11, 0x11, 0x3f, 0xff, 0xff, 0xfe, 0x95, 0x20, 0x10, 0xff, 0xff, 0xff,
0xff, 0xff, 0xe0, 0x44, 0xa4, 0x7f, 0xff, 0xff, 0xff, 0x81, 0x09, 0x01, 0xff, 0xff, 0xff, 0xff,
0xff, 0xf2, 0x04, 0x25, 0xff, 0xff, 0xff, 0xff, 0xe8, 0x40, 0x13, 0xff, 0xff, 0xff, 0xff, 0xff,
0xf0, 0x41, 0x4f, 0xff, 0xff, 0xff, 0xff, 0xfa, 0x29, 0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8,
0x08, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfd, 0x22,
0xaf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa4, 0x4f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x0f,
0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x49, 0x4f, 0xff,
0xff, 0xff, 0xff, 0xff, 0x00, 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x0f, 0xff, 0xff,
0xff, 0xff, 0xfe, 0x20, 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xd1, 0x5f, 0xff, 0xff, 0xff,
0xff, 0xfe, 0x12, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe8, 0x0f, 0xff, 0xff, 0xff, 0xff,
0xfe, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff,
0x41, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfd, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x13,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x07, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x8f, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x0f, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x5f, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0x8f, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x3f, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf9, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
const unsigned char giftBlack [] PROGMEM = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xab, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf7, 0xbf, 0xff, 0xff, 0xfd, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfd, 0xdf, 0xff, 0xff, 0xd7, 0xff, 0xff,
0xff, 0xff, 0xff, 0xef, 0xff, 0xff, 0xff, 0xff, 0xfd, 0x6f, 0xff, 0xfd, 0x7f, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xaf, 0xff, 0xfb, 0xaf, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xef, 0xff, 0xfa, 0xf5, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xbf, 0xff, 0xfd, 0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xaf, 0xff, 0xfa, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xfd, 0xaf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x6f, 0xff, 0xfe, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xdf, 0xff, 0xfb, 0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xff, 0xff,
0xff, 0xef, 0xff, 0xfa, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xdf, 0xff, 0xfb, 0xbf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xd7,
0xff, 0xfd, 0xf7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xff,
0xff, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf7,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xd7, 0xf7, 0xaf, 0xff,
0xff, 0xff, 0xff, 0xff, 0xf7, 0xfb, 0xff, 0xff, 0xff, 0xe8, 0x7f, 0xeb, 0xbf, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0x4b, 0xff, 0x5a, 0xd5, 0x5f, 0x7f, 0xf5, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xaa, 0xab, 0xfe, 0xdb, 0x77, 0xd7, 0x5f, 0xfd, 0x2f, 0xff,
0xff, 0xff, 0xff, 0xff, 0xfd, 0x55, 0x4f, 0xff, 0x7d, 0xac, 0xaf, 0xeb, 0xfc, 0xaa, 0xff, 0xff,
0xdf, 0xfd, 0xff, 0xd5, 0x55, 0x5f, 0xfb, 0x7d, 0x7f, 0xff, 0xfb, 0xff, 0x55, 0x5f, 0xff, 0xff,
0xff, 0xff, 0x7b, 0xaa, 0xbf, 0xfe, 0xff, 0xff, 0xff, 0xed, 0xff, 0x55, 0x6b, 0xff, 0xdf, 0xfd,
0xff, 0xad, 0x55, 0x7f, 0xf7, 0xff, 0xff, 0xff, 0xfd, 0x7f, 0xd5, 0xae, 0xff, 0xff, 0xff, 0xfd,
0x6a, 0xd5, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xea, 0xdb, 0x7f, 0xdf, 0xfe, 0xf7, 0x6e,
0xaa, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xfe, 0xbf, 0xf5, 0x6d, 0xdf, 0xff, 0xff, 0xfb, 0xb5, 0x57,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xfa, 0xb6, 0xb7, 0xbf, 0xff, 0xda, 0xdb, 0x57, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0x5f, 0xfe, 0xd7, 0xff, 0xff, 0xff, 0xf7, 0x6d, 0x5f, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xf7, 0xfd, 0x7a, 0xab, 0xff, 0xff, 0xf5, 0xb5, 0x5f, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xbf, 0xff, 0xaf, 0xff, 0xff, 0xff, 0xfe, 0xdb, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xef, 0xff, 0xda, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xf7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
// 'logo', 50x50px
const unsigned char logoBlack [] PROGMEM = {
0xff, 0xff, 0xf8, 0x07, 0xff, 0xff, 0xc0, 0xff, 0xff, 0x80, 0x00, 0x7f, 0xff, 0xc0, 0xff, 0xfe,
0x07, 0xf8, 0x1f, 0xff, 0xc0, 0xff, 0xf8, 0x7c, 0xcf, 0x87, 0xff, 0xc0, 0xff, 0xe1, 0xf8, 0xc7,
0xe1, 0xff, 0xc0, 0xff, 0xc7, 0xf8, 0x07, 0xf8, 0xff, 0xc0, 0xff, 0x8f, 0xf8, 0x07, 0xfc, 0x7f,
0xc0, 0xff, 0x3f, 0xf9, 0x27, 0xfb, 0x3f, 0xc0, 0xfe, 0x67, 0xf9, 0xe7, 0xf3, 0x9f, 0xc0, 0xfc,
0xc3, 0xff, 0xff, 0xe3, 0xcf, 0xc0, 0xf8, 0x91, 0xfc, 0x0f, 0xe0, 0xe7, 0xc0, 0xf9, 0x24, 0xe0,
0x71, 0xc0, 0xe3, 0xc0, 0xf3, 0x09, 0x80, 0x7e, 0x60, 0x13, 0xc0, 0xe7, 0x03, 0x00, 0x7f, 0xb8,
0x39, 0xc0, 0xe7, 0xc6, 0x00, 0x7f, 0xd8, 0xf9, 0xc0, 0xcf, 0xec, 0x00, 0x7f, 0xef, 0xfc, 0xc0,
0xcf, 0xf8, 0x00, 0x7f, 0xf7, 0xfc, 0xc0, 0xcf, 0xf0, 0x00, 0x7f, 0xf3, 0xfe, 0xc0, 0x9f, 0xf0,
0x00, 0x7f, 0xfb, 0xfe, 0x40, 0x9f, 0xe0, 0x00, 0x7f, 0xf9, 0xfe, 0x40, 0x9f, 0xe0, 0x00, 0x7f,
0xfd, 0xfe, 0x40, 0x9f, 0xe0, 0x00, 0x7f, 0xfd, 0xfe, 0x40, 0x9f, 0xe0, 0x00, 0x7f, 0xfc, 0xff,
0x40, 0x9f, 0xe0, 0x00, 0x7f, 0xfc, 0xff, 0x00, 0x9f, 0xc0, 0x00, 0x3f, 0xfc, 0xff, 0x00, 0x9f,
0xcf, 0xff, 0x80, 0x00, 0xff, 0x00, 0x9f, 0xef, 0xff, 0x80, 0x00, 0xff, 0x00, 0x9f, 0xef, 0xff,
0x80, 0x01, 0xff, 0x40, 0x9f, 0xef, 0xff, 0x80, 0x01, 0xfe, 0x40, 0x9f, 0xef, 0xff, 0x80, 0x01,
0xfe, 0x40, 0x9f, 0xf7, 0xff, 0x80, 0x03, 0xfe, 0x40, 0xcf, 0xf7, 0xff, 0x80, 0x03, 0xfe, 0x40,
0xcf, 0xfb, 0xff, 0x80, 0x07, 0xfc, 0xc0, 0xcf, 0xf9, 0xff, 0x80, 0x07, 0xfc, 0xc0, 0xe7, 0xfc,
0xff, 0x80, 0x0f, 0xfc, 0xc0, 0xe7, 0xfe, 0x7f, 0x80, 0x1f, 0xf9, 0xc0, 0xf3, 0xff, 0x3f, 0x80,
0x3f, 0xf1, 0xc0, 0xf3, 0xff, 0xc7, 0x80, 0xff, 0xf3, 0xc0, 0xf9, 0xff, 0xf0, 0x03, 0xff, 0xe7,
0xc0, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xc7, 0xc0, 0xfc, 0x7f, 0xff, 0xff, 0xff, 0x8f, 0xc0, 0xfe,
0x3f, 0xff, 0xff, 0xff, 0x1f, 0xc0, 0xff, 0x1f, 0xff, 0xff, 0xfe, 0x3f, 0xc0, 0xff, 0x8f, 0xff,
0xff, 0xfc, 0x7f, 0xc0, 0xff, 0xe3, 0xff, 0xff, 0xf0, 0xff, 0xc0, 0xff, 0xf0, 0xff, 0xff, 0xc3,
0xff, 0xc0, 0xff, 0xfc, 0x1f, 0xfe, 0x0f, 0xff, 0xc0, 0xff, 0xff, 0x00, 0x00, 0x3f, 0xff, 0xc0,
0xff, 0xff, 0xe0, 0x01, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0
};
// 'logo', 50x50px
const unsigned char logoYellow [] PROGMEM = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0
};
// 'pressure', 25x25px
const unsigned char pressureBlack [] PROGMEM = {
0xfb, 0xf3, 0xff, 0x80, 0xf1, 0xe3, 0xe0, 0x00, 0xe1, 0xe3, 0xe0, 0x00, 0xe3, 0xc3, 0xfe, 0x00,
0xc7, 0xc7, 0xfe, 0x00, 0xc7, 0xcf, 0xfe, 0x00, 0xcf, 0xcf, 0xfe, 0x00, 0xcf, 0xcf, 0xf0, 0x00,
0xc7, 0xcf, 0xf0, 0x00, 0xc3, 0xcf, 0xfe, 0x00, 0xe3, 0xc7, 0xfe, 0x00, 0xf3, 0xc3, 0xfe, 0x00,
0xf3, 0xe3, 0xe0, 0x00, 0xf3, 0xf3, 0xe0, 0x00, 0xf1, 0xf3, 0xfe, 0x00, 0xf1, 0xf3, 0xfe, 0x00,
0xf1, 0xf3, 0xfe, 0x00, 0xf3, 0xf3, 0xf0, 0x00, 0x62, 0xe3, 0xf0, 0x00, 0x62, 0x67, 0xfe, 0x00,
0x22, 0x47, 0xfe, 0x00, 0x06, 0x07, 0xfe, 0x00, 0x0e, 0x1f, 0xe0, 0x00, 0x06, 0x07, 0xe0, 0x00,
0x02, 0x03, 0xff, 0x80
};
// 'humidity', 19x25px
const unsigned char humidityBlack [] PROGMEM = {
0xff, 0xbf, 0xe0, 0xff, 0x1f, 0xe0, 0xfe, 0x0f, 0xe0, 0xfe, 0x4f, 0xe0, 0xfc, 0xe7, 0xe0, 0xf9,
0xf3, 0xe0, 0xf1, 0xf9, 0xe0, 0xf3, 0xf8, 0xe0, 0xe7, 0xfc, 0xe0, 0xcc, 0x7e, 0x60, 0xc9, 0x3e,
0x20, 0x9b, 0xb3, 0x20, 0x99, 0x27, 0x80, 0x3c, 0x4f, 0x80, 0x3f, 0x9f, 0x80, 0x3f, 0x3f, 0x80,
0x3e, 0x7f, 0x80, 0x3c, 0xc7, 0x80, 0xb9, 0x93, 0x80, 0x9f, 0xbb, 0x20, 0x8f, 0x93, 0x20, 0xc7,
0xc6, 0x60, 0xe3, 0xf8, 0xe0, 0xf0, 0x01, 0xe0, 0xfc, 0x07, 0xe0
};
// 'temperature', 13x25px
const unsigned char temperatureBlack [] PROGMEM = {
0xf8, 0x38, 0xf3, 0x98, 0xf7, 0xd8, 0x37, 0xd8, 0xf6, 0xd8, 0xf4, 0x58, 0x34, 0x58, 0xf4, 0x58,
0xf4, 0x58, 0x34, 0x58, 0xf4, 0x58, 0xf4, 0x58, 0x34, 0x58, 0xf4, 0x58, 0xf4, 0x58, 0x34, 0x58,
0xe4, 0x48, 0xc8, 0x20, 0xd3, 0x10, 0xd3, 0x10, 0xd0, 0x10, 0xc8, 0x20, 0xe4, 0x48, 0xf3, 0x98,
0xf8, 0x38
};
#endif |
ayanchoudhary/learn2pwn | mitigations/tasks/task1/canary.c | // gcc -o canary canary.c -m32 -no-pie -fno-pic -mpreferred-stack-boundary=2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int nextind, devrand;
char *password;
int cans[2];
void initCanary(char *s)
{
memset(s, 0, 0x28u);
read(devrand, s + 0x28, 4u);
*((unsigned int *)s + 11) = nextind;
cans[nextind] = *((unsigned int *)s + 10);
nextind++;
}
void checkCanary(int *a1)
{
if ( *(unsigned int *)(a1 + 10) != cans[*(unsigned int *)(a1 + 11)] )
{
puts("---------------------- HEY NO STACK SMASHING! --------------------");
exit(1);
}
}
void checkPass(char *s1, char *s2)
{
if ( !memcmp(s1, s2, 0x20u) )
{
puts("*unlocks door*\nYou're cool, c'mon in");
system("/bin/cat ./flag");
}
else
{
puts("Yeah right! Scram");
}
}
void doCanary(char *buf)
{
initCanary(buf);
read(0, buf, 0x1A4u);
checkCanary((int *)buf);
}
void main(int argc, const char **argv, const char **envp)
{
char s2[0x30]; // [sp+0h] [bp-34h]@1
int fd; // [sp+30h] [bp-4h]@1
setvbuf(stdout, 0, 2, 0x14u);
setvbuf(stdin, 0, 2, 0x14u);
devrand = open("/dev/urandom", 0);
password = malloc(0x20u);
printf("*slides open window*\nPassword? ");
doCanary(s2);
fd = open("./password", 0);
read(fd, password, 0x21u);
checkPass(password, s2);
}
|
tahussle/bebbang | wallet/qt/ntp1/ntp1tokenlistmodel.h | #ifndef NTP1TOKENLISTMODEL_H
#define NTP1TOKENLISTMODEL_H
#include <QAbstractTableModel>
#include <QTimer>
#include <atomic>
#include "init.h"
#include "ntp1/ntp1wallet.h"
#include "wallet.h"
class NTP1TokenListModel : public QAbstractTableModel
{
Q_OBJECT
boost::shared_ptr<NTP1Wallet> ntp1wallet;
bool walletLocked;
bool walletUpdateRunning;
boost::atomic_flag walletUpdateLockFlag = BOOST_ATOMIC_FLAG_INIT;
boost::atomic_bool updateWalletAgain;
QTimer* walletUpdateEnderTimer;
boost::promise<boost::shared_ptr<NTP1Wallet>> updateWalletPromise;
boost::unique_future<boost::shared_ptr<NTP1Wallet>> updateWalletFuture;
static void UpdateWalletBalances(boost::shared_ptr<NTP1Wallet> wallet,
boost::promise<boost::shared_ptr<NTP1Wallet>>& promise);
class NTP1WalletTxUpdater : public WalletNewTxUpdateFunctor
{
NTP1TokenListModel* model;
int currentBlockHeight;
public:
NTP1WalletTxUpdater(NTP1TokenListModel* Model) : model(Model), currentBlockHeight(-1) {}
void run(uint256, int currentHeight) Q_DECL_OVERRIDE
{
if (currentBlockHeight < 0) {
setReferenceBlockHeight();
}
if (currentHeight <= currentBlockHeight + HEIGHT_OFFSET_TOLERANCE) {
model->reloadBalances();
}
}
virtual ~NTP1WalletTxUpdater() {}
// WalletNewTxUpdateFunctor interface
public:
void setReferenceBlockHeight() Q_DECL_OVERRIDE { currentBlockHeight = nBestHeight; }
};
boost::shared_ptr<NTP1WalletTxUpdater> ntp1WalletTxUpdater;
void SetupNTP1WalletTxUpdaterToWallet()
{
while (!std::atomic_load(&pwalletMain).get()) {
boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
}
std::atomic_load(&pwalletMain)->setFunctorOnTxInsert(ntp1WalletTxUpdater);
}
public:
static QString __getTokenName(int index, boost::shared_ptr<NTP1Wallet> theWallet);
static QString __getTokenId(int index, boost::shared_ptr<NTP1Wallet> theWallet);
static QString __getTokenDescription(int index, boost::shared_ptr<NTP1Wallet> theWallet);
static QString __getTokenBalance(int index, boost::shared_ptr<NTP1Wallet> theWallet);
static QString __getIssuanceTxid(int index, boost::shared_ptr<NTP1Wallet> theWallet);
static QIcon __getTokenIcon(int index, boost::shared_ptr<NTP1Wallet> theWallet);
void clearNTP1Wallet();
void refreshNTP1Wallet();
NTP1TokenListModel();
virtual ~NTP1TokenListModel();
void reloadBalances();
int rowCount(const QModelIndex& parent) const Q_DECL_OVERRIDE;
int columnCount(const QModelIndex& parent) const Q_DECL_OVERRIDE;
QVariant data(const QModelIndex& index, int role) const Q_DECL_OVERRIDE;
/** Roles to get specific information from a token row.
These are independent of column.
*/
enum RoleIndex
{
TokenNameRole = Qt::UserRole,
TokenDescriptionRole,
TokenIdRole,
AmountRole,
IssuanceTxidRole
};
void saveWalletToFile();
void loadWalletFromFile();
boost::shared_ptr<NTP1Wallet> getCurrentWallet() const;
static const std::string WalletFileName;
signals:
void signal_walletUpdateRunning(bool running);
private slots:
void beginWalletUpdate();
void endWalletUpdate();
};
extern std::atomic<NTP1TokenListModel*> ntp1TokenListModelInstance;
#endif // NTP1TOKENLISTMODEL_H
|
tahussle/bebbang | wallet/ntp1/ntp1sendtxdata.h | #ifndef NTP1SENDTXDATA_H
#define NTP1SENDTXDATA_H
#include "ntp1/ntp1wallet.h"
#include "ntp1sendtokensonerecipientdata.h"
#include <deque>
#include <string>
#include <unordered_set>
struct IntermediaryTI
{
static const unsigned int CHANGE_OUTPUT_FAKE_INDEX = 10000000;
std::vector<NTP1Script::TransferInstruction> TIs;
NTP1OutPoint input;
};
/**
* This class locates available NPT1 tokens in an NTP1Wallet object and either finds the required amount
* of tokens in the wallet or simply ensures that the required amounts exist in the wallet
*
* @brief The NTP1SendTxData class
*/
class NTP1SendTxData
{
// this is a vector because order must be preserved
std::vector<NTP1OutPoint> tokenSourceInputs;
std::vector<IntermediaryTI> intermediaryTIs;
std::map<std::string, NTP1Int> totalChangeTokens;
std::map<std::string, NTP1Int> totalTokenAmountsInSelectedInputs;
std::vector<NTP1SendTokensOneRecipientData> recipientsList;
boost::shared_ptr<NTP1Wallet> usedWallet;
int64_t __addInputsThatCoversNeblAmount(uint64_t neblAmount);
bool ready = false;
public:
NTP1SendTxData();
/**
* @brief calculateSources
* @param wallet
* @param inputs: inputs to be used; if no inputs provided, everything in the wallet will be used
* @param recipients
* @param recalculateFee
* @param neblAmount amount to be sent with the transaction
*/
void selectNTP1Tokens(boost::shared_ptr<NTP1Wallet> wallet, std::vector<NTP1OutPoint> inputs,
std::vector<NTP1SendTokensOneRecipientData> recipients,
bool addMoreInputsIfRequired);
void selectNTP1Tokens(boost::shared_ptr<NTP1Wallet> wallet, const std::vector<COutPoint>& inputs,
const std::vector<NTP1SendTokensOneRecipientData>& recipients,
bool addMoreInputsIfRequired);
static const std::string NEBL_TOKEN_ID;
// returns the total balance in the selected addresses (tokenSourceAddresses)
static int64_t EstimateTxSizeInBytes(int64_t num_of_inputs, int64_t num_of_outputs);
static int64_t EstimateTxFee(int64_t num_of_inputs, int64_t num_of_outputs);
std::vector<NTP1OutPoint> getUsedInputs() const;
std::map<std::string, NTP1Int> getChangeTokens() const;
std::map<std::string, NTP1Int> getTotalTokensInInputs() const;
bool isReady() const;
// list of recipients after removing Nebl recipients
std::vector<NTP1SendTokensOneRecipientData> getNTP1TokenRecipientsList() const;
boost::shared_ptr<NTP1Wallet> getWallet() const;
std::vector<IntermediaryTI> getIntermediaryTIs() const;
/**
* @brief hasNTP1Tokens
* @return true if the resulting inputs have NTP1 tokens
*/
bool hasNTP1Tokens() const;
uint64_t getRequiredNeblsForOutputs() const;
static void FixTIsChangeOutputIndex(std::vector<NTP1Script::TransferInstruction>& TIs,
int changeOutputIndex);
};
#endif // NTP1SENDTXDATA_H
|
tahussle/bebbang | wallet/qt/ntp1sendsingletokenfields.h | #ifndef NTP1SENDSINGLETOKENFIELDS_H
#define NTP1SENDSINGLETOKENFIELDS_H
#include <QComboBox>
#include <QGridLayout>
#include <QLineEdit>
#include <QPushButton>
#include <functional>
#include "ntp1/ntp1listelementtokendata.h"
#include "ntp1/ntp1sendtokensonerecipientdata.h"
#include "ntp1senddialog.h"
class NTP1SendSingleTokenFields Q_DECL_FINAL : public QWidget
{
Q_OBJECT
QGridLayout* mainLayout;
QLineEdit* amount;
QLineEdit* destination;
QComboBox* tokenTypeComboBox;
QPushButton* closeButton;
void createWidgets();
std::function<boost::shared_ptr<NTP1Wallet>(void)> retrieveLatestWallet;
std::deque<NTP1ListElementTokenData> currentTokens;
void fillCurrentTokens();
public:
explicit NTP1SendSingleTokenFields(
std::function<boost::shared_ptr<NTP1Wallet>(void)> WalletRetriever, QWidget* parent = Q_NULLPTR);
virtual ~NTP1SendSingleTokenFields();
NTP1SendTokensOneRecipientData createRecipientData() const;
void resetAllFields();
signals:
void signal_closeThis(QWidget* theWidget);
public slots:
void slot_closeThis();
void slot_hideClose();
void slot_showClose();
void slot_updateTokenList();
};
#endif // NTP1SENDSINGLETOKENFIELDS_H
|
tahussle/bebbang | wallet/qt/ntp1summary.h | #ifndef NTP1SUMMARY_H
#define NTP1SUMMARY_H
#include "ntp1/ntp1tokenlistfilterproxy.h"
#include "ntp1/ntp1tokenlistitemdelegate.h"
#include "ntp1/ntp1tokenlistmodel.h"
#include "ui_ntp1summary.h"
#include "json/NTP1MetadataViewer.h"
#include <QTimer>
#include <QWidget>
#include <boost/thread.hpp>
#include <boost/thread/future.hpp>
QT_BEGIN_NAMESPACE
class QModelIndex;
QT_END_NAMESPACE
class Ui_NTP1Summary;
class WalletModel;
/** NTP1Summary page widget */
class NTP1Summary : public QWidget
{
Q_OBJECT
public:
explicit NTP1Summary(QWidget* parent = 0);
~NTP1Summary();
void setModel(NTP1TokenListModel* model);
void showOutOfSyncWarning(bool fShow);
public slots:
signals:
void tokenClicked(const QModelIndex& index);
public:
Ui_NTP1Summary* ui;
NTP1TokenListModel* getTokenListModel() const;
private:
static const QString copyTokenIdText;
static const QString copyTokenSymbolText;
static const QString copyTokenNameText;
static const QString viewInBlockExplorerText;
static const QString viewIssuanceMetadataText;
qint64 currentBalance;
qint64 currentStake;
qint64 currentUnconfirmedBalance;
qint64 currentImmatureBalance;
NTP1TokenListModel* model;
NTP1TokenListFilterProxy* filter;
NTP1TokenListItemDelegate* tokenDelegate;
QMenu* contextMenu = Q_NULLPTR;
QAction* copyTokenIdAction = Q_NULLPTR;
QAction* copyTokenSymbolAction = Q_NULLPTR;
QAction* copyTokenNameAction = Q_NULLPTR;
QAction* viewInBlockExplorerAction = Q_NULLPTR;
QAction* showMetadataAction = Q_NULLPTR;
NTP1MetadataViewer* metadataViewer;
// caching mechanism for the metadata to avoid accessing the db repeatedly4
std::unordered_map<uint256, json_spirit::Value> issuanceTxidVsMetadata;
private slots:
void handleTokenClicked(const QModelIndex& index);
void slot_contextMenuRequested(QPoint pos);
void slot_copyTokenIdAction();
void slot_copyTokenSymbolAction();
void slot_copyTokenNameAction();
void slot_visitInBlockExplorerAction();
void slot_showMetadataAction();
// QWidget interface
protected:
void keyPressEvent(QKeyEvent* event);
void setupContextMenu();
};
#endif // NTP1SUMMARY_H
|
tahussle/bebbang | wallet/txdb-lmdb.h | <reponame>tahussle/bebbang
// Copyright (c) 2009-2012 The Bitcoin Developers.
// Authored by Google, Inc.
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_LMDB_H
#define BITCOIN_LMDB_H
//#define DEEP_LMDB_LOGGING
#include "main.h"
#include <atomic>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "liblmdb/lmdb.h"
#include "ntp1/ntp1transaction.h"
#define ENABLE_AUTO_RESIZE
// global environment pointer
extern std::unique_ptr<MDB_env, void (*)(MDB_env*)> dbEnv;
// global database pointers
using DbSmartPtrType = std::unique_ptr<MDB_dbi, void (*)(MDB_dbi*)>;
extern DbSmartPtrType glob_db_main;
extern DbSmartPtrType glob_db_blockIndex;
extern DbSmartPtrType glob_db_blocks;
extern DbSmartPtrType glob_db_version;
extern DbSmartPtrType glob_db_tx;
extern DbSmartPtrType glob_db_ntp1Tx;
extern DbSmartPtrType glob_db_ntp1tokenNames;
const std::string LMDB_MAINDB = "MainDb";
const std::string LMDB_BLOCKINDEXDB = "BlockIndexDb";
const std::string LMDB_BLOCKSDB = "BlocksDb";
const std::string LMDB_VERSIONDB = "VersionDb";
const std::string LMDB_TXDB = "TxDb";
const std::string LMDB_NTP1TXDB = "Ntp1txDb";
const std::string LMDB_NTP1TOKENNAMESDB = "Ntp1NamesDb";
constexpr static float DB_RESIZE_PERCENT = 0.9f;
const std::string QuickSyncDataLink =
"https://raw.githubusercontent.com/NeblioTeam/neblio-quicksync/master/download.json";
// this custom size is used in tests
#ifndef CUSTOM_LMDB_DB_SIZE
#if defined(__arm__)
// force a value so it can compile with 32-bit ARM
constexpr static uint64_t DB_DEFAULT_MAPSIZE = UINT64_C(1) << 31;
#else
#if defined(ENABLE_AUTO_RESIZE)
constexpr static uint64_t DB_DEFAULT_MAPSIZE = UINT64_C(1) << 30;
#else
constexpr static uint64_t DB_DEFAULT_MAPSIZE = UINT64_C(1) << 33;
#endif
#endif
#else
constexpr static uint64_t DB_DEFAULT_MAPSIZE = CUSTOM_LMDB_DB_SIZE;
#endif
#define HAS_MEMBER_FUNC(func, name) \
template <typename T, typename Sign> \
struct name \
{ \
typedef char yes[1]; \
typedef char no[2]; \
template <typename U, U> \
struct type_check; \
template <typename _1> \
static yes& chk(type_check<Sign, &_1::func>*); \
template <typename> \
static no& chk(...); \
static bool const value = sizeof(chk<T>(0)) == sizeof(yes); \
}
HAS_MEMBER_FUNC(toString, has_toString_class);
HAS_MEMBER_FUNC(ToString, has_ToString_class);
template <typename T>
constexpr bool Has_ToString()
{
return has_ToString_class<T, std::string (T::*)()>::value;
}
template <typename T>
constexpr bool Has_toString()
{
return has_toString_class<T, std::string (T::*)()>::value;
}
template <typename T>
typename enable_if<Has_ToString<T>() && Has_toString<T>(), std::string>::type
KeyAsString(const T& k, const std::string& /*keyStr*/)
{
return k->ToString();
}
template <typename T>
typename enable_if<Has_ToString<T>() && !Has_toString<T>(), std::string>::type
KeyAsString(const T& k, const std::string& /*keyStr*/)
{
return k->ToString();
}
template <typename T>
typename enable_if<!Has_ToString<T>() && Has_toString<T>(), std::string>::type
KeyAsString(const T& k, const std::string& /*keyStr*/)
{
return k->toString();
}
template <typename T>
typename enable_if<!Has_ToString<T>() && !Has_toString<T>(), std::string>::type
KeyAsString(const T& /*t*/, const std::string& keyStr)
{
if (std::all_of(keyStr.begin(), keyStr.end(), ::isprint)) {
return keyStr;
} else {
return "(in hex: 0x" + boost::algorithm::hex(keyStr) + ")";
}
}
class CTxDB;
void lmdb_resized(MDB_env* env);
inline int lmdb_txn_begin(MDB_env* env, MDB_txn* parent, unsigned int flags, MDB_txn** txn)
{
int res = mdb_txn_begin(env, parent, flags, txn);
if (res == MDB_MAP_RESIZED) {
lmdb_resized(env);
res = mdb_txn_begin(env, parent, flags, txn);
}
return res;
}
struct mdb_txn_safe
{
mdb_txn_safe(const bool check = true);
mdb_txn_safe(const mdb_txn_safe&) = delete;
mdb_txn_safe& operator=(const mdb_txn_safe&) = delete;
~mdb_txn_safe();
mdb_txn_safe(mdb_txn_safe&& other);
mdb_txn_safe& operator=(mdb_txn_safe&& other);
void commit(std::string message = "");
void commitIfValid(std::string message = "");
// This should only be needed for batch transaction which must be ensured to
// be aborted before mdb_env_close, not after. So we can't rely on
// BlockchainLMDB destructor to call mdb_txn_safe destructor, as that's too late
// to properly abort, since mdb_env_close would have been called earlier.
void abort();
void abortIfValid();
void uncheck();
operator MDB_txn*() { return m_txn; }
operator MDB_txn**() { return &m_txn; }
MDB_txn* rawPtr() const { return m_txn; }
uint64_t num_active_tx() const;
static void prevent_new_txns();
static void wait_no_active_txns();
static void allow_new_txns();
MDB_txn* m_txn;
bool m_batch_txn = false;
bool m_check;
static std::atomic<uint64_t> num_active_txns;
// could use a mutex here, but this should be sufficient.
static std::atomic_flag creation_gate;
};
// Class that provides access to a LevelDB. Note that this class is frequently
// instantiated on the stack and then destroyed again, so instantiation has to
// be very cheap. Unfortunately that means, a CTxDB instance is actually just a
// wrapper around some global state.
//
// A LevelDB is a key/value store that is optimized for fast usage on hard
// disks. It prefers long read/writes to seeks and is based on a series of
// sorted key/value mapping files that are stacked on top of each other, with
// newer files overriding older files. A background thread compacts them
// together when too many files stack up.
//
// Learn more: http://code.google.com/p/leveldb/
class CTxDB
{
public:
static boost::filesystem::path DB_DIR;
// this flag is useful for disabling quicksync manually, for example, for tests
static bool QuickSyncHigherControl_Enabled;
CTxDB(const char* pszMode = "r+");
CTxDB(const CTxDB&) = delete;
CTxDB(CTxDB&&) = delete;
CTxDB& operator=(const CTxDB&) = delete;
CTxDB& operator=(CTxDB&&) = delete;
~CTxDB();
// Destroys the underlying shared global state accessed by this TxDB.
void Close();
static void __deleteDb();
private:
// Points to the global instance databases on construction.
MDB_dbi* db_main;
MDB_dbi* db_blockIndex;
MDB_dbi* db_blocks;
MDB_dbi* db_tx;
MDB_dbi* db_ntp1Tx;
MDB_dbi* db_ntp1tokenNames;
// A batch stores up writes and deletes for atomic application. When this
// field is non-NULL, writes/deletes go there instead of directly to disk.
std::unique_ptr<mdb_txn_safe> activeBatch;
bool fReadOnly;
int nVersion;
void (*dbDeleter)(MDB_dbi*) = [](MDB_dbi* p) {
if (p) {
mdb_close(dbEnv.get(), *p);
delete p;
}
};
protected:
// Returns true and sets (value,false) if activeBatch contains the given key
// or leaves value alone and sets deleted = true if activeBatch contains a
// delete for it.
// bool ScanBatch(const CDataStream& key, std::string* value, bool* deleted) const;
template <typename K, typename T>
bool Read(const K& key, T& value, MDB_dbi* dbPtr, int serializationTypeModifiers = 0,
size_t offset = 0)
{
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(1000);
ssKey << key;
mdb_txn_safe localTxn(false);
if (!activeBatch) {
localTxn = mdb_txn_safe();
if (auto res = lmdb_txn_begin(dbEnv.get(), nullptr, MDB_RDONLY, localTxn)) {
printf("Failed to begin transaction at read with error code %i; and error code: %s\n",
res, mdb_strerror(res));
}
}
// only one of them should be active
assert(localTxn.rawPtr() == nullptr || activeBatch == nullptr);
std::string&& keyBin = ssKey.str();
MDB_val kS = {keyBin.size(), (void*)(keyBin.c_str())};
MDB_val vS = {0, nullptr};
if (auto ret = mdb_get((!activeBatch ? localTxn : *activeBatch), *dbPtr, &kS, &vS)) {
std::string dbgKey = KeyAsString(key, ssKey.str());
if (ret == MDB_NOTFOUND) {
printf("Failed to read lmdb key %s as it doesn't exist\n", dbgKey.c_str());
} else {
printf("Failed to read lmdb key %s with an unknown error of code %i; and error: %s\n",
dbgKey.c_str(), ret, mdb_strerror(ret));
}
if (localTxn.rawPtr()) {
localTxn.abort();
}
return false;
}
// Unserialize value
assert(offset <= vS.mv_size);
assert(vS.mv_data != nullptr);
try {
CDataStream ssValue(static_cast<const char*>(vS.mv_data) + offset,
static_cast<const char*>(vS.mv_data) + vS.mv_size,
SER_DISK | serializationTypeModifiers, CLIENT_VERSION);
ssValue >> value;
} catch (std::exception& e) {
printf("Failed to deserialized data when reading for key %s\n", ssKey.str().c_str());
return false;
}
if (localTxn.rawPtr()) {
localTxn.abort();
}
return true;
}
template <typename K, typename T, template <typename, typename = std::allocator<T> > class Container>
bool ReadMultiple(const K& key, Container<T>& values, MDB_dbi* dbPtr)
{
values.clear();
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(1000);
ssKey << key;
mdb_txn_safe localTxn(false);
if (!activeBatch) {
localTxn = mdb_txn_safe();
if (auto res = lmdb_txn_begin(dbEnv.get(), nullptr, MDB_RDONLY, localTxn)) {
printf("Failed to begin transaction at read with error code %i; and error code: %s\n",
res, mdb_strerror(res));
}
}
// only one of them should be active
assert(localTxn.rawPtr() == nullptr || activeBatch == nullptr);
std::string&& keyBin = ssKey.str();
MDB_val kS = {keyBin.size(), (void*)(keyBin.c_str())};
MDB_val vS = {0, nullptr};
MDB_cursor* cursorRawPtr = nullptr;
if (auto rc = mdb_cursor_open((!activeBatch ? localTxn : *activeBatch), *dbPtr, &cursorRawPtr)) {
return error("ReadMultiple: Failed to open lmdb cursor with error code %d; and error: %s\n",
rc, mdb_strerror(rc));
}
std::unique_ptr<MDB_cursor, void (*)(MDB_cursor*)> cursorPtr(
cursorRawPtr, [](MDB_cursor* p) {
if (p)
mdb_cursor_close(p);
});
int itemRes = mdb_cursor_get(cursorPtr.get(), &kS, &vS, MDB_SET);
if (itemRes) {
std::string dbgKey = KeyAsString(key, ssKey.str());
if (itemRes != 0 && itemRes != MDB_NOTFOUND) {
printf("txdb-lmdb: Cursor with key %s does not exist; with an error of code %i; and error: %s\n",
dbgKey.c_str(), itemRes, mdb_strerror(itemRes));
if (localTxn.rawPtr()) {
localTxn.abort();
}
return false;
}
}
do {
// if the first item is empty, break immediately
if (itemRes) {
break;
}
// Unserialize value
assert(vS.mv_data != nullptr);
try {
CDataStream ssValue(static_cast<const char*>(vS.mv_data),
static_cast<const char*>(vS.mv_data) + vS.mv_size, SER_DISK,
CLIENT_VERSION);
T value;
ssValue >> value;
values.insert(values.end(), value);
} catch (std::exception& e) {
unsigned int sz = static_cast<unsigned int>(values.size());
printf("Failed to deserialized element number %u in lmdb ReadMultiple() data when "
"reading for key %s\n",
sz, ssKey.str().c_str());
return false;
}
itemRes = mdb_cursor_get(cursorRawPtr, &kS, &vS, MDB_NEXT);
} while (itemRes == 0);
cursorPtr.reset();
if (localTxn.rawPtr()) {
localTxn.abort();
}
return true;
}
template <typename K, typename T>
bool Write(const K& key, const T& value, MDB_dbi* dbPtr)
{
if (fReadOnly) {
printf("Accessing lmdb write function in read only mode");
assert("Write called on database in read-only mode");
return false;
}
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(1000);
ssKey << key;
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.reserve(10000);
ssValue << value;
// you can't resize the db when a tx is active
if (!activeBatch && CTxDB::need_resize()) {
printf("LMDB memory map needs to be resized, doing that now.\n");
CTxDB::do_resize();
}
mdb_txn_safe localTxn(false);
if (!activeBatch) {
localTxn = mdb_txn_safe();
if (auto res = lmdb_txn_begin(dbEnv.get(), nullptr, 0, localTxn)) {
printf("Failed to begin transaction at read with error code %i; and error: %s\n", res,
mdb_strerror(res));
}
}
// only one of them should be active
assert(localTxn.rawPtr() == nullptr || activeBatch == nullptr);
std::string&& keyBin = ssKey.str();
MDB_val kS = {keyBin.size(), (void*)(keyBin.c_str())};
std::string&& valBin = ssValue.str();
MDB_val vS = {valBin.size(), (void*)(valBin.c_str())};
if (auto ret = mdb_put((!activeBatch ? localTxn : *activeBatch), *dbPtr, &kS, &vS, 0)) {
std::string dbgKey = KeyAsString(key, ssKey.str());
if (ret == MDB_MAP_FULL) {
printf("Failed to write key %s with lmdb, MDB_MAP_FULL\n", dbgKey.c_str());
} else {
printf("Failed to write key %s with lmdb; Code %i; Error: %s\n", dbgKey.c_str(), ret,
mdb_strerror(ret));
}
if (localTxn.rawPtr()) {
localTxn.abort();
}
return false;
}
if (localTxn.rawPtr()) {
localTxn.commitIfValid("Tx while writing");
}
return true;
}
template <typename K, typename T>
bool WriteMultiple(const K& key, const T& value, MDB_dbi* dbPtr)
{
if (fReadOnly) {
printf("Accessing lmdb write function in read only mode");
assert("Write called on database in read-only mode");
return false;
}
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(1000);
ssKey << key;
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.reserve(10000);
ssValue << value;
// you can't resize the db when a tx is active
if (!activeBatch && CTxDB::need_resize()) {
printf("LMDB memory map needs to be resized, doing that now.\n");
CTxDB::do_resize();
}
mdb_txn_safe localTxn(false);
if (!activeBatch) {
localTxn = mdb_txn_safe();
if (auto res = lmdb_txn_begin(dbEnv.get(), nullptr, 0, localTxn)) {
printf("Failed to begin transaction at read with error code %i; and error: %s\n", res,
mdb_strerror(res));
}
}
// only one of them should be active
assert(localTxn.rawPtr() == nullptr || activeBatch == nullptr);
std::string&& keyBin = ssKey.str();
MDB_val kS = {keyBin.size(), (void*)(keyBin.c_str())};
std::string&& valBin = ssValue.str();
MDB_val vS = {valBin.size(), (void*)(valBin.c_str())};
MDB_cursor* cursorRawPtr = nullptr;
if (auto rc = mdb_cursor_open((!activeBatch ? localTxn : *activeBatch), *dbPtr, &cursorRawPtr)) {
return error("ReadMultiple: Failed to open lmdb cursor with error code %d; and error: %s\n",
rc, mdb_strerror(rc));
}
std::unique_ptr<MDB_cursor, void (*)(MDB_cursor*)> cursorPtr(
cursorRawPtr, [](MDB_cursor* p) {
if (p)
mdb_cursor_close(p);
});
if (auto ret = mdb_cursor_put(cursorPtr.get(), &kS, &vS, 0)) {
std::string dbgKey = KeyAsString(key, ssKey.str());
if (ret == MDB_MAP_FULL) {
printf("Failed to write key %s with lmdb, MDB_MAP_FULL\n", dbgKey.c_str());
} else {
printf("Failed to write key %s with lmdb; Code %i; Error: %s\n", dbgKey.c_str(), ret,
mdb_strerror(ret));
}
if (localTxn.rawPtr()) {
localTxn.abort();
}
return false;
}
cursorPtr.reset();
localTxn.commitIfValid("Tx while writing");
return true;
}
template <typename K>
bool Erase(const K& key, MDB_dbi* dbPtr)
{
if (!dbPtr)
return false;
if (fReadOnly) {
printf("Accessing lmdb erase function in read-only mode.");
assert("Erase called on database in read-only mode");
return false;
}
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(1000);
ssKey << key;
mdb_txn_safe localTxn(false);
if (!activeBatch) {
localTxn = mdb_txn_safe();
if (auto res = lmdb_txn_begin(dbEnv.get(), nullptr, 0, localTxn)) {
printf("Failed to begin transaction at read with error code %i; and error: %s\n", res,
mdb_strerror(res));
}
}
// only one of them should be active
assert(localTxn.rawPtr() == nullptr || activeBatch == nullptr);
std::string&& keyBin = ssKey.str();
MDB_val kS = {keyBin.size(), (void*)(keyBin.c_str())};
MDB_val vS{0, nullptr};
if (auto ret = mdb_del((!activeBatch ? localTxn : *activeBatch), *dbPtr, &kS, &vS)) {
std::string dbgKey = KeyAsString(key, ssKey.str());
printf("Failed to delete entry with key %s with lmdb; Code %i; Error message: %s\n",
dbgKey.c_str(), ret, mdb_strerror(ret));
if (localTxn.rawPtr()) {
localTxn.abort();
}
return false;
}
localTxn.commitIfValid("Tx while erasing");
return true;
}
template <typename K>
bool EraseAll(const K& key, MDB_dbi* dbPtr)
{
if (!dbPtr)
return false;
if (fReadOnly) {
printf("Accessing lmdb erase function in read-only mode.");
assert("Erase called on database in read-only mode");
return false;
}
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(1000);
ssKey << key;
mdb_txn_safe localTxn(false);
if (!activeBatch) {
localTxn = mdb_txn_safe();
if (auto res = lmdb_txn_begin(dbEnv.get(), nullptr, 0, localTxn)) {
printf("Failed to begin transaction at read with error code %i; and error: %s\n", res,
mdb_strerror(res));
}
}
// only one of them should be active
assert(localTxn.rawPtr() == nullptr || activeBatch == nullptr);
std::string&& keyBin = ssKey.str();
MDB_val kS = {keyBin.size(), (void*)(keyBin.c_str())};
MDB_val vS{0, nullptr};
MDB_cursor* cursorRawPtr = nullptr;
if (auto rc = mdb_cursor_open((!activeBatch ? localTxn : *activeBatch), *dbPtr, &cursorRawPtr)) {
return error("EraseDup: Failed to open lmdb cursor with error code %d; and error: %s\n",
rc, mdb_strerror(rc));
}
std::unique_ptr<MDB_cursor, void (*)(MDB_cursor*)> cursorPtr(
cursorRawPtr, [](MDB_cursor* p) {
if (p)
mdb_cursor_close(p);
});
int itemRes = mdb_cursor_get(cursorPtr.get(), &kS, &vS, MDB_SET);
if (itemRes) {
std::string dbgKey = KeyAsString(key, ssKey.str());
if (itemRes != 0) {
printf("Failed to erase lmdb key %s with an error of code %i; and error: %s\n",
dbgKey.c_str(), itemRes, mdb_strerror(itemRes));
}
if (localTxn.rawPtr()) {
localTxn.abort();
}
return false;
}
if (auto ret = mdb_cursor_del(cursorPtr.get(), MDB_NODUPDATA)) {
std::string dbgKey = KeyAsString(key, ssKey.str());
printf("Failed to delete entry with key %s with lmdb; Code %i; Error message: %s\n",
dbgKey.c_str(), ret, mdb_strerror(ret));
if (localTxn.rawPtr()) {
localTxn.abort();
}
return false;
}
cursorPtr.reset();
localTxn.commitIfValid("Tx while erasing");
return true;
}
template <typename K>
bool Exists(const K& key, MDB_dbi* dbPtr)
{
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(1000);
ssKey << key;
std::string unused;
mdb_txn_safe localTxn(false);
if (!activeBatch) {
localTxn = mdb_txn_safe();
if (auto res = lmdb_txn_begin(dbEnv.get(), nullptr, MDB_RDONLY, localTxn)) {
printf("Failed to begin transaction at read with error code %i; and error: %s\n", res,
mdb_strerror(res));
}
}
// only one of them should be active
assert(localTxn.rawPtr() == nullptr || activeBatch == nullptr);
std::string&& keyBin = ssKey.str();
MDB_val kS = {keyBin.size(), (void*)(keyBin.c_str())};
MDB_val vS{0, nullptr};
if (auto ret = mdb_get((!activeBatch ? localTxn : *activeBatch), *dbPtr, &kS, &vS)) {
if (localTxn.rawPtr()) {
localTxn.abort();
}
std::string dbgKey = KeyAsString(key, ssKey.str());
if (ret == MDB_NOTFOUND) {
return false;
} else {
printf("Failed to check whether key %s exists with an unknown error of code %i; and "
"error: %s\n",
dbgKey.c_str(), ret, mdb_strerror(ret));
}
return false;
} else {
if (localTxn.rawPtr()) {
localTxn.abort();
}
return true;
}
}
public:
inline static void lmdb_db_open(MDB_txn* txn, const char* name, int flags, MDB_dbi& dbi,
const std::string& error_string)
{
if (int res = mdb_dbi_open(txn, name, flags, &dbi)) {
printf("Error opening lmdb database. Error code: %d; and error: %s\n", res,
mdb_strerror(res));
throw std::runtime_error(error_string + ": " + std::to_string(res));
}
}
static bool need_resize(uint64_t threshold_size = 0);
void do_resize(uint64_t increase_size = 0);
bool TxnBegin(std::size_t required_size = 0);
bool TxnCommit();
bool TxnAbort();
// for tests
bool test1_WriteStrKeyVal(const std::string& key, const std::string& val);
bool test1_ReadStrKeyVal(const std::string& key, std::string& val);
bool test1_ExistsStrKeyVal(const std::string& key);
bool test1_EraseStrKeyVal(const std::string& key);
bool test2_ReadMultipleStr1KeyVal(const std::string& key, std::vector<string> &val);
bool test2_WriteStrKeyVal(const std::string& key, const std::string& val);
bool test2_ExistsStrKeyVal(const std::string& key);
bool test2_EraseStrKeyVal(const std::string& key);
bool ReadVersion(int& nVersion);
bool WriteVersion(int nVersion);
bool ReadTxIndex(uint256 hash, CTxIndex& txindex);
bool UpdateTxIndex(uint256 hash, const CTxIndex& txindex);
bool ReadTx(const CDiskTxPos& txPos, CTransaction& tx);
bool ReadNTP1Tx(uint256 hash, NTP1Transaction& ntp1tx);
bool WriteNTP1Tx(uint256 hash, const NTP1Transaction& ntp1tx);
bool ReadNTP1TxsWithTokenSymbol(const std::string& tokenName, std::vector<uint256>& txs);
bool WriteNTP1TxWithTokenSymbol(const std::string& tokenName, const NTP1Transaction& tx);
bool EraseTxIndex(const CTransaction& tx);
bool ContainsTx(uint256 hash);
bool ContainsNTP1Tx(uint256 hash);
bool ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex);
bool ReadDiskTx(uint256 hash, CTransaction& tx);
bool ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex);
bool ReadDiskTx(COutPoint outpoint, CTransaction& tx);
bool ReadBlock(uint256 hash, CBlock& blk, bool fReadTransactions = true);
bool WriteBlock(uint256 hash, const CBlock& blk);
bool WriteBlockIndex(const CDiskBlockIndex& blockindex);
bool ReadHashBestChain(uint256& hashBestChain);
bool WriteHashBestChain(uint256 hashBestChain);
bool ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust);
bool WriteBestInvalidTrust(CBigNum bnBestInvalidTrust);
bool ReadSyncCheckpoint(uint256& hashCheckpoint);
bool WriteSyncCheckpoint(uint256 hashCheckpoint);
bool ReadCheckpointPubKey(std::string& strPubKey);
bool WriteCheckpointPubKey(const std::string& strPubKey);
bool LoadBlockIndex();
void init_blockindex(bool fRemoveOld = false);
private:
bool LoadBlockIndexGuts();
inline void loadDbPointers();
inline void resetDbPointers();
static inline void resetGlobalDbPointers();
};
void CTxDB::loadDbPointers()
{
db_main = glob_db_main.get();
db_blockIndex = glob_db_blockIndex.get();
db_blocks = glob_db_blocks.get();
db_tx = glob_db_tx.get();
db_ntp1Tx = glob_db_ntp1Tx.get();
db_ntp1tokenNames = glob_db_ntp1tokenNames.get();
}
void CTxDB::resetDbPointers()
{
db_main = nullptr;
db_blockIndex = nullptr;
db_blocks = nullptr;
db_tx = nullptr;
db_ntp1Tx = nullptr;
db_ntp1tokenNames = nullptr;
}
void CTxDB::resetGlobalDbPointers()
{
glob_db_main.reset();
glob_db_blockIndex.reset();
glob_db_blocks.reset();
glob_db_tx.reset();
glob_db_ntp1Tx.reset();
glob_db_ntp1tokenNames.reset();
}
#endif // BITCOIN_LMDB_H
|
tahussle/bebbang | wallet/ntp1/ntp1tokenmetadata.h | <gh_stars>0
#ifndef NTP1TOKENMETADATA_H
#define NTP1TOKENMETADATA_H
#include "base58.h"
#include "json_spirit.h"
#include "ntp1tokenminimalmetadata.h"
#include "uint256.h"
#include <vector>
class NTP1TokenMetaData : public NTP1TokenMinimalMetaData
{
uint64_t numOfHolders;
uint64_t totalSupply;
uint64_t numOfTransfers;
uint64_t numOfIssuance;
uint64_t numOfBurns;
uint64_t firstBlock;
CBitcoinAddress issueAddress;
std::string tokenName;
std::string tokenDescription;
std::string tokenIssuer;
std::string iconURL;
std::string iconImageType;
json_spirit::Value userData;
json_spirit::Value urls;
public:
void setNull();
bool isNull() const;
void importRestfulAPIJsonData(const std::string& data);
void importRestfulAPIJsonData(const json_spirit::Value& data);
json_spirit::Value exportDatabaseJsonData(bool for_rpc = false) const;
void importDatabaseJsonData(const json_spirit::Value& data);
NTP1TokenMetaData();
uint64_t getNumOfHolders() const;
uint64_t getTotalSupply() const;
uint64_t getNumOfTransfers() const;
uint64_t getNumOfIssuance() const;
uint64_t getNumOfBurns() const;
uint64_t getFirstBlock() const;
const CBitcoinAddress& getIssueAddress() const;
const std::string& getTokenName() const;
const std::string& getTokenDescription() const;
const std::string& getTokenIssuer() const;
const std::string& getIconURL() const;
const std::string& getIconImageType() const;
friend inline bool operator==(const NTP1TokenMetaData& lhs, const NTP1TokenMetaData& rhs);
void setTokenName(const std::string& value);
};
bool operator==(const NTP1TokenMetaData& lhs, const NTP1TokenMetaData& rhs)
{
return (lhs.getTokenId() == rhs.getTokenId() && lhs.getIssuanceTxId() == rhs.getIssuanceTxId() &&
lhs.getDivisibility() == rhs.getDivisibility() &&
lhs.getLockStatus() == rhs.getLockStatus() &&
lhs.getAggregationPolicy() == rhs.getAggregationPolicy() &&
lhs.numOfHolders == rhs.numOfHolders && lhs.totalSupply == rhs.totalSupply &&
lhs.numOfTransfers == rhs.numOfTransfers && lhs.numOfIssuance == rhs.numOfIssuance &&
lhs.numOfBurns == rhs.numOfBurns && lhs.firstBlock == rhs.firstBlock &&
lhs.issueAddress == rhs.issueAddress && lhs.tokenName == rhs.tokenName &&
lhs.tokenDescription == rhs.tokenDescription && lhs.tokenIssuer == rhs.tokenIssuer &&
lhs.iconURL == rhs.iconURL && lhs.iconImageType == rhs.iconImageType);
}
#endif // NTP1TOKENMETADATA_H
|
tahussle/bebbang | wallet/ntp1/ntp1apicalls.h | <reponame>tahussle/bebbang
#ifndef NTP1APICALLS_H
#define NTP1APICALLS_H
#include "ntp1tokenmetadata.h"
#include "ntp1tools.h"
#include "ntp1transaction.h"
class NTP1APICalls
{
public:
NTP1APICalls();
static bool RetrieveData_AddressContainsNTP1Tokens(const std::string& address, bool testnet);
static uint64_t RetrieveData_TotalNeblsExcludingNTP1(const std::string& address, bool testnet);
static NTP1TokenMetaData RetrieveData_NTP1TokensMetaData(const std::string& tokenId,
const std::string& tx, int outputIndex,
bool testnet);
static const long NTP1_CONNECTION_TIMEOUT = 10;
static NTP1Transaction RetrieveData_TransactionInfo(const std::string& txHash, bool testnet);
static std::string RetrieveData_TransactionInfo_Str(const std::string& txHash, bool testnet);
};
#endif // NTP1APICALLS_H
|
tahussle/bebbang | wallet/ntp1/ntp1tools.h | <reponame>tahussle/bebbang
#ifndef NTP1TOOLS_H
#define NTP1TOOLS_H
#include "curltools.h"
#include "json/json_spirit.h"
class NTP1Tools
{
public:
NTP1Tools();
static const std::string NTPAPI_base_url_mainnet_local;
static const std::string NTPAPI_base_url_testnet_local;
static const std::string NTPAPI_base_url_mainnet_remote;
static const std::string NTPAPI_base_url_testnet_remote;
static const std::string NTPAPI_addressInfo;
static const std::string NTPAPI_transactionInfo;
static const std::string NTPAPI_tokenId;
static const std::string NTPAPI_tokenMetaData;
static const std::string NTPAPI_stakeHolders;
static const std::string NTPAPI_sendTokens;
static const std::string EXPLORER_base_url_mainnet;
static const std::string EXPLORER_base_url_testnet;
static const std::string EXPLORER_tokenInfo;
static const std::string EXPLORER_transactionInfo;
// json parsing methods
static std::string GetStrField(const json_spirit::Object& data, const std::string& fieldName);
static bool GetBoolField(const json_spirit::Object& data, const std::string& fieldName);
static uint64_t GetUint64Field(const json_spirit::Object& data, const std::string& fieldName);
static int64_t GetInt64Field(const json_spirit::Object& data, const std::string& fieldName);
static NTP1Int GetNTP1IntField(const json_spirit::Object& data, const std::string& fieldName);
static json_spirit::Array GetArrayField(const json_spirit::Object& data,
const std::string& fieldName);
static json_spirit::Object GetObjectField(const json_spirit::Object& data,
const std::string& fieldName);
// local string manipulation methods
static std::string GetURL_APIBase(bool testnet);
static std::string GetURL_AddressInfo(const std::string& address, bool testnet);
static std::string GetURL_TransactionInfo(const std::string& txHash, bool testnet);
static std::string GetURL_TokenID(const std::string& tokenSymbol, bool testnet);
static std::string GetURL_TokenMetaData(const std::string& tokenID, bool testnet);
static std::string GetURL_TokenUTXOMetaData(const std::string& tokenID, const std::string& txHash,
unsigned long outputIndex, bool testnet);
static std::string GetURL_StakeHolders(const std::string& tokenID, bool testnet);
static std::string GetURL_SendTokens(bool testnet);
static std::string GetURL_ExplorerBase(bool testnet);
static std::string GetURL_ExplorerTokenInfo(const std::string& tokenId, bool testnet);
static std::string GetURL_ExplorerTransactionInfo(const std::string& txId, bool testnet);
};
#endif // NTP1TOOLS_H
|
tahussle/bebbang | wallet/qt/ntp1senddialog.h | <reponame>tahussle/bebbang
#ifndef NTP1SENDDIALOG_H
#define NTP1SENDDIALOG_H
#include <QGridLayout>
#include <QGroupBox>
#include <QPushButton>
#include <QScrollArea>
#include <QVBoxLayout>
#include <QVector>
#include <QWidget>
#include "ntp1/ntp1sendtokensdata.h"
#include "ntp1/ntp1tokenlistmodel.h"
#include "ntp1sendtokensfeewidget.h"
class NTP1SendSingleTokenFields;
class NTP1TokenListModel;
class NTP1SendDialog Q_DECL_FINAL : public QWidget
{
Q_OBJECT
QGridLayout* mainLayout;
QPushButton* addRecipientButton;
QPushButton* sendButton;
QVBoxLayout* recipientWidgetsLayout;
QWidget* recipientWidgetsWidget;
QVector<NTP1SendSingleTokenFields*> recipientWidgets;
QScrollArea* recipientWidgetsScrollArea;
NTP1TokenListModel* tokenListDataModel;
NTP1SendTokensFeeWidget* feeWidget;
public:
explicit NTP1SendDialog(NTP1TokenListModel* tokenListModel, QWidget* parent = Q_NULLPTR);
~NTP1SendDialog();
void createWidgets();
boost::shared_ptr<NTP1Wallet> getLatestNTP1Wallet() const;
NTP1SendTokensData createTransactionData() const;
public slots:
void slot_addRecipientWidget();
void slot_removeRecipientWidget(QWidget* widget);
void slot_actToShowOrHideCloseButtons();
void slot_updateAllRecipientDialogsTokens();
void slot_sendClicked();
void resetAllFields();
protected:
void showAllCloseButtons();
void hideAllCloseButtons();
signals:
void signal_updateAllRecipientDialogsTokens();
};
#endif // NTP1SENDDIALOG_H
|
tahussle/bebbang | wallet/qt/ntp1/ntp1tokenlistfilterproxy.h | #ifndef NTP1TOKENLISTFILTERPROXY_H
#define NTP1TOKENLISTFILTERPROXY_H
#include <QSortFilterProxyModel>
#include <QLineEdit>
class NTP1TokenListFilterProxy : public QSortFilterProxyModel
{
QLineEdit* filterLineEdit;
public:
NTP1TokenListFilterProxy(QLineEdit *FilterLineEdit = NULL);
// QSortFilterProxyModel interface
protected:
bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const;
};
#endif // NTP1TOKENLISTFILTERPROXY_H
|
tahussle/bebbang | wallet/ntp1/ntp1tokenminimalmetadata.h | <reponame>tahussle/bebbang<gh_stars>0
#ifndef NTP1TOKENMINIMALMETADATA_H
#define NTP1TOKENMINIMALMETADATA_H
#include "uint256.h"
#include <string>
#include <vector>
class NTP1TokenMinimalMetaData
{
protected:
std::string tokenId;
uint256 issuanceTxId;
uint64_t divisibility;
bool lockStatus;
std::string aggregationPolicy;
public:
NTP1TokenMinimalMetaData();
void setNull();
void setTokenId(const std::string& Str);
void setIssuanceTxIdHex(const std::string& hex);
const std::string& getTokenId() const;
std::string getIssuanceTxIdHex() const;
uint64_t getDivisibility() const;
bool getLockStatus() const;
const std::string& getAggregationPolicy() const;
uint256 getIssuanceTxId() const;
friend inline bool operator==(const NTP1TokenMinimalMetaData& lhs,
const NTP1TokenMinimalMetaData& rhs);
};
bool operator==(const NTP1TokenMinimalMetaData& lhs, const NTP1TokenMinimalMetaData& rhs)
{
return (lhs.getTokenId() == rhs.getTokenId() && lhs.getIssuanceTxId() == rhs.getIssuanceTxId() &&
lhs.getDivisibility() == rhs.getDivisibility() &&
lhs.getLockStatus() == rhs.getLockStatus() &&
lhs.getAggregationPolicy() == rhs.getAggregationPolicy());
}
#endif // NTP1TOKENMINIMALMETADATA_H
|
tahussle/bebbang | wallet/qt/bitcoingui.h | #ifndef BITCOINGUI_H
#define BITCOINGUI_H
#include "ntp1summary.h"
#include <QLinearGradient>
#include <QMainWindow>
#include <QPainter>
#include <QProgressDialog>
#include <QStatusBar>
#include <QSystemTrayIcon>
#include <QToolBar>
#include "overviewpage.h"
#include <stdint.h>
#include "neblioupdatedialog.h"
#include "neblioupdater.h"
class TransactionTableModel;
class ClientModel;
class WalletModel;
class TransactionView;
class OverviewPage;
class AddressBookPage;
class SendCoinsDialog;
class SignVerifyMessageDialog;
class Notificator;
class RPCConsole;
QT_BEGIN_NAMESPACE
class QLabel;
class QLineEdit;
class QTableView;
class QAbstractItemModel;
class QModelIndex;
class QProgressBar;
class QStackedWidget;
class QUrl;
QT_END_NAMESPACE
/**
Bitcoin GUI main class. This class represents the main window of the Bitcoin UI. It communicates with
both the client and wallet models to give the user an up-to-date view of the current core state.
*/
class BitcoinGUI : public QMainWindow
{
Q_OBJECT
ClickableLabel* updaterLabel;
NeblioUpdater neblioUpdater;
NeblioReleaseInfo latestRelease;
boost::promise<bool> updateAvailablePromise;
boost::unique_future<bool> updateAvailableFuture;
QTimer* updateConcluderTimer;
int updateConcluderTimeout;
QTimer* updateCheckTimer;
int updateCheckTimerTimeout;
QTimer* animationStopperTimer;
int animationStopperTimerTimeout;
NeblioUpdateDialog* updateDialog;
bool isUpdateRunning; // since update check is asynchronous, this is true while checking is running
// The following are the images that can show up in the updater
QMovie* updaterSpinnerMovie;
QMovie* updaterCheckMovie;
QMovie* updaterUpdateExistsMovie;
QMovie* updaterErrorMovie;
void setupUpdateControls();
QTimer* backupCheckerTimer;
int backupCheckerTimerPeriod;
QTimer* backupBlinkerTimer;
int backupBlinkerTimerPeriod;
bool backupBlinkerOn;
public:
explicit BitcoinGUI(QWidget* parent = 0);
~BitcoinGUI();
/** Set the client model.
The client model represents the part of the core that communicates with the P2P network, and is
wallet-agnostic.
*/
void setClientModel(ClientModel* clientModel);
/** Set the wallet model.
The wallet model represents a bitcoin wallet, and offers access to the list of transactions,
address book and sending functionality.
*/
void setWalletModel(WalletModel* walletModel);
protected:
void changeEvent(QEvent* e);
void closeEvent(QCloseEvent* event);
void dragEnterEvent(QDragEnterEvent* event);
void dropEvent(QDropEvent* event);
private:
ClientModel* clientModel;
WalletModel* walletModel;
bool logoSwitched{false};
QStackedWidget* centralWidget;
OverviewPage* overviewPage;
NTP1Summary* ntp1SummaryPage;
QWidget* transactionsPage;
AddressBookPage* addressBookPage;
AddressBookPage* receiveCoinsPage;
SendCoinsDialog* sendCoinsPage;
SignVerifyMessageDialog* signVerifyMessageDialog;
QLabel* labelEncryptionIcon;
QLabel* labelStakingIcon;
QLabel* labelConnectionsIcon;
QLabel* labelBlocksIcon;
QLabel* labelBackupAlertIcon;
QLabel* progressBarLabel;
QProgressBar* progressBar;
QProgressDialog* blockchainExporterProg;
QMenuBar* appMenuBar;
QAction* overviewAction;
QAction* ntp1tokensAction;
QAction* historyAction;
QAction* quitAction;
QAction* sendCoinsAction;
QAction* addressBookAction;
QAction* signMessageAction;
QAction* verifyMessageAction;
QAction* exportBlockchainBootstrapAction;
QAction* aboutAction;
QAction* receiveCoinsAction;
QAction* optionsAction;
QAction* toggleHideAction;
QAction* exportAction;
QAction* encryptWalletAction;
QAction* backupWalletAction;
QAction* importWalletAction;
QAction* changePassphraseAction;
QAction* unlockWalletAction;
QAction* lockWalletAction;
QAction* aboutQtAction;
QAction* openRPCConsoleAction;
QSystemTrayIcon* trayIcon;
Notificator* notificator;
TransactionView* transactionView;
RPCConsole* rpcConsole;
QMovie* syncIconMovie;
QToolBar* toolbar;
uint64_t nWeight;
/** Create the main UI actions. */
void createActions();
/** Create the menu bar and sub-menus. */
void createMenuBar();
/** Create the toolbars */
void createToolBars();
/** Create system tray icon and notification */
void createTrayIcon();
/** Create system tray menu (or setup the dock menu) */
void createTrayIconMenu();
void paintEvent(QPaintEvent*)
{
QPainter painter(this);
// paint the upper bar with blue gradient
if (toolbar != NULL) {
painter.setRenderHint(QPainter::Antialiasing);
painter.setBrush(QBrush(QColor(0, 0, 255)));
QRect rect(0, toolbar->pos().y(), this->size().width(), toolbar->height());
QLinearGradient gradient(rect.topLeft(),
rect.topRight()); // diagonal gradient from top-left to bottom-right
gradient.setColorAt(0, QColor(86, 167, 225));
gradient.setColorAt(1, QColor(96, 98, 173));
painter.fillRect(rect, gradient);
}
painter.setRenderHint(QPainter::Antialiasing);
painter.setBrush(QBrush(QColor(65, 65, 65)));
if (overviewPage == NULL)
return;
// This draws the bottom gray bar after calculating its position
if (overviewAction->isChecked()) {
painter.drawRect(0,
overviewPage->ui->bottom_bar_widget
->mapTo(overviewPage->ui->bottom_bar_widget->window(), QPoint(0, 0))
.y(),
this->size().width(), overviewPage->ui->bottom_bar_widget->height());
}
if (ntp1tokensAction->isChecked()) {
painter.drawRect(0,
ntp1SummaryPage->ui->bottom_bar_widget
->mapTo(ntp1SummaryPage->ui->bottom_bar_widget->window(), QPoint(0, 0))
.y(),
this->size().width(), ntp1SummaryPage->ui->bottom_bar_widget->height());
}
}
public slots:
/** Set number of connections shown in the UI */
void setNumConnections(int count);
/** Set number of blocks shown in the UI */
void setNumBlocks(int count, int nTotalBlocks);
/** Set the encryption status as shown in the UI.
@param[in] status current encryption status
@see WalletModel::EncryptionStatus
*/
void setEncryptionStatus(int status);
/** Notify the user of an error in the network or transaction handling code. */
void error(const QString& title, const QString& message, bool modal);
/** Asks the user whether to pay the transaction fee or to cancel the transaction.
It is currently not possible to pass a return value to another thread through
BlockingQueuedConnection, so an indirected pointer is used.
https://bugreports.qt-project.org/browse/QTBUG-10440
@param[in] nFeeRequired the required fee
@param[out] payFee true to pay the fee, false to not pay the fee
*/
void askFee(qint64 nFeeRequired, bool* payFee);
void handleURI(QString strURI);
private slots:
/** Switch to overview (home) page */
void gotoOverviewPage();
/** Switch to NTP1 tokens summary page */
void gotoNTP1SummaryPage();
/** Switch to history (transactions) page */
void gotoHistoryPage();
/** Switch to address book page */
void gotoAddressBookPage();
/** Switch to receive coins page */
void gotoReceiveCoinsPage();
/** Switch to send coins page */
void gotoSendCoinsPage();
/** Show Sign/Verify Message dialog and switch to sign message tab */
void gotoSignMessageTab(QString addr = "");
/** Show Sign/Verify Message dialog and switch to verify message tab */
void gotoVerifyMessageTab(QString addr = "");
void exportBlockchainBootstrap();
/** Show configuration dialog */
void optionsClicked();
/** Show about dialog */
void aboutClicked();
#ifndef Q_OS_MAC
/** Handle tray icon clicked */
void trayIconActivated(QSystemTrayIcon::ActivationReason reason);
#endif
/** Show incoming transaction notification for new transactions.
The new items are those between start and end inclusive, under the given parent item.
*/
void incomingTransaction(const QModelIndex& parent, int start, int end);
/** Encrypt the wallet */
void encryptWallet(bool status);
/** Backup the wallet */
void backupWallet();
/** Import a wallet */
void importWallet();
/** Change encrypted wallet passphrase */
void changePassphrase();
/** Ask for passphrase to unlock wallet temporarily */
void unlockWallet();
void lockWallet();
/** Show window if hidden, unminimize when minimized, rise when obscured or show if hidden and
* fToggleHidden is true */
void showNormalIfMinimized(bool fToggleHidden = false);
/** simply calls showNormalIfMinimized(true) for use in SLOT() macro */
void toggleHidden();
void updateWeight();
void updateStakingIcon();
// Stop the animation after playing once
void updateCheckAnimation_frameChanged(int frameNumber);
// This function calls the update check asynchronously
void checkForNeblioUpdates();
// Called periodically to asynchronously check if the update process is finished
void finishCheckForNeblioUpdates();
void stopAnimations();
void checkWhetherBackupIsMade();
void startBackupAlertBlinker();
void stopBackupAlertBlinker();
void blinkBackupAlertIcon();
};
#endif
|
tahussle/bebbang | wallet/qt/ui_overviewpage.h | <filename>wallet/qt/ui_overviewpage.h
/********************************************************************************
** Form generated from reading UI file 'overviewpage.ui'
**
** Created by: Qt User Interface Compiler version 5.7.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_OVERVIEWPAGE_H
#define UI_OVERVIEWPAGE_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QFrame>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QListView>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
#include <QMovie>
#include "ClickableLabel.h"
QT_BEGIN_NAMESPACE
class Ui_OverviewPage
{
public:
QPixmap left_logo_pix;
QPixmap left_logo_tachyon_pix;
QGridLayout *main_layout;
QVBoxLayout *left_logo_layout;
QLabel *left_logo_label;
QVBoxLayout *logo_layout;
QVBoxLayout *right_balance_layout;
QFrame *wallet_contents_frame;
QVBoxLayout *verticalLayout;
QHBoxLayout *horizontalLayout_2;
QLabel *recent_tx_label;
QLabel *labelTransactionsStatus;
QListView *listTransactions;
QLabel *labelWalletStatus;
QLabel *wallet_label;
QGridLayout *balance_layout;
QLabel *spendable_title_label;
QLabel *spendable_value_label;
QLabel *stake_title_label;
QLabel *stake_value_label;
QLabel *unconfirmed_title_label;
QLabel *unconfirmed_value_label;
QLabel *immature_title_label;
QLabel *immature_value_label;
QLabel *labelTotalText;
QLabel *total_value_label;
QWidget *bottom_bar_widget;
QLabel *bottom_bar_logo_label;
QGridLayout *bottom_layout;
QPixmap bottom_logo_pix;
int bottom_bar_downscale_factor;
void setupUi(QWidget *OverviewPage)
{
if (OverviewPage->objectName().isEmpty())
OverviewPage->setObjectName(QStringLiteral("OverviewPage"));
OverviewPage->resize(761, 452);
main_layout = new QGridLayout(OverviewPage);
main_layout->setObjectName(QStringLiteral("horizontalLayout"));
left_logo_layout = new QVBoxLayout();
left_logo_layout->setObjectName(QStringLiteral("verticalLayout_2"));
left_logo_label = new QLabel(OverviewPage);
left_logo_label->setObjectName(QStringLiteral("frame"));
// logo_label->setFrameShadow(QFrame::Raised);
left_logo_label->setLineWidth(0);
// logo_label->setFrameStyle(QFrame::StyledPanel);
left_logo_pix = QPixmap(":images/neblio_vertical");
left_logo_pix = left_logo_pix.scaledToHeight(OverviewPage->height()*3./4., Qt::SmoothTransformation);
left_logo_tachyon_pix = QPixmap(":images/logo_left_tachyon");
left_logo_tachyon_pix = left_logo_tachyon_pix.scaledToHeight(OverviewPage->height()*3./4., Qt::SmoothTransformation);
left_logo_label->setPixmap(left_logo_pix);
left_logo_label->setAlignment(Qt::AlignCenter);
logo_layout = new QVBoxLayout(left_logo_label);
logo_layout->setObjectName(QStringLiteral("verticalLayout_4"));
left_logo_layout->addWidget(left_logo_label);
main_layout->addLayout(left_logo_layout, 0, 0, 1, 1);
bottom_logo_pix = QPixmap(":images/neblio_horizontal");
bottom_bar_widget = new QWidget(OverviewPage);
bottom_layout = new QGridLayout(bottom_bar_widget);
bottom_bar_logo_label = new QLabel(bottom_bar_widget);
bottom_bar_downscale_factor = 8;
main_layout->addWidget(bottom_bar_widget, 1, 0, 1, 2);
bottom_bar_widget->setLayout(bottom_layout);
bottom_layout->addWidget(bottom_bar_logo_label, 0, 0, 1, 1);
bottom_logo_pix = bottom_logo_pix.scaledToHeight(OverviewPage->height()/bottom_bar_downscale_factor, Qt::SmoothTransformation);
bottom_bar_logo_label->setPixmap(bottom_logo_pix);
bottom_bar_logo_label->setAlignment(Qt::AlignRight);
right_balance_layout = new QVBoxLayout();
right_balance_layout->setObjectName(QStringLiteral("verticalLayout_3"));
wallet_contents_frame = new QFrame(OverviewPage);
wallet_contents_frame->setObjectName(QStringLiteral("frame_2"));
wallet_contents_frame->setFrameShape(QFrame::StyledPanel);
// wallet_contents_frame->setFrameShadow(QFrame::Raised);
verticalLayout = new QVBoxLayout(wallet_contents_frame);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2"));
recent_tx_label = new QLabel(wallet_contents_frame);
recent_tx_label->setObjectName(QStringLiteral("label_4"));
horizontalLayout_2->addWidget(recent_tx_label);
labelTransactionsStatus = new QLabel(wallet_contents_frame);
labelTransactionsStatus->setObjectName(QStringLiteral("labelTransactionsStatus"));
labelTransactionsStatus->setStyleSheet(QStringLiteral("QLabel { color: red; }"));
labelTransactionsStatus->setText(QStringLiteral("(out of sync)"));
labelTransactionsStatus->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
horizontalLayout_2->addWidget(labelTransactionsStatus);
verticalLayout->addLayout(horizontalLayout_2);
listTransactions = new QListView(wallet_contents_frame);
listTransactions->setObjectName(QStringLiteral("listTransactions"));
listTransactions->setStyleSheet(QStringLiteral("QListView { background: transparent; }"));
listTransactions->setFrameShape(QFrame::NoFrame);
listTransactions->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
listTransactions->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
listTransactions->setSelectionMode(QAbstractItemView::NoSelection);
verticalLayout->addWidget(listTransactions);
labelWalletStatus = new QLabel(wallet_contents_frame);
labelWalletStatus->setObjectName(QStringLiteral("labelWalletStatus"));
labelWalletStatus->setStyleSheet(QStringLiteral("QLabel { color: red; }"));
labelWalletStatus->setText(QStringLiteral("(out of sync)"));
labelWalletStatus->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter);
verticalLayout->addWidget(labelWalletStatus);
wallet_label = new QLabel(wallet_contents_frame);
wallet_label->setObjectName(QStringLiteral("label_5"));
QFont font;
font.setPointSize(11);
font.setBold(true);
font.setWeight(75);
wallet_label->setFont(font);
verticalLayout->addWidget(wallet_label);
balance_layout = new QGridLayout();
balance_layout->setObjectName(QStringLiteral("formLayout_2"));
// balance_layout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
// balance_layout->setHorizontalSpacing(12);
// balance_layout->setVerticalSpacing(12);
spendable_title_label = new QLabel(wallet_contents_frame);
spendable_title_label->setObjectName(QStringLiteral("label"));
QFont font1;
// font1.setPointSize(10);
spendable_title_label->setFont(font1);
balance_layout->addWidget(spendable_title_label, 0, 0);
spendable_value_label = new QLabel(wallet_contents_frame);
spendable_value_label->setObjectName(QStringLiteral("labelBalance"));
QFont font2;
font2.setPointSize(10);
font2.setBold(true);
font2.setWeight(75);
spendable_value_label->setFont(font2);
spendable_value_label->setCursor(QCursor(Qt::IBeamCursor));
spendable_value_label->setText(QStringLiteral("0 NEBL"));
spendable_value_label->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
balance_layout->addWidget(spendable_value_label, 0, 1);
stake_title_label = new QLabel(wallet_contents_frame);
stake_title_label->setObjectName(QStringLiteral("label_6"));
stake_title_label->setFont(font1);
balance_layout->addWidget(stake_title_label, 1, 0);
stake_value_label = new QLabel(wallet_contents_frame);
stake_value_label->setObjectName(QStringLiteral("labelStake"));
stake_value_label->setFont(font2);
stake_value_label->setCursor(QCursor(Qt::IBeamCursor));
stake_value_label->setText(QStringLiteral("0 NEBL"));
stake_value_label->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
balance_layout->addWidget(stake_value_label, 1, 1);
unconfirmed_title_label = new QLabel(wallet_contents_frame);
unconfirmed_title_label->setObjectName(QStringLiteral("label_3"));
unconfirmed_title_label->setFont(font1);
balance_layout->addWidget(unconfirmed_title_label, 2, 0);
unconfirmed_value_label = new QLabel(wallet_contents_frame);
unconfirmed_value_label->setObjectName(QStringLiteral("labelUnconfirmed"));
unconfirmed_value_label->setFont(font2);
unconfirmed_value_label->setCursor(QCursor(Qt::IBeamCursor));
unconfirmed_value_label->setText(QStringLiteral("0 NEBL"));
unconfirmed_value_label->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
balance_layout->addWidget(unconfirmed_value_label, 2, 1);
immature_title_label = new QLabel(wallet_contents_frame);
immature_title_label->setObjectName(QStringLiteral("labelImmatureText"));
immature_title_label->setFont(font1);
balance_layout->addWidget(immature_title_label, 3, 0);
immature_value_label = new QLabel(wallet_contents_frame);
immature_value_label->setObjectName(QStringLiteral("labelImmature"));
immature_value_label->setFont(font2);
immature_value_label->setText(QStringLiteral("0 NEBL"));
immature_value_label->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
balance_layout->addWidget(immature_value_label, 3, 1);
verticalLayout->addLayout(balance_layout);
labelTotalText = new QLabel(wallet_contents_frame);
labelTotalText->setObjectName(QStringLiteral("labelTotalText"));
QFont font3;
font3.setFamily(QStringLiteral("Arial"));
font3.setPointSize(16);
labelTotalText->setFont(font3);
verticalLayout->addWidget(labelTotalText);
total_value_label = new QLabel(wallet_contents_frame);
total_value_label->setObjectName(QStringLiteral("labelTotal"));
QFont font4;
font4.setFamily(QStringLiteral("Arial"));
font4.setPointSize(16);
font4.setBold(true);
font4.setWeight(75);
total_value_label->setFont(font4);
total_value_label->setCursor(QCursor(Qt::IBeamCursor));
total_value_label->setText(QStringLiteral("0 BTC"));
total_value_label->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
verticalLayout->addWidget(total_value_label);
right_balance_layout->addWidget(wallet_contents_frame);
main_layout->addLayout(right_balance_layout, 0, 1, 1, 1);
retranslateUi(OverviewPage);
QMetaObject::connectSlotsByName(OverviewPage);
} // setupUi
void retranslateUi(QWidget *OverviewPage)
{
OverviewPage->setWindowTitle(QApplication::translate("OverviewPage", "Form", Q_NULLPTR));
recent_tx_label->setText(QApplication::translate("OverviewPage", "<b>Recent transactions</b>", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
labelTransactionsStatus->setToolTip(QApplication::translate("OverviewPage", "The displayed information may be out of date. Your wallet automatically synchronizes with the neblio network after a connection is established, but this process has not completed yet.", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
#ifndef QT_NO_TOOLTIP
labelWalletStatus->setToolTip(QApplication::translate("OverviewPage", "The displayed information may be out of date. Your wallet automatically synchronizes with the neblio network after a connection is established, but this process has not completed yet.", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
wallet_label->setText(QApplication::translate("OverviewPage", "Wallet", Q_NULLPTR));
spendable_title_label->setText(QApplication::translate("OverviewPage", "Spendable:", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
spendable_value_label->setToolTip(QApplication::translate("OverviewPage", "Your current spendable balance", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
stake_title_label->setText(QApplication::translate("OverviewPage", "Stake:", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
stake_value_label->setToolTip(QApplication::translate("OverviewPage", "Total number of tokens that were staked, and do not yet count toward the current balance", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
unconfirmed_title_label->setText(QApplication::translate("OverviewPage", "Unconfirmed:", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
unconfirmed_value_label->setToolTip(QApplication::translate("OverviewPage", "Total of transactions that have yet to be confirmed, and do not yet count toward the current balance", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
immature_title_label->setText(QApplication::translate("OverviewPage", "Immature:", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
immature_value_label->setToolTip(QApplication::translate("OverviewPage", "Mined balance that has not yet matured", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
labelTotalText->setText(QApplication::translate("OverviewPage", "Total:", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
total_value_label->setToolTip(QApplication::translate("OverviewPage", "Your current total balance", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
} // retranslateUi
};
namespace Ui {
class OverviewPage: public Ui_OverviewPage {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_OVERVIEWPAGE_H
|
tahussle/bebbang | wallet/NetworkForks.h | <gh_stars>0
#ifndef NETWORKFORKS_H
#define NETWORKFORKS_H
#include "init.h"
#include <map>
enum NetworkFork : uint16_t
{
NETFORK__1_FIRST_ONE = 0,
NETFORK__2_CONFS_CHANGE,
NETFORK__3_TACHYON
};
class NetworkForks
{
std::map<NetworkFork, int> forksToBlockMap;
std::map<int, NetworkFork> blockToForksMap;
const boost::atomic<int>& bestHeight_internal;
public:
NetworkForks(const std::map<NetworkFork, int>& ForksToBlocks,
const boost::atomic<int>& BestHeightVar);
bool isForkActivated(NetworkFork fork) const;
NetworkFork getForkAtBlockNumber(int blockNumber) const;
int getFirstBlockOfFork(NetworkFork fork) const;
};
const NetworkForks
MainnetForks(std::map<NetworkFork, int>{{NetworkFork::NETFORK__1_FIRST_ONE, 0},
// number of stake confirmations changed to 10
{NetworkFork::NETFORK__2_CONFS_CHANGE, 248000},
// Tachyon upgrade. Approx Jan 12th 2019
{NetworkFork::NETFORK__3_TACHYON, 387028}},
nBestHeight);
const NetworkForks TestnetForks(std::map<NetworkFork, int>{{NetworkFork::NETFORK__1_FIRST_ONE, 0},
{NetworkFork::NETFORK__2_CONFS_CHANGE,
std::numeric_limits<int>::max()},
// Roughly Aug 1 2018 Noon EDT
{NetworkFork::NETFORK__3_TACHYON, 110100}},
nBestHeight);
const NetworkForks& GetNetForks();
#endif // NETWORKFORKS_H
|
tahussle/bebbang | wallet/curltools.h | #ifndef CURLTOOLS_H
#define CURLTOOLS_H
#include "util.h"
#include <atomic>
#include <boost/filesystem/fstream.hpp>
#include <curl/curl.h>
class cURLTools
{
public:
static size_t CurlWrite_CallbackFunc_StdString(void* contents, size_t size, size_t nmemb,
std::deque<char>* s);
static size_t CurlRead_CallbackFunc_StdString(void* dest, size_t size, size_t nmemb, void* userp);
static int CurlProgress_CallbackFunc(void*, double TotalToDownload, double NowDownloaded,
double /*TotalToUpload*/, double /*NowUploaded*/);
static void CurlGlobalInit_ThreadSafe();
static std::string GetFileFromHTTPS(const std::string& URL, long ConnectionTimeout,
bool IncludeProgressBar);
static std::string PostJsonToHTTPS(const std::string& URL, long ConnectionTimeout,
const std::string& data, bool chunked);
static void GetLargeFileFromHTTPS(const std::string& URL, long ConnectionTimeout,
const boost::filesystem::path& targetPath,
std::atomic<float>& progress);
static int CurlAtomicProgress_CallbackFunc(void* number, double TotalToDownload,
double NowDownloaded, double, double);
static size_t CurlWrite_CallbackFunc_File(void* contents, size_t size, size_t nmemb,
boost::filesystem::fstream* fs);
};
#endif // CURLTOOLS_H
|
tahussle/bebbang | wallet/init.h | // Copyright (c) 2009-2010 <NAME>
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_INIT_H
#define BITCOIN_INIT_H
#include "boost/atomic.hpp"
#include "wallet.h"
#include <memory>
extern std::shared_ptr<CWallet> pwalletMain;
extern boost::atomic<bool> appInitiated;
void StartShutdown();
void Shutdown(void* parg);
bool AppInit2();
std::string HelpMessage();
// option to rescan the wallet
extern std::string SC_SCHEDULE_ON_RESTART_OPNAME__RESCAN;
#endif
|
tahussle/bebbang | wallet/ntp1/ntp1sendtokensdata.h | <gh_stars>0
#ifndef NTP1SENDTOKENSDATA_H
#define NTP1SENDTOKENSDATA_H
#include "ntp1/ntp1wallet.h"
#include "ntp1sendtokensonerecipientdata.h"
#include <deque>
#include <string>
/**
* This class is used for a systematic construction of NTP1 transactions. Follow the steps:
* 1. Add recipients
* 2. Call calculateSources() to calculate the spending addresses of NTP1 tokens
*
* @brief The NTP1SendTokensData class
*/
class NTP1SendTokensData
{
std::deque<NTP1SendTokensOneRecipientData> recipients;
std::deque<std::string> tokenSourceAddresses;
int64_t fee;
public:
NTP1SendTokensData();
void addRecipient(const NTP1SendTokensOneRecipientData& data);
void addTokenSourceAddress(const std::string& tokenSourceAddress);
void calculateSources(boost::shared_ptr<NTP1Wallet> wallet, bool recalculateFee);
void setFee(uint64_t Fee);
json_spirit::Value exportJsonData() const;
std::string exportToAPIFormat() const;
// returns the total balance in the selected addresses (tokenSourceAddresses)
int64_t __addAddressesThatCoverFees();
static int64_t EstimateTxSizeInBytes(int64_t num_of_inputs, int64_t num_of_outputs);
static int64_t EstimateTxFee(int64_t num_of_inputs, int64_t num_of_outputs);
};
#endif // NTP1SENDTOKENSDATA_H
|
tahussle/bebbang | wallet/ThreadSafeMap.h | <filename>wallet/ThreadSafeMap.h
#ifndef THREADSAFEMAP_H
#define THREADSAFEMAP_H
#include <boost/thread.hpp>
#include <map>
template <typename K, typename V>
class ThreadSafeMap
{
std::map<K, V> theMap;
mutable boost::shared_mutex mtx;
public:
using MapType = std::map<K, V>;
ThreadSafeMap();
ThreadSafeMap(const std::map<K, V>& rhs);
ThreadSafeMap(const ThreadSafeMap<K, V>& rhs);
ThreadSafeMap<K, V>& operator=(const ThreadSafeMap<K, V>& rhs);
std::size_t erase(const K& key);
void set(const K& key, const V& value);
bool exists(const K& key) const;
std::size_t size() const;
bool empty() const;
template <typename K_, typename V_>
friend bool operator==(const ThreadSafeMap<K_, V_>& lhs, const ThreadSafeMap<K_, V_>& rhs);
bool get(const K& key, V& value) const;
void clear();
std::map<K, V> getInternalMap() const;
void setInternalMap(const std::map<K, V>& TheMap);
};
template <typename K, typename V>
ThreadSafeMap<K, V>::ThreadSafeMap(const ThreadSafeMap<K, V>& rhs)
{
boost::unique_lock<boost::shared_mutex> lock1(mtx);
boost::shared_lock<boost::shared_mutex> lock2(rhs.mtx);
this->theMap = rhs.theMap;
}
template <typename K, typename V>
ThreadSafeMap<K, V>& ThreadSafeMap<K, V>::
operator=(const ThreadSafeMap<K, V>& rhs)
{
boost::unique_lock<boost::shared_mutex> lock1(mtx);
boost::shared_lock<boost::shared_mutex> lock2(rhs.mtx);
this->theMap = rhs.theMap;
return *this;
}
template <typename K_, typename V_>
bool operator==(const ThreadSafeMap<K_, V_>& lhs, const ThreadSafeMap<K_, V_>& rhs)
{
if (&lhs == &rhs) {
return true;
}
boost::shared_lock<boost::shared_mutex> lock1(lhs.mtx);
boost::shared_lock<boost::shared_mutex> lock2(rhs.mtx);
return (lhs.theMap == rhs.theMap);
}
template <typename K, typename V>
void ThreadSafeMap<K, V>::set(const K& key, const V& value)
{
boost::unique_lock<boost::shared_mutex> lock(mtx);
theMap[key] = value;
}
template <typename K, typename V>
bool ThreadSafeMap<K, V>::get(const K& key, V& value) const
{
boost::shared_lock<boost::shared_mutex> lock(mtx);
typename std::map<K, V>::const_iterator it = theMap.find(key);
if (it == theMap.cend()) {
return false;
} else {
value = it->second;
return true;
}
}
template <typename K, typename V>
void ThreadSafeMap<K, V>::clear()
{
boost::unique_lock<boost::shared_mutex> lock(mtx);
theMap.clear();
}
template <typename K, typename V>
bool ThreadSafeMap<K, V>::exists(const K& key) const
{
boost::shared_lock<boost::shared_mutex> lock(mtx);
return (theMap.find(key) != theMap.end());
}
template <typename K, typename V>
std::size_t ThreadSafeMap<K, V>::size() const
{
boost::shared_lock<boost::shared_mutex> lock(mtx);
return theMap.size();
}
template <typename K, typename V>
bool ThreadSafeMap<K, V>::empty() const
{
boost::shared_lock<boost::shared_mutex> lock(mtx);
return theMap.empty();
}
template <typename K, typename V>
ThreadSafeMap<K, V>::ThreadSafeMap()
{
}
template <typename K, typename V>
ThreadSafeMap<K, V>::ThreadSafeMap(const std::map<K, V>& rhs)
{
boost::unique_lock<boost::shared_mutex> lock(mtx);
theMap = rhs;
}
template <typename K, typename V>
std::size_t ThreadSafeMap<K, V>::erase(const K& key)
{
boost::unique_lock<boost::shared_mutex> lock(mtx);
return theMap.erase(key);
}
template <typename K, typename V>
std::map<K, V> ThreadSafeMap<K, V>::getInternalMap() const
{
boost::unique_lock<boost::shared_mutex> lock(mtx);
std::map<K, V> safeCopy = theMap;
return safeCopy;
}
template <typename K, typename V>
void ThreadSafeMap<K, V>::setInternalMap(const std::map<K, V>& TheMap)
{
boost::unique_lock<boost::shared_mutex> lock(mtx);
theMap = TheMap;
}
#endif // THREADSAFEMAP_H
|
kamval/RN2483 | Software/RN2483_LoRAWAN_v1.30.X/mcc_generated_files/i2c1_driver.h | /*
(c) 2016 Microchip Technology Inc. and its subsidiaries. You may use this
software and any derivatives exclusively with Microchip products.
THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
PARTICULAR PURPOSE, OR ITS INTERACTION WITH MICROCHIP PRODUCTS, COMBINATION
WITH ANY OTHER PRODUCTS, OR USE IN ANY APPLICATION.
IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE
TERMS.
*/
#ifndef I2C1_DRIVER_H
#define I2C1_DRIVER_H
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#define INLINE inline
typedef void (*interruptHandler)(void);
/* arbitration interface */
INLINE void i2c1_driver_close(void);
/* Interrupt interfaces */
INLINE void mssp1_enableIRQ(void);
INLINE __bit mssp1_IRQisEnabled(void);
INLINE void mssp1_disableIRQ(void);
INLINE void mssp1_clearIRQ(void);
INLINE void mssp1_setIRQ(void);
INLINE __bit mssp1_IRQisSet(void);
INLINE void mssp1_waitForEvent(uint16_t*);
/* I2C interfaces */
__bit i2c1_driver_open(void);
INLINE char i2c1_driver_getRXData(void);
INLINE char i2c1_driver_getAddr(void);
INLINE void i2c1_driver_setAddr(char addr);
INLINE void i2c1_driver_setMask(char mask);
INLINE void i2c1_driver_TXData(char d);
INLINE void i2c1_driver_resetBus(void);
INLINE void i2c1_driver_start(void);
INLINE void i2c1_driver_restart(void);
INLINE void i2c1_driver_stop(void);
INLINE __bit i2c1_driver_isNACK(void);
INLINE void i2c1_driver_startRX(void);
INLINE void i2c1_driver_sendACK(void);
INLINE void i2c1_driver_sendNACK(void);
INLINE void i2c1_driver_clearBusCollision(void);
__bit i2c1_driver_initSlaveHardware(void);
INLINE void i2c1_driver_releaseClock(void);
INLINE __bit i2c1_driver_isBufferFull(void);
INLINE __bit i2c1_driver_isStart(void);
INLINE __bit i2c1_driver_isStop(void);
INLINE __bit i2c1_driver_isAddress(void);
INLINE __bit i2c1_driver_isData(void);
INLINE __bit i2c1_driver_isRead(void);
INLINE __bit i2c1_driver_isWriteCollision(void);
INLINE __bit i2c1_driver_isReceiveOverflow(void);
INLINE void i2c1_driver_setBusCollisionISR(interruptHandler handler);
INLINE void i2c1_driver_setI2cISR(interruptHandler handler);
void (*i2c1_driver_busCollisionISR)(void);
void (*i2c1_driver_i2cISR)(void);
#endif // I2C1_DRIVER_H
|
kamval/RN2483 | Software/RN2483_LoRAWAN_v1.10.X/mcc_generated_files/LoRaWAN/lorawan_eu.c | <filename>Software/RN2483_LoRAWAN_v1.10.X/mcc_generated_files/LoRaWAN/lorawan_eu.c
/********************************************************************
* Copyright (C) 2016 Microchip Technology Inc. and its subsidiaries
* (Microchip). All rights reserved.
*
* You are permitted to use the software and its derivatives with Microchip
* products. See the license agreement accompanying this software, if any, for
* more info about your rights and obligations.
*
* SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF
* MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR
* PURPOSE. IN NO EVENT SHALL MICROCHIP, SMSC, OR ITS LICENSORS BE LIABLE OR
* OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH
* OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY FOR ANY DIRECT OR INDIRECT
* DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR OTHER SIMILAR COSTS. To the fullest
* extend allowed by law, Microchip and its licensors liability will not exceed
* the amount of fees, if any, that you paid directly to Microchip to use this
* software.
*************************************************************************
*
* lorawan_eu.c
*
* LoRaWAN EU file
*
******************************************************************************/
/****************************** INCLUDES **************************************/
#include <math.h>
#include <stdbool.h>
#include "lorawan.h"
#include "lorawan_aes.h"
#include "lorawan_aes_cmac.h"
#include "lorawan_private.h"
#include "lorawan_defs.h"
#include "AES.h"
#include "radio_interface.h"
#include "sw_timer.h"
#include "lorawan_eu.h"
/****************************** VARIABLES *************************************/
const uint8_t rxWindowSize[] = {8, 10, 14, 26, 49, 88, 60, 8};
// Max Payload Size
const uint8_t maxPayloadSize[8] = {51, 51, 51, 115, 242, 242, 242, 56}; // for FSK max message size should be 64 bytes
// Channels by ism band
ChannelParams_t Channels[MAX_EU_SINGLE_BAND_CHANNELS];
static const int8_t rxWindowOffset[] = {-33, -50, -58, -62, -66, -68, -15, -2};
// Tx power possibilities by ism band
static const int8_t txPower868[] = {20, 14, 11, 8, 5, 2};
static const int8_t txPower433[] = {10, 7, 4, 1, -2, -5};
// Spreading factor possibilities
static const uint8_t spreadingFactor[] = {12, 11, 10, 9, 8, 7, 7};
// Bandwidth possibilities
static const uint8_t bandwidth[] = {BW_125KHZ, BW_125KHZ, BW_125KHZ, BW_125KHZ, BW_125KHZ, BW_125KHZ, BW_250KHZ};
// Modulation possibilities
static const uint8_t modulation[] = {MODULATION_LORA, MODULATION_LORA, MODULATION_LORA, MODULATION_LORA, MODULATION_LORA, MODULATION_LORA, MODULATION_LORA, MODULATION_FSK};
static const ChannelParams_t DefaultChannels868[] = {
LC0_868,
LC1_868,
LC2_868,
};
static const ChannelParams_t DefaultChannels433[] = {
LC0_433,
LC1_433,
LC2_433,
};
static const uint8_t FskSyncWordBuff[3] = {0xC1, 0x94, 0xC1};
/************************ PRIVATE FUNCTION PROTOTYPES *************************/
static void CreateAllSoftwareTimers (void);
static void SetCallbackSoftwareTimers (void);
static void StopAllSoftwareTimers (void);
static void InitDefault868Channels (void);
static void InitDefault433Channels (void);
static void UpdateDataRange (uint8_t channelId, uint8_t dataRangeNew);
static void UpdateChannelIdStatus (uint8_t channelId, bool statusNew);
static LorawanError_t ValidateRxOffset (uint8_t rxOffset);
static LorawanError_t ValidateFrequency (uint32_t frequencyNew);
static LorawanError_t ValidateDataRange (uint8_t dataRangeNew);
static LorawanError_t ValidateChannelId (uint8_t channelId, bool allowedForDefaultChannels);
static LorawanError_t ValidateChannelMaskCntl (uint8_t channelMaskCntl);
static void EnableChannels (uint16_t channelMask, uint8_t channelMaskCntl);
static void UpdateFrequency (uint8_t channelId, uint32_t frequencyNew );
static void UpdateDutyCycle (uint8_t channelId, uint16_t dutyCycleNew);
static LorawanError_t ValidateChannelMask (uint16_t channelMask);
static void EnableChannels1 (uint16_t channelMask, uint8_t channelMaskCntl, uint8_t channelIndexMin, uint8_t channelIndexMax);
static void DutyCycleCallback (uint8_t param);
static void ConfigureRadioTx(uint8_t dataRate, uint32_t freq);
/****************************** FUNCTIONS *************************************/
void LORAWAN_Init(RxAppDataCb_t RxPayload, RxJoinResponseCb_t RxJoinResponse) // this function resets everything to the default values
{
// Allocate software timers and their callbacks
if (loRa.macInitialized == DISABLED)
{
CreateAllSoftwareTimers ();
SetCallbackSoftwareTimers ();
loRa.macInitialized = ENABLED;
}
else
{
StopAllSoftwareTimers ();
}
rxPayload.RxAppData = RxPayload;
rxPayload.RxJoinResponse = RxJoinResponse;
RADIO_Init(&radioBuffer[16], EU868_CALIBRATION_FREQ);
srand (RADIO_ReadRandom ()); // for the loRa random function we need a seed that is obtained from the radio
LORAWAN_Reset (ISM_EU868);
}
void LORAWAN_Reset (IsmBand_t ismBandNew)
{
if (loRa.macInitialized == ENABLED)
{
StopAllSoftwareTimers ();
}
loRa.syncWord = 0x34;
RADIO_SetLoRaSyncWord(loRa.syncWord);
loRa.macStatus.value = 0;
loRa.linkCheckMargin = 255; // reserved
loRa.linkCheckGwCnt = 0;
loRa.lastTimerValue = 0;
loRa.lastPacketLength = 0;
loRa.fCntDown.value = 0;
loRa.fCntUp.value = 0;
loRa.devNonce = 0;
loRa.prescaler = 1;
loRa.adrAckCnt = 0;
loRa.counterAdrAckDelay = 0;
loRa.offset = 0;
loRa.lastTimerValue = 0;
// link check mechanism should be disabled
loRa.macStatus.linkCheck = DISABLED;
//flags all 0-es
loRa.macStatus.value = 0;
loRa.lorawanMacStatus.value = 0;
loRa.maxRepetitionsConfirmedUplink = 7; // 7 retransmissions should occur for each confirmed frame sent until ACK is received
loRa.maxRepetitionsUnconfirmedUplink = 0; // 0 retransmissions should occur for each unconfirmed frame sent until a response is received
loRa.counterRepetitionsConfirmedUplink = 1;
loRa.counterRepetitionsUnconfirmedUplink = 1;
loRa.batteryLevel = BATTERY_LEVEL_INVALID; // the end device was not able to measure the battery level
loRa.ismBand = ismBandNew;
loRa.deviceClass = CLASS_A;
// initialize default channels
loRa.maxChannels = MAX_EU_SINGLE_BAND_CHANNELS;
if(ISM_EU868 == ismBandNew)
{
RADIO_Init(&radioBuffer[16], EU868_CALIBRATION_FREQ);
InitDefault868Channels ();
loRa.receiveWindow2Parameters.dataRate = EU868_DEFAULT_RX_WINDOW2_DR;
loRa.receiveWindow2Parameters.frequency = EU868_DEFAULT_RX_WINDOW2_FREQ;
}
else
{
RADIO_Init(&radioBuffer[16], EU433_CALIBRATION_FREQ);
InitDefault433Channels ();
loRa.receiveWindow2Parameters.dataRate = EU433_DEFAULT_RX_WINDOW2_DR;
loRa.receiveWindow2Parameters.frequency = EU433_DEFAULT_RX_WINDOW2_FREQ;
}
loRa.txPower = 1;
loRa.currentDataRate = DR0;
UpdateMinMaxChDataRate ();
//keys will be filled with 0
loRa.macKeys.value = 0; //no keys are set
memset (&loRa.activationParameters, 0, sizeof(loRa.activationParameters));
//protocol parameters receive the default values
loRa.protocolParameters.receiveDelay1 = RECEIVE_DELAY1;
loRa.protocolParameters.receiveDelay2 = RECEIVE_DELAY2;
loRa.protocolParameters.joinAcceptDelay1 = JOIN_ACCEPT_DELAY1;
loRa.protocolParameters.joinAcceptDelay2 = JOIN_ACCEPT_DELAY2;
loRa.protocolParameters.ackTimeout = ACK_TIMEOUT;
loRa.protocolParameters.adrAckDelay = ADR_ACK_DELAY;
loRa.protocolParameters.adrAckLimit = ADR_ACK_LIMIT;
loRa.protocolParameters.maxFcntGap = MAX_FCNT_GAP;
loRa.protocolParameters.maxMultiFcntGap = MAX_MCAST_FCNT_GAP;
LORAWAN_LinkCheckConfigure (DISABLED); // disable the link check mechanism
}
LorawanError_t LORAWAN_SetReceiveWindow2Parameters (uint32_t frequency, uint8_t dataRate)
{
LorawanError_t result = OK;
if ( (ValidateFrequency (frequency) == OK) && (ValidateDataRate (dataRate) == OK) )
{
UpdateReceiveWindow2Parameters (frequency, dataRate);
}
else
{
result = INVALID_PARAMETER;
}
return result;
}
uint32_t LORAWAN_GetFrequency (uint8_t channelId)
{
return Channels[channelId].frequency;
}
LorawanError_t LORAWAN_SetDataRange (uint8_t channelId, uint8_t dataRangeNew)
{
LorawanError_t result = OK;
if ( (ValidateChannelId (channelId, ALL_CHANNELS) != OK) || (ValidateDataRange (dataRangeNew) != OK) )
{
result = INVALID_PARAMETER;
}
else
{
UpdateDataRange (channelId, dataRangeNew);
}
return result;
}
uint8_t LORAWAN_GetDataRange (uint8_t channelId)
{
uint8_t result = 0xFF;
if (ValidateChannelId (channelId, ALL_CHANNELS) == OK)
{
result = Channels[channelId].dataRange.value;
}
return result;
}
LorawanError_t LORAWAN_SetChannelIdStatus (uint8_t channelId, bool statusNew)
{
LorawanError_t result = OK;
if (ValidateChannelId (channelId, ALL_CHANNELS) != OK)
{
result = INVALID_PARAMETER;
}
else
{
if ( (Channels[channelId].parametersDefined & (FREQUENCY_DEFINED | DATA_RANGE_DEFINED | DUTY_CYCLE_DEFINED) ) == (FREQUENCY_DEFINED | DATA_RANGE_DEFINED | DUTY_CYCLE_DEFINED) )
{
UpdateChannelIdStatus (channelId, statusNew);
}
else
{
result = INVALID_PARAMETER;
}
}
return result;
}
bool LORAWAN_GetChannelIdStatus (uint8_t channelId)
{
bool result = DISABLED;
if (ValidateChannelId (channelId, ALL_CHANNELS) == OK)
{
result = Channels[channelId].status;
}
return result;
}
LorawanError_t LORAWAN_SetFrequency (uint8_t channelId, uint32_t frequencyNew)
{
LorawanError_t result = OK;
if ( (ValidateChannelId (channelId, 0) != OK) || (ValidateFrequency (frequencyNew) != OK) )
{
return INVALID_PARAMETER;
}
UpdateFrequency (channelId, frequencyNew);
return result;
}
LorawanError_t LORAWAN_SetDutyCycle (uint8_t channelId, uint16_t dutyCycleValue)
{
LorawanError_t result = OK;
if (ValidateChannelId (channelId, ALL_CHANNELS) == OK)
{
UpdateDutyCycle (channelId, dutyCycleValue);
}
else
{
result = INVALID_PARAMETER;
}
return result;
}
uint16_t LORAWAN_GetDutyCycle (uint8_t channelId)
{
uint16_t result = UINT16_MAX;
if (ValidateChannelId (channelId, ALL_CHANNELS) == OK)
{
result = Channels[channelId].dutyCycle;
}
return result;
}
uint8_t LORAWAN_GetIsmBand(void) //returns the ISM band
{
return loRa.ismBand;
}
void LORAWAN_TxDone(uint16_t timeOnAir)
{
if (loRa.macStatus.macPause == DISABLED)
{
bool found = false;
uint8_t i;
uint32_t delta = 0, minim = UINT32_MAX, ticks;
//This flag is used when the reception in RX1 is overlapping the opening of RX2
loRa.rx2DelayExpired = 0;
loRa.macStatus.macState = BEFORE_RX1;
i = loRa.lastUsedChannelIndex;
// the join request should never exceed 0.1%
if (loRa.lorawanMacStatus.joining == 1)
{
SwTimerSetTimeout(loRa.joinAccept1TimerId, MS_TO_TICKS_SHORT(loRa.protocolParameters.joinAcceptDelay1 + rxWindowOffset[loRa.receiveWindow1Parameters.dataRate]));
SwTimerSetTimeout(loRa.joinAccept2TimerId, MS_TO_TICKS_SHORT(loRa.protocolParameters.joinAcceptDelay2 + rxWindowOffset[loRa.receiveWindow2Parameters.dataRate]));
SwTimerStart(loRa.joinAccept1TimerId);
SwTimerStart(loRa.joinAccept2TimerId);
Channels[i].channelTimer = ((uint32_t)timeOnAir) * (((uint32_t)DUTY_CYCLE_JOIN_REQUEST + 1) * ((uint32_t)loRa.prescaler) - 1);
}
else
{
SwTimerSetTimeout(loRa.receiveWindow1TimerId, MS_TO_TICKS_SHORT(loRa.protocolParameters.receiveDelay1 + rxWindowOffset[loRa.receiveWindow1Parameters.dataRate]));
SwTimerSetTimeout(loRa.receiveWindow2TimerId, MS_TO_TICKS_SHORT(loRa.protocolParameters.receiveDelay2 + rxWindowOffset[loRa.receiveWindow2Parameters.dataRate]));
SwTimerStart(loRa.receiveWindow1TimerId);
if (CLASS_A == loRa.deviceClass)
{
SwTimerStart(loRa.receiveWindow2TimerId);
}
Channels[i].channelTimer = ((uint32_t)timeOnAir) * (((uint32_t)Channels[i].dutyCycle + 1) * ((uint32_t)loRa.prescaler) - 1);
}
if(SwTimerIsRunning(loRa.dutyCycleTimerId))
{
SwTimerStop(loRa.dutyCycleTimerId);
ticks = SwTimerReadValue (loRa.dutyCycleTimerId);
delta = loRa.lastTimerValue - TICKS_TO_MS(ticks);
}
for (i=0; i < MAX_EU_SINGLE_BAND_CHANNELS; i++)
{
if ((Channels[i].status == ENABLED) && ( Channels[i].channelTimer != 0 ))
{
if( i != loRa.lastUsedChannelIndex )
{
if (Channels[i].channelTimer > delta)
{
Channels[i].channelTimer = Channels[i].channelTimer - delta;
}
else
{
Channels[i].channelTimer = 0;
}
}
if ( (Channels[i].channelTimer <= minim) && (Channels[i].channelTimer !=0) )
{
minim = Channels[i].channelTimer;
found = true;
}
}
}
if (found == true)
{
loRa.lastTimerValue = minim;
SwTimerSetTimeout (loRa.dutyCycleTimerId, MS_TO_TICKS (minim));
SwTimerStart (loRa.dutyCycleTimerId);
}
if (CLASS_C == loRa.deviceClass)
{
loRa.macStatus.macState = CLASS_C_RX2_1_OPEN;
LORAWAN_EnterContinuousReceive();
}
}
else
{
if ((RADIO_GetStatus() & RADIO_FLAG_TIMEOUT) != 0)
{
// Radio transmission ended by watchdog timer
rxPayload.RxAppData( NULL, 0, RADIO_NOT_OK );
}
else
{
//Standalone radio transmissions finished OK, using the same callback as in LoRaWAN tx
if ( rxPayload.RxAppData != NULL )
{
rxPayload.RxAppData( NULL, 0, RADIO_OK );
}
}
}
}
// this function is called by the radio when the first or the second receive window expired without receiving any message (either for join accept or for message)
void LORAWAN_RxTimeout(void)
{
uint8_t i;
uint32_t minim = UINT32_MAX;
if (loRa.macStatus.macPause == 0)
{
// if the timeout is after the first receive window, we have to wait for the second receive window....
if ( loRa.macStatus.macState == RX1_OPEN )
{
if (CLASS_A == loRa.deviceClass)
{
loRa.macStatus.macState = BETWEEN_RX1_RX2;
}
else if (CLASS_C == loRa.deviceClass)
{
LORAWAN_ReceiveWindow2Callback(0);
}
}
else
{
// if last message sent was a join request, the join was not accepted after the second window expired
if (loRa.lorawanMacStatus.joining == 1)
{
SetJoinFailState();
}
// if last message sent was a data message, and there was no reply...
else if (loRa.macStatus.networkJoined == 1)
{
if (loRa.lorawanMacStatus.ackRequiredFromNextDownlinkMessage == ENABLED) // if last uplink packet was confirmed, we have to send this packet by the number indicated by NbRepConfFrames
{
if (loRa.counterRepetitionsConfirmedUplink <= loRa.maxRepetitionsConfirmedUplink)
{
loRa.macStatus.macState = RETRANSMISSION_DELAY;
SwTimerSetTimeout(loRa.ackTimeoutTimerId, MS_TO_TICKS_SHORT(loRa.protocolParameters.ackTimeout));
SwTimerStart(loRa.ackTimeoutTimerId);
}
else
{
ResetParametersForConfirmedTransmission ();
if (rxPayload.RxAppData != NULL)
{
rxPayload.RxAppData (NULL, 0, MAC_NOT_OK);
}
}
}
else
{
if (loRa.counterRepetitionsUnconfirmedUplink <= loRa.maxRepetitionsUnconfirmedUplink)
{
loRa.macStatus.macState = RETRANSMISSION_DELAY;
if (SelectChannelForTransmission (1) == OK)
{
//resend the last packet if the radio transmit function succeedes
if (RADIO_Transmit (&macBuffer[16], loRa.lastPacketLength) == OK)
{
loRa.counterRepetitionsUnconfirmedUplink ++ ; //for each retransmission, the counter increments
loRa.macStatus.macState = TRANSMISSION_OCCURRING; // set the state of MAC to transmission occurring. No other packets can be sent afterwards
}
else
// if radio cannot transmit, then no more retransmissions will occur for this packet
{
ResetParametersForUnconfirmedTransmission ();
if (rxPayload.RxAppData != NULL)
{
rxPayload.RxAppData(NULL, 0, MAC_NOT_OK); // inform the application layer that no message was received back from the server
}
}
}
else
{
// if no channel was found due to duty cycle limitations, start a timer and send the packet when the first channel will be free
for (i = 0; i <= loRa.maxChannels; i ++)
{
if ( (Channels[i].status == ENABLED) && (Channels[i].channelTimer != 0) && (Channels[i].channelTimer <= minim) && (loRa.currentDataRate >= Channels[i].dataRange.min) && (loRa.currentDataRate <= Channels[i].dataRange.max) )
{
minim = Channels[i].channelTimer;
}
}
SwTimerSetTimeout (loRa.unconfirmedRetransmisionTimerId, MS_TO_TICKS_SHORT(minim + 50) );
SwTimerStart (loRa.unconfirmedRetransmisionTimerId);
}
}
else
{
ResetParametersForUnconfirmedTransmission ();
if (rxPayload.RxAppData != NULL)
{
rxPayload.RxAppData(NULL, 0, MAC_OK); // inform the application layer that no message was received back from the server
}
}
}
}
}
}
else
{
//Standalone radio reception NOK, using the same callback as in LoRaWAN rx
if (rxPayload.RxAppData != NULL)
{
rxPayload.RxAppData(NULL, 0, RADIO_NOT_OK);
}
}
}
LorawanError_t ValidateDataRate (uint8_t dataRate)
{
LorawanError_t result = OK;
if ( dataRate > DR7 )
{
result = INVALID_PARAMETER;
}
return result;
}
LorawanError_t ValidateTxPower (uint8_t txPowerNew)
{
LorawanError_t result = OK;
if (((ISM_EU868 == loRa.ismBand) && (0 == txPowerNew)) || (txPowerNew > 5))
{
result = INVALID_PARAMETER;
}
return result;
}
uint8_t* ExecuteDutyCycle (uint8_t *ptr)
{
uint8_t maxDCycle;
maxDCycle = *(ptr++);
if (maxDCycle < 15)
{
loRa.prescaler = 1 << maxDCycle; // Execute the 2^maxDCycle here
loRa.macStatus.prescalerModified = ENABLED;
}
if (maxDCycle == 255)
{
loRa.macStatus.silentImmediately = ENABLED;
}
return ptr;
}
uint8_t* ExecuteLinkAdr (uint8_t *ptr)
{
uint8_t txPower, dataRate;
uint16_t channelMask;
txPower = *(ptr) & LAST_NIBBLE;
dataRate = ( *(ptr) & FIRST_NIBBLE ) >> SHIFT4;
ptr++;
channelMask = (*((uint16_t*)ptr));
ptr = ptr + sizeof (channelMask);
Redundancy_t *redundancy;
redundancy = (Redundancy_t*)(ptr++);
if (ENABLED == loRa.macStatus.adr)
{
if ( (ValidateChannelMaskCntl(redundancy->chMaskCntl) == OK) && (ValidateChannelMask(channelMask) == OK) ) // If the ChMask field value is one of values meaning RFU, the end-device should reject the command and unset the Channel mask ACK bit in its response.
{
loRa.macCommands[loRa.crtMacCmdIndex].channelMaskAck = 1;
}
if ( (ValidateDataRate (dataRate) == OK) && (dataRate >= loRa.minDataRate) && (dataRate <= loRa.maxDataRate) )
{
loRa.macCommands[loRa.crtMacCmdIndex].dataRateAck = 1;
}
if (ValidateTxPower (txPower) == OK)
{
loRa.macCommands[loRa.crtMacCmdIndex].powerAck = 1;
}
if ( (loRa.macCommands[loRa.crtMacCmdIndex].powerAck == 1) && (loRa.macCommands[loRa.crtMacCmdIndex].dataRateAck == 1) && (loRa.macCommands[loRa.crtMacCmdIndex].channelMaskAck == 1) )
{
EnableChannels (channelMask, redundancy->chMaskCntl);
UpdateTxPower (txPower);
loRa.macStatus.txPowerModified = ENABLED; // the current tx power was modified, so the user is informed about the change via this flag
UpdateCurrentDataRate (dataRate);
if (redundancy->nbRep == 0)
{
loRa.maxRepetitionsUnconfirmedUplink = 0;
}
else
{
loRa.maxRepetitionsUnconfirmedUplink = redundancy->nbRep - 1;
}
loRa.macStatus.nbRepModified = 1;
}
}
else
{
loRa.macCommands[loRa.crtMacCmdIndex].channelMaskAck = 0;
loRa.macCommands[loRa.crtMacCmdIndex].dataRateAck = 0;
loRa.macCommands[loRa.crtMacCmdIndex].powerAck = 0;
}
return ptr;
}
uint8_t* ExecuteDevStatus (uint8_t *ptr)
{
return ptr;
}
uint8_t* ExecuteNewChannel (uint8_t *ptr)
{
uint8_t channelIndex;
DataRange_t drRange;
uint32_t frequency = 0;
channelIndex = *(ptr++);
frequency = (*((uint32_t*)ptr)) & 0x00FFFFFF;
frequency = frequency * 100;
ptr = ptr + 3; // 3 bytes for frequecy
drRange.value = *(ptr++);
if (ValidateChannelId (channelIndex, WITHOUT_DEFAULT_CHANNELS) == OK)
{
if ( (ValidateFrequency (frequency) == OK) || (frequency == 0) )
{
loRa.macCommands[loRa.crtMacCmdIndex].channelFrequencyAck = 1;
}
if (ValidateDataRange (drRange.value) == OK)
{
loRa.macCommands[loRa.crtMacCmdIndex].dataRateRangeAck = 1;
}
}
if ( (loRa.macCommands[loRa.crtMacCmdIndex].channelFrequencyAck == 1) && (loRa.macCommands[loRa.crtMacCmdIndex].dataRateRangeAck == 1) )
{
if (loRa.lastUsedChannelIndex < 16)
{
if (frequency != 0)
{
UpdateFrequency (channelIndex, frequency);
UpdateDataRange (channelIndex, drRange.value);
UpdateDutyCycle (channelIndex, DUTY_CYCLE_DEFAULT);
UpdateChannelIdStatus (channelIndex, ENABLED);
}
else
{
LORAWAN_SetChannelIdStatus (channelIndex, DISABLED); // according to the spec, a frequency value of 0 disables the channel
}
}
else
{
if (frequency != 0)
{
UpdateFrequency (channelIndex + 16, frequency);
UpdateDataRange (channelIndex + 16, drRange.value);
UpdateDutyCycle (channelIndex + 16, DUTY_CYCLE_DEFAULT);
UpdateChannelIdStatus (channelIndex + 16, ENABLED);
}
else
{
LORAWAN_SetChannelIdStatus (channelIndex + 16, DISABLED); // according to the spec, a frequency value of 0 disables the channel
}
}
loRa.macStatus.channelsModified = 1; // a new channel was added, so the flag is set to inform the user
}
return ptr;
}
uint8_t* ExecuteRxParamSetupReq (uint8_t *ptr)
{
DlSettings_t dlSettings;
uint32_t frequency = 0;
//In the status field (response) we have to include the following: channle ACK, RX2 data rate ACK, RX1DoffsetACK
dlSettings.value = *(ptr++);
frequency = (*((uint32_t*)ptr)) & 0x00FFFFFF;
frequency = frequency * 100;
ptr = ptr + 3; //3 bytes for frequency
if (ValidateFrequency (frequency) == OK)
{
loRa.macCommands[loRa.crtMacCmdIndex].channelAck = 1;
}
if (ValidateDataRate (dlSettings.bits.rx2DataRate) == OK)
{
loRa.macCommands[loRa.crtMacCmdIndex].dataRateReceiveWindowAck = 1;
}
if (ValidateRxOffset (dlSettings.bits.rx1DROffset) == OK)
{
loRa.macCommands[loRa.crtMacCmdIndex].rx1DROffestAck = 1;
}
if ( (loRa.macCommands[loRa.crtMacCmdIndex].dataRateReceiveWindowAck == 1) && (loRa.macCommands[loRa.crtMacCmdIndex].channelAck == 1) && (loRa.macCommands[loRa.crtMacCmdIndex].rx1DROffestAck == 1))
{
loRa.offset = dlSettings.bits.rx1DROffset;
UpdateReceiveWindow2Parameters (frequency, dlSettings.bits.rx2DataRate);
loRa.macStatus.secondReceiveWindowModified = 1;
}
return ptr;
}
LorawanError_t SearchAvailableChannel (uint8_t maxChannels, bool transmissionType, uint8_t* channelIndex)
{
uint8_t randomNumberCopy, randomNumber, i;
LorawanError_t result = OK;
randomNumber = Random (maxChannels) + 1; //this is a guard so that randomNumber is not 0 and the search will happen
randomNumberCopy = randomNumber;
while (randomNumber)
{
for (i=0; (i < maxChannels) && (randomNumber != 0) ; i++)
{
if ( ( Channels[i].status == ENABLED ) && ( Channels[i].channelTimer == 0 ) && ( loRa.currentDataRate >= Channels[i].dataRange.min ) && ( loRa.currentDataRate <= Channels[i].dataRange.max ) )
{
if (transmissionType == 0) // if transmissionType is join request, then check also for join request channels
{
if ( Channels[i].joinRequestChannel == 1 )
{
randomNumber --;
}
}
else
{
randomNumber --;
}
}
}
// if after one search in all the vector no valid channel was found, exit the loop and return an error
if ( randomNumber == randomNumberCopy )
{
result = NO_CHANNELS_FOUND;
break;
}
}
if ( i != 0)
{
*channelIndex = i - 1;
}
else
{
result = NO_CHANNELS_FOUND;
}
return result;
}
void UpdateCfList (uint8_t bufferLength, JoinAccept_t *joinAccept)
{
uint8_t i;
uint32_t frequency;
uint8_t channelIndex;
if ( (bufferLength == SIZE_JOIN_ACCEPT_WITH_CFLIST) )
{
// 3 is the minimum channel index for single band
channelIndex = 3;
for (i = 0; i < NUMBER_CFLIST_FREQUENCIES; i++ )
{
frequency = 0;
memcpy (&frequency, joinAccept->members.cfList + 3*i, 3);
frequency *= 100;
if (frequency != 0)
{
if (ValidateFrequency (frequency) == OK)
{
Channels[i+channelIndex].frequency = frequency;
Channels[i+channelIndex].dataRange.max = DR5;
Channels[i+channelIndex].dataRange.min = DR0;
Channels[i+channelIndex].dutyCycle = DUTY_CYCLE_DEFAULT_NEW_CHANNEL;
Channels[i+channelIndex].parametersDefined = 0xFF; //all parameters defined
LORAWAN_SetChannelIdStatus(i+channelIndex, ENABLED);
loRa.macStatus.channelsModified = ENABLED; // a new channel was added, so the flag is set to inform the user
}
}
else
{
LORAWAN_SetChannelIdStatus(i+channelIndex, DISABLED);
}
}
loRa.macStatus.channelsModified = ENABLED;
}
}
void ConfigureRadio(uint8_t dataRate, uint32_t freq)
{
RADIO_SetModulation (modulation[dataRate]);
RADIO_SetChannelFrequency (freq);
RADIO_SetFrequencyHopPeriod (DISABLED);
if (dataRate <= DR6)
{
//LoRa modulation
RADIO_SetSpreadingFactor (spreadingFactor[dataRate]);
RADIO_SetBandwidth (bandwidth[dataRate]);
RADIO_SetLoRaSyncWord(loRa.syncWord);
}
else
{
//FSK modulation
RADIO_SetFSKSyncWord(sizeof(FskSyncWordBuff) / sizeof(FskSyncWordBuff[0]), (uint8_t*)FskSyncWordBuff);
}
}
uint32_t GetRx1Freq (void)
{
return loRa.receiveWindow1Parameters.frequency;
}
void UpdateDLSettings(uint8_t dlRx2Dr, uint8_t dlRx1DrOffset)
{
if (dlRx2Dr <= DR7)
{
loRa.receiveWindow2Parameters.dataRate = dlRx2Dr;
}
if (dlRx1DrOffset <= 5)
{
// update the offset between the uplink data rate and the downlink data rate used to communicate with the end device on the first reception slot
loRa.offset = dlRx1DrOffset;
}
}
void StartReTxTimer(void)
{
uint8_t i;
uint32_t minim = UINT32_MAX;
for (i = 0; i <= loRa.maxChannels; i++)
{
if ( (Channels[i].status == ENABLED) && (Channels[i].channelTimer != 0) && (Channels[i].channelTimer <= minim) && (loRa.currentDataRate >= Channels[i].dataRange.min) && (loRa.currentDataRate <= Channels[i].dataRange.max) )
{
minim = Channels[i].channelTimer;
}
}
loRa.macStatus.macState = RETRANSMISSION_DELAY;
SwTimerSetTimeout (loRa.automaticReplyTimerId, MS_TO_TICKS_SHORT(minim) );
SwTimerStart (loRa.automaticReplyTimerId);
}
LorawanError_t SelectChannelForTransmission (bool transmissionType) // transmission type is 0 means join request, transmission type is 1 means data message mode
{
LorawanError_t result = OK;
uint8_t channelIndex;
result = SearchAvailableChannel (MAX_EU_SINGLE_BAND_CHANNELS, transmissionType, &channelIndex);
if (result == OK)
{
loRa.lastUsedChannelIndex = channelIndex;
loRa.receiveWindow1Parameters.frequency = Channels[channelIndex].frequency;
loRa.receiveWindow1Parameters.dataRate = loRa.currentDataRate;
ConfigureRadioTx(loRa.receiveWindow1Parameters.dataRate, loRa.receiveWindow1Parameters.frequency);
}
return result;
}
static void CreateAllSoftwareTimers (void)
{
loRa.joinAccept1TimerId = SwTimerCreate();
loRa.joinAccept2TimerId = SwTimerCreate();
loRa.receiveWindow1TimerId = SwTimerCreate();
loRa.receiveWindow2TimerId = SwTimerCreate();
loRa.linkCheckTimerId = SwTimerCreate();
loRa.ackTimeoutTimerId = SwTimerCreate();
loRa.automaticReplyTimerId = SwTimerCreate();
loRa.unconfirmedRetransmisionTimerId = SwTimerCreate();
loRa.abpJoinTimerId = SwTimerCreate();
loRa.dutyCycleTimerId = SwTimerCreate();
}
static void SetCallbackSoftwareTimers (void)
{
SwTimerSetCallback(loRa.joinAccept1TimerId, LORAWAN_ReceiveWindow1Callback, 0);
SwTimerSetCallback(loRa.joinAccept2TimerId, LORAWAN_ReceiveWindow2Callback, 0);
SwTimerSetCallback(loRa.linkCheckTimerId, LORAWAN_LinkCheckCallback, 0);
SwTimerSetCallback(loRa.receiveWindow1TimerId, LORAWAN_ReceiveWindow1Callback, 0);
SwTimerSetCallback(loRa.receiveWindow2TimerId, LORAWAN_ReceiveWindow2Callback, 0);
SwTimerSetCallback(loRa.ackTimeoutTimerId, AckRetransmissionCallback, 0);
SwTimerSetCallback(loRa.automaticReplyTimerId, AutomaticReplyCallback, 0);
SwTimerSetCallback(loRa.unconfirmedRetransmisionTimerId, UnconfirmedTransmissionCallback, 0);
SwTimerSetCallback(loRa.abpJoinTimerId, UpdateJoinSuccessState, 0);
SwTimerSetCallback (loRa.dutyCycleTimerId, DutyCycleCallback, 0);
}
static void StopAllSoftwareTimers (void)
{
SwTimerStop(loRa.joinAccept1TimerId);
SwTimerStop(loRa.joinAccept2TimerId);
SwTimerStop(loRa.linkCheckTimerId);
SwTimerStop(loRa.receiveWindow1TimerId);
SwTimerStop(loRa.receiveWindow2TimerId);
SwTimerStop(loRa.ackTimeoutTimerId);
SwTimerStop(loRa.automaticReplyTimerId);
SwTimerStop(loRa.unconfirmedRetransmisionTimerId);
SwTimerStop(loRa.abpJoinTimerId);
SwTimerStop(loRa.dutyCycleTimerId);
}
static void InitDefault868Channels (void)
{
uint8_t i;
memset (Channels, 0, sizeof(Channels) );
memcpy (Channels, DefaultChannels868, sizeof(DefaultChannels868) );
for (i = 3; i < MAX_EU_SINGLE_BAND_CHANNELS; i++)
{
// for undefined channels the duty cycle should be a very big value, and the data range a not-valid value
//duty cycle 0 means no duty cycle limitation, the bigger the duty cycle value, the greater the limitation
Channels[i].dutyCycle = UINT16_MAX;
Channels[i].dataRange.value = UINT8_MAX;
}
}
static void InitDefault433Channels (void)
{
uint8_t i;
memset (Channels, 0, sizeof(Channels) );
memcpy (Channels, DefaultChannels433, sizeof(DefaultChannels433) );
for (i = 3; i < MAX_EU_SINGLE_BAND_CHANNELS; i++)
{
// for undefined channels the duty cycle should be a very big value, and the data range a not-valid value
//duty cycle 0 means no duty cycle limitation, the bigger the duty cycle value, the greater the limitation
Channels[i].dutyCycle = UINT16_MAX;
Channels[i].dataRange.value = UINT8_MAX;
}
}
static void UpdateDataRange (uint8_t channelId, uint8_t dataRangeNew)
{
uint8_t i;
// after updating the data range of a channel we need to check if the minimum dataRange has changed or not.
// The user cannot set the current data rate outside the range of the data range
loRa.minDataRate = DR7;
loRa.maxDataRate = DR0;
Channels[channelId].dataRange.value = dataRangeNew;
Channels[channelId].parametersDefined |= DATA_RANGE_DEFINED;
for (i=0; i < loRa.maxChannels; i++)
{
if ( (Channels[i].dataRange.min < loRa.minDataRate) && (Channels[i].status == ENABLED) )
{
loRa.minDataRate = Channels[i].dataRange.min;
}
if ( (Channels[i].dataRange.max > loRa.maxDataRate) && (Channels[i].status == ENABLED) )
{
loRa.maxDataRate = Channels[i].dataRange.max;
}
}
if (loRa.currentDataRate > loRa.maxDataRate)
{
loRa.currentDataRate = loRa.maxDataRate;
}
if (loRa.currentDataRate < loRa.minDataRate)
{
loRa.currentDataRate = loRa.minDataRate;
}
}
static void UpdateChannelIdStatus (uint8_t channelId, bool statusNew)
{
uint8_t i;
Channels[channelId].status = statusNew;
if(Channels[channelId].status == DISABLED)
{
//Clear the dutycycle timer of the channel
Channels[channelId].channelTimer = 0;
}
for (i = 0; i < loRa.maxChannels; i++)
{
if ( (Channels[i].dataRange.min < loRa.minDataRate) && (Channels[i].status == ENABLED) )
{
loRa.minDataRate = Channels[i].dataRange.min;
}
if ( (Channels[i].dataRange.max > loRa.maxDataRate) && (Channels[i].status == ENABLED) )
{
loRa.maxDataRate = Channels[i].dataRange.max;
}
}
if (loRa.currentDataRate > loRa.maxDataRate)
{
loRa.currentDataRate = loRa.maxDataRate;
}
if (loRa.currentDataRate < loRa.minDataRate)
{
loRa.currentDataRate = loRa.minDataRate;
}
}
static LorawanError_t ValidateRxOffset (uint8_t rxOffset)
{
LorawanError_t result = OK;
if (rxOffset > 5)
{
result = INVALID_PARAMETER;
}
return result;
}
static LorawanError_t ValidateFrequency (uint32_t frequencyNew)
{
LorawanError_t result = OK;
if(ISM_EU868 == loRa.ismBand)
{
if ( (frequencyNew > FREQ_870000KHZ) || (frequencyNew < FREQ_863000KHZ) )
{
result = INVALID_PARAMETER ;
}
}
else
{
if ( (frequencyNew > FREQ_434790KHZ) || (frequencyNew < FREQ_433050KHZ) )
{
result = INVALID_PARAMETER ;
}
}
return result;
}
static LorawanError_t ValidateDataRange (uint8_t dataRangeNew)
{
LorawanError_t result = OK;
uint8_t dataRateMax, dataRateMin;
dataRateMin = dataRangeNew & LAST_NIBBLE;
dataRateMax = (dataRangeNew & FIRST_NIBBLE) >> SHIFT4;
if ( (ValidateDataRate (dataRateMax) != OK) || (ValidateDataRate (dataRateMin) != OK ) || (dataRateMax < dataRateMin) )
{
result = INVALID_PARAMETER;
}
return result;
}
static LorawanError_t ValidateChannelId (uint8_t channelId, bool allowedForDefaultChannels) //if allowedForDefaultChannels is 1, all the channels can be modified, if it is 0 channels 0, 1, 2 and 16, 17, and 18 (dual band) cannot be modified
{
LorawanError_t result = OK;
if ( (channelId >= MAX_EU_SINGLE_BAND_CHANNELS) || ( (allowedForDefaultChannels == WITHOUT_DEFAULT_CHANNELS) && (channelId < 3) ) )
{
result = INVALID_PARAMETER ;
}
return result;
}
static LorawanError_t ValidateChannelMaskCntl (uint8_t channelMaskCntl)
{
LorawanError_t result = OK;
if ( (channelMaskCntl != 0) && (channelMaskCntl != 6) )
{
result = INVALID_PARAMETER;
}
return result;
}
static void EnableChannels (uint16_t channelMask, uint8_t channelMaskCntl)
{
EnableChannels1 (channelMask, channelMaskCntl, 0, MAX_EU_SINGLE_BAND_CHANNELS);
}
static void UpdateFrequency (uint8_t channelId, uint32_t frequencyNew )
{
Channels[channelId].frequency = frequencyNew;
Channels[channelId].parametersDefined |= FREQUENCY_DEFINED;
}
static void UpdateDutyCycle (uint8_t channelId, uint16_t dutyCycleNew)
{
Channels[channelId].dutyCycle = dutyCycleNew;
Channels[channelId].parametersDefined |= DUTY_CYCLE_DEFINED;
}
static LorawanError_t ValidateChannelMask (uint16_t channelMask)
{
uint8_t i = 0;
if(channelMask != 0x0000U)
{
for (i = 0; i < MAX_EU_SINGLE_BAND_CHANNELS; i++)
{
if ( ( (channelMask & BIT0) == BIT0) && ( (Channels[i].parametersDefined & (FREQUENCY_DEFINED | DATA_RANGE_DEFINED | DUTY_CYCLE_DEFINED) ) != (FREQUENCY_DEFINED | DATA_RANGE_DEFINED | DUTY_CYCLE_DEFINED) ) ) // if the channel mask sent enables a yet undefined channel, the command is discarded and the device state is not changed
{
return INVALID_PARAMETER;
}
else
{
channelMask = channelMask >> SHIFT1;
}
}
return OK;
}
else
{
//ChMask set to 0x0000 in ADR may be used as a DoS attack so receiving this results in an error
return INVALID_PARAMETER;
}
}
static void EnableChannels1 (uint16_t channelMask, uint8_t channelMaskCntl, uint8_t channelIndexMin, uint8_t channelIndexMax)
{
uint8_t i;
if (channelMaskCntl == 6)
{
for ( i = channelIndexMin; i < channelIndexMax; i++ )
{
UpdateChannelIdStatus (i, ENABLED);
}
}
else if (channelMaskCntl == 0)
{
for ( i = channelIndexMin; i < channelIndexMax; i++ )
{
if ( channelMask & BIT0 == BIT0)
{
UpdateChannelIdStatus (i, ENABLED);
}
else
{
UpdateChannelIdStatus (i, DISABLED);
}
channelMask = channelMask >> SHIFT1;
}
}
}
static void DutyCycleCallback (uint8_t param)
{
uint32_t minim = UINT32_MAX;
bool found = false;
uint8_t i;
for (i=0; i < MAX_EU_SINGLE_BAND_CHANNELS; i++)
{
//Validate this only for enabled channels
if ((Channels[i].status == ENABLED) && ( Channels[i].channelTimer != 0 ))
{
if ( Channels[i].channelTimer > loRa.lastTimerValue )
{
Channels[i].channelTimer = Channels[i].channelTimer - loRa.lastTimerValue;
}
else
{
Channels[i].channelTimer = 0;
}
if ( (Channels[i].channelTimer <= minim) && (Channels[i].channelTimer != 0) )
{
minim = Channels[i].channelTimer;
found = true;
}
}
}
if ( found == true )
{
loRa.lastTimerValue = minim;
SwTimerSetTimeout (loRa.dutyCycleTimerId, MS_TO_TICKS(minim));
SwTimerStart (loRa.dutyCycleTimerId);
}
}
static void ConfigureRadioTx(uint8_t dataRate, uint32_t freq)
{
int8_t txPower;
ConfigureRadio(dataRate, freq);
if (ISM_EU868 == loRa.ismBand)
{
txPower = txPower868[loRa.txPower];
}
else
{
txPower = txPower868[loRa.txPower];
}
RADIO_SetOutputPower (txPower);
RADIO_SetCRC(ENABLED);
RADIO_SetIQInverted(DISABLED);
}
|
kamval/RN2483 | Software/RN2483_LoRAWAN_v1.00.X/main.c | <filename>Software/RN2483_LoRAWAN_v1.00.X/main.c
/**
Generated Main Source File
Company:
Microchip Technology Inc.
File Name:
main.c
Summary:
This is the main file generated using PIC10 / PIC12 / PIC16 / PIC18 MCUs
Description:
This header file provides implementations for driver APIs for all modules selected in the GUI.
Generation Information :
Product Revision : PIC10 / PIC12 / PIC16 / PIC18 MCUs - 1.77
Device : PIC18LF46K22
Driver Version : 2.00
*/
/*
(c) 2018 Microchip Technology Inc. and its subsidiaries.
Subject to your compliance with these terms, you may use Microchip software and any
derivatives exclusively with Microchip products. It is your responsibility to comply with third party
license terms applicable to your use of third party software (including open source software) that
may accompany Microchip software.
THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY
IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS
FOR A PARTICULAR PURPOSE.
IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP
HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO
THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL
CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT
OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS
SOFTWARE.
*/
#include "mcc_generated_files/mcc.h"
// Choose Activation Method ABP == 1; OTAA ==0;
uint8_t activationMethod = 0;
// Activation Method OTAA Keys
uint8_t deviceEUI[8] = { 0x00, 0x09, 0x50, 0xDF, 0x9B, 0xE2, 0x73, 0x3B };
uint8_t applicationEUI[8] = { 0x70, 0xB3, 0xD5, 0x7E, 0xD0, 0x00, 0xB6, 0x92 };
uint8_t applicationKey[16] = { 0x60, 0x86, 0x59, 0xFB, 0xFD, 0xB0, 0xD7, 0x3E, 0x0C, 0x71, 0x85, 0x31, 0x70, 0x8E, 0x7A, 0x8D };
// Activation Method ABP Keys
uint8_t nwkSKey[16] = { 0x1A, 0xBB, 0x89, 0xEB, 0x2A, 0xB0, 0x24, 0xE4, 0x1D, 0xCD, 0x53, 0x2D, 0x74, <KEY> };
uint8_t appSKey[16] = { 0x77, 0xD1, 0x17, 0x66, 0xE8, 0xBD, 0xE5, 0xD4, 0xE0, 0xA7, 0xE8, 0x71, 0xB5, 0x6E, 0x57, 0x9C };
uint32_t deviceAddr = 0x2601198B;
// Data to be send
uint8_t data[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
// Function prototypes
void RxData(uint8_t* pData, uint8_t dataLength, OpStatus_t status) { }
void RxJoinResponse(bool status) { }
/*
Main application
*/
void main(void)
{
// Initialize the device
SYSTEM_Initialize();
// If using interrupts in PIC18 High/Low Priority Mode you need to enable the Global High and Low Interrupts
// If using interrupts in PIC Mid-Range Compatibility Mode you need to enable the Global and Peripheral Interrupts
// Use the following macros to:
// Enable the Global Interrupts
INTERRUPT_GlobalInterruptEnable();
// Enable the Peripheral Interrupts
INTERRUPT_PeripheralInterruptEnable();
// Disable the Global Interrupts
//INTERRUPT_GlobalInterruptDisable();
// Disable the Peripheral Interrupts
//INTERRUPT_PeripheralInterruptDisable();
// LORAWAN init
//LORAWAN_Reset(ISM_EU868);
LORAWAN_Init(RxData, RxJoinResponse);
if(activationMethod == 0){
// Activation Method OTAA
LORAWAN_SetApplicationEui(applicationEUI);
LORAWAN_SetDeviceEui(deviceEUI);
LORAWAN_SetApplicationKey(applicationKey);
// Issue Join
LORAWAN_Join(OTAA);
}
else{
// Activation Method ABP
LORAWAN_SetNetworkSessionKey(nwkSKey);
LORAWAN_SetApplicationSessionKey(appSKey);
LORAWAN_SetDeviceAddress(deviceAddr);
// Issue Join
LORAWAN_Join(ABP);
}
while (1)
{
// Add your application code
LORAWAN_Mainloop();
// All other function calls of the user-defined
// application must be made here
LORAWAN_Send(UNCNF, 2, data, 8);
}
}
/**
End of File
*/ |
kamval/RN2483 | Software/RN2483_LoRAWAN_v1.10.X/mcc_generated_files/tmr5.h | /**
TMR5 Generated Driver API Header File
@Company
Microchip Technology Inc.
@File Name
tmr5.h
@Summary
This is the generated header file for the TMR5 driver using PIC10 / PIC12 / PIC16 / PIC18 MCUs
@Description
This header file provides APIs for driver for TMR5.
Generation Information :
Product Revision : PIC10 / PIC12 / PIC16 / PIC18 MCUs - 1.77
Device : PIC18LF46K22
Driver Version : 2.01
The generated drivers are tested against the following:
Compiler : XC8 2.05 and above
MPLAB : MPLAB X 5.20
*/
/*
(c) 2018 Microchip Technology Inc. and its subsidiaries.
Subject to your compliance with these terms, you may use Microchip software and any
derivatives exclusively with Microchip products. It is your responsibility to comply with third party
license terms applicable to your use of third party software (including open source software) that
may accompany Microchip software.
THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY
IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS
FOR A PARTICULAR PURPOSE.
IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP
HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO
THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL
CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT
OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS
SOFTWARE.
*/
#ifndef TMR5_H
#define TMR5_H
/**
Section: Included Files
*/
#include <stdbool.h>
#include <stdint.h>
#ifdef __cplusplus // Provide C++ Compatibility
extern "C" {
#endif
/**
Section: TMR5 APIs
*/
/**
@Summary
Initializes the TMR5
@Description
This routine initializes the TMR5.
This routine must be called before any other TMR5 routine is called.
This routine should only be called once during system initialization.
@Preconditions
None
@Param
None
@Returns
None
@Comment
@Example
<code>
TMR5_Initialize();
</code>
*/
void TMR5_Initialize(void);
/**
@Summary
Start TMR5
@Description
This routine is used to Start TMR5.
@Preconditions
The TMR5_Initialize() routine should be called
prior to use this routine.
@Param
None
@Returns
None
@Example
<code>
// Initialize TMR5 module
// Start TMR5
TMR5_StartTimer();
while(1)
{
}
</code>
*/
void TMR5_StartTimer(void);
/**
@Summary
Stop TMR5
@Description
This routine is used to Stop TMR5.
@Preconditions
The TMR5_Initialize() routine should be called
prior to use this routine.
@Param
None
@Returns
None
@Example
</code>
TMR5_Initialize();
TMR5_StartTimer();
if(TMR5_HasOverflowOccured())
{
TMR5_StopTimer();
}
<code>
*/
void TMR5_StopTimer(void);
/**
@Summary
Read TMR5 register.
@Description
This routine is used to Read TMR5 register.
@Preconditions
The TMR5_Initialize() routine should be called
prior to use this routine.
@Param
None
@Returns
TMR5 value at the time of the function call read as a 16-bit value
@Example
<code>
uint16_t timerVal=0;
TMR5_Initialize();
TMR5_StartTimer();
// some delay or code
TMR5_StopTimer();
timerVal=TMR5_ReadTimer();
</code>
*/
uint16_t TMR5_ReadTimer(void);
/**
@Summary
Write TMR5 register.
@Description
This routine is used to Write TMR5 register.
@Preconditions
The TMR5_Initialize() routine should be called
prior to use this routine.
@Param
timerVal : Timer value to be loaded
@Returns
None
@Example
<code>
TMR5_Initialize();
TMR5_WriteTimer(0x055);
TMR5_StartTimer();
</code>
*/
void TMR5_WriteTimer(uint16_t timerVal);
/**
@Summary
Reload TMR5 register.
@Description
This routine is used to reload TMR5 register.
@Preconditions
The TMR5_Initialize() routine should be called
prior to use this routine.
@Param
None
@Returns
None
@Example
<code>
TMR5_Initialize();
TMR5_StartTimer();
if(TMR5_HasOverflowOccured())
{
TMR5_StopTimer();
}
TMR5_Reload();}
</code>
*/
void TMR5_Reload(void);
/**
@Summary
Starts the single pulse acquisition in TMR5 gate operation.
@Description
This function starts the single pulse acquisition in TMR5 gate operation.
This function must be used when the TMR5 gate is enabled.
@Preconditions
Initialize the TMR5 with gate enable before calling this function.
@Param
None
@Returns
None
@Example
<code>
uint16_t xVal;
uint16_t yVal;
//enable TMR5 singlepulse mode
TMR5_StartSinglePulseAcquistion();
//check TMR5 gate status
if(TMR5_CheckGateValueStatus()== 0)
{
xVal = TMR5_ReadTimer();
}
// wait untill gate interrupt occured
while(TMR5GIF == 0)
{
}
yVal = TMR5_ReadTimer();
</code>
*/
void TMR5_StartSinglePulseAcquisition(void);
/**
@Summary
Check the current state of Timer1 gate.
@Description
This function reads the TMR5 gate value and return it.
This function must be used when the TMR5 gate is enabled.
@Preconditions
Initialize the TMR5 with gate enable before calling this function.
@Param
None
@Returns
None
@Example
<code>
uint16_t xVal;
uint16_t yVal;
//enable TMR5 singlepulse mode
TMR5_StartSinglePulseAcquistion();
//check TMR5 gate status
if(TMR5_CheckGateValueStatus()== 0)
{
xVal = TMR5_ReadTimer();
}
//wait untill gate interrupt occured
while(TMR5IF == 0)
{
}
yVal = TMR5_ReadTimer();
</code>
*/
uint8_t TMR5_CheckGateValueStatus(void);
/**
@Summary
Get the TMR5 overflow status.
@Description
This routine get the TMR5 overflow status.
@Preconditions
The TMR5_Initialize() routine should be called
prior to use this routine.
@Param
None
@Returns
true - Overflow has occured.
false - Overflow has not occured.
@Comment
@Example
<code>
TMR5_Initialize();
TMR5_StartTimer();
while(1)
{
if(TMR5_HasOverflowOccured())
{
TMR5_StopTimer();
}
}
</code>
*/
bool TMR5_HasOverflowOccured(void);
#ifdef __cplusplus // Provide C++ Compatibility
}
#endif
#endif // TMR5_H
/**
End of File
*/ |
kamval/RN2483 | Software/RN2483_LoRAWAN_v1.10.X/mcc_generated_files/ext_int.h | <filename>Software/RN2483_LoRAWAN_v1.10.X/mcc_generated_files/ext_int.h
/**
EXT_INT Generated Driver File
@Company
Microchip Technology Inc.
@File Name
ext_int.c
@Summary
This is the generated driver implementation file for the EXT_INT driver using PIC10 / PIC12 / PIC16 / PIC18 MCUs
@Description
This source file provides implementations for driver APIs for EXT_INT.
Generation Information :
Product Revision : PIC10 / PIC12 / PIC16 / PIC18 MCUs - 1.77
Device : PIC18LF46K22
Driver Version : 1.11
The generated drivers are tested against the following:
Compiler : XC8 2.05 and above
MPLAB : MPLAB X 5.20
*/
/*
(c) 2018 Microchip Technology Inc. and its subsidiaries.
Subject to your compliance with these terms, you may use Microchip software and any
derivatives exclusively with Microchip products. It is your responsibility to comply with third party
license terms applicable to your use of third party software (including open source software) that
may accompany Microchip software.
THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY
IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS
FOR A PARTICULAR PURPOSE.
IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP
HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO
THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL
CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT
OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS
SOFTWARE.
*/
#ifndef _EXT_INT_H
#define _EXT_INT_H
/**
Section: Includes
*/
#include <xc.h>
// Provide C++ Compatibility
#ifdef __cplusplus
extern "C" {
#endif
/**
Section: Macros
*/
/**
@Summary
Clears the interrupt flag for INT1
@Description
This routine clears the interrupt flag for the external interrupt, INT1.
@Preconditions
None.
@Returns
None.
@Param
None.
@Example
<code>
void INT1_ISR(void)
{
// User Area Begin->code
// User Area End->code
EXT_INT1_InterruptFlagClear();
}
</code>
*/
#define EXT_INT1_InterruptFlagClear() (INTCON3bits.INT1IF = 0)
/**
@Summary
Clears the interrupt enable for INT1
@Description
This routine clears the interrupt enable for the external interrupt, INT1.
After calling this routine, external interrupts on this pin will not be serviced by the
interrupt handler, INT1.
@Preconditions
None.
@Returns
None.
@Param
None.
@Example
Changing the external interrupt edge detect from negative to positive
<code>
// clear the interrupt enable
EXT_INT1_InterruptDisable();
// change the edge
EXT_INT1_risingEdgeSet();
// clear the interrupt flag and re-enable the interrupt
EXT_INT1_InterruptFlagClear();
EXT_INT1_InterruptEnable();
</code>
*/
#define EXT_INT1_InterruptDisable() (INTCON3bits.INT1IE = 0)
/**
@Summary
Sets the interrupt enable for INT1
@Description
This routine sets the interrupt enable for the external interrupt, INT1.
After calling this routine, external interrupts on this pin will be serviced by the
interrupt handler, INT1.
@Preconditions
None.
@Returns
None.
@Param
None.
@Example
Setting the external interrupt to handle positive edge interrupts
<code>
// set the edge
EXT_INT1_risingEdgeSet();
// clear the interrupt flag and enable the interrupt
EXT_INT1_InterruptFlagClear();
EXT_INT1_InterruptEnable();
</code>
*/
#define EXT_INT1_InterruptEnable() (INTCON3bits.INT1IE = 1)
/**
@Summary
Sets the edge detect of the external interrupt to negative edge.
@Description
This routine set the edge detect of the extern interrupt to negative edge.
After this routine is called the interrupt flag will be set when the external
interrupt pins level transitions from a high to low level.
@Preconditions
None.
@Returns
None.
@Param
None.
@Example
Setting the external interrupt to handle negative edge interrupts
<code>
// set the edge
EXT_INT1_risingEdgeSet();
// clear the interrupt flag and enable the interrupt
EXT_INT1_InterruptFlagClear();
EXT_INT1_InterruptEnable();
</code>
*/
#define EXT_INT1_risingEdgeSet() (INTCON2bits.INTEDG1 = 1)
/**
@Summary
Sets the edge detect of the external interrupt to positive edge.
@Description
This routine set the edge detect of the extern interrupt to positive edge.
After this routine is called the interrupt flag will be set when the external
interrupt pins level transitions from a low to high level.
@Preconditions
None.
@Returns
None.
@Param
None.
@Example
Setting the external interrupt to handle positive edge interrupts
<code>
// set the edge
EXT_INT1_risingEdgeSet();
// clear the interrupt flag and enable the interrupt
EXT_INT1_InterruptFlagClear();
EXT_INT1_InterruptEnable();
</code>
*/
#define EXT_INT1_fallingEdgeSet() (INTCON2bits.INTEDG1 = 0)
/**
@Summary
Clears the interrupt flag for INT2
@Description
This routine clears the interrupt flag for the external interrupt, INT2.
@Preconditions
None.
@Returns
None.
@Param
None.
@Example
<code>
void INT2_ISR(void)
{
// User Area Begin->code
// User Area End->code
EXT_INT2_InterruptFlagClear();
}
</code>
*/
#define EXT_INT2_InterruptFlagClear() (INTCON3bits.INT2IF = 0)
/**
@Summary
Clears the interrupt enable for INT2
@Description
This routine clears the interrupt enable for the external interrupt, INT2.
After calling this routine, external interrupts on this pin will not be serviced by the
interrupt handler, INT2.
@Preconditions
None.
@Returns
None.
@Param
None.
@Example
Changing the external interrupt edge detect from negative to positive
<code>
// clear the interrupt enable
EXT_INT2_InterruptDisable();
// change the edge
EXT_INT2_risingEdgeSet();
// clear the interrupt flag and re-enable the interrupt
EXT_INT2_InterruptFlagClear();
EXT_INT2_InterruptEnable();
</code>
*/
#define EXT_INT2_InterruptDisable() (INTCON3bits.INT2IE = 0)
/**
@Summary
Sets the interrupt enable for INT2
@Description
This routine sets the interrupt enable for the external interrupt, INT2.
After calling this routine, external interrupts on this pin will be serviced by the
interrupt handler, INT2.
@Preconditions
None.
@Returns
None.
@Param
None.
@Example
Setting the external interrupt to handle positive edge interrupts
<code>
// set the edge
EXT_INT2_risingEdgeSet();
// clear the interrupt flag and enable the interrupt
EXT_INT2_InterruptFlagClear();
EXT_INT2_InterruptEnable();
</code>
*/
#define EXT_INT2_InterruptEnable() (INTCON3bits.INT2IE = 1)
/**
@Summary
Sets the edge detect of the external interrupt to negative edge.
@Description
This routine set the edge detect of the extern interrupt to negative edge.
After this routine is called the interrupt flag will be set when the external
interrupt pins level transitions from a high to low level.
@Preconditions
None.
@Returns
None.
@Param
None.
@Example
Setting the external interrupt to handle negative edge interrupts
<code>
// set the edge
EXT_INT2_risingEdgeSet();
// clear the interrupt flag and enable the interrupt
EXT_INT2_InterruptFlagClear();
EXT_INT2_InterruptEnable();
</code>
*/
#define EXT_INT2_risingEdgeSet() (INTCON2bits.INTEDG2 = 1)
/**
@Summary
Sets the edge detect of the external interrupt to positive edge.
@Description
This routine set the edge detect of the extern interrupt to positive edge.
After this routine is called the interrupt flag will be set when the external
interrupt pins level transitions from a low to high level.
@Preconditions
None.
@Returns
None.
@Param
None.
@Example
Setting the external interrupt to handle positive edge interrupts
<code>
// set the edge
EXT_INT2_risingEdgeSet();
// clear the interrupt flag and enable the interrupt
EXT_INT2_InterruptFlagClear();
EXT_INT2_InterruptEnable();
</code>
*/
#define EXT_INT2_fallingEdgeSet() (INTCON2bits.INTEDG2 = 0)
/**
Section: External Interrupt Initializers
*/
/**
@Summary
Initializes the external interrupt pins
@Description
This routine initializes the EXT_INT driver to detect the configured edge, clear
the interrupt flag and enable the interrupt.
The following external interrupts will be initialized:
INT1 - EXT_INT1
INT2 - EXT_INT2
@Preconditions
None.
@Returns
None.
@Param
None.
@Example
Initialize the external interrupt pins
<code>
EXT_INT_Initialize();
</code>
*/
void EXT_INT_Initialize(void);
/**
Section: External Interrupt Handlers
*/
/**
@Summary
Interrupt Service Routine for EXT_INT1 - INT1 pin
@Description
This ISR will execute whenever the signal on the INT1 pin will transition to the preconfigured state.
@Preconditions
EXT_INT intializer called
@Returns
None.
@Param
None.
*/
void INT1_ISR(void);
/**
@Summary
Callback function for EXT_INT1 - INT1
@Description
Allows for a specific callback function to be called in the INT1 ISR.
It also allows for a non-specific interrupt handler to be called at runtime.
@Preconditions
EXT_INT intializer called
@Returns
None.
@Param
None.
@Example
EXT_INT_Initializer();
void INT1_CallBack();
*/
void INT1_CallBack(void);
/**
@Summary
Interrupt Handler Setter for EXT_INT1 - INT1 pin
@Description
Allows selecting an interrupt handler for EXT_INT1 - INT1 at application runtime
@Preconditions
EXT_INT intializer called
@Returns
None.
@Param
InterruptHandler function pointer.
@Example
EXT_INT_Initializer();
INT1_SetInterruptHandler(MyInterruptHandler);
*/
void INT1_SetInterruptHandler(void (* InterruptHandler)(void));
/**
@Summary
Dynamic Interrupt Handler for EXT_INT1 - INT1 pin
@Description
This is the dynamic interrupt handler to be used together with the INT1_SetInterruptHandler() method.
This handler is called every time the INT1 ISR is executed and allows any function to be registered at runtime.
@Preconditions
EXT_INT intializer called
@Returns
None.
@Param
None.
@Example
EXT_INT_Initializer();
INT1_SetInterruptHandler(INT1_InterruptHandler);
*/
extern void (*INT1_InterruptHandler)(void);
/**
@Summary
Default Interrupt Handler for EXT_INT1 - INT1 pin
@Description
This is a predefined interrupt handler to be used together with the INT1_SetInterruptHandler() method.
This handler is called every time the INT1 ISR is executed.
@Preconditions
EXT_INT intializer called
@Returns
None.
@Param
None.
@Example
EXT_INT_Initializer();
INT1_SetInterruptHandler(INT1_DefaultInterruptHandler);
*/
void INT1_DefaultInterruptHandler(void);
/**
@Summary
Interrupt Service Routine for EXT_INT2 - INT2 pin
@Description
This ISR will execute whenever the signal on the INT2 pin will transition to the preconfigured state.
@Preconditions
EXT_INT intializer called
@Returns
None.
@Param
None.
*/
void INT2_ISR(void);
/**
@Summary
Callback function for EXT_INT2 - INT2
@Description
Allows for a specific callback function to be called in the INT2 ISR.
It also allows for a non-specific interrupt handler to be called at runtime.
@Preconditions
EXT_INT intializer called
@Returns
None.
@Param
None.
@Example
EXT_INT_Initializer();
void INT2_CallBack();
*/
void INT2_CallBack(void);
/**
@Summary
Interrupt Handler Setter for EXT_INT2 - INT2 pin
@Description
Allows selecting an interrupt handler for EXT_INT2 - INT2 at application runtime
@Preconditions
EXT_INT intializer called
@Returns
None.
@Param
InterruptHandler function pointer.
@Example
EXT_INT_Initializer();
INT2_SetInterruptHandler(MyInterruptHandler);
*/
void INT2_SetInterruptHandler(void (* InterruptHandler)(void));
/**
@Summary
Dynamic Interrupt Handler for EXT_INT2 - INT2 pin
@Description
This is the dynamic interrupt handler to be used together with the INT2_SetInterruptHandler() method.
This handler is called every time the INT2 ISR is executed and allows any function to be registered at runtime.
@Preconditions
EXT_INT intializer called
@Returns
None.
@Param
None.
@Example
EXT_INT_Initializer();
INT2_SetInterruptHandler(INT2_InterruptHandler);
*/
extern void (*INT2_InterruptHandler)(void);
/**
@Summary
Default Interrupt Handler for EXT_INT2 - INT2 pin
@Description
This is a predefined interrupt handler to be used together with the INT2_SetInterruptHandler() method.
This handler is called every time the INT2 ISR is executed.
@Preconditions
EXT_INT intializer called
@Returns
None.
@Param
None.
@Example
EXT_INT_Initializer();
INT2_SetInterruptHandler(INT2_DefaultInterruptHandler);
*/
void INT2_DefaultInterruptHandler(void);
// Provide C++ Compatibility
#ifdef __cplusplus
}
#endif
#endif
|
kamval/RN2483 | Software/RN2483_LoRAWAN_v1.10.X/mcc_generated_files/LoRaWAN/lorawan_eu.h | <filename>Software/RN2483_LoRAWAN_v1.10.X/mcc_generated_files/LoRaWAN/lorawan_eu.h
/********************************************************************
* Copyright (C) 2016 Microchip Technology Inc. and its subsidiaries
* (Microchip). All rights reserved.
*
* You are permitted to use the software and its derivatives with Microchip
* products. See the license agreement accompanying this software, if any, for
* more info about your rights and obligations.
*
* SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF
* MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR
* PURPOSE. IN NO EVENT SHALL MICROCHIP, SMSC, OR ITS LICENSORS BE LIABLE OR
* OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH
* OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY FOR ANY DIRECT OR INDIRECT
* DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR OTHER SIMILAR COSTS. To the fullest
* extend allowed by law, Microchip and its licensors liability will not exceed
* the amount of fees, if any, that you paid directly to Microchip to use this
* software.
*************************************************************************
*
* lorawan.h
*
* LoRaWAN EU header file
*
*
* Hardware:
* RN-2xx3-PICTAIL
*
* Author Date Ver Comment
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* M17319 2016.03.29 0.1
******************************************************************************/
#ifndef _LORAWAN_EU_H
#define _LORAWAN_EU_H
#ifdef __cplusplus
extern "C" {
#endif
/****************************** INCLUDES **************************************/
#include <xc.h>
#include "lorawan_defs.h"
/****************************** DEFINES ***************************************/
//maximum number of channels
#define MAX_EU_SINGLE_BAND_CHANNELS 16 // 16 channels numbered from 0 to 15
#define ALL_CHANNELS 1
#define WITHOUT_DEFAULT_CHANNELS 0
//dutycycle definition
#define DUTY_CYCLE_DEFAULT 302 //0.33 %
#define DUTY_CYCLE_JOIN_REQUEST 3029 //0.033%
#define DUTY_CYCLE_DEFAULT_NEW_CHANNEL 999 //0.1%
//EU default channels for 868 Mhz
#define LC0_868 {868100000, ENABLED, { ( ( DR5 << SHIFT4 ) | DR0 ) }, 302, 0, 1, 0xFF}
#define LC1_868 {868300000, ENABLED, { ( ( DR5 << SHIFT4 ) | DR0 ) }, 302, 0, 1, 0xFF}
#define LC2_868 {868500000, ENABLED, { ( ( DR5 << SHIFT4 ) | DR0 ) }, 302, 0, 1, 0xFF}
//EU default channels for 433 Mhz (the same channels are for join request)
#define LC0_433 {433175000, ENABLED, { ( ( DR5 << SHIFT4 ) | DR0 ) }, 302, 0, 1, 0xFF}
#define LC1_433 {433375000, ENABLED, { ( ( DR5 << SHIFT4 ) | DR0 ) }, 302, 0, 1, 0xFF}
#define LC2_433 {433575000, ENABLED, { ( ( DR5 << SHIFT4 ) | DR0 ) }, 302, 0, 1, 0xFF}
#define TXPOWER_MIN 0
#define TXPOWER_MAX 5
#define SIZE_JOIN_ACCEPT_WITH_CFLIST 33
#define NUMBER_CFLIST_FREQUENCIES 5
// masks for channel parameters
#define FREQUENCY_DEFINED 0X01
#define DATA_RANGE_DEFINED 0X02
#define DUTY_CYCLE_DEFINED 0x04
/***************************** TYPEDEFS ***************************************/
typedef union
{
uint8_t joinAcceptCounter[29];
struct
{
Mhdr_t mhdr;
uint8_t appNonce[3];
uint8_t networkId[3];
DeviceAddress_t deviceAddress;
DlSettings_t DLSettings;
uint8_t rxDelay;
uint8_t cfList[16];
} members;
} JoinAccept_t;
//Channel parameters
typedef struct
{
uint32_t frequency;
bool status;
DataRange_t dataRange;
uint16_t dutyCycle;
uint32_t channelTimer;
bool joinRequestChannel;
uint8_t parametersDefined;
} ChannelParams_t;
typedef union
{
uint16_t value;
struct
{
unsigned ackRequiredFromNextDownlinkMessage:1; //if set, the next downlink message should have the ACK bit set because an ACK is needed for the end device
unsigned ackRequiredFromNextUplinkMessage:1; //if set, the next uplink message should have the ACK bit set because an ACK is needed for the server
unsigned joining: 1;
unsigned fPending:1;
unsigned adrAckRequest:1;
unsigned synchronization:1; //if set, there is no need to send immediately a packet because the application sent one from the callback
};
} LorawanMacStatus_t;
typedef struct
{
LorawanMacStatus_t lorawanMacStatus;
LorawanStatus_t macStatus;
FCnt_t fCntUp;
FCnt_t fCntDown;
FCnt_t fMcastCntDown;
LoRaClass_t deviceClass;
ReceiveWindowParameters_t receiveWindow1Parameters;
ReceiveWindowParameters_t receiveWindow2Parameters;
ActivationParameters_t activationParameters;
ChannelParams_t channelParameters;
ProtocolParams_t protocolParameters;
IsmBand_t ismBand;
LorawanMacKeys_t macKeys;
uint8_t crtMacCmdIndex;
LorawanCommands_t macCommands[MAX_NB_CMD_TO_PROCESS];
uint32_t lastTimerValue;
uint32_t periodForLinkCheck;
uint16_t adrAckCnt;
uint16_t devNonce;
uint16_t lastPacketLength;
uint8_t maxRepetitionsUnconfirmedUplink;
uint8_t maxRepetitionsConfirmedUplink;
uint8_t counterRepetitionsUnconfirmedUplink;
uint8_t counterRepetitionsConfirmedUplink;
uint8_t lastUsedChannelIndex;
uint16_t prescaler;
uint8_t linkCheckMargin;
uint8_t linkCheckGwCnt;
uint8_t currentDataRate;
uint8_t batteryLevel;
uint8_t txPower;
uint8_t joinAccept1TimerId;
uint8_t joinAccept2TimerId;
uint8_t receiveWindow1TimerId;
uint8_t receiveWindow2TimerId;
uint8_t automaticReplyTimerId;
uint8_t linkCheckTimerId;
uint8_t ackTimeoutTimerId;
uint8_t dutyCycleTimerId;
uint8_t unconfirmedRetransmisionTimerId;
uint8_t minDataRate;
uint8_t maxDataRate;
uint8_t maxChannels;
uint8_t counterAdrAckDelay;
uint8_t offset;
bool macInitialized;
bool rx2DelayExpired;
bool abpJoinStatus;
uint8_t abpJoinTimerId;
uint8_t syncWord;
} LoRa_t;
extern LoRa_t loRa;
/*************************** FUNCTIONS PROTOTYPE ******************************/
#ifdef __cplusplus
}
#endif
#endif /* _LORAWAN_EU_H */ |
any1/wlvncc | src/vnc.c | <reponame>any1/wlvncc
/*
* Copyright (c) 2020 <NAME>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <stdbool.h>
#include <pixman.h>
#include <rfb/rfbclient.h>
#include <wayland-client.h>
#include "vnc.h"
extern const unsigned short code_map_linux_to_qnum[];
extern const unsigned int code_map_linux_to_qnum_len;
static rfbBool vnc_client_alloc_fb(rfbClient* client)
{
struct vnc_client* self = rfbClientGetClientData(client, NULL);
assert(self);
return self->alloc_fb(self) < 0 ? FALSE : TRUE;
}
static void vnc_client_update_box(rfbClient* client, int x, int y, int width,
int height)
{
struct vnc_client* self = rfbClientGetClientData(client, NULL);
assert(self);
pixman_region_union_rect(&self->damage, &self->damage, x, y, width,
height);
}
static void vnc_client_finish_update(rfbClient* client)
{
struct vnc_client* self = rfbClientGetClientData(client, NULL);
assert(self);
self->update_fb(self);
pixman_region_clear(&self->damage);
}
static void vnc_client_got_cut_text(rfbClient* client, const char* text,
int len)
{
struct vnc_client* self = rfbClientGetClientData(client, NULL);
assert(self);
if (self->cut_text)
self->cut_text(self, text, len);
}
struct vnc_client* vnc_client_create(void)
{
struct vnc_client* self = calloc(1, sizeof(*self));
if (!self)
return NULL;
/* These are defaults that can be changed with
* vnc_client_set_pixel_format().
*/
int bits_per_sample = 8;
int samples_per_pixel = 3;
int bytes_per_pixel = 4;
rfbClient* client = rfbGetClient(bits_per_sample, samples_per_pixel,
bytes_per_pixel);
if (!client)
goto failure;
self->client = client;
rfbClientSetClientData(client, NULL, self);
client->MallocFrameBuffer = vnc_client_alloc_fb;
client->GotFrameBufferUpdate = vnc_client_update_box;
client->FinishedFrameBufferUpdate = vnc_client_finish_update;
client->GotXCutText = vnc_client_got_cut_text;
return self;
failure:
free(self);
return NULL;
}
void vnc_client_destroy(struct vnc_client* self)
{
rfbClientCleanup(self->client);
free(self);
}
int vnc_client_connect(struct vnc_client* self, const char* address, int port)
{
rfbClient* client = self->client;
if (!ConnectToRFBServer(client, address, port))
return -1;
if (!InitialiseRFBConnection(client))
return -1;
client->width = client->si.framebufferWidth;
client->height = client->si.framebufferHeight;
if (!client->MallocFrameBuffer(client))
return -1;
if (!SetFormatAndEncodings(client))
return -1;
if (client->updateRect.x < 0) {
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
}
if (!SendFramebufferUpdateRequest(client,
client->updateRect.x, client->updateRect.y,
client->updateRect.w, client->updateRect.h,
FALSE))
return -1;
return 0;
}
int vnc_client_set_pixel_format(struct vnc_client* self,
enum wl_shm_format format)
{
rfbPixelFormat* dst = &self->client->format;
int bpp = -1;
switch (format) {
case WL_SHM_FORMAT_ARGB8888:
case WL_SHM_FORMAT_XRGB8888:
dst->redShift = 16;
dst->greenShift = 8;
dst->blueShift = 0;
bpp = 32;
break;
default:
return -1;
}
switch (bpp) {
case 32:
dst->bitsPerPixel = 32;
dst->depth = 24;
dst->redMax = 0xff;
dst->greenMax = 0xff;
dst->blueMax = 0xff;
break;
default:
abort();
}
dst->trueColour = 1;
dst->bigEndian = FALSE;
self->client->appData.requestedDepth = dst->depth;
return 0;
}
int vnc_client_get_width(const struct vnc_client* self)
{
return self->client->width;
}
int vnc_client_get_height(const struct vnc_client* self)
{
return self->client->height;
}
int vnc_client_get_stride(const struct vnc_client* self)
{
// TODO: What happens if bitsPerPixel == 24?
return self->client->width * self->client->format.bitsPerPixel / 8;
}
void* vnc_client_get_fb(const struct vnc_client* self)
{
return self->client->frameBuffer;
}
void vnc_client_set_fb(struct vnc_client* self, void* fb)
{
self->client->frameBuffer = fb;
}
int vnc_client_get_fd(const struct vnc_client* self)
{
return self->client->sock;
}
const char* vnc_client_get_desktop_name(const struct vnc_client* self)
{
return self->client->desktopName;
}
int vnc_client_process(struct vnc_client* self)
{
return HandleRFBServerMessage(self->client) ? 0 : -1;
}
void vnc_client_send_pointer_event(struct vnc_client* self, int x, int y,
uint32_t button_mask)
{
SendPointerEvent(self->client, x, y, button_mask);
}
void vnc_client_send_keyboard_event(struct vnc_client* self, uint32_t symbol,
uint32_t code, bool is_pressed)
{
if (code >= code_map_linux_to_qnum_len)
return;
uint32_t qnum = code_map_linux_to_qnum[code];
if (!qnum)
qnum = code;
if (!SendExtendedKeyEvent(self->client, symbol, qnum, is_pressed))
SendKeyEvent(self->client, symbol, is_pressed);
}
void vnc_client_set_encodings(struct vnc_client* self, const char* encodings)
{
self->client->appData.encodingsString = encodings;
}
void vnc_client_set_quality_level(struct vnc_client* self, int value)
{
self->client->appData.qualityLevel = value;
}
void vnc_client_set_compression_level(struct vnc_client* self, int value)
{
self->client->appData.compressLevel = value;
}
void vnc_client_send_cut_text(struct vnc_client* self, const char* text,
size_t len)
{
// libvncclient doesn't modify text, so typecast is OK.
SendClientCutText(self->client, (char*)text, len);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.