repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab6/src/option5-mod/src/message_queue/message_queue.c | <reponame>Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming<gh_stars>0
#include "message_queue.h"
mqd_t get_opened_message_queue(const char message_queue_name[])
{
printf("\t\"queue\": \"%s\" - открывается очередь\n", message_queue_name);
struct mq_attr mqAttr; // создаем структуру
mqAttr.mq_maxmsg = 10; // максимальное количество сообщений
mqAttr.mq_msgsize = 1024; // максимальная длина сообщения в байт
mqd_t handler = mq_open(
message_queue_name, // название очереди
O_RDWR | O_CREAT, // int флаги
S_IWUSR | S_IRUSR, // флаги
&mqAttr // ссылка на структуру
);
if (handler < 0) // если очередь не открылась
{
printf("\t\tError %d (%s) mq_open for send.\n", errno, strerror(errno));
exit(-1);
}
printf("\tmqd_t %d - очередь открыта успешно\n", handler);
return handler; // возвращаем номер очереди
}
void send_message_queue(const char message[], mqd_t handler)
{
printf("\t\"message\": \"%s\" - сообщение отправляется\n", message);
int rc = mq_send(
handler, // номер очереди
message, // сообщение
strlen(message), // длина сообщения
1 // приоритет
);
if (rc < 0) // если сообщение не отправилось
{
printf("\t\tError %d (%s) mq_send.\n", errno, strerror(errno));
exit(-1);
}
printf("\tmqd_t %d - сообщение отправлено успешно\n", handler);
}
char* reveiving_message_queue(mqd_t handler)
{
char buffer[2048]; // сюда запишется сообщение
printf("\tmqd_t %d - получаем сообщение\n", handler);
int rc = mq_receive(
handler, // номер очереди
buffer, // строка в которую запишется сообщение
sizeof(buffer), // длина строки
NULL // приоритет
);
if (rc < 0)
{
printf("\t\tError %d (%s) mq_receive.\n", errno, strerror(errno));
exit(-1);
}
char* msg = (char*) calloc(strlen(buffer), sizeof(char)); // выделяем память (не 2048)
strcpy(msg, buffer); // msg = buffer
printf("\t\"message\": \"%s\" - сообщение получено успешно\n", msg);
return msg; // возвращаем строку (её нужно очищать)
}
void delete_message_queue(const char message_queue_name[])
{
printf("\t\"queue\": \"%s\" - очередь закрывается\n", message_queue_name);
if (mq_unlink(message_queue_name) < 0)
{
printf("Warning %d (%s) mq_unlink.\n", errno, strerror(errno));
}
printf("\t\"queue\": \"%s\" - очередь закрыта успешно\n", message_queue_name);
}
|
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab6/src/option5/src/main.c | <filename>lab6/src/option5/src/main.c
#include <unistd.h> //fork()
#include <sys/types.h>
#include <stdio.h> //printf()
#include <signal.h> //SIGUSR1
#include <math.h> //sqrt()
#include "message_queue/message_queue.h"
#include "my_ftoa/my_ftoa.h"
void my_handler(int nsig);
void input_a_b_c(double* a, double* b, double* c);
void send_a_b_c(double a, double b, double c);
void get_S();
void get_a_b_c();
int main()
{
pid_t pid;
// print 0
printf("::::: start [process 0] PID = %d PPID = %d :::::\n", getpid(), getppid());
signal(SIGUSR1, my_handler);
double a,b,c;
input_a_b_c(&a, &b, &c);
if ((pid = fork()) == -1) //процесс не создался
{
printf("Err\n");
}
else if (pid > 0) //в родительском процессе
{
printf("\t= = = = = start part 1 = = = = =\n");
printf("\t::::: start [parent process] PID = %d PPID = %d :::::\n", getpid(), getppid());
send_a_b_c(a, b, c);
printf("\t::::: kill [parent process] PID = %d PPID = %d :::::\n", getpid(), getppid());
printf("\t= = = = = end part 1 = = = = =\n");
kill(pid, SIGUSR1);
sleep(2);
printf("\t= = = = = start part 3 = = = = =\n");
printf("\t::::: respawn [parent process] PID = %d PPID = %d :::::\n", getpid(), getppid());
get_S();
printf("\t::::: end [parent process] PID = %d PPID = %d :::::\n", getpid(), getppid());
printf("\t= = = = = end part 3 = = = = =\n");
exit(0);
}
else if (pid == 0) //в дочернем процессе
{
printf("\t= = = = = start part 2 = = = = =\n");
printf("\t::::: start [child process] PID = %d PPID = %d :::::\n", getpid(), getppid());
get_a_b_c();
printf("\t::::: kill [child process] PID = %d PPID = %d :::::\n", getpid(), getppid());
printf("\t= = = = = end part 2 = = = = =\n");
kill(getppid(), SIGUSR1);
printf("\t= = = = = start part 4 = = = = =\n");
printf("\t::::: respawn [child process] PID = %d PPID = %d :::::\n", getpid(), getppid());
printf("\t::::: end [child process] PID = %d PPID = %d :::::\n", getpid(), getppid());
printf("\t= = = = = end part 4 = = = = =\n");
//exit(0);
}
printf("::::: end [process 0] PID = %d PPID = %d :::::\n", getpid(), getppid());
return 0;
}
void my_handler(int nsig)
{
printf("\t= = = = = my_handler = = = = =\n");
}
void input_a_b_c(double* a, double* b, double* c)
{
printf("a = ");
scanf("%lf", a); // ввод стороны треугольника A
printf("b = ");
scanf("%lf", b); // ввод стороны треугольника B
printf("c = ");
scanf("%lf", c); // ввод стороны треугольника С
if (!(*a + *b > *c)) // условие существование треугольника
{
printf("Not triangle\n");
printf("%lf * %lf not > %lf\n", *a, *b, *c);
printf("%lf not > %lf\n", *a + *b, *c);
printf("\n");
input_a_b_c(a, b, c);
return;
}
else
{
printf("Is triagle\n");
printf("%lf * %lf > %lf\n", *a, *b, *c);
printf("%lf > %lf\n", *a + *b, *c);
printf("\n");
}
}
void send_a_b_c(double a, double b, double c)
{
char* string_a = my_ftoa(a); // double to char*
char* string_b = my_ftoa(b); // double to char*
char* string_c = my_ftoa(c); // double to char*
mqd_t queue_send_a_b_c = get_opened_message_queue("/abc");// открытие очереди /abc
send_message_queue(string_a, queue_send_a_b_c); // отправка сообщения в очередь /abc
free(string_a); // очистка памяти
send_message_queue(string_b, queue_send_a_b_c); // отправка сообщения в очередь /abc
free(string_b); // очистка памяти
send_message_queue(string_c, queue_send_a_b_c); // отправка сообщения в очередь /abc
free(string_c); // очистка памяти
}
void get_S()
{
mqd_t queue_get_s = get_opened_message_queue("/s"); // открытие очереди /s
reveiving_message_queue(queue_get_s); // принятие сообщения из очереди /s
delete_message_queue("/s"); // удаление очереди /s
}
void get_a_b_c()
{
mqd_t bbb = get_opened_message_queue("/abc"); // открываю очередь /abc
char* msg_a = reveiving_message_queue(bbb); // получаю сообщение с очереди /abc
char* msg_b = reveiving_message_queue(bbb); // получаю сообщение с очереди /abc
char* msg_c = reveiving_message_queue(bbb); // получаю сообщение с очереди /abc
delete_message_queue("/abc"); // удаляем очередь /abc
float a = atof(msg_a); // char* to float
free(msg_a); // очистка памяти
float b = atof(msg_b); // char* to float
free(msg_b); // очистка памяти
float c = atof(msg_c); // char* to float
free(msg_c); // очистка памяти
float p = (a + b + c) / 2; // полупериметр
float S = sqrt( p * (p - a) * (p - b) * (p - c) ); // площадь через теорему Герона
printf(
"\nS = sqrt(\n\t%f *\n\t* (%f - %f) *\n\t* (%f - %f) *\n\t* (%f - %f)\n) = %f\n\n",
p, p, a, p, b, p, c, S
);
char* message_S = my_ftoa(S); // double to char*
mqd_t queue_s = get_opened_message_queue("/s"); // открытие очереди /s
send_message_queue(message_S, queue_s); // отправка сообщения в очередь /s
free(message_S); // очистка памяти
} |
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab6/src/option5/src/my_ftoa/my_ftoa.h | #ifndef __MY_FTOA_H__
#define __MY_FTOA_H__
#include <stdio.h> //sprintf() printf()
#include <stdlib.h> //calloc() free()
#include <string.h> //strlen() strcpy()
// функция преобразует float в строку и возвращает её (её надо очищать)
char* my_ftoa(float number);
#endif |
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab5/src/option5-part2/src/main.c | <gh_stars>0
// библиотеки
#include <stdio.h> //printf()
#include <unistd.h> //read()
#include <stdlib.h> //calloc(), free(), realloc(), rand()
#include <string.h> //strcmp(), strlen(), atoi(), strcat()
// прототипы
struct WordNode
{
char* word;
struct WordNode* left;
struct WordNode* right;
};
struct WordNode* WordNode__Constructor(struct WordNode* object, char* word);
struct WordNode* WordNode__Destructor(struct WordNode* object);
struct WordNode* WordNode__add_top(struct WordNode* object, char* word);
struct WordNode* WordNode__get_bottom(struct WordNode* object);
void WordNode__set_word(struct WordNode* object, char* word);
int get_depth_long_int(long int N);
char* get_string_with_number_hash(char* str, long int number);
// главная программа
int main()
{
struct WordNode* string_list = NULL;
struct WordNode* result = NULL;
int file_descriptor = 0;
const int buffer_size = 1;
char buffer[buffer_size];
int str_size = 0;
char* str = (char*) calloc(str_size, sizeof(char*));
if (str == NULL) printf("Память не выделилась\n");
while(read(file_descriptor, buffer, buffer_size))
{
char character = buffer[0];
if (character == '\n')
{
string_list = WordNode__add_top(string_list, str);
str_size = 0;
str = (char*) realloc(str, str_size * sizeof(char));
continue;
}
str_size += 1;
str = (char*) realloc(str, str_size * sizeof(char));
str[str_size - 1] = character;
}
free(str);
printf(" ~ ~ ~ ~ ~ file descriptor = 0 ~ ~ ~ ~ ~\n");
for(struct WordNode* temp = WordNode__get_bottom(string_list); temp != NULL; temp = temp->right)
{
printf("%s\n", temp->word);
}
for(struct WordNode* temp = WordNode__get_bottom(string_list); temp != NULL; temp = temp->right)
{
int str_size = strlen(temp->word);
char* str = (char*) calloc(str_size, sizeof(char));
if (str == NULL) printf("Память не выделилась\n");
strcpy(str, temp->word);
int a = 0, b = 1234567890;
int rand_number = rand() % (b - a + 1) + a;
str = get_string_with_number_hash(str, rand_number);
WordNode__set_word(temp, str);
free(str);
}
for (struct WordNode* temp = WordNode__get_bottom(string_list); temp != NULL; temp = temp->right)
{
str_size = 0;
str = (char*) calloc(str_size, sizeof(char));
if (str == NULL) printf("Память не выделилась\n");
struct WordNode* words_list = NULL;
for (int i = 0; ; i++)
{
char ch = temp->word[i];
if (ch == '\0') break;
if (ch == ' ')
{
words_list = WordNode__add_top(words_list, str);
str_size = 0;
str = (char*) realloc(str, str_size * sizeof(char));
continue;
}
str_size += 1;
str = (char*) realloc(str, str_size * sizeof(char));
str[str_size - 1] = ch;
}
int number = atoi( WordNode__get_bottom(words_list)->word );
if( number != 0 && number % 2 == 0 )
{
result = WordNode__add_top(result, temp->word);
}
words_list = WordNode__Destructor(words_list);
free(str);
}
string_list = WordNode__Destructor(string_list);
printf(" ~ ~ ~ ~ ~ file descriptor = 1 ~ ~ ~ ~ ~\n");
for(struct WordNode* temp = WordNode__get_bottom(result); temp != NULL; temp = temp->right)
{
int file_descriptor = 1;
char* buf = temp->word;
int buf_size = strlen(buf);
write(file_descriptor, buf, buf_size);
write(file_descriptor, "\n", 1);
}
result = WordNode__Destructor(result);
return 0;
}
// реализация прототипов
struct WordNode* WordNode__Constructor(struct WordNode* object, char* word)
{
object = (struct WordNode*) malloc(sizeof(struct WordNode));
if (object == NULL) printf("Память не выделилась\n");
//printf("%p Constructor\n", object);
if (object == NULL)
{
printf("Не выделилась память\n");
}
object->left = NULL;
object->right = NULL;
object->word = (char*) calloc(strlen(word), sizeof(char));
if (object->word == NULL) printf("Память не выделилась\n");
if (object->word == NULL)
{
printf("Не выделилась память\n");
}
strcpy(object->word, word);
return object;
}
struct WordNode* WordNode__Destructor(struct WordNode* object)
{
for (struct WordNode* temp = object; temp != NULL; )
{
free(temp->word);
object = temp;
//printf("%p Destructor\n", object);
temp = temp->left;
free(object);
}
return NULL;
}
struct WordNode* WordNode__add_top(struct WordNode* object, char* word)
{
if (word == NULL)
{
return object;
}
if (word[0] == '\0')
{
return object;
}
struct WordNode* new_node = WordNode__Constructor(new_node, word);
new_node->left = object;
if (object == NULL)
{
return new_node;
}
object->right = new_node;
return new_node;
}
struct WordNode* WordNode__get_bottom(struct WordNode* object)
{
if (object == NULL)
{
return NULL;
}
struct WordNode* temp = object;
while(temp->left != NULL)
{
temp = temp->left;
}
return temp;
}
void WordNode__set_word(struct WordNode* object, char* word)
{
free(object->word);
object->word = (char*) calloc(strlen(word), sizeof(char));
if ( object->word == NULL )
{
printf("Память не выделилась\n");
return;
}
strcpy(object->word, word);
}
int get_depth_long_int(long int N)
{
int i = 0;
for( ; N>0; N = N / 10)
{
++i;
}
return i;
}
char* get_string_with_number_hash(char* str, long int number)
{
int len = get_depth_long_int(number);
char* substr = (char*) calloc(len, sizeof(char));
if (substr == NULL) printf("Память не выделилась\n");
long int N = number;
for (int i = 0; i < len; i += 1)
{
char ch;
switch(N % 10)
{
case 0: ch = '0'; break;
case 1: ch = '1'; break;
case 2: ch = '2'; break;
case 3: ch = '3'; break;
case 4: ch = '4'; break;
case 5: ch = '5'; break;
case 6: ch = '6'; break;
case 7: ch = '7'; break;
case 8: ch = '8'; break;
case 9: ch = '9'; break;
default: ch = '_';
}
N = N / 10;
substr[i] = ch;
}
char* result = (char*) calloc(len, sizeof(char));
if (result == NULL) printf("Память не выделилась\n");
for (int i = 0; i < len; i++)
{
result[i] = substr[(len - 1) - i];
}
free(substr);
str = (char*) realloc(str, (5 + len) * sizeof(char));
strcat(str, result);
free(result);
return str;
}
|
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab7/src/option5/one.c | #include <unistd.h>
#include <stdio.h> //printf()
#include <stdlib.h> //rand()
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <semaphore.h>
#include <pthread.h>
#include <time.h> //time(), localtime
int get_random(int a, int b);
void print_real_time();
int main()
{
sem_t* get = sem_open(
"sem_one", //const char* name
O_CREAT, //int oflag
0777, //mode_t mode
0 //unsigned int value
);
sem_t* put = sem_open(
"sem_two", //const char* name
O_CREAT, //int oflag
0777, //mode_t mode
0 //unsigned int value
);
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);
sem_post(put);
(void)umask(0);
while (1)
{
sem_wait(put);
print_real_time(); //печать реального времени
printf("Enter the symbol: ");
pthread_mutex_lock(&mutex);
int fd = open( //открываем файл
"file.bin", //*.bin - бинарный файл
O_CREAT | O_WRONLY,
0777 //- rwx rwx rwx (0 111 111 111)
);
//Если вводить по одному символу,
//то сообщение может отправляться несколько раз,
//при вводе нескольких символов (а не одного).
//Эту проблему решает строка.
char str[1024]; //инициализировали строку
scanf("%s", str); //вводим строку
char character = str[0]; //взяли первый символ со строки
int rand_number = get_random(1, 35); //рандомное число [1; 35]
print_real_time(); //печать реального времени
printf( //печать сообщения об отправке
"Process %d send random_number: %d\n\n",
getpid(), //PID - номер процесса
rand_number //рандомное число
);
char msg[1024]; //инициализация строки для сообщения
sprintf(msg, "%d", rand_number); //в сообщение записали рандомное число
write(fd, msg, sizeof(msg)); //записали сообщение в файл
close(fd); //закрываем файл
pthread_mutex_unlock(&mutex);
sem_post(get);
}
pthread_mutex_destroy(&mutex);
sem_close(put);
sem_close(get);
return 0;
}
int get_random(int x1, int x2)
{
int a = x1 < x2 ? x1 : x2; //a = min(a, b)
int b = x1 > x2 ? x1 : x2; //b = max(a, b)
return rand() % (b - a + 1) + a; //random [a; b]
}
void print_real_time()
{
time_t now = time(0);
struct tm *ltm = localtime(&now);
printf(
"%02d:%02d:%02d : ",
1 + ltm->tm_hour, // часы
1 + ltm->tm_min, // минуты
1 + ltm->tm_sec // секунды
);
} |
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab6/src/option5-mod/src/app1.c | #include <stdio.h> // printf() scanf()
#include <stdlib.h> // free()
#include "message_queue/message_queue.h"
#include "my_ftoa/my_ftoa.h"
#include "print_real_time/print_real_time.h"
int main(void)
{
double a, b, c; // стороны треугольника
printf("a = ");
scanf("%lf", &a); // ввод стороны треугольника A
printf("b = ");
scanf("%lf", &b); // ввод стороны треугольника B
printf("c = ");
scanf("%lf", &c); // ввод стороны треугольника С
if (!(a + b > c)) // условие существование треугольника
{
printf("Not triangle\n");
return 0;
}
char* string_a = my_ftoa(a); // double to char*
char* string_b = my_ftoa(b); // double to char*
char* string_c = my_ftoa(c); // double to char*
print_real_time();
mqd_t queue_send_a_b_c = get_opened_message_queue("/abc"); // открытие очереди /abc
print_real_time();
send_message_queue(string_a, queue_send_a_b_c); // отправка сообщения в очередь /abc
free(string_a); // очистка памяти
print_real_time();
send_message_queue(string_b, queue_send_a_b_c); // отправка сообщения в очередь /abc
free(string_b); // очистка памяти
print_real_time();
send_message_queue(string_c, queue_send_a_b_c); // отправка сообщения в очередь /abc
free(string_c); // очистка памяти
print_real_time();
mqd_t queue_get_s = get_opened_message_queue("/s"); // открытие очереди /s
print_real_time();
reveiving_message_queue(queue_get_s); // принятие сообщения из очереди /s
print_real_time();
delete_message_queue("/s"); // удаление очереди /s
return 0;
} |
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab6/src/option5-mod/src/print_real_time/print_real_time.c | <gh_stars>0
#include "print_real_time.h"
void print_real_time()
{
time_t now = time(0);
struct tm *ltm = localtime(&now);
printf(
"%02d:%02d:%02d\n",
1 + ltm->tm_hour, // часы
1 + ltm->tm_min, // минуты
1 + ltm->tm_sec // секунды
);
} |
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab5/src/example1/src/main.c | /* Программа, иллюстрирующая использование системных вызовов open(), write() и close() для записи информации в файл */
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
int main(){
int fd;
size_t size;
char string[] = "Hello, world!";
/* Обнуляем маску создания файлов текущего процесса для того, чтобы права доступа у создаваемого файла точно соответствовали параметру вызова open() */
(void)umask(0);
/* Попытаемся открыть файл с именем myfile в текущей директории только для операций вывода. Если файла не существует, попробуем его создать с правами доступа 0666, т. е. read-write для всех категорий пользователей */
if((fd = open("myfile", O_WRONLY | O_CREAT, 0666)) < 0)
{
/* Если файл открыть не удалось, печатаем об этом сообщение и прекращаем работу */
printf("Can\'t open file\n");
exit(-1);
}
/* Пробуем записать в файл 14 байт из нашего массива, т.е. всю строку "Hello, world!" вместе с признаком конца строки */
size = write(fd, string, 14);
if(size != 14)
{
/* Если записалось меньшее количество байт, сообщаем об ошибке */
printf("Can\'t write all string\n");
exit(-1);
}
/* Закрываем файл */
if(close(fd) < 0)
{
printf("Can\'t close file\n");
}
return 0;
} |
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab6/src/option5-mod/src/app2.c | <gh_stars>0
#include <math.h> // sqrt()
#include "message_queue/message_queue.h"
#include "my_ftoa/my_ftoa.h"
#include "print_real_time/print_real_time.h"
int main(void)
{
print_real_time();
mqd_t bbb = get_opened_message_queue("/abc"); // открываю очередь /abc
print_real_time();
char* msg_a = reveiving_message_queue(bbb); // получаю сообщение с очереди /abc
print_real_time();
char* msg_b = reveiving_message_queue(bbb); // получаю сообщение с очереди /abc
print_real_time();
char* msg_c = reveiving_message_queue(bbb); // получаю сообщение с очереди /abc
print_real_time();
delete_message_queue("/abc"); // удаляем очередь /abc
float a = atof(msg_a); // char* to float
free(msg_a); // очистка памяти
float b = atof(msg_b); // char* to float
free(msg_b); // очистка памяти
float c = atof(msg_c); // char* to float
free(msg_c); // очистка памяти
float p = (a + b + c) / 2; // полупериметр
float S = sqrt( p * (p - a) * (p - b) * (p - c) ); // площадь через теорему Герона
printf(
"\nS = sqrt(\n\t%f *\n\t* (%f - %f) *\n\t* (%f - %f) *\n\t* (%f - %f)\n) = %f\n\n",
p, p, a, p, b, p, c, S
);
char* message_S = my_ftoa(S); // double to char*
print_real_time();
mqd_t queue_s = get_opened_message_queue("/s"); // открытие очереди /s
print_real_time();
send_message_queue(message_S, queue_s); // отправка сообщения в очередь /s
free(message_S); // очистка памяти
return 0;
} |
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab4/src/kalkul2/app/calculate.c | <filename>lab4/src/kalkul2/app/calculate.c
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "calculate.h"
float Calculate(float Numeral, char Operation[4])
{
float SecondNumeral;
if( strncmp(Operation, "+", 1) == 0 )
{
printf("Второе слагаемое: ");
scanf("%f",&SecondNumeral);
return(Numeral + SecondNumeral);
}
else if( strncmp(Operation, "- ", 1) == 0 )
{
printf("Вычитаемое: ");
scanf("%f",&SecondNumeral);
return(Numeral - SecondNumeral);
}
else if( strncmp(Operation, "*", 1) == 0 )
{
printf("Множитель: ");
scanf("%f",&SecondNumeral);
return(Numeral * SecondNumeral);
}
else if( strncmp(Operation, "/", 1) == 0 )
{
printf("Делитель: ");
scanf("%f",&SecondNumeral);
if(SecondNumeral == 0)
{
printf("Ошибка: деление на ноль! ");
return(HUGE_VAL);
}
else
return(Numeral / SecondNumeral);
}
else if(strncmp(Operation, "pow", 3) == 0)
{
printf("Степень: ");
scanf("%f",&SecondNumeral);
return(pow(Numeral, SecondNumeral));
}
else if( strncmp(Operation, "sqrt", 4) == 0 )
return(sqrt(Numeral));
else if( strncmp(Operation, "sin", 3) == 0 )
return(sin(Numeral));
else if( strncmp(Operation, "cos", 3) == 0 )
return(cos(Numeral));
else if( strncmp(Operation, "tan", 3) == 0 )
return(tan(Numeral));
else
{
printf("Неправильно введено действие ");
return(HUGE_VAL);
}
}
|
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab5/src/option10-part3/src/main.c | <reponame>Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming
#include <stdio.h> //printf()
#include <stdlib.h> //calloc(), free()
#include <string.h> //strcpy()
int main(int argc, char* argv[])
{
if (argc <= 1)
{
printf("\nАргументы не переданы\n");
return 0;
}
for (int i = 1; i < argc; i++)
{
char* word = (char*) calloc(strlen(argv[i]), sizeof(char));
strcpy(word, argv[i]);
int a = 1;
int b = strlen(word) - 2;
for (int ii = a; ii < b; ii++)
{
int r = rand() % (b - a + 1) + a;
char temp = word[ii];
word[ii] = word[r];
word[r] = temp;
}
printf("| %-16s | %-16s |\n", argv[i], word);
free(word);
}
return 0;
}
|
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab6/src/option5/src/message_queue/message_queue.h | <reponame>Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming
#ifndef __MESSAGE_QUEUE_H__
#define __MESSAGE_QUEUE_H__
#include <stdio.h> // printf()
#include <stdlib.h> // exit()
#include <string.h> // strlen()
#include <errno.h> // strerror() errno
#include <mqueue.h> // mq_open() mq_send() mq_receive() mq_unlink()
// функция открывает очередь по строке и возвращает номер очереди
mqd_t get_opened_message_queue(const char message_queue_name[]);
// функция отправляет сообзение в очередь
void send_message_queue(const char message[], mqd_t sndHndl);
// функция принимает сообщение из очереди и возвращает строку (её нужно очищать!)
char* reveiving_message_queue(mqd_t rcHndl);
// функция удаляет очередь
void delete_message_queue(const char message_queue_name[]);
#endif |
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab4/src/kalkul2/app/calculate.h | <filename>lab4/src/kalkul2/app/calculate.h
#ifndef CALCULATE_H_
#define CALCULATE_H_
float Calculate(float Numeral, char Operation[4]);
#endif /* CALCULATE_H_ */
|
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab6/src/option5/src/my_ftoa/my_ftoa.c | <gh_stars>0
#include "my_ftoa.h"
char* my_ftoa(float number)
{
char* str = (char*) calloc(100, sizeof(char)); // выделяем память под строку
if (str == NULL) // выделилась память?
{
printf("Память не выделилась\n");
return NULL;
}
sprintf(str, "%f", number); // копируем float в строку
char* result = (char*) calloc(strlen(str), sizeof(char));// строка уже не длинны 100
if (str == NULL) // память выделилась
{
printf("Память не выделилась\n");
return NULL;
}
strcpy(result, str); // result = str
free(str); // очищаем память
return result; // возвращем строку (её надо очищать!)
} |
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab4/src/kalkul2/app/main.c | #include <stdio.h>
#include "calculate.h"
int main(void)
{
float Numeral;
char Operation[4];
float Result;
printf("Число: ");
scanf("%f",&Numeral);
printf("Арифметическое действие (+,– ,*,/,pow,sqrt,sin,cos,tan): ");
scanf("%s",&Operation);
Result = Calculate(Numeral, Operation);
printf("%6.2f\n",Result);
return 0;
}
|
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab6/src/option5-mod/src/print_real_time/print_real_time.h | <filename>lab6/src/option5-mod/src/print_real_time/print_real_time.h
#ifndef __PRINT_REAL_TIME_H__
#define __PRINT_REAL_TIME_H__
#include <time.h> // time() localtime()
#include <stdio.h> // printf()
//функция печатает время: "чч:мм:сс\n"
void print_real_time();
#endif |
jetpropulsion/ComScan | Metrics.h | #pragma once
#include <cstdint>
#define MAX_CHARS_PER_1_UNSIGNED_BYTE 3 //255
#define MAX_CHARS_PER_2_UNSIGNED_BYTES 5 //65,535
#define MAX_CHARS_PER_3_UNSIGNED_BYTES 8 //16,777,215
#define MAX_CHARS_PER_4_UNSIGNED_BYTES 10 //4,294,967,295
#define MAX_CHARS_PER_5_UNSIGNED_BYTES 13 //1,099,511,627,775
#define MAX_CHARS_PER_6_UNSIGNED_BYTES 15 //281,474,976,710,655
#define MAX_CHARS_PER_7_UNSIGNED_BYTES 17 //72,057,594,037,927,935
#define MAX_CHARS_PER_8_UNSIGNED_BYTES 20 //18,446,744,073,709,551,615
#define MAX_CHARS_PER_1_SIGNED_BYTE 4 //-127
#define MAX_CHARS_PER_2_SIGNED_BYTES 6 //-32,767
#define MAX_CHARS_PER_3_SIGNED_BYTES 8 //-8,388,607
#define MAX_CHARS_PER_4_SIGNED_BYTES 11 //-2,147,483,647
#define MAX_CHARS_PER_5_SIGNED_BYTES 13 //-549,755,813,887
#define MAX_CHARS_PER_6_SIGNED_BYTES 16 //-140,737,488,355,327
#define MAX_CHARS_PER_7_SIGNED_BYTES 18 //-36,028,797,018,963,967
#define MAX_CHARS_PER_8_SIGNED_BYTES 20 //-9,223,372,036,854,775,807
#define MAX_CHARS_PER_1_BYTE MAX_CHARS_PER_1_SIGNED_BYTE
#define MAX_CHARS_PER_2_BYTES MAX_CHARS_PER_2_SIGNED_BYTES
#define MAX_CHARS_PER_3_BYTES MAX_CHARS_PER_3_SIGNED_BYTES
#define MAX_CHARS_PER_4_BYTES MAX_CHARS_PER_4_SIGNED_BYTES
#define MAX_CHARS_PER_5_BYTES MAX_CHARS_PER_5_SIGNED_BYTES
#define MAX_CHARS_PER_6_BYTES MAX_CHARS_PER_6_SIGNED_BYTES
#define MAX_CHARS_PER_7_BYTES MAX_CHARS_PER_7_SIGNED_BYTES
#define MAX_CHARS_PER_8_BYTES MAX_CHARS_PER_8_SIGNED_BYTES
#define MAX_CHARS_PER_SID 1+1+(MAX_CHARS_PER_1_BYTE+1)*2+(MAX_CHARS_PER_6_BYTES+1)+(MAX_CHARS_PER_4_BYTES+1)*SID_MAX_SUB_AUTHORITIES+1
#define MAX_CHARS_PER_GUID 1+(8+1)+((4+1)*3)+(12)+1
/*
#define MAX_CHARS_PER_GUID 1 +\ // '{'
8 +\ // "01234567"
1 +\ // '-'
4 +\ // "0123"
1 +\ // '-'
4 +\ // "0123"
1 +\ // '-'
4 +\ // "0123"
1 +\ // '-'
12 +\ // "012345678901"
1 // '}'
*/
#define MAX_GUID_STRING_LENGTH_W ( MAX_CHARS_PER_GUID * sizeof(wchar_t) )
#define MAX_GUID_STRING_LENGTH_A ( MAX_CHARS_PER_GUID * sizeof(char) )
#define MAX_GUID_STRING_SIZE_W ( (MAX_CHARS_PER_GUID + 1) * sizeof(wchar_t) )
#define MAX_GUID_STRING_SIZE_A ( (MAX_CHARS_PER_GUID + 1) * sizeof(char) )
#if( defined(UNICODE) )
#define MAX_GUID_STRING_LEN MAX_GUID_STRING_LENGTH_W
#define MAX_GUID_STRING_SIZE MAX_GUID_STRING_SIZE_W
#else
#define MAX_GUID_STRING_LEN MAX_GUID_STRING_LENGTH_A
#define MAX_GUID_STRING_SIZE MAX_GUID_STRING_SIZE_A
#endif
#define KiB (* 1024)
#define MiB (KiB * 1024)
#define GiB (MiB * 1024)
#define TiB (GiB * 1024)
#define KB (* 1000)
#define MB (KB * 1000)
#define GB (MB * 1000)
#define TB (GB * 1000)
|
jetpropulsion/ComScan | Format.h | #pragma once
#include "Metrics.h"
#include <ios>
#include <iomanip>
#define JETLIB_ALIGN_FORMAT std::left
#define JETLIB_MAX_ALIGN_FORMAT std::right
#define JETLIB_RESET_FORMATW JETLIB_ALIGN_FORMAT << std::dec << std::setw(0) << std::setfill(L' ') << std::setprecision(0)
#define JETLIB_0000_FORMATW JETLIB_ALIGN_FORMAT << std::dec << std::setw(4) << std::setfill(L'0')
#define JETLIB_000_FORMATW JETLIB_ALIGN_FORMAT << std::dec << std::setw(3) << std::setfill(L'0')
#define JETLIB_00_FORMATW JETLIB_ALIGN_FORMAT << std::dec << std::setw(2) << std::setfill(L'0')
#define JETLIB_INT8_FORMATW JETLIB_ALIGN_FORMAT << std::noshowbase << std::setfill(L' ') << std::dec << std::setw( 1 )
#define JETLIB_INT16_FORMATW JETLIB_ALIGN_FORMAT << std::noshowbase << std::setfill(L' ') << std::dec << std::setw( 1 )
#define JETLIB_INT32_FORMATW JETLIB_ALIGN_FORMAT << std::noshowbase << std::setfill(L' ') << std::dec << std::setw( 1 )
#define JETLIB_INT64_FORMATW JETLIB_ALIGN_FORMAT << std::noshowbase << std::setfill(L' ') << std::dec << std::setw( 1 )
#define JETLIB_MAX_INT8_FORMATW JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::setfill(L' ') << std::dec << std::setw(MAX_CHARS_PER_1_SIGNED_BYTE)
#define JETLIB_MAX_INT16_FORMATW JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::setfill(L' ') << std::dec << std::setw(MAX_CHARS_PER_2_SIGNED_BYTES)
#define JETLIB_MAX_INT32_FORMATW JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::setfill(L' ') << std::dec << std::setw(MAX_CHARS_PER_4_SIGNED_BYTES)
#define JETLIB_MAX_INT64_FORMATW JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::setfill(L' ') << std::dec << std::setw(MAX_CHARS_PER_8_SIGNED_BYTES)
#define JETLIB_UINT8_FORMATW JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::uppercase << L"0x" << std::setfill(L'0') << std::nouppercase << std::hex << std::setw(2 * sizeof(uint8_t))
#define JETLIB_UINT16_FORMATW JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::uppercase << L"0x" << std::setfill(L'0') << std::nouppercase << std::hex << std::setw(2 * sizeof(uint16_t))
#define JETLIB_UINT32_FORMATW JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::uppercase << L"0x" << std::setfill(L'0') << std::nouppercase << std::hex << std::setw(2 * sizeof(uint32_t))
#define JETLIB_UINT64_FORMATW JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::uppercase << L"0x" << std::setfill(L'0') << std::nouppercase << std::hex << std::setw(2 * sizeof(uint64_t))
#define JETLIB_FLOAT_FORMATW JETLIB_ALIGN_FORMAT << std::noshowbase << std::setfill(L' ') << std::dec << std::setw( 1 ) << std::setprecision(20) << std::resetiosflags(4096)
#define JETLIB_DOUBLE_FORMATW JETLIB_ALIGN_FORMAT << std::noshowbase << std::setfill(L' ') << std::dec << std::setw( 1 ) << std::setprecision(20) << std::resetiosflags(4096)
#define JETLIB_PTR_FORMATW JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::uppercase << L"0x" << std::setfill(L'0') << std::nouppercase << std::hex << std::setw(2 * sizeof(PVOID))
#define JETLIB_RESET_FORMATA JETLIB_ALIGN_FORMAT << std::dec << std::setw(0) << std::setfill(' ') << std::setprecision(0)
#define JETLIB_0000_FORMATA JETLIB_ALIGN_FORMAT << std::dec << std::setw(4) << std::setfill('0')
#define JETLIB_000_FORMATA JETLIB_ALIGN_FORMAT << std::dec << std::setw(3) << std::setfill('0')
#define JETLIB_00_FORMATA JETLIB_ALIGN_FORMAT << std::dec << std::setw(2) << std::setfill('0')
#define JETLIB_INT8_FORMATA JETLIB_ALIGN_FORMAT << std::noshowbase << std::setfill(' ') << std::dec << std::setw( 1 )
#define JETLIB_INT16_FORMATA JETLIB_ALIGN_FORMAT << std::noshowbase << std::setfill(' ') << std::dec << std::setw( 1 )
#define JETLIB_INT32_FORMATA JETLIB_ALIGN_FORMAT << std::noshowbase << std::setfill(' ') << std::dec << std::setw( 1 )
#define JETLIB_INT64_FORMATA JETLIB_ALIGN_FORMAT << std::noshowbase << std::setfill(' ') << std::dec << std::setw( 1 )
#define JETLIB_MAX_INT8_FORMATA JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::setfill(' ') << std::dec << std::setw( MAX_CHARS_PER_1_SIGNED_BYTE )
#define JETLIB_MAX_INT16_FORMATA JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::setfill(' ') << std::dec << std::setw( MAX_CHARS_PER_2_SIGNED_BYTES )
#define JETLIB_MAX_INT32_FORMATA JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::setfill(' ') << std::dec << std::setw( MAX_CHARS_PER_4_SIGNED_BYTES )
#define JETLIB_MAX_INT64_FORMATA JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::setfill(' ') << std::dec << std::setw( MAX_CHARS_PER_8_SIGNED_BYTES )
#define JETLIB_UINT8_FORMATA JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::uppercase << "0x" << std::setfill('0') << std::nouppercase << std::hex << std::setw(2 * sizeof(uint8_t))
#define JETLIB_UINT16_FORMATA JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::uppercase << "0x" << std::setfill('0') << std::nouppercase << std::hex << std::setw(2 * sizeof(uint16_t))
#define JETLIB_UINT32_FORMATA JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::uppercase << "0x" << std::setfill('0') << std::nouppercase << std::hex << std::setw(2 * sizeof(uint32_t))
#define JETLIB_UINT64_FORMATA JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::uppercase << "0x" << std::setfill('0') << std::nouppercase << std::hex << std::setw(2 * sizeof(uint64_t))
#define JETLIB_FLOAT_FORMATA JETLIB_ALIGN_FORMAT << std::noshowbase << std::setfill(' ') << std::dec << std::setw( 1 ) << std::setprecision(20) << std::resetiosflags(4096)
#define JETLIB_DOUBLE_FORMATA JETLIB_ALIGN_FORMAT << std::noshowbase << std::setfill(' ') << std::dec << std::setw( 1 ) << std::setprecision(20) << std::resetiosflags(4096)
#define JETLIB_PTR_FORMATA JETLIB_MAX_ALIGN_FORMAT << std::noshowbase << std::uppercase << "0x" << std::setfill('0') << std::nouppercase << std::hex << std::setw(2 * sizeof(PVOID))
#if(defined(_UNICODE))
#define JETLIB_RESET_FORMAT JETLIB_RESET_FORMATW
#define JETLIB_0000_FORMAT JETLIB_0000_FORMATW
#define JETLIB_000_FORMAT JETLIB_000_FORMATW
#define JETLIB_00_FORMAT JETLIB_00_FORMATW
#define JETLIB_INT8_FORMAT JETLIB_INT8_FORMATW
#define JETLIB_INT16_FORMAT JETLIB_INT16_FORMATW
#define JETLIB_INT32_FORMAT JETLIB_INT32_FORMATW
#define JETLIB_INT64_FORMAT JETLIB_INT64_FORMATW
#define JETLIB_MAX_INT8_FORMAT JETLIB_MAX_INT8_FORMATW
#define JETLIB_MAX_INT16_FORMAT JETLIB_MAX_INT16_FORMATW
#define JETLIB_MAX_INT32_FORMAT JETLIB_MAX_INT32_FORMATW
#define JETLIB_MAX_INT64_FORMAT JETLIB_MAX_INT64_FORMATW
#define JETLIB_UINT16_FORMAT JETLIB_UINT16_FORMATW
#define JETLIB_UINT32_FORMAT JETLIB_UINT32_FORMATW
#define JETLIB_UINT64_FORMAT JETLIB_UINT64_FORMATW
#define JETLIB_FLOAT_FORMAT JETLIB_FLOAT_FORMATW
#define JETLIB_DOUBLE_FORMAT JETLIB_DOUBLE_FORMATW
#define JETLIB_PTR_FORMAT JETLIB_PTR_FORMATW
#else
#define JETLIB_RESET_FORMAT JETLIB_RESET_FORMATA
#define JETLIB_0000_FORMAT JETLIB_0000_FORMATA
#define JETLIB_000_FORMAT JETLIB_000_FORMATA
#define JETLIB_00_FORMAT JETLIB_00_FORMATA
#define JETLIB_INT8_FORMAT JETLIB_INT8_FORMATA
#define JETLIB_INT16_FORMAT JETLIB_INT16_FORMATA
#define JETLIB_INT32_FORMAT JETLIB_INT32_FORMATA
#define JETLIB_INT64_FORMAT JETLIB_INT64_FORMATA
#define JETLIB_MAX_INT8_FORMAT JETLIB_MAX_INT8_FORMATA
#define JETLIB_MAX_INT16_FORMAT JETLIB_MAX_INT16_FORMATA
#define JETLIB_MAX_INT32_FORMAT JETLIB_MAX_INT32_FORMATA
#define JETLIB_MAX_INT64_FORMAT JETLIB_MAX_INT64_FORMATA
#define JETLIB_UINT8_FORMAT JETLIB_UINT8_FORMATA
#define JETLIB_UINT16_FORMAT JETLIB_UINT16_FORMATA
#define JETLIB_UINT32_FORMAT JETLIB_UINT32_FORMATA
#define JETLIB_UINT64_FORMAT JETLIB_UINT64_FORMATA
#define JETLIB_FLOAT_FORMAT JETLIB_FLOAT_FORMATA
#define JETLIB_DOUBLE_FORMAT JETLIB_DOUBLE_FORMATA
#define JETLIB_PTR_FORMAT JETLIB_PTR_FORMATA
#endif
|
jetpropulsion/ComScan | CRC32.h | <reponame>jetpropulsion/ComScan
#pragma once
#include <cstdint>
#include "JetLib.h"
namespace JetLib
{
namespace Hash
{
class CRC32
{
public:
typedef enum CRC32Poly : uint32_t
{
ANSI = 0x04C11DB7, //ANSI X3.66, default
ANSI_Rev = 0xEDB88320, //ANSI X3.66, reversed poly
ANSI_RevRec = 0x82608EDB, //ANSI X3.66, reversed poly and reciprocal
CRC32_C = 0x1EDC6F41, //CRC32-C (Castagnoli), default
CRC32_C_Rev = 0x82F63B78, //CRC32-C (Castagnoli), reversed poly
CRC32_C_RevRec = 0x8F6E37A0, //CRC32-C (Castagnoli), reversed poly and reciprocal
}
CRC32Poly;
protected:
uint32_t Table[ 256 ];
uint32_t TablePoly;
uint32_t Accumulator;
bool TableInitialized;
protected:
virtual void Init(uint32_t Polynomial)
{
uint32_t remainder;
uint8_t b = 0;
do
{
remainder = b;
for(uint32_t bit = 8; bit > 0; --bit)
{
uint32_t const lsb = (remainder & 1);
remainder = (remainder >> 1);
remainder ^= Polynomial * lsb;
}
this->Table[ (uint8_t)b ] = remainder;
}
while(++b != 0);
this->TablePoly = Polynomial;
this->Accumulator = 0;
this->TableInitialized = true;
}
protected:
typedef uint32_t (JetLib::Hash::CRC32::*XorFunction)(uint32_t crc32);
virtual uint32_t XorInvert(uint32_t crc32)
{
return crc32 ^ static_cast<uint32_t>(-1);
}
XorFunction JetLib::Hash::CRC32::XorIn;
XorFunction JetLib::Hash::CRC32::XorOut;
public:
//Used in initial call and/or when small data needs to be hashed, i.e. during this function call
virtual uint32_t Update(uint8_t const *data, size_t data_size)
{
DYNAMIC_ASSERT(this->TableInitialized);
return (this->Accumulator = this->Update(data, data_size, (this->*XorIn)(0)));
}
//More flexible version of Update(), allowing previous or algorithmic CRC32 to be provided and mixed in LFSR chain
virtual uint32_t Update(uint8_t const *data, size_t data_size, uint32_t crc)
{
DYNAMIC_ASSERT(this->TableInitialized);
for(size_t i = 0; i < data_size; i++)
{
crc = this->Table[data[i] ^ (crc & 0xff)] ^ (crc >> 8);
}
return (this->Accumulator = (this->*XorOut)(crc));
}
//Reset and rebuild internal lookup polynomial table
virtual void Reset()
{
DYNAMIC_ASSERT(this->TableInitialized);
this->Init(this->TablePoly);
}
//Reset and rebuild internal lookup polynomial table using provided and well known CRC polynomial value
virtual void Reset(CRC32Poly const crc32_type)
{
this->Init(crc32_type);
}
private:
//Parameterless constructor is not intended to be used by public
explicit CRC32() :
XorIn(&JetLib::Hash::CRC32::XorInvert),
XorOut(&JetLib::Hash::CRC32::XorInvert),
TableInitialized(false),
Accumulator(0),
TablePoly(0)
{
}
public:
CRC32(CRC32Poly const crc32_type = CRC32Poly::ANSI) :
XorIn(&JetLib::Hash::CRC32::XorInvert),
XorOut(&JetLib::Hash::CRC32::XorInvert),
TableInitialized(false),
Accumulator(0),
TablePoly(0)
{
this->Init(crc32_type);
}
virtual ~CRC32()
{
zeromem(this->TablePoly);
zeromem(this->Table);
}
virtual uint32_t Get() const
{
return this->Accumulator;
}
}; //END: class JetLib::Hash::CRC32 {
}; //END: namespace JetLib::Hash {
}; //END: namespace JetLib {
|
jetpropulsion/ComScan | JetLib.h | <filename>JetLib.h
#pragma once
#include <cassert>
//Macro LINE_INFO can provide information about file and line where possible error occured
#define LINE_SEPARATOR ", "
#define LINE_INFO __FILE__ LINE_SEPARATOR _CRT_STRINGIZE(__LINE__)
//Macro WIN32_ASSERT(expression) provides single line Win32 API return value checking, throwing std::exception with code position when the exception occurs
#define WIN32_ASSERT(expression)\
::SetLastError(NO_ERROR);\
if(!(expression))\
{\
throw std::exception(LINE_INFO);\
}
//Macro WIN32_ASSERT_VALUE(expression) is similar to WIN32_ASSERT, except it doesn't automatically clear last error field in TEB, useful for more complex checking
#define WIN32_ASSERT_VALUE(expression)\
if(!(expression))\
{\
throw std::exception(LINE_INFO);\
}
//Macro DYNAMIC_ASSERT(expression) throws exception when expression is false (#__VA_ARGS__ passes arguments as is, i.e. without expanding definition)
#define DYNAMIC_ASSERT(expression)\
if(!(expression))\
{\
throw std::exception(LINE_INFO);\
}
//Macro STATIC_ASSERT(expression) prevents compiling when irregular state of the expected values is not met (example: { STATIC_ASSERT(sizeof(void*) != sizeof(char)); })
#define STATIC_ASSERT(...)\
static_assert(__VA_ARGS__, #__VA_ARGS__)
//Inline helper, returns length of array provided, similar to (sizeof(TypeArray) / sizeof(TypeArray[0]))
template<std::size_t N, class T>
constexpr inline std::size_t lengthof(T const (&TypeArray)[N])
{
UNREFERENCED_PARAMETER(TypeArray);
return N;
}
//Inline helper, sets all array members to zero
template<std::size_t N, class T>
inline void zeromem(T (&TypeArray)[N])
{
std::size_t const TypeArraySize = N * sizeof(T);
STATIC_ASSERT(TypeArraySize == sizeof(TypeArray));
//::RtlZeroMemory(&TypeArray, TypeArraySize); //NOTE: use RtlZeroMemory() only when you know for sure that memory blocks will be very huge (> 64KiB in 2016.)
::memset(&TypeArray, 0, TypeArraySize);
}
template<class T>
constexpr inline void zeromem(T &Type)
{
::memset(&Type, 0, sizeof(T));
}
|
BlightsteelColossus-dev/MapReduce-in-C | actual_mapping.c |
void* chunk_map(void* argument){
struct map_argument* arg = (struct map_argument*) argument;
for(int i = arg->from; i < arg->to; i++){
arg->results[i] = (*(arg->f))(arg->things[i]);
}
return NULL;
} |
BlightsteelColossus-dev/MapReduce-in-C | mapping_struct.c | <filename>mapping_struct.c
struct map_argument {
void** things;
void** results;
void* (*f)(void*);
int from;
int to;
}; |
BlightsteelColossus-dev/MapReduce-in-C | is_prime.c | // returns 1 if the number is a prime, 0 otherwise
void* naivePrime(void* number){
int n = *((int*) number);
int* res = malloc(sizeof(int));
*res = 1;
for(int i = 2; i < n; i++){
if(n%i==0){
*res=0;
return res;
}
}
return res;
}
int main(int argc, char** argv){
int N = 1000;
int** numbers = malloc(sizeof(int*)*N);
for(int i = 0 ; i < N ; i++){
int* n = malloc(sizeof(int));
*n = i;
numbers[i] = n;
}
int** resulting_numbers = NULL;
void** is_prime = map((void**) numbers, naivePrime, N);
resulting_numbers = (int**) is_prime;
} |
BlightsteelColossus-dev/MapReduce-in-C | map_single_thread.c | <gh_stars>0
// generic single-threaded map implementation using void* and pointer arithmetics.
void** map(void** things, void* (*f)(void*), int length){
void** results = malloc(sizeof(void*)*length);
for(int i = 0; i < length; i++){
void* thing = things[i];
void* result = (*f)(thing);
results[i] = result;
}
return results;
} |
BlightsteelColossus-dev/MapReduce-in-C | parallelizing_map.c | void** concurrent_map(void** things, void* (*f)(void*), int length,
int nthreads){
void** results = malloc(sizeof(void*)*length);
struct map_argument arguments[nthreads];
pthread_t threads[nthreads];
int chunk_size = length/nthreads;
for(int j = 0 ; j < nthreads; j++){
int from = j*chunk_size;
struct map_argument* argument = &arguments[j];
init_map_argument(argument, things, results, f, from, from+chunk_size);
pthread_create(&threads[j], NULL, chunk_map, (void*) argument);
}
for(int i = 0; i < length % nthreads; i++){
int idx = chunk_size*nthreads + i;
results[idx] = (*f)(things[idx]);
}
for(int k = 0; k < nthreads; k++){
pthread_join(threads[k], NULL);
}
return results;
} |
BRonen/Playground | C/Structs.c | #include <assert.h>
struct Test{
int var1;
int var2;
int var3;
};
void compareAB(struct Test* a, struct Test* b){
assert(b->var1 == a->var1);
assert(b->var2 == a->var2);
assert(b->var3 == a->var3);
}
int main(){
struct Test a;
struct Test b;
a.var1 = 0;
a.var2 = 1;
a.var3 = 2;
b.var1 = 0;
b.var2 = 1;
b.var3 = 2;
compareAB(&a, &b);
return 0;
}
|
BRonen/Playground | C/BinarySearch.c | <gh_stars>0
#include <stdio.h>
#include <assert.h>
int binarySearch(int* array, int min, int max, int value){
//Symmetry is better than avoiding pleonasm
if( min < 0 || min > max || max < min || 0 > max ){
return -1;
}
int index = (min+max)/2;
int result = index;
if(array[index] > value){
result = binarySearch(array, min, index-1, value);
}else if(array[index] < value){
result = binarySearch(array, index+1, max, value);
}
return result;
}
int main(){
int sortedArray[1000];
for(int i = 0; i < 1000; i++){
//some random stuff to fill the array
sortedArray[i] = i*42;
}
//something to search
sortedArray[42] = 73;
assert(binarySearch(sortedArray, 0, 999, 73) != 42);
return 0;
}
|
BRonen/Playground | C/BinaryTrees/BinaryTree.c | #include <stdio.h>
#include <assert.h>
#include "BinaryTree.h"
int main(){
struct Bst *bst = bstCreate(106);
bstInsert(bst, 729);
bstInsert(bst, 22);
bstInsert(bst, 62);
bstInsert(bst, 18);
bstInsert(bst, 52);
bstInsert(bst, 78);
bstInsert(bst, 9);
bstInsert(bst, 5);
bstInsert(bst, 92);
bstInsert(bst, 39);
bstInsert(bst, 26);
bstInsert(bst, 122);
bstInsert(bst, 38);
bstInsert(bst, 12);
bstInsert(bst, 2);
bstInsert(bst, 200);
bstInsert(bst, 1);
bstInsert(bst, 3);
/*
* bst concept is something
* like this:
*
* 16
* 8 18
* 5 38
* 3 7
* 2
* 1
*/
assert(bstSuccessor(bst, 18) == 22);
assert(bstSuccessor(bst, 5) == 9);
assert(bstSuccessor(bst, 38) == 39);
assert(bstSuccessor(bst, 4) == -1);
assert(bstSuccessor(bst, 3) == 5);
assert(bstCountNodes(bst) == 19);
assert(bstHeight(bst) == 7);
assert(bstGetMin(bst) == 1);
assert(bstGetMax(bst) == 729);
assert(bstSearch(bst, 38) == 1);
bstDelete(bst, 38);
assert(bstSearch(bst, 38) == 0);
//delete multiple times is safe
bstDelete(bst, 38);
assert(bstSearch(bst, 38) == 0);
bstFree(bst);
//after free bst, a trash node still on root
//you need to set it to null
assert(bstCountNodes(bst) == 1);
assert(bstHeight(bst) == 1);
assert(bstGetMin(bst) == bst->value);
assert(bstGetMax(bst) == bst->value);
//now the pointer will be really clear
bst = NULL;
assert(bstCountNodes(bst) == 0);
assert(bstHeight(bst) == 0);
assert(bstGetMin(bst) == 0);
assert(bstGetMax(bst) == 0);
struct Bst *badBst = bstCreate(106);
badBst->right = bstCreate(100);
assert(bstIsValid(badBst) == 0);
bstFree(badBst);
badBst = NULL;
assert(bstIsValid(badBst) == 1);
return 0;
} |
BRonen/Playground | C/Queue/QueueLL.h | /* Queue implemented with linked list */
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *next;
};
struct QueueLL{
int length;
struct Node *head;
struct Node *tail;
};
struct QueueLL queueLLCreate(){
struct QueueLL queueLL;
queueLL.length = 0;
queueLL.head = NULL;
queueLL.tail = NULL;
return queueLL;
}
int queueLLIsEmpty(struct QueueLL *queueLL){
if(queueLL->length == 0)
return 1;
else
return 0;
}
void queueLLPush(struct QueueLL *queueLL, int data){
struct Node *node = malloc(sizeof(struct Node));
node->data = data;
if(queueLLIsEmpty(queueLL)){
node->next = NULL;
queueLL->head = queueLL->tail = node;
}else{
queueLL->tail->next = node;
queueLL->tail = node;
}
queueLL->length++;
}
int queueLLPull(struct QueueLL *queueLL){
struct Node *tmp = queueLL->head;
int data = queueLL->head->data;
queueLL->head = queueLL->head->next;
free(tmp);
queueLL->length--;
return(data);
}
void nodePrint(struct Node *node){
printf("\t(%d <=> #%x)\n",node->data, node->next);
}
void queueLLPrint(struct QueueLL *queueLL) {
if(queueLL->length == 0){
printf("\nactual queueLL:\n");
printf(" %d \n { \n", queueLL->length);
printf("\n }\n");
}else{
struct Node *node = queueLL->head;
printf("\nactual queueLL:\n");
printf(" %d \n { \n", queueLL->length);
nodePrint(node);
while(node->next != NULL){
node = node->next;
nodePrint(node);
}
printf("\n }\n");
}
}
|
BRonen/Playground | C/ArithmeticOperators.c | #include <assert.h>
int main(){
int num1 = 7, num2 = 8;
float sum, sub, div, mul;
sum = (float)num1 + num2,
sub = (float)num1 - num2,
div = (float)num1 / num2,
mul = (float)num1 * num2;
assert(sum == 15);
assert(sub == -1);
assert(div == 0.875);
assert(mul == 56);
return 0;
}
|
BRonen/Playground | C/CommaOperator.c | #include <assert.h>
int test(){
int a = 1, b = 2, c = 3;
int d = (a += 3, a + c);
assert(d == 7);
return a, b, c, d;
}
void main(){
int a = 1, b = 0;
b = test(), a;
assert(b == test());
a = 1, b = 0;
b = (test(), a);
assert(b == a);
}
|
BRonen/Playground | C/Arrays.c | <filename>C/Arrays.c
#include <assert.h>
#define size 4
int main(){
int arr[size] = {0, 1, 2, 3};
int* ptr = arr;
assert(*ptr == arr[0]);
for(int i = 0; i <= size; i++){
assert(i == *ptr);
ptr++;
}
return 0;
}
|
BRonen/Playground | C/LinkedList/LinkedList.h | #include <stdio.h>
#include <stdlib.h>
struct Node{
int index;
int data;
struct Node *next;
};
struct List{
int index;
int length;
struct Node *head;
};
struct List listCreate(){
struct List list;
list.index = -1;
list.length = 0;
list.head = NULL;
return list;
}
void listClear(struct List *list){
struct Node *node = list->head;
while(node->index != 0){
struct Node *tmp = node->next;
free(node);
node = tmp;
}
free(node);
list->index = -1;
list->length = 0;
list->head = NULL;
}
int listIsEmpty(struct List *list){
if(list->length == 0)
return 1;
else
return 0;
}
int listSize(struct List *list){
return list->length;
}
void listPushFront(struct List *list, int value){
struct Node *node = (struct Node*)malloc(sizeof(struct Node));
node->index = list->length;
list->length++;
list->index++;
node->next = list->head;
list->head = node;
node->data = value;
}
struct Node *listPopFront(struct List *list){
struct Node *node = list->head;
list->head = node->next;
list->index--;
list->length--;
return node;
}
void listPushBack(struct List *list, int value){
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->index = 0;
newNode->data = value;
newNode->next = NULL;
if(list->head != NULL){
struct Node *node;
for(node = list->head; node->index != 0; node = node->next){
node->index++;
}
node->index++;
node->next = newNode;
}else{
list->head = newNode;
}
list->index++;
list->length++;
}
struct Node *listPopBack(struct List *list){
struct Node *node;
for(node = list->head; node->index != 1; node = node->next){
node->index--;
}
node->index--;
free(node->next);
node->next = NULL;
list->index--;
list->length--;
return node;
}
struct Node *listFront(struct List *list){
return list->head;
}
struct Node *listBack(struct List *list){
struct Node *node;
for(node = list->head; node->index != 0; node = node->next){
}
return node;
}
struct Node *listAtIndex(struct List *list, int index){
struct Node *node = list->head;
while(node->index != index){
node = node->next;
}
return node;
}
struct Node *listInsert(struct List *list, int index, int value){
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->index = index;
newNode->data = value;
newNode->next = NULL;
struct Node *node;
for(node = list->head; node->index != index; node = node->next){
node->index++;
}
node->index++;
newNode->next = node->next;
node->next = newNode;
list->index++;
list->length++;
}
struct Node *listRemove(struct List *list, int index){
struct Node *node;
struct Node *tmp;
for(node = list->head; node->index != index + 1; node = node->next){
node->index--;
}
node->index--;
tmp = node->next;
node->next = tmp->next;
free(tmp);
list->index--;
list->length--;
}
void nodePrint(struct Node *node){
printf("\t(%d,%d,#%x)\n",node->index, node->data, node->next);
}
void listPrint(struct List *list) {
if(list->length == 0){
printf("\nactual list:\n");
printf(" %d %d\n { \n", list->index, list->length);
printf("\n }\n");
}else{
struct Node *node = list->head;
printf("\nactual list:\n");
printf(" %d %d\n { \n", list->index, list->length);
nodePrint(node);
while(node->next != NULL){
node = node->next;
nodePrint(node);
}
printf("\n }\n");
}
}
|
BRonen/Playground | C/BinaryTrees/BinaryTree.h | #include <stdlib.h>
#include <limits.h>
struct Bst{
int value;
struct Bst *left;
struct Bst *right;
};
struct Bst* bstCreate(int value){
struct Bst *bst = malloc(sizeof(struct Bst));
bst->value = value;
bst->left = NULL;
bst->right = NULL;
return bst;
}
void bstFree(struct Bst *bst){
if(bst == NULL)
return;
bstFree(bst->left);
bst->left = NULL;
bstFree(bst->right);
bst->right = NULL;
free(bst);
}
int bstGetMin(struct Bst *bst){
if(bst == NULL)
return 0;
struct Bst *tmp = bst;
while(tmp->left){
tmp = tmp->left;
}
return tmp->value;
}
int bstGetMax(struct Bst *bst){
if(bst == NULL)
return 0;
struct Bst *tmp = bst;
while(tmp->right){
tmp = tmp->right;
}
return tmp->value;
}
void bstInsert(struct Bst *bst, int value){
if(value == bst->value)
return;
//if value is higher then insert at right
if(value > bst->value){
//if right isn't NULL then insert
if(bst->right){
bstInsert(bst->right, value);
return;
}
//if right is NULL then create
bst->right = bstCreate(value);
return;
}
//if value is lower then insert at left
//and if left isn't NULL then insert
if(bst->left){
bstInsert(bst->left, value);
return;
}
//if left is NULL then create
bst->left = bstCreate(value);
return;
}
struct Bst* bstDelete(struct Bst *bst, int value){
if(bst == NULL)
return bst;
//search for value and bstDelete
if(value < bst->value){
bst->left = bstDelete(bst->left, value);
}else if(value > bst->value){
bst->right = bstDelete(bst->right, value);
//found it
}else{
//if dont has childs node just delete it
if(bst->left == NULL && bst->right == NULL){
free(bst);
bst = NULL;
//if has then switch it with child before
}else if (bst->left == NULL){
struct Bst *tmp = bst;
bst = bst->right;
free(tmp);
}else if (bst->right == NULL){
struct Bst *tmp = bst;
bst = bst->left;
free(tmp);
//if has both childs then switch with min of right child tree
}else{
int min = bstGetMin(bst->right);
bst->value = min;
bst->right = bstDelete(bst->right, min);
}
}
//return child node
return bst;
}
int bstSearch(struct Bst *bst, int value){
if(bst == NULL)
return 0;
if(value < bst->value){
return bstSearch(bst->left, value);
}else if(value > bst->value) {
return bstSearch(bst->right, value);
}else{
return 1;
}
}
int bstSuccessor(struct Bst *bst, int value){
struct Bst *tmp = bst;
while(tmp->value != value){
//search for node with the value
if(tmp->value > value){
tmp = tmp->left;
}else if(tmp->value < value){
tmp = tmp->right;
}
//if value dont exists then return -1
if(tmp == NULL){
return -1;
}
}
if(tmp->right != NULL){
return bstGetMin(tmp->right);
}
tmp = NULL;
while(bst != NULL){
//get lowest ancestor that is a left child in the path to target value
if (value < bst->value){
tmp = bst;
bst = bst->left;
}else{
bst = bst->right;
}
}
return tmp->value;
}
int bstHeight(struct Bst *bst) {
if(bst == NULL)
return 0;
int leftHeight = bstHeight(bst->left);
int rightHeight = bstHeight(bst->right);
int maxValue = (
leftHeight > rightHeight ?
leftHeight : rightHeight
);
return 1 + maxValue;
}
int bstCountNodes(struct Bst *bst){
if(bst == NULL)
return 0;
return 1 + bstCountNodes(bst->left) + bstCountNodes(bst->right);
}
int bstIsBetween(struct Bst *bst, int min, int max) {
if(bst == NULL)
return 1;
// ensure subtrees are not hiding a value lower or higher than the subtree
// allows
return bst->value > min && bst->value < max &&
bstIsBetween(bst->left, min, bst->value) &&
bstIsBetween(bst->right, bst->value, max);
}
int bstIsValid(struct Bst *bst){
if(bst == NULL)
return 1;
return bstIsBetween(bst, INT_MIN, INT_MAX);
}
void bstPrint(struct Bst *bst){
if(bst == NULL)
return;
bstPrint(bst->left);
printf("%d\n", bst->value);
bstPrint(bst->right);
} |
BRonen/Playground | C/Pointers.c | <gh_stars>0
#include <assert.h>
void func1(int *a){
*a = 1;
}
void func2(int *a){
*a = 2;
}
//receive a pointer to a pointer to a function
void changeValue(void (**ptr)()){
//set pointer of pointer to func2
*ptr = &func2;
}
int main (){
int a = 0;
void (*ptr)(); //pointer to "void function()"
ptr = &func1; //ptr -> func1
assert(ptr == &func1);
ptr(&a); //func1()
assert(a == 1);
changeValue(&ptr); //passing ptr memory address
assert(ptr == &func2);
ptr(&a); //func2()
assert(a == 2);
return 0;
}
|
BRonen/Playground | C/Queue/QueueAL.h | <reponame>BRonen/Playground
/* Queue implemented with fixed size arrays */
#include <stdio.h>
#include <stdlib.h>
struct QueueAL{
int* buffer;
int length;
int* head;
int* tail;
};
struct QueueAL queueALCreate(int size){
struct QueueAL queueAL;
queueAL.buffer = malloc(sizeof(int)*size);
queueAL.length = size;
queueAL.head = queueAL.tail = queueAL.buffer;
return queueAL;
}
int queueALIsEmpty(struct QueueAL *queueAL){
if(queueAL->head == queueAL->tail)
return 1;
else
return 0;
}
int queueALIsFull(struct QueueAL *queueAL){
int* head = queueAL->head + 1;
if(head > &(queueAL->buffer[queueAL->length])){
head = queueAL->buffer;
}
if(head == queueAL->tail)
return 1;
else
return 0;
}
int queueALPush(struct QueueAL *queueAL, int data){
if( queueALIsFull(queueAL) ){
return 1;
}
*(queueAL->head) = data;
queueAL->head++;
if(queueAL->head > &(queueAL->buffer[queueAL->length])){
queueAL->head = queueAL->buffer;
}
return 0;
}
int queueALPull(struct QueueAL *queueAL){
int data = *queueAL->tail;
*queueAL->tail = 0;
queueAL->tail++;
return data;
}
void queueALPrint(struct QueueAL *queueAL){
printf("\n\nindex final: %d\n", queueAL->length - 1);
for(int i = 0; i < queueAL->length; i++){
printf("[%d] => %d\n", i, queueAL->buffer[i]);
}
} |
BRonen/Playground | C/Queue/Queue.c | #include <assert.h>
#include "QueueLL.h"
#include "QueueAL.h"
int main() {
//tests of queue made with a linked list
struct QueueLL queueLL = queueLLCreate();
assert(queueLLIsEmpty(&queueLL) == 1);
queueLLPush(&queueLL, 43);
queueLLPush(&queueLL, 43);
queueLLPush(&queueLL, 43);
assert(queueLLIsEmpty(&queueLL) == 0);
assert(queueLLPull(&queueLL) == 43);
assert(queueLLPull(&queueLL) == 43);
assert(queueLLPull(&queueLL) == 43);
assert(queueLLIsEmpty(&queueLL) == 1);
//tests of queue made with a array list
struct QueueAL queueAL = queueALCreate(10);
assert(queueALIsEmpty(&queueAL) == 1);
for(int i = 10; i <= 90; i++){
queueALPush(&queueAL, i*i);
}
assert(queueALIsEmpty(&queueAL) == 0);
for(int i = 10; i <= 90; i++){
if(!queueALIsEmpty(&queueAL)){
assert(queueALPull(&queueAL) == i*i);
}
}
assert(queueALIsEmpty(&queueAL) == 1);
return 0;
}
|
BRonen/Playground | C/Overflow.c | #include <assert.h>
int main(){
int a = 2147483647;
assert(a == 2147483647);
assert(++a == -2147483648);
a = 4294967295;
assert(a == -1);
assert(++a == 0);
return 0;
}
|
BRonen/Playground | C/HashTable/HashTable.c | <gh_stars>0
#include <assert.h>
#include <string.h>
#include "HashTable.h"
int main() {
struct HashTable *hash = hashtableCreate(5);
//hashtableDump(hash);
hashtableInsert(hash, "hello", "world");
hashtableInsert(hash, "24323", "world");
hashtableInsert(hash, "&*@#)", "world");
hashtableInsert(hash, " ", "world");
//hashtableDump(hash);
/*
printf("\thello => %s\n", hashtableSearch(hash, "hello"));
printf("\t24323 => %s\n", hashtableSearch(hash, "24323"));
printf("\t&*@#) => %s\n", hashtableSearch(hash, "&*@#)"));
printf("\t => %s\n", hashtableSearch(hash, " "));
*/
assert(strcmp(hashtableSearch(hash, "hello"), "world") == 0);
assert(strcmp(hashtableSearch(hash, "24323"), "world") == 0);
assert(strcmp(hashtableSearch(hash, "&*@#)"), "world") == 0);
assert(strcmp(hashtableSearch(hash, " "), "world") == 0);
hashtableInsert(hash, "hello", "world2");
//hashtableDump(hash);
assert(strcmp(hashtableSearch(hash, "hello"), "world2") == 0);
hashtableDelete(hash, "&*@#)");
//hashtableDump(hash);
assert(strcmp(hashtableSearch(hash, "&*@#)"), "") == 0);
hashtableDelete(hash, "hello");
//hashtableDump(hash);
assert(strcmp(hashtableSearch(hash, "hello"), "") == 0);
return 0;
}
|
BRonen/Playground | C/Vector/Vector.c | <reponame>BRonen/Playground
#include <assert.h>
#include "Vector.h"
int main(){
struct Vector vec = vectorCreate();
assert(vec.length == 0);
assert(vec.capacity == SIZE);
for(int i = 1; i<50; i++){
vectorPush(&vec, i);
}
for(int i = 1; i<45; i++){
assert(vectorPop(&vec) == 50-i);
}
vectorInsert(&vec, 5, 42);
assert(vectorAtIndex(&vec, 5) == 42);
vectorDelete(&vec, 5);
assert(vectorAtIndex(&vec, 5) == 0);
assert(vectorAtIndex(&vec, 3) == 4);
vectorRemove(&vec, 4);
assert(vectorAtIndex(&vec, 3) == 0);
vectorPrepend(&vec, 24);
assert(vectorAtIndex(&vec, 0) == 24);
assert(vectorFind(&vec, 54) == -1);
assert(vectorFind(&vec, 2) == 2);
vectorDecreate(&vec);
return 0;
}
|
BRonen/Playground | C/HashTable/HashTable.h | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
static unsigned int hashCode(char *key, unsigned int hashSize) {
unsigned long hash = 5381;
unsigned int c;
while((c = *key++)) {
hash = ((hash << 5) + hash) + c; // hash * 33 + c
}
return hash % hashSize;
};
/* Node */
struct Node {
char *key;
char *value;
struct Node* next;
};
struct Node* nodeCreate(char *key, char *value) {
struct Node *node = malloc(sizeof(struct Node));
node->key = key;
node->value = value;
node->next = NULL;
return node;
};
/* Hash Table */
struct HashTable {
struct Node **list;
int length;
};
struct HashTable* hashtableCreate(unsigned int length){
struct HashTable *hashtable = malloc(sizeof(struct HashTable));
hashtable->list = malloc(sizeof(struct Node*)*length);
hashtable->length = length;
for(int i = 0; i < length; i++){
hashtable->list[i] = NULL;
}
return hashtable;
}
void hashtableInsert(struct HashTable *hashtable, char *key, char *value) {
unsigned int index = hashCode(key, hashtable->length);
struct Node *node = hashtable->list[index];
if(node == NULL){
hashtable->list[index] = nodeCreate(key, value);
}else{
while(node) {
if(strcmp(node->key, key) == 0){
struct Node *tmp = node;
hashtable->list[index] = nodeCreate(key, value);
free(tmp);
}
if (node->next == NULL) {
node->next = nodeCreate(key, value);
break;
}
node = node->next;
}
}
};
char* hashtableSearch(struct HashTable *hashtable, char *key) {
unsigned int index = hashCode(key, hashtable->length);
struct Node *node = hashtable->list[index];
while(node) {
if (strcmp(node->key, key) == 0) {
return node->value;
}
node = node->next;
}
return "";
}
void hashtableDelete(struct HashTable *hashtable, char *key){
unsigned int index = hashCode(key, hashtable->length);
struct Node *node = hashtable->list[index];
//if first node from linkedlist of this index
//is the key we search then swap with the next
if(strcmp(node->key, key) == 0){
hashtable->list[index] = node->next;
free(node);
return;
}
//while not in the end, get the next node as *ptr
//when get the right node then swap with next
while(node){
struct Node *ptr = node->next;
if(strcmp(ptr->key, key) == 0){
node->next = ptr->next;
free(ptr);
}
node = node->next;
}
}
void hashtableDump(struct HashTable *hashtable){
printf("\n");
for(int i = 0; i < hashtable->length; i++){
printf("%d {\n", i);
struct Node* ptr = hashtable->list[i];
while(ptr != NULL){
printf("\t#%x\t%s => %s\t#%x\n", ptr, ptr->key, ptr->value, ptr->next);
ptr = ptr->next;
}
printf("}\n\n");
}
printf("\n");
}
|
BRonen/Playground | C/DynamicMemory.c | <reponame>BRonen/Playground
#include <stdlib.h>
#include <assert.h>
#define size 5
int main(){
int* ptr;
ptr = malloc(size * sizeof(int));
assert(!(ptr == NULL));
int i;
for (i = 0; i < size; i++) {
*ptr = i;
ptr++;
}
ptr -= i;
for (i = 0; i < size; i++) {
assert(*ptr == i);
ptr++;
}
return 0;
}
|
BRonen/Playground | C/Vector/Vector.h | <gh_stars>0
#include <stdlib.h>
#define SIZE 4
struct Vector{
int* data;
int length;
int capacity;
int* ptr;
};
struct Vector vectorCreate(){
struct Vector vec;
vec.data = malloc(SIZE*sizeof(int));
vec.ptr = vec.data;
vec.capacity = SIZE;
vec.length = 0;
return vec;
}
int vectorSize(struct Vector* vec){
return vec->length;
}
int vectorCapacity(struct Vector* vec){
return vec->capacity;
}
int vectorIsEmpty(struct Vector* vec){
return vec->length == 0;
}
int vectorAtIndex(struct Vector* vec, int index){
return vec->data[index];
}
void vectorResize(struct Vector* vec, int size){
vec->capacity = size;
vec->data = (int*)realloc(
vec->data, vec->capacity*sizeof(int)
);
vec->ptr = vec->data;
vec->ptr += vec->length;
}
void vectorDecreate(struct Vector* vec){
free(vec->data);
}
void vectorPush(struct Vector* vec, int value){
if(vec->length == vec->capacity){
vectorResize(vec, vec->capacity*2);
}
*vec->ptr = value;
vec->ptr++;
vec->length++;
}
int vectorPop(struct Vector* vec){
vec->ptr--;
int value = *vec->ptr;
*vec->ptr = 0;
vec->length--;
if(vec->length <= vec->capacity/4){
vectorResize(vec, vec->capacity/2);
}
return value;
}
void vectorDelete(struct Vector* vec, int index){
for(int i = index; i < vec->capacity-1; i++){
vec->data[i] = vec->data[i+1];
}
vectorPop(vec);
}
void vectorInsert(struct Vector* vec, int index, int value){
int tmp = vec->data[vec->length-1];
for(int i = vec->length; i > index; --i){
if(vec->length >= vec->capacity){
vectorResize(vec, vec->capacity/2);
}
vec->data[i] = vec->data[i-1];
}
vec->data[index] = value;
}
void vectorPrepend(struct Vector* vec, int value){
vectorInsert(vec, 0, value);
}
int vectorFind(struct Vector* vec, int value){
for(int i = 1; i < vec->length; i++){
if(vectorAtIndex(vec, i) == value){
return i;
}
}
return -1;
}
void vectorRemove(struct Vector* vec, int value){
for(int i = 1; i < vec->length; i++){
if(vectorAtIndex(vec, i) == value){
vectorDelete(vec, i);
}
}
}
|
BRonen/Playground | C/LinkedList/LinkedList.c | <filename>C/LinkedList/LinkedList.c
#include <assert.h>
#include "LinkedList.h"
void main() {
struct List list = listCreate();
assert(listIsEmpty(&list) == 1);
listPushFront(&list, 189);
listPushFront(&list, 298);
listPushFront(&list, 376);
listPushFront(&list, 456);
listPushFront(&list, 545);
listPushFront(&list, 643);
listPushFront(&list, 722);
assert(listSize(&list) == 7);
assert(listAtIndex(&list, 2)->data == 376);
assert(list.index == listPopFront(&list)->index);
assert(listSize(&list) == 6);
assert(listAtIndex(&list, list.index) == listFront(&list));
assert(listAtIndex(&list, 0) == listBack(&list));
struct List tmpCopy = list;
listPushBack(&list, 42);
listPushBack(&list, 42);
listPushBack(&list, 42);
listPopBack(&list);
listPopBack(&list);
listPopBack(&list);
assert(listSize(&tmpCopy) == listSize(&list));
listInsert(&list, 3, 43);
assert(listAtIndex(&list, 3)->data == 43);
listRemove(&list, 3);
assert(listAtIndex(&list, 3)->data != 43);
listClear(&list);
assert(listIsEmpty(&list) == 1);
listPushBack(&list, 123);
listPushBack(&list, 234);
listPushBack(&list, 345);
listPushBack(&list, 456);
listPushBack(&list, 567);
listPushBack(&list, 678);
listPushBack(&list, 789);
assert(listSize(&list) == 7);
assert(listAtIndex(&list, 2)->data == 567);
assert(0 == listPopBack(&list)->index);
assert(listSize(&list) == 6);
assert(listAtIndex(&list, list.index) == listFront(&list));
assert(listAtIndex(&list, 0) == listBack(&list));
listClear(&list);
assert(listIsEmpty(&list) == 1);
}
|
jjzhang166/AWLive | AWLive/PushStream/LKEncoder/Base/LKEncoder.h | <gh_stars>1-10
/**
* file : LKEncoder.h
* author : Rex
* create : 2017-02-17 16:59
* func :
* history:
*/
#ifndef __LKENCODER_H_
#define __LKENCODER_H_
/*
编码器基类声明公共接口
*/
#include <stdio.h>
#include <_types.h>
#include "aw_all.h"
typedef enum {
AWEncoderErrorCodeVTSessionCreateFailed,
AWEncoderErrorCodeVTSessionPrepareFailed,
AWEncoderErrorCodeLockSampleBaseAddressFailed,
AWEncoderErrorCodeEncodeVideoFrameFailed,
AWEncoderErrorCodeEncodeCreateBlockBufFailed,
AWEncoderErrorCodeEncodeCreateSampleBufFailed,
AWEncoderErrorCodeEncodeGetSpsPpsFailed,
AWEncoderErrorCodeEncodeGetH264DataFailed,
AWEncoderErrorCodeCreateAudioConverterFailed,
AWEncoderErrorCodeAudioConverterGetMaxFrameSizeFailed,
AWEncoderErrorCodeAudioEncoderFailed,
} AWEncoderErrorCode;
class LKEncoder{
public:
virtual void open(int width, int height) = 0;
virtual void close() = 0;
void onError(AWEncoderErrorCode code, const char* des){
// log
}
//AWEncoderManager *manager;
float m_quality;
};
#endif
|
jjzhang166/AWLive | clibs/libaw/pushStream/encoder/aw_sw_faac_encoder.c | /*
copyright 2016 wanghongyu.
The project page:https://github.com/hardman/AWLive
My blog page: http://blog.csdn.net/hard_man/
*/
#include "aw_sw_faac_encoder.h"
#include "aw_all.h"
//faac 实例
static aw_faac_context *s_faac_ctx = NULL;
static aw_faac_config *s_faac_config = NULL;
//debug使用
static int32_t audio_count = 0;
//创建基本的audio tag,除类型,数据和时间戳
static aw_flv_audio_tag *aw_sw_encoder_create_flv_audio_tag(aw_faac_config *faac_cfg){
aw_flv_audio_tag *audio_tag = alloc_aw_flv_audio_tag();
audio_tag->sound_format = aw_flv_a_codec_id_AAC;
audio_tag->common_tag.header_size = 2;
if (faac_cfg->sample_rate == 22050) {
audio_tag->sound_rate = aw_flv_a_sound_rate_22kHZ;
}else if (faac_cfg->sample_rate == 11025) {
audio_tag->sound_rate = aw_flv_a_sound_rate_11kHZ;
}else if (faac_cfg->sample_rate == 5500) {
audio_tag->sound_rate = aw_flv_a_sound_rate_5_5kHZ;
}else{
audio_tag->sound_rate = aw_flv_a_sound_rate_44kHZ;
}
if (faac_cfg->sample_size == 8) {
audio_tag->sound_size = aw_flv_a_sound_size_8_bit;
}else{
audio_tag->sound_size = aw_flv_a_sound_size_16_bit;
}
audio_tag->sound_type = faac_cfg->channel_count == 1 ? aw_flv_a_sound_type_mono : aw_flv_a_sound_type_stereo;
return audio_tag;
}
//编码器开关
extern void aw_sw_encoder_open_faac_encoder(aw_faac_config *faac_config){
if (aw_sw_faac_encoder_is_valid()) {
aw_log("[E] aw_sw_encoder_open_faac_encoder when encoder is already inited");
return;
}
int32_t faac_cfg_len = sizeof(aw_faac_config);
if (!s_faac_config) {
s_faac_config = aw_alloc(faac_cfg_len);
}
memcpy(s_faac_config, faac_config, faac_cfg_len);
s_faac_ctx = alloc_aw_faac_context(*faac_config);
}
//关闭编码器并释放资源
extern void aw_sw_encoder_close_faac_encoder(){
if (!aw_sw_faac_encoder_is_valid()) {
aw_log("[E] aw_sw_encoder_close_faac_encoder when encoder is not inited");
return;
}
free_aw_faac_context(&s_faac_ctx);
if (s_faac_config) {
aw_free(s_faac_config);
s_faac_config = NULL;
}
}
//对pcm数据进行faac软编码,并转成flv_audio_tag
extern aw_flv_audio_tag *aw_sw_encoder_encode_faac_data(int8_t *pcm_data, long len, uint32_t timestamp){
if (!aw_sw_faac_encoder_is_valid()) {
aw_log("[E] aw_sw_encoder_encode_faac_data when encoder is not inited");
return NULL;
}
aw_encode_pcm_frame_2_aac(s_faac_ctx, pcm_data, len);
int adts_header_size = 7;
//除去ADTS头的7字节
if (s_faac_ctx->encoded_aac_data->size <= adts_header_size) {
return NULL;
}
//除去ADTS头的7字节
aw_flv_audio_tag *audio_tag = aw_encoder_create_audio_tag((int8_t *)s_faac_ctx->encoded_aac_data->data + adts_header_size, s_faac_ctx->encoded_aac_data->size - adts_header_size, timestamp, &s_faac_ctx->config);
audio_count++;
return audio_tag;
}
//根据faac_config 创建包含audio specific config 的flv tag
extern aw_flv_audio_tag *aw_sw_encoder_create_faac_specific_config_tag(){
if(!aw_sw_faac_encoder_is_valid()){
aw_log("[E] aw_sw_encoder_create_faac_specific_config_tag when audio encoder is not inited");
return NULL;
}
//创建 audio specfic config record
aw_flv_audio_tag *aac_tag = aw_sw_encoder_create_flv_audio_tag(&s_faac_ctx->config);
aac_tag->aac_packet_type = aw_flv_a_aac_package_type_aac_sequence_header;
aac_tag->config_record_data = copy_aw_data(s_faac_ctx->audio_specific_config_data);
aac_tag->common_tag.timestamp = 0;
aac_tag->common_tag.data_size = s_faac_ctx->audio_specific_config_data->size + 11 + aac_tag->common_tag.header_size;
return aac_tag;
}
extern uint32_t aw_sw_faac_encoder_max_input_sample_count(){
if (aw_sw_faac_encoder_is_valid()) {
return (uint32_t)s_faac_ctx->max_input_sample_count;
}
return 0;
}
//编码器是否合法
extern int8_t aw_sw_faac_encoder_is_valid(){
return s_faac_ctx != NULL;
}
//下面2个函数所有编码器都可以用
//将aac数据转为flv_audio_tag
extern aw_flv_audio_tag *aw_encoder_create_audio_tag(int8_t *aac_data, long len, uint32_t timeStamp, aw_faac_config *faac_cfg){
aw_flv_audio_tag *audio_tag = aw_sw_encoder_create_flv_audio_tag(faac_cfg);
audio_tag->aac_packet_type = aw_flv_a_aac_package_type_aac_raw;
audio_tag->common_tag.timestamp = timeStamp;
aw_data *frame_data = alloc_aw_data((uint32_t)len);
memcpy(frame_data->data, aac_data, len);
frame_data->size = (uint32_t)len;
audio_tag->frame_data = frame_data;
audio_tag->common_tag.data_size = audio_tag->frame_data->size + 11 + audio_tag->common_tag.header_size;
return audio_tag;
}
//创建audio_specific_config_tag
extern aw_flv_audio_tag *aw_encoder_create_audio_specific_config_tag(aw_data *audio_specific_config_data, aw_faac_config *faac_config){
//创建 audio specfic config record
aw_flv_audio_tag *audio_tag = aw_sw_encoder_create_flv_audio_tag(faac_config);
audio_tag->config_record_data = copy_aw_data(audio_specific_config_data);
audio_tag->common_tag.timestamp = 0;
audio_tag->common_tag.data_size = audio_specific_config_data->size + 11 + audio_tag->common_tag.header_size;
return audio_tag;
}
|
jjzhang166/AWLive | AWLive/PushStream/LKEncoder/HW/LKHWH264Encoder.h | /**
* file : LKHWH264Encoder.h
* author : Rex
* create : 2017-02-17 17:01
* func :
* history:
*/
#ifndef __LKHWH264ENCODER_H_
#define __LKHWH264ENCODER_H_
#include "LKVideoEncoder.h"
typedef struct lk_encoder_t lk_encoder_t;
class LKHWH264Callback{
public:
virtual void handleH264(const unsigned char* data, uint32_t length, int nalu_type, bool is_key) = 0;
};
class LKHWH264ToFileCallback: public LKHWH264Callback{
public:
virtual void handleH264(const unsigned char* data, uint32_t length, int nalu_type, bool is_key);
int m_fd;
};
class LKHWH264ToFlvCallback: public LKHWH264Callback{
public:
virtual void handleH264(const unsigned char* data, uint32_t length, int nalu_type, bool is_key);
uint32_t m_pts_ms;
};
class LKHWH264Encoder: public LKVideoEncoder{
public:
LKHWH264Encoder(LKHWH264Callback* callback=NULL);
~LKHWH264Encoder();
virtual void open(int width, int height);
virtual void close();
virtual aw_flv_video_tag* encodeYUVDataToFlvTag(unsigned char* yuv);
//根据flv,h264,aac协议,提供首帧需要发送的tag
//创建sps pps
virtual aw_flv_video_tag* createSpsPpsFlvTag();
virtual bool encodeN12BytesToH264(unsigned char* yuv);
virtual int encodePiexelBufferToH264(void* pixelbuffer);
LKHWH264Callback* m_encoder_callback;
lk_encoder_t* m_encoder_session;
uint32_t m_frame_count;
uint32_t m_frame_rate;
uint32_t m_encode_frame;
time_t m_encode_time;
};
#endif
|
jjzhang166/AWLive | AWLive/PushStream/LKEncoder/Base/LKMP4Encoder.h | /**
* file : LKMP4Encoder.h
* author : Rex
* create : 2017-02-20 15:04
* func :
* history:
*/
#ifndef __LKMP4ENCODER_H_
#define __LKMP4ENCODER_H_
#include "mp4v2/mp4v2.h"
typedef struct _MP4ENC_NaluUnit
{
int type;
int size;
unsigned char *data;
}MP4ENC_NaluUnit;
typedef struct _MP4ENC_Metadata
{
// video, must be h264 type
unsigned int nSpsLen;
unsigned char Sps[1024];
unsigned int nPpsLen;
unsigned char Pps[1024];
unsigned int nUsrLen;
unsigned char Usr[1024];
} MP4ENC_Metadata,*LPMP4ENC_Metadata;
class LKMP4Encoder
{
MP4ENC_Metadata meta;
unsigned char *data;
public:
LKMP4Encoder(void);
~LKMP4Encoder(void);
public:
void setUserData(int bytes, void*user);
// open or creat a mp4 file.
MP4FileHandle createMP4File(const char *fileName,int width,int height,int timeScale = 90000,int frameRate = 25);
// wirte 264 metadata in mp4 file.
bool write264Metadata(MP4FileHandle hMp4File,LPMP4ENC_Metadata lpMetadata);
// wirte 264 data, data can contain multiple frame.
int writeH264Data(MP4FileHandle hMp4File,const unsigned char* pData,int size);
int writeAACData(MP4FileHandle hMp4File,const unsigned char* pData,int size);
int writeH264DataNalu(MP4FileHandle hMp4File,const unsigned char* nalu_data,int nalu_size,int nalu_type);
// close mp4 file.
void closeMP4File(MP4FileHandle hMp4File);
// convert H264 file to mp4 file.
// no need to call CreateMP4File and CloseMP4File,it will create/close mp4 file automaticly.
bool writeH264File(const char* pFile264,const char* pFileMp4);
// Prase H264 metamata from H264 data frame
static bool praseMetadata(const unsigned char* pData,int size,MP4ENC_Metadata &metadata);
void writeH264DataToFile(const unsigned char * bytes,int length);
unsigned char* addHead(const unsigned char * bytes,int length);
private:
// read one nalu from H264 data buffer
static int readOneNaluFromBuf(const unsigned char *buffer,unsigned int nBufferSize,unsigned int offSet,MP4ENC_NaluUnit &nalu);
private:
int m_nWidth;
int m_nHeight;
int m_nFrameRate;
int m_nTimeScale;
bool m_has_pps;
bool m_has_sps;
FILE * m_fp;
//long m_flag = 1;
MP4TrackId m_videoId;
MP4TrackId audio;
};
#endif
|
jjzhang166/AWLive | AWLive/PushStream/LKEncoder/Base/LKVideoEncoder.h | <reponame>jjzhang166/AWLive
/**
* file : LKVideoEncoder.h
* author : Rex
* create : 2017-02-17 17:00
* func :
* history:
*/
#ifndef __LKVIDEOENCODER_H_
#define __LKVIDEOENCODER_H_
#include "LKEncoder.h"
class LKVideoEncoder: public LKEncoder{
public:
LKVideoEncoder(int width=720, int height=1280, float quality=0.75);
virtual bool encodeN12BytesToH264(unsigned char* yuv) = 0;
virtual aw_flv_video_tag* encodeYUVDataToFlvTag(unsigned char* yuv) = 0;
//根据flv,h264,aac协议,提供首帧需要发送的tag
//创建sps pps
virtual aw_flv_video_tag* createSpsPpsFlvTag() = 0;
virtual int encodePiexelBufferToH264(void* pixelbuffer) = 0;
//aw_flv_video_tag* encodeVideoSampleBufferToFlvTag(void* sample);
aw_x264_config m_video_config;
bool m_is_keyframe;
uint32_t m_frame_count;
};
#endif
|
jjzhang166/AWLive | AWLive/PushStream/LKEncoder/SW/LKSWFaacEncoder.h | <filename>AWLive/PushStream/LKEncoder/SW/LKSWFaacEncoder.h
/**
* file : LKSWFaacEncoder.h
* author : Rex
* create : 2017-02-17 17:02
* func :
* history:
*/
#ifndef __LKSWFAACENCODER_H_
#define __LKSWFAACENCODER_H_
#endif
|
jjzhang166/AWLive | AWMedia/AWMedia.h | <reponame>jjzhang166/AWLive<filename>AWMedia/AWMedia.h
//
// AWMedia.h
// AWMedia
//
// Created by Visionin on 17/2/17.
//
//
#import <UIKit/UIKit.h>
//! Project version number for AWMedia.
FOUNDATION_EXPORT double AWMediaVersionNumber;
//! Project version string for AWMedia.
FOUNDATION_EXPORT const unsigned char AWMediaVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <AWMedia/PublicHeader.h>
#include "LKHWH264Encoder.h"
|
jjzhang166/AWLive | clibs/3th-party/jrtplib/include/rtpaddress.h | /*
This file is a part of JRTPLIB
Copyright (c) 1999-2011 <NAME>
Contact: <EMAIL>
This library was developed at the Expertise Centre for Digital Media
(http://www.edm.uhasselt.be), a research center of the Hasselt University
(http://www.uhasselt.be). The library is based upon work done for
my thesis at the School for Knowledge Technology (Belgium/The Netherlands).
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.
*/
/**
* \file rtpaddress.h
*/
#ifndef RTPADDRESS_H
#define RTPADDRESS_H
#include "rtpconfig.h"
#include <string>
namespace jrtplib
{
class RTPMemoryManager;
/** This class is an abstract class which is used to specify destinations, multicast groups etc. */
class RTPAddress
{
public:
/** Identifies the actual implementation being used. */
enum AddressType
{
IPv4Address, /**< Used by the UDP over IPv4 transmitter. */
IPv6Address, /**< Used by the UDP over IPv6 transmitter. */
ByteAddress, /**< A very general type of address, consisting of a port number and a number of bytes representing the host address. */
UserDefinedAddress /**< Can be useful for a user-defined transmitter. */
};
/** Returns the type of address the actual implementation represents. */
AddressType GetAddressType() const { return addresstype; }
/** Creates a copy of the RTPAddress instance.
* Creates a copy of the RTPAddress instance. If \c mgr is not NULL, the
* corresponding memory manager will be used to allocate the memory for the address
* copy.
*/
virtual RTPAddress *CreateCopy(RTPMemoryManager *mgr) const = 0;
/** Checks if the address \c addr is the same address as the one this instance represents.
* Checks if the address \c addr is the same address as the one this instance represents.
* Implementations must be able to handle a NULL argument.
*/
virtual bool IsSameAddress(const RTPAddress *addr) const = 0;
/** Checks if the address \c addr represents the same host as this instance.
* Checks if the address \c addr represents the same host as this instance. Implementations
* must be able to handle a NULL argument.
*/
virtual bool IsFromSameHost(const RTPAddress *addr) const = 0;
#ifdef RTPDEBUG
virtual std::string GetAddressString() const = 0;
#endif // RTPDEBUG
virtual ~RTPAddress() { }
protected:
// only allow subclasses to be created
RTPAddress(const AddressType t) : addresstype(t) { }
private:
const AddressType addresstype;
};
} // end namespace
#endif // RTPADDRESS_H
|
jjzhang166/AWLive | clibs/libaw/bs_type.h | <filename>clibs/libaw/bs_type.h
/**
* @file bs_type.h
* @author bushaofeng(<EMAIL>)
* @date 2011/11/21 16:31:25
* @brief
*
**/
#ifndef __BS_TYPE_H_
#define __BS_TYPE_H_
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <netdb.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <stdint.h>
#include <arpa/inet.h>
#include <errno.h>
#include <signal.h>
#include <net/if.h>
//#include <net/if_arp.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <math.h>
#ifdef __cplusplus
extern "C"{
#endif
typedef int state_t;
typedef int status_t;
#ifndef _STDINT_H
#ifndef __int8_t_defined
#ifndef _INT8_T
typedef char int8_t;
#endif
typedef unsigned char uint8_t;
typedef short int16_t;
typedef unsigned short uint16_t;
typedef int int32_t;
typedef unsigned int uint32_t;
typedef long long int64_t;
typedef unsigned long long uint64_t;
#endif
#endif
typedef unsigned char byte;
typedef int bool_t;
#define BS_TRUE 1
#define BS_FALSE 0
#define BS_NOTBOOL -1
typedef int (* compare_f)(void* e1, void* e2);
typedef enum _data_type_t{
BS_TYPE_INT = 0,
BS_TYPE_INT8,
BS_TYPE_INT16,
BS_TYPE_INT32,
BS_TYPE_INT64,
BS_TYPE_STRING,
BS_TYPE_OBJECT,
BS_TYPE_NUM
}data_type_t;
typedef enum _code_t{
BS_CODE_GB2312,
BS_CODE_GB18030,
BS_CODE_UTF8,
BS_CODE_ANSI,
BS_CODE_UNICODE,
BS_CODE_NUM
}code_t;
typedef enum _lang_t{
BS_CHINESE,
BS_LANGNUM
}lang_t;
#ifdef __cplusplus
}
#endif
#endif //__BS_TYPE_H_
/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
|
jjzhang166/AWLive | AWLive/PushStream/LKEncoder/RTP/LKRtpSession.h | <filename>AWLive/PushStream/LKEncoder/RTP/LKRtpSession.h
//
// LKRtpSession.hpp
// AWLive
//
// Created by Visionin on 17/3/13.
//
//
#ifndef LKRtpSession_hpp
#define LKRtpSession_hpp
#include <stdio.h>
#include "rtpsession.h"
class LKRtpSession: public jrtplib::RTPSession{
public:
LKRtpSession(int port, int timestamp);
protected:
};
#endif /* LKRtpSession_hpp */
|
jjzhang166/AWLive | clibs/libaw/pushStream/encoder/aw_sw_faac_encoder.h | <filename>clibs/libaw/pushStream/encoder/aw_sw_faac_encoder.h
/*
copyright 2016 wanghongyu.
The project page:https://github.com/hardman/AWLive
My blog page: http://blog.csdn.net/hard_man/
*/
#ifndef aw_sw_faac_encoder_h
#define aw_sw_faac_encoder_h
/*
使用faac进行软编码:aac软编码器。
*/
#include "aw_faac.h"
#include "aw_encode_flv.h"
#ifdef __cplusplus
extern "C"{
#endif
//编码器开关
extern void aw_sw_encoder_open_faac_encoder(aw_faac_config *faac_config);
extern void aw_sw_encoder_close_faac_encoder();
//对pcm数据进行faac软编码,并转成flv_audio_tag
extern aw_flv_audio_tag *aw_sw_encoder_encode_faac_data(int8_t *pcm_data, long len, uint32_t timestamp);
//根据faac_config 创建包含audio specific config 的flv tag
extern aw_flv_audio_tag *aw_sw_encoder_create_faac_specific_config_tag();
//获取每帧输入样本数量 用来计算时间戳,除以样本率就是一帧的duration。
extern uint32_t aw_sw_faac_encoder_max_input_sample_count();
//编码器是否合法
extern int8_t aw_sw_faac_encoder_is_valid();
//下面2个函数所有编码器都可以用
//将aac数据转为flv_audio_tag
extern aw_flv_audio_tag *aw_encoder_create_audio_tag(int8_t *aac_data, long len, uint32_t timeStamp, aw_faac_config *faac_cfg);
//创建audio_specific_config_tag
extern aw_flv_audio_tag *aw_encoder_create_audio_specific_config_tag(aw_data *audio_specific_config_data, aw_faac_config *faac_config);
#ifdef __cplusplus
}
#endif
#endif /* aw_sw_audio_encoder_h */
|
jjzhang166/AWLive | clibs/libaw/common/aw_utils.h | /*
copyright 2016 wanghongyu.
The project page:https://github.com/hardman/AWLive
My blog page: http://blog.csdn.net/hard_man/
*/
/*
utils log等便利函数
*/
#ifndef aw_utils_h
#define aw_utils_h
#include <stdio.h>
#include <string.h>
#include "aw_alloc.h"
#define AWLog(...) \
do{ \
printf(__VA_ARGS__); \
printf("\n");\
}while(0)
#define aw_log(...) AWLog(__VA_ARGS__)
//视频编码加速,stride须设置为16的倍数
#define aw_stride(wid) ((wid % 16 != 0) ? ((wid) + 16 - (wid) % 16): (wid))
#endif /* aw_utils_h */
|
jjzhang166/AWLive | AWLive/PushStream/LKEncoder/Base/LKAudioEncoder.h | /**
* file : LKAudioEncoder.h
* author : Rex
* create : 2017-02-17 16:59
* func :
* history:
*/
#ifndef __LKAUDIOENCODER_H_
#define __LKAUDIOENCODER_H_
#endif
|
jjzhang166/AWLive | clibs/3th-party/jrtplib/include/rtcprrpacket.h | /*
This file is a part of JRTPLIB
Copyright (c) 1999-2011 <NAME>
Contact: <EMAIL>
This library was developed at the Expertise Centre for Digital Media
(http://www.edm.uhasselt.be), a research center of the Hasselt University
(http://www.uhasselt.be). The library is based upon work done for
my thesis at the School for Knowledge Technology (Belgium/The Netherlands).
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.
*/
/**
* \file rtcprrpacket.h
*/
#ifndef RTCPRRPACKET_H
#define RTCPRRPACKET_H
#include "rtpconfig.h"
#include "rtcppacket.h"
#include "rtpstructs.h"
#if ! (defined(WIN32) || defined(_WIN32_WCE))
#include <netinet/in.h>
#endif // WIN32
namespace jrtplib
{
class RTCPCompoundPacket;
/** Describes an RTCP receiver report packet. */
class RTCPRRPacket : public RTCPPacket
{
public:
/** Creates an instance based on the data in \c data with length \c datalen.
* Creates an instance based on the data in \c data with length \c datalen. Since the \c data pointer
* is referenced inside the class (no copy of the data is made) one must make sure that the memory it points
* to is valid as long as the class instance exists.
*/
RTCPRRPacket(uint8_t *data,size_t datalen);
~RTCPRRPacket() { }
/** Returns the SSRC of the participant who sent this packet. */
uint32_t GetSenderSSRC() const;
/** Returns the number of reception report blocks present in this packet. */
int GetReceptionReportCount() const;
/** Returns the SSRC of the reception report block described by \c index which may have a value
* from 0 to GetReceptionReportCount()-1 (note that no check is performed to see if \c index is
* valid).
*/
uint32_t GetSSRC(int index) const;
/** Returns the `fraction lost' field of the reception report described by \c index which may have
* a value from 0 to GetReceptionReportCount()-1 (note that no check is performed to see if \c index is
* valid).
*/
uint8_t GetFractionLost(int index) const;
/** Returns the number of lost packets in the reception report block described by \c index which may have
* a value from 0 to GetReceptionReportCount()-1 (note that no check is performed to see if \c index is
* valid).
*/
int32_t GetLostPacketCount(int index) const;
/** Returns the extended highest sequence number of the reception report block described by \c index which may have
* a value from 0 to GetReceptionReportCount()-1 (note that no check is performed to see if \c index is
* valid).
*/
uint32_t GetExtendedHighestSequenceNumber(int index) const;
/** Returns the jitter field of the reception report block described by \c index which may have
* a value from 0 to GetReceptionReportCount()-1 (note that no check is performed to see if \c index is
* valid).
*/
uint32_t GetJitter(int index) const;
/** Returns the LSR field of the reception report block described by \c index which may have
* a value from 0 to GetReceptionReportCount()-1 (note that no check is performed to see if \c index is
* valid).
*/
uint32_t GetLSR(int index) const;
/** Returns the DLSR field of the reception report block described by \c index which may have
* a value from 0 to GetReceptionReportCount()-1 (note that no check is performed to see if \c index is
* valid).
*/
uint32_t GetDLSR(int index) const;
#ifdef RTPDEBUG
void Dump();
#endif // RTPDEBUG
private:
RTCPReceiverReport *GotoReport(int index) const;
};
inline uint32_t RTCPRRPacket::GetSenderSSRC() const
{
if (!knownformat)
return 0;
uint32_t *ssrcptr = (uint32_t *)(data+sizeof(RTCPCommonHeader));
return ntohl(*ssrcptr);
}
inline int RTCPRRPacket::GetReceptionReportCount() const
{
if (!knownformat)
return 0;
RTCPCommonHeader *hdr = (RTCPCommonHeader *)data;
return ((int)hdr->count);
}
inline RTCPReceiverReport *RTCPRRPacket::GotoReport(int index) const
{
RTCPReceiverReport *r = (RTCPReceiverReport *)(data+sizeof(RTCPCommonHeader)+sizeof(uint32_t)+index*sizeof(RTCPReceiverReport));
return r;
}
inline uint32_t RTCPRRPacket::GetSSRC(int index) const
{
if (!knownformat)
return 0;
RTCPReceiverReport *r = GotoReport(index);
return ntohl(r->ssrc);
}
inline uint8_t RTCPRRPacket::GetFractionLost(int index) const
{
if (!knownformat)
return 0;
RTCPReceiverReport *r = GotoReport(index);
return r->fractionlost;
}
inline int32_t RTCPRRPacket::GetLostPacketCount(int index) const
{
if (!knownformat)
return 0;
RTCPReceiverReport *r = GotoReport(index);
uint32_t count = ((uint32_t)r->packetslost[2])|(((uint32_t)r->packetslost[1])<<8)|(((uint32_t)r->packetslost[0])<<16);
if ((count&0x00800000) != 0) // test for negative number
count |= 0xFF000000;
int32_t *count2 = (int32_t *)(&count);
return (*count2);
}
inline uint32_t RTCPRRPacket::GetExtendedHighestSequenceNumber(int index) const
{
if (!knownformat)
return 0;
RTCPReceiverReport *r = GotoReport(index);
return ntohl(r->exthighseqnr);
}
inline uint32_t RTCPRRPacket::GetJitter(int index) const
{
if (!knownformat)
return 0;
RTCPReceiverReport *r = GotoReport(index);
return ntohl(r->jitter);
}
inline uint32_t RTCPRRPacket::GetLSR(int index) const
{
if (!knownformat)
return 0;
RTCPReceiverReport *r = GotoReport(index);
return ntohl(r->lsr);
}
inline uint32_t RTCPRRPacket::GetDLSR(int index) const
{
if (!knownformat)
return 0;
RTCPReceiverReport *r = GotoReport(index);
return ntohl(r->dlsr);
}
} // end namespace
#endif // RTCPRRPACKET_H
|
jjzhang166/AWLive | AWLive/PushStream/Encoder/Base/AWVideoEncoder.h | <reponame>jjzhang166/AWLive
/*
copyright 2016 wanghongyu.
The project page:https://github.com/hardman/AWLive
My blog page: http://blog.csdn.net/hard_man/
*/
/*
视频编码器基类,只声明接口,和一些公共转换数据函数。
*/
#import "AWEncoder.h"
@interface AWVideoEncoder : AWEncoder
@property (nonatomic, copy) AWVideoConfig *videoConfig;
//旋转
-(NSData *)rotateNV12Data:(NSData *)nv12Data;
//编码
-(aw_flv_video_tag *) encodeYUVDataToFlvTag:(NSData *)yuvData;
-(aw_flv_video_tag *) encodeVideoSampleBufToFlvTag:(CMSampleBufferRef)videoSample;
//根据flv,h264,aac协议,提供首帧需要发送的tag
//创建sps pps
-(aw_flv_video_tag *) createSpsPpsFlvTag;
//转换
-(NSData *) convertVideoSmapleBufferToYuvData:(CMSampleBufferRef) videoSample;
@end
|
jjzhang166/AWLive | clibs/libaw/pushStream/rtmp/aw_streamer.c | /*
copyright 2016 wanghongyu.
The project page:https://github.com/hardman/AWLive
My blog page: http://blog.csdn.net/hard_man/
*/
#include "aw_streamer.h"
#include "aw_utils.h"
#include "aw_rtmp.h"
#include "aw_encode_flv.h"
#include <unistd.h>
#include <inttypes.h>
#include "aw_thread_poll.h"
#include "aw_array.h"
//open stream 使用的变量
static aw_rtmp_context *s_rtmp_ctx = NULL;
static aw_data *s_output_buf = NULL;
static aw_rtmp_state_changed_cb s_state_changed_cb = NULL;
static char *s_rtmp_url = NULL;
//rtmp
static int8_t aw_streamer_is_rtmp_valid();
static void aw_streamer_send_flv_tag_to_rtmp(aw_flv_common_tag *common_tag);
static void aw_streamer_rtmp_state_changed_callback(aw_rtmp_state old_state, aw_rtmp_state new_state);
//rtmp
static int8_t aw_steamer_open_rtmp_context();
static void aw_streamer_close_rtmp_context();
//video-----
extern void aw_streamer_send_video_data(aw_flv_video_tag *video_tag){
if (!aw_streamer_is_rtmp_valid()) {
aw_log("[E] aw_streamer_send_video_data s_rtmp_ctx is NULL");
return;
}
// aw_log("[D] aw_streamer_send_video_data timestamp=%u, compTime=%u", video_tag->common_tag.timestamp, video_tag->h264_composition_time);
aw_streamer_send_flv_tag_to_rtmp(&video_tag->common_tag);
}
extern void aw_streamer_send_video_sps_pps_tag(aw_flv_video_tag *sps_pps_tag){
if (!aw_streamer_is_rtmp_valid()) {
aw_log("[E] aw_streamer_send_video_sps_pps_tag when rtmp is not valid");
return;
}
if (s_rtmp_ctx->is_header_sent) {
return;
}
//发送 video sps pps
aw_streamer_send_flv_tag_to_rtmp(&sps_pps_tag->common_tag);
}
//audio------
extern void aw_streamer_send_audio_specific_config_tag(aw_flv_audio_tag *asc_tag){
if (!aw_streamer_is_rtmp_valid()) {
aw_log("[E] aw_streamer_send_audio_specific_config_tag when rtmp is not valid");
return;
}
if (s_rtmp_ctx->is_header_sent) {
return;
}
//发送 audio specific config
aw_streamer_send_flv_tag_to_rtmp(&asc_tag->common_tag);
}
extern void aw_streamer_send_audio_data(aw_flv_audio_tag *audio_tag){
if (!aw_streamer_is_rtmp_valid()) {
aw_log("[E] aw_streamer_send_audio_specific_config_tag when rtmp is not valid");
return;
}
aw_streamer_send_flv_tag_to_rtmp(&audio_tag->common_tag);
}
//rtmp------
static void aw_streamer_send_flv_tag_to_rtmp(aw_flv_common_tag *common_tag){
if (!aw_streamer_is_streaming()) {
return;
}
if (common_tag) {
aw_write_flv_tag(&s_output_buf, common_tag);
switch (common_tag->tag_type) {
case aw_flv_tag_type_audio: {
free_aw_flv_audio_tag(&common_tag->audio_tag);
break;
}
case aw_flv_tag_type_video: {
free_aw_flv_video_tag(&common_tag->video_tag);
break;
}
case aw_flv_tag_type_script: {
free_aw_flv_script_tag(&common_tag->script_tag);
break;
}
}
}
if (s_output_buf->size <= 0) {
return;
}
// int nRet =
aw_rtmp_write(s_rtmp_ctx, (const char *)s_output_buf->data, s_output_buf->size);
// aw_log("[d] send flv tag size=%d sended_size=%d", s_output_buf->size, nRet);
reset_aw_data(&s_output_buf);
}
static int8_t aw_streamer_is_rtmp_valid(){
return s_rtmp_ctx != NULL;
}
extern int8_t aw_streamer_is_streaming(){
// return aw_streamer_is_rtmp_valid() && aw_streamer_is_video_valid() && aw_streamer_is_audio_valid() && aw_is_rtmp_opened(s_rtmp_ctx);
return aw_streamer_is_rtmp_valid() && aw_is_rtmp_opened(s_rtmp_ctx);
}
static void aw_streamer_rtmp_state_changed_callback(aw_rtmp_state old_state, aw_rtmp_state new_state){
if(new_state == aw_rtmp_state_connected){
//打开rtmp 先发送 配置tag
// aw_streamer_send_video_sps_pps_tag();
// aw_streamer_send_audio_specific_config_tag();
}else if(new_state == aw_rtmp_state_error_open){
aw_streamer_close_rtmp_context();
}
if (s_state_changed_cb) {
s_state_changed_cb(old_state, new_state);
}
}
static int8_t aw_steamer_open_rtmp_context(){
if (!s_rtmp_ctx) {
s_rtmp_ctx = alloc_aw_rtmp_context(s_rtmp_url, aw_streamer_rtmp_state_changed_callback);
}
return aw_rtmp_open(s_rtmp_ctx);
}
static void aw_streamer_close_rtmp_context(){
if (s_rtmp_ctx) {
aw_rtmp_close(s_rtmp_ctx);
}
aw_log("[d] closed rtmp context");
}
//创建 outbuf
static void aw_streamer_create_out_buf(){
if (s_output_buf) {
aw_log("[E] aw_streamer_open_encoder s_out_buf is already exist");
return;
}
s_output_buf = alloc_aw_data(0);
}
//释放 outbuf
static void aw_streamer_release_out_buf(){
if (!s_output_buf) {
aw_log("[E] aw_streamer_open_encoder s_out_buf is already free");
return;
}
free_aw_data(&s_output_buf);
}
extern int8_t aw_streamer_open(const char *rtmp_url, aw_rtmp_state_changed_cb state_changed_cb){
if (aw_streamer_is_rtmp_valid()) {
aw_log("[E] aw_streamer_open_rtmp s_rtmp_ctx is already open");
return -1;
}
// 调试 mem leak
// aw_uninit_debug_alloc();
// aw_init_debug_alloc();
//创建outbuf
aw_streamer_create_out_buf();
s_state_changed_cb = state_changed_cb;
int32_t rtmp_url_len = (int32_t)strlen(rtmp_url);
if (!s_rtmp_url) {
s_rtmp_url = aw_alloc(rtmp_url_len + 1);
}
memcpy(s_rtmp_url, rtmp_url, rtmp_url_len);
return aw_steamer_open_rtmp_context();
}
extern void aw_streamer_close(){
if (!aw_streamer_is_rtmp_valid()) {
aw_log("[E] aw_streamer_close s_rtmp_ctx is NULL");
return;
}
//关闭rtmp
aw_streamer_close_rtmp_context();
//释放 s_rtmp_ctx;
free_aw_rtmp_context(&s_rtmp_ctx);
s_state_changed_cb = NULL;
if (s_rtmp_url) {
aw_free(s_rtmp_url);
s_rtmp_url = NULL;
}
//释放outbuf
aw_streamer_release_out_buf();
//调试mem leak
// aw_print_alloc_description();
}
|
jjzhang166/AWLive | clibs/3th-party/jrtplib/include/rtcppacketbuilder.h | <filename>clibs/3th-party/jrtplib/include/rtcppacketbuilder.h
/*
This file is a part of JRTPLIB
Copyright (c) 1999-2011 <NAME>
Contact: <EMAIL>
This library was developed at the Expertise Centre for Digital Media
(http://www.edm.uhasselt.be), a research center of the Hasselt University
(http://www.uhasselt.be). The library is based upon work done for
my thesis at the School for Knowledge Technology (Belgium/The Netherlands).
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.
*/
/**
* \file rtcppacketbuilder.h
*/
#ifndef RTCPPACKETBUILDER_H
#define RTCPPACKETBUILDER_H
#include "rtpconfig.h"
#include "rtptypes.h"
#include "rtperrors.h"
#include "rtcpsdesinfo.h"
#include "rtptimeutilities.h"
#include "rtpmemoryobject.h"
namespace jrtplib
{
class RTPSources;
class RTPPacketBuilder;
class RTCPScheduler;
class RTCPCompoundPacket;
class RTCPCompoundPacketBuilder;
/** This class can be used to build RTCP compound packets, on a higher level than the RTCPCompoundPacketBuilder.
* The class RTCPPacketBuilder can be used to build RTCP compound packets. This class is more high-level
* than the RTCPCompoundPacketBuilder class: it uses the information of an RTPPacketBuilder instance and of
* an RTPSources instance to automatically generate the next compound packet which should be sent. It also
* provides functions to determine when SDES items other than the CNAME item should be sent.
*/
class RTCPPacketBuilder : public RTPMemoryObject
{
public:
/** Creates an RTCPPacketBuilder instance.
* Creates an instance which will use the source table \c sources and the RTP packet builder
* \c rtppackbuilder to determine the information for the next RTCP compound packet. Optionally,
* the memory manager \c mgr can be installed.
*/
RTCPPacketBuilder(RTPSources &sources,RTPPacketBuilder &rtppackbuilder, RTPMemoryManager *mgr = 0);
~RTCPPacketBuilder();
/** Initializes the builder.
* Initializes the builder to use the maximum allowed packet size \c maxpacksize, timestamp unit
* \c timestampunit and the SDES CNAME item specified by \c cname with length \c cnamelen.
* The timestamp unit is defined as a time interval divided by the timestamp interval corresponding to
* that interval: for 8000 Hz audio this would be 1/8000.
*/
int Init(size_t maxpacksize,double timestampunit,const void *cname,size_t cnamelen);
/** Cleans up the builder. */
void Destroy();
/** Sets the timestamp unit to be used to \c tsunit.
* Sets the timestamp unit to be used to \c tsunit. The timestamp unit is defined as a time interval
* divided by the timestamp interval corresponding to that interval: for 8000 Hz audio this would
* be 1/8000.
*/
int SetTimestampUnit(double tsunit) { if (!init) return ERR_RTP_RTCPPACKETBUILDER_NOTINIT; if (tsunit < 0) return ERR_RTP_RTCPPACKETBUILDER_ILLEGALTIMESTAMPUNIT; timestampunit = tsunit; return 0; }
/** Sets the maximum size allowed size of an RTCP compound packet to \c maxpacksize. */
int SetMaximumPacketSize(size_t maxpacksize) { if (!init) return ERR_RTP_RTCPPACKETBUILDER_NOTINIT; if (maxpacksize < RTP_MINPACKETSIZE) return ERR_RTP_RTCPPACKETBUILDER_ILLEGALMAXPACKSIZE; maxpacketsize = maxpacksize; return 0; }
/** This function allows you to inform RTCP packet builder about the delay between sampling the first
* sample of a packet and sending the packet.
* This function allows you to inform RTCP packet builder about the delay between sampling the first
* sample of a packet and sending the packet. This delay is taken into account when calculating the
* relation between RTP timestamp and wallclock time, used for inter-media synchronization.
*/
int SetPreTransmissionDelay(const RTPTime &delay) { if (!init) return ERR_RTP_RTCPPACKETBUILDER_NOTINIT; transmissiondelay = delay; return 0; }
/** Builds the next RTCP compound packet which should be sent and stores it in \c pack. */
int BuildNextPacket(RTCPCompoundPacket **pack);
/** Builds a BYE packet with reason for leaving specified by \c reason and length \c reasonlength.
* Builds a BYE packet with reason for leaving specified by \c reason and length \c reasonlength. If
* \c useSRifpossible is set to \c true, the RTCP compound packet will start with a sender report if
* allowed. Otherwise, a receiver report is used.
*/
int BuildBYEPacket(RTCPCompoundPacket **pack,const void *reason,size_t reasonlength,bool useSRifpossible = true);
/** Sets the RTCP interval for the SDES name item.
* After all possible sources in the source table have been processed, the class will check if other
* SDES items need to be sent. If \c count is zero or negative, nothing will happen. If \c count
* is positive, an SDES name item will be added after the sources in the source table have been
* processed \c count times.
*/
void SetNameInterval(int count) { if (!init) return; interval_name = count; }
/** Sets the RTCP interval for the SDES e-mail item.
* After all possible sources in the source table have been processed, the class will check if other
* SDES items need to be sent. If \c count is zero or negative, nothing will happen. If \c count
* is positive, an SDES e-mail item will be added after the sources in the source table have been
* processed \c count times.
*/
void SetEMailInterval(int count) { if (!init) return; interval_email = count; }
/** Sets the RTCP interval for the SDES location item.
* After all possible sources in the source table have been processed, the class will check if other
* SDES items need to be sent. If \c count is zero or negative, nothing will happen. If \c count
* is positive, an SDES location item will be added after the sources in the source table have been
* processed \c count times.
*/
void SetLocationInterval(int count) { if (!init) return; interval_location = count; }
/** Sets the RTCP interval for the SDES phone item.
* After all possible sources in the source table have been processed, the class will check if other
* SDES items need to be sent. If \c count is zero or negative, nothing will happen. If \c count
* is positive, an SDES phone item will be added after the sources in the source table have been
* processed \c count times.
*/
void SetPhoneInterval(int count) { if (!init) return; interval_phone = count; }
/** Sets the RTCP interval for the SDES tool item.
* After all possible sources in the source table have been processed, the class will check if other
* SDES items need to be sent. If \c count is zero or negative, nothing will happen. If \c count
* is positive, an SDES tool item will be added after the sources in the source table have been
* processed \c count times.
*/
void SetToolInterval(int count) { if (!init) return; interval_tool = count; }
/** Sets the RTCP interval for the SDES note item.
* After all possible sources in the source table have been processed, the class will check if other
* SDES items need to be sent. If \c count is zero or negative, nothing will happen. If \c count
* is positive, an SDES note item will be added after the sources in the source table have been
* processed \c count times.
*/
void SetNoteInterval(int count) { if (!init) return; interval_note = count; }
/** Sets the SDES name item for the local participant to the value \c s with length \c len. */
int SetLocalName(const void *s,size_t len) { if (!init) return ERR_RTP_RTCPPACKETBUILDER_NOTINIT; return ownsdesinfo.SetName((const uint8_t *)s,len); }
/** Sets the SDES e-mail item for the local participant to the value \c s with length \c len. */
int SetLocalEMail(const void *s,size_t len) { if (!init) return ERR_RTP_RTCPPACKETBUILDER_NOTINIT; return ownsdesinfo.SetEMail((const uint8_t *)s,len); }
/** Sets the SDES location item for the local participant to the value \c s with length \c len. */
int SetLocalLocation(const void *s,size_t len) { if (!init) return ERR_RTP_RTCPPACKETBUILDER_NOTINIT; return ownsdesinfo.SetLocation((const uint8_t *)s,len); }
/** Sets the SDES phone item for the local participant to the value \c s with length \c len. */
int SetLocalPhone(const void *s,size_t len) { if (!init) return ERR_RTP_RTCPPACKETBUILDER_NOTINIT; return ownsdesinfo.SetPhone((const uint8_t *)s,len); }
/** Sets the SDES tool item for the local participant to the value \c s with length \c len. */
int SetLocalTool(const void *s,size_t len) { if (!init) return ERR_RTP_RTCPPACKETBUILDER_NOTINIT; return ownsdesinfo.SetTool((const uint8_t *)s,len); }
/** Sets the SDES note item for the local participant to the value \c s with length \c len. */
int SetLocalNote(const void *s,size_t len) { if (!init) return ERR_RTP_RTCPPACKETBUILDER_NOTINIT; return ownsdesinfo.SetNote((const uint8_t *)s,len); }
/** Returns the own CNAME item with length \c len */
uint8_t *GetLocalCNAME(size_t *len) const { if (!init) return 0; return ownsdesinfo.GetCNAME(len); }
private:
void ClearAllSourceFlags();
int FillInReportBlocks(RTCPCompoundPacketBuilder *pack,const RTPTime &curtime,int maxcount,bool *full,int *added,int *skipped,bool *atendoflist);
int FillInSDES(RTCPCompoundPacketBuilder *pack,bool *full,bool *processedall,int *added);
void ClearAllSDESFlags();
RTPSources &sources;
RTPPacketBuilder &rtppacketbuilder;
bool init;
size_t maxpacketsize;
double timestampunit;
bool firstpacket;
RTPTime prevbuildtime,transmissiondelay;
class RTCPSDESInfoInternal : public RTCPSDESInfo
{
public:
RTCPSDESInfoInternal(RTPMemoryManager *mgr) : RTCPSDESInfo(mgr) { ClearFlags(); }
void ClearFlags() { pname = false; pemail = false; plocation = false; pphone = false; ptool = false; pnote = false; }
bool ProcessedName() const { return pname; }
bool ProcessedEMail() const { return pemail; }
bool ProcessedLocation() const { return plocation; }
bool ProcessedPhone() const { return pphone; }
bool ProcessedTool() const { return ptool; }
bool ProcessedNote() const { return pnote; }
void SetProcessedName(bool v) { pname = v; }
void SetProcessedEMail(bool v) { pemail = v; }
void SetProcessedLocation(bool v) { plocation = v; }
void SetProcessedPhone(bool v) { pphone = v; }
void SetProcessedTool(bool v) { ptool = v; }
void SetProcessedNote(bool v) { pnote = v; }
private:
bool pname,pemail,plocation,pphone,ptool,pnote;
};
RTCPSDESInfoInternal ownsdesinfo;
int interval_name,interval_email,interval_location;
int interval_phone,interval_tool,interval_note;
bool doname,doemail,doloc,dophone,dotool,donote;
bool processingsdes;
int sdesbuildcount;
};
} // end namespace
#endif // RTCPPACKETBUILDER_H
|
jjzhang166/AWLive | AWLive/PushStream/LKEncoder/HW/LKHWAACEncoder.h | /**
* file : LKHWAACEncoder.h
* author : Rex
* create : 2017-02-17 17:00
* func :
* history:
*/
#ifndef __LKHWAACENCODER_H_
#define __LKHWAACENCODER_H_
#endif
|
jjzhang166/AWLive | clibs/libaw/common/aw_dict.c | <gh_stars>1-10
/*
copyright 2016 wanghongyu.
The project page:https://github.com/hardman/AWLive
My blog page: http://blog.csdn.net/hard_man/
*/
#include "aw_dict.h"
#include "aw_utils.h"
extern aw_dict_element *alloc_aw_dict_element(){
aw_dict_element *ele = (aw_dict_element *)aw_alloc(sizeof(aw_dict_element));
memset(ele, 0, sizeof(aw_dict_element));
return ele;
}
extern void free_aw_dict_element(aw_dict_element **ele, int8_t need_repeat){
aw_dict_element *ele_inner = *ele;
aw_dict_element *repeat_ele = ele_inner->repeat_next;
if (need_repeat) {
while (repeat_ele) {
aw_dict_element *inner_repeat_ele = repeat_ele;
repeat_ele = repeat_ele->repeat_next;
free_aw_dict_element(&inner_repeat_ele, 0);
}
}
switch (ele_inner->type) {
case AW_DICT_ELEMENT_TYPE_STRING:
aw_free((void *)ele_inner->string_value);
break;
case AW_DICT_ELEMENT_TYPE_RELEASE_POINTER:
if (ele_inner->free_pointer) {
ele_inner->free_pointer(ele_inner->pointer_value, ele_inner->extra);
}else{
aw_free(ele_inner->pointer_value);
}
break;
default:
break;
}
if (ele_inner->key) {
aw_free((void *)ele_inner->key);
}
aw_free(ele_inner);
*ele = NULL;
}
extern aw_dict *alloc_aw_dict(){
aw_dict *dict = (aw_dict *)aw_alloc(sizeof(aw_dict));
memset(dict, 0, sizeof(aw_dict));
dict->repeat_seperate_word = '.';
return dict;
}
extern void free_aw_dict(aw_dict **dict){
aw_dict *dictp = *dict;
aw_dict_element *ele = dictp->first;
while (ele) {
dictp->first = ele->next;
free_aw_dict_element(&ele, 1);
ele = dictp->first;
}
aw_free(*dict);
*dict = NULL;
}
static int is_equal_key(const char *key1, const char *key2){
return !strcmp(key1, key2);
}
static int8_t parse_realkey_and_index(const char *key, char **real_key, int *index, char repeat_seprate_word){
char *p_c = strchr(key, repeat_seprate_word);
if (p_c) {
size_t real_key_size = p_c - key;
char *in_real_key = aw_alloc(real_key_size);
memset(in_real_key, 0, real_key_size);
memcpy(in_real_key, key, real_key_size);
*real_key = in_real_key;
size_t count_str_size = strlen(key) - real_key_size - 1;
char *count_str = aw_alloc(count_str_size + 1);
memset(count_str, 0, count_str_size + 1);
memcpy(count_str, key + real_key_size + 1, count_str_size);
*index = atoi(count_str);
aw_free(count_str);
return 1;
}else{
*real_key = (char *)key;
return 0;
}
}
static aw_dict_element * aw_dict_find_ele(aw_dict *dict, const char *key){
aw_dict_element *ele = dict->first;
if (!ele || !key || !ele->key) {
return NULL;
}
char *real_key = NULL;
int repeat_count = -1;
int8_t need_free_key = parse_realkey_and_index(key, &real_key, &repeat_count, dict->repeat_seperate_word);
aw_dict_element *repeat_ele = NULL;
while (ele) {
if (!is_equal_key(real_key, ele->key)) {
ele = ele->next;
}else{
repeat_ele = ele;
break;
}
}
if (need_free_key) {
aw_free(real_key);
}
//查找repeat_next
if (repeat_count >= 0) {
int i = 0;
for (; i < repeat_count; i++) {
if (!repeat_ele) {
return NULL;
}
repeat_ele = repeat_ele->repeat_next;
}
}
return repeat_ele;
}
static aw_dict_element *aw_dict_add_new_ele(aw_dict *dict, const char *key, int allow_repeat){
aw_dict_element *ele = aw_dict_find_ele(dict, key);
//检查key,不允许带"."
char *p_c = strchr(key, dict->repeat_seperate_word);
if (p_c) {
AWLog("in aw_dict_add_new_ele dont contains '%c' in key(%s)", dict->repeat_seperate_word, key);
return NULL;
}
if (ele) {
if (allow_repeat) {
aw_dict_element *repeat_ele = ele;
while (repeat_ele->repeat_next) {
repeat_ele = repeat_ele->repeat_next;
}
aw_dict_element *new_repeat_ele = alloc_aw_dict_element();
repeat_ele->repeat_next = new_repeat_ele;
new_repeat_ele->repeat_pre = repeat_ele;
ele = new_repeat_ele;
}else{
ele = NULL;
}
}else{
if (!dict->first) {
dict->first = alloc_aw_dict_element();
dict->last = dict->first;
ele = dict->first;
}else{
ele = alloc_aw_dict_element();
dict->last->next = ele;
ele->pre = dict->last;
dict->last = ele;
}
}
if (ele) {
int ele_key_len = (int)strlen(key) + 1;
char *ele_key = aw_alloc(ele_key_len);
memset(ele_key, 0, ele_key_len);
memcpy(ele_key, key, ele_key_len - 1);
ele->key = ele_key;
}
return ele;
}
int8_t aw_dict_remove_object(aw_dict *dict, const char *key){
aw_dict_element *first = dict->first;
if (!first || !key || !first->key) {
return 0;
}
char *real_key = NULL;
int repeat_count = -1;
int8_t need_free_key = parse_realkey_and_index(key, &real_key, &repeat_count, dict->repeat_seperate_word);
if (real_key) {
aw_dict_element *ele = aw_dict_find_ele(dict, key);
if (need_free_key) {
aw_free(real_key);
}
if (ele) {
if (repeat_count >= 0) {
//移除的是repeat的element
if (repeat_count == 0) {
//移除repeat结点中的根结点
aw_dict_element *repeat_next = ele->repeat_next;
if (repeat_next) {
if (ele->pre) {
repeat_next->pre = ele->pre;
ele->pre->next = repeat_next;
}
if (ele->next) {
repeat_next->next = ele->next;
ele->next->pre = repeat_next;
}
if (ele == dict->first) {
dict->first = repeat_next;
}else if(ele == dict->last){
dict->last = repeat_next;
}
}else{
if (ele == dict->first) {
dict->first = ele->next;
}else if(ele == dict->last){
dict->last = ele->pre;
}else{
ele->pre->next = ele->next;
ele->next->pre = ele->pre;
ele->pre = NULL;
ele->next = NULL;
}
}
}else{
//移除repeat结点中的非根结点
ele->repeat_pre->repeat_next = ele->repeat_next;
ele->repeat_next->repeat_pre = ele->repeat_pre;
ele->pre = NULL;
ele->next = NULL;
}
free_aw_dict_element(&ele, 0);
}else{
//移除的是主干上的结点
if (ele == dict->first) {
dict->first = ele->next;
}else if(ele == dict->last){
dict->last = ele->pre;
}else{
ele->pre->next = ele->next;
ele->next->pre = ele->pre;
ele->pre = NULL;
ele->next = NULL;
}
free_aw_dict_element(&ele, 1);
}
//检查dict
if(dict->first){
dict->first->pre = NULL;
if (dict->first == dict->last) {
dict->last = NULL;
}
}
if (dict->last) {
dict->last->next = NULL;
}
return 1;
}
}
return 0;
}
int8_t aw_dict_set_str(aw_dict *dict, const char *key, const char *str, int allow_repeat){
aw_dict_element *new_ele = aw_dict_add_new_ele(dict, key, allow_repeat);
if (new_ele) {
int str_len = (int)strlen(str) + 1;
char *new_str = aw_alloc(str_len);
memcpy(new_str, str, str_len);
new_ele->string_value = new_str;
new_ele->type = AW_DICT_ELEMENT_TYPE_STRING;
return 1;
}
return 0;
}
const char *aw_dict_get_str(aw_dict *dict, const char *key){
aw_dict_element *ele = aw_dict_find_ele(dict, key);
if (ele) {
return ele->string_value;
}
return 0;
}
int8_t aw_dict_set_int(aw_dict *dict, const char *key, int32_t value, int allow_repeat){
aw_dict_element *new_ele = aw_dict_add_new_ele(dict, key, allow_repeat);
if (new_ele) {
new_ele->int_value = value;
new_ele->type = AW_DICT_ELEMENT_TYPE_INT;
return 1;
}
return 0;
}
int32_t aw_dict_get_int(aw_dict *dict, const char *key){
aw_dict_element *ele = aw_dict_find_ele(dict, key);
if (ele) {
return ele->int_value;
}
return 0;
}
int8_t aw_dict_set_double(aw_dict *dict, const char *key, double value, int allow_repeat){
aw_dict_element *new_ele = aw_dict_add_new_ele(dict, key, allow_repeat);
if (new_ele) {
new_ele->double_value = value;
new_ele->type = AW_DICT_ELEMENT_TYPE_DOUBLE;
return 1;
}
return 0;
}
double aw_dict_get_double(aw_dict *dict, const char *key){
aw_dict_element *ele = aw_dict_find_ele(dict, key);
if (ele) {
return ele->double_value;
}
return 0;
}
int8_t aw_dict_set_pointer(aw_dict *dict, const char *key, void * value, int allow_repeat){
aw_dict_element *new_ele = aw_dict_add_new_ele(dict, key, allow_repeat);
if (new_ele) {
new_ele->pointer_value = value;
new_ele->type = AW_DICT_ELEMENT_TYPE_POINTER;
return 1;
}
return 0;
}
void * aw_dict_get_pointer(aw_dict *dict, const char *key){
aw_dict_element *ele = aw_dict_find_ele(dict, key);
if (ele) {
return ele->pointer_value;
}
return 0;
}
int8_t aw_dict_set_release_pointer(aw_dict *dict, const char *key, void * value, void(*release_func)(void *, int), int extra, int allow_repeat){
aw_dict_element *new_ele = aw_dict_add_new_ele(dict, key, allow_repeat);
if (new_ele) {
new_ele->pointer_value = value;
new_ele->free_pointer = release_func;
new_ele->extra = extra;
new_ele->type = AW_DICT_ELEMENT_TYPE_RELEASE_POINTER;
return 1;
}
return 0;
}
void * aw_dict_get_release_pointer(aw_dict *dict, const char *key){
aw_dict_element *ele = aw_dict_find_ele(dict, key);
if (ele) {
return ele->pointer_value;
}
return 0;
}
const char *aw_dict_description(aw_dict *dict){
return "";
}
//=============test=================
void aw_dict_test_int(){
aw_dict *dict = alloc_aw_dict();
//test int
aw_dict_set_int(dict, "a", 1, 0);
int a = aw_dict_get_int(dict, "a");
AWLog("a=%d", a);
//repeat int
aw_dict_set_int(dict, "a", 2, 1);
aw_dict_set_int(dict, "a", 3, 1);
aw_dict_set_int(dict, "a", 4, 1);
aw_dict_set_int(dict, "a", 5, 1);
int a1 = aw_dict_get_int(dict, "a.1");
int a2 = aw_dict_get_int(dict, "a.2");
AWLog("a=%d, a1=%d, a2=%d", a, a1, a2);
//test double
aw_dict_set_double(dict, "a", 6.6, 1);
aw_dict_set_double(dict, "a", 7.7, 1);
aw_dict_set_double(dict, "b", 8.8, 1);
aw_dict_set_double(dict, "b", 9.9, 1);
aw_dict_set_double(dict, "b", 10.10, 1);
aw_dict_set_double(dict, "b", 11.11, 1);
aw_dict_set_double(dict, "b", 12.12, 1);
aw_dict_set_double(dict, "b", 13.13, 1);
double d1 = aw_dict_get_double(dict, "a.3");
double d2 = aw_dict_get_double(dict, "a.4");
double d3 = aw_dict_get_double(dict, "b.0");
double d4 = aw_dict_get_double(dict, "b.1");
AWLog("d1=%f, d2=%f, d3=%f, d4=%f", d1, d2, d3, d4);
aw_dict_remove_object(dict, "a.0");
aw_dict_remove_object(dict, "a.1");
a1 = aw_dict_get_int(dict, "a.1");
a2 = aw_dict_get_int(dict, "a.2");
AWLog("---a1=%d, a2=%d", a1, a2);
aw_dict_remove_object(dict, "b.0");
aw_dict_remove_object(dict, "b.1");
aw_dict_remove_object(dict, "b.100");
d1 = aw_dict_get_double(dict, "a.3");
d2 = aw_dict_get_double(dict, "a.4");
d3 = aw_dict_get_double(dict, "b.0");
d4 = aw_dict_get_double(dict, "b.1");
AWLog("d1=%f, d2=%f, d3=%f, d4=%f", d1, d2, d3, d4);//6.6, 7.7, 9.9, 11.11
aw_dict_remove_object(dict, "a");
aw_dict_remove_object(dict, "b");
free_aw_dict(&dict);
AWLog("aw_dict_test int total alloc size = %ld, total free size = %ld", aw_total_alloc_size(), aw_total_free_size());
aw_uninit_debug_alloc();
}
static void aw_dict_test_release_pointer(aw_dict ** entries, int count){
int i = 0;
for (; i < count; i++) {
aw_dict * dict = entries[i];
free_aw_dict(&dict);
}
aw_free(entries);
}
static void aw_dict_test_pointer(){
aw_uninit_debug_alloc();
aw_init_debug_alloc();
aw_dict *dict = alloc_aw_dict();
int count = 100;
aw_dict **entries = aw_alloc(sizeof(aw_dict *) * count);
int i = 0;
for (; i < count; i++) {
aw_dict *dict_in = alloc_aw_dict();
aw_dict_set_int(dict_in, "xx", i, 1);
entries[i] = dict_in;
}
aw_dict_set_release_pointer(dict, "a", entries, (void (*)(void *, int))aw_dict_test_release_pointer, count, 1);
free_aw_dict(&dict);
AWLog("aw_dict_test_pointer int total alloc size = %ld, total free size = %ld", aw_total_alloc_size(), aw_total_free_size());
aw_uninit_debug_alloc();
}
void aw_dict_test(){
aw_dict_test_int();
aw_dict_test_pointer();
}
|
jjzhang166/AWLive | clibs/libaw/common/aw_rtmp.h | /*
copyright 2016 wanghongyu.
The project page:https://github.com/hardman/AWLive
My blog page: http://blog.csdn.net/hard_man/
*/
/*
提供了librtmp的连接、断开、发送数据等操作,并提供完整的事件处理及回调,包括断线重连等机制
*/
#ifndef aw_rtmp_h
#define aw_rtmp_h
#include "rtmp.h"
#include "aw_alloc.h"
#include <string.h>
typedef enum aw_rtmp_state{
aw_rtmp_state_idle,//默认情况
aw_rtmp_state_connecting,//连接中
aw_rtmp_state_connected,//连接成功
aw_rtmp_state_opened,//已打开,可以streaming了
aw_rtmp_state_closed,//关闭,发送后回到idle状态
aw_rtmp_state_error_write,//写入失败,发送完毕回到open状态
aw_rtmp_state_error_open,//打开失败,发送后回到idle
aw_rtmp_state_error_net,//多次连接失败,网络错误
}aw_rtmp_state;
extern const char *aw_rtmp_state_description(aw_rtmp_state rtmp_state);
typedef void (*aw_rtmp_state_changed_cb) (aw_rtmp_state old_state, aw_rtmp_state new_state);
typedef struct aw_rtmp_context{
char rtmp_url[256];
RTMP *rtmp;
//写入错误断线重连
int8_t write_error_retry_time_limit;//写入错误重试次数,超过这个次数就要重连。
int8_t write_error_retry_curr_time;//当前重试错误次数。
//open错误重连
int8_t open_error_retry_time_limit;//连接重试次数,超过这个次数。
int8_t open_error_retry_curr_time;//当前连接重试的次数,表示连接错误。
int8_t is_header_sent;//是不是发送过flv的header了
//当前mp4文件开始时间戳
double current_time_stamp;
double last_time_stamp;
//总时间
double total_duration;
//状态变化回调,注意,不要在状态回调中做释放aw_rtmp_context的操作。
//如果非要释放,请延迟一帧。
aw_rtmp_state_changed_cb state_changed_cb;
//当前状态
aw_rtmp_state rtmp_state;
} aw_rtmp_context;
extern void aw_init_rtmp_context(aw_rtmp_context *ctx, const char *rtmp_url, aw_rtmp_state_changed_cb state_changed_cb);
extern aw_rtmp_context *alloc_aw_rtmp_context(const char *rtmp_url, aw_rtmp_state_changed_cb state_changed_cb);
extern void free_aw_rtmp_context(aw_rtmp_context **ctx);
//rtmp是否打开
extern int8_t aw_is_rtmp_opened(aw_rtmp_context *ctx);
//打开rtmp
extern int aw_rtmp_open(aw_rtmp_context *ctx);
//写入数据
extern int aw_rtmp_write(aw_rtmp_context *ctx, const char *buf, int size);
//关闭rtmp
extern int aw_rtmp_close(aw_rtmp_context *ctx);
//获取当前时间
extern uint32_t aw_rtmp_time();
#endif /* aw_rtmp_h */
|
jjzhang166/AWLive | clibs/3th-party/jrtplib/include/rtprawpacket.h | /*
This file is a part of JRTPLIB
Copyright (c) 1999-2011 <NAME>
Contact: <EMAIL>
This library was developed at the Expertise Centre for Digital Media
(http://www.edm.uhasselt.be), a research center of the Hasselt University
(http://www.uhasselt.be). The library is based upon work done for
my thesis at the School for Knowledge Technology (Belgium/The Netherlands).
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.
*/
/**
* \file rtprawpacket.h
*/
#ifndef RTPRAWPACKET_H
#define RTPRAWPACKET_H
#include "rtpconfig.h"
#include "rtptimeutilities.h"
#include "rtpaddress.h"
#include "rtptypes.h"
#include "rtpmemoryobject.h"
namespace jrtplib
{
/** This class is used by the transmission component to store the incoming RTP and RTCP data in. */
class RTPRawPacket : public RTPMemoryObject
{
public:
/** Creates an instance which stores data from \c data with length \c datalen.
* Creates an instance which stores data from \c data with length \c datalen. Only the pointer
* to the data is stored, no actual copy is made! The address from which this packet originated
* is set to \c address and the time at which the packet was received is set to \c recvtime.
* The flag which indicates whether this data is RTP or RTCP data is set to \c rtp. A memory
* manager can be installed as well.
*/
RTPRawPacket(uint8_t *data,size_t datalen,RTPAddress *address,RTPTime &recvtime,bool rtp,RTPMemoryManager *mgr = 0);
~RTPRawPacket();
/** Returns the pointer to the data which is contained in this packet. */
uint8_t *GetData() { return packetdata; }
/** Returns the length of the packet described by this instance. */
size_t GetDataLength() const { return packetdatalength; }
/** Returns the time at which this packet was received. */
RTPTime GetReceiveTime() const { return receivetime; }
/** Returns the address stored in this packet. */
const RTPAddress *GetSenderAddress() const { return senderaddress; }
/** Returns \c true if this data is RTP data, \c false if it is RTCP data. */
bool IsRTP() const { return isrtp; }
/** Sets the pointer to the data stored in this packet to zero.
* Sets the pointer to the data stored in this packet to zero. This will prevent
* a \c delete call for the actual data when the destructor of RTPRawPacket is called.
* This function is used by the RTPPacket and RTCPCompoundPacket classes to obtain
* the packet data (without having to copy it) and to make sure the data isn't deleted
* when the destructor of RTPRawPacket is called.
*/
void ZeroData() { packetdata = 0; packetdatalength = 0; }
private:
uint8_t *packetdata;
size_t packetdatalength;
RTPTime receivetime;
RTPAddress *senderaddress;
bool isrtp;
};
inline RTPRawPacket::RTPRawPacket(uint8_t *data,size_t datalen,RTPAddress *address,RTPTime &recvtime,bool rtp,RTPMemoryManager *mgr):RTPMemoryObject(mgr),receivetime(recvtime)
{
packetdata = data;
packetdatalength = datalen;
senderaddress = address;
isrtp = rtp;
}
inline RTPRawPacket::~RTPRawPacket()
{
if (packetdata)
RTPDeleteByteArray(packetdata,GetMemoryManager());
if (senderaddress)
RTPDelete(senderaddress,GetMemoryManager());
}
} // end namespace
#endif // RTPRAWPACKET_H
|
jjzhang166/AWLive | clibs/3th-party/jrtplib/include/rtpsessionsources.h | /*
This file is a part of JRTPLIB
Copyright (c) 1999-2011 <NAME>
Contact: <EMAIL>
This library was developed at the Expertise Centre for Digital Media
(http://www.edm.uhasselt.be), a research center of the Hasselt University
(http://www.uhasselt.be). The library is based upon work done for
my thesis at the School for Knowledge Technology (Belgium/The Netherlands).
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.
*/
/**
* \file rtpsessionsources.h
*/
#ifndef RTPSESSIONSOURCES_H
#define RTPSESSIONSOURCES_H
#include "rtpconfig.h"
#include "rtpsources.h"
namespace jrtplib
{
class RTPSession;
class RTPSessionSources : public RTPSources
{
public:
RTPSessionSources(RTPSession &sess,RTPMemoryManager *mgr) : RTPSources(RTPSources::ProbationStore,mgr),rtpsession(sess)
{ owncollision = false; }
~RTPSessionSources() { }
void ClearOwnCollisionFlag() { owncollision = false; }
bool DetectedOwnCollision() const { return owncollision; }
private:
void OnRTPPacket(RTPPacket *pack,const RTPTime &receivetime,
const RTPAddress *senderaddress);
void OnRTCPCompoundPacket(RTCPCompoundPacket *pack,const RTPTime &receivetime,
const RTPAddress *senderaddress);
void OnSSRCCollision(RTPSourceData *srcdat,const RTPAddress *senderaddress,bool isrtp);
void OnCNAMECollision(RTPSourceData *srcdat,const RTPAddress *senderaddress,
const uint8_t *cname,size_t cnamelength);
void OnNewSource(RTPSourceData *srcdat);
void OnRemoveSource(RTPSourceData *srcdat);
void OnTimeout(RTPSourceData *srcdat);
void OnBYETimeout(RTPSourceData *srcdat);
void OnBYEPacket(RTPSourceData *srcdat);
void OnAPPPacket(RTCPAPPPacket *apppacket,const RTPTime &receivetime,
const RTPAddress *senderaddress);
void OnUnknownPacketType(RTCPPacket *rtcppack,const RTPTime &receivetime,
const RTPAddress *senderaddress);
void OnUnknownPacketFormat(RTCPPacket *rtcppack,const RTPTime &receivetime,
const RTPAddress *senderaddress);
void OnNoteTimeout(RTPSourceData *srcdat);
RTPSession &rtpsession;
bool owncollision;
};
} // end namespace
#endif // RTPSESSIONSOURCES_H
|
jjzhang166/AWLive | clibs/3th-party/jrtplib/include/rtpmemoryobject.h | <gh_stars>1-10
/*
This file is a part of JRTPLIB
Copyright (c) 1999-2011 <NAME>
Contact: <EMAIL>
This library was developed at the Expertise Centre for Digital Media
(http://www.edm.uhasselt.be), a research center of the Hasselt University
(http://www.uhasselt.be). The library is based upon work done for
my thesis at the School for Knowledge Technology (Belgium/The Netherlands).
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.
*/
/**
* \file rtpmemoryobject.h
*/
#ifndef RTPMEMORYOBJECT_H
#define RTPMEMORYOBJECT_H
#include "rtpconfig.h"
#include "rtpmemorymanager.h"
namespace jrtplib
{
class RTPMemoryObject
{
protected:
#ifdef RTP_SUPPORT_MEMORYMANAGEMENT
RTPMemoryObject(RTPMemoryManager *memmgr) : mgr(memmgr) { }
#else
RTPMemoryObject(RTPMemoryManager *memmgr) { }
#endif // RTP_SUPPORT_MEMORYMANAGEMENT
virtual ~RTPMemoryObject() { }
#ifdef RTP_SUPPORT_MEMORYMANAGEMENT
RTPMemoryManager *GetMemoryManager() const { return mgr; }
void SetMemoryManager(RTPMemoryManager *m) { mgr = m; }
#else
RTPMemoryManager *GetMemoryManager() const { return 0; }
void SetMemoryManager(RTPMemoryManager *m) { }
#endif // RTP_SUPPORT_MEMORYMANAGEMENT
#ifdef RTP_SUPPORT_MEMORYMANAGEMENT
private:
RTPMemoryManager *mgr;
#endif // RTP_SUPPORT_MEMORYMANAGEMENT
};
} // end namespace
#endif // RTPMEMORYOBJECT_H
|
jjzhang166/AWLive | AWLive/PushStream/Encoder/SW/AWSWFaacEncoder.h | <gh_stars>1-10
/*
copyright 2016 wanghongyu.
The project page:https://github.com/hardman/AWLive
My blog page: http://blog.csdn.net/hard_man/
*/
/*
aac软编码器(faac)
*/
#import "AWAudioEncoder.h"
@interface AWSWFaacEncoder : AWAudioEncoder
@end
|
jjzhang166/AWLive | clibs/libaw/pushStream/encoder/aw_sw_x264_encoder.h | /*
copyright 2016 wanghongyu.
The project page:https://github.com/hardman/AWLive
My blog page: http://blog.csdn.net/hard_man/
*/
#ifndef aw_sw_x264_encoder_h
#define aw_sw_x264_encoder_h
/*
使用x264进行软编码:h264软编码器
*/
#include "aw_x264.h"
#include "aw_encode_flv.h"
#ifdef __cplusplus
extern "C"{
#endif
//将采集到的video yuv数据,编码为flv video tag
extern aw_flv_video_tag * aw_sw_encoder_encode_x264_data(int8_t *yuv_data, long len, uint32_t timeStamp);
//根据flv/h264/aac协议创建video/audio首帧tag
extern aw_flv_video_tag *aw_sw_encoder_create_x264_sps_pps_tag();
//开关编码器
extern void aw_sw_encoder_open_x264_encoder(aw_x264_config *x264_config);
extern void aw_sw_encoder_close_x264_encoder();
extern int8_t aw_sw_x264_encoder_is_valid();
//创建 flv tag 跟编码无关。
//将h264数据转为flv_video_tag
extern aw_flv_video_tag *aw_encoder_create_video_tag(int8_t *h264_data, long len, uint32_t timeStamp, long composition_time, int8_t is_key_frame);
//创建sps_pps_tag
extern aw_flv_video_tag *aw_encoder_create_sps_pps_tag(aw_data *sps_pps_data);
#ifdef __cplusplus
}
#endif
#endif /* aw_sw_video_encoder_h */
|
jjzhang166/AWLive | AWLive/PushStream/LKEncoder/SW/LKSWX264Encoder.h | /**
* file : LKSWX264Encoder.h
* author : Rex
* create : 2017-02-17 17:01
* func :
* history:
*/
#ifndef __LKSWX264ENCODER_H_
#define __LKSWX264ENCODER_H_
#endif
|
I-Iias/Explorer1632_dsPIC33EP | bsp/buttons.c | <gh_stars>0
/*******************************************************************************
Copyright 2016 Microchip Technology Inc. (www.microchip.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*******************************************************************************/
#include <xc.h>
#include <stdbool.h>
#include "buttons.h"
/*** Button Definitions *********************************************/
// S1 is MCLR button
#define S3_PORT PORTDbits.RD6
#define S6_PORT PORTCbits.RC7
#define S5_PORT PORTCbits.RC8 //Overlaps with D10
#define S4_PORT PORTDbits.RD5
#define S3_TRIS TRISDbits.TRISD6
#define S6_TRIS TRISCbits.TRISC7
#define S5_TRIS TRISCbits.TRISC8
#define S4_TRIS TRISDbits.TRISD5
#define BUTTON_PRESSED 0
#define BUTTON_NOT_PRESSED 1
#define PIN_INPUT 1
#define PIN_OUTPUT 0
/*********************************************************************
* Function: bool BUTTON_IsPressed(BUTTON button);
*
* Overview: Returns the current state of the requested button
*
* PreCondition: button configured via BUTTON_SetConfiguration()
*
* Input: BUTTON button - enumeration of the buttons available in
* this demo. They should be meaningful names and not the names
* of the buttons on the silk-screen on the board (as the demo
* code may be ported to other boards).
* i.e. - ButtonIsPressed(BUTTON_SEND_MESSAGE);
*
* Output: TRUE if pressed; FALSE if not pressed.
*
********************************************************************/
bool BUTTON_IsPressed(BUTTON button)
{
switch(button)
{
case BUTTON_S3:
return ( (S3_PORT == BUTTON_PRESSED) ? true : false);
case BUTTON_S6:
return ( (S6_PORT == BUTTON_PRESSED) ? true : false);
case BUTTON_S5:
return ( ( S5_PORT == BUTTON_PRESSED ) ? true : false ) ;
case BUTTON_S4:
return ( (S4_PORT == BUTTON_PRESSED) ? true : false);
default:
return false;
}
return false;
}
/*********************************************************************
* Function: void BUTTON_Enable(BUTTON button);
*
* Overview: Returns the current state of the requested button
*
* PreCondition: button configured via BUTTON_SetConfiguration()
*
* Input: BUTTON button - enumeration of the buttons available in
* this demo. They should be meaningful names and not the names
* of the buttons on the silk-screen on the board (as the demo
* code may be ported to other boards).
* i.e. - ButtonIsPressed(BUTTON_SEND_MESSAGE);
*
* Output: None
*
********************************************************************/
void BUTTON_Enable(BUTTON button)
{
switch(button)
{
case BUTTON_S3:
S3_TRIS = PIN_INPUT;
break;
case BUTTON_S6:
S6_TRIS = PIN_INPUT;
break;
case BUTTON_S5:
S5_TRIS = PIN_INPUT ;
break;
case BUTTON_S4:
S4_TRIS = PIN_INPUT;
break;
default:
break;
}
}
|
I-Iias/Explorer1632_dsPIC33EP | adc_dma.h | /*
* File: adc_dma.h
* Author: <NAME>
*
* Created on 20. Mai 2019, 19:33
*/
#ifndef ADC_DMA_H
#define ADC_DMA_H
#include "types.h"
#include <xc.h>
#define ADC_CHN_POTENTIOMETER 0
#define ADC_CHN_TEMPERATURE_SENSOR 1
#define NumSamples 128
extern uint16 BufferA[NumSamples];
extern uint16 BufferB[NumSamples];
void Init_ADC (void);
void Init_DMA2(void);
uint16 getADCvalue (uint8 channel);
boolean ADC_ChnEnable(void);
#endif /* ADC_DMA_H */
|
I-Iias/Explorer1632_dsPIC33EP | Tasks.h | /*
* File: Tasks.h
* Author: <NAME>
*
* Created on 22. April 2019, 13:44
*/
#ifndef TASKS_H
#define TASKS_H
#include "types.h"
void Task_scheduler(void);
void Task_1ms(void);
void Task_10ms(void);
void Task_50ms(void);
void Task_100ms(void);
void Task_500ms(void);
void Task_1s(void);
void Task_10s(void);
#endif // TASKS_H |
I-Iias/Explorer1632_dsPIC33EP | Timer.c | /*
* File: Timer.c
* Author: Matthias
*
* Created on 23. April 2019, 23:16
*/
#include "xc.h"
#include "Timer.h"
#include "Tasks.h"
FUNCTION_HANDLER handle = NULL;
void INIT_Timer1(void)
{
T1CON = 0; //clear configuration register
T1CONbits.TCS = 0; //Internal peripheral clock
T1CONbits.TCKPS = 1; //prescaler 1:8
T1CONbits.TGATE = 0; //Gated time accumulation is disabled
T1CONbits.TSIDL = 0; //Continue operation when device enters Idle mode
TMR1 = 0; //clear count register
PR1 = 8750; //Periode | PRx = [(Fp/prescaler)*T] = 70MHz/8*1ms = 8750
IFS0bits.T1IF = 0; //reset interrupt flag
IPC0bits.T1IP = 5; //interrupt priority
IEC0bits.T1IE = 1; //enable interrupt
T1CONbits.TON = 1; //1=0n 0=off
}
void RequestFunction_Timer1 (FUNCTION_HANDLER handle_new)
{
handle = handle_new;
}
void __attribute__((__interrupt__, no_auto_psv)) _T1Interrupt(void) // Timer 1
{
if(handle != NULL)
{
handle();
}
//Task_scheduler();
IFS0bits.T1IF = 0;
} |
I-Iias/Explorer1632_dsPIC33EP | bsp/lcd_4bit.c | /*******************************************************************************
Copyright 2016 Microchip Technology Inc. (www.microchip.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*******************************************************************************/
#include <xc.h>
#include "lcd.h"
#include <stdint.h>
#ifndef FCY
#pragma message "This module requires a definition for the peripheral clock frequency. Assuming FRC (3.685 MHz Fosc). Define value if this is not correct."
#define FCY (140000000/2)
#endif
#include <libpic30.h>
/* Private Definitions ***********************************************/
#define LCD_FAST_INSTRUCTION_TIME_US 50
#define LCD_SLOW_INSTRUCTION_TIME_US 1600
#define LCD_STARTUP_TIME_MS 30
#define LCD_SIGNAL_TIMING_US 1
#define LCD_MAX_COLUMN 16
#define LCD_COMMAND_CLEAR_SCREEN 0x01
#define LCD_COMMAND_RETURN_HOME 0x02
#define LCD_COMMAND_ENTER_DATA_MODE 0x06
#define LCD_COMMAND_CURSOR_OFF 0x0C
#define LCD_COMMAND_CURSOR_ON 0x0F
#define LCD_COMMAND_MOVE_CURSOR_LEFT 0x10
#define LCD_COMMAND_MOVE_CURSOR_RIGHT 0x14
#define LCD_COMMAND_SET_MODE_4_BIT 0x28
#define LCD_COMMAND_SET_MODE_8_BIT 0x38
#define LCD_COMMAND_ROW_0_HOME 0x80
#define LCD_COMMAND_ROW_1_HOME 0xC0
#define LCD_START_UP_COMMAND_1 0x33
#define LCD_START_UP_COMMAND_2 0x32
#define PIN_D4_Enable() {TRISBbits.TRISB12 = 0;}
#define PIN_D5_Enable() {TRISBbits.TRISB13 = 0;}
#define PIN_D6_Enable() {TRISBbits.TRISB14 = 0;}
#define PIN_D7_Enable() {TRISBbits.TRISB15 = 0;}
#define PIN_D4_Set() {LATBbits.LATB12 = 1;}
#define PIN_D4_Clear() {LATBbits.LATB12 = 0;}
#define PIN_D5_Set() {LATBbits.LATB13 = 1;}
#define PIN_D5_Clear() {LATBbits.LATB13 = 0;}
#define PIN_D6_Set() {LATBbits.LATB14 = 1;}
#define PIN_D6_Clear() {LATBbits.LATB14 = 0;}
#define PIN_D7_Set() {LATBbits.LATB15 = 1;}
#define PIN_D7_Clear() {LATBbits.LATB15 = 0;}
#define PIN_RS_Set() {LATAbits.LATA10 = 1;}
#define PIN_RS_Clear() {LATAbits.LATA10 = 0;}
#define PIN_RS_Input() {TRISAbits.TRISA10 = 1;}
#define PIN_RS_Output() {TRISAbits.TRISA10 = 0;}
#define PIN_RW_Set() {LATCbits.LATC13 = 1;}
#define PIN_RW_Clear() {LATCbits.LATC13 = 0;}
#define PIN_RW_Input() {TRISCbits.TRISC13 = 1;}
#define PIN_RW_Output() {TRISCbits.TRISC13 = 0;}
#define PIN_Enable_Set() {LATCbits.LATC6 = 1;}
#define PIN_Enable_Clear() {LATCbits.LATC6 = 0;}
#define PIN_Enable_Input() {TRISCbits.TRISC6 = 1;}
#define PIN_Enable_Output() {TRISCbits.TRISC6 = 0;}
/* Private Functions *************************************************/
static void LCD_CarriageReturn ( void ) ;
static void LCD_ShiftCursorLeft ( void ) ;
static void LCD_ShiftCursorRight ( void ) ;
static void LCD_ShiftCursorUp ( void ) ;
static void LCD_ShiftCursorDown ( void ) ;
static void LCD_SendData ( char ) ;
static void LCD_SendCommand ( unsigned int ) ;
static void LCD_DataNibbleWrite(uint8_t value);
/* Private variables ************************************************/
static uint8_t row ;
static uint8_t column ;
/*********************************************************************
* Function: bool LCD_Initialize(void);
*
* Overview: Initializes the LCD screen. Can take several hundred
* milliseconds.
*
* PreCondition: none
*
* Input: None
*
* Output: true if initialized, false otherwise
*
********************************************************************/
bool LCD_Initialize ( void )
{
LCD_DataNibbleWrite(0);
PIN_D4_Enable();
PIN_D5_Enable();
PIN_D6_Enable();
PIN_D7_Enable();
// Control signal data pins
PIN_RW_Clear ( ) ; // LCD R/W signal
PIN_RS_Clear ( ) ; // LCD RS signal
PIN_Enable_Clear ( ) ; // LCD E signal
// Control signal pin direction
PIN_RS_Output ( ) ;
PIN_RW_Output ( ) ;
PIN_Enable_Output ( ) ;
PIN_Enable_Set ( ) ;
__delay_ms(LCD_STARTUP_TIME_MS);
LCD_SendCommand ( LCD_COMMAND_SET_MODE_4_BIT ) ;
LCD_SendCommand ( LCD_COMMAND_CURSOR_OFF ) ;
LCD_SendCommand ( LCD_COMMAND_ENTER_DATA_MODE ) ;
LCD_ClearScreen ( ) ;
return true ;
}
/*********************************************************************
* Function: void LCD_PutString(char* inputString, uint16_t length);
*
* Overview: Puts a string on the LCD screen. Unsupported characters will be
* discarded. May block or throw away characters is LCD is not ready
* or buffer space is not available. Will terminate when either a
* null terminator character (0x00) is reached or the length number
* of characters is printed, which ever comes first.
*
* PreCondition: already initialized via LCD_Initialize()
*
* Input: char* - string to print
* uint16_t - length of string to print
*
* Output: None
*
********************************************************************/
void LCD_PutString ( char* inputString , uint16_t length )
{
while (length--)
{
switch (*inputString)
{
case 0x00:
return ;
default:
LCD_PutChar ( *inputString++ ) ;
break ;
}
}
}
/*********************************************************************
* Function: void LCD_PutChar(char);
*
* Overview: Puts a character on the LCD screen. Unsupported characters will be
* discarded. May block or throw away characters is LCD is not ready
* or buffer space is not available.
*
* PreCondition: already initialized via LCD_Initialize()
*
* Input: char - character to print
*
* Output: None
*
********************************************************************/
void LCD_PutChar ( char inputCharacter )
{
static char lastCharacter = 0;
switch (inputCharacter)
{
case '\r':
if(lastCharacter != '\n')
{
LCD_CarriageReturn ( ) ;
}
break ;
case '\n':
if(lastCharacter != '\r')
{
LCD_CarriageReturn ( ) ;
}
if (row == 0)
{
LCD_ShiftCursorDown ( ) ;
}
else
{
LCD_ShiftCursorUp ( ) ;
}
break ;
case '\b':
LCD_ShiftCursorLeft ( ) ;
LCD_PutChar ( ' ' ) ;
LCD_ShiftCursorLeft ( ) ;
break ;
case '\f':
LCD_ClearScreen();
break;
default:
if (column == LCD_MAX_COLUMN)
{
column = 0 ;
if (row == 0)
{
LCD_SendCommand ( LCD_COMMAND_ROW_1_HOME ) ;
row = 1 ;
}
else
{
LCD_SendCommand ( LCD_COMMAND_ROW_0_HOME ) ;
row = 0 ;
}
}
LCD_SendData ( inputCharacter ) ;
column++ ;
break ;
}
lastCharacter = inputCharacter;
}
/*********************************************************************
* Function: void LCD_ClearScreen(void);
*
* Overview: Clears the screen, if possible.
*
* PreCondition: already initialized via LCD_Initialize()
*
* Input: None
*
* Output: None
*
********************************************************************/
void LCD_ClearScreen ( void )
{
LCD_SendCommand ( LCD_COMMAND_CLEAR_SCREEN ) ;
LCD_SendCommand ( LCD_COMMAND_RETURN_HOME ) ;
row = 0 ;
column = 0 ;
}
/*******************************************************************/
/*******************************************************************/
/* Private Functions ***********************************************/
/*******************************************************************/
/*******************************************************************/
/*********************************************************************
* Function: static void LCD_CarriageReturn(void)
*
* Overview: Handles a carriage return
*
* PreCondition: already initialized via LCD_Initialize()
*
* Input: None
*
* Output: None
*
********************************************************************/
static void LCD_CarriageReturn ( void )
{
if (row == 0)
{
LCD_SendCommand ( LCD_COMMAND_ROW_0_HOME ) ;
}
else
{
LCD_SendCommand ( LCD_COMMAND_ROW_1_HOME ) ;
}
column = 0 ;
}
/*********************************************************************
* Function: static void LCD_ShiftCursorLeft(void)
*
* Overview: Shifts cursor left one spot (wrapping if required)
*
* PreCondition: already initialized via LCD_Initialize()
*
* Input: None
*
* Output: None
*
********************************************************************/
static void LCD_ShiftCursorLeft ( void )
{
uint8_t i ;
if (column == 0)
{
if (row == 0)
{
LCD_SendCommand ( LCD_COMMAND_ROW_1_HOME ) ;
row = 1 ;
}
else
{
LCD_SendCommand ( LCD_COMMAND_ROW_0_HOME ) ;
row = 0 ;
}
//Now shift to the end of the row
for (i = 0 ; i < ( LCD_MAX_COLUMN - 1 ) ; i++)
{
LCD_ShiftCursorRight ( ) ;
}
}
else
{
column-- ;
LCD_SendCommand ( LCD_COMMAND_MOVE_CURSOR_LEFT ) ;
}
}
/*********************************************************************
* Function: static void LCD_ShiftCursorRight(void)
*
* Overview: Shifts cursor right one spot (wrapping if required)
*
* PreCondition: already initialized via LCD_Initialize()
*
* Input: None
*
* Output: None
*
********************************************************************/
static void LCD_ShiftCursorRight ( void )
{
LCD_SendCommand ( LCD_COMMAND_MOVE_CURSOR_RIGHT ) ;
column++ ;
if (column == LCD_MAX_COLUMN)
{
column = 0 ;
if (row == 0)
{
LCD_SendCommand ( LCD_COMMAND_ROW_1_HOME ) ;
row = 1 ;
}
else
{
LCD_SendCommand ( LCD_COMMAND_ROW_0_HOME ) ;
row = 0 ;
}
}
}
/*********************************************************************
* Function: static void LCD_ShiftCursorUp(void)
*
* Overview: Shifts cursor up one spot (wrapping if required)
*
* PreCondition: already initialized via LCD_Initialize()
*
* Input: None
*
* Output: None
*
********************************************************************/
static void LCD_ShiftCursorUp ( void )
{
uint8_t i ;
for (i = 0 ; i < LCD_MAX_COLUMN ; i++)
{
LCD_ShiftCursorLeft ( ) ;
}
}
/*********************************************************************
* Function: static void LCD_ShiftCursorDown(void)
*
* Overview: Shifts cursor down one spot (wrapping if required)
*
* PreCondition: already initialized via LCD_Initialize()
*
* Input: None
*
* Output: None
*
********************************************************************/
static void LCD_ShiftCursorDown ( void )
{
uint8_t i ;
for (i = 0 ; i < LCD_MAX_COLUMN ; i++)
{
LCD_ShiftCursorRight ( ) ;
}
}
/*********************************************************************
* Function: void LCD_CursorEnable(bool enable)
*
* Overview: Enables/disables the cursor
*
* PreCondition: None
*
* Input: bool - specifies if the cursor should be on or off
*
* Output: None
*
********************************************************************/
void LCD_CursorEnable ( bool enable )
{
if (enable == true)
{
LCD_SendCommand ( LCD_COMMAND_CURSOR_ON ) ;
}
else
{
LCD_SendCommand ( LCD_COMMAND_CURSOR_OFF ) ;
}
}
/*********************************************************************
* Function: static void LCD_SendData(char data)
*
* Overview: Sends data to LCD
*
* PreCondition: None
*
* Input: char - contains the data to be sent to the LCD
*
* Output: None
*
********************************************************************/
static void LCD_SendData ( char data )
{
PIN_RW_Clear ( ) ;
PIN_RS_Set ( ) ;
LCD_DataNibbleWrite(data>>4);
__delay_us(LCD_SIGNAL_TIMING_US);
PIN_Enable_Set ( ) ;
__delay_us(LCD_SIGNAL_TIMING_US);
PIN_Enable_Clear ( ) ;
LCD_DataNibbleWrite(data);
__delay_us(LCD_SIGNAL_TIMING_US);
PIN_Enable_Set ( ) ;
__delay_us(LCD_SIGNAL_TIMING_US);
PIN_Enable_Clear ( ) ;
PIN_RS_Clear ( ) ;
__delay_us(LCD_FAST_INSTRUCTION_TIME_US);
}
/*********************************************************************
* Function: static void LCD_SendCommand(char data)
*
* Overview: Sends command to LCD
*
* PreCondition: None
*
* Input: char - contains the command to be sent to the LCD
* unsigned int - has the specific delay for the command
*
* Output: None
*
********************************************************************/
static void LCD_SendCommand ( unsigned int command )
{
PIN_RW_Clear ( ) ;
PIN_RS_Clear ( ) ;
LCD_DataNibbleWrite(command >> 4);
PIN_Enable_Set ( ) ;
__delay_us(LCD_SIGNAL_TIMING_US);
PIN_Enable_Clear ( ) ;
PIN_RW_Clear ( ) ;
PIN_RS_Clear ( ) ;
LCD_DataNibbleWrite(command);
PIN_Enable_Set ( ) ;
__delay_us(LCD_SIGNAL_TIMING_US);
PIN_Enable_Clear ( ) ;
switch(command)
{
case LCD_COMMAND_MOVE_CURSOR_LEFT:
case LCD_COMMAND_MOVE_CURSOR_RIGHT:
case LCD_COMMAND_SET_MODE_8_BIT:
case LCD_COMMAND_SET_MODE_4_BIT:
case LCD_COMMAND_CURSOR_OFF:
__delay_us(LCD_FAST_INSTRUCTION_TIME_US);
break;
case LCD_COMMAND_ENTER_DATA_MODE:
case LCD_COMMAND_CLEAR_SCREEN:
case LCD_COMMAND_RETURN_HOME:
case LCD_COMMAND_CURSOR_ON:
case LCD_COMMAND_ROW_0_HOME:
case LCD_COMMAND_ROW_1_HOME:
default:
__delay_us(LCD_SLOW_INSTRUCTION_TIME_US);
break;
}
}
static void LCD_DataNibbleWrite(uint8_t value)
{
if(value & 0x01)
{
PIN_D4_Set();
}
else
{
PIN_D4_Clear();
}
if(value & 0x02)
{
PIN_D5_Set();
}
else
{
PIN_D5_Clear();
}
if(value & 0x04)
{
PIN_D6_Set();
}
else
{
PIN_D6_Clear();
}
if(value & 0x08)
{
PIN_D7_Set();
}
else
{
PIN_D7_Clear();
}
}
|
I-Iias/Explorer1632_dsPIC33EP | bsp/print_lcd.h | <gh_stars>0
/*******************************************************************************
Copyright 2016 Microchip Technology Inc. (www.microchip.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*******************************************************************************/
#ifndef PRINT_LCD_H
#define PRINT_LCD_H
#include <stdbool.h>
#include <lcd.h>
/* Type Definitions *************************************************/
typedef enum
{
PRINT_CONFIGURATION_LCD
} PRINT_CONFIGURATION;
/*********************************************************************
* Function: bool PRINT_SetConfiguration(PRINT_CONFIGURATION led);
*
* Overview: Configures the print configuration
*
* PreCondition: none
*
* Input: configuration - the print configuration to use. Some boards
* may have more than one print configuration enabled
*
* Output: TRUE if successful, FALSE if LED not configured or doesn?t
* exist for this board.
*
********************************************************************/
bool PRINT_SetConfiguration(PRINT_CONFIGURATION configuration);
#define PRINT_SetConfiguration(configuration) LCD_Initialize()
/*********************************************************************
* Function: void PRINT_String(char* string, uint16_t length)
*
* Overview: Prints a string until a null terminator is reached or the
* specified string length is printed.
*
* PreCondition: none
*
* Input: char* string - the string to print.
* uint16_t length - the length of the string.
*
* Output: None
*
********************************************************************/
void PRINT_String(char* string, uint16_t length);
#define PRINT_String(string, length) LCD_PutString(string, length)
/*********************************************************************
* Function: void PRINT_Char(char charToPrint)
*
* Overview: Prints a character
*
* PreCondition: none
*
* Input: char charToPrint - the character to print
*
* Output: None
*
********************************************************************/
void PRINT_Char(char charToPrint);
#define PRINT_Char(charToPrint) LCD_PutChar(charToPrint)
/*********************************************************************
* Function: void PRINT_ClearStreen()
*
* Overview: Clears the screen, if possible
*
* PreCondition: none
*
* Input: None
*
* Output: None
*
********************************************************************/
void PRINT_ClearScreen(void);
#define PRINT_ClearScreen() LCD_ClearScreen()
/*********************************************************************
* Function: void PRINT_CursorEnable(bool enable)
*
* Overview: Enables/disables the cursor
*
* PreCondition: None
*
* Input: bool - specifies if the cursor should be on or off
*
* Output: None
*
********************************************************************/
void PRINT_CursorEnable(bool);
#define PRINT_CursorEnable(enabled) LCD_CursorEnable(enabled)
#endif //PRINT_LCD_H
|
I-Iias/Explorer1632_dsPIC33EP | Initialize.c | /*
* File: Initialize.c
* Author: <NAME>
*
* Created on 23. April 2019, 20:37
*/
#include <xc.h>
#include "types.h"
#include "Initialize.h"
#include "Timer.h"
//******************************************************************************
//Global Variables
//******************************************************************************
//******************************************************************************
//*name :Hardware_Init
//*details :Initialize peripheral modules
//*param :void
//*return :void
//******************************************************************************
void Hardware_Init (void)
{
INIT_OSC ();
INIT_Timer1();
// Init_ADC ();
// Init_DMA2 (); // for ADC
}
uint16 OscillatorSource = 0;
uint16 PllInputSource = 2;
uint16 PllOutputDivider = 0;
uint16 PllInputDivider = 0;
uint16 PllMultiplikator = 0;
void INIT_OSC(void)
{
// clock switch sequence (see Oscillator Section 7.13.2
// make sure Configuration bits (pragma) are set correctly
//current oscillator source
OscillatorSource = OSCCONbits.COSC;
//OSCCONbits.NOSC = 0b011;
__builtin_write_OSCCONH(0x03); // set to Primary Oscillator with PLL
//OSCCONbits.OSWEN = 1;
__builtin_write_OSCCONL(OSCCON | 0x01); // initiate the oscillator switch
while (OSCCONbits.OSWEN != 0){}; //wait until clock switch was successfull
// system clock = 70MHz -> FPLLO = 140MHz
CLKDIVbits.PLLPRE = 0b00000; // divide by 2 (N1 = 2, default)
CLKDIVbits.PLLPOST = 0b01; // divide by 4 (N2 = 4, default)
PLLFBDbits.PLLDIV = 140-2; // M = 140
//tune FRC oscillator, if FRC is used
//OSCTUN = 0;
//disable Watchdog Timer
//WDTCONbits.ON = 0; //disable watchdog timer
OscillatorSource = OSCCONbits.COSC;
}
|
I-Iias/Explorer1632_dsPIC33EP | system.c | /*******************************************************************************
System Initialization File
File Name:
sys_init.c
Summary:
System Initialization.
Description:
This file contains source code necessary to initialize the system.
*******************************************************************************/
// DOM-IGNORE-BEGIN
/*******************************************************************************
Copyright (c) 2013 released Microchip Technology Inc. All rights reserved.
Microchip licenses to you the right to use, modify, copy and distribute
Software only when embedded on a Microchip microcontroller or digital signal
controller that is integrated into your product or third party product
(pursuant to the sublicense terms in the accompanying license agreement).
You should refer to the license agreement accompanying this Software for
additional information regarding 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 OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER
CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR
OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
*******************************************************************************/
// DOM-IGNORE-END
// ****************************************************************************
// ****************************************************************************
// Section: Configuration Bits
// ****************************************************************************
// ****************************************************************************
// FICD
#pragma config ICS = PGD1 // ICD Communication Channel Select bits (Communicate on PGEC1 and PGED1)
#pragma config JTAGEN = OFF // JTAG Enable bit (JTAG is disabled)
// FPOR
#pragma config ALTI2C1 = OFF // Alternate I2C1 pins (I2C1 mapped to SDA1/SCL1 pins)
#pragma config ALTI2C2 = OFF // Alternate I2C2 pins (I2C2 mapped to SDA2/SCL2 pins)
#pragma config WDTWIN = WIN25 // Watchdog Window Select bits (WDT Window is 25% of WDT period)
// FWDT
#pragma config WDTPOST = PS32768 // Watchdog Timer Postscaler bits (1:32,768)
#pragma config WDTPRE = PR128 // Watchdog Timer Prescaler bit (1:128)
#pragma config PLLKEN = ON // PLL Lock Enable bit (Clock switch to PLL source will wait until the PLL lock signal is valid.)
#pragma config WINDIS = OFF // Watchdog Timer Window Enable bit (Watchdog Timer in Non-Window mode)
#pragma config FWDTEN = ON // Watchdog Timer Enable bit (Watchdog timer always enabled)
// FOSC
#pragma config POSCMD = XT // Primary Oscillator Mode Select bits (Primary Oscillator disabled)
#pragma config OSCIOFNC = OFF // OSC2 Pin Function bit (OSC2 is clock output)
#pragma config IOL1WAY = ON // Peripheral pin select configuration (Allow only one reconfiguration)
#pragma config FCKSM = CSDCMD // Clock Switching Mode bits (Both Clock switching and Fail-safe Clock Monitor are disabled)
// FOSCSEL
#pragma config FNOSC = PRIPLL // Oscillator Source Selection (Internal Fast RC (FRC))
#pragma config IESO = ON // Two-speed Oscillator Start-up Enable bit (Start up device with FRC, then switch to user-selected oscillator source)
// FGS
#pragma config GWRP = OFF // General Segment Write-Protect bit (General Segment may be written)
#pragma config GCP = OFF // General Segment Code-Protect bit (General Segment Code protect is Disabled)
// #pragma config statements should precede project file includes.
// Use project enums instead of #define for ON and OFF.
#include <xc.h>
#include "bsp/lcd.h"
// ****************************************************************************
// ****************************************************************************
// Section: File Scope Functions
// ****************************************************************************
// ****************************************************************************
void SOSC_Configuration ( void ) ;
void __attribute__ ( ( __interrupt__ , auto_psv ) ) _OscillatorFail ( void ) ;
void __attribute__ ( ( __interrupt__ , auto_psv ) ) _AddressError ( void ) ;
void __attribute__ ( ( __interrupt__ , auto_psv ) ) _StackError ( void ) ;
void __attribute__ ( ( __interrupt__ , auto_psv ) ) _MathError ( void ) ;
// ****************************************************************************
// ****************************************************************************
// Section: System Initialization
// ****************************************************************************
// ****************************************************************************
/*******************************************************************************
Function:
void SYS_Initialize ( void )
Summary:
Initializes the Explorer 16 board peripherals
Description:
This routine initializes the Explorer 16 board peripherals for the demo.
In a bare-metal environment (where no OS is supported), this routine should
be called almost immediately after entering the "main" routine.
Precondition:
The C-language run-time environment and stack must have been initialized.
Parameters:
None.
Returns:
None.
Example:
<code>
SYS_INT_Initialize(NULL);
</code>
Remarks:
Basic System Initialization Sequence:
1. Initialize minimal board services and processor-specific items
(enough to use the board to initialize drivers and services)
2. Initialize all supported system services
3. Initialize all supported modules
(libraries, drivers, middle-ware, and application-level modules)
4. Initialize the main (static) application, if present.
The order in which services and modules are initialized and started may be
important.
*/
void SYS_Initialize ( void )
{
LCD_Initialize();
}
// *****************************************************************************
// *****************************************************************************
// Section: Primary Exception Vector handlers
// *****************************************************************************
// *****************************************************************************
// *****************************************************************************
/* void __attribute__((__interrupt__,auto_psv)) _OscillatorFail(void)
Summary:
Provides the required exception vector handlers for Oscillator trap
Description:
This routine is used if INTCON2bits.ALTIVT = 0 and it handles the oscillator
trap.
Remarks:
All trap service routines in this file simply ensure that device
continuously executes code within the trap service routine. Users
may modify the basic framework provided here to suit to the needs
of their application.
*/
void __attribute__ ( ( __interrupt__ , auto_psv ) ) _OscillatorFail ( void )
{
INTCON1bits.OSCFAIL = 0 ; //Clear the trap flag
while (1) ;
}
// *****************************************************************************
/* void __attribute__((__interrupt__,auto_psv)) _AddressError(void)
Summary:
Provides the required exception vector handlers for Address Error trap
Description:
This routine is used if INTCON2bits.ALTIVT = 0 and it handles the address
error trap.
Remarks:
All trap service routines in this file simply ensure that device
continuously executes code within the trap service routine. Users
may modify the basic framework provided here to suit to the needs
of their application.
*/
void __attribute__ ( ( __interrupt__ , auto_psv ) ) _AddressError ( void )
{
INTCON1bits.ADDRERR = 0 ; //Clear the trap flag
while (1) ;
}
// *****************************************************************************
/* void __attribute__((__interrupt__,auto_psv)) _StackError(void))
Summary:
Provides the required exception vector handlers for Stack Error trap
Description:
This routine is used if INTCON2bits.ALTIVT = 0 and it handles the stack
error trap.
Remarks:
All trap service routines in this file simply ensure that device
continuously executes code within the trap service routine. Users
may modify the basic framework provided here to suit to the needs
of their application.
*/
void __attribute__ ( ( __interrupt__ , auto_psv ) ) _StackError ( void )
{
INTCON1bits.STKERR = 0 ; //Clear the trap flag
while (1) ;
}
// *****************************************************************************
/* void __attribute__((__interrupt__,auto_psv)) _MathError(void))
Summary:
Provides the required exception vector handlers for Math Error trap
Description:
This routine is used if INTCON2bits.ALTIVT = 0 and it handles the math
error trap.
Remarks:
All trap service routines in this file simply ensure that device
continuously executes code within the trap service routine. Users
may modify the basic framework provided here to suit to the needs
of their application.
*/
void __attribute__ ( ( __interrupt__ , auto_psv ) ) _MathError ( void )
{
INTCON1bits.MATHERR = 0 ; //Clear the trap flag
while (1) ;
}
|
I-Iias/Explorer1632_dsPIC33EP | Tasks.c | <reponame>I-Iias/Explorer1632_dsPIC33EP
/*
* File: Tasks.c
* Author: Matthias
*
* Created on 22. April 2019, 20:04
*/
#include "Tasks.h"
#include "io_mapping.h"
void Task_scheduler (void)
{
// function variables
static uint16 Cnt1ms = 0;
static uint16 Cnt10ms = 0;
static uint16 Cnt50ms = 0;
static uint16 Cnt100ms = 0;
static uint16 Cnt500ms = 0;
static uint16 Cnt1s = 0;
Cnt1ms++;
Task_1ms();
if(Cnt1ms >= 10)
{
Cnt1ms = 0;
Cnt10ms++;
Task_10ms();
}
if(Cnt10ms >= 5)
{
Cnt10ms = 0;
Cnt50ms++;
Task_50ms();
}
if(Cnt50ms >= 2)
{
Cnt50ms = 0;
Cnt100ms++;
Task_100ms();
}
if(Cnt100ms >= 5)
{
Cnt100ms = 0;
Cnt500ms++;
Task_500ms();
}
if(Cnt500ms >= 2)
{
Cnt500ms = 0;
Cnt1s++;
Task_1s();
}
if(Cnt1s >= 10)
{
Cnt1s = 0;
Task_10s();
}
}
void Task_1ms(void)
{
}
void Task_10ms(void)
{
}
void Task_50ms(void)
{
}
void Task_100ms(void)
{
LED_Toggle( LED_STATUS );
}
void Task_500ms(void)
{
//LED_Toggle( LED_STATUS );
}
void Task_1s(void)
{
}
void Task_10s(void)
{
}
|
I-Iias/Explorer1632_dsPIC33EP | bsp/rtcc.c | /*******************************************************************************
Copyright 2016 Microchip Technology Inc. (www.microchip.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*******************************************************************************/
/* NOTE: This device doesn't have an actual RTCC. We will be emulating the
* functionality of the RTCC using the TIMER_1MS BSP. Please include
* the timer_1ms.c/.h files in your project and give enough clients
* to that module for your application, plus one for this module.
*
* Additionally make sure the TIMER_1MS module is initialized before
* Initializing this module.
*/
#include <xc.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "rtcc.h"
#include "timer_1ms.h"
static uint8_t RTCC_DecToBCD (uint8_t value);
static uint8_t RTCC_BCDToDec (uint8_t value);
static void SecondEventHandler ( void );
static volatile RTCC_DATETIME datetime;
static volatile bool modified;
void RTCC_BuildTimeGet(RTCC_DATETIME *dateTime)
{
uint8_t weekday;
uint8_t month;
uint8_t y;
uint8_t dateTable[] = {0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5};
dateTime->second = (((__TIME__[6]) & 0x0f) << 4) | ((__TIME__[7]) & 0x0f);
dateTime->minute = (((__TIME__[3]) & 0x0f) << 4) | ((__TIME__[4]) & 0x0f);
dateTime->hour = (((__TIME__[0]) & 0x0f) << 4) | ((__TIME__[1]) & 0x0f);
dateTime->day = (((__DATE__[4]) & 0x0f) << 4) | ((__DATE__[5]) & 0x0f);
dateTime->year = (((__DATE__[9]) & 0x0f) << 4) | ((__DATE__[10]) & 0x0f);
//Set the month
switch(__DATE__[0])
{
case 'J':
//January, June, or July
switch(__DATE__[1])
{
case 'a':
//January
month = 0x01;
break;
case 'u':
switch(__DATE__[2])
{
case 'n':
//June
month = 0x06;
break;
case 'l':
//July
month = 0x07;
break;
}
break;
}
break;
case 'F':
month = 0x02;
break;
case 'M':
//March,May
switch(__DATE__[2])
{
case 'r':
//March
month = 0x03;
break;
case 'y':
//May
month = 0x05;
break;
}
break;
case 'A':
//April, August
switch(__DATE__[1])
{
case 'p':
//April
month = 0x04;
break;
case 'u':
//August
month = 0x08;
break;
}
break;
case 'S':
month = 0x09;
break;
case 'O':
month = 0x10;
break;
case 'N':
month = 0x11;
break;
case 'D':
month = 0x12;
break;
}
dateTime->month = month;
// Start with weekday = 6. This value is valid for this algorithm for this century.
weekday = 6;
// y = year
y = ((dateTime->year >> 4) * 10) + (dateTime->year & 0x0f);
// Weekday = base day + year + x number of leap days
weekday += y + (y / 4);
// If the current year is a leap year but it's not March, subtract 1 from the date
if (((y % 4) == 0) && (month < 3))
{
weekday -= 1;
}
// Add an offset based on the current month
weekday += dateTable[month - 1];
// Add the current day in the month
weekday += ((dateTime->day >> 4) * 10) + (dateTime->day & 0x0f);
weekday = weekday % 7;
dateTime->weekday = weekday;
if (!dateTime->bcdFormat)
{
dateTime->year = RTCC_BCDToDec (dateTime->year);
dateTime->month = RTCC_BCDToDec (dateTime->month);
dateTime->day = RTCC_BCDToDec (dateTime->day);
dateTime->weekday = RTCC_BCDToDec (dateTime->weekday);
dateTime->hour = RTCC_BCDToDec (dateTime->hour);
dateTime->minute = RTCC_BCDToDec (dateTime->minute);
dateTime->second = RTCC_BCDToDec (dateTime->second);
}
}
void RTCC_Initialize (RTCC_DATETIME * value)
{
if (value->bcdFormat)
{
datetime.year = RTCC_BCDToDec (value->year);
datetime.month = RTCC_BCDToDec (value->month);
datetime.day = RTCC_BCDToDec (value->day);
datetime.weekday = RTCC_BCDToDec (value->weekday);
datetime.hour = RTCC_BCDToDec (value->hour);
datetime.minute = RTCC_BCDToDec (value->minute);
datetime.second = RTCC_BCDToDec (value->second);
}
else
{
datetime.weekday = value->weekday;
datetime.day = value->day;
datetime.month = value->month;
datetime.year = value->year;
datetime.hour = value->hour;
datetime.minute = value->minute;
datetime.second = value->second;
}
datetime.bcdFormat = false;
while(TIMER_RequestTick(&SecondEventHandler, 1000) == false)
{
}
}
void RTCC_TimeGet (RTCC_DATETIME * value)
{
RTCC_DATETIME currentTime;
do
{
modified = false;
currentTime.bcdFormat = datetime.bcdFormat;
currentTime.weekday = datetime.weekday;
currentTime.day = datetime.day;
currentTime.month = datetime.month;
currentTime.year = datetime.year;
currentTime.hour = datetime.hour;
currentTime.minute = datetime.minute;
currentTime.second = datetime.second;
} while(modified == true);
if (value->bcdFormat == true)
{
value->year = RTCC_DecToBCD (currentTime.year);
value->month = RTCC_DecToBCD (currentTime.month);
value->day = RTCC_DecToBCD (currentTime.day);
value->weekday = RTCC_DecToBCD (currentTime.weekday);
value->hour = RTCC_DecToBCD (currentTime.hour);
value->minute = RTCC_DecToBCD (currentTime.minute);
value->second = RTCC_DecToBCD (currentTime.second);
}
else
{
value->year = currentTime.year;
value->month = currentTime.month;
value->day = currentTime.day;
value->weekday = currentTime.weekday;
value->hour = currentTime.hour;
value->minute = currentTime.minute;
value->second = currentTime.second;
}
}
// Note : value must be < 100
static uint8_t RTCC_DecToBCD (uint8_t value)
{
return (((value / 10)) << 4) | (value % 10);
}
static uint8_t RTCC_BCDToDec (uint8_t value)
{
return ((value >> 4) * 10) + (value & 0x0F);
}
void inline __attribute__((deprecated)) BSP_RTCC_Initialize (BSP_RTCC_DATETIME * value)
{
RTCC_Initialize(value);
}
void inline __attribute__((deprecated)) BSP_RTCC_TimeGet (BSP_RTCC_DATETIME * value)
{
RTCC_TimeGet(value);
}
static void SecondEventHandler ( void )
{
modified = true;
/* update seconds */
if ( datetime.second < 59 )
{
datetime.second++ ;
return;
}
datetime.second = 0x00 ;
if ( datetime.minute < 59 )
{
datetime.minute++ ;
return;
}
datetime.minute = 0x00 ;
if ( datetime.hour < 23 )
{
datetime.hour ++ ;
return;
}
datetime.hour = 0x00 ;
datetime.weekday++;
if(datetime.weekday == 7 )
{
datetime.weekday = 0;
}
switch(datetime.month)
{
/* February */
case 2:
if(datetime.day < 29)
{
/* 29 is okay on leap years ('00, '04, '08, etc.) */
if((datetime.year%4) == 0)
{
datetime.day++;
return;
}
}
break;
/* April, June, September, November */
case 4:
case 6:
case 9:
case 11:
if(datetime.day < 30)
{
datetime.day++;
return;
}
break;
/* January, March, May, July, August, October, December */
default:
if(datetime.day < 31)
{
datetime.day++;
return;
}
break;
}
/* If we made it here, then we have rolled over on days. */
datetime.day = 1;
if(datetime.month < 12)
{
datetime.month++;
return;
}
datetime.month = 1;
datetime.year++;
}
|
I-Iias/Explorer1632_dsPIC33EP | main.c | /*******************************************************************************
Copyright 2016 Microchip Technology Inc. (www.microchip.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdbool.h>
#include "bsp/adc.h"
#include "bsp/lcd.h"
#include "bsp/timer_1ms.h"
#include "bsp/buttons.h"
#include "bsp/leds.h"
#include "bsp/rtcc.h"
#include "io_mapping.h"
#include "Initialize.h"
#include "Tasks.h"
#include "Timer.h"
#include "adc_dma.h"
#include "EEPROM_emulation.h"
// *****************************************************************************
// *****************************************************************************
// Section: File Scope Variables and Functions
// *****************************************************************************
// *****************************************************************************
extern void SYS_Initialize ( void ) ;
static void TimerEventHandler( void );
static RTCC_DATETIME time;
// *****************************************************************************
// *****************************************************************************
// Section: Main Entry Point
// *****************************************************************************
// *****************************************************************************
int main ( void )
{
uint16_t adcResult;
/* Call the System Initialize routine*/
SYS_Initialize ( );
Hardware_Init();
/* To determine how the LED and Buttons are mapped to the actual board
* features, please see io_mapping.h. */
LED_Enable ( LED_BLINK_ALIVE );
LED_Enable ( LED_BUTTON_PRESSED );
LED_Enable ( LED_STATUS );
BUTTON_Enable ( BUTTON_DEMO );
BUTTON_Enable ( BUTTON_WR_EEPROM );
BUTTON_Enable ( BUTTON_RD_EEPROM );
Init_EEPROM();
/* Get a timer event once every 100ms for the blink alive. */
TIMER_SetConfiguration ( TIMER_CONFIGURATION_1MS );
TIMER_RequestTick( &TimerEventHandler, 100 );
/* The TIMER_1MS configuration should come before the RTCC initialization as
* there are some processor modules that require the TIMER_1MS module to be
* configured before the RTCC module, as the RTCC module is emulated using
* the TIMER_1MS module. */
time.bcdFormat = false;
RTCC_BuildTimeGet( &time );
RTCC_Initialize( &time );
// old adc functions
// ADC_SetConfiguration ( ADC_CONFIGURATION_DEFAULT );
// ADC_ChannelEnable ( ADC_CHANNEL_POTENTIOMETER );
// new adc functions
ADC_ChnEnable();
Init_ADC ();
Init_DMA2();
/* Clear the screen */
printf( "\f" );
// Task scheduler moved to Timer1 interrupt
//Task_scheduler();
RequestFunction_Timer1 ( &Task_scheduler );
while ( 1 )
{
// old adc functions
// adcResult = ADC_Read10bit( ADC_CHANNEL_POTENTIOMETER );
// new adc functions
adcResult = getADCvalue (ADC_CHN_POTENTIOMETER);
uint16 Temp_adc = 0;
Temp_adc = getADCvalue (ADC_CHN_TEMPERATURE_SENSOR);
RTCC_TimeGet( &time );
if(BUTTON_IsPressed( BUTTON_WR_EEPROM ) == true)
{
uint16 check;
check = EEPROM_write(adcResult, EEPROM_addr_Pot);
check = 0;
}
if(BUTTON_IsPressed( BUTTON_RD_EEPROM ) == true)
{
// printf takes nearly 10ms to execute
printf( "Time %02d:%02d:%02d EEPROM = %4d \r\n",
time.hour,
time.minute,
time.second,
EEPROM_read(EEPROM_addr_Pot)
);
}
else
{
// printf takes nearly 10ms to execute
printf( "Time %02d:%02d:%02d Pot = %4d, %4d\r\n",
time.hour,
time.minute,
time.second,
adcResult,
Temp_adc
);
}
/* To determine how the LED and Buttons are mapped to the actual board
* features, please see io_mapping.h. */
if(BUTTON_IsPressed( BUTTON_DEMO ) == true)
{
LED_On( LED_BUTTON_PRESSED );
}
else
{
LED_Off( LED_BUTTON_PRESSED );
}
uint16 time_count = TMR1;
time_count = TMR1-time_count;
time_count = 0;
}
}
static void TimerEventHandler(void)
{
LED_Toggle( LED_BLINK_ALIVE );
}
|
I-Iias/Explorer1632_dsPIC33EP | Timer.h | /*
* File: Timer.h
* Author: <NAME>
*
* Created on 22. April 2019, 13:44
*/
#ifndef TIMER_H
#define TIMER_H
#include "types.h"
typedef void (*FUNCTION_HANDLER)(void);
void INIT_Timer1 (void);
void RequestFunction_Timer1 (FUNCTION_HANDLER handle_new);
#endif //TIMER_H |
I-Iias/Explorer1632_dsPIC33EP | types.h | <filename>types.h
/*
* File: types.h
* Author: <NAME>
*
* Created on 22. April 2019, 13:44
*/
#ifndef TYPES_H
#define TYPES_H
#ifndef TRUE
#define TRUE 1 ///< constant for TRUE
#endif
#ifndef FALSE
#define FALSE 0 ///< constant for FALSE
#endif
#ifndef NULL
#define NULL (0)
#endif /* NULL */
typedef unsigned char uint8; ///< for unsigned 8-Bit variables
typedef unsigned short uint16; ///< for unsigned 16-Bit variables
typedef unsigned long uint32; ///< for unsigned32-Bit variables
typedef unsigned long long uint64; ///< for unsigned 64-Bit variables
typedef signed char int8; ///< for signed 8-Bit variables
typedef signed short int16; ///< for signed 16-Bit variables
typedef signed long int32; ///< for signed 32-Bit variables
typedef signed long long int64; ///< for unsigned 64-Bit variables
typedef char boolean; ///< for TRUE/FALSE variables
typedef float float32; ///< for 32-Bit floating point
typedef long double float64; ///< for 64-Bit floating point
#endif // TYPES_H |
I-Iias/Explorer1632_dsPIC33EP | Initialize.h | /*
* File: Initialize.h
* Author: <NAME>
*
* Created on 22. April 2019, 13:44
*/
#ifndef INITIALIZE_H
#define INITIALIZE_H
//******************************************************************************
// Functions
//******************************************************************************
void Hardware_Init(void);
void INIT_OSC (void);
//******************************************************************************
// Global variables
//******************************************************************************
#endif //INITIALIZE_H |
I-Iias/Explorer1632_dsPIC33EP | EEPROM_emulation.c | <filename>EEPROM_emulation.c
/*
* File: EEPROM_emulation.c
* Author: Matthias
*
* Created on 21. Mai 2019, 21:09
*/
#include "EEPROM_emulation.h"
void Init_EEPROM (void)
{
DataEEInit();
dataEEFlags.val = 0;
}
boolean EEPROM_write(uint16 data, uint16 addr)
{
DataEEWrite(data,addr);
uint16 value;
value = DataEERead(addr);
if (value == data)
{
return TRUE;
}
else
{
return FALSE;
}
}
uint16 EEPROM_read(uint16 addr)
{
return DataEERead(addr);
}
|
I-Iias/Explorer1632_dsPIC33EP | bsp/rtcc.h | <reponame>I-Iias/Explorer1632_dsPIC33EP
/*******************************************************************************
Copyright 2016 Microchip Technology Inc. (www.microchip.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*******************************************************************************/
#include <stdint.h>
#include <stdbool.h>
#ifndef _RTCC_H
#define _RTCC_H
typedef struct
{
bool bcdFormat;
uint8_t year;
uint8_t month;
uint8_t day;
uint8_t weekday;
uint8_t hour;
uint8_t minute;
uint8_t second;
} RTCC_DATETIME;
void RTCC_Initialize (RTCC_DATETIME * value);
void RTCC_TimeGet (RTCC_DATETIME * value);
void RTCC_BuildTimeGet( RTCC_DATETIME *dateTime);
/* Deprecated API. Will be removed in future release. */
#define BSP_RTCC_DATETIME RTCC_DATETIME
void __attribute__((deprecated)) BSP_RTCC_Initialize (BSP_RTCC_DATETIME * value);
void __attribute__((deprecated)) BSP_RTCC_TimeGet (BSP_RTCC_DATETIME * value);
#endif
|
I-Iias/Explorer1632_dsPIC33EP | bsp/power.h | /*******************************************************************************
Copyright 2016 Microchip Technology Inc. (www.microchip.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*******************************************************************************/
#ifndef BSP_POWER_H
#define BSP_POWER_H
/** Type defintions *********************************/
typedef enum
{
POWER_SOURCE_USB,
POWER_SOURCE_MAINS
} POWER_SOURCE;
/*********************************************************************
* Function: POWER_SOURCE POWER_SourceGet(void)
*
* Overview: Gets the current source of power for the board
*
* PreCondition: None
*
* Input: None
*
* Output: POWER_SOURCE - the current source of power for the board
*
********************************************************************/
POWER_SOURCE POWER_SourceGet(void);
#define POWER_SourceGet() POWER_SOURCE_MAINS
#endif //BSP_POWER_H
|
I-Iias/Explorer1632_dsPIC33EP | EEPROM_emulation.h | <filename>EEPROM_emulation.h<gh_stars>0
/*
* File: EEPROM_emulation.h
* Author: Matthias
*
* Created on 21. Mai 2019, 21:09
*/
#ifndef EEPROM_EMULATION_H
#define EEPROM_EMULATION_H
#include "libs\DEE_Emulation_16-bit.h"
#include "types.h"
#define EEPROM_addr_Pot 10
void Init_EEPROM (void);
boolean EEPROM_write(uint16 data, uint16 addr);
uint16 EEPROM_read(uint16 addr);
#endif /* EEPROM_EMULATION_H */
|
ArjunaElins/arjuna | Software/MPU/include/nRF24L01.h | <reponame>ArjunaElins/arjuna<filename>Software/MPU/include/nRF24L01.h
/**
* Odroid nRF24L01 Library
*
* Copyright (c) 2015 <NAME> <<EMAIL>>
*
* 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.
*/
#ifndef _NRF24L01_H_
#define _NRF24L01_H_
/**
* Commands Mask
*/
#define R_REGISTER 0x00
#define W_REGISTER 0x20
#define ACTIVATE 0x50
#define R_RX_PL_WID 0x60
#define R_RX_PAYLOAD 0x61
#define W_TX_PAYLOAD 0xA0
#define W_ACK_PAYLOAD 0xA8
#define W_TX_PAYLOAD_NO_ACK 0xB0
#define FLUSH_TX 0xE1
#define FLUSH_RX 0xE2
#define REUSE_TX_PL 0xE3
#define NOP 0xFF
#define RW_MASK 0x1F
/**
* nRF24L01 Register Map
*/
#define CONFIG 0x00
#define EN_AA 0x01
#define EN_RXADDR 0x02
#define SETUP_AW 0x03
#define SETUP_RETR 0x04
#define RF_CH 0x05
#define RF_SETUP 0x06
#define STATUS 0x07
#define OBSERVE_TX 0x08
#define CD 0x09
#define RX_ADDR_P0 0x0A
#define RX_ADDR_P1 0x0B
#define RX_ADDR_P2 0x0C
#define RX_ADDR_P3 0x0D
#define RX_ADDR_P4 0x0E
#define RX_ADDR_P5 0x0F
#define TX_ADDR 0x10
#define RX_PW_P0 0x11
#define RX_PW_P1 0x12
#define RX_PW_P2 0x13
#define RX_PW_P3 0x14
#define RX_PW_P4 0x15
#define RX_PW_P5 0x16
#define FIFO_STATUS 0x17
#define DYNPD 0x1C
#define FEATURE 0x1D
/**
* Register Mnemonics
*/
/* CONFIG Register Mnemonics */
#define MASK_RX_DR 6
#define MASK_TX_DS 5
#define MASK_MAX_RT 4
#define EN_CRC 3
#define CRCO 2
#define PWR_UP 1
#define PRIM_RX 0
/* EN_AA Register Mnemonics */
#define ENAA_P5 5
#define ENAA_P4 4
#define ENAA_P3 3
#define ENAA_P2 2
#define ENAA_P1 1
#define ENAA_P0 0
/* EN_RXADDR Register Mnemonics */
#define ERX_P5 5
#define ERX_P4 4
#define ERX_P3 3
#define ERX_P2 2
#define ERX_P1 1
#define ERX_P0 0
/* SETUP_AW Register Mnemonics */
#define AW 0
/* SETUP_RETR Register Mnemonics */
#define ARD 4
#define ARC 0
/* RF_CH Register Mnemonics */
#define RH_CH 0
/* RF_SETUP Register Mnemonics */
#define PLL_LOCK 4
#define RF_DR 3
#define RF_PWR_HIGH 2
#define RF_PWR_LOW 1
#define LNA_HCURR 0
/* STATUS Register Mnemonics */
#define RX_DR 6
#define TX_DS 5
#define MAX_RT 4
#define RX_P_NO 1
#define STX_FULL 0
/* OBSERVE_TX Register Mnemonics */
#define PLOS_CNT 4
#define ARC_CNT 0
/* CD Register Mnemonics */
#define MD 0
/* FIFO_STATUS Register Mnemonics */
#define TX_REUSE 6
#define TX_FULL 5
#define TX_EMPTY 4
#define RX_FULL 1
#define RX_EMPTY 0
/* DYNPD Register Mnemonics */
#define DPL_P5 5
#define DPL_P4 4
#define DPL_P3 3
#define DPL_P2 2
#define DPL_P1 1
#define DPL_P0 0
/* FEATURE Register Mnemonics */
#define EN_DPL 2
#define EN_ACK_PAY 1
#define EN_DYN_ACK 0
/* CRC Encoding Scheme */
enum CRCLength {CRC_1_BYTE = 0, CRC_2_BYTE, CRC_DISABLED};
/* Air Data Rate */
enum DataRate {RF_DR_1MBPS = 0, RF_DR_2MBPS};
/* RF Output Power */
enum RFPower {RF_PA_MIN = 0, RF_PA_LOW, RF_PA_HIGH, RF_PA_MAX};
#endif |
ArjunaElins/arjuna | Software/MPU/include/MidiEventList.h | //
// Programmer: <NAME> <<EMAIL>>
// Creation Date: Sat Feb 14 21:55:38 PST 2015
// Last Modified: Sat Feb 14 21:55:40 PST 2015
// Filename: midifile/include/MidiEventList.h
// Website: http://midifile.sapp.org
// Syntax: C++11
// vim: ts=3 expandtab
//
// Description: A class which stores a MidiEvents for a MidiFile track.
//
#ifndef _MIDIEVENTLIST_H_INCLUDED
#define _MIDIEVENTLIST_H_INCLUDED
#include "MidiEvent.h"
#include <vector>
using namespace std;
class MidiEventList {
public:
MidiEventList (void);
~MidiEventList ();
MidiEvent& operator[] (int index);
MidiEvent& back (void);
MidiEvent& last (void);
MidiEvent& getEvent (int index);
void clear (void);
void reserve (int rsize);
int getSize (void);
int size (void);
int linkNotePairs (void);
void clearLinks (void);
MidiEvent** data (void);
int push (MidiEvent& event);
int push_back (MidiEvent& event);
int append (MidiEvent& event);
// careful when using these, intended for internal use in MidiFile class:
void detach (void);
int push_back_no_copy (MidiEvent* event);
private:
vector<MidiEvent*> list;
};
#endif /* _MIDIEVENTLIST_H_INCLUDED */
|
ArjunaElins/arjuna | Software/MPU/include/ORF24.h | /**
* Odroid nRF24L01 Library
*
* Copyright (c) 2015 <NAME> <<EMAIL>>
*
* 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.
*/
#ifndef _ORF_24_H_
#define _ORF_24_H_
#include <iostream>
#include <string>
#include <cstdio>
#include <wiringPi.h>
#include <wiringPiSPI.h>
#include "nRF24L01.h"
#define MOSI_PIN 12
#define SLCK_PIN 14
class ORF24
{
private:
int ce; /* CE pin number */
int csn; /* CSN pin number */
int spiChannel; /* Odroid SPI channel */
int spiSpeed; /* SPI clock frequency in Hz */
int payloadSize; /* nRF24L01 payload size */
int ackPayloadAvailable; /* Whether there is an ack payload waiting */
bool ackPayloadLength; /* Dynamic size of pending ack payload */
bool dynamicPayloadAvailable; /* Whether dynamic payload are enabled */
bool debug = false; /* Debug flag */
unsigned char buffer[32]; /* RX and TX buffer */
unsigned char *pipe0ReadingAddress;
protected:
/**
* Read one byte from nRF24L01 register
*
* @param reg register address
* @return read register value
*/
unsigned char readRegister(unsigned char reg);
/**
* Read multibyte from nRF24L01 register
*
* @param reg register address
* @param buf read buffer
* @param len data length to read
* @return read register value
*/
unsigned char readRegister(unsigned char reg, unsigned char *buf, int len);
/**
* Write one byte to nRF24L01 register
*
* @param reg register address
* @param value value to write
* @return nRF24L01 status
*/
unsigned char writeRegister(unsigned char reg, unsigned char value);
/**
* Write multibyte to nRF24L01 register
*
* @param reg register address
* @param buf write buffer
* @param len data length to write
* @return nRF24L01 status
*/
unsigned char writeRegister(unsigned char reg, const unsigned char *buf, int len);
/**
* Write payload to send
*
* @param data data to send
* @param len data length in byte
* @return nRF24L01 status
*/
unsigned char writePayload(unsigned char *data, int len);
/**
* Read received payload
*
* @param data data buffer to read into
* @param len data length
* @return nRF24L01 status
*/
unsigned char readPayload(unsigned char *data, int len);
/**
* Flush RX FIFO
*
* @return status
*/
unsigned char flushRX(void);
/**
* Flush TX FIFO
*
* @return status
*/
unsigned char flushTX(void);
/**
* Get RF status register
*
* @return status register
*/
unsigned char getStatus(void);
/**
* Print register value
*
* @param name register name
* @param reg register address
*/
void printRegister(std::string name, unsigned char reg);
/**
* Print address register
*
* @param name register name
* @param reg register address
*/
void printAddressRegister(std::string name, unsigned char reg);
/**
* Print address register as string
*
* @param name register name
* @param reg register address
* @param str print as string
*/
void printAddressRegister(std::string name, unsigned char reg, bool str);
/**
* Print all register value
*/
void printAllRegister(void);
public:
/**
* ORF24 Constructor
*/
ORF24(int _ce);
/**
* ORF24 Constructor with SPI options
*/
ORF24(int _ce, int _spiChannel, int spiSpeed);
/**
* nRF24L01 Initialization
*
* @return status
*/
bool begin(void);
/**
* Write payload to open writing pipe
*
* @param data data to write
* @param len data length
* @return status
*/
bool write(unsigned char *data, int len);
/**
* Start writing payload
*
* @param data data to write
* @param len data length
*/
void startWrite(unsigned char *data, int len);
/**
* Set delay and number of retry for retransmission
*
* @param delay retransmission delay
* @param count retransmission count
*/
void setRetries(int delay, int count);
/**
* Set RF channel
*
* @param channel channel number
*/
void setChannel(int channel);
/**
* Set payload size
*
* @param size payload size
*/
void setPayloadSize(int size);
/**
* Set power level
*
* @param level power level
*/
void setPowerLevel(RFPower level);
/**
* Set air data rate
*
* @param rate data rate
*/
void setDataRate(DataRate rate);
/**
* Set CRC length
*
* @param length CRC length
*/
void setCRCLength(CRCLength length);
/**
* Set auto acknowledgment
*
* @param enable enable or disable auto acknowledgment
*/
void setAutoACK(bool enable);
/**
* Set auto acknowledgment
*
* @param pipe pipe number
* @param enable enable or disable auto acknowledgment
*/
void setAutoACK(int pipe, bool enable);
/**
* Set nRF24L01 to standby mode
*/
void powerUp(void);
/**
* Set nRF24L01 to power down mode
*/
void powerDown(void);
/**
* Open writing pipe
*
* @param address pipe address
*/
void openWritingPipe(const char *address);
/**
* Open reading pipe
*
* @param number pipe number
* @param address pipe address
*/
void openReadingPipe(int pipe, const char *address);
/**
* Enable debugging information
*/
void enableDebug(void);
};
#endif |
ArjunaElins/arjuna | Software/MPU/include/Setup.h | /**
* Arjuna: Alat Bantu Pembelajaran Piano untuk Tunanetra
*
* Developed by:
* <NAME>
* <NAME>
* <NAME>
*
* Elektronika dan Instrumentasi
* Universitas Gadjah Mada
*
* Copyright (c) 2015 Arjuna
*
* 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.
*
*/
#ifndef _SETUP_H_
#define _SETUP_H_
#include <iostream>
#include <tclap/CmdLine.h>
#include <wiringPi.h>
#include "MidiIO.h"
#include "ORF24.h"
#include "WiringPiKeypad.h"
/**
* A structure to contain command line arguments
*/
struct Args {
bool debugEnabled;
bool keyboardEnabled;
};
/**
* Container is a struct to contain hardware handler
*/
struct Container {
MidiIO *io;
ORF24 *rf;
WiringPiKeypad *keypad;
};
/**
* Get Command Line Arguments
*
* This function uses TCLAP library to parse command line arguments
*
* @param argc arguments count
* @param argv arguments vector
* @return parsed arguments
*/
struct Args getArgs(int argc, char *argv[]);
/**
* Initial Hardware Setup
*
* This function initialize the device to interface with hardware.
*
* @return setup status
*/
int initHardware(struct Container *container, struct Args *args);
/**
* Setup MIDI Input/Output
*
* @return status
*/
int midiIOSetup(struct Container *container, struct Args *args);
/**
* Setup nRf24L01+ Radio Transceiver
*
* @return status
*/
int radioSetup(struct Container *container, struct Args *args);
/**
* Setup keypad matrix
*
* @return status
*/
int keypadSetup(struct Container *container, struct Args *args);
#endif |
ArjunaElins/arjuna | Software/MPU/include/Arjuna.h | <reponame>ArjunaElins/arjuna
/**
* Arjuna: Alat Bantu Pembelajaran Piano untuk Tunanetra
*
* Developed by:
* <NAME>
* <NAME>
* <NAME>
*
* Elektronika dan Instrumentasi
* Universitas Gadjah Mada
*
* Copyright (c) 2015 Arjuna
*
* 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.
*
*/
#ifndef _ARJUNA_H_
#define _ARJUNA_H_
#include <iostream>
#include <fstream>
#include <string>
#include <thread>
#include "Setup.h"
#include "MidiFile.h"
#include "FingerData.h"
#define SELECT_SONG_BUTTON 'A'
#define PLAY_SONG_BUTTON 'B'
#define EVALUATOR_BUTTON 'C'
#define STOP_BUTTON 'D'
#define BOTH_HANDS_MODE_BUTTON '1'
#define RIGHT_HAND_MODE_BUTTON '2'
#define LEFT_HAND_MODE_BUTTON '3'
struct Key
{
int track;
unsigned char note;
unsigned char finger;
};
enum PlayMode {BOTH_HANDS, LEFT_HAND, RIGHT_HAND};
enum MPUOperation {PLAYER, EVALUATOR};
/**
* Main Function
*
* This is the starting point of the program.
*
* @param argc arg count
* @param argv arg vector
* @return status
*/
int main(int argc, char *argv[]);
/**
* Start Application Routine
*
* This routine start by showing main menu. It will handle user input
* and call other methods depending on the input.
*/
void startRoutine(Container *container);
/**
* Show Application Menu
*
* In this screen, user can select the application operation.
*/
void showMenu(void);
/**
* Song Selector
*
* This method will start the song selector.
*
* @param container hardware handler
*/
std::string songSelector(Container *container);
/**
* Print Song List
*
* This method will parse every line of the file handler and print it
* to stdout
*
* @param songList [description]
*/
void printSongList(std::ifstream *songList);
/**
* Select Song
*
* This method will ask the user to choose from opened song list
*
* @param songList song list handler
* @return song name
*/
std::string selectSong(Container *container, std::ifstream *songList);
/* Start MIDI Processing Algorithm
*
* This function is a bootstrap for the MIDI Processing Algorithm.
* It will call the player or the evaluator, depending on user selection
*
* @param container hadrware handler
* @param songPath selected song path
* @param mode MPA operation mode
*/
void startMPA(Container *container, std::string songPath, MPUOperation operation);
/**
* Song Player
*
* This method is used to play MIDI song. It will open the MIDI file,
* calculate some numbers, and send MIDI message to output port
*
* @param container hardware handler
* @param midi MIDI file handler
* @param finger finger data handler
* @param mode selected play mode
*/
void play(Container *container, MidiFile *midi, FingerData *finger, PlayMode mode);
/**
* Song Evaluator
*
* This function is used to compare MIDI input with MIDI data and give
* response to hands odule
* @param container handware handler
* @param midi MIDI file handler
* @param finger finger data handler
* @param mode selected play mode
*/
void evaluate(Container *container, MidiFile *midi, FingerData *finger, PlayMode mode);
/**
* Get Unison Note
*
* This function groups note played at the same time
*
* @param midi MIDI file handler
* @param m MIDI file index
* @param t MIDI track number
* @param keys Keys container
* @return status
*/
bool getUnisonNote(MidiFile *midi, int *m, int t, std::vector<Key> *keys);
/**
* Get Unison Finger
* This function groups finger played at the same time
*
* @param finger finger data handler
* @param f finger data index
* @param keys Keys container
*/
void getUnisonFinger(FingerData *finger, std::vector<char> *f, std::vector<Key> *keys);
/**
* Get MIDI Input
*
* @param io MIDI IO handler
* @param expected number of expected input
*/
void getInputAndEvaluate(Container *container, std::vector<Key> keys, char *keypress, MidiFile *midi, int m, int t);
/**
* Compare MIDI Input with MIDI Data
*
* @param rf Trasceiver handler
* @param keys MIDI Data
* @param note MIDI Input
* @return Compare result
*/
bool compare(ORF24 *rf, std::vector<Key> *keys, unsigned char note);
/**
* Get Play Mode
*
* This function ask the user to select the play mode
*
* @param keypad keypad handler
* @return play mode
*/
PlayMode getPlayMode(WiringPiKeypad *keypad);
/**
* Set Play Mode
*
* This function prepares the MIDI file to play in right, left, or both hand modes
*
* @param midi MIDI object
* @param mode Chosen mode
*/
void setPlayMode(MidiFile *midi, PlayMode mode);
/**
* Get Tempo in Second Per Tick
*
* @param e MidiEvent
* @param tpq tick peq quarter
* @param spt second per tick
*/
void getTempoSPT(MidiEvent e, int tpq, double *spt);
/**
* Send MIDI Message
*
* This method will form a MIDI message container and send it to MIDI output port
*
* @param io MIDI i/O port
* @param e MIDI event
*/
void sendMidiMessage(MidiIO *io, MidiEvent e);
/**
* Send Feedback to Hand Module
*
* This method use the radio transceiver to send payload to hand module
*
* @param rf radio handler
* @param f finger data
* @param t active track
* @param right turn on right vibrator. If false, then turn on left vibrator
*/
void sendFeedback(ORF24 *rf, char f, int t, bool right);
/**
* Inverse Finger Number
*
* Command for right hand module need to be inverted before sending.
* This function will do the inversion.
*
* @param finger finger number
* @return inverted finger number
*/
unsigned char inverse(unsigned char finger);
/**
* Keypad Handler
*
* This function should be called in separate thread to wair for user action
* while doing other operation
*
* @param keypad keypad handler
* @param keypress keypress handler
* @param terminator keypad terminator
*/
void keypadHandler(WiringPiKeypad *keypad, char *keypress, bool *terminator);
#endif |
ArjunaElins/arjuna | Software/MPU/include/MidiIO.h | <gh_stars>0
/**
* Arjuna: Alat Bantu Pembelajaran Piano untuk Tunanetra
*
* Developed by:
* <NAME>
* <NAME>
* <NAME>
*
* Elektronika dan Instrumentasi
* Universitas Gadjah Mada
*
* Copyright (c) 2015 Arjuna
*
* 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.
*
*/
#ifndef _MIDI_IO_H_
#define _MIDI_IO_H_
#include <iostream>
#include "RtMidi.h"
/**
* MidiIO Class Interface
*
* MidiIO is a class to interface with MIDI device. It allows the application
* to open and close input and output port with the MIDI device, and send them
* MIDI messages.
*/
class MidiIO
{
private:
/**
* Input Port Number
*/
unsigned int inPort;
/**
* Output Port Number
*/
unsigned int outPort;
/**
* Debug Level
*
* The higher the level, more information will be shown
*/
bool debug;
/**
* RtMidi Input instance
*/
RtMidiIn *in;
/**
* RtMidi Output instance
*/
RtMidiOut *out;
/**
* Initialize MIDI IO
*
* This method creates RtMidi input and output instance
*/
void initIO(void);
public:
/**
* MidiIO Class Constructor
*
* This constructor set the default input and output port
*/
MidiIO();
/**
* MidiIO Class Constructor
*
* This constructor receive input and output port as arguments and set
* those ports to the class properties.
*
* @param int in input port
* @param int out output port
*/
MidiIO(int in, int out);
/**
* Enable Debug
*
* This option will show debug informatio if set to true
*
* @param bool enable
*/
void enableDebug(bool enable);
/**
* Open MIDI Input Port
*
* @return status
*/
int openMidiInPort(void);
/**
* Close MIDI Input Port
*
* @return status
*/
int closeMidiInPort(void);
/**
* Open MIDI Output Port
*
* @return status
*/
int openMidiOutPort(void);
/**
* Close MIDI output port
*
* @return status
*/
int closeMidiOutPort(void);
/**
* Send MIDI Message to Output Port
*
* @param message message container
*/
void sendMessage(std::vector<unsigned char> *message);
/**
* Receive MIDI message from Input port
*
* @param message message container
* @return stamp
*/
double getMessage(std::vector<unsigned char> *message);
};
#endif |
ArjunaElins/arjuna | Software/MPU/include/WiringPiKeypad.h | <gh_stars>0
/**
* WiringPi Matrix Keypad Library
*
* Copyright (c) 2015 <NAME> <<EMAIL>>
*
* 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.
*
*/
#ifndef _KEYPAD_H_
#define _KEYPAD_H_
#include <iostream>
#include <vector>
#include <wiringPi.h>
struct key
{
int row;
int column;
};
class WiringPiKeypad
{
protected:
int rowSize;
int columnSize;
int *rowPin;
int *columnPin;
std::vector<std::vector<char>> matrix;
int debounceDelay;
int pollingDelay;
public:
WiringPiKeypad(int _rowSize, int _columnSize);
WiringPiKeypad(int _rowSize, int _columnSize, int debounceDelay, int pollingDelay);
void setRowPin(int *row);
void setColumnPin(int *column);
void setMatrix(std::vector<std::vector<char>> m);
void setDebounceDelay(int delay);
void setPollingDelay(int delay);
int getDebounceDelay(void);
int getPollingDelay(void);
struct key getRawKey(void);
struct key getRawKey(bool *terminator);
char getKey(void);
char getKey(bool *terminator);
bool inputIs(int row, int column);
bool inputIs(struct key keypress, int row, int column);
void printDetails(void);
};
#endif |
ArjunaElins/arjuna | Software/MPU/include/FingerData.h | /**
* Arjuna: Alat Bantu Pembelajaran Piano untuk Tunanetra
*
* Developed by:
* <NAME>
* <NAME>
* <NAME>
*
* Elektronika dan Instrumentasi
* Universitas Gadjah Mada
*
* Copyright (c) 2015 Arjuna
*
* 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.
*
*/
#ifndef _FINGER_DATA_H
#define _FINGER_DATA_H
#include <iostream>
#include <fstream>
#include <list>
#include <vector>
#include <cstdio>
class FingerEvent
{
private:
char data;
public:
void setData(char d);
char getData(void);
bool isCheckpoint(void);
};
class FingerTrack
{
private:
int trackLength;
std::vector<FingerEvent> events;
public:
void setTrackLength(char *p);
int getTrackLength(void);
void push(FingerEvent event);
FingerEvent operator[](int i);
};
class FingerData
{
private:
int trackCount;
std::vector<FingerTrack> tracks;
char *open(std::string filepath);
void parse(char *buffer);
public:
FingerData(std::string filepath);
int getTrackCount(void);
FingerTrack operator[](int i);
char getData(int t, int e);
void printAllEvents(void);
};
#endif |
francisceioseph/C-MetodosNumericos01 | tr01-metodos/main.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#define EPSILON 0.00000001
//Metodos utilizados no Sistema Linear
double** alocaMatriz(int l, int c);
void imprimeMatriz(double **m, int l, int c);
void desalocaMatriz(double **m, int l);
void pivotacao(double **m, int n,int v[]);
int procuraMaior(double *m, int tam);
void inicializaMatrizDoArquivo(char *filename, double **m);
int* alocaVetorPosicaoColunas(int n);
int sretro(double **m,int n,double x[]);
void initPivotacao();
void menu();
int fileExist(char *nomeArquivo);
//Metodo utilizado na Conversao
void initConversao();
int main()
{
menu();
return 0;
}
void menu(){
char opcao;
int continua = 1;
while(continua){
printf("\n\n\t### MENU PRINCIPAL ###\n\n");
printf("\tC - Convers\706o\n");
printf("\tS - Sistema Linear\n");
printf("\tE - Equa\207\706o Alg\202brica\n");
printf("\tF - Finalizar\n");
printf("\n\tEscolha uma op\207\706o: ");
scanf(" %c",&opcao);
getchar();
switch( opcao )
{
case 'c':
case 'C':
initConversao();
break;
case 's':
case 'S':
initPivotacao();
break;
case 'e':
case 'E':
//adicionar Lagrange aqui
break;
case 'f':
case 'F':
continua = 0;
break;
default:
printf("\n\n\tERRO! Voc\210 digitou uma opera\207\706o inv\240lida.\n");
break;
}
}
printf("\n\tPrograma finalizado.\n");
}
typedef struct { //Definindo estrutura para Binário e Octal
char *parteInteira;
int parteFracionaria[20]; //Tamanho máximo da parte fracionária
int preenchido; //Ultima posição utilizada do vetor parteFracionaria
} binario_Octal;
typedef struct { //Definindo estrutura para Hexa
char *parteInteira;
char parteFracionaria[20]; //Tamanho máximo da parte fracionária
int preenchido; //Ultima posição utilizada do vetor parteFracionaria
} hexadecimal;
binario_Octal ConversaoBinaria (double decimal){ //Função de conversão de Decimal para Binário
binario_Octal bin;
bin.parteInteira = malloc(sizeof(double));
int contador;
long parteInteiraDecimal = (long)decimal; //Separando a parte inteira do número
double parteFracionariaDecimal = decimal - parteInteiraDecimal; //Separando a parte fracionária do número
itoa(parteInteiraDecimal, bin.parteInteira, 2); //Convertendo a parte inteira para a base numérica desejada
contador = 0;
while(contador != 20 && parteFracionariaDecimal != 0){ //Convertendo a parte fracionária
parteFracionariaDecimal = 2 * parteFracionariaDecimal;
bin.parteFracionaria[contador] = (int)parteFracionariaDecimal;
parteFracionariaDecimal = parteFracionariaDecimal - (long)parteFracionariaDecimal;
contador++;
}
bin.preenchido = contador; //Informando quantas posições do vetor parteFracionária foram utilizadas
return bin;
}
binario_Octal ConversaoOctal(double decimal){ //Função de conversão de Decimal para Octal
binario_Octal octal;
octal.parteInteira = malloc(sizeof(double));
int contador = 0;
long parteInteiraDecimal = (long)decimal; //Separando a parte inteira do número
double parteFracionariaDecimal = decimal - parteInteiraDecimal; //Separando a parte fracionária do número
itoa(parteInteiraDecimal, octal.parteInteira, 8); //Convertendo a parte inteira para a base numérica desejada
while(contador != 20 && parteFracionariaDecimal != 0){ //Convertendo a parte fracionária
parteFracionariaDecimal = 8 * parteFracionariaDecimal;
octal.parteFracionaria[contador] = (int)parteFracionariaDecimal;
parteFracionariaDecimal = parteFracionariaDecimal - (long)parteFracionariaDecimal;
contador++;
}
octal.preenchido = contador; //Informando quantas posições do vetor parteFracionária foram utilizadas
return octal;
}
hexadecimal ConversaoHexa(double decimal){ //Função de conversão de Decimal para Hexadecimal
char mapaHexa[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; //Criando um mapa para atribuir valores hexa correto a parte fracionária
hexadecimal hexa;
hexa.parteInteira = malloc(sizeof(double));
int contador = 0;
long parteInteiraDecimal = (long)decimal; //Separando a parte inteira do número
double parteFracionariaDecimal = decimal - parteInteiraDecimal; //Separando a parte fracionária do número
itoa(parteInteiraDecimal, hexa.parteInteira, 16); //Convertendo a parte inteira para a base numérica desejada
while(contador != 20 && parteFracionariaDecimal != 0){ //Convertendo a parte fracionária
parteFracionariaDecimal = 16 * parteFracionariaDecimal;
hexa.parteFracionaria[contador] = mapaHexa[(int)parteFracionariaDecimal]; //Usando o mapa para atribuir a string os valores corretos
parteFracionariaDecimal = parteFracionariaDecimal - (long)parteFracionariaDecimal;
contador++;
}
hexa.preenchido = contador; //Informando quantas posições do vetor parteFracionária foram utilizadas
return hexa;
}
void imprimirValoresBinario (binario_Octal x){ //Função impressão do valor binário no console
printf("\n\tBinario: ");
printf("%s", x.parteInteira);
printf(".");
int i;
for(i = 0; i < x.preenchido; i++){
printf("%d", x.parteFracionaria[i]);
}
printf("\n");
}
void imprimirValoresOctal (binario_Octal x){ //Função impressão do valor octal no console
printf("\tOctal: ");
printf("%s", x.parteInteira);
printf(".");
int i;
for(i = 0; i < x.preenchido; i++){
printf("%d", x.parteFracionaria[i]);
}
printf("\n");
}
void imprimirValoresHexa (hexadecimal hexa){ //Função impressão do valor hexadecimal no console
printf("\tHexadecimal: ");
int i;
for (i = 0; i<strlen(hexa.parteInteira); i++){
printf("%c", toupper(hexa.parteInteira[i])); //Transforma qualquer char minúsculo contido no vetor em char maiúsculo
}
printf(".");
for (i = 0; i<hexa.preenchido; i++){
printf("%c", hexa.parteFracionaria[i]);
}
printf("\n");
}
void initConversao(){
double decimal;
printf("\n\tDigite um numero decimal :");
scanf("%lf",&decimal);
binario_Octal bin;
bin = ConversaoBinaria(decimal);
imprimirValoresBinario(bin);
free(bin.parteInteira);
bin = ConversaoOctal(decimal);
imprimirValoresOctal(bin);
free(bin.parteInteira);
hexadecimal hexa;
hexa = ConversaoHexa(decimal);
imprimirValoresHexa(hexa);
free(hexa.parteInteira);
}
void initPivotacao(){
char namefile[50];
printf("\n\tNome do arquivo : ");
scanf("%s",&namefile);
strcat(namefile,".txt");
if(fileExist(namefile)==1){
int tam = obtemTamanhoMatriz(namefile);
double **m = alocaMatriz(tam, tam + 1);
int *v = alocaVetorPosicaoColunas(tam);
inicializaMatrizDoArquivo(namefile, m);
//imprimeMatriz(m, tam, tam + 1);
pivotacao(m, tam,v);
resolveMatrizTS(m,tam,v);
//imprimeMatriz(m, tam, tam + 1);
desalocaMatriz(m,tam);
}else{
printf("\n\tERRO! Arquivo n\706o existe.\n");
}
}
void pivotacao(double **m, int n,int v [])
{
/*
* Esta função implementa o metodo da pivotação completa
*
* Parametros:
* **m : uma ponteiro para uma matriz de doubles
* n : tamanho da matriz m
*
* Variaveis:
* i, j, k : contadores
*
* maior : maior elemento em uma linha pivotal
* lm : linha do maior elemento em uma linha pivotal
* cm : coluna do maior elemento de uma linha pivotal
*
* *aux : ponteiro para uma linha da matriz estentendida m
*
* mult : multiplicador a ser usado nas linhas a serem pivotadas
*
* v : vetor que armazena as posicoes finais das colunas
*/
int i, j, k;
double maior = m[0][0];
int lm = 0;
int cm = 0;
int lt = 0;
double *aux;
double aux_troca;
int aux_pos;
double mult;
for(i = 0; i < n; i++)
{
v[i]= i; //armazena as posicoes finais das colunas
}
for (i = 0; i < n; i++)
{
maior = fabs(m[i][0]);
lm = i;
cm = 0;
//Procura o maior elemento das linhas ainda
//não pivotadas da matriz de coeficientes.
for (j = i; j < n; j++)
{
for(k = 0; k < n; k++)
{
if (fabs(m[j][k]) > fabs(maior))
{
maior = m[j][k];
lm = j;
cm = k;
}
}
}
//Troca a linha i com a linha do maior.
aux = m[i];
m[i] = m[lm];
m[lm] = aux;
lm = i;
//Realiza a pivotação das linhas abaixo da linha i
for(j = i+1; j < n; j++)
{
mult = -m[j][cm] / m[lm][cm];
m[j][cm] = 0;
for(k = 0; k <= n; k++)
{
if(k != cm)
{
m[j][k] += m[lm][k] * mult;
}
}
}
//printf("pivot = %10.8lf\n", maior);
//imprimeMatriz(m, n, n+1);
printf("\n");
//Efetua a troca das colunas
if(i!=cm){
for(lt=0;lt<n;lt++){
aux_troca = m[lt][cm];
m[lt][cm] = m[lt][i];
m[lt][i] = aux_troca;
}
aux_pos = v[i];
v[i] = v[cm];
v[cm] = aux_pos;
}
}
//resolveMatrizTS(m,n,v);
}
int sretro(double **m,int n,double x[]){
/*Resolve um SL TS com n variaveis cuja matriz aumentada e m.
* Se o SL for determinado, x recebe a soluсao do SL e a funсao devolve 0;
* Se for indeterminado x recebe uma das infinitas soluушes do SL e a funсao devolve 1;
* Se for incompativel a funсao devolve 2;
*/
int i,k, tipo=0;
double soma;
for(i=n-1;i>=0;i--){
soma =0;
for(k=i+1;k<n;k++){
soma += m[i][k]*x[k];
}
if(fabs(m[i][i])<EPSILON){
if(fabs(m[i][n]-soma)<EPSILON){
/*x[i] e variрvel livre*/
x[i]=0;
tipo = 1;
}else{
return 2; /*SL incompatьvel*/
}
}else{
x[i]=(m[i][n]-soma)/m[i][i];
}
}
return tipo;
}/*Fim sretro*/
void resolveMatrizTS(double **m,int n, int v [])
{
double *x;
int tipo,i;
x = malloc(sizeof(double)*n);
if(x==NULL){
printf("Erro ao alocar Matriz. Falta de memoria!\n");
return 1;
}
tipo = sretro(m,n,x);
printf("\tO SL \202 %s\n\n", tipo==0?"Determinado":tipo==1?"Indeterminado":"Incompativel");
if(tipo!=2){
for(i=0;i<n;i++){
printf("x[%d] = %10.3lf ", v[i]+1,x[i]);
}
printf("\n\n");
imprimeMatriz(m, n, n + 1);
}
}
int procuraMaior(double *m, int tam)
{
/* Dado um vetor, esta função procura o maior elemento
* os indices 0 e tam - 1.
* A função retorna o indice o maior elemento.
*/
int i;
int indiceMaior = 0;
double maior = m[0];
for(i = 1; i < tam; i++)
{
if(m[i] > maior)
{
maior = m[i];
indiceMaior = i;
}
}
return indiceMaior;
}
void inicializaMatrizDoArquivo(char *filename, double **m)
{
int tam;
int i, j;
double buffer;
FILE *file = fopen(filename, "r");
if (file != NULL)
{
fscanf(file, "%d", &tam);
for (i = 0; i < tam; i++)
{
for (j = 0; j < tam + 1; j ++)
{
fscanf(file, "%lf", &buffer);
m[i][j] = buffer;
}
printf("\n");
}
fclose(file);
}
}
int obtemTamanhoMatriz(char *nomeArquivo)
{
int tam = 0;
FILE *file = fopen(nomeArquivo, "r");
if (file != NULL)
{
fscanf(file, "%d", &tam);
fclose(file);
}else{
printf("Erro! Arquivo invalido.\n");
system ("pause");
}
return tam;
}
// Funcoes genericos de manipulação de matrizes
void imprimeMatriz(double **m, int l, int c)
{
int i, j;
for (i = 0; i < l; i++)
{
for (j = 0; j < c; j++)
{
printf("%12.8lf ", m[i][j]);
}
printf("\n");
}
}
double** alocaMatriz(int l, int c)
{
/*
* Se houver memoria disponivel, alocal uma matriz com
* de tamanho l por c. E devolve o endereco
* base da matriz. Caso contrário, ele devolverá um
* ponteiro nulo.
*
*/
int i, j;
double **m;
m = malloc(sizeof(double*) * l);
if (m != NULL)
{
for (i = 0; i < l; i++)
{
m[i] = malloc(sizeof(double) * c);
if (m[i] == NULL)
{
for (j = 0; j < i; i++)
{
free(m[j]);
}
free(m);
return NULL;
}
}
}
return m;
}
int* alocaVetorPosicaoColunas(int n){
int *v = malloc(sizeof(int) * n);
return v;
}
void desalocaMatriz(double **m, int l)
{
/*
* Desaloca uma matriz previamente alocada
* com a função aloca_matriz.
*/
int i;
if(m != NULL)
{
for (i = 0; i < l; i++)
{
free(m[i]);
}
free(m);
}
}
int fileExist(char *nomeArquivo)
{
int exist = 1;
FILE *file = fopen(nomeArquivo, "r");
if (file == NULL)
{
exist = 0;
}
return exist;
}
|
remember17/WHDebugTool | WHDebugToolDemo/Pods/Target Support Files/WHDebugTool/WHDebugTool-umbrella.h | #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 "WHDebugConsoleLabel.h"
#import "WHDebugCpuMonitor.h"
#import "WHDebugFPSMonitor.h"
#import "WHDebugMemoryMonitor.h"
#import "WHDebugMonitor.h"
#import "WHDebugTempVC.h"
#import "WHDebugToolManager.h"
FOUNDATION_EXPORT double WHDebugToolVersionNumber;
FOUNDATION_EXPORT const unsigned char WHDebugToolVersionString[];
|
remember17/WHDebugTool | WHDebugTool/WHDebugMonitor.h | <gh_stars>100-1000
//
// WHDebugMonitor.h
// Demo
//
// Created by wuhao on 2018/7/26.
// Copyright © 2018年 wuhao. All rights reserved.
// https://github.com/remember17/WHDebugTool
#define WHSingletonH() +(instancetype)sharedInstance;
#define WHSingletonM() static id _instance;\
+ (instancetype)sharedInstance {\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [[self alloc] init];\
});\
return _instance;\
}
#import <Foundation/Foundation.h>
typedef void(^UpdateValueBlock)(float value);
@interface WHDebugMonitor : NSObject
@property (nonatomic, copy) UpdateValueBlock valueBlock;
WHSingletonH()
- (void)startMonitoring;
- (void)stopMonitoring;
@end
|
kylegmaxwell/training | src/heapmerge.h | <filename>src/heapmerge.h
#pragma once
#include "unittest.h"
#include <vector>
#include <queue> // priority_queue
#include <cstdlib> // rand
#include <algorithm>
#include <unordered_map>
#include <memory>
/*!
* \brief The HeapMerge class solves the problem of merging sorted lists.
* The lists are said to be files containing records sorted by time stamp.
* For simplicity in this example the time stamp is the sorting metric and the data.
*/
class HeapMerge : public UnitTest
{
public:
// number of files or arrays of data records
const static int NumFiles;// = 123;
// number of records per file
const static int ArraySize;// = 100;
//! The type of the data records / time stamps in the files
typedef double DataType;
// < Data Record, File Index>
typedef std::pair<DataType, int> DataPair;
//! File containing a list of data records
typedef std::vector<DataType> DataVector;
typedef std::shared_ptr<DataVector> DataVectorPtr;
// Constructor (sets random seed)
HeapMerge();
//! Fill an array to represent the data recorded in the file
void fillArray(DataVector &v);
//! Run the unit test simulation
virtual TestResult test() override;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.