id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
754,643
main.cc
nucleron_matiec/main.cc
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * Copyright (C) 2003-2011 Mario de Sousa (msousa@fe.up.pt) * Copyright (C) 2007-2011 Laurent Bessard and Edouard Tisserant * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* **************************************************************** **************************************************************** **************************************************************** ********* ********* ********* ********* ********* O V E R A L L A R C H I T E C T U R E ********* ********* ********* ********* ********* **************************************************************** **************************************************************** **************************************************************** The compiler works in 4(+1) stages: Stage 1 - Lexical analyser - implemented with flex (iec.flex) Stage 2 - Syntax parser - implemented with bison (iec.y) Stage 3 - Semantics analyser - not yet implemented Stage 4 - Code generator - implemented in C++ Stage 4+1 - Binary code generator - gcc, javac, etc... Data structures passed between stages, in global variables: 1->2 : tokens (int), and token values (char *) 2->1 : symbol tables (defined in symtable.hh) 2->3 : abstract syntax tree (tree of C++ classes, in absyntax.hh file) 3->4 : Same as 2->3 4->4+1 : file with program in c, java, etc... The compiler works in several passes: Pass 1: executes stages 1 and 2 simultaneously Pass 2: executes stage 3 Pass 3: executes stage 4 Pass 4: executes stage 4+1 */ #include <stdio.h> #include <getopt.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include <iostream> #include "config/config.h" #include "absyntax/absyntax.hh" #include "absyntax_utils/absyntax_utils.hh" #include "stage1_2/stage1_2.hh" #include "stage3/stage3.hh" #include "stage4/stage4.hh" #include "main.hh" #ifndef HGVERSION #define HGVERSION "" #endif void error_exit(const char *file_name, int line_no, const char *errmsg, ...) { va_list argptr; va_start(argptr, errmsg); /* second argument is last fixed pamater of error_exit() */ fprintf(stderr, "\nInternal compiler error in file %s at line %d", file_name, line_no); if (errmsg != NULL) { fprintf(stderr, ": "); vfprintf(stderr, errmsg, argptr); } else { fprintf(stderr, "."); } fprintf(stderr, "\n"); va_end(argptr); exit(EXIT_FAILURE); } static void printusage(const char *cmd) { printf("\nsyntax: %s [<options>] [-O <output_options>] [-I <include_directory>] [-T <target_directory>] <input_file>\n", cmd); printf(" -h : show this help message\n"); printf(" -v : print version number\n"); printf(" -f : display full token location on error messages\n"); printf(" -p : allow use of forward references (a non-standard extension?)\n"); printf(" -l : use a relaxed datatype equivalence model (a non-standard extension?)\n"); printf(" -s : allow use of safe datatypes (SAFEBOOL, etc.) (defined in PLCOpen Safety)\n"); // PLCopen TC5 "Safety Software Technical Specification - Part 1" v1.0 printf(" -n : allow use of nested comments (an IEC 61131-3 v3 feature)\n"); printf(" -r : allow use of references (REF_TO, REF, ^, NULL) (an IEC 61131-3 v3 feature)\n"); printf(" -R : allow use of REF_TO ANY datatypes (a non-standard extension!)\n"); printf(" as well as REF_TO in ARRAYs and STRUCTs (a non-standard extension!)\n"); printf(" -a : allow use of non-literals in array size limits (a non-standard extension!)\n"); printf(" -i : allow POUs with no in out and inout parameters (a non-standard extension!)\n"); printf(" -b : allow functions returning VOID (a non-standard extension!)\n"); printf(" -e : disable generation of implicit EN and ENO parameters.\n"); printf(" -c : create conversion functions for enumerated data types\n"); printf(" -O : options for output (code generation) stage. Available options for %s are...\n", cmd); runtime_options.allow_missing_var_in = false; /* disable: allow definition and invocation of POUs with no input, output and in_out parameters! */ stage4_print_options(); printf("\n"); printf("%s - Copyright (C) 2003-2014 \n" "This program comes with ABSOLUTELY NO WARRANTY!\n" "This is free software licensed under GPL v3, and you are welcome to redistribute it under the conditions specified by this license.\n", PACKAGE_NAME); } /* declare the global options variable */ runtime_options_t runtime_options; int main(int argc, char **argv) { symbol_c *tree_root, *ordered_tree_root; char * builddir = NULL; int optres, errflg = 0; int path_len; /* Default values for the command line options... */ runtime_options.allow_void_datatype = false; /* disable: allow declaration of functions returning VOID */ runtime_options.allow_missing_var_in = false; /* disable: allow definition and invocation of POUs with no input, output and in_out parameters! */ runtime_options.disable_implicit_en_eno = false; /* disable: do not generate EN and ENO parameters */ runtime_options.pre_parsing = false; /* disable: allow use of forward references (run pre-parsing phase before the definitive parsing phase that builds the AST) */ runtime_options.safe_extensions = false; /* disable: allow use of SAFExxx datatypes */ runtime_options.full_token_loc = false; /* disable: error messages specify full token location */ runtime_options.conversion_functions = false; /* disable: create a conversion function for derived datatype */ runtime_options.nested_comments = false; /* disable: Allow the use of nested comments. */ runtime_options.ref_standard_extensions = false; /* disable: Allow the use of REFerences (keywords REF_TO, REF, DREF, ^, NULL). */ runtime_options.ref_nonstand_extensions = false; /* disable: Allow the use of non-standard extensions to REF_TO datatypes: REF_TO ANY, and REF_TO in struct elements! */ runtime_options.nonliteral_in_array_size= false; /* disable: Allow the use of constant non-literals when specifying size of arrays (ARRAY [1..max] OF INT) */ runtime_options.includedir = NULL; /* Include directory, where included files will be searched for... */ /* Default values for the command line options... */ runtime_options.relaxed_datatype_model = false; /* by default use the strict datatype equivalence model */ /******************************************/ /* Parse command line options... */ /******************************************/ while ((optres = getopt(argc, argv, ":nehvfplsrRabicI:T:O:")) != -1) { switch(optres) { case 'h': printusage(argv[0]); return 0; case 'v': fprintf(stdout, "%s version %s\n" "changeset id: %s\n", PACKAGE_NAME, PACKAGE_VERSION, HGVERSION); return 0; case 'l': runtime_options.relaxed_datatype_model = true; break; case 'p': runtime_options.pre_parsing = true; break; case 'f': runtime_options.full_token_loc = true; break; case 's': runtime_options.safe_extensions = true; break; case 'R': runtime_options.ref_standard_extensions = true; /* use of REF_TO ANY implies activating support for REF extensions! */ runtime_options.ref_nonstand_extensions = true; break; case 'r': runtime_options.ref_standard_extensions = true; break; case 'a': runtime_options.nonliteral_in_array_size = true; break; case 'b': runtime_options.allow_void_datatype = true; break; case 'i': runtime_options.allow_missing_var_in = true; break; case 'c': runtime_options.conversion_functions = true; break; case 'n': runtime_options.nested_comments = true; break; case 'e': runtime_options.disable_implicit_en_eno = true; break; case 'I': /* NOTE: To improve the usability under windows: * We delete last char's path if it ends with "\". * In this way compiler front-end accepts paths with or without * slash terminator. */ path_len = strlen(optarg) - 1; if (optarg[path_len] == '\\') optarg[path_len]= '\0'; runtime_options.includedir = optarg; break; case 'T': /* NOTE: see note above */ path_len = strlen(optarg) - 1; if (optarg[path_len] == '\\') optarg[path_len]= '\0'; builddir = optarg; break; case 'O': if (stage4_parse_options(optarg) < 0) errflg++; break; case ':': /* -I, -T, or -O without operand */ fprintf(stderr, "Option -%c requires an operand\n", optopt); errflg++; break; case '?': fprintf(stderr, "Unrecognized option: -%c\n", optopt); errflg++; break; default: fprintf(stderr, "Unknown error while parsing command line options."); errflg++; break; } } if (optind == argc) { fprintf(stderr, "Missing input file\n"); errflg++; } if (optind > argc) { fprintf(stderr, "Too many input files\n"); errflg++; } if (errflg) { printusage(argv[0]); return EXIT_FAILURE; } /***************************/ /* Run the compiler... */ /***************************/ /* 1st Pass */ if (stage1_2(argv[optind], &tree_root) < 0) return EXIT_FAILURE; /* 2nd Pass */ /* basically loads some symbol tables to speed up look ups later on */ absyntax_utils_init(tree_root); /* moved to bison, although it could perfectly well still be here instead of in bison code. */ //add_en_eno_param_decl_c::add_to(tree_root); /* Do semantic verification of code */ if (stage3(tree_root, &ordered_tree_root) < 0) return EXIT_FAILURE; /* 3rd Pass */ if (stage4(ordered_tree_root, builddir) < 0) return EXIT_FAILURE; /* 4th Pass */ /* Call gcc, g++, or whatever... */ /* Currently implemented in the Makefile! */ return 0; }
11,142
C++
.cc
227
45.325991
177
0.619306
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,645
absyntax.cc
nucleron_matiec/absyntax/absyntax.cc
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * Copyright (C) 2003-2011 Mario de Sousa (msousa@fe.up.pt) * Copyright (C) 2007-2011 Laurent Bessard and Edouard Tisserant * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* * Definition of the Abstract Syntax data structure components */ #include <stdio.h> #include <stdlib.h> /* required for exit() */ #include <string.h> #include "absyntax.hh" //#include "../stage1_2/iec.hh" /* required for BOGUS_TOKEN_ID, etc... */ #include "visitor.hh" #include "../main.hh" // required for ERROR() and ERROR_MSG() macros. /* The base class of all symbols */ symbol_c::symbol_c( int first_line, int first_column, const char *ffile, long int first_order, int last_line, int last_column, const char *lfile, long int last_order ) { this->first_file = ffile, this->first_line = first_line; this->first_column = first_column; this->first_order = first_order; this->last_file = lfile, this->last_line = last_line; this->last_column = last_column; this->last_order = last_order; this->parent = NULL; this->token = NULL; this->datatype = NULL; this->scope = NULL; } token_c::token_c(const char *value, int fl, int fc, const char *ffile, long int forder, int ll, int lc, const char *lfile, long int lorder) :symbol_c(fl, fc, ffile, forder, ll, lc, lfile, lorder) { this->value = value; this->token = this; // every token is its own reference token. // printf("New token: %s\n", value); } # define LIST_CAP_INIT 8 # define LIST_CAP_INCR 8 list_c::list_c( int fl, int fc, const char *ffile, long int forder, int ll, int lc, const char *lfile, long int lorder) :symbol_c(fl, fc, ffile, forder, ll, lc, lfile, lorder),c(LIST_CAP_INIT) { n = 0; elements = (element_entry_t*)malloc(LIST_CAP_INIT*sizeof(element_entry_t)); if (NULL == elements) ERROR_MSG("out of memory"); } list_c::list_c(symbol_c *elem, int fl, int fc, const char *ffile, long int forder, int ll, int lc, const char *lfile, long int lorder) :symbol_c(fl, fc, ffile, forder, ll, lc, lfile, lorder),c(LIST_CAP_INIT) { n = 0; elements = (element_entry_t*)malloc(LIST_CAP_INIT*sizeof(element_entry_t)); if (NULL == elements) ERROR_MSG("out of memory"); add_element(elem); } /*******************************************/ /* get element in position pos of the list */ /*******************************************/ symbol_c *list_c::get_element(int pos) {return elements[pos].symbol;} /******************************************/ /* find element associated to token value */ /******************************************/ symbol_c *list_c::find_element(symbol_c *token) { token_c *t = dynamic_cast<token_c *>(token); if (t == NULL) ERROR; return find_element((const char *)t->value); } symbol_c *list_c::find_element(const char *token_value) { // We could use strcasecmp(), but it's best to always use the same // method of string comparison throughout matiec nocasecmp_c ncc; for (int i = 0; i < n; i++) if (!ncc(elements[i].token_value, token_value)) return elements[i].symbol; return NULL; // not found } /***********************************************/ /* append a new element to the end of the list */ /***********************************************/ void list_c::add_element(symbol_c *elem) {add_element(elem, elem);} void list_c::add_element(symbol_c *elem, symbol_c *token) { token_c *t = (token == NULL)? NULL : token->token; add_element(elem, (t == NULL)? NULL : t->value); } void list_c::add_element(symbol_c *elem, const char *token_value) { if (c <= n) if (!(elements=(element_entry_t*)realloc(elements,(c+=LIST_CAP_INCR)*sizeof(element_entry_t)))) ERROR_MSG("out of memory"); //elements[n++] = {token_value, elem}; // only available from C++11 onwards, best not use it for now. elements[n].symbol = elem; elements[n].token_value = token_value; n++; if (NULL == elem) return; /* Sometimes add_element() is called in stage3 or stage4 to temporarily add an AST symbol to the list. * Since this symbol already belongs in some other place in the aST, it will have the 'parent' pointer set, * and so we must not overwrite it. We only set the 'parent' pointer on new symbols that have the 'parent' * pointer still set to NULL. */ if (NULL == elem->parent) elem->parent = this; /* adjust the location parameters, taking into account the new element. */ if (NULL == first_file) { first_file = elem->first_file; first_line = elem->first_line; first_column = elem->first_column; } if ((first_line == elem->first_line) && (first_column > elem->first_column)) { first_column = elem->first_column; } if (first_line > elem->first_line) { first_line = elem->first_line; first_column = elem->first_column; } if (NULL == last_file) { last_file = elem->last_file; last_line = elem->last_line; last_column = elem->last_column; } if ((last_line == elem->last_line) && (last_column < elem->last_column)) { last_column = elem->last_column; } if (last_line < elem->last_line) { last_line = elem->last_line; last_column = elem->last_column; } } /*********************************************/ /* insert a new element before position pos. */ /*********************************************/ /* To insert into the begining of list, call with pos=0 */ /* To insert into the end of list, call with pos=list->n */ void list_c::insert_element(symbol_c *elem, int pos) {insert_element(elem, elem, pos);} void list_c::insert_element(symbol_c *elem, symbol_c *token, int pos) { token_c *t = (token == NULL)? NULL : token->token; insert_element(elem, (t == NULL)? NULL : t->value, pos); } void list_c::insert_element(symbol_c *elem, const char *token_value, int pos) { if((pos<0) || (n<pos)) ERROR; /* add new element to end of list. Basically alocate required memory... */ /* will also increment n by 1 ! */ add_element(elem); /* if not inserting into end position, shift all elements up one position, to open up a slot in pos for new element */ if(pos < (n-1)){ for(int i=n-2 ; i>=pos ; --i) elements[i+1] = elements[i]; elements[pos].symbol = elem; elements[pos].token_value = token_value; } } /***********************************/ /* remove element at position pos. */ /***********************************/ void list_c::remove_element(int pos) { if((pos<0) || (n<=pos)) ERROR; /* Shift all elements down one position, starting at the entry to delete. */ for (int i = pos; i < n-1; i++) elements[i] = elements[i+1]; /* corrent the new size */ n--; /* elements = (symbol_c **)realloc(elements, n * sizeof(element_entry_t)); */ /* TODO: adjust the location parameters, taking into account the removed element. */ } /**********************************/ /* Remove all elements from list. */ /**********************************/ void list_c::clear(void) { n = 0; /* TODO: adjust the location parameters, taking into account the removed element. */ } #define SYM_LIST(class_name_c, ...) \ class_name_c::class_name_c( \ int fl, int fc, const char *ffile, long int forder, \ int ll, int lc, const char *lfile, long int lorder) \ :list_c(fl, fc, ffile, forder, ll, lc, lfile, lorder) {} \ class_name_c::class_name_c(symbol_c *elem, \ int fl, int fc, const char *ffile, long int forder, \ int ll, int lc, const char *lfile, long int lorder) \ :list_c(elem, fl, fc, ffile, forder, ll, lc, lfile, lorder) {} \ void *class_name_c::accept(visitor_c &visitor) {return visitor.visit(this);} #define SYM_TOKEN(class_name_c, ...) \ class_name_c::class_name_c(const char *value, \ int fl, int fc, const char *ffile, long int forder, \ int ll, int lc, const char *lfile, long int lorder) \ :token_c(value, fl, fc, ffile, forder, ll, lc, lfile, lorder) {} \ void *class_name_c::accept(visitor_c &visitor) {return visitor.visit(this);} #define SYM_REF0(class_name_c, ...) \ class_name_c::class_name_c( \ int fl, int fc, const char *ffile, long int forder, \ int ll, int lc, const char *lfile, long int lorder) \ :symbol_c(fl, fc, ffile, forder, ll, lc, lfile, lorder) {} \ void *class_name_c::accept(visitor_c &visitor) {return visitor.visit(this);} #define SYM_REF1(class_name_c, ref1, ...) \ class_name_c::class_name_c(symbol_c *ref1, \ int fl, int fc, const char *ffile, long int forder, \ int ll, int lc, const char *lfile, long int lorder) \ :symbol_c(fl, fc, ffile, forder, ll, lc, lfile, lorder) { \ this->ref1 = ref1; \ if (NULL != ref1) ref1->parent = this; \ } \ void *class_name_c::accept(visitor_c &visitor) {return visitor.visit(this);} #define SYM_REF2(class_name_c, ref1, ref2, ...) \ class_name_c::class_name_c(symbol_c *ref1, \ symbol_c *ref2, \ int fl, int fc, const char *ffile, long int forder, \ int ll, int lc, const char *lfile, long int lorder) \ :symbol_c(fl, fc, ffile, forder, ll, lc, lfile, lorder) { \ this->ref1 = ref1; \ this->ref2 = ref2; \ if (NULL != ref1) ref1->parent = this; \ if (NULL != ref2) ref2->parent = this; \ } \ void *class_name_c::accept(visitor_c &visitor) {return visitor.visit(this);} #define SYM_REF3(class_name_c, ref1, ref2, ref3, ...) \ class_name_c::class_name_c(symbol_c *ref1, \ symbol_c *ref2, \ symbol_c *ref3, \ int fl, int fc, const char *ffile, long int forder, \ int ll, int lc, const char *lfile, long int lorder) \ :symbol_c(fl, fc, ffile, forder, ll, lc, lfile, lorder) { \ this->ref1 = ref1; \ this->ref2 = ref2; \ this->ref3 = ref3; \ if (NULL != ref1) ref1->parent = this; \ if (NULL != ref2) ref2->parent = this; \ if (NULL != ref3) ref3->parent = this; \ } \ void *class_name_c::accept(visitor_c &visitor) {return visitor.visit(this);} #define SYM_REF4(class_name_c, ref1, ref2, ref3, ref4, ...) \ class_name_c::class_name_c(symbol_c *ref1, \ symbol_c *ref2, \ symbol_c *ref3, \ symbol_c *ref4, \ int fl, int fc, const char *ffile, long int forder, \ int ll, int lc, const char *lfile, long int lorder) \ :symbol_c(fl, fc, ffile, forder, ll, lc, lfile, lorder) { \ this->ref1 = ref1; \ this->ref2 = ref2; \ this->ref3 = ref3; \ this->ref4 = ref4; \ if (NULL != ref1) ref1->parent = this; \ if (NULL != ref2) ref2->parent = this; \ if (NULL != ref3) ref3->parent = this; \ if (NULL != ref4) ref4->parent = this; \ } \ void *class_name_c::accept(visitor_c &visitor) {return visitor.visit(this);} #define SYM_REF5(class_name_c, ref1, ref2, ref3, ref4, ref5, ...) \ class_name_c::class_name_c(symbol_c *ref1, \ symbol_c *ref2, \ symbol_c *ref3, \ symbol_c *ref4, \ symbol_c *ref5, \ int fl, int fc, const char *ffile, long int forder, \ int ll, int lc, const char *lfile, long int lorder) \ :symbol_c(fl, fc, ffile, forder, ll, lc, lfile, lorder) { \ this->ref1 = ref1; \ this->ref2 = ref2; \ this->ref3 = ref3; \ this->ref4 = ref4; \ this->ref5 = ref5; \ if (NULL != ref1) ref1->parent = this; \ if (NULL != ref2) ref2->parent = this; \ if (NULL != ref3) ref3->parent = this; \ if (NULL != ref4) ref4->parent = this; \ if (NULL != ref5) ref5->parent = this; \ } \ void *class_name_c::accept(visitor_c &visitor) {return visitor.visit(this);} #define SYM_REF6(class_name_c, ref1, ref2, ref3, ref4, ref5, ref6, ...) \ class_name_c::class_name_c(symbol_c *ref1, \ symbol_c *ref2, \ symbol_c *ref3, \ symbol_c *ref4, \ symbol_c *ref5, \ symbol_c *ref6, \ int fl, int fc, const char *ffile, long int forder, \ int ll, int lc, const char *lfile, long int lorder) \ :symbol_c(fl, fc, ffile, forder, ll, lc, lfile, lorder) { \ this->ref1 = ref1; \ this->ref2 = ref2; \ this->ref3 = ref3; \ this->ref4 = ref4; \ this->ref5 = ref5; \ this->ref6 = ref6; \ if (NULL != ref1) ref1->parent = this; \ if (NULL != ref2) ref2->parent = this; \ if (NULL != ref3) ref3->parent = this; \ if (NULL != ref4) ref4->parent = this; \ if (NULL != ref5) ref5->parent = this; \ if (NULL != ref6) ref6->parent = this; \ } \ void *class_name_c::accept(visitor_c &visitor) {return visitor.visit(this);} #include "absyntax.def" #undef SYM_LIST #undef SYM_TOKEN #undef SYM_TOKEN #undef SYM_REF0 #undef SYM_REF1 #undef SYM_REF2 #undef SYM_REF3 #undef SYM_REF4 #undef SYM_REF5 #undef SYM_REF6
14,740
C++
.cc
327
40.021407
120
0.569774
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,646
create_enumtype_conversion_functions.cc
nucleron_matiec/stage1_2/create_enumtype_conversion_functions.cc
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2009-2012 Mario de Sousa (msousa@fe.up.pt) * Copyright (C) 2012 Manuele Conti (conti.ma@alice.it) * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ #include <sstream> #include "create_enumtype_conversion_functions.hh" /* set to 1 to see debug info during execution */ static const int debug = 0; /* * The create_enumtype_conversion_functions_c class generates ST source code! * This code is in actual fact datatype conversion functions between user defined * enumerated datatypes, and some basic datatypes. * * These conversion functions cannot be implemented the normal way (i.e. in the standard library) * since they convert from/to a datatype that is defined by the user. So, we generate these conversions * functions on the fly! * (to get an idea of what the generated code looks like, see the comments in create_enumtype_conversion_functions.cc) * * Currently, we support conversion between the user defined enumerated datatype and STRING, * SINT, INT, DINT, LINT, USINT, UINT, UDINT, ULINT (basically the ANY_INT) * * ST source code is generated when the method get_declaration() is called. since the * create_enumtype_conversion_functions_c inherits from the iterator visitor, this method may be * passed either the root of an abstract syntax tree, or sub-tree of the AST. * * This class will iterate through that AST, and for each enumerated type declaration, will * create the apropriate conversion functions. */ create_enumtype_conversion_functions_c *create_enumtype_conversion_functions_c::singleton = NULL; create_enumtype_conversion_functions_c:: create_enumtype_conversion_functions_c(symbol_c *ignore) {} create_enumtype_conversion_functions_c::~create_enumtype_conversion_functions_c(void) {} std::string &create_enumtype_conversion_functions_c::get_declaration(symbol_c *symbol) { if (NULL == singleton) singleton = new create_enumtype_conversion_functions_c(NULL); if (NULL == singleton) ERROR_MSG("Out of memory. Bailing out!\n"); singleton->text = ""; if (NULL != symbol) symbol->accept(*singleton); return singleton->text; } /* As the name of derived datatypes and POUs are still stored as identifiers in the respective datatype and POU declaration, */ /* only the indintifier_c visitor should be necessary! */ void *create_enumtype_conversion_functions_c::visit( identifier_c *symbol) {currentToken = symbol->value; return NULL;} void *create_enumtype_conversion_functions_c::visit( poutype_identifier_c *symbol) {ERROR; return NULL;} void *create_enumtype_conversion_functions_c::visit(derived_datatype_identifier_c *symbol) {ERROR; return NULL;} /**********************/ /* B 1.3 - Data types */ /**********************/ /********************************/ /* B 1.3.3 - Derived data types */ /********************************/ void *create_enumtype_conversion_functions_c::visit(enumerated_type_declaration_c *symbol) { std::string enumerateName; std::string functionName; std::list <std::string> enumerateValues; symbol->enumerated_type_name->accept(*this); enumerateName = currentToken; symbol->enumerated_spec_init->accept(*this); enumerateValues = currentTokenList; printStringToEnum (enumerateName, enumerateValues); printEnumToString (enumerateName, enumerateValues); for (size_t s = 8; s <= 64; s*= 2) { printIntegerToEnum (enumerateName, enumerateValues, true , s); printEnumToInteger (enumerateName, enumerateValues, true , s); printIntegerToEnum (enumerateName, enumerateValues, false, s); printEnumToInteger (enumerateName, enumerateValues, false, s); } if (debug) std::cout << text << std::endl; return NULL; } void *create_enumtype_conversion_functions_c::visit(enumerated_value_list_c *symbol) { list_c *list; currentTokenList.clear(); list = (list_c *)symbol; for (int i = 0; i < list->n; i++) { list->get_element(i)->accept(*this); currentTokenList.push_back(currentToken); } return NULL; } /* * getIntegerName function generate a integer data name from signed and size. */ std::string create_enumtype_conversion_functions_c::getIntegerName(bool isSigned, size_t size) { std::string integerType = ""; if (! isSigned) { integerType = "U"; } switch(size) { case 8 : integerType += "S"; break; case 16: break; case 32: integerType += "D"; break; case 64: integerType += "L"; break; default: break; } integerType +="INT"; return integerType; } /* * printStringToEnum function print conversion function from STRING to <ENUM>: * ST Output: * FUNCTION STRING_TO_<ENUM> : <ENUM> VAR_INPUT IN: STRING; END_VAR IF IN = '<ENUM.VALUE_1>' THEN STRING_TO_<ENUM> := <ENUM>#<ENUM.VALUE_1>; RETURN; END_IF; ... IF IN = '<ENUM.VALU_N>' THEN STRING_TO_<ENUM> := <ENUM>#<ENUM.VALUE_N>; RETURN; END_IF; ENO := FALSE; END_FUNCTION Note: if you change code below remember to update this comment. */ void create_enumtype_conversion_functions_c::printStringToEnum (std::string &enumerateName, std::list<std::string> &enumerateValues) { std::list <std::string>::const_iterator itr; std::string functionName; functionName = "STRING_TO_" + enumerateName; text += "FUNCTION " + functionName + " : " + enumerateName; text += "\nVAR_INPUT\nIN : STRING;\nEND_VAR\n"; for (itr = enumerateValues.begin(); itr != enumerateValues.end(); ++itr) { std::string value = *itr; text += "IF IN = '" + value + "' THEN\n"; text += " " + functionName + " := " + enumerateName + "#" + value + ";\n"; text += " RETURN;\n"; text += "END_IF;\n"; } text += "ENO := FALSE;\n"; text += "END_FUNCTION\n\n"; } /* * printEnumToString function print conversion function from <ENUM> to STRING: * ST Output: * FUNCTION <ENUM>_TO_STRING : STRING VAR_INPUT IN: <ENUM>; END_VAR IF IN = <ENUM>#<ENUM.VALUE_1> THEN <ENUM>_TO_STRING := '<ENUM>#<ENUM.VALUE_1>'; RETURN; END_IF; ... IF IN = <ENUM>#<ENUM.VALUE_N> THEN <ENUM>_TO_STRING := '<ENUM>#<ENUM.VALUE_N>'; RETURN; END_IF; ENO := FALSE; END_FUNCTION Note: if you change code below remember to update this comment. */ void create_enumtype_conversion_functions_c::printEnumToString (std::string &enumerateName, std::list<std::string> &enumerateValues) { std::list <std::string>::const_iterator itr; std::string functionName; functionName = enumerateName + "_TO_STRING"; text += "FUNCTION " + functionName + " : STRING"; text += "\nVAR_INPUT\nIN : " + enumerateName + ";\nEND_VAR\n"; for (itr = enumerateValues.begin(); itr != enumerateValues.end(); ++itr) { std::string value = *itr; text += "IF IN = " + enumerateName + "#" + value + " THEN\n"; text += " " + functionName + " := '" + enumerateName + "#" + value + "';\n"; text += " RETURN;\n"; text += "END_IF;\n"; } text += "ENO := FALSE;\n"; text += "END_FUNCTION\n\n"; } /* * printIntegerToEnum function print conversion function from <INTEGER> to <ENUM>: * ST Output: * FUNCTION <INTEGER>_TO_<ENUM> : <ENUM> VAR_INPUT IN: <INTEGER>; END_VAR IF IN = 1 THEN <INTEGER>_TO_<ENUM> := <ENUM>#<ENUM.VALUE_1>; RETURN; END_IF; ... IF IN = N THEN <INTEGER>_TO_<ENUM> := <ENUM>#<ENUM.VALUE_N>; RETURN; END_IF; ENO := FALSE; END_FUNCTION Note: if you change code below remember to update this comment. */ void create_enumtype_conversion_functions_c::printIntegerToEnum (std::string &enumerateName, std::list<std::string> &enumerateValues, bool isSigned, size_t size) { std::list <std::string>::const_iterator itr; std::string functionName; std::string integerType; int count; integerType = getIntegerName(isSigned, size); functionName = integerType + "_TO_" + enumerateName; text += "FUNCTION " + functionName + " : " + enumerateName; text += "\nVAR_INPUT\nIN : " + integerType + ";\nEND_VAR\n"; count = 0; for (itr = enumerateValues.begin(); itr != enumerateValues.end(); ++itr) { std::string value = *itr; std::stringstream out; out << count; text += "IF IN = " + out.str() + " THEN\n"; text += " " + functionName + " := " + enumerateName + "#" + value + ";\n"; text += " RETURN;\n"; text += "END_IF;\n"; count++; } text += "ENO := FALSE;\n"; text += "END_FUNCTION\n\n"; } /* * printEnumToInteger function print conversion function from <ENUM> to <INTEGER>: * ST Output: * FUNCTION <ENUM>_TO_<INTEGER> : <INTEGER> VAR_INPUT IN: <INTEGER>; END_VAR IF IN = <ENUM>#<ENUM.VALUE_1> THEN <ENUM>_TO_<INTEGER> := 1; RETURN; END_IF; ... IF IN = <ENUM>#<ENUM.VALUE_N> THEN <ENUM>_TO_<INTEGER> := N; RETURN; END_IF; ENO := FALSE; END_FUNCTION Note: if you change code below remember to update this comment. */ void create_enumtype_conversion_functions_c::printEnumToInteger (std::string &enumerateName, std::list<std::string> &enumerateValues, bool isSigned, size_t size) { std::list <std::string>::const_iterator itr; std::string functionName; std::string integerType; int count; integerType = getIntegerName(isSigned, size); functionName = enumerateName + "_TO_" + integerType; text += "FUNCTION " + functionName + " : " + integerType; text += "\nVAR_INPUT\nIN : " + enumerateName + ";\nEND_VAR\n"; count = 0; for (itr = enumerateValues.begin(); itr != enumerateValues.end(); ++itr) { std::string value = *itr; std::stringstream out; out << count; text += "IF IN = " + enumerateName + "#" + value + " THEN\n"; text += " " + functionName + " := " + out.str() + ";\n"; text += " RETURN;\n"; text += "END_IF;\n"; count++; } text += "ENO := FALSE;\n"; text += "END_FUNCTION\n\n"; }
11,103
C++
.cc
286
34.86014
163
0.653664
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,648
remove_forward_dependencies.cc
nucleron_matiec/stage3/remove_forward_dependencies.cc
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2014 Mario de Sousa (msousa@fe.up.pt) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* * Re-oder the POUs in te library so that no forward references occur. * * Since stage1_2 now suppport POUs that contain references to POUS that are only declared later, * (e.g. a variable of FB1_t is declared, before the FB1_T function block is itself declared!) * we may need to re-order all the POUs in the library so that these forward references do not occur. * * This utility function will do just that. However, it does not destroy the original abstract syntax * tree (AST). It instead creates a new re-ordered AST, by instantiating a new library_c object. * This new library_c object will however point to the *same* objects of the original AST, just in * a new order. * This means that the new and original AST share all the object instances, and only use a distinct * library_c object! */ #include "remove_forward_dependencies.hh" #include "../main.hh" // required for ERROR() and ERROR_MSG() macros. #include "../absyntax_utils/absyntax_utils.hh" #define FIRST_(symbol1, symbol2) (((symbol1)->first_order < (symbol2)->first_order) ? (symbol1) : (symbol2)) #define LAST_(symbol1, symbol2) (((symbol1)->last_order > (symbol2)->last_order) ? (symbol1) : (symbol2)) #define FIRST_(symbol1, symbol2) (((symbol1)->first_order < (symbol2)->first_order) ? (symbol1) : (symbol2)) #define LAST_(symbol1, symbol2) (((symbol1)->last_order > (symbol2)->last_order) ? (symbol1) : (symbol2)) #define STAGE3_ERROR(error_level, symbol1, symbol2, ...) { \ if (current_display_error_level >= error_level) { \ fprintf(stderr, "%s:%d-%d..%d-%d: error: ", \ FIRST_(symbol1,symbol2)->first_file, FIRST_(symbol1,symbol2)->first_line, FIRST_(symbol1,symbol2)->first_column,\ LAST_(symbol1,symbol2) ->last_line, LAST_(symbol1,symbol2) ->last_column);\ fprintf(stderr, __VA_ARGS__); \ fprintf(stderr, "\n"); \ error_count++; \ } \ } #define STAGE3_WARNING(symbol1, symbol2, ...) { \ fprintf(stderr, "%s:%d-%d..%d-%d: warning: ", \ FIRST_(symbol1,symbol2)->first_file, FIRST_(symbol1,symbol2)->first_line, FIRST_(symbol1,symbol2)->first_column,\ LAST_(symbol1,symbol2) ->last_line, LAST_(symbol1,symbol2) ->last_column);\ fprintf(stderr, __VA_ARGS__); \ fprintf(stderr, "\n"); \ warning_found = true; \ } /* NOTE: We create an independent visitor for this task instead of having this done by the remove_forward_dependencies_c * because we do not want to handle the ***_pragma_c classes while doing this search. * (remove_forward_dependencies_c needs to visit those classes when handling all the possible entries in * library_c, and must have those visitors) * * NOTE: * This class could have been written by visiting all the AST objects that could _reference_ a * - FB type * - Program type * - Function type * and by checking whether those references are in the declared_identifiers list. * However, one of those objects, the ref_spec_c, may reference an FB type, or any other datatype, so we must have a way * of knowing what is being referenced in this case. I have opted to introduce a new object type in the AST, the * poutype_identifier_c, that will be used anywhere in the AST that references either a PROGRAM name or a FB type name * or a FUNCTION name (previously a simple identifier_c was used!). * This means that we merely need to visit the new poutype_identifier_c object in this visitor. */ class find_forward_dependencies_c: public search_visitor_c { private: identifiers_symbtable_t *declared_identifiers; // list of identifiers already declared by the symbols in the new tree public: find_forward_dependencies_c(identifiers_symbtable_t *declared_identifiers_) {declared_identifiers = declared_identifiers_;} /*******************************************/ /* B 1.1 - Letters, digits and identifiers */ /*******************************************/ // return NULL if the symbol is already in the declared_identifiers symbol table, otherwise return the missing symbol! void *visit( poutype_identifier_c *symbol) {if (declared_identifiers->find(symbol) != declared_identifiers->end()) return NULL; else return symbol;} }; /* class find_forward_dependencies_c */ /* A class to count the number of POUs (Function, FBs Programs and Configurations) in a library. * This will be used to make sure whether we have copied all the POUs from the original AST (abstract * syntax tree) to the new AST. * Note that we can't simply use the number of 'elements' in the AST, as it may contain unknown/unsupported pragmas. */ class pou_count_c: public search_visitor_c { private: static pou_count_c *singleton; long long int count; public: static long long int get_count(library_c *library) { if (NULL == singleton) singleton = new pou_count_c; if (NULL == singleton) ERROR; singleton->count = 0; library->accept(*singleton); return singleton->count; } /**************************************/ /* B.1.5 - Program organization units */ /**************************************/ void *visit( function_declaration_c *symbol) {count++; return NULL;} void *visit(function_block_declaration_c *symbol) {count++; return NULL;} void *visit( program_declaration_c *symbol) {count++; return NULL;} void *visit( configuration_declaration_c *symbol) {count++; return NULL;} }; /* class pou_count_c */ pou_count_c *pou_count_c::singleton = NULL; symbol_c remove_forward_dependencies_c_null_symbol; /************************************************************/ /************************************************************/ /****** The main class: Remove Forward Depencies *******/ /************************************************************/ /************************************************************/ // constructor & destructor remove_forward_dependencies_c:: remove_forward_dependencies_c(void) { find_forward_dependencies = new find_forward_dependencies_c(&declared_identifiers); current_display_error_level = error_level_default; error_count = 0; } remove_forward_dependencies_c::~remove_forward_dependencies_c(void) { delete find_forward_dependencies; } int remove_forward_dependencies_c::get_error_count(void) { return error_count; } library_c *remove_forward_dependencies_c::create_new_tree(symbol_c *tree) { library_c *old_tree = dynamic_cast<library_c *>(tree); if (NULL == old_tree) ERROR; new_tree = new library_c; *((symbol_c *)new_tree) = *((symbol_c *)tree); // copy any annotations from tree to new_tree; new_tree->clear(); // remove all elements from list. tree->accept(*this); return new_tree; } void *remove_forward_dependencies_c::handle_library_symbol(symbol_c *symbol, symbol_c *name, symbol_c *search1, symbol_c *search2, symbol_c *search3) { if (inserted_symbols.find(symbol) != inserted_symbols.end()) return NULL; // already previously inserted into new_tree and declared_identifiers. Do not handle again! if ((search1 != NULL) && (search1->accept(*find_forward_dependencies) != NULL)) return NULL; // A forward depency has not yet been satisfied. Wait for a later iteration to try again! if ((search2 != NULL) && (search2->accept(*find_forward_dependencies) != NULL)) return NULL; // A forward depency has not yet been satisfied. Wait for a later iteration to try again! if ((search3 != NULL) && (search3->accept(*find_forward_dependencies) != NULL)) return NULL; // A forward depency has not yet been satisfied. Wait for a later iteration to try again! /* no forward dependencies found => insert into new AST, and add to the 'defined identifiers' and 'inserted symbol' lists */ if (declared_identifiers.find(name) == declared_identifiers.end()) declared_identifiers.insert(name, NULL); // only add if not yet in the symbol table (an overloaded version of this same POU could have been inderted previously!) inserted_symbols.insert(symbol); new_tree->add_element(current_code_generation_pragma); new_tree->add_element(symbol); return NULL; } /* Tell the user that the source code contains a circular dependency */ void remove_forward_dependencies_c::print_circ_error(library_c *symbol) { /* Note that we only print Functions and FBs, as Programs and Configurations cannot contain circular references due to syntax rules */ /* Note too that circular references in derived datatypes is also not possible due to sytax! */ int initial_error_count = error_count; for (int i = 0; i < symbol->n; i++) if ( (inserted_symbols.find(symbol->get_element(i)) == inserted_symbols.end()) // if not copied to new AST &&( (NULL != dynamic_cast <function_block_declaration_c *>(symbol->get_element(i))) // and (is a FB ||(NULL != dynamic_cast < function_declaration_c *>(symbol->get_element(i))))) // or a Function) STAGE3_ERROR(0, symbol->get_element(i), symbol->get_element(i), "POU (%s) contains a self-reference and/or belongs in a circular referencing loop", get_datatype_info_c::get_id_str(symbol->get_element(i))); if (error_count == initial_error_count) ERROR; // We were unable to determine which POUs contain the circular references!! } /***************************/ /* B 0 - Programming Model */ /***************************/ /* enumvalue_symtable is filled in by enum_declaration_check_c, during stage3 semantic verification, with a list of all enumerated constants declared inside this POU */ // SYM_LIST(library_c, enumvalue_symtable_t enumvalue_symtable;) void *remove_forward_dependencies_c::visit(library_c *symbol) { /* this method is the expected entry point for this visitor, and implements the main algorithm of the visitor */ /* first insert all the derived datatype declarations, in the same order by which they are delcared in the original AST */ /* Since IEC 61131-3 does not allow FBs in arrays or structures, it is actually safe to place all the datatypes before all the POUs! */ for (int i = 0; i < symbol->n; i++) if (NULL != dynamic_cast <data_type_declaration_c *>(symbol->get_element(i))) new_tree->add_element(symbol->get_element(i)); /* now do the POUs, in whatever order is necessary to guarantee no forward references. */ long long int old_tree_pou_count = pou_count_c::get_count(symbol); // if no code generation pragma exists before the first entry in the library, the default is to enable code generation. enable_code_generation_pragma_c *default_code_generation_pragma = new enable_code_generation_pragma_c; int prev_n; cycle_count = 0; do { cycle_count++; prev_n = new_tree->n; current_code_generation_pragma = default_code_generation_pragma; for (int i = 0; i < symbol->n; i++) symbol->get_element(i)->accept(*this); } while (prev_n != new_tree->n); // repeat while new elementns are still being added to the new AST if (old_tree_pou_count != pou_count_c::get_count(new_tree)) print_circ_error(symbol); return NULL; } /**************************************/ /* B.1.5 - Program organization units */ /**************************************/ /***********************/ /* B 1.5.1 - Functions */ /***********************/ // SYM_REF4(function_declaration_c, derived_function_name, type_name, var_declarations_list, function_body, enumvalue_symtable_t enumvalue_symtable;) void *remove_forward_dependencies_c::visit(function_declaration_c *symbol) {return handle_library_symbol(symbol, symbol->derived_function_name, symbol->type_name, symbol->var_declarations_list, symbol->function_body);} /*****************************/ /* B 1.5.2 - Function Blocks */ /*****************************/ /* FUNCTION_BLOCK derived_function_block_name io_OR_other_var_declarations function_block_body END_FUNCTION_BLOCK */ // SYM_REF3(function_block_declaration_c, fblock_name, var_declarations, fblock_body, enumvalue_symtable_t enumvalue_symtable;) void *remove_forward_dependencies_c::visit(function_block_declaration_c *symbol) {return handle_library_symbol(symbol, symbol->fblock_name, symbol->var_declarations, symbol->fblock_body);} /**********************/ /* B 1.5.3 - Programs */ /**********************/ /* PROGRAM program_type_name program_var_declarations_list function_block_body END_PROGRAM */ // SYM_REF3(program_declaration_c, program_type_name, var_declarations, function_block_body, enumvalue_symtable_t enumvalue_symtable;) void *remove_forward_dependencies_c::visit(program_declaration_c *symbol) {return handle_library_symbol(symbol, symbol->program_type_name, symbol->var_declarations, symbol->function_block_body);} /********************************/ /* B 1.7 Configuration elements */ /********************************/ /* CONFIGURATION configuration_name (...) END_CONFIGURATION */ // SYM_REF5(configuration_declaration_c, configuration_name, global_var_declarations, resource_declarations, access_declarations, instance_specific_initializations, enumvalue_symtable_t enumvalue_symtable;) void *remove_forward_dependencies_c::visit(configuration_declaration_c *symbol) {return handle_library_symbol(symbol, symbol->configuration_name, symbol->global_var_declarations, symbol->resource_declarations, symbol->access_declarations);} /********************/ /* 2.1.6 - Pragmas */ /********************/ void *remove_forward_dependencies_c::visit(disable_code_generation_pragma_c *symbol) {current_code_generation_pragma = symbol; return NULL;} void *remove_forward_dependencies_c::visit( enable_code_generation_pragma_c *symbol) {current_code_generation_pragma = symbol; return NULL;} /* I have no ideia what this pragma is. Where should we place it in the re-ordered tree? * Without knowing the semantics of the pragma, it is not possible to hande it correctly. * We therefore print out an error message, and abort! */ // TODO: print error message! void *remove_forward_dependencies_c::visit(pragma_c *symbol) { if (1 != cycle_count) return NULL; // only handle unknown pragmas in the first cycle! STAGE3_WARNING(symbol, symbol, "Unrecognized pragma. Including the pragma when using the '-p' command line option for 'allow use of forward references' may result in unwanted behaviour."); new_tree->add_element(symbol); return NULL; }
16,651
C++
.cc
249
63.53012
211
0.634823
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,651
flow_control_analysis.cc
nucleron_matiec/stage3/flow_control_analysis.cc
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2012 Mario de Sousa (msousa@fe.up.pt) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* * Do flow control analysis of the IEC 61131-3 code. * * We currently only do this for IL code. * This class will annotate the abstract syntax tree, by filling in the * prev_il_instruction variable in the il_instruction_c, so it points to * the previous il_instruction_c object in the instruction list instruction_list_c. * * Since IL code can contain jumps (JMP), the same il_instruction may effectively have * several previous il_instructions. In order to accommodate this, each il_instruction * will maintain a vector (i..e an array) of pointers to all the previous il_instructions. * We do however attempt to guarantee that the first element in the vector (array) will preferentially * point to the il instruction that is right before / imediately preceding the current il instructions, * i.e. the first element in the array will tend to point to the previous il_instruction * that is not a jump JMP IL instruction! * * The result will essentially be a graph of il_instruction_c objects, each * pointing to the previous il_instruction_c object. * * The reality is we will get several independent and isolated linked lists * (actually, since we now process labels correctly, this is really a graph): * one for each block of IL code (e.g. inside a Function, FB or Program). * Additionally, when the IL code has an expression (expression_c object), we will actually * have one more isolated linked list for the IL code inside that expression. * * e.g. * line_1: LD 1 * line_2: ADD (42 * line_3: ADD B * line_4: ADD C * line_5: ) * line_6: ADD D * line_7: ST E * * will result in two independent linked lists: * main list: line_7 -> line_6 -> line2 -> line_1 * expr list: lin4_4 -> line_3 -> (operand of line_2, i.e. '42') * * * In the main list, each: * line_x: IL_operation IL_operand * is encoded as * il_instruction_c(label, il_incomplete_instruction) * these il_instruction_c objects will point back to the previous il_instruction_c object. * * In the expr list, each * line_x: IL_operation IL_operand * is encoded as * il_simple_instruction_c(il_simple_instruction) * these il_simple_instruction_c objects will point back to the previous il_simple_instruction_c object, * except the for the first il_simple_instruction_c object in the list, which will point back to * the first il_operand (in the above example, '42'), or NULL is it does not exist. * * * label: * identifier_c * * il_incomplete_instruction: * il_simple_operation (il_simple_operation_c, il_function_call_c) * | il_expression (il_expression_c) * | il_jump_operation (il_jump_operation_c) * | il_fb_call (il_fb_call_c) * | il_formal_funct_call (il_formal_funct_call_c) * | il_return_operator (RET_operator_c, RETC_operator_c, RETCN_operator_c) * * * il_expression_c(il_expr_operator, il_operand, simple_instr_list) * * il_operand: * variable (symbolic_variable_c, direct_variable_c, array_variable_c, structured_variable_c) * | enumerated_value (enumerated_value_c) * | constant (lots of literal classes _c) * * simple_instr_list: * list of il_simple_instruction * * il_simple_instruction: * il_simple_operation (il_simple_operation_c, il_function_call_c) * | il_expression (il_expression_c) * | il_formal_funct_call (il_formal_funct_call_c) * */ #include "flow_control_analysis.hh" /* set to 1 to see debug info during execution */ static int debug = 0; flow_control_analysis_c::flow_control_analysis_c(symbol_c *ignore) { prev_il_instruction = NULL; curr_il_instruction = NULL; prev_il_instruction_is_JMP_or_RET = false; search_il_label = NULL; } flow_control_analysis_c::~flow_control_analysis_c(void) { } void flow_control_analysis_c::link_insert(symbol_c *prev_instruction, symbol_c *next_instruction) { il_instruction_c *next_a = dynamic_cast<il_instruction_c *>(next_instruction); il_instruction_c *prev_a = dynamic_cast<il_instruction_c *>(prev_instruction); il_simple_instruction_c *next_b = dynamic_cast<il_simple_instruction_c *>(next_instruction); il_simple_instruction_c *prev_b = dynamic_cast<il_simple_instruction_c *>(prev_instruction); if (NULL != next_a) next_a->prev_il_instruction.insert(next_a->prev_il_instruction.begin(), prev_instruction); else if (NULL != next_b) next_b->prev_il_instruction.insert(next_b->prev_il_instruction.begin(), prev_instruction); else ERROR; if (NULL != prev_a) prev_a->next_il_instruction.insert(prev_a->next_il_instruction.begin(), next_instruction); else if (NULL != prev_b) prev_b->next_il_instruction.insert(prev_b->next_il_instruction.begin(), next_instruction); else ERROR; } void flow_control_analysis_c::link_pushback(symbol_c *prev_instruction, symbol_c *next_instruction) { il_instruction_c *next = dynamic_cast<il_instruction_c *>(next_instruction); il_instruction_c *prev = dynamic_cast<il_instruction_c *>(prev_instruction); if ((NULL == next) || (NULL == prev)) ERROR; next->prev_il_instruction.push_back(prev); prev->next_il_instruction.push_back(next); } /************************************/ /* B 1.5 Program organization units */ /************************************/ /*********************/ /* B 1.5.1 Functions */ /*********************/ void *flow_control_analysis_c::visit(function_declaration_c *symbol) { search_il_label = new search_il_label_c(symbol); if (debug) printf("Doing flow control analysis in body of function %s\n", ((token_c *)(symbol->derived_function_name))->value); symbol->function_body->accept(*this); delete search_il_label; search_il_label = NULL; return NULL; } /***************************/ /* B 1.5.2 Function blocks */ /***************************/ void *flow_control_analysis_c::visit(function_block_declaration_c *symbol) { search_il_label = new search_il_label_c(symbol); if (debug) printf("Doing flow control analysis in body of FB %s\n", ((token_c *)(symbol->fblock_name))->value); symbol->fblock_body->accept(*this); delete search_il_label; search_il_label = NULL; return NULL; } /********************/ /* B 1.5.3 Programs */ /********************/ void *flow_control_analysis_c::visit(program_declaration_c *symbol) { search_il_label = new search_il_label_c(symbol); if (debug) printf("Doing flow control analysis in body of program %s\n", ((token_c *)(symbol->program_type_name))->value); symbol->function_block_body->accept(*this); delete search_il_label; search_il_label = NULL; return NULL; } /********************************/ /* B 1.7 Configuration elements */ /********************************/ void *flow_control_analysis_c::visit(configuration_declaration_c *symbol) { return NULL; } /****************************************/ /* B.2 - Language IL (Instruction List) */ /****************************************/ /***********************************/ /* B 2.1 Instructions and Operands */ /***********************************/ /*| instruction_list il_instruction */ // SYM_LIST(instruction_list_c) void *flow_control_analysis_c::visit(instruction_list_c *symbol) { prev_il_instruction_is_JMP_or_RET = false; for(int i = 0; i < symbol->n; i++) { prev_il_instruction = NULL; if (i > 0) prev_il_instruction = symbol->get_element(i-1); curr_il_instruction = symbol->get_element(i); curr_il_instruction->accept(*this); curr_il_instruction = NULL; } return NULL; } /* | label ':' [il_incomplete_instruction] eol_list */ // SYM_REF2(il_instruction_c, label, il_instruction) // void *visit(instruction_list_c *symbol); void *flow_control_analysis_c::visit(il_instruction_c *symbol) { if ((NULL != prev_il_instruction) && (!prev_il_instruction_is_JMP_or_RET)) /* We try to guarantee that the previous il instruction that is in the previous line, will occupy the first element of the vector. * In order to do that, we use insert() instead of push_back() */ link_insert(prev_il_instruction, symbol); /* check if it is an il_expression_c, a JMP[C[N]], or a RET, and if so, handle it correctly */ prev_il_instruction_is_JMP_or_RET = false; if (NULL != symbol->il_instruction) symbol->il_instruction->accept(*this); return NULL; } /* | il_simple_operator [il_operand] */ // SYM_REF2(il_simple_operation_c, il_simple_operator, il_operand) // void *flow_control_analysis_c::visit(il_simple_operation_c *symbol) /* | function_name [il_operand_list] */ /* NOTE: The parameters 'called_function_declaration' and 'extensible_param_count' are used to pass data between the stage 3 and stage 4. */ // SYM_REF2(il_function_call_c, function_name, il_operand_list, symbol_c *called_function_declaration; int extensible_param_count;) // void *flow_control_analysis_c::visit(il_function_call_c *symbol) /* | il_expr_operator '(' [il_operand] eol_list [simple_instr_list] ')' */ // SYM_REF3(il_expression_c, il_expr_operator, il_operand, simple_instr_list); void *flow_control_analysis_c::visit(il_expression_c *symbol) { if(NULL == symbol->simple_instr_list) /* nothing to do... */ return NULL; symbol_c *save_prev_il_instruction = prev_il_instruction; /* Stage2 will insert an artificial (and equivalent) LD <il_operand> to the simple_instr_list if necessary. We can therefore ignore the 'il_operand' entry! */ // prev_il_instruction = symbol->il_operand; prev_il_instruction = NULL; symbol->simple_instr_list->accept(*this); prev_il_instruction = save_prev_il_instruction; return NULL; } /* il_jump_operator label */ // SYM_REF2(il_jump_operation_c, il_jump_operator, label) void *flow_control_analysis_c::visit(il_jump_operation_c *symbol) { /* search for the il_instruction_c containing the label */ il_instruction_c *destination = search_il_label->find_label(symbol->label); /* give the visit(JMP_operator *) an oportunity to set the prev_il_instruction_is_JMP_or_RET flag! */ symbol->il_jump_operator->accept(*this); if (NULL != destination) link_pushback(curr_il_instruction, destination); return NULL; } /* il_call_operator prev_declared_fb_name * | il_call_operator prev_declared_fb_name '(' ')' * | il_call_operator prev_declared_fb_name '(' eol_list ')' * | il_call_operator prev_declared_fb_name '(' il_operand_list ')' * | il_call_operator prev_declared_fb_name '(' eol_list il_param_list ')' */ /* NOTE: The parameter 'called_fb_declaration'is used to pass data between stage 3 and stage4 (although currently it is not used in stage 4 */ // SYM_REF4(il_fb_call_c, il_call_operator, fb_name, il_operand_list, il_param_list, symbol_c *called_fb_declaration) // void *flow_control_analysis_c::visit(il_fb_call_c *symbol) /* | function_name '(' eol_list [il_param_list] ')' */ /* NOTE: The parameter 'called_function_declaration' is used to pass data between the stage 3 and stage 4. */ // SYM_REF2(il_formal_funct_call_c, function_name, il_param_list, symbol_c *called_function_declaration; int extensible_param_count;) // void *flow_control_analysis_c::visit(il_formal_funct_call_c *symbol) // void *visit(il_operand_list_c *symbol); void *flow_control_analysis_c::visit(simple_instr_list_c *symbol) { for(int i = 0; i < symbol->n; i++) { /* The prev_il_instruction for element[0] was set in visit(il_expression_c *) */ if (i>0) prev_il_instruction = symbol->get_element(i-1); symbol->get_element(i)->accept(*this); } return NULL; } // SYM_REF1(il_simple_instruction_c, il_simple_instruction, symbol_c *prev_il_instruction;) void *flow_control_analysis_c::visit(il_simple_instruction_c*symbol) { if (NULL != prev_il_instruction) /* We try to guarantee that the previous il instruction that is in the previous line, will occupy the first element of the vector. * In order to do that, we use insert() instead of push_back() */ link_insert(prev_il_instruction, symbol); return NULL; } /* void *visit(il_param_list_c *symbol); void *visit(il_param_assignment_c *symbol); void *visit(il_param_out_assignment_c *symbol); */ /*******************/ /* B 2.2 Operators */ /*******************/ // void *visit( LD_operator_c *symbol); // void *visit( LDN_operator_c *symbol); // void *visit( ST_operator_c *symbol); // void *visit( STN_operator_c *symbol); // void *visit( NOT_operator_c *symbol); // void *visit( S_operator_c *symbol); // void *visit( R_operator_c *symbol); // void *visit( S1_operator_c *symbol); // void *visit( R1_operator_c *symbol); // void *visit( CLK_operator_c *symbol); // void *visit( CU_operator_c *symbol); // void *visit( CD_operator_c *symbol); // void *visit( PV_operator_c *symbol); // void *visit( IN_operator_c *symbol); // void *visit( PT_operator_c *symbol); // void *visit( AND_operator_c *symbol); // void *visit( OR_operator_c *symbol); // void *visit( XOR_operator_c *symbol); // void *visit( ANDN_operator_c *symbol); // void *visit( ORN_operator_c *symbol); // void *visit( XORN_operator_c *symbol); // void *visit( ADD_operator_c *symbol); // void *visit( SUB_operator_c *symbol); // void *visit( MUL_operator_c *symbol); // void *visit( DIV_operator_c *symbol); // void *visit( MOD_operator_c *symbol); // void *visit( GT_operator_c *symbol); // void *visit( GE_operator_c *symbol); // void *visit( EQ_operator_c *symbol); // void *visit( LT_operator_c *symbol); // void *visit( LE_operator_c *symbol); // void *visit( NE_operator_c *symbol); // void *visit( CAL_operator_c *symbol); // void *visit( CALC_operator_c *symbol); // void *visit(CALCN_operator_c *symbol); /* this next visit function will be called directly from visit(il_instruction_c *) */ void *flow_control_analysis_c::visit( RET_operator_c *symbol) { prev_il_instruction_is_JMP_or_RET = true; return NULL; } // void *visit( RETC_operator_c *symbol); // void *visit(RETCN_operator_c *symbol); /* this next visit function will be called from visit(il_jump_operation_c *) */ void *flow_control_analysis_c::visit( JMP_operator_c *symbol) { prev_il_instruction_is_JMP_or_RET = true; return NULL; } // void *visit( JMPC_operator_c *symbol); // void *visit(JMPCN_operator_c *symbol); /* Symbol class handled together with function call checks */ // void *visit(il_assign_operator_c *symbol, variable_name); /* Symbol class handled together with function call checks */ // void *visit(il_assign_operator_c *symbol, option, variable_name);
15,671
C++
.cc
341
43.929619
159
0.680576
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,652
forced_narrow_candidate_datatypes.cc
nucleron_matiec/stage3/forced_narrow_candidate_datatypes.cc
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2012 Mario de Sousa (msousa@fe.up.pt) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* * Data type analysis of IL code may leave some IL instructions with an undefined datatype. * This visitor will set the datatype for all these symbols, so that all symbols have a well * defined datatype when we reach stage4. * * Example: * ========= * * VAR * N : INT := 99 ; * tonv: TON; * byte_var: BYTE; * tonv : TON; * a : BYTE; * t : time; * tod1: tod; * END_VAR * * (0) --> Data type before executing forced_narrow_candidate_datatypes_c * (1) --> Data type after executing 1st pass of forced_narrow_candidate_datatypes_c * (2) --> Data type after executing 2nd pass of forced_narrow_candidate_datatypes_c * * --- --> NULL (undefined datatype) * *** --> invalid_type_name_c (invalid datatype) * * (0) PASS1 (1) PASS2 (2) * * --- (e) *** *** CAL tonv ( * PT := T#1s * ) * --- (e) *** *** JMP l4 * * --- (e) sint sint l0: LD 1 * --- (e) sint sint ADD 2 * --- (c) sint sint CAL tonv ( * PT := T#1s * ) * * --- (e) sint sint LD 45 * --- (c) sint sint ADD 45 * * * --- (e) sint sint LD 3 * --- (e) sint sint l1: * --- (c) sint sint l2: ADD 4 * int int int LD 5 * int int int ST n * int int int JMP l3 * * --- (d) --- (e) sint LD 5 * --- (d) --- (e) sint SUB 6 * --- (d)(e) sint sint JMP l1 * * --- (e) bool bool LD FALSE * --- (e) bool bool NOT * --- (b) bool bool RET * * int int int l3: * int int int ST n * --- (b) int int RET * * --- (e) *** *** l4: * --- (e) *** *** CAL tonv ( * PT := T#1s * ) * --- (a) *** *** JMP l0 * --- (b) byte byte LD 88 * * * */ #include "forced_narrow_candidate_datatypes.hh" #include "datatype_functions.hh" /* set to 1 to see debug info during execution */ static int debug = 0; forced_narrow_candidate_datatypes_c::forced_narrow_candidate_datatypes_c(symbol_c *ignore) :narrow_candidate_datatypes_c(ignore) { } forced_narrow_candidate_datatypes_c::~forced_narrow_candidate_datatypes_c(void) { } void forced_narrow_candidate_datatypes_c::set_datatype_in_prev_il_instructions(symbol_c *datatype, il_instruction_c *symbol) { if (NULL == symbol) ERROR; /* In the forced_narrow_candidate_datatypes algorithm, we do NOT set any datatypes to invalid_type_name_c * Any IL instructions that really are of an invalid_type_name_c (because the IL code is buggy?) have already * been set by the standard narrow_candidate_datatypes algorithm. * * Remember too that valid IL code may also have some IL instructions correctly set to invalid_type_name_c, especially * in cases where the data in the accumulator will not be used in the current IL instruction * For example: * LD bool_var * JMPC label1 * LD 34 * ST int_var * lable1: <---- This IL instruction_c (with NULL symbol->il_instruction) has invalid_type_name_c datatype!! * LD T#3s And yet, the code is legal!!! * ST time_var */ if (!get_datatype_info_c::is_type_valid(datatype)) return; // Call the 'original' version of the set_datatype_in_prev_il_instructions() function, from narrow_candidate_datatypes_c return narrow_candidate_datatypes_c::set_datatype_in_prev_il_instructions(datatype, symbol); } void forced_narrow_candidate_datatypes_c::forced_narrow_il_instruction(symbol_c *symbol, std::vector <symbol_c *> &next_il_instruction) { if (NULL == symbol->datatype) { if (symbol->candidate_datatypes.empty()) { symbol->datatype = &(get_datatype_info_c::invalid_type_name); // This will occur in the situations (a) in the above example // return NULL; // No need to return control to the visit() method of the base class... But we do so, just to be safe (called at the end of this function)! } else { if (next_il_instruction.empty()) { symbol->datatype = symbol->candidate_datatypes[0]; // This will occur in the situations (b) in the above example } else { symbol_c *next_datatype = NULL; /* find the datatype of the following IL instructions (they should all be identical by now, but we don't have an assertion checking for this. */ for (unsigned int i=0; i < next_il_instruction.size(); i++) if (NULL != next_il_instruction[i]->datatype) next_datatype = next_il_instruction[i]->datatype; if (get_datatype_info_c::is_type_valid(next_datatype)) { // This will occur in the situations (c) in the above example symbol->datatype = symbol->candidate_datatypes[0]; } else { // This will occur in the situations (d) in the above example // it is not possible to determine the exact situation in the current pass, so we can't do anything just yet. Leave it for the next time around! } } } } } /****************************************/ /* B.2 - Language IL (Instruction List) */ /****************************************/ /***********************************/ /* B 2.1 Instructions and Operands */ /***********************************/ /*| instruction_list il_instruction */ // SYM_LIST(instruction_list_c) void *forced_narrow_candidate_datatypes_c::visit(instruction_list_c *symbol) { for(int j = 0; j < 2; j++) { for(int i = symbol->n-1; i >= 0; i--) { symbol->get_element(i)->accept(*this); } } /* Assert that this algorithm managed to remove all NULL datatypes! */ /* NOTE: The forced_narrow_candidate_datatypes_c assumes that the original IEC 61131-3 source code does not have any bugs! * This means we cannot run this assertion here, as the compiler will bork in the presence of bug in the code being compiled! Not good!! */ /* for(int i = symbol->n-1; i >= 0; i--) { if (NULL == symbol->get_element(i)->datatype) ERROR; } */ return NULL; } /* | label ':' [il_incomplete_instruction] eol_list */ // SYM_REF2(il_instruction_c, label, il_instruction) // void *visit(instruction_list_c *symbol); void *forced_narrow_candidate_datatypes_c::visit(il_instruction_c *symbol) { forced_narrow_il_instruction(symbol, symbol->next_il_instruction); /* return control to the visit() method of the base class! */ return narrow_candidate_datatypes_c::visit(symbol); // This handles the situations (e) in the above example } /* | il_simple_operator [il_operand] */ // SYM_REF2(il_simple_operation_c, il_simple_operator, il_operand) // void *forced_narrow_candidate_datatypes_c::visit(il_simple_operation_c *symbol) /* | function_name [il_operand_list] */ /* NOTE: The parameters 'called_function_declaration' and 'extensible_param_count' are used to pass data between the stage 3 and stage 4. */ // SYM_REF2(il_function_call_c, function_name, il_operand_list, symbol_c *called_function_declaration; int extensible_param_count;) // void *forced_narrow_candidate_datatypes_c::visit(il_function_call_c *symbol) /* | il_expr_operator '(' [il_operand] eol_list [simple_instr_list] ')' */ // SYM_REF3(il_expression_c, il_expr_operator, il_operand, simple_instr_list); // void *forced_narrow_candidate_datatypes_c::visit(il_expression_c *symbol) /* il_jump_operator label */ // SYM_REF2(il_jump_operation_c, il_jump_operator, label) // void *forced_narrow_candidate_datatypes_c::visit(il_jump_operation_c *symbol) /* il_call_operator prev_declared_fb_name * | il_call_operator prev_declared_fb_name '(' ')' * | il_call_operator prev_declared_fb_name '(' eol_list ')' * | il_call_operator prev_declared_fb_name '(' il_operand_list ')' * | il_call_operator prev_declared_fb_name '(' eol_list il_param_list ')' */ /* NOTE: The parameter 'called_fb_declaration'is used to pass data between stage 3 and stage4 (although currently it is not used in stage 4 */ // SYM_REF4(il_fb_call_c, il_call_operator, fb_name, il_operand_list, il_param_list, symbol_c *called_fb_declaration) // void *forced_narrow_candidate_datatypes_c::visit(il_fb_call_c *symbol) /* | function_name '(' eol_list [il_param_list] ')' */ /* NOTE: The parameter 'called_function_declaration' is used to pass data between the stage 3 and stage 4. */ // SYM_REF2(il_formal_funct_call_c, function_name, il_param_list, symbol_c *called_function_declaration; int extensible_param_count;) // void *forced_narrow_candidate_datatypes_c::visit(il_formal_funct_call_c *symbol) // void *visit(il_operand_list_c *symbol); // void *forced_narrow_candidate_datatypes_c::visit(simple_instr_list_c *symbol) // SYM_REF1(il_simple_instruction_c, il_simple_instruction, symbol_c *prev_il_instruction;) void *forced_narrow_candidate_datatypes_c::visit(il_simple_instruction_c*symbol) { forced_narrow_il_instruction(symbol, symbol->next_il_instruction); /* return control to the visit() method of the base class! */ return narrow_candidate_datatypes_c::visit(symbol); // This handle the situations (e) in the above example } /* void *visit(il_param_list_c *symbol); void *visit(il_param_assignment_c *symbol); void *visit(il_param_out_assignment_c *symbol); */ /***************************************/ /* B.3 - Language ST (Structured Text) */ /***************************************/ // SYM_LIST(statement_list_c) /* The normal narrow_candidate_datatypes_c algorithm does not leave any symbol, in an ST code, with an undefined datatype. * There is therefore no need to re-run the narrow algorithm here, so we overide the narrow_candidate_datatypes_c visitor, * and simply bug out! */ void *forced_narrow_candidate_datatypes_c::visit(statement_list_c *symbol) {return NULL;}
12,538
C++
.cc
237
45.312236
161
0.562423
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,657
case_element_iterator.cc
nucleron_matiec/absyntax_utils/case_element_iterator.cc
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2003-2011 Mario de Sousa (msousa@fe.up.pt) * Copyright (C) 2007-2011 Laurent Bessard and Edouard Tisserant * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* * Case element iterator. * Iterate through the elements of a case list. * * This is part of the 4th stage that generates * a c++ source program equivalent to the IL and ST * code. */ /* Given a case_list_c and a type of element, iterate through * each element, returning the symbol of each element if from * the good type...case_element_iterator_c */ #include "case_element_iterator.hh" #include "../main.hh" // required for ERROR() and ERROR_MSG() macros. //#define DEBUG #ifdef DEBUG #define TRACE(classname) printf("\n____%s____\n",classname); #else #define TRACE(classname) #endif void* case_element_iterator_c::handle_case_element(symbol_c *case_element) { if (current_case_element == case_element) { current_case_element = NULL; } else if (current_case_element == NULL) { current_case_element = case_element; return case_element; } /* Not found! */ return NULL; } void* case_element_iterator_c::iterate_list(list_c *list) { void *res; for (int i = 0; i < list->n; i++) { res = list->get_element(i)->accept(*this); if (res != NULL) return res; } return NULL; } /* start off at the first case element once again... */ void case_element_iterator_c::reset(void) { current_case_element = NULL; } /* initialize the iterator object. * We must be given a reference to a case_list_c that will be analyzed... */ case_element_iterator_c::case_element_iterator_c(symbol_c *list, case_element_t element_type) { /* do some consistency check... */ case_list_c* case_list = dynamic_cast<case_list_c*>(list); if (NULL == case_list) ERROR; /* OK. Now initialize this object... */ this->case_list = list; this->wanted_element_type = element_type; reset(); } /* Skip to the next case element of type chosen. After object creation, * the object references on case element _before_ the first, so * this function must be called once to get the object to * reference the first element... * * Returns the case element's symbol! */ symbol_c *case_element_iterator_c::next(void) { void *res = case_list->accept(*this); if (res == NULL) return NULL; return current_case_element; } /******************************/ /* B 1.2.1 - Numeric Literals */ /******************************/ void *case_element_iterator_c::visit(integer_c *symbol) { switch (wanted_element_type) { case element_single: return handle_case_element(symbol); break; default: break; } return NULL; } void *case_element_iterator_c::visit(neg_integer_c *symbol) { switch (wanted_element_type) { case element_single: return handle_case_element(symbol); break; default: break; } return NULL; } /********************************/ /* B 1.3.3 - Derived data types */ /********************************/ /* signed_integer DOTDOT signed_integer */ void *case_element_iterator_c::visit(subrange_c *symbol) { switch (wanted_element_type) { case element_subrange: return handle_case_element(symbol); break; default: break; } return NULL; } /* enumerated_type_name '#' identifier */ void *case_element_iterator_c::visit(enumerated_value_c *symbol) { switch (wanted_element_type) { case element_single: return handle_case_element(symbol); break; default: break; } return NULL; } /********************************/ /* B 3.2.3 Selection Statements */ /********************************/ void *case_element_iterator_c::visit(case_list_c *symbol) { return iterate_list(symbol); }
4,662
C++
.cc
153
27.862745
95
0.676195
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,659
array_dimension_iterator.cc
nucleron_matiec/absyntax_utils/array_dimension_iterator.cc
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2003-2011 Mario de Sousa (msousa@fe.up.pt) * Copyright (C) 2007-2011 Laurent Bessard and Edouard Tisserant * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* * Array dimension iterator. * Iterate through the dimensions of array specification. * * This is part of the 4th stage that generates * a c++ source program equivalent to the IL and ST * code. */ /* Given a array_specification_c, iterate through * each subrange, returning the symbol of each subrange * ...array_dimension_iterator_c */ #include "array_dimension_iterator.hh" #include "../main.hh" // required for ERROR() and ERROR_MSG() macros. //#define DEBUG #ifdef DEBUG #define TRACE(classname) printf("\n____%s____\n",classname); #else #define TRACE(classname) #endif void* array_dimension_iterator_c::iterate_list(list_c *list) { void *res; for (int i = 0; i < list->n; i++) { res = list->get_element(i)->accept(*this); if (res != NULL) return res; } return NULL; } /* start off at the first case element once again... */ void array_dimension_iterator_c::reset(void) { current_array_dimension = NULL; } /* initialize the iterator object. * We must be given a reference to a array_specification_c that will be analyzed... */ array_dimension_iterator_c::array_dimension_iterator_c(symbol_c *symbol) { /* do some consistency check... */ /* NOTE: We comment out the consistency check so the compiler does not bork when it encounters buggy source code. * e.g. Code that handles a non array variable as an array! * VAR v1, v2: int; END_VAR * v1 := v2[33, 45]; * The above error will be caught by the datatype checking algorithms! */ array_spec_init_c * array_spec_init = dynamic_cast<array_spec_init_c *>(symbol); if (NULL != array_spec_init) symbol = array_spec_init->array_specification; array_specification_c* array_spec = dynamic_cast<array_specification_c*>(symbol); // if (NULL == array_spec) ERROR; /* OK. Now initialize this object... */ this->array_specification = array_spec; // Set to array_spec and not symbol => will be NULL if not an array_specification_c* !! reset(); } /* Skip to the next subrange. After object creation, * the object references on subrange _before_ the first, so * this function must be called once to get the object to * reference the first subrange... * * Returns the subrange symbol! */ subrange_c *array_dimension_iterator_c::next(void) { if (NULL == array_specification) return NULL; /* The source code probably has a bug which will be caught somewhere else! */ void *res = array_specification->accept(*this); if (NULL == res) return NULL; return current_array_dimension; } /********************************/ /* B 1.3.3 - Derived data types */ /********************************/ /* signed_integer DOTDOT signed_integer */ void *array_dimension_iterator_c::visit(subrange_c *symbol) { if (current_array_dimension == symbol) { current_array_dimension = NULL; } else if (current_array_dimension == NULL) { current_array_dimension = symbol; return symbol; } /* Not found! */ return NULL; } /* ARRAY '[' array_subrange_list ']' OF non_generic_type_name */ void *array_dimension_iterator_c::visit(array_specification_c *symbol) { return symbol->array_subrange_list->accept(*this); } /* array_subrange_list ',' subrange */ void *array_dimension_iterator_c::visit(array_subrange_list_c *symbol) { return iterate_list(symbol); }
4,502
C++
.cc
118
35.805085
129
0.69642
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,661
search_base_type.cc
nucleron_matiec/absyntax_utils/search_base_type.cc
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2003-2012 Mario de Sousa (msousa@fe.up.pt) * Copyright (C) 2007-2011 Laurent Bessard and Edouard Tisserant * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* Determine the data type on which another data type is based on. * If a new default initial value is given, we DO NOT consider it a * new base class, and continue looking further! * * E.g. TYPE new_int_t : INT; END_TYPE; * TYPE new_int2_t : INT = 2; END_TYPE; * TYPE new_subr_t : INT (4..5); END_TYPE; * * new_int_t is really an INT!! * new_int2_t is also really an INT!! * new_subr_t is also really an INT!! * * Note that a FB declaration is also considered a base type, as * we may have FB instances declared of a specific FB type. */ #include "absyntax_utils.hh" #include "../main.hh" // required for ERROR() and ERROR_MSG() macros. /* pointer to singleton instance */ search_base_type_c *search_base_type_c::search_base_type_singleton = NULL; search_base_type_c::search_base_type_c(void) {current_basetype_name = NULL; current_basetype = NULL; current_equivtype = NULL;} /* static method! */ void search_base_type_c::create_singleton(void) { if (NULL == search_base_type_singleton) search_base_type_singleton = new search_base_type_c(); if (NULL == search_base_type_singleton) ERROR; } /* static method! */ symbol_c *search_base_type_c::get_equivtype_decl(symbol_c *symbol) { create_singleton(); if (NULL == symbol) return NULL; search_base_type_singleton->current_basetype_name = NULL; search_base_type_singleton->current_basetype = NULL; search_base_type_singleton->current_equivtype = NULL; symbol_c *basetype = (symbol_c *)symbol->accept(*search_base_type_singleton); if (NULL != search_base_type_singleton->current_equivtype) return search_base_type_singleton->current_equivtype; return basetype; } /* static method! */ symbol_c *search_base_type_c::get_basetype_decl(symbol_c *symbol) { create_singleton(); if (NULL == symbol) return NULL; search_base_type_singleton->current_basetype_name = NULL; search_base_type_singleton->current_basetype = NULL; search_base_type_singleton->current_equivtype = NULL; return (symbol_c *)symbol->accept(*search_base_type_singleton); } /* static method! */ symbol_c *search_base_type_c::get_basetype_id (symbol_c *symbol) { create_singleton(); if (NULL == symbol) return NULL; search_base_type_singleton->current_basetype_name = NULL; search_base_type_singleton->current_basetype = NULL; search_base_type_singleton->current_equivtype = NULL; symbol->accept(*search_base_type_singleton); return (symbol_c *)search_base_type_singleton->current_basetype_name; } /*************************/ /* B.1 - Common elements */ /*************************/ /*******************************************/ /* B 1.1 - Letters, digits and identifiers */ /*******************************************/ void *search_base_type_c::handle_datatype_identifier(token_c *type_name) { this->current_basetype_name = type_name; /* if we have reached this point, it is because the current_basetype is not yet pointing to the base datatype we are looking for, * so we will be searching for the delcaration of the type named in type_name, which might be the base datatype (we search recursively!) */ this->current_basetype = NULL; /* look up the type declaration... */ type_symtable_t::iterator iter1 = type_symtable.find(type_name); if (iter1 != type_symtable.end()) return iter1->second->accept(*this); // iter1->second is the type_decl function_block_type_symtable_t::iterator iter2 = function_block_type_symtable.find(type_name); if (iter2 != function_block_type_symtable.end()) return iter2->second->accept(*this); // iter2->second is the type_decl /* Type declaration not found!! */ ERROR; return NULL; } void *search_base_type_c::visit( identifier_c *type_name) {return handle_datatype_identifier(type_name);} void *search_base_type_c::visit(derived_datatype_identifier_c *type_name) {return handle_datatype_identifier(type_name);} void *search_base_type_c::visit( poutype_identifier_c *type_name) {return handle_datatype_identifier(type_name);} /*********************/ /* B 1.2 - Constants */ /*********************/ /******************************/ /* B 1.2.1 - Numeric Literals */ /******************************/ /* Numeric literals without any explicit type cast have unknown data type, * so we continue considering them as their own basic data types until * they can be resolved (for example, when using '30+x' where 'x' is a LINT variable, the * numeric literal '30' must then be considered a LINT so the ADD function may be called * with all inputs of the same data type. * If 'x' were a SINT, then the '30' would have to be a SINT too! */ void *search_base_type_c::visit(real_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(neg_real_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(integer_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(neg_integer_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(binary_integer_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(octal_integer_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(hex_integer_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(boolean_true_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(boolean_false_c *symbol) {return (void *)symbol;} /***********************************/ /* B 1.3.1 - Elementary Data Types */ /***********************************/ void *search_base_type_c::visit(time_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(bool_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(sint_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(int_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(dint_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(lint_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(usint_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(uint_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(udint_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(ulint_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(real_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(lreal_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(date_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(tod_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(dt_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(byte_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(word_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(dword_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(lword_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(string_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(wstring_type_name_c *symbol) {return (void *)symbol;} /* A non standard datatype! */ void *search_base_type_c::visit(void_type_name_c *symbol) {return (void *)symbol;} /******************************************************/ /* Extensions to the base standard as defined in */ /* "Safety Software Technical Specification, */ /* Part 1: Concepts and Function Blocks, */ /* Version 1.0 – Official Release" */ /* by PLCopen - Technical Committee 5 - 2006-01-31 */ /******************************************************/ void *search_base_type_c::visit(safetime_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safebool_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safesint_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safeint_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safedint_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safelint_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safeusint_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safeuint_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safeudint_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safeulint_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safereal_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safelreal_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safedate_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safetod_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safedt_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safebyte_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safeword_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safedword_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safelword_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safestring_type_name_c *symbol) {return (void *)symbol;} void *search_base_type_c::visit(safewstring_type_name_c *symbol) {return (void *)symbol;} /********************************/ /* B.1.3.2 - Generic data types */ /********************************/ void *search_base_type_c::visit(generic_type_any_c *symbol) {return (void *)symbol;} /********************************/ /* B 1.3.3 - Derived data types */ /********************************/ /* simple_type_name ':' simple_spec_init */ void *search_base_type_c::visit(simple_type_declaration_c *symbol) { return symbol->simple_spec_init->accept(*this); } /* simple_specification ASSIGN constant */ void *search_base_type_c::visit(simple_spec_init_c *symbol) { return symbol->simple_specification->accept(*this); } /* subrange_type_name ':' subrange_spec_init */ void *search_base_type_c::visit(subrange_type_declaration_c *symbol) { this->current_equivtype = symbol; return symbol->subrange_spec_init->accept(*this); } /* subrange_specification ASSIGN signed_integer */ void *search_base_type_c::visit(subrange_spec_init_c *symbol) { if (NULL == this->current_equivtype) this->current_equivtype = symbol; return symbol->subrange_specification->accept(*this); } /* integer_type_name '(' subrange')' */ void *search_base_type_c::visit(subrange_specification_c *symbol) { if (NULL == this->current_equivtype) this->current_equivtype = symbol; return symbol->integer_type_name->accept(*this); } /* signed_integer DOTDOT signed_integer */ void *search_base_type_c::visit(subrange_c *symbol) {ERROR; return NULL;} /* should never get called... */ /* enumerated_type_name ':' enumerated_spec_init */ void *search_base_type_c::visit(enumerated_type_declaration_c *symbol) { this->current_basetype_name = symbol->enumerated_type_name; /* NOTE: We want search_base_type_c to return a enumerated_type_declaration_c as the base datatpe if possible * (i.e. if it is a named datatype declared inside a TYPE ... END_TYPE declarations, as opposed to an * anonymous datatype declared in a VAR ... AND_VAR declaration). * However, we cannot return this symbol just yet, as it may not be the final base datatype. * So we store it in a temporary current_basetype variable! */ this->current_basetype = symbol; return symbol->enumerated_spec_init->accept(*this); } /* enumerated_specification ASSIGN enumerated_value */ void *search_base_type_c::visit(enumerated_spec_init_c *symbol) { // current_basetype may have been set in the previous enumerated_type_declaration_c visitor, in which case we do not want to overwrite the value! if (NULL == this->current_basetype) this->current_basetype = symbol; /* NOTE: the following line may call either the visitor to * - identifier_c, in which case this is not yet the base datatype we are looking for (it will set current_basetype to NULL!) * - enumerated_value_list_c, in which case we have found the base datatype. */ return symbol->enumerated_specification->accept(*this); } /* helper symbol for enumerated_specification->enumerated_spec_init */ /* enumerated_value_list ',' enumerated_value */ void *search_base_type_c::visit(enumerated_value_list_c *symbol) { // current_basetype may have been set in the previous enumerated_type_declaration_c or enumerated_spec_init_c visitors, in which case we do not want to overwrite the value! if (NULL == this->current_basetype) this->current_basetype = symbol; return (void *)current_basetype; } /* enumerated_type_name '#' identifier */ // SYM_REF2(enumerated_value_c, type, value) void *search_base_type_c::visit(enumerated_value_c *symbol) {ERROR; return NULL;} /* should never get called... */ /* identifier ':' array_spec_init */ void *search_base_type_c::visit(array_type_declaration_c *symbol) { this->current_basetype_name = symbol->identifier; return symbol->array_spec_init->accept(*this); } /* array_specification [ASSIGN array_initialization} */ /* array_initialization may be NULL ! */ void *search_base_type_c::visit(array_spec_init_c *symbol) { /* Note that the 'array_specification' may be either an identifier of a previsously defined array type, * or an array_specification_c, so we can not stop here and simply return a array_spec_init_c, * especially if we are looking for the base class! */ return symbol->array_specification->accept(*this); } /* ARRAY '[' array_subrange_list ']' OF non_generic_type_name */ void *search_base_type_c::visit(array_specification_c *symbol) {return (void *)symbol;} /* helper symbol for array_specification */ /* array_subrange_list ',' subrange */ void *search_base_type_c::visit(array_subrange_list_c *symbol) {ERROR; return NULL;} /* should never get called... */ /* array_initialization: '[' array_initial_elements_list ']' */ /* helper symbol for array_initialization */ /* array_initial_elements_list ',' array_initial_elements */ void *search_base_type_c::visit(array_initial_elements_list_c *symbol) {ERROR; return NULL;} /* should never get called... */ /* integer '(' [array_initial_element] ')' */ /* array_initial_element may be NULL ! */ void *search_base_type_c::visit(array_initial_elements_c *symbol) {ERROR; return NULL;} /* should never get called... */ /* structure_type_name ':' structure_specification */ /* NOTE: structure_specification will point to either a * initialized_structure_c * OR A * structure_element_declaration_list_c */ void *search_base_type_c::visit(structure_type_declaration_c *symbol) { this->current_basetype_name = symbol->structure_type_name; return symbol->structure_specification->accept(*this); } /* var1_list ':' structure_type_name */ void *search_base_type_c::visit(structured_var_declaration_c *symbol) {return symbol;} /* structure_type_name ASSIGN structure_initialization */ /* structure_initialization may be NULL ! */ void *search_base_type_c::visit(initialized_structure_c *symbol) {return symbol->structure_type_name->accept(*this);} /* helper symbol for structure_declaration */ /* structure_declaration: STRUCT structure_element_declaration_list END_STRUCT */ /* structure_element_declaration_list structure_element_declaration ';' */ void *search_base_type_c::visit(structure_element_declaration_list_c *symbol) {return (void *)symbol;} /* structure_element_name ':' *_spec_init */ void *search_base_type_c::visit(structure_element_declaration_c *symbol) {return symbol->spec_init->accept(*this);} /* helper symbol for structure_initialization */ /* structure_initialization: '(' structure_element_initialization_list ')' */ /* structure_element_initialization_list ',' structure_element_initialization */ void *search_base_type_c::visit(structure_element_initialization_list_c *symbol) {ERROR; return NULL;} /* should never get called... */ /* structure_element_name ASSIGN value */ void *search_base_type_c::visit(structure_element_initialization_c *symbol) {ERROR; return NULL;} /* should never get called... */ /* string_type_name ':' elementary_string_type_name string_type_declaration_size string_type_declaration_init */ /* SYM_REF4(string_type_declaration_c, string_type_name, elementary_string_type_name, string_type_declaration_size, string_type_declaration_init) // may be == NULL! */ void *search_base_type_c::visit(string_type_declaration_c *symbol) {return (void *)symbol;} /* function_block_type_name ASSIGN structure_initialization */ /* structure_initialization -> may be NULL ! */ // SYM_REF2(fb_spec_init_c, function_block_type_name, structure_initialization) void *search_base_type_c::visit(fb_spec_init_c *symbol) { return symbol->function_block_type_name->accept(*this); } /* ref_spec: REF_TO (non_generic_type_name | function_block_type_name) */ // SYM_REF1(ref_spec_c, type_name) void *search_base_type_c::visit(ref_spec_c *symbol) {return (void *)symbol;} /* For the moment, we do not support initialising reference data types */ /* ref_spec_init: ref_spec [ ASSIGN ref_initialization ]; */ /* NOTE: ref_initialization may be NULL!! */ // SYM_REF2(ref_spec_init_c, ref_spec, ref_initialization) void *search_base_type_c::visit(ref_spec_init_c *symbol) {return symbol->ref_spec->accept(*this);} /* ref_type_decl: identifier ':' ref_spec_init */ // SYM_REF2(ref_type_decl_c, ref_type_name, ref_spec_init) void *search_base_type_c::visit(ref_type_decl_c *symbol) { this->current_basetype_name = symbol->ref_type_name; return symbol->ref_spec_init->accept(*this); } /*****************************/ /* B 1.5.2 - Function Blocks */ /*****************************/ /* FUNCTION_BLOCK derived_function_block_name io_OR_other_var_declarations function_block_body END_FUNCTION_BLOCK */ // SYM_REF3(function_block_declaration_c, fblock_name, var_declarations, fblock_body) void *search_base_type_c::visit(function_block_declaration_c *symbol) {return (void *)symbol;} /*********************************************/ /* B.1.6 Sequential function chart elements */ /*********************************************/ /* INITIAL_STEP step_name ':' action_association_list END_STEP */ // SYM_REF2(initial_step_c, step_name, action_association_list) void *search_base_type_c::visit(initial_step_c *symbol) { this->current_basetype_name = NULL; /* this pseudo data type does not have a type name! */ return (void *)symbol; } /* STEP step_name ':' action_association_list END_STEP */ // SYM_REF2(step_c, step_name, action_association_list) void *search_base_type_c::visit(step_c *symbol) { this->current_basetype_name = NULL; /* this pseudo data type does not have a type name! */ return (void *)symbol; }
20,867
C++
.cc
358
56.215084
174
0.678285
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,663
search_fb_instance_decl.cc
nucleron_matiec/absyntax_utils/search_fb_instance_decl.cc
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2003-2011 Mario de Sousa (msousa@fe.up.pt) * Copyright (C) 2007-2011 Laurent Bessard and Edouard Tisserant * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ #include "absyntax_utils.hh" /* Returns the function block type declaration * of a specific function block instance. */ /* Returns the type name of a specific function block * instance. This class will search the variable * declarations inside the scope given to it * searching for the declaration of the function * block instance. * * The class constructor must be given the search scope * (function, function block or program within which * the function block instance was declared). * * This class will search the tree from the root given to the * constructor. Another option would be to build a symbol table, * and search that instead. Building the symbol table would be done * while visiting the variable declaration objects in the parse * tree. Unfortuantely, generate_c_c does not visit these * objects, delegating it to another class. This means that * we would need another specialised class just to build the * symbol table. We might just as well have a specialised class * that searches the tree itself for the relevant info. This * class is exactly that...! */ search_fb_instance_decl_c::search_fb_instance_decl_c(symbol_c *search_scope) { this->search_scope = search_scope; this->current_fb_type_name = NULL; } symbol_c *search_fb_instance_decl_c::get_type_name(symbol_c *fb_instance_name) { this->search_name = fb_instance_name; return (symbol_c *)search_scope->accept(*this); } /***************************/ /* B 0 - Programming Model */ /***************************/ void *search_fb_instance_decl_c::visit(library_c *symbol) { /* we do not want to search multiple declaration scopes, * so we do not visit all the functions, fucntion blocks, etc... */ return NULL; } /******************************************/ /* B 1.4.3 - Declaration & Initialisation */ /******************************************/ /* name_list ':' function_block_type_name ASSIGN structure_initialization */ /* structure_initialization -> may be NULL ! */ void *search_fb_instance_decl_c::visit(fb_name_decl_c *symbol) { current_fb_type_name = spec_init_sperator_c::get_spec(symbol->fb_spec_init); return symbol->fb_name_list->accept(*this); } /* name_list ',' fb_name */ void *search_fb_instance_decl_c::visit(fb_name_list_c *symbol) { list_c *list = symbol; for(int i = 0; i < list->n; i++) { if (compare_identifiers(list->get_element(i), search_name) == 0) /* by now, current_fb_declaration should be != NULL */ return current_fb_type_name; } return NULL; } /* name_list ',' fb_name */ void *search_fb_instance_decl_c::visit(external_declaration_c *symbol) { if (compare_identifiers(symbol->global_var_name, search_name) == 0) return spec_init_sperator_c::get_spec(symbol->specification); return NULL; } /**************************************/ /* B.1.5 - Program organization units */ /**************************************/ /***********************/ /* B 1.5.1 - Functions */ /***********************/ void *search_fb_instance_decl_c::visit(function_declaration_c *symbol) { /* no need to search through all the body, so we only * visit the variable declarations...! */ return symbol->var_declarations_list->accept(*this); } /*****************************/ /* B 1.5.2 - Function Blocks */ /*****************************/ void *search_fb_instance_decl_c::visit(function_block_declaration_c *symbol) { /* no need to search through all the body, so we only * visit the variable declarations...! */ return symbol->var_declarations->accept(*this); } /**********************/ /* B 1.5.3 - Programs */ /**********************/ void *search_fb_instance_decl_c::visit(program_declaration_c *symbol) { /* no need to search through all the body, so we only * visit the variable declarations...! */ return symbol->var_declarations->accept(*this); }
4,983
C++
.cc
127
37.086614
80
0.669835
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,664
type_initial_value.cc
nucleron_matiec/absyntax_utils/type_initial_value.cc
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2003-2011 Mario de Sousa (msousa@fe.up.pt) * Copyright (C) 2007-2011 Laurent Bessard and Edouard Tisserant * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* * Determine the default initial value of a type declaration. * * This is part of the 4th stage that generates * a c++ source program equivalent to the IL and ST * code. */ /* Given a type definition declration, determine its default * initial value. Note that types based on other types * may have to iterate through each type it is based on * to determine the initial value. * E.g. * TYPE * A_t : INT := 10; * B_t : A_t := 20; * C_t : B_t; * D_t : C_t := 40; * END_TYPE * Where the default initial value for C_t is 20! */ /* NOTE: The main program only needs one instance of * this class of object. This class * is therefore a singleton. */ #include "absyntax_utils.hh" //#define DEBUG #ifdef DEBUG #define TRACE(classname) printf("\n____%s____\n",classname); #else #define TRACE(classname) #endif type_initial_value_c *type_initial_value_c::instance(void) { if (_instance != NULL) return _instance; _instance = new type_initial_value_c; null_literal = new ref_value_null_literal_c(); real_0 = new real_c("0"); integer_0 = new integer_c("0"); integer_1 = new integer_c("1"); bool_0 = new boolean_literal_c(new bool_type_name_c(),new boolean_false_c()); /* FIXME: Our current implementation only allows dates from 1970 onwards, * but the standard defines the date 0001-01-01 as the default value * for the DATE data type. Untill we fix our implementation, we use 1970-01-01 * as our default value!! */ //date_literal_0 = new date_literal_c(integer_1, integer_1, integer_1); date_literal_0 = new date_literal_c(new integer_c("1970"), integer_1, integer_1); daytime_literal_0 = new daytime_c(integer_0, integer_0, real_0); time_0 = new duration_c (new time_type_name_c(), NULL, new interval_c(NULL, NULL, NULL, integer_0, NULL)); // T#0s date_0 = new date_c (new date_type_name_c(), date_literal_0); // D#0001-01-01 tod_0 = new time_of_day_c (new tod_type_name_c(), daytime_literal_0); // TOD#00:00:00 dt_0 = new date_and_time_c(new dt_type_name_c(), date_literal_0, daytime_literal_0); // DT#0001-01-01-00:00:00 string_0 = new single_byte_character_string_c("''"); wstring_0 = new double_byte_character_string_c("\"\""); return _instance; } type_initial_value_c::type_initial_value_c(void) {} symbol_c *type_initial_value_c::get(symbol_c *type) { TRACE("type_initial_value_c::get(): called "); return (symbol_c *)type->accept(*type_initial_value_c::instance()); } void *type_initial_value_c::handle_type_spec(symbol_c *base_type_name, symbol_c *type_spec_init) { if (type_spec_init != NULL) return type_spec_init; /* no initial value specified, so we return the initial value of the type this type is based on... */ return base_type_name->accept(*this); } void *type_initial_value_c::handle_type_name(symbol_c *type_name) { /* look up the type declaration... */ type_symtable_t::iterator iter = type_symtable.find(type_name); /* Type declaration not found!! */ /* NOTE: Variables declared out of function block 'data types',for eg: VAR timer: TON; END_VAR * do not have a default value, so (TON) will never be found in the type symbol table. This means * we cannot simply consider this an error and abort, but must rather return a NULL. */ if (iter == type_symtable.end()) return NULL; return iter->second->accept(*this); // iter->second is the type_decl } /* visitor for identifier_c should no longer be necessary. All references to derived datatypes are now stored in then */ /* AST using either poutype_identifier_c or derived_datatype_identifier_c. In principe, the following should not be necesasry */ void *type_initial_value_c::visit( identifier_c *symbol) {return handle_type_name(symbol);} /* should never occur */ void *type_initial_value_c::visit( poutype_identifier_c *symbol) {return handle_type_name(symbol);} /* in practice it might never get called, as FB, Functions and Programs do not have initial value */ void *type_initial_value_c::visit(derived_datatype_identifier_c *symbol) {return handle_type_name(symbol);} /***********************************/ /* B 1.3.1 - Elementary Data Types */ /***********************************/ void *type_initial_value_c::visit(time_type_name_c *symbol) {return (void *)time_0;} void *type_initial_value_c::visit(bool_type_name_c *symbol) {return (void *)bool_0;} void *type_initial_value_c::visit(sint_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(int_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(dint_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(lint_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(usint_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(uint_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(udint_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(ulint_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(real_type_name_c *symbol) {return (void *)real_0;} void *type_initial_value_c::visit(lreal_type_name_c *symbol) {return (void *)real_0;} void *type_initial_value_c::visit(date_type_name_c *symbol) {return (void *)date_0;} void *type_initial_value_c::visit(tod_type_name_c *symbol) {return (void *)tod_0;} void *type_initial_value_c::visit(dt_type_name_c *symbol) {return (void *)dt_0;} void *type_initial_value_c::visit(byte_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(word_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(dword_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(lword_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(string_type_name_c *symbol) {return (void *)string_0;} void *type_initial_value_c::visit(wstring_type_name_c *symbol) {return (void *)wstring_0;} void *type_initial_value_c::visit(safetime_type_name_c *symbol) {return (void *)time_0;} void *type_initial_value_c::visit(safebool_type_name_c *symbol) {return (void *)bool_0;} void *type_initial_value_c::visit(safesint_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(safeint_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(safedint_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(safelint_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(safeusint_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(safeuint_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(safeudint_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(safeulint_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(safereal_type_name_c *symbol) {return (void *)real_0;} void *type_initial_value_c::visit(safelreal_type_name_c *symbol) {return (void *)real_0;} void *type_initial_value_c::visit(safedate_type_name_c *symbol) {return (void *)date_0;} void *type_initial_value_c::visit(safetod_type_name_c *symbol) {return (void *)tod_0;} void *type_initial_value_c::visit(safedt_type_name_c *symbol) {return (void *)dt_0;} void *type_initial_value_c::visit(safebyte_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(safeword_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(safedword_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(safelword_type_name_c *symbol) {return (void *)integer_0;} void *type_initial_value_c::visit(safestring_type_name_c *symbol) {return (void *)string_0;} void *type_initial_value_c::visit(safewstring_type_name_c *symbol) {return (void *)wstring_0;} /********************************/ /* B 1.3.3 - Derived data types */ /********************************/ /* simple_type_name ':' simple_spec_init */ void *type_initial_value_c::visit(simple_type_declaration_c *symbol) { return symbol->simple_spec_init->accept(*this); } /* simple_specification ASSIGN constant */ void *type_initial_value_c::visit(simple_spec_init_c *symbol) { return handle_type_spec(symbol->simple_specification, symbol->constant); } /* subrange_type_name ':' subrange_spec_init */ void *type_initial_value_c::visit(subrange_type_declaration_c *symbol) { return symbol->subrange_spec_init->accept(*this); } /* subrange_specification ASSIGN signed_integer */ void *type_initial_value_c::visit(subrange_spec_init_c *symbol) { return handle_type_spec(symbol->subrange_specification, symbol->signed_integer); } /* integer_type_name '(' subrange')' */ void *type_initial_value_c::visit(subrange_specification_c *symbol) { /* if no initial value explicitly given, then use the lowest value of the subrange */ if (symbol->subrange != NULL) return symbol->subrange->accept(*this); else return symbol->integer_type_name->accept(*this); } /* signed_integer DOTDOT signed_integer */ void *type_initial_value_c::visit(subrange_c *symbol) {return symbol->lower_limit;} /* enumerated_type_name ':' enumerated_spec_init */ void *type_initial_value_c::visit(enumerated_type_declaration_c *symbol) { return symbol->enumerated_spec_init->accept(*this); } /* enumerated_specification ASSIGN enumerated_value */ void *type_initial_value_c::visit(enumerated_spec_init_c *symbol) { return handle_type_spec(symbol->enumerated_specification, symbol->enumerated_value); } /* helper symbol for enumerated_specification->enumerated_spec_init */ /* enumerated_value_list ',' enumerated_value */ void *type_initial_value_c::visit(enumerated_value_list_c *symbol) { /* stage1_2 never creates an enumerated_value_list_c with no entries. If this occurs, then something must have changed! */ if (symbol->n <= 0) ERROR; /* if no initial value explicitly given, then use the lowest value of the subrange */ return (void *)symbol->get_element(0); } /* enumerated_type_name '#' identifier */ // SYM_REF2(enumerated_value_c, type, value) void *type_initial_value_c::visit(enumerated_value_c *symbol) {ERROR; return NULL;} /* identifier ':' array_spec_init */ void *type_initial_value_c::visit(array_type_declaration_c *symbol) { return symbol->array_spec_init->accept(*this); } /* array_specification [ASSIGN array_initialization} */ /* array_initialization may be NULL ! */ void *type_initial_value_c::visit(array_spec_init_c *symbol) { return handle_type_spec(symbol->array_specification, symbol->array_initialization); } /* ARRAY '[' array_subrange_list ']' OF non_generic_type_name */ void *type_initial_value_c::visit(array_specification_c *symbol) { //symbol_c *init_value = (symbol_c *)symbol->non_generic_type_name->accept(*this); /* Now build a array_initial_elements_list_c list, and populate it * with 1 element of the array_initial_elements_c class */ /* The array_initial_elements_c will contain a reference to the init_value, * and another constant representing the number of elements in the array. * In essence, we are building the equivilant of the following ST/IL code: * New_array_t : ARRAY [1..30, 51..60] of INT := [40(XXX)]; * from the user given code * New_array_t : ARRAY [1..30, 51..60] of INT; * and replacing XXX with the default initial value of INT. */ /* now we need to determine the number of elements in the array... */ /* Easier said than done, as the array may have a list of subranges, as in the * example given above!! */ /* TODO !!!!!*/ /* For now, just assume an array with 1 element. * I (Mario) want to finish off this part of the code before getting boged down * in something else... */ // NOTE: We are leaking memory, as the integer will never get free'd!! //integer_c *integer = new integer_c("1"); // NOTE: We are leaking memory, as the array_initial_elements will never get free'd!! //array_initial_elements_c *array_initial_elements = new array_initial_elements_c(integer, init_value); // NOTE: We are leaking memory, as the array_initial_elements_list will never get free'd!! array_initial_elements_list_c *array_initial_elements_list = new array_initial_elements_list_c(); //array_initial_elements_list->add_element(array_initial_elements); return array_initial_elements_list; } /* helper symbol for array_specification */ /* array_subrange_list ',' subrange */ void *type_initial_value_c::visit(array_subrange_list_c *symbol) {ERROR; return NULL;} /* array_initialization: '[' array_initial_elements_list ']' */ /* helper symbol for array_initialization */ /* array_initial_elements_list ',' array_initial_elements */ void *type_initial_value_c::visit(array_initial_elements_list_c *symbol) {ERROR; return NULL;} /* integer '(' [array_initial_element] ')' */ /* array_initial_element may be NULL ! */ void *type_initial_value_c::visit(array_initial_elements_c *symbol) {ERROR; return NULL;} /* TODO: from this point forward... */ /* structure_type_name ':' structure_specification */ void *type_initial_value_c::visit(structure_type_declaration_c *symbol) {return NULL;} /* structure_type_name ASSIGN structure_initialization */ /* structure_initialization may be NULL ! */ void *type_initial_value_c::visit(initialized_structure_c *symbol) { return handle_type_spec(symbol->structure_type_name, symbol->structure_initialization); } /* helper symbol for structure_declaration */ /* structure_declaration: STRUCT structure_element_declaration_list END_STRUCT */ /* structure_element_declaration_list structure_element_declaration ';' */ void *type_initial_value_c::visit(structure_element_declaration_list_c *symbol) { structure_element_initialization_list_c *structure_element_initialization_list = new structure_element_initialization_list_c(); return structure_element_initialization_list; } /* structure_element_name ':' *_spec_init */ void *type_initial_value_c::visit(structure_element_declaration_c *symbol) {return NULL;} /* helper symbol for structure_initialization */ /* structure_initialization: '(' structure_element_initialization_list ')' */ /* structure_element_initialization_list ',' structure_element_initialization */ void *type_initial_value_c::visit(structure_element_initialization_list_c *symbol) {return NULL;} /* structure_element_name ASSIGN value */ void *type_initial_value_c::visit(structure_element_initialization_c *symbol) {return NULL;} /* string_type_name ':' elementary_string_type_name string_type_declaration_size string_type_declaration_init */ /* * NOTE: * (Summary: Contrary to what is expected, the * string_type_declaration_c is not used to store * simple string type declarations that do not include * size limits. * For e.g.: * str1_type: STRING := "hello!" * will be stored in a simple_type_declaration_c * instead of a string_type_declaration_c. * The following: * str2_type: STRING [64] := "hello!" * will be stored in a sring_type_declaration_c * * Read on for why this is done... * End Summary) * * According to the spec, the valid construct * TYPE new_str_type : STRING := "hello!"; END_TYPE * has two possible routes to type_declaration... * * Route 1: * type_declaration: single_element_type_declaration * single_element_type_declaration: simple_type_declaration * simple_type_declaration: identifier ':' simple_spec_init * simple_spec_init: simple_specification ASSIGN constant * (shift: identifier <- 'new_str_type') * simple_specification: elementary_type_name * elementary_type_name: STRING * (shift: elementary_type_name <- STRING) * (reduce: simple_specification <- elementary_type_name) * (shift: constant <- "hello!") * (reduce: simple_spec_init: simple_specification ASSIGN constant) * (reduce: ...) * * * Route 2: * type_declaration: string_type_declaration * string_type_declaration: identifier ':' elementary_string_type_name string_type_declaration_size string_type_declaration_init * (shift: identifier <- 'new_str_type') * elementary_string_type_name: STRING * (shift: elementary_string_type_name <- STRING) * (shift: string_type_declaration_size <- empty ) * string_type_declaration_init: ASSIGN character_string * (shift: character_string <- "hello!") * (reduce: string_type_declaration_init <- ASSIGN character_string) * (reduce: string_type_declaration <- identifier ':' elementary_string_type_name string_type_declaration_size string_type_declaration_init ) * (reduce: type_declaration <- string_type_declaration) * * * At first glance it seems that removing route 1 would make * the most sense. Unfortunately the construct 'simple_spec_init' * shows up multiple times in other rules, so changing this construct * would also mean changing all the rules in which it appears. * I (Mario) therefore chose to remove route 2 instead. This means * that the above declaration gets stored in a * simple_type_declaration_c, and not in a string_type_declaration_c * as would be expected! */ /* string_type_name ':' elementary_string_type_name string_type_declaration_size string_type_declaration_init */ // SYM_REF4(string_type_declaration_c, string_type_name, // elementary_string_type_name, // string_type_declaration_size, // string_type_declaration_init) /* may be == NULL! */ void *type_initial_value_c::visit(string_type_declaration_c *symbol) { return handle_type_spec(symbol->elementary_string_type_name, symbol->string_type_declaration_init); } /* REF_TO (non_generic_type_name | function_block_type_name) */ void *type_initial_value_c::visit(ref_spec_c *symbol) { return null_literal; } /* ref_spec [ ASSIGN ref_initialization ]; */ /* NOTE: ref_initialization may be NULL!! */ void *type_initial_value_c::visit(ref_spec_init_c *symbol) { return handle_type_spec(symbol->ref_spec, symbol->ref_initialization); } /* identifier ':' ref_spec_init */ void *type_initial_value_c::visit(ref_type_decl_c *symbol) { return symbol->ref_spec_init->accept(*this); } type_initial_value_c *type_initial_value_c::_instance = NULL; ref_value_null_literal_c *type_initial_value_c::null_literal = NULL; real_c *type_initial_value_c::real_0 = NULL; integer_c *type_initial_value_c::integer_0 = NULL; integer_c *type_initial_value_c::integer_1 = NULL; boolean_literal_c *type_initial_value_c::bool_0 = NULL; date_literal_c *type_initial_value_c::date_literal_0 = NULL; daytime_c *type_initial_value_c::daytime_literal_0 = NULL; duration_c *type_initial_value_c::time_0 = NULL; date_c *type_initial_value_c::date_0 = NULL; time_of_day_c *type_initial_value_c::tod_0 = NULL; date_and_time_c *type_initial_value_c::dt_0 = NULL; single_byte_character_string_c *type_initial_value_c::string_0 = NULL; double_byte_character_string_c *type_initial_value_c::wstring_0 = NULL;
20,894
C++
.cc
375
53.736
209
0.694828
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,666
search_varfb_instance_type.cc
nucleron_matiec/absyntax_utils/search_varfb_instance_type.cc
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2003-2012 Mario de Sousa (msousa@fe.up.pt) * Copyright (C) 2007-2011 Laurent Bessard and Edouard Tisserant * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* Determine the data type of a variable. * The variable may be a simple variable, a function block instance, a * struture element within a data structured type (a struct or a fb), or * an array element. * A mixture of array element of a structure element of a structure element * of a .... is also suported! * * example: * window.points[1].coordinate.x * window.points[1].colour * etc... ARE ALLOWED! * * This class must be passed the scope within which the * variable was declared, and the variable name... * * * * * * This class has several members, depending on the exact data the caller * is looking for... * * - item i: we can get either the name of the data type(A), * or it's declaration (B) * (notice however that some variables belong to a data type that does * not have a name, only a declaration as in * VAR a: ARRAY [1..3] of INT; END_VAR * ) * - item ii: we can get either the direct data type (1), * or the base type (2) * * By direct type, I mean the data type of the variable. By base type, I * mean the data type on which the direct type is based on. For example, in * a subrange on INT, the direct type is the subrange itself, while the * base type is INT. * e.g. * This means that if we find that the variable is of type MY_INT, * which was previously declared to be * TYPE MY_INT: INT := 9; * option (1) will return MY_INT * option (2) will return INT * * * Member functions: * ================ * get_basetype_id() ---> returns 2A (implemented, although currently it is not needed! ) * get_basetype_decl() ---> returns 2B * get_type_id() ---> returns 1A * * Since we haven't yet needed it, we don't yet implement * get_type_decl() ---> returns 1B */ #include "absyntax_utils.hh" void search_varfb_instance_type_c::init(void) { this->current_type_id = NULL; this->current_basetype_id = NULL; this->current_basetype_decl = NULL; this->current_field_selector = NULL; } search_varfb_instance_type_c::search_varfb_instance_type_c(symbol_c *search_scope): search_var_instance_decl(search_scope) { this->init(); } /* We expect to be passed a symbolic_variable_c */ symbol_c *search_varfb_instance_type_c::get_type_id(symbol_c *variable_name) { this->init(); variable_name->accept(*this); return current_type_id; } symbol_c *search_varfb_instance_type_c::get_basetype_id(symbol_c *variable_name) { this->init(); variable_name->accept(*this); return current_basetype_id; } symbol_c *search_varfb_instance_type_c::get_basetype_decl(symbol_c *variable_name) { this->init(); variable_name->accept(*this); return current_basetype_decl; } /*************************/ /* B.1 - Common elements */ /*************************/ /*******************************************/ /* B 1.1 - Letters, digits and identifiers */ /*******************************************/ // SYM_TOKEN(identifier_c) void *search_varfb_instance_type_c::visit(identifier_c *variable_name) { /* symbol should be a variable name!! */ /* Note: although the method is called get_decl(), it is getting the declaration of the variable, which for us is the type_id of that variable! */ current_type_id = search_var_instance_decl.get_decl (variable_name); current_basetype_decl = search_base_type_c::get_basetype_decl(current_type_id); current_basetype_id = search_base_type_c::get_basetype_id (current_type_id); /* What if the variable has not been declared? Then this should not be a compiler error! * However, currently stage 2 of the compiler already detects when variables have not been delcared, * so if the variable's declaration is not found, then that means that we have an internal compiler error! * * Actually, the above is not true anymore. See the use of the any_symbolic_variable in iec_bison.yy * - when defining the delay of a delayed action association in SFC * - in program connections inside configurations (will this search_varfb_instance_type_c class be called to handle this??) */ // if (NULL == current_type_id) ERROR; return NULL; } /********************************/ /* B 1.3.3 - Derived data types */ /********************************/ /* identifier ':' array_spec_init */ /* NOTE: I don't think this will ever get called, since in the visit method for array_variable_c * we use the basetype_decl for recursively calling this class, and the base type should never be a * array_type_declaration_c, but for now, let's leave it in... */ void *search_varfb_instance_type_c::visit(array_type_declaration_c *symbol) { ERROR; return NULL; } /* array_specification [ASSIGN array_initialization] */ /* array_initialization may be NULL ! */ /* NOTE: I don't think this will ever get called, since in the visit method for array_variable_c * we use the basetype_decl for recursively calling this class, and the base type should never be a * array_spec_init_c, but for now, let's leave it in... */ void *search_varfb_instance_type_c::visit(array_spec_init_c *symbol) { /* Note that the 'array_specification' may be either an identifier of a previsously defined array type, * or an array_specification_c, so we can not stop here and simply return a array_spec_init_c, * especially if we are looking for the base class! */ ERROR; return NULL; } /* ARRAY '[' array_subrange_list ']' OF non_generic_type_name */ /* NOTE: This method will be reached after being called from the * search_varfb_instance_type_c::visit(array_variable_c *symbol) * method, so we must return the data type of the data stored in the array, * and not the data type of the array itself! */ void *search_varfb_instance_type_c::visit(array_specification_c *symbol) { /* found the type of the element we were looking for! */ current_type_id = symbol->non_generic_type_name; current_basetype_decl = search_base_type_c::get_basetype_decl(current_type_id); current_basetype_id = search_base_type_c::get_basetype_id (current_type_id); return NULL; } /* structure_type_name ':' structure_specification */ /* NOTE: this is only used inside a TYPE ... END_TYPE declaration. * It is never used directly when declaring a new variable! */ /* NOTE: I don't think this will ever get called, since in the visit method for structured_variable_c * we use the basetype_decl for recursively calling this class, and the base type should never be a * structure_type_declaration_c, but for now, let's leave it in... */ void *search_varfb_instance_type_c::visit(structure_type_declaration_c *symbol) { if (NULL == current_field_selector) return NULL; // the source code has a datatype consistency bug that will be caught later!! symbol->structure_specification->accept(*this); return NULL; /* NOTE: structure_specification will point to either a * initialized_structure_c * OR A * structure_element_declaration_list_c */ } /* structure_type_name ASSIGN structure_initialization */ /* structure_initialization may be NULL ! */ // SYM_REF2(initialized_structure_c, structure_type_name, structure_initialization) /* NOTE: only the initialized structure is never used when declaring a new variable instance */ /* NOTE: I don't think this will ever get called, since in the visit method for structured_variable_c * we use the basetype_decl for recursively calling this class, and the base type should never be a * initialized_structure_c, but for now, let's leave it in... */ void *search_varfb_instance_type_c::visit(initialized_structure_c *symbol) { if (NULL == current_field_selector) return NULL; // the source code has a datatype consistency bug that will be caught later!! /* recursively find out the data type of current_field_selector... */ symbol->structure_type_name->accept(*this); return NULL; } /* helper symbol for structure_declaration */ /* structure_declaration: STRUCT structure_element_declaration_list END_STRUCT */ /* structure_element_declaration_list structure_element_declaration ';' */ void *search_varfb_instance_type_c::visit(structure_element_declaration_list_c *symbol) { if (NULL == current_field_selector) return NULL; // the source code has a datatype consistency bug that will be caught later!! /* now search the structure declaration */ for(int i = 0; i < symbol->n; i++) { symbol->get_element(i)->accept(*this); } return NULL; } /* structure_element_name ':' spec_init */ void *search_varfb_instance_type_c::visit(structure_element_declaration_c *symbol) { if (NULL == current_field_selector) return NULL; // the source code has a datatype consistency bug that will be caught later!! if (compare_identifiers(symbol->structure_element_name, current_field_selector) == 0) { /* found the type of the element we were looking for! */ current_type_id = symbol->spec_init; current_basetype_decl = search_base_type_c::get_basetype_decl(current_type_id); current_basetype_id = search_base_type_c::get_basetype_id (current_type_id); } /* Did not find the type of the element we were looking for! */ /* Will keep looking... */ return NULL; } /* helper symbol for structure_initialization */ /* structure_initialization: '(' structure_element_initialization_list ')' */ /* structure_element_initialization_list ',' structure_element_initialization */ void *search_varfb_instance_type_c::visit(structure_element_initialization_list_c *symbol) {ERROR; return NULL;} /* should never get called... */ /* structure_element_name ASSIGN value */ void *search_varfb_instance_type_c::visit(structure_element_initialization_c *symbol) {ERROR; return NULL;} /* should never get called... */ /*********************/ /* B 1.4 - Variables */ /*********************/ // SYM_REF1(symbolic_variable_c, var_name) void *search_varfb_instance_type_c::visit(symbolic_variable_c *symbol) { symbol->var_name->accept(*this); return NULL; } /********************************************/ /* B.1.4.1 Directly Represented Variables */ /********************************************/ // SYM_TOKEN(direct_variable_c) /* We do not yet handle this. Will we ever need to handle it, as the data type of the direct variable is * directly obtainable from the syntax of the direct variable itself? */ /*************************************/ /* B 1.4.2 - Multi-element variables */ /*************************************/ /* subscripted_variable '[' subscript_list ']' */ // SYM_REF2(array_variable_c, subscripted_variable, subscript_list) /* NOTE: when passed a array_variable_c, which represents some IEC61131-3 code similar to X[42] * we must return the data type of the value _stored_ in the array. * If you want to get the data type of the array itself (i.e. just the X variable, without the [42]) * then this class must be called with the identifier_c 'X'. */ void *search_varfb_instance_type_c::visit(array_variable_c *symbol) { /* determine the data type of the subscripted_variable... * This should be an array_specification_c * ARRAY [xx..yy] OF Stored_Data_Type */ symbol->subscripted_variable->accept(*this); symbol_c *basetype_decl = current_basetype_decl; this->init(); /* set all current_*** pointers to NULL ! */ /* Now we determine the 'Stored_Data_Type', i.e. the data type of the variable stored in the array. */ if (NULL != basetype_decl) { basetype_decl->accept(*this); } return NULL; } /* record_variable '.' field_selector */ /* WARNING: input and/or output variables of function blocks * may be accessed as fields of a structured variable! * Code handling a structured_variable_c must take this into account! * (i.e. that a FB instance may be accessed as a structured variable)! * * WARNING: Status bit (.X) and activation time (.T) of STEPS in SFC diagrams * may be accessed as fields of a structured variable! * Code handling a structured_variable_c must take this into account * (i.e. that an SFC STEP may be accessed as a structured variable)! */ // SYM_REF2(structured_variable_c, record_variable, field_selector) void *search_varfb_instance_type_c::visit(structured_variable_c *symbol) { symbol->record_variable->accept(*this); symbol_c *basetype_decl = current_basetype_decl; this->init(); /* set all current_*** pointers to NULL ! */ /* Now we search for the data type of the field... But only if we were able to determine the data type of the variable */ if (NULL != basetype_decl) { current_field_selector = symbol->field_selector; basetype_decl->accept(*this); current_field_selector = NULL; } return NULL; } /**************************************/ /* B.1.5 - Program organization units */ /**************************************/ /*****************************/ /* B 1.5.2 - Function Blocks */ /*****************************/ /* FUNCTION_BLOCK derived_function_block_name io_OR_other_var_declarations function_block_body END_FUNCTION_BLOCK */ // SYM_REF4(function_block_declaration_c, fblock_name, var_declarations, fblock_body, unused) void *search_varfb_instance_type_c::visit(function_block_declaration_c *symbol) { if (NULL == current_field_selector) return NULL; // the source code has a datatype consistency bug that will be caught later!! /* now search the function block declaration for the variable... */ /* If not found, these pointers will all be set to NULL!! */ search_var_instance_decl_c search_decl(symbol); current_type_id = search_decl.get_decl(current_field_selector); current_basetype_decl = search_base_type_c::get_basetype_decl(current_type_id); current_basetype_id = search_base_type_c::get_basetype_id (current_type_id); return NULL; } /*********************************************/ /* B.1.6 Sequential function chart elements */ /*********************************************/ /* INITIAL_STEP step_name ':' action_association_list END_STEP */ // SYM_REF2(initial_step_c, step_name, action_association_list) /* NOTE: this method may be called from visit(structured_variable_c *symbol) method| */ void *search_varfb_instance_type_c::visit(initial_step_c *symbol) { if (NULL == current_field_selector) return NULL; // the source code has a datatype consistency bug that will be caught later!! identifier_c T("T"); identifier_c X("X"); /* Hard code the datatypes of the implicit variables Stepname.X and Stepname.T */ if (compare_identifiers(&T, current_field_selector) == 0) current_type_id = &get_datatype_info_c::time_type_name; if (compare_identifiers(&X, current_field_selector) == 0) current_type_id = &get_datatype_info_c::bool_type_name; current_basetype_decl = search_base_type_c::get_basetype_decl(current_type_id); current_basetype_id = search_base_type_c::get_basetype_id (current_type_id); return NULL; } /* STEP step_name ':' action_association_list END_STEP */ // SYM_REF2(step_c, step_name, action_association_list) /* NOTE: this method may be called from visit(structured_variable_c *symbol) method| */ void *search_varfb_instance_type_c::visit(step_c *symbol) { /* The code here should be identicial to the code in the visit(initial_step_c *) visitor! So we simply call the other visitor! */ initial_step_c initial_step(NULL, NULL); return initial_step.accept(*this); } /***************************************/ /* B.3 - Language ST (Structured Text) */ /***************************************/ /***********************/ /* B 3.1 - Expressions */ /***********************/ /* SYM_REF1(deref_expression_c, exp) --> an extension to the IEC 61131-3 standard - based on the IEC 61131-3 v3 standard. Returns address of the varible! */ void *search_varfb_instance_type_c::visit(deref_expression_c *symbol) { symbol->exp->accept(*this); symbol_c *basetype_decl = current_basetype_decl; this->init(); /* set all current_*** pointers to NULL ! */ /* Check whether the expression if a REF_TO datatype, and if so, set the new datatype to the datatype it references! */ /* Determine whether the datatype is a ref_spec_c, as this is the class used as the */ /* canonical/base datatype of REF_TO types (see search_base_type_c ...) */ ref_spec_c * ref_spec = dynamic_cast<ref_spec_c *>(basetype_decl); if (NULL != ref_spec) { current_basetype_decl = search_base_type_c::get_basetype_decl(ref_spec->type_name); current_basetype_id = search_base_type_c::get_basetype_id (ref_spec->type_name); } return NULL; } /* SYM_REF1(deref_operator_c, exp) --> an extension to the IEC 61131-3 standard - based on the IEC 61131-3 v3 standard. Returns address of the varible! */ void *search_varfb_instance_type_c::visit(deref_operator_c *symbol) { symbol->exp->accept(*this); symbol_c *basetype_decl = current_basetype_decl; this->init(); /* set all current_*** pointers to NULL ! */ /* Check whether the expression if a REF_TO datatype, and if so, set the new datatype to the datatype it references! */ /* Determine whether the datatype is a ref_spec_c, as this is the class used as the */ /* canonical/base datatype of REF_TO types (see search_base_type_c ...) */ ref_spec_c * ref_spec = dynamic_cast<ref_spec_c *>(basetype_decl); if (NULL != ref_spec) { current_basetype_decl = search_base_type_c::get_basetype_decl(ref_spec->type_name); current_basetype_id = search_base_type_c::get_basetype_id (ref_spec->type_name); } return NULL; }
18,832
C++
.cc
377
47.352785
157
0.681642
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,667
search_var_instance_decl.cc
nucleron_matiec/absyntax_utils/search_var_instance_decl.cc
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2003-2011 Mario de Sousa (msousa@fe.up.pt) * Copyright (C) 2007-2011 Laurent Bessard and Edouard Tisserant * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* Search in a VAR* END_VAR declaration for the delcration of the specified variable instance. * Will return: * - the declaration itself (get_decl() ) * - the type of declaration in which the variable was declared (get_vartype() ) * * The variable instance may NOT be a member of a structure of a memeber * of a structure of an element of an array of ... * * For example, considering the following 'variables': * window.points[1].coordinate.x * window.points[1].colour * offset[99] * * passing a reference to 'points', 'points[1]', 'points[1].colour', 'colour' * ARE NOT ALLOWED! * * This class must only be passed the name of the variable that will appear * in the variable declaration. In the above examples, this would be * 'window.points[1].coordinate.x' * 'window.points[1].coordinate' * 'window.points[1]' * 'window' * 'window.points[1].colour' * 'offset' * 'offset[99]' * * */ /* Note: * Determining the declaration type of a specific variable instance (including * function block instances) really means determining whether the variable was declared in a * VAR_INPUT * VAR_OUTPUT * VAR_IN_OUT * VAR * VAR_TEMP * VAR_EXTERNAL * VAR_GLOBAL * VAR <var_name> AT <location> -> Located variable! * */ /* Note: * The current_type_decl that this class returns may reference the * name of a type, or the type declaration itself! * For an example of the first, consider a variable declared as ... * x : AAA; * where the AAA type is previously declared as whatever. * For an example of the second, consider a variable declared as ... * x : array of int [10]; ----> is allowed * * If it is the first, we will return a reference to the name, if the second * we return a reference to the declaration!! */ #include "absyntax_utils.hh" search_var_instance_decl_c::search_var_instance_decl_c(symbol_c *search_scope) { this->current_vartype = none_vt; this->search_scope = search_scope; this->search_name = NULL; this->current_type_decl = NULL; this->current_option = none_opt; } symbol_c *search_var_instance_decl_c::get_decl(symbol_c *variable) { this->current_vartype = none_vt; this->current_option = none_opt; this->search_name = get_var_name_c::get_name(variable); if (NULL == search_scope) return NULL; // NOTE: This is not an ERROR! declaration_check_c, for e.g., relies on this returning NULL! return (symbol_c *)search_scope->accept(*this); } symbol_c *search_var_instance_decl_c::get_basetype_decl(symbol_c *variable) { return search_base_type_c::get_basetype_decl(get_decl(variable)); } search_var_instance_decl_c::vt_t search_var_instance_decl_c::get_vartype(symbol_c *variable) { this->current_vartype = none_vt; this->current_option = none_opt; this->search_name = get_var_name_c::get_name(variable); if (NULL == search_scope) ERROR; search_scope->accept(*this); return this->current_vartype; } search_var_instance_decl_c::opt_t search_var_instance_decl_c::get_option(symbol_c *variable) { this->current_vartype = none_vt; this->current_option = none_opt; this->search_name = get_var_name_c::get_name(variable); if (NULL == search_scope) ERROR; search_scope->accept(*this); return this->current_option; } /***************************/ /* B 0 - Programming Model */ /***************************/ void *search_var_instance_decl_c::visit(library_c *symbol) { /* we do not want to search multiple declaration scopes, * so we do not visit all the functions, function blocks, etc... */ return NULL; } /******************************************/ /* B 1.4.3 - Declaration & Initialization */ /******************************************/ /* edge -> The F_EDGE or R_EDGE directive */ // SYM_REF2(edge_declaration_c, edge, var1_list) // TODO void *search_var_instance_decl_c::visit(constant_option_c *symbol) { current_option = constant_opt; return NULL; } void *search_var_instance_decl_c::visit(retain_option_c *symbol) { current_option = retain_opt; return NULL; } void *search_var_instance_decl_c::visit(non_retain_option_c *symbol) { current_option = non_retain_opt; return NULL; } void *search_var_instance_decl_c::visit(input_declarations_c *symbol) { current_vartype = input_vt; current_option = none_opt; /* not really required. Just to make the code more readable */ if (NULL != symbol->option) symbol->option->accept(*this); void *res = symbol->input_declaration_list->accept(*this); if (res == NULL) { current_vartype = none_vt; current_option = none_opt; } return res; } /* VAR_OUTPUT [RETAIN | NON_RETAIN] var_init_decl_list END_VAR */ /* option -> may be NULL ! */ void *search_var_instance_decl_c::visit(output_declarations_c *symbol) { current_vartype = output_vt; current_option = none_opt; /* not really required. Just to make the code more readable */ if (NULL != symbol->option) symbol->option->accept(*this); void *res = symbol->var_init_decl_list->accept(*this); if (res == NULL) { current_vartype = none_vt; current_option = none_opt; } return res; } /* VAR_IN_OUT var_declaration_list END_VAR */ void *search_var_instance_decl_c::visit(input_output_declarations_c *symbol) { current_vartype = inoutput_vt; current_option = none_opt; /* not really required. Just to make the code more readable */ void *res = symbol->var_declaration_list->accept(*this); if (res == NULL) { current_vartype = none_vt; } return res; } /* ENO : BOOL */ void *search_var_instance_decl_c::visit(eno_param_declaration_c *symbol) { if (compare_identifiers(symbol->name, search_name) == 0) return symbol->type; return NULL; } /* EN : BOOL */ void *search_var_instance_decl_c::visit(en_param_declaration_c *symbol) { if (compare_identifiers(symbol->name, search_name) == 0) return symbol->type_decl; return NULL; } /* VAR [CONSTANT] var_init_decl_list END_VAR */ /* option -> may be NULL ! */ /* helper symbol for input_declarations */ void *search_var_instance_decl_c::visit(var_declarations_c *symbol) { current_vartype = private_vt; current_option = none_opt; /* not really required. Just to make the code more readable */ if (NULL != symbol->option) symbol->option->accept(*this); void *res = symbol->var_init_decl_list->accept(*this); if (res == NULL) { current_vartype = none_vt; current_option = none_opt; } return res; } /* VAR RETAIN var_init_decl_list END_VAR */ void *search_var_instance_decl_c::visit(retentive_var_declarations_c *symbol) { current_vartype = private_vt; current_option = retain_opt; void *res = symbol->var_init_decl_list->accept(*this); if (res == NULL) { current_vartype = none_vt; current_option = none_opt; } return res; } /* VAR [CONSTANT|RETAIN|NON_RETAIN] located_var_decl_list END_VAR */ /* option -> may be NULL ! */ //SYM_REF2(located_var_declarations_c, option, located_var_decl_list) void *search_var_instance_decl_c::visit(located_var_declarations_c *symbol) { current_vartype = located_vt; current_option = none_opt; /* not really required. Just to make the code more readable */ if (NULL != symbol->option) symbol->option->accept(*this); void *res = symbol->located_var_decl_list->accept(*this); if (res == NULL) { current_vartype = none_vt; current_option = none_opt; } return res; } /*| VAR_EXTERNAL [CONSTANT] external_declaration_list END_VAR */ /* option -> may be NULL ! */ //SYM_REF2(external_var_declarations_c, option, external_declaration_list) void *search_var_instance_decl_c::visit(external_var_declarations_c *symbol) { current_vartype = external_vt; current_option = none_opt; /* not really required. Just to make the code more readable */ if (NULL != symbol->option) symbol->option->accept(*this); void *res = symbol->external_declaration_list->accept(*this); if (res == NULL) { current_vartype = none_vt; current_option = none_opt; } return res; } /*| VAR_GLOBAL [CONSTANT|RETAIN] global_var_decl_list END_VAR */ /* option -> may be NULL ! */ //SYM_REF2(global_var_declarations_c, option, global_var_decl_list) void *search_var_instance_decl_c::visit(global_var_declarations_c *symbol) { current_vartype = global_vt; current_option = none_opt; /* not really required. Just to make the code more readable */ if (NULL != symbol->option) symbol->option->accept(*this); void *res = symbol->global_var_decl_list->accept(*this); if (res == NULL) { current_vartype = none_vt; current_option = none_opt; } return res; } /* var1_list is one of the following... * simple_spec_init_c * * subrange_spec_init_c * * enumerated_spec_init_c * */ // SYM_REF2(var1_init_decl_c, var1_list, spec_init) void *search_var_instance_decl_c::visit(var1_init_decl_c *symbol) { current_type_decl = symbol->spec_init; return symbol->var1_list->accept(*this); } /* var1_list ',' variable_name */ // SYM_LIST(var1_list_c) void *search_var_instance_decl_c::visit(var1_list_c *symbol) { list_c *list = symbol; for(int i = 0; i < list->n; i++) { if (compare_identifiers(list->get_element(i), search_name) == 0) /* by now, current_type_decl should be != NULL */ return current_type_decl; } return NULL; } /* name_list ':' function_block_type_name ASSIGN structure_initialization */ /* structure_initialization -> may be NULL ! */ void *search_var_instance_decl_c::visit(fb_name_decl_c *symbol) { // TODO: The following line is wrong! It should be // current_type_decl = symbol->fb_spec_init; // However, this change will require a check of all callers, to see if they would handle this correctly. // For now, just keep what we have had historically, and seems to be working. current_type_decl = spec_init_sperator_c::get_spec(symbol->fb_spec_init); return symbol->fb_name_list->accept(*this); } /* name_list ',' fb_name */ void *search_var_instance_decl_c::visit(fb_name_list_c *symbol) { list_c *list = symbol; for(int i = 0; i < list->n; i++) { if (compare_identifiers(list->get_element(i), search_name) == 0) /* by now, current_fb_declaration should be != NULL */ return current_type_decl; } return NULL; } /* var1_list ':' array_spec_init */ // SYM_REF2(array_var_init_decl_c, var1_list, array_spec_init) void *search_var_instance_decl_c::visit(array_var_init_decl_c *symbol) { current_type_decl = symbol->array_spec_init; return symbol->var1_list->accept(*this); } /* var1_list ':' initialized_structure */ // SYM_REF2(structured_var_init_decl_c, var1_list, initialized_structure) void *search_var_instance_decl_c::visit(structured_var_init_decl_c *symbol) { current_type_decl = symbol->initialized_structure; return symbol->var1_list->accept(*this); } /* var1_list ':' array_specification */ // SYM_REF2(array_var_declaration_c, var1_list, array_specification) void *search_var_instance_decl_c::visit(array_var_declaration_c *symbol) { current_type_decl = symbol->array_specification; return symbol->var1_list->accept(*this); } /* var1_list ':' structure_type_name */ // SYM_REF2(structured_var_declaration_c, var1_list, structure_type_name) void *search_var_instance_decl_c::visit(structured_var_declaration_c *symbol) { current_type_decl = symbol->structure_type_name; return symbol->var1_list->accept(*this); } /* [variable_name] location ':' located_var_spec_init */ /* variable_name -> may be NULL ! */ // SYM_REF4(located_var_decl_c, variable_name, location, located_var_spec_init, unused) // TODO!! /* global_var_name ':' (simple_specification|subrange_specification|enumerated_specification|array_specification|prev_declared_structure_type_name|function_block_type_name */ // SYM_REF2(external_declaration_c, global_var_name, specification) void *search_var_instance_decl_c::visit(external_declaration_c *symbol) { if (compare_identifiers(symbol->global_var_name, search_name) == 0) return symbol->specification; return NULL; } /*| global_var_spec ':' [located_var_spec_init|function_block_type_name] */ /* type_specification ->may be NULL ! */ // SYM_REF2(global_var_decl_c, global_var_spec, type_specification) void *search_var_instance_decl_c::visit(global_var_decl_c *symbol) { if (symbol->type_specification != NULL) { current_type_decl = symbol->type_specification; return symbol->global_var_spec->accept(*this); } else return NULL; } /*| global_var_name location */ //SYM_REF2(global_var_spec_c, global_var_name, location) void *search_var_instance_decl_c::visit(global_var_spec_c *symbol) { if (symbol->global_var_name != NULL && compare_identifiers(symbol->global_var_name, search_name) == 0) return current_type_decl; else return symbol->location->accept(*this); } /*| global_var_list ',' global_var_name */ //SYM_LIST(global_var_list_c) void *search_var_instance_decl_c::visit(global_var_list_c *symbol) { list_c *list = symbol; for(int i = 0; i < list->n; i++) { if (compare_identifiers(list->get_element(i), search_name) == 0) /* by now, current_type_decl should be != NULL */ return current_type_decl; } return NULL; } /* [variable_name] location ':' located_var_spec_init */ /* variable_name -> may be NULL ! */ //SYM_REF4(located_var_decl_c, variable_name, location, located_var_spec_init, unused) void *search_var_instance_decl_c::visit(located_var_decl_c *symbol) { if (symbol->variable_name != NULL && compare_identifiers(symbol->variable_name, search_name) == 0) return symbol->located_var_spec_init; else { current_type_decl = symbol->located_var_spec_init; return symbol->location->accept(*this); } } /*| global_var_spec ':' [located_var_spec_init|function_block_type_name] */ /* type_specification ->may be NULL ! */ // SYM_REF2(global_var_decl_c, global_var_spec, type_specification) // TODO!! /* AT direct_variable */ // SYM_REF2(location_c, direct_variable, unused) void *search_var_instance_decl_c::visit(location_c *symbol) { if (compare_identifiers(symbol->direct_variable, search_name) == 0) return current_type_decl; else return NULL; } /*| global_var_list ',' global_var_name */ // SYM_LIST(global_var_list_c) // TODO!! /* var1_list ':' single_byte_string_spec */ // SYM_REF2(single_byte_string_var_declaration_c, var1_list, single_byte_string_spec) void *search_var_instance_decl_c::visit(single_byte_string_var_declaration_c *symbol) { current_type_decl = symbol->single_byte_string_spec; return symbol->var1_list->accept(*this); } /* STRING ['[' integer ']'] [ASSIGN single_byte_character_string] */ /* integer ->may be NULL ! */ /* single_byte_character_string ->may be NULL ! */ // SYM_REF2(single_byte_string_spec_c, integer, single_byte_character_string) // TODO!! /* var1_list ':' double_byte_string_spec */ // SYM_REF2(double_byte_string_var_declaration_c, var1_list, double_byte_string_spec) void *search_var_instance_decl_c::visit(double_byte_string_var_declaration_c *symbol) { current_type_decl = symbol->double_byte_string_spec; return symbol->var1_list->accept(*this); } /* WSTRING ['[' integer ']'] [ASSIGN double_byte_character_string] */ /* integer ->may be NULL ! */ /* double_byte_character_string ->may be NULL ! */ // SYM_REF2(double_byte_string_spec_c, integer, double_byte_character_string) // TODO!! /* variable_name incompl_location ':' var_spec */ // SYM_REF4(incompl_located_var_decl_c, variable_name, incompl_location, var_spec, unused) // TODO!! /* AT incompl_location_token */ // SYM_TOKEN(incompl_location_c) // TODO!! /**************************************/ /* B.1.5 - Program organization units */ /**************************************/ /***********************/ /* B 1.5.1 - Functions */ /***********************/ // SYM_REF4(function_declaration_c, derived_function_name, type_name, var_declarations_list, function_body) void *search_var_instance_decl_c::visit(function_declaration_c *symbol) { /* functions have a variable named after themselves, to store * the variable that will be returned!! */ if (compare_identifiers(symbol->derived_function_name, search_name) == 0) return symbol->type_name; /* no need to search through all the body, so we only * visit the variable declarations...! */ return symbol->var_declarations_list->accept(*this); } /*****************************/ /* B 1.5.2 - Function Blocks */ /*****************************/ /* FUNCTION_BLOCK derived_function_block_name io_OR_other_var_declarations function_block_body END_FUNCTION_BLOCK */ // SYM_REF3(function_block_declaration_c, fblock_name, var_declarations, fblock_body) void *search_var_instance_decl_c::visit(function_block_declaration_c *symbol) { /* visit the variable declarations...! */ void *res = symbol->var_declarations->accept(*this); if (NULL != res) return res; /* not yet found, so we look into the body, to see if it is an SFC step! */ return symbol->fblock_body->accept(*this); } /**********************/ /* B 1.5.3 - Programs */ /**********************/ /* PROGRAM program_type_name program_var_declarations_list function_block_body END_PROGRAM */ // SYM_REF3(program_declaration_c, program_type_name, var_declarations, function_block_body) void *search_var_instance_decl_c::visit(program_declaration_c *symbol) { /* visit the variable declarations...! */ void *res = symbol->var_declarations->accept(*this); if (NULL != res) return res; /* not yet found, so we look into the body, to see if it is an SFC step! */ return symbol->function_block_body->accept(*this); } /*********************************************/ /* B.1.6 Sequential function chart elements */ /*********************************************/ /* | sequential_function_chart sfc_network */ // SYM_LIST(sequential_function_chart_c) /* search_var_instance_decl_c inherits from serach_visitor_c, so no need to implement the following method. */ // void *search_var_instance_decl_c::visit(sequential_function_chart_c *symbol) {...} /* initial_step {step | transition | action} */ // SYM_LIST(sfc_network_c) /* search_var_instance_decl_c inherits from serach_visitor_c, so no need to implement the following method. */ // void *search_var_instance_decl_c::visit(sfc_network_c *symbol) {...} /* INITIAL_STEP step_name ':' action_association_list END_STEP */ // SYM_REF2(initial_step_c, step_name, action_association_list) void *search_var_instance_decl_c::visit(initial_step_c *symbol) { if (compare_identifiers(symbol->step_name, search_name) == 0) return symbol; return NULL; } /* STEP step_name ':' action_association_list END_STEP */ // SYM_REF2(step_c, step_name, action_association_list) void *search_var_instance_decl_c::visit(step_c *symbol) { if (compare_identifiers(symbol->step_name, search_name) == 0) return symbol; return NULL; } /********************************/ /* B 1.7 Configuration elements */ /********************************/ /* CONFIGURATION configuration_name optional_global_var_declarations (resource_declaration_list | single_resource_declaration) optional_access_declarations optional_instance_specific_initializations END_CONFIGURATION */ /* SYM_REF6(configuration_declaration_c, configuration_name, global_var_declarations, resource_declarations, access_declarations, instance_specific_initializations, unused) */ void *search_var_instance_decl_c::visit(configuration_declaration_c *symbol) { /* no need to search through all the configuration, so we only * visit the global variable declarations...! */ if (symbol->global_var_declarations != NULL) return symbol->global_var_declarations->accept(*this); else return NULL; } /* RESOURCE resource_name ON resource_type_name optional_global_var_declarations single_resource_declaration END_RESOURCE */ // SYM_REF4(resource_declaration_c, resource_name, resource_type_name, global_var_declarations, resource_declaration) void *search_var_instance_decl_c::visit(resource_declaration_c *symbol) { /* no need to search through all the resource, so we only * visit the global variable declarations...! */ if (symbol->global_var_declarations != NULL) return symbol->global_var_declarations->accept(*this); else return NULL; } /* task_configuration_list program_configuration_list */ // SYM_REF2(single_resource_declaration_c, task_configuration_list, program_configuration_list) void *search_var_instance_decl_c::visit(single_resource_declaration_c *symbol) { /* no need to search through all the resource, * and there is no global variable declarations...! */ return NULL; } /****************************************/ /* B.2 - Language IL (Instruction List) */ /****************************************/ /***********************************/ /* B 2.1 Instructions and Operands */ /***********************************/ /*| instruction_list il_instruction */ // SYM_LIST(instruction_list_c) void *search_var_instance_decl_c::visit(instruction_list_c *symbol) { /* IL code does not contain any variable declarations! */ return NULL; } /***************************************/ /* B.3 - Language ST (Structured Text) */ /***************************************/ /********************/ /* B 3.2 Statements */ /********************/ // SYM_LIST(statement_list_c) void *search_var_instance_decl_c::visit(statement_list_c *symbol) { /* ST code does not contain any variable declarations! */ return NULL; }
22,616
C++
.cc
562
37.843416
175
0.685883
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,678
generate_iec.cc
nucleron_matiec/stage4/generate_iec/generate_iec.cc
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2003-2011 Mario de Sousa (msousa@fe.up.pt) * Copyright (C) 2007-2011 Laurent Bessard and Edouard Tisserant * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* * Code to be included into the code generated by the 4th stage. * * This is part of the 4th stage that generates * a ST and IL source program equivalent to the IL and ST * code. * This is expected to be used mainly in debuging the syntax * and lexical parser, and as a starting point for other * 4th stages. */ /* Compile with the following option, to print out the const_value of each symbol, which was filled in by constant_folding_c during stage3 */ // #define DEBUG_CONST_VALUE // #include <stdio.h> /* required for NULL */ #include <string> #include <iostream> #include <sstream> #include <typeinfo> #include "generate_iec.hh" #include "../stage4.hh" #include "../../main.hh" // required for ERROR() and ERROR_MSG() macros. /***********************************************************************/ /***********************************************************************/ /***********************************************************************/ /***********************************************************************/ /* Parse command line options passed from main.c !! */ int stage4_parse_options(char *options) {return 0;} void stage4_print_options(void) { printf(" (no options available when generating IEC 61131-3 code)\n"); } /***********************************************************************/ /***********************************************************************/ /***********************************************************************/ /***********************************************************************/ //class generate_iec_c: public iterator_visitor_c { class generate_iec_c: public visitor_c { private: stage4out_c &s4o; public: generate_iec_c(stage4out_c *s4o_ptr): s4o(*s4o_ptr) {} ~generate_iec_c(void) {} private: void print_const_value(symbol_c *symbol) { #ifdef DEBUG_CONST_VALUE if (NULL == symbol) return; bool first = true; if (NULL != symbol->const_value_uint64) { first?s4o.print("{"):s4o.print("; "); first = false; s4o.print("uint64:"); if (symbol->const_value_uint64->status == symbol_c::cs_const_value) s4o.print_uint64(symbol->const_value_uint64->value); if (symbol->const_value_uint64->status == symbol_c::cs_overflow) s4o.print("OVERFLOW"); } if (NULL != symbol->const_value_int64) { first?s4o.print("{"):s4o.print("; "); first = false; s4o.print("int64:"); if (symbol->const_value_int64->status == symbol_c::cs_const_value) s4o.print_int64(symbol->const_value_int64->value); if (symbol->const_value_int64->status == symbol_c::cs_overflow) s4o.print("OVERFLOW"); } if (NULL != symbol->const_value_real64) { first?s4o.print("{"):s4o.print("; "); first = false; s4o.print("real64:"); if (symbol->const_value_real64->status == symbol_c::cs_const_value) s4o.print_real64(symbol->const_value_real64->value); if (symbol->const_value_real64->status == symbol_c::cs_overflow) s4o.print("OVERFLOW"); } if (NULL != symbol->const_value_bool) { first?s4o.print("{"):s4o.print("; "); first = false; s4o.print("bool:"); if (symbol->const_value_bool->status == symbol_c::cs_const_value) s4o.print((symbol->const_value_bool->value)?"true":"false"); if (symbol->const_value_bool->status == symbol_c::cs_overflow) s4o.print("OVERFLOW"); } if (!first) s4o.print("}"); #endif return; } void *print_token(token_c *token) { print_const_value(token); return s4o.print(token->value); } void *print_literal(symbol_c *type, symbol_c *value) { print_const_value(value); if (NULL != type) { type->accept(*this); s4o.print("#"); } value->accept(*this); return NULL; } void *print_list(list_c *list, std::string pre_elem_str = "", std::string inter_elem_str = "", std::string post_elem_str = "") { if (list->n > 0) { s4o.print(pre_elem_str); list->get_element(0)->accept(*this); } for(int i = 1; i < list->n; i++) { s4o.print(inter_elem_str); list->get_element(i)->accept(*this); } if (list->n > 0) s4o.print(post_elem_str); return NULL; } void *print_binary_expression(symbol_c *symbol, symbol_c *l_exp, symbol_c *r_exp, const char *operation) { print_const_value(symbol); s4o.print("("); l_exp->accept(*this); s4o.print(operation); r_exp->accept(*this); s4o.print(")"); return NULL; } void *print_unary_expression(symbol_c *symbol, symbol_c *exp, const char *operation) { print_const_value(symbol); s4o.print(operation); exp->accept(*this); return NULL; } public: /* EN/ENO */ #if 0 void *visit(en_param_c *symbol) { s4o.print("EN"); return NULL; } void *visit(eno_param_c *symbol) { s4o.print("ENO"); return NULL; } void *visit(en_param_c *symbol) { return symbol->param_name->accept(*this); } void *visit(eno_param_c *symbol) { return symbol->param_name->accept(*this); } #endif /* A class used to identify an entry (literal, variable, etc...) in the abstract syntax tree with an invalid data type */ /* This is only used from stage3 onwards. Stages 1 and 2 will never create any instances of invalid_type_name_c */ // SYM_REF0(invalid_type_name_c) void *visit(invalid_type_name_c *symbol) { ERROR; return NULL; } /******************/ /* 2.1.6 Pragmas */ /******************/ void *visit(enable_code_generation_pragma_c*) {s4o.print("{enable code generation}"); return NULL;} void *visit(disable_code_generation_pragma_c*) {s4o.print("{disable code generation}"); return NULL;} void *visit(pragma_c *symbol) {return print_token(symbol);} /***************************/ /* B 0 - Programming Model */ /***************************/ void *visit(library_c *symbol) {return print_list(symbol);} /*******************************************/ /* B 1.1 - Letters, digits and identifiers */ /*******************************************/ void *visit( identifier_c *symbol) {return print_token(symbol);} void *visit(derived_datatype_identifier_c *symbol) {return print_token(symbol);} void *visit( poutype_identifier_c *symbol) {return print_token(symbol);} /*********************/ /* B 1.2 - Constants */ /*********************/ /*********************************/ /* B 1.2.XX - Reference Literals */ /*********************************/ /* defined in IEC 61131-3 v3 - Basically the 'NULL' keyword! */ void *visit(ref_value_null_literal_c *symbol) {s4o.print("NULL"); return NULL;} /******************************/ /* B 1.2.1 - Numeric Literals */ /******************************/ void *visit(real_c *symbol) {return print_token(symbol);} void *visit(neg_real_c *symbol) {return print_unary_expression(symbol, symbol->exp, "-");} void *visit(integer_c *symbol) {return print_token(symbol);} void *visit(neg_integer_c *symbol) {return print_unary_expression(symbol, symbol->exp, "-");} void *visit(binary_integer_c *symbol) {return print_token(symbol);} void *visit(octal_integer_c *symbol) {return print_token(symbol);} void *visit(hex_integer_c *symbol) {return print_token(symbol);} void *visit(integer_literal_c *symbol) {return print_literal(symbol->type, symbol->value);} void *visit(real_literal_c *symbol) {return print_literal(symbol->type, symbol->value);} void *visit(bit_string_literal_c *symbol) {return print_literal(symbol->type, symbol->value);} void *visit(boolean_literal_c *symbol) {return print_literal(symbol->type, symbol->value);} /* helper class for boolean_literal_c */ void *visit(boolean_true_c *symbol) {s4o.print(/*"TRUE" */"1"); return NULL;} void *visit(boolean_false_c *symbol) {s4o.print(/*"FALSE"*/"0"); return NULL;} /*******************************/ /* B.1.2.2 Character Strings */ /*******************************/ void *visit(double_byte_character_string_c *symbol) {return print_token(symbol);} void *visit(single_byte_character_string_c *symbol) {return print_token(symbol);} /***************************/ /* B 1.2.3 - Time Literals */ /***************************/ /************************/ /* B 1.2.3.1 - Duration */ /************************/ void *visit(neg_time_c *symbol) {s4o.print("-"); return NULL;} void *visit(duration_c *symbol) { s4o.print("TIME#"); if (symbol->neg != NULL) symbol->neg->accept(*this); symbol->interval->accept(*this); return NULL; } void *visit(fixed_point_c *symbol) {return print_token(symbol);} /* SYM_REF5(interval_c, days, hours, minutes, seconds, milliseconds) */ void *visit(interval_c *symbol) { if (NULL != symbol->days) { symbol->days->accept(*this); s4o.print("d"); } if (NULL != symbol->hours) { symbol->hours->accept(*this); s4o.print("h"); } if (NULL != symbol->minutes) { symbol->minutes->accept(*this); s4o.print("m"); } if (NULL != symbol->seconds) { symbol->seconds->accept(*this); s4o.print("s"); } if (NULL != symbol->milliseconds) { symbol->milliseconds->accept(*this); s4o.print("ms"); } return NULL; } /************************************/ /* B 1.2.3.2 - Time of day and Date */ /************************************/ void *visit(time_of_day_c *symbol) { s4o.print("TIME_OF_DAY#"); symbol->daytime->accept(*this); return NULL; } void *visit(daytime_c *symbol) { symbol->day_hour->accept(*this); s4o.print(":"); symbol->day_minute->accept(*this); s4o.print(":"); symbol->day_second->accept(*this); return NULL; } void *visit(date_c *symbol) { s4o.print("DATE#"); symbol->date_literal->accept(*this); return NULL; } void *visit(date_literal_c *symbol) { symbol->year->accept(*this); s4o.print("-"); symbol->month->accept(*this); s4o.print("-"); symbol->day->accept(*this); return NULL; } void *visit(date_and_time_c *symbol) { s4o.print("DATE_AND_TIME#"); symbol->date_literal->accept(*this); s4o.print("-"); symbol->daytime->accept(*this); return NULL; } /***********************************/ /* B 1.3.1 - Elementary Data Types */ /***********************************/ void *visit( time_type_name_c *symbol) {s4o.print("TIME"); return NULL;} void *visit( bool_type_name_c *symbol) {s4o.print("BOOL"); return NULL;} void *visit( sint_type_name_c *symbol) {s4o.print("SINT"); return NULL;} void *visit( int_type_name_c *symbol) {s4o.print("INT"); return NULL;} void *visit( dint_type_name_c *symbol) {s4o.print("DINT"); return NULL;} void *visit( lint_type_name_c *symbol) {s4o.print("LINT"); return NULL;} void *visit( usint_type_name_c *symbol) {s4o.print("USINT"); return NULL;} void *visit( uint_type_name_c *symbol) {s4o.print("UINT"); return NULL;} void *visit( udint_type_name_c *symbol) {s4o.print("UDINT"); return NULL;} void *visit( ulint_type_name_c *symbol) {s4o.print("ULINT"); return NULL;} void *visit( real_type_name_c *symbol) {s4o.print("REAL"); return NULL;} void *visit( lreal_type_name_c *symbol) {s4o.print("LREAL"); return NULL;} void *visit( date_type_name_c *symbol) {s4o.print("DATE"); return NULL;} void *visit( tod_type_name_c *symbol) {s4o.print("TOD"); return NULL;} void *visit( dt_type_name_c *symbol) {s4o.print("DT"); return NULL;} void *visit( byte_type_name_c *symbol) {s4o.print("BYTE"); return NULL;} void *visit( word_type_name_c *symbol) {s4o.print("WORD"); return NULL;} void *visit( lword_type_name_c *symbol) {s4o.print("LWORD"); return NULL;} void *visit( dword_type_name_c *symbol) {s4o.print("DWORD"); return NULL;} void *visit( string_type_name_c *symbol) {s4o.print("STRING"); return NULL;} void *visit( wstring_type_name_c *symbol) {s4o.print("WSTRING"); return NULL;} void *visit( void_type_name_c *symbol) {s4o.print("VOID"); return NULL;} /* a non-standard extension! */ void *visit( safetime_type_name_c *symbol) {s4o.print("SAFETIME"); return NULL;} void *visit( safebool_type_name_c *symbol) {s4o.print("SAFEBOOL"); return NULL;} void *visit( safesint_type_name_c *symbol) {s4o.print("SAFESINT"); return NULL;} void *visit( safeint_type_name_c *symbol) {s4o.print("SAFEINT"); return NULL;} void *visit( safedint_type_name_c *symbol) {s4o.print("SAFEDINT"); return NULL;} void *visit( safelint_type_name_c *symbol) {s4o.print("SAFELINT"); return NULL;} void *visit( safeusint_type_name_c *symbol) {s4o.print("SAFEUSINT"); return NULL;} void *visit( safeuint_type_name_c *symbol) {s4o.print("SAFEUINT"); return NULL;} void *visit( safeudint_type_name_c *symbol) {s4o.print("SAFEUDINT"); return NULL;} void *visit( safeulint_type_name_c *symbol) {s4o.print("SAFEULINT"); return NULL;} void *visit( safereal_type_name_c *symbol) {s4o.print("SAFEREAL"); return NULL;} void *visit( safelreal_type_name_c *symbol) {s4o.print("SAFELREAL"); return NULL;} void *visit( safedate_type_name_c *symbol) {s4o.print("SAFEDATE"); return NULL;} void *visit( safetod_type_name_c *symbol) {s4o.print("SAFETOD"); return NULL;} void *visit( safedt_type_name_c *symbol) {s4o.print("SAFEDT"); return NULL;} void *visit( safebyte_type_name_c *symbol) {s4o.print("SAFEBYTE"); return NULL;} void *visit( safeword_type_name_c *symbol) {s4o.print("SAFEWORD"); return NULL;} void *visit( safelword_type_name_c *symbol) {s4o.print("SAFELWORD"); return NULL;} void *visit( safedword_type_name_c *symbol) {s4o.print("SAFEDWORD"); return NULL;} void *visit( safestring_type_name_c *symbol) {s4o.print("SAFESTRING"); return NULL;} void *visit(safewstring_type_name_c *symbol) {s4o.print("SAFEWSTRING"); return NULL;} /********************************/ /* B.1.3.2 - Generic data types */ /********************************/ void *visit(generic_type_any_c *symbol) {s4o.print("ANY"); return NULL;} /********************************/ /* B 1.3.3 - Derived data types */ /********************************/ /* TYPE type_declaration_list END_TYPE */ void *visit(data_type_declaration_c *symbol) { s4o.print("TYPE\n"); s4o.indent_right(); symbol->type_declaration_list->accept(*this); s4o.indent_left(); s4o.print("END_TYPE\n\n\n"); return NULL; } /* helper symbol for data_type_declaration */ /*| type_declaration_list type_declaration ';' */ void *visit(type_declaration_list_c *symbol) { return print_list(symbol, s4o.indent_spaces, ";\n" + s4o.indent_spaces, ";\n"); } /* simple_type_name ':' simple_spec_init */ void *visit(simple_type_declaration_c *symbol) { symbol->simple_type_name->accept(*this); s4o.print(" : "); symbol->simple_spec_init->accept(*this); return NULL; } /* simple_specification ASSIGN constant */ void *visit(simple_spec_init_c *symbol) { symbol->simple_specification->accept(*this); if (symbol->constant != NULL) { s4o.print(" := "); symbol->constant->accept(*this); } return NULL; } /* subrange_type_name ':' subrange_spec_init */ void *visit(subrange_type_declaration_c *symbol) { symbol->subrange_type_name->accept(*this); s4o.print(" : "); symbol->subrange_spec_init->accept(*this); return NULL; } /* subrange_specification ASSIGN signed_integer */ void *visit(subrange_spec_init_c *symbol) { symbol->subrange_specification->accept(*this); if (symbol->signed_integer != NULL) { s4o.print(" := "); symbol->signed_integer->accept(*this); } return NULL; } /* integer_type_name '(' subrange')' */ void *visit(subrange_specification_c *symbol) { symbol->integer_type_name->accept(*this); if (symbol->subrange != NULL) { s4o.print("("); symbol->subrange->accept(*this); s4o.print(")"); } return NULL; } /* signed_integer DOTDOT signed_integer */ void *visit(subrange_c *symbol) { symbol->lower_limit->accept(*this); s4o.print(" .. "); symbol->upper_limit->accept(*this); return NULL; } /* enumerated_type_name ':' enumerated_spec_init */ void *visit(enumerated_type_declaration_c *symbol) { symbol->enumerated_type_name->accept(*this); s4o.print(" : "); symbol->enumerated_spec_init->accept(*this); return NULL; } /* enumerated_specification ASSIGN enumerated_value */ void *visit(enumerated_spec_init_c *symbol) { symbol->enumerated_specification->accept(*this); if (symbol->enumerated_value != NULL) { s4o.print(" := "); symbol->enumerated_value->accept(*this); } return NULL; } /* helper symbol for enumerated_specification->enumerated_spec_init */ /* enumerated_value_list ',' enumerated_value */ void *visit(enumerated_value_list_c *symbol) {print_list(symbol, "(", ", ", ")"); return NULL;} /* enumerated_type_name '#' identifier */ void *visit(enumerated_value_c *symbol) { if (symbol->type != NULL) { symbol->type->accept(*this); s4o.print("#"); } symbol->value->accept(*this); return NULL; } /* identifier ':' array_spec_init */ void *visit(array_type_declaration_c *symbol) { symbol->identifier->accept(*this); s4o.print(" : "); symbol->array_spec_init->accept(*this); return NULL; } /* array_specification [ASSIGN array_initialization} */ /* array_initialization may be NULL ! */ void *visit(array_spec_init_c *symbol) { symbol->array_specification->accept(*this); if (symbol->array_initialization != NULL) { s4o.print(" := "); symbol->array_initialization->accept(*this); } return NULL; } /* ARRAY '[' array_subrange_list ']' OF non_generic_type_name */ void *visit(array_specification_c *symbol) { s4o.print("ARRAY ["); symbol->array_subrange_list->accept(*this); s4o.print("] OF "); symbol->non_generic_type_name->accept(*this); return NULL; } /* helper symbol for array_specification */ /* array_subrange_list ',' subrange */ void *visit(array_subrange_list_c *symbol) {print_list(symbol, "", ", "); return NULL;} /* helper symbol for array_initialization */ /* array_initial_elements_list ',' array_initial_elements */ void *visit(array_initial_elements_list_c *symbol) {print_list(symbol, "[", ", ", "]"); return NULL;} /* integer '(' [array_initial_element] ')' */ /* array_initial_element may be NULL ! */ void *visit(array_initial_elements_c *symbol) { symbol->integer->accept(*this); s4o.print("("); if (symbol->array_initial_element != NULL) symbol->array_initial_element->accept(*this); s4o.print(")"); return NULL; } /* structure_type_name ':' structure_specification */ void *visit(structure_type_declaration_c *symbol) { symbol->structure_type_name->accept(*this); s4o.print(" : "); symbol->structure_specification->accept(*this); return NULL; } /* structure_type_name ASSIGN structure_initialization */ /* structure_initialization may be NULL ! */ void *visit(initialized_structure_c *symbol) { symbol->structure_type_name->accept(*this); if (symbol->structure_initialization != NULL) { s4o.print(" := "); symbol->structure_initialization->accept(*this); } return NULL; } /* helper symbol for structure_declaration */ /* structure_declaration: STRUCT structure_element_declaration_list END_STRUCT */ /* structure_element_declaration_list structure_element_declaration ';' */ void *visit(structure_element_declaration_list_c *symbol) { s4o.print("STRUCT\n"); s4o.indent_right(); print_list(symbol, s4o.indent_spaces, ";\n" + s4o.indent_spaces, ";\n" + s4o.indent_spaces); s4o.print("END_STRUCT"); s4o.indent_left(); return NULL; } /* structure_element_name ':' *_spec_init */ void *visit(structure_element_declaration_c *symbol) { symbol->structure_element_name->accept(*this); s4o.print(" : "); symbol->spec_init->accept(*this); return NULL; } /* helper symbol for structure_initialization */ /* structure_initialization: '(' structure_element_initialization_list ')' */ /* structure_element_initialization_list ',' structure_element_initialization */ void *visit(structure_element_initialization_list_c *symbol) {print_list(symbol, "(", ", ", ")"); return NULL;} /* structure_element_name ASSIGN value */ void *visit(structure_element_initialization_c *symbol) { symbol->structure_element_name->accept(*this); s4o.print(" := "); symbol->value->accept(*this); return NULL; } /* string_type_name ':' elementary_string_type_name string_type_declaration_size string_type_declaration_init */ void *visit(string_type_declaration_c *symbol) { symbol->string_type_name->accept(*this); s4o.print(" : "); symbol->elementary_string_type_name->accept(*this); symbol->string_type_declaration_size->accept(*this); if (symbol->string_type_declaration_init != NULL) symbol->string_type_declaration_init->accept(*this); return NULL; } /* function_block_type_name ASSIGN structure_initialization */ /* structure_initialization -> may be NULL ! */ void *visit(fb_spec_init_c *symbol) { symbol->function_block_type_name->accept(*this); if (symbol->structure_initialization != NULL) { s4o.print(" := "); symbol->structure_initialization->accept(*this); } return NULL; } /* ref_spec: REF_TO (non_generic_type_name | function_block_type_name) */ // SYM_REF1(ref_spec_c, type_name) void *visit(ref_spec_c *symbol) { s4o.print("REF_TO "); symbol->type_name->accept(*this); return NULL; } /* For the moment, we do not support initialising reference data types */ /* ref_spec_init: ref_spec [ ASSIGN ref_initialization ]; */ /* NOTE: ref_initialization may be NULL!! */ // SYM_REF2(ref_spec_init_c, ref_spec, ref_initialization) void *visit(ref_spec_init_c *symbol) { symbol->ref_spec->accept(*this); if (symbol->ref_initialization != NULL) { s4o.print(" := "); symbol->ref_initialization->accept(*this); } return NULL; } /* ref_type_decl: identifier ':' ref_spec_init */ // SYM_REF2(ref_type_decl_c, ref_type_name, ref_spec_init) void *visit(ref_type_decl_c *symbol) { symbol->ref_type_name->accept(*this); s4o.print(" : "); symbol->ref_spec_init->accept(*this); return NULL; } /*********************/ /* B 1.4 - Variables */ /*********************/ void *visit(symbolic_variable_c *symbol) {return symbol->var_name->accept(*this);} void *visit(symbolic_constant_c *symbol) {return symbol->var_name->accept(*this);} /********************************************/ /* B.1.4.1 Directly Represented Variables */ /********************************************/ void *visit(direct_variable_c *symbol) {return print_token(symbol);} /*************************************/ /* B.1.4.2 Multi-element Variables */ /*************************************/ /* subscripted_variable '[' subscript_list ']' */ void *visit(array_variable_c *symbol) { symbol->subscripted_variable->accept(*this); s4o.print("["); symbol->subscript_list->accept(*this); s4o.print("]"); return NULL; } /* subscript_list ',' subscript */ void *visit(subscript_list_c *symbol) {return print_list(symbol, "", ", ");} /* record_variable '.' field_selector */ void *visit(structured_variable_c *symbol) { symbol->record_variable->accept(*this); s4o.print("."); symbol->field_selector->accept(*this); return NULL; } /******************************************/ /* B 1.4.3 - Declaration & Initialisation */ /******************************************/ void *visit(constant_option_c *symbol) {s4o.print("CONSTANT"); return NULL;} void *visit(retain_option_c *symbol) {s4o.print("RETAIN"); return NULL;} void *visit(non_retain_option_c *symbol) {s4o.print("NON_RETAIN"); return NULL;} /* VAR_INPUT [RETAIN | NON_RETAIN] input_declaration_list END_VAR */ /* option -> the RETAIN/NON_RETAIN/<NULL> directive... */ void *visit(input_declarations_c *symbol) { if (typeid(*(symbol->method)) == typeid(explicit_definition_c)) { s4o.print(s4o.indent_spaces); s4o.print("VAR_INPUT "); if (symbol->option != NULL) symbol->option->accept(*this); s4o.print("\n"); s4o.indent_right(); symbol->input_declaration_list->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("END_VAR\n"); } return NULL; } /* helper symbol for input_declarations */ /*| input_declaration_list input_declaration ';' */ void *visit(input_declaration_list_c *symbol) { return print_list(symbol, s4o.indent_spaces, ";\n" + s4o.indent_spaces, ";\n"); } /* edge -> The F_EDGE or R_EDGE directive */ void *visit(edge_declaration_c *symbol) { symbol->var1_list->accept(*this); s4o.print(" : BOOL "); symbol->edge->accept(*this); return NULL; } /* dummy classes only used as flags! */ void *visit(explicit_definition_c *symbol) {return NULL;} void *visit(implicit_definition_c *symbol) {return NULL;} /* EN : BOOL := 1 */ void *visit(en_param_declaration_c *symbol) { if (typeid(*(symbol->method)) == typeid(explicit_definition_c)) { symbol->name->accept(*this); s4o.print(" : "); symbol->type_decl->accept(*this); } return NULL; } /* ENO : BOOL */ void *visit(eno_param_declaration_c *symbol) { if (typeid(*(symbol->method)) == typeid(explicit_definition_c)) { symbol->name->accept(*this); s4o.print(" : "); symbol->type->accept(*this); } return NULL; } void *visit(raising_edge_option_c *symbol) { s4o.print("R_EDGE"); return NULL; } void *visit(falling_edge_option_c *symbol) { s4o.print("F_EDGE"); return NULL; } /* var1_list is one of the following... * simple_spec_init_c * * subrange_spec_init_c * * enumerated_spec_init_c * */ void *visit(var1_init_decl_c *symbol) { symbol->var1_list->accept(*this); s4o.print(" : "); symbol->spec_init->accept(*this); return NULL; } void *visit(var1_list_c *symbol) {return print_list(symbol, "", ", ");} /* | [var1_list ','] variable_name '..' */ /* NOTE: This is an extension to the standard!!! */ /* In order to be able to handle extensible standard functions * (i.e. standard functions that may have a variable number of * input parameters, such as AND(word#33, word#44, word#55, word#66), * we have extended the acceptable syntax to allow var_name '..' * in an input variable declaration. * * This allows us to parse the declaration of standard * extensible functions and load their interface definition * into the abstract syntax tree just like we do to other * user defined functions. * This has the advantage that we can later do semantic * checking of calls to functions (be it a standard or user defined * function) in (almost) exactly the same way. * * Of course, we have a flag that disables this syntax when parsing user * written code, so we only allow this extra syntax while parsing the * 'header' file that declares all the standard IEC 61131-3 functions. */ void *visit(extensible_input_parameter_c *symbol) { symbol->var_name->accept(*this); s4o.print(" .. "); return NULL; } /* var1_list ':' array_spec_init */ void *visit(array_var_init_decl_c *symbol) { symbol->var1_list->accept(*this); s4o.print(" : "); symbol->array_spec_init->accept(*this); return NULL; } /* var1_list ':' initialized_structure */ void *visit(structured_var_init_decl_c *symbol) { symbol->var1_list->accept(*this); s4o.print(" : "); symbol->initialized_structure->accept(*this); return NULL; } /* name_list ':' function_block_type_name ASSIGN structure_initialization */ /* structure_initialization -> may be NULL ! */ void *visit(fb_name_decl_c *symbol) { symbol->fb_name_list->accept(*this); s4o.print(" : "); symbol->fb_spec_init->accept(*this); return NULL; } /* name_list ',' fb_name */ void *visit(fb_name_list_c *symbol) {return print_list(symbol, "", ", ");} /* VAR_OUTPUT [RETAIN | NON_RETAIN] var_init_decl_list END_VAR */ /* option -> may be NULL ! */ void *visit(output_declarations_c *symbol) { if (typeid(*(symbol->method)) == typeid(explicit_definition_c)) { s4o.print(s4o.indent_spaces); s4o.print("VAR_OUTPUT "); if (symbol->option != NULL) symbol->option->accept(*this); s4o.print("\n"); s4o.indent_right(); symbol->var_init_decl_list->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("END_VAR\n"); } return NULL; } /* VAR_IN_OUT END_VAR */ void *visit(input_output_declarations_c *symbol) { s4o.print(s4o.indent_spaces); s4o.print("VAR_IN_OUT "); s4o.print("\n"); s4o.indent_right(); symbol->var_declaration_list->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("END_VAR\n"); return NULL; } /* helper symbol for input_output_declarations */ /* var_declaration_list var_declaration ';' */ void *visit(var_declaration_list_c *symbol) { return print_list(symbol, s4o.indent_spaces, ";\n" + s4o.indent_spaces, ";\n"); } /* var1_list ':' array_specification */ void *visit(array_var_declaration_c *symbol) { symbol->var1_list->accept(*this); s4o.print(" : "); symbol->array_specification->accept(*this); return NULL; } /* var1_list ':' structure_type_name */ void *visit(structured_var_declaration_c *symbol) { symbol->var1_list->accept(*this); s4o.print(" : "); symbol->structure_type_name->accept(*this); return NULL; } /* VAR [CONSTANT] var_init_decl_list END_VAR */ /* option -> may be NULL ! */ void *visit(var_declarations_c *symbol) { s4o.print(s4o.indent_spaces); s4o.print("VAR "); if (symbol->option != NULL) symbol->option->accept(*this); s4o.print("\n"); s4o.indent_right(); symbol->var_init_decl_list->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("END_VAR\n"); return NULL; } /* VAR RETAIN var_init_decl_list END_VAR */ void *visit(retentive_var_declarations_c *symbol) { s4o.print(s4o.indent_spaces); s4o.print("VAR RETAIN "); s4o.print("\n"); s4o.indent_right(); symbol->var_init_decl_list->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("END_VAR\n"); return NULL; } /* VAR [CONSTANT|RETAIN|NON_RETAIN] located_var_decl_list END_VAR */ /* option -> may be NULL ! */ void *visit(located_var_declarations_c *symbol) { s4o.print(s4o.indent_spaces); s4o.print("VAR "); if (symbol->option != NULL) symbol->option->accept(*this); s4o.print("\n"); s4o.indent_right(); symbol->located_var_decl_list->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("END_VAR\n"); return NULL; } /* helper symbol for located_var_declarations */ /* located_var_decl_list located_var_decl ';' */ void *visit(located_var_decl_list_c *symbol) { return print_list(symbol, s4o.indent_spaces, ";\n" + s4o.indent_spaces, ";\n"); } /* [variable_name] location ':' located_var_spec_init */ /* variable_name -> may be NULL ! */ void *visit(located_var_decl_c *symbol) { if (symbol->variable_name != NULL) { symbol->variable_name->accept(*this); s4o.print(" "); } symbol->location->accept(*this); s4o.print(" : "); symbol->located_var_spec_init->accept(*this); return NULL; } /*| VAR_EXTERNAL [CONSTANT] external_declaration_list END_VAR */ /* option -> may be NULL ! */ void *visit(external_var_declarations_c *symbol) { s4o.print(s4o.indent_spaces); s4o.print("VAR_EXTERNAL "); if (symbol->option != NULL) symbol->option->accept(*this); s4o.print("\n"); s4o.indent_right(); symbol->external_declaration_list->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("END_VAR\n"); return NULL; } /* helper symbol for external_var_declarations */ /*| external_declaration_list external_declaration';' */ void *visit(external_declaration_list_c *symbol) { return print_list(symbol, s4o.indent_spaces, ";\n" + s4o.indent_spaces, ";\n"); } /* global_var_name ':' (simple_specification|subrange_specification|enumerated_specification|array_specification|prev_declared_structure_type_name|function_block_type_name) */ void *visit(external_declaration_c *symbol) { symbol->global_var_name->accept(*this); s4o.print(" : "); symbol->specification->accept(*this); return NULL; } /*| VAR_GLOBAL [CONSTANT|RETAIN] global_var_decl_list END_VAR */ /* option -> may be NULL ! */ void *visit(global_var_declarations_c *symbol) { s4o.print(s4o.indent_spaces); s4o.print("VAR_GLOBAL "); if (symbol->option != NULL) symbol->option->accept(*this); s4o.print("\n"); s4o.indent_right(); symbol->global_var_decl_list->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("END_VAR\n"); return NULL; } /* helper symbol for global_var_declarations */ /*| global_var_decl_list global_var_decl ';' */ void *visit(global_var_decl_list_c *symbol) { return print_list(symbol, s4o.indent_spaces, ";\n" + s4o.indent_spaces, ";\n"); } /*| global_var_spec ':' [located_var_spec_init|function_block_type_name] */ /* type_specification ->may be NULL ! */ void *visit(global_var_decl_c *symbol) { symbol->global_var_spec->accept(*this); s4o.print(" : "); if (symbol->type_specification != NULL) symbol->type_specification->accept(*this); return NULL; } /*| global_var_name location */ void *visit(global_var_spec_c *symbol) { symbol->global_var_name->accept(*this); s4o.print(" "); symbol->location->accept(*this); return NULL; } /* AT direct_variable */ void *visit(location_c *symbol) { s4o.print("AT "); symbol->direct_variable->accept(*this); return NULL; } /*| global_var_list ',' global_var_name */ void *visit(global_var_list_c *symbol) {return print_list(symbol, "", ", ");} /* var1_list ':' single_byte_string_spec */ void *visit(single_byte_string_var_declaration_c *symbol) { symbol->var1_list->accept(*this); s4o.print(" : "); symbol->single_byte_string_spec->accept(*this); return NULL; } /* single_byte_limited_len_string_spec [ASSIGN single_byte_character_string] */ /* single_byte_character_string ->may be NULL ! */ void *visit(single_byte_string_spec_c *symbol) { symbol->string_spec->accept(*this); if (symbol->single_byte_character_string != NULL) { s4o.print(" := "); symbol->single_byte_character_string->accept(*this); } return NULL; } /* STRING ['[' integer ']'] */ /* integer ->may be NULL ! */ void *visit(single_byte_limited_len_string_spec_c *symbol) { symbol->string_type_name->accept(*this); if (symbol->character_string_len != NULL) { s4o.print(" ["); symbol->character_string_len->accept(*this); s4o.print("]"); } return NULL; } /* var1_list ':' double_byte_string_spec */ void *visit(double_byte_string_var_declaration_c *symbol) { symbol->var1_list->accept(*this); s4o.print(" : "); symbol->double_byte_string_spec->accept(*this); return NULL; } /* double_byte_limited_len_string_spec [ASSIGN double_byte_character_string] */ /* integer ->may be NULL ! */ /* double_byte_character_string ->may be NULL ! */ void *visit(double_byte_string_spec_c *symbol) { symbol->string_spec->accept(*this); if (symbol->double_byte_character_string != NULL) { s4o.print(" := "); symbol->double_byte_character_string->accept(*this); } return NULL; } /* WSTRING ['[' integer ']'] */ /* integer ->may be NULL ! */ void *visit(double_byte_limited_len_string_spec_c *symbol) { symbol->string_type_name->accept(*this); if (symbol->character_string_len != NULL) { s4o.print(" ["); symbol->character_string_len->accept(*this); s4o.print("]"); } return NULL; } /*| VAR [RETAIN|NON_RETAIN] incompl_located_var_decl_list END_VAR */ /* option ->may be NULL ! */ void *visit(incompl_located_var_declarations_c *symbol) { s4o.print(s4o.indent_spaces); s4o.print("VAR "); if (symbol->option != NULL) symbol->option->accept(*this); s4o.print("\n"); s4o.indent_right(); symbol->incompl_located_var_decl_list->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("END_VAR\n"); return NULL; } /* helper symbol for incompl_located_var_declarations */ /*| incompl_located_var_decl_list incompl_located_var_decl ';' */ void *visit(incompl_located_var_decl_list_c *symbol) { return print_list(symbol, s4o.indent_spaces, ";\n" + s4o.indent_spaces, ";\n"); } /* variable_name incompl_location ':' var_spec */ void *visit(incompl_located_var_decl_c *symbol) { symbol->variable_name->accept(*this); s4o.print(" "); symbol->incompl_location->accept(*this); s4o.print(" : "); symbol->var_spec->accept(*this); return NULL; } /* AT incompl_location_token */ void *visit(incompl_location_c *symbol) { s4o.print(" AT "); return print_token(symbol); } /* intermediate helper symbol for: * - non_retentive_var_decls * - output_declarations */ /* | var_init_decl_list var_init_decl ';' */ void *visit(var_init_decl_list_c *symbol) { return print_list(symbol, s4o.indent_spaces, ";\n" + s4o.indent_spaces, ";\n"); } /***********************/ /* B 1.5.1 - Functions */ /***********************/ void *visit(function_declaration_c *symbol) { s4o.print("FUNCTION "); symbol->derived_function_name->accept(*this); s4o.print(" : "); symbol->type_name->accept(*this); s4o.print("\n"); s4o.indent_right(); symbol->var_declarations_list->accept(*this); s4o.print("\n"); symbol->function_body->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces + "END_FUNCTION\n\n\n"); return NULL; } /* intermediate helper symbol for function_declaration */ void *visit(var_declarations_list_c *symbol) {return print_list(symbol);} void *visit(function_var_decls_c *symbol) { //s4o.print(s4o.indent_spaces); s4o.print("VAR "); if (symbol->option != NULL) symbol->option->accept(*this); s4o.print("\n"); s4o.indent_right(); symbol->decl_list->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("END_VAR\n"); return NULL; } /* intermediate helper symbol for function_var_decls */ void *visit(var2_init_decl_list_c *symbol) { print_list(symbol, s4o.indent_spaces, ";\n" + s4o.indent_spaces, ";\n"); return NULL; } /*****************************/ /* B 1.5.2 - Function Blocks */ /*****************************/ /* FUNCTION_BLOCK derived_function_block_name io_OR_other_var_declarations function_block_body END_FUNCTION_BLOCK */ void *visit(function_block_declaration_c *symbol) { s4o.print("FUNCTION_BLOCK "); symbol->fblock_name->accept(*this); s4o.print("\n"); s4o.indent_right(); symbol->var_declarations->accept(*this); s4o.print("\n"); symbol->fblock_body->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces + "END_FUNCTION_BLOCK\n\n\n"); return NULL; } /* VAR_TEMP temp_var_decl_list END_VAR */ void *visit(temp_var_decls_c *symbol) { s4o.print("VAR_TEMP\n"); s4o.indent_right(); symbol->var_decl_list->accept(*this); s4o.indent_left(); s4o.print("END_VAR\n"); return NULL; } /* intermediate helper symbol for temp_var_decls */ void *visit(temp_var_decls_list_c *symbol) {return print_list(symbol);} /* VAR NON_RETAIN var_init_decl_list END_VAR */ void *visit(non_retentive_var_decls_c *symbol) { s4o.print("VAR NON_RETAIN\n"); s4o.indent_right(); symbol->var_decl_list->accept(*this); s4o.indent_left(); s4o.print("END_VAR\n"); return NULL; } /**********************/ /* B 1.5.3 - Programs */ /**********************/ /* PROGRAM program_type_name program_var_declarations_list function_block_body END_PROGRAM */ void *visit(program_declaration_c *symbol) { s4o.print("PROGRAM "); symbol->program_type_name->accept(*this); s4o.print("\n"); s4o.indent_right(); symbol->var_declarations->accept(*this); s4o.print("\n"); symbol->function_block_body->accept(*this); s4o.indent_left(); s4o.print("END_PROGRAM\n\n\n"); return NULL; } /***********************************/ /* B 1.6 Sequential Function Chart */ /***********************************/ /* sequential_function_chart {sfc_network} */ void *visit(sequential_function_chart_c *symbol) { print_list(symbol, "", "\n", ""); return NULL; } /* sfc_network {step | transition | action} */ void *visit(sfc_network_c *symbol) { print_list(symbol, "", "\n", ""); return NULL; } /* INITIAL_STEP step_name ':' [action_association_list] END_STEP */ void *visit(initial_step_c *symbol) { s4o.print(s4o.indent_spaces); s4o.print("INITIAL_STEP "); symbol->step_name->accept(*this); s4o.print(":\n"); s4o.indent_right(); symbol->action_association_list->accept(*this); s4o.print("\n"); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("END_STEP\n"); return NULL; } /* STEP step_name ':' [action_association_list] END_STEP */ void *visit(step_c *symbol) { s4o.print(s4o.indent_spaces); s4o.print("STEP "); symbol->step_name->accept(*this); s4o.print(":\n"); s4o.indent_right(); symbol->action_association_list->accept(*this); s4o.print("\n"); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("END_STEP\n"); return NULL; } /* action_association_list {action_association} */ void *visit(action_association_list_c *symbol) { print_list(symbol, "", "\n", ""); return NULL; } /* action_name '(' [action_qualifier] [indicator_name_list] ')' */ void *visit(action_association_c *symbol) { s4o.print(s4o.indent_spaces); symbol->action_name->accept(*this); s4o.print("("); if(symbol->action_qualifier != NULL){ symbol->action_qualifier->accept(*this); } if(symbol->indicator_name_list != NULL){ symbol->indicator_name_list->accept(*this); } s4o.print(");"); return NULL; } /* indicator_name_list ',' indicator_name */ void *visit(indicator_name_list_c *symbol) { print_list(symbol, ", ", ", ", ""); return NULL; } /* action_qualifier [',' action_time] */ void *visit(action_qualifier_c *symbol) { symbol->action_qualifier->accept(*this); if(symbol->action_time != NULL){ s4o.print(", "); symbol->action_time->accept(*this); } return NULL; } /* N | R | S | P */ void *visit(qualifier_c *symbol) { print_token(symbol); return NULL; } /* L | D | SD | DS | SL */ void *visit(timed_qualifier_c *symbol) { print_token(symbol); return NULL; } /* TRANSITION [transition_name] ['(''PRIORITY'':='integer')'] * FROMstepsTO steps * ':' simple_instr_list | ':=' expression * END_TRANSITION */ void *visit(transition_c *symbol) { s4o.print(s4o.indent_spaces); s4o.print("TRANSITION "); if (symbol->transition_name != NULL){ symbol->transition_name->accept(*this); s4o.print(" "); } if (symbol->integer != NULL){ s4o.print("(PRIORITY := "); symbol->integer->accept(*this); s4o.print(") "); } s4o.print("FROM "); symbol->from_steps->accept(*this); s4o.print(" TO "); symbol->to_steps->accept(*this); s4o.indent_right(); symbol->transition_condition->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("END_TRANSITION\n"); return NULL; } void *visit(transition_condition_c *symbol) { if (symbol->transition_condition_il != NULL) { s4o.print(":\n"); symbol->transition_condition_il->accept(*this); } if (symbol->transition_condition_st != NULL) { s4o.print("\n"); s4o.print(s4o.indent_spaces); s4o.print(":= "); symbol->transition_condition_st->accept(*this); s4o.print(";\n"); } return NULL; } /* step_name | step_name_list */ void *visit(steps_c *symbol) { if(symbol->step_name != NULL){ symbol->step_name->accept(*this); } if(symbol->step_name_list != NULL){ symbol->step_name_list->accept(*this); } return NULL; } /* '(' step_name ',' step_name {',' step_name} ')' */ void *visit(step_name_list_c *symbol) { print_list(symbol, "(", ", ", ")"); return NULL; } /* ACTION action_name ':' function_block_body END_ACTION */ void *visit(action_c *symbol) { s4o.print(s4o.indent_spaces); s4o.print("ACTION "); symbol->action_name->accept(*this); s4o.print(":\n"); s4o.indent_right(); symbol->function_block_body->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("END_ACTION\n"); return NULL; } /********************************/ /* B 1.7 Configuration elements */ /********************************/ /* CONFIGURATION configuration_name optional_global_var_declarations (resource_declaration_list | single_resource_declaration) optional_access_declarations optional_instance_specific_initializations END_CONFIGURATION */ void *visit(configuration_declaration_c *symbol) { s4o.print("CONFIGURATION "); symbol->configuration_name->accept(*this); s4o.print("\n"); s4o.indent_right(); if (symbol->global_var_declarations != NULL) symbol->global_var_declarations->accept(*this); symbol->resource_declarations->accept(*this); if (symbol->access_declarations != NULL) symbol->access_declarations->accept(*this); if (symbol->instance_specific_initializations != NULL) symbol->instance_specific_initializations->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces + "END_CONFIGURATION\n\n\n"); return NULL; } /* intermediate helper symbol for configuration_declaration */ /* { global_var_declarations_list } */ void *visit(global_var_declarations_list_c *symbol) {return print_list(symbol);} /* helper symbol for configuration_declaration */ /*| resource_declaration_list resource_declaration */ void *visit(resource_declaration_list_c *symbol) {return print_list(symbol);} /* RESOURCE resource_name ON resource_type_name optional_global_var_declarations single_resource_declaration END_RESOURCE */ void *visit(resource_declaration_c *symbol) { s4o.print(s4o.indent_spaces + "RESOURCE "); symbol->resource_name->accept(*this); s4o.print(" ON "); symbol->resource_type_name->accept(*this); s4o.print("\n"); s4o.indent_right(); if (symbol->global_var_declarations != NULL) symbol->global_var_declarations->accept(*this); symbol->resource_declaration->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces + "END_RESOURCE\n"); return NULL; } /* task_configuration_list program_configuration_list */ void *visit(single_resource_declaration_c *symbol) { symbol->task_configuration_list->accept(*this); symbol->program_configuration_list->accept(*this); return NULL; } /* helper symbol for single_resource_declaration */ /*| task_configuration_list task_configuration ';'*/ void *visit(task_configuration_list_c *symbol) { return print_list(symbol, s4o.indent_spaces, ";\n" + s4o.indent_spaces, ";\n"); } /* helper symbol for single_resource_declaration */ /*| program_configuration_list program_configuration ';'*/ void *visit(program_configuration_list_c *symbol) { return print_list(symbol, s4o.indent_spaces, ";\n" + s4o.indent_spaces, ";\n"); } /* helper symbol for * - access_path * - instance_specific_init */ /* | any_fb_name_list any_identifier '.'*/ void *visit(any_fb_name_list_c *symbol) {return print_list(symbol, ".", ".");} /* [resource_name '.'] global_var_name ['.' structure_element_name] */ void *visit(global_var_reference_c *symbol) { if (symbol->resource_name != NULL) { symbol->resource_name->accept(*this); s4o.print("."); } symbol->global_var_name->accept(*this); if (symbol->structure_element_name != NULL) { s4o.print("."); symbol->structure_element_name->accept(*this); } return NULL; } /* program_name '.' symbolic_variable */ void *visit(program_output_reference_c *symbol) { symbol->program_name->accept(*this); s4o.print("."); symbol->symbolic_variable->accept(*this); return NULL; } /* TASK task_name task_initialization */ void *visit(task_configuration_c *symbol) { s4o.print("TASK "); symbol->task_name->accept(*this); s4o.print(" "); symbol->task_initialization->accept(*this); return NULL; } /* '(' [SINGLE ASSIGN data_source ','] [INTERVAL ASSIGN data_source ','] PRIORITY ASSIGN integer ')' */ void *visit(task_initialization_c *symbol) { s4o.print("("); if (symbol->single_data_source != NULL) { s4o.print("SINGLE := "); symbol->single_data_source->accept(*this); s4o.print(", "); } if (symbol->interval_data_source != NULL) { s4o.print("INTERVAL := "); symbol->interval_data_source->accept(*this); s4o.print(", "); } s4o.print("PRIORITY := "); symbol->priority_data_source->accept(*this); s4o.print(")"); return NULL; } /* PROGRAM [RETAIN | NON_RETAIN] program_name [WITH task_name] ':' program_type_name ['(' prog_conf_elements ')'] */ void *visit(program_configuration_c *symbol) { s4o.print("PROGRAM "); if (symbol->retain_option != NULL) symbol->retain_option->accept(*this); symbol->program_name->accept(*this); if (symbol->task_name != NULL) { s4o.print(" WITH "); symbol->task_name->accept(*this); } s4o.print(" : "); symbol->program_type_name->accept(*this); if (symbol->prog_conf_elements != NULL) { s4o.print("("); symbol->prog_conf_elements->accept(*this); s4o.print(")"); } return NULL; } /* prog_conf_elements ',' prog_conf_element */ void *visit(prog_conf_elements_c *symbol) {return print_list(symbol, "", ", ");} /* fb_name WITH task_name */ void *visit(fb_task_c *symbol) { symbol->fb_name->accept(*this); s4o.print(" WITH "); symbol->task_name->accept(*this); return NULL; } /* any_symbolic_variable ASSIGN prog_data_source */ void *visit(prog_cnxn_assign_c *symbol) { symbol->symbolic_variable->accept(*this); s4o.print(" := "); symbol->prog_data_source->accept(*this); return NULL; } /* any_symbolic_variable SENDTO data_sink */ void *visit(prog_cnxn_sendto_c *symbol) { symbol->symbolic_variable->accept(*this); s4o.print(" => "); symbol->data_sink->accept(*this); return NULL; } /* VAR_CONFIG instance_specific_init_list END_VAR */ void *visit(instance_specific_initializations_c *symbol) { s4o.print(s4o.indent_spaces + "VAR_CONFIG\n"); s4o.indent_right(); symbol->instance_specific_init_list->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces + "END_VAR\n"); return NULL; } /* helper symbol for instance_specific_initializations */ /*| instance_specific_init_list instance_specific_init ';'*/ void *visit(instance_specific_init_list_c *symbol) { return print_list(symbol, s4o.indent_spaces, ";\n" + s4o.indent_spaces, ";\n"); } /* resource_name '.' program_name '.' optional_fb_name_list '.' ((variable_name [location] ':' located_var_spec_init) | (fb_name ':' fb_initialization)) */ void *visit(instance_specific_init_c *symbol) { symbol->resource_name->accept(*this); s4o.print("."); symbol->program_name->accept(*this); symbol->any_fb_name_list->accept(*this); if (symbol->variable_name != NULL) { s4o.print("."); symbol->variable_name->accept(*this); } if (symbol->location != NULL) { s4o.print(" "); symbol->location->accept(*this); } s4o.print(" : "); symbol->initialization->accept(*this); return NULL; } /* helper symbol for instance_specific_init */ /* function_block_type_name ':=' structure_initialization */ void *visit(fb_initialization_c *symbol) { symbol->function_block_type_name->accept(*this); s4o.print(" := "); symbol->structure_initialization->accept(*this); return NULL; } /***********************************/ /* B 2.1 Instructions and Operands */ /***********************************/ /*| instruction_list il_instruction */ void *visit(instruction_list_c *symbol) { return print_list(symbol, s4o.indent_spaces, "\n" + s4o.indent_spaces, "\n"); } /* | label ':' [il_incomplete_instruction] eol_list */ void *visit(il_instruction_c *symbol) { if (symbol->label != NULL) { symbol->label->accept(*this); s4o.print(": "); } if (symbol->il_instruction != NULL) { symbol->il_instruction->accept(*this); } return NULL; } /* | il_simple_operator [il_operand] */ void *visit(il_simple_operation_c *symbol) { symbol->il_simple_operator->accept(*this); if (symbol->il_operand != NULL) symbol->il_operand->accept(*this); return NULL; } /* | function_name [il_operand_list] */ void *visit(il_function_call_c *symbol) { symbol->function_name->accept(*this); s4o.print(" "); if (symbol->il_operand_list != NULL) symbol->il_operand_list->accept(*this); return NULL; } /* | il_expr_operator '(' [il_operand] eol_list [simple_instr_list] ')' */ void *visit(il_expression_c *symbol) { /* Since stage2 will insert an artificial (and equivalent) LD <il_operand> to the simple_instr_list when an 'il_operand' exists, we know * that if (symbol->il_operand != NULL), then the first IL instruction in the simple_instr_list will be the equivalent and artificial * 'LD <il_operand>' IL instruction. * Since we do not want the extra LD instruction, we simply remove it! */ if (symbol->il_operand != NULL) ((list_c *)symbol->simple_instr_list)->remove_element(0); symbol->il_expr_operator->accept(*this); s4o.print("("); if (symbol->il_operand != NULL) symbol->il_operand->accept(*this); if (symbol->simple_instr_list != NULL) { s4o.print("\n"); s4o.indent_right(); symbol->simple_instr_list->accept(*this); s4o.print(s4o.indent_spaces); s4o.indent_left(); } s4o.print(")"); return NULL; } /* il_jump_operator label */ void *visit(il_jump_operation_c *symbol) { symbol->il_jump_operator->accept(*this); symbol->label->accept(*this); return NULL; } /* il_call_operator prev_declared_fb_name * | il_call_operator prev_declared_fb_name '(' ')' * | il_call_operator prev_declared_fb_name '(' eol_list ')' * | il_call_operator prev_declared_fb_name '(' il_operand_list ')' * | il_call_operator prev_declared_fb_name '(' eol_list il_param_list ')' */ void *visit(il_fb_call_c *symbol) { symbol->il_call_operator->accept(*this); symbol->fb_name->accept(*this); s4o.print("("); if (symbol->il_operand_list != NULL) symbol->il_operand_list->accept(*this); if (symbol->il_param_list != NULL) { s4o.print("\n"); s4o.indent_right(); symbol->il_param_list->accept(*this); s4o.indent_left(); } s4o.print(")"); return NULL; } /* | function_name '(' eol_list [il_param_list] ')' */ void *visit(il_formal_funct_call_c *symbol) { symbol->function_name->accept(*this); s4o.print("("); s4o.print("\n"); if (symbol->il_param_list != NULL) { s4o.indent_right(); symbol->il_param_list->accept(*this); s4o.print(")"); s4o.indent_left(); } return NULL; } /* | il_operand_list ',' il_operand */ void *visit(il_operand_list_c *symbol) { return print_list(symbol, "", ", "); } /* | simple_instr_list il_simple_instruction */ void *visit(simple_instr_list_c *symbol) { return print_list(symbol, s4o.indent_spaces, "\n" + s4o.indent_spaces, "\n"); } /* il_simple_instruction: * il_simple_operation eol_list * | il_expression eol_list * | il_formal_funct_call eol_list */ void *visit(il_simple_instruction_c *symbol) { return symbol->il_simple_instruction->accept(*this); } /* | il_initial_param_list il_param_instruction */ void *visit(il_param_list_c *symbol) { // return print_list(symbol); return print_list(symbol, s4o.indent_spaces, ",\n" + s4o.indent_spaces, "\n" + s4o.indent_spaces); } /* il_assign_operator il_operand * | il_assign_operator '(' eol_list simple_instr_list ')' */ void *visit(il_param_assignment_c *symbol) { symbol->il_assign_operator->accept(*this); s4o.print(" := "); if (symbol->il_operand != NULL) symbol->il_operand->accept(*this); if (symbol->simple_instr_list != NULL) { s4o.print("(\n"); s4o.indent_right(); symbol->simple_instr_list->accept(*this); s4o.print(s4o.indent_spaces); s4o.print(")"); s4o.indent_left(); } return NULL; } /* il_assign_out_operator variable */ void *visit(il_param_out_assignment_c *symbol) { symbol->il_assign_out_operator->accept(*this); s4o.print(" => "); symbol->variable->accept(*this); return NULL; } /*******************/ /* B 2.2 Operators */ /*******************/ void *visit(LD_operator_c *symbol) {s4o.print("LD "); return NULL;} void *visit(LDN_operator_c *symbol) {s4o.print("LDN "); return NULL;} void *visit(ST_operator_c *symbol) {s4o.print("ST "); return NULL;} void *visit(STN_operator_c *symbol) {s4o.print("STN "); return NULL;} void *visit(NOT_operator_c *symbol) {s4o.print("NOT "); return NULL;} void *visit(S_operator_c *symbol) {s4o.print("S "); return NULL;} void *visit(R_operator_c *symbol) {s4o.print("R "); return NULL;} void *visit(S1_operator_c *symbol) {s4o.print("S1 "); return NULL;} void *visit(R1_operator_c *symbol) {s4o.print("R1 "); return NULL;} void *visit(CLK_operator_c *symbol) {s4o.print("CLK "); return NULL;} void *visit(CU_operator_c *symbol) {s4o.print("CU "); return NULL;} void *visit(CD_operator_c *symbol) {s4o.print("CD "); return NULL;} void *visit(PV_operator_c *symbol) {s4o.print("PV "); return NULL;} void *visit(IN_operator_c *symbol) {s4o.print("IN "); return NULL;} void *visit(PT_operator_c *symbol) {s4o.print("PT "); return NULL;} void *visit(AND_operator_c *symbol) {s4o.print("AND "); return NULL;} void *visit(OR_operator_c *symbol) {s4o.print("OR "); return NULL;} void *visit(XOR_operator_c *symbol) {s4o.print("XOR "); return NULL;} void *visit(ANDN_operator_c *symbol) {s4o.print("ANDN "); return NULL;} void *visit(ORN_operator_c *symbol) {s4o.print("ORN "); return NULL;} void *visit(XORN_operator_c *symbol) {s4o.print("XORN "); return NULL;} void *visit(ADD_operator_c *symbol) {s4o.print("ADD "); return NULL;} void *visit(SUB_operator_c *symbol) {s4o.print("SUB "); return NULL;} void *visit(MUL_operator_c *symbol) {s4o.print("MUL "); return NULL;} void *visit(DIV_operator_c *symbol) {s4o.print("DIV "); return NULL;} void *visit(MOD_operator_c *symbol) {s4o.print("MOD "); return NULL;} void *visit(GT_operator_c *symbol) {s4o.print("GT "); return NULL;} void *visit(GE_operator_c *symbol) {s4o.print("GE "); return NULL;} void *visit(EQ_operator_c *symbol) {s4o.print("EQ "); return NULL;} void *visit(LT_operator_c *symbol) {s4o.print("LT "); return NULL;} void *visit(LE_operator_c *symbol) {s4o.print("LE "); return NULL;} void *visit(NE_operator_c *symbol) {s4o.print("NE "); return NULL;} void *visit(CAL_operator_c *symbol) {s4o.print("CAL "); return NULL;} void *visit(CALC_operator_c *symbol) {s4o.print("CALC "); return NULL;} void *visit(CALCN_operator_c *symbol) {s4o.print("CALCN "); return NULL;} void *visit(RET_operator_c *symbol) {s4o.print("RET "); return NULL;} void *visit(RETC_operator_c *symbol) {s4o.print("RETC "); return NULL;} void *visit(RETCN_operator_c *symbol) {s4o.print("RETCN "); return NULL;} void *visit(JMP_operator_c *symbol) {s4o.print("JMP "); return NULL;} void *visit(JMPC_operator_c *symbol) {s4o.print("JMPC "); return NULL;} void *visit(JMPCN_operator_c *symbol) {s4o.print("JMPCN "); return NULL;} /*| any_identifier ASSIGN */ void *visit(il_assign_operator_c *symbol) { symbol->variable_name->accept(*this); s4o.print(" := "); return NULL; } /*| [NOT] any_identifier SENDTO */ void *visit(il_assign_out_operator_c *symbol) { if (symbol->option != NULL) symbol->option->accept(*this); symbol->variable_name->accept(*this); s4o.print(" => "); return NULL; } /***********************/ /* B 3.1 - Expressions */ /***********************/ void *visit( deref_operator_c *symbol) {return symbol->exp->accept(*this); s4o.print("^");} /* an extension to the IEC 61131-3 standard - based on the IEC 61131-3 v3 standard. ^ -> dereferences an address into a variable! */ void *visit( deref_expression_c *symbol) {return s4o.print("DREF("); symbol->exp->accept(*this); s4o.print(")");} /* an extension to the IEC 61131-3 standard - based on the IEC 61131-3 v3 standard. DREF() -> dereferences an address into a variable! */ void *visit( ref_expression_c *symbol) {return s4o.print( "REF("); symbol->exp->accept(*this); s4o.print(")");} /* an extension to the IEC 61131-3 standard - based on the IEC 61131-3 v3 standard. REF() -> returns address of the varible! */ void *visit( or_expression_c *symbol) {return print_binary_expression(symbol, symbol->l_exp, symbol->r_exp, " OR ");} void *visit( xor_expression_c *symbol) {return print_binary_expression(symbol, symbol->l_exp, symbol->r_exp, " XOR ");} void *visit( and_expression_c *symbol) {return print_binary_expression(symbol, symbol->l_exp, symbol->r_exp, " AND ");} void *visit( equ_expression_c *symbol) {return print_binary_expression(symbol, symbol->l_exp, symbol->r_exp, " = ");} void *visit(notequ_expression_c *symbol) {return print_binary_expression(symbol, symbol->l_exp, symbol->r_exp, " <> ");} void *visit( lt_expression_c *symbol) {return print_binary_expression(symbol, symbol->l_exp, symbol->r_exp, " < ");} void *visit( gt_expression_c *symbol) {return print_binary_expression(symbol, symbol->l_exp, symbol->r_exp, " > ");} void *visit( le_expression_c *symbol) {return print_binary_expression(symbol, symbol->l_exp, symbol->r_exp, " <= ");} void *visit( ge_expression_c *symbol) {return print_binary_expression(symbol, symbol->l_exp, symbol->r_exp, " >= ");} void *visit( add_expression_c *symbol) {return print_binary_expression(symbol, symbol->l_exp, symbol->r_exp, " + ");} void *visit( sub_expression_c *symbol) {return print_binary_expression(symbol, symbol->l_exp, symbol->r_exp, " - ");} void *visit( mul_expression_c *symbol) {return print_binary_expression(symbol, symbol->l_exp, symbol->r_exp, " * ");} void *visit( div_expression_c *symbol) {return print_binary_expression(symbol, symbol->l_exp, symbol->r_exp, " / ");} void *visit( mod_expression_c *symbol) {return print_binary_expression(symbol, symbol->l_exp, symbol->r_exp, " MOD ");} void *visit( power_expression_c *symbol) {return print_binary_expression(symbol, symbol->l_exp, symbol->r_exp, " ** ");} void *visit( neg_expression_c *symbol) {return print_unary_expression (symbol, symbol->exp, "-");} void *visit( not_expression_c *symbol) {return print_unary_expression (symbol, symbol->exp, "NOT ");} void *visit(function_invocation_c *symbol) { symbol->function_name->accept(*this); s4o.print("("); /* If the syntax parser is working correctly, exactly one of the * following two symbols will be NULL, while the other is != NULL. */ if (symbol-> formal_param_list != NULL) symbol-> formal_param_list->accept(*this); if (symbol->nonformal_param_list != NULL) symbol->nonformal_param_list->accept(*this); s4o.print(")"); return NULL; } /********************/ /* B 3.2 Statements */ /********************/ void *visit(statement_list_c *symbol) { return print_list(symbol, s4o.indent_spaces, ";\n" + s4o.indent_spaces, ";\n"); } /*********************************/ /* B 3.2.1 Assignment Statements */ /*********************************/ void *visit( assignment_statement_c *symbol) { symbol->l_exp->accept(*this); s4o.print(" := "); symbol->r_exp->accept(*this); return NULL; } /*****************************************/ /* B 3.2.2 Subprogram Control Statements */ /*****************************************/ /* RETURN */ void *visit(return_statement_c *symbol) { s4o.print("RETURN"); return NULL; } /* fb_name '(' [param_assignment_list] ')' */ void *visit(fb_invocation_c *symbol) { symbol->fb_name->accept(*this); s4o.print("("); /* If the syntax parser is working correctly, at most one of the * following two symbols will be NULL, while the other is != NULL. * The two may be NULL simultaneously! */ if (symbol-> formal_param_list != NULL) symbol-> formal_param_list->accept(*this); if (symbol->nonformal_param_list != NULL) symbol->nonformal_param_list->accept(*this); s4o.print(")"); return NULL; } /* helper symbol for fb_invocation */ /* param_assignment_list ',' param_assignment */ void *visit(param_assignment_list_c *symbol) {return print_list(symbol, "", ", ");} void *visit(input_variable_param_assignment_c *symbol) { symbol->variable_name->accept(*this); s4o.print(" := "); symbol->expression->accept(*this); return NULL; } void *visit(output_variable_param_assignment_c *symbol) { if (symbol->not_param != NULL) symbol->not_param->accept(*this); symbol->variable_name->accept(*this); s4o.print(" => "); symbol->variable->accept(*this); return NULL; } void *visit(not_paramassign_c *symbol) { s4o.print("NOT "); return NULL; } /********************************/ /* B 3.2.3 Selection Statements */ /********************************/ void *visit(if_statement_c *symbol) { s4o.print("IF "); symbol->expression->accept(*this); s4o.print(" THEN\n"); s4o.indent_right(); symbol->statement_list->accept(*this); s4o.indent_left(); symbol->elseif_statement_list->accept(*this); if (symbol->else_statement_list != NULL) { s4o.print(s4o.indent_spaces); s4o.print("ELSE\n"); s4o.indent_right(); symbol->else_statement_list->accept(*this); s4o.indent_left(); } s4o.print(s4o.indent_spaces); s4o.print("END_IF"); return NULL; } /* helper symbol for if_statement */ void *visit(elseif_statement_list_c *symbol) {return print_list(symbol);} /* helper symbol for elseif_statement_list */ void *visit(elseif_statement_c *symbol) { s4o.print(s4o.indent_spaces); s4o.print("ELSIF "); symbol->expression->accept(*this); s4o.print(s4o.indent_spaces); s4o.print("THEN\n"); s4o.indent_right(); symbol->statement_list->accept(*this); s4o.indent_left(); return NULL; } void *visit(case_statement_c *symbol) { s4o.print("CASE "); symbol->expression->accept(*this); s4o.print(" OF\n"); s4o.indent_right(); symbol->case_element_list->accept(*this); if (symbol->statement_list != NULL) { s4o.print(s4o.indent_spaces + "ELSE\n"); s4o.indent_right(); symbol->statement_list->accept(*this); s4o.indent_left(); } s4o.indent_left(); s4o.print(s4o.indent_spaces + "END_CASE"); return NULL; } /* helper symbol for case_statement */ void *visit(case_element_list_c *symbol) { return print_list(symbol); } void *visit(case_element_c *symbol) { s4o.print(s4o.indent_spaces); symbol->case_list->accept(*this); s4o.print(":\n"); s4o.indent_right(); symbol->statement_list->accept(*this); s4o.indent_left(); return NULL; } void *visit(case_list_c *symbol) {return print_list(symbol, "", ", ");} /********************************/ /* B 3.2.4 Iteration Statements */ /********************************/ void *visit(for_statement_c *symbol) { s4o.print("FOR "); symbol->control_variable->accept(*this); s4o.print(" := "); symbol->beg_expression->accept(*this); s4o.print(" TO "); symbol->end_expression->accept(*this); if (symbol->by_expression != NULL) { s4o.print(" BY "); symbol->by_expression->accept(*this); } s4o.print(" DO\n"); s4o.indent_right(); symbol->statement_list->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("END_FOR"); return NULL; } void *visit(while_statement_c *symbol) { s4o.print("WHILE "); symbol->expression->accept(*this); s4o.print(" DO\n"); s4o.indent_right(); symbol->statement_list->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("END_WHILE"); return NULL; } void *visit(repeat_statement_c *symbol) { s4o.print("REPEAT\n"); s4o.indent_right(); symbol->statement_list->accept(*this); s4o.indent_left(); s4o.print(s4o.indent_spaces); s4o.print("UNTIL "); symbol->expression->accept(*this); s4o.print("\n" + s4o.indent_spaces + "END_REPEAT"); return NULL; } void *visit(exit_statement_c *symbol) { s4o.print("EXIT"); return NULL; } }; /* class generate_iec_c */ /***********************************************************************/ /***********************************************************************/ /***********************************************************************/ /***********************************************************************/ /***********************************************************************/ /***********************************************************************/ /***********************************************************************/ /***********************************************************************/ visitor_c *new_code_generator(stage4out_c *s4o, const char *builddir) {return new generate_iec_c(s4o);} void delete_code_generator(visitor_c *code_generator) {delete code_generator;}
69,505
C++
.cc
1,857
34.898223
252
0.647622
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,681
iec_std_lib.h
nucleron_matiec/lib/C/iec_std_lib.h
/* * copyright 2008 Edouard TISSERANT * copyright 2011 Mario de Sousa (msousa@fe.up.pt) * * Offered to the public under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /**** * IEC 61131-3 standard function library */ /* NOTE: This file is full of (what may seem at first) very strange macros. * If you want to know what all these strange macros are doing, * just parse this file through a C preprocessor (e.g. cpp), * and analyse the output! * $gcc -E iec_std_lib.h */ #ifndef _IEC_STD_LIB_H #define _IEC_STD_LIB_H #include <limits.h> #include <float.h> #include <math.h> #include <stdint.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #ifdef DEBUG_IEC #define DBG(...) printf(__VA_ARGS__); #define DBG_TYPE(TYPENAME, name) __print_##TYPENAME(name); #else #define DBG(...) #define DBG_TYPE(TYPENAME, name) #endif /* * Include type defs. */ #include "iec_types_all.h" extern TIME __CURRENT_TIME; extern BOOL __DEBUG; /* TODO typedef struct { __strlen_t len; u_int16_t body[STR_MAX_LEN]; } WSTRING; */ /* # if __WORDSIZE == 64 #define __32b_sufix #define __64b_sufix L #else #define __32b_sufix L #define __64b_sufix LL #endif */ # if __WORDSIZE == 64 #define __32b_sufix #define __64b_sufix L #else #define __32b_sufix L /* changed this from LL to L temporarily. It was causing a bug when compiling resulting code with gcc. * I have other things to worry about at the moment.. */ #define __64b_sufix L #endif #define __lit(type,value,...) (type)value##__VA_ARGS__ // Keep this macro expention step to let sfx(__VA_ARGS__) change into L or LL #define __literal(type,value,...) __lit(type,value,__VA_ARGS__) #define __BOOL_LITERAL(value) __literal(BOOL,value) #define __SINT_LITERAL(value) __literal(SINT,value) #define __INT_LITERAL(value) __literal(INT,value) #define __DINT_LITERAL(value) __literal(DINT,value,__32b_sufix) #define __LINT_LITERAL(value) __literal(LINT,value,__64b_sufix) #define __USINT_LITERAL(value) __literal(USINT,value) #define __UINT_LITERAL(value) __literal(UINT,value) #define __UDINT_LITERAL(value) __literal(UDINT,value,__32b_sufix) #define __ULINT_LITERAL(value) __literal(ULINT,value,__64b_sufix) #define __REAL_LITERAL(value) __literal(REAL,value,__32b_sufix) #define __LREAL_LITERAL(value) __literal(LREAL,value,__64b_sufix) #define __TIME_LITERAL(value) __literal(TIME,value) #define __DATE_LITERAL(value) __literal(DATE,value) #define __TOD_LITERAL(value) __literal(TOD,value) #define __DT_LITERAL(value) __literal(DT,value) #define __STRING_LITERAL(count,value) (STRING){count,value} #define __BYTE_LITERAL(value) __literal(BYTE,value) #define __WORD_LITERAL(value) __literal(WORD,value) #define __DWORD_LITERAL(value) __literal(DWORD,value,__32b_sufix) #define __LWORD_LITERAL(value) __literal(LWORD,value,__64b_sufix) typedef union __IL_DEFVAR_T { BOOL BOOLvar; SINT SINTvar; INT INTvar; DINT DINTvar; LINT LINTvar; USINT USINTvar; UINT UINTvar; UDINT UDINTvar; ULINT ULINTvar; BYTE BYTEvar; WORD WORDvar; DWORD DWORDvar; LWORD LWORDvar; REAL REALvar; LREAL LREALvar; TIME TIMEvar; TOD TODvar; DT DTvar; DATE DATEvar; } __IL_DEFVAR_T; /**********************************************************************/ /**********************************************************************/ /***** *****/ /***** Some helper functions... *****/ /***** ...used later: *****/ /***** - when declaring the IEC 61131-3 standard functions *****/ /***** - in the C source code itself in SFC and ST expressions *****/ /***** *****/ /**********************************************************************/ /**********************************************************************/ /****************************/ /* Notify IEC runtime error */ /****************************/ /* function that generates an IEC runtime error */ static inline void __iec_error(void) { /* TODO... */ fprintf(stderr, "IEC 61131-3 runtime error.\n"); /*exit(1);*/ } /*******************/ /* Math Operations */ /*******************/ static inline double __expt(double in1, double in2) { return pow(in1, in2); } /*******************************/ /* Time normalization function */ /*******************************/ static inline void __normalize_timespec (IEC_TIMESPEC *ts) { if( ts->tv_nsec < -1000000000 || (( ts->tv_sec > 0 ) && ( ts->tv_nsec < 0 ))){ ts->tv_sec--; ts->tv_nsec += 1000000000; } if( ts->tv_nsec > 1000000000 || (( ts->tv_sec < 0 ) && ( ts->tv_nsec > 0 ))){ ts->tv_sec++; ts->tv_nsec -= 1000000000; } } /**********************************************/ /* Time conversion to/from timespec functions */ /**********************************************/ /* NOTE: The following function was turned into a macro, so it could be used to initialize the initial value of TIME variables. * Since each macro parameter is evaluated several times, the macro may result in multiple function invocations if an expression * containing a function invocation is passed as a parameter. However, currently matiec only uses this conversion macro with * constant literals, so it is safe to change it into a macro. */ /* NOTE: I (Mario - msousa@fe.up.pt) believe that the following function contains a bug when handling negative times. * The equivalent macro has this bug fixed. * e.g.; * T#3.8s * using the function, will result in a timespec of 3.8s !!!: * tv_sec = 4 <----- 1 * 3.8 is rounded up when converting a double to an int! * tv_nsec = -200 000 000 <----- 1 * (3.8 - 4)*1e9 * * -T#3.8s * using the function, will result in a timespec of -11.8s !!!: * tv_sec = -4 <----- -1 * 3.8 is rounded down when converting a double to an int! * tv_nsec = -7 800 000 000 <----- -1 * (3.8 - -4)*1e9 */ /* NOTE: Due to the fact that the C compiler may round a tv_sec number away from zero, * the following macro may result in a timespec that is not normalized, i.e. with a tv_sec > 0, and a tv_nsec < 0 !!!! * This is due to the rounding that C compiler applies when converting a (long double) to a (long int). * To produce normalized timespec's we need to use floor(), but we cannot call any library functions since we want this macro to be * useable as a variable initializer. * VAR x : TIME = T#3.5h; END_VAR ---> IEC_TIME x = __time_to_timespec(1, 0, 0, 0, 3.5, 0); */ /* static inline IEC_TIMESPEC __time_to_timespec(int sign, double mseconds, double seconds, double minutes, double hours, double days) { IEC_TIMESPEC ts; // sign is 1 for positive values, -1 for negative time... long double total_sec = ((days*24 + hours)*60 + minutes)*60 + seconds + mseconds/1e3; if (sign >= 0) sign = 1; else sign = -1; ts.tv_sec = sign * (long int)total_sec; ts.tv_nsec = sign * (long int)((total_sec - ts.tv_sec)*1e9); return ts; } */ /* NOTE: Unfortunately older versions of ANSI C (e.g. C99) do not allow explicit identification of elements in initializers * e.g. {tv_sec = 1, tv_nsec = 300} * They are therefore commented out. This however means that any change to the definition of IEC_TIMESPEC may require this * macro to be updated too! */ #define __time_to_timespec(sign,mseconds,seconds,minutes,hours,days) \ ((IEC_TIMESPEC){\ /*tv_sec =*/ ((long int) (((sign>=0)?1:-1)*((((long double)days*24 + (long double)hours)*60 + (long double)minutes)*60 + (long double)seconds + (long double)mseconds/1e3))), \ /*tv_nsec =*/ ((long int)(( \ ((long double)(((sign>=0)?1:-1)*((((long double)days*24 + (long double)hours)*60 + (long double)minutes)*60 + (long double)seconds + (long double)mseconds/1e3))) - \ ((long int) (((sign>=0)?1:-1)*((((long double)days*24 + (long double)hours)*60 + (long double)minutes)*60 + (long double)seconds + (long double)mseconds/1e3))) \ )*1e9))\ }) /* NOTE: The following function was turned into a macro, so it could be used to initialize the initial value of TOD (TIME_OF_DAY) variables */ /* NOTE: many (but not all) of the same comments made regarding __time_to_timespec() are also valid here, so go and read those comments too!*/ /* static inline IEC_TIMESPEC __tod_to_timespec(double seconds, double minutes, double hours) { IEC_TIMESPEC ts; long double total_sec = (hours*60 + minutes)*60 + seconds; ts.tv_sec = (long int)total_sec; ts.tv_nsec = (long int)((total_sec - ts.tv_sec)*1e9); return ts; } */ #define __tod_to_timespec(seconds,minutes,hours) \ ((IEC_TIMESPEC){\ /*tv_sec =*/ ((long int) ((((long double)hours)*60 + (long double)minutes)*60 + (long double)seconds)), \ /*tv_nsec =*/ ((long int)(( \ ((long double)((((long double)hours)*60 + (long double)minutes)*60 + (long double)seconds)) - \ ((long int) ((((long double)hours)*60 + (long double)minutes)*60 + (long double)seconds)) \ )*1e9))\ }) #define EPOCH_YEAR 1970 #define SECONDS_PER_MINUTE 60 #define SECONDS_PER_HOUR (60 * SECONDS_PER_MINUTE) #define SECONDS_PER_DAY (24 * SECONDS_PER_HOUR) #define __isleap(year) \ ((year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0)) static const unsigned short int __mon_yday[2][13] = { /* Normal years. */ { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}, /* Leap years. */ { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366} }; typedef struct { int tm_sec; /* Seconds. [0-60] (1 leap second) */ int tm_min; /* Minutes. [0-59] */ int tm_hour; /* Hours. [0-23] */ int tm_day; /* Day. [1-31] */ int tm_mon; /* Month. [0-11] */ int tm_year; /* Year */ } tm; static inline tm convert_seconds_to_date_and_time(long int seconds) { tm dt; long int days, rem; days = seconds / SECONDS_PER_DAY; rem = seconds % SECONDS_PER_DAY; if (rem < 0) { rem += SECONDS_PER_DAY; days--; } // time of day dt.tm_hour = rem / SECONDS_PER_HOUR; rem %= SECONDS_PER_HOUR; dt.tm_min = rem / 60; dt.tm_sec = rem % 60; // date dt.tm_year = EPOCH_YEAR; while (days >= (rem = __isleap(dt.tm_year) ? 366 : 365)) { dt.tm_year++; days -= rem; } while (days < 0) { dt.tm_year--; days += __isleap(dt.tm_year) ? 366 : 365; } dt.tm_mon = 1; while (days >= __mon_yday[__isleap(dt.tm_year)][dt.tm_mon]) { dt.tm_mon += 1; } dt.tm_day = days - __mon_yday[__isleap(dt.tm_year)][dt.tm_mon - 1] + 1; return dt; } static inline IEC_TIMESPEC __date_to_timespec(int day, int month, int year) { IEC_TIMESPEC ts; int a4, b4, a100, b100, a400, b400; int yday; int intervening_leap_days; if (month < 1 || month > 12) __iec_error(); yday = __mon_yday[__isleap(year)][month - 1] + day; if (yday > __mon_yday[__isleap(year)][month]) __iec_error(); a4 = (year >> 2) - ! (year & 3); b4 = (EPOCH_YEAR >> 2) - ! (EPOCH_YEAR & 3); a100 = a4 / 25 - (a4 % 25 < 0); b100 = b4 / 25 - (b4 % 25 < 0); a400 = a100 >> 2; b400 = b100 >> 2; intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400); ts.tv_sec = ((year - EPOCH_YEAR) * 365 + intervening_leap_days + yday - 1) * 24 * 60 * 60; ts.tv_nsec = 0; return ts; } static inline IEC_TIMESPEC __dt_to_timespec(double seconds, double minutes, double hours, int day, int month, int year) { IEC_TIMESPEC ts_date = __date_to_timespec(day, month, year); IEC_TIMESPEC ts = __tod_to_timespec(seconds, minutes, hours); ts.tv_sec += ts_date.tv_sec; return ts; } /*******************/ /* Time operations */ /*******************/ #define __time_cmp(t1, t2) (t2.tv_sec == t1.tv_sec ? t1.tv_nsec - t2.tv_nsec : t1.tv_sec - t2.tv_sec) static inline TIME __time_add(TIME IN1, TIME IN2){ TIME res ={IN1.tv_sec + IN2.tv_sec, IN1.tv_nsec + IN2.tv_nsec }; __normalize_timespec(&res); return res; } static inline TIME __time_sub(TIME IN1, TIME IN2){ TIME res ={IN1.tv_sec - IN2.tv_sec, IN1.tv_nsec - IN2.tv_nsec }; __normalize_timespec(&res); return res; } static inline TIME __time_mul(TIME IN1, LREAL IN2){ LREAL s_f = IN1.tv_sec * IN2; time_t s = (time_t)s_f; div_t ns = div((int)((LREAL)IN1.tv_nsec * IN2), 1000000000); TIME res = {(long)s + ns.quot, (long)ns.rem + (s_f - s) * 1000000000 }; __normalize_timespec(&res); return res; } static inline TIME __time_div(TIME IN1, LREAL IN2){ LREAL s_f = IN1.tv_sec / IN2; time_t s = (time_t)s_f; TIME res = {(long)s, (long)(IN1.tv_nsec / IN2 + (s_f - s) * 1000000000) }; __normalize_timespec(&res); return res; } /***************/ /* Convertions */ /***************/ /*****************/ /* REAL_TO_INT */ /*****************/ static inline LINT __real_round(LREAL IN) { return fmod(IN, 1) == 0 ? ((LINT)IN / 2) * 2 : (LINT)IN; } static inline LINT __preal_to_sint(LREAL IN) { return IN >= 0 ? __real_round(IN + 0.5) : __real_round(IN - 0.5); } static inline LINT __preal_to_uint(LREAL IN) { return IN >= 0 ? __real_round(IN + 0.5) : 0; } static inline LINT __real_to_sint(LREAL IN) {return (LINT)__preal_to_sint(IN);} static inline LWORD __real_to_bit(LREAL IN) {return (LWORD)__preal_to_uint(IN);} static inline ULINT __real_to_uint(LREAL IN) {return (ULINT)__preal_to_uint(IN);} /***************/ /* TO_STRING */ /***************/ static inline STRING __bool_to_string(BOOL IN) { if(IN) return (STRING){4, "TRUE"}; return (STRING){5,"FALSE"}; } static inline STRING __bit_to_string(LWORD IN) { STRING res; res = __INIT_STRING; res.len = snprintf((char*)res.body, STR_MAX_LEN, "16#%llx",(long long unsigned int)IN); if(res.len > STR_MAX_LEN) res.len = STR_MAX_LEN; return res; } static inline STRING __real_to_string(LREAL IN) { STRING res; res = __INIT_STRING; res.len = snprintf((char*)res.body, STR_MAX_LEN, "%.10g", IN); if(res.len > STR_MAX_LEN) res.len = STR_MAX_LEN; return res; } static inline STRING __sint_to_string(LINT IN) { STRING res; res = __INIT_STRING; res.len = snprintf((char*)res.body, STR_MAX_LEN, "%lld", (long long int)IN); if(res.len > STR_MAX_LEN) res.len = STR_MAX_LEN; return res; } static inline STRING __uint_to_string(ULINT IN) { STRING res; res = __INIT_STRING; res.len = snprintf((char*)res.body, STR_MAX_LEN, "%llu", (long long unsigned int)IN); if(res.len > STR_MAX_LEN) res.len = STR_MAX_LEN; return res; } /***************/ /* FROM_STRING */ /***************/ static inline BOOL __string_to_bool(STRING IN) { int i; if (IN.len == 1) return !memcmp(&IN.body,"1", IN.len); for (i = 0; i < IN.len; i++) IN.body[i] = toupper(IN.body[i]); return IN.len == 4 ? !memcmp(&IN.body,"TRUE", IN.len) : 0; } static inline LINT __pstring_to_sint(STRING* IN) { LINT res = 0; __strlen_t l; unsigned int shift = 0; if(IN->body[0]=='2' && IN->body[1]=='#'){ /* 2#0101_1010_1011_1111 */ for(l = IN->len - 1; l >= 2 && shift < 64; l--) { char c = IN->body[l]; if( c >= '0' && c <= '1'){ res |= ( c - '0') << shift; shift += 1; } } }else if(IN->body[0]=='8' && IN->body[1]=='#'){ /* 8#1234_5665_4321 */ for(l = IN->len - 1; l >= 2 && shift < 64; l--) { char c = IN->body[l]; if( c >= '0' && c <= '7'){ res |= ( c - '0') << shift; shift += 3; } } }else if(IN->body[0]=='1' && IN->body[1]=='6' && IN->body[2]=='#'){ /* 16#1234_5678_9abc_DEFG */ for(l = IN->len - 1; l >= 3 && shift < 64; l--) { char c = IN->body[l]; if( c >= '0' && c <= '9'){ res |= (LWORD)( c - '0') << shift; shift += 4; }else if( c >= 'a' && c <= 'f'){ res |= (LWORD)( c - 'a' + 10 ) << shift; shift += 4; }else if( c >= 'A' && c <= 'F'){ res |= (LWORD)( c - 'A' + 10 ) << shift; shift += 4; } } }else{ /* -123456789 */ LINT fac = IN->body[0] == '-' ? -1 : 1; for(l = IN->len - 1; l >= 0 && shift < 20; l--) { char c = IN->body[l]; if( c >= '0' && c <= '9'){ res += ( c - '0') * fac; fac *= 10; shift += 1; }else if( c >= '.' ){ /* reset value */ res = 0; fac = IN->body[0] == '-' ? -1 : 1; shift = 0; } } } return res; } static inline LINT __string_to_sint(STRING IN) {return (LINT)__pstring_to_sint(&IN);} static inline LWORD __string_to_bit (STRING IN) {return (LWORD)__pstring_to_sint(&IN);} static inline ULINT __string_to_uint(STRING IN) {return (ULINT)__pstring_to_sint(&IN);} static inline LREAL __string_to_real(STRING IN) { __strlen_t l; l = IN.len; /* search the dot */ while(--l > 0 && IN.body[l] != '.'); if(l != 0){ return atof((const char *)&IN.body); }else{ return (LREAL)__pstring_to_sint(&IN); } } /***************/ /* TO_TIME */ /***************/ static inline TIME __int_to_time(LINT IN) {return (TIME){IN, 0};} static inline TIME __real_to_time(LREAL IN) {return (TIME){IN, (IN - (LINT)IN) * 1000000000};} static inline TIME __string_to_time(STRING IN){ __strlen_t l; /* TODO : * * Duration literals without underlines: T#14ms T#-14ms T#14.7s T#14.7m * short prefix T#14.7h t#14.7d t#25h15m * t#5d14h12m18s3.5ms * long prefix TIME#14ms TIME#-14ms time#14.7s * Duration literals with underlines: * short prefix t#25h_15m t#5d_14h_12m_18s_3.5ms * long prefix TIME#25h_15m * time#5d_14h_12m_18s_3.5ms * * Long prefix notation Short prefix notation * DATE#1984-06-25 D#1984-06-25 * date#1984-06-25 d#1984-06-25 * TIME_OF_DAY#15:36:55.36 TOD#15:36:55.36 * time_of_day#15:36:55.36 tod#15:36:55.36 * DATE_AND_TIME#1984-06-25-15:36:55.36 DT#1984-06-25-15:36:55.36 * date_and_time#1984-06-25-15:36:55.36 dt#1984-06-25-15:36:55.36 * */ /* Quick hack : only transform seconds */ /* search the dot */ l = IN.len; while(--l > 0 && IN.body[l] != '.'); if(l != 0){ LREAL IN_val = atof((const char *)&IN.body); return (TIME){(long)IN_val, (long)(IN_val - (LINT)IN_val)*1000000000}; }else{ return (TIME){(long)__pstring_to_sint(&IN), 0}; } } /***************/ /* FROM_TIME */ /***************/ static inline LREAL __time_to_real(TIME IN){ return (LREAL)IN.tv_sec + ((LREAL)IN.tv_nsec/1000000000); } static inline LINT __time_to_int(TIME IN) {return IN.tv_sec;} static inline STRING __time_to_string(TIME IN){ STRING res; div_t days; /*t#5d14h12m18s3.5ms*/ res = __INIT_STRING; days = div(IN.tv_sec, SECONDS_PER_DAY); if(!days.rem && IN.tv_nsec == 0){ res.len = snprintf((char*)&res.body, STR_MAX_LEN, "T#%dd", days.quot); }else{ div_t hours = div(days.rem, SECONDS_PER_HOUR); if(!hours.rem && IN.tv_nsec == 0){ res.len = snprintf((char*)&res.body, STR_MAX_LEN, "T#%dd%dh", days.quot, hours.quot); }else{ div_t minuts = div(hours.rem, SECONDS_PER_MINUTE); if(!minuts.rem && IN.tv_nsec == 0){ res.len = snprintf((char*)&res.body, STR_MAX_LEN, "T#%dd%dh%dm", days.quot, hours.quot, minuts.quot); }else{ if(IN.tv_nsec == 0){ res.len = snprintf((char*)&res.body, STR_MAX_LEN, "T#%dd%dh%dm%ds", days.quot, hours.quot, minuts.quot, minuts.rem); }else{ res.len = snprintf((char*)&res.body, STR_MAX_LEN, "T#%dd%dh%dm%ds%gms", days.quot, hours.quot, minuts.quot, minuts.rem, (LREAL)IN.tv_nsec / 1000000); } } } } if(res.len > STR_MAX_LEN) res.len = STR_MAX_LEN; return res; } static inline STRING __date_to_string(DATE IN){ STRING res; tm broken_down_time; /* D#1984-06-25 */ broken_down_time = convert_seconds_to_date_and_time(IN.tv_sec); res = __INIT_STRING; res.len = snprintf((char*)&res.body, STR_MAX_LEN, "D#%d-%2.2d-%2.2d", broken_down_time.tm_year, broken_down_time.tm_mon, broken_down_time.tm_day); if(res.len > STR_MAX_LEN) res.len = STR_MAX_LEN; return res; } static inline STRING __tod_to_string(TOD IN){ STRING res; tm broken_down_time; time_t seconds; /* TOD#15:36:55.36 */ seconds = IN.tv_sec; if (seconds >= SECONDS_PER_DAY){ __iec_error(); return (STRING){9,"TOD#ERROR"}; } broken_down_time = convert_seconds_to_date_and_time(seconds); res = __INIT_STRING; if(IN.tv_nsec == 0){ res.len = snprintf((char*)&res.body, STR_MAX_LEN, "TOD#%2.2d:%2.2d:%2.2d", broken_down_time.tm_hour, broken_down_time.tm_min, broken_down_time.tm_sec); }else{ res.len = snprintf((char*)&res.body, STR_MAX_LEN, "TOD#%2.2d:%2.2d:%09.6f", broken_down_time.tm_hour, broken_down_time.tm_min, (LREAL)broken_down_time.tm_sec + (LREAL)IN.tv_nsec / 1e9); } if(res.len > STR_MAX_LEN) res.len = STR_MAX_LEN; return res; } static inline STRING __dt_to_string(DT IN){ STRING res; tm broken_down_time; /* DT#1984-06-25-15:36:55.36 */ broken_down_time = convert_seconds_to_date_and_time(IN.tv_sec); if(IN.tv_nsec == 0){ res.len = snprintf((char*)&res.body, STR_MAX_LEN, "DT#%d-%2.2d-%2.2d-%2.2d:%2.2d:%2.2d", broken_down_time.tm_year, broken_down_time.tm_mon, broken_down_time.tm_day, broken_down_time.tm_hour, broken_down_time.tm_min, broken_down_time.tm_sec); }else{ res.len = snprintf((char*)&res.body, STR_MAX_LEN, "DT#%d-%2.2d-%2.2d-%2.2d:%2.2d:%09.6f", broken_down_time.tm_year, broken_down_time.tm_mon, broken_down_time.tm_day, broken_down_time.tm_hour, broken_down_time.tm_min, (LREAL)broken_down_time.tm_sec + ((LREAL)IN.tv_nsec / 1e9)); } if(res.len > STR_MAX_LEN) res.len = STR_MAX_LEN; return res; } /**********************************************/ /* [ANY_DATE | TIME] _TO_ [ANY_DATE | TIME] */ /**********************************************/ static inline TOD __date_and_time_to_time_of_day(DT IN) { return (TOD){ IN.tv_sec % SECONDS_PER_DAY + (IN.tv_sec < 0 ? SECONDS_PER_DAY : 0), IN.tv_nsec}; } static inline DATE __date_and_time_to_date(DT IN){ return (DATE){ IN.tv_sec - IN.tv_sec % SECONDS_PER_DAY - (IN.tv_sec < 0 ? SECONDS_PER_DAY : 0), 0}; } /*****************/ /* FROM/TO BCD */ /*****************/ static inline BOOL __test_bcd(LWORD IN) { while (IN) { if ((IN & 0xf) > 9) return 1; IN >>= 4; } return 0; } static inline ULINT __bcd_to_uint(LWORD IN){ ULINT res = IN & 0xf; ULINT factor = 10ULL; while (IN >>= 4) { res += (IN & 0xf) * factor; factor *= 10; } return res; } static inline LWORD __uint_to_bcd(ULINT IN){ LWORD res = IN % 10; USINT shift = 4; while (IN /= 10) { res |= (IN % 10) << shift; shift += 4; } return res; } /************/ /* MOVE_* */ /************/ /* some helpful __move_[ANY] functions, used in the *_TO_** and MOVE standard functions */ /* e.g. __move_BOOL, __move_BYTE, __move_REAL, __move_TIME, ... */ #define __move_(TYPENAME)\ static inline TYPENAME __move_##TYPENAME(TYPENAME op1) {return op1;} __ANY(__move_) #include "iec_std_functions.h" #ifdef DISABLE_EN_ENO_PARAMETERS #include "iec_std_FB_no_ENENO.h" #else #include "iec_std_FB.h" #endif #endif /* _IEC_STD_LIB_H */
25,489
C++
.h
667
33.283358
193
0.552869
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,682
accessor.h
nucleron_matiec/lib/C/accessor.h
#ifndef __ACCESSOR_H #define __ACCESSOR_H #define __INITIAL_VALUE(...) __VA_ARGS__ // variable declaration macros #define __DECLARE_VAR(type, name)\ __IEC_##type##_t name; #define __DECLARE_GLOBAL(type, domain, name)\ __IEC_##type##_t domain##__##name;\ static __IEC_##type##_t *GLOBAL__##name = &(domain##__##name);\ void __INIT_GLOBAL_##name(type value) {\ (*GLOBAL__##name).value = value;\ }\ IEC_BYTE __IS_GLOBAL_##name##_FORCED(void) {\ return (*GLOBAL__##name).flags & __IEC_FORCE_FLAG;\ }\ type* __GET_GLOBAL_##name(void) {\ return &((*GLOBAL__##name).value);\ } #define __DECLARE_GLOBAL_FB(type, domain, name)\ type domain##__##name;\ static type *GLOBAL__##name = &(domain##__##name);\ type* __GET_GLOBAL_##name(void) {\ return &(*GLOBAL__##name);\ }\ extern void type##_init__(type* data__, BOOL retain); #define __DECLARE_GLOBAL_LOCATION(type, location)\ extern type *location; #define __DECLARE_GLOBAL_LOCATED(type, resource, name)\ __IEC_##type##_p resource##__##name;\ static __IEC_##type##_p *GLOBAL__##name = &(resource##__##name);\ void __INIT_GLOBAL_##name(type value) {\ *((*GLOBAL__##name).value) = value;\ }\ IEC_BYTE __IS_GLOBAL_##name##_FORCED(void) {\ return (*GLOBAL__##name).flags & __IEC_FORCE_FLAG;\ }\ type* __GET_GLOBAL_##name(void) {\ return (*GLOBAL__##name).value;\ } #define __DECLARE_GLOBAL_PROTOTYPE(type, name)\ extern type* __GET_GLOBAL_##name(void); #define __DECLARE_EXTERNAL(type, name)\ __IEC_##type##_p name; #define __DECLARE_EXTERNAL_FB(type, name)\ type* name; #define __DECLARE_LOCATED(type, name)\ __IEC_##type##_p name; // variable initialization macros #define __INIT_RETAIN(name, retained)\ name.flags |= retained?__IEC_RETAIN_FLAG:0; #define __INIT_VAR(name, initial, retained)\ name.value = initial;\ __INIT_RETAIN(name, retained) #define __INIT_GLOBAL(type, name, initial, retained)\ {\ type temp = initial;\ __INIT_GLOBAL_##name(temp);\ __INIT_RETAIN((*GLOBAL__##name), retained)\ } #define __INIT_GLOBAL_FB(type, name, retained)\ type##_init__(&(*GLOBAL__##name), retained); #define __INIT_GLOBAL_LOCATED(domain, name, location, retained)\ domain##__##name.value = location;\ __INIT_RETAIN(domain##__##name, retained) #define __INIT_EXTERNAL(type, global, name, retained)\ {\ name.value = __GET_GLOBAL_##global();\ __INIT_RETAIN(name, retained)\ } #define __INIT_EXTERNAL_FB(type, global, name, retained)\ name = __GET_GLOBAL_##global(); #define __INIT_LOCATED(type, location, name, retained)\ {\ extern type *location;\ name.value = location;\ __INIT_RETAIN(name, retained)\ } #define __INIT_LOCATED_VALUE(name, initial)\ *(name.value) = initial; // variable getting macros #define __GET_VAR(name, ...)\ name.value __VA_ARGS__ #define __GET_EXTERNAL(name, ...)\ ((name.flags & __IEC_FORCE_FLAG) ? name.fvalue __VA_ARGS__ : (*(name.value)) __VA_ARGS__) #define __GET_EXTERNAL_FB(name, ...)\ __GET_VAR(((*name) __VA_ARGS__)) #define __GET_LOCATED(name, ...)\ ((name.flags & __IEC_FORCE_FLAG) ? name.fvalue __VA_ARGS__ : (*(name.value)) __VA_ARGS__) #define __GET_VAR_BY_REF(name, ...)\ ((name.flags & __IEC_FORCE_FLAG) ? &(name.fvalue __VA_ARGS__) : &(name.value __VA_ARGS__)) #define __GET_EXTERNAL_BY_REF(name, ...)\ ((name.flags & __IEC_FORCE_FLAG) ? &(name.fvalue __VA_ARGS__) : &((*(name.value)) __VA_ARGS__)) #define __GET_EXTERNAL_FB_BY_REF(name, ...)\ __GET_EXTERNAL_BY_REF(((*name) __VA_ARGS__)) #define __GET_LOCATED_BY_REF(name, ...)\ ((name.flags & __IEC_FORCE_FLAG) ? &(name.fvalue __VA_ARGS__) : &((*(name.value)) __VA_ARGS__)) #define __GET_VAR_REF(name, ...)\ (&(name.value __VA_ARGS__)) #define __GET_EXTERNAL_REF(name, ...)\ (&((*(name.value)) __VA_ARGS__)) #define __GET_EXTERNAL_FB_REF(name, ...)\ (&(__GET_VAR(((*name) __VA_ARGS__)))) #define __GET_LOCATED_REF(name, ...)\ (&((*(name.value)) __VA_ARGS__)) #define __GET_VAR_DREF(name, ...)\ (*(name.value __VA_ARGS__)) #define __GET_EXTERNAL_DREF(name, ...)\ (*((*(name.value)) __VA_ARGS__)) #define __GET_EXTERNAL_FB_DREF(name, ...)\ (*(__GET_VAR(((*name) __VA_ARGS__)))) #define __GET_LOCATED_DREF(name, ...)\ (*((*(name.value)) __VA_ARGS__)) // variable setting macros #define __SET_VAR(prefix, name, suffix, new_value)\ if (!(prefix name.flags & __IEC_FORCE_FLAG)) prefix name.value suffix = new_value #define __SET_EXTERNAL(prefix, name, suffix, new_value)\ {extern IEC_BYTE __IS_GLOBAL_##name##_FORCED(void);\ if (!(prefix name.flags & __IEC_FORCE_FLAG || __IS_GLOBAL_##name##_FORCED()))\ (*(prefix name.value)) suffix = new_value;} #define __SET_EXTERNAL_FB(prefix, name, suffix, new_value)\ __SET_VAR((*(prefix name)), suffix, new_value) #define __SET_LOCATED(prefix, name, suffix, new_value)\ if (!(prefix name.flags & __IEC_FORCE_FLAG)) *(prefix name.value) suffix = new_value #endif //__ACCESSOR_H
4,874
C++
.h
124
37.185484
96
0.629591
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,683
fill_candidate_datatypes.hh
nucleron_matiec/stage3/fill_candidate_datatypes.hh
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2009-2012 Mario de Sousa (msousa@fe.up.pt) * Copyright (C) 2012 Manuele Conti (manuele.conti@sirius-es.it) * Copyright (C) 2012 Matteo Facchinetti (matteo.facchinetti@sirius-es.it) * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* NOTE: The algorithm implemented here assumes that flow control analysis has already been completed! * BEFORE running this visitor, be sure to CALL the flow_control_analysis_c visitor! */ /* * Fill the candidate datatype list for all symbols that may legally 'have' a data type (e.g. variables, literals, function calls, expressions, etc.) * * The candidate datatype list will be filled with a list of all the data types that expression may legally take. * For example, the very simple literal '0' (as in foo := 0), may represent a: * BOOL, BYTE, WORD, DWORD, LWORD, USINT, SINT, UINT, INT, UDINT, DINT, ULINT, LINT (as well as the SAFE versions of these data tyes too!) * * WARNING: This visitor class starts off by building a map of all enumeration constants that are defined in the source code (i.e. a library_c symbol), * and this map is later used to determine the datatpe of each use of an enumeration constant. By implication, the fill_candidate_datatypes_c * visitor class will only work corretly if it is asked to visit a symbol of class library_c!! */ #include "../absyntax_utils/absyntax_utils.hh" #include "datatype_functions.hh" class fill_candidate_datatypes_c: public iterator_visitor_c { private: search_var_instance_decl_c *search_var_instance_decl; /* When calling a function block, we must first find it's type, * by searching through the declarations of the variables currently * in scope. * This class does just that... * A new object instance is instantiated whenever we start checking semantics * for a function block type declaration, or a program declaration. * This object instance will then later be called while the * function block's or the program's body is being handled. * * Note that functions cannot contain calls to function blocks, * so we do not create an object instance when handling * a function declaration. */ // search_var_instance_decl_c *search_var_instance_decl; /* This variable was created to pass information from * fill_candidate_datatypes_c::visit(enumerated_spec_init_c *symbol) function to * fill_candidate_datatypes_c::visit(enumerated_value_list_c *symbol) function. */ symbol_c *current_enumerated_spec_type; /* pointer to the Function, FB, or Program currently being analysed */ symbol_c *current_scope; /* Pointer to the previous IL instruction, which contains the current data type (actually, the list of candidate data types) of the data stored in the IL stack, i.e. the default variable, a.k.a. accumulator */ symbol_c *prev_il_instruction; /* the current IL operand being analyzed */ symbol_c *il_operand; symbol_c *widening_conversion(symbol_c *left_type, symbol_c *right_type, const struct widen_entry widen_table[]); /* Match a function declaration with a function call through their parameters.*/ /* returns true if compatible function/FB invocation, otherwise returns false */ bool match_nonformal_call(symbol_c *f_call, symbol_c *f_decl); bool match_formal_call (symbol_c *f_call, symbol_c *f_decl, symbol_c **first_param_datatype = NULL); void handle_function_call(symbol_c *fcall, generic_function_call_t fcall_data); void *handle_implicit_il_fb_call(symbol_c *il_instruction, const char *param_name, symbol_c *&called_fb_declaration); void *handle_S_and_R_operator (symbol_c *symbol, const char *operator_str, symbol_c *&called_fb_declaration); void *handle_equality_comparison(const struct widen_entry widen_table[], symbol_c *symbol, symbol_c *l_expr, symbol_c *r_expr); void *handle_binary_expression (const struct widen_entry widen_table[], symbol_c *symbol, symbol_c *l_expr, symbol_c *r_expr); void *handle_binary_operator (const struct widen_entry widen_table[], symbol_c *symbol, symbol_c *l_expr, symbol_c *r_expr); void *handle_conditional_il_flow_control_operator (symbol_c *symbol); void *fill_type_decl (symbol_c *symbol, symbol_c *type_name, symbol_c *spec_init); void *fill_spec_init (symbol_c *symbol, symbol_c *type_spec, symbol_c *init_value); void *fill_var_declaration (symbol_c *var_list, symbol_c *type); /* a helper function... */ symbol_c *base_type(symbol_c *symbol); /* add a data type to a candidate data type list, while guaranteeing no duplicate entries! */ /* Returns true if it really did add the datatype to the list, or false if it was already present in the list! */ bool add_datatype_to_candidate_list (symbol_c *symbol, symbol_c *datatype); bool add_2datatypes_to_candidate_list(symbol_c *symbol, symbol_c *datatype1, symbol_c *datatype2); void remove_incompatible_datatypes(symbol_c *symbol); public: fill_candidate_datatypes_c(symbol_c *ignore); virtual ~fill_candidate_datatypes_c(void); /***************************/ /* B 0 - Programming Model */ /***************************/ void *visit(library_c *symbol); /*************************/ /* B.1 - Common elements */ /*************************/ /*******************************************/ /* B 1.1 - Letters, digits and identifiers */ /*******************************************/ // void *visit( identifier_c *symbol); void *visit(derived_datatype_identifier_c *symbol); // void *visit( poutype_identifier_c *symbol); /*********************/ /* B 1.2 - Constants */ /*********************/ /*********************************/ /* B 1.2.XX - Reference Literals */ /*********************************/ /* defined in IEC 61131-3 v3 - Basically the 'NULL' keyword! */ void *visit(ref_value_null_literal_c *symbol); /******************************/ /* B 1.2.1 - Numeric Literals */ /******************************/ void *handle_any_integer(symbol_c *symbol); void *handle_any_real (symbol_c *symbol); void *handle_any_literal(symbol_c *symbol, symbol_c *symbol_value, symbol_c *symbol_type); void *visit(real_c *symbol); void *visit(integer_c *symbol); void *visit(neg_real_c *symbol); void *visit(neg_integer_c *symbol); void *visit(binary_integer_c *symbol); void *visit(octal_integer_c *symbol); void *visit(hex_integer_c *symbol); void *visit(integer_literal_c *symbol); void *visit(real_literal_c *symbol); void *visit(bit_string_literal_c *symbol); void *visit(boolean_literal_c *symbol); void *visit(boolean_true_c *symbol); void *visit(boolean_false_c *symbol); /*******************************/ /* B.1.2.2 Character Strings */ /*******************************/ void *visit(double_byte_character_string_c *symbol); void *visit(single_byte_character_string_c *symbol); /***************************/ /* B 1.2.3 - Time Literals */ /***************************/ /************************/ /* B 1.2.3.1 - Duration */ /************************/ void *visit(duration_c *symbol); /************************************/ /* B 1.2.3.2 - Time of day and Date */ /************************************/ void *visit(time_of_day_c *symbol); void *visit(date_c *symbol); void *visit(date_and_time_c *symbol); /**********************/ /* B 1.3 - Data types */ /**********************/ /********************************/ /* B 1.3.3 - Derived data types */ /********************************/ // void *visit(data_type_declaration_c *symbol); /* Not required. already handled by iterator_visitor_c base class */ // void *visit(type_declaration_list_c *symbol); /* Not required. already handled by iterator_visitor_c base class */ void *visit(simple_type_declaration_c *symbol); void *visit(simple_spec_init_c *symbol); void *visit(subrange_type_declaration_c *symbol); void *visit(subrange_spec_init_c *symbol); // void *visit(subrange_specification_c *symbol); void *visit(subrange_c *symbol); void *visit(enumerated_type_declaration_c *symbol); void *visit(enumerated_spec_init_c *symbol); void *visit(enumerated_value_list_c *symbol); void *visit(enumerated_value_c *symbol); void *visit(array_type_declaration_c *symbol); void *visit(array_spec_init_c *symbol); // void *visit(array_specification_c *symbol); /* Not required. already handled by iterator_visitor_c base class */ // void *visit(array_subrange_list_c *symbol); // void *visit(array_initial_elements_list_c *symbol); // void *visit(array_initial_elements_c *symbol); void *visit(structure_type_declaration_c *symbol); void *visit(initialized_structure_c *symbol); // void *visit(structure_element_declaration_list_c *symbol); // void *visit(structure_element_declaration_c *symbol); void *visit(structure_element_initialization_list_c *symbol); void *visit(structure_element_initialization_c *symbol); // void *visit(string_type_declaration_c *symbol); void *visit(fb_spec_init_c *symbol); void *visit(ref_spec_c *symbol); // Defined in IEC 61131-3 v3 void *visit(ref_spec_init_c *symbol); // Defined in IEC 61131-3 v3 void *visit(ref_type_decl_c *symbol); // Defined in IEC 61131-3 v3 /*********************/ /* B 1.4 - Variables */ /*********************/ void *visit(symbolic_variable_c *symbol); /********************************************/ /* B 1.4.1 - Directly Represented Variables */ /********************************************/ void *visit(direct_variable_c *symbol); /*************************************/ /* B 1.4.2 - Multi-element variables */ /*************************************/ void *visit(array_variable_c *symbol); void *visit(structured_variable_c *symbol); /******************************************/ /* B 1.4.3 - Declaration & Initialisation */ /******************************************/ void *visit(var1_list_c *symbol); void *visit(location_c *symbol); void *visit(located_var_decl_c *symbol); void *visit(var1_init_decl_c *symbol); void *visit(array_var_init_decl_c *symbol); void *visit(structured_var_init_decl_c *symbol); void *visit(fb_name_decl_c *symbol); void *visit(array_var_declaration_c *symbol); void *visit(structured_var_declaration_c *symbol); void *visit(external_declaration_c *symbol); void *visit(global_var_decl_c *symbol); void *visit(incompl_located_var_decl_c *symbol); //void *visit(single_byte_string_var_declaration_c *symbol); //void *visit(double_byte_string_var_declaration_c *symbol); /**************************************/ /* B 1.5 - Program organization units */ /**************************************/ /***********************/ /* B 1.5.1 - Functions */ /***********************/ void *visit(function_declaration_c *symbol); /*****************************/ /* B 1.5.2 - Function blocks */ /*****************************/ void *visit(function_block_declaration_c *symbol); /**********************/ /* B 1.5.3 - Programs */ /**********************/ void *visit(program_declaration_c *symbol); /********************************************/ /* B 1.6 Sequential function chart elements */ /********************************************/ void *visit(transition_condition_c *symbol); /********************************/ /* B 1.7 Configuration elements */ /********************************/ void *visit(configuration_declaration_c *symbol); void *visit(resource_declaration_c *symbol); void *visit(single_resource_declaration_c *symbol); /****************************************/ /* B.2 - Language IL (Instruction List) */ /****************************************/ /***********************************/ /* B 2.1 Instructions and Operands */ /***********************************/ void *visit(instruction_list_c *symbol); void *visit(il_instruction_c *symbol); void *visit(il_simple_operation_c *symbol); void *visit(il_function_call_c *symbol); void *visit(il_expression_c *symbol); void *visit(il_jump_operation_c *symbol); void *visit(il_fb_call_c *symbol); void *visit(il_formal_funct_call_c *symbol); // void *visit(il_operand_list_c *symbol); void *visit(simple_instr_list_c *symbol); void *visit(il_simple_instruction_c*symbol); // void *visit(il_param_list_c *symbol); // void *visit(il_param_assignment_c *symbol); // void *visit(il_param_out_assignment_c *symbol); /*******************/ /* B 2.2 Operators */ /*******************/ void *visit(LD_operator_c *symbol); void *visit(LDN_operator_c *symbol); void *visit(ST_operator_c *symbol); void *visit(STN_operator_c *symbol); void *visit(NOT_operator_c *symbol); void *visit(S_operator_c *symbol); void *visit(R_operator_c *symbol); void *visit(S1_operator_c *symbol); void *visit(R1_operator_c *symbol); void *visit(CLK_operator_c *symbol); void *visit(CU_operator_c *symbol); void *visit(CD_operator_c *symbol); void *visit(PV_operator_c *symbol); void *visit(IN_operator_c *symbol); void *visit(PT_operator_c *symbol); void *visit(AND_operator_c *symbol); void *visit(OR_operator_c *symbol); void *visit(XOR_operator_c *symbol); void *visit(ANDN_operator_c *symbol); void *visit(ORN_operator_c *symbol); void *visit(XORN_operator_c *symbol); void *visit(ADD_operator_c *symbol); void *visit(SUB_operator_c *symbol); void *visit(MUL_operator_c *symbol); void *visit(DIV_operator_c *symbol); void *visit(MOD_operator_c *symbol); void *visit(GT_operator_c *symbol); void *visit(GE_operator_c *symbol); void *visit(EQ_operator_c *symbol); void *visit(LT_operator_c *symbol); void *visit(LE_operator_c *symbol); void *visit(NE_operator_c *symbol); void *visit(CAL_operator_c *symbol); void *visit(CALC_operator_c *symbol); void *visit(CALCN_operator_c *symbol); void *visit(RET_operator_c *symbol); void *visit(RETC_operator_c *symbol); void *visit(RETCN_operator_c *symbol); void *visit(JMP_operator_c *symbol); void *visit(JMPC_operator_c *symbol); void *visit(JMPCN_operator_c *symbol); /* Symbol class handled together with function call checks */ // void *visit(il_assign_operator_c *symbol, variable_name); /* Symbol class handled together with function call checks */ // void *visit(il_assign_operator_c *symbol, option, variable_name); /***************************************/ /* B.3 - Language ST (Structured Text) */ /***************************************/ /***********************/ /* B 3.1 - Expressions */ /***********************/ void *visit( deref_operator_c *symbol); void *visit( deref_expression_c *symbol); void *visit( ref_expression_c *symbol); void *visit( or_expression_c *symbol); void *visit( xor_expression_c *symbol); void *visit( and_expression_c *symbol); void *visit( equ_expression_c *symbol); void *visit( notequ_expression_c *symbol); void *visit( lt_expression_c *symbol); void *visit( gt_expression_c *symbol); void *visit( le_expression_c *symbol); void *visit( ge_expression_c *symbol); void *visit( add_expression_c *symbol); void *visit( sub_expression_c *symbol); void *visit( mul_expression_c *symbol); void *visit( div_expression_c *symbol); void *visit( mod_expression_c *symbol); void *visit( power_expression_c *symbol); void *visit( neg_expression_c *symbol); void *visit( not_expression_c *symbol); void *visit(function_invocation_c *symbol); /*********************************/ /* B 3.2.1 Assignment Statements */ /*********************************/ void *visit(assignment_statement_c *symbol); /*****************************************/ /* B 3.2.2 Subprogram Control Statements */ /*****************************************/ void *visit(fb_invocation_c *symbol); /********************************/ /* B 3.2.3 Selection Statements */ /********************************/ void *visit(if_statement_c *symbol); // void *visit(elseif_statement_list_c *symbol); void *visit(elseif_statement_c *symbol); void *visit(case_statement_c *symbol); /********************************/ /* B 3.2.4 Iteration Statements */ /********************************/ void *visit(for_statement_c *symbol); void *visit(while_statement_c *symbol); void *visit(repeat_statement_c *symbol); }; // fill_candidate_datatypes_c
18,269
C++
.h
366
45.20765
213
0.594889
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,684
print_datatypes_error.hh
nucleron_matiec/stage3/print_datatypes_error.hh
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2009-2011 Mario de Sousa (msousa@fe.up.pt) * Copyright (C) 2011-2012 Manuele Conti (manuele.conti@sirius-es.it) * Copyright (C) 2011-2012 Matteo Facchinetti (matteo.facchinetti@sirius-es.it) * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* NOTE: The algorithm implemented here assumes that the symbol_c.candidate_datatype, and the symbol_c.datatype * annotations have already been apropriately filled in! * BEFORE running this visitor, be sure to CALL the fill_candidate_datatypes_c, and the narrow_candidate_datatypes_c visitors! */ /* * By analysing the candidate datatype lists, as well as the chosen datatype for each expression, determine * if an datatype error has been found, and if so, print out an error message. */ #include "../absyntax_utils/absyntax_utils.hh" #include "datatype_functions.hh" class print_datatypes_error_c: public iterator_visitor_c { private: /* The level of detail that the user wants us to display error messages. */ // #define error_level_default (1) #define error_level_default (1) #define error_level_nagging (4) unsigned int current_display_error_level; search_varfb_instance_type_c *search_varfb_instance_type; /* When calling a function block, we must first find it's type, * by searching through the declarations of the variables currently * in scope. * This class does just that... * A new object instance is instantiated whenever we start checking semantics * for a function block type declaration, or a program declaration. * This object instance will then later be called while the * function block's or the program's body is being handled. * * Note that functions cannot contain calls to function blocks, * so we do not create an object instance when handling * a function declaration. */ /* In IL code, once we find a type mismatch error, it is best to * ignore any further errors until the end of the logical operation, * i.e. until the next LD. * However, we cannot clear the il_error flag on all LD operations, * as these may also be used within parenthesis. LD operations * within parenthesis may not clear the error flag. * We therefore need a counter to know how deep inside a parenthesis * structure we are. */ int il_parenthesis_level; bool il_error; int error_count; bool warning_found; /* the current data type of the data stored in the IL stack, i.e. the default variable */ il_instruction_c *fake_prev_il_instruction; /* the narrow algorithm will need access to the intersected candidate_datatype lists of all prev_il_instructions, as well as the * list of the prev_il_instructions. * Instead of creating two 'global' (within the class) variables, we create a single il_instruction_c variable (fake_prev_il_instruction), * and shove that data into this single variable. */ symbol_c *il_operand_type; symbol_c *il_operand; /* some helper functions... */ void handle_function_invocation(symbol_c *fcall, generic_function_call_t fcall_data); void *handle_implicit_il_fb_invocation(const char *param_name, symbol_c *il_operator, symbol_c *called_fb_declaration); void *handle_conditional_flow_control_IL_instruction(symbol_c *symbol, const char *oper); void *print_binary_operator_errors (const char *il_operator, symbol_c *symbol, bool deprecated_operation = false); void *print_binary_expression_errors(const char *operation , symbol_c *symbol, symbol_c *l_expr, symbol_c *r_expr, bool deprecated_operation = false); public: print_datatypes_error_c(symbol_c *ignore); virtual ~print_datatypes_error_c(void); int get_error_count(); /*********************/ /* B 1.2 - Constants */ /*********************/ /******************************/ /* B 1.2.1 - Numeric Literals */ /******************************/ void *visit(real_c *symbol); void *visit(integer_c *symbol); void *visit(neg_real_c *symbol); void *visit(neg_integer_c *symbol); void *visit(binary_integer_c *symbol); void *visit(octal_integer_c *symbol); void *visit(hex_integer_c *symbol); void *visit(integer_literal_c *symbol); void *visit(real_literal_c *symbol); void *visit(bit_string_literal_c *symbol); void *visit(boolean_literal_c *symbol); void *visit(boolean_true_c *symbol); void *visit(boolean_false_c *symbol); /*******************************/ /* B.1.2.2 Character Strings */ /*******************************/ void *visit(double_byte_character_string_c *symbol); void *visit(single_byte_character_string_c *symbol); /***************************/ /* B 1.2.3 - Time Literals */ /***************************/ /************************/ /* B 1.2.3.1 - Duration */ /************************/ void *visit(duration_c *symbol); /************************************/ /* B 1.2.3.2 - Time of day and Date */ /************************************/ void *visit(time_of_day_c *symbol); void *visit(date_c *symbol); void *visit(date_and_time_c *symbol); /**********************/ /* B 1.3 - Data types */ /**********************/ /********************************/ /* B 1.3.3 - Derived data types */ /********************************/ void *visit(simple_spec_init_c *symbol); // void *visit(data_type_declaration_c *symbol); /* use base iterator_c method! */ void *visit(enumerated_value_c *symbol); // void *visit(structure_element_initialization_list_c *symbol); void *visit(structure_element_initialization_c *symbol); /*********************/ /* B 1.4 - Variables */ /*********************/ void *visit(symbolic_variable_c *symbol); /********************************************/ /* B 1.4.1 - Directly Represented Variables */ /********************************************/ void *visit(direct_variable_c *symbol); /*************************************/ /* B 1.4.2 - Multi-element variables */ /*************************************/ void *visit(array_variable_c *symbol); void *visit(subscript_list_c *symbol); void *visit(structured_variable_c *symbol); /******************************************/ /* B 1.4.3 - Declaration & Initialisation */ /******************************************/ void *visit(location_c *symbol); void *visit(located_var_decl_c *symbol); /**************************************/ /* B 1.5 - Program organization units */ /**************************************/ /***********************/ /* B 1.5.1 - Functions */ /***********************/ void *visit(function_declaration_c *symbol); /*****************************/ /* B 1.5.2 - Function blocks */ /*****************************/ void *visit(function_block_declaration_c *symbol); /**********************/ /* B 1.5.3 - Programs */ /**********************/ void *visit(program_declaration_c *symbol); /********************************************/ /* B 1.6 Sequential function chart elements */ /********************************************/ void *visit(transition_condition_c *symbol); /********************************/ /* B 1.7 Configuration elements */ /********************************/ void *visit(configuration_declaration_c *symbol); /****************************************/ /* B.2 - Language IL (Instruction List) */ /****************************************/ /***********************************/ /* B 2.1 Instructions and Operands */ /***********************************/ // void *visit(instruction_list_c *symbol); void *visit(il_instruction_c *symbol); void *visit(il_simple_operation_c *symbol); void *visit(il_function_call_c *symbol); void *visit(il_expression_c *symbol); void *visit(il_fb_call_c *symbol); void *visit(il_formal_funct_call_c *symbol); // void *visit(il_operand_list_c *symbol); // void *visit(simple_instr_list_c *symbol); void *visit(il_simple_instruction_c*symbol); // void *visit(il_param_list_c *symbol); // void *visit(il_param_assignment_c *symbol); // void *visit(il_param_out_assignment_c *symbol); /*******************/ /* B 2.2 Operators */ /*******************/ void *visit(LD_operator_c *symbol); void *visit(LDN_operator_c *symbol); void *visit(ST_operator_c *symbol); void *visit(STN_operator_c *symbol); void *visit(NOT_operator_c *symbol); void *visit(S_operator_c *symbol); void *visit(R_operator_c *symbol); void *visit(S1_operator_c *symbol); void *visit(R1_operator_c *symbol); void *visit(CLK_operator_c *symbol); void *visit(CU_operator_c *symbol); void *visit(CD_operator_c *symbol); void *visit(PV_operator_c *symbol); void *visit(IN_operator_c *symbol); void *visit(PT_operator_c *symbol); void *visit(AND_operator_c *symbol); void *visit(OR_operator_c *symbol); void *visit(XOR_operator_c *symbol); void *visit(ANDN_operator_c *symbol); void *visit(ORN_operator_c *symbol); void *visit(XORN_operator_c *symbol); void *visit(ADD_operator_c *symbol); void *visit(SUB_operator_c *symbol); void *visit(MUL_operator_c *symbol); void *visit(DIV_operator_c *symbol); void *visit(MOD_operator_c *symbol); void *visit(GT_operator_c *symbol); void *visit(GE_operator_c *symbol); void *visit(EQ_operator_c *symbol); void *visit(LT_operator_c *symbol); void *visit(LE_operator_c *symbol); void *visit(NE_operator_c *symbol); void *visit(CAL_operator_c *symbol); void *visit(CALC_operator_c *symbol); void *visit(CALCN_operator_c *symbol); void *visit(RET_operator_c *symbol); void *visit(RETC_operator_c *symbol); void *visit(RETCN_operator_c *symbol); void *visit(JMP_operator_c *symbol); void *visit(JMPC_operator_c *symbol); void *visit(JMPCN_operator_c *symbol); /* Symbol class handled together with function call checks */ // void *visit(il_assign_operator_c *symbol, variable_name); /* Symbol class handled together with function call checks */ // void *visit(il_assign_operator_c *symbol, option, variable_name); /***************************************/ /* B.3 - Language ST (Structured Text) */ /***************************************/ /***********************/ /* B 3.1 - Expressions */ /***********************/ void *visit( deref_operator_c *symbol); void *visit( deref_expression_c *symbol); void *visit( ref_expression_c *symbol); void *visit( or_expression_c *symbol); void *visit( xor_expression_c *symbol); void *visit( and_expression_c *symbol); void *visit( equ_expression_c *symbol); void *visit( notequ_expression_c *symbol); void *visit( lt_expression_c *symbol); void *visit( gt_expression_c *symbol); void *visit( le_expression_c *symbol); void *visit( ge_expression_c *symbol); void *visit( add_expression_c *symbol); void *visit( sub_expression_c *symbol); void *visit( mul_expression_c *symbol); void *visit( div_expression_c *symbol); void *visit( mod_expression_c *symbol); void *visit( power_expression_c *symbol); void *visit( neg_expression_c *symbol); void *visit( not_expression_c *symbol); void *visit(function_invocation_c *symbol); /*********************************/ /* B 3.2.1 Assignment Statements */ /*********************************/ void *visit(assignment_statement_c *symbol); /*****************************************/ /* B 3.2.2 Subprogram Control Statements */ /*****************************************/ void *visit(fb_invocation_c *symbol); /********************************/ /* B 3.2.3 Selection Statements */ /********************************/ void *visit(if_statement_c *symbol); // void *visit(elseif_statement_list_c *symbol); void *visit(elseif_statement_c *symbol); void *visit(case_statement_c *symbol); // void *visit(case_element_list_c *symbol); // void *visit(case_element_c *symbol); // void *visit(case_list_c *symbol); /********************************/ /* B 3.2.4 Iteration Statements */ /********************************/ void *visit(for_statement_c *symbol); void *visit(while_statement_c *symbol); void *visit(repeat_statement_c *symbol); }; // print_datatypes_error_c
13,715
C++
.h
304
40.4375
155
0.58052
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,685
narrow_candidate_datatypes.hh
nucleron_matiec/stage3/narrow_candidate_datatypes.hh
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2009-2012 Mario de Sousa (msousa@fe.up.pt) * Copyright (C) 2012 Manuele Conti (manuele.conti@sirius-es.it) * Copyright (C) 2012 Matteo Facchinetti (matteo.facchinetti@sirius-es.it) * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* NOTE: The algorithm implemented here assumes that candidate datatype lists have already been filled! * BEFORE running this visitor, be sure to CALL the fill_candidate_datatype_c visitor! */ /* * Choose, from the list of all the possible datatypes each expression may take, the single datatype that it will in fact take. * The resulting (chosen) datatype, will be stored in the symbol_c.datatype variable, leaving the candidate datatype list untouched! * * For rvalue expressions, this decision will be based on the datatype of the lvalue expression. * For lvalue expressions, the candidate datatype list should have a single entry. * * For example, the very simple literal '0' in 'foo := 0', may represent a: * BOOL, BYTE, WORD, DWORD, LWORD, USINT, SINT, UINT, INT, UDINT, DINT, ULINT, LINT (as well as the SAFE versions of these data tyes too!) * * In this class, the datatype of '0' will be set to the same datatype as the 'foo' variable. * If the intersection of the candidate datatype lists of the left and right side expressions is empty, * then a datatype error has been found, and the datatype is either left at NULL, or set to a pointer of an invalid_type_name_c object! */ #ifndef _NARROW_CANDIDATE_DATATYPES_HH #define _NARROW_CANDIDATE_DATATYPES_HH #include "../absyntax_utils/absyntax_utils.hh" #include "datatype_functions.hh" class narrow_candidate_datatypes_c: public iterator_visitor_c { private: search_varfb_instance_type_c *search_varfb_instance_type; symbol_c *il_operand; il_instruction_c *fake_prev_il_instruction; il_instruction_c *current_il_instruction; protected: virtual void set_datatype_in_prev_il_instructions(symbol_c *datatype, il_instruction_c *symbol); private: bool is_widening_compatible(const struct widen_entry widen_table[], symbol_c *left_type, symbol_c *right_type, symbol_c *result_type, bool *deprecated_status = NULL); void *narrow_spec_init (symbol_c *symbol, symbol_c *type_decl, symbol_c *init_value); void *narrow_type_decl (symbol_c *symbol, symbol_c *type_name, symbol_c *spec_init); void narrow_function_invocation (symbol_c *f_call, generic_function_call_t fcall_data); void narrow_nonformal_call (symbol_c *f_call, symbol_c *f_decl, int *ext_parm_count = NULL); void narrow_formal_call (symbol_c *f_call, symbol_c *f_decl, int *ext_parm_count = NULL); void *narrow_implicit_il_fb_call (symbol_c *symbol, const char *param_name, symbol_c *&called_fb_declaration); void *narrow_S_and_R_operator (symbol_c *symbol, const char *param_name, symbol_c * called_fb_declaration); void *narrow_store_operator (symbol_c *symbol); void *narrow_conditional_operator(symbol_c *symbol); void *narrow_binary_operator (const struct widen_entry widen_table[], symbol_c *symbol, bool *deprecated_operation = NULL); void *narrow_binary_expression (const struct widen_entry widen_table[], symbol_c *symbol, symbol_c *l_expr, symbol_c *r_expr, bool *deprecated_operation = NULL, bool allow_enums = false); void *narrow_equality_comparison (const struct widen_entry widen_table[], symbol_c *symbol, symbol_c *l_expr, symbol_c *r_expr, bool *deprecated_operation = NULL); void *narrow_var_declaration (symbol_c *type); void *set_il_operand_datatype (symbol_c *il_operand, symbol_c *datatype); public: narrow_candidate_datatypes_c(symbol_c *ignore); virtual ~narrow_candidate_datatypes_c(void); symbol_c *base_type(symbol_c *symbol); /*************************/ /* B.1 - Common elements */ /*************************/ /*******************************************/ /* B 1.1 - Letters, digits and identifiers */ /*******************************************/ // void *visit( identifier_c *symbol); void *visit(derived_datatype_identifier_c *symbol); // void *visit( poutype_identifier_c *symbol); /**********************/ /* B 1.3 - Data types */ /**********************/ /***********************************/ /* B 1.3.1 - Elementary Data Types */ /***********************************/ void *visit( time_type_name_c *symbol); void *visit( bool_type_name_c *symbol); void *visit( sint_type_name_c *symbol); void *visit( int_type_name_c *symbol); void *visit( dint_type_name_c *symbol); void *visit( lint_type_name_c *symbol); void *visit( usint_type_name_c *symbol); void *visit( uint_type_name_c *symbol); void *visit( udint_type_name_c *symbol); void *visit( ulint_type_name_c *symbol); void *visit( real_type_name_c *symbol); void *visit( lreal_type_name_c *symbol); void *visit( date_type_name_c *symbol); void *visit( tod_type_name_c *symbol); void *visit( dt_type_name_c *symbol); void *visit( byte_type_name_c *symbol); void *visit( word_type_name_c *symbol); void *visit( dword_type_name_c *symbol); void *visit( lword_type_name_c *symbol); void *visit( string_type_name_c *symbol); void *visit( wstring_type_name_c *symbol); void *visit(safetime_type_name_c *symbol); void *visit(safebool_type_name_c *symbol); void *visit(safesint_type_name_c *symbol); void *visit(safeint_type_name_c *symbol); void *visit(safedint_type_name_c *symbol); void *visit(safelint_type_name_c *symbol); void *visit(safeusint_type_name_c *symbol); void *visit(safeuint_type_name_c *symbol); void *visit(safeudint_type_name_c *symbol); void *visit(safeulint_type_name_c *symbol); void *visit(safereal_type_name_c *symbol); void *visit(safelreal_type_name_c *symbol); void *visit(safedate_type_name_c *symbol); void *visit(safetod_type_name_c *symbol); void *visit(safedt_type_name_c *symbol); void *visit(safebyte_type_name_c *symbol); void *visit(safeword_type_name_c *symbol); void *visit(safedword_type_name_c *symbol); void *visit(safelword_type_name_c *symbol); void *visit(safestring_type_name_c *symbol); void *visit(safewstring_type_name_c *symbol); /********************************/ /* B.1.3.2 - Generic data types */ /********************************/ /********************************/ /* B 1.3.3 - Derived data types */ /********************************/ // void *visit(data_type_declaration_c *symbol); /* Not required. already handled by iterator_visitor_c base class */ // void *visit(type_declaration_list_c *symbol); /* Not required. already handled by iterator_visitor_c base class */ void *visit(simple_type_declaration_c *symbol); /* Not required. already handled by iterator_visitor_c base class */ void *visit(simple_spec_init_c *symbol); void *visit(subrange_type_declaration_c *symbol); void *visit(subrange_spec_init_c *symbol); void *visit(subrange_specification_c *symbol); void *visit(subrange_c *symbol); void *visit(enumerated_type_declaration_c *symbol); void *visit(enumerated_spec_init_c *symbol); void *visit(enumerated_value_list_c *symbol); // void *visit(enumerated_value_c *symbol); /* Not required */ void *visit(array_type_declaration_c *symbol); void *visit(array_spec_init_c *symbol); // void *visit(array_specification_c *symbol); // void *visit(array_subrange_list_c *symbol); // void *visit(array_initial_elements_list_c *symbol); // void *visit(array_initial_elements_c *symbol); void *visit(structure_type_declaration_c *symbol); void *visit(initialized_structure_c *symbol); // void *visit(structure_element_declaration_list_c *symbol); // void *visit(structure_element_declaration_c *symbol); void *visit(structure_element_initialization_list_c *symbol); void *visit(structure_element_initialization_c *symbol); // void *visit(string_type_declaration_c *symbol); void *visit(fb_spec_init_c *symbol); void *visit(ref_spec_c *symbol); // Defined in IEC 61131-3 v3 void *visit(ref_spec_init_c *symbol); // Defined in IEC 61131-3 v3 void *visit(ref_type_decl_c *symbol); // Defined in IEC 61131-3 v3 /*********************/ /* B 1.4 - Variables */ /*********************/ void *visit(symbolic_variable_c *symbol); /********************************************/ /* B 1.4.1 - Directly Represented Variables */ /********************************************/ /*************************************/ /* B 1.4.2 - Multi-element variables */ /*************************************/ void *visit(array_variable_c *symbol); void *visit(subscript_list_c *symbol); void *visit(structured_variable_c *symbol); /******************************************/ /* B 1.4.3 - Declaration & Initialisation */ /******************************************/ void *visit(var1_list_c *symbol); void *visit(location_c *symbol); void *visit(located_var_decl_c *symbol); void *visit(var1_init_decl_c *symbol); void *visit(array_var_init_decl_c *symbol); void *visit(structured_var_init_decl_c *symbol); void *visit(fb_name_decl_c *symbol); void *visit(array_var_declaration_c *symbol); void *visit(structured_var_declaration_c *symbol); void *visit(external_declaration_c *symbol); void *visit(global_var_decl_c *symbol); void *visit(incompl_located_var_decl_c *symbol); //void *visit(single_byte_string_var_declaration_c *symbol); //void *visit(double_byte_string_var_declaration_c *symbol); /**************************************/ /* B 1.5 - Program organization units */ /**************************************/ /***********************/ /* B 1.5.1 - Functions */ /***********************/ void *visit(function_declaration_c *symbol); /*****************************/ /* B 1.5.2 - Function blocks */ /*****************************/ void *visit(function_block_declaration_c *symbol); /**********************/ /* B 1.5.3 - Programs */ /**********************/ void *visit(program_declaration_c *symbol); /********************************************/ /* B 1.6 Sequential function chart elements */ /********************************************/ void *visit(transition_condition_c *symbol); void *visit(action_qualifier_c *symbol); /********************************/ /* B 1.7 Configuration elements */ /********************************/ void *visit(configuration_declaration_c *symbol); void *visit(resource_declaration_c *symbol); void *visit(single_resource_declaration_c *symbol); /****************************************/ /* B.2 - Language IL (Instruction List) */ /****************************************/ /***********************************/ /* B 2.1 Instructions and Operands */ /***********************************/ void *visit(instruction_list_c *symbol); void *visit(il_instruction_c *symbol); void *visit(il_simple_operation_c *symbol); void *visit(il_function_call_c *symbol); void *visit(il_expression_c *symbol); void *visit(il_jump_operation_c *symbol); void *visit(il_fb_call_c *symbol); void *visit(il_formal_funct_call_c *symbol); // void *visit(il_operand_list_c *symbol); void *visit(simple_instr_list_c *symbol); void *visit(il_simple_instruction_c*symbol); // void *visit(il_param_list_c *symbol); // void *visit(il_param_assignment_c *symbol); // void *visit(il_param_out_assignment_c *symbol); /*******************/ /* B 2.2 Operators */ /*******************/ void *visit(LD_operator_c *symbol); void *visit(LDN_operator_c *symbol); void *visit(ST_operator_c *symbol); void *visit(STN_operator_c *symbol); void *visit(NOT_operator_c *symbol); void *visit(S_operator_c *symbol); void *visit(R_operator_c *symbol); void *visit(S1_operator_c *symbol); void *visit(R1_operator_c *symbol); void *visit(CLK_operator_c *symbol); void *visit(CU_operator_c *symbol); void *visit(CD_operator_c *symbol); void *visit(PV_operator_c *symbol); void *visit(IN_operator_c *symbol); void *visit(PT_operator_c *symbol); void *visit(AND_operator_c *symbol); void *visit(OR_operator_c *symbol); void *visit(XOR_operator_c *symbol); void *visit(ANDN_operator_c *symbol); void *visit(ORN_operator_c *symbol); void *visit(XORN_operator_c *symbol); void *visit(ADD_operator_c *symbol); void *visit(SUB_operator_c *symbol); void *visit(MUL_operator_c *symbol); void *visit(DIV_operator_c *symbol); void *visit(MOD_operator_c *symbol); void *visit(GT_operator_c *symbol); void *visit(GE_operator_c *symbol); void *visit(EQ_operator_c *symbol); void *visit(LT_operator_c *symbol); void *visit(LE_operator_c *symbol); void *visit(NE_operator_c *symbol); void *visit(CAL_operator_c *symbol); void *visit(CALC_operator_c *symbol); void *visit(CALCN_operator_c *symbol); void *visit(RET_operator_c *symbol); void *visit(RETC_operator_c *symbol); void *visit(RETCN_operator_c *symbol); void *visit(JMP_operator_c *symbol); void *visit(JMPC_operator_c *symbol); void *visit(JMPCN_operator_c *symbol); /* Symbol class handled together with function call checks */ // void *visit(il_assign_operator_c *symbol, variable_name); /* Symbol class handled together with function call checks */ // void *visit(il_assign_operator_c *symbol, option, variable_name); /***************************************/ /* B.3 - Language ST (Structured Text) */ /***************************************/ /***********************/ /* B 3.1 - Expressions */ /***********************/ void *visit( deref_operator_c *symbol); void *visit( deref_expression_c *symbol); void *visit( ref_expression_c *symbol); void *visit( or_expression_c *symbol); void *visit( xor_expression_c *symbol); void *visit( and_expression_c *symbol); void *visit( equ_expression_c *symbol); void *visit( notequ_expression_c *symbol); void *visit( lt_expression_c *symbol); void *visit( gt_expression_c *symbol); void *visit( le_expression_c *symbol); void *visit( ge_expression_c *symbol); void *visit( add_expression_c *symbol); void *visit( sub_expression_c *symbol); void *visit( mul_expression_c *symbol); void *visit( div_expression_c *symbol); void *visit( mod_expression_c *symbol); void *visit( power_expression_c *symbol); void *visit( neg_expression_c *symbol); void *visit( not_expression_c *symbol); void *visit(function_invocation_c *symbol); /*********************************/ /* B 3.2.1 Assignment Statements */ /*********************************/ void *visit(assignment_statement_c *symbol); /*****************************************/ /* B 3.2.2 Subprogram Control Statements */ /*****************************************/ void *visit(fb_invocation_c *symbol); /********************************/ /* B 3.2.3 Selection Statements */ /********************************/ void *visit(if_statement_c *symbol); void *visit(elseif_statement_c *symbol); void *visit(case_statement_c *symbol); void *visit(case_element_list_c *symbol); void *visit(case_element_c *symbol); void *visit(case_list_c *symbol); /********************************/ /* B 3.2.4 Iteration Statements */ /********************************/ void *visit(for_statement_c *symbol); void *visit(while_statement_c *symbol); void *visit(repeat_statement_c *symbol); }; // narrow_candidate_datatypes_c #endif // #ifndef _NARROW_CANDIDATE_DATATYPES_HH
17,479
C++
.h
349
45.498567
193
0.597528
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,686
forced_narrow_candidate_datatypes.hh
nucleron_matiec/stage3/forced_narrow_candidate_datatypes.hh
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2012 Mario de Sousa (msousa@fe.up.pt) * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* * forced_narrow_candidate_datatypes_c * */ #include "../absyntax_utils/absyntax_utils.hh" #include "narrow_candidate_datatypes.hh" class forced_narrow_candidate_datatypes_c: public narrow_candidate_datatypes_c { private: void forced_narrow_il_instruction(symbol_c *symbol, std::vector <symbol_c *> &next_il_instruction); protected: virtual void set_datatype_in_prev_il_instructions(symbol_c *datatype, il_instruction_c *symbol); public: forced_narrow_candidate_datatypes_c(symbol_c *ignore); virtual ~forced_narrow_candidate_datatypes_c(void); /****************************************/ /* B.2 - Language IL (Instruction List) */ /****************************************/ /***********************************/ /* B 2.1 Instructions and Operands */ /***********************************/ void *visit(instruction_list_c *symbol); void *visit(il_instruction_c *symbol); // void *visit(il_simple_operation_c *symbol); // void *visit(il_function_call_c *symbol); // void *visit(il_expression_c *symbol); // void *visit(il_jump_operation_c *symbol); // void *visit(il_fb_call_c *symbol); // void *visit(il_formal_funct_call_c *symbol); // void *visit(il_operand_list_c *symbol); // void *visit(simple_instr_list_c *symbol); void *visit(il_simple_instruction_c*symbol); // void *visit(il_param_list_c *symbol); // void *visit(il_param_assignment_c *symbol); // void *visit(il_param_out_assignment_c *symbol); // void *visit(il_assign_operator_c *symbol); // void *visit(il_assign_operator_c *symbol); /***************************************/ /* B.3 - Language ST (Structured Text) */ /***************************************/ void *visit(statement_list_c *symbol); }; // forced_narrow_candidate_datatypes_c
2,893
C++
.h
71
37.830986
103
0.651038
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,687
search_base_type.hh
nucleron_matiec/absyntax_utils/search_base_type.hh
/* * matiec - a compiler for the programming languages defined in IEC 61131-3 * * Copyright (C) 2003-2012 Mario de Sousa (msousa@fe.up.pt) * Copyright (C) 2007-2011 Laurent Bessard and Edouard Tisserant * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This code is made available on the understanding that it will not be * used in safety-critical situations without a full and competent review. */ /* * An IEC 61131-3 compiler. * * Based on the * FINAL DRAFT - IEC 61131-3, 2nd Ed. (2001-12-10) * */ /* Determine the data type on which another data type is based on. */ /* * What is a Base Type? * A base type is the fundamental data type from which the type is derived. * The main idea is that if two datatyes (A and B) share a common base type, * then these two datatypes may be used interchangeably in an expression. * * What is an Equivalent Type? * An equivalent type is the data type from which the type is derived. * The Base type and the Equivalent type will always be the same, with the * exception of subranges! * * E.g. TYPE new_int_t : INT; END_TYPE; * TYPE new_int2_t : INT := 2; END_TYPE; * TYPE new_int3_t : new_int2_t := 3; END_TYPE; * TYPE new_sub_t : INT (4..10); END_TYPE; * TYPE new_sub2_t : new_sub_t := 5 ; END_TYPE; * TYPE new_sub3_t : new_sub2_t := 6 ; END_TYPE; * TYPE new_sub4_t : new_int3_t (4..10); END_TYPE; <----- This is NOT legal syntax! * * new_int_t : base type->INT equivalent type->INT * new_int2_t : base type->INT equivalent type->INT * new_int3_t : base type->INT equivalent type->INT * new_sub_t : base type->INT equivalent type->new_sub_t * new_sub2_t : base type->INT equivalent type->new_sub_t * new_sub3_t : base type->INT equivalent type->new_sub_t * * Note too that a FB declaration is also considered a base type, as * we may have FB instances declared of a specific FB type. */ class search_base_type_c: public null_visitor_c { private: symbol_c *current_basetype_name; symbol_c *current_basetype; symbol_c *current_equivtype; static search_base_type_c *search_base_type_singleton; // Make this a singleton class! private: static void create_singleton(void); void *handle_datatype_identifier(token_c *type_name); public: search_base_type_c(void); static symbol_c *get_equivtype_decl(symbol_c *symbol); /* get the Equivalent Type declaration */ static symbol_c *get_basetype_decl (symbol_c *symbol); /* get the Base Type declaration */ static symbol_c *get_basetype_id (symbol_c *symbol); /* get the Base Type identifier */ public: /*************************/ /* B.1 - Common elements */ /*************************/ /*******************************************/ /* B 1.1 - Letters, digits and identifiers */ /*******************************************/ void *visit( identifier_c *type_name); void *visit(derived_datatype_identifier_c *type_name); void *visit( poutype_identifier_c *type_name); /*********************/ /* B 1.2 - Constants */ /*********************/ /******************************/ /* B 1.2.1 - Numeric Literals */ /******************************/ /* Numeric literals without any explicit type cast have unknown data type, * so we continue considering them as their own basic data types until * they can be resolved (for example, when using '30+x' where 'x' is a LINT variable, the * numeric literal '30' must then be considered a LINT so the ADD function may be called * with all inputs of the same data type. * If 'x' were a SINT, then the '30' would have to be a SINT too! */ void *visit(real_c *symbol); void *visit(neg_real_c *symbol); void *visit(integer_c *symbol); void *visit(neg_integer_c *symbol); void *visit(binary_integer_c *symbol); void *visit(octal_integer_c *symbol); void *visit(hex_integer_c *symbol); void *visit(boolean_true_c *symbol); void *visit(boolean_false_c *symbol); /***********************************/ /* B 1.3.1 - Elementary Data Types */ /***********************************/ void *visit(time_type_name_c *symbol); void *visit(bool_type_name_c *symbol); void *visit(sint_type_name_c *symbol); void *visit(int_type_name_c *symbol); void *visit(dint_type_name_c *symbol); void *visit(lint_type_name_c *symbol); void *visit(usint_type_name_c *symbol); void *visit(uint_type_name_c *symbol); void *visit(udint_type_name_c *symbol); void *visit(ulint_type_name_c *symbol); void *visit(real_type_name_c *symbol); void *visit(lreal_type_name_c *symbol); void *visit(date_type_name_c *symbol); void *visit(tod_type_name_c *symbol); void *visit(dt_type_name_c *symbol); void *visit(byte_type_name_c *symbol); void *visit(word_type_name_c *symbol); void *visit(dword_type_name_c *symbol); void *visit(lword_type_name_c *symbol); void *visit(string_type_name_c *symbol); void *visit(wstring_type_name_c *symbol); void *visit(void_type_name_c *symbol); /* A non standard datatype! */ /******************************************************/ /* Extensions to the base standard as defined in */ /* "Safety Software Technical Specification, */ /* Part 1: Concepts and Function Blocks, */ /* Version 1.0 – Official Release" */ /* by PLCopen - Technical Committee 5 - 2006-01-31 */ /******************************************************/ void *visit(safetime_type_name_c *symbol); void *visit(safebool_type_name_c *symbol); void *visit(safesint_type_name_c *symbol); void *visit(safeint_type_name_c *symbol); void *visit(safedint_type_name_c *symbol); void *visit(safelint_type_name_c *symbol); void *visit(safeusint_type_name_c *symbol); void *visit(safeuint_type_name_c *symbol); void *visit(safeudint_type_name_c *symbol); void *visit(safeulint_type_name_c *symbol); void *visit(safereal_type_name_c *symbol); void *visit(safelreal_type_name_c *symbol); void *visit(safedate_type_name_c *symbol); void *visit(safetod_type_name_c *symbol); void *visit(safedt_type_name_c *symbol); void *visit(safebyte_type_name_c *symbol); void *visit(safeword_type_name_c *symbol); void *visit(safedword_type_name_c *symbol); void *visit(safelword_type_name_c *symbol); void *visit(safestring_type_name_c *symbol); void *visit(safewstring_type_name_c *symbol); /********************************/ /* B.1.3.2 - Generic data types */ /********************************/ void *visit(generic_type_any_c *symbol); /********************************/ /* B 1.3.3 - Derived data types */ /********************************/ /* simple_type_name ':' simple_spec_init */ void *visit(simple_type_declaration_c *symbol); /* simple_specification ASSIGN constant */ void *visit(simple_spec_init_c *symbol); /* subrange_type_name ':' subrange_spec_init */ void *visit(subrange_type_declaration_c *symbol); /* subrange_specification ASSIGN signed_integer */ void *visit(subrange_spec_init_c *symbol); /* integer_type_name '(' subrange')' */ void *visit(subrange_specification_c *symbol); /* signed_integer DOTDOT signed_integer */ void *visit(subrange_c *symbol); /* enumerated_type_name ':' enumerated_spec_init */ void *visit(enumerated_type_declaration_c *symbol); /* enumerated_specification ASSIGN enumerated_value */ void *visit(enumerated_spec_init_c *symbol); /* helper symbol for enumerated_specification->enumerated_spec_init */ /* enumerated_value_list ',' enumerated_value */ void *visit(enumerated_value_list_c *symbol); /* enumerated_type_name '#' identifier */ // SYM_REF2(enumerated_value_c, type, value) void *visit(enumerated_value_c *symbol); /* identifier ':' array_spec_init */ void *visit(array_type_declaration_c *symbol); /* array_specification [ASSIGN array_initialization} */ /* array_initialization may be NULL ! */ void *visit(array_spec_init_c *symbol); /* ARRAY '[' array_subrange_list ']' OF non_generic_type_name */ void *visit(array_specification_c *symbol); /* helper symbol for array_specification */ /* array_subrange_list ',' subrange */ void *visit(array_subrange_list_c *symbol); /* array_initialization: '[' array_initial_elements_list ']' */ /* helper symbol for array_initialization */ /* array_initial_elements_list ',' array_initial_elements */ void *visit(array_initial_elements_list_c *symbol); /* integer '(' [array_initial_element] ')' */ /* array_initial_element may be NULL ! */ void *visit(array_initial_elements_c *symbol); /* structure_type_name ':' structure_specification */ /* NOTE: structure_specification will point to either a * initialized_structure_c * OR A * structure_element_declaration_list_c */ void *visit(structure_type_declaration_c *symbol); /* var1_list ':' structure_type_name */ void *visit(structured_var_declaration_c *symbol); /* structure_type_name ASSIGN structure_initialization */ /* structure_initialization may be NULL ! */ void *visit(initialized_structure_c *symbol); /* helper symbol for structure_declaration */ /* structure_declaration: STRUCT structure_element_declaration_list END_STRUCT */ /* structure_element_declaration_list structure_element_declaration ';' */ void *visit(structure_element_declaration_list_c *symbol); /* structure_element_name ':' *_spec_init */ void *visit(structure_element_declaration_c *symbol); /* helper symbol for structure_initialization */ /* structure_initialization: '(' structure_element_initialization_list ')' */ /* structure_element_initialization_list ',' structure_element_initialization */ void *visit(structure_element_initialization_list_c *symbol); /* structure_element_name ASSIGN value */ void *visit(structure_element_initialization_c *symbol); /* string_type_name ':' elementary_string_type_name string_type_declaration_size string_type_declaration_init */ /* SYM_REF4(string_type_declaration_c, string_type_name, elementary_string_type_name, string_type_declaration_size, string_type_declaration_init) // may be == NULL! */ void *visit(string_type_declaration_c *symbol); /* function_block_type_name ASSIGN structure_initialization */ /* structure_initialization -> may be NULL ! */ void *visit(fb_spec_init_c *symbol); /* REF_TO (non_generic_type_name | function_block_type_name) */ void *visit(ref_spec_c *symbol); // Defined in IEC 61131-3 v3 /* ref_spec [ ASSIGN ref_initialization ]; *//* NOTE: ref_initialization may be NULL!! */ void *visit(ref_spec_init_c *symbol); // Defined in IEC 61131-3 v3 /* identifier ':' ref_spec_init */ void *visit(ref_type_decl_c *symbol); // Defined in IEC 61131-3 v3 /*****************************/ /* B 1.5.2 - Function Blocks */ /*****************************/ /* FUNCTION_BLOCK derived_function_block_name io_OR_other_var_declarations function_block_body END_FUNCTION_BLOCK */ // SYM_REF3(function_block_declaration_c, fblock_name, var_declarations, fblock_body) void *visit(function_block_declaration_c *symbol); /*********************************************/ /* B.1.6 Sequential function chart elements */ /*********************************************/ /* INITIAL_STEP step_name ':' action_association_list END_STEP */ // SYM_REF2(initial_step_c, step_name, action_association_list) void *visit(initial_step_c *symbol); /* STEP step_name ':' action_association_list END_STEP */ // SYM_REF2(step_c, step_name, action_association_list) void *visit(step_c *symbol); }; // search_base_type_c
12,669
C++
.h
262
44.416031
119
0.639075
nucleron/matiec
132
47
5
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
754,689
main.cpp
dridri_bcflight/controller_rc/main.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <execinfo.h> #include <signal.h> #include <iostream> #include <Link.h> #include "ControllerClient.h" #include "ui/GlobalUI.h" #include "Config.h" #include "Debug.h" #include <links/Socket.h> #include <nRF24L01.h> #include <SX127x.h> #ifdef BUILD_rawwifi #include <RawWifi.h> #endif void SegFaultHandler( int sig ) { std::string msg; char name[64] = ""; pthread_getname_np( pthread_self(), name, sizeof(name) ); if ( name[0] == '\0' or !strcmp( name, "flight" ) ) { msg = "Thread <unknown> crashed !"; } else { msg = "Thread \"" + std::string(name) + "\" crashed !"; } std::cout << "\e[0;41m" << msg << "\e[0m\n"; void* array[16]; size_t size; size = backtrace( array, 16 ); fprintf( stderr, "Error: signal %d :\n", sig ); char** trace = backtrace_symbols( array, size ); std::cout << "\e[91mStack trace :\e[0m\n"; for ( size_t j = 0; j < size; j++ ) { std::cout << "\e[91m" << trace[j] << "\e[0m\n"; } while ( 1 ) { usleep( 1000 * 1000 * 10 ); } } int main( int ac, char** av ) { Debug::setDebugLevel( Debug::Verbose ); Controller* controller = nullptr; Link* controller_link = nullptr; struct sigaction sa; memset( &sa, 0, sizeof(sa) ); sa.sa_handler = &SegFaultHandler; sigaction( 11, &sa, NULL ); if ( ac <= 1 ) { std::cout << "FATAL ERROR : No config file specified !\n"; return -1; } Config* config = new Config( av[1] ); config->Reload(); Debug::setDebugLevel( static_cast<Debug::Level>( config->integer( "debug_level", 3 ) ) ); config->LoadSettings(); if ( config->string( "controller.link.link_type" ) == "Socket" ) { ::Socket::PortType type = ::Socket::TCP; if ( config->string( "controller.link.type" ) == "UDP" ) { type = ::Socket::UDP; } else if ( config->string( "controller.link.type" ) == "UDPLite" ) { type = ::Socket::UDPLite; } controller_link = new ::Socket( config->string( "controller.link.address", "192.168.32.1" ), config->integer( "controller.link.port", 2020 ), type ); } else if ( config->string( "controller.link.link_type" ) == "nRF24L01" ) { std::string device = config->string( "controller.link.device", "spidev1." ); int cspin = config->integer( "controller.link.cspin", -1 ); int cepin = config->integer( "controller.link.cepin", -1 ); int irqpin = config->integer( "controller.link.irqpin", -1 ); int channel = config->integer( "controller.link.channel", 100 ); int input_port = config->integer( "controller.link.input_port", 1 ); int output_port = config->integer( "controller.link.output_port", 0 ); bool drop_invalid_packets = config->boolean( "controller.link.drop", true ); bool blocking = config->boolean( "controller.link.blocking", true ); if ( cspin < 0 ) { std::cout << "WARNING : No CS-pin specified for nRF24L01, cannot create link !\n"; } else if ( cepin < 0 ) { std::cout << "WARNING : No CE-pin specified for nRF24L01, cannot create link !\n"; } else { controller_link = new nRF24L01( device, cspin, cepin, irqpin, channel, input_port, output_port, drop_invalid_packets ); controller_link->setBlocking( blocking ); } } else if ( config->string( "controller.link.link_type" ) == "SX127x" ) { SX127x::Config conf; memset( &conf, 0, sizeof(SX127x::Config) ); strncpy( conf.device, config->string( "controller.link.device", "spidev1.1" ).c_str(), sizeof(conf.device)-1 ); conf.resetPin = config->integer( "controller.link.resetpin", -1 ); conf.txPin = config->integer( "controller.link.txpin", -1 ); conf.rxPin = config->integer( "controller.link.rxpin", -1 ); conf.irqPin = config->integer( "controller.link.irqpin", -1 ); conf.frequency = config->integer( "controller.link.frequency", 433000000 ); conf.inputPort = config->integer( "controller.link.input_port", 1 ); conf.outputPort = config->integer( "controller.link.output_port", 0 ); conf.dropBroken = config->boolean( "controller.link.drop", true ); conf.blocking = config->boolean( "controller.link.blocking", true ); conf.retries = config->integer( "controller.link.retries", 1 ); conf.bitrate = config->integer( "controller.link.bitrate", 76800 ); conf.bandwidth = config->integer( "controller.link.bandwidth", 250000 ); conf.bandwidthAfc = config->integer( "controller.link.bandwidthAfc", 500000 ); conf.fdev = config->integer( "controller.link.fdev", 20000 ); conf.modem = config->string( "controller.link.modem", "FSK" ) == "LoRa" ? SX127x::LoRa : SX127x::FSK; controller_link = new SX127x( conf ); } else { #ifdef BUILD_rawwifi controller_link = new RawWifi( config->string( "controller.link.device", "wlan0" ), config->integer( "controller.link.output_port", 0 ), config->integer( "controller.link.input_port", 1 ), -1 ); static_cast< RawWifi* >( controller_link )->SetChannel( config->integer( "controller.link.channel", 11 ) ); #endif } controller = new ControllerClient( config, controller_link, config->boolean( "controller.spectate", false ) ); controller->setUpdateFrequency( config->integer( "controller.update_frequency", 100 ) ); GlobalUI* ui = new GlobalUI( config, controller ); ui->Start(); while ( 1 ) { usleep( 1000 * 1000 ); } std::cout << "Exiting (this should not happen)\n"; return 0; }
5,907
C++
.cpp
134
41.686567
196
0.683689
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,690
Config.cpp
dridri_bcflight/controller_rc/Config.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <list> #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include "Config.h" Config::Config( const std::string& filename ) : mFilename( filename ) , L( nullptr ) { L = luaL_newstate(); // luaL_openlibs( L ); Reload(); } Config::~Config() { lua_close(L); } std::string Config::ReadFile() { std::string ret = ""; std::ifstream file( mFilename ); if ( file.is_open() ) { file.seekg( 0, file.end ); int length = file.tellg(); char* buf = new char[ length + 1 ]; file.seekg( 0, file.beg ); file.read( buf, length ); buf[length] = 0; ret = buf; delete buf; file.close(); } return ret; } void Config::WriteFile( const std::string& content ) { std::ofstream file( mFilename ); if ( file.is_open() ) { file.write( content.c_str(), content.length() ); file.close(); } } std::string Config::string( const std::string& name, const std::string& def ) { std::cout << "Config::string( " << name << " )"; if ( LocateValue( name ) < 0 ) { std::cout << " => not found !\n"; return def; } std::string ret = lua_tolstring( L, -1, nullptr ); std::cout << " => " << ret << "\n"; return ret; } int Config::integer( const std::string& name, int def ) { std::cout << "Config::integer( " << name << " )"; if ( LocateValue( name ) < 0 ) { std::cout << " => not found !\n"; return def; } int ret = lua_tointeger( L, -1 ); std::cout << " => " << ret << "\n"; return ret; } float Config::number( const std::string& name, float def ) { std::cout << "Config::number( " << name << " )"; if ( LocateValue( name ) < 0 ) { std::cout << " => not found !\n"; return def; } float ret = lua_tonumber( L, -1 ); std::cout << " => " << ret << "\n"; return ret; } bool Config::boolean( const std::string& name, bool def ) { std::cout << "Config::boolean( " << name << " )"; if ( LocateValue( name ) < 0 ) { std::cout << " => not found !\n"; return def; } bool ret = lua_toboolean( L, -1 ); std::cout << " => " << ret << "\n"; return ret; } std::vector<int> Config::integerArray( const std::string& name ) { std::cout << "Config::integerArray( " << name << " )"; if ( LocateValue( name ) < 0 ) { std::cout << " => not found !\n"; return std::vector<int>(); } std::vector<int> ret; size_t len = lua_objlen( L, -1 ); if ( len > 0 ) { for ( size_t i = 1; i <= len; i++ ) { lua_rawgeti( L, -1, i ); int value = lua_tointeger( L, -1 ); ret.emplace_back( value ); lua_pop( L, 1 ); } } lua_pop( L, 1 ); std::cout << " => Ok\n"; return ret; } int Config::LocateValue( const std::string& _name ) { const char* name = _name.c_str(); if ( strchr( name, '.' ) == nullptr ) { lua_getfield( L, LUA_GLOBALSINDEX, name ); } else { char tmp[128]; int i, j, k; for ( i = 0, j = 0, k = 0; name[i]; i++ ) { if ( name[i] == '.' ) { tmp[j] = 0; if ( k == 0 ) { lua_getfield( L, LUA_GLOBALSINDEX, tmp ); } else { lua_getfield( L, -1, tmp ); } if ( lua_type( L, -1 ) == LUA_TNIL ) { return -1; } memset( tmp, 0, sizeof( tmp ) ); j = 0; k++; } else { tmp[j] = name[i]; j++; } } tmp[j] = 0; lua_getfield( L, -1, tmp ); if ( lua_type( L, -1 ) == LUA_TNIL ) { return -1; } } return 0; } void Config::DumpVariable( const std::string& name, int index, int indent ) { for ( int i = 0; i < indent; i++ ) { std::cout << " "; } if ( name != "" ) { std::cout << name << " = "; } if ( indent == 0 ) { LocateValue( name ); } if ( lua_isnil( L, index ) ) { std::cout << "nil"; } else if ( lua_isnumber( L, index ) ) { std::cout << lua_tonumber( L, index ); } else if ( lua_isboolean( L, index ) ) { std::cout << ( lua_toboolean( L, index ) ? "true" : "false" ); } else if ( lua_isstring( L, index ) ) { std::cout << "\"" << lua_tostring( L, index ) << "\""; } else if ( lua_iscfunction( L, index ) ) { std::cout << "C-function()"; } else if ( lua_isuserdata( L, index ) ) { std::cout << "__userdata__"; } else if ( lua_istable( L, index ) ) { std::cout << "{\n"; size_t len = lua_objlen( L, index ); if ( len > 0 ) { for ( size_t i = 1; i <= len; i++ ) { lua_rawgeti( L, index, i ); DumpVariable( "", -1, indent + 1 ); lua_pop( L, 1 ); std::cout << ",\n"; } } else { lua_pushnil( L ); while( lua_next( L, -2 ) != 0 ) { std::string key = lua_tostring( L, index-1 ); if ( lua_isnumber( L, index - 1 ) ) { key = "[" + key + "]"; } DumpVariable( key, index, indent + 1 ); lua_pop( L, 1 ); std::cout << ",\n"; } } for ( int i = 0; i < indent; i++ ) { std::cout << " "; } std::cout << "}"; } else { std::cout << "__unknown__"; } if ( indent == 0 ) { std::cout << "\n"; } } void Config::Reload() { luaL_dostring( L, "function Vector( x, y, z, w ) return { x = x, y = y, z = z, w = w } end" ); luaL_dostring( L, "function Socket( params ) params.link_type = \"Socket\" ; return params end" ); luaL_dostring( L, "function RF24( params ) params.link_type = \"nRF24L01\" ; return params end" ); luaL_dostring( L, "function SX127x( params ) params.link_type = \"SX127x\" ; return params end" ); luaL_dostring( L, "function RawWifi( params ) params.link_type = \"RawWifi\" ; if params.device == nil then params.device = \"wlan0\" end ; if params.blocking == nil then params.blocking = true end ; if params.retries == nil then params.retries = 2 end ; return params end" ); luaL_dostring( L, "function Voltmeter( params ) params.sensor_type = \"Voltmeter\" ; return params end" ); luaL_dostring( L, "function Buzzer( params ) params.type = \"Buzzer\" ; return params end" ); luaL_dostring( L, "battery = {}" ); luaL_dostring( L, "controller = {}" ); luaL_dostring( L, "stream = {}" ); luaL_dostring( L, "touchscreen = {}" ); luaL_loadfile( L, mFilename.c_str() ); int ret = lua_pcall( L, 0, LUA_MULTRET, 0 ); if ( ret != 0 ) { std::cout << "Lua : Error while executing file \"" << mFilename << "\" : \"" << lua_tostring( L, -1 ) << "\"\n"; return; } } void Config::Save() { } const bool Config::setting( const std::string& name, const bool def ) const { if ( mSettings.count( name ) > 0 ) { return ( mSettings.at( name ) == "true" ); } return def; } const int Config::setting( const std::string& name, const int def ) const { if ( mSettings.count( name ) > 0 ) { return atoi( mSettings.at( name ).c_str() ); } return def; } const float Config::setting( const std::string& name, const float def ) const { if ( mSettings.count( name ) > 0 ) { return atof( mSettings.at( name ).c_str() ); } return def; } const std::string& Config::setting( const std::string& name, const std::string& def ) const { if ( mSettings.count( name ) > 0 ) { return mSettings.at( name ); } return def; } void Config::setSetting( const std::string& name, const bool v ) { mSettings[ name ] = ( v ? "true" : "false" ); } void Config::setSetting( const std::string& name, const int v ) { std::stringstream ss; ss << v; mSettings[ name ] = ss.str(); } void Config::setSetting( const std::string& name, const float v ) { std::stringstream ss; ss << v; mSettings[ name ] = ss.str(); } void Config::setSetting( const std::string& name, const std::string& v ) { mSettings[ name ] = v; } void Config::LoadSettings( const std::string& filename ) { std::string line; std::string key; std::string value; std::ifstream file( filename, std::ios_base::in ); if ( file.is_open() ) { while ( std::getline( file, line ) ) { key = line.substr( 0, line.find( "=" ) ); value = line.substr( line.find( "=" ) + 1 ); mSettings[ key ] = value; std::cout << "mSettings[ " << key << " ] = '" << mSettings[ key ] << "'\n"; } } } void Config::SaveSettings( const std::string& filename ) { std::stringstream ss; std::ofstream file( filename, std::ios_base::out ); if ( file.is_open() ) { for ( auto it : mSettings ) { ss.str( "" ); ss << it.first << "=" << it.second << "\n"; std::cout << "Write : " << ss.str(); file.write( ss.str().c_str(), ss.str().length() ); } } }
8,847
C++
.cpp
315
25.530159
277
0.590598
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,691
GlobalUI.cpp
dridri_bcflight/controller_rc/ui/GlobalUI.cpp
#include <iostream> #include <unistd.h> #include <linux/input.h> #include <QtCore/QtPlugin> #include "GlobalUI.h" #include "MainWindow.h" #include "Controller.h" #include "Config.h" #ifndef BOARD_generic // Q_IMPORT_PLUGIN( QLinuxFbIntegrationPlugin ); #endif GlobalUI::GlobalUI( Config* config, Controller* controller ) : Thread( "GlobalUI" ) , mApplication( nullptr ) , mConfig( config ) , mController( controller ) { } GlobalUI::~GlobalUI() { } bool GlobalUI::run() { if ( mApplication == nullptr ) { std::string fbdev = "linuxfb:fb=" + mConfig->string( "touchscreen.framebuffer", "/dev/fb0" ); std::string rotate = "QT_QPA_EVDEV_TOUCHSCREEN_PARAMETERS=/dev/input/event0:rotate=" + std::to_string( mConfig->integer( "touchscreen.rotate", 0 ) ); std::cout << fbdev << "\n"; std::cout << rotate << "\n"; putenv( (char*)rotate.c_str() ); putenv( (char*)"QT_QPA_FB_DISABLE_INPUT=0" ); putenv( (char*)"QT_QPA_FB_NO_LIBINPUT=0" ); putenv( (char*)"QT_QPA_FB_USE_LIBINPUT=0" ); putenv( (char*)"QT_LOGGING_RULES=qt.qpa.input=true" ); int ac = 3; const char* av[4] = { "controller", "-platform", fbdev.c_str(), nullptr }; #ifdef BOARD_generic ac = 1; #endif mApplication = new QApplication( ac, (char**)av ); QPalette palette; palette.setColor( QPalette::Window, QColor( 49, 54, 59 ) ); palette.setColor( QPalette::WindowText, Qt::white ); palette.setColor( QPalette::Base, QColor( 35, 38, 41 ) ); palette.setColor( QPalette::AlternateBase, QColor( 35, 38, 41 ) ); palette.setColor( QPalette::ToolTipBase, Qt::white ); palette.setColor( QPalette::ToolTipText, Qt::white ); palette.setColor( QPalette::Text, Qt::white ); palette.setColor( QPalette::Button, QColor( 31, 36, 41 ) ); palette.setColor( QPalette::ButtonText, Qt::white ); palette.setColor( QPalette::BrightText, Qt::blue ); palette.setColor( QPalette::Highlight, QColor( 142, 0, 0 ) ); palette.setColor( QPalette::HighlightedText, Qt::black ); palette.setColor( QPalette::Disabled, QPalette::Text, Qt::darkGray ); palette.setColor( QPalette::Disabled, QPalette::ButtonText, Qt::darkGray ); mApplication->setPalette( palette ); mMainWindow = new MainWindow( mController ); mMainWindow->setGeometry( 0, 0, 480, 320 ); mMainWindow->setMinimumSize( 480, 320 ); mMainWindow->setMaximumSize( 480, 320 ); mMainWindow->show(); } printf( "UI running\n" ); return mApplication->exec(); mMainWindow->Update(); mApplication->processEvents(); #ifndef BOARD_generic usleep( 1000 * 1000 / 10 ); #endif return true; }
2,549
C++
.cpp
70
34.085714
151
0.704785
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,692
MainWindow.cpp
dridri_bcflight/controller_rc/ui/MainWindow.cpp
#include <QtWidgets/QGridLayout> #include <QtGui/QFontDatabase> #include <cmath> #include "MainWindow.h" #include "ui_window.h" #include "ui_main.h" #include "ui_calibrate.h" #include "ui_camera.h" #include "ui_network.h" #include "ui_settings.h" #include <links/Socket.h> #ifdef BUILD_rawwifi #include <links/RawWifi.h> #else #define NO_RAWWIFI #endif MainWindow::MainWindow( Controller* controller ) : QMainWindow() , mController( controller ) , mUpdateTimer( new QTimer( this ) ) { for ( uint32_t i = 0; i < 4; i++ ) { mCalibrationValues[i].min = 65535; mCalibrationValues[i].center = 0; mCalibrationValues[i].max = 0; } mCameraLensShader.r.base = 64; mCameraLensShader.g.base = 64; mCameraLensShader.b.base = 64; ui = new Ui::MainWindow; ui->setupUi(this); ui->gridLayout_2->setMargin( 0 ); ui->gridLayout_2->setSpacing( 0 ); ui->centralLayout->setMargin( 0 ); ui->centralLayout->setSpacing( 0 ); connect( ui->btnHome, SIGNAL( clicked() ), this, SLOT( Home() ) ); connect( ui->btnCalibrate, SIGNAL( clicked() ), this, SLOT( Calibrate() ) ); connect( ui->btnNetwork, SIGNAL( clicked() ), this, SLOT( Network() ) ); connect( ui->btnCamera, SIGNAL( clicked() ), this, SLOT( Camera() ) ); connect( ui->btnSettings, SIGNAL( clicked() ), this, SLOT( Settings() ) ); uiPageMain = new Ui::PageMain; mPageMain = new QWidget(); uiPageMain->setupUi( mPageMain ); connect( uiPageMain->calibrate_gyro, SIGNAL( clicked() ), this, SLOT( CalibrateGyro() ) ); connect( uiPageMain->calibrate_imu, SIGNAL( clicked() ), this, SLOT( CalibrateIMU() ) ); connect( uiPageMain->beep, SIGNAL( released() ), this, SLOT( MotorsBeep() ) ); connect( uiPageMain->reset_battery, SIGNAL( clicked() ), this, SLOT( ResetBattery() ) ); uiPageCalibrate = new Ui::PageCalibrate; mPageCalibrate = new QWidget(); uiPageCalibrate->setupUi( mPageCalibrate ); connect( uiPageCalibrate->btnReset, SIGNAL( clicked() ), this, SLOT( CalibrationReset() ) ); connect( uiPageCalibrate->btnApply, SIGNAL( clicked() ), this, SLOT( CalibrationApply() ) ); uiPageCamera = new Ui::PageCamera; mPageCamera = new QWidget(); uiPageCamera->setupUi( mPageCamera ); connect( uiPageCamera->white_balance, SIGNAL( clicked() ), this, SLOT( VideoWhiteBalance() ) ); connect( uiPageCamera->lock_white_balance, SIGNAL( clicked() ), this, SLOT( VideoLockWhiteBalance() ) ); connect( uiPageCamera->exposure_mode, SIGNAL( clicked() ), this, SLOT( VideoExposureMode() ) ); connect( uiPageCamera->brightness_dec, SIGNAL( clicked() ), this, SLOT( VideoBrightnessDecrease() ) ); connect( uiPageCamera->brightness_inc, SIGNAL( clicked() ), this, SLOT( VideoBrightnessIncrease() ) ); connect( uiPageCamera->contrast_dec, SIGNAL( clicked() ), this, SLOT( VideoContrastDecrease() ) ); connect( uiPageCamera->contrast_inc, SIGNAL( clicked() ), this, SLOT( VideoContrastIncrease() ) ); connect( uiPageCamera->saturation_dec, SIGNAL( clicked() ), this, SLOT( VideoSaturationDecrease() ) ); connect( uiPageCamera->saturation_inc, SIGNAL( clicked() ), this, SLOT( VideoSaturationIncrease() ) ); connect( uiPageCamera->iso_dec, SIGNAL( clicked() ), this, SLOT( VideoIsoDecrease() ) ); connect( uiPageCamera->iso_inc, SIGNAL( clicked() ), this, SLOT( VideoIsoIncrease() ) ); connect( uiPageCamera->iso_auto, SIGNAL( clicked() ), this, SLOT( VideoIsoAuto() ) ); connect( uiPageCamera->shutter_speed_dec, SIGNAL( clicked() ), this, SLOT( VideoShutterSpeedDecrease() ) ); connect( uiPageCamera->shutter_speed_inc, SIGNAL( clicked() ), this, SLOT( VideoShutterSpeedIncrease() ) ); connect( uiPageCamera->shutter_speed_auto, SIGNAL( clicked() ), this, SLOT( VideoShutterSpeedAuto() ) ); connect( uiPageCamera->r_base_dec, &QPushButton::clicked, [this](){ mCameraLensShader.r.base = std::max( 0, mCameraLensShader.r.base - 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->r_base_inc, &QPushButton::clicked, [this](){ mCameraLensShader.r.base = std::min( 255, mCameraLensShader.r.base + 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->r_radius_dec, &QPushButton::clicked, [this](){ mCameraLensShader.r.radius = std::max( 0, mCameraLensShader.r.radius - 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->r_radius_inc, &QPushButton::clicked, [this](){ mCameraLensShader.r.radius = std::min( 128, mCameraLensShader.r.radius + 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->r_strength_dec, &QPushButton::clicked, [this](){ mCameraLensShader.r.strength = std::max( -255, mCameraLensShader.r.strength - 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->r_strength_inc, &QPushButton::clicked, [this](){ mCameraLensShader.r.strength = std::min( 255, mCameraLensShader.r.strength + 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->g_base_dec, &QPushButton::clicked, [this](){ mCameraLensShader.g.base = std::max( 0, mCameraLensShader.g.base - 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->g_base_inc, &QPushButton::clicked, [this](){ mCameraLensShader.g.base = std::min( 255, mCameraLensShader.g.base + 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->g_radius_dec, &QPushButton::clicked, [this](){ mCameraLensShader.g.radius = std::max( 0, mCameraLensShader.g.radius - 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->g_radius_inc, &QPushButton::clicked, [this](){ mCameraLensShader.g.radius = std::min( 128, mCameraLensShader.g.radius + 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->g_strength_dec, &QPushButton::clicked, [this](){ mCameraLensShader.g.strength = std::max( -255, mCameraLensShader.g.strength - 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->g_strength_inc, &QPushButton::clicked, [this](){ mCameraLensShader.g.strength = std::min( 255, mCameraLensShader.g.strength + 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->b_base_dec, &QPushButton::clicked, [this](){ mCameraLensShader.b.base = std::max( 0, mCameraLensShader.b.base - 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->b_base_inc, &QPushButton::clicked, [this](){ mCameraLensShader.b.base = std::min( 255, mCameraLensShader.b.base + 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->b_radius_dec, &QPushButton::clicked, [this](){ mCameraLensShader.b.radius = std::max( 0, mCameraLensShader.b.radius - 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->b_radius_inc, &QPushButton::clicked, [this](){ mCameraLensShader.b.radius = std::min( 128, mCameraLensShader.b.radius + 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->b_strength_dec, &QPushButton::clicked, [this](){ mCameraLensShader.b.strength = std::max( -255, mCameraLensShader.b.strength - 1 ); this->CameraUpdateLensShader(); } ); connect( uiPageCamera->b_strength_inc, &QPushButton::clicked, [this](){ mCameraLensShader.b.strength = std::min( 255, mCameraLensShader.b.strength + 1 ); this->CameraUpdateLensShader(); } ); uiPageNetwork = new Ui::PageNetwork; mPageNetwork = new QWidget(); uiPageNetwork->setupUi( mPageNetwork ); connect( uiPageNetwork->vtxReset, &QPushButton::clicked, this, &MainWindow::VTXReset ); connect( uiPageNetwork->vtxSet, &QPushButton::clicked, this, &MainWindow::VTXSet ); /* #ifdef NO_RAWWIFI uiPageNetwork->btnRawWifi->setVisible( false ); #else if ( static_cast<RawWifi*>(mController->link()) != nullptr ) { uiPageNetwork->btnRawWifi->setChecked( true ); } else #endif if ( static_cast<Socket*>(mController->link()) != nullptr ) { uiPageNetwork->btnSocket->setChecked( true ); } */ uiPageSettings = new Ui::PageSettings; mPageSettings = new QWidget(); uiPageSettings->setupUi( mPageSettings ); connect( uiPageSettings->simulatorMode, SIGNAL( toggled(bool) ), this, SLOT( SimulatorMode(bool) ) ); int id = QFontDatabase::addApplicationFont( "data/FreeMonoBold.ttf" ); QString family = QFontDatabase::applicationFontFamilies(id).at(0); QFont mono( family, 14 ); mono.setBold( true ); QFont mono_medium( family, 13 ); mono_medium.setBold( true ); QFont mono_small( family, 12 ); setFont( mono ); // mPageMain->setFont( mono ); uiPageMain->status->setFont( mono_small ); uiPageMain->warnings->setFont( mono_medium ); ui->btnHome->setChecked( true ); ui->centralLayout->addWidget( mPageMain ); connect( mUpdateTimer, SIGNAL( timeout() ), this, SLOT( Update() ) ); mUpdateTimer->start( 1000 / 10 ); QTimer* fullRepaintTimer = new QTimer( this ); connect( fullRepaintTimer, SIGNAL( timeout() ), this, SLOT( repaint() ) ); fullRepaintTimer->start( 1000 ); } MainWindow::~MainWindow() { delete ui; } void MainWindow::Update() { if ( ui->btnHome->isChecked() ) { std::string status = ""; std::string warnings = ""; if ( not mController->isConnected() ) { status = "Disconnected"; } else { if ( mController->username() != "" ) { status += "Connected to " + mController->username() + "\n"; } else { status += "Connected\n"; } if ( mController->calibrating() ) { status += "Calibrating...\n"; } else if ( not mController->calibrated() ) { status += "Gyro calibration needed\n"; } if ( status == "" ) { status = "Ready\n"; } if ( mController->mode() == Controller::Stabilize ) { status += "Stabilized mode\n"; } else if ( mController->mode() == Controller::Rate ) { status += "Accro mode\n"; } if ( mController->armed() ) { status += "Armed\n"; } else { status += "Disarmed\n"; } if ( mController->batteryLevel() < 0.15f ) { warnings += "LOW DRONE BATTERY\n"; } if ( mController->localBatteryVoltage() < 0.15f ) { warnings += "LOW CONTROLLER BATTERY\n"; } if ( mController->CPUTemp() > 80 ) { warnings += "HIGH CPU TEMP (" + std::to_string(mController->CPUTemp()) + "°C)\n"; } if ( mController->cameraMissing() ) { warnings += "CAMERA MISSING\n"; } } uiPageMain->status->setText( QString::fromStdString( status ) ); uiPageMain->warnings->setText( QString::fromStdString( warnings ) ); uiPageMain->localVoltage->setText( QString("%1 V").arg( (double)mController->localBatteryVoltage(), 5, 'f', 2, '0' ) ); uiPageMain->voltage->setText( QString("%1 V").arg( (double)mController->batteryVoltage(), 5, 'f', 2, '0' ) ); uiPageMain->totalCurrent->setText( QString("%1 mAh").arg( mController->totalCurrent() ) ); uiPageMain->latency->setText( QString("%1 ms").arg( mController->ping() ) ); if ( mController->link()->RxQuality() > 0 ) { uiPageMain->txquality->setText( QString("%1% TX").arg( mController->droneRxQuality() ) ); } else { uiPageMain->txquality->setText( QString("??% TX") ); } uiPageMain->txlevel->setText( QString("%1 dBm").arg( mController->droneRxLevel() ) ); uiPageMain->rxquality->setText( QString("%1% RX").arg( mController->link()->RxQuality() ) ); uiPageMain->rxlevel->setText( QString("%1 dBm").arg( mController->link()->RxLevel() ) ); } else if ( ui->btnCalibrate->isChecked() ) { int idx = -1; uint16_t value = 0; if ( uiPageCalibrate->tabWidget->tabText(uiPageCalibrate->tabWidget->currentIndex()) == "Thrust" ) { idx = 0; value = mController->joystick(0)->LastRaw(); } else if ( uiPageCalibrate->tabWidget->tabText(uiPageCalibrate->tabWidget->currentIndex()) == "Yaw" ) { idx = 1; value = mController->joystick(1)->LastRaw(); } else if ( uiPageCalibrate->tabWidget->tabText(uiPageCalibrate->tabWidget->currentIndex()) == "Pitch" ) { idx = 2; value = mController->joystick(2)->LastRaw(); } else if ( uiPageCalibrate->tabWidget->tabText(uiPageCalibrate->tabWidget->currentIndex()) == "Roll" ) { idx = 3; value = mController->joystick(3)->LastRaw(); } if ( idx >= 0 and value != 0 ) { mCalibrationValues[idx].min = std::min( mCalibrationValues[idx].min, value ); mCalibrationValues[idx].center = value; mCalibrationValues[idx].max = std::max( mCalibrationValues[idx].max, value ); uiPageCalibrate->min->setText( QString( "Min : %1").arg( mCalibrationValues[idx].min ) ); uiPageCalibrate->center->setText( QString( "Center : %1").arg( mCalibrationValues[idx].center ) ); uiPageCalibrate->max->setText( QString( "Max : %1").arg( mCalibrationValues[idx].max ) ); } } else if ( ui->btnNetwork->isChecked() ) { uiPageNetwork->vtxFrequency->setText( QString::fromStdString( std::to_string(mController->vtxFrequency()) + " MHz" ) ); uiPageNetwork->vtxPowerDbm->setText( QString::fromStdString( std::to_string(mController->vtxPowerDbm()) + " dBm" ) ); } } void MainWindow::Home() { ui->btnHome->setChecked( true ); ui->btnCalibrate->setChecked( false ); ui->btnNetwork->setChecked( false ); ui->btnCamera->setChecked( false ); ui->btnSettings->setChecked( false ); mPageCalibrate->setVisible( false ); mPageCamera->setVisible( false ); mPageNetwork->setVisible( false ); mPageSettings->setVisible( false ); mPageMain->setVisible( true ); ui->centralLayout->removeWidget( mPageCalibrate ); ui->centralLayout->removeWidget( mPageCamera ); ui->centralLayout->removeWidget( mPageNetwork ); ui->centralLayout->removeWidget( mPageSettings ); ui->centralLayout->addWidget( mPageMain ); } void MainWindow::Calibrate() { mController->Lock(); ui->btnHome->setChecked( false ); ui->btnCalibrate->setChecked( true ); ui->btnNetwork->setChecked( false ); ui->btnCamera->setChecked( false ); ui->btnSettings->setChecked( false ); mPageMain->setVisible( false ); mPageCamera->setVisible( false ); mPageNetwork->setVisible( false ); mPageSettings->setVisible( false ); mPageCalibrate->setVisible( true ); ui->centralLayout->removeWidget( mPageMain ); ui->centralLayout->removeWidget( mPageCamera ); ui->centralLayout->removeWidget( mPageNetwork ); ui->centralLayout->removeWidget( mPageSettings ); ui->centralLayout->addWidget( mPageCalibrate ); mController->Unlock(); } void MainWindow::Network() { ui->btnHome->setChecked( false ); ui->btnCalibrate->setChecked( false ); ui->btnNetwork->setChecked( true ); ui->btnCamera->setChecked( false ); ui->btnSettings->setChecked( false ); mPageMain->setVisible( false ); mPageCalibrate->setVisible( false ); mPageCamera->setVisible( false ); mPageSettings->setVisible( false ); mPageNetwork->setVisible( true ); ui->centralLayout->removeWidget( mPageMain ); ui->centralLayout->removeWidget( mPageCalibrate ); ui->centralLayout->removeWidget( mPageCamera ); ui->centralLayout->removeWidget( mPageSettings ); ui->centralLayout->addWidget( mPageNetwork ); VTXUpdate(); } void MainWindow::Camera() { ui->btnHome->setChecked( false ); ui->btnCalibrate->setChecked( false ); ui->btnNetwork->setChecked( false ); ui->btnCamera->setChecked( true ); ui->btnSettings->setChecked( false ); mPageMain->setVisible( false ); mPageCalibrate->setVisible( false ); mPageNetwork->setVisible( false ); mPageSettings->setVisible( false ); mPageCamera->setVisible( true ); ui->centralLayout->removeWidget( mPageMain ); ui->centralLayout->removeWidget( mPageCalibrate ); ui->centralLayout->removeWidget( mPageNetwork ); ui->centralLayout->removeWidget( mPageSettings ); ui->centralLayout->addWidget( mPageCamera ); /* TODO : debug if ( mController and mController->isConnected() ) { uiPageCamera->iso->setText( QString::number( mController->VideoGetIso() ) ); mController->getCameraLensShader( &mCameraLensShader.r, &mCameraLensShader.g, &mCameraLensShader.b ); CameraUpdateLensShader( false ); } */ } void MainWindow::Settings() { ui->btnHome->setChecked( false ); ui->btnCalibrate->setChecked( false ); ui->btnNetwork->setChecked( false ); ui->btnCamera->setChecked( false ); ui->btnSettings->setChecked( true ); mPageMain->setVisible( false ); mPageCalibrate->setVisible( false ); mPageCamera->setVisible( false ); mPageNetwork->setVisible( false ); mPageSettings->setVisible( true ); ui->centralLayout->removeWidget( mPageMain ); ui->centralLayout->removeWidget( mPageCalibrate ); ui->centralLayout->removeWidget( mPageCamera ); ui->centralLayout->removeWidget( mPageNetwork ); ui->centralLayout->addWidget( mPageSettings ); } void MainWindow::CalibrateGyro() { mController->Calibrate(); } void MainWindow::CalibrateIMU() { mController->CalibrateAll(); } void MainWindow::ResetBattery() { mController->ResetBattery(); } void MainWindow::MotorsBeep() { mController->MotorsBeep( uiPageMain->beep->isChecked() ); } void MainWindow::CalibrationReset() { int idx = -1; if ( uiPageCalibrate->tabWidget->tabText(uiPageCalibrate->tabWidget->currentIndex()) == "Thrust" ) { idx = 0; } else if ( uiPageCalibrate->tabWidget->tabText(uiPageCalibrate->tabWidget->currentIndex()) == "Yaw" ) { idx = 1; } else if ( uiPageCalibrate->tabWidget->tabText(uiPageCalibrate->tabWidget->currentIndex()) == "Pitch" ) { idx = 2; } else if ( uiPageCalibrate->tabWidget->tabText(uiPageCalibrate->tabWidget->currentIndex()) == "Roll" ) { idx = 3; } if ( idx >= 0 ) { mCalibrationValues[idx].min = 65535; mCalibrationValues[idx].center = 0; mCalibrationValues[idx].max = 0; uiPageCalibrate->min->setText( QString( "Min : %1").arg( mCalibrationValues[idx].min ) ); uiPageCalibrate->center->setText( QString( "Center : %1").arg( mCalibrationValues[idx].center ) ); uiPageCalibrate->max->setText( QString( "Max : %1").arg( mCalibrationValues[idx].max ) ); } } void MainWindow::CalibrationApply() { if ( uiPageCalibrate->tabWidget->tabText(uiPageCalibrate->tabWidget->currentIndex()) == "Thrust" ) { mController->SaveThrustCalibration( mCalibrationValues[0].min, mCalibrationValues[0].center, mCalibrationValues[0].max ); } else if ( uiPageCalibrate->tabWidget->tabText(uiPageCalibrate->tabWidget->currentIndex()) == "Yaw" ) { mController->SaveYawCalibration( mCalibrationValues[1].min, mCalibrationValues[1].center, mCalibrationValues[1].max ); } else if ( uiPageCalibrate->tabWidget->tabText(uiPageCalibrate->tabWidget->currentIndex()) == "Pitch" ) { mController->SavePitchCalibration( mCalibrationValues[2].min, mCalibrationValues[2].center, mCalibrationValues[2].max ); } else if ( uiPageCalibrate->tabWidget->tabText(uiPageCalibrate->tabWidget->currentIndex()) == "Roll" ) { mController->SaveRollCalibration( mCalibrationValues[3].min, mCalibrationValues[3].center, mCalibrationValues[3].max ); } } void MainWindow::VideoBrightnessDecrease() { if ( mController and mController->isConnected() ) { mController->VideoBrightnessDecrease(); } } void MainWindow::VideoBrightnessIncrease() { if ( mController and mController->isConnected() ) { mController->VideoBrightnessIncrease(); } } void MainWindow::VideoContrastDecrease() { if ( mController and mController->isConnected() ) { mController->VideoContrastDecrease(); } } void MainWindow::VideoContrastIncrease() { if ( mController and mController->isConnected() ) { mController->VideoContrastIncrease(); } } void MainWindow::VideoSaturationDecrease() { if ( mController and mController->isConnected() ) { mController->VideoSaturationDecrease(); } } void MainWindow::VideoSaturationIncrease() { if ( mController and mController->isConnected() ) { mController->VideoSaturationIncrease(); } } void MainWindow::VideoIsoDecrease() { if ( mController and mController->isConnected() ) { mController->VideoIsoDecrease(); uiPageCamera->iso->setText( QString::number( mController->VideoGetIso() ) ); } } void MainWindow::VideoIsoIncrease() { if ( mController and mController->isConnected() ) { mController->VideoIsoIncrease(); uiPageCamera->iso->setText( QString::number( mController->VideoGetIso() ) ); } } void MainWindow::VideoShutterSpeedDecrease() { if ( mController and mController->isConnected() ) { mController->VideoShutterSpeedDecrease(); uiPageCamera->iso->setText( QString::number( mController->VideoGetShutterSpeed() ) ); } } void MainWindow::VideoShutterSpeedIncrease() { if ( mController and mController->isConnected() ) { mController->VideoShutterSpeedIncrease(); uiPageCamera->iso->setText( QString::number( mController->VideoGetShutterSpeed() ) ); } } void MainWindow::VideoShutterSpeedAuto() { // TODO } void MainWindow::VideoWhiteBalance() { if ( mController and mController->isConnected() ) { uiPageCamera->white_balance->setText( "White balance : " + QString::fromStdString(mController->VideoWhiteBalance()) ); } } void MainWindow::VideoLockWhiteBalance() { if ( mController and mController->isConnected() ) { uiPageCamera->white_balance->setText( "White balance : \n" + QString::fromStdString(mController->VideoLockWhiteBalance()) ); } } void MainWindow::VideoExposureMode() { if ( mController and mController->isConnected() ) { uiPageCamera->exposure_mode->setText( "Exposure mode : \n" + QString::fromStdString(mController->VideoExposureMode()) ); } } void MainWindow::CameraUpdateLensShader( bool send ) { if ( not mController or not mController->isConnected() ) { return; } auto update_basic = []( QLabel* label, int value ) { label->setText( QString::number( value ) ); }; auto update_positive = []( QLabel* label, int value ) { label->setText( QString::number( value >> 5 ) + "." + QString::number( ( value & 0b00011111 ) * 100 / 32 ).rightJustified( 2, '0' ) ); }; auto update_negative = []( QLabel* label, int value ) { if ( value < 0 ) { label->setText( QString("-") + QString::number( (-value) >> 5 ) + "." + QString::number( ( (-value) & 0b00011111 ) * 100 / 32 ).rightJustified( 2, '0' ) ); } else { label->setText( QString::number( value >> 5 ) + "." + QString::number( ( value & 0b00011111 ) * 100 / 32 ) ); } }; update_positive( uiPageCamera->r_v_base, mCameraLensShader.r.base ); update_negative( uiPageCamera->r_v_strength, mCameraLensShader.r.strength ); update_basic( uiPageCamera->r_v_radius, mCameraLensShader.r.radius ); update_positive( uiPageCamera->g_v_base, mCameraLensShader.g.base ); update_negative( uiPageCamera->g_v_strength, mCameraLensShader.g.strength ); update_basic( uiPageCamera->g_v_radius, mCameraLensShader.g.radius ); update_positive( uiPageCamera->b_v_base, mCameraLensShader.b.base ); update_negative( uiPageCamera->b_v_strength, mCameraLensShader.b.strength ); update_basic( uiPageCamera->b_v_radius, mCameraLensShader.b.radius ); QImage image = QImage(52, 39, QImage::Format_RGB32 ); uint32_t stride = 52 * 39; for ( int32_t y = 0; y < 39; y++ ) { for ( int32_t x = 0; x < 52; x++ ) { int32_t r = mCameraLensShader.r.base; int32_t g = mCameraLensShader.g.base; int32_t b = mCameraLensShader.b.base; int32_t dist = std::sqrt( ( x - 52 / 2 ) * ( x - 52 / 2 ) + ( y - 39 / 2 ) * ( y - 39 / 2 ) ); if ( mCameraLensShader.r.radius > 0 ) { float dot_r = (float)std::max( 0, mCameraLensShader.r.radius - dist ) / (float)mCameraLensShader.r.radius; r = std::max( 0, std::min( 255, r + (int32_t)( dot_r * mCameraLensShader.r.strength ) ) ); } if ( mCameraLensShader.g.radius > 0 ) { float dot_g = (float)std::max( 0, mCameraLensShader.g.radius - dist ) / (float)mCameraLensShader.g.radius; g = std::max( 0, std::min( 255, g + (int32_t)( dot_g * mCameraLensShader.g.strength ) ) ); } if ( mCameraLensShader.b.radius > 0 ) { float dot_b = (float)std::max( 0, mCameraLensShader.b.radius - dist ) / (float)mCameraLensShader.b.radius; b = std::max( 0, std::min( 255, b + (int32_t)( dot_b * mCameraLensShader.b.strength ) ) ); } mCameraLensShader.grid[ stride*0 + 52*y + x ] = r; mCameraLensShader.grid[ stride*1 + 52*y + x ] = g; mCameraLensShader.grid[ stride*2 + 52*y + x ] = g; mCameraLensShader.grid[ stride*3 + 52*y + x ] = b; image.setPixel( x, y, QColor( r, g, b ).rgba() ); } } uiPageCamera->shader->setPixmap( QPixmap::fromImage(image) ); if ( send ) { mController->setCameraLensShader( mCameraLensShader.r, mCameraLensShader.g, mCameraLensShader.b ); } } void MainWindow::VTXUpdate() { mController->VTXGetSettings(); uiPageNetwork->vtxChannelSpin->setValue( mController->vtxChannel() ); uiPageNetwork->vtxPowerSpin->setValue( mController->vtxPower() ); uiPageNetwork->vtxFrequency->setText( QString::fromStdString( std::to_string(mController->vtxFrequency()) + " MHz" ) ); uiPageNetwork->vtxPowerDbm->setText( QString::fromStdString( std::to_string(mController->vtxPowerDbm()) + " dBm" ) ); } void MainWindow::VTXReset() { VTXUpdate(); } void MainWindow::VTXSet() { if ( uiPageNetwork->vtxChannelSpin->value() != mController->vtxChannel() ) { mController->VTXSetChannel( uiPageNetwork->vtxChannelSpin->value() ); uiPageNetwork->vtxFrequency->setText( QString::fromStdString( std::to_string(mController->vtxFrequency()) + " MHz" ) ); } if ( uiPageNetwork->vtxPowerSpin->value() != mController->vtxPower() ) { mController->VTXSetPower( uiPageNetwork->vtxPowerSpin->value() ); uiPageNetwork->vtxPowerDbm->setText( QString::fromStdString( std::to_string(mController->vtxPowerDbm()) + " dBm" ) ); } } void MainWindow::SimulatorMode( bool enabled ) { bool ok = mController->SimulatorMode( enabled ); if ( not ok and enabled ) { uiPageSettings->simulatorMode->setChecked( ok ); } }
25,140
C++
.cpp
543
43.909761
192
0.716949
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,693
MCP320x.cpp
dridri_bcflight/controller_rc/ADCs/MCP320x.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <iostream> #include <string.h> #include "MCP320x.h" MCP320x::MCP320x( const std::string& devfile ) : mSPI( new SPI( devfile, 500000 ) ) { } MCP320x::~MCP320x() { } void MCP320x::setSmoothFactor( uint8_t channel, float f ) { mSmoothFactor[channel] = f; } uint16_t MCP320x::Read( uint8_t channel, float dt ) { static const int nbx = 4; uint32_t b[3] = { 0, 0, 0 }; uint8_t bx[nbx][3] = { { 0 } }; uint8_t buf[12]; buf[0] = 0b00000110 | ( ( channel & 0b100 ) >> 2 ); buf[1] = ( ( channel & 0b11 ) << 6 ); buf[2] = 0x00; buf[3] = 0b00000110 | ( ( channel & 0b100 ) >> 2 ); buf[4] = ( ( channel & 0b11 ) << 6 ); buf[5] = 0x00; buf[6] = 0b00000110 | ( ( channel & 0b100 ) >> 2 ); buf[7] = ( ( channel & 0b11 ) << 6 ); buf[8] = 0x00; buf[9] = 0b00000110 | ( ( channel & 0b100 ) >> 2 ); buf[10] = ( ( channel & 0b11 ) << 6 ); buf[11] = 0x00; for ( int i = 0; i < nbx; i++ ) { if ( mSPI->Transfer( buf, bx[i], 3 ) < 0 ) { return 0; } } uint32_t ret[nbx] = { 0 }; uint32_t final_ret = 0; for ( int i = 0; i < nbx; i++ ) { ret[i] = ( ( bx[i][1] & 0b1111 ) << 8 ) | bx[i][2]; } for ( int j = 0; j < nbx; j++ ) { for ( int i = 0; i < nbx; i++ ) { if ( i != j and std::abs( (int32_t)(ret[i] - ret[j]) ) > 250 ) { if ( channel == 3 ) { // printf( "ADC too large (%d, %d - %d)\n", ret[i] - ret[j], ret[i], ret[j] ); } return 0; } } final_ret += ret[j]; } final_ret /= nbx; final_ret &= 0xFFFFFFF7; // Raw value if ( dt == 0.0f ) { return final_ret; } if ( mSmoothFactor.find(channel) != mSmoothFactor.end() ) { float smooth = mSmoothFactor[channel]; if ( smooth > 0.0f and smooth < 1.0f ) { float s = smooth * std::max( 0.0f, std::min( 1.0f, dt * 1000.0f ) ); mLastValue[channel] = std::max( 0.0f, mLastValue[channel] * s + (float)final_ret * ( 1.0f - s ) ); if ( channel == 3 ) { // printf( "ok : %d\n", (uint16_t)mLastValue[channel] ); } return (uint16_t)mLastValue[channel]; } } return final_ret; }
2,784
C++
.cpp
92
27.934783
101
0.602689
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,694
SPI.cpp
dridri_bcflight/controller_rc/boards/rpi/SPI.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <sys/fcntl.h> #include <sys/ioctl.h> #include <linux/i2c-dev.h> #include <errno.h> #include <unistd.h> #include <string.h> #include <iostream> #include <mutex> #include "SPI.h" static std::mutex spi_mutex; SPI::SPI( const std::string& device, uint32_t speed_hz ) { spi_mutex.lock(); mFD = open( device.c_str(), O_RDWR ); std::cout << "SPI fd : " << mFD << "\n"; uint8_t mode, lsb; mode = SPI_MODE_0; mBitsPerWord = 8; if ( ioctl( mFD, SPI_IOC_WR_MODE, &mode ) < 0 ) { std::cout << "SPI wr_mode\n"; } if ( ioctl( mFD, SPI_IOC_RD_MODE, &mode ) < 0 ) { std::cout << "SPI rd_mode\n"; } if ( ioctl( mFD, SPI_IOC_WR_BITS_PER_WORD, &mBitsPerWord ) < 0 ) { std::cout << "SPI write bits_per_word\n"; } if ( ioctl( mFD, SPI_IOC_RD_BITS_PER_WORD, &mBitsPerWord ) < 0 ) { std::cout << "SPI read bits_per_word\n"; } if ( ioctl( mFD, SPI_IOC_WR_MAX_SPEED_HZ, &speed_hz ) < 0 ) { std::cout << "can't set max speed hz\n"; } if ( ioctl( mFD, SPI_IOC_RD_MAX_SPEED_HZ, &speed_hz ) < 0 ) { std::cout << "SPI max_speed_hz\n"; } if ( ioctl( mFD, SPI_IOC_RD_LSB_FIRST, &lsb ) < 0 ) { std::cout << "SPI rd_lsb_fist\n"; } std::cout << "SPI " << device.c_str() << ":" << mFD <<": spi mode " << (int)mode << ", " << mBitsPerWord << "bits " << ( lsb ? "(lsb first) " : "" ) << "per word, " << speed_hz << " Hz max\n"; memset( mXFer, 0, sizeof( mXFer ) ); for ( uint32_t i = 0; i < sizeof( mXFer ) / sizeof( struct spi_ioc_transfer ); i++) { mXFer[i].len = 0; mXFer[i].cs_change = 0; // Keep CS activated mXFer[i].delay_usecs = 0; mXFer[i].speed_hz = speed_hz; mXFer[i].bits_per_word = 8; } spi_mutex.unlock(); } SPI::~SPI() { } int SPI::Transfer( void* tx, void* rx, uint32_t len ) { spi_mutex.lock(); mXFer[0].tx_buf = (uintptr_t)tx; mXFer[0].len = len; mXFer[0].rx_buf = (uintptr_t)rx; int ret = ioctl( mFD, SPI_IOC_MESSAGE(1), mXFer ); spi_mutex.unlock(); return ret; }
2,657
C++
.cpp
87
28.321839
196
0.637681
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,695
GPIO.cpp
dridri_bcflight/controller_rc/boards/rpi/GPIO.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <pigpio.h> // #include <wiringPi.h> #include <unistd.h> #include <sys/poll.h> #include <sys/ioctl.h> #include <fcntl.h> #include <softPwm.h> #include <string.h> #include <string> #include "GPIO.h" std::map< int, std::list<std::pair<std::function<void()>,GPIO::ISRMode>> > GPIO::mInterrupts; void GPIO::setMode( int pin, GPIO::Mode mode ) { gpioSetMode( pin, mode ); } void GPIO::setPUD( int pin, PUDMode mode ) { gpioSetPullUpDown( pin, mode ); } void GPIO::setPWM( int pin, int initialValue, int pwmRange ) { // TODO : switch from wiringPi to pigpio // setMode( pin, Output ); // softPwmCreate( pin, initialValue, pwmRange ); } void GPIO::Write( int pin, bool en ) { gpioWrite( pin, en ); } bool GPIO::Read( int pin ) { return gpioRead( pin ); } void GPIO::SetupInterrupt( int pin, GPIO::ISRMode mode, std::function<void()> fct ) { if ( mInterrupts.find( pin ) != mInterrupts.end() ) { mInterrupts.at( pin ).emplace_back( std::make_pair( fct, mode ) ); } else { std::list<std::pair<std::function<void()>,GPIO::ISRMode>> lst; lst.emplace_back( std::make_pair( fct, mode ) ); mInterrupts.emplace( std::make_pair( pin, lst ) ); system( ( "echo " + std::to_string( pin ) + " > /sys/class/gpio/export" ).c_str() ); int32_t fd = open( ( "/sys/class/gpio/gpio" + std::to_string( pin ) + "/value" ).c_str(), O_RDWR ); system( ( "echo both > /sys/class/gpio/gpio" + std::to_string( pin ) + "/edge" ).c_str() ); int count = 0; char c = 0; ioctl( fd, FIONREAD, &count ); for ( int i = 0; i < count; i++ ) { (void)read( fd, &c, 1 ); } int32_t* argp = (int32_t*)malloc( sizeof(int32_t) * 2 ); argp[0] = pin; argp[1] = fd; pthread_t thid; pthread_create( &thid, nullptr, (void*(*)(void*))&GPIO::ISR, argp ); } } void* GPIO::ISR( void* argp ) { int32_t pin = ((int32_t*)argp)[0]; int32_t fd = ((int32_t*)argp)[1]; struct pollfd fds; char buffer[16]; pthread_setname_np( pthread_self(), ( "GPIO::ISR_" + std::to_string( pin ) ).c_str() ); struct sched_param sched; memset( &sched, 0, sizeof(sched) ); sched.sched_priority = std::min( sched_get_priority_max( SCHED_RR ), 99 ); sched_setscheduler( 0, SCHED_RR, &sched ); usleep( 1000 ); std::list<std::pair<std::function<void()>,GPIO::ISRMode>>& fcts = mInterrupts.at( pin ); while ( true ) { fds.fd = fd; fds.events = POLLPRI; lseek( fd, 0, SEEK_SET ); if ( poll( &fds, 1, -1 ) == 1 and read( fd, buffer, 2 ) > 0 ) { for ( std::pair<std::function<void()>,GPIO::ISRMode> fct : fcts ) { if ( buffer[0] == '1' and fct.second != Falling ) { fct.first(); } else if ( buffer[0] == '0' and fct.second != Rising ) { fct.first(); } } } } return nullptr; }
3,423
C++
.cpp
103
30.902913
101
0.65303
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,696
ControllerClient.cpp
dridri_bcflight/controller_rc/boards/rpi/ControllerClient.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <unistd.h> #include <fcntl.h> #include <sys/mount.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <pigpio.h> #include "GPIO.h" #include <iostream> #include <fstream> #include <cmath> #include <Config.h> #include "ControllerClient.h" #include "Socket.h" #include "Debug.h" #include "../../libcontroller/PT1.h" Config* ControllerClient::mConfig = nullptr; ControllerClient::ControllerClient( Config* config, Link* link, bool spectate ) : Controller( link, spectate ) , mADC( nullptr ) , mSimulatorEnabled( false ) , mSimulatorSocketServer( nullptr ) , mSimulatorSocket( nullptr ) , mSimulatorTicks( 0 ) { mConfig = config; gpioInitialise(); GPIO::setPUD( 0, GPIO::PullDown ); GPIO::setPUD( 1, GPIO::PullDown ); GPIO::setPUD( 4, GPIO::PullDown ); GPIO::setPUD( 5, GPIO::PullDown ); GPIO::setPUD( 6, GPIO::PullDown ); GPIO::setPUD( 12, GPIO::PullDown ); GPIO::setPUD( 13, GPIO::PullDown ); GPIO::setPUD( 22, GPIO::PullDown ); GPIO::setPUD( 23, GPIO::PullDown ); GPIO::setPUD( 24, GPIO::PullDown ); GPIO::setPUD( 26, GPIO::PullDown ); GPIO::setPUD( 27, GPIO::PullDown ); GPIO::setMode( 0, GPIO::Input ); GPIO::setMode( 1, GPIO::Input ); GPIO::setMode( 4, GPIO::Input ); GPIO::setMode( 5, GPIO::Input ); GPIO::setMode( 6, GPIO::Input ); GPIO::setMode( 12, GPIO::Input ); GPIO::setMode( 13, GPIO::Input ); GPIO::setMode( 22, GPIO::Input ); GPIO::setMode( 23, GPIO::Input ); GPIO::setMode( 24, GPIO::Input ); GPIO::setMode( 26, GPIO::Input ); GPIO::setMode( 27, GPIO::Input ); mSimulatorThread = new HookThread<ControllerClient>( "Simulator", this, &ControllerClient::RunSimulator ); mSimulatorThread->Start(); } ControllerClient::~ControllerClient() { } int8_t ControllerClient::ReadSwitch( uint32_t id ) { static const uint32_t map[] = { 0, 1, 4, 5, 6, 12, 13, 22, 23, 24, 26, 27 }; if ( id == 4 ) { return 0; } if ( id >= 12 ) { return 0; } if ( map[id] == 0 ) { return 0; } int8_t ret = !GPIO::Read( map[id] ); if ( id == 1 ) { ret = !ret; } return ret; } float ControllerClient::ReadThrust( float dt ) { return mJoysticks[0].Read( dt ); } float ControllerClient::ReadRoll( float dt ) { return mJoysticks[3].Read( dt ); } float ControllerClient::ReadPitch( float dt ) { return mJoysticks[2].Read( dt ); } float ControllerClient::ReadYaw( float dt ) { return mJoysticks[1].Read( dt ); } bool ControllerClient::run() { if ( mADC == nullptr ) { mADC = new MCP320x( mConfig->string( "adc.device", "/dev/spidev1.0" ) ); if ( mADC ) { // mADC->setSmoothFactor( 0, 0.5f ); // mADC->setSmoothFactor( 1, 0.5f ); // mADC->setSmoothFactor( 2, 0.5f ); // mADC->setSmoothFactor( 3, 0.5f ); mADC->setSmoothFactor( 4, 0.75f ); mJoysticks[0] = Joystick( mADC, 0, 0, mConfig->boolean( "adc.inverse.thrust", false ), true ); mJoysticks[1] = Joystick( mADC, 1, 1, mConfig->boolean( "adc.inverse.yaw", false ) ); mJoysticks[2] = Joystick( mADC, 2, 3, mConfig->boolean( "adc.inverse.pitch", false ) ); mJoysticks[3] = Joystick( mADC, 3, 2, mConfig->boolean( "adc.inverse.roll", false ) ); mJoysticks[0].setFilter( new PT1_1( 10.0f ) ); mJoysticks[1].setFilter( new PT1_1( 10.0f ) ); mJoysticks[2].setFilter( new PT1_1( 10.0f ) ); mJoysticks[3].setFilter( new PT1_1( 10.0f ) ); } } if ( mADC ) { uint16_t battery_voltage = mADC->Read( 4, 0.001f ); if ( battery_voltage != 0 ) { float voltage = (float)battery_voltage * 4.2902f / 1024.0f; if ( mLocalBatteryVoltage == 0.0f ) { mLocalBatteryVoltage = voltage; } else { mLocalBatteryVoltage = mLocalBatteryVoltage * 0.98f + voltage * 0.02f; } } } return Controller::run(); } bool ControllerClient::RunSimulator() { uint64_t ticks = Thread::GetTick(); if ( ticks - mSimulatorTicks < 1000 / 100 ) { usleep( 1000LLU * std::max( 0LL, 1000LL / 100LL - (int64_t)( ticks - mTicks ) - 1LL ) ); } float dt = ((float)( Thread::GetTick() - mSimulatorTicks ) ) / 1000000.0f; mSimulatorTicks = Thread::GetTick(); typedef struct { int8_t throttle; int8_t roll; int8_t pitch; int8_t yaw; } __attribute__((packed)) ControllerData; ControllerData data; if ( not mSimulatorEnabled ) { if ( mSimulatorSocket ) { delete mSimulatorSocket; } if ( mSimulatorSocketServer ) { delete mSimulatorSocketServer; } mSimulatorSocket = nullptr; mSimulatorSocketServer = nullptr; usleep( 1000 * 1000 * 2 ); return true; } if ( not mSimulatorSocketServer ) { mSimulatorSocketServer = new rpi::Socket( 5000 ); mSimulatorSocketServer->Connect(); std::cout << "mSimulatorSocketServer : " << mSimulatorSocketServer << "\n"; } if ( not mSimulatorSocket ) { mSimulatorSocket = mSimulatorSocketServer->WaitClient(); std::cout << "mSimulatorSocket : " << mSimulatorSocket << "\n"; } float f_thrust = ReadThrust( dt ); float f_yaw = ReadYaw( dt ); float f_pitch = ReadPitch( dt ); float f_roll = ReadRoll( dt ); if ( f_thrust >= 0.0f and f_thrust <= 1.0f ) { data.throttle = (int8_t)( std::max( 0, std::min( 127, (int32_t)( f_thrust * 127.0f ) ) ) ); } if ( f_yaw >= -1.0f and f_yaw <= 1.0f ) { if ( fabsf( f_yaw ) <= 0.025f ) { f_yaw = 0.0f; } else if ( f_yaw < 0.0f ) { f_yaw += 0.025f; } else if ( f_yaw > 0.0f ) { f_yaw -= 0.025f; } f_yaw *= 1.0f / ( 1.0f - 0.025f ); data.yaw = (int8_t)( std::max( -127, std::min( 127, (int32_t)( f_yaw * 127.0f ) ) ) ); } if ( f_pitch >= -1.0f and f_pitch <= 1.0f ) { if ( fabsf( f_pitch ) <= 0.025f ) { f_pitch = 0.0f; } else if ( f_pitch < 0.0f ) { f_pitch += 0.025f; } else if ( f_pitch > 0.0f ) { f_pitch -= 0.025f; } f_pitch *= 1.0f / ( 1.0f - 0.025f ); data.pitch = (int8_t)( std::max( -127, std::min( 127, (int32_t)( f_pitch * 127.0f ) ) ) ); } if ( f_roll >= -1.0f and f_roll <= 1.0f ) { if ( fabsf( f_roll ) <= 0.025f ) { f_roll = 0.0f; } else if ( f_roll < 0.0f ) { f_roll += 0.025f; } else if ( f_roll > 0.0f ) { f_roll -= 0.025f; } f_roll *= 1.0f / ( 1.0f - 0.025f ); data.roll = (int8_t)( std::max( -127, std::min( 127, (int32_t)( f_roll * 127.0f ) ) ) ); } if ( mSimulatorSocket->Send( &data, sizeof(data) ) <= 0 ) { delete mSimulatorSocket; mSimulatorSocket = nullptr; } return true; } ControllerClient::Joystick::Joystick( MCP320x* adc, int id, int adc_channel, bool inverse, bool thrust_mode ) : mADC( adc ) , mId( id ) , mADCChannel( adc_channel ) , mCalibrated( false ) , mInverse( inverse ) , mThrustMode( thrust_mode ) , mMin( 0 ) , mCenter( 32767 ) , mMax( 65535 ) { fDebug( adc, id, adc_channel, inverse, thrust_mode ); mMin = mConfig->setting( "Joystick:" + std::to_string( mId ) + ":min", 0 ); mCenter = mConfig->setting( "Joystick:" + std::to_string( mId ) + ":cen", 32767 ); mMax = mConfig->setting( "Joystick:" + std::to_string( mId ) + ":max", 65535 ); if ( mMin != 0 and mCenter != 32767 and mMax != 65535 ) { mCalibrated = true; } } ControllerClient::Joystick::~Joystick() { } void ControllerClient::Joystick::SetCalibratedValues( uint16_t min, uint16_t center, uint16_t max ) { mMin = min; mCenter = center; mMax = max; mCalibrated = true; } uint16_t ControllerClient::Joystick::ReadRaw( float dt ) { if ( mADC == nullptr ) { return 0; } uint32_t raw = mADC->Read( mADCChannel, dt ); if ( raw == 0 ) { return 0; } if ( mInverse ) { raw = 4096 - raw; } // if ( raw != 0 ) { // mLastRaw = mLastRaw * 0.5f + raw * 0.5f; // } mLastRaw = raw; return mLastRaw; } float ControllerClient::Joystick::Read( float dt ) { uint16_t raw = ReadRaw( dt ); if ( raw == 0 ) { return std::numeric_limits<float>::quiet_NaN(); } if ( mThrustMode ) { float ret = (float)( raw - mMin ) / (float)( mMax - mMin ); ret = 0.001953125f * std::round( ret * 512.0f ); ret = std::max( 0.0f, std::min( 1.0f, ret ) ); if ( mFilter ) { ret = mFilter->filter( ret, dt ); } return ret; } float base = mMax - mCenter; if ( raw < mCenter ) { base = mCenter - mMin; } float ret = (float)( raw - mCenter ) / base; ret = 0.001953125f * std::round( ret * 512.0f ); ret = std::max( -1.0f, std::min( 1.0f, ret ) ); if ( mFilter ) { ret = mFilter->filter( ret, dt ); } // std::cout << mADCChannel << " : " << ret << "\n"; return ret; } void ControllerClient::SaveThrustCalibration( uint16_t min, uint16_t center, uint16_t max ) { mJoysticks[0].SetCalibratedValues( min, center, max ); mConfig->setSetting( "Joystick:" + std::to_string( 0 ) + ":min", min ); mConfig->setSetting( "Joystick:" + std::to_string( 0 ) + ":cen", center ); mConfig->setSetting( "Joystick:" + std::to_string( 0 ) + ":max", max ); mount( "", "/", "", MS_REMOUNT, nullptr ); mConfig->SaveSettings( "/root/settings" ); mount( "", "/", "", MS_REMOUNT | MS_RDONLY, nullptr ); } void ControllerClient::SaveYawCalibration( uint16_t min, uint16_t center, uint16_t max ) { mJoysticks[1].SetCalibratedValues( min, center, max ); mConfig->setSetting( "Joystick:" + std::to_string( 1 ) + ":min", min ); mConfig->setSetting( "Joystick:" + std::to_string( 1 ) + ":cen", center ); mConfig->setSetting( "Joystick:" + std::to_string( 1 ) + ":max", max ); mount( "", "/", "", MS_REMOUNT, nullptr ); mConfig->SaveSettings( "/root/settings" ); mount( "", "/", "", MS_REMOUNT | MS_RDONLY, nullptr ); } void ControllerClient::SavePitchCalibration( uint16_t min, uint16_t center, uint16_t max ) { mJoysticks[2].SetCalibratedValues( min, center, max ); mConfig->setSetting( "Joystick:" + std::to_string( 2 ) + ":min", min ); mConfig->setSetting( "Joystick:" + std::to_string( 2 ) + ":cen", center ); mConfig->setSetting( "Joystick:" + std::to_string( 2 ) + ":max", max ); mount( "", "/", "", MS_REMOUNT, nullptr ); mConfig->SaveSettings( "/root/settings" ); mount( "", "/", "", MS_REMOUNT | MS_RDONLY, nullptr ); } void ControllerClient::SaveRollCalibration( uint16_t min, uint16_t center, uint16_t max ) { mJoysticks[3].SetCalibratedValues( min, center, max ); mConfig->setSetting( "Joystick:" + std::to_string( 3 ) + ":min", min ); mConfig->setSetting( "Joystick:" + std::to_string( 3 ) + ":cen", center ); mConfig->setSetting( "Joystick:" + std::to_string( 3 ) + ":max", max ); mount( "", "/", "", MS_REMOUNT, nullptr ); mConfig->SaveSettings( "/root/settings" ); mount( "", "/", "", MS_REMOUNT | MS_RDONLY, nullptr ); } bool ControllerClient::SimulatorMode( bool e ) { mSimulatorEnabled = e; return e; }
11,132
C++
.cpp
342
30.230994
109
0.646204
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,697
Socket.cpp
dridri_bcflight/controller_rc/boards/rpi/Socket.cpp
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <unistd.h> /* close */ #include <netdb.h> /* gethostbyname */ #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define closesocket(s) close(s) typedef int SOCKET; typedef struct sockaddr_in SOCKADDR_IN; typedef struct sockaddr SOCKADDR; typedef struct in_addr IN_ADDR; #include "Socket.h" #include <iostream> #define UDPLITE_SEND_CSCOV 10 /* sender partial coverage (as sent) */ #define UDPLITE_RECV_CSCOV 11 /* receiver partial coverage (threshold ) */ rpi::Socket::Socket() : mSocketType( Client ) , mPort( 0 ) , mPortType( TCP ) , mSocket( -1 ) { } rpi::Socket::Socket( uint16_t port, PortType type ) : mSocketType( Server ) , mPort( port ) , mPortType( type ) , mSocket( -1 ) { } rpi::Socket::Socket( const std::string& host, uint16_t port, PortType type ) : mSocketType( Client ) , mHost( host ) , mPort( port ) , mPortType( type ) , mSocket( -1 ) { } rpi::Socket::~Socket() { if ( mSocket >= 0 ) { shutdown( mSocket, 2 ); closesocket( mSocket ); } } bool rpi::Socket::isConnected() const { return ( mSocket >= 0 ); } int rpi::Socket::Connect() { if ( mSocket < 0 ) { int type = ( mPortType == UDP or mPortType == UDPLite ) ? SOCK_DGRAM : SOCK_STREAM; int proto = ( mPortType == UDPLite ) ? IPPROTO_UDPLITE : ( ( mPortType == UDP ) ? IPPROTO_UDP : 0 ); mSocket = socket( AF_INET, type, proto ); int option = 1; setsockopt( mSocket, SOL_SOCKET, ( 15/*SO_REUSEPORT*/ | SO_REUSEADDR ), (char*)&option, sizeof( option ) ); if ( mPortType == TCP ) { int flag = 1; setsockopt( mSocket, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(int) ); } if ( mPortType == UDPLite ) { uint16_t checksum_coverage = 8; setsockopt( mSocket, IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, &checksum_coverage, sizeof(checksum_coverage) ); setsockopt( mSocket, IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, &checksum_coverage, sizeof(checksum_coverage) ); } if ( mSocketType == Server ) { char myname[256]; gethostname( myname, sizeof(myname) ); memset( &mSin, 0, sizeof( mSin ) ); mSin.sin_addr.s_addr = htonl( INADDR_ANY ); mSin.sin_family = AF_INET; mSin.sin_port = htons( mPort ); if ( bind( mSocket, (SOCKADDR*)&mSin, sizeof(mSin) ) < 0 ) { std::cout << "rpi::Socket ( " << mPort << " ) error : " << strerror(errno) << "\n"; close( mSocket ); return -1; } } } if ( mPortType == TCP ) { if ( mSocketType == Server ) { } else { memset( &mSin, 0, sizeof( mSin ) ); struct hostent* hp = gethostbyname( mHost.c_str() ); if ( hp and hp->h_addr_list and hp->h_addr_list[0] ) { mSin.sin_addr = *(IN_ADDR *) hp->h_addr; } else { mSin.sin_addr.s_addr = inet_addr( mHost.c_str() ); } mSin.sin_family = AF_INET; mSin.sin_port = htons( mPort ); if ( connect( mSocket, (SOCKADDR*)&mSin, sizeof(mSin) ) < 0 ) { std::cout << "rpi::Socket connect to " << mHost << ":" << mPort << " error : " << strerror(errno) << "\n"; close( mSocket ); mSocket = -1; return -1; } } } else if ( mPortType == UDP or mPortType == UDPLite ) { // TODO } return 0; } rpi::Socket* rpi::Socket::WaitClient() { if ( mSocketType == Server and mPortType == TCP ) { int clientFD; struct sockaddr_in clientSin; int size = 0; int ret = listen( mSocket, 5 ); if ( !ret ) { clientFD = accept( mSocket, (SOCKADDR*)&clientSin, (socklen_t*)&size ); printf( "rpi::Socket::WaitClient clientFD : %d, %d, %s\n", ret, errno, strerror(errno) ); if ( clientFD >= 0 ) { rpi::Socket* client = new rpi::Socket(); client->mSocket = clientFD; client->mSin = clientSin; return client; } } else { printf( "rpi::Socket::WaitClient err %d, %d, %s\n", ret, errno, strerror(errno) ); close( mSocket ); } } return nullptr; } int rpi::Socket::Receive( void* buf, uint32_t len, int timeout ) { int ret = 0; memset( buf, 0, len ); if ( mPortType == UDP or mPortType == UDPLite ) { uint32_t fromsize = sizeof( mClientSin ); ret = recvfrom( mSocket, buf, len, 0, (SOCKADDR *)&mClientSin, &fromsize ); } else { ret = recv( mSocket, buf, len, MSG_NOSIGNAL ); } if ( ret <= 0 ) { if ( errno == 11 ) { return -11; } std::cout << "rpi::Socket on port " << mPort << " disconnected ( " << ret << " : " << errno << ", " << strerror( errno ) << " )\n"; close( mSocket ); mSocket = -1; return -1; } return ret; } int rpi::Socket::Send( const void* buf, uint32_t len, int timeout ) { int ret = 0; if ( mPortType == UDP or mPortType == UDPLite ) { uint32_t sendsize = sizeof( mClientSin ); ret = sendto( mSocket, buf, len, 0, (SOCKADDR *)&mClientSin, sendsize ); } else { ret = send( mSocket, buf, len, MSG_NOSIGNAL ); } if ( ret <= 0 and ( errno == EAGAIN or errno == -EAGAIN ) ) { return 0; } if ( ret < 0 and mPortType != UDP and mPortType != UDPLite ) { std::cout << "rpi::Socket on port " << mPort << " disconnected\n"; close( mSocket ); mSocket = -1; return -1; } return ret; }
5,196
C++
.cpp
175
27.017143
133
0.630735
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,698
ControllerClient.cpp
dridri_bcflight/controller_rc/boards/generic/ControllerClient.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <unistd.h> #include <fcntl.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <cmath> #include "ControllerClient.h" ControllerClient::ControllerClient( Config* config, Link* link, bool spectate ) : Controller( link, spectate ) { } ControllerClient::~ControllerClient() { } bool ControllerClient::run() { return Controller::run(); }
1,074
C++
.cpp
34
29.823529
80
0.756286
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,699
Controller.cpp
dridri_bcflight/flight/Controller.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <unistd.h> #include <stdio.h> #include <algorithm> #include <cmath> #include "Main.h" #include "Config.h" #include "Controller.h" #include <Link.h> #include <IMU.h> #include <Gyroscope.h> #include <Accelerometer.h> #include <Magnetometer.h> #include <Sensor.h> #include <Stabilizer.h> #include <Frame.h> #include "video/Camera.h" #include "peripherals/SmartAudio.h" #include <DynamicNotchFilter.h> #include <FilterChain.h> inline uint16_t ntohs( uint16_t x ) { return ( ( x & 0xff ) << 8 ) | ( x >> 8 ); } Controller::Controller() : ControllerBase() , Thread( "controller" ) , mMain( Main::instance() ) , mTimedOut( false ) // , mArmed( false ) , mPing( 0 ) // , mRPY( Vector3f() ) // , mThrust( 0.0f ) , mTicks( 0 ) , mTelemetryThread( new HookThread< Controller >( "telemetry", this, &Controller::TelemetryRun ) ) , mTelemetryTick( 0 ) , mTelemetryCounter( 0 ) , mEmergencyTick( 0 ) , mTelemetryFrequency( 0 ) , mTelemetryFull( false ) { mExpo = Vector4f(); mExpo.x = 4; mExpo.y = 4; mExpo.z = 3; mExpo.w = 2; mThrustExpo = Vector2f(); mThrustExpo.x = 0.0f; mThrustExpo.y = 0.0f; } Controller::~Controller() { } void Controller::Start() { gDebug() << "Starting RX thread"; Thread::Start(); if ( mTelemetryFrequency > 0 ) { gDebug() << "Starting telemetry thread (at " << mTelemetryFrequency << "Hz)"; mTelemetryThread->setFrequency( mTelemetryFrequency ); mTelemetryThread->Start(); } gDebug() << "Controller ready !"; } Link* Controller::link() const { return mLink; } bool Controller::connected() const { return isConnected(); } /* bool Controller::armed() const { return mArmed; } */ uint32_t Controller::ping() const { return mPing; } /* float Controller::thrust() const { return mThrust; } const Vector3f& Controller::RPY() const { // return mSmoothRPY; return mRPY; } */ void Controller::onEvent( ControllerBase::Cmd cmdId, const std::function<void(const LuaValue& v)>& f ) { fDebug( this, cmdId, "f" ); mEvents[cmdId] = f; } void Controller::Emergency() { gDebug() << "EMERGENCY MODE !"; mMain->stabilizer()->Reset( 0.0f ); mMain->frame()->Disarm(); // mThrust = 0.0f; // mSmoothRPY = Vector3f(); // mRPY = Vector3f(); mMain->stabilizer()->Reset( 0.0f ); mMain->stabilizer()->Disarm(); // mArmed = false; } void Controller::UpdateSmoothControl( const float& dt ) { // mSmoothControl.Predict( dt ); // mSmoothRPY = mSmoothControl.Update( dt, mRPY ); } void Controller::SendDebug( const string& s ) { /* Packet packet( DEBUG_OUTPUT ); packet.WriteString( s ); mSendMutex.lock(); mLink->Write( &packet ); mSendMutex.unlock(); */ } float Controller::setRoll( float value, bool raw ) { if ( not raw ) { if ( value >= 0.0f ) { value = ( exp( value * mExpo.x ) - 1.0f ) / ( exp( mExpo.x ) - 1.0f ); } else { value = -( exp( -value * mExpo.x ) - 1.0f ) / ( exp( mExpo.x ) - 1.0f ); } } // mRPY.x = value; mMain->stabilizer()->setRoll( value ); return value; } float Controller::setPitch( float value, bool raw ) { if ( not raw ) { if ( value >= 0.0f ) { value = ( exp( value * mExpo.y ) - 1.0f ) / ( exp( mExpo.y ) - 1.0f ); } else { value = -( exp( -value * mExpo.y ) - 1.0f ) / ( exp( mExpo.y ) - 1.0f ); } } // mRPY.y = value; mMain->stabilizer()->setPitch( value ); return value; } float Controller::setYaw( float value, bool raw ) { if ( abs( value ) < 0.01f ) { value = 0.0f; } if ( not raw ) { if ( value >= 0.0f ) { value = ( exp( value * mExpo.z ) - 1.0f ) / ( exp( mExpo.z ) - 1.0f ); } else { value = -( exp( -value * mExpo.z ) - 1.0f ) / ( exp( mExpo.z ) - 1.0f ); } } // mRPY.z = value; mMain->stabilizer()->setYaw( value ); return value; } float Controller::setThrust( float value, bool raw ) { if ( abs( value ) < 0.01f ) { value = 0.0f; } // if ( not mMain->stabilizer()->altitudeHold() ) { if ( not raw ) { // value = log( value * ( mExpo.z - 1.0f ) + 1.0f ) / log( mExpo.z ); // value = pow( value, mThrustExpo.x ) * ( 1.0f - value ) * -mThrustExpo.y + value; value = value * mThrustExpo.x * ( 1.0f - value ) + pow( value, mThrustExpo.y ); if ( value < 0.0f or isnan( value ) or ( isinf( value ) and value < 0.0f ) ) { value = 0.0f; } if ( value > 1.0f or isinf( value ) ) { value = 1.0f; } // mThrust = value; } mMain->stabilizer()->setThrust( value ); // } return value; } void Controller::Arm() { gDebug() << "Arming"; mMain->imu()->ResetYaw(); mMain->stabilizer()->Reset( mMain->imu()->RPY().z ); mMain->frame()->Arm(); // mRPY.x = 0.0f; // mRPY.y = 0.0f; // mRPY.z = 0.0f; // mArmed = true; mMain->stabilizer()->Arm(); } void Controller::Disarm() { gDebug() << "Disarming"; mMain->stabilizer()->Disarm(); // mArmed = false; // mThrust = 0.0f; mMain->stabilizer()->Reset( 0.0f ); // mRPY = Vector3f(); // mSmoothRPY = Vector3f(); mMain->frame()->Disarm(); } bool Controller::run() { char stmp[64]; if ( !mMain->ready() ) { usleep( 1000 * 250 ); return true; } if ( !mLink ) { gDebug() << "Controller no link"; usleep( 1000 * 250 ); return true; } if ( !mLink->isConnected() ) { mConnected = false; // mRPY.x = 0.0f; // mRPY.y = 0.0f; mMain->stabilizer()->Disarm(); mMain->stabilizer()->setRoll( 0.0f ); mMain->stabilizer()->setPitch( 0.0f ); gDebug() << "Link not up, connecting..."; int ret = mLink->Connect(); gDebug() << "mLink->Connect() returned " << ret; if ( mLink->isConnected() ) { gDebug() << "Controller link initialized !"; mEmergencyTick = 0; } else { usleep( 1000 * 250 ); } return true; } SyncReturn readret = CONTINUE; Packet command; if ( ( readret = mLink->Read( &command, 0 ) ) == TIMEOUT ) { if ( not mTimedOut ) { mMain->blackbox()->Enqueue( "Controller:connected", "false" ); } mTimedOut = true; // if ( mArmed ) { if ( mMain->stabilizer()->armed() ) { gDebug() << "Controller connection lost !"; // mThrust = 0.0f; mMain->stabilizer()->Disarm(); mMain->stabilizer()->Reset( 0.0f ); mMain->frame()->Disarm(); // mRPY = Vector3f(); // mSmoothRPY = Vector3f(); // mArmed = false; gDebug() << "STONE MODE !"; return true; } } else if ( readret == CONTINUE ) { return true; } else { if ( mTimedOut ) { if ( mConnected ) { mMain->blackbox()->Enqueue( "Controller:connected", "true" ); } mTimedOut = false; } } mMain->blackbox()->Enqueue( "Link:quality", to_string(mLink->RxQuality()) + "% @" + to_string(mLink->RxLevel()) + "dBm" ); auto ReadCmd = []( Packet* command, Cmd* cmd ) { uint8_t part1 = 0; uint8_t part2 = 0; if ( command->ReadU8( &part1 ) == sizeof(uint8_t) ) { if ( ( part1 & SHORT_COMMAND ) == SHORT_COMMAND ) { *cmd = (Cmd)part1; return (int)sizeof(uint8_t); } if ( command->ReadU8( &part2 ) == sizeof(uint8_t) ) { *cmd = (Cmd)ntohs( ( ((uint16_t)part2) << 8 ) | part1 ); return (int)sizeof(uint16_t); } } return 0; }; if ( not mConnected ) { // mSendMutex.lock(); // Packet connect; // connect.WriteU8( CONNECT ); // mLink->Write( &connect ); // mSendMutex.unlock(); // printf( "sent CONNECT\n" ); for ( int32_t i = 0; i < readret; i++ ) { uint8_t part1 = 0; if ( command.ReadU8( &part1 ) == sizeof(uint8_t) ) { // if ( part1 == CONNECT ) { if ( part1 == PING ) { gDebug() << "Controller connected !"; mConnected = true; mConnectionEstablished = true; } } } usleep( 1000 * 10 ); return true; } Cmd cmd = (Cmd)0; LuaValue commandArg; bool acknowledged = false; while ( ReadCmd( &command, &cmd ) > 0 ) { // if ( cmd != PING and cmd != TELEMETRY and cmd != CONTROLS and cmd != STATUS ) { gTrace() << "Received command (" << hex << (int)cmd << dec << ") : " << mCommandsNames[(cmd)]; // } bool do_response = false; Packet response; if ( ( cmd & SHORT_COMMAND ) == SHORT_COMMAND ) { response.WriteU8( cmd ); } else { response.WriteU16( cmd ); } if ( ( cmd & ACK_ID ) == ACK_ID ) { uint16_t id = cmd & ~ACK_ID; gDebug() << "Received ACK with ID " << id; if ( id == mRXAckID ) { acknowledged = true; } else { acknowledged = false; } mRXAckID = id; response.WriteU16( cmd ); do_response = true; cmd = ACK_ID; } if ( not mConnected ) { if ( cmd == PING ) { gDebug() << "Controller connected !"; mConnected = true; mConnectionEstablished = true; mMain->blackbox()->Enqueue( "Controller:connected", "true" ); mMain->blackbox()->Enqueue( "Controller:armed", mMain->stabilizer()->armed() ? "true" : "false" ); } else { gDebug() << "Ignoring command " << hex << (int)cmd << dec << "(size : " << readret << ")"; continue; } } switch ( cmd ) { case ACK_ID: { break; } case PING : { uint16_t ticks = 0; if ( command.ReadU16( &ticks ) == sizeof(uint16_t) ) { response.WriteU16( ticks ); uint16_t last = command.ReadU16(); mPing = last; response.WriteU16( last ); // Copy-back reported ping // mMain->blackbox()->Enqueue( "Controller:ping", to_string(mPing) + "ms" ); do_response = true; } break; } case TELEMETRY: { // Send telemetry Telemetry telemetry; telemetry.battery_voltage = (uint16_t)( mMain->powerThread()->VBat() * 100.0f ); telemetry.total_current = (uint16_t)( mMain->powerThread()->CurrentTotal() * 1000.0f ); telemetry.current_draw = (uint8_t)( mMain->powerThread()->CurrentDraw() * 10.0f ); telemetry.battery_level = (uint8_t)( mMain->powerThread()->BatteryLevel() * 100.0f ); telemetry.cpu_load = Board::CPULoad(); telemetry.cpu_temp = Board::CPUTemp(); telemetry.rx_quality = mLink->RxQuality(); telemetry.rx_level = mLink->RxLevel(); response.Write( (uint8_t*)&telemetry, sizeof(telemetry) ); // Send status uint32_t status = 0; if ( mMain->stabilizer()->armed() ) { status |= STATUS_ARMED; } if ( mMain->imu()->state() == IMU::Running ) { status |= STATUS_CALIBRATED; } else if ( mMain->imu()->state() == IMU::Calibrating or mMain->imu()->state() == IMU::CalibratingAll ) { status |= STATUS_CALIBRATING; } // if ( mMain->camera() ) { // if ( mMain->camera()->nightMode() ) { // status |= STATUS_NIGHTMODE; // } // } response.WriteU8( STATUS ); response.WriteU32( status ); do_response = true; break; } case CONTROLS : { if ( not mConnected ) { // Should never happen (except at first controller connection) break; } Controls controls = { 0, 0, 0, 0, 0, 0, 0, 0 }; if ( command.Read( (uint8_t*)&controls, sizeof(controls) ) == sizeof(controls) ) { if ( controls.arm and not mMain->stabilizer()->armed() and mMain->imu()->state() == IMU::Running ) { Arm(); mMain->stabilizer()->Arm(); mMain->blackbox()->Enqueue( "Controller:armed", mMain->stabilizer()->armed() ? "true" : "false" ); } else if ( not controls.arm and mMain->stabilizer()->armed() ) { Disarm(); mMain->stabilizer()->Disarm(); mMain->blackbox()->Enqueue( "Controller:armed", mMain->stabilizer()->armed() ? "true" : "false" ); } if ( mMain->stabilizer()->armed() ) { float thrust = ((float)controls.thrust) / 511.0f; float roll = ((float)controls.roll) / 511.0f; float pitch = ((float)controls.pitch) / 511.0f; float yaw = ((float)controls.yaw) / 511.0f; gTrace() << "Controls : " << thrust << ", " << roll << ", " << pitch << ", " << yaw; thrust = setThrust( thrust ); roll = setRoll( roll ); pitch = setPitch( pitch ); yaw = setYaw( yaw ); sprintf( stmp, "\"%.4f,%.4f,%.4f,%.4f\"", thrust, roll, pitch, yaw ); mMain->blackbox()->Enqueue( "Controller:trpy", stmp ); } } break; } case GET_BOARD_INFOS : { string res = mMain->board()->infos(); response.WriteString( res ); do_response = true; break; } #ifdef BUILD_video case GET_SENSORS_INFOS : { string res = Sensor::infosAll().serialize(); response.WriteString( res ); do_response = true; break; } case GET_CAMERAS_INFOS : { string res = Camera::infosAll().serialize(); response.WriteString( res ); do_response = true; break; } #endif case GET_CONFIG_FILE : { string conf = mMain->config()->ReadFile(); response.WriteU32( crc32( (uint8_t*)conf.c_str(), conf.length() ) ); response.WriteString( conf ); do_response = true; break; } case SET_CONFIG_FILE : { uint32_t crc = command.ReadU32(); string conf = command.ReadString(); if ( crc32( (uint8_t*)conf.c_str(), conf.length() ) == crc ) { gDebug() << "Received new configuration : " << conf; response.WriteU32( 0 ); #ifdef SYSTEM_NAME_Linux mSendMutex.lock(); #endif mLink->Write( &response ); #ifdef SYSTEM_NAME_Linux mSendMutex.unlock(); #endif mMain->config()->WriteFile( conf ); mMain->board()->Reset(); } else { gDebug() << "Received broken configuration"; response.WriteU32( 1 ); do_response = true; } break; } case UPDATE_UPLOAD_INIT : { gDebug() << "UPDATE_UPLOAD_INIT"; if ( mTelemetryThread->running() ) { mTelemetryThread->Pause(); gDebug() << "Telemetry thread paused"; } break; } case UPDATE_UPLOAD_DATA : { gDebug() << "UPDATE_UPLOAD_DATA"; uint32_t crc = command.ReadU32(); uint32_t offset = command.ReadU32(); uint32_t offset2 = command.ReadU32(); uint32_t size = command.ReadU32(); uint32_t size2 = command.ReadU32(); if ( offset == offset2 and offset < 4 * 1024 * 1024 ) { if ( size == size2 and size < 4 * 1024 * 1024 ) { uint8_t* buf = new uint8_t[ size + 32 ]; command.Read( (uint8_t*)buf, size ); uint32_t local_crc = crc32( buf, size ); if ( local_crc == crc ) { response.WriteU32( 1 ); #ifdef SYSTEM_NAME_Linux mSendMutex.lock(); #endif mLink->Write( &response ); #ifdef SYSTEM_NAME_Linux mSendMutex.unlock(); #endif Board::UpdateFirmwareData( buf, offset, size ); } else { gDebug() << "Firmware upload CRC32 is invalid (corrupted WiFi frame ?)"; response.WriteU32( 2 ); do_response = true; } } else { gDebug() << "Firmware upload size is incoherent (corrupted WiFi frame ?)"; response.WriteU32( 3 ); do_response = true; } } else { gDebug() << "Firmware upload offset is incoherent (corrupted WiFi frame ?)"; response.WriteU32( 4 ); do_response = true; } break; } case UPDATE_UPLOAD_PROCESS : { gDebug() << "UPDATE_UPLOAD_PROCESS"; uint32_t crc = command.ReadU32(); gDebug() << "Processing firmware update..."; Board::UpdateFirmwareProcess( crc ); break; } case ENABLE_TUN_DEVICE : { gDebug() << "Enabling tun device..."; Board::EnableTunDevice(); break; } case DISABLE_TUN_DEVICE : { gDebug() << "Disabling tun device..."; Board::DisableTunDevice(); break; } case CALIBRATE : { uint32_t full_recalibration = 0; float curr_altitude = 0.0f; if ( command.ReadU32( &full_recalibration ) == sizeof(uint32_t) and command.ReadFloat( &curr_altitude ) == sizeof(float) ) { if ( mMain->stabilizer()->armed() ) { response.WriteU32( 0xFFFFFFFF ); } else { if ( full_recalibration ) { mMain->imu()->RecalibrateAll(); } else { mMain->imu()->Recalibrate(); } response.WriteU32( 3 ); } do_response = true; } response.WriteU16( CALIBRATING ); response.WriteU32( 1 ); break; } case CALIBRATE_ESCS : { // TODO : Abort ESC calibration if already done once, or if drone has been armed before if ( not mMain->stabilizer()->armed() ) { mMain->stabilizer()->CalibrateESCs(); } break; } case MOTOR_TEST : { uint32_t id = command.ReadU32(); if ( not mMain->stabilizer()->armed() ) { mMain->stabilizer()->MotorTest(id); } break; } case MOTORS_BEEP : { bool enabled = command.ReadU16() != 0; gDebug() << "MOTORS_BEEP : " << enabled; if ( not mMain->frame()->armed() ) { mMain->frame()->MotorsBeep( enabled ); } break; } case SET_TIMESTAMP : { uint32_t timestamp = 0; if ( command.ReadU32( &timestamp ) == sizeof(timestamp) ) { mMain->board()->setLocalTimestamp( timestamp ); response.WriteU32( 0 ); do_response = true; } break; } case SET_FULL_TELEMETRY : { uint32_t full = 0; if ( command.ReadU32( &full ) == sizeof(full) ) { mTelemetryFull = full; } break; } case ARM : { /* if ( mMain->imu()->state() != IMU::Running ) { response.WriteU32( 0 ); do_response = true; break; } Arm(); mMain->blackbox()->Enqueue( "Controller:armed", mArmed ? "true" : "false" ); response.WriteU32( mArmed ); do_response = true; */ break; } case DISARM : { /* if ( mMain->imu()->state() == IMU::Off ) { response.WriteU32( 0 ); do_response = true; break; } Disarm(); mMain->blackbox()->Enqueue( "Controller:armed", mArmed ? "true" : "false" ); response.WriteU32( mArmed ); do_response = true; */ break; } case RESET_BATTERY : { uint32_t value = 0; if ( command.ReadU32( &value ) == sizeof(value) ) { mMain->powerThread()->ResetFullBattery( value ); } break; } case SET_ROLL : { float value; if ( command.ReadFloat( &value ) == 0 ) { break; } setRoll( value ); // sprintf( stmp, "%.4f", mRPY.x ); // mMain->blackbox()->Enqueue( "Controller:roll", stmp ); break; } case SET_PITCH : { float value; if ( command.ReadFloat( &value ) == 0 ) { break; } setPitch( value ); // sprintf( stmp, "%.4f", mRPY.y ); // mMain->blackbox()->Enqueue( "Controller:pitch", stmp ); break; } case SET_YAW : { float value; if ( command.ReadFloat( &value ) == 0 ) { break; } setYaw( value ); // sprintf( stmp, "%.4f", mRPY.z ); // mMain->blackbox()->Enqueue( "Controller:yaw", stmp ); break; } case SET_THRUST : { float value; if ( command.ReadFloat( &value ) == 0 ) { break; } setThrust( value ); // sprintf( stmp, "%.4f", mThrust ); // mMain->blackbox()->Enqueue( "Controller:thrust", stmp ); break; } case RESET_MOTORS : { // mThrust = 0.0f; mMain->stabilizer()->Disarm(); mMain->stabilizer()->Reset( 0.0f ); mMain->frame()->Disarm(); // mRPY = Vector3f(); break; } case SET_MODE : { uint32_t mode = 0; if( command.ReadU32( &mode ) == sizeof(uint32_t) ) { gDebug() << "SET_MODE : " << mode; mMain->stabilizer()->setMode( mode ); // mRPY.x = 0.0f; // mRPY.y = 0.0f; setRoll( 0.0f, true ); setPitch( 0.0f, true ); if ( mode == (uint32_t)Stabilizer::Rate ) { setYaw( 0.0f, true ); mMain->blackbox()->Enqueue( "Controller:mode", "Rate" ); } else if ( mode == (uint32_t)Stabilizer::Stabilize ) { mMain->imu()->ResetRPY(); setYaw( mMain->imu()->RPY().z, true ); mMain->blackbox()->Enqueue( "Controller:mode", "Stabilize" ); } response.WriteU32( mMain->stabilizer()->mode() ); do_response = true; } break; } case SET_ALTITUDE_HOLD : { uint32_t enabled = 0; if( command.ReadU32( &enabled ) == sizeof(uint32_t) ) { mMain->stabilizer()->setAltitudeHold( enabled != 0 and Sensor::Altimeters().size() > 0 ); response.WriteU32( mMain->stabilizer()->altitudeHold() ); do_response = true; } break; } case SET_ROLL_PID_P : { float value; if ( command.ReadFloat( &value ) == 0 or abs(value) > 1.0f ) { break; } mMain->stabilizer()->setRollP( value ); response.WriteFloat( value ); do_response = true; break; } case SET_ROLL_PID_I : { float value; if ( command.ReadFloat( &value ) == 0 or abs(value) > 1.0f ) { break; } mMain->stabilizer()->setRollI( value ); response.WriteFloat( value ); do_response = true; break; } case SET_ROLL_PID_D : { float value; if ( command.ReadFloat( &value ) == 0 or abs(value) > 1.0f ) { break; } mMain->stabilizer()->setRollD( value ); response.WriteFloat( value ); do_response = true; break; } case ROLL_PID_FACTORS : { Vector3f pid = mMain->stabilizer()->getRollPID(); response.WriteFloat( pid.x ); response.WriteFloat( pid.y ); response.WriteFloat( pid.z ); do_response = true; break; } case SET_PITCH_PID_P : { float value; if ( command.ReadFloat( &value ) == 0 or abs(value) > 1.0f ) { break; } mMain->stabilizer()->setPitchP( value ); response.WriteFloat( value ); do_response = true; break; } case SET_PITCH_PID_I : { float value; if ( command.ReadFloat( &value ) == 0 or abs(value) > 1.0f ) { break; } mMain->stabilizer()->setPitchI( value ); response.WriteFloat( value ); do_response = true; break; } case SET_PITCH_PID_D : { float value; if ( command.ReadFloat( &value ) == 0 or abs(value) > 1.0f ) { break; } mMain->stabilizer()->setPitchD( value ); response.WriteFloat( value ); do_response = true; break; } case PITCH_PID_FACTORS : { Vector3f pid = mMain->stabilizer()->getPitchPID(); response.WriteFloat( pid.x ); response.WriteFloat( pid.y ); response.WriteFloat( pid.z ); do_response = true; break; } case SET_YAW_PID_P : { float value; if ( command.ReadFloat( &value ) == 0 or abs(value) > 1.0f ) { break; } mMain->stabilizer()->setYawP( value ); response.WriteFloat( value ); do_response = true; break; } case SET_YAW_PID_I : { float value; if ( command.ReadFloat( &value ) == 0 or abs(value) > 1.0f ) { break; } mMain->stabilizer()->setYawI( value ); response.WriteFloat( value ); do_response = true; break; } case SET_YAW_PID_D : { float value; if ( command.ReadFloat( &value ) == 0 or abs(value) > 1.0f ) { break; } mMain->stabilizer()->setYawD( value ); response.WriteFloat( value ); do_response = true; break; } case YAW_PID_FACTORS : { Vector3f pid = mMain->stabilizer()->getYawPID(); response.WriteFloat( pid.x ); response.WriteFloat( pid.y ); response.WriteFloat( pid.z ); do_response = true; break; } case PID_OUTPUT : { Vector3f pid = mMain->stabilizer()->lastPIDOutput(); response.WriteFloat( pid.x ); response.WriteFloat( pid.y ); response.WriteFloat( pid.z ); do_response = true; break; } case SET_OUTER_PID_P : { float value; if ( command.ReadFloat( &value ) == 0 or abs(value) > 50.0f ) { break; } // mMain->stabilizer()->setOuterP( value ); response.WriteFloat( value ); do_response = true; break; } case SET_OUTER_PID_I : { float value; if ( command.ReadFloat( &value ) == 0 or abs(value) > 50.0f ) { break; } // mMain->stabilizer()->setOuterI( value ); response.WriteFloat( value ); do_response = true; break; } case SET_OUTER_PID_D : { float value; if ( command.ReadFloat( &value ) == 0 or abs(value) > 50.0f ) { break; } // mMain->stabilizer()->setOuterD( value ); response.WriteFloat( value ); do_response = true; break; } case OUTER_PID_FACTORS : { // Vector3f pid = mMain->stabilizer()->getOuterPID(); // response.WriteFloat( pid.x ); // response.WriteFloat( pid.y ); // response.WriteFloat( pid.z ); response.WriteFloat( 0.0f ); response.WriteFloat( 0.0f ); response.WriteFloat( 0.0f ); do_response = true; break; } case OUTER_PID_OUTPUT : { // Vector3f pid = mMain->stabilizer()->lastOuterPIDOutput(); // response.WriteFloat( pid.x ); // response.WriteFloat( pid.y ); // response.WriteFloat( pid.z ); response.WriteFloat( 0.0f ); response.WriteFloat( 0.0f ); response.WriteFloat( 0.0f ); do_response = true; break; } case SET_HORIZON_OFFSET : { Vector3f v; if ( command.ReadFloat( &v.x ) == 0 or command.ReadFloat( &v.y ) == 0 or abs(v.x) > 45.0f or abs(v.y) > 45.0f ) { break; } mMain->stabilizer()->setHorizonOffset( v ); response.WriteFloat( v.x ); response.WriteFloat( v.y ); do_response = true; break; } case HORIZON_OFFSET : { response.WriteFloat( mMain->stabilizer()->horizonOffset().x ); response.WriteFloat( mMain->stabilizer()->horizonOffset().y ); do_response = true; break; } case VIDEO_PAUSE : { /* Camera* cam = mMain->camera(); if ( cam ) { cam->Pause(); gDebug() << "Video paused"; } */ response.WriteU32( 1 ); do_response = true; break; } case VIDEO_RESUME : { /* Camera* cam = mMain->camera(); if ( cam ) { cam->Resume(); gDebug() << "Video resumed"; } */ response.WriteU32( 0 ); do_response = true; break; } case VIDEO_START_RECORD : { response.WriteU32( 1 ); do_response = true; break; } case VIDEO_STOP_RECORD : { response.WriteU32( 0 ); do_response = true; break; } case VIDEO_TAKE_PICTURE : { Camera* cam = mMain->camera(); if ( cam ) { cam->TakePicture(); gDebug() << "Picture taken"; } break; } case VIDEO_BRIGHTNESS_INCR : { Camera* cam = mMain->camera(); if ( cam ) { gDebug() << "Setting camera brightness to " << cam->brightness() + 0.05f; cam->setBrightness( cam->brightness() + 0.05f ); } break; } case VIDEO_BRIGHTNESS_DECR : { Camera* cam = mMain->camera(); if ( cam ) { gDebug() << "Setting camera brightness to " << cam->brightness() - 0.05f; cam->setBrightness( cam->brightness() - 0.05f ); } break; } case VIDEO_CONTRAST_INCR : { Camera* cam = mMain->camera(); if ( cam ) { gDebug() << "Setting camera contrast to " << cam->contrast() + 0.05f; cam->setContrast( cam->contrast() + 0.05f ); } break; } case VIDEO_CONTRAST_DECR : { Camera* cam = mMain->camera(); if ( cam ) { gDebug() << "Setting camera contrast to " << cam->contrast() - 0.05f; cam->setContrast( cam->contrast() - 0.05f ); } break; } case VIDEO_SATURATION_INCR : { Camera* cam = mMain->camera(); if ( cam ) { gDebug() << "Setting camera saturation to " << cam->saturation() + 0.05f; cam->setSaturation( cam->saturation() + 0.05f ); } break; } case VIDEO_SATURATION_DECR : { Camera* cam = mMain->camera(); if ( cam ) { gDebug() << "Setting camera saturation to " << cam->saturation() - 0.05f; cam->setSaturation( cam->saturation() - 0.05f ); } break; } case VIDEO_ISO_INCR : { Camera* cam = mMain->camera(); if ( cam ) { gDebug() << "Setting camera ISO to " << cam->ISO() + 100; cam->setISO( cam->ISO() + 100 ); } break; } case VIDEO_ISO_DECR : { Camera* cam = mMain->camera(); if ( cam and cam->ISO() > 0 ) { gDebug() << "Setting camera ISO to " << cam->ISO() - 100; cam->setISO( cam->ISO() - 100 ); } break; } case VIDEO_SHUTTER_SPEED_INCR : { Camera* cam = mMain->camera(); if ( cam ) { gDebug() << "Setting camera shutter speed to " << cam->shutterSpeed() + 100; cam->setShutterSpeed( cam->shutterSpeed() + 100 ); } break; } case VIDEO_SHUTTER_SPEED_DECR : { Camera* cam = mMain->camera(); if ( cam and cam->shutterSpeed() > 0 ) { gDebug() << "Setting camera shutter speed to " << cam->shutterSpeed() - 100; cam->setShutterSpeed( cam->shutterSpeed() - 100 ); } break; } case VIDEO_ISO : { Camera* cam = mMain->camera(); if ( cam ) { response.WriteU32( (uint32_t)cam->ISO() ); do_response = true; } break; } case VIDEO_SHUTTER_SPEED : { Camera* cam = mMain->camera(); if ( cam ) { response.WriteU32( cam->shutterSpeed() ); do_response = true; } break; } case VIDEO_LENS_SHADER : { Camera* cam = mMain->camera(); if ( cam ) { Camera::LensShaderColor r, g, b; cam->getLensShader( &r, &g, &b ); response.WriteU8( r.base ); response.WriteU8( r.radius ); response.WriteU8( r.strength ); response.WriteU8( g.base ); response.WriteU8( g.radius ); response.WriteU8( g.strength ); response.WriteU8( b.base ); response.WriteU8( b.radius ); response.WriteU8( b.strength ); do_response = true; } break; } case VIDEO_SET_LENS_SHADER : { Camera::LensShaderColor r, g, b; r.base = command.ReadU8(); r.radius = command.ReadU8(); r.strength = command.ReadU8(); g.base = command.ReadU8(); g.radius = command.ReadU8(); g.strength = command.ReadU8(); b.base = command.ReadU8(); b.radius = command.ReadU8(); b.strength = command.ReadU8(); auto int35_float = []( int32_t value ) { if ( value < 0 ) { return -1.0f * ( (float)( (-value) >> 5 ) + (float)( (-value) & 0b00011111 ) / 32.0f ); } return (float)( value >> 5 ) + (float)( value & 0b00011111 ) / 32.0f; }; if ( r.base != 0 and g.base != 0 and b.base != 0 and r.strength != 0 and g.strength != 0 and b.strength != 0 ) { mMain->config()->setNumber( "camera.lens_shading.r.base", int35_float( r.base ) ); mMain->config()->setInteger( "camera.lens_shading.r.radius", r.radius ); mMain->config()->setNumber( "camera.lens_shading.r.strength", int35_float( r.strength ) ); mMain->config()->setNumber( "camera.lens_shading.g.base", int35_float( g.base ) ); mMain->config()->setInteger( "camera.lens_shading.g.radius", g.radius ); mMain->config()->setNumber( "camera.lens_shading.g.strength", int35_float( g.strength ) ); mMain->config()->setNumber( "camera.lens_shading.b.base", int35_float( b.base ) ); mMain->config()->setInteger( "camera.lens_shading.b.radius", b.radius ); mMain->config()->setNumber( "camera.lens_shading.b.strength", int35_float( b.strength ) ); mMain->config()->Save(); Camera* cam = mMain->camera(); if ( cam ) { cam->setLensShader( r, g, b ); } } break; } case VIDEO_NIGHT_MODE : { uint32_t night = command.ReadU32(); commandArg = night; /* Camera* cam = mMain->camera(); if ( cam ) { gDebug() << "Setting camera to " << ( night ? "night" : "day" ) << " mode"; cam->setNightMode( night ); } */ response.WriteU32( night ); do_response = true; break; } case VIDEO_EXPOSURE_MODE : { Camera* cam = mMain->camera(); string ret = "(none)"; if ( cam ) { if ( acknowledged ) { ret = cam->exposureMode(); } else { ret = cam->switchExposureMode(); gDebug() << "Camera exposure mode set to \"" << ret << "\""; } } response.WriteString( ret ); do_response = true; break; } case VIDEO_WHITE_BALANCE : { Camera* cam = mMain->camera(); string ret = "(none)"; if ( cam ) { if ( acknowledged ) { ret = cam->whiteBalance(); } else { ret = cam->switchWhiteBalance(); gDebug() << "Camera white balance set to \"" << ret << "\""; } } response.WriteString( ret ); do_response = true; break; } case VIDEO_LOCK_WHITE_BALANCE : { Camera* cam = mMain->camera(); string ret = "(none)"; if ( cam ) { if ( acknowledged ) { ret = cam->whiteBalance(); } else { ret = cam->lockWhiteBalance(); gDebug() << "Camera white balance \"" << ret << "\""; } } response.WriteString( ret ); do_response = true; break; } case GET_RECORDINGS_LIST : { string rec = mMain->getRecordingsList(); response.WriteU32( crc32( (uint8_t*)rec.c_str(), rec.length() ) ); response.WriteString( rec ); do_response = true; break; } /* case RECORD_DOWNLOAD : { string file = command.ReadString(); // mMain->UploadFile( filename ); // TODO break; } */ case GET_USERNAME : { if ( mMain->username() != "" ) { response.WriteString( mMain->username() ); } else { response.WriteString( "[unknown]" ); } do_response = true; break; } case VTX_GET_SETTINGS : { SmartAudio* vtx = mMain->config()->Object<SmartAudio>( "vtx" ); gDebug() << "VTX_GET_SETTINGS, vtx : " << vtx; if ( vtx ) { response.WriteU8( uint8_t(vtx->getChannel()) ); response.WriteU16( uint16_t(vtx->getFrequency()) ); response.WriteU8( uint8_t(vtx->getPower()) ); response.WriteU8( uint8_t(vtx->getPowerDbm()) ); response.WriteU8( vtx->getPowerTable().size() ); for ( auto v : vtx->getPowerTable() ) { response.WriteU8( v ); } } else { response.WriteU8( 0xFF ); response.WriteU16( 0xFFFF ); response.WriteU8( 0xFF ); response.WriteU8( 0xFF ); response.WriteU8( 0 ); } do_response = true; break; } case VTX_SET_POWER : { SmartAudio* vtx = mMain->config()->Object<SmartAudio>( "vtx" ); if ( vtx ) { vtx->setPower( command.ReadU8() ); response.WriteU8( uint8_t(vtx->getPower()) ); response.WriteU8( uint8_t(vtx->getPowerDbm()) ); } else { response.WriteU8( 0xFF ); response.WriteU8( 0xFF ); } do_response = true; break; } case VTX_SET_CHANNEL : { SmartAudio* vtx = mMain->config()->Object<SmartAudio>( "vtx" ); if ( vtx ) { vtx->setChannel( command.ReadU8() ); response.WriteU8( uint8_t(vtx->getChannel()) ); response.WriteU16( uint16_t(vtx->getFrequency()) ); } else { response.WriteU8( 0xFF ); response.WriteU16( 0xFFFF ); } do_response = true; break; } default: { printf( "Controller::run() WARNING : Unknown command 0x%08X\n", cmd ); break; } } const auto& f = mEvents[cmd]; if ( f ) { f(commandArg); } if ( do_response ) { #ifdef SYSTEM_NAME_Linux mSendMutex.lock(); #endif mLink->Write( &response ); #ifdef SYSTEM_NAME_Linux mSendMutex.unlock(); #endif } } return true; } bool Controller::TelemetryRun() { if ( !mLink or !mLink->isConnected() ) { usleep( 1000 * 10 ); return true; } Packet telemetry; if ( mTelemetryCounter % 10 == 0 ) { telemetry.WriteU16( STABILIZER_FREQUENCY ); telemetry.WriteU32( mMain->loopFrequency() ); if ( mMain->frame() and mTelemetryFull ) { vector< Motor* >* motors = mMain->frame()->motors(); if ( motors ) { telemetry.WriteU16( MOTORS_SPEED ); telemetry.WriteU32( motors->size() ); for ( Motor* m : *motors ) { telemetry.WriteFloat( m->speed() ); } } } #ifdef CAMERA if ( mMain->cameraType() != "" ) { telemetry.WriteU16( ERROR_CAMERA_MISSING ); } #endif } if ( mTelemetryCounter % 5 == 0 ) { if ( mMain->powerThread() ) { telemetry.WriteU16( VBAT ); telemetry.WriteFloat( mMain->powerThread()->VBat() ); telemetry.WriteU16( TOTAL_CURRENT ); telemetry.WriteFloat( mMain->powerThread()->CurrentTotal() ); telemetry.WriteU16( CURRENT_DRAW ); telemetry.WriteFloat( mMain->powerThread()->CurrentDraw() ); telemetry.WriteU16( BATTERY_LEVEL ); telemetry.WriteFloat( mMain->powerThread()->BatteryLevel() ); } telemetry.WriteU16( CPU_LOAD ); telemetry.WriteU32( Board::CPULoad() ); telemetry.WriteU16( CPU_TEMP ); telemetry.WriteU32( Board::CPUTemp() ); telemetry.WriteU16( RX_QUALITY ); telemetry.WriteU32( mLink->RxQuality() ); telemetry.WriteU16( RX_LEVEL ); telemetry.WriteU32( mLink->RxLevel() ); } if ( mTelemetryFull ) { if ( mMain->stabilizer() ) { telemetry.WriteU16( SET_THRUST ); telemetry.WriteFloat( mMain->stabilizer()->thrust() ); } if ( mMain->imu() ) { telemetry.WriteU16( ROLL_PITCH_YAW ); telemetry.WriteFloat( mMain->imu()->RPY().x ); telemetry.WriteFloat( mMain->imu()->RPY().y ); telemetry.WriteFloat( mMain->imu()->RPY().z ); telemetry.WriteU16( CURRENT_ACCELERATION ); telemetry.WriteFloat( mMain->imu()->acceleration().xyz().length() ); telemetry.WriteU16( ALTITUDE ); telemetry.WriteFloat( mMain->imu()->altitude() ); telemetry.WriteU16( RATES ); telemetry.WriteFloat( mMain->imu()->rate().x ); telemetry.WriteFloat( mMain->imu()->rate().y ); telemetry.WriteFloat( mMain->imu()->rate().z ); telemetry.WriteU16( GYRO ); telemetry.WriteFloat( mMain->imu()->gyroscope().x ); telemetry.WriteFloat( mMain->imu()->gyroscope().y ); telemetry.WriteFloat( mMain->imu()->gyroscope().z ); telemetry.WriteU16( ACCEL ); telemetry.WriteFloat( mMain->imu()->acceleration().x ); telemetry.WriteFloat( mMain->imu()->acceleration().y ); telemetry.WriteFloat( mMain->imu()->acceleration().z ); telemetry.WriteU16( MAGN ); telemetry.WriteFloat( mMain->imu()->magnetometer().x ); telemetry.WriteFloat( mMain->imu()->magnetometer().y ); telemetry.WriteFloat( mMain->imu()->magnetometer().z ); telemetry.WriteU16( GYRO_DTERM ); telemetry.WriteFloat( mMain->stabilizer()->filteredRPYDerivative().x ); telemetry.WriteFloat( mMain->stabilizer()->filteredRPYDerivative().y ); telemetry.WriteFloat( mMain->stabilizer()->filteredRPYDerivative().z ); Filter<Vector3f>* ratesFilter = mMain->imu()->ratesFilters(); if ( ratesFilter ) { DynamicNotchFilter<Vector3f>* dnf = nullptr; dnf = dynamic_cast<typeof(dnf)>(ratesFilter); if ( dnf == nullptr ) { FilterChain<Vector3f>* chain = dynamic_cast<FilterChain<Vector3f>*>( ratesFilter ); if ( chain ) { for ( auto f : chain->filters() ) { if (( dnf = dynamic_cast<typeof(dnf)>(f) )) { break; } } } } if ( dnf ) { const std::vector<Vector3f> data = dnf->dftOutput<float, 3>(); telemetry.WriteU16( RATE_DNF_DFT ); telemetry.WriteU16( data.size() * sizeof(Vector3f) ); telemetry.Write( reinterpret_cast<const uint8_t*>(data.data()), data.size() * sizeof(Vector3f) ); } } } } #ifdef SYSTEM_NAME_Linux mSendMutex.lock(); #endif mLink->Write( &telemetry ); #ifdef SYSTEM_NAME_Linux mSendMutex.unlock(); #endif // mTelemetryTick = Board::WaitTick( 1000000 / mTelemetryFrequency, mTelemetryTick ); mTelemetryCounter++; return true; } uint32_t Controller::crc32( const uint8_t* buf, uint32_t len ) { uint32_t k = 0; uint32_t crc = 0; crc = ~crc; while ( len-- ) { crc ^= *buf++; for ( k = 0; k < 8; k++ ) { crc = ( crc & 1 ) ? ( (crc >> 1) ^ 0x82f63b78 ) : ( crc >> 1 ); } } return ~crc; }
39,622
C++
.cpp
1,387
24.33814
128
0.601059
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,700
Config.cpp
dridri_bcflight/flight/Config.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <list> #include <fstream> #include <algorithm> #include <string.h> #include "Debug.h" #include "Config.h" #include <Accelerometer.h> #include <Gyroscope.h> #include <Magnetometer.h> #include <Motor.h> #include <Link.h> extern "C" uint32_t _mem_usage(); extern "C" void lua_init( lua_State* L ); Config::Config( const string& filename, const string& settings_filename ) : mFilename( filename ) , mSettingsFilename( settings_filename ) , mLua( nullptr ) { gDebug() << "step 1 : " << _mem_usage(); gDebug() << LUA_RELEASE; // L = luaL_newstate(); mLua = new Lua(); lua_init( mLua->state() ); gDebug() << "step 2 : " << _mem_usage(); /* // luaL_openlibs( L ); static const luaL_Reg lualibs[] = { { "", luaopen_base }, { LUA_TABLIBNAME, luaopen_table }, { LUA_STRLIBNAME, luaopen_string }, { LUA_MATHLIBNAME, luaopen_math }, { nullptr, nullptr } }; const luaL_Reg* lib = lualibs; for (; lib->func; lib++ ) { lua_pushcfunction( L, lib->func ); lua_pushstring( L, lib->name ); lua_call( L, 1, 0 ); } */ } Config::~Config() { // lua_close(L); if ( mLua ) { delete mLua; } } Lua* Config::luaState() const { return mLua; } string Config::ReadFile() { string ret = ""; ifstream file( mFilename ); if ( file.is_open() ) { file.seekg( 0, file.end ); int length = file.tellg(); char* buf = new char[ length + 1 ]; file.seekg( 0, file.beg ); file.read( buf, length ); buf[length] = 0; ret = buf; delete buf; file.close(); } return ret; } void Config::WriteFile( const string& content ) { ofstream file( mFilename ); if ( file.is_open() ) { file.write( content.c_str(), content.length() ); file.close(); } } string Config::String( const string& name, const string& def ) { Debug dbg(Debug::Verbose); dbg + _debug_date() + self_thread() + _debug_level(Debug::Verbose) + __CLASS_NAME__ + "::" + __FUNCTION_NAME__ + "("; dbg.fDebug_top(name); LuaValue v = mLua->value( name ); if ( v.type() != LuaValue::String ) { dbg << " => not found !"; return def; } string ret = v.toString(); dbg << " => " << ret << ""; return ret; } int Config::Integer( const string& name, int def ) { Debug dbg(Debug::Verbose); dbg + _debug_date() + self_thread() + _debug_level(Debug::Verbose) + __CLASS_NAME__ + "::" + __FUNCTION_NAME__ + "("; dbg.fDebug_top(name); LuaValue v = mLua->value( name ); if ( v.type() != LuaValue::Integer ) { dbg << " => not found !"; return def; } int ret = v.toInteger(); dbg << " => " << ret << ""; return ret; } float Config::Number( const string& name, float def ) { Debug dbg(Debug::Verbose); dbg + _debug_date() + self_thread() + _debug_level(Debug::Verbose) + __CLASS_NAME__ + "::" + __FUNCTION_NAME__ + "("; dbg.fDebug_top(name); LuaValue v = mLua->value( name ); if ( v.type() != LuaValue::Number and v.type() != LuaValue::Integer ) { dbg << " => not found !"; return def; } float ret = v.toNumber(); dbg << " => " << ret << ""; return ret; } bool Config::Boolean( const string& name, bool def ) { Debug dbg(Debug::Verbose); dbg + _debug_date() + self_thread() + _debug_level(Debug::Verbose) + __CLASS_NAME__ + "::" + __FUNCTION_NAME__ + "("; dbg.fDebug_top(name); LuaValue v = mLua->value( name ); if ( v.type() != LuaValue::Boolean ) { dbg << " => not found !"; return def; } bool ret = v.toBoolean(); dbg << " => " << ret << ""; return ret; } void* Config::Object( const string& name, void* def ) { Debug dbg(Debug::Verbose); dbg + _debug_date() + self_thread() + _debug_level(Debug::Verbose) + __CLASS_NAME__ + "::" + __FUNCTION_NAME__ + "("; dbg.fDebug_top(name); LuaValue v = mLua->value( name ); if ( v.type() != LuaValue::UserData ) { dbg << " => not found !"; return def; } void* ret = v.toUserData(); dbg << " => " << ret << ""; return ret; } vector<int> Config::IntegerArray( const string& name ) { Debug dbg(Debug::Verbose); dbg + _debug_date() + self_thread() + _debug_level(Debug::Verbose) + __CLASS_NAME__ + "::" + __FUNCTION_NAME__ + "("; dbg.fDebug_top(name); LuaValue v = mLua->value( name ); if ( v.type() != LuaValue::Table ) { dbg << " => not found !"; return vector<int>(); } vector<int> ret; const map< string, LuaValue >& t = v.toTable(); for ( std::pair< string, LuaValue > a : t ) { int i = a.second.toInteger(); dbg << ", " << i; ret.emplace_back( i ); } dbg << " => Ok"; return ret; } int Config::ArrayLength( const string& name ) { Debug dbg(Debug::Verbose); dbg + _debug_date() + self_thread() + _debug_level(Debug::Verbose) + __CLASS_NAME__ + "::" + __FUNCTION_NAME__ + "("; dbg.fDebug_top(name); LuaValue v = mLua->value( name ); if ( v.type() != LuaValue::Table ) { dbg << " => not found !"; return -1; } int ret = 0; const map< string, LuaValue >& t = v.toTable(); for ( std::pair< string, LuaValue > a : t ) { ret++; } return ret; } int Config::LocateValue( const string& _name ) { return 0; } string Config::DumpVariable( const string& name, int index, int indent ) { return name + " = " + mLua->value( name ).serialize(); } void Config::Execute( const string& code, bool silent ) { if ( not silent ) { fDebug( code ); } mLua->do_string( code ); } static inline string& ltrim( string& s, const char* t = " \t\n\r\f\v" ) { s.erase(0, s.find_first_not_of(t)); return s; } static inline string& rtrim( string& s, const char* t = " \t\n\r\f\v" ) { s.erase(s.find_last_not_of(t) + 1); return s; } static inline string& trim( string& s, const char* t = " \t\n\r\f\v" ) { return ltrim(rtrim(s, t), t); } #define LUAdostring( s ) gDebug() << "dostring : " << string(s); mLua->do_string( string(s) ); void Config::Reload() { gDebug() << "Reload 1 : " << _mem_usage(); LUAdostring( "Debug = {}" ); LUAdostring( "Debug.ERROR = " + to_string((int)Debug::Error) ); LUAdostring( "Debug.WARNING = " + to_string((int)Debug::Warning) ); LUAdostring( "Debug.INFO = " + to_string((int)Debug::Info) ); LUAdostring( "Debug.VERBOSE = " + to_string((int)Debug::Verbose) ); LUAdostring( "Debug.TRACE = " + to_string((int)Debug::Trace) ); LUAdostring( "function Vector( x, y, z, w ) return { x = x or 0, y = y or 0, z = z or 0, w = w or 0 } end" ); LUAdostring( "PID = setmetatable( {}, { __call = function ( self, p, i, d ) return { p = p or 0, i = i or 0, d = d or 0 } end } )" ); LUAdostring( "PT1 = PT1_3" ); LUAdostring( "board = { type = \"" + string( BOARD ) + "\" }" ); LUAdostring( "system = { loop_time = 2000 }" ); if ( mFilename != "" ) { int ret = mLua->do_file( mFilename ); if ( ret != 0 ) { exit(0); } } if ( mSettingsFilename != "" ) { string line; string key; string value; ifstream file( mSettingsFilename, fstream::in ); if ( file.is_open() ) { while ( getline( file, line ) ) { key = line.substr( 0, line.find( "=" ) ); value = line.substr( line.find( "=" ) + 1 ); key = trim( key ); value = trim( value ); gDebug() << "mSettings[\"" << key << "\"] = '" << mSettings[ key ] << "'"; mSettings[ key ] = value; LUAdostring( key + " = " + value ); } } } } void Config::Apply() { } void Config::setBoolean( const string& name, const bool v ) { mSettings[name] = ( v ? "true" : "false" ); LUAdostring( name + "=" + mSettings[name] ); } void Config::setInteger( const string& name, const int v ) { mSettings[name] = to_string(v); LUAdostring( name + "=" + mSettings[name] ); } void Config::setNumber( const string& name, const float v ) { mSettings[name] = to_string(v); LUAdostring( name + "=" + mSettings[name] ); } void Config::setString( const string& name, const string& v ) { mSettings[name] = v; LUAdostring( name + "=" + v ); } void Config::Save() { ofstream file( mSettingsFilename ); string str; if ( file.is_open() ) { for ( pair< string, string > setting : mSettings ) { str = setting.first + " = " + setting.second + "\n"; gDebug() << "Saving setting : " << str; file.write( str.c_str(), str.length() ); } file.close(); } }
8,738
C++
.cpp
298
27.080537
140
0.620022
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,701
Console.cpp
dridri_bcflight/flight/Console.cpp
#ifdef SYSTEM_NAME_Linux #include <termios.h> #include <sys/ioctl.h> #endif #include <regex> #include "Console.h" #include "Config.h" Console::Console( Config* config ) : Thread( "console" ) , mConfig( config ) { #ifdef SYSTEM_NAME_Linux if ( getenv("TERM") ) { struct termios term; ioctl(0, TCGETS, &term ); term.c_lflag &= (~ICANON); term.c_cc[VMIN] = 1; term.c_cc[VTIME] = 0; ioctl( 0, TCSETS, &term ); printf("ok\n"); } #endif } Console::~Console() { } bool Console::alnum( char c ) { return ( c >= 'a' and c <= 'z' ) or ( c >= 'A' and c <= 'Z' ) or ( c >= '0' and c <= '9' ) or c == '_'; } bool Console::luavar( char c ) { return ( c >= 'a' and c <= 'z' ) or ( c >= 'A' and c <= 'Z' ) or ( c >= '0' and c <= '9' ) or c == '_' or c == '.' or c == '[' or c == ']'; } bool Console::run() { uint32_t cursor = 0; vector<string> history; for ( const string& s : mFullHistory ) { history.emplace_back( string(s) ); } history.emplace_back(string()); uint32_t history_cursor = history.size() - 1; string* prompt = &history.back(); printf("\33[2K\rflight> "); fflush(stdout); while ( true and not Thread::stopped() ) { fd_set selectset; struct timeval timeout = { 0, 100000 }; FD_ZERO( &selectset ); FD_SET( 0, &selectset ); int waitRet = select( 1, &selectset, nullptr, nullptr, &timeout ); if( waitRet <= 0 ) { continue; } char buf[256]; memset( buf, 0, 256 ); int32_t res = read( 0, buf, 255 ); if (res <= 0) { // This happens when flight is started as a service Thread::Stop(); return false; } buf[res] = 0; // printf("line: %d %02x %02X %02X %02X %02X %02X\n", res, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]); if ( buf[0] == 0x0a ) { break; } else if ( buf[0] == 0x09 ) { int32_t start = cursor; int32_t end = cursor; while ( start > 0 and luavar((*prompt)[start - 1]) ) { start--; } while ( end < (int32_t)prompt->length() and alnum((*prompt)[end]) ) { end++; } if ( start >= 0 and end <= (int32_t)prompt->length() ) { // printf( "start, end : %d, %d\n", start, end ); string query = "_G." + prompt->substr( start, end - start ); string leftquery = query.substr( 0, query.rfind( "." ) ); string rightquery = query.substr( query.rfind( "." ) + 1 ); const vector<string> allKeys = mConfig->luaState()->valueKeys( leftquery ); vector<string> keys; for ( const string& k : allKeys ) { if ( k.find(rightquery) == 0 ) { keys.push_back( k ); } } string commonPart = ""; if ( keys.size() > 0 ) { bool finished = false; while ( true ) { for ( const string& k : keys ) { if ( k.find(commonPart) == k.npos ) { commonPart = commonPart.substr( 0, commonPart.length() - 1 ); finished = true; break; } } if ( finished or commonPart.length() >= keys[0].length() ) { break; } commonPart = keys[0].substr( 0, commonPart.length() + 1 ); }; } if ( commonPart.length() > rightquery.length() ) { string newValue = ( leftquery + "." ).substr( 3 ) + commonPart; *prompt = prompt->substr( 0, start ) + newValue + prompt->substr( end ); cursor = start + newValue.length(); } else if ( keys.size() > 1 ) { printf("\n"); fflush(stdout); for ( const string& k : keys ) { printf( "%s ", k.c_str() ); } printf("\n"); fflush(stdout); } } } else if ( buf[0] == 0x1b and buf[1] == 0x5b ) { if ( buf[2] == 0x41 ) { // up if ( history_cursor > 0 ) { history_cursor--; prompt = &history[history_cursor]; cursor = prompt->length(); } } else if ( buf[2] == 0x42 ) { // down if ( history_cursor < history.size() - 1 ) { history_cursor++; prompt = &history[history_cursor]; cursor = prompt->length(); } } else if ( buf[2] == 0x44 ) { // left if ( cursor > 0 ) { cursor--; } } else if ( buf[2] == 0x43 ) { // right cursor = std::min( (uint32_t)prompt->length(), cursor + 1 ); } else if ( buf[2] == 0x31 and res >= 6 ) { // ctrl if ( buf[3] == 0x3B and buf[4] == 0x35 ) { if ( buf[5] == 0x44 ) { // ctrl + left bool base_type = alnum( (*prompt)[cursor - 1] ); while ( cursor > 0 and alnum( (*prompt)[cursor - 1] ) == base_type ) { cursor--; } } else if ( buf[5] == 0x43 ) { // ctrl + right bool base_type = alnum( (*prompt)[cursor] ); while ( cursor < prompt->length() and alnum( (*prompt)[cursor] ) == base_type ) { cursor++; } } } } else if ( buf[2] == 0x33 ) { // del if ( cursor < prompt->length() ) { prompt->erase( cursor, 1 ); } } else if ( buf[2] == 0x48 ) { // home cursor = 0; } else if ( buf[2] == 0x46 ) { // end cursor = prompt->length(); } } else if ( buf[0] == 0x1b and buf[1] == 0x7f ) { uint32_t cursor2 = cursor; bool base_type = alnum( (*prompt)[cursor2 - 1] ); while ( cursor2 > 0 and alnum( (*prompt)[cursor2 - 1] ) == base_type ) { cursor2--; } prompt->erase( cursor2, cursor - cursor2 ); cursor = cursor2; } else if ( buf[0] == 0x7f ) { if ( cursor > 0 ) { prompt->erase( cursor - 1, 1 ); cursor--; } } else { prompt->insert( cursor, buf ); cursor = std::min( (uint32_t)prompt->length(), cursor + (uint32_t)strlen(buf) ); } string cursor_move; for ( uint32_t i = 0; i < prompt->length() - cursor; i++ ) { cursor_move += "\033[D"; } printf("\33[2K\rflight> %s%s", prompt->c_str(), cursor_move.c_str()); fflush(stdout); } string ppt = string(*prompt); if ( mFullHistory.size() == 0 or ppt != mFullHistory.back() ) { mFullHistory.emplace_back( ppt ); } mConfig->Execute( *prompt, true ); return true; }
5,814
C++
.cpp
198
25.19697
140
0.548473
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,703
Matrix.cpp
dridri_bcflight/flight/Matrix.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include "Debug.h" #include "Matrix.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <cmath> #define PI_OVER_360 0.0087266f #define PI_OVER_180 0.0174532f #define PI_OVER_90 0.0349065f #define min( a, b ) ( ( (a) < (b) ) ? (a) : (b) ) #define max( a, b ) ( ( (a) > (b) ) ? (a) : (b) ) Matrix::Matrix( int w, int h ) : mWidth( w ) , mHeight( h ) { m = (float*)malloc( sizeof(float) * w * h ); Identity(); } Matrix::Matrix( const Matrix& other ) : mWidth( other.mWidth ) , mHeight( other.mHeight ) { m = (float*)malloc( sizeof(float) * mWidth * mHeight ); memcpy( m, other.m, sizeof(float) * mWidth * mHeight ); } Matrix::~Matrix() { if ( m == nullptr ) { gDebug() << "CRITICAL : corrupt matrix !!!"; exit(0); } free( m ); m = nullptr; } void Matrix::Orthogonal( float left, float right, float bottom, float top, float zNear, float zFar ) { Identity(); float tx = - (right + left) / (right - left); float ty = - (top + bottom) / (top - bottom); float tz = - (zFar + zNear) / (zFar - zNear); m[0] = 2.0 / (right - left); m[5] = 2.0 / (top - bottom); m[10] = -2.0 / (zFar - zNear); m[12] = tx; m[13] = ty; m[14] = tz; } float* Matrix::data() { return m; } const float* Matrix::constData() const { return (float*)m; } const int Matrix::width() const { return mWidth; } const int Matrix::height() const { return mHeight; } void Matrix::Clear() { if ( m == nullptr ) { gDebug() << "CRITICAL : corrupt matrix !!!"; exit(0); } memset( m, 0, sizeof(float) * mWidth * mHeight ); } void Matrix::Identity() { Clear(); if ( mWidth == mHeight ) { for ( int i = 0; i < mWidth * mHeight; i++ ) { if ( i % ( mWidth + 1 ) == 0 ) { m[i] = 1.0f; } } } } void Matrix::RotateX( float a ) { Matrix t; t.Identity(); float c = cos( a ); float s = sin( a ); t.m[1*4+1] = c; t.m[1*4+2] = s; t.m[2*4+1] = -s; t.m[2*4+2] = c; // operator*=(t); } void Matrix::RotateY( float a ) { Matrix t; t.Identity(); float c = cos( a ); float s = sin( a ); t.m[0*4+0] = c; t.m[0*4+2] = -s; t.m[2*4+0] = s; t.m[2*4+2] = c; // operator*=(t); } void Matrix::RotateZ( float a ) { Matrix t; t.Identity(); float c = cos( a ); float s = sin( a ); t.m[0*4+0] = c; t.m[0*4+1] = s; t.m[1*4+0] = -s; t.m[1*4+1] = c; // operator*=(t); } Matrix Matrix::Transpose() { Matrix ret( mHeight, mWidth ); for ( int j = 0; j < mHeight; j++ ) { for ( int i = 0; i < mWidth; i++ ) { ret.m[ i * mHeight + j ] = m[ j * mWidth + i ]; } } return ret; } Matrix Matrix::Inverse() { if ( mWidth != mHeight ) { gDebug() << "Error : cannort inverse a non-square matrix !"; return *this; } Matrix tmp( mWidth, mHeight ); Matrix ret( mWidth, mHeight ); int i, I; int k, K; for ( i = 0; i < mWidth*mWidth; i++ ) { tmp.m[i] = m[i]; } for ( i = 0, I = 0; i < mWidth; i++, I += mWidth ) { ret.m[ I + i ] = 1.0 / tmp.m[ I + i ]; for ( int j = 0; j < mWidth; j++ ) { if ( j != i ) { ret.m[ I + j ] = -tmp.m[ I + j ] / tmp.m[ I + i ]; } for ( k = 0, K = 0; k < mWidth; k++, K += mWidth ) { if ( k != i ) { ret.m[ K + i ] = tmp.m[ K + i ] / tmp.m[ I + i ]; } if ( j != i && k != i ) { ret.m[ K + j ] = tmp.m[ K + j ] - tmp.m[ I + j ] * tmp.m[ K + i ] / tmp.m[ I + i ]; } } } for ( k = 0; k < mWidth*mWidth; k++ ) { tmp.m[k] = ret.m[k]; } } return ret; } void Matrix::operator=( const Matrix& other ) { if ( other.mWidth == mWidth and other.mHeight == mHeight ) { memcpy( m, other.m, sizeof(float) * mWidth * mHeight ); return; } mWidth = other.mWidth; mHeight = other.mHeight; if ( m ) { free( m ); } m = (float*)malloc( sizeof(float) * mWidth * mHeight ); memcpy( m, other.m, sizeof(float) * mWidth * mHeight ); } Matrix operator+( const Matrix& m1, const Matrix& m2 ) { int w = min( m1.width(), m2.width() ); int h = min( m1.height(), m2.height() ); Matrix ret( w, h ); for ( int j = 0, j1 = 0, j2 = 0; j < h; j++, j1 += m1.width(), j2 += m2.width() ) { for ( int i = 0; i < w; i++ ) { ret.m[ j * w + i ] = m1.m[ j * m1.width() + i ] + m2.m[ j * m2.width() + i ]; } } return ret; } Matrix operator-( const Matrix& m1, const Matrix& m2 ) { int w = min( m1.width(), m2.width() ); int h = min( m1.height(), m2.height() ); Matrix ret( w, h ); for ( int j = 0, j1 = 0, j2 = 0; j < h; j++, j1 += m1.width(), j2 += m2.width() ) { for ( int i = 0; i < w; i++ ) { ret.m[ j * w + i ] = m1.m[ j * m1.width() + i ] - m2.m[ j * m2.width() + i ]; // ret.m[ j * w + i ] = m1.m[ j1 + i ] - m2.m[ j2 + i ]; } } return ret; } /* #if ( defined(__ARM_FP) && defined(__ARM_NEON) ) #include <arm_neon.h> void matrix_multiply_4x4_neon( float32_t* C, float32_t* A, float32_t* B ) { float32x4_t A0, A1, A2, A3; float32x4_t B0, B1, B2, B3; float32x4_t C0, C1, C2, C3; A0 = vld1q_f32( A ); A1 = vld1q_f32( A + 4 ); A2 = vld1q_f32( A + 8 ); A3 = vld1q_f32( A + 12 ); B0 = vld1q_f32( B ); B1 = vld1q_f32( B + 4 ); B2 = vld1q_f32( B + 8 ); B3 = vld1q_f32( B + 12 ); C0 = vmovq_n_f32( 0 ); C1 = vmovq_n_f32( 0 ); C2 = vmovq_n_f32( 0 ); C3 = vmovq_n_f32( 0 ); C0 = vfmaq_laneq_f32( C0, A0, B0, 0 ); C0 = vfmaq_laneq_f32( C0, A1, B0, 1 ); C0 = vfmaq_laneq_f32( C0, A2, B0, 2 ); C0 = vfmaq_laneq_f32( C0, A3, B0, 3 ); vst1q_f32(C, C0 ); C1 = vfmaq_laneq_f32( C1, A0, B1, 0 ); C1 = vfmaq_laneq_f32( C1, A1, B1, 1 ); C1 = vfmaq_laneq_f32( C1, A2, B1, 2 ); C1 = vfmaq_laneq_f32( C1, A3, B1, 3 ); vst1q_f32( C + 4, C1 ); C2 = vfmaq_laneq_f32( C2, A0, B2, 0 ); C2 = vfmaq_laneq_f32( C2, A1, B2, 1 ); C2 = vfmaq_laneq_f32( C2, A2, B2, 2 ); C2 = vfmaq_laneq_f32( C2, A3, B2, 3 ); vst1q_f32( C + 8, C2 ); C3 = vfmaq_laneq_f32( C3, A0, B3, 0 ); C3 = vfmaq_laneq_f32( C3, A1, B3, 1 ); C3 = vfmaq_laneq_f32( C3, A2, B3, 2 ); C3 = vfmaq_laneq_f32( C3, A3, B3, 3 ); vst1q_f32( C + 12, C3 ); } #endif */ Matrix operator*( const Matrix& m1, const Matrix& m2 ) { Matrix ret( m2.width(), m1.height() ); memset( ret.data(), 0, sizeof(float) * ret.width() * ret.height() ); /* #if ( defined(__ARM_FP) && defined(__ARM_NEON) ) if ( m1.width() == 4 and m1.height() == 4 and m2.width() == 4 and m2.height() == 4 ) { matrix_multiply_4x4_neon( ret.data(), m1.data(), m2.data() ); return ret; } #endif */ for ( int i = 0; i < ret.height(); i++ ) { for ( int j = 0; j < ret.width(); j++ ) { for ( int n = 0; n < m2.height(); n++ ) { ret.data()[ i * ret.width() + j ] += m1.constData()[ i * m1.width() + n ] * m2.constData()[ n * m2.width() + j ]; } } } return ret; } Vector4f operator*( const Matrix& m, const Vector4f& vec ) { Vector4f ret = Vector4f(); for ( int j = 0, line = 0; j < m.height(); j++, line += m.width() ) { for ( int i = 0; i < m.width(); i++ ) { ret[j] += vec[i] * m.constData()[ j * m.width() + i ]; } } return ret; }
7,583
C++
.cpp
291
23.80756
117
0.561097
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,704
Main.cpp
dridri_bcflight/flight/Main.cpp
/* BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <unistd.h> #include <stdio.h> #include <fcntl.h> // #include <wiringPi.h> #ifdef SYSTEM_NAME_Linux #include <dirent.h> #endif #include <sys/stat.h> #include "Main.h" #include "Config.h" #include "Console.h" #include "Controller.h" #include <SPI.h> #include <I2C.h> #include <IMU.h> #include <Sensor.h> #include <Gyroscope.h> #include <Accelerometer.h> #include <Magnetometer.h> #include <Altimeter.h> #include <GPS.h> #include <Voltmeter.h> #include <CurrentSensor.h> #include <fake_sensors/FakeAccelerometer.h> #include <fake_sensors/FakeGyroscope.h> #include <Servo.h> #include <Stabilizer.h> #include <Frame.h> #include <Camera.h> #include <Microphone.h> #include <HUD.h> #ifdef BUILD_SOCKET #include <Socket.h> #endif #ifdef BUILD_RAWWIFI #include <RawWifi.h> #endif Main* Main::mInstance = nullptr; Main* Main::instance() { return mInstance; } int Main::flight_entry( int ac, char** av ) { new Main(); return 0; } Main::Main() : mReady( false ) , mLPS( 0 ) , mLPSCounter( 0 ) , mPowerThread( nullptr ) , mBlackBox( nullptr ) , mIMU( nullptr ) , mStabilizer( nullptr ) , mController( nullptr ) , mCamera( nullptr ) , mHUD( nullptr ) , mMicrophone( nullptr ) , mRecorder( nullptr ) , mCameraType( "" ) { mInstance = this; #ifdef SYSTEM_NAME_Linux if ( std::getenv("INVOCATION_ID") != nullptr ) { Debug::setColors( false ); } #endif #ifdef BUILD_sensors #ifdef BOARD_generic #pragma message "Adding noisy fake accelerometer and gyroscope" Sensor::AddDevice( new FakeAccelerometer( 3, Vector3f( 2.0f, 2.0f, 2.0f ) ) ); Sensor::AddDevice( new FakeGyroscope( 3, Vector3f( 1.3f, 1.3f, 1.3f ) ) ); #endif #endif mBoard = new Board( this ); Board::InformLoading(); #ifdef BOARD_generic mConfig = new Config( "config.lua", "settings.lua" ); #elif defined( SYSTEM_NAME_Linux ) mConfig = new Config( "/var/flight/config.lua", "/var/flight/settings.lua" ); #endif mConfig->Reload(); Debug::setDebugLevel( static_cast<Debug::Level>( mConfig->Integer( "debug_level", 3 ) ) ); Board::InformLoading(); DetectDevices(); Board::InformLoading(); mConfig->Apply(); Board::InformLoading(); mUsername = mConfig->String( "username" ); #ifdef BUILD_blackbox mBlackBox = mConfig->Object<BlackBox>( "blackbox" ); Board::InformLoading(); #endif #ifdef BUILD_power mPowerThread = new PowerThread( this ); mPowerThread->setFrequency( 20 ); mPowerThread->Start(); mPowerThread->setPriority( 97 ); Board::InformLoading(); #endif mIMU = mConfig->Object<IMU>( "imu" ); mFrame = mConfig->Object<Frame>( "frame" ); mStabilizer = mConfig->Object<Stabilizer>( "stabilizer" ); mController = mConfig->Object<Controller>( "controller" ); mCamera = mConfig->Object<Camera>( "camera" ); mMicrophone = mConfig->Object<Microphone>( "microphone" ); mHUD = mConfig->Object<HUD>( "hud" ); if ( mFrame ) { mFrame->WarmUp(); } if ( mStabilizer and mStabilizer->frame() == nullptr ) { mStabilizer->setFrame( mFrame ); } if ( mCamera ) { mCamera->Start(); } if ( mMicrophone ) { mMicrophone->Setup(); } if ( mController ) { mController->setPriority( 98 ); mController->Start(); } #ifdef BUILD_stabilizer mLoopTime = mConfig->Integer( "stabilizer.loop_time", 2000 ); gDebug() << "Stabilizer frequency : " << ( 1000000 / mLoopTime ) << "Hz"; mTicks = 0; mWaitTicks = 0; mLPSTicks = 0; mLPS = 0; mStabilizerThread = new HookThread< Main >( "stabilizer", this, &Main::StabilizerThreadRun ); mStabilizerThread->setFrequency( 100 ); mTicks = mBoard->GetTicks(); mStabilizerThread->Start(); mStabilizerThread->setPriority( 99, -1, true ); #endif // BUILD_stabilizer #ifdef SYSTEM_NAME_Linux atexit( []() { fDebug(); Thread::StopAll(); }); #endif mReady = true; usleep( 1 * 1000 * 1000 ); #ifdef SYSTEM_NAME_Linux if ( std::getenv("INVOCATION_ID") == nullptr ) { #endif mConsole = new Console( mConfig ); mConsole->Start(); mConsole->setPriority( 2 ); #ifdef SYSTEM_NAME_Linux } #endif Thread::setMainPriority( 1 ); } const bool Main::ready() const { return mReady; } bool Main::StabilizerThreadRun() { #ifdef BUILD_stabilizer uint64_t tick = mBoard->GetTicks(); float dt = ((float)( tick - mTicks ) ) / 1000000.0f; mTicks = mBoard->GetTicks(); if ( abs( dt ) >= 1.0 ) { gWarning() << "Critical : dt too high !! ( " << dt << " )"; // mFrame->Disarm(); return true; } mIMU->Loop( tick, dt ); if ( mIMU->state() == IMU::Running ) { mStabilizer->Update( mIMU, dt ); // mWaitTicks = mBoard->WaitTick( mLoopTime, mWaitTicks, -150 ); } else if ( mIMU->state() == IMU::Off ) { // Nothing to do } else if ( mIMU->state() == IMU::Calibrating or mIMU->state() == IMU::CalibratingAll ) { mStabilizerThread->setFrequency( 1000000 / mLoopTime ); Board::InformLoading(); } else if ( mIMU->state() == IMU::CalibrationDone ) { Board::LoadingDone(); mStabilizerThread->setFrequency( 1000000 / mLoopTime ); } mLPSCounter++; if ( mBoard->GetTicks() >= mLPSTicks + 1000 * 1000 / 10 ) { mLPS = mLPSCounter * 10; mLPSCounter = 0; mLPSTicks = mBoard->GetTicks(); mBlackBox->Enqueue( "Stabilizer:lps", to_string(mLPS) ); } return true; #else // BUILD_stabilizer return false; #endif // BUILD_stabilizer } Main::~Main() { } string Main::getRecordingsList() const { string ret; #ifdef SYSTEM_NAME_Linux DIR* dir; struct dirent* ent; if ( ( dir = opendir( "/var/VIDEO/" ) ) != nullptr ) { while ( ( ent = readdir( dir ) ) != nullptr ) { struct stat st; stat( ( "/var/VIDEO/" + string( ent->d_name ) ).c_str(), &st ); /*if ( mCamera ) { uint32_t width = 0; uint32_t height = 0; uint32_t bpp = 0; uint32_t* data = mCamera->getFileSnapshot( "/var/VIDEO/" + string( ent->d_name ), &width, &height, &bpp ); string b64_data = base64_encode( (uint8_t*)data, width * height * ( bpp / 8 ) ); ret += string( ent->d_name ) + ":" + to_string( st.st_size ) + ":" + to_string( width ) + ":" + to_string( height ) + ":" + to_string( bpp ) + ":" + b64_data + ";"; } else */{ ret += string( ent->d_name ) + ":" + to_string( st.st_size ) + ":::;"; } } closedir( dir ); } #endif if ( ret.length() == 0 or ret == "" ) { ret = ";"; } gDebug() << "Recordings : " << ret; return ret; } uint32_t Main::loopFrequency() const { return mLPS; } Config* Main::config() const { return mConfig; } PowerThread* Main::powerThread() const { return mPowerThread; } Board* Main::board() const { return mBoard; } BlackBox* Main::blackbox() const { return mBlackBox; } IMU* Main::imu() const { return mIMU; } Frame* Main::frame() const { return mFrame; } Stabilizer* Main::stabilizer() const { return mStabilizer; } Controller* Main::controller() const { return mController; } Camera* Main::camera() const { return mCamera; } HUD* Main::hud() const { return mHUD; } Microphone* Main::microphone() const { return mMicrophone; } const string& Main::cameraType() const { return mCameraType; } const string& Main::username() const { return mUsername; } void Main::DetectDevices() { #ifdef BUILD_sensors int countGyro = 0; int countAccel = 0; int countMagn = 0; int countAlti = 0; int countGps = 0; int countVolt = 0; int countCurrent = 0; Sensor::UpdateDevices(); /* list< int > I2Cdevs = I2C::ScanAll(); for ( int dev : I2Cdevs ) { string name = mConfig->String( "sensors_map_i2c[" + to_string(dev) + "]", "" ); // Sensor::RegisterDevice( dev, name, mConfig, "" ); Sensor::RegisterDevice( dev, name ); } // TODO : register SPI/1-wire/.. devices */ for ( Sensor* s : Sensor::Devices() ) { if ( dynamic_cast< Gyroscope* >( s ) != nullptr ) { countGyro++; } if ( dynamic_cast< Accelerometer* >( s ) != nullptr ) { countAccel++; } if ( dynamic_cast< Magnetometer* >( s ) != nullptr ) { countMagn++; } if ( dynamic_cast< Altimeter* >( s ) != nullptr ) { countAlti++; } if ( dynamic_cast< GPS* >( s ) != nullptr ) { countGps++; } if ( dynamic_cast< Voltmeter* >( s ) != nullptr ) { countVolt++; } if ( dynamic_cast< CurrentSensor* >( s ) != nullptr ) { countCurrent++; } } gDebug() << countGyro << " gyroscope(s) found"; for ( Sensor* s : Sensor::Devices() ) { if ( dynamic_cast< Gyroscope* >( s ) != nullptr ) { gDebug() << " " << s->names().front(); } } gDebug() << countAccel << " accelerometer(s) found"; for ( Sensor* s : Sensor::Devices() ) { if ( dynamic_cast< Accelerometer* >( s ) != nullptr ) { gDebug() << " " << s->names().front(); } } gDebug() << countMagn << " magnetometer(s) found"; for ( Sensor* s : Sensor::Devices() ) { if ( dynamic_cast< Magnetometer* >( s ) != nullptr ) { gDebug() << " " << s->names().front(); } } gDebug() << countAlti << " altimeter(s) found"; for ( Sensor* s : Sensor::Devices() ) { if ( dynamic_cast< Altimeter* >( s ) != nullptr ) { gDebug() << " " << s->names().front(); } } gDebug() << countGps << " GPS(es) found"; for ( Sensor* s : Sensor::Devices() ) { if ( dynamic_cast< GPS* >( s ) != nullptr ) { gDebug() << " " << s->names().front(); } } gDebug() << countVolt << " voltmeter(s) found"; for ( Sensor* s : Sensor::Devices() ) { if ( dynamic_cast< Voltmeter* >( s ) != nullptr ) { gDebug() << " " << s->names().front(); } } gDebug() << countCurrent << " current sensor(s) found"; for ( Sensor* s : Sensor::Devices() ) { if ( dynamic_cast< CurrentSensor* >( s ) != nullptr ) { gDebug() << " " << s->names().front(); } } #endif // BUILD_sensors #ifdef BUILD_links int countLink = 0; for ( Link* l : Link::links() ) { countLink++; } gDebug() << countLink << " link(s) found"; for ( Link* l : Link::links() ) { gDebug() << " " << l->name(); } #endif // BUILD_links } static const string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; string Main::base64_encode( const uint8_t* buf, uint32_t size ) { string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while ( size-- ) { char_array_3[i++] = *(buf++); if ( i == 3 ) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for ( i = 0; i < 4; i++ ) { ret += base64_chars[char_array_4[i]]; } i = 0; } } if ( i ) { for(j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for ( j = 0; j < (i + 1); j++ ) { ret += base64_chars[char_array_4[j]]; } while ( i++ < 3 ) { ret += '='; } } return ret; }
11,682
C++
.cpp
438
24.424658
168
0.642595
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,705
PowerThread.cpp
dridri_bcflight/flight/PowerThread.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <unistd.h> #include <algorithm> #include "Main.h" #include "PowerThread.h" #include "Config.h" #include <Sensor.h> #include <Voltmeter.h> #include <CurrentSensor.h> #include <GPIO.h> static float linear_lipo_voltage_level[21] = { 3.27f, // 0% 3.61f, // 5% 3.69f, // 10% 3.71f, // 15% 3.73f, // 20% 3.75f, // 25% 3.77f, // 30% 3.79f, // 35% 3.80f, // 40% 3.82f, // 45% 3.84f, // 50% 3.85f, // 55% 3.87f, // 60% 3.91f, // 65% 3.95f, // 70% 3.98f, // 75% 4.02f, // 80% 4.08f, // 85% 4.11f, // 90% 4.15f, // 95% 4.20f // 100% }; PowerThread::PowerThread( Main* main ) : Thread( "power" ) , mMain( main ) , mLowVoltageValue( 9.9 ) , mLowVoltageBuzzerPin( -1 ) , mLowVoltageTick( 0 ) , mLowVoltagePatternCase( 0 ) , mSaveTicks( Board::GetTicks() ) , mTicks( Board::GetTicks() ) , mCellsCount( 0 ) , mVBat( 0.0f ) , mCurrentTotal( 0.0f ) , mCurrentDraw( 0.0f ) , mBatteryLevel( 0.0f ) , mBatteryCapacity( 2500.0f ) , mVoltageSensor{ NONE, nullptr, 0, 0, 0 } , mCurrentSensor{ NONE, nullptr, 0, 0, 0 } { mBatteryCapacity = main->config()->Integer( "battery.capacity", 1800.0f ); if ( 1 ) { mVoltageSensor.sensor = main->config()->Object<Sensor>( "battery.voltage.sensor" ); mVoltageSensor.channel = main->config()->Integer( "battery.voltage.channel" ); mVoltageSensor.multiplier = main->config()->Number( "battery.voltage.multiplier", 1.0f ); mVoltageSensor.shift = main->config()->Number( "battery.voltage.shift", 0.0f ); } /* if ( false ) { string sensorName = main->config()->String( "battery.current.sensor_type" ); for ( auto it : Sensor::Voltmeters() ) { list< string > names = it->names(); if ( find( names.begin(), names.end(), sensorName ) != names.end() ) { mCurrentSensor.type = VOLTAGE; mCurrentSensor.sensor = it; break; } } for ( auto it : Sensor::CurrentSensors() ) { list< string > names = it->names(); if ( find( names.begin(), names.end(), sensorName ) != names.end() ) { mCurrentSensor.type = CURRENT; mCurrentSensor.sensor = it; break; } } if ( mCurrentSensor.sensor == nullptr ) { gDebug() << "FATAL ERROR : Unsupported sensor ( " << sensorName << " ) for battery current !"; } / if ( sensorType == "Voltmeter" ) { mCurrentSensor.type = VOLTAGE; mCurrentSensor.sensor = Sensor::voltmeter( main->config()->String( "battery.current.device" ) ); } else if ( sensorType == "CurrentSensor" ) { mCurrentSensor.type = CURRENT; mCurrentSensor.sensor = Sensor::currentSensor( main->config()->String( "battery.current.device" ) ); } else { gDebug() << "WARNING : Unsupported sensor type ( " << sensorType << " ) for battery current !"; } / mCurrentSensor.channel = main->config()->Integer( "battery.current.channel" ); mCurrentSensor.shift = main->config()->Number( "battery.current.shift" ); mCurrentSensor.multiplier = main->config()->Number( "battery.current.multiplier" ); } */ mLowVoltageValue = main->config()->Number( "battery.low_voltage", 3.7f ); /* string low_voltage_trigger = main->config()->String( "battery.low_voltage_trigger.type" ); if ( low_voltage_trigger == "Buzzer" ) { mLowVoltageBuzzerPin = main->config()->Integer( "battery.low_voltage_trigger.pin", -1 ); if ( mLowVoltageBuzzerPin > 0 ) { GPIO::setMode( mLowVoltageBuzzerPin, GPIO::Output ); GPIO::Write( mLowVoltageBuzzerPin, 0 ); } vector<int> array = main->config()->IntegerArray( "battery.low_voltage_trigger.pattern" ); for ( uint32_t i = 0; i < array.size(); i++ ) { mLowVoltageBuzzerPattern.emplace_back( array[i] * 1000 ); } } */ mLastVBat = atof( Board::LoadRegister( "VBat" ).c_str() ); mCurrentTotal = atof( Board::LoadRegister( "CurrentTotal" ).c_str() ); mCellsCount = atof( Board::LoadRegister( "CellsCount" ).c_str() ); } PowerThread::~PowerThread() { } float PowerThread::VBat() const { return mVBat; } float PowerThread::CurrentTotal() const { return mCurrentTotal; } float PowerThread::CurrentDraw() const { return mCurrentDraw; } float PowerThread::BatteryLevel() const { return mBatteryLevel; } void PowerThread::ResetFullBattery( uint32_t capacity_mah ) { #ifdef SYSTEM_NAME_Linux mCapacityMutex.lock(); #endif mCellsCount = 0; mCurrentTotal = 0.0f; if ( capacity_mah != 0 ) { // mBatteryCapacity = (float)capacity_mah; } #ifdef SYSTEM_NAME_Linux mCapacityMutex.unlock(); #endif } bool PowerThread::run() { float dt = (float)( Board::GetTicks() - mTicks ) / 1000000.0f; mTicks = Board::GetTicks(); if ( abs( dt ) > 2.0 ) { gDebug() << "Critical : dt too high !! ( " << dt << " )"; return true; } float volt = 0.0f; float current = 0.0f; try { if ( mVoltageSensor.sensor ) { Voltmeter* meter = dynamic_cast< Voltmeter* >( mVoltageSensor.sensor ); if ( meter ) { volt = meter->Read( mVoltageSensor.channel ); volt = ( volt + mVoltageSensor.shift ) * mVoltageSensor.multiplier; } } /* if ( mCurrentSensor.sensor ) { if ( mCurrentSensor.type == VOLTAGE ) { current = static_cast< Voltmeter* >( mCurrentSensor.sensor )->Read( mCurrentSensor.channel ); } else if ( mCurrentSensor.type == CURRENT ) { current = static_cast< CurrentSensor* >( mCurrentSensor.sensor )->Read( mCurrentSensor.channel ); } current = ( current + mCurrentSensor.shift ) * mCurrentSensor.multiplier; } */ } catch ( const std::exception& e ) { return true; } if ( mVBat == 0.0f ) { mVBat = volt; } mVBat = mVBat * 0.9f + volt * 0.1f; // Smooth over time mCurrentDraw = current;// / 3600.0f; #ifdef SYSTEM_NAME_Linux mCapacityMutex.lock(); #endif if ( mCellsCount == 0 ) { if ( mVBat >= 3.365f * 6.0f ) { mCellsCount = 6; } else if ( mVBat >= 3.365f * 5.0f ) { mCellsCount = 5; } else if ( mVBat >= 3.365f * 4.0f ) { mCellsCount = 4; } else if ( mVBat >= 3.365f * 3.0f ) { mCellsCount = 3; } else if ( mVBat >= 3.365f * 2.0f ) { mCellsCount = 2; } else if ( mVBat >= 3.365f * 1.0f ) { mCellsCount = 1; } else { mCellsCount = 6; gDebug() << "Critical : DANGEROUS BATTERY VOLTAGE ! (" << mVBat << "V)"; } } #ifdef SYSTEM_NAME_Linux mCapacityMutex.unlock(); #endif if ( mLowVoltageBuzzerPin > 0 ) { if ( mVBat <= mLowVoltageValue * (float)mCellsCount ) { if ( mTicks - mLowVoltageTick >= mLowVoltageBuzzerPattern[mLowVoltagePatternCase] ) { mLowVoltagePatternCase = ( mLowVoltagePatternCase + 1 ) % mLowVoltageBuzzerPattern.size(); mLowVoltageTick = mTicks; } GPIO::Write( mLowVoltageBuzzerPin, ( mLowVoltagePatternCase % 2 ) == 0 ); } else { GPIO::Write( mLowVoltageBuzzerPin, 0 ); } } #ifdef SYSTEM_NAME_Linux mCapacityMutex.lock(); #endif mCurrentTotal += current * dt / 3600.0f; mBatteryLevel = 1.0f - ( mCurrentTotal * 1000.0f ) / mBatteryCapacity; if ( mCurrentSensor.sensor == nullptr ) { // No current sensor float vcell = mVBat / (float)mCellsCount; uint32_t lvlCount = sizeof(linear_lipo_voltage_level)/sizeof(float); uint32_t lvl = 0; for ( lvl = 0; lvl < lvlCount - 1 and vcell > linear_lipo_voltage_level[lvl + 1]; lvl++ ); uint32_t lvl_next = std::min( lvl + 1U, lvlCount ); float flvl0 = linear_lipo_voltage_level[lvl]; float flvl1 = linear_lipo_voltage_level[lvl_next]; float mix = ( vcell - flvl0 ) / ( flvl1 - flvl0 ); mBatteryLevel = ((float)lvl + mix) / (float)(lvlCount - 1); } // mBatteryLevel = max( 0.0f, min( 1.0f, mBatteryLevel ) ); mBatteryLevel = min( 1.0f, mBatteryLevel ); if ( Board::GetTicks() - mSaveTicks >= 5 * 1000 * 1000 ) { Board::SaveRegister( "VBat", to_string( mVBat ) ); Board::SaveRegister( "CurrentTotal", to_string( mCurrentTotal ) ); Board::SaveRegister( "BatteryCapacity", to_string( mBatteryCapacity ) ); mSaveTicks = Board::GetTicks(); } #ifdef SYSTEM_NAME_Linux mCapacityMutex.unlock(); #endif return true; }
8,560
C++
.cpp
265
29.758491
103
0.670376
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,706
BlackBox.cpp
dridri_bcflight/flight/BlackBox.cpp
#include <unistd.h> #ifdef SYSTEM_NAME_Linux #include <dirent.h> #endif #include <Board.h> #include <Debug.h> #include "BlackBox.h" BlackBox::BlackBox() : Thread( "BlackBox" ) , mID( 0 ) , mFile( nullptr ) { #ifdef SYSTEM_NAME_Linux char filename[256]; DIR* dir; struct dirent* ent; if ( ( dir = opendir( "/var/BLACKBOX" ) ) != nullptr ) { while ( ( ent = readdir( dir ) ) != nullptr ) { string file = string( ent->d_name ); uint32_t id = atoi( file.substr( file.rfind( "_" ) + 1 ).c_str() ); if ( id >= mID ) { mID = id + 1; } } closedir( dir ); sprintf( filename, "/var/BLACKBOX/blackbox_%06u.csv", mID ); mFile = fopen( filename, "wb" ); gDebug() << "mFile : " << mFile << ", filename : " << filename; } #elif defined( SYSTEM_NAME_Generic ) // TODO #endif if ( mFile == nullptr ) { Board::defectivePeripherals()["BlackBox"] = true; Stop(); return; } setFrequency( 100 ); Start(); } BlackBox::~BlackBox() { } void BlackBox::Start( bool enabled ) { if ( enabled and not Thread::running() ) { Thread::Start(); } else { Thread::Stop(); } } const uint32_t BlackBox::id() const { if ( this == nullptr or not Thread::running() ) { return 0; } return mID; } void BlackBox::Enqueue( const string& data, const string& value ) { if ( this == nullptr or not Thread::running() ) { return; } #ifdef SYSTEM_NAME_Linux uint64_t time = Board::GetTicks(); string str = to_string(time) + "," + data + "," + value; mQueueMutex.lock(); mQueue.emplace_back( str ); mQueueMutex.unlock(); #endif } #define CHECK_ENABLED() \ if ( this == nullptr or not Thread::running() ) { \ return; \ } template<> void BlackBox::Enqueue( const string& data, const Vector<float, 1>& v ) { CHECK_ENABLED(); char stmp[64]; sprintf( stmp, "\"%.4f\"", v.x ); } template<> void BlackBox::Enqueue( const string& data, const Vector<float, 2>& v ) { CHECK_ENABLED(); char stmp[64]; sprintf( stmp, "\"%.4f,%.4f\"", v.x, v.y ); } template<> void BlackBox::Enqueue( const string& data, const Vector<float, 3>& v ) { CHECK_ENABLED(); char stmp[64]; sprintf( stmp, "\"%.4f,%.4f,%.4f\"", v.x, v.y, v.z ); } template<> void BlackBox::Enqueue( const string& data, const Vector<float, 4>& v ) { CHECK_ENABLED(); char stmp[64]; sprintf( stmp, "\"%.4f,%.4f,%.4f,%.4f\"", v.x, v.y, v.z, v.w ); } template<> void BlackBox::Enqueue( const string& data, const Vector<int, 1>& v ) { CHECK_ENABLED(); char stmp[64]; sprintf( stmp, "\"%d\"", v.x ); } template<> void BlackBox::Enqueue( const string& data, const Vector<int, 2>& v ) { CHECK_ENABLED(); char stmp[64]; sprintf( stmp, "\"%d,%d\"", v.x, v.y ); } template<> void BlackBox::Enqueue( const string& data, const Vector<int, 3>& v ) { CHECK_ENABLED(); char stmp[64]; sprintf( stmp, "\"%d,%d,%d\"", v.x, v.y, v.z ); } template<> void BlackBox::Enqueue( const string& data, const Vector<int, 4>& v ) { CHECK_ENABLED(); char stmp[64]; sprintf( stmp, "\"%d,%d,%d,%d\"", v.x, v.y, v.z, v.w ); } void BlackBox::Enqueue( const string* data, const string* values, int n ) { if ( this == nullptr or not Thread::running() ) { return; } #ifdef SYSTEM_NAME_Linux uint64_t time = Board::GetTicks(); mQueueMutex.lock(); for ( int i = 0; i < n; i++ ) { string str = to_string(time) + "," + data[i] + "," + values[i]; mQueue.emplace_back( str ); } mQueueMutex.unlock(); #endif } void BlackBox::Enqueue( const char* data[], const char* values[], int n ) { if ( this == nullptr or not Thread::running() ) { return; } #ifdef SYSTEM_NAME_Linux uint64_t time = Board::GetTicks(); char str[2048] = ""; mQueueMutex.lock(); for ( int i = 0; i < n; i++ ) { sprintf( str, "%llu,%s,%s", time, data[i], values[i] ); mQueue.emplace_back( string(str) ); } mQueueMutex.unlock(); #endif } bool BlackBox::run() { // exit(0); // return false; #ifdef SYSTEM_NAME_Linux string data; mQueueMutex.lock(); while ( mQueue.size() > 0 ) { string str = mQueue.front(); mQueue.pop_front(); mQueueMutex.unlock(); data += str + "\n"; mQueueMutex.lock(); } mQueueMutex.unlock(); if ( data.length() > 0 ) { if ( fwrite( data.c_str(), data.length(), 1, mFile ) != data.length() ) { if ( errno == ENOSPC ) { Board::setDiskFull(); } } if ( fflush( mFile ) < 0 or fsync( fileno( mFile ) ) < 0 ) { if ( errno == ENOSPC ) { Board::setDiskFull(); } } } #endif return true; }
4,430
C++
.cpp
184
21.896739
82
0.625952
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,707
EKF.cpp
dridri_bcflight/flight/stabilizer/EKF.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <Debug.h> #include "EKF.h" EKF::EKF( uint32_t n_inputs, uint32_t n_outputs ) : mInputsCount( n_inputs ) , mOutputsCount( n_outputs ) , mQ( Matrix( mOutputsCount, mOutputsCount ) ) , mR( Matrix( mInputsCount, mInputsCount ) ) , mC( Matrix( mOutputsCount, mInputsCount ) ) , mSigma( Matrix( mOutputsCount, mOutputsCount ) ) , mInput( Matrix( 1, mInputsCount ) ) , mState( Matrix( 1, mOutputsCount ) ) { mC.Clear(); mSigma.Clear(); mInput.Clear(); mState.Clear(); } EKF::~EKF() { } void EKF::setInputFilter( uint32_t row, float filter ) { mR.m[row * mR.width() + row] = filter; } void EKF::setOutputFilter( uint32_t row, float filter ) { mQ.m[row * mQ.width() + row] = filter; } void EKF::setSelector( uint32_t input_row, uint32_t output_row, float selector ) { mC.m[input_row * mC.width() + output_row] = selector; } Vector4f EKF::state( uint32_t offset ) const { Vector4f ret; for ( uint32_t i = 0; i < 4 and offset + i < (uint32_t)mState.height(); i++ ) { ret[i] = mState.constData()[offset + i]; } return ret; } void EKF::UpdateInput( uint32_t row, float input ) { mInput.m[row] = input; } void EKF::Process( float dt ) { // Predict mSigma = mSigma + mQ; // Update Matrix Gk = mSigma * mC.Transpose() * ( mC * mSigma * mC.Transpose() + mR ).Inverse(); mSigma = ( Matrix( mOutputsCount, mOutputsCount ) - Gk * mC ) * mSigma; mState = mState + ( Gk * ( mInput - mC * mState ) ); } void EKF::DumpInput() { printf( "EKF Input [%d, %d] = {\n", mInput.width(), mInput.height() ); for ( int j = 0; j < mInput.height(); j++ ) { printf( "\t" ); for ( int i = 0; i < mInput.width(); i++ ) { printf( "%.4f ", mInput.m[ j * mInput.width() + i ] ); } printf( "\n" ); } printf( "}\n" ); }
2,463
C++
.cpp
82
28.036585
87
0.67161
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,708
Stabilizer.cpp
dridri_bcflight/flight/stabilizer/Stabilizer.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <unistd.h> #include <math.h> #include <Debug.h> #include <Main.h> #include <Board.h> #include <IMU.h> #include <Controller.h> #include "Config.h" #include "Stabilizer.h" Stabilizer::Stabilizer() : mMain( Main::instance() ) , mFrame( nullptr ) , mMode( Rate ) , mAltitudeHold( false ) , mRateRollPID( PID<float>() ) , mRatePitchPID( PID<float>() ) , mRateYawPID( PID<float>() ) , mRollHorizonPID( PID<float>() ) , mPitchHorizonPID( PID<float>() ) , mAltitudePID( PID<float>() ) , mAltitudeControl( 0.0f ) , mDerivativeFilter( nullptr ) , mTPAMultiplier( 1.0f ) , mTPAThreshold( 1.0f ) , mAntiGravityGain( 1.0f ) , mAntiGravityThreshold( 0.0f ) , mAntiGravityDecay( 10.0f ) , mAntigravityThrustAccum( 0.0f ) , mArmed( false ) , mFilteredRPYDerivative( Vector3f() ) , mLockState( 0 ) , mHorizonMultiplier( Vector3f( 15.0f, 15.0f, 1.0f ) ) , mHorizonOffset( Vector3f() ) , mHorizonMaxRate( Vector3f( 300.0f, 300.0f, 300.0f ) ) { fDebug(this); mAltitudePID.setP( 0.001 ); mAltitudePID.setI( 0.010 ); mAltitudePID.setDeadBand( 0.05f ); } Stabilizer::~Stabilizer() { } Frame* Stabilizer::frame() const { return mFrame; } void Stabilizer::setFrame( Frame* frame ) { mFrame = frame; } void Stabilizer::setRollP( float p ) { mRateRollPID.setP( p ); Board::SaveRegister( "PID:Roll:P", to_string( p ) ); } void Stabilizer::setRollI( float i ) { mRateRollPID.setI( i ); Board::SaveRegister( "PID:Roll:I", to_string( i ) ); } void Stabilizer::setRollD( float d ) { mRateRollPID.setD( d ); Board::SaveRegister( "PID:Roll:D", to_string( d ) ); } Vector3f Stabilizer::getRollPID() const { return mRateRollPID.getPID(); } void Stabilizer::setPitchP( float p ) { mRatePitchPID.setP( p ); Board::SaveRegister( "PID:Pitch:P", to_string( p ) ); } void Stabilizer::setPitchI( float i ) { mRatePitchPID.setI( i ); Board::SaveRegister( "PID:Pitch:I", to_string( i ) ); } void Stabilizer::setPitchD( float d ) { mRatePitchPID.setD( d ); Board::SaveRegister( "PID:Pitch:D", to_string( d ) ); } Vector3f Stabilizer::getPitchPID() const { return mRatePitchPID.getPID(); } void Stabilizer::setYawP( float p ) { mRateYawPID.setP( p ); Board::SaveRegister( "PID:Yaw:P", to_string( p ) ); } void Stabilizer::setYawI( float i ) { mRateYawPID.setI( i ); Board::SaveRegister( "PID:Yaw:I", to_string( i ) ); } void Stabilizer::setYawD( float d ) { mRateYawPID.setD( d ); Board::SaveRegister( "PID:Yaw:D", to_string( d ) ); } Vector3f Stabilizer::getYawPID() const { return mRateYawPID.getPID(); } Vector3f Stabilizer::lastPIDOutput() const { return Vector3f( mRateRollPID.state(), mRatePitchPID.state(), mRateYawPID.state() ); } void Stabilizer::setHorizonOffset( const Vector3f& v ) { mHorizonOffset = v; } Vector3f Stabilizer::horizonOffset() const { return mHorizonOffset; } void Stabilizer::setMode( uint32_t mode ) { mMode = (Mode)mode; } uint32_t Stabilizer::mode() const { return (uint32_t)mMode; } void Stabilizer::setAltitudeHold( bool enabled ) { mAltitudeHold = enabled; } bool Stabilizer::altitudeHold() const { return mAltitudeHold; } void Stabilizer::Arm() { mArmed = true; } void Stabilizer::Disarm() { mArmed = false; } bool Stabilizer::armed() const { return mArmed; } float Stabilizer::thrust() const { return mThrust; } const Vector3f& Stabilizer::RPY() const { return mRPY; } const Vector3f& Stabilizer::filteredRPYDerivative() const { return mFilteredRPYDerivative; } void Stabilizer::Reset( const float& yaw ) { mRateRollPID.Reset(); mRatePitchPID.Reset(); mRateYawPID.Reset(); mRollHorizonPID.Reset(); mPitchHorizonPID.Reset(); mRPY.x = 0.0f; mRPY.y = 0.0f; mRPY.z = 0.0f; mThrust = 0.0f; } void Stabilizer::setRoll( float value ) { mRPY.x = value; } void Stabilizer::setPitch( float value ) { mRPY.y = value; } void Stabilizer::setYaw( float value ) { mRPY.z = value; } void Stabilizer::setThrust( float value ) { mPreviousThrust = mThrust; mThrust = value; } void Stabilizer::Update( IMU* imu, float dt ) { Vector3f rate_control = Vector3f(); if ( mLockState >= 1 ) { mLockState = 2; return; } Vector3f rates = imu->rate(); if ( mDerivativeFilter ) { mFilteredRPYDerivative = mDerivativeFilter->filter( rates, dt ); } else { mFilteredRPYDerivative = rates; } if ( not mArmed ) { return; } // We didn't take off yet (or really close to ground just after take-off), so we bypass stabilization, and just return if ( mFrame->airMode() == false and mThrust <= 0.15f ) { mFrame->Stabilize( Vector3f( 0.0f, 0.0f, 0.0f ), mThrust ); return; } Vector3f rollPIDMultiplier = Vector3f( 1.0f, 1.0f, 1.0f ); Vector3f pitchPIDMultiplier = Vector3f( 1.0f, 1.0f, 1.0f ); Vector3f yawPIDMultiplier = Vector3f( 1.0f, 1.0f, 1.0f ); // Throttle PID Attenuation (TPA) : reduce PID gains when throttle is high // y=min( 1, 1 − ( (x−t) / (1−t) ) * m ) // See https://www.desmos.com/calculator/wi8qeuzct6 if ( mTPAThreshold > 0.0f and mTPAThreshold < 1.0f ) { float tpa = ( ( mThrust - mTPAThreshold ) / ( 1.0f - mTPAThreshold ) ) * mTPAMultiplier; Vector3f tpaPID = Vector3f( 1.0f - 0.25f * std::max( 0.0f, std::min( 1.0f, tpa ) ), 1.0f - 0.25f * std::max( 0.0f, std::min( 1.0f, tpa ) ), 1.0f - std::max( 0.0f, std::min( 1.0f, tpa ) ) ); rollPIDMultiplier = rollPIDMultiplier * tpaPID; pitchPIDMultiplier = pitchPIDMultiplier * tpaPID; yawPIDMultiplier = yawPIDMultiplier * tpaPID; } // Anti-gravity if ( mAntiGravityThreshold > 0.0f ) { float delta = std::abs( mThrust - mPreviousThrust ) / dt; mAntigravityThrustAccum = std::min( 1.0f, mAntigravityThrustAccum * ( 1.0f - dt * mAntiGravityDecay ) + delta * dt ); float ag = 1.0f + (mAntiGravityGain - 1.0f) * std::max(0.0f, std::min( 1.0f, ( mAntigravityThrustAccum - mAntiGravityThreshold ) / (1.0f - mAntiGravityThreshold) ) ); rollPIDMultiplier.y *= ag; pitchPIDMultiplier.y *= ag; yawPIDMultiplier.y *= ag; if ( ag > 1.0f ) { gTrace() << "AG: " << ag << " | " << mAntigravityThrustAccum << " | " << delta; } } switch ( mMode ) { case Stabilize : { Vector3f drone_state = imu->RPY(); Vector3f control_angles = mRPY; control_angles.x = mHorizonMultiplier.x * min( max( control_angles.x, -1.0f ), 1.0f ) + mHorizonOffset.x; control_angles.y = mHorizonMultiplier.y * min( max( control_angles.y, -1.0f ), 1.0f ) + mHorizonOffset.y; // TODO : when user-input is 0, set control_angles by using imu->velocity().xy to compensate position drifting, if enabled mRollHorizonPID.Process( control_angles.x, drone_state.x, dt ); mPitchHorizonPID.Process( control_angles.y, drone_state.y, dt ); rate_control.x = mRollHorizonPID.state(); rate_control.y = mPitchHorizonPID.state(); rate_control.x = max( -mHorizonMaxRate.x, min( mHorizonMaxRate.x, rate_control.x ) ); rate_control.y = max( -mHorizonMaxRate.y, min( mHorizonMaxRate.y, rate_control.y ) ); rate_control.z = mRPY.z * mRateFactor; // TEST : Bypass heading for now break; } case ReturnToHome : case Follow : case Rate : default : { rate_control = mRPY * mRateFactor; break; } } float deltaR = rate_control.x - rates.x; float deltaP = rate_control.y - rates.y; float deltaY = rate_control.z - rates.z; float deltaRd = rate_control.x - mFilteredRPYDerivative.x; float deltaPd = rate_control.y - mFilteredRPYDerivative.y; float deltaYd = rate_control.z - mFilteredRPYDerivative.z; mRateRollPID.Process( deltaR, deltaR, deltaRd, dt, rollPIDMultiplier ); mRatePitchPID.Process( deltaP, deltaP, deltaPd, dt, pitchPIDMultiplier ); mRateYawPID.Process( deltaY, deltaY, deltaYd, dt, yawPIDMultiplier ); float thrust = mThrust; /* if ( mAltitudeHold ) { thrust = thrust * 2.0f - 1.0f; if ( abs( thrust ) < 0.1f ) { thrust = 0.0f; } else if ( thrust > 0.0f ) { thrust = ( thrust - 0.1f ) * ( 1.0f / 0.9f ); } else if ( thrust < 0.0f ) { thrust = ( thrust + 0.1f ) * ( 1.0f / 0.9f ); } thrust *= 0.01f; // Reduce to 1m/s mAltitudeControl += thrust; mAltitudePID.Process( mAltitudeControl, imu->altitude(), dt ); thrust = mAltitudePID.state(); } */ Vector3f ratePID( mRateRollPID.state(), mRatePitchPID.state(), mRateYawPID.state() ); Main::instance()->blackbox()->Enqueue( "Stabilizer:ratePID", ratePID ); if ( mFrame->Stabilize( ratePID, thrust ) == false ) { gDebug() << "stab error"; Reset( imu->RPY().z ); } } void Stabilizer::MotorTest(uint32_t id) { mLockState = 1; while ( mLockState != 2 ) { usleep( 1000 * 10 ); } mFrame->MotorTest(id); mLockState = 0; } void Stabilizer::CalibrateESCs() { if ( mMain->imu()->state() != IMU::Off ) { mLockState = 1; while ( mLockState != 2 ) { usleep( 1000 * 10 ); } } mFrame->CalibrateESCs(); mLockState = 0; }
9,506
C++
.cpp
332
26.436747
168
0.700044
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,709
IMU.cpp
dridri_bcflight/flight/stabilizer/IMU.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <unistd.h> #include <cmath> #include <Debug.h> #include "IMU.h" #include "Config.h" #include "Stabilizer.h" #include "Accelerometer.h" #include "Gyroscope.h" #include "Magnetometer.h" #include "Altimeter.h" #include "GPS.h" #include "MahonyAHRS.h" #include <Controller.h> IMU::IMU() : mMain( Main::instance() ) , mSensorsUpdateSlow( 0 ) , mPositionUpdate( false ) , mRatesFilter( nullptr ) , mAccelerometerFilter( nullptr ) , mState( Off ) , mAcceleration( Vector3f() ) , mGyroscope( Vector3f() ) , mMagnetometer( Vector3f() ) , mGPSLocation( Vector2f() ) , mGPSSpeed( 0.0f ) , mGPSAltitude( 0.0f ) , mAltitudeOffset( 0.0f ) , mProximity( 0.0f ) , mRPY( Vector3f() ) , mdRPY( Vector3f() ) , mRate( Vector3f() ) , mRPYOffset( Vector3f() ) , mCalibrationStep( 0 ) , mCalibrationTimer( 0 ) , mRPYAccum( Vector4f() ) , mGravity( Vector3f() ) // , mRates( EKF( 3, 3 ) ) // , mAccelerationSmoother( EKF( 3, 3 ) ) , mAttitude( nullptr ) , mPosition( EKF( 3, 3 ) ) , mVelocity( EKF( 3, 3 ) ) , mLastAccelAttitude( Vector4f() ) , mLastAcceleration( Vector3f() ) , mGyroscopeErrorCounter( 0 ) { /** mPosition matrix : * - Inputs : * - XY velocity integrated over time 0 1 * - altitude (either absolute or proximity) 2 * - Outputs : * - smoothed position 0 1 * - smoothed altitude 2 **/ mPosition.setSelector( 0, 0, 1.0f ); mPosition.setSelector( 1, 1, 1.0f ); mPosition.setSelector( 2, 2, 1.0f ); /** mVelocity matrix : * - Inputs : * - smoothed linear acceleration 0 1 2 * - Outputs : * - smoothed linear velocity 0 1 2 **/ mVelocity.setSelector( 0, 0, 1.0f ); mVelocity.setSelector( 1, 1, 1.0f ); mVelocity.setSelector( 2, 2, 1.0f ); mMain->blackbox()->Enqueue( "IMU:state", "Off" ); } IMU::~IMU() { } const IMU::State& IMU::state() const { return mState; } const Vector3f IMU::RPY() const { return mRPY; } const Vector3f IMU::dRPY() const { return mdRPY; } const Vector3f IMU::rate() const { return mRate; } const float IMU::altitude() const { return mPosition.state( 0 ).z; } const Vector3f IMU::velocity() const { return mVelocity.state( 0 ); } const Vector3f IMU::position() const { return mPosition.state( 0 ); } const Vector3f IMU::acceleration() const { return mAccelerationSmoothed; } const Vector3f IMU::gyroscope() const { return mGyroscope; } const Vector3f IMU::magnetometer() const { return mMagnetometer; } const Vector3f IMU::gpsLocation() const { return Vector3f( mGPSLocation.x, mGPSLocation.y, mGPSAltitude ); } const float IMU::gpsSpeed() const { return mGPSSpeed; } const uint32_t IMU::gpsSatellitesSeen() const { return mGPSSatellitesSeen; } const uint32_t IMU::gpsSatellitesUsed() const { return mGPSSatellitesUsed; } void IMU::setPositionFilterInput( const Vector3f& v ) { fDebug(v.x, v.y, v.z); mPosition.setInputFilter( 0, v.x ); mPosition.setInputFilter( 1, v.y ); mPosition.setInputFilter( 2, v.z ); } void IMU::setPositionFilterOutput( const Vector3f& v ) { fDebug(v.x, v.y, v.z); mPosition.setOutputFilter( 0, v.x ); mPosition.setOutputFilter( 1, v.y ); mPosition.setOutputFilter( 2, v.z ); } void IMU::registerConsumer( const std::function<void(uint64_t, const Vector3f&, const Vector3f&)>& f ) { mConsumers.push_back( f ); } void IMU::Loop( uint64_t tick, float dt ) { // fDebug( dt, mState ); if ( mState == Running ) { UpdateSensors( tick, ( mMain->stabilizer()->mode() == Stabilizer::Rate ) ); UpdateAttitude( dt ); if ( mPositionUpdate ) { #ifdef SYSTEM_NAME_Linux mPositionUpdateMutex.lock(); #endif mPositionUpdate = false; #ifdef SYSTEM_NAME_Linux mPositionUpdateMutex.unlock(); #endif UpdatePosition( dt ); } } else if ( mState == Off ) { // Just update GPS UpdateGPS(); // Nothing more to do } else if ( mState == Calibrating or mState == CalibratingAll ) { Calibrate( dt, ( mState == CalibratingAll ) ); } else if ( mState == CalibrationDone ) { mState = Running; mMain->blackbox()->Enqueue( "IMU:state", "Running" ); } } void IMU::Calibrate( float dt, bool all ) { switch ( mCalibrationStep ) { case 0 : { gDebug() << "Calibrating " << ( all ? "all" : "partial" ) << " sensors"; mMain->blackbox()->Enqueue( "IMU:state", "Calibrating" ); mCalibrationStep++; mCalibrationTimer = Board::GetTicks(); break; } case 1 : { for ( auto dev : Sensor::Devices() ) { if ( all or dynamic_cast< Gyroscope* >( dev ) != nullptr or dynamic_cast< Altimeter* >( dev ) != nullptr ) { dev->Calibrate( dt, false ); } } if ( Board::GetTicks() - mCalibrationTimer >= 1000 * 1000 * 2 ) { mCalibrationStep++; } break; } case 2 : { gDebug() << "Calibration last pass"; for ( auto dev : Sensor::Devices() ) { if ( all or dynamic_cast< Gyroscope* >( dev ) != nullptr or dynamic_cast< Altimeter* >( dev ) != nullptr ) { dev->Calibrate( dt, true ); } } mCalibrationStep++; if ( all == false ) { mCalibrationStep = 5; } break; } case 3 : { gDebug() << "Calibrating gravity"; mGravity = Vector3f(); mCalibrationStep++; mCalibrationTimer = Board::GetTicks(); break; } case 4 : { UpdateSensors( dt ); mGravity = ( mGravity * 0.5f ) + ( mAcceleration * 0.5f ); if ( Board::GetTicks() - mCalibrationTimer >= 1000 * 1000 * 1 ) { mCalibrationStep++; } break; } case 5 : { gDebug() << "Calibration almost done..."; mState = CalibrationDone; mMain->blackbox()->Enqueue( "IMU:state", "CalibrationDone" ); mAcceleration = Vector3f(); mGyroscope = Vector3f(); mMagnetometer = Vector3f(); mRPY = Vector3f(); mdRPY = Vector3f(); mRate = Vector3f(); gDebug() << "Calibration done !"; mMain->frame()->Disarm(); // Activate motors break; } default: break; } } void IMU::Recalibrate() { bool cal_all = false; for ( Accelerometer* dev : Sensor::Accelerometers() ) { if ( not dev->calibrated() ) { cal_all = true; break; } } if ( cal_all ) { gDebug() << "Full recalibration needed..."; RecalibrateAll(); return; } mCalibrationStep = 0; mState = Calibrating; mRPYOffset = Vector3f(); gDebug() << "Calibrating gyroscope..."; } void IMU::RecalibrateAll() { mCalibrationStep = 0; mState = CalibratingAll; mRPYOffset = Vector3f(); gDebug() << "Calibrating all sensors..."; } void IMU::ResetRPY() { mAcceleration = Vector3f(); mRPY = Vector3f(); } void IMU::ResetYaw() { mRPY.z = 0.0f; /* mVirtualNorth = Vector3f(); while ( mVirtualNorth.x == 0.0f and mVirtualNorth.y == 0.0f and mVirtualNorth.z == 0.0f ) { usleep( 1000 ); } */ } void IMU::UpdateSensors( uint64_t tick, bool gyro_only ) { Vector4f total_accel; Vector4f total_gyro; Vector4f total_magn; Vector2f total_alti; Vector2f total_proxi; Vector3f total_lat_lon; Vector3f vtmp; // float ftmp; // char stmp[64]; for ( Gyroscope* dev : mGyroscopes ) { vtmp.x = vtmp.y = vtmp.z = 0.0f; int ret = dev->Read( &vtmp ); if ( ret > 0 ) { total_gyro += Vector4f( vtmp, 1.0f ); } } if ( total_gyro.w > 0.0f ) { mGyroscope = total_gyro.xyz() / total_gyro.w; } if ( mState == Running and ( not gyro_only or mAcroRPYCounter == 0 ) ) { for ( Accelerometer* dev : mAccelerometers ) { vtmp.x = vtmp.y = vtmp.z = 0.0f; dev->Read( &vtmp ); total_accel += Vector4f( vtmp, 1.0f ); } if ( total_accel.w > 0.0f ) { mLastAcceleration = mAcceleration; mAcceleration = total_accel.xyz() / total_accel.w; } if ( mSensorsUpdateSlow % 2 == 0 ) { for ( Magnetometer* dev : mMagnetometers ) { vtmp.x = vtmp.y = vtmp.z = 0.0f; dev->Read( &vtmp ); total_magn += Vector4f( vtmp, 1.0f ); } if ( total_magn.w > 0.0f ) { mMagnetometer = total_magn.xyz() / total_magn.w; } // sprintf( stmp, "\"%.4f,%.4f,%.4f\"", mMagnetometer.x, mMagnetometer.y, mMagnetometer.z ); // mMain->blackbox()->Enqueue( "IMU:magnetometer", stmp ); // TODO : handle Altimeters /* for ( Altimeter* dev : mAltimeters ) { ftmp = 0.0f; dev->Read( &ftmp ); if ( dev->type() == Altimeter::Proximity and ftmp > 0.0f ) { total_proxi += Vector2f( ftmp, 1.0f ); } else if ( dev->type() == Altimeter::Absolute and std::abs( ftmp - mAltitude ) < 15.0f ) { // this avoids to use erroneous values, 10 is arbitrary but nothing should be able to move by 10m in only one tick total_alti += Vector2f( ftmp, 1.0f ); } } if ( total_proxi.y > 0.0f ) { mProximity = total_proxi.x / total_proxi.y; } */ UpdateGPS(); #ifdef SYSTEM_NAME_Linux mPositionUpdateMutex.lock(); #endif mPositionUpdate = true; #ifdef SYSTEM_NAME_Linux mPositionUpdateMutex.unlock(); #endif } } for ( auto f : mConsumers ) { f( tick, mGyroscope, mAcceleration ); } // Update RPY only at 1/16 update frequency when in Rate mode mAcroRPYCounter = ( mAcroRPYCounter + 1 ) % 16; mSensorsUpdateSlow = ( mSensorsUpdateSlow + 1 ) % 16; } void IMU::UpdateGPS() { if ( mGPSes.size() == 0 ) { return; } char stmp[64]; Vector2f total_lat_lon; float total_alti = 0.0f; float total_speed = 0.0f; uint32_t total_seen = 0; uint32_t total_used = 0; for ( GPS* dev : mGPSes ) { float lattitude = 0.0f; float longitude = 0.0f; float altitude = 0.0f; float speed = 0.0f; bool ret = dev->Read( &lattitude, &longitude, &altitude, &speed ); if ( ret ) { total_lat_lon += Vector2f( lattitude, longitude ); total_alti += altitude; total_speed += speed; } uint32_t seen = 0; uint32_t used = 0; ret = dev->Stats( &seen, &used ); total_seen += seen; total_used += used; } mGPSAltitude = total_alti / mGPSes.size(); mGPSLocation = total_lat_lon.xy() * ( 1.0f / mGPSes.size() ); mGPSSpeed = total_speed / mGPSes.size(); mGPSSatellitesSeen = total_seen; mGPSSatellitesUsed = total_used; mMain->blackbox()->Enqueue( "IMU:gps", Vector4f( mGPSLocation.x, mGPSLocation.y, mGPSAltitude, mGPSSpeed ) ); } void IMU::UpdateAttitude( float dt ) { // Process rates Vector3f rate = mGyroscope; if ( mRatesFilter ) { rate = mRatesFilter->filter( mGyroscope, dt ); } mRate = rate; // Process acceleration if ( mAccelerometerFilter ) { mAccelerationSmoothed = mAccelerometerFilter->filter( mAcceleration, dt ); } else { mAccelerationSmoothed = mAcceleration; } // Process attitude mAttitude->UpdateInput( 0, mRate ); mAttitude->UpdateInput( 1, mAccelerationSmoothed ); mAttitude->Process( dt ); Vector4f rpy = mAttitude->state(); /* static uint32_t test = 0; if ( test++ == 10 ) { float heading = 0.0f; Vector3f mag = mMagnetometer.xyz(); mag.normalize(); if ( mag.y >= 0.0f ) { heading = acos( mag.x ); } else { heading = -acos( mag.x ); } test = 0; heading = heading * 180.0f / M_PI; // printf( "heading : %.2f [ %.2f, %.2f, %.2f ]\n", heading, mMagnetometer.x, mMagnetometer.y, mMagnetometer.z ); } */ mdRPY = ( rpy - mRPY ) * dt; mRPY = rpy; if ( mMain->blackbox() ) { const std::string keys[5] = { "IMU:gyroscope", "IMU:accelerometer", "IMU:rate", "IMU:acceleration", "IMU:rpy" }; const Vector3f values[5] = { mGyroscope, mAcceleration, mRate, mAccelerationSmoothed, mRPY }; mMain->blackbox()->Enqueue( keys, values, 5 ); } } void IMU::UpdateVelocity( float dt ) { Vector3f velo = mVelocity.state( 0 ); // Vector3f accel = mAccelerationSmoother.state( 0 ); Vector3f accel = mAccelerometerFilter->state(); mVelocity.UpdateInput( 0, velo.x + accel.x * dt ); mVelocity.UpdateInput( 1, velo.y + accel.y * dt ); mVelocity.UpdateInput( 2, velo.z + accel.z * dt ); // TODO : mix with position, to avoid drifting mVelocity.Process( dt ); } void IMU::UpdatePosition( float dt ) { /* Vector3f position = mVelocity.state( 0 ); Vector3f velo = mVelocity.state( 0 ); mPosition.UpdateInput( 0, position.x + velo.x * dt ); mPosition.UpdateInput( 2, position.y + velo.y * dt ); float altitude = 0.0f; if ( mProximity > 0.0f ) { mAltitudeOffset = mAltitude - mProximity; altitude = mProximity; } else { altitude = mAltitude - mAltitudeOffset; } mPosition.UpdateInput( 2, altitude ); */ /* // Calculate acceleration on Z-axis float accel_z = cos( mRPY.x ) * cos( mRPY.y ) * ( mAcceleration.z - mGravity.z ); // Integrate position on Z-axis float pos_z = mPosition.state( 2 ) + accel_z * dt * dt; mPosition.UpdateInput( 2, pos_z ); */ // mPosition.Process( dt ); }
13,109
C++
.cpp
483
24.610766
210
0.668846
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,710
DynamicNotchFilter.cpp
dridri_bcflight/flight/stabilizer/DynamicNotchFilter.cpp
#include <cassert> #include <Main.h> #include <IMU.h> #include "DynamicNotchFilter.h" #include "BiquadFilter.h" #include <fftw3.h> template<typename V> _DynamicNotchFilterBase<V>::_DynamicNotchFilterBase( uint8_t n ) : Filter<V>() , mMinFreq( 100 ) , mMaxFreq( 600 ) , mN( n ) , mState( V() ) , mFixedDt( 0.0f ) , mInputIndex( 0 ) , mAnalysisThread( new HookThread<_DynamicNotchFilterBase<V>>( "dnf", this, &_DynamicNotchFilterBase<V>::analysisRun ) ) { fDebug( (int)n ); uint32_t nSamples = 1000000 / Main::instance()->config()->Integer( "stabilizer.loop_time", 2000 ); mFixedDt = 1.0f / nSamples; mNumSamples = std::min( nSamples, 512U ); mSampleResolution = nSamples / mNumSamples; mDFTs.reserve( n ); for ( uint8_t i = 0; i < n; i++ ) { mDFTs[i].input = (float*)fftwf_malloc( sizeof(float) * mNumSamples ); mDFTs[i].inputBuffer = (float*)fftwf_malloc( sizeof(float) * mNumSamples ); mDFTs[i].output = (fftwf_complex*)fftwf_malloc( sizeof(fftwf_complex) * ( mNumSamples / 2 + 1 ) ); mDFTs[i].plan = fftwf_plan_dft_r2c_1d( mNumSamples, mDFTs[i].inputBuffer, mDFTs[i].output, FFTW_ESTIMATE ); mDFTs[i].magnitude = (float*)fftwf_malloc( sizeof(float) * ( mNumSamples / 2 + 1 ) ); mPeakFilters.push_back( std::vector<PeakFilter>() ); mPeakFilters[i].reserve( DYNAMIC_NOTCH_COUNT ); for ( uint8_t p = 0; p < DYNAMIC_NOTCH_COUNT; p++ ) { mPeakFilters[i][p].filter = new BiquadFilter<float>( 0.707f ); } } Start(); } template<> DynamicNotchFilter<float>::DynamicNotchFilter() : _DynamicNotchFilterBase<float>( 1 ) { fDebug( (int)1 ); } template<typename V> void _DynamicNotchFilterBase<V>::Start() { uint32_t main_freq = 1000000 / Main::instance()->config()->Integer( "stabilizer.loop_time", 2000 ); mAnalysisThread->setFrequency( main_freq / 12 ); mAnalysisThread->Start(); } template<> DynamicNotchFilter<Vector<float, 1>>::DynamicNotchFilter() : _DynamicNotchFilterBase<Vector<float,1>>( 1 ) {} template<> DynamicNotchFilter<Vector<float, 2>>::DynamicNotchFilter() : _DynamicNotchFilterBase<Vector<float,2>>( 2 ) {} template<> DynamicNotchFilter<Vector<float, 3>>::DynamicNotchFilter() : _DynamicNotchFilterBase<Vector<float,3>>( 3 ) {} template<> DynamicNotchFilter<Vector<float, 4>>::DynamicNotchFilter() : _DynamicNotchFilterBase<Vector<float,4>>( 4 ) {} template<> void DynamicNotchFilter<float>::pushSample( const float& sample ) { std::lock_guard<std::mutex> lock( mInputMutex ); mDFTs[0].input[mInputIndex] = sample; mInputIndex = ( mInputIndex + 1 ) % mNumSamples; } template<> void DynamicNotchFilter<Vector3f>::pushSample( const Vector3f& sample ) { std::lock_guard<std::mutex> lock( mInputMutex ); for ( uint8_t i = 0; i < 3; i++ ) { mDFTs[i].input[mInputIndex] = sample.ptr[i]; } mInputIndex = ( mInputIndex + 1 ) % mNumSamples; } template<typename V> V DynamicNotchFilter<V>::filter( const V& input, float dt ) { (void)dt; return input; } template<> float DynamicNotchFilter<float>::filter( const float& input, float dt ) { (void)dt; pushSample( input ); float result = input; for ( int p = 0; p < DYNAMIC_NOTCH_COUNT; p++ ) { const PeakFilter& peakFilter = mPeakFilters[0][p]; if ( peakFilter.filter->centerFrequency() <= 0.0f ) { continue; } // result = peakFilter.filter->filter( result, dt ); // BiquadFilter tends to infinity with variable dt result = peakFilter.filter->filter( result, mFixedDt ); } return result; } template<> Vector3f DynamicNotchFilter<Vector3f>::filter( const Vector3f& input, float dt ) { assert(mN == 3); (void)dt; pushSample( input ); Vector3f result = Vector3f( input.x, input.y, input.z ); for ( uint8_t i = 0; i < 3; i++ ) { for ( int p = 0; p < DYNAMIC_NOTCH_COUNT; p++ ) { PeakFilter& peakFilter = mPeakFilters[i][p]; if ( peakFilter.filter->centerFrequency() <= 0.0f ) { continue; } // result.ptr[i] = peakFilter.filter->filter( result.ptr[i], dt ); // BiquadFilter tends to infinity with variable dt result.ptr[i] = peakFilter.filter->filter( result.ptr[i], mFixedDt ); } } return result; } template<typename V> V _DynamicNotchFilterBase<V>::state() { return mState; } template<typename V> __attribute__((optimize("unroll-loops"))) bool _DynamicNotchFilterBase<V>::analysisRun() { // printf( "\n" ); const float dT = 1.0f / float(mAnalysisThread->frequency()); const uint32_t binMin = mMinFreq / ( mSampleResolution * 2 ); const uint32_t binMax = std::min( mMaxFreq / ( mSampleResolution * 2 ), mNumSamples / 2 + 1 ); // Copy input samples to aligned FFTW3 buffer mInputMutex.lock(); uint32_t startIdx = ( mInputIndex + 1 ) % mNumSamples; for ( uint8_t i = 0; i < mN; i++ ) { memcpy( mDFTs[i].inputBuffer, &mDFTs[i].input[startIdx], sizeof(float) * ( mNumSamples - startIdx ) ); memcpy( &mDFTs[i].inputBuffer[( mNumSamples - startIdx )], mDFTs[i].input, sizeof(float) * startIdx ); } mInputMutex.unlock(); // Apply Hann window for ( uint32_t n = 0; n < mNumSamples; n++ ) { float window = 0.5f * ( 1.0f - std::cos(2.0f * float(M_PI) * n / (mNumSamples - 1)) ); #pragma GCC unroll 4 for ( uint8_t i = 0; i < mN; i++ ) { mDFTs[i].inputBuffer[n] *= window; } } // Execute FFT #pragma GCC unroll 4 for ( uint8_t i = 0; i < mN; i++ ) { fftwf_execute( mDFTs[i].plan ); } // Extract DFT magnitude components and initialize noise floor float* noise = new float[mN]; memset( noise, 0, sizeof(float) * mN ); for ( uint8_t i = 0; i < mN; i++ ) { for ( uint32_t j = 0; j < mNumSamples / 2 + 1; j++ ) { // mDFTs[i].magnitude[j] = std::sqrt( mDFTs[i].output[j][0] * mDFTs[i].output[j][0] + mDFTs[i].output[j][1] * mDFTs[i].output[j][1] ); mDFTs[i].magnitude[j] = std::abs( mDFTs[i].output[j][0] ); if ( j >= binMin && j<= binMax ) { noise[i] += mDFTs[i].magnitude[j]; } } } // Detect top peaks const int maxPeaks = DYNAMIC_NOTCH_COUNT; const int peakDetectionSurround = 2; std::vector<Peak>* peaks = new std::vector<Peak>[mN]; for ( uint8_t i = 0; i < mN; i++ ) { peaks[i].reserve( DYNAMIC_NOTCH_COUNT ); memset( peaks[i].data(), 0, sizeof(Peak) * DYNAMIC_NOTCH_COUNT ); for ( uint32_t j = binMin + peakDetectionSurround; j < binMax - peakDetectionSurround; j++ ) { float val = mDFTs[i].magnitude[j]; bool above = true; // float localMean = 0.0f; for ( int k = -peakDetectionSurround; k <= peakDetectionSurround; k++ ) { // localMean += mDFTs[i].magnitude[j + k]; if ( val < mDFTs[i].magnitude[j + k] ) { above = false; break; } } // localMean /= 2 * peakDetectionSurround + 1; if ( /*val > localMean &&*/ std::abs(val) > 0.0f && above ) { for ( uint8_t k = 0; k < maxPeaks; k++ ) { if ( val > peaks[i][k].magnitude ) { // if(i==1)printf( "found peak at % 4d (% 4d Hz) magnitude=%4.4f\n", j, j * mSampleResolution * 2, val ); for ( uint8_t l = maxPeaks - 1; l > k; l-- ) { peaks[i][l].frequency = peaks[i][l - 1].frequency; peaks[i][l].magnitude = peaks[i][l - 1].magnitude; peaks[i][l].dftIndex = peaks[i][l - 1].dftIndex; } peaks[i][k].dftIndex = j; peaks[i][k].magnitude = val; peaks[i][k].frequency = (float)j / mNumSamples; break; } } j++; } } } // Sort peaks by index, ascending for ( uint8_t i = 0; i < mN; i++ ) { for ( uint8_t j = 0; j < maxPeaks; j++ ) { for ( uint8_t k = j + 1; k < maxPeaks; k++ ) { if ( peaks[i][j].dftIndex > peaks[i][k].dftIndex && peaks[i][k].dftIndex != 0 ) { Peak temp = peaks[i][j]; peaks[i][j] = peaks[i][k]; peaks[i][k] = temp; } } } } int* peaksCount = new int[mN]; float* noiseFloor = new float[mN]; memset( peaksCount, 0, sizeof(int) * mN ); memset( noiseFloor, 0, sizeof(float) * mN ); // Approximate noise floor for ( uint8_t i = 0; i < mN; i++ ) { noiseFloor[i] = noise[i]; float* dft = mDFTs[i].magnitude; const std::vector<Peak>& axisPeaks = peaks[i]; for (int p = 0; p < maxPeaks; p++) { if (axisPeaks[p].dftIndex == 0) { continue; } noiseFloor[i] -= 0.50f * dft[axisPeaks[p].dftIndex - 2]; noiseFloor[i] -= 0.75f * dft[axisPeaks[p].dftIndex - 1]; noiseFloor[i] -= dft[axisPeaks[p].dftIndex]; noiseFloor[i] -= 0.75f * dft[axisPeaks[p].dftIndex + 1]; noiseFloor[i] -= 0.50f * dft[axisPeaks[p].dftIndex + 2]; peaksCount[i]++; } noiseFloor[i] /= ( mNumSamples / 2 ) - peaksCount[i] + 1; // noiseFloor[i] *= 2.0f; } // Vector4i peaksI; // Process peaks for ( uint8_t i = 0; i < mN; i++ ) { // const std::vector<float>& dft = mDFTs[i].magnitude; const std::vector<Peak>& axisPeaks = peaks[i]; for ( int p = 0; p < peaksCount[i]; p++ ) { if ( axisPeaks[p].dftIndex == 0 || axisPeaks[p].magnitude <= noiseFloor[i] ) { continue; } PeakFilter* peakFilter = nullptr; peakFilter = &mPeakFilters[i][p]; /* float minDistance = 0.0f; for ( uint8_t j = 0; j < DYNAMIC_NOTCH_COUNT; j++ ) { if ( mPeakFilters[i][j].centerFrequency == 0.0f ) { peakFilter = &mPeakFilters[i][j]; break; } float distance = std::abs( mPeakFilters[i][j].centerFrequency - axisPeaks[p].frequency ); if ( peakFilter == nullptr || distance < minDistance ) { peakFilter = &mPeakFilters[i][j]; minDistance = distance; } } 20/512*512*(4000/512)*2 = 312 */ if ( peakFilter == nullptr ) { continue; } float smoothCutoff = 4.0f * std::clamp( axisPeaks[p].magnitude / noiseFloor[i], 1.0f, 10.0f ); // float gain = 2.0f * float(M_PI) * smoothCutoff * dT; // gain = 0.5f * ( gain / ( gain + 1.0f ) ); float centerFrequency = axisPeaks[p].frequency * float(mNumSamples * mSampleResolution); // * 2.0f; // printf( "%.2f → %.2f\n", peakFilter->centerFrequency, centerFrequency ); // peakFilter->centerFrequency += gain * ( centerFrequency - peakFilter->centerFrequency ); peakFilter->filter->setCenterFrequency( centerFrequency, 0.1f * smoothCutoff * dT ); // if ( i == 2 ) { // peaksI[p] = int(peakFilter->filter->centerFrequency()); // } } } // char dbgPeaks[64]; // sprintf( dbgPeaks, "{ % 4d, % 4d, % 4d, % 4d } [ %2.2f ]", peaksI.x, peaksI.y, peaksI.z, peaksI.w, noiseFloor[2] ); // gDebug() + "peaks : " + std::string(dbgPeaks); delete[] noiseFloor; delete[] peaksCount; delete[] peaks; delete[] noise; return true; } template class _DynamicNotchFilterBase<float>; template class DynamicNotchFilter<float>; template class _DynamicNotchFilterBase<Vector2f>; template class DynamicNotchFilter<Vector<float, 2>>; template class _DynamicNotchFilterBase<Vector3f>; template class DynamicNotchFilter<Vector<float, 3>>; template class _DynamicNotchFilterBase<Vector4f>; template class DynamicNotchFilter<Vector<float, 4>>; DynamicNotchFilter_3::DynamicNotchFilter_3() : DynamicNotchFilter<Vector<float, 3>>() { }
10,821
C++
.cpp
281
35.455516
137
0.651892
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,711
MahonyAHRS.cpp
dridri_bcflight/flight/stabilizer/MahonyAHRS.cpp
#include "MahonyAHRS.h" #include <Debug.h> MahonyAHRS::MahonyAHRS( float kp, float ki ) : mRotationMatrix( Matrix( 3, 3 ) ) , mState( Quaternion() ) , mIntegral( Vector3f() ) , mKp( kp ) , mKi( ki ) { fDebug( kp, ki ); memset( mRotationMatrix.m, 0, sizeof( float ) * 9 ); } MahonyAHRS::~MahonyAHRS() { } void MahonyAHRS::UpdateInput( uint32_t row, const Vector3f& input ) { if ( row >= mInputs.size() ) { mInputs.resize( row + 1 ); } mInputs[row] = input; } void MahonyAHRS::Process( float dt ) { Vector3f gyro = mInputs[0] * M_PI / 180.0f; Vector3f e = Vector3f(); if ( mInputs.size() >= 3 ) { Vector3f mag = mInputs[2].normalized(); // TODO } if ( mInputs.size() >= 2 ) { Vector3f acc = mInputs[1].normalized(); float tmp = acc.x; acc.x = -acc.y; acc.y = tmp; Vector3f rot = Vector3f( mRotationMatrix( 0, 2 ), mRotationMatrix( 1, 2 ), mRotationMatrix( 2, 2 ) ); e += acc ^ rot; } // Apply feedback terms mIntegral += e * mKi * dt; // integral error scaled by Ki gyro += e * mKp + mIntegral; // apply integral feedback, proportional error + integral error // pre-multiply common factors gyro *= 0.5f * dt; // compute quaternion rate of change mState = mState + Quaternion( mState.w * gyro.x + mState.y * gyro.z - mState.z * gyro.y, mState.w * gyro.y - mState.x * gyro.z + mState.z * gyro.x, mState.w * gyro.z + mState.x * gyro.y - mState.y * gyro.x, -mState.x * gyro.x - mState.y * gyro.y - mState.z * gyro.z ); // normalise quaternion mState.normalize(); // compute rotation matrix from quaternion computeMatrix(); // compute final state float roll = std::atan2( mRotationMatrix( 1, 2 ), mRotationMatrix( 2, 2 ) ) * 180.0f / M_PI; float pitch = ( 0.5f * M_PI - std::acos( -mRotationMatrix( 0, 2 ) ) ) * 180.0f / M_PI; float yaw = std::atan2( mRotationMatrix( 0, 1 ), mRotationMatrix( 0, 0 ) ) * 180.0f / M_PI; mFinalState = Vector3f( roll, pitch, yaw ); } const Vector3f& MahonyAHRS::state() const { return mFinalState; } void MahonyAHRS::computeMatrix() { // Extract quaternion components float qx = mState.x; float qy = mState.y; float qz = mState.z; float qw = mState.w; // Compute temporary variables to avoid redundant multiplications float qx2 = qx * qx; float qy2 = qy * qy; float qz2 = qz * qz; float qwqx = qw * qx; float qwqy = qw * qy; float qwqz = qw * qz; float qxqy = qx * qy; float qxqz = qx * qz; float qyqz = qy * qz; // Compute rotation matrix elements mRotationMatrix.m[0] = 1.0f - 2.0f * ( qy2 + qz2 ); mRotationMatrix.m[1] = 2.0f * ( qxqy - qwqz ); mRotationMatrix.m[2] = 2.0f * ( qxqz + qwqy ); mRotationMatrix.m[3] = 2.0f * ( qxqy + qwqz ); mRotationMatrix.m[4] = 1.0f - 2.0f * ( qx2 + qz2 ); mRotationMatrix.m[5] = 2.0f * ( qyqz - qwqx ); mRotationMatrix.m[6] = 2.0f * ( qxqz - qwqy ); mRotationMatrix.m[7] = 2.0f * ( qyqz + qwqx ); mRotationMatrix.m[8] = 1.0f - 2.0f * ( qx2 + qy2 ); }
3,001
C++
.cpp
92
29.576087
103
0.632802
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,712
LinuxCamera.cpp
dridri_bcflight/flight/video/LinuxCamera.cpp
#include <sys/fcntl.h> #include <sys/ioctl.h> #include <linux/v4l2-controls.h> #include <linux/videodev2.h> #include "LinuxCamera.h" #include "LiveOutput.h" #include "Debug.h" #include <thread> #include <sys/mman.h> std::unique_ptr<libcamera::CameraManager> LinuxCamera::sCameraManager = nullptr; class LibCameraStream : private std::streambuf, public std::ostream { public: LibCameraStream() : std::ostream(this) {} private: int overflow( int c ) override { // printf("0x%02X, '%c'\n", c, c); if ( c == '\n' ) { int32_t pos = buf.find("]"); if ( pos > 0 ) { pos = buf.find("]", pos + 1); if ( pos > 0 ) { int32_t pos2 = buf.find("INFO", pos); if ( pos2 ) { buf = buf.substr( pos2 + 5 ); } else { buf = buf.substr( pos + 2, 7 ) + buf.substr( pos + 2 + 8 ); } } } Debug(Debug::Verbose) + _debug_date() + self_thread() << buf.c_str(); buf.clear(); } else { buf += (char)c; } return 0; } std::string buf; }; static int xioctl( int fd, unsigned long ctl, void* arg ) { int ret, num_tries = 10; do { ret = ioctl( fd, ctl, arg ); } while (ret == -1 && errno == EINTR && num_tries-- > 0 ); return ret; } static void mergeControlLists( libcamera::ControlList& dest, const libcamera::ControlList& src ) { for ( auto it : src ) { dest.set( it.first, it.second ); } } static uint32_t stride64( uint32_t value ) { return ((value >> 6) << 6) + (((value >> 6) & 1) << 6); } LinuxCamera::LinuxCamera() : mLivePreview( false ) , mWidth( 1280 ) , mHeight( 720 ) , mFps( 60 ) , mHDR( false ) , mShutterSpeed( 0 ) , mISO( 0 ) , mSharpness( 0.25f ) , mBrightness( 0.0f ) , mContrast( 1.0f ) , mSaturation( 1.0f ) , mVflip( false ) , mHflip( false ) , mWhiteBalance( "auto" ) , mNightISO( 0 ) , mNightBrightness( 0.0f ) , mNightContrast( 1.0f ) , mNightSaturation( 1.0f ) , mCurrentFramerate( 0 ) , mExposureTime( 0 ) , mAwbGains({ 0.0f, 0.0f }) , mNightMode( false ) , mCamera( nullptr ) , mRawStreamConfiguration( nullptr ) , mPreviewStreamConfiguration( nullptr ) , mVideoStreamConfiguration( nullptr ) , mStillStreamConfiguration( nullptr ) , mPreviewSurface( nullptr ) , mPreviewSurfaceSet( false ) , mStopping( false ) { fDebug(); LibCameraStream* test = new LibCameraStream(); libcamera::logSetStream( test, true ); if ( sCameraManager == nullptr ) { sCameraManager = std::make_unique<libcamera::CameraManager>(); sCameraManager->start(); if ( sCameraManager->cameras().empty() ) { gError() << "No camera found on this system"; sCameraManager->stop(); return; } } gDebug() << "libcamera available cameras :"; for ( auto const& camera : sCameraManager->cameras() ) { const libcamera::ControlList &props = camera->properties(); std::string name; const auto &location = props.get(libcamera::properties::Location); if ( location ) { switch ( *location ) { case libcamera::properties::CameraLocationFront: name = "Internal front camera"; break; case libcamera::properties::CameraLocationBack: name = "Internal back camera"; break; case libcamera::properties::CameraLocationExternal: name = "External camera"; const auto &model = props.get(libcamera::properties::Model); if ( model ) { name = *model; } break; } } gDebug() << " " << name << " (" << camera->id() << ")"; } } LinuxCamera::~LinuxCamera() { fDebug(); } LuaValue LinuxCamera::infos() { LuaValue ret; if ( not mCamera ) { ret["Device"] = "None"; return ret; } ret["Device"] = mCamera->id(); if ( mPreviewStreamConfiguration ) { ret["Viewfinder Configuration"] = mPreviewStreamConfiguration->toString(); } if ( mVideoStreamConfiguration ) { ret["Video Configuration"] = mVideoStreamConfiguration->toString(); } if ( mStillStreamConfiguration ) { ret["Still Configuration"] = mStillStreamConfiguration->toString(); } ret["Resolution"] = std::to_string(mWidth) + "x" + std::to_string(mHeight); ret["Framerate"] = mFps; ret["HDR"] = ( mHDR ? "on" : "off" ); if ( mCamera->controls().find( libcamera::controls::MAX_LATENCY) != mCamera->controls().end() ) { ret["Max Latency"] = mCamera->controls().at( libcamera::controls::MAX_LATENCY ).toString(); } return ret; } void LinuxCamera::Start() { fDebug(); if ( sCameraManager->cameras().size() == 0 ) { gError() << "No camera detected !"; return; } if ( dynamic_cast<LiveOutput*>(mLiveEncoder) != nullptr and !mPreviewSurface ) { mLivePreview = true; mPreviewSurface = new DRMSurface(); } mCamera = sCameraManager->get( sCameraManager->cameras()[0]->id() ); mCamera->acquire(); std::vector<libcamera::StreamRole> roles; // roles.push_back( libcamera::StreamRole::Raw ); roles.push_back( libcamera::StreamRole::Viewfinder ); roles.push_back( libcamera::StreamRole::VideoRecording ); // roles.push_back( libcamera::StreamRole::StillCapture ); mCameraConfiguration = mCamera->generateConfiguration( roles ); uint32_t iStream = 0; if ( std::find( roles.begin(), roles.end(), libcamera::StreamRole::Raw ) != roles.end() ) { mRawStreamConfiguration = &mCameraConfiguration->at(iStream++); } if ( std::find( roles.begin(), roles.end(), libcamera::StreamRole::Viewfinder ) != roles.end() ) { mPreviewStreamConfiguration = &mCameraConfiguration->at(iStream++); } if ( std::find( roles.begin(), roles.end(), libcamera::StreamRole::VideoRecording ) != roles.end() ) { mVideoStreamConfiguration = &mCameraConfiguration->at(iStream++); } if ( std::find( roles.begin(), roles.end(), libcamera::StreamRole::StillCapture ) != roles.end() ) { mStillStreamConfiguration = &mCameraConfiguration->at(iStream++); } uint32_t bufferCount = 1; if ( mRawStreamConfiguration ) { mRawStreamConfiguration->pixelFormat = libcamera::formats::SRGGB12_CSI2P; mRawStreamConfiguration->size.width = mWidth; mRawStreamConfiguration->size.height = mHeight; mRawStreamConfiguration->bufferCount = 1; } if ( mPreviewStreamConfiguration ) { mPreviewStreamConfiguration->pixelFormat = libcamera::formats::YUV420; mPreviewStreamConfiguration->size.width = ( mLivePreview ? mPreviewSurface->mode()->hdisplay : mWidth ); mPreviewStreamConfiguration->size.height = ( mLivePreview ? mPreviewSurface->mode()->vdisplay : mHeight ); mPreviewStreamConfiguration->bufferCount = bufferCount; } if ( mVideoStreamConfiguration ) { mVideoStreamConfiguration->pixelFormat = libcamera::formats::YUV420; mVideoStreamConfiguration->size.width = mWidth; mVideoStreamConfiguration->size.height = mHeight; mVideoStreamConfiguration->bufferCount = bufferCount; } if ( mStillStreamConfiguration ) { // TODO } mCameraConfiguration->transform = ( mHflip ? libcamera::Transform::HFlip : libcamera::Transform::Identity ) | ( mVflip ? libcamera::Transform::VFlip : libcamera::Transform::Identity ); mCameraConfiguration->validate(); if ( mRawStreamConfiguration ) { gDebug() << "Validated raw configuration is: " << mRawStreamConfiguration->toString(); } if ( mPreviewStreamConfiguration ) { gDebug() << "Validated viewfinder configuration is: " << mPreviewStreamConfiguration->toString(); } if ( mVideoStreamConfiguration ) { gDebug() << "Validated video configuration is: " << mVideoStreamConfiguration->toString(); } if ( mStillStreamConfiguration ) { gDebug() << "Validated still configuration is: " << mStillStreamConfiguration->toString(); } if ( mHDR ) { setHDR( mHDR, true ); } mCamera->configure( mCameraConfiguration.get() ); if ( mVideoStreamConfiguration ) { mWidth = mVideoStreamConfiguration->size.width; mHeight = mVideoStreamConfiguration->size.height; } mAllControls.set( libcamera::controls::FrameDurationLimits, libcamera::Span<const int64_t, 2>({ 1000000 / mFps, 1000000 / mFps }) ); mAllControls.set( libcamera::controls::ExposureTime, mShutterSpeed ); mAllControls.set( libcamera::controls::AnalogueGain, (float)mISO / 100.0f ); mAllControls.set( libcamera::controls::Sharpness, mSharpness ); mAllControls.set( libcamera::controls::Brightness, mBrightness ); mAllControls.set( libcamera::controls::Contrast, mContrast ); mAllControls.set( libcamera::controls::Saturation, mSaturation ); mAllControls.set( libcamera::controls::AfMode, libcamera::controls::AfModeAuto ); // AfModeContinuous mAllControls.set( libcamera::controls::draft::SceneFlicker, libcamera::controls::draft::SceneFickerOff ); // mAllControls.set( libcamera::controls::AeMeteringMode, libcamera::controls::MeteringMatrix ); mAllControls.set( libcamera::controls::AeMeteringMode, libcamera::controls::MeteringSpot ); mAllControls.set( libcamera::controls::draft::NoiseReductionMode, libcamera::controls::draft::NoiseReductionModeEnum::NoiseReductionModeFast ); setWhiteBalance( mWhiteBalance, &mAllControls ); if ( mExposureMode == "short" ) { mAllControls.set( libcamera::controls::AeExposureMode, libcamera::controls::AeExposureModeEnum::ExposureShort ); } else if ( mExposureMode == "long" ) { mAllControls.set( libcamera::controls::AeExposureMode, libcamera::controls::AeExposureModeEnum::ExposureLong ); } else if ( mExposureMode == "custom" ) { mAllControls.set( libcamera::controls::AeExposureMode, libcamera::controls::AeExposureModeEnum::ExposureCustom ); } else { mAllControls.set( libcamera::controls::AeExposureMode, libcamera::controls::AeExposureModeEnum::ExposureNormal ); } if ( mRawStreamConfiguration ) { mControlListQueue[mRawStreamConfiguration->stream()] = libcamera::ControlList(); } if ( mPreviewStreamConfiguration ) { mControlListQueue[mPreviewStreamConfiguration->stream()] = libcamera::ControlList(); } if ( mVideoStreamConfiguration ) { mControlListQueue[mVideoStreamConfiguration->stream()] = libcamera::ControlList(); } if ( mStillStreamConfiguration ) { mControlListQueue[mStillStreamConfiguration->stream()] = libcamera::ControlList(); } mAllocator = new libcamera::FrameBufferAllocator( mCamera ); for ( libcamera::StreamConfiguration& cfg : *mCameraConfiguration ) { if ( mAllocator->allocate(cfg.stream()) < 0 ) { gError() << "Cannot allocate buffers"; return; } const std::vector<std::unique_ptr<libcamera::FrameBuffer>>& buffers = mAllocator->buffers(cfg.stream()); gDebug() << "Allocated " << buffers.size() << " buffers for stream " << cfg.toString(); for ( uint32_t i = 0; i < buffers.size(); i++ ) { const std::unique_ptr<libcamera::FrameBuffer> &buffer = buffers[i]; size_t sz = 0; for ( auto plane : buffer->planes() ) { sz += plane.length; } uint8_t* ptr = static_cast<uint8_t*>( mmap( nullptr, sz, PROT_READ | PROT_WRITE, MAP_SHARED, buffer->planes()[0].fd.get(), 0 ) ); if ( !ptr ) { gError() << "Failed to mmap buffer for stream " << cfg.toString(); } gDebug() << "mmap buffer for stream " << cfg.toString() << " : " << ptr; mPlaneBuffers[buffer.get()] = ptr; } if ( mLivePreview and &cfg == mPreviewStreamConfiguration ) { for ( uint32_t i = 0; i < buffers.size(); i++ ) { const std::unique_ptr<libcamera::FrameBuffer> &buffer = buffers[i]; mPreviewFrameBuffers[buffer.get()] = new DRMFrameBuffer( mPreviewStreamConfiguration->size.width, mPreviewStreamConfiguration->size.height, stride64(mPreviewStreamConfiguration->size.width), DRM_FORMAT_YUV420, 0, buffer->planes()[0].fd.get() ); } } } for ( uint32_t i = 0; i < bufferCount; i++ ) { std::unique_ptr<libcamera::Request> request = mCamera->createRequest(); for ( libcamera::StreamConfiguration& cfg : *mCameraConfiguration ) { const std::vector<std::unique_ptr<libcamera::FrameBuffer>>& buffers = mAllocator->buffers(cfg.stream()); const std::unique_ptr<libcamera::FrameBuffer> &buffer = buffers[i]; if ( request->addBuffer( cfg.stream(), buffer.get() ) < 0 ) { gError() << "Cannot set buffer into request for stream " << cfg.toString(); return; } } mRequests.push_back(std::move(request)); } if ( mVideoEncoder ) { mVideoEncoder->SetInputResolution( mWidth, mHeight ); } if ( mLiveEncoder ) { mLiveEncoder->SetInputResolution( mWidth, mHeight ); } mCamera->requestCompleted.connect( this, &LinuxCamera::requestComplete ); mCamera->start(&mAllControls); for ( std::unique_ptr<libcamera::Request>& request : mRequests ) { mRequestsAliveMutex.lock(); mRequestsAlive.insert( request.get() ); mRequestsAliveMutex.unlock(); mCamera->queueRequest( request.get() ); } } void LinuxCamera::Stop() { /* { // We don't want QueueRequest to run asynchronously while we stop the camera. std::lock_guard<std::mutex> lock(camera_stop_mutex_); if ( mCamera->stop() ) { gError() << "Failed to stop camera"; } } mCamera->requestCompleted.disconnect( this, &LinuxCamera::requestComplete ); mRequests.clear(); mControlListQueueMutex.lock(); mControlListQueue.clear(); mControlListQueueMutex.unlock(); mCamera->release(); mCamera.reset(); gDebug() << "Camera stopped!"; */ } void LinuxCamera::requestComplete( libcamera::Request* request ) { if ( request->status() == libcamera::Request::RequestCancelled ) { if ( mStopping ) { mRequestsAliveMutex.lock(); mRequestsAlive.erase( request ); mRequestsAliveMutex.unlock(); } } else { const libcamera::ControlList& metadata = request->metadata(); const libcamera::Request::BufferMap& buffers = request->buffers(); /* for (const auto& ctrl : metadata) { const libcamera::ControlId* id = libcamera::controls::controls.at(ctrl.first); const libcamera::ControlValue& value = ctrl.second; std::cout << "\t" << id->name() << " = " << value.toString() << std::endl; } */ mCurrentFramerate = 1000000L / *metadata.get( libcamera::controls::FrameDuration ); mExposureTime = *metadata.get( libcamera::controls::ExposureTime ); mAwbGains = *metadata.get( libcamera::controls::ColourGains ); mColorTemperature = *metadata.get( libcamera::controls::ColourTemperature ); /* gDebug() << "Framerate: " << mCurrentFramerate; gDebug() << "Exposure time: " << mExposureTime; gDebug() << "AWB gains: " << mAwbGains[0] << ", " << mAwbGains[1]; gDebug() << "Color temperature: " << mColorTemperature; */ if ( buffers.size() > 0 ) { libcamera::ControlList mergedControls; for ( auto bufferPair : buffers ) { const libcamera::Stream* stream = bufferPair.first; libcamera::FrameBuffer* buffer = bufferPair.second; if ( stream == mPreviewStreamConfiguration->stream() ) { if ( mLivePreview and mPreviewSurface and ( mPreviewFrameBuffers.size() > 1 or not mPreviewSurfaceSet ) ) { mPreviewSurfaceSet = true; mPreviewSurface->Show( mPreviewFrameBuffers[buffer] ); } } if ( mPreviewStreamConfiguration and stream == mPreviewStreamConfiguration->stream() ) { if ( mLiveEncoder ) { auto ts = metadata.get(libcamera::controls::SensorTimestamp); int64_t timestamp_ns = ts ? *ts : buffer->metadata().timestamp; size_t sz = 0; for ( auto plane : buffer->planes() ) { sz += plane.length; } mLiveEncoder->EnqueueBuffer( sz, mPlaneBuffers[buffer], timestamp_ns / 1000, buffer->planes()[0].fd.get() ); } } if ( mVideoStreamConfiguration and stream == mVideoStreamConfiguration->stream() ) { if ( mVideoEncoder ) { auto ts = metadata.get(libcamera::controls::SensorTimestamp); int64_t timestamp_ns = ts ? *ts : buffer->metadata().timestamp; size_t sz = 0; for ( auto plane : buffer->planes() ) { sz += plane.length; } mVideoEncoder->EnqueueBuffer( sz, mPlaneBuffers[buffer], timestamp_ns / 1000, buffer->planes()[0].fd.get() ); } } mControlListQueueMutex.lock(); libcamera::ControlList& controls = mControlListQueue[stream]; if ( controls.size() > 0 ) { mergeControlLists( mergedControls, controls ); controls.clear(); } mControlListQueueMutex.unlock(); } request->reuse( libcamera::Request::ReuseBuffers ); mergeControlLists( request->controls(), mergedControls ); mCamera->queueRequest( request ); } } } void LinuxCamera::Pause() { } void LinuxCamera::Resume() { } bool LinuxCamera::LiveThreadRun() { return true; } bool LinuxCamera::RecordThreadRun() { return true; } bool LinuxCamera::TakePictureThreadRun() { return true; } void LinuxCamera::setHDR( bool hdr, bool force ) { if ( mHDR == hdr and not force ) { return; } mRequestsAliveMutex.lock(); bool wasRunning = mRequestsAlive.size() > 0; mRequestsAliveMutex.unlock(); if ( wasRunning ) { mStopping = true; mCamera->stop(); mRequestsAliveMutex.lock(); while ( mRequestsAlive.size() > 0 ) { mRequestsAliveMutex.unlock(); usleep( 100 ); mRequestsAliveMutex.lock(); } mRequestsAliveMutex.unlock(); mStopping = false; } { bool ok = false; int fd = -1; v4l2_control ctrl { V4L2_CID_WIDE_DYNAMIC_RANGE, hdr }; for ( int i = 0; i < 4 && !ok; i++ ) { std::string dev = std::string("/dev/v4l-subdev") + (char)('0' + i); if ( (fd = open(dev.c_str(), O_RDWR, 0)) >= 0 ) { ok = !xioctl( fd, VIDIOC_S_CTRL, &ctrl ); close(fd); } } if ( !ok ) { gWarning() << "WARNING: Cannot " << ( hdr ? "en" : "dis" ) << "able HDR mode"; } else { mHDR = hdr; } } if ( wasRunning ) { mCamera->configure( mCameraConfiguration.get() ); mCamera->start( &mAllControls ); for ( std::unique_ptr<libcamera::Request>& request : mRequests ) { mRequestsAliveMutex.lock(); mRequestsAlive.insert( request.get() ); mRequestsAliveMutex.unlock(); request->reuse( libcamera::Request::ReuseBuffers ); mCamera->queueRequest(request.get()); } } } void LinuxCamera::getLensShader( Camera::LensShaderColor* r, Camera::LensShaderColor* g, Camera::LensShaderColor* b ) { } void LinuxCamera::setLensShader( const Camera::LensShaderColor& r, const Camera::LensShaderColor& g, const Camera::LensShaderColor& b ) { } std::string LinuxCamera::switchExposureMode() { return ""; } bool LinuxCamera::setWhiteBalance( const std::string& mode, libcamera::ControlList* controlsList ) { static const std::map< std::string, libcamera::controls::AwbModeEnum > awbModes = { { "auto", libcamera::controls::AwbModeEnum::AwbAuto }, { "incandescent", libcamera::controls::AwbModeEnum::AwbIncandescent }, { "tungsten", libcamera::controls::AwbModeEnum::AwbTungsten }, { "fluorescent", libcamera::controls::AwbModeEnum::AwbFluorescent }, { "indoor", libcamera::controls::AwbModeEnum::AwbIndoor }, { "daylight", libcamera::controls::AwbModeEnum::AwbDaylight }, { "cloudy", libcamera::controls::AwbModeEnum::AwbCloudy }, { "custom", libcamera::controls::AwbModeEnum::AwbCustom }, }; if ( awbModes.find( mode ) != awbModes.end() ) { if ( controlsList ) { (*controlsList).set( libcamera::controls::AwbMode, awbModes.at( mode ) ); } else { libcamera::ControlList controls; (controlsList ? *controlsList : controls).set( libcamera::controls::AwbMode, awbModes.at( mode ) ); pushControlList( controls ); } mWhiteBalance = mode; return true; } return false; } std::string LinuxCamera::switchWhiteBalance() { static const std::map< std::string, std::string > nextMode = { { "auto", "incandescent" }, { "incandescent", "fluorescent" }, { "fluorescent", "daylight" }, { "daylight", "cloudy" }, { "cloudy", "auto" }, { "custom", "auto" }, }; if ( nextMode.find( mWhiteBalance ) == nextMode.end() ) { setWhiteBalance( "auto" ); libcamera::ControlList controls; controls.set( libcamera::controls::ColourGains, libcamera::Span<const float, 2>({ 0.0f, 0.0f }) ); pushControlList( controls ); return "auto"; } std::string newMode = nextMode.at( mWhiteBalance ); setWhiteBalance( newMode ); return newMode; } std::string LinuxCamera::lockWhiteBalance() { libcamera::ControlList controls; if ( mAwbGains[0] < 0.0f or mAwbGains[1] < 0.0f or mAwbGains[0] > 16.0f or mAwbGains[1] > 16.0f ) { return mWhiteBalance; } auto span = libcamera::Span<const float, 2>({ mAwbGains[0], mAwbGains[1] }); controls.set( libcamera::controls::AwbMode, libcamera::controls::AwbModeEnum::AwbCustom ); controls.set( libcamera::controls::ColourGains, span ); pushControlList( controls ); char buf[64]; snprintf( buf, sizeof(buf), "R%.2fB%.2f", span[0], span[1] ); mWhiteBalance = buf; return mWhiteBalance; } void LinuxCamera::updateSettings() { libcamera::ControlList controls; controls.set( libcamera::controls::AnalogueGain, (float)mISO / 100.0f ); controls.set( libcamera::controls::Brightness, mBrightness ); controls.set( libcamera::controls::Contrast, mContrast ); controls.set( libcamera::controls::Saturation, mSaturation ); setWhiteBalance( mWhiteBalance, &controls ); if ( mExposureMode == "short" ) { controls.set( libcamera::controls::AeExposureMode, libcamera::controls::AeExposureModeEnum::ExposureShort ); } else if ( mExposureMode == "long" ) { controls.set( libcamera::controls::AeExposureMode, libcamera::controls::AeExposureModeEnum::ExposureLong ); } else if ( mExposureMode == "custom" ) { controls.set( libcamera::controls::AeExposureMode, libcamera::controls::AeExposureModeEnum::ExposureCustom ); } else { controls.set( libcamera::controls::AeExposureMode, libcamera::controls::AeExposureModeEnum::ExposureNormal ); } // controls.set( libcamera::controls::draft::NoiseReductionMode, libcamera::controls::draft::NoiseReductionModeEnum::NoiseReductionModeOff ); pushControlList( controls ); } void LinuxCamera::pushControlList( const libcamera::ControlList& list ) { mControlListQueueMutex.lock(); if ( mRawStreamConfiguration ) { mergeControlLists( mControlListQueue[mRawStreamConfiguration->stream()], list ); } if ( mPreviewStreamConfiguration ) { mergeControlLists( mControlListQueue[mPreviewStreamConfiguration->stream()], list ); } if ( mVideoStreamConfiguration ) { mergeControlLists( mControlListQueue[mVideoStreamConfiguration->stream()], list ); } if ( mStillStreamConfiguration ) { mergeControlLists( mControlListQueue[mStillStreamConfiguration->stream()], list ); } mControlListQueueMutex.unlock(); } void LinuxCamera::setShutterSpeed( uint32_t value ) { } void LinuxCamera::setISO( int32_t value ) { fDebug( value ); mISO = value; libcamera::ControlList controls; mAllControls.set( libcamera::controls::AnalogueGain, (float)mISO / 100.0f ); pushControlList( controls ); } void LinuxCamera::setSaturation( float value ) { fDebug( value ); mSaturation = value; libcamera::ControlList controls; controls.set( libcamera::controls::Saturation, mSaturation ); pushControlList( controls ); } void LinuxCamera::setContrast( float value ) { fDebug( value ); mContrast = value; libcamera::ControlList controls; controls.set( libcamera::controls::Contrast, mContrast ); pushControlList( controls ); } void LinuxCamera::setBrightness( float value ) { fDebug( value ); mBrightness = value; libcamera::ControlList controls; controls.set( libcamera::controls::Brightness, mBrightness ); pushControlList( controls ); } const uint32_t LinuxCamera::width() { return mWidth; } const uint32_t LinuxCamera::height() { return mHeight; } const uint32_t LinuxCamera::framerate() { return mCurrentFramerate; } const bool LinuxCamera::recording() { return false; } const std::string LinuxCamera::exposureMode() { return ""; } const std::string LinuxCamera::whiteBalance() { return mWhiteBalance; } const bool LinuxCamera::nightMode() { return mNightMode; } const uint32_t LinuxCamera::shutterSpeed() { return mExposureTime; } const int32_t LinuxCamera::ISO() { return mISO; } const float LinuxCamera::saturation() { return mSaturation; } const float LinuxCamera::contrast() { return mContrast; } const float LinuxCamera::brightness() { return mBrightness; } void LinuxCamera::TakePicture() { } void LinuxCamera::StopRecording() { } void LinuxCamera::StartRecording() { } uint32_t LinuxCamera::getLastPictureID() { return 0; } const std::string LinuxCamera::recordFilename() { return ""; } uint32_t* LinuxCamera::getFileSnapshot( const std::string& filename, uint32_t* width, uint32_t* height, uint32_t* bpp ) { return nullptr; }
24,191
C++
.cpp
694
32.105187
248
0.714261
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,713
LiveOutput.cpp
dridri_bcflight/flight/video/LiveOutput.cpp
#include "LiveOutput.h" LiveOutput::LiveOutput() : VideoEncoder() { } LiveOutput::~LiveOutput() { } void LiveOutput::Setup() { } void LiveOutput::EnqueueBuffer( size_t size, void* mem, int64_t timestamp_us, int fd ) { // Nothing to do here (void)size; (void)mem; (void)timestamp_us; (void)fd; }
308
C++
.cpp
19
14.526316
86
0.72695
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,714
DRMSurface.cpp
dridri_bcflight/flight/video/DRMSurface.cpp
#include <xf86drm.h> #include <xf86drmMode.h> #include <stdio.h> #include <list> #include <algorithm> #include "DRMSurface.h" #include "Debug.h" std::list< uint32_t > usedPlanes; DRMSurface::DRMSurface( int32_t zindex ) : mZindex( zindex ) , mKmsSet( false ) { drmModeRes* resources = drmModeGetResources( drmFd() ); drmModeConnector* connector = nullptr; for ( int i = 0; i < resources->count_connectors; i++ ) { drmModeConnector* conn = drmModeGetConnector( drmFd(), resources->connectors[i] ); if ( conn->connection == DRM_MODE_CONNECTED and ( conn->connector_type != DRM_MODE_CONNECTOR_DPI and conn->connector_type != DRM_MODE_CONNECTOR_DSI ) ) { connector = conn; break; } else if ( conn ) { drmModeFreeConnector( conn ); } } if ( connector == nullptr ) { fprintf(stderr, "Unable to get connector\n"); drmModeFreeResources(resources); exit(0); } mConnectorId = connector->connector_id; gDebug() << "Connector " << mConnectorId << " modes :"; for ( int i = 0; i < connector->count_modes; i++ ) { gDebug() << i << " : " << connector->modes[i].hdisplay << "x" << connector->modes[i].vdisplay << "@" << connector->modes[i].vrefresh; } for ( int i = 0; i < connector->count_modes; i++ ) { // if ( i == 22 ) { // if ( connector->modes[i].hdisplay == 1280 and connector->modes[i].vdisplay == 720 ) { mMode = connector->modes[i]; break; // } } // printf("resolution: %ix%i\n", mMode.hdisplay, mMode.vdisplay); drmModeEncoder* encoder = ( connector->encoder_id ? drmModeGetEncoder( drmFd(), connector->encoder_id ) : nullptr ); if ( encoder == nullptr ) { fprintf(stderr, "Unable to get encoder\n"); drmModeFreeConnector(connector); drmModeFreeResources(resources); exit(0); } mCrtcId = encoder->crtc_id; drmModeSetCrtc( drmFd(), mCrtcId, 0, 0, 0, &mConnectorId, 1, &mMode ); mPlaneId = 0; drmModePlaneResPtr planes = drmModeGetPlaneResources( drmFd() ); zindex = std::min( zindex, (int32_t)planes->count_planes - 1 ); for ( uint32_t i = 0; i < planes->count_planes && mPlaneId == 0; i++ ) { drmModePlanePtr plane = drmModeGetPlane( drmFd(), planes->planes[i] ); if ( i >= (uint32_t)zindex and std::find(usedPlanes.begin(), usedPlanes.end(), plane->plane_id) == usedPlanes.end() ) { // printf( "Plane %d : %d %d %d %d\n", i, plane->x, plane->y, plane->crtc_x, plane->crtc_y ); drmModeObjectProperties* props = drmModeObjectGetProperties( drmFd(), plane->plane_id, DRM_MODE_OBJECT_ANY ); for ( uint32_t j = 0; j < props->count_props && mPlaneId == 0; j++ ) { drmModePropertyRes* prop = drmModeGetProperty( drmFd(), props->props[j] ); // printf( " %s : %llu\n", prop->name, props->prop_values[j] ); if ( strcmp(prop->name, "type") == 0 and props->prop_values[j] == DRM_PLANE_TYPE_OVERLAY ) { mPlaneId = plane->plane_id; usedPlanes.push_back( mPlaneId ); break; } drmModeFreeProperty(prop); } drmModeFreeObjectProperties(props); } drmModeFreePlane(plane); } // printf( " ================> plane_id : 0x%08X\n", mPlaneId ); drmModeFreeEncoder(encoder); drmModeFreeConnector(connector); drmModeFreeResources(resources); } DRMSurface::~DRMSurface() { } const drmModeModeInfo* DRMSurface::mode() const { return &mMode; } void DRMSurface::Show( DRMFrameBuffer* fb ) { // fDebug( drmFd(), mPlaneId, mCrtcId, fb->handle(), 0, 0, 0, mMode.hdisplay, mMode.vdisplay, 0, 0, fb->width(), fb->height() ); // if ( drmModeSetPlane( drmFd(), mPlaneId, mCrtcId, fb->handle(), 0, 0, 0, fb->width(), fb->height(), 0, 0, mMode.hdisplay << 16, mMode.vdisplay << 16 ) ) { if ( mZindex == 0 and not mKmsSet ) { mKmsSet = true; drmModeSetCrtc( drmFd(), mCrtcId, fb->handle(), 0, 0, &mConnectorId, 1, &mMode ); } else { if ( drmModeSetPlane( drmFd(), mPlaneId, mCrtcId, fb->handle(), 0, 0, 0, mMode.hdisplay, mMode.vdisplay, 0, 0, fb->width() << 16, fb->height() << 16 ) ) { throw std::runtime_error("drmModeSetPlane failed: " + std::string(strerror(errno))); } } }
4,002
C++
.cpp
97
38.525773
158
0.661095
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,715
AvcodecEncoder.cpp
dridri_bcflight/flight/video/AvcodecEncoder.cpp
extern "C" { #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libavutil/pixfmt.h> #include <libavutil/frame.h> #include <libavutil/hwcontext_drm.h> #include <libavutil/imgutils.h> #include <libavutil/opt.h> } #include "AvcodecEncoder.h" #include "Debug.h" #include <libdrm/drm_fourcc.h> static const std::map< AvcodecEncoder::Format, std::string > formatToString = { { AvcodecEncoder::FORMAT_H264, "h264" }, { AvcodecEncoder::FORMAT_MJPEG, "mjpeg" } }; AvcodecEncoder::AvcodecEncoder() : VideoEncoder() { } AvcodecEncoder::~AvcodecEncoder() { } void AvcodecEncoder::Setup() { fDebug(); mReady = true; avformat_network_init(); // Find the H.264 encoder mCodec = avcodec_find_encoder( AV_CODEC_ID_H264 ); if ( !mCodec ) { gError() << "Codec not found"; return; } // Allocate codec context mCodecContext = avcodec_alloc_context3( mCodec ); if ( !mCodecContext ) { gError() << "Could not allocate video codec context"; return; } // Set codec parameters mCodecContext->bit_rate = mBitrate; mCodecContext->width = mWidth; mCodecContext->height = mHeight; mCodecContext->time_base = (AVRational){ 1, 1000 * 1000 }; mCodecContext->framerate = (AVRational){ mFramerate * 1000, 1000 }; mCodecContext->gop_size = 10; mCodecContext->max_b_frames = 0; mCodecContext->pix_fmt = AV_PIX_FMT_YUV420P; mCodecContext->sw_pix_fmt = AV_PIX_FMT_YUV420P; mCodecContext->me_range = 16; mCodecContext->me_cmp = 1; // No chroma ME mCodecContext->me_subpel_quality = 0; mCodecContext->thread_count = 0; mCodecContext->thread_type = FF_THREAD_FRAME; mCodecContext->slices = 1; av_opt_set( mCodecContext->priv_data, "preset", "superfast", 0 ); av_opt_set( mCodecContext->priv_data, "partitions", "i8x8,i4x4", 0 ); av_opt_set( mCodecContext->priv_data, "weightp", "none", 0 ); av_opt_set( mCodecContext->priv_data, "weightb", "0", 0 ); av_opt_set( mCodecContext->priv_data, "motion-est", "dia", 0 ); av_opt_set( mCodecContext->priv_data, "sc_threshold", "0", 0 ); av_opt_set( mCodecContext->priv_data, "rc-lookahead", "0", 0 ); av_opt_set( mCodecContext->priv_data, "mixed_ref", "0", 0 ); if ( avcodec_open2( mCodecContext, mCodec, nullptr ) < 0 ) { gError() << "Could not open codec"; return; } if ( mRecorder ) { mRecorderTrackId = mRecorder->AddVideoTrack( formatToString.at(mFormat), mWidth, mHeight, mFramerate, formatToString.at(mFormat) ); } } void AvcodecEncoder::EnqueueBuffer( size_t size, void* mem, int64_t timestamp_us, int fd ) { if ( not mReady ) { Setup(); usleep( 10 * 1000 ); } AVFrame *frame = av_frame_alloc(); frame->format = AV_PIX_FMT_YUV420P; frame->width = mWidth; frame->height = mHeight; frame->linesize[0] = mWidth; frame->linesize[1] = frame->linesize[2] = mWidth >> 1; frame->pts = timestamp_us; frame->buf[0] = av_buffer_create( (uint8_t *)mem, size, nullptr, nullptr, 0 ); av_image_fill_pointers( frame->data, AV_PIX_FMT_YUV420P, frame->height, frame->buf[0]->data, frame->linesize ); av_frame_make_writable( frame ); AVPacket packet; av_init_packet( &packet ); packet.data = NULL; packet.size = 0; int ret = avcodec_send_frame( mCodecContext, frame ); if ( ret < 0 ) { gError() << "Error sending frame to codec context (" << ret << ")"; return; } ret = avcodec_receive_packet( mCodecContext, &packet ); if (ret < 0) { gError() << "Error receiving packet from codec context"; return; } if ( mRecorder and (int32_t)mRecorderTrackId != -1 ) { bool keyframe = packet.flags & AV_PKT_FLAG_KEY; mRecorder->WriteSample( mRecorderTrackId, timestamp_us, packet.data, packet.size, keyframe ); } av_packet_unref(&packet); }
3,667
C++
.cpp
108
31.796296
133
0.705483
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,716
DRM.cpp
dridri_bcflight/flight/video/DRM.cpp
#include <sys/fcntl.h> #include <unistd.h> #include <string.h> #include <xf86drm.h> #include <xf86drmMode.h> #include <drm.h> #include <string> #include "DRM.h" #include "Debug.h" int DRM::sDrmFd = -1; int DRM::drmFd() { if ( sDrmFd < 0 ) { for ( int dev = 0; dev <= 1; dev++ ) { std::string device = std::string("/dev/dri/card") + std::to_string(dev); sDrmFd = open( device.c_str(), O_RDWR/* | O_CLOEXEC*/ ); if ( sDrmFd >= 0 ) { drmModeResPtr res = drmModeGetResources( sDrmFd ); if ( !res ) { close( sDrmFd ); sDrmFd = -1; } else { drmModeFreeResources( res ); gDebug() << "Card " << device << " has DRM capability"; break; } } } if ( sDrmFd < 0 ) { gError() << "No /dev/dri/cardX available with DRM capability (" << strerror(errno) << ")"; exit(3); } drmSetMaster( sDrmFd ); } return sDrmFd; }
878
C++
.cpp
36
21.166667
93
0.594724
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,717
VideoEncoder.cpp
dridri_bcflight/flight/video/VideoEncoder.cpp
#include "VideoEncoder.h" VideoEncoder::VideoEncoder() : mRecorder( nullptr ) , mLink( nullptr ) , mRecorderTrackId( (uint32_t)-1 ) , mInputWidth( 0 ) , mInputHeight( 0 ) { } VideoEncoder::~VideoEncoder() { } void VideoEncoder::SetInputResolution( int width, int height ) { mInputWidth = width; mInputHeight = height; }
333
C++
.cpp
17
17.823529
62
0.741935
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,718
Camera.cpp
dridri_bcflight/flight/video/Camera.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <Debug.h> #include "Camera.h" list<Camera*> Camera::sCameras; Camera::Camera() : mLiveEncoder( nullptr ) , mVideoEncoder( nullptr ) // , mStillEncoder( nullptr ) { fDebug(); sCameras.push_back( this ); } Camera::~Camera() { fDebug(); } LuaValue Camera::infosAll() { LuaValue ret; uint32_t i = 0; for ( auto& c : sCameras ) { ret["Camera " + to_string( i )] = c->infos(); } return ret; }
1,131
C++
.cpp
41
25.634146
72
0.722479
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,719
RecorderBasic.cpp
dridri_bcflight/flight/video/RecorderBasic.cpp
#ifdef SYSTEM_NAME_Linux #include <dirent.h> #include <string.h> #include "RecorderBasic.h" #include <Board.h> #include "Debug.h" RecorderBasic::RecorderBasic() : Recorder() , Thread( "RecorderBasic" ) , mBaseDirectory( "/var/VIDEO/" ) , mRecordId( 0 ) , mRecordSyncCounter( 0 ) { } RecorderBasic::~RecorderBasic() { } bool RecorderBasic::recording() { return Thread::running(); } void RecorderBasic::Start() { fDebug(); if ( recording() ) { return; } uint32_t fileid = 0; DIR* dir; struct dirent* ent; if ( ( dir = opendir( mBaseDirectory.c_str() ) ) != nullptr ) { while ( ( ent = readdir( dir ) ) != nullptr ) { string file = string( ent->d_name ); if ( file.find( "record_" ) != file.npos ) { uint32_t id = std::atoi( file.substr( file.rfind( "_" ) + 1 ).c_str() ); if ( id >= fileid ) { fileid = id + 1; } } } closedir( dir ); } mRecordId = fileid; char filename[256]; sprintf( filename, (mBaseDirectory + "/record_%06u.csv").c_str(), mRecordId ); mRecordFile = fopen( filename, "wb" ); fprintf( mRecordFile, "# new_track,track_id,type(video/audio),filename\n" ); fprintf( mRecordFile, "# track_id,record_time,pos_in_file,frame_size\n" ); for ( auto& track : mTracks ) { track->recordStart = 0; } Thread::Start(); } void RecorderBasic::Stop() { fDebug(); Thread::Stop(); Thread::Join(); for ( auto sample : mPendingSamples ) { delete sample->buf; delete sample; } mPendingSamples.clear(); for ( auto track : mTracks ) { if ( track->file ) { fclose( track->file ); track->file = nullptr; } } } uint32_t RecorderBasic::AddVideoTrack( const std::string& format, uint32_t width, uint32_t height, uint32_t average_fps, const string& extension ) { Track* track = (Track*)malloc( sizeof(Track) ); memset( track, 0, sizeof(Track) ); track->type = TrackTypeVideo; strcpy( track->format, format.c_str() ); track->width = width; track->height = height; track->average_fps = average_fps; strcpy( track->extension, extension.c_str() ); track->id = mTracks.size(); mTracks.emplace_back( track ); /* Track* track = new Track; track->type = TrackTypeVideo; sprintf( track->filename, "video_%ux%u_%02ufps_%06u.%s", width, height, average_fps, mRecordId, extension.c_str() ); track->file = fopen( ( string("/var/VIDEO/") + string(track->filename) ).c_str(), "wb" ); mWriteMutex.lock(); track->id = mTracks.size(); fprintf( mRecordFile, "new_track,%u,video,%s\n", track->id, track->filename ); mTracks.emplace_back( track ); mWriteMutex.unlock(); */ return track->id; } uint32_t RecorderBasic::AddAudioTrack( const std::string& format, uint32_t channels, uint32_t sample_rate, const string& extension ) { Track* track = (Track*)malloc( sizeof(Track) ); memset( track, 0, sizeof(Track) ); track->type = TrackTypeAudio; strcpy( track->format, format.c_str() ); track->channels = channels; track->sample_rate = sample_rate; strcpy( track->extension, extension.c_str() ); track->id = mTracks.size(); mTracks.emplace_back( track ); /* Track* track = new Track; track->type = TrackTypeAudio; sprintf( track->filename, "audio_%uhz_%uch_%06u.%s", sample_rate, channels, mRecordId, extension.c_str() ); track->file = fopen( ( string("/var/VIDEO/") + string(track->filename) ).c_str(), "wb" ); mWriteMutex.lock(); track->id = mTracks.size(); fprintf( mRecordFile, "new_track,%u,audio,%s\n", track->id, track->filename ); mTracks.emplace_back( track ); mWriteMutex.unlock(); */ return track->id; } void RecorderBasic::WriteSample( uint32_t track_id, uint64_t record_time_us, void* buf, uint32_t buflen, bool keyframe ) { if ( not recording() ) { return; } Track* track = mTracks.at(track_id); if ( not track ) { return; } if ( track->recordStart == 0 ) { track->recordStart = record_time_us; } record_time_us -= track->recordStart; // fDebug( track_id, record_time_us, buf, buflen ); PendingSample* sample = new PendingSample; sample->track = track; sample->record_time_us = record_time_us; sample->buf = new uint8_t[buflen]; sample->buflen = buflen; memcpy( sample->buf, buf, buflen ); mWriteMutex.lock(); mPendingSamples.emplace_back( sample ); mWriteMutex.unlock(); } void RecorderBasic::WriteGyro( uint64_t record_time_us, const Vector3f& gyro, const Vector3f& accel ) { (void)record_time_us; (void)gyro; (void)accel; } bool RecorderBasic::run() { // Wait until there is data to write (TBD : use pthread_cond for passive wait ?) mWriteMutex.lock(); if ( mPendingSamples.size() == 0 ) { mWriteMutex.unlock(); usleep( 1000 * 5 ); // wait 5 ms, allowing up to 200FPS video recording return true; } PendingSample* sample = mPendingSamples.front(); mPendingSamples.pop_front(); mWriteMutex.unlock(); if ( sample->track->file == nullptr ) { Track* track = sample->track; if ( track->type == TrackTypeVideo ) { sprintf( track->filename, "video_%ux%u_%02ufps_%06u.%s", track->width, track->height, track->average_fps, mRecordId, track->extension ); fprintf( mRecordFile, "new_track,%u,video,%s\n", track->id, track->filename ); } else if ( track->type == TrackTypeAudio ) { sprintf( track->filename, "audio_%uhz_%uch_%06u.%s", track->sample_rate, track->channels, mRecordId, track->extension ); fprintf( mRecordFile, "new_track,%u,audio,%s\n", track->id, track->filename ); } track->file = fopen( ( mBaseDirectory + "/" + string(track->filename) ).c_str(), "wb" ); } uint32_t pos = ftell( sample->track->file ); if ( fwrite( sample->buf, 1, sample->buflen, sample->track->file ) != sample->buflen ) { goto err; } if ( fprintf( mRecordFile, "%u,%llu,%u,%u\n", sample->track->id, sample->record_time_us, pos, sample->buflen ) <= 0 ) { goto err; } if ( mRecordSyncCounter == 0 ) { if ( fflush( mRecordFile ) < 0 or fsync( fileno( mRecordFile ) ) < 0 ) { goto err; } } mRecordSyncCounter = ( mRecordSyncCounter + 1 ) % 10; // sync on disk every 10 samples (up to 10*1/FPS seconds) goto end; err: if ( errno == ENOSPC ) { Board::setDiskFull(); } end: delete[] sample->buf; delete sample; return true; } #endif // SYSTEM_NAME_Linux
6,155
C++
.cpp
196
29.086735
146
0.678958
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,720
Recorder.cpp
dridri_bcflight/flight/video/Recorder.cpp
#ifdef SYSTEM_NAME_Linux #include <dirent.h> #include <string.h> #include "Recorder.h" #include <Board.h> #include "Debug.h" std::set<Recorder*> Recorder::sRecorders; Recorder::Recorder() { sRecorders.insert( this ); } Recorder::~Recorder() { } const std::set<Recorder*>& Recorder::recorders() { return sRecorders; } #endif // SYSTEM_NAME_Linux
358
C++
.cpp
19
17.157895
48
0.75
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,721
V4L2Encoder.cpp
dridri_bcflight/flight/video/V4L2Encoder.cpp
#include <sys/fcntl.h> #include <poll.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <linux/videodev2.h> #include <map> #include <chrono> #include "V4L2Encoder.h" #include "Socket.h" #include "Debug.h" static constexpr int NUM_INPUT_BUFFERS = 6; static constexpr int NUM_OUTPUT_BUFFERS = 12; static int xioctl( int fd, unsigned long ctl, void* arg ) { int ret, num_tries = 10; do { ret = ioctl( fd, ctl, arg ); } while (ret == -1 && errno == EINTR && num_tries-- > 0 ); return ret; } static const std::map< V4L2Encoder::Format, std::string > formatToString = { { V4L2Encoder::FORMAT_H264, "h264" }, { V4L2Encoder::FORMAT_MJPEG, "mjpeg" } }; V4L2Encoder::V4L2Encoder() : VideoEncoder() , mVideoDevice( "/dev/video11" ) , mFormat( FORMAT_H264 ) , mBitrate( 4 * 1024 * 1024 ) , mQuality( 100 ) , mWidth( 1280 ) , mHeight( 720 ) , mFramerate( 30 ) , mReady( false ) , mFD( -1 ) { } V4L2Encoder::~V4L2Encoder() { } void V4L2Encoder::Setup() { mReady = true; mFD = open( mVideoDevice.c_str(), O_RDWR, 0 ); if ( mFD < 0 ) { throw std::runtime_error("failed to open V4L2 encoder"); } gDebug() << "Opened V4L2Encoder on " << mVideoDevice << " as fd " << mFD; if ( mInputWidth == 0 ) { mInputWidth = mWidth; } if ( mInputHeight == 0 ) { mInputHeight = mHeight; } gDebug() << "input resolution : " << mInputWidth << "x" << mInputHeight; v4l2_format fmt = {}; fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; fmt.fmt.pix_mp.width = mInputWidth; fmt.fmt.pix_mp.height = mInputHeight; // We assume YUV420 here, but it would be nice if we could do something // like info.pixel_format.toV4L2Fourcc(); fmt.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_YUV420; fmt.fmt.pix_mp.plane_fmt[0].bytesperline = mInputWidth; // On YUV420, stride == width fmt.fmt.pix_mp.field = V4L2_FIELD_ANY; // fmt.fmt.pix_mp.colorspace = get_v4l2_colorspace(info.colour_space); // TOD fmt.fmt.pix_mp.num_planes = 1; if ( xioctl( mFD, VIDIOC_S_FMT, &fmt ) < 0 ) { throw std::runtime_error("failed to set output format"); } switch ( mFormat ) { case FORMAT_H264: SetupH264(); break; case FORMAT_MJPEG: SetupMJPEG(); break; default: throw std::runtime_error("unsupported format"); } struct v4l2_streamparm parm = {}; parm.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; parm.parm.output.timeperframe.numerator = 1000 / mFramerate; parm.parm.output.timeperframe.denominator = 1000; if ( xioctl( mFD, VIDIOC_S_PARM, &parm ) < 0 ) { throw std::runtime_error("failed to set streamparm"); } // Request that the necessary buffers are allocated. The output queue // (input to the encoder) shares buffers from our caller, these must be // DMABUFs. Buffers for the encoded bitstream must be allocated and // m-mapped. v4l2_requestbuffers reqbufs = {}; reqbufs.count = NUM_INPUT_BUFFERS; reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; reqbufs.memory = V4L2_MEMORY_DMABUF; if ( xioctl( mFD, VIDIOC_REQBUFS, &reqbufs ) < 0 ) { throw std::runtime_error("request for input buffers failed"); } gDebug() << "Got " << reqbufs.count << " input buffers"; // We have to maintain a list of the buffers we can use when our caller gives // us another frame to encode. for (unsigned int i = 0; i < reqbufs.count; i++) { mInputBuffersAvailable.push(i); } reqbufs = {}; reqbufs.count = NUM_OUTPUT_BUFFERS; reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; reqbufs.memory = V4L2_MEMORY_MMAP; if ( xioctl( mFD, VIDIOC_REQBUFS, &reqbufs ) < 0 ) { throw std::runtime_error("request for output buffers failed"); } gDebug() << "Got " << reqbufs.count << " output buffers"; mOutputBuffersCount = reqbufs.count; for ( uint32_t i = 0; i < reqbufs.count; i++ ) { v4l2_plane planes[VIDEO_MAX_PLANES]; v4l2_buffer buffer = {}; buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; buffer.memory = V4L2_MEMORY_MMAP; buffer.index = i; buffer.length = 1; buffer.m.planes = planes; if ( xioctl( mFD, VIDIOC_QUERYBUF, &buffer ) < 0 ) { throw std::runtime_error("failed to output query buffer " + std::to_string(i)); } BufferDescription outputBuf = { .mem = mmap( 0, buffer.m.planes[0].length, PROT_READ | PROT_WRITE, MAP_SHARED, mFD, buffer.m.planes[0].m.mem_offset ), .size = buffer.m.planes[0].length }; if ( outputBuf.mem == MAP_FAILED ) { throw std::runtime_error("failed to mmap output buffer " + std::to_string(i)); } mOutputBuffers.push_back( outputBuf ); // Whilst we're going through all the output buffers, we may as well queue // them ready for the encoder to write into. if ( xioctl( mFD, VIDIOC_QBUF, &buffer ) < 0 ) { throw std::runtime_error("failed to queue output buffer " + std::to_string(i)); } } // Enable streaming and we're done. v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; if ( xioctl( mFD, VIDIOC_STREAMON, &type ) < 0 ) { throw std::runtime_error("failed to start output streaming"); } type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; if ( xioctl( mFD, VIDIOC_STREAMON, &type ) < 0 ) { throw std::runtime_error("failed to start output streaming"); } gDebug() << "Codec streaming started"; if ( mRecorder ) { mRecorderTrackId = mRecorder->AddVideoTrack( formatToString.at(mFormat), mWidth, mHeight, mFramerate, formatToString.at(mFormat) ); } if ( mLink and not mLink->isConnected() ) { mLink->Connect(); if ( mLink->isConnected() ) { gDebug() << "V4L2Encoder live output link connected !"; mLink->setBlocking( false ); } } Thread::setName( "V4L2Encoder::pollThread" ); Thread::Start(); } void V4L2Encoder::SetupH264() { v4l2_control ctrl = {}; { ctrl.id = V4L2_CID_MPEG_VIDEO_BITRATE; ctrl.value = mBitrate; if ( xioctl( mFD, VIDIOC_S_CTRL, &ctrl ) < 0 ) { throw std::runtime_error("failed to set bitrate peak"); } } { ctrl.id = V4L2_CID_MPEG_VIDEO_BITRATE_MODE; ctrl.value = V4L2_MPEG_VIDEO_BITRATE_MODE_VBR; if ( xioctl( mFD, VIDIOC_S_CTRL, &ctrl ) < 0 ) { throw std::runtime_error("failed to set bitrate mode"); } } { ctrl.id = V4L2_CID_MPEG_VIDEO_H264_PROFILE; ctrl.value = V4L2_MPEG_VIDEO_H264_PROFILE_HIGH; if ( xioctl( mFD, VIDIOC_S_CTRL, &ctrl ) < 0 ) { throw std::runtime_error("failed to set profile"); } } { ctrl.id = V4L2_CID_MPEG_VIDEO_H264_LEVEL; ctrl.value = V4L2_MPEG_VIDEO_H264_LEVEL_4_2; if ( xioctl( mFD, VIDIOC_S_CTRL, &ctrl ) < 0 ) { throw std::runtime_error("failed to set level"); } } { ctrl.id = V4L2_CID_MPEG_VIDEO_H264_I_PERIOD; ctrl.value = 10; if ( xioctl( mFD, VIDIOC_S_CTRL, &ctrl ) < 0 ) { throw std::runtime_error("failed to set intra period"); } } { ctrl.id = V4L2_CID_MPEG_VIDEO_REPEAT_SEQ_HEADER; ctrl.value = 1; // Inline headers if ( xioctl( mFD, VIDIOC_S_CTRL, &ctrl ) < 0 ) { throw std::runtime_error("failed to set inline headers"); } } v4l2_format fmt = {}; fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.width = mWidth; fmt.fmt.pix_mp.height = mHeight; fmt.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_H264; fmt.fmt.pix_mp.field = V4L2_FIELD_ANY; fmt.fmt.pix_mp.colorspace = V4L2_COLORSPACE_DEFAULT; fmt.fmt.pix_mp.num_planes = 1; fmt.fmt.pix_mp.plane_fmt[0].bytesperline = 0; fmt.fmt.pix_mp.plane_fmt[0].sizeimage = 512 << 10; if ( xioctl( mFD, VIDIOC_S_FMT, &fmt ) < 0 ) { throw std::runtime_error("failed to set output format"); } } void V4L2Encoder::SetupMJPEG() { { v4l2_control ctrl = {}; ctrl.id = V4L2_CID_MPEG_VIDEO_BITRATE; ctrl.value = mBitrate; if ( xioctl( mFD, VIDIOC_S_CTRL, &ctrl ) < 0 ) { throw std::runtime_error("failed to set bitrate peak"); } } v4l2_format fmt = {}; fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.width = mWidth; fmt.fmt.pix_mp.height = mHeight; fmt.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_MJPEG; fmt.fmt.pix_mp.field = V4L2_FIELD_ANY; fmt.fmt.pix_mp.colorspace = V4L2_COLORSPACE_DEFAULT; fmt.fmt.pix_mp.num_planes = 1; fmt.fmt.pix_mp.plane_fmt[0].bytesperline = mWidth * 3; fmt.fmt.pix_mp.plane_fmt[0].sizeimage = 2048 << 10; if ( xioctl( mFD, VIDIOC_S_FMT, &fmt ) < 0 ) { throw std::runtime_error("failed to set output format"); } } int64_t tt = 0; void V4L2Encoder::EnqueueBuffer( size_t size, void* mem, int64_t timestamp_us, int fd ) { // fDebug( size, mem, timestamp_us, fd ); // gDebug() << "Enqueuing at " << ( 1000000 / ( timestamp_us - tt ) ) << "FPS"; // tt = timestamp_us; if ( not mReady ) { Setup(); usleep( 10 * 1000 ); } if ( ( not mRecorder or not mRecorder->recording() ) and ( not mLink or not mLink->isConnected() ) ) { return; } int index; { // We need to find an available output buffer (input to the codec) to // "wrap" the DMABUF. std::lock_guard<std::mutex> lock(mInputBuffersAvailableMutex); if ( mInputBuffersAvailable.empty() ) { // throw std::runtime_error("no buffers available to queue codec input"); // gWarning() << "No buffers available to queue codec input, dropping frame"; return; } index = mInputBuffersAvailable.front(); mInputBuffersAvailable.pop(); } v4l2_buffer buf = {}; v4l2_plane planes[VIDEO_MAX_PLANES] = {}; buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; buf.index = index; buf.field = V4L2_FIELD_NONE; buf.memory = V4L2_MEMORY_DMABUF; buf.length = 1; buf.timestamp.tv_sec = timestamp_us / 1000000; buf.timestamp.tv_usec = timestamp_us % 1000000; buf.m.planes = planes; buf.m.planes[0].m.fd = fd; buf.m.planes[0].bytesused = size; buf.m.planes[0].length = size; if ( xioctl( mFD, VIDIOC_QBUF, &buf ) < 0 ) { throw std::runtime_error("failed to queue input to codec : " + std::string(strerror(errno))); } } bool V4L2Encoder::run() { // while ( true ) { pollfd p = { mFD, POLLIN, 0 }; int ret = poll( &p, 1, 10 ); { std::lock_guard<std::mutex> lock(mInputBuffersAvailableMutex); if ( mInputBuffersAvailable.size() == NUM_OUTPUT_BUFFERS ) { return true; } } if ( ret < 0 ) { if ( errno == EINTR ) { return true; } throw std::runtime_error("unexpected errno " + std::to_string(errno) + " from poll"); } if ( p.revents & POLLIN ) { v4l2_plane planes[VIDEO_MAX_PLANES] = {}; memset(planes, 0, sizeof(planes)); v4l2_buffer buf = {}; buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; buf.memory = V4L2_MEMORY_DMABUF; buf.length = 1; buf.m.planes = planes; int ret = xioctl( mFD, VIDIOC_DQBUF, &buf ); if ( ret == 0 ) { // Return this to the caller, first noting that this buffer, identified // by its index, is available for queueing up another frame. { std::lock_guard<std::mutex> lock(mInputBuffersAvailableMutex); mInputBuffersAvailable.push(buf.index); } } buf = {}; buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; buf.memory = V4L2_MEMORY_MMAP; buf.length = 1; buf.m.planes = planes; ret = xioctl( mFD, VIDIOC_DQBUF, &buf ); if ( ret == 0 ) { // We push this encoded buffer to another thread so that our // application can take its time with the data without blocking the // encode process. int64_t timestamp_us = (buf.timestamp.tv_sec * (int64_t)1000000) + buf.timestamp.tv_usec; if ( mRecorder and (int32_t)mRecorderTrackId != -1 ) { mRecorder->WriteSample( mRecorderTrackId, timestamp_us, mOutputBuffers[buf.index].mem, buf.m.planes[0].bytesused, buf.flags & V4L2_BUF_FLAG_KEYFRAME ); } if ( mLink and mLink->isConnected() ) { if ( dynamic_cast<Socket*>(mLink) ) { uint32_t dummy = 0; mLink->Read( &dummy, sizeof(dummy), 0 ); // Dummy Read to get sockaddr_t from client } int err = mLink->Write( (uint8_t*)mOutputBuffers[buf.index].mem, buf.m.planes[0].bytesused, false, 0 ); if ( err < 0 ) { gWarning() << "Link->Write() error : " << strerror(errno) << " (" << errno << ")"; } } v4l2_buffer buf2 = {}; v4l2_plane planes[VIDEO_MAX_PLANES] = {}; buf2.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; buf2.memory = V4L2_MEMORY_MMAP; buf2.index = buf.index; buf2.length = 1; buf2.m.planes = planes; buf2.m.planes[0].bytesused = 0; buf2.m.planes[0].length = buf.m.planes[0].length; if ( xioctl( mFD, VIDIOC_QBUF, &buf2) < 0 ) { throw std::runtime_error("failed to re-queue encoded buffer"); } } } // } return true; }
12,268
C++
.cpp
361
31.105263
156
0.673528
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,722
RecorderAvformat.cpp
dridri_bcflight/flight/video/RecorderAvformat.cpp
#include <sys/statvfs.h> #include <dirent.h> #include "RecorderAvformat.h" #include "Board.h" #include "Debug.h" #include "Main.h" #include "IMU.h" RecorderAvformat::RecorderAvformat() : Recorder() , Thread( "RecorderAvformat" ) , mRecordStartTick( 0 ) , mRecordStartSystemTick( 0 ) , mActive( false ) , mOutputContext( nullptr ) , mMuxerReady( false ) , mStopWrite( false ) , mWriteTicks( 0 ) , mGyroFile( nullptr ) , mConsumerRegistered( false ) { } RecorderAvformat::~RecorderAvformat() { } static std::string averr( int err ) { char str[AV_ERROR_MAX_STRING_SIZE] = ""; return std::string( av_make_error_string( str, AV_ERROR_MAX_STRING_SIZE, err ) ); } void RecorderAvformat::WriteSample( PendingSample* sample ) { // fTrace( sample->track->type, sample->track->stream->id, sample->record_time_us, sample->buflen, sample->keyframe ); AVPacket* pkt = av_packet_alloc(); av_packet_from_data( pkt, sample->buf, sample->buflen ); pkt->stream_index = sample->track->stream->id; pkt->dts = sample->record_time_us; pkt->pts = sample->record_time_us; pkt->pos = -1LL; pkt->flags = ( sample->keyframe ? AV_PKT_FLAG_KEY : 0 ); if ( sample->track->type == TrackTypeVideo ) { pkt->flags = ( sample->keyframe ? AV_PKT_FLAG_KEY : 0 ); if ( not mMuxerReady and sample->track->stream->codecpar->extradata == nullptr ) { sample->track->stream->codecpar->extradata = (uint8_t*)malloc( 50 ); sample->track->stream->codecpar->extradata_size = 50; // memcpy( sample->track->stream->codecpar->extradata, sample->buf, 50 ); memcpy( sample->track->stream->codecpar->extradata, mVideoHeader.data(), 50 ); } } if ( sample->track->type == TrackTypeAudio ) { pkt->flags = ( sample->keyframe ? AV_PKT_FLAG_KEY : 0 ); if ( not mMuxerReady and sample->track->stream->codecpar->extradata == nullptr ) { sample->track->stream->codecpar->extradata = (uint8_t*)malloc( 0 ); // sample->track->stream->codecpar->extradata_size = 15; // memcpy( sample->track->stream->codecpar->extradata, mAudioHeader.data(), 15 ); } } if ( not mMuxerReady ) { bool all_ready = true; for ( auto track : mTracks ) { all_ready &= ( track->stream->codecpar->extradata != nullptr ); } if ( all_ready ) { int ret = avformat_write_header( mOutputContext, nullptr ); if (ret < 0) { fprintf(stderr, "Error occurred when opening output file: %s\n", averr(ret).c_str()); return; } else { gDebug() << "Avformat muxer ready"; mMuxerReady = true; Main::instance()->blackbox()->Enqueue( "Recorder:start", mRecordFilename ); } } else { av_packet_free(&pkt); return; } } av_packet_rescale_ts( pkt, (AVRational){ 1, 1000000 }, sample->track->stream->time_base ); gTrace() << "rescaled ts : " << pkt->pts << " " << pkt->dts << " " << pkt->duration << " " << sample->track->stream->time_base.num << "/" << sample->track->stream->time_base.den; int errwrite = av_interleaved_write_frame( mOutputContext, pkt ); // avio_flush( mOutputContext->pb ); // sync(); av_packet_free(&pkt); if ( errwrite < 0 ) { if ( errwrite == ENOSPC or errno == ENOSPC ) { Board::setDiskFull(); } } } bool RecorderAvformat::run() { mWriteMutex.lock(); while ( mPendingSamples.size() > 0 ) { PendingSample* sample = mPendingSamples.front(); mPendingSamples.pop_front(); mWriteMutex.unlock(); WriteSample( sample ); delete sample; mWriteMutex.lock(); } mWriteMutex.unlock(); mGyroMutex.lock(); while ( mPendingGyros.size() > 0 ) { PendingGyro* gyro = mPendingGyros.front(); mPendingGyros.pop_front(); mGyroMutex.unlock(); // fprintf( mGyroFile, "%llu,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f\n", gyro->t, gyro->gx, gyro->gy, gyro->gz, gyro->ax, gyro->ay, gyro->az ); fprintf( mGyroFile, "%llu,%.6f,%.6f,%.6f\n", gyro->t, gyro->gx, gyro->gy, gyro->gz ); mGyroMutex.lock(); } mGyroMutex.unlock(); mWriteTicks = Board::WaitTick( 1000 * 1000 / 300, mWriteTicks ); return not mStopWrite; } void RecorderAvformat::Start() { fDebug(); while ( mStopWrite ) { usleep( 1000 * 200 ); } mActiveMutex.lock(); if ( mActive ) { mActiveMutex.unlock(); return; } mActive = true; mActiveMutex.unlock(); uint32_t fileid = 0; DIR* dir; struct dirent* ent; if ( ( dir = opendir( mBaseDirectory.c_str() ) ) != nullptr ) { while ( ( ent = readdir( dir ) ) != nullptr ) { string file = string( ent->d_name ); if ( file.find( "record_" ) != file.npos ) { uint32_t id = std::atoi( file.substr( file.rfind( "_" ) + 1 ).c_str() ); if ( id >= fileid ) { fileid = id + 1; } } } closedir( dir ); } mRecordId = fileid; char filename[256]; sprintf( filename, (mBaseDirectory + "/record_%010u.mkv").c_str(), mRecordId ); mRecordFilename = std::string( filename ); avformat_alloc_output_context2( &mOutputContext, nullptr, nullptr, filename ); if ( !mOutputContext ) { gError() << "Failed to allocate avformat output context"; mActiveMutex.lock(); mActive = false; mActiveMutex.unlock(); return; } for ( auto* track : mTracks ) { if ( track->type == TrackTypeAudio ) { track->stream = avformat_new_stream( mOutputContext, nullptr ); track->stream->id = mOutputContext->nb_streams - 1; track->stream->time_base = (AVRational){ 1, 1000000 }; // track->stream->r_frame_rate = (AVRational){ 30, 1 }; track->stream->start_time = 0; track->stream->codecpar->codec_id = std::string(track->format) == "mp3" ? AV_CODEC_ID_MP3 : AV_CODEC_ID_PCM_S16LE; track->stream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; track->stream->codecpar->channels = track->channels; track->stream->codecpar->sample_rate = track->sample_rate; if ( std::string(track->format) == "mp3" ) { track->stream->codecpar->bit_rate = 320 * 1024; } track->stream->codecpar->codec_tag = 0; track->stream->codecpar->format = AV_SAMPLE_FMT_S16; track->stream->codecpar->extradata = nullptr; } else if ( track->type == TrackTypeVideo ) { track->stream = avformat_new_stream( mOutputContext, nullptr ); track->stream->id = mOutputContext->nb_streams - 1; track->stream->time_base = (AVRational){ 1, 1000000 }; // track->stream->avg_frame_rate = (AVRational){ 30, 1 }; track->stream->r_frame_rate = (AVRational){ 30, 1 }; track->stream->start_time = 0; track->stream->codecpar->codec_id = std::string(track->format) == "h264" ? AV_CODEC_ID_H264 : AV_CODEC_ID_MJPEG; track->stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; track->stream->codecpar->width = track->width; track->stream->codecpar->height = track->height; track->stream->codecpar->bit_rate = 0; track->stream->codecpar->codec_tag = 0; track->stream->codecpar->format = std::string(track->format) == "h264" ? AV_PIX_FMT_YUV420P : AV_PIX_FMT_RGB24; track->stream->codecpar->extradata = nullptr; } } av_dump_format( mOutputContext, 0, filename, 1 ); for ( auto* track : mTracks ) { printf("track %d stream_index : %d\n", track->type, track->stream->id ); } /* int ret = 0; if ( (ret = avio_open( &mOutputContext->pb, filename, AVIO_FLAG_WRITE) ) ) { gError() << "Could not open " << filename << " : " << averr(ret).c_str(); mActiveMutex.lock(); mActive = false; mActiveMutex.unlock(); return; } */ gTrace() << "A"; mOutputFile = fopen( filename, "wb+" ); if ( !mOutputFile ) { gError() << "Could not open " << filename << " : " << strerror(errno); mActiveMutex.lock(); mActive = false; mActiveMutex.unlock(); return; } gTrace() << "B"; mOutputContext->pb = avio_alloc_context( mOutputBuffer, sizeof(mOutputBuffer), 1, this, nullptr, []( void* thiz, uint8_t* buf, int sz ) { return (int)fwrite( buf, 1, sz, static_cast<RecorderAvformat*>(thiz)->mOutputFile ); }, nullptr ); gTrace() << "C"; if ( !mOutputContext->pb ) { gError() << "Could not allocate AVFormat output context"; mActiveMutex.lock(); mActive = false; mActiveMutex.unlock(); return; } gTrace() << "D"; sprintf( filename, (mBaseDirectory + "/record_%010u.gcsv").c_str(), mRecordId ); mGyroFile = fopen( filename, "wb+" ); if ( mGyroFile ) { fprintf( mGyroFile, "GYROFLOW IMU LOG\n" ); fprintf( mGyroFile, "version,1.3\n" ); fprintf( mGyroFile, "id,bcflight\n" ); fprintf( mGyroFile, "orientation,ZYx\n" ); // TODO : use IMU orientation fprintf( mGyroFile, "note,development_test\n" ); fprintf( mGyroFile, "fwversion,FIRMWARE_0.1.0\n" ); // fprintf( mGyroFile, "timestamp,1644159993\n" ); // current datetime fprintf( mGyroFile, "vendor,bcflight\n" ); fprintf( mGyroFile, "videofilename,record_%010u.mkv\n", mRecordId ); fprintf( mGyroFile, "lensprofile,Raspberry Pi Foundation/Raspberry Pi Foundation_Camera Module 3 (Sony IMX708)_Stock wide (120°)_libcamera native 1080p (2304x1296-pBAA)_1080p_16by9_1920x1080-30.00fps.json\n" ); fprintf( mGyroFile, "lens_info,wide\n" ); fprintf( mGyroFile, "frame_readout_time,%.6f\n", 1.0f / 30.0f ); fprintf( mGyroFile, "frame_readout_direction,0\n" ); fprintf( mGyroFile, "tscale,0.000001\n" ); fprintf( mGyroFile, "gscale,%.6f\n", M_PI / 180.0f ); // BCFlight is in Deg, GCSV is in Rad fprintf( mGyroFile, "ascale,1.0\n" ); // fprintf( mGyroFile, "t,gx,gy,gz,ax,ay,az\n" ); fprintf( mGyroFile, "t,gx,gy,gz\n" ); fprintf( mGyroFile, "0,0.000000,0.000000,0.000000\n" ); } gTrace() << "E"; if ( not mConsumerRegistered ) { mConsumerRegistered = true; Main::instance()->imu()->registerConsumer( [this](uint64_t t, const Vector3f& g, const Vector3f& a) { // fDebug( t, g.x, g.y, g.z ); WriteGyro( t, g, a ); }); } gTrace() << "F"; mMuxerReady = false; mRecordStartTick = 0; mRecordStartSystemTick = 0; Thread::Start(); } void RecorderAvformat::Stop() { if ( not recording() or not mActive ) { mWriteMutex.unlock(); mGyroMutex.unlock(); return; } mStopWrite = true; Thread::Stop(); Thread::Join(); gTrace() << "A"; mWriteMutex.lock(); while ( mPendingSamples.size() > 0 ) { PendingSample* sample = mPendingSamples.front(); mPendingSamples.pop_front(); mWriteMutex.unlock(); WriteSample( sample ); delete sample; mWriteMutex.lock(); } mWriteMutex.unlock(); gTrace() << "B"; Main::instance()->blackbox()->Enqueue( "Recorder:stop", mRecordFilename ); av_write_trailer( mOutputContext ); avio_flush( mOutputContext->pb ); // avio_closep( &mOutputContext->pb ); avio_context_free( &mOutputContext->pb ); avformat_free_context( mOutputContext ); mOutputContext = nullptr; for ( auto* track : mTracks ) { track->stream = nullptr; } mMuxerReady = false; mRecordStartTick = 0; mRecordStartSystemTick = 0; mGyroMutex.lock(); while ( mPendingGyros.size() > 0 ) { PendingGyro* gyro = mPendingGyros.front(); mPendingGyros.pop_front(); mGyroMutex.unlock(); // fprintf( mGyroFile, "%llu,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f\n", gyro->t, gyro->gx, gyro->gy, gyro->gz, gyro->ax, gyro->ay, gyro->az ); fprintf( mGyroFile, "%llu,%.6f,%.6f,%.6f\n", gyro->t, gyro->gx, gyro->gy, gyro->gz ); mGyroMutex.lock(); } mGyroMutex.unlock(); if ( mGyroFile ) { fclose( mGyroFile ); mGyroFile = nullptr; } mActiveMutex.lock(); mStopWrite = false; mActive = false; mActiveMutex.unlock(); } bool RecorderAvformat::recording() { return Thread::running(); } uint32_t RecorderAvformat::AddVideoTrack( const std::string& format, uint32_t width, uint32_t height, uint32_t average_fps, const std::string& extension ) { Track* track = (Track*)malloc( sizeof(Track) ); memset( track, 0, sizeof(Track) ); track->type = TrackTypeVideo; strcpy( track->format, format.c_str() ); track->width = width; track->height = height; track->average_fps = average_fps; track->id = mTracks.size(); mTracks.emplace_back( track ); return track->id; } uint32_t RecorderAvformat::AddAudioTrack( const std::string& format, uint32_t channels, uint32_t sample_rate, const std::string& extension ) { Track* track = (Track*)malloc( sizeof(Track) ); memset( track, 0, sizeof(Track) ); track->type = TrackTypeAudio; strcpy( track->format, format.c_str() ); track->channels = channels; track->sample_rate = sample_rate; track->id = mTracks.size(); mTracks.emplace_back( track ); return track->id; } void RecorderAvformat::WriteSample( uint32_t track_id, uint64_t record_time_us, void* buf, uint32_t buflen, bool keyframe ) { // fTrace( track_id, record_time_us, buf, buflen, keyframe ); Track* track = mTracks.at(track_id); if ( not track ) { return; } if ( mVideoHeader.size() == 0 and track->type == TrackTypeVideo ) { mVideoHeader.insert( mVideoHeader.end(), (uint8_t*)buf, (uint8_t*)buf + std::min( buflen, 50U ) ); } if ( mAudioHeader.size() == 0 and track->type == TrackTypeAudio ) { mAudioHeader.insert( mAudioHeader.end(), (uint8_t*)buf, (uint8_t*)buf + std::min( buflen, 15U ) ); } if ( not recording() or mStopWrite ) { return; } if ( mRecordStartTick == 0 ) { if ( track->type == TrackTypeVideo ) { mRecordStartTick = record_time_us; mRecordStartSystemTick = Board::GetTicks(); } else { // Wait for the video stream to start first return; } } if ( track->type == TrackTypeVideo ) { record_time_us -= mRecordStartTick; } if ( track->type == TrackTypeAudio ) { record_time_us -= mRecordStartSystemTick; } PendingSample* sample = new PendingSample; sample->track = track; sample->record_time_us = record_time_us; sample->buf = new uint8_t[buflen]; sample->buflen = buflen; sample->keyframe = keyframe; memcpy( sample->buf, buf, buflen ); mWriteMutex.lock(); mPendingSamples.emplace_back( sample ); mWriteMutex.unlock(); } void RecorderAvformat::WriteGyro( uint64_t record_time_us, const Vector3f& gyro, const Vector3f& accel ) { if ( not mGyroFile or record_time_us < mRecordStartSystemTick or mRecordStartSystemTick == 0 or not recording() or mStopWrite ) { return; } PendingGyro* g = new PendingGyro(); g->t = record_time_us - mRecordStartSystemTick; g->gx = gyro.x; g->gy = gyro.y; g->gz = gyro.z; g->ax = accel.x; g->ay = accel.y; g->az = accel.z; mGyroMutex.lock(); mPendingGyros.emplace_back( g ); mGyroMutex.unlock(); }
14,090
C++
.cpp
402
32.405473
213
0.675471
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,723
HUD.cpp
dridri_bcflight/flight/video/HUD.cpp
#if ( BUILD_HUD == 1 ) #include <Main.h> #include <RendererHUDNeo.h> #include "Camera.h" #include "HUD.h" #include <GLContext.h> #include <Stabilizer.h> #include <IMU.h> #include <Link.h> #include <Config.h> #include <Sensor.h> #include <peripherals/SmartAudio.h> HUD::HUD() : Thread( "HUD" ) , mGLContext( nullptr ) , mRendererHUD( nullptr ) , mNightMode( false ) , mHUDFramerate( 30 ) , mWaitTicks( 0 ) , mShowFrequency( false ) , mAccelerationAccum( 0.0f ) , mFrameTop( 10 ) , mFrameBottom( 10 ) , mFrameLeft( 20 ) , mFrameRight( 20 ) , mRatio( 1.0f ) , mFontSize( 60 ) , mCorrection( false ) , mStereo( false ) , mStereoStrength( 0.004f ) , mReady( false ) , mVTX( nullptr ) { mGLContext = GLContext::instance(); Start(); } HUD::~HUD() { } bool HUD::run() { if ( not mReady ) { mReady = true; setFrequency( mHUDFramerate ); mVTX = Main::instance()->config()->Object<SmartAudio>( "vtx" ); mGLContext->runOnGLThread( [this]() { Config* config = Main::instance()->config(); Vector4i render_region = Vector4i( mFrameTop, mFrameBottom, mFrameLeft, mFrameRight ); mRendererHUD = new RendererHUDNeo( mGLContext->glWidth(), mGLContext->glHeight(), mRatio, mFontSize, render_region, mCorrection ); mRendererHUD->setStereo( mStereo ); mRendererHUD->set3DStrength( mStereoStrength ); mRendererHUD->setStereo( false ); mRendererHUD->set3DStrength( 0.0f ); }, true ); mGLContext->addLayer( [this]() { mRendererHUD->PreRender(); mRendererHUD->Render( &mDroneStats, 0.0f, &mVideoStats, &mLinkStats ); mImagesMutex.lock(); for ( std::pair< uintptr_t, Image > image : mImages ) { Image img = image.second; mRendererHUD->RenderImage( mFrameLeft + img.x, mFrameTop + img.y, img.width, img.height, img.img ); } mImagesMutex.unlock(); if ( false ) { uint32_t time = Board::GetTicks() / 1000; uint32_t minuts = time / ( 1000 * 60 ); uint32_t seconds = ( time / 1000 ) % 60; uint32_t ms = time % 1000; char txt[256]; sprintf( txt, "%02d:%02d:%03d", minuts, seconds, ms ); mRendererHUD->RenderText( 200, 200, txt, 0xFFFFFFFF, 4.0f, RendererHUD::TextAlignment::CENTER ); } }); } if ( frequency() != mHUDFramerate ) { setFrequency( mHUDFramerate ); } Controller* controller = Main::instance()->controller(); Stabilizer* stabilizer = Main::instance()->stabilizer(); IMU* imu = Main::instance()->imu(); PowerThread* powerThread = Main::instance()->powerThread(); Camera* camera = Main::instance()->camera(); mFrameRate = min( camera ? camera->framerate() : 0, mGLContext->displayFrameRate() ); if ( mNightMode != mRendererHUD->nightMode() ) { mRendererHUD->setNightMode( mNightMode ); } DroneStats dronestats; LinkStats linkStats; VideoStats videoStats; dronestats.username = Main::instance()->username(); dronestats.messages = Board::messages(); dronestats.blackBoxId = Main::instance()->blackbox()->id(); dronestats.cpuUsage = Board::CPULoad(); dronestats.memUsage = Board::MemoryUsage(); if ( controller and stabilizer ) { dronestats.armed = stabilizer->armed(); dronestats.mode = (DroneMode)stabilizer->mode(); dronestats.ping = controller->ping(); dronestats.thrust = stabilizer->thrust(); } if ( imu ) { mAccelerationAccum = ( mAccelerationAccum * 0.995f + imu->acceleration().length() * 0.005f ); dronestats.acceleration = mAccelerationAccum; dronestats.rpy = imu->RPY(); if ( Sensor::GPSes().size() > 0 ) { dronestats.gpsLocation = imu->gpsLocation(); dronestats.gpsSpeed = imu->gpsSpeed(); dronestats.gpsSatellitesSeen = imu->gpsSatellitesSeen(); dronestats.gpsSatellitesUsed = imu->gpsSatellitesUsed(); } else { dronestats.gpsSpeed = NAN; } } if ( powerThread ) { dronestats.batteryLevel = powerThread->BatteryLevel(); dronestats.batteryVoltage = powerThread->VBat(); dronestats.batteryTotalCurrent = (uint32_t)( powerThread->CurrentTotal() * 1000 ); } if ( controller and controller->link() ) { linkStats.qual = controller->link()->RxQuality(); linkStats.level = controller->link()->RxLevel(); linkStats.noise = 0; linkStats.channel = ( mShowFrequency ? controller->link()->Frequency() : controller->link()->Channel() ); linkStats.source = 0; } if ( camera ) { videoStats.width = (int)camera->width(); videoStats.height = (int)camera->height(); videoStats.fps = (int)camera->framerate(); strncpy( videoStats.whitebalance, camera->whiteBalance().c_str(), sizeof(videoStats.whitebalance) ); // strncpy( video_stats.whitebalance, camera->whiteBalance().c_str(), 32 ); // strncpy( video_stats.exposure, camera->exposureMode().c_str(), 32 ); // video_stats.photo_id = camera->getLastPictureID(); } if ( mVTX ) { videoStats.vtxPower = (int8_t)mVTX->getPower(); videoStats.vtxPowerDbm = mVTX->getPowerDbm(); videoStats.vtxFrequency = mVTX->getFrequency(); videoStats.vtxChannel = mVTX->getChannel(); strncpy( videoStats.vtxBand, mVTX->getBandName().c_str(), sizeof(videoStats.vtxBand) ); } mDroneStats = dronestats; mLinkStats = linkStats; memcpy( &mVideoStats, &videoStats, sizeof(VideoStats) ); return true; } uintptr_t HUD::LoadImage( const std::string& path ) { uintptr_t ret = 0; mGLContext->runOnGLThread( [this, &ret, path]() { ret = mRendererHUD->LoadImage( path ); }, true); return ret; } void HUD::ShowImage( int32_t x, int32_t y, uint32_t w, uint32_t h, const uintptr_t img ) { mImagesMutex.lock(); if ( mImages.find(img) == mImages.end() ) { Image struc = { img, x, y, w, h }; mImages.insert( std::make_pair( img, struc ) ); } mImagesMutex.unlock(); } void HUD::HideImage( const uintptr_t img ) { mImagesMutex.lock(); if ( mImages.find(img) != mImages.end() ) { mImages.erase( img ); } mImagesMutex.unlock(); } void HUD::AddLayer( const std::function<void()>& func ) { mGLContext->addLayer( func ); } void HUD::PrintText( int32_t x, int32_t y, const std::string& text, uint32_t color, TextAlignment halign, TextAlignment valign ) { mRendererHUD->RenderText( x, y, text, color, 0.75f, (RendererHUD::TextAlignment)halign, (RendererHUD::TextAlignment)valign ); } #endif // ( BUILD_HUD == 1 )
6,167
C++
.cpp
180
31.672222
133
0.69869
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,724
DRMFrameBuffer.cpp
dridri_bcflight/flight/video/DRMFrameBuffer.cpp
#include <xf86drm.h> #include <xf86drmMode.h> #include <string.h> #include <string> #include "DRMFrameBuffer.h" #include "Debug.h" DRMFrameBuffer::DRMFrameBuffer( uint32_t width, uint32_t height, uint32_t stride, uint32_t format, uint32_t bufferObjectHandle, int dmaFd ) : mWidth( width ) , mHeight( height ) , mDmaFd( dmaFd ) , mBufferObjectHandle( bufferObjectHandle ) , mFrameBufferHandle( 0 ) { fDebug( width, height, stride, format, bufferObjectHandle, dmaFd ); if ( !bufferObjectHandle and dmaFd ) { if ( drmPrimeFDToHandle( drmFd(), dmaFd, &mBufferObjectHandle ) ) { gError() << "drmPrimeFDToHandle failed for fd " << dmaFd << " : " << strerror(errno); } } // uint32_t offsets[4] = { 0 }; // uint32_t pitches[4] = { 0 }; // uint32_t bo_handles[4] = { 0 }; uint32_t offsets[4] = { 0, stride * height, stride * height + (stride / 2) * (height / 2) }; uint32_t pitches[4] = { stride, stride / 2, stride / 2 }; uint32_t bo_handles[4] = { mBufferObjectHandle, mBufferObjectHandle, mBufferObjectHandle }; if ( format == DRM_FORMAT_YUV420 ) { offsets[1] = stride * height; offsets[2] = stride * height + (stride / 2) * (height / 2); pitches[0] = stride; pitches[1] = stride / 2; pitches[2] = stride / 2; bo_handles[0] = mBufferObjectHandle; bo_handles[1] = mBufferObjectHandle; bo_handles[2] = mBufferObjectHandle; } else if ( format == DRM_FORMAT_ARGB8888 ) { pitches[0] = stride; pitches[1] = stride; pitches[2] = stride; pitches[3] = stride; bo_handles[0] = mBufferObjectHandle; bo_handles[1] = mBufferObjectHandle; bo_handles[2] = mBufferObjectHandle; bo_handles[3] = mBufferObjectHandle; } if ( drmModeAddFB2( drmFd(), width, height, format, bo_handles, pitches, offsets, &mFrameBufferHandle, 0 ) ) { gError() << "drmModeAddFB2 failed : " << strerror(errno); } } DRMFrameBuffer::~DRMFrameBuffer() { } const uint32_t DRMFrameBuffer::handle() const { return mFrameBufferHandle; } const uint32_t DRMFrameBuffer::width() const { return mWidth; } const uint32_t DRMFrameBuffer::height() const { return mHeight; }
2,112
C++
.cpp
71
27.352113
139
0.69688
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,725
Multicopter.cpp
dridri_bcflight/flight/frames/Multicopter.cpp
#include <Debug.h> #include <Config.h> #include <Controller.h> #include "IMU.h" #include <motors/BrushlessPWM.h> #include <motors/OneShot125.h> #include <Servo.h> #include <Board.h> #include "Multicopter.h" Multicopter::Multicopter() : Frame() , mMaxSpeed( 1.0f ) , mAirModeTrigger( 1.0f ) , mAirModeSpeed( 0.0f ) // , mAirModeTrigger( config->Number( "frame.air_mode.trigger", 0.35f ) ) // , mAirModeSpeed( config->Number( "frame.air_mode.speed", 0.15f ) ) { /* float maxspeed = config->Number( "frame.max_speed", 1.0f ); if ( maxspeed > 0.0f and maxspeed <= 1.0f ) { mMaxSpeed = maxspeed; } int motors_count = config->ArrayLength( "frame.motors" ); if ( motors_count < 3 ) { gDebug() << "ERROR : There should be at least 3 configured motors !"; return; } mMotors.resize( motors_count ); mPIDMultipliers.resize( motors_count ); mStabSpeeds.resize( motors_count ); for ( uint32_t i = 0; i < mMotors.size(); i++ ) { string object = "frame.motors[" + to_string(i+1) + "]"; mMotors[i] = Motor::Instanciate( config->String( object + ".motor_type", "PWM" ), config, object ); mPIDMultipliers[i].x = config->Number( object + ".pid_vector.x" ); mPIDMultipliers[i].y = config->Number( object + ".pid_vector.y" ); mPIDMultipliers[i].z = config->Number( object + ".pid_vector.z" ); if ( mPIDMultipliers[i].length() == 0.0f ) { gDebug() << "WARNING : PID multipliers for motor " << (i+1) << " seem to be not set !"; } mMotors[i]->Disable(); } */ } Multicopter::~Multicopter() { } void Multicopter::Arm() { fDebug(); Frame::Arm(); char stmp[256] = "\""; uint32_t spos = 1; if ( mStabSpeeds.size() < mMotors.size() ) { mStabSpeeds.resize( mMotors.size() ); } for ( uint32_t i = 0; i < mMotors.size(); i++ ) { mStabSpeeds[i] = 0.0f; mMotors[i]->Arm(); mMotors[i]->setSpeed( 0.0f, true ); spos += sprintf( stmp + spos, "%.4f,", mMotors[i]->speed() ); } mArmed = true; Main::instance()->blackbox()->Enqueue( "Multicopter:motors", string(stmp) + "\"" ); } void Multicopter::Disarm() { fDebug(); char stmp[256] = "\""; uint32_t spos = 1; mAirMode = false; if ( mStabSpeeds.size() < mMotors.size() ) { mStabSpeeds.resize( mMotors.size() ); } for ( uint32_t i = 0; i < mMotors.size(); i++ ) { mStabSpeeds[i] = 0.0f; mMotors[i]->setSpeed( 0.0f, true ); } for ( uint32_t i = 0; i < mMotors.size(); i++ ) { mMotors[i]->Disarm(); spos += sprintf( stmp + spos, "%.4f,", mMotors[i]->speed() ); } mArmed = false; Main::instance()->blackbox()->Enqueue( "Multicopter:motors", string(stmp) + "\"" ); } void Multicopter::WarmUp() { fDebug(); } bool Multicopter::Stabilize( const Vector3f& pid_output, float thrust ) { if ( not mArmed ) { return false; } if ( thrust >= mAirModeTrigger ) { if ( not mAirMode ) { gDebug() << "Now in air mode"; } mAirMode = true; } if ( mAirMode or thrust >= 0.0f ) { float expected_min = ( mAirMode ? mAirModeSpeed : 0.0f ); float expected_max = mMaxSpeed; float overall_min = 1e6f; float overall_max = -1e6f; for ( uint32_t i = 0; i < mMotors.size(); i++ ) { mStabSpeeds[i] = ( mMatrix[i].xyz() & pid_output ) + mMatrix[i].w * thrust; overall_min = std::min( overall_min, mStabSpeeds[i] ); overall_max = std::max( overall_max, mStabSpeeds[i] ); } if ( overall_min < expected_min ) { for ( uint32_t i = 0; i < mMotors.size(); i++ ) { mStabSpeeds[i] += expected_min - overall_min; } overall_max += expected_min - overall_min; overall_min = expected_min; } float stab_multiplier = 1.0f; if ( overall_max > expected_max ) { stab_multiplier = ( expected_max ) / ( std::max(1.0f, overall_max) - std::min(0.0f, overall_min) ); } for ( uint32_t i = 0; i < mMotors.size(); i++ ) { float v = mStabSpeeds[i]; mStabSpeeds[i] = expected_min + ( mStabSpeeds[i] - expected_min ) * stab_multiplier; mMotors[i]->setSpeed( mStabSpeeds[i], ( i >= mMotors.size() - 1 ) ); } if ( Main::instance()->blackbox() ) { char stmp[256] = "\""; uint32_t spos = 1; for ( uint32_t i = 0; i < mMotors.size(); i++ ) { spos += sprintf( stmp + spos, "%.4f,", mMotors[i]->speed() ); } Main::instance()->blackbox()->Enqueue( "Multicopter:motors", string(stmp) + "\"" ); } return true; } for ( uint32_t i = 0; i < mMotors.size(); i++ ) { mMotors[i]->setSpeed( 0.0f, ( i >= mMotors.size() - 1 ) ); } return false; }
4,410
C++
.cpp
140
28.842857
102
0.623613
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,726
Frame.cpp
dridri_bcflight/flight/frames/Frame.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <unistd.h> #include <Debug.h> #include "Frame.h" #include <Config.h> map< string, function< Frame* ( Config* ) > > Frame::mKnownFrames; Frame::Frame() : mMotors( vector< Motor* >() ) , mArmed( false ) , mAirMode( false ) , mMotorsBeep( false ) , mMotorBeepMode( 0 ) , mMotorsBeepThread( new HookThread< Frame >( "motors_beep", this, &Frame::MotorsBeepRun ) ) { mMotorsBeepThread->setFrequency( 1 ); } Frame::~Frame() { } void Frame::MotorTest( uint32_t id ) { gDebug() << "Test motor : " << id; if (mMotors.size() <= id) { gDebug() << "Out of range abort"; } Motor* m = mMotors[id]; m->setSpeed( 0.0f, true ); usleep(1 * 1000 * 1000); m->Disarm(); usleep(1 * 1000 * 1000); m->setSpeed( 0.0f, true ); usleep(1 * 1000 * 1000); m->setSpeed(0.05f, true); gDebug() << "Waiting for 5 seconds"; usleep(5 * 1000 * 1000); m->Disarm(); gDebug() << "Disarm ESC"; } void Frame::MotorsBeep( bool enabled ) { mMotorsBeep = enabled; if ( enabled and not mMotorsBeepThread->running() ) { mMotorBeepMode = 0; mMotorsBeepThread->Start(); } else if ( not enabled and mMotorsBeepThread->running() ) { mMotorsBeepThread->Stop(); } } bool Frame::MotorsBeepRun() { for ( Motor* m : mMotors ) { m->Beep( mMotorBeepMode ); } usleep( 260 * 1000 ); for ( Motor* m : mMotors ) { m->Disarm(); } usleep( 1000 * 1000 ); mMotorBeepMode = ( mMotorBeepMode + 1 ) % 2; return true; } void Frame::CalibrateESCs() { fDebug(); gDebug() << "Disabling ESCs"; for ( Motor* m : mMotors ) { m->Disable(); } gDebug() << "Waiting 10 seconds..."; usleep( 10 * 1000 * 1000 ); gDebug() << "Setting maximal speed"; for ( Motor* m : mMotors ) { m->setSpeed( 1.0f, true ); } gDebug() << "Waiting 8 seconds..."; usleep( 8 * 1000 * 1000 ); gDebug() << "Setting minimal speed"; for ( Motor* m : mMotors ) { m->setSpeed( 0.0f, true ); } gDebug() << "Waiting 8 seconds..."; usleep( 8 * 1000 * 1000 ); gDebug() << "Disarm all ESCs"; for ( Motor* m : mMotors ) { m->Disarm(); } } void Frame::Arm() { if ( mMotorsBeep ) { mMotorsBeepThread->Stop(); mMotorsBeepThread->Join(); mMotorsBeep = false; usleep( 500 * 1000 ); } } bool Frame::armed() const { return mArmed; } bool Frame::airMode() const { return mAirMode; } vector< Motor* >* Frame::motors() { return &mMotors; } void Frame::RegisterFrame( const string& name, function< Frame* ( Config* ) > instanciate ) { mKnownFrames[ name ] = instanciate; }
3,189
C++
.cpp
128
22.828125
93
0.671622
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,727
MultiLink.cpp
dridri_bcflight/flight/links/MultiLink.cpp
#ifdef BUILD_MultiLink #include <../links/Link.h> #include <../links/Link.h> #include <../links/Link.h> /* * BCFlight * Copyright (C) 2017 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include "MultiLink.h" #include <Main.h> #include <Config.h> int MultiLink::flight_register( Main* main ) { RegisterLink( "MultiLink", &MultiLink::Instanciate ); return 0; } Link* MultiLink::Instanciate( Config* config, const string& lua_object ) { int senders_count = config->ArrayLength( lua_object + ".senders" ); int receivers_count = config->ArrayLength( lua_object + ".receivers" ); int read_timeout = config->Integer( lua_object + ".read_timeout" ); if ( senders_count < 1 and receivers_count < 0 ) { gDebug() << "WARNING : There should be at least 1 sender or receiver, cannot create Link !"; return nullptr; } list<Link*> senders; for ( int i = 0; i < senders_count; i++ ) { senders.emplace_back( Link::Create( config, lua_object + ".senders[" + to_string(i+1) + "]" ) ); } list<Link*> receivers; for ( int i = 0; i < receivers_count; i++ ) { receivers.emplace_back( Link::Create( config, lua_object + ".receivers[" + to_string(i+1) + "]" ) ); } MultiLink* ret = new MultiLink( senders, receivers ); ret->setReadTimeout( read_timeout ); return ret; } MultiLink::MultiLink( list<Link*> senders, list<Link*> receivers ) : Link() , mBlocking( true ) , mReadTimeout( 2000 ) , mSenders( senders ) , mReceivers( receivers ) { for ( Link* link : mReceivers ) { link->setBlocking( true ); } } MultiLink::MultiLink( std::initializer_list<Link*> senders, std::initializer_list<Link*> receivers ) : MultiLink( static_cast<list<Link*>>(senders), static_cast<list<Link*>>(receivers) ) { } MultiLink::~MultiLink() { } int MultiLink::Connect() { int ret = 0; for ( Link* link : mSenders ) { if ( link->Connect() != 0 ) { ret = 1; } } for ( Link* link : mReceivers ) { if ( link->Connect() != 0 ) { ret = 1; } } mConnected = ( not ret ); return ret; } int MultiLink::setBlocking( bool blocking ) { mBlocking = blocking; return 0; } void MultiLink::setReadTimeout( uint32_t timeout ) { mReadTimeout = timeout; } void MultiLink::setRetriesCount( int retries ) { for ( Link* link : mSenders ) { link->setRetriesCount( retries ); } } int MultiLink::retriesCount() const { return mSenders.front()->retriesCount(); } int32_t MultiLink::Channel() { return mReceivers.front()->Channel(); } int32_t MultiLink::Frequency() { return mReceivers.front()->Frequency(); } int32_t MultiLink::RxQuality() { return mReceivers.front()->RxQuality(); } int32_t MultiLink::RxLevel() { return mReceivers.front()->RxLevel(); } uint32_t MultiLink::fullReadSpeed() { return 0; } SyncReturn MultiLink::Write( const void* buf, uint32_t len, bool ack, int32_t timeout ) { int32_t ret = 0; for ( Link* link : mSenders ) { int32_t r = link->Write( buf, len, ack, timeout ); if ( r > ret ) { ret = r; } } return ret; } SyncReturn MultiLink::Read( void* buf, uint32_t len, int32_t timeout ) { int ret = 0; int32_t hopping_timeout = 50; uint32_t time_base = Board::GetTicks(); if ( mReceivers.size() == 0 ) { return -1; } // if ( timeout > 0 ) { // hopping_timeout = timeout / mReceivers.size(); // } if ( timeout == 0 ) { timeout = mReadTimeout; } do { // First, try to receive using the first receiver Link* front = mReceivers.front(); ret = front->Read( buf, len, hopping_timeout ); // If good, then return now if ( ret > 0 ) { return ret; } else if ( ret == TIMEOUT ) { // gDebug() << front->Frequency() << " front timed out"; } // Else, try with the others until one is responding for ( list<Link*>::iterator it = mReceivers.begin(); it != mReceivers.end(); it++ ) { if ( (*it) != front ) { ret = (*it)->Read( buf, len, hopping_timeout ); // If good, put this receiver in front, and return now if ( ret > 0 ) { Link* tmp = mReceivers.front(); mReceivers.front() = *it; *it = tmp; return ret; } else if ( ret == TIMEOUT ) { // gDebug() << (*it)->Frequency() << " timed out"; } else { // gDebug() << (*it)->Frequency() << " error " << ret; } } } if ( Board::GetTicks() - time_base >= (uint64_t)timeout * 1000llu ) { return TIMEOUT; } } while ( mBlocking ); return ret; } #endif // BUILD_MultiLink
5,020
C++
.cpp
182
25.247253
102
0.666667
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,728
SX127x.cpp
dridri_bcflight/flight/links/SX127x.cpp
#include <unistd.h> #include "SX127x.h" #include "SX127xRegs.h" #include "SX127xRegs-LoRa.h" #include <Config.h> #include <Debug.h> #include <SPI.h> #include <GPIO.h> #include <Board.h> #include <cmath> #define min( a, b ) ( ( (a) < (b) ) ? (a) : (b) ) #define max( a, b ) ( ( (a) > (b) ) ? (a) : (b) ) #define TICKS ( Board::GetTicks() / 1000 ) #define TIMEOUT_MS 1000 // 1000 ms #define XTAL_FREQ 32000000 #define FREQ_STEP 61.03515625f #define PACKET_SIZE 32 // #define MAX_BLOCK_ID 256 #define MAX_BLOCK_ID 128 // TODO : LoRa see https://github.com/chandrawi/LoRaRF-Python/blob/main/LoRaRF/SX127x.py static uint8_t GetFskBandwidthRegValue( uint32_t bandwidth ); static const char* GetRegName( uint8_t reg ); typedef struct FskBandwidth_t { uint32_t bandwidth; uint8_t RegValue; } FskBandwidth_t; static const FskBandwidth_t FskBandwidths[] = { { 2600 , 0x17 }, { 3100 , 0x0F }, { 3900 , 0x07 }, { 5200 , 0x16 }, { 6300 , 0x0E }, { 7800 , 0x06 }, { 10400 , 0x15 }, { 12500 , 0x0D }, { 15600 , 0x05 }, { 20800 , 0x14 }, { 25000 , 0x0C }, { 31300 , 0x04 }, { 41700 , 0x13 }, { 50000 , 0x0B }, { 62500 , 0x03 }, { 83333 , 0x12 }, { 100000, 0x0A }, { 125000, 0x02 }, { 166700, 0x11 }, { 200000, 0x09 }, { 250000, 0x01 }, { 300000, 0x00 }, // Invalid Badwidth }; const struct { const char* name; uint8_t reg; } regnames[] = { { "REG_FIFO" , 0x00 }, { "REG_OPMODE" , 0x01 }, { "REG_BITRATEMSB" , 0x02 }, { "REG_BITRATELSB" , 0x03 }, { "REG_FDEVMSB" , 0x04 }, { "REG_FDEVLSB" , 0x05 }, { "REG_FRFMSB" , 0x06 }, { "REG_FRFMID" , 0x07 }, { "REG_FRFLSB" , 0x08 }, { "REG_PACONFIG" , 0x09 }, { "REG_PARAMP" , 0x0A }, { "REG_OCP" , 0x0B }, { "REG_LNA" , 0x0C }, { "REG_RXCONFIG" , 0x0D }, { "REG_RSSICONFIG" , 0x0E }, { "REG_RSSICOLLISION" , 0x0F }, { "REG_RSSITHRESH" , 0x10 }, { "REG_RSSIVALUE" , 0x11 }, { "REG_RXBW" , 0x12 }, { "REG_AFCBW" , 0x13 }, { "REG_OOKPEAK" , 0x14 }, { "REG_OOKFIX" , 0x15 }, { "REG_OOKAVG" , 0x16 }, { "REG_RES17" , 0x17 }, { "REG_RES18" , 0x18 }, { "REG_RES19" , 0x19 }, { "REG_AFCFEI" , 0x1A }, { "REG_AFCMSB" , 0x1B }, { "REG_AFCLSB" , 0x1C }, { "REG_FEIMSB" , 0x1D }, { "REG_FEILSB" , 0x1E }, { "REG_PREAMBLEDETECT" , 0x1F }, { "REG_RXTIMEOUT1" , 0x20 }, { "REG_RXTIMEOUT2" , 0x21 }, { "REG_RXTIMEOUT3" , 0x22 }, { "REG_RXDELAY" , 0x23 }, { "REG_OSC" , 0x24 }, { "REG_PREAMBLEMSB" , 0x25 }, { "REG_PREAMBLELSB" , 0x26 }, { "REG_SYNCCONFIG" , 0x27 }, { "REG_SYNCVALUE1" , 0x28 }, { "REG_SYNCVALUE2" , 0x29 }, { "REG_SYNCVALUE3" , 0x2A }, { "REG_SYNCVALUE4" , 0x2B }, { "REG_SYNCVALUE5" , 0x2C }, { "REG_SYNCVALUE6" , 0x2D }, { "REG_SYNCVALUE7" , 0x2E }, { "REG_SYNCVALUE8" , 0x2F }, { "REG_PACKETCONFIG1" , 0x30 }, { "REG_PACKETCONFIG2" , 0x31 }, { "REG_PAYLOADLENGTH" , 0x32 }, { "REG_NODEADRS" , 0x33 }, { "REG_BROADCASTADRS" , 0x34 }, { "REG_FIFOTHRESH" , 0x35 }, { "REG_SEQCONFIG1" , 0x36 }, { "REG_SEQCONFIG2" , 0x37 }, { "REG_TIMERRESOL" , 0x38 }, { "REG_TIMER1COEF" , 0x39 }, { "REG_TIMER2COEF" , 0x3A }, { "REG_IMAGECAL" , 0x3B }, { "REG_TEMP" , 0x3C }, { "REG_LOWBAT" , 0x3D }, { "REG_IRQFLAGS1" , 0x3E }, { "REG_IRQFLAGS2" , 0x3F }, { "REG_DIOMAPPING1" , 0x40 }, { "REG_DIOMAPPING2" , 0x41 }, { "REG_VERSION" , 0x42 }, { "REG_PLLHOP" , 0x44 }, { "REG_TCXO" , 0x4B }, { "REG_PADAC" , 0x4D }, { "REG_FORMERTEMP" , 0x5B }, { "REG_BITRATEFRAC" , 0x5D }, { "REG_AGCREF" , 0x61 }, { "REG_AGCTHRESH1" , 0x62 }, { "REG_AGCTHRESH2" , 0x63 }, { "REG_AGCTHRESH3" , 0x64 }, { "REG_PLL" , 0x70 }, { "unk" , 0xFF }, }; static uint8_t crc8( const uint8_t* buf, uint32_t len ); SX127x::SX127x() : Link() , mSPI( nullptr ) , mReady( false ) , mDevice( "/dev/spidev0.0" ) , mResetPin( -1 ) , mTXPin( -1 ) , mRXPin( -1 ) , mIRQPin( -1 ) , mLedPin( -1 ) , mBlocking( true ) , mDropBroken( true ) , mEnableTCXO( false ) , mModem( FSK ) , mFrequency( 433000000 ) , mInputPort( 0 ) , mOutputPort( 1 ) , mRetries( 1 ) , mReadTimeout( 1000 ) , mBitrate( 76800 ) , mBandwidth( 250000 ) , mBandwidthAfc( 500000 ) , mFdev( 200000 ) , mRSSI( 0 ) , mRxQuality( 0 ) , mPerfTicks( 0 ) , mPerfLastRxBlock( 0 ) , mPerfValidBlocks( 0 ) , mPerfInvalidBlocks( 0 ) , mPerfBlocksPerSecond( 0 ) , mPerfMaxBlocksPerSecond( 0 ) , mDiversitySpi( nullptr ) , mDiversityDevice( "" ) , mDiversityResetPin( -1 ) , mDiversityIrqPin( -1 ) , mDiversityLedPin( -1 ) , mTXBlockID( 0 ) { // mDropBroken = false; // TEST (using custom CRC instead) } SX127x::~SX127x() { } void SX127x::init() { fDebug(); mReady = true; if ( mResetPin < 0 ) { gDebug() << "WARNING : No Reset-pin specified for SX127x, cannot create link !"; return; } if ( mIRQPin < 0 ) { gDebug() << "WARNING : No IRQ-pin specified for SX127x, cannot create link !"; return; } memset( &mRxBlock, 0, sizeof(mRxBlock) ); mSPI = new SPI( mDevice, 5 * 1000 * 1000 ); // 7 mSPI->Connect(); GPIO::setMode( mResetPin, GPIO::Output ); GPIO::Write( mResetPin, false ); GPIO::setMode( mIRQPin, GPIO::Input ); // GPIO::setPUD( mIRQPin, GPIO::PullDown ); GPIO::setMode( mLedPin, GPIO::Output ); GPIO::SetupInterrupt( mIRQPin, GPIO::Rising, [this](){ this->Interrupt( mSPI, mLedPin ); GPIO::Write( mLedPin, false ); }); if ( mTXPin >= 0 ) { GPIO::Write( mTXPin, false ); GPIO::setMode( mTXPin, GPIO::Output ); } if ( mRXPin >= 0 ) { GPIO::Write( mRXPin, false ); GPIO::setMode( mRXPin, GPIO::Output ); } if ( mDiversityDevice.length() > 0 ) { if ( mDiversityResetPin < 0 ) { gDebug() << "WARNING : No Reset-pin specified for SX127x diversity, cannot create link !"; } else { if ( mDiversityIrqPin < 0 ) { gDebug() << "WARNING : No IRQ-pin specified for SX127x diversity, cannot create link !"; } else { mDiversitySpi = new SPI( mDiversityDevice, 5 * 1000 * 1000 ); // 7 mDiversitySpi->Connect(); GPIO::setMode( mDiversityResetPin, GPIO::Output ); GPIO::Write( mDiversityResetPin, false ); GPIO::setMode( mDiversityIrqPin, GPIO::Input ); GPIO::setMode( mDiversityLedPin, GPIO::Output ); GPIO::SetupInterrupt( mDiversityIrqPin, GPIO::Rising, [this](){ this->Interrupt( mDiversitySpi, mDiversityLedPin ); GPIO::Write( mDiversityLedPin, false ); } ); } } } gDebug() << "Reset pins : " << mResetPin << ", " << mDiversityResetPin; gDebug() << "LED pins : " << mLedPin << ", " << mDiversityLedPin; } int SX127x::Connect() { fDebug(); if ( !mReady ) { init(); } // Reset chip reset(); if ( not ping() ) { gDebug() << "Module online : " << ping(); Board::defectivePeripherals()["SX127x"] = true; return -1; } int32_t ret = Setup( mSPI ); if ( ret >= 0 and mDiversitySpi ) { ret = Setup( mDiversitySpi ); } return ret; } int32_t SX127x::Setup( SPI* spi ) { // Cut the PA just in case, RFO output, power = -1 dBm writeRegister( spi, REG_PACONFIG, 0x00 ); { // Start calibration in LF band writeRegister ( spi, REG_IMAGECAL, ( readRegister( spi, REG_IMAGECAL ) & RF_IMAGECAL_IMAGECAL_MASK ) | RF_IMAGECAL_IMAGECAL_START ); while ( ( readRegister( spi, REG_IMAGECAL ) & RF_IMAGECAL_IMAGECAL_RUNNING ) == RF_IMAGECAL_IMAGECAL_RUNNING ) { usleep( 10 ); } } { // Set frequency to mid-HF band setFrequency( spi, 868000000 ); // Start calibration in HF band writeRegister( spi, REG_IMAGECAL, ( readRegister( spi, REG_IMAGECAL ) & RF_IMAGECAL_IMAGECAL_MASK ) | RF_IMAGECAL_IMAGECAL_START ); while ( ( readRegister( spi, REG_IMAGECAL ) & RF_IMAGECAL_IMAGECAL_RUNNING ) == RF_IMAGECAL_IMAGECAL_RUNNING ) { usleep( 10 ); } } // Start module in sleep mode setOpMode( spi, RF_OPMODE_SLEEP ); // Set modem setModem( spi, mModem ); // Set frequency setFrequency( spi, mFrequency ); bool boosted_module_20dbm = true; // Set PA to maximum => TODO : make it more configurable writeRegister( spi, REG_PACONFIG, ( boosted_module_20dbm ? RF_PACONFIG_PASELECT_PABOOST : RF_PACONFIG_PASELECT_RFO ) | 0x70 | 0xF ); writeRegister( spi, REG_PADAC, 0x80 | ( boosted_module_20dbm ? RF_PADAC_20DBM_ON : RF_PADAC_20DBM_OFF ) ); writeRegister( spi, REG_OCP, RF_OCP_TRIM_240_MA | RF_OCP_OFF ); writeRegister( spi, REG_PARAMP, RF_PARAMP_SHAPING_NONE | RF_PARAMP_0040_US | RF_PARAMP_LOWPNTXPLL_OFF ); // writeRegister( spi, REG_PARAMP, RF_PARAMP_SHAPING_NONE | ( mModem == LoRa ? RF_PARAMP_0050_US : RF_PARAMP_0010_US ) | RF_PARAMP_LOWPNTXPLL_OFF ); // Set LNA writeRegister( spi, REG_LNA, RF_LNA_GAIN_G1 | RF_LNA_BOOST_ON ); // Enable TCXO if available if ( mEnableTCXO ) { while ( ( readRegister( spi, REG_TCXO ) & RF_TCXO_TCXOINPUT_ON ) != RF_TCXO_TCXOINPUT_ON ) { usleep( 50 ); writeRegister( spi, REG_TCXO, ( readRegister( REG_TCXO ) | RF_TCXO_TCXOINPUT_ON ) ); } } if ( mModem == FSK ) { // Set RX/Sync config // writeRegister( spi, REG_RXCONFIG, RF_RXCONFIG_RESTARTRXONCOLLISION_ON | RF_RXCONFIG_AFCAUTO_OFF | RF_RXCONFIG_AGCAUTO_OFF ); // writeRegister( spi, REG_RXCONFIG, RF_RXCONFIG_RXTRIGER_PREAMBLEDETECT | RF_RXCONFIG_RESTARTRXONCOLLISION_ON | RF_RXCONFIG_AFCAUTO_OFF | RF_RXCONFIG_AGCAUTO_OFF ); writeRegister( spi, REG_SYNCCONFIG, RF_SYNCCONFIG_SYNC_ON | RF_SYNCCONFIG_AUTORESTARTRXMODE_WAITPLL_ON | RF_SYNCCONFIG_PREAMBLEPOLARITY_AA | RF_SYNCCONFIG_SYNCSIZE_4 ); writeRegister( spi, REG_SYNCVALUE1, 0x64 ); writeRegister( spi, REG_SYNCVALUE2, 0x72 ); writeRegister( spi, REG_SYNCVALUE3, 0x69 ); writeRegister( spi, REG_SYNCVALUE4, 0x30 ); writeRegister( spi, REG_PREAMBLEDETECT, RF_PREAMBLEDETECT_DETECTOR_ON | RF_PREAMBLEDETECT_DETECTORSIZE_1 | RF_PREAMBLEDETECT_DETECTORTOL_20 ); } // Set RSSI smoothing writeRegister( spi, REG_RSSICONFIG, RF_RSSICONFIG_SMOOTHING_16 ); if ( mModem == LoRa ) { mBandwidth = 250000; mBitrate = 7; } TxConfig_t txconf = { .fdev = mFdev, // Hz .bandwidth = mBandwidth, // Hz .datarate = mBitrate, // bps .coderate = 1, // only for LoRa .preambleLen = 2, .crcOn = mDropBroken, .freqHopOn = false, .hopPeriod = 0, .iqInverted = false, .timeout = 2000, }; // txconf.crcOn = false; SetupTX( spi, txconf ); RxConfig_t rxconf = { .bandwidth = txconf.bandwidth, // Hz .datarate = txconf.datarate, // bps .coderate = txconf.coderate, // only for LoRa .bandwidthAfc = mBandwidthAfc, // Hz .preambleLen = txconf.preambleLen, .symbTimeout = 1, // only for LoRa .payloadLen = PACKET_SIZE, .crcOn = txconf.crcOn, .freqHopOn = false, .hopPeriod = 0, .iqInverted = false, }; SetupRX( spi, rxconf ); gDebug() << "Module online : " << ping( spi ); gDebug() << "Modem : " << ( ( readRegister( spi, REG_OPMODE ) & RFLR_OPMODE_LONGRANGEMODE_ON ) ? "LoRa" : "FSK" ); gDebug() << "Frequency : " << (uint32_t)((float)(((uint32_t)readRegister(spi, REG_FRFMSB) << 16 ) | ((uint32_t)readRegister(spi, REG_FRFMID) << 8 ) | ((uint32_t)readRegister(spi, REG_FRFLSB) )) * FREQ_STEP) << "Hz"; gDebug() << "PACONFIG : 0x" << hex << (int)readRegister( spi, REG_PACONFIG ); gDebug() << "PADAC : 0x" << hex << (int)readRegister( spi, REG_PADAC ); gDebug() << "PARAMP : 0x" << hex << (int)readRegister( spi, REG_PARAMP ); gDebug() << "OCP : 0x" << hex << (int)readRegister( spi, REG_OCP ); gDebug() << "RXCONFIG : " << hex << (int)readRegister( spi, REG_RXCONFIG ); gDebug() << "SYNCCONFIG : " << hex << (int)readRegister( spi, REG_SYNCCONFIG ); startReceiving( spi ); mConnected = true; return 0; } void SX127x::SetupTX( SPI* spi, const TxConfig_t& conf ) { switch( mModem ) { case FSK : { uint32_t fdev = ( uint16_t )( ( double )conf.fdev / ( double )FREQ_STEP ); writeRegister( spi, REG_FDEVMSB, ( uint8_t )( fdev >> 8 ) ); writeRegister( spi, REG_FDEVLSB, ( uint8_t )( fdev & 0xFF ) ); uint32_t datarate = ( uint16_t )( ( double )XTAL_FREQ / ( double )conf.datarate ); writeRegister( spi, REG_BITRATEMSB, ( uint8_t )( datarate >> 8 ) ); writeRegister( spi, REG_BITRATELSB, ( uint8_t )( datarate & 0xFF ) ); writeRegister( spi, REG_PREAMBLEMSB, ( conf.preambleLen >> 8 ) & 0x00FF ); writeRegister( spi, REG_PREAMBLELSB, conf.preambleLen & 0xFF ); writeRegister( spi, REG_PACKETCONFIG1, ( readRegister( spi, REG_PACKETCONFIG1 ) & RF_PACKETCONFIG1_CRC_MASK & RF_PACKETCONFIG1_PACKETFORMAT_MASK ) | RF_PACKETCONFIG1_PACKETFORMAT_VARIABLE | ( conf.crcOn << 4 ) ); writeRegister( spi, REG_PACKETCONFIG2, ( readRegister( spi, REG_PACKETCONFIG2 ) | RF_PACKETCONFIG2_DATAMODE_PACKET ) ); } break; case LoRa : { uint32_t bandwidth = conf.bandwidth; if ( bandwidth == 125000 ) { bandwidth = 7; } else if ( bandwidth == 250000 ) { bandwidth = 8; } else if ( bandwidth == 500000 ) { bandwidth = 9; } else { gDebug() << "ERROR: When using LoRa modem only bandwidths 125, 250 and 500 kHz are supported !"; return; } uint32_t spreading_factor = max( 6u, min( 12u, conf.datarate ) ); // uint32_t lowDatarateOptimize = ( ( ( bandwidth == 7 ) and ( ( spreading_factor == 11 ) or ( spreading_factor == 12 ) ) ) or ( ( bandwidth == 8 ) and ( spreading_factor == 12 ) ) ); if( conf.freqHopOn == true ) { writeRegister( spi, REG_LR_PLLHOP, ( readRegister( spi, REG_LR_PLLHOP ) & RFLR_PLLHOP_FASTHOP_MASK ) | RFLR_PLLHOP_FASTHOP_ON ); writeRegister( spi, REG_LR_HOPPERIOD, conf.hopPeriod ); } gDebug() << "default REG_LR_MODEMCONFIG2 : 0x" << hex << (int)readRegister( spi, REG_LR_MODEMCONFIG2 ); writeRegister( spi, REG_LR_MODEMCONFIG1, ( readRegister( spi, REG_LR_MODEMCONFIG1 ) & RFLR_MODEMCONFIG1_BW_MASK & RFLR_MODEMCONFIG1_CODINGRATE_MASK & RFLR_MODEMCONFIG1_IMPLICITHEADER_MASK ) | ( bandwidth << 4 ) | ( conf.coderate << 1 ) | RFLR_MODEMCONFIG1_IMPLICITHEADER_OFF ); writeRegister( spi, REG_LR_MODEMCONFIG2, ( readRegister( spi, REG_LR_MODEMCONFIG2 ) & RFLR_MODEMCONFIG2_SF_MASK & RFLR_MODEMCONFIG2_RXPAYLOADCRC_MASK ) | ( spreading_factor << 4 ) | ( conf.crcOn << 2 ) ); // writeRegister( spi, REG_LR_MODEMCONFIG3, ( readRegister( spi, REG_LR_MODEMCONFIG3 ) & RFLR_MODEMCONFIG3_LOWDATARATEOPTIMIZE_MASK ) | ( lowDatarateOptimize << 3 ) ); // writeRegister( spi, REG_LR_PREAMBLEMSB, ( conf.preambleLen >> 8 ) & 0x00FF ); // writeRegister( spi, REG_LR_PREAMBLELSB, conf.preambleLen & 0xFF ); if( spreading_factor == 6 ) { // writeRegister( spi, REG_LR_DETECTOPTIMIZE, ( readRegister( spi, REG_LR_DETECTOPTIMIZE ) & RFLR_DETECTIONOPTIMIZE_MASK ) | RFLR_DETECTIONOPTIMIZE_SF6 ); // writeRegister( spi, REG_LR_DETECTIONTHRESHOLD, RFLR_DETECTIONTHRESH_SF6 ); } else { // writeRegister( spi, REG_LR_DETECTOPTIMIZE, ( readRegister( spi, REG_LR_DETECTOPTIMIZE ) & RFLR_DETECTIONOPTIMIZE_MASK ) | RFLR_DETECTIONOPTIMIZE_SF7_TO_SF12 ); // writeRegister( spi, REG_LR_DETECTIONTHRESHOLD, RFLR_DETECTIONTHRESH_SF7_TO_SF12 ); } } break; } } void SX127x::SetupRX( SPI* spi, const RxConfig_t& conf ) { switch( mModem ) { case FSK : { uint32_t datarate = ( uint32_t )( ( double )XTAL_FREQ / ( double )conf.datarate ); writeRegister( spi, REG_BITRATEMSB, ( uint8_t )( datarate >> 8 ) ); writeRegister( spi, REG_BITRATELSB, ( uint8_t )( datarate & 0xFF ) ); writeRegister( spi, REG_RXBW, GetFskBandwidthRegValue( conf.bandwidth ) ); writeRegister( spi, REG_AFCBW, GetFskBandwidthRegValue( conf.bandwidthAfc ) ); writeRegister( spi, REG_PREAMBLEMSB, ( uint8_t )( ( conf.preambleLen >> 8 ) & 0xFF ) ); writeRegister( spi, REG_PREAMBLELSB, ( uint8_t )( conf.preambleLen & 0xFF ) ); // writeRegister( spi, REG_PAYLOADLENGTH, conf.payloadLen ); writeRegister( spi, REG_PAYLOADLENGTH, 0xFF ); writeRegister( spi, REG_PACKETCONFIG1, ( readRegister( spi, REG_PACKETCONFIG1 ) & RF_PACKETCONFIG1_CRC_MASK & RF_PACKETCONFIG1_PACKETFORMAT_MASK ) | RF_PACKETCONFIG1_PACKETFORMAT_VARIABLE | ( conf.crcOn << 4 ) ); writeRegister( spi, REG_PACKETCONFIG2, ( readRegister( spi, REG_PACKETCONFIG2 ) | RF_PACKETCONFIG2_DATAMODE_PACKET ) ); } break; case LoRa : { uint32_t bandwidth = conf.bandwidth; if ( bandwidth == 125000 ) { bandwidth = 7; } else if ( bandwidth == 250000 ) { bandwidth = 8; } else if ( bandwidth == 500000 ) { bandwidth = 9; } else { gDebug() << "ERROR: When using LoRa modem only bandwidths 125, 250 and 500 kHz are supported !"; return; } uint32_t spreading_factor = max( 6u, min( 12u, conf.datarate ) ); // uint32_t lowDatarateOptimize = ( ( ( bandwidth == 7 ) and ( ( spreading_factor == 11 ) or ( spreading_factor == 12 ) ) ) or ( ( bandwidth == 8 ) and ( spreading_factor == 12 ) ) ); writeRegister( spi, REG_LR_MODEMCONFIG1, ( readRegister( spi, REG_LR_MODEMCONFIG1 ) & RFLR_MODEMCONFIG1_BW_MASK & RFLR_MODEMCONFIG1_CODINGRATE_MASK & RFLR_MODEMCONFIG1_IMPLICITHEADER_MASK ) | ( bandwidth << 4 ) | ( conf.coderate << 1 ) | RFLR_MODEMCONFIG1_IMPLICITHEADER_OFF ); writeRegister( spi, REG_LR_MODEMCONFIG2, ( readRegister( spi, REG_LR_MODEMCONFIG2 ) & RFLR_MODEMCONFIG2_SF_MASK & RFLR_MODEMCONFIG2_RXPAYLOADCRC_MASK & RFLR_MODEMCONFIG2_SYMBTIMEOUTMSB_MASK ) | ( spreading_factor << 4 ) | ( conf.crcOn << 2 ) | ( ( conf.symbTimeout >> 8 ) & ~RFLR_MODEMCONFIG2_SYMBTIMEOUTMSB_MASK ) ); // writeRegister( spi, REG_LR_MODEMCONFIG3, ( readRegister( spi, REG_LR_MODEMCONFIG3 ) & RFLR_MODEMCONFIG3_LOWDATARATEOPTIMIZE_MASK ) | ( lowDatarateOptimize << 3 ) ); // writeRegister( spi, REG_LR_SYMBTIMEOUTLSB, ( uint8_t )( conf.symbTimeout & 0xFF ) ); // writeRegister( spi, REG_LR_PREAMBLEMSB, ( uint8_t )( ( conf.preambleLen >> 8 ) & 0xFF ) ); // writeRegister( spi, REG_LR_PREAMBLELSB, ( uint8_t )( conf.preambleLen & 0xFF ) ); if( conf.freqHopOn == true ) { writeRegister( spi, REG_LR_PLLHOP, ( readRegister( spi, REG_LR_PLLHOP ) & RFLR_PLLHOP_FASTHOP_MASK ) | RFLR_PLLHOP_FASTHOP_ON ); writeRegister( spi, REG_LR_HOPPERIOD, conf.hopPeriod ); } if( ( bandwidth == 9 ) and ( mFrequency > 525000000 ) ) { // ERRATA 2.1 - Sensitivity Optimization with a 500 kHz Bandwidth // writeRegister( spi, REG_LR_TEST36, 0x02 ); // writeRegister( spi, REG_LR_TEST3A, 0x64 ); } else if( bandwidth == 9 ) { // ERRATA 2.1 - Sensitivity Optimization with a 500 kHz Bandwidth // writeRegister( spi, REG_LR_TEST36, 0x02 ); // writeRegister( spi, REG_LR_TEST3A, 0x7F ); } else { // ERRATA 2.1 - Sensitivity Optimization with a 500 kHz Bandwidth // writeRegister( spi, REG_LR_TEST36, 0x03 ); } if( spreading_factor == 6 ) { // writeRegister( spi, REG_LR_DETECTOPTIMIZE, ( readRegister( spi, REG_LR_DETECTOPTIMIZE ) & RFLR_DETECTIONOPTIMIZE_MASK ) | RFLR_DETECTIONOPTIMIZE_SF6 ); // writeRegister( spi, REG_LR_DETECTIONTHRESHOLD, RFLR_DETECTIONTHRESH_SF6 ); } else { // writeRegister( spi, REG_LR_DETECTOPTIMIZE, ( readRegister( spi, REG_LR_DETECTOPTIMIZE ) & RFLR_DETECTIONOPTIMIZE_MASK ) | RFLR_DETECTIONOPTIMIZE_SF7_TO_SF12 ); // writeRegister( spi, REG_LR_DETECTIONTHRESHOLD, RFLR_DETECTIONTHRESH_SF7_TO_SF12 ); } } break; } } void SX127x::setFrequency( float f ) { setFrequency( mSPI, f ); if ( mDiversitySpi ) { setFrequency( mDiversitySpi, f ); } } void SX127x::setFrequency( SPI* spi, float f ) { uint32_t freq = (uint32_t)( (float)f / FREQ_STEP ); writeRegister( spi, REG_FRFMSB, (uint8_t)( (freq >> 16) & 0xFF ) ); writeRegister( spi, REG_FRFMID, (uint8_t)( (freq >> 8) & 0xFF ) ); writeRegister( spi, REG_FRFLSB, (uint8_t)( freq & 0xFF ) ); } void SX127x::startReceiving( SPI* spi ) { auto start = [this]( SPI* spi ) { if ( mModem == LoRa ) { writeRegister( spi, REG_LR_INVERTIQ, ( ( readRegister( spi, REG_LR_INVERTIQ ) & RFLR_INVERTIQ_TX_MASK & RFLR_INVERTIQ_RX_MASK ) | RFLR_INVERTIQ_RX_OFF | RFLR_INVERTIQ_TX_OFF ) ); writeRegister( spi, REG_LR_INVERTIQ2, RFLR_INVERTIQ2_OFF ); writeRegister( spi, REG_LR_IRQFLAGSMASK, RFLR_IRQFLAGS_VALIDHEADER | RFLR_IRQFLAGS_TXDONE | RFLR_IRQFLAGS_CADDONE | RFLR_IRQFLAGS_FHSSCHANGEDCHANNEL | RFLR_IRQFLAGS_CADDETECTED ); writeRegister( spi, REG_DIOMAPPING1, ( readRegister( spi, REG_DIOMAPPING1 ) & RFLR_DIOMAPPING1_DIO0_MASK ) | RFLR_DIOMAPPING1_DIO0_00 ); writeRegister( spi, REG_LR_DETECTOPTIMIZE, readRegister( spi, REG_LR_DETECTOPTIMIZE ) | 0x80 ); writeRegister( spi, REG_LR_FIFORXBASEADDR, 0 ); writeRegister( spi, REG_LR_FIFOADDRPTR, 0 ); } setOpMode( spi, RF_OPMODE_RECEIVER ); writeRegister( spi, REG_LNA, RF_LNA_GAIN_G1 | RF_LNA_BOOST_ON ); }; if ( not spi or spi == mSPI ) { mSending = false; mSendingEnd = false; if ( mTXPin >= 0 ) { GPIO::Write( mTXPin, false ); } if ( mRXPin >= 0 ) { GPIO::Write( mRXPin, true ); } } if ( spi ) { start( spi ); } else { start( mSPI ); if ( mDiversitySpi ) { start( mDiversitySpi ); } } } void SX127x::startTransmitting() { mInterruptMutex.lock(); if ( mDiversitySpi ) { setOpMode( mDiversitySpi, RF_OPMODE_STANDBY ); } if ( mRXPin >= 0 ) { GPIO::Write( mRXPin, false ); } if ( mTXPin >= 0 ) { GPIO::Write( mTXPin, true ); } if ( mModem == LoRa ) { writeRegister( REG_LR_IRQFLAGSMASK, RFLR_IRQFLAGS_RXTIMEOUT | RFLR_IRQFLAGS_RXDONE | RFLR_IRQFLAGS_PAYLOADCRCERROR | RFLR_IRQFLAGS_VALIDHEADER | RFLR_IRQFLAGS_CADDONE | RFLR_IRQFLAGS_FHSSCHANGEDCHANNEL | RFLR_IRQFLAGS_CADDETECTED ); writeRegister( REG_DIOMAPPING1, ( readRegister( REG_DIOMAPPING1 ) & RFLR_DIOMAPPING1_DIO0_MASK ) | RFLR_DIOMAPPING1_DIO0_01 ); } setOpMode( mSPI, RF_OPMODE_TRANSMITTER ); mInterruptMutex.unlock(); } int SX127x::setBlocking( bool blocking ) { mBlocking = blocking; return 0; } void SX127x::setRetriesCount( int retries ) { mRetries = retries; } int SX127x::retriesCount() const { return mRetries; } int32_t SX127x::Channel() { return 0; } int32_t SX127x::Frequency() { return mFrequency / 1000000; } int32_t SX127x::RxQuality() { return mRxQuality; } int32_t SX127x::RxLevel() { return mRSSI; } void SX127x::PerfUpdate() { /* mPerfMutex.lock(); if ( TICKS - mPerfTicks >= 250 ) { int32_t count = mRxBlock.block_id - mPerfLastRxBlock; if ( count < 0 ) { count = 255 + count; } if ( count == 0 or count == 1 ) { mRxQuality = 0; } else { mRxQuality = 100 * ( mPerfValidBlocks * 4 + mPerfInvalidBlocks ) / ( count * 4 ); if ( mRxQuality > 100 ) { mRxQuality = 100; } } mPerfTicks = TICKS; mPerfLastRxBlock = mRxBlock.block_id; mPerfValidBlocks = 0; mPerfInvalidBlocks = 0; } mPerfMutex.unlock(); */ const uint64_t divider = 1; // Calculate RxQuality using packets received on the last 250ms uint64_t tick = TICKS; mPerfMutex.lock(); while ( mTotalHistory.size() > 0 and mTotalHistory.front() <= tick - ( 1000LLU / divider ) ) { mPerfTotalBlocks = max( 0, mPerfTotalBlocks - 1 ); mTotalHistory.pop_front(); } while ( mMissedHistory.size() > 0 and mMissedHistory.front() <= tick - ( 1000LLU / divider ) ) { mPerfMissedBlocks = max( 0, mPerfMissedBlocks - 1 ); mMissedHistory.pop_front(); } mPerfMutex.unlock(); uint32_t receivedBlocks = mPerfTotalBlocks - mPerfMissedBlocks; mRxQuality = min( 100, 100 * receivedBlocks / mPerfTotalBlocks ); /* const uint64_t divider = 4; // Calculate RxQuality using packets received on the last 250ms mPerfMutex.lock(); uint64_t tick = TICKS; while ( mPerfHistory.size() > 0 and mPerfHistory.front() <= tick - ( 1000LLU / divider ) ) { mPerfValidBlocks = max( 0, mPerfValidBlocks - 1 ); mPerfHistory.pop_front(); } mPerfMutex.unlock(); mPerfBlocksPerSecond = mPerfValidBlocks * divider; mPerfMaxBlocksPerSecond = max( mPerfMaxBlocksPerSecond, mPerfBlocksPerSecond ); if ( mPerfBlocksPerSecond == 0 ) { mRxQuality = 0; } else if ( mPerfMaxBlocksPerSecond > 0 ) { mRxQuality = min( 100, 100 * ( mPerfBlocksPerSecond + 1 ) / mPerfMaxBlocksPerSecond ); } */ // if ( TICKS - mPerfTicks >= 250 ) { // mPerfTicks = TICKS; // gDebug() << "mPerfBlocksPerSecond : " << mPerfBlocksPerSecond; // } } SyncReturn SX127x::Read( void* pRet, uint32_t len, int32_t timeout ) { bool timedout = false; uint64_t started_waiting_at = TICKS; if ( timeout <= 0 ) { timeout = mReadTimeout; } do { bool ok = false; mRxQueueMutex.lock(); ok = ( mRxQueue.size() > 0 ); mRxQueueMutex.unlock(); if ( ok ) { break; } if ( timeout > 0 and TICKS - started_waiting_at > (uint32_t)timeout ) { timedout = true; break; } PerfUpdate(); usleep( 50 ); } while ( mBlocking ); mRxQueueMutex.lock(); if ( mRxQueue.size() == 0 ) { mRxQueueMutex.unlock(); if ( timedout ) { if ( mLedPin ) { GPIO::Write( mLedPin, 1 ); if ( mDiversityLedPin >= 0 ) { GPIO::Write( mDiversityLedPin, 1 ); } usleep( 500 ); GPIO::Write( mLedPin, 0 ); if ( mDiversityLedPin >= 0 ) { GPIO::Write( mDiversityLedPin, 0 ); } } if ( !ping() ) { gDebug() << "Module online : " << ping(); } return TIMEOUT; } return 0; } pair< uint8_t*, uint32_t > data = mRxQueue.front(); mRxQueue.pop_front(); mRxQueueMutex.unlock(); memcpy( pRet, data.first, data.second ); delete data.first; return data.second; } SyncReturn SX127x::Write( const void* data, uint32_t len, bool ack, int32_t timeout ) { fTrace( data, len, ack, timeout ); // while ( mSending ) { // usleep( 10 ); // } mSending = true; uint8_t buf[32]; memset( buf, 0, sizeof(buf) ); Header* header = (Header*)buf; mTXBlockID = ( mTXBlockID + 1 ) % MAX_BLOCK_ID; header->block_id = mTXBlockID; uint8_t packets_count = (uint8_t)std::ceil( (float)len / (float)( PACKET_SIZE - sizeof(Header) ) ); uint8_t header_len = sizeof(Header); if ( len <= PACKET_SIZE - sizeof(Header) ) { header->small_packet = 1; header_len = sizeof(HeaderMini); HeaderMini* small_header = (HeaderMini*)buf; small_header->crc = crc8( (uint8_t*)data, len ); packets_count = 1; } else { header->packets_count = packets_count; } uint32_t offset = 0; for ( uint8_t packet = 0; packet < packets_count; packet++ ) { uint32_t plen = 32 - header_len; if ( offset + plen > len ) { plen = len - offset; } memcpy( buf + header_len, (uint8_t*)data + offset, plen ); if ( header->small_packet == 0 ) { header->crc = crc8( (uint8_t*)data + offset, plen ); } // for ( int32_t retry = 0; retry < mRetries; retry++ ) { // while ( mSending ) { // usleep( 1 ); // } uint8_t tx[64]; uint8_t rx[64]; memset( tx, 0, sizeof(tx) ); memset( rx, 0, sizeof(rx) ); if ( mModem == LoRa ) { writeRegister( REG_LR_PAYLOADLENGTH, plen + header_len ); writeRegister( REG_LR_FIFOTXBASEADDR, 0 ); writeRegister( REG_LR_FIFOADDRPTR, 0 ); tx[0] = REG_FIFO | 0x80; memcpy( &tx[1], buf, plen + header_len ); } else { writeRegister( REG_FIFOTHRESH, RF_FIFOTHRESH_TXSTARTCONDITION_FIFOTHRESH | ( plen + header_len ) ); tx[0] = REG_FIFO | 0x80; tx[1] = plen + header_len; memcpy( &tx[2], buf, plen + header_len ); } mSendingEnd = false; // printf( "Sending [%u] { %d %d %d } [%d bytes]\n", plen + header_len, header->block_id, header->packet_id, header->packets_count, plen ); mSendingEnd = true; mSendTime = TICKS; startTransmitting(); mSPI->Transfer( tx, rx, plen + header_len + 1 + ( mModem == FSK ) ); while ( mModem == LoRa and mSending ) { usleep( 1 ); } } if ( header->small_packet == 0 ) { header->packet_id++; } offset += plen; } return len; } SyncReturn SX127x::WriteAck( const void* buf, uint32_t len ) { return 0; } uint32_t SX127x::fullReadSpeed() { return 0; } int SX127x::Receive( uint8_t* buf, uint32_t buflen, void* pRet, uint32_t len ) { const auto updatePerfHistory = [this]( uint8_t block_id ) { int32_t deltaBlocks = 0; if ( block_id >= mRxBlock.block_id ) { deltaBlocks = block_id - mRxBlock.block_id; } else { deltaBlocks = block_id - ((int32_t)mRxBlock.block_id - MAX_BLOCK_ID); } mPerfMutex.lock(); for ( int32_t i = 0; i < deltaBlocks; i++ ) { mTotalHistory.push_back( TICKS ); mPerfTotalBlocks++; } if ( deltaBlocks > 1 ) { mMissedHistory.push_back( TICKS ); mPerfMissedBlocks++; } mPerfMutex.unlock(); }; Header* header = (Header*)buf; uint8_t* data = buf + sizeof(Header); int final_size = 0; uint32_t datalen = buflen - sizeof(Header); if ( header->small_packet ) { HeaderMini* small_header = (HeaderMini*)buf; data = buf + sizeof(HeaderMini); datalen = buflen - sizeof(HeaderMini); if ( crc8( data, datalen ) != small_header->crc ) { return -1; } if ( small_header->block_id == mRxBlock.block_id and mRxBlock.received ) { // gTrace() << "Block (small) " << (int)header->block_id << " already received"; return -1; } updatePerfHistory( small_header->block_id ); mRxBlock.block_id = small_header->block_id; mRxBlock.received = true; mPerfValidBlocks++; mPerfMutex.lock(); mPerfHistory.push_back( TICKS ); mPerfMutex.unlock(); memcpy( pRet, data, datalen ); // gTrace() << "Received block (small) " << (int)header->block_id; return datalen; } uint8_t c = crc8( data, datalen ); if ( c != header->crc ) { gDebug() << "Invalid CRC (" << (int)c << " != " << (int)header->crc << ")"; mPerfInvalidBlocks++; return -1; } if ( header->block_id == mRxBlock.block_id and mRxBlock.received ) { gDebug() << "Block " << (int)header->block_id << " already received"; return -1; } updatePerfHistory( header->block_id ); if ( header->block_id != mRxBlock.block_id ) { memset( &mRxBlock, 0, sizeof(mRxBlock) ); mRxBlock.block_id = header->block_id; mRxBlock.packets_count = header->packets_count; } // printf( "Received [%d] { %d %d %d } [%d bytes]\n", buflen, header->block_id, header->packet_id, header->packets_count, datalen ); if ( header->packets_count == 1 ) { // printf( "small block\n" ); mRxBlock.block_id = header->block_id; mRxBlock.received = true; mPerfValidBlocks++; mPerfMutex.lock(); mPerfHistory.push_back( TICKS ); mPerfMutex.unlock(); memcpy( pRet, data, datalen ); return datalen; } memcpy( mRxBlock.packets[header->packet_id].data, data, datalen ); mRxBlock.packets[header->packet_id].size = datalen; if ( header->packet_id >= mRxBlock.packets_count - 1 ) { bool valid = true; for ( uint8_t i = 0; i < mRxBlock.packets_count; i++ ) { if ( mRxBlock.packets[i].size == 0 ) { mPerfInvalidBlocks++; valid = false; break; } if ( final_size + mRxBlock.packets[i].size >= (int)len ) { mPerfInvalidBlocks++; valid = false; break; } memcpy( &((uint8_t*)pRet)[final_size], mRxBlock.packets[i].data, mRxBlock.packets[i].size ); final_size += mRxBlock.packets[i].size; } if ( mDropBroken and valid == false ) { mPerfInvalidBlocks++; return -1; } mRxBlock.received = true; mPerfValidBlocks++; mPerfMutex.lock(); mPerfHistory.push_back( TICKS ); mPerfMutex.unlock(); return final_size; } return final_size; } void SX127x::Interrupt( SPI* spi, int32_t ledPin ) { // fTrace(); int32_t rssi = 0; // Take RSSI first, before the value becomes invalidated if ( mModem == FSK ) { rssi = -( readRegister( spi, REG_RSSIVALUE ) >> 1 ); } else { rssi = -157 + readRegister( spi, REG_LR_PKTRSSIVALUE ); // TBD : use REG_LR_RSSIVALUE ? } // int module = spi->device()[spi->device().length() - 1] - '0'; mInterruptMutex.lock(); uint64_t tick_ms = TICKS; uint8_t opMode = getOpMode( spi ); // if ( opMode != RF_OPMODE_RECEIVER and opMode != RF_OPMODE_SYNTHESIZER_RX ) { if ( opMode == RF_OPMODE_TRANSMITTER or opMode == RF_OPMODE_SYNTHESIZER_TX ) { // gDebug() << "SX127x::Interrupt(" << module << ") SendTime : " << dec << TICKS - mSendTime; if ( mSendingEnd ) { startReceiving(); } mSending = false; // gDebug() << "unlock"; mInterruptMutex.unlock(); return; } // gDebug() << "SX127x::Interrupt(" << module << ")"; if ( ledPin >= 0 ) { GPIO::Write( ledPin, true ); } mRSSI = rssi; if( mDropBroken ) { bool crc_err = false; if ( mModem == LoRa ) { uint8_t irqFlags = readRegister( spi, REG_LR_IRQFLAGS ); crc_err = ( ( irqFlags & RFLR_IRQFLAGS_PAYLOADCRCERROR_MASK ) == RFLR_IRQFLAGS_PAYLOADCRCERROR ); } else { uint8_t irqFlags = readRegister( spi, REG_IRQFLAGS2 ); crc_err = ( ( irqFlags & RF_IRQFLAGS2_CRCOK ) != RF_IRQFLAGS2_CRCOK ); } if( crc_err ) { gDebug() << "SX127x::Interrupt() CRC error"; if ( mModem == LoRa ) { mInterruptMutex.unlock(); return; } // Clear Irqs writeRegister( spi, REG_IRQFLAGS1, RF_IRQFLAGS1_RSSI | RF_IRQFLAGS1_PREAMBLEDETECT | RF_IRQFLAGS1_SYNCADDRESSMATCH ); writeRegister( spi, REG_IRQFLAGS2, RF_IRQFLAGS2_FIFOOVERRUN ); while ( writeRegister( spi, REG_RXCONFIG, readRegister( spi, REG_RXCONFIG ) | RF_RXCONFIG_RESTARTRXWITHOUTPLLLOCK ) == false and TICKS - tick_ms < 50 ) { usleep( 1 ); } // gDebug() << "unlock"; mInterruptMutex.unlock(); return; } } uint8_t tx[128]; uint8_t rx[128]; memset( tx, 0, sizeof(tx) ); memset( rx, 0, sizeof(rx) ); tx[0] = REG_FIFO & 0x7f; uint8_t len = 0; if ( mModem == LoRa ) { len = readRegister( spi, REG_LR_RXNBBYTES ); } else { len = readRegister( spi, REG_FIFO ); } spi->Transfer( tx, rx, len + 1 ); if ( len > 0 ) { PerfUpdate(); uint8_t* buf = new uint8_t[32768]; int ret = Receive( rx + 1, len, buf, 32768 ); if ( ret > 0 ) { mRxQueueMutex.lock(); mRxQueue.emplace_back( make_pair( buf, ret ) ); mRxQueueMutex.unlock(); } else { delete[] buf; } } if ( mModem == FSK ) { while ( writeRegister( spi, REG_RXCONFIG, readRegister( spi, REG_RXCONFIG ) | RF_RXCONFIG_RESTARTRXWITHPLLLOCK ) == false and TICKS - tick_ms < 50 ) { usleep( 1 ); } } // gDebug() << "SX127x::Interrupt(" << module << ") done"; mInterruptMutex.unlock(); } void SX127x::reset() { GPIO::Write( mResetPin, false ); if ( mDiversitySpi ) { GPIO::Write( mDiversityResetPin, false ); } usleep( 1000 * 250 ); GPIO::Write( mResetPin, true ); if ( mDiversitySpi ) { GPIO::Write( mDiversityResetPin, true ); } usleep( 1000 * 250 ); } bool SX127x::ping( SPI* spi ) { if ( not spi ) { if ( mDiversitySpi ) { // gDebug() << "ping 0 : " << std::hex << (int)readRegister( mSPI, REG_VERSION ); // gDebug() << "ping 1 : " << std::hex << (int)readRegister( mDiversitySpi, REG_VERSION ); return ( readRegister( mSPI, REG_VERSION ) == SAMTEC_ID ) && ( readRegister( mDiversitySpi, REG_VERSION ) == SAMTEC_ID ); } else { spi = mSPI; } } return readRegister( spi, REG_VERSION ) == SAMTEC_ID; } void SX127x::setModem( SPI* spi, Modem modem ) { switch( modem ) { default: case FSK: setOpMode( spi, RF_OPMODE_SLEEP ); writeRegister( spi, REG_OPMODE, ( readRegister(spi, REG_OPMODE) & RFLR_OPMODE_LONGRANGEMODE_MASK ) | RFLR_OPMODE_LONGRANGEMODE_OFF ); break; case LoRa: setOpMode( spi, RF_OPMODE_SLEEP ); writeRegister( spi, REG_OPMODE, ( readRegister(spi, REG_OPMODE) & RFLR_OPMODE_LONGRANGEMODE_MASK ) | RFLR_OPMODE_LONGRANGEMODE_ON ); break; } writeRegister( spi, REG_DIOMAPPING1, ( readRegister( spi, REG_DIOMAPPING1 ) & RF_DIOMAPPING1_DIO0_MASK ) | RF_DIOMAPPING1_DIO0_00 ); writeRegister( spi, REG_DIOMAPPING2, ( readRegister( spi, REG_DIOMAPPING2 ) & RF_DIOMAPPING2_MAP_MASK ) | RF_DIOMAPPING2_MAP_PREAMBLEDETECT ); } uint32_t SX127x::getOpMode( SPI* spi ) { return readRegister( spi, REG_OPMODE ) & ~RF_OPMODE_MASK; } bool SX127x::setOpMode( SPI* spi, uint32_t opMode ) { writeRegister( spi, REG_OPMODE, ( readRegister(spi, REG_OPMODE) & RF_OPMODE_MASK ) | opMode ); uint64_t tick = TICKS; uint32_t retry_tick = TICKS; bool stalling = false; while ( getOpMode(spi) != opMode and ( opMode == RF_OPMODE_RECEIVER or TICKS - tick < 250 ) ) { usleep( 1 ); if ( TICKS - tick > 100 ) { if ( not stalling ) { gDebug() << "setOpMode(" << opMode << ") stalling ! (!=" << getOpMode(spi) << ")"; } stalling = true; } if ( TICKS - retry_tick > 100 ) { writeRegister( spi, REG_OPMODE, ( readRegister(spi, REG_OPMODE) & RF_OPMODE_MASK ) | opMode ); retry_tick = TICKS; } } if ( stalling ) { gDebug() << "setOpMode(" << opMode << ") stalled (" << to_string(TICKS - tick) << "ms) !"; } if ( getOpMode(spi) != opMode ) { gDebug() << "ERROR : cannot set SX127x to opMode 0x" << hex << (int)opMode << " (0x" << (int)getOpMode(spi) << ")" << dec; return false; } else { // gDebug() << "SX127x : opMode now set to 0x" << hex << (int)opMode << dec; } return true; //time < TIMEOUT; } bool SX127x::writeRegister( uint8_t address, uint8_t value ) { uint8_t tx[32]; uint8_t rx[32]; memset( tx, 0, sizeof(tx) ); memset( rx, 0, sizeof(rx) ); tx[0] = address | 0x80; tx[1] = value; mSPI->Transfer( tx, rx, 2 ); if ( address != REG_FIFO ) { uint8_t ret = readRegister( address ); if ( address == REG_RXCONFIG ) { value &= ~( RF_RXCONFIG_RESTARTRXWITHOUTPLLLOCK | RF_RXCONFIG_RESTARTRXWITHPLLLOCK ); } if ( ret != value and address != REG_OPMODE and address != REG_IRQFLAGS1 ) { gDebug() << "Error while setting register " << GetRegName(address) << " to 0x" << hex << (int)value << " (0x" << (int)ret << ")" << dec; return false; } } return true; } uint8_t SX127x::readRegister( uint8_t address ) { uint8_t tx[32]; uint8_t rx[32]; memset( tx, 0, sizeof(tx) ); memset( rx, 0, sizeof(rx) ); tx[0] = address & 0x7F; tx[1] = 0; mSPI->Transfer( tx, rx, 2 ); return rx[1]; } bool SX127x::writeRegister( SPI* spi, uint8_t address, uint8_t value ) { uint8_t tx[32]; uint8_t rx[32]; memset( tx, 0, sizeof(tx) ); memset( rx, 0, sizeof(rx) ); tx[0] = address | 0x80; tx[1] = value; spi->Transfer( tx, rx, 2 ); if ( address != REG_FIFO ) { uint8_t ret = readRegister( address ); if ( address == REG_RXCONFIG ) { value &= ~( RF_RXCONFIG_RESTARTRXWITHOUTPLLLOCK | RF_RXCONFIG_RESTARTRXWITHPLLLOCK ); } if ( ret != value and address != REG_OPMODE and address != REG_IRQFLAGS1 ) { gDebug() << "[" << spi->device() << "]Error while setting register " << GetRegName(address) << " to 0x" << hex << (int)value << " (0x" << (int)ret << ")" << dec; return false; } } return true; } uint8_t SX127x::readRegister( SPI* spi, uint8_t address ) { uint8_t tx[32]; uint8_t rx[32]; memset( tx, 0, sizeof(tx) ); memset( rx, 0, sizeof(rx) ); tx[0] = address & 0x7F; tx[1] = 0; spi->Transfer( tx, rx, 2 ); return rx[1]; } string SX127x::name() const { return "SX127x"; } LuaValue SX127x::infos() const { LuaValue ret; ret["Bus"] = mSPI->infos(); ret["Frequency"] = mFrequency; ret["Bandwidth"] = mBandwidth; ret["Bandwidth Afc"] = mBandwidthAfc; ret["Fdev"] = mFdev; ret["Reset Pin"] = mResetPin; ret["IRQ Pin"] = mIRQPin; ret["LED Pin"] = mLedPin; ret["TX Pin"] = mTXPin; ret["RX Pin"] = mRXPin; ret["Blocking"] = mBlocking; if ( mDiversitySpi ) { ret["Diversity"] = LuaValue(); ret["Diversity"]["Bus"] = mDiversitySpi->infos(); ret["Diversity"]["Reset Pin"] = mDiversityResetPin; ret["Diversity"]["IRQ Pin"] = mDiversityIrqPin; ret["Diversity"]["LED Pin"] = mDiversityLedPin; } return ret; } static uint8_t GetFskBandwidthRegValue( uint32_t bandwidth ) { for( uint8_t i = 0; i < ( sizeof( FskBandwidths ) / sizeof( FskBandwidth_t ) ) - 1; i++ ) { if( ( bandwidth >= FskBandwidths[i].bandwidth ) and ( bandwidth < FskBandwidths[i + 1].bandwidth ) ) { return FskBandwidths[i].RegValue; } } return 0x01; // 250khz default } static const char* GetRegName( uint8_t reg ) { for ( uint32_t i = 0; regnames[i].reg != 0xFF; i++ ) { if ( regnames[i].reg == reg ) { return regnames[i].name; } } return "unk"; } static uint8_t crc8( const uint8_t* buf, uint32_t len ) { uint8_t crc = 0x00; while (len--) { uint8_t extract = *buf++; for ( uint8_t tempI = 8; tempI; tempI--) { uint8_t sum = (crc ^ extract) & 0x01; crc >>= 1; if (sum) { crc ^= 0x8C; } extract >>= 1; } } return crc; }
40,228
C++
.cpp
1,153
32.213356
320
0.647183
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,729
SBUS.cpp
dridri_bcflight/flight/links/SBUS.cpp
#include "SBUS.h" #include <Config.h> #include <Debug.h> #include <ControllerBase.h> using namespace STD; int SBUS::flight_register( Main* main ) { RegisterLink( "SBUS", &SBUS::Instanciate ); return 0; } Link* SBUS::Instanciate( Config* config, const string& lua_object ) { string stype = config->String( lua_object + ".device" ); int speed = config->Integer( lua_object + ".speed", 100000 ); int c_thrust = config->Integer( lua_object + ".channels.thrust", 0 ); int c_roll = config->Integer( lua_object + ".channels.roll", 1 ); int c_pitch = config->Integer( lua_object + ".channels.pitch", 2 ); int c_yaw = config->Integer( lua_object + ".channels.yaw", 3 ); int c_arm = config->Integer( lua_object + ".channels.arm", 4 ); return new SBUS( stype, speed, c_thrust, c_roll, c_pitch, c_yaw, c_arm ); } SBUS::SBUS( const string& device, int speed, uint8_t armChannel, uint8_t thrustChannel, uint8_t rollChannel, uint8_t pitchChannel, uint8_t yawChannel ) : Link() , mSerial( new Serial( device, speed ) ) , mArmChannel( armChannel ) , mThrustChannel( thrustChannel ) , mRollChannel( rollChannel ) , mPitchChannel( pitchChannel ) , mYawChannel( yawChannel ) , mCalibrating( false ) { } SBUS::~SBUS() { } int SBUS::retriesCount() const { return 0; } int32_t SBUS::RxLevel() { return 0; } int32_t SBUS::RxQuality() { return 0; } int SBUS::Connect() { mConnected = true; return 0; } int32_t SBUS::Channel() { return 0; } int SBUS::setBlocking( bool blocking ) { (void)blocking; return 0; } void SBUS::setRetriesCount( int retries ) { } // 00000000 10000000 01000000 00100000 00010000 00001000 00000100 00000010 00000001 00000000 uint32_t X = 0; SyncReturn SBUS::Read( void* buf, uint32_t len, int32_t timeout ) { vector< uint8_t > mBuffer; uint8_t data[32]; int32_t ret = 0; int32_t i = 0; while ( mBuffer.size() < 25 ) { ret = mSerial->Read( data, 25 - mBuffer.size() ); i = 0; if ( mBuffer.size() == 0 ) { while ( i < ret and data[i] != 0x0F ) { i++; } } if ( i < ret ) { mBuffer.insert( mBuffer.end(), &data[i], &data[ret] ); } } /* for ( uint32_t i = 0; i < 25; i += 8 ) { for ( uint32_t j = 0; j < 8 && i + j < 25; j++ ) { printf( "%02X ", mBuffer[i + j] ); } printf( "\n" ); } */ if ( mBuffer[24] != 0x00 ) { // printf( "error (%02X)\n", mBuffer[24] ); } else { mChannels[0] = ((mBuffer[1] |mBuffer[2]<<8) & 0x07FF); mChannels[1] = ((mBuffer[2]>>3 |mBuffer[3]<<5) & 0x07FF); mChannels[2] = ((mBuffer[3]>>6 |mBuffer[4]<<2 |mBuffer[5]<<10) & 0x07FF); mChannels[3] = ((mBuffer[5]>>1 |mBuffer[6]<<7) & 0x07FF); mChannels[4] = ((mBuffer[6]>>4 |mBuffer[7]<<4) & 0x07FF); mChannels[5] = ((mBuffer[7]>>7 |mBuffer[8]<<1 |mBuffer[9]<<9) & 0x07FF); mChannels[6] = ((mBuffer[9]>>2 |mBuffer[10]<<6) & 0x07FF); mChannels[7] = ((mBuffer[10]>>5|mBuffer[11]<<3) & 0x07FF); mChannels[8] = ((mBuffer[12] |mBuffer[13]<<8) & 0x07FF); mChannels[9] = ((mBuffer[13]>>3|mBuffer[14]<<5) & 0x07FF); mChannels[10] = ((mBuffer[14]>>6|mBuffer[15]<<2|mBuffer[16]<<10) & 0x07FF); mChannels[11] = ((mBuffer[16]>>1|mBuffer[17]<<7) & 0x07FF); mChannels[12] = ((mBuffer[17]>>4|mBuffer[18]<<4) & 0x07FF); mChannels[13] = ((mBuffer[18]>>7|mBuffer[19]<<1|mBuffer[20]<<9) & 0x07FF); mChannels[14] = ((mBuffer[20]>>2|mBuffer[21]<<6) & 0x07FF); mChannels[15] = ((mBuffer[21]>>5|mBuffer[22]<<3) & 0x07FF); mChannels[16] = ((mBuffer[23]) & 0x0001) ? 2047 : 0; mChannels[17] = ((mBuffer[23] >> 1) & 0x0001) ? 2047 : 0; /* for ( uint32_t c = 0; c < 18; c++ ) { gDebug() << "mChannels[" << c << "] : " << mChannels[c]; } */ mFailsafe = ((mBuffer[23] >> 3) & 0x0001) ? true : false; // if ((mBuffer[23] >> 2) & 0x0001) lost++; // TODO ControllerBase::Controls controls; float f_thrust = ( ( (float)mChannels[mThrustChannel] - 172.0f ) / 1640.0f ); float f_yaw = ( ( (float)mChannels[mYawChannel] - 992.0f ) / 820.0f ); float f_pitch = ( ( (float)mChannels[mPitchChannel] - 992.0f ) / 820.0f ); float f_roll = ( ( (float)mChannels[mRollChannel] - 992.0f ) / 820.0f ); if ( f_thrust >= 0.0f and f_thrust <= 1.0f ) { controls.thrust = (int8_t)( max( 0, min( 127, (int32_t)( f_thrust * 127.0f ) ) ) ); } if ( f_yaw >= -1.0f and f_yaw <= 1.0f ) { if ( fabsf( f_yaw ) <= 0.025f ) { f_yaw = 0.0f; } else if ( f_yaw < 0.0f ) { f_yaw += 0.025f; } else if ( f_yaw > 0.0f ) { f_yaw -= 0.025f; } f_yaw *= 1.0f / ( 1.0f - 0.025f ); controls.yaw = (int8_t)( max( -127, min( 127, (int32_t)( f_yaw * 127.0f ) ) ) ); } if ( f_pitch >= -1.0f and f_pitch <= 1.0f ) { if ( fabsf( f_pitch ) <= 0.025f ) { f_pitch = 0.0f; } else if ( f_pitch < 0.0f ) { f_pitch += 0.025f; } else if ( f_pitch > 0.0f ) { f_pitch -= 0.025f; } f_pitch *= 1.0f / ( 1.0f - 0.025f ); controls.pitch = (int8_t)( max( -127, min( 127, (int32_t)( f_pitch * 127.0f ) ) ) ); } if ( f_roll >= -1.0f and f_roll <= 1.0f ) { if ( fabsf( f_roll ) <= 0.025f ) { f_roll = 0.0f; } else if ( f_roll < 0.0f ) { f_roll += 0.025f; } else if ( f_roll > 0.0f ) { f_roll -= 0.025f; } f_roll *= 1.0f / ( 1.0f - 0.025f ); controls.roll = (int8_t)( max( -127, min( 127, (int32_t)( f_roll * 127.0f ) ) ) ); } controls.arm = ( mChannels[mArmChannel] > 500 ); // TBD : disarm if mFailsafe is true ? Packet txFrame; if ( not controls.arm and ( f_thrust >= 0.85f and f_pitch >= 0.85f ) ) { if ( not mCalibrating ) { mCalibrating = true; struct { uint32_t cmd = 0; uint32_t full_recalibration = 1; float current_altitude = 0.0f; } calibrate_cmd; calibrate_cmd.cmd = board_htonl( ControllerBase::CALIBRATE ); txFrame.Write( (uint8_t*)&calibrate_cmd, sizeof( calibrate_cmd ) ); } } else { mCalibrating = false; } txFrame.WriteU8( ControllerBase::CONTROLS ); txFrame.Write( (uint8_t*)&controls, sizeof(controls) ); memcpy( buf, txFrame.data().data(), txFrame.data().size() ); return txFrame.data().size(); } return 0; } SyncReturn SBUS::Write( const void* buf, uint32_t len, bool ack, int32_t timeout ) { (void)buf; (void)ack; (void)timeout; // Haha this is SBUS, just fake it return len; }
6,412
C++
.cpp
192
30.645833
151
0.582835
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,730
Link.cpp
dridri_bcflight/flight/links/Link.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include "Link.h" #include <Debug.h> #include <Config.h> map< string, function< Link* ( Config*, const string& ) > > Link::mKnownLinks; list< Link* > Link::sLinks; Link::Link() : mConnected( false ) { sLinks.emplace_back( this ); } Link::~Link() { } void Packet::Write( const uint8_t* data, uint32_t bytes ) { /* mData.insert( mData.end(), (uint32_t*)data, (uint32_t*)( data + ( bytes & 0xFFFFFFFC ) ) ); if ( bytes & 0b11 ) { uint32_t last = 0; for ( uint32_t i = 0; i <= 3 and ( bytes & 0xFFFFFFFC ) + i < bytes; i++ ) { last = ( last << 8 ) | data[( bytes & 0xFFFFFFFC ) + i]; } last = htonl( last ); mData.emplace_back( last ); mData.emplace_back( 0 ); } */ mData.insert( mData.end(), &data[0], &data[bytes] ); } void Packet::WriteU8( uint8_t v ) { mData.insert( mData.end(), &v, &v + sizeof(uint8_t) ); } void Packet::WriteU16( uint16_t v ) { union { uint16_t u; uint8_t b[2]; } u; u.u = board_htons( v ); mData.insert( mData.end(), u.b, u.b + sizeof(uint16_t) ); } void Packet::WriteU32( uint32_t v ) { union { uint32_t u; uint8_t b[4]; } u; u.u = board_htonl( v ); mData.insert( mData.end(), u.b, u.b + sizeof(uint32_t) ); } void Packet::WriteString( const string& str ) { Write( (const uint8_t*)str.c_str(), str.length() ); } uint32_t Packet::Read( uint8_t* data, uint32_t bytes ) { if ( mReadOffset + bytes <= mData.size() ) { memcpy( data, mData.data() + mReadOffset, bytes ); mReadOffset += bytes; return bytes; } memset( data, 0, bytes ); return 0; } uint32_t Packet::ReadU8( uint8_t* u ) { if ( mReadOffset + sizeof(uint8_t) <= mData.size() ) { *u = ((uint8_t*)(mData.data() + mReadOffset))[0]; mReadOffset += sizeof(uint8_t); return sizeof(uint8_t); } *u = 0; return 0; } uint32_t Packet::ReadU16( uint16_t* u ) { if ( mReadOffset + sizeof(uint16_t) <= mData.size() ) { *u = ((uint16_t*)(mData.data() + mReadOffset))[0]; *u = board_ntohs( *u ); mReadOffset += sizeof(uint16_t); return sizeof(uint16_t); } *u = 0; return 0; } uint32_t Packet::ReadU32( uint32_t* u ) { if ( mReadOffset + sizeof(uint32_t) <= mData.size() ) { *u = ((uint32_t*)(mData.data() + mReadOffset))[0]; *u = board_ntohl( *u ); mReadOffset += sizeof(uint32_t); return sizeof(uint32_t); } *u = 0; return 0; } uint32_t Packet::ReadFloat( float* f ) { union { float f; uint32_t u; } u; uint32_t ret = ReadU32( &u.u ); *f = u.f; return ret; } uint32_t Packet::ReadU32() { uint32_t ret = 0; ReadU32( &ret ); return ret; } uint16_t Packet::ReadU16() { uint16_t ret = 0; ReadU16( &ret ); return ret; } uint8_t Packet::ReadU8() { uint8_t ret = 0; ReadU8( &ret ); return ret; } float Packet::ReadFloat() { float ret = 0.0f; ReadFloat( &ret ); return ret; } string Packet::ReadString() { string res = ""; uint32_t i = 0; for ( i = 0; mReadOffset + i < mData.size(); i++ ) { uint8_t c = mData.at( mReadOffset + i ); if ( c ) { res += (char)c; } else { break; } } mReadOffset += i; return res; } SyncReturn Link::Read( Packet* p, int32_t timeout ) { uint8_t buffer[8192] = { 0 }; int32_t ret = Read( buffer, 8192, timeout ); if ( ret > 0 ) { p->Write( buffer, ret ); } return ret; } SyncReturn Link::Write( const Packet* p, bool ack, int32_t timeout ) { return Write( p->data().data(), p->data().size(), ack, timeout ); } bool Link::isConnected() const { return mConnected; } Link* Link::Create( Config* config, const string& lua_object ) { Link* instance = (Link*)strtoull( config->String( lua_object + "._instance" ).c_str(), nullptr, 10 ); if ( instance ) { gDebug() << "Reselecting already existing Link"; return instance; } string type = config->String( lua_object + ".link_type", "" ); Link* ret = nullptr; if ( type != "" and mKnownLinks.find( type ) != mKnownLinks.end() ) { ret = mKnownLinks[ type ]( config, lua_object ); } if ( ret != nullptr ) { config->Execute( lua_object + "._instance = \"" + to_string( (uintptr_t)ret ) + "\"" ); return ret; } gDebug() << "Error : Link type \"" << type << "\" not supported !"; return nullptr; } // -- Socket{ type = "TCP/UDP/UDPLite", port = port_number[, broadcast = true/false] } <= broadcast is false by default void Link::RegisterLink( const string& name, function< Link* ( Config*, const string& ) > instanciate ) { fDebug( name ); mKnownLinks[ name ] = instanciate; } LuaValue Link::infosAll() { LuaValue ret; for ( auto link : sLinks ) { ret[ link->name() ] = link->infos(); } return ret; }
5,248
C++
.cpp
209
23.004785
121
0.645996
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,731
RawWifi.cpp
dridri_bcflight/flight/links/RawWifi.cpp
#include "RawWifi.h" #if (BUILD_RAWWIFI == 1) #include "../librawwifi++/RawWifi.h" #include "../librawwifi++/WifiInterfaceLinux.h" #include <Debug.h> RawWifi::RawWifi() : Link() , Thread( "RawWifi" ) , mDevice( "wlan0" ) , mOutputPort( 0 ) , mInputPort( 1 ) , mChannel( 9 ) , mBlocking( true ) , mRawWifi( nullptr ) , mWifiInterface( nullptr ) { } RawWifi::~RawWifi() { mConnected = false; if ( mRawWifi ) { delete mRawWifi; } if ( mWifiInterface ) { delete mWifiInterface; } } int RawWifi::Connect() { // Debug::setDebugLevel( Debug::Level::Trace ); try { mWifiInterface = new rawwifi::WifiInterfaceLinux( mDevice, 11, 18, 20, 3 ); // mWifiInterface = new rawwifi::WifiInterfaceLinux( mDevice, 11, 18, 0, 54 ); } catch ( std::exception& e ) { gError() << "Failed to create WifiInterface: " << e.what(); mWifiInterface = nullptr; return -1; } try { mRawWifi = new rawwifi::RawWifi( mDevice, mInputPort, mOutputPort, mBlocking, 0 ); } catch ( std::exception& e ) { gError() << "Failed to create RawWifi: " << e.what(); mRawWifi = nullptr; return -1; } Thread::setName( "RawWifi[" + mDevice + "][" + to_string( mInputPort ) + "," + to_string( mOutputPort ) + "]" ); Thread::Start(); mConnected = true; return 0; } int RawWifi::setBlocking( bool blocking ) { return 0; } void RawWifi::setRetriesCount( int retries ) { } int RawWifi::retriesCount() const { return 1; } int32_t RawWifi::Channel() { return mChannel; } int32_t RawWifi::Frequency() { return 0; } int32_t RawWifi::RxQuality() { return 0; } int32_t RawWifi::RxLevel() { return 0; } SyncReturn RawWifi::Read( void* buf, uint32_t len, int32_t timeout ) { fDebug( buf, len, timeout ); bool valid = false; return mRawWifi->Receive( reinterpret_cast<uint8_t*>(buf), len, &valid, timeout ); } SyncReturn RawWifi::Write( const void* buf, uint32_t len, bool ack, int32_t timeout ) { // return mRawWifi->Send( reinterpret_cast<const uint8_t*>(buf), len, 1 ); std::lock_guard<std::mutex> lck(mPacketsQueueMutex); mPacketsQueue.push_back( std::vector<uint8_t>( reinterpret_cast<const uint8_t*>(buf), reinterpret_cast<const uint8_t*>(buf) + len ) ); mPacketsQueueCond.notify_one(); return len; } bool RawWifi::run() { std::unique_lock<std::mutex> lk(mPacketsQueueMutex); mPacketsQueueCond.wait( lk, [this]{ return not mPacketsQueue.empty(); } ); lk.unlock(); mPacketsQueueMutex.lock(); while ( not mPacketsQueue.empty() ) { std::vector<uint8_t> packet = mPacketsQueue.front(); mPacketsQueue.pop_front(); mPacketsQueueMutex.unlock(); mRawWifi->Send( packet.data(), packet.size(), 1 ); mPacketsQueueMutex.lock(); } mPacketsQueueMutex.unlock(); return true; } #else // BUILD_RAWWIFI RawWifi::RawWifi() : Link() , Thread( "RawWifi" ) , mDevice( "wlan0" ) , mOutputPort( 0 ) , mInputPort( 1 ) , mChannel( 9 ) , mBlocking( true ) , mRawWifi( nullptr ) , mWifiInterface( nullptr ) { } RawWifi::~RawWifi() { } int RawWifi::Connect() { return 0; } int RawWifi::setBlocking( bool blocking ) { return 0; } void RawWifi::setRetriesCount( int retries ) { } int RawWifi::retriesCount() const { return 1; } int32_t RawWifi::Channel() { return mChannel; } int32_t RawWifi::Frequency() { return 0; } int32_t RawWifi::RxQuality() { return 0; } int32_t RawWifi::RxLevel() { return 0; } SyncReturn RawWifi::Read( void* buf, uint32_t len, int32_t timeout ) { return 0; } SyncReturn RawWifi::Write( const void* buf, uint32_t len, bool ack, int32_t timeout ) { return 0; } bool RawWifi::run() { return false; } #endif // BUILD_RAWWIFI
3,619
C++
.cpp
167
19.706587
135
0.700767
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,732
nRF24L01.cpp
dridri_bcflight/flight/links/nRF24L01.cpp
/* * BCFlight * Copyright (C) 2017 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #ifdef BUILD_nRF24L01 #include <cmath> #include <Main.h> #include <Config.h> #include <Debug.h> #include "nRF24L01.h" #include <GPIO.h> #define min( a, b ) ( ( (a) < (b) ) ? (a) : (b) ) #define max( a, b ) ( ( (a) > (b) ) ? (a) : (b) ) int nRF24L01::flight_register( Main* main ) { RegisterLink( "RF24", &nRF24L01::Instanciate ); return 0; } Link* nRF24L01::Instanciate( Config* config, const string& lua_object ) { string device = config->String( lua_object + ".device", "/dev/spidev0.0" ); int cspin = config->Integer( lua_object + ".cspin", -1 ); int cepin = config->Integer( lua_object + ".cepin", -1 ); int irqpin = config->Integer( lua_object + ".irqpin", -1 ); int channel = config->Integer( lua_object + ".channel", 100 ); int input_port = config->Integer( lua_object + ".input_port", 0 ); int output_port = config->Integer( lua_object + ".output_port", 1 ); bool blocking = config->Boolean( lua_object + ".blocking", true ); bool drop = config->Boolean( lua_object + ".drop", true ); if ( cspin < 0 ) { gDebug() << "WARNING : No CS-pin specified for nRF24L01, cannot create link !"; return nullptr; } if ( cepin < 0 ) { gDebug() << "WARNING : No CE-pin specified for nRF24L01, cannot create link !"; return nullptr; } nRF24L01* link = new nRF24L01( device, cspin, cepin, channel, input_port, output_port, drop ); link->setBlocking( blocking ); if ( irqpin >= 0 ) { GPIO::SetupInterrupt( irqpin, GPIO::Falling, [link](){ link->Interrupt(); } ); } return link; } nRF24L01::nRF24L01( const string& device, uint8_t cspin, uint8_t cepin, uint8_t channel, uint32_t input_port, uint32_t output_port, bool drop_invalid_packets ) : Link() , mDevice( device ) , mCSPin( cspin ) , mCEPin( cepin ) , mRadio( nullptr ) , mBlocking( true ) , mDropBroken( drop_invalid_packets ) , mChannel( max( 1u, min( 126u, (uint32_t)channel ) ) ) , mInputPort( input_port ) , mOutputPort( output_port ) , mRetries( 1 ) , mReadTimeout( 2000 ) , mTXBlockID( 0 ) , mRPD( false ) , mSmoothRPD( 0 ) , mRxQuality( 0 ) , mPerfTicks( 0 ) , mPerfLastRxBlock( 0 ) , mPerfValidBlocks( 0 ) , mPerfInvalidBlocks( 0 ) { memset( &mRxBlock, 0, sizeof(mRxBlock) ); } nRF24L01::~nRF24L01() { } int nRF24L01::Connect() { if ( mRadio != nullptr ) { return 0; } mRadio = new nRF24::RF24( mCEPin, mCSPin, BCM2835_SPI_SPEED_8MHZ ); mRadio->begin(); mRadio->setPALevel( nRF24::RF24_PA_MAX ); mRadio->setAutoAck( true ); mRadio->setRetries( 5, 3 ); mRadio->setAddressWidth( 3 ); mRadio->setPayloadSize( 32 ); mRadio->enableAckPayload(); mRadio->enableDynamicAck(); mRadio->setChannel( mChannel - 1 ); mRadio->setDataRate( nRF24::RF24_250KBPS ); mRadio->setCRCLength( mDropBroken ? nRF24::RF24_CRC_16 : nRF24::RF24_CRC_DISABLED ); mRadio->openWritingPipe( (uint64_t)( 0x00BCF000 | mOutputPort ) ); mRadio->openReadingPipe( 1, (uint64_t)( 0x00BCF000 | mInputPort ) ); mRadio->maskIRQ( true, true, false ); mRadio->printDetails(); mRadio->startListening(); mConnected = true; return 0; } int nRF24L01::setBlocking( bool blocking ) { mBlocking = blocking; return 0; } void nRF24L01::setRetriesCount( int retries ) { mRetries = retries; } int nRF24L01::retriesCount() const { return mRetries; } int32_t nRF24L01::Channel() { return mChannel; } int32_t nRF24L01::Frequency() { return 2400 + mChannel; } int32_t nRF24L01::RxQuality() { return mRxQuality; } int32_t nRF24L01::RxLevel() { return mSmoothRPD; } uint32_t nRF24L01::fullReadSpeed() { return 0; } void nRF24L01::PerfUpdate() { mPerfMutex.lock(); if ( Board::GetTicks() - mPerfTicks >= 1000 * 1000 ) { int32_t count = mRxBlock.block_id - mPerfLastRxBlock; if ( count == 0 or count == 1 ) { mRxQuality = 0; } else { if ( count < 0 ) { count = 255 + count; } mRxQuality = 100 * ( mPerfValidBlocks * 4 + mPerfInvalidBlocks ) / ( count * 4 ); if ( mRxQuality > 100 ) { mRxQuality = 100; } } mPerfTicks = Board::GetTicks(); mPerfLastRxBlock = mRxBlock.block_id; mPerfValidBlocks = 0; mPerfInvalidBlocks = 0; } mPerfMutex.unlock(); } SyncReturn nRF24L01::Read( void* pRet, uint32_t len, int32_t timeout ) { bool timedout = false; uint64_t started_waiting_at = Board::GetTicks(); if ( timeout == 0 ) { timeout = mReadTimeout; } do { /* mInterruptMutex.lock(); bool rpd = mRadio->testRPD(); if ( mRadio->available() ) { mRPD = rpd; mSmoothRPD = mSmoothRPD * 0.95f + ( mRPD ? -25 : -80 ) * 0.05f; } mInterruptMutex.unlock(); */ bool ok = false; mRxQueueMutex.lock(); ok = ( mRxQueue.size() > 0 ); mRxQueueMutex.unlock(); if ( ok ) { break; } if ( timeout > 0 and Board::GetTicks() - started_waiting_at > (uint64_t)timeout * 1000llu ) { timedout = true; break; } PerfUpdate(); usleep( 100 ); } while ( mBlocking ); PerfUpdate(); mRxQueueMutex.lock(); if ( mRxQueue.size() == 0 ) { mRxQueueMutex.unlock(); if ( timedout ) { // cout << "WARNING : Read timeout\n"; return TIMEOUT; } return 0; } pair< uint8_t*, uint32_t > data = mRxQueue.front(); mRxQueue.pop_front(); mRxQueueMutex.unlock(); memcpy( pRet, data.first, data.second ); delete data.first; return data.second; } SyncReturn nRF24L01::WriteAck( const void* data, uint32_t len ) { if ( len > 32 - sizeof(Header) ) { len = 32 - sizeof(Header); } uint8_t buf[32]; memset( buf, 0, sizeof(buf) ); memcpy( &buf[sizeof(Header)], data, len ); Header* header = (Header*)buf; header->packet_size = len; header->packet_id = 0; header->packets_count = 1; mInterruptMutex.lock(); header->block_id = ++mTXBlockID; mRadio->writeAckPayload( 1, buf, sizeof(Header) + len ); mInterruptMutex.unlock(); return len; } SyncReturn nRF24L01::Write( const void* data, uint32_t len, bool ack, int32_t timeout ) { if ( len > 255 * ( 32 - sizeof(Header) ) ) { return 0; } int ret = Send( data, len, ack ); return ret; } int nRF24L01::Send( const void* data, uint32_t len, bool ack ) { mInterruptMutex.lock(); mRadio->stopListening(); uint8_t buf[32]; memset( buf, 0, sizeof(buf) ); Header* header = (Header*)buf; header->block_id = ++mTXBlockID; header->packets_count = (uint8_t)ceil( (float)len / (float)( 32 - sizeof(Header) ) ); static uint32_t send_id = 0; uint32_t offset = 0; for ( uint8_t packet = 0; packet < header->packets_count; packet++ ) { uint32_t plen = 32 - sizeof(Header); if ( offset + plen > len ) { plen = len - offset; } memset( buf + sizeof(Header), 0, sizeof(buf) - sizeof(Header) ); memcpy( buf + sizeof(Header), (uint8_t*)data + offset, plen ); header->packet_size = plen; mRadio->writeFast( buf, sizeof(buf), not ack ); if ( send_id++ == 2 or packet + 1 == header->packets_count ) { send_id = 0; mRadio->txStandBy(); } header->packet_id++; offset += plen; } mRadio->startListening(); mInterruptMutex.unlock(); return len; } int nRF24L01::Receive( void* pRet, uint32_t len ) { uint8_t buf[32]; Header* header = (Header*)buf; uint8_t* data = buf + sizeof(Header); int final_size = 0; PerfUpdate(); memset( buf, 0, sizeof(buf) ); mInterruptMutex.lock(); mRadio->read( buf, sizeof(buf) ); mInterruptMutex.unlock(); uint32_t datalen = header->packet_size; if ( header->block_id == mRxBlock.block_id and mRxBlock.received ) { return CONTINUE; } if ( header->block_id != mRxBlock.block_id ) { memset( &mRxBlock, 0, sizeof(mRxBlock) ); mRxBlock.block_id = header->block_id; mRxBlock.packets_count = header->packets_count; } if ( header->packets_count == 1 ) { // printf( "small block\n" ); mRxBlock.block_id = header->block_id; mRxBlock.received = true; mPerfValidBlocks++; memcpy( pRet, data, datalen ); return datalen; } /* printf( "header = {\n" " block_id = %d\n" " packet_id = %d\n" " packets_count = %d\n", header->block_id, header->packet_id, header->packets_count ); */ memcpy( mRxBlock.packets[header->packet_id].data, data, datalen ); mRxBlock.packets[header->packet_id].size = datalen; if ( header->packet_id >= mRxBlock.packets_count - 1 ) { bool valid = true; for ( uint8_t i = 0; i < mRxBlock.packets_count; i++ ) { if ( mRxBlock.packets[i].size == 0 ) { mPerfInvalidBlocks++; valid = false; break; } if ( final_size + mRxBlock.packets[i].size >= (int)len ) { mPerfInvalidBlocks++; valid = false; break; } memcpy( &((uint8_t*)pRet)[final_size], mRxBlock.packets[i].data, mRxBlock.packets[i].size ); final_size += mRxBlock.packets[i].size; } if ( mDropBroken and valid == false ) { return CONTINUE; } mRxBlock.received = true; mPerfValidBlocks++; return final_size; } return final_size; } void nRF24L01::Interrupt() { while ( mRadio->available() ) { uint8_t* buf = new uint8_t[32768]; int ret = Receive( buf, 32768 ); if ( ret > 0 ) { // printf( "Received %d bytes\n", ret ); mRxQueueMutex.lock(); mRxQueue.emplace_back( make_pair( buf, ret ) ); mRxQueueMutex.unlock(); } else { delete buf; } } } #endif // BUILD_nRF24L01
9,790
C++
.cpp
347
25.786744
159
0.672145
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,733
Socket.cpp
dridri_bcflight/flight/links/Socket.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #if ( BUILD_SOCKET == 1 ) #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <unistd.h> /* close */ #include <netdb.h> /* gethostbyname */ #ifdef HAVE_LIBIW #include <iwlib.h> #endif #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define closesocket(s) close(s) typedef int SOCKET; typedef struct sockaddr_in SOCKADDR_IN; typedef struct sockaddr SOCKADDR; typedef struct in_addr IN_ADDR; #include "Debug.h" #include "Board.h" #include "Socket.h" #include "../Config.h" #define UDPLITE_SEND_CSCOV 10 /* sender partial coverage (as sent) */ #define UDPLITE_RECV_CSCOV 11 /* receiver partial coverage (threshold ) */ Socket::Socket( uint16_t port, Socket::PortType type, bool broadcast, uint32_t timeout ) : mPort( port ) , mPortType( type ) , mBroadcast( broadcast ) , mTimeout( timeout ) , mSocket( -1 ) , mClientSocket( -1 ) , mChannel( 0 ) { fDebug( port, type, broadcast, timeout ); #ifdef HAVE_LIBIW iwstats stats; wireless_config info; iwrange range; int iwSocket = iw_sockets_open(); memset( &stats, 0, sizeof( stats ) ); if ( iw_get_basic_config( iwSocket, "wlan0", &info ) == 0 ) { if ( iw_get_range_info( iwSocket, "wlan0", &range ) == 0 ) { mChannel = iw_freq_to_channel( info.freq, &range ); } } iw_sockets_close( iwSocket ); #endif } Socket::Socket() : Socket( 0 ) { fDebug(); } Socket::~Socket() { if ( mConnected and mSocket >= 0 ) { shutdown( mSocket, 2 ); closesocket( mSocket ); } } int32_t Socket::Channel() { return mChannel; } int32_t Socket::RxQuality() { #ifdef HAVE_LIBIW // TODO : use "iw dev wlan0 station dump" instead iwstats stats; errno = 0; int32_t ret = 0; int iwSocket = iw_sockets_open(); memset( &stats, 0, sizeof( stats ) ); if ( iw_get_stats( iwSocket, "wlan0", &stats, nullptr, 0 ) == 0 ) { ret = (int32_t)stats.qual.qual * 100 / 70; } iw_sockets_close( iwSocket ); #else int32_t ret = 0; #endif return ret; } int32_t Socket::RxLevel() { #ifdef HAVE_LIBIW iwstats stats; int32_t ret = -200; int iwSocket = iw_sockets_open(); memset( &stats, 0, sizeof( stats ) ); if ( iw_get_stats( iwSocket, "wlan0", &stats, nullptr, 0 ) == 0 ) { union { int8_t s; uint8_t u; } conv = { .u = stats.qual.level }; ret = conv.s; } iw_sockets_close( iwSocket ); #else int32_t ret = 0; #endif return ret; } int Socket::setBlocking( bool blocking ) { int flags = fcntl( mSocket, F_GETFL, 0 ); flags = blocking ? ( flags & ~O_NONBLOCK) : ( flags | O_NONBLOCK ); return ( fcntl( mSocket, F_SETFL, flags ) == 0 ); } int Socket::retriesCount() const { if ( mPortType == UDP or mPortType == UDPLite ) { // TODO } return 1; } void Socket::setRetriesCount( int retries ) { if ( mPortType == UDP or mPortType == UDPLite ) { // TODO : set retries count } } int Socket::Connect() { fDebug( mPort, mPortType ); if ( mConnected ) { return 0; } setBlocking( true ); if ( mSocket < 0 ) { int type = ( mPortType == UDP or mPortType == UDPLite ) ? SOCK_DGRAM : SOCK_STREAM; int proto = ( mPortType == UDPLite ) ? IPPROTO_UDPLITE : ( ( mPortType == UDP ) ? IPPROTO_UDP : 0 ); char myname[256]; gethostname( myname, sizeof(myname) ); memset( &mSin, 0, sizeof( mSin ) ); mSin.sin_addr.s_addr = htonl( INADDR_ANY ); mSin.sin_family = AF_INET; mSin.sin_port = htons( mPort ); mSocket = socket( AF_INET, type, proto ); int option = 1; setsockopt( mSocket, SOL_SOCKET, ( 15/*SO_REUSEPORT*/ | SO_REUSEADDR ), (char*)&option, sizeof( option ) ); if ( mPortType == TCP ) { int flag = 1; setsockopt( mSocket, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(int) ); } if ( mBroadcast ) { int broadcastEnable = 1; setsockopt( mSocket, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable) ); } if ( mPortType == UDPLite ) { uint16_t checksum_coverage = 8; setsockopt( mSocket, IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, &checksum_coverage, sizeof(checksum_coverage) ); setsockopt( mSocket, IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, &checksum_coverage, sizeof(checksum_coverage) ); } if ( bind( mSocket, (SOCKADDR*)&mSin, sizeof(mSin) ) < 0 ) { gDebug() << "Socket ( " << mPort << " ) error : " << strerror(errno); mConnected = false; return -1; } } if ( mPortType == TCP ) { int ret = listen( mSocket, 5 ); int size = 0; if ( !ret ) { mClientSocket = accept( mSocket, (SOCKADDR*)&mClientSin, (socklen_t*)&size ); if ( mClientSocket < 0 ) { mConnected = false; return -1; } } else { mConnected = false; return -1; } } else if ( mPortType == UDP or mPortType == UDPLite ) { if ( not mBroadcast ) { mClientSin.sin_family = AF_UNSPEC; /* uint32_t flag = 0; uint32_t fromsize = sizeof( mClientSin ); int ret = recvfrom( mSocket, &flag, sizeof( flag ), 0, (SOCKADDR*)&mClientSin, &fromsize ); if ( ret > 0 ) { flag = ntohl( flag ); gDebug() << "flag : " << ntohl( flag ); if ( flag != 0x12345678 ) { mConnected = false; return -1; } } else { gDebug() << strerror( errno ); mConnected = false; return -1; } */ } } mConnected = true; return 0; } SyncReturn Socket::Read( void* buf, uint32_t len, int timeout ) { if ( !mConnected ) { return -1; } int ret = 0; memset( buf, 0, len ); // If timeout is not set, default it to mTimeout if ( timeout <= 0 ) { timeout = mTimeout; } uint64_t timebase = Board::GetTicks(); if ( timeout > 0 ) { struct timeval tv; tv.tv_sec = timeout / 1000; tv.tv_usec = 1000 * ( timeout % 1000 ); setsockopt( mSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(struct timeval) ); } if ( mPortType == UDP or mPortType == UDPLite ) { uint32_t fromsize = sizeof( mClientSin ); ret = recvfrom( mSocket, buf, len, 0, (SOCKADDR *)&mClientSin, &fromsize ); } else { ret = recv( mClientSocket, buf, len, MSG_NOSIGNAL ); } if ( ret <= 0 ) { if ( ( Board::GetTicks() - timebase >= timeout * 1000ULL ) or errno == 11 ) { return TIMEOUT; } gDebug() << "UDP disconnected ( " << ret << " : " << errno << ", " << strerror( errno ) << " )"; mConnected = false; return -1; } return ret; } SyncReturn Socket::Write( const void* buf, uint32_t len, bool ack, int timeout ) { if ( !mConnected ) { return -1; } int ret = 0; if ( mPortType == UDP or mPortType == UDPLite ) { if ( mBroadcast ) { mClientSin.sin_family = AF_INET; mClientSin.sin_port = htons( mPort ); mClientSin.sin_addr.s_addr = inet_addr( "192.168.32.255" ); } if ( mClientSin.sin_family == AF_UNSPEC ) { return 0; } uint32_t sendsize = sizeof( mClientSin ); uint32_t pos = 0; while ( pos < len and ret >= 0 ) { uint32_t sz = std::min( len - pos, 65000U ); int r = sendto( mSocket, (uint8_t*)buf + pos, sz, 0, (SOCKADDR *)&mClientSin, sendsize ); if ( r < 0 ) { ret = r; break; } pos += r; ret += r; } } else { ret = send( mClientSocket, buf, len, MSG_NOSIGNAL ); } if ( ret <= 0 and ( errno == EAGAIN or errno == -EAGAIN ) ) { return 0; } if ( ret < 0 and mPortType != UDP and mPortType != UDPLite ) { gDebug() << "TCP disconnected"; mConnected = false; return -1; } return ret; } LuaValue Socket::infos() const { LuaValue ret; ret[ "Port" ] = (int)mPort; if ( mPortType == TCP ) { ret[ "Port Type" ] = "TCP"; } else if ( mPortType == UDP ) { ret[ "Port Type" ] = "UDP"; } else if ( mPortType == UDPLite ) { ret[ "Port Type" ] = "UDPLite"; } ret[ "Broadcast" ] = mBroadcast ? "true" : "false"; ret[ "Timeout" ] = mTimeout; return ret; } #endif // ( BUILD_SOCKET == 1 )
8,473
C++
.cpp
306
25.160131
109
0.649032
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,735
spi.cpp
dridri_bcflight/flight/links/RF24/utility/spi.cpp
#include "spi.h" #include <pthread.h> #include <string.h> #include <string> #include <SPI.h> static ::SPI* mSPI = nullptr; static string mSPIDevice = ""; #ifdef SYSTEM_NAME_Linux static pthread_mutex_t spiMutex = PTHREAD_MUTEX_INITIALIZER; #endif nRF24::SPI::SPI() { } nRF24::SPI::~SPI() { } void nRF24::SPI::begin( const string& device ) { mSPIDevice = device; } void nRF24::SPI::end() { } void nRF24::SPI::beginTransaction( SPISettings settings ) { if ( mSPI == nullptr ) { uint32_t speed = 0; switch ( settings.clck ) { case BCM2835_SPI_SPEED_64MHZ: speed = 64000000; break; case BCM2835_SPI_SPEED_32MHZ: speed = 32000000; break; case BCM2835_SPI_SPEED_16MHZ: speed = 16000000; break; case BCM2835_SPI_SPEED_8MHZ: speed = 8000000; break; case BCM2835_SPI_SPEED_4MHZ: speed = 4000000; break; case BCM2835_SPI_SPEED_2MHZ: speed = 2000000; break; case BCM2835_SPI_SPEED_1MHZ: speed = 1000000; break; case BCM2835_SPI_SPEED_512KHZ: speed = 512000; break; case BCM2835_SPI_SPEED_256KHZ: speed = 256000; break; case BCM2835_SPI_SPEED_128KHZ: speed = 128000; break; case BCM2835_SPI_SPEED_64KHZ: speed = 64000; break; case BCM2835_SPI_SPEED_32KHZ: speed = 32000; break; case BCM2835_SPI_SPEED_16KHZ: speed = 16000; break; case BCM2835_SPI_SPEED_8KHZ: default: speed = 8000; break; } mSPI = new ::SPI( mSPIDevice, speed ); } #ifdef SYSTEM_NAME_Linux pthread_mutex_lock( &spiMutex ); #endif } void nRF24::SPI::endTransaction() { #ifdef SYSTEM_NAME_Linux pthread_mutex_unlock( &spiMutex ); #endif } void nRF24::SPI::setBitOrder( uint8_t bit_order ) { // Unsupported by rpi } void nRF24::SPI::setDataMode( uint8_t data_mode ) { } void nRF24::SPI::setClockDivider( uint16_t spi_speed ) { } void nRF24::SPI::chipSelect( int csn_pin ) { } uint8_t nRF24::SPI::transfer( uint8_t _data ) { uint8_t data = 0; mSPI->Transfer( &_data, &data, 1 ); return data; } void nRF24::SPI::transfernb(char* tbuf, char* rbuf, uint32_t len) { mSPI->Transfer( tbuf, rbuf, len ); } void nRF24::SPI::transfern(char* buf, uint32_t len) { char* rbuf = new char[len]; mSPI->Transfer( buf, rbuf, len ); memcpy( buf, rbuf, len ); delete rbuf; }
2,314
C++
.cpp
114
17.482456
65
0.686924
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,736
BMP180.cpp
dridri_bcflight/flight/sensors/BMP180.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <unistd.h> #include <cmath> #include "BMP180.h" #define BMP180_REG_CONTROL 0xF4 #define BMP180_REG_RESULT 0xF6 #define BMP180_COMMAND_TEMPERATURE 0x2E #define BMP180_COMMAND_PRESSURE0 0x34 #define BMP180_COMMAND_PRESSURE1 0x74 #define BMP180_COMMAND_PRESSURE2 0xB4 #define BMP180_COMMAND_PRESSURE3 0xF4 int BMP180::flight_register( Main* main ) { Device dev; dev.iI2CAddr = 0x77; dev.name = "BMP180"; dev.fInstanciate = BMP180::Instanciate; mKnownDevices.push_back( dev ); return 0; } Sensor* BMP180::Instanciate( Config* config, const string& object, Bus* bus ) { // TODO : use bus return new BMP180(); } BMP180::BMP180() : Altimeter() , mI2C( new I2C( 0x77 ) ) { mNames.emplace_back( "BMP180" ); mNames.emplace_back( "bmp180" ); mI2C->Read16( 0xAA, &AC1, true ); mI2C->Read16( 0xAC, &AC2, true ); mI2C->Read16( 0xAE, &AC3, true ); mI2C->Read16( 0xB0, &AC4, true ); mI2C->Read16( 0xB2, &AC5, true ); mI2C->Read16( 0xB4, &AC6, true ); mI2C->Read16( 0xB6, &VB1, true ); mI2C->Read16( 0xB8, &VB2, true ); mI2C->Read16( 0xBA, &MB, true ); mI2C->Read16( 0xBC, &MC, true ); mI2C->Read16( 0xBE, &MD, true ); float c3 = 160.0 * pow( 2, -15 ) * AC3; float c4 = pow( 10, -3 ) * pow( 2, -15 ) * AC4; float b1 = pow( 160, 2 ) * pow( 2, -30 ) * VB1; c5 = ( pow( 2, -15 ) / 160 ) * AC5; c6 = AC6; mc = ( pow( 2, 11 ) / pow( 160, 2 ) ) * MC; md = MD / 160.0; x0 = AC1; x1 = 160.0 * pow( 2, -13 ) * AC2; x2 = pow( 160, 2 ) * pow( 2, -25 ) * VB2; y0 = c4 * pow( 2, 15 ); y1 = c4 * c3; y2 = c4 * b1; p0 = ( 3791.0 - 8.0 ) / 1600.0; p1 = 1.0 - 7357.0 * pow( 2, -20 ); p2 = 3038.0 * 100.0 * pow( 2, -36 ); // mBasePressure = ReadPressure(); mBasePressure = 1013.45 / pow( 1 - ( 65.0 / 44330.0 ), 5.255 ); } BMP180::~BMP180() { } void BMP180::Calibrate( float dt, bool last_pass ) { (void)dt; (void)last_pass; } float BMP180::ReadTemperature() { int16_t raw_temp = 0; // Start temperature sampling if ( mI2C->Write8( BMP180_REG_CONTROL, BMP180_COMMAND_TEMPERATURE ) <= 0 ) { // TODO : return last temperature return 0.0f; } usleep( 1000 * 5 ); // Get temperature if ( mI2C->Read16( BMP180_REG_RESULT, &raw_temp, true ) == 0 ) { // TODO : return last temperature return 0.0f; } float a = c5 * ( (float)raw_temp - c6 ); return a + ( mc / ( a + md ) ); } float BMP180::ReadPressure() { unsigned char data[3]; float temperature = ReadTemperature(); // Start pressure if ( mI2C->Write8( BMP180_REG_CONTROL, BMP180_COMMAND_PRESSURE3 ) <= 0 ) { // TODO : return last pressure return 0.0f; } usleep( 1000 * 26 ); // Get pressure if ( mI2C->Read( BMP180_REG_RESULT, data, 3 ) != 3 ) { // TODO : return last pressure return 0.0f; } float pu = ( data[0] * 256.0 ) + data[1] + ( data[2] / 256.0 ); float s = temperature - 25.0; float x = ( x2 * pow( s, 2 ) ) + ( x1 * s ) + x0; float y = ( y2 * pow( s, 2 ) ) + ( y1 * s ) + y0; float z = ( pu - x ) / y; return ( p2 * pow( z, 2 ) ) + ( p1 * z ) + p0; } void BMP180::Read( float* altitude ) { *altitude = 44330.0 * ( 1.0 - pow( ReadPressure() / mBasePressure, 1 / 5.255 ) ); }
3,827
C++
.cpp
128
27.90625
82
0.644529
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,737
Gyroscope.cpp
dridri_bcflight/flight/sensors/Gyroscope.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include "Gyroscope.h" Gyroscope::Gyroscope() : Sensor() , mAxes{ false } { } Gyroscope::~Gyroscope() { } const bool* Gyroscope::axes() const { return mAxes; }
883
C++
.cpp
30
27.533333
72
0.744982
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,738
Accelerometer.cpp
dridri_bcflight/flight/sensors/Accelerometer.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include "Accelerometer.h" Accelerometer::Accelerometer() : Sensor() , mAxes{ false } { } Accelerometer::~Accelerometer() { } const bool* Accelerometer::axes() const { return mAxes; }
907
C++
.cpp
30
28.333333
72
0.752009
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,739
LSM303.cpp
dridri_bcflight/flight/sensors/LSM303.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <unistd.h> #include <Main.h> #include "LSM303.h" int LSM303::flight_register( Main* main ) { Device dev1; Device dev2; dev1.iI2CAddr = 0x19; dev1.name = "LSM303Accel"; dev1.fInstanciate = LSM303Accel::Instanciate; dev2.iI2CAddr = 0x1E; dev2.name = "LSM303Mag"; dev2.fInstanciate = LSM303Mag::Instanciate; mKnownDevices.push_back( dev1 ); mKnownDevices.push_back( dev2 ); return 0; } Sensor* LSM303Mag::Instanciate( Config* config, const string& object, Bus* bus ) { // TODO : use bus return new LSM303Mag(); } Sensor* LSM303Accel::Instanciate( Config* config, const string& object, Bus* bus ) { // TODO : use bus return new LSM303Accel(); } LSM303Accel::LSM303Accel() : Accelerometer() , mI2C( new I2C( 0x19 ) ) , mCalibrationAccum( Vector4f() ) , mOffset( Vector3f() ) { mNames = { "LSM303", "lsm303", "lsm303dlhc" }; mAxes[0] = true; mAxes[1] = true; mAxes[2] = true; mI2C->Write8( LSM303_REGISTER_ACCEL_CTRL_REG1_A, 0b01110111 ); // mI2C->Write8( LSM303_REGISTER_ACCEL_CTRL_REG1_A, 0b01000111 ); // mI2C->Write8( LSM303_REGISTER_ACCEL_CTRL_REG1_A, 0b10010111 ); mI2C->Write8( LSM303_REGISTER_ACCEL_CTRL_REG4_A, 0b00101000 ); mI2C->Write8( LSM303_REGISTER_ACCEL_CTRL_REG5_A, 0b01000000 ); } LSM303Mag::LSM303Mag() : Magnetometer() , mI2C( new I2C( 0x1E ) ) { mNames = { "LSM303", "lsm303", "lsm303dlhc" }; mAxes[0] = true; mAxes[1] = true; mAxes[2] = true; mI2C->Write8( LSM303_REGISTER_MAG_MR_REG_M, 0x00 ); } LSM303Accel::~LSM303Accel() { } LSM303Mag::~LSM303Mag() { } void LSM303Accel::Calibrate( float dt, bool last_pass ) { Vector3f accel; Read( &accel, true ); mCalibrationAccum += Vector4f( accel, 1.0f ); if ( last_pass ) { mOffset = mCalibrationAccum.xyz() / mCalibrationAccum.w; mCalibrationAccum = Vector4f(); mCalibrated = true; gDebug() << "LSM303 SAVING CALIBRATED OFFSETS !"; aDebug( "Offset", mOffset.x, mOffset.y, mOffset.z ); Board::SaveRegister( "LSM303:Accelerometer:Offset:X", to_string( mOffset.x ) ); Board::SaveRegister( "LSM303:Accelerometer:Offset:Y", to_string( mOffset.y ) ); Board::SaveRegister( "LSM303:Accelerometer:Offset:Z", to_string( mOffset.z ) ); } } void LSM303Mag::Calibrate( float dt, bool last_pass ) { // TODO } void LSM303Accel::Read( Vector3f* v, bool raw ) { short saccel[3] = { 0 }; uint8_t status = 0; do { mI2C->Read8( LSM303_REGISTER_ACCEL_STATUS_REG_A, &status ); usleep( 0 ); } while ( !( status & 0b00001111 ) ); mI2C->Read( LSM303_REGISTER_ACCEL_Oraw_temp_X_L_A | 0x80, saccel, sizeof(saccel) ); v->x = ACCEL_MS2( saccel[0] ); v->y = ACCEL_MS2( saccel[1] ); v->z = ACCEL_MS2( saccel[2] ); v->x -= mOffset.x; v->y -= mOffset.y; ApplySwap( *v ); mLastValues = *v; } void LSM303Mag::Read( Vector3f* v, bool raw ) { uint16_t _smag[3] = { 0 }; int16_t smag[3] = { 0 }; mI2C->Read( LSM303_REGISTER_MAG_Oraw_temp_X_H_M, _smag, sizeof(_smag) ); smag[0] = ( ( ( _smag[0] >> 8 ) & 0xFF ) | ( ( _smag[0] << 8 ) & 0x0F00 ) ) << 4; smag[1] = ( ( ( _smag[1] >> 8 ) & 0xFF ) | ( ( _smag[1] << 8 ) & 0x0F00 ) ) << 4; smag[2] = ( ( ( _smag[2] >> 8 ) & 0xFF ) | ( ( _smag[2] << 8 ) & 0x0F00 ) ) << 4; v->x = (float)smag[0] / 1.0f; v->y = (float)smag[1] / 1.0f; v->z = (float)smag[2] / 1.0f; ApplySwap( *v ); mLastValues = *v; }
4,009
C++
.cpp
127
29.488189
84
0.675943
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,741
Voltmeter.cpp
dridri_bcflight/flight/sensors/Voltmeter.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include "Voltmeter.h" Voltmeter::Voltmeter() : Sensor() { } Voltmeter::~Voltmeter() { }
808
C++
.cpp
25
30.4
72
0.748395
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,742
LinuxGPS.cpp
dridri_bcflight/flight/sensors/LinuxGPS.cpp
#include "LinuxGPS.h" #include "Debug.h" #include <cmath> #ifdef BUILD_LinuxGPS LinuxGPS::LinuxGPS() : GPS() , mGpsData( nullptr ) { fDebug(); int rc = 0; mGpsData = new struct gps_data_t; memset( mGpsData, 0, sizeof(struct gps_data_t) ); if ( ( rc = gps_open( "localhost", "2947", mGpsData ) ) < 0 ) { gError() << "gps_open failed : " << gps_errstr(rc) << " (" << rc << ")"; delete mGpsData; mGpsData = nullptr; return; } gps_stream( mGpsData, WATCH_ENABLE | WATCH_JSON, nullptr ); } LinuxGPS::~LinuxGPS() { if ( mGpsData ) { gps_stream( mGpsData, WATCH_DISABLE, nullptr ); gps_close( mGpsData ); } } void LinuxGPS::Calibrate( float dt, bool last_pass ) { (void)dt; (void)last_pass; } time_t LinuxGPS::getTime() { // Read must be called to update this value if ( mGpsData and mGpsData->set & MODE_SET and mGpsData->fix.mode >= MODE_NO_FIX ) { return mGpsData->fix.time.tv_sec; } return 0; } bool LinuxGPS::Read( float* latitude, float* longitude, float* altitude, float* speed ) { int rc = 0; if ( mGpsData and gps_waiting( mGpsData, 0 ) ) { if ( ( rc = gps_read( mGpsData, nullptr, 0 ) ) < 0 ) { gWarning() << "gps_read failed : " << gps_errstr(rc) << " (" << rc << ")"; } else { if ( mGpsData->set & MODE_SET ) { if ( mGpsData->fix.mode < 0 || mGpsData->fix.mode >= 3 ) { mGpsData->fix.mode = 0; } if ( ( mGpsData->fix.mode == MODE_2D or mGpsData->fix.mode == MODE_3D ) and not isnan(mGpsData->fix.latitude) and not isnan(mGpsData->fix.longitude) ) { gTrace() << "latitude: " << mGpsData->fix.latitude << ", longitude: " << mGpsData->fix.longitude << ", speed: " << mGpsData->fix.speed << ", timestamp: " << mGpsData->fix.time.tv_sec; *latitude = mGpsData->fix.latitude; *longitude = mGpsData->fix.longitude; *altitude = mGpsData->fix.altitude; *speed = mGpsData->fix.speed; return true; } else { gTrace() << "no GPS data available"; } } } } return false; } bool LinuxGPS::Stats( uint32_t* satSeen, uint32_t* satUsed ) { if ( mGpsData ) { *satSeen = mGpsData->satellites_visible; *satUsed = mGpsData->satellites_used; return true; } return false; } #else LinuxGPS::LinuxGPS(): GPS() { fDebug(); } LinuxGPS::~LinuxGPS() { fDebug(); } void LinuxGPS::Calibrate( float dt, bool last_pass ) { (void)dt; (void)last_pass; } time_t LinuxGPS::getTime() { return 0; } bool LinuxGPS::Read( float* latitude, float* longitude, float* altitude, float* speed ) { (void)latitude; (void)longitude; (void)altitude; (void)speed; return false; } bool LinuxGPS::Stats( uint32_t* satSeen, uint32_t* satUsed ) { (void)satSeen; (void)satUsed; return false; } #endif
2,704
C++
.cpp
108
22.564815
188
0.653951
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,743
Sensor.cpp
dridri_bcflight/flight/sensors/Sensor.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include "Sensor.h" #include "Gyroscope.h" #include "Accelerometer.h" #include "Magnetometer.h" #include "GPS.h" #include "Altimeter.h" #include "Voltmeter.h" #include "CurrentSensor.h" #include <Matrix.h> #include "I2C.h" #include "SPI.h" #include <Config.h> list< Sensor::Device > Sensor::mKnownDevices; list< Sensor* > Sensor::mDevices; list< Gyroscope* > Sensor::mGyroscopes; list< Accelerometer* > Sensor::mAccelerometers; list< Magnetometer* > Sensor::mMagnetometers; list< Altimeter* > Sensor::mAltimeters; list< GPS* > Sensor::mGPSes; list< Voltmeter* > Sensor::mVoltmeters; list< CurrentSensor* > Sensor::mCurrentSensors; Sensor::Sensor() : mNames( std::list<string>() ) , mCalibrated( false ) , mSwapMode( SwapModeNone ) , mAxisSwap{ 0, 0, 0, 0 } , mAxisMatrix( Matrix( 4, 4 ) ) { mDevices.push_back( this ); UpdateDevices(); } Sensor::~Sensor() { } const list< string >& Sensor::names() const { return mNames; } const bool Sensor::calibrated() const { return mCalibrated; } Vector4f Sensor::lastValues() const { return mLastValues; } void Sensor::setAxisSwap( const Vector4i& swap ) { mAxisSwap = swap; if ( mSwapMode == SwapModeNone ) { mSwapMode = SwapModeAxis; } } void Sensor::setAxisMatrix( const Matrix& matrix ) { mAxisMatrix = matrix; mSwapMode = SwapModeMatrix; } void Sensor::ApplySwap( Vector3f& v ) { Vector3f tmp = Vector3f( v.x, v.y, v.z ); if ( mSwapMode == SwapModeAxis ) { v[0] = tmp[ abs( mAxisSwap[0] ) - 1 ]; v[1] = tmp[ abs( mAxisSwap[1] ) - 1 ]; v[2] = tmp[ abs( mAxisSwap[2] ) - 1 ]; if ( mAxisSwap[0] < 0 ) { v[0] = -v[0]; } if ( mAxisSwap[1] < 0 ) { v[1] = -v[1]; } if ( mAxisSwap[2] < 0 ) { v[2] = -v[2]; } } else if ( mSwapMode == SwapModeMatrix ) { v = mAxisMatrix * tmp; } } void Sensor::ApplySwap( Vector4f& v ) { Vector4f tmp = Vector4f( v.x, v.y, v.z, v.w ); if ( mSwapMode == SwapModeAxis ) { v[0] = tmp[ abs( mAxisSwap[0] ) - 1 ]; v[1] = tmp[ abs( mAxisSwap[1] ) - 1 ]; v[2] = tmp[ abs( mAxisSwap[2] ) - 1 ]; v[3] = tmp[ abs( mAxisSwap[3] ) - 1 ]; if ( mAxisSwap[0] < 0 ) { v[0] = -v[0]; } if ( mAxisSwap[1] < 0 ) { v[1] = -v[1]; } if ( mAxisSwap[2] < 0 ) { v[2] = -v[2]; } if ( mAxisSwap[3] < 0 ) { v[3] = -v[3]; } } else if ( mSwapMode == SwapModeMatrix ) { v = mAxisMatrix * tmp; } } LuaValue Sensor::swapInfos() const { LuaValue ret; const auto axisString = [] ( const int axis ) { const string sign = axis < 0 ? "-" : ""; switch ( std::abs( axis ) ) { case 1: return sign + "X"; case 2: return sign + "Y"; case 3: return sign + "Z"; case 4: return sign + "W"; } return string(""); }; if ( mSwapMode == SwapModeAxis ) { ret["x"] = axisString( mAxisSwap[0] ); ret["y"] = axisString( mAxisSwap[1] ); ret["z"] = axisString( mAxisSwap[2] ); if ( mAxisSwap[3] != 0 ) { ret["w"] = axisString( mAxisSwap[3] ); } } else { for ( uint32_t i = 0; i < (uint32_t)mAxisMatrix.height(); ++i ) { ret[i] = LuaValue(); for ( uint32_t j = 0; j < (uint32_t)mAxisMatrix.width(); ++j ) { ret[i][j] = mAxisMatrix.constData()[i * mAxisMatrix.width() + j]; } } } return ret; } void Sensor::AddDevice( Sensor* sensor ) { mDevices.push_back( sensor ); UpdateDevices(); } /* void Sensor::RegisterDevice( int I2Caddr, const string& name, Config* config, const string& object ) { for ( Device d : mKnownDevices ) { if ( d.iI2CAddr == I2Caddr and ( name == "" or !strcmp( d.name, name.c_str() ) ) ) { Sensor* dev = d.fInstanciate( config, object, new I2C(d.iI2CAddr) ); if ( dev ) { mDevices.push_back( dev ); UpdateDevices(); break; } } } } void Sensor::RegisterDevice( const string& name, Config* config, const string& object ) { fDebug( name, config, object ); for ( Device d : mKnownDevices ) { if ( !strcmp( d.name, name.c_str() ) ) { const string dev = config->String( object + ".device" ); Bus* bus = nullptr; if ( dev.find("spi") != string::npos or dev.find("SPI") != string::npos or dev.find("Spi") != string::npos ) { bus = new SPI( dev, config->Integer( object + ".speed", 500000 ) ); } if ( bus ) { Sensor* dev = d.fInstanciate( config, object, bus ); if ( dev ) { mDevices.push_back( dev ); UpdateDevices(); break; } } } } } */ const list< Sensor::Device >& Sensor::KnownDevices() { return mKnownDevices; } list< Sensor* > Sensor::Devices() { return mDevices; } list< Gyroscope* > Sensor::Gyroscopes() { return mGyroscopes; } list< Accelerometer* > Sensor::Accelerometers() { return mAccelerometers; } list< Magnetometer* > Sensor::Magnetometers() { return mMagnetometers; } list< Altimeter* > Sensor::Altimeters() { return mAltimeters; } list< GPS* > Sensor::GPSes() { return mGPSes; } list< Voltmeter* > Sensor::Voltmeters() { return mVoltmeters; } list< CurrentSensor* > Sensor::CurrentSensors() { return mCurrentSensors; } Gyroscope* Sensor::gyroscope( const string& name ) { for ( auto it = mGyroscopes.begin(); it != mGyroscopes.end(); it++ ) { Gyroscope* g = (*it); for ( auto it2 = g->names().begin(); it2 != g->names().end(); it2++ ) { if ( (*it2) == name ) { return g; } } } return nullptr; } Accelerometer* Sensor::accelerometer( const string& name ) { for ( auto it = mAccelerometers.begin(); it != mAccelerometers.end(); it++ ) { Accelerometer* a = (*it); for ( auto it2 = a->names().begin(); it2 != a->names().end(); it2++ ) { if ( (*it2) == name ) { return a; } } } return nullptr; } Magnetometer* Sensor::magnetometer( const string& name ) { for ( auto it = mMagnetometers.begin(); it != mMagnetometers.end(); it++ ) { Magnetometer* m = (*it); for ( auto it2 = m->names().begin(); it2 != m->names().end(); it2++ ) { if ( (*it2) == name ) { return m; } } } return nullptr; } GPS* Sensor::gps( const string& name ) { for ( auto it = mGPSes.begin(); it != mGPSes.end(); it++ ) { GPS* g = (*it); for ( auto it2 = g->names().begin(); it2 != g->names().end(); it2++ ) { if ( (*it2) == name ) { return g; } } } return nullptr; } Altimeter* Sensor::altimeter( const string& name ) { for ( auto it = mAltimeters.begin(); it != mAltimeters.end(); it++ ) { Altimeter* a = (*it); for ( auto it2 = a->names().begin(); it2 != a->names().end(); it2++ ) { if ( (*it2) == name ) { return a; } } } return nullptr; } Voltmeter* Sensor::voltmeter( const string& name ) { for ( auto it = mVoltmeters.begin(); it != mVoltmeters.end(); it++ ) { Voltmeter* v = (*it); for ( auto it2 = v->names().begin(); it2 != v->names().end(); it2++ ) { if ( (*it2) == name ) { return v; } } } return nullptr; } CurrentSensor* Sensor::currentSensor( const string& name ) { for ( auto it = mCurrentSensors.begin(); it != mCurrentSensors.end(); it++ ) { CurrentSensor* c = (*it); for ( auto it2 = c->names().begin(); it2 != c->names().end(); it2++ ) { if ( (*it2) == name ) { return c; } } } return nullptr; } void Sensor::UpdateDevices() { mGyroscopes.clear(); mAccelerometers.clear(); mMagnetometers.clear(); mAltimeters.clear(); mGPSes.clear(); mVoltmeters.clear(); mCurrentSensors.clear(); for ( Sensor* s : mDevices ) { Gyroscope* g = dynamic_cast< Gyroscope* >( s ); if ( g != nullptr ) { mGyroscopes.push_back( g ); } } for ( Sensor* s : mDevices ) { Accelerometer* a = dynamic_cast< Accelerometer* >( s ); if ( a != nullptr ) { mAccelerometers.push_back( a ); } } for ( Sensor* s : mDevices ) { Magnetometer* m = dynamic_cast< Magnetometer* >( s ); if ( m != nullptr ) { mMagnetometers.push_back( m ); } } for ( Sensor* s : mDevices ) { GPS* g = dynamic_cast< GPS* >( s ); if ( g != nullptr ) { mGPSes.push_back( g ); } } for ( Sensor* s : mDevices ) { Altimeter* a = dynamic_cast< Altimeter* >( s ); if ( a != nullptr ) { mAltimeters.push_back( a ); } } for ( Sensor* s : mDevices ) { Voltmeter* v = dynamic_cast< Voltmeter* >( s ); if ( v != nullptr ) { mVoltmeters.push_back( v ); } } for ( Sensor* s : mDevices ) { CurrentSensor* c = dynamic_cast< CurrentSensor* >( s ); if ( c != nullptr ) { mCurrentSensors.push_back( c ); } } } LuaValue Sensor::infosAll() { LuaValue ret; static const auto listSensors = [] ( const std::list< Sensor* >* sensors ) { LuaValue ret = LuaValue( std::list<LuaValue>() ); for ( Sensor* s : *sensors ) { const std::string& name = s->names().front(); if ( name.length() == 0 ) { continue; } ret[s->names().front()] = s->infos(); } return ret; }; ret["Gyroscopes"] = listSensors( reinterpret_cast<std::list<Sensor*>*>(&mGyroscopes) ); ret["Accelerometers"] = listSensors( reinterpret_cast<std::list<Sensor*>*>(&mAccelerometers) ); ret["Magnetometers"] = listSensors( reinterpret_cast<std::list<Sensor*>*>(&mMagnetometers) ); ret["Altimeters"] = listSensors( reinterpret_cast<std::list<Sensor*>*>(&mAltimeters) ); ret["GPSes"] = listSensors( reinterpret_cast<std::list<Sensor*>*>(&mGPSes) ); ret["Voltmeters"] = listSensors( reinterpret_cast<std::list<Sensor*>*>(&mVoltmeters) ); ret["CurrentSensors"] = listSensors( reinterpret_cast<std::list<Sensor*>*>(&mCurrentSensors) ); return ret; }
10,033
C++
.cpp
389
23.244216
113
0.631073
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,744
Magnetometer.cpp
dridri_bcflight/flight/sensors/Magnetometer.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include "Magnetometer.h" Magnetometer::Magnetometer() : Sensor() , mAxes{ false } { } Magnetometer::~Magnetometer() { } const bool* Magnetometer::axes() const { return mAxes; }
901
C++
.cpp
30
28.133333
72
0.750289
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,745
ADS1015.cpp
dridri_bcflight/flight/sensors/ADS1015.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <unistd.h> #include "ADS1015.h" #define ADS1015_REG_POINTER_MASK (0x03) #define ADS1015_REG_POINTER_CONVERT (0x00) #define ADS1015_REG_POINTER_CONFIG (0x01) #define ADS1015_REG_POINTER_LOWTHRESH (0x02) #define ADS1015_REG_POINTER_HITHRESH (0x03) #define ADS1015_REG_CONFIG_OS_MASK (0x8000) #define ADS1015_REG_CONFIG_OS_SINGLE (0x8000) // Write: Set to start a single-conversion #define ADS1015_REG_CONFIG_OS_BUSY (0x0000) // Read: Bit = 0 when conversion is in progress #define ADS1015_REG_CONFIG_OS_NOTBUSY (0x8000) // Read: Bit = 1 when device is not performing a conversion #define ADS1015_REG_CONFIG_MUX_MASK (0x7000) #define ADS1015_REG_CONFIG_MUX_DIFF_0_1 (0x0000) // Differential P = AIN0, N = AIN1 (default) #define ADS1015_REG_CONFIG_MUX_DIFF_0_3 (0x1000) // Differential P = AIN0, N = AIN3 #define ADS1015_REG_CONFIG_MUX_DIFF_1_3 (0x2000) // Differential P = AIN1, N = AIN3 #define ADS1015_REG_CONFIG_MUX_DIFF_2_3 (0x3000) // Differential P = AIN2, N = AIN3 #define ADS1015_REG_CONFIG_MUX_SINGLE_0 (0x4000) // Single-ended AIN0 #define ADS1015_REG_CONFIG_MUX_SINGLE_1 (0x5000) // Single-ended AIN1 #define ADS1015_REG_CONFIG_MUX_SINGLE_2 (0x6000) // Single-ended AIN2 #define ADS1015_REG_CONFIG_MUX_SINGLE_3 (0x7000) // Single-ended AIN3 #define ADS1015_REG_CONFIG_PGA_MASK (0x0E00) #define ADS1015_REG_CONFIG_PGA_6_144V (0x0000) // +/-6.144V range = Gain 2/3 #define ADS1015_REG_CONFIG_PGA_4_096V (0x0200) // +/-4.096V range = Gain 1 #define ADS1015_REG_CONFIG_PGA_2_048V (0x0400) // +/-2.048V range = Gain 2 (default) #define ADS1015_REG_CONFIG_PGA_1_024V (0x0600) // +/-1.024V range = Gain 4 #define ADS1015_REG_CONFIG_PGA_0_512V (0x0800) // +/-0.512V range = Gain 8 #define ADS1015_REG_CONFIG_PGA_0_256V (0x0A00) // +/-0.256V range = Gain 16 #define ADS1015_REG_CONFIG_MODE_MASK (0x0100) #define ADS1015_REG_CONFIG_MODE_CONTIN (0x0000) // Continuous conversion mode #define ADS1015_REG_CONFIG_MODE_SINGLE (0x0100) // Power-down single-shot mode (default) #define ADS1015_REG_CONFIG_DR_MASK (0x00E0) #define ADS1015_REG_CONFIG_DR_128SPS (0x0000) // 128 samples per second #define ADS1015_REG_CONFIG_DR_250SPS (0x0020) // 250 samples per second #define ADS1015_REG_CONFIG_DR_490SPS (0x0040) // 490 samples per second #define ADS1015_REG_CONFIG_DR_920SPS (0x0060) // 920 samples per second #define ADS1015_REG_CONFIG_DR_1600SPS (0x0080) // 1600 samples per second (default) #define ADS1015_REG_CONFIG_DR_2400SPS (0x00A0) // 2400 samples per second #define ADS1015_REG_CONFIG_DR_3300SPS (0x00C0) // 3300 samples per second #define ADS1015_REG_CONFIG_CMODE_MASK (0x0010) #define ADS1015_REG_CONFIG_CMODE_TRAD (0x0000) // Traditional comparator with hysteresis (default) #define ADS1015_REG_CONFIG_CMODE_WINDOW (0x0010) // Window comparator #define ADS1015_REG_CONFIG_CPOL_MASK (0x0008) #define ADS1015_REG_CONFIG_CPOL_ACTVLOW (0x0000) // ALERT/RDY pin is low when active (default) #define ADS1015_REG_CONFIG_CPOL_ACTVHI (0x0008) // ALERT/RDY pin is high when active #define ADS1015_REG_CONFIG_CLAT_MASK (0x0004) // Determines if ALERT/RDY pin latches once asserted #define ADS1015_REG_CONFIG_CLAT_NONLAT (0x0000) // Non-latching comparator (default) #define ADS1015_REG_CONFIG_CLAT_LATCH (0x0004) // Latching comparator #define ADS1015_REG_CONFIG_CQUE_MASK (0x0003) #define ADS1015_REG_CONFIG_CQUE_1CONV (0x0000) // Assert ALERT/RDY after one conversions #define ADS1015_REG_CONFIG_CQUE_2CONV (0x0001) // Assert ALERT/RDY after two conversions #define ADS1015_REG_CONFIG_CQUE_4CONV (0x0002) // Assert ALERT/RDY after four conversions #define ADS1015_REG_CONFIG_CQUE_NONE (0x0003) // Disable the comparator and put ALERT/RDY in high state (default) ADS1015::ADS1015() : mI2C( new I2C( 0x48 ) ) , mRingBuffer{ 0.0f } , mRingSum( 0.0f ) , mRingIndex( 0 ) , mChannelReady{ false } { mNames = { "ADS1015" }; mI2C->Connect(); usleep( 1000 * 100 ); uint16_t id = 0; mI2C->Read16( 0x0B, &id ); gDebug() << "ADS1015 ID: " << (uint32_t)id; } ADS1015::~ADS1015() { delete mI2C; } void ADS1015::Calibrate( float dt, bool last_pass ) { (void)dt; } float ADS1015::Read( int channel ) { uint16_t _ret1 = 0; uint16_t _ret2 = 0; int r1 = 0; int r2 = 0; int r3 = 0; // if ( not mChannelReady[channel] ) { uint16_t config = ADS1015_REG_CONFIG_CQUE_NONE | // Disable the comparator (default val) ADS1015_REG_CONFIG_CLAT_NONLAT | // Non-latching (default val) ADS1015_REG_CONFIG_CPOL_ACTVLOW | // Alert/Rdy active low (default val) ADS1015_REG_CONFIG_CMODE_WINDOW | // Traditional comparator (default val) ADS1015_REG_CONFIG_DR_1600SPS | // 1600 samples per second (default) ADS1015_REG_CONFIG_MODE_SINGLE; // Single-shot mode (default) config |= ADS1015_REG_CONFIG_PGA_4_096V; config |= ( ADS1015_REG_CONFIG_MUX_SINGLE_0 + ( channel << 12 ) ); config |= ADS1015_REG_CONFIG_OS_SINGLE; // config |= ADS1015_REG_CONFIG_OS_NOTBUSY; config = ( ( config << 8 ) & 0xFF00 ) | ( ( config >> 8 ) & 0xFF ); r1 = mI2C->Write16( ADS1015_REG_POINTER_CONFIG, config ); usleep( 10000 ); // mChannelReady[channel] = true; // } r2 = mI2C->Read16( ADS1015_REG_POINTER_CONVERT, &_ret1 ); r3 = mI2C->Read16( ADS1015_REG_POINTER_CONVERT, &_ret2 ); _ret1 = ( ( _ret1 << 8 ) & 0xFF00 ) | ( ( _ret1 >> 8 ) & 0xFF ); _ret2 = ( ( _ret2 << 8 ) & 0xFF00 ) | ( ( _ret2 >> 8 ) & 0xFF ); // printf("r1, r2, r3 : %d, %d, %d | %d, %d\n", r1, r2, r3, _ret1, _ret2); if ( r1 < 0 or r2 < 0 or r3 < 0 or std::abs((int)_ret1 - (int)_ret2) > 128 ) { // printf("'%s'\n", strerror(errno)); throw std::exception(); } // float fret = (float)( ret * 6.144f / 32768.0f ); float fret = (float)( _ret1 * 4.096f / 32768.0f ); return fret; } LuaValue ADS1015::infos() { LuaValue ret = LuaValue(); ret["Channels"] = 4; ret["Rate"] = "1600 SPS"; ret["Resolution"] = "12 bits"; ret["Bus"] = "I2C"; return ret; }
6,753
C++
.cpp
136
47.625
117
0.697494
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,746
L3GD20H.cpp
dridri_bcflight/flight/sensors/L3GD20H.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <unistd.h> #include <Main.h> #include "L3GD20H.h" int L3GD20H::flight_register( Main* main ) { Device dev; dev.iI2CAddr = 0x6b; dev.name = "L3GD20H"; dev.fInstanciate = L3GD20H::Instanciate; mKnownDevices.push_back( dev ); return 0; } Gyroscope* L3GD20H::Instanciate( Config* config, const string& object, Bus* bus ) { // TODO : use bus return new L3GD20H(); } L3GD20H::L3GD20H() : Gyroscope() , mI2C( new I2C( 0x6b ) ) , mCalibrationAccum( Vector4f() ) , mOffset( Vector3f() ) { mNames = { "L3GD20", "l3gd20", "l3gd20h" }; mAxes[0] = true; mAxes[1] = true; mAxes[2] = true; mI2C->Write8( L3GD20_CTRL_REG2, 0b00000000 ); mI2C->Write8( L3GD20_CTRL_REG3, 0b00001000 ); mI2C->Write8( L3GD20_CTRL_REG4, 0b00110000 ); mI2C->Write8( L3GD20_CTRL_REG5, 0b01000000 ); mI2C->Write8( L3GD20_FIFO_CTRL_REG, 0b01000000 ); mI2C->Write8( L3GD20_CTRL_REG1, 0b11111111 ); } L3GD20H::~L3GD20H() { } void L3GD20H::Calibrate( float dt, bool last_pass ) { Vector3f gyro; Read( &gyro, true ); mCalibrationAccum += Vector4f( gyro, 1.0f ); if ( last_pass ) { mOffset = mCalibrationAccum.xyz() / mCalibrationAccum.w; aDebug( "Offset", mOffset.x, mOffset.y, mOffset.z ); mCalibrationAccum = Vector4f(); mCalibrated = true; } } int L3GD20H::Read( Vector3f* v, bool raw ) { short sgyro[3] = { 0 }; if ( mI2C->Read( L3GD20_OUT_X_L | 0x80, sgyro, sizeof(sgyro) ) != sizeof(sgyro) ) { return -1; } v->x = 0.0703125f * (float)sgyro[0]; v->y = 0.0703125f * (float)sgyro[1]; v->z = 0.0703125f * (float)sgyro[2]; v->operator-=( mOffset ); ApplySwap( *v ); mLastValues = *v; return 3; }
2,338
C++
.cpp
80
27.2
84
0.70415
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,748
CurrentSensor.cpp
dridri_bcflight/flight/sensors/CurrentSensor.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include "CurrentSensor.h" CurrentSensor::CurrentSensor() : Sensor() { } CurrentSensor::~CurrentSensor() { }
828
C++
.cpp
25
31.2
72
0.754693
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,749
MPU6050.cpp
dridri_bcflight/flight/sensors/MPU6050.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <cmath> #include <unistd.h> #include "MPU6050.h" #include "Config.h" #include "SPI.h" int MPU6050::flight_register( Main* main ) { Device dev1; Device dev2; dev1.iI2CAddr = 0x68; dev1.name = "MPU6050"; dev1.fInstanciate = []( Config* config, const string& object, Bus* bus ) { return MPU6050::Instanciate( bus, config, object ); }; dev2.iI2CAddr = 0x69; dev2.name = "MPU6050"; dev2.fInstanciate = []( Config* config, const string& object, Bus* bus ) { return MPU6050::Instanciate( bus, config, object ); }; mKnownDevices.push_back( dev1 ); mKnownDevices.push_back( dev2 ); return 0; } Sensor* MPU6050::Instanciate( Bus* bus, Config* config, const string& object ) { I2C* i2c = static_cast<I2C*>(bus); uint8_t whoami = 0x00; i2c->Read8( MPU_6050_WHO_AM_I, &whoami ); bool mpu9250 = ( whoami == 0x71 or whoami == 0x73 ); bool icm20608 = ( whoami == 0xAF ); gDebug() << "whoami [0x" << hex << (int)i2c->address() << "]0x" << hex << (int)whoami; if ( mpu9250 ) { gDebug() << "I2C module at address 0x" << hex << (int)i2c->address() << " is MPU9250"; } else if ( icm20608 ) { gDebug() << "I2C module at address 0x" << hex << (int)i2c->address() << " is ICM28608"; } // No power management, internal clock source: 0b00000000 i2c->Write8( MPU_6050_PWR_MGMT_1, 0b00000000 ); // Disable all interrupts: 0b00000000 i2c->Write8( MPU_6050_INT_ENABLE, 0b00000000 ); // Disable all FIFOs: 0b00000000 i2c->Write8( MPU_6050_FIFO_EN, 0b00000000 ); // 1 kHz sampling rate: 0b00000000 i2c->Write8( MPU_6050_SMPRT_DIV, 0b00000000 ); // No ext sync, DLPF at 94Hz for the accel and 98Hz for the gyro: 0b00000010) (~200Hz: 0b00000001) i2c->Write8( MPU_6050_DEFINE, 0b00000011 ); // Gyro range at +/-2000 °/s i2c->Write8( MPU_6050_GYRO_CONFIG, 0b00011000 ); // Accel range at +/-16g i2c->Write8( MPU_6050_ACCEL_CONFIG, 0b00011000 ); // Bypass mode enabled: 0b00000010 i2c->Write8( MPU_6050_INT_PIN_CFG, 0b00000010 ); // No FIFO and no I2C slaves: 0b00000000 i2c->Write8( MPU_6050_USER_CTRL, 0b00000000 ); if ( mpu9250 or icm20608 ) { // DLPF at 99Hz for the accel i2c->Write8( MPU_6050_ACCEL_CONFIG_2, 0b00000110 ); } // TODO : use config ('use_dmp') // TODO : see https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/MPU6050_6Axis_MotionApps20.h if ( false ) { MPU6050* mpu = new MPU6050( i2c ); delete mpu; exit(0); } // delete i2c; // Manually add sensors to mDevices since they use the same address Sensor* mag = new MPU6050Mag( i2c ); Sensor* gyro = new MPU6050Gyro( i2c ); Sensor* accel = new MPU6050Accel( i2c ); mDevices.push_back( mag ); mDevices.push_back( accel ); return gyro; /* uint8_t read_reg = 0; if ( dynamic_cast<SPI*>(bus) != nullptr ) { read_reg = 0x80; } uint8_t whoami = 0x00; bus->Read8( read_reg | MPU_6050_WHO_AM_I, &whoami ); bool mpu9250 = ( whoami == 0x71 or whoami == 0x73 ); bool icm20608 = ( whoami == 0xAF ); bool icm42605 = ( whoami == 0x42 ); gDebug() << "whoami : 0x" << hex << (int)whoami; if ( mpu9250 ) { // TODO : put back these logs // gDebug() << "I2C module at address 0x" << hex << (int)bus->address() << " is MPU9250"; } else if ( icm20608 ) { // gDebug() << "I2C module at address 0x" << hex << (int)bus->address() << " is ICM20608"; } // No power management, internal clock source: 0b00000000 bus->Write8( MPU_6050_PWR_MGMT_1, 0b00000000 ); // Disable all interrupts: 0b00000000 bus->Write8( MPU_6050_INT_ENABLE, 0b00000000 ); // Disable all FIFOs: 0b00000000 bus->Write8( MPU_6050_FIFO_EN, 0b00000000 ); // Gyro range at +/-2000 °/s bus->Write8( MPU_6050_GYRO_CONFIG, 0b00011000 ); // Accel range at +/-16g bus->Write8( MPU_6050_ACCEL_CONFIG, 0b00011000 ); // Set sample_rate divider // const uint32_t rate = 1000000 / config->Integer( "stabilizer.loop_time", 2000 ); // bus->Write8( MPU_6050_SMPRT_DIV, 8000 / min(8000U, rate) - 1 ); if ( config && config->Boolean( "gyroscopes.MPU6050.DLPF", true ) ) { // Enable DLPF if ( mpu9250 or icm20608 ) { // No ext sync, DLPF at 98Hz for the gyro bus->Write8( MPU_6050_DEFINE, 0b00000010 ); } else { // MPU6050 : No ext sync, DLPF at 94Hz for the accel and 98Hz for the gyro: 0b00000010) (~200Hz: 0b00000001) bus->Write8( MPU_6050_DEFINE, 0b00000010 ); } // // 1 kHz sampling rate: 0b00000000 // bus->Write8( MPU_6050_SMPRT_DIV, 0b00000000 ); } else { // No ext sync, no DLPF bus->Write8( MPU_6050_DEFINE, 0b00000000 ); // if ( ( mpu9250 or icm20608 ) and rate > 8000 ) { // bus->Write8( MPU_6050_GYRO_CONFIG, 0b00011011 ); // } } if ( config && ( mpu9250 or icm20608 ) and config->Boolean( "accelerometers.MPU6050.DLPF", true ) ) { // Enable DLPF // DLPF at 99Hz for the accel bus->Write8( MPU_6050_ACCEL_CONFIG_2, 0b00000010 ); } // Bypass mode enabled: 0b00000010 bus->Write8( MPU_6050_INT_PIN_CFG, 0b00000010 ); // No FIFO and no I2C slaves: 0b00000000 if ( dynamic_cast<SPI*>(bus) != nullptr ) { bus->Write8( MPU_6050_USER_CTRL, 0b00010000 ); // Force SPI mode } else { bus->Write8( MPU_6050_USER_CTRL, 0b00000000 ); } // TODO : use config ('use_dmp') // TODO : see https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/MPU6050_6Axis_MotionApps20.h if ( false ) { // MPU6050* mpu = new MPU6050( bus ); // delete mpu; // exit(0); } // delete i2c; // Manually add sensors to mDevices since they use the same address Sensor* mag = new MPU6050Mag( bus ); Sensor* gyro = new MPU6050Gyro( bus ); Sensor* accel = new MPU6050Accel( bus ); mDevices.push_back( mag ); mDevices.push_back( accel ); */ return gyro; } MPU6050Accel::MPU6050Accel( Bus* bus ) : Accelerometer() , mBus( bus ) , mCalibrationAccum( Vector4f() ) , mOffset( Vector3f() ) { mNames = { "MPU6050" }; mOffset.x = atof( Board::LoadRegister( "MPU6050:Accelerometer:Offset:X" ).c_str() ); mOffset.y = atof( Board::LoadRegister( "MPU6050:Accelerometer:Offset:Y" ).c_str() ); mOffset.z = atof( Board::LoadRegister( "MPU6050:Accelerometer:Offset:Z" ).c_str() ); if ( mOffset.x != 0.0f and mOffset.y != 0.0f and mOffset.z != 0.0f ) { mCalibrated = true; } } MPU6050Gyro::MPU6050Gyro( Bus* bus ) : Gyroscope() , mBus( bus ) , mCalibrationAccum( Vector4f() ) , mOffset( Vector3f() ) { mNames = { "MPU6050" }; } MPU6050Mag::MPU6050Mag( Bus* bus ) : Magnetometer() // , mI2C9150( new I2C( addr ) ) // , mI2C( new I2C( MPU_6050_I2C_MAGN_ADDRESS ) ) , mBus( bus ) , mState( 0 ) , mData{ 0 } , mCalibrationData{ 0.0f } , mBias{ 0.0f } , mBiasMin{ 32767 } , mBiasMax{ -32767 } { mNames = { "MPU6050" }; // TODO : talk to mag accros SPI if using SPI uint8_t id = 0; int ret = mBus->Read8( MPU_6050_WIA | 0x80, &id ); if ( ret < 0 or id != MPU_6050_AKM_ID ) { return; } mBus->Write8( MPU_6050_CNTL, 0x00 ); usleep( 1000 * 10 ); mBus->Write8( MPU_6050_CNTL, 0x0F ); // Enter Fuse ROM access mode usleep( 1000 * 10 ); uint8_t rawData[3]; // x/y/z gyro calibration data stored here mBus->Read( AK8963_ASAX, rawData, 3 ); mCalibrationData[0] = (float)(rawData[0] - 128)/256.0f + 1.0f; mCalibrationData[1] = (float)(rawData[1] - 128)/256.0f + 1.0f; mCalibrationData[2] = (float)(rawData[2] - 128)/256.0f + 1.0f; mBus->Write8( MPU_6050_CNTL, 0x00 ); // Configure the magnetometer for continuous read and highest resolution // set Mscale bit 4 to 1 (0) to enable 16 (14) bit resolution in CNTL register, // and enable continuous mode data acquisition Mmode (bits [3:0]), 0010 for 8 Hz and 0110 for 100 Hz sample rates mBus->Write8( MPU_6050_CNTL, 0x01 << 4 | 0x06 ); // Set magnetometer data resolution and sample ODR // Single measurement mode: 0b00000001 // mBus->Write8( MPU_6050_CNTL, 0b00000001 ); usleep( 100 * 1000 ); } MPU6050Accel::~MPU6050Accel() { } MPU6050Gyro::~MPU6050Gyro() { } MPU6050Mag::~MPU6050Mag() { } void MPU6050Accel::Calibrate( float dt, bool last_pass ) { if ( mCalibrated ) { mCalibrated = false; mCalibrationAccum = Vector4f(); mOffset = Vector3f(); } Vector3f accel; Read( &accel, true ); mCalibrationAccum += Vector4f( accel, 1.0f ); if ( last_pass ) { mOffset = mCalibrationAccum.xyz() / mCalibrationAccum.w; mCalibrationAccum = Vector4f(); mCalibrated = true; gDebug() << "MPU6050 SAVING CALIBRATED OFFSETS !"; aDebug( "mOffset", mOffset.x, mOffset.y, mOffset.z ); Board::SaveRegister( "MPU6050:Accelerometer:Offset:X", to_string( mOffset.x ) ); Board::SaveRegister( "MPU6050:Accelerometer:Offset:Y", to_string( mOffset.y ) ); Board::SaveRegister( "MPU6050:Accelerometer:Offset:Z", to_string( mOffset.z ) ); } } void MPU6050Gyro::Calibrate( float dt, bool last_pass ) { if ( mCalibrated ) { mCalibrated = false; mCalibrationAccum = Vector4f(); mOffset = Vector3f(); } Vector3f gyro; Read( &gyro, true ); mCalibrationAccum += Vector4f( gyro, 1.0f ); if ( last_pass ) { mOffset = mCalibrationAccum.xyz() / mCalibrationAccum.w; mCalibrationAccum = Vector4f(); mCalibrated = true; } } void MPU6050Mag::Calibrate( float dt, bool last_pass ) { const float MPU9250mRes = 10.0f * 4912.0f / 32760.0f; int16_t raw_vec[3]; uint8_t state = 0; uint8_t rawData[7]; // x/y/z gyro register data, ST2 register stored here, must read ST2 at end of data acquisition mBus->Read8( MPU_6050_ST1, &state ); if ( state & 0x01 ) { // wait for magnetometer data ready bit to be set mBus->Read( MPU_6050_HXL, rawData, 7 ); // Read the six raw data and ST2 registers sequentially into data array uint8_t c = rawData[6]; // End data read by reading ST2 register if ( !( c & 0x08 ) ) { // Check if magnetic sensor overflow set, if not then report data raw_vec[0] = ((int16_t)rawData[1] << 8) | rawData[0]; // Turn the MSB and LSB into a signed 16-bit value raw_vec[1] = ((int16_t)rawData[3] << 8) | rawData[2]; // Data stored as little Endian raw_vec[2] = ((int16_t)rawData[5] << 8) | rawData[4]; for ( uint32_t i = 0; i < 3; i++ ) { mBiasMax[i] = max( mBiasMax[i], raw_vec[i] ); mBiasMin[i] = min( mBiasMin[i], raw_vec[i] ); } } } if ( last_pass ) { mBias[0] = (float)( ( mBiasMax[0] + mBiasMin[0] ) / 2 ) * MPU9250mRes * mCalibrationData[0]; mBias[1] = (float)( ( mBiasMax[1] + mBiasMin[1] ) / 2 ) * MPU9250mRes * mCalibrationData[1]; mBias[2] = (float)( ( mBiasMax[2] + mBiasMin[2] ) / 2 ) * MPU9250mRes * mCalibrationData[2]; mCalibrated = true; printf( "mBias : %.2f, %.2f, %.2f\n", mBias[0], mBias[1], mBias[2] ); } } void MPU6050Accel::Read( Vector3f* v, bool raw ) { int16_t curr[3] = { 0 }; uint8_t saccel[6] = { 0 }; mBus->Read( MPU_6050_ACCEL_XOUT_H | 0x80, saccel, sizeof(saccel) ); curr[0] = (int16_t)( saccel[0] << 8 | saccel[1] ); curr[1] = (int16_t)( saccel[2] << 8 | saccel[3] ); curr[2] = (int16_t)( saccel[4] << 8 | saccel[5] ); v->x = (float)( curr[0] ) * 8.0f * 6.103515625e-04f; v->y = (float)( curr[1] ) * 8.0f * 6.103515625e-04f; v->z = (float)( curr[2] ) * 8.0f * 6.103515625e-04f; ApplySwap( *v ); if ( not raw ) { v->x -= mOffset.x; v->y -= mOffset.y; } mLastValues = *v; } int MPU6050Gyro::Read( Vector3f* v, bool raw ) { // int16_t sgyro[3] = { 0 }; uint8_t sgyro[6] = { 0 }; if ( mBus->Read( MPU_6050_GYRO_XOUT_H | 0x80, sgyro, sizeof(sgyro) ) != sizeof(sgyro) ) { return -1; } v->x = (float)( (int16_t)( sgyro[0] << 8 | sgyro[1] ) ) * 0.061037018952f; v->y = (float)( (int16_t)( sgyro[2] << 8 | sgyro[3] ) ) * 0.061037018952f; v->z = (float)( (int16_t)( sgyro[4] << 8 | sgyro[5] ) ) * 0.061037018952f; ApplySwap( *v ); if ( not raw ) { v->x -= mOffset.x; v->y -= mOffset.y; v->z -= mOffset.z; } mLastValues = *v; return 3; } void MPU6050Mag::Read( Vector3f* v, bool raw ) { float mx, my, mz; const float MPU9250mRes = 10.0f * 4912.0f / 32760.0f; int16_t raw_vec[3]; uint8_t state = 0; uint8_t rawData[7]; // x/y/z gyro register data, ST2 register stored here, must read ST2 at end of data acquisition mBus->Read8( MPU_6050_ST1, &state ); if ( state & 0x01 ) { // wait for magnetometer data ready bit to be set mBus->Read( MPU_6050_HXL, rawData, 7 ); // Read the six raw data and ST2 registers sequentially into data array uint8_t c = rawData[6]; // End data read by reading ST2 register if ( !( c & 0x08 ) ) { // Check if magnetic sensor overflow set, if not then report data raw_vec[0] = ((int16_t)rawData[1] << 8) | rawData[0]; // Turn the MSB and LSB into a signed 16-bit value raw_vec[1] = ((int16_t)rawData[3] << 8) | rawData[2]; // Data stored as little Endian raw_vec[2] = ((int16_t)rawData[5] << 8) | rawData[4]; } } mx = (float)raw_vec[0] * MPU9250mRes * mCalibrationData[0] - mBias[0]; my = (float)raw_vec[1] * MPU9250mRes * mCalibrationData[1] - mBias[1]; mz = (float)raw_vec[2] * MPU9250mRes * mCalibrationData[2] - mBias[2]; v->x = mx; v->y = my; v->z = mz; /* switch( mState ) { case 0 : { // Check if data is ready. uint8_t status = 0; mBus->Read8( MPU_6050_ST1, &status ); if ( status & 0x01 ) { mState = 1; } // Duplicate last measurements *v = mLastValues; break; } case 1 : { // Read X axis for ( int i = 0; i < 2; i++ ) { mBus->Read8( MPU_6050_HXL + i, &mData[i] ); } mState = 2; // Duplicate last measurements *v = mLastValues; break; } case 2 : { // Read Y axis for ( int i = 2; i < 4; i++ ) { mBus->Read8( MPU_6050_HXL + i, &mData[i] ); } mState = 3; // Duplicate last measurements *v = mLastValues; break; } case 3 : { // Read Z axis for ( int i = 4; i < 6; i++ ) { mBus->Read8( MPU_6050_HXL + i, &mData[i] ); } v->x = (float)( (int16_t)( mData[1] << 8 | mData[0] ) ) * 0.3001221001221001f; v->y = (float)( (int16_t)( mData[3] << 8 | mData[2] ) ) * 0.3001221001221001f; v->z = (float)( (int16_t)( mData[5] << 8 | mData[4] ) ) * 0.3001221001221001f; mLastValues = *v; // Re-arm single measurement mode mBus->Write8( MPU_6050_CNTL, 0b00000001 ); mState = 0; break; } default : { mState = 0; } } */ } LuaValue MPU6050Gyro::infos() { LuaValue ret; ret["Bus"] = mBus->infos(); ret["Resolution"] = "16 bits"; ret["Scale"] = "2000°/s"; return ret; } LuaValue MPU6050Accel::infos() { LuaValue ret; ret["Bus"] = mBus->infos(); ret["Resolution"] = "16 bits"; ret["Scale"] = "16g"; return ret; } LuaValue MPU6050Mag::infos() { return ""; // TODO // return "I2Caddr = " + to_string( mBus->address() ) + ", " + "Resolution = \"13 bits\", " + "Scale = \"1200μT\""; }
15,215
C++
.cpp
430
32.923256
130
0.654386
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,750
SR04.cpp
dridri_bcflight/flight/sensors/SR04.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <unistd.h> #include <Debug.h> #include <GPIO.h> #include "SR04.h" #include "Config.h" int SR04::flight_register( Main* main ) { Device dev; dev.iI2CAddr = 0; dev.name = "SR04"; dev.fInstanciate = SR04::Instanciate; mKnownDevices.push_back( dev ); return 0; } Sensor* SR04::Instanciate( Config* config, const string& object, Bus* bus ) { // TODO : handle bus ? SR04* sr04 = new SR04( config->Integer( object + ".gpio_trigger" ), config->Integer( object + ".gpio_echo" ) ); return sr04; } SR04::SR04( uint32_t gpio_trigger, uint32_t gpio_echo ) : Altimeter() , mTriggerPin( gpio_trigger ) , mEchoPin( gpio_echo ) , mRiseTick( 0 ) , mAltitude( 0.0f ) { mNames.emplace_back( "SR04" ); mNames.emplace_back( "sr04" ); GPIO::setMode( mTriggerPin, GPIO::Output ); GPIO::setMode( mEchoPin, GPIO::Input ); GPIO::SetupInterrupt( mEchoPin, GPIO::Both, [this](){ this->Interrupt(); } ); } SR04::~SR04() { } void SR04::Calibrate( float dt, bool last_pass ) { } void SR04::Interrupt() { mISRLock.lock(); if ( mRiseTick == 0 ) { mRiseTick = Board::GetTicks(); } else { uint64_t time = Board::GetTicks() - mRiseTick; mRiseTick = 0; if ( time > 40000 ) { mAltitude = 0.0f; } else { mAltitude = ( (float)time / 58.0f - 1.0f ) / 100.0f; } } mISRLock.unlock(); } void SR04::Read( float* altitude ) { GPIO::Write( mTriggerPin, true ); usleep( 12 ); GPIO::Write( mTriggerPin, false ); *altitude = mAltitude; } LuaValue SR04::infos() { LuaValue ret; ret["Trigger Pin"] = mTriggerPin; ret["Echo Pin"] = mEchoPin; return ret; }
2,295
C++
.cpp
86
24.662791
112
0.698036
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,751
ICM4xxxx.cpp
dridri_bcflight/flight/sensors/ICM4xxxx.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <cmath> #include <unistd.h> #include "ICM4xxxx.h" #include "Config.h" #include "SPI.h" static const map< uint8_t, string > known = { { 0x42, "ICM-42605" } }; static const map< uint8_t, bool > hasMagnetometer = { { 0x42, false } }; ICM4xxxx::ICM4xxxx() : Sensor() , mChipReady( false ) , mGyroscope( nullptr ) , mAccelerometer( nullptr ) , mMagnetometer( nullptr ) , dmpReady( false ) { } void ICM4xxxx::InitChip() { uint8_t read_reg = 0; if ( dynamic_cast<SPI*>(mBus) != nullptr ) { read_reg = 0x80; } mBus->Connect(); uint8_t whoami = 0x00; mBus->Read8( read_reg | ICM_4xxxx_WHO_AM_I, &whoami ); gDebug() << "whoami : " << hex << showbase << (int)whoami; if ( known.find( whoami ) != known.end() ) { gDebug() << "ICM4xxxx module at " << mBus->toString() << " is " << known.at(whoami); mName = known.at(whoami); } else { gWarning() << "Unknown ICM4xxxx module at " << mBus->toString() << ", continuing anyway"; } mBus->Write8( ICM_4xxxx_DEVICE_CONFIG, 0b00000001 ); usleep( 1000 * 10 ); mBus->Write8( ICM_4xxxx_DEVICE_CONFIG, 0b00000001 ); usleep( 1000 * 10 ); mBus->Write8( ICM_4xxxx_DEVICE_CONFIG, 0b00000001 ); usleep( 1000 * 10 ); // Disable all sensors while configuring mBus->Write8( ICM_4xxxx_PWR_MGMT0, 0b00000000 ); // Can be tweaked to : // 249Hz : (21, 440, 6) // 524Hz : (39, 1536, 4) // 995Hz : (63, 3968, 3) mBus->Write8( ICM_4xxxx_BANK_SEL, ICM_4xxxx_BANK_SELECT1 ); mBus->Write8( ICM_4xxxx_GYRO_CONFIG_STATIC3, 21 ); mBus->Write8( ICM_4xxxx_GYRO_CONFIG_STATIC4, 440 & 0xFF ); mBus->Write8( ICM_4xxxx_GYRO_CONFIG_STATIC5, (440 >> 8) | (6 << 4) ); // Fixed values for accelerometer mBus->Write8( ICM_4xxxx_BANK_SEL, ICM_4xxxx_BANK_SELECT2 ); mBus->Write8( ICM_4xxxx_ACCEL_CONFIG_STATIC2, 21 ); mBus->Write8( ICM_4xxxx_ACCEL_CONFIG_STATIC3, 440 & 0xFF ); mBus->Write8( ICM_4xxxx_ACCEL_CONFIG_STATIC4, (440 >> 8) | (6 << 4) ); mBus->Write8( ICM_4xxxx_BANK_SEL, ICM_4xxxx_BANK_SELECT0 ); // Accel & Gyro LPF : Low-latency mBus->Write8( ICM_4xxxx_GYRO_ACCEL_CONFIG0, ( 14 << 4 ) | 14 ); // mBus->Write8( ICM_4xxxx_GYRO_ACCEL_CONFIG0, ( 7 << 4 ) | 7 ); // mBus->Write8( ICM_4xxxx_INTF_CONFIG0, 0b00000011 ); mBus->Write8( ICM_4xxxx_INTF_CONFIG0, 0b00110000 ); // uint8_t config1 = 0; // mBus->Read8( ICM_4xxxx_INTF_CONFIG1, &config1 ); // config1 &= ~0xC0; // AFSR mask // config1 |= 0x40; // AFSR disable // mBus->Write8( ICM_4xxxx_INTF_CONFIG1, config1 ); mBus->Write8( ICM_4xxxx_INTF_CONFIG6, 0b01010011 ); mBus->Write8( ICM_4xxxx_DRIVE_CONFIG, 0b00000101 ); mBus->Write8( ICM_4xxxx_FIFO_CONFIG, 0b00000000 ); mBus->Write8( ICM_4xxxx_INT_CONFIG0, 0b00011011 ); mBus->Write8( ICM_4xxxx_INT_CONFIG1, 0b01100000 ); // Disable all interrupts mBus->Write8( ICM_4xxxx_INT_SOURCE0, 0b00001000 ); mBus->Write8( ICM_4xxxx_INT_SOURCE1, 0b00000000 ); mBus->Write8( ICM_4xxxx_INT_SOURCE3, 0b00000000 ); mBus->Write8( ICM_4xxxx_INT_SOURCE4, 0b00000000 ); // Disable all FIFOs: 0b00000000 mBus->Write8( ICM_4xxxx_FIFO_CONFIG1, 0b00000000 ); mBus->Write8( ICM_4xxxx_FIFO_CONFIG2, 0b00000000 ); mBus->Write8( ICM_4xxxx_FIFO_CONFIG3, 0b00000000 ); // Enable all sensors in low-noise mode + never go idle mBus->Write8( ICM_4xxxx_PWR_MGMT0, 0b00011111 ); uint32_t loopTime = Main::instance()->config()->Integer( "stabilizer.loop_time", 2000 ); uint32_t loopRate = 1000000 / loopTime; const std::list< std::tuple< uint32_t, uint8_t > > rates = { { 25, 0b00001010 }, { 50, 0b00001001 }, { 100, 0b00001000 }, { 200, 0b00000111 }, { 500, 0b00001111 }, { 1000, 0b00000110 }, { 2000, 0b00000101 }, { 4000, 0b00000100 }, { 8000, 0b00000011 }, }; uint8_t rate = 0b00000000; for ( auto r : rates ) { if ( loopRate <= std::get<0>(r) ) { rate = std::get<1>(r); break; } } gDebug() << "Setting ICM4xxxx rate to " << loopRate << "Hz (" << (int)rate << ")"; mBus->Write8( ICM_4xxxx_GYRO_CONFIG0, rate ); mBus->Write8( ICM_4xxxx_ACCEL_CONFIG0, rate ); mChipReady = true; } ICM4xxxxGyro* ICM4xxxx::gyroscope() { if ( !mChipReady ) { InitChip(); } if ( !mGyroscope ) { mGyroscope = new ICM4xxxxGyro( mBus, mName ); if ( mSwapMode == SwapModeAxis ) { mGyroscope->setAxisSwap(mAxisSwap); } if ( mSwapMode == SwapModeMatrix ) { mGyroscope->setAxisMatrix(mAxisMatrix); } } return mGyroscope; } ICM4xxxxAccel* ICM4xxxx::accelerometer() { if ( !mChipReady ) { InitChip(); } if ( !mAccelerometer ) { mAccelerometer = new ICM4xxxxAccel( mBus, mName ); if ( mSwapMode == SwapModeAxis ) { mAccelerometer->setAxisSwap(mAxisSwap); } if ( mSwapMode == SwapModeMatrix ) { mAccelerometer->setAxisMatrix(mAxisMatrix); } } return mAccelerometer; } ICM4xxxxMag* ICM4xxxx::magnetometer() { if ( !mChipReady ) { InitChip(); } if ( !mMagnetometer and hasMagnetometer.at( mWhoAmI ) ) { mMagnetometer = new ICM4xxxxMag( mBus, mName ); if ( mSwapMode == SwapModeAxis ) { mMagnetometer->setAxisSwap(mAxisSwap); } if ( mSwapMode == SwapModeMatrix ) { mMagnetometer->setAxisMatrix(mAxisMatrix); } } return mMagnetometer; } void ICM4xxxx::setGyroscopeAxisSwap( const Vector4i& swap ) { gyroscope()->setAxisSwap( swap ); } void ICM4xxxx::setAccelerometerAxisSwap( const Vector4i& swap ) { accelerometer()->setAxisSwap( swap ); } void ICM4xxxx::setMagnetometerAxisSwap( const Vector4i& swap ) { magnetometer()->setAxisSwap( swap ); } ICM4xxxxAccel::ICM4xxxxAccel( Bus* bus, const std::string& name ) : Accelerometer() , mBus( bus ) , mCalibrationAccum( Vector4f() ) , mOffset( Vector3f() ) { mNames = { name }; mOffset.x = atof( Board::LoadRegister( "ICM4xxxx<" + mBus->toString() + ">:Accelerometer:Offset:X" ).c_str() ); mOffset.y = atof( Board::LoadRegister( "ICM4xxxx<" + mBus->toString() + ">:Accelerometer:Offset:Y" ).c_str() ); mOffset.z = atof( Board::LoadRegister( "ICM4xxxx<" + mBus->toString() + ">:Accelerometer:Offset:Z" ).c_str() ); if ( mOffset.x != 0.0f and mOffset.y != 0.0f and mOffset.z != 0.0f ) { mCalibrated = true; } } ICM4xxxxGyro::ICM4xxxxGyro( Bus* bus, const std::string& name ) : Gyroscope() , mBus( bus ) , mCalibrationAccum( Vector4f() ) , mOffset( Vector3f() ) { mNames = { name }; } ICM4xxxxMag::ICM4xxxxMag( Bus* bus, const std::string& name ) : Magnetometer() // , mI2C9150( new I2C( addr ) ) // , mI2C( new I2C( ICM_4xxxx_I2C_MAGN_ADDRESS ) ) , mBus( bus ) , mState( 0 ) , mData{ 0 } , mCalibrationData{ 0.0f } , mBias{ 0.0f } , mBiasMin{ 32767 } , mBiasMax{ -32767 } { mNames = { name }; // TODO : talk to mag accross SPI if using SPI // TODO /* uint8_t id = 0; int ret = mBus->Read8( ICM_4xxxx_WIA | 0x80, &id ); if ( ret < 0 or id != ICM_4xxxx_AKM_ID ) { return; } mBus->Write8( ICM_4xxxx_CNTL, 0x00 ); usleep( 1000 * 10 ); mBus->Write8( ICM_4xxxx_CNTL, 0x0F ); // Enter Fuse ROM access mode usleep( 1000 * 10 ); uint8_t rawData[3]; // x/y/z gyro calibration data stored here mBus->Read( AK8963_ASAX, rawData, 3 ); mCalibrationData[0] = (float)(rawData[0] - 128)/256.0f + 1.0f; mCalibrationData[1] = (float)(rawData[1] - 128)/256.0f + 1.0f; mCalibrationData[2] = (float)(rawData[2] - 128)/256.0f + 1.0f; mBus->Write8( ICM_4xxxx_CNTL, 0x00 ); // Configure the magnetometer for continuous read and highest resolution // set Mscale bit 4 to 1 (0) to enable 16 (14) bit resolution in CNTL register, // and enable continuous mode data acquisition Mmode (bits [3:0]), 0010 for 8 Hz and 0110 for 100 Hz sample rates mBus->Write8( ICM_4xxxx_CNTL, 0x01 << 4 | 0x06 ); // Set magnetometer data resolution and sample ODR // Single measurement mode: 0b00000001 // mBus->Write8( ICM_4xxxx_CNTL, 0b00000001 ); usleep( 100 * 1000 ); */ } ICM4xxxxAccel::~ICM4xxxxAccel() { } ICM4xxxxGyro::~ICM4xxxxGyro() { } ICM4xxxxMag::~ICM4xxxxMag() { } void ICM4xxxxAccel::Calibrate( float dt, bool last_pass ) { if ( mCalibrated ) { mCalibrated = false; mCalibrationAccum = Vector4f(); mOffset = Vector3f(); } Vector3f accel( 0.0f, 0.0f, 0.0f ); Read( &accel, true ); mCalibrationAccum += Vector4f( accel, 1.0f ); if ( last_pass ) { mOffset = mCalibrationAccum.xyz() / mCalibrationAccum.w; mCalibrationAccum = Vector4f(); mCalibrated = true; gDebug() << "ICM4xxxx SAVING CALIBRATED OFFSETS !"; aDebug( "mOffset", mOffset.x, mOffset.y, mOffset.z ); Board::SaveRegister( "ICM4xxxx<" + mBus->toString() + ">:Accelerometer:Offset:X", to_string( mOffset.x ) ); Board::SaveRegister( "ICM4xxxx<" + mBus->toString() + ">:Accelerometer:Offset:Y", to_string( mOffset.y ) ); Board::SaveRegister( "ICM4xxxx<" + mBus->toString() + ">:Accelerometer:Offset:Z", to_string( mOffset.z ) ); } } void ICM4xxxxGyro::Calibrate( float dt, bool last_pass ) { if ( mCalibrated ) { mCalibrated = false; mCalibrationAccum = Vector4f(); mOffset = Vector3f(); } Vector3f gyro( 0.0f, 0.0f, 0.0f ); Read( &gyro, true ); mCalibrationAccum += Vector4f( gyro, 1.0f ); if ( last_pass ) { mOffset = mCalibrationAccum.xyz() / mCalibrationAccum.w; mCalibrationAccum = Vector4f(); mCalibrated = true; aDebug( "mOffset", mOffset.x, mOffset.y, mOffset.z ); } } void ICM4xxxxMag::Calibrate( float dt, bool last_pass ) { mCalibrated = true; /* const float MPU9250mRes = 10.0f * 4912.0f / 32760.0f; int16_t raw_vec[3]; uint8_t state = 0; uint8_t rawData[7]; // x/y/z gyro register data, ST2 register stored here, must read ST2 at end of data acquisition mBus->Read8( ICM_4xxxx_ST1, &state ); if ( state & 0x01 ) { // wait for magnetometer data ready bit to be set mBus->Read( ICM_4xxxx_HXL, rawData, 7 ); // Read the six raw data and ST2 registers sequentially into data array uint8_t c = rawData[6]; // End data read by reading ST2 register if ( !( c & 0x08 ) ) { // Check if magnetic sensor overflow set, if not then report data raw_vec[0] = ((int16_t)rawData[1] << 8) | rawData[0]; // Turn the MSB and LSB into a signed 16-bit value raw_vec[1] = ((int16_t)rawData[3] << 8) | rawData[2]; // Data stored as little Endian raw_vec[2] = ((int16_t)rawData[5] << 8) | rawData[4]; for ( uint32_t i = 0; i < 3; i++ ) { mBiasMax[i] = max( mBiasMax[i], raw_vec[i] ); mBiasMin[i] = min( mBiasMin[i], raw_vec[i] ); } } } if ( last_pass ) { mBias[0] = (float)( ( mBiasMax[0] + mBiasMin[0] ) / 2 ) * MPU9250mRes * mCalibrationData[0]; mBias[1] = (float)( ( mBiasMax[1] + mBiasMin[1] ) / 2 ) * MPU9250mRes * mCalibrationData[1]; mBias[2] = (float)( ( mBiasMax[2] + mBiasMin[2] ) / 2 ) * MPU9250mRes * mCalibrationData[2]; mCalibrated = true; printf( "mBias : %.2f, %.2f, %.2f\n", mBias[0], mBias[1], mBias[2] ); } */ } void ICM4xxxxAccel::Read( Vector3f* v, bool raw ) { int16_t curr[3] = { 0 }; uint8_t saccel[6] = { 0 }; int r = mBus->Read( ICM_4xxxx_ACCEL_DATA_X1 | 0x80, saccel, sizeof(saccel) ); curr[0] = (int16_t)( saccel[0] << 8 | saccel[1] ); curr[1] = (int16_t)( saccel[2] << 8 | saccel[3] ); curr[2] = (int16_t)( saccel[4] << 8 | saccel[5] ); v->x = (float)( curr[0] ) * 8.0f * 6.103515625e-04f; v->y = (float)( curr[1] ) * 8.0f * 6.103515625e-04f; v->z = (float)( curr[2] ) * 8.0f * 6.103515625e-04f; ApplySwap( *v ); if ( not raw ) { v->x -= mOffset.x; v->y -= mOffset.y; } mLastValues = *v; } int ICM4xxxxGyro::Read( Vector3f* v, bool raw ) { // fDebug(); // int16_t sgyro[3] = { 0 }; uint8_t sgyro[6] = { 0 }; int ret = 0; ret = mBus->Read( ICM_4xxxx_GYRO_DATA_X1 | 0x80, sgyro, sizeof(sgyro) ); if ( ret != sizeof(sgyro) ) { gWarning() << "read " << ret << " bytes instead of " << sizeof(sgyro); return -1; } v->x = (float)( (int16_t)( sgyro[0] << 8 | sgyro[1] ) ) * 0.061037018952f; v->y = (float)( (int16_t)( sgyro[2] << 8 | sgyro[3] ) ) * 0.061037018952f; v->z = (float)( (int16_t)( sgyro[4] << 8 | sgyro[5] ) ) * 0.061037018952f; ApplySwap( *v ); if ( not raw ) { v->x -= mOffset.x; v->y -= mOffset.y; v->z -= mOffset.z; } mLastValues = *v; // gDebug() << "ret 3"; return 3; } void ICM4xxxxMag::Read( Vector3f* v, bool raw ) {/* float mx, my, mz; const float MPU9250mRes = 10.0f * 4912.0f / 32760.0f; int16_t raw_vec[3]; uint8_t state = 0; uint8_t rawData[7]; // x/y/z gyro register data, ST2 register stored here, must read ST2 at end of data acquisition mBus->Read8( ICM_4xxxx_ST1, &state ); if ( state & 0x01 ) { // wait for magnetometer data ready bit to be set mBus->Read( ICM_4xxxx_HXL, rawData, 7 ); // Read the six raw data and ST2 registers sequentially into data array uint8_t c = rawData[6]; // End data read by reading ST2 register if ( !( c & 0x08 ) ) { // Check if magnetic sensor overflow set, if not then report data raw_vec[0] = ((int16_t)rawData[1] << 8) | rawData[0]; // Turn the MSB and LSB into a signed 16-bit value raw_vec[1] = ((int16_t)rawData[3] << 8) | rawData[2]; // Data stored as little Endian raw_vec[2] = ((int16_t)rawData[5] << 8) | rawData[4]; } } mx = (float)raw_vec[0] * MPU9250mRes * mCalibrationData[0] - mBias[0]; my = (float)raw_vec[1] * MPU9250mRes * mCalibrationData[1] - mBias[1]; mz = (float)raw_vec[2] * MPU9250mRes * mCalibrationData[2] - mBias[2]; v->x = mx; v->y = my; v->z = mz; */ /* switch( mState ) { case 0 : { // Check if data is ready. uint8_t status = 0; mBus->Read8( ICM_4xxxx_ST1, &status ); if ( status & 0x01 ) { mState = 1; } // Duplicate last measurements *v = mLastValues; break; } case 1 : { // Read X axis for ( int i = 0; i < 2; i++ ) { mBus->Read8( ICM_4xxxx_HXL + i, &mData[i] ); } mState = 2; // Duplicate last measurements *v = mLastValues; break; } case 2 : { // Read Y axis for ( int i = 2; i < 4; i++ ) { mBus->Read8( ICM_4xxxx_HXL + i, &mData[i] ); } mState = 3; // Duplicate last measurements *v = mLastValues; break; } case 3 : { // Read Z axis for ( int i = 4; i < 6; i++ ) { mBus->Read8( ICM_4xxxx_HXL + i, &mData[i] ); } v->x = (float)( (int16_t)( mData[1] << 8 | mData[0] ) ) * 0.3001221001221001f; v->y = (float)( (int16_t)( mData[3] << 8 | mData[2] ) ) * 0.3001221001221001f; v->z = (float)( (int16_t)( mData[5] << 8 | mData[4] ) ) * 0.3001221001221001f; mLastValues = *v; // Re-arm single measurement mode mBus->Write8( ICM_4xxxx_CNTL, 0b00000001 ); mState = 0; break; } default : { mState = 0; } } */ } LuaValue ICM4xxxxGyro::infos() { LuaValue ret; ret["bus"] = mBus->infos(); // TODO : read from chip ret["precision"] = "16 bits"; ret["scale"] = "2000°/s"; ret["sample_rate"] = "1kHz"; ret["swap_axis"] = swapInfos(); return ret; } LuaValue ICM4xxxxAccel::infos() { LuaValue ret; ret["bus"] = mBus->infos(); // TODO : read from chip ret["precision"] = "16 bits"; ret["scale"] = "16g"; ret["sample_rate"] = "1kHz"; ret["swap_axis"] = swapInfos(); return ret; } LuaValue ICM4xxxxMag::infos() { return ""; // TODO }
15,646
C++
.cpp
472
30.663136
117
0.654474
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,752
BMP280.cpp
dridri_bcflight/flight/sensors/BMP280.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <unistd.h> #include <cmath> #include "BMP280.h" #include "Lua.h" #define BMP280_REGISTER_DIG_T1 0x88 #define BMP280_REGISTER_DIG_T2 0x8A #define BMP280_REGISTER_DIG_T3 0x8C #define BMP280_REGISTER_DIG_P1 0x8E #define BMP280_REGISTER_DIG_P2 0x90 #define BMP280_REGISTER_DIG_P3 0x92 #define BMP280_REGISTER_DIG_P4 0x94 #define BMP280_REGISTER_DIG_P5 0x96 #define BMP280_REGISTER_DIG_P6 0x98 #define BMP280_REGISTER_DIG_P7 0x9A #define BMP280_REGISTER_DIG_P8 0x9C #define BMP280_REGISTER_DIG_P9 0x9E #define BMP280_REGISTER_CHIPID 0xD0 #define BMP280_REGISTER_VERSION 0xD1 #define BMP280_REGISTER_SOFTRESET 0xE0 #define BMP280_REGISTER_CAL26 0xE1 #define BMP280_REGISTER_CONTROL 0xF4 #define BMP280_REGISTER_CONFIG 0xF5 #define BMP280_REGISTER_PRESSUREDATA 0xF7 #define BMP280_REGISTER_TEMPDATA 0xFA BMP280::BMP280() : Altimeter() , mI2C( new I2C( 0x76 ) ) , mBaseAltitudeAccum( Vector2f() ) { mNames.emplace_back( "BMP280" ); mNames.emplace_back( "bmp280" ); mI2C->Read16( BMP280_REGISTER_DIG_T1, &dig_T1 ); mI2C->Read16( BMP280_REGISTER_DIG_T2, &dig_T2 ); mI2C->Read16( BMP280_REGISTER_DIG_T3, &dig_T3 ); mI2C->Read16( BMP280_REGISTER_DIG_P1, &dig_P1 ); mI2C->Read16( BMP280_REGISTER_DIG_P2, &dig_P2 ); mI2C->Read16( BMP280_REGISTER_DIG_P3, &dig_P3 ); mI2C->Read16( BMP280_REGISTER_DIG_P4, &dig_P4 ); mI2C->Read16( BMP280_REGISTER_DIG_P5, &dig_P5 ); mI2C->Read16( BMP280_REGISTER_DIG_P6, &dig_P6 ); mI2C->Read16( BMP280_REGISTER_DIG_P7, &dig_P7 ); mI2C->Read16( BMP280_REGISTER_DIG_P8, &dig_P8 ); mI2C->Read16( BMP280_REGISTER_DIG_P9, &dig_P9 ); // mI2C->Write8( BMP280_REGISTER_CONTROL, 0x3F ); mI2C->Write8( BMP280_REGISTER_CONTROL, 0b10110111 ); } BMP280::~BMP280() { } void BMP280::Calibrate( float dt, bool last_pass ) { (void)dt; const float seaLevelhPA = 1013.25; const float p = ReadPressure(); if ( p > 0.0f ) { float altitude = 44330.0 * ( 1.0 - pow( p / seaLevelhPA, 0.1903 ) ); mBaseAltitudeAccum += Vector2f( altitude, 1.0f ); } if ( last_pass ) { mBaseAltitude = mBaseAltitudeAccum.x / mBaseAltitudeAccum.y; mBaseAltitudeAccum = Vector2f(); } } float BMP280::ReadTemperature() { int32_t var1, var2; uint32_t adc_T; mI2C->Read24( BMP280_REGISTER_TEMPDATA, &adc_T ); adc_T >>= 4; var1 = ( ( ( (adc_T>>3) - ((int32_t)dig_T1<<1) ) ) * ((int32_t)dig_T2) ) >> 11; var2 = ( ( ( ( (adc_T>>4) - ((int32_t)dig_T1) ) * ( (adc_T>>4) - ((int32_t)dig_T1) ) ) >> 12 ) * ((int32_t)dig_T3)) >> 14; t_fine = var1 + var2; float T = (float)( ( t_fine * 5 + 128 ) >> 8 ); return T / 100.0f; } float BMP280::ReadPressure() { int64_t var1, var2, p; uint32_t adc_P; // Must be done first to get the t_fine variable set up ReadTemperature(); mI2C->Read24( BMP280_REGISTER_PRESSUREDATA, &adc_P ); adc_P >>= 4; var1 = ((int64_t)t_fine) - 128000; var2 = var1 * var1 * (int64_t)dig_P6; var2 = var2 + ( ( var1 * (int64_t)dig_P5 ) << 17 ); var2 = var2 + ( ((int64_t)dig_P4) << 35 ); var1 = ( ( var1 * var1 * (int64_t)dig_P3 ) >> 8 ) + ( ( var1 * (int64_t)dig_P2 ) << 12 ); var1 = ( ( ( ((int64_t)1) << 47) + var1 ) ) * ((int64_t)dig_P1) >> 33; if ( var1 == 0 ) { return 0.0f; // avoid exception caused by division by zero } p = 1048576 - adc_P; p = ( ( ( p << 31 ) - var2 ) * 3125 ) / var1; var1 = ( ((int64_t)dig_P9) * (p>>13) * (p>>13) ) >> 25; var2 = ( ((int64_t)dig_P8) * p ) >> 19; p = ( ( p + var1 + var2 ) >> 8 ) + ( ((int64_t)dig_P7) << 4 ); return (float)p / 256.0f / 100.0f; } void BMP280::Read( float* altitude ) { const float seaLevelhPA = 1013.25; const float p = ReadPressure(); if ( p > 0.0f ) { *altitude = ( 44330.0 * ( 1.0 - pow( p / seaLevelhPA, 0.1903 ) ) - mBaseAltitude ); } } LuaValue BMP280::infos() { LuaValue ret; ret["Bus"] = mI2C->infos(); return ret; }
4,604
C++
.cpp
130
33.461538
123
0.659536
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,753
FakeAccelerometer.cpp
dridri_bcflight/flight/sensors/fake_sensors/FakeAccelerometer.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #ifdef BOARD_generic #include <cmath> #include "FakeAccelerometer.h" FakeAccelerometer::FakeAccelerometer( int axisCount, const Vector3f& noiseGain ) : Accelerometer() , mAxisCount( axisCount ) , mNoiseGain( noiseGain ) , mSinCounter( 0.0f ) { mNames = { "FakeAccelerometer" }; } FakeAccelerometer::~FakeAccelerometer() { } void FakeAccelerometer::Calibrate( float dt, bool last_pass ) { } void FakeAccelerometer::Read( Vector3f* v, bool raw ) { for ( int i = 0; i < mAxisCount; i++ ) { v->operator[](0) = 0.0f * sin( mSinCounter ) + mNoiseGain[0] * ( (float)( rand() % 65536 ) - 32768.0f ) / 32768.0f; v->operator[](1) = mNoiseGain[1] * ( (float)( rand() % 65536 ) - 32768.0f ) / 32768.0f; v->operator[](2) = 9.8f + mNoiseGain[2] * ( (float)( rand() % 65536 ) - 32768.0f ) / 32768.0f; } mLastValues = *v; mSinCounter += 0.01; } LuaValue FakeAccelerometer::infos() { LuaValue ret; ret["Resolution"] = "32 bits float"; ret["Scale"] = "16g"; return ret; } #endif // BOARD_generic
1,726
C++
.cpp
52
31.192308
117
0.707052
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,754
FakeGyroscope.cpp
dridri_bcflight/flight/sensors/fake_sensors/FakeGyroscope.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #ifdef BOARD_generic #include <cmath> #include "FakeGyroscope.h" FakeGyroscope::FakeGyroscope( int axisCount, const Vector3f& noiseGain ) : Gyroscope() , mAxisCount( axisCount ) , mNoiseGain( noiseGain ) , mSinCounter( 0.0f ) { mNames = { "FakeGyroscope" }; } FakeGyroscope::~FakeGyroscope() { } void FakeGyroscope::Calibrate( float dt, bool last_pass ) { } int FakeGyroscope::Read( Vector3f* v, bool raw ) { for ( int i = 0; i < mAxisCount; i++ ) { v->operator[](0) = 0.0f * sin( mSinCounter + 3.14 / 2 ) + mNoiseGain[0] * ( (float)( rand() % 65536 ) - 32768.0f ) / 32768.0f; v->operator[](1) = mNoiseGain[1] * ( (float)( rand() % 65536 ) - 32768.0f ) / 32768.0f; v->operator[](2) = mNoiseGain[2] * ( (float)( rand() % 65536 ) - 32768.0f ) / 32768.0f; } mLastValues = *v; mSinCounter += 0.1; return mAxisCount; } LuaValue FakeGyroscope::infos() { LuaValue ret; ret["Resolution"] = "32 bits float"; return ret; } #endif // BOARD_generic
1,685
C++
.cpp
52
30.403846
128
0.702719
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,755
SmartAudio.cpp
dridri_bcflight/flight/peripherals/SmartAudio.cpp
#include "SmartAudio.h" #include "Debug.h" #include <Board.h> #include <GPIO.h> #define CMD_GET_SETTINGS 0x01 #define CMD_SET_POWER 0x02 #define CMD_SET_CHANNEL 0x03 #define CMD_SET_FREQUENCY 0x04 #define CMD_SET_MODE 0x05 // TODO : run in separate thread typedef struct { uint16_t header; uint8_t command; uint8_t length; } __attribute__((packed)) SmartAudioCommand; typedef struct { std::string name; uint16_t frequencies[8]; } Band; static const std::vector< Band > vtxBandsFrequencies = { { "Boscam A", { 5865, 5845, 5825, 5805, 5785, 5765, 5745, 5725 } }, { "Boscam B", { 5733, 5752, 5771, 5790, 5809, 5828, 5847, 5866 } }, { "Boscam E", { 5705, 5685, 5665, 5645, 5885, 5905, 5925, 5945 } }, { "FatShark", { 5740, 5760, 5780, 5800, 5820, 5840, 5860, 5880 } }, { "RaceBand", { 5658, 5695, 5732, 5769, 5806, 5843, 5880, 5917 } }, }; static uint8_t crc8( const uint8_t* ptr, uint8_t len ); SmartAudio::SmartAudio( Serial* bus, uint8_t txpin, bool frequency_cmd_supported ) : mBus( bus ) , mTXPin( txpin ) , mSetFrequencySupported( frequency_cmd_supported ) , mTXStopBits( 2 ) , mRXStopBits( 1 ) , mLastCommandTick( 0 ) , mVersion( 1 ) , mFrequency( 0 ) , mPower( 0 ) , mChannel( 0 ) , mBand( 0 ) { } SmartAudio::SmartAudio() : SmartAudio( nullptr, 0, false ) { } SmartAudio::~SmartAudio() { } void SmartAudio::setStopBits( uint8_t tx, uint8_t rx ) { mTXStopBits = tx; mRXStopBits = rx; } void SmartAudio::Connect() { mBus->Connect(); Update(); } int SmartAudio::SendCommand( uint8_t cmd_code, const uint8_t* data, const uint8_t datalen ) { uint64_t tick = Board::GetTicks(); uint64_t diff = tick - mLastCommandTick; if ( diff < 200 * 1000 ) { usleep( 200*1000 - diff ); } int ret = 0; uint8_t command[32] = { 0 }; command[0] = 0x00; SmartAudioCommand* cmd = (SmartAudioCommand*)( command + 1 ); cmd->header = 0x55AA; cmd->command = ( cmd_code << 1 ) + 1; cmd->length = datalen; memcpy( command + 1 + sizeof(SmartAudioCommand), data, datalen ); uint8_t crc = crc8( (uint8_t*)cmd, sizeof(SmartAudioCommand) + datalen ); command[ 1 + sizeof(SmartAudioCommand) + datalen ] = crc; // Enter TX mode mBus->setStopBits( mTXStopBits ); GPIO::setMode( mTXPin, GPIO::Alt4 ); // Send bytes ret = mBus->Write( command, 1 + sizeof(SmartAudioCommand) + datalen + 1 ); // // Leave TX mode usleep( 1000 * 16 ); GPIO::setMode( mTXPin, GPIO::Input ); mBus->setStopBits( mRXStopBits ); // Read self echo uint8_t dummy[16] = { 0x00 }; uint8_t readi = 0; uint16_t ret2 = 0; do { int r = mBus->Read( dummy + readi, 1 ); if ( r <= 0 ) { return r; } ret2 += r; readi++; } while ( dummy[readi-1] != crc && ret2 < 16); mLastCommandTick = Board::GetTicks(); return ret; } void SmartAudio::Update() { fDebug(); SendCommand( CMD_GET_SETTINGS, nullptr, 0 ); uint8_t response[ 32 ] = { 0 }; int sz = mBus->Read( response, sizeof(response) ); SmartAudioCommand* resp = (SmartAudioCommand*)response; if ( resp->header != 0x55AA or ( resp->command & 0b00000111 ) != CMD_GET_SETTINGS ) { gDebug() << "SmartAudio: invalid response (header=" << resp->header << ", command=" << resp->command << ")"; return; } mVersion = resp->command >> 3; mChannel = response[ sizeof(SmartAudioCommand) ]; mPower = response[ sizeof(SmartAudioCommand) + 1 ]; uint8_t mode = response[ sizeof(SmartAudioCommand) + 2 ]; uint8_t freq_mode = mode & 0b00000001; mFrequency = ( response[ sizeof(SmartAudioCommand) + 3 ] << 8 ) + response[ sizeof(SmartAudioCommand) + 4 ]; mBand = mChannel / 8; if ( freq_mode == 0 ) { mFrequency = vtxBandsFrequencies[mBand].frequencies[mChannel % 8]; } // Version 3 if ( resp->command == 0x11 && resp->length > 10 ) { uint8_t maxPowers = ((uint8_t*)resp)[10]; std::vector<int32_t> powers; for ( uint8_t i = 0; i <= maxPowers && i + 11 <= resp->length + 2; i++ ) { uint8_t power = ((uint8_t*)resp)[11 + i]; powers.push_back( power ); } mPowerTable = powers; } gDebug() << "SmartAudio Update :"; gDebug() << " version : " << (int)mVersion; gDebug() << " mode : " << (int)mode; gDebug() << " channel : " << (int)mChannel; gDebug() << " power : " << (int)mPower; gDebug() << " frequency : " << (int)mFrequency << " MHz"; gDebug() << " band : " << vtxBandsFrequencies[mBand].name << "(" << mBand << ")"; if ( mPowerTable.size() > 0 ) { char powers[128] = ""; for ( uint8_t i = 0; i < mPowerTable.size(); i++ ) { char p[16] = ""; sprintf( p, "%s [%d]=%ddBm", i == 0 ? "" : ",", i, mPowerTable[i] ); strcat( powers, p ); } gDebug() << " available powers : {" << powers << " }"; } } void SmartAudio::setFrequency( uint16_t frequency ) { fDebug( (int)frequency ); if ( not mSetFrequencySupported ) { setChannel( channelFromFrequency( frequency ) ); return; } uint8_t data[2] = { 0 }; data[0] = ( frequency >> 8 ) & 0b00111111; data[1] = frequency & 0xFF; SendCommand( CMD_SET_FREQUENCY, data, 2 ); uint8_t response[ 32 ] = { 0 }; int sz = mBus->Read( response, sizeof(response) ); if ( sz <= 0 ) { gWarning() << "Setting frequency failed, no response from VTX"; return; } mFrequency = ( response[4] << 8 ) + response[5]; mChannel = channelFromFrequency( mFrequency ); mBand = mChannel / 8; gDebug() << "VTX frequency now set to " << (int)mFrequency; gDebug() << "VTX band now set to : " << vtxBandsFrequencies[mBand].name << " (" << (int)mBand << ")"; gDebug() << "VTX channel now set to " << (int)mChannel; } void SmartAudio::setPower( uint8_t power ) { fDebug( (int)power ); uint8_t data[1] = { power }; SendCommand( CMD_SET_POWER, data, 1 ); uint8_t response[ 32 ] = { 0 }; int sz = mBus->Read( response, sizeof(response) ); if ( sz <= 0 ) { gWarning() << "Setting power failed, no response from VTX"; return; } mPower = response[4]; if ( mPower < mPowerTable.size() ) { gDebug() << "VTX power now set to " << (int)mPowerTable[mPower] << " dBm"; } } void SmartAudio::setChannel( uint8_t channel ) { fDebug( (int)channel ); uint8_t data[1] = { channel }; SendCommand( CMD_SET_CHANNEL, data, 1 ); uint8_t response[ 32 ] = { 0 }; int sz = mBus->Read( response, sizeof(response) ); if ( sz <= 0 ) { gWarning() << "Setting channel failed, no response from VTX"; return; } mChannel = response[4]; mBand = mChannel / 8; mFrequency = vtxBandsFrequencies[mBand].frequencies[mChannel % 8]; gDebug() << "VTX channel now set to " << (int)mChannel; gDebug() << "VTX band now set to : " << vtxBandsFrequencies[mBand].name << " (" << (int)mBand << ")"; gDebug() << "VTX frequency now set to " << (int)mFrequency; } void SmartAudio::setMode( uint8_t mode ) { fDebug( (int)mode ); uint8_t data[1] = { mode }; SendCommand( CMD_SET_MODE, data, 1 ); uint8_t response[ 32 ] = { 0 }; int sz = mBus->Read( response, sizeof(response) ); if ( sz <= 0 ) { gWarning() << "Setting mode failed, no response from VTX"; return; } mode = response[4]; gDebug() << "VTX mode now set to " << (int)mode; } int SmartAudio::getFrequency() const { return mFrequency; } int SmartAudio::getPower() const { return mPower; } int SmartAudio::getPowerDbm() const { if ( mPower < mPowerTable.size() ) { return (int)mPowerTable[mPower]; } return -1; } int SmartAudio::getChannel() const { return mChannel; } int SmartAudio::getBand() const { return mBand; } std::string SmartAudio::getBandName() const { return std::string( vtxBandsFrequencies[mBand].name ); } std::vector<int> SmartAudio::getPowerTable() const { return mPowerTable; } int8_t SmartAudio::channelFromFrequency( uint16_t frequency ) { for ( int band = 0; band < 5; band++ ) { for ( int freq = 0; freq < 8; freq++ ) { if ( vtxBandsFrequencies[band].frequencies[freq] == frequency ) { return band * 8 + freq; } } } return -1; } static const uint8_t crc8tab[256] = { 0x00, 0xD5, 0x7F, 0xAA, 0xFE, 0x2B, 0x81, 0x54, 0x29, 0xFC, 0x56, 0x83, 0xD7, 0x02, 0xA8, 0x7D, 0x52, 0x87, 0x2D, 0xF8, 0xAC, 0x79, 0xD3, 0x06, 0x7B, 0xAE, 0x04, 0xD1, 0x85, 0x50, 0xFA, 0x2F, 0xA4, 0x71, 0xDB, 0x0E, 0x5A, 0x8F, 0x25, 0xF0, 0x8D, 0x58, 0xF2, 0x27, 0x73, 0xA6, 0x0C, 0xD9, 0xF6, 0x23, 0x89, 0x5C, 0x08, 0xDD, 0x77, 0xA2, 0xDF, 0x0A, 0xA0, 0x75, 0x21, 0xF4, 0x5E, 0x8B, 0x9D, 0x48, 0xE2, 0x37, 0x63, 0xB6, 0x1C, 0xC9, 0xB4, 0x61, 0xCB, 0x1E, 0x4A, 0x9F, 0x35, 0xE0, 0xCF, 0x1A, 0xB0, 0x65, 0x31, 0xE4, 0x4E, 0x9B, 0xE6, 0x33, 0x99, 0x4C, 0x18, 0xCD, 0x67, 0xB2, 0x39, 0xEC, 0x46, 0x93, 0xC7, 0x12, 0xB8, 0x6D, 0x10, 0xC5, 0x6F, 0xBA, 0xEE, 0x3B, 0x91, 0x44, 0x6B, 0xBE, 0x14, 0xC1, 0x95, 0x40, 0xEA, 0x3F, 0x42, 0x97, 0x3D, 0xE8, 0xBC, 0x69, 0xC3, 0x16, 0xEF, 0x3A, 0x90, 0x45, 0x11, 0xC4, 0x6E, 0xBB, 0xC6, 0x13, 0xB9, 0x6C, 0x38, 0xED, 0x47, 0x92, 0xBD, 0x68, 0xC2, 0x17, 0x43, 0x96, 0x3C, 0xE9, 0x94, 0x41, 0xEB, 0x3E, 0x6A, 0xBF, 0x15, 0xC0, 0x4B, 0x9E, 0x34, 0xE1, 0xB5, 0x60, 0xCA, 0x1F, 0x62, 0xB7, 0x1D, 0xC8, 0x9C, 0x49, 0xE3, 0x36, 0x19, 0xCC, 0x66, 0xB3, 0xE7, 0x32, 0x98, 0x4D, 0x30, 0xE5, 0x4F, 0x9A, 0xCE, 0x1B, 0xB1, 0x64, 0x72, 0xA7, 0x0D, 0xD8, 0x8C, 0x59, 0xF3, 0x26, 0x5B, 0x8E, 0x24, 0xF1, 0xA5, 0x70, 0xDA, 0x0F, 0x20, 0xF5, 0x5F, 0x8A, 0xDE, 0x0B, 0xA1, 0x74, 0x09, 0xDC, 0x76, 0xA3, 0xF7, 0x22, 0x88, 0x5D, 0xD6, 0x03, 0xA9, 0x7C, 0x28, 0xFD, 0x57, 0x82, 0xFF, 0x2A, 0x80, 0x55, 0x01, 0xD4, 0x7E, 0xAB, 0x84, 0x51, 0xFB, 0x2E, 0x7A, 0xAF, 0x05, 0xD0, 0xAD, 0x78, 0xD2, 0x07, 0x53, 0x86, 0x2C, 0xF9 }; static uint8_t crc8( const uint8_t* ptr, uint8_t len ) { uint8_t crc = 0; for ( uint8_t i = 0; i < len; i++ ) { crc = crc8tab[crc ^ *ptr++]; } return crc; }
9,611
C++
.cpp
288
31.184028
110
0.651986
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,756
WS2812.cpp
dridri_bcflight/flight/peripherals/WS2812.cpp
#include <string.h> #include "WS2812.h" WS2812::WS2812( uint8_t gpio_pin, uint32_t leds_count ) : mGPIOPin( gpio_pin ) , mLedsCount( leds_count ) { /* mPWM = new PWM( 14, 10 * 1000 * 1000, 13 * 24, 1, &gpio_pin, 1 ); // mPWM = new PWM( 14, 1 * 1000 * 1000, 13 * 24 + 600, 1, &gpio_pin, 1 ); */ mLedsColors = new rgb_t[ mLedsCount ]; memset( mLedsColors, 0, sizeof(rgb_t) * mLedsCount ); } WS2812::~WS2812() { } void WS2812::SetLEDColor( uint32_t led, uint8_t r, uint8_t g, uint8_t b ) { mLedsColors[led].r = r; mLedsColors[led].g = g; mLedsColors[led].b = b; } void WS2812::Update() { int32_t i = 0; uint32_t j = 0; uint8_t buffer[13 * 24]; memset( buffer, 0, sizeof(buffer) ); for ( i = 7; i >= 0; i-- ) { if ( ( mLedsColors[0].r >> i ) & 0x1 ) { buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; } else { buffer[j++] = 1; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; } } for ( i = 7; i >= 0; i-- ) { if ( ( mLedsColors[0].g >> i ) & 0x1 ) { buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; } else { buffer[j++] = 1; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; } } for ( i = 7; i >= 0; i-- ) { if ( ( mLedsColors[0].b >> i ) & 0x1 ) { buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 1; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; } else { buffer[j++] = 1; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; buffer[j++] = 0; } } // mPWM->SetPWMBuffer( mGPIOPin, buffer, sizeof(buffer) ); // mPWM->SetPWMus( mGPIOPin, 200 ); // mPWM->Update(); }
2,592
C++
.cpp
122
18.032787
74
0.485575
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,757
main.cpp
dridri_bcflight/flight/tests/main.cpp
#include <catch2/catch_session.hpp> #include <Debug.h> int main( int argc, char* argv[] ) { Debug::setDebugLevel( Debug::Trace ); Debug::setColors( false ); int result = Catch::Session().run( argc, argv ); return result; }
229
C++
.cpp
9
23.777778
49
0.706422
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,758
test_BiquadFilter.cpp
dridri_bcflight/flight/tests/stabilizer/test_BiquadFilter.cpp
#include <catch2/catch_all.hpp> #include <stabilizer/BiquadFilter.h> #include <random> using namespace Catch::literals; TEST_CASE("BiquadFilter Notch", "[BiquadFilter]") { BiquadFilter<float> filter( 0.707f ); filter.setCenterFrequency( 100.0f ); float input = 1.0f; float output = filter.filter( input, 0.002f ); REQUIRE(output == Catch::Approx(0.6).epsilon(0.1)); } TEST_CASE("BiquadFilter Notch sine", "[BiquadFilter]") { BiquadFilter<float> filter( 0.707f ); filter.setCenterFrequency( 100.0f, 0.00001f ); float output = 0.0f; for ( uint32_t t = 0; t < 1000000; t++ ) { float input = std::sin( float(t) * 100.0f / 1000000.0f ); output = filter.filter( input, 0.002f ); } REQUIRE(output == Catch::Approx(-0.5).epsilon(0.1)); } /* TEST_CASE("BiquadFilter Notch sine variable dT", "[BiquadFilter]") { const int32_t frequency = 1000; const float base_dt = 1.0f / float(frequency); const float dt_variation = 0.25f; // 25% const float sine_frequency = 100.0f; const float sine_amplitude = 1.0f; // 5.0f; const float notch_frequency = 100.0f; std::mt19937 generator( 42 ); std::uniform_real_distribution<float> distribution( -base_dt*dt_variation, base_dt*dt_variation ); BiquadFilter<float> filter( 0.707f ); filter.setCenterFrequency( notch_frequency, 0.1f ); float output = 0.0f; for ( uint32_t t = 0; t < frequency; t++ ) { float input = sine_amplitude * std::sin( 2.0f * float(M_PI) * float(t) * sine_frequency / (float)frequency ); float dt = base_dt + distribution(generator); output = filter.filter( input, dt ); printf( "[%dHz] %f → %f\n", int(1.0f / dt), input, output ); } REQUIRE(output == Catch::Approx(-42).epsilon(0.1)); } */ TEST_CASE("BiquadFilter 100Hz notch on 100Hz sine", "[BiquadFilter]") { const uint32_t frequency = 1000; const float dt = 1.0f / 1000.0f; const float sine_frequency = 100.0f; const float sine_amplitude = 5.0f; const float notch_frequency = 100.0f; const float notch_frequency_var_freq = 40.0f; const float notch_frequency_var_amp = 20.0f; const float notch_frequency_gain = 10.0f; const float sine_max_filtered_amplitude = 2.0f; const float loopDT = 1.0f / float(frequency); BiquadFilter<float> filter( 0.707f ); float output = 0.0f; for ( uint32_t t = 0; t < frequency * 100; t++ ) { float pi2t = 2.0f * float(M_PI) * float(t); float input = sine_amplitude * std::sin( pi2t * sine_frequency / (float)frequency ); float centerFreq = notch_frequency + notch_frequency_var_amp * std::cos( pi2t * notch_frequency_var_freq / float(frequency) ); filter.setCenterFrequency( centerFreq, notch_frequency_gain * loopDT ); output = filter.filter( input, dt ); if ( t > frequency / int(notch_frequency) ) { REQUIRE( std::abs(output) <= sine_max_filtered_amplitude ); } } } TEST_CASE("BiquadFilter 10Hz notch on 10Hz sine", "[BiquadFilter]") { const uint32_t frequency = 1000; const float dt = 1.0f / 1000.0f; const float sine_frequency = 10.0f; const float sine_amplitude = 5.0f; const float notch_frequency = 10.0f; const float notch_frequency_var_freq = 40.0f; const float notch_frequency_var_amp = 20.0f; const float notch_frequency_gain = 10.0f; const float sine_max_filtered_amplitude = 2.0f; const float loopDT = 1.0f / float(frequency); BiquadFilter<float> filter( 0.707f ); float output = 0.0f; for ( uint32_t t = 0; t < frequency * 100; t++ ) { float pi2t = 2.0f * float(M_PI) * float(t); float input = sine_amplitude * std::sin( pi2t * sine_frequency / (float)frequency ); float centerFreq = notch_frequency + notch_frequency_var_amp * std::cos( pi2t * notch_frequency_var_freq / float(frequency) ); filter.setCenterFrequency( centerFreq, notch_frequency_gain * loopDT ); output = filter.filter( input, dt ); if ( t > frequency / int(notch_frequency) ) { REQUIRE( std::abs(output) <= sine_max_filtered_amplitude ); } } } TEST_CASE("BiquadFilter 10Hz notch on 100Hz sine", "[BiquadFilter]") { const uint32_t frequency = 1000; const float dt = 1.0f / 1000.0f; const float sine_frequency = 100.0f; const float sine_amplitude = 5.0f; const float notch_frequency = 10.0f; const float notch_frequency_var_freq = 40.0f; const float notch_frequency_var_amp = 20.0f; const float notch_frequency_gain = 10.0f; const auto sine_max_filtered_amplitude = (5.0_a).epsilon(0.1f); const float loopDT = 1.0f / float(frequency); BiquadFilter<float> filter( 0.707f ); float output = 0.0f; for ( uint32_t t = 0; t < frequency * 100; t++ ) { float pi2t = 2.0f * float(M_PI) * float(t); float input = sine_amplitude * std::sin( pi2t * sine_frequency / (float)frequency ); float centerFreq = notch_frequency + notch_frequency_var_amp * std::cos( pi2t * notch_frequency_var_freq / float(frequency) ); filter.setCenterFrequency( centerFreq, notch_frequency_gain * loopDT ); output = filter.filter( input, dt ); if ( t > frequency / int(notch_frequency) ) { REQUIRE( std::abs(output) <= sine_max_filtered_amplitude ); } } } TEST_CASE("BiquadFilter 100Hz notch on 100Hz sine, dt off by 10%", "[BiquadFilter]") { const uint32_t frequency = 1000; const float dt = 1.1f / 1000.0f; const float sine_frequency = 100.0f; const float sine_amplitude = 5.0f; const float notch_frequency = 100.0f; const float notch_frequency_var_freq = 40.0f; const float notch_frequency_var_amp = 20.0f; const float notch_frequency_gain = 10.0f; const float sine_max_filtered_amplitude = 2.0f; const float loopDT = 1.0f / float(frequency); BiquadFilter<float> filter( 0.707f ); float output = 0.0f; for ( uint32_t t = 0; t < frequency * 100; t++ ) { float pi2t = 2.0f * float(M_PI) * float(t); float input = sine_amplitude * std::sin( pi2t * sine_frequency / (float)frequency ); float centerFreq = notch_frequency + notch_frequency_var_amp * std::cos( pi2t * notch_frequency_var_freq / float(frequency) ); filter.setCenterFrequency( centerFreq, notch_frequency_gain * loopDT ); output = filter.filter( input, dt ); if ( t > frequency / int(notch_frequency) ) { REQUIRE( std::abs(output) <= sine_max_filtered_amplitude ); } } } TEST_CASE("BiquadFilter 100Hz notch on 100Hz sine, dt off by 20%", "[BiquadFilter]") { const uint32_t frequency = 1000; const float dt = 1.2f / 1000.0f; const float sine_frequency = 100.0f; const float sine_amplitude = 5.0f; const float notch_frequency = 100.0f; const float notch_frequency_var_freq = 40.0f; const float notch_frequency_var_amp = 20.0f; const float notch_frequency_gain = 10.0f; const float sine_max_filtered_amplitude = 2.5f; const float loopDT = 1.0f / float(frequency); BiquadFilter<float> filter( 0.707f ); float output = 0.0f; for ( uint32_t t = 0; t < frequency * 100; t++ ) { float pi2t = 2.0f * float(M_PI) * float(t); float input = sine_amplitude * std::sin( pi2t * sine_frequency / (float)frequency ); float centerFreq = notch_frequency + notch_frequency_var_amp * std::cos( pi2t * notch_frequency_var_freq / float(frequency) ); filter.setCenterFrequency( centerFreq, notch_frequency_gain * loopDT ); output = filter.filter( input, dt ); if ( t > frequency / int(notch_frequency) ) { REQUIRE( std::abs(output) <= sine_max_filtered_amplitude ); } } } TEST_CASE("BiquadFilter 20Hz notch on 20Hz sine, noisy", "[BiquadFilter]") { const uint32_t frequency = 1000; const float dt = 1.2f / 1000.0f; const float sine_frequency = 20.0f; const float sine_amplitude = 5.0f; const float notch_frequency = 20.0f; const float notch_frequency_var_freq = 40.0f; const float notch_frequency_var_amp = 20.0f; const float notch_frequency_gain = 10.0f; const float sine_max_filtered_amplitude = 2.5f; const float loopDT = 1.0f / float(frequency); std::mt19937 gen(42); std::normal_distribution<float> whiteNoiseGen(0.0f, 1.0f); BiquadFilter<float> filter( 0.707f ); float output = 0.0f; for ( uint32_t t = 0; t < frequency * 100; t++ ) { float pi2t = 2.0f * float(M_PI) * float(t); float white_noise = std::clamp( whiteNoiseGen(gen) * 0.5f, -1.0f, 1.0f ); float input = sine_amplitude * std::sin( pi2t * sine_frequency / (float)frequency ); float centerFreq = notch_frequency + notch_frequency_var_amp * std::cos( pi2t * notch_frequency_var_freq / float(frequency) ); filter.setCenterFrequency( centerFreq, notch_frequency_gain * loopDT ); output = filter.filter( white_noise + input, dt ); if ( t > frequency / int(notch_frequency) ) { REQUIRE( std::abs(output) <= sine_max_filtered_amplitude + std::abs(white_noise) ); } } }
8,521
C++
.cpp
190
42.415789
128
0.701602
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,759
Microphone.cpp
dridri_bcflight/flight/audio/Microphone.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include "Debug.h" #include "Microphone.h" Microphone::Microphone() { } Microphone::~Microphone() { }
821
C++
.cpp
25
30.92
72
0.752212
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,760
AlsaMic.cpp
dridri_bcflight/flight/audio/AlsaMic.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #if ( defined( BOARD_rpi ) ) #include <dirent.h> #include "AlsaMic.h" #include <Main.h> #include <Debug.h> #include <Link.h> #include <Recorder.h> #include <video/Camera.h> AlsaMic::AlsaMic() : Microphone() , mDevice( "plughw:1,0" ) , mRate( 44100 ) , mChannels( 1 ) , mLink( nullptr ) , mRecorder( nullptr ) , mRecorderTrackId( 0 ) , mRecordSyncCounter( 0 ) , mRecordStream( nullptr ) { fDebug(); } AlsaMic::~AlsaMic() { } void AlsaMic::Setup() { fDebug( mDevice ); int err = 0; snd_pcm_hw_params_t* hw_params; if ( ( err = snd_pcm_open( &mPCM, mDevice.c_str(), SND_PCM_STREAM_CAPTURE, 0 ) ) < 0 ) { gError() << "cannot open audio device " << mDevice.c_str() << " (" << snd_strerror( err ) << ")"; Board::defectivePeripherals()["Microphone"] = true; return; } gTrace() << "audio interface opened"; if ( ( err = snd_pcm_hw_params_malloc( &hw_params ) ) < 0 ) { gError() << "cannot allocate hardware parameter structure (" << snd_strerror( err ) << ")"; return; } gTrace() << "hw_params allocated"; if ( ( err = snd_pcm_hw_params_any( mPCM, hw_params ) ) < 0 ) { gError() << "cannot initialize hardware parameter structure (" << snd_strerror( err ) << ")"; return; } gTrace() << "hw_params initialized"; if ( ( err = snd_pcm_hw_params_set_access( mPCM, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED ) ) < 0 ) { gError() << "cannot set access type (" << snd_strerror( err ) << ")"; return; } gTrace() << "hw_params access set"; if ( ( err = snd_pcm_hw_params_set_format( mPCM, hw_params, SND_PCM_FORMAT_S16_LE ) ) < 0 ) { gError() << "cannot set sample format (" << snd_strerror( err ) << ")"; return; } gTrace() << "hw_params format set"; if ( ( err = snd_pcm_hw_params_set_rate_near( mPCM, hw_params, &mRate, 0 ) ) < 0 ) { gError() << "cannot set sample rate (" << snd_strerror( err ) << ")"; return; } gTrace() << "hw_params rate set to " << mRate; if ( ( err = snd_pcm_hw_params_set_channels( mPCM, hw_params, mChannels ) ) < 0 ) { gError() << "cannot set channel count (" << snd_strerror( err ) << ")"; return; } gTrace() << "hw_params channels set to " << mChannels; /* snd_pcm_uframes_t framesize = 1024; if ( ( err = snd_pcm_hw_params_set_period_size_near( mPCM, hw_params, &framesize, 0 ) ) < 0 ) { gError() << "cannot set frame size (" << snd_strerror( err ) << ")"; return; } gTrace() << "hw_params frame size set to %u\n", framesize); if ( ( err = snd_pcm_hw_params_set_periods( mPCM, hw_params, 1, 1 ) ) < 0 ) { gError() << "cannot set periods (" << snd_strerror( err ) << ")"; // return; } gTrace() << "hw_params periods set to 1"; snd_pcm_uframes_t bufsize = 1024; if ( ( err = snd_pcm_hw_params_set_buffer_size_near( mPCM, hw_params, &bufsize ) ) < 0 ) { gError() << "cannot set buffer size (" << snd_strerror( err ) << ")"; return; } gTrace() << "hw_params buffer size set to %u\n", bufsize); */ if ( ( err = snd_pcm_hw_params( mPCM, hw_params ) ) < 0 ) { gError() << "cannot set parameters (" << snd_strerror( err ) << ")"; return; } gTrace() << "hw_params set"; snd_pcm_hw_params_free( hw_params ); gTrace() << "hw_params freed"; if ( ( err = snd_pcm_prepare ( mPCM ) ) < 0 ) { gError() << "cannot prepare audio interface for use (" << snd_strerror( err ) << ")"; return; } gDebug() << "Audio interface prepared"; shine_set_config_mpeg_defaults( &mShineConfig.mpeg ); mShineConfig.wave.channels = ( ( mChannels == 2 ) ? PCM_STEREO : PCM_MONO ); mShineConfig.wave.samplerate = mRate; mShineConfig.mpeg.mode = ( ( mChannels == 2 ) ? STEREO : MONO ); mShineConfig.mpeg.bitr = 320; mShine = shine_initialise( &mShineConfig ); gTrace() << "shine_samples_per_pass : " << shine_samples_per_pass( mShine ); if ( mRecorder ) { mRecorderTrackId = mRecorder->AddAudioTrack( "wav", mChannels, mRate, "mp3" ); } mLiveThread = new HookThread<AlsaMic>( "microphone", this, &AlsaMic::LiveThreadRun ); mLiveThread->Start(); mLiveThread->setPriority( 90, 3 ); } bool AlsaMic::LiveThreadRun() { if ( mLink and not mLink->isConnected() ) { mLink->Connect(); if ( mLink->isConnected() ) { gDebug() << "Microphone connected !"; mLink->setBlocking( false ); } return true; } uint8_t data[32768]; snd_pcm_sframes_t size = snd_pcm_readi( mPCM, data, 1152 ); if ( size > 0 ) { if ( mLink ) { mLink->Write( data, size * sizeof(int16_t), false, 0 ); } RecordWrite( (char*)data, size ); } else { gDebug() << "snd_pcm_readi error : " << size; if ( size == -EPIPE ) { snd_pcm_recover( mPCM, (int)size, 0 ); } else { Board::defectivePeripherals()["Microphone"] = true; return false; } } return true; } int AlsaMic::RecordWrite( char* data, int datalen ) { mRecorder->WriteSample( mRecorderTrackId, Board::GetTicks(), data, datalen * 2 ); return datalen; fTrace( (void*)data, datalen ); int baselen = datalen; datalen = 0; data = (char*)shine_encode_buffer_interleaved( mShine, (int16_t*)data, &datalen ); if ( mRecorder ) { mRecorder->WriteSample( mRecorderTrackId, Board::GetTicks(), data, datalen ); return datalen; } int ret = 0; if ( !mRecordStream ) { char filename[256]; string file = Main::instance()->camera()->recordFilename(); if ( file == "" ) { return 0; } uint32_t fileid = atoi( file.substr( file.rfind( "_" ) + 1 ).c_str() ); sprintf( filename, "/var/VIDEO/audio_%dhz_%dch_%06u.mp3", mRate, mChannels, fileid ); mRecordStream = fopen( filename, "wb" ); } ret = fwrite( data, 1, datalen, mRecordStream ); mRecordSyncCounter = ( mRecordSyncCounter + 1 ) % 2048; if ( mRecordSyncCounter % 15 == 0 ) { // sync on disk every 15 frames (up to 15*512*1/44100 seconds) fflush( mRecordStream ); fsync( fileno( mRecordStream ) ); } return ret; } #endif // BOARD_rpi
6,510
C++
.cpp
187
32.417112
102
0.648631
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,761
BrushlessPWM.cpp
dridri_bcflight/flight/motors/BrushlessPWM.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <cmath> #include <Debug.h> #include "BrushlessPWM.h" #include "Config.h" #ifdef BUILD_BrushlessPWM int BrushlessPWM::flight_register( Main* main ) { RegisterMotor( "PWM", BrushlessPWM::Instanciate ); return 0; } Motor* BrushlessPWM::Instanciate( Config* config, const string& object ) { int fl_pin = config->Integer( object + ".pin" ); int fl_min = config->Integer( object + ".minimum_us", 1020 ); int fl_max = config->Integer( object + ".maximum_us", 1860 ); return new BrushlessPWM( fl_pin, fl_min, fl_max ); } BrushlessPWM::BrushlessPWM( uint32_t pin, int us_min, int us_max ) : Motor() , mPWM( new PWM( pin, 1000000, 2000, 2 ) ) , mMinUS( us_min ) , mMaxUS( us_max ) { } BrushlessPWM::~BrushlessPWM() { } void BrushlessPWM::setSpeedRaw( float speed, bool force_hw_update ) { if ( isnan( speed ) or isinf( speed ) ) { return; } if ( speed < 0.0f ) { speed = 0.0f; } if ( speed > 1.0f ) { speed = 1.0f; } uint32_t us = mMinUS + (uint32_t)( ( mMaxUS - mMinUS ) * speed ); mPWM->SetPWMus( us ); if ( force_hw_update ) { mPWM->Update(); } } void BrushlessPWM::Disarm() { mPWM->SetPWMus( mMinUS - 1 ); mPWM->Update(); } void BrushlessPWM::Disable() { mPWM->SetPWMus( 0 ); mPWM->Update(); } #endif // BUILD_BrushlessPWM
1,990
C++
.cpp
72
25.694444
72
0.702105
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,762
OneShot125.cpp
dridri_bcflight/flight/motors/OneShot125.cpp
#include <cmath> #include "OneShot125.h" #include "Config.h" #include "Debug.h" #ifdef BUILD_OneShot125 #if (defined(BOARD_rpi) || defined(BOARD_generic)) // #define TIME_BASE 34500000 // #define SCALE ( TIME_BASE / 1000000 ) // #define STEPS 10000 // #define STEP_US 50 #define TIME_BASE 62500000 #define STEPS 9000 #define SCALE ( STEPS / 250 ) #define STEP_US 25 #elif defined( BOARD_teensy4 ) #define TIME_BASE 1000000000 #define SCALE 1000 #define STEPS 250000 #define STEP_US 0 // unused #endif int OneShot125::flight_register( Main* main ) { RegisterMotor( "OneShot125", OneShot125::Instanciate ); return 0; } Motor* OneShot125::Instanciate( Config* config, const string& object ) { int fl_pin = config->Integer( object + ".pin" ); int fl_min = config->Integer( object + ".minimum_us", 125 ); int fl_max = config->Integer( object + ".maximum_us", 250-8 ); PWM* pwm = static_cast<PWM*>( config->Object( object + ".pwm" ) ); return new OneShot125( fl_pin, fl_min, fl_max, pwm ); } OneShot125::OneShot125( uint32_t pin, int us_min, int us_max, PWM* pwm ) : Motor() , mPWM( pwm ) , mPin( pin ) , mMinUS( us_min ) , mMaxUS( us_max ) , mScale( SCALE ) { fDebug( pin, us_min, us_max, pwm ); gDebug() << this; if ( !mPWM ) { #ifdef BOARD_rpi if ( PWM::HasTruePWM() ) { mPWM = new PWM( pin, 10 * 1000 * 1000, 2500, 1 ); mScale = 10; } else #endif { mPWM = new PWM( pin, TIME_BASE, STEPS, STEP_US ); } } } OneShot125::OneShot125( const LuaValue& pin ) : OneShot125( pin.toInteger(), 125, 250-8, nullptr ) { } OneShot125::~OneShot125() { } void OneShot125::setSpeedRaw( float speed, bool force_hw_update ) { fDebug( speed, force_hw_update ); if ( isnan( speed ) or isinf( speed ) ) { return; } if ( speed < 0.0f ) { speed = 0.0f; } if ( speed > 1.0f ) { speed = 1.0f; } uint32_t us = mMinUS * mScale + (uint32_t)( (float)( mMaxUS - mMinUS ) * speed * (float)mScale ); mPWM->SetPWMus( us ); if ( force_hw_update ) { mPWM->Update(); } } void OneShot125::Disarm() { // mPWM->SetPWMus( 100 * mScale ); mPWM->SetPWMus( 0 ); mPWM->Update(); } void OneShot125::Disable() { if ( not mPWM ) { return; } mPWM->SetPWMus( 0 ); mPWM->Update(); } #endif // BUILD_OneShot125
2,259
C++
.cpp
96
21.5
98
0.661215
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,763
Motor.cpp
dridri_bcflight/flight/motors/Motor.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <cmath> #include "Motor.h" map< string, function< Motor* ( Config*, const string& ) > > Motor::mKnownMotors; Motor::Motor() : mSpeed( -1 ) { } Motor::~Motor() { } const float Motor::speed() const { return mSpeed; } void Motor::KeepSpeed() { setSpeed( mSpeed ); } void Motor::setSpeed( float speed, bool force_hw_update ) { if ( speed == mSpeed and not force_hw_update ) { return; } /* uint8_t uspeed = (int)( fmaxf( 0, fminf( 255, (int)( speed * 255.0f ) ) ) ); setSpeedRaw( uspeed ); */ setSpeedRaw( speed, force_hw_update ); mSpeed = speed; } Motor* Motor::Instanciate( const string& name, Config* config, const string& object ) { if ( mKnownMotors.find( name ) != mKnownMotors.end() ) { return mKnownMotors[ name ]( config, object ); } return nullptr; } void Motor::RegisterMotor( const string& name, function< Motor* ( Config*, const string& ) > instanciate ) { mKnownMotors[ name ] = instanciate; }
1,659
C++
.cpp
58
26.741379
106
0.716267
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,764
DShot.cpp
dridri_bcflight/flight/motors/DShot.cpp
#include "DShot.h" #include "DShotDriver.h" #ifdef BUILD_DShot DShot::DShot( uint32_t pin ) : Motor() , mDriver( DShotDriver::instance() ) , mPin( pin ) { mDriver->disablePinValue( mPin ); mDriver->Update(); } DShot::~DShot() { } void DShot::setSpeedRaw( float speed, bool force_hw_update ) { if ( speed < 0.0f ) { speed = 0.0f; } if ( speed > 1.0f ) { speed = 1.0f; } mDriver->setPinValue( mPin, 48 + ( 2047 - 48 ) * speed ); if ( force_hw_update ) { mDriver->Update(); } } void DShot::Beep( uint8_t beepMode ) { mDriver->setPinValue( mPin, 1 + beepMode % 5, true ); mDriver->Update(); } void DShot::Disable() { mDriver->disablePinValue( mPin ); mDriver->Update(); } void DShot::Disarm() { mDriver->setPinValue( mPin, 0 ); mDriver->Update(); } #endif // BUILD_DShot
808
C++
.cpp
43
16.837209
60
0.663551
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,765
PWMProxy.cpp
dridri_bcflight/flight/motors/PWMProxy.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <unistd.h> #include <cmath> #include <Debug.h> #include "PWMProxy.h" #include "SPI.h" #include "Config.h" #ifdef BUILD_PWMProxy uint16_t _g_ADCChan1 = 0; // Ugly HACK SPI* PWMProxy::testBus = nullptr; uint8_t PWMProxy::testBusTx[] = { 0 }; int PWMProxy::flight_register( Main* main ) { RegisterMotor( "PWMProxy", PWMProxy::Instanciate ); return 0; } Motor* PWMProxy::Instanciate( Config* config, const string& object ) { int fl_channel = config->Integer( object + ".channel" ); int fl_min = config->Integer( object + ".minimum_us", 1020 ); int fl_max = config->Integer( object + ".maximum_us", 1860 ); int fl_start = config->Integer( object + ".range_start_us", 1000 ); int fl_length = config->Integer( object + ".range_length_us", 1000 ); return new PWMProxy( fl_channel, fl_min, fl_max, fl_start, fl_length ); } PWMProxy::PWMProxy( uint32_t channel, int us_min, int us_max, int us_start, int us_length ) : Motor() , mChannel( channel ) , mMinUS( us_min ) , mMaxUS( us_max ) , mStartUS( us_start ) , mLengthUS( us_length ) { if ( !testBus ) { testBus = new SPI( "/dev/spidev3.0", 8000000 ); usleep( 1000 * 1000 ); printf( "Send reset\n" ); testBus->Write( { 0x01, 1, 1, 1, 1, 1, 1, 1, 1 } ); usleep( 1000 * 1000 ); printf( "Send resetaaa\n" ); testBus->Write( { 0x01, 1, 1, 1, 1, 1, 1, 1, 1 } ); usleep( 1000 * 1000 ); printf( "Send REG_PWM_CONFIG\n" ); testBus->Write( { 0x28, 0b00000000, 0, 0, 0, 0, 0, 0, 0 } ); usleep( 1000 * 1000 ); printf( "Send minval and maxval (%u, %u, n=%u)\n", us_start, us_length, ( us_max - us_start ) * 65535 / us_length ); testBus->Write<uint32_t>( 0x30, { (uint32_t)us_start, (uint32_t)us_length } ); usleep( 1000 * 1000 * 2 ); printf( "Send REG_DEVICE_CONFIG\n" ); testBus->Write( { 0x20, 0b00000001, 0, 0, 0, 0, 0, 0, 0 } ); usleep( 1000 * 1000 ); testBusTx[0] = 0x42; const uint16_t value = ( mMinUS - mStartUS ) * 65535 / mLengthUS - 10; memcpy( &testBusTx[1], &value, sizeof(uint16_t) ); memcpy( &testBusTx[3], &value, sizeof(uint16_t) ); memcpy( &testBusTx[5], &value, sizeof(uint16_t) ); memcpy( &testBusTx[7], &value, sizeof(uint16_t) ); } mBus = testBus; } PWMProxy::~PWMProxy() { } // 64045 → 2978 void PWMProxy::setSpeedRaw( float speed, bool force_hw_update ) { static uint8_t __attribute__((aligned(32))) dummy[10] = { 0 }; if ( isnan( speed ) or isinf( speed ) ) { return; } if ( speed < 0.0f ) { speed = 0.0f; } if ( speed > 1.0f ) { speed = 1.0f; } // uint32_t value = mMinUS + (uint32_t)( ( mMaxUS - mMinUS ) * speed ); // uint16_t value = ( mMinUS + (uint32_t)( ( mMaxUS - mMinUS ) * speed ) - mStartUS ) * 65535 / mLengthUS; uint16_t value = (uint32_t)( ( (float)mMinUS + ( (float)( mMaxUS - mMinUS ) * speed ) - (float)mStartUS ) * 65535.0f ) / mLengthUS; // gDebug() << "Motor at channel " << (int)mChannel << " speed : " << value << "(" << speed << ")"; if ( mChannel == 0 ) { printf( "%02.6f, %06u, %05.6f, %05.6f\n", speed, value, (float)( mMaxUS - mMinUS ) * speed, ( (float)mMinUS + ( (float)( mMaxUS - mMinUS ) * speed ) - (float)mStartUS ) ); } memcpy( &testBusTx[1 + mChannel*2], &value, sizeof(uint16_t) ); if ( force_hw_update ) { // uint16_t b[4]; /* uint16_t v = 100; memcpy( &testBusTx[1 + 0], &v, 2 ); memcpy( &testBusTx[1 + 2], &v, 2 ); memcpy( &testBusTx[1 + 4], &v, 2 ); memcpy( &testBusTx[1 + 6], &v, 2 ); */ // memcpy( b, &testBusTx[1], 2 * 4 ); // printf( "Transfer %d, %d, %d, %d {", b[0], b[1], b[2], b[3] ); for(int i = 0; i < 9; i++) printf( " %02X", ((uint8_t*)testBusTx)[i]); printf( " }\n" ); testBus->Transfer( testBusTx, dummy + 1, 9 ); _g_ADCChan1 = ((uint16_t*)dummy)[1]; } } void PWMProxy::Arm() { testBus->Write( { 0x20, 0b00000101, 0, 0, 0, 0, 0, 0, 0 } ); usleep( 100 ); } void PWMProxy::Disarm() { static uint8_t dummy[9] = { 0 }; uint16_t value = ( mMinUS - mStartUS ) * 65535 / mLengthUS; if ( value > 10 ) { value -= 10; } // gDebug() << "Motor at channel " << (int)mChannel << " speed : " << value << " (disarm)"; memcpy( &testBusTx[1 + mChannel*2], &value, sizeof(uint16_t) ); uint16_t b[4]; memcpy( b, &testBusTx[1], 2 * 4 ); printf( "DISARM Transfer %d, %d, %d, %d {", b[0], b[1], b[2], b[3] ); for(int i = 0; i < 9; i++) printf( " %02X", ((uint8_t*)testBusTx)[i]); printf( " }\n" ); testBus->Transfer( testBusTx, dummy, 9 ); usleep( 100 ); testBus->Write( { 0x20, 0b00000001, 0, 0, 0, 0, 0, 0, 0 } ); } void PWMProxy::Disable() { static uint8_t dummy[9] = { 0 }; /* uint16_t value = 0; // gDebug() << "Motor at channel " << (int)mChannel << " speed : " << value << " (disable)"; memcpy( &testBusTx[1 + mChannel*2], &value, sizeof(uint16_t) ); */ // uint16_t b[4]; // memcpy( b, &testBusTx[1], 2 * 4 ); // printf( "Transfer %d, %d, %d, %d {", b[0], b[1], b[2], b[3] ); for(int i = 0; i < 9; i++) printf( " %02X", ((uint8_t*)testBusTx)[i]); printf( " }\n" ); /* testBus->Transfer( testBusTx, dummy, 9 ); */ testBus->Write( { 0x20, 0b00000001, 0, 0, 0, 0, 0, 0, 0 } ); usleep( 100 ); testBus->Write( { 0x70, 1, 1, 1, 1, 1, 1, 1, 1 } ); usleep( 100 ); } #endif // BUILD_PWMProxy
5,870
C++
.cpp
156
35.5
173
0.612568
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,766
OneShot42.cpp
dridri_bcflight/flight/motors/OneShot42.cpp
#include <cmath> #include "OneShot42.h" #include "Config.h" #ifdef BUILD_OneShot42 int OneShot42::flight_register( Main* main ) { RegisterMotor( "OneShot42", OneShot42::Instanciate ); return 0; } Motor* OneShot42::Instanciate( Config* config, const string& object ) { int fl_pin = config->Integer( object + ".pin" ); int fl_min = config->Integer( object + ".minimum_us", 42 ); int fl_max = config->Integer( object + ".maximum_us", 84-4 ); return new OneShot42( fl_pin, fl_min, fl_max ); } OneShot42::OneShot42( uint32_t pin, int us_min, int us_max ) : Motor() , mPin( pin ) , mMinUS( us_min ) , mMaxUS( us_max ) , mScale( 0 ) { #ifdef BOARD_rpi // DMA fake-PWM cannot handle these frequencies if ( PWM::HasTruePWM() ) { mPWM = new PWM( pin, 37500000, 3150, 1 ); mScale = 37.5f; mMinValue = 1575; } #else // TODO #endif } OneShot42::~OneShot42() { } void OneShot42::setSpeedRaw( float speed, bool force_hw_update ) { if ( isnan( speed ) or isinf( speed ) ) { return; } if ( speed < 0.0f ) { speed = 0.0f; } if ( speed > 1.0f ) { speed = 1.0f; } uint32_t us = mMinValue + (uint32_t)( (float)( mMaxUS - mMinUS ) * speed * mScale ); mPWM->SetPWMus( us ); if ( force_hw_update ) { mPWM->Update(); } } void OneShot42::Disarm() { mPWM->SetPWMus( 36 * mScale ); mPWM->Update(); } void OneShot42::Disable() { if ( not mPWM ) { return; } mPWM->SetPWMus( 0 ); mPWM->Update(); } #endif // BUILD_OneShot42
1,460
C++
.cpp
68
19.485294
85
0.659621
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
754,767
DMArpi.cpp
dridri_bcflight/flight/boards/rpi/DMArpi.cpp
#include <unistd.h> #include <sys/fcntl.h> #include <sys/mman.h> #include "mailbox.h" #include "DMArpi.h" #include "Debug.h" #define PAGE_SIZE 4096 #define PAGE_SHIFT 12 #define DMA_BASE (periph_virt_base + 0x00007000) #define DMA_CHAN_SIZE 0x100 /* size of register space for a single DMA channel */ #define DMA_CHAN_MAX 14 /* number of DMA Channels we have... actually, there are 15... but channel fifteen is mapped at a different DMA_BASE, so we leave that one alone */ #define PWM0_BASE_OFFSET 0x0020C000 #define PWM0_BASE (periph_virt_base + PWM0_BASE_OFFSET) #define PWM0_PHYS_BASE (periph_phys_base + PWM0_BASE_OFFSET) #define PWM0_LEN 0x28 #define PWM1_BASE_OFFSET 0x0020C800 #define PWM1_BASE (periph_virt_base + PWM1_BASE_OFFSET) #define PWM1_PHYS_BASE (periph_phys_base + PWM1_BASE_OFFSET) #define PWM1_LEN 0x28 #define PWM_BASE_OFFSET PWM0_BASE_OFFSET #define PWM_BASE PWM0_BASE #define PWM_PHYS_BASE PWM0_PHYS_BASE #define PWM_LEN PWM0_LEN #define PCM_BASE_OFFSET 0x00203000 #define PCM_BASE (periph_virt_base + PCM_BASE_OFFSET) #define PCM_PHYS_BASE (periph_phys_base + PCM_BASE_OFFSET) #define PCM_LEN 0x24 #define CLK_BASE_OFFSET 0x00101000 #define CLK_BASE (periph_virt_base + CLK_BASE_OFFSET) #define CLK_LEN 0xA8 #define GPIO_BASE_OFFSET 0x00200000 #define GPIO_BASE (periph_virt_base + GPIO_BASE_OFFSET) #define GPIO_PHYS_BASE (periph_phys_base + GPIO_BASE_OFFSET) #define GPIO_LEN 0x100 #define DMA_NO_WIDE_BURSTS (1<<26) #define DMA_WAIT_RESP (1<<3) #define DMA_TDMODE (1<<1) #define DMA_D_DREQ (1<<6) #define DMA_PER_MAP(x) ((x)<<16) #define DMA_END (1<<1) #define DMA_RESET (1<<31) #define DMA_INT (1<<2) #define DMAENABLE 0x00000ff0 #define DMA_CS (0x00/4) #define DMA_CONBLK_AD (0x04/4) #define DMA_SOURCE_AD (0x0c/4) #define DMA_DEBUG (0x20/4) #define GPIO_FSEL0 (0x00/4) #define GPIO_SET0 (0x1c/4) #define GPIO_CLR0 (0x28/4) #define GPIO_LEV0 (0x34/4) #define GPIO_PULLEN (0x94/4) #define GPIO_PULLCLK (0x98/4) #define GPIO_MODE_IN 0b000 #define GPIO_MODE_OUT 0b001 #define GPIO_MODE_ALT0 0b100 #define GPIO_MODE_ALT1 0b101 #define GPIO_MODE_ALT2 0b110 #define GPIO_MODE_ALT3 0b111 #define GPIO_MODE_ALT4 0b011 #define GPIO_MODE_ALT5 0b010 #define PWM_CTL (0x00/4) #define PWM_PWMC (0x08/4) #define PWM_RNG1 (0x10/4) #define PWM_DAT1 (0x14/4) #define PWM_FIFO (0x18/4) #define PWM_RNG2 (0x20/4) #define PWM_DAT2 (0x24/4) #define PWMCLK_CNTL 40 #define PWMCLK_DIV 41 #define PWMCTL_PWEN1 (1<<0) #define PWMCTL_MODE1 (1<<1) #define PWMCTL_RPTL1 (1<<2) #define PWMCTL_SBIT1 (1<<3) #define PWMCTL_POLA1 (1<<4) #define PWMCTL_USEF1 (1<<5) #define PWMCTL_CLRF (1<<6) #define PWMCTL_MSEN1 (1<<7) #define PWMCTL_PWEN2 (1<<8) #define PWMCTL_MODE2 (1<<9) #define PWMCTL_RPTL2 (1<<10) #define PWMCTL_SBIT2 (1<<11) #define PWMCTL_POLA2 (1<<12) #define PWMCTL_USEF2 (1<<13) #define PWMCTL_MSEN2 (1<<15) #define PWMPWMC_ENAB (1<<31) #define PWMPWMC_THRSHLD ((15<<8)|(15<<0)) #define PCM_CS_A (0x00/4) #define PCM_FIFO_A (0x04/4) #define PCM_MODE_A (0x08/4) #define PCM_RXC_A (0x0c/4) #define PCM_TXC_A (0x10/4) #define PCM_DREQ_A (0x14/4) #define PCM_INTEN_A (0x18/4) #define PCM_INT_STC_A (0x1c/4) #define PCM_GRAY (0x20/4) #define PCMCLK_CNTL 38 #define PCMCLK_DIV 39 #define BUS_TO_PHYS(x) ((x)&~0xC0000000) /* New Board Revision format: SRRR MMMM PPPP TTTT TTTT VVVV S scheme (0=old, 1=new) R RAM (0=256, 1=512, 2=1024) M manufacturer (0='SONY',1='EGOMAN',2='EMBEST',3='UNKNOWN',4='EMBEST') P processor (0=2835, 1=2836) T type (0='A', 1='B', 2='A+', 3='B+', 4='Pi 2 B', 5='Alpha', 6='Compute Module') V revision (0-15) */ #define BOARD_REVISION_SCHEME_MASK (0x1 << 23) #define BOARD_REVISION_SCHEME_OLD (0x0 << 23) #define BOARD_REVISION_SCHEME_NEW (0x1 << 23) #define BOARD_REVISION_RAM_MASK (0x7 << 20) #define BOARD_REVISION_MANUFACTURER_MASK (0xF << 16) #define BOARD_REVISION_MANUFACTURER_SONY (0 << 16) #define BOARD_REVISION_MANUFACTURER_EGOMAN (1 << 16) #define BOARD_REVISION_MANUFACTURER_EMBEST (2 << 16) #define BOARD_REVISION_MANUFACTURER_UNKNOWN (3 << 16) #define BOARD_REVISION_MANUFACTURER_EMBEST2 (4 << 16) #define BOARD_REVISION_PROCESSOR_MASK (0xF << 12) #define BOARD_REVISION_PROCESSOR_2835 (0 << 12) #define BOARD_REVISION_PROCESSOR_2836 (1 << 12) #define BOARD_REVISION_TYPE_MASK (0xFF << 4) #define BOARD_REVISION_TYPE_PI1_A (0 << 4) #define BOARD_REVISION_TYPE_PI1_B (1 << 4) #define BOARD_REVISION_TYPE_PI1_A_PLUS (2 << 4) #define BOARD_REVISION_TYPE_PI1_B_PLUS (3 << 4) #define BOARD_REVISION_TYPE_PI2_B (4 << 4) #define BOARD_REVISION_TYPE_ALPHA (5 << 4) #define BOARD_REVISION_TYPE_PI3_B (8 << 4) #define BOARD_REVISION_TYPE_PI3_BP (0xD << 4) #define BOARD_REVISION_TYPE_PI3_AP (0x7 << 5) #define BOARD_REVISION_TYPE_CM (6 << 4) #define BOARD_REVISION_TYPE_CM3 (10 << 4) #define BOARD_REVISION_TYPE_PI4_B (0x11 << 4) #define BOARD_REVISION_TYPE_CM4 (20 << 4) #define BOARD_REVISION_REV_MASK (0xF) #define LENGTH(x) (sizeof(x) / sizeof(x[0])) #define BUS_TO_PHYS(x) ((x)&~0xC0000000) std::map< uint32_t, DMArpi* > DMArpi::mUsedChannels; DMArpi::DMArpi( uint32_t commands_count ) { for ( mChannel = DMA_CHAN_MAX - 1; mChannel > 0; mChannel-- ) { if ( mUsedChannels.find(mChannel) == mUsedChannels.end() ) { break; } } mMbox.handle = mbox_open(); if ( mMbox.handle < 0 ) { gError() << "Failed to open mailbox"; exit(1); } uint32_t mbox_board_rev = get_board_revision( mMbox.handle ); gDebug() << "MBox Board Revision : " << mbox_board_rev; get_model( mbox_board_rev ); uint32_t mbox_dma_channels = get_dma_channels( mMbox.handle ); gDebug() << "PWM Channels Info: " << mbox_dma_channels << ", using PWM Channel: " << (int)mChannel; gDebug() << "DMA Base : " << DMA_BASE; dma_virt_base = (uint32_t*)map_peripheral( DMA_BASE, ( DMA_CHAN_SIZE * ( DMA_CHAN_MAX + 1 ) ) ); dma_reg = dma_virt_base + mChannel * ( DMA_CHAN_SIZE / sizeof(dma_reg) ); /* uint32_t numPages = ( commands_count * sizeof(dma_cb_t) + ( mNumOutputs * 1 * sizeof(uint32_t) ) + PAGE_SIZE - 1 ) >> PAGE_SHIFT; mMbox.mem_ref = mem_alloc( mMbox.handle, numPages * PAGE_SIZE, PAGE_SIZE, mem_flag ); dprintf( "mem_ref %u\n", mMbox.mem_ref ); mMbox.bus_addr = mem_lock( mMbox.handle, mMbox.mem_ref ); dprintf( "bus_addr = %#x\n", mMbox.bus_addr ); mMbox.virt_addr = (uint8_t*)mapmem( BUS_TO_PHYS(mMbox.bus_addr), numPages * PAGE_SIZE ); dprintf( "virt_addr %p\n", mMbox.virt_addr ); uint32_t offset = 0; mCtls[0].sample = (uint32_t*)( &mMbox.virt_addr[offset] ); offset += sizeof(uint32_t) * mNumSamples * ( 1 + ( mMode == MODE_BUFFER ) ); mCtls[0].cb = (dma_cb_t*)( &mMbox.virt_addr[offset] ); offset += sizeof(dma_cb_t) * mNumSamples * ( 2 + ( mMode == MODE_BUFFER ) ); if ( (unsigned long)mMbox.virt_addr & ( PAGE_SIZE - 1 ) ) { fatal("pi-blaster: Virtual address is not page aligned\n"); } close( mMbox.handle ); mMbox.handle = -1; init_ctrl_data(); init_hardware( time_base ); update_pwm(); */ } DMArpi::~DMArpi() { } void DMArpi::get_model( unsigned mbox_board_rev ) { int board_model = 0; if ( ( mbox_board_rev & BOARD_REVISION_SCHEME_MASK ) == BOARD_REVISION_SCHEME_NEW ) { if ((mbox_board_rev & BOARD_REVISION_TYPE_MASK) == BOARD_REVISION_TYPE_PI2_B) { board_model = 2; } else if ((mbox_board_rev & BOARD_REVISION_TYPE_MASK) == BOARD_REVISION_TYPE_PI3_B) { board_model = 3; } else if ((mbox_board_rev & BOARD_REVISION_TYPE_MASK) == BOARD_REVISION_TYPE_PI3_BP) { board_model = 3; } else if ((mbox_board_rev & BOARD_REVISION_TYPE_MASK) == BOARD_REVISION_TYPE_PI3_AP) { board_model = 3; } else if ((mbox_board_rev & BOARD_REVISION_TYPE_MASK) == BOARD_REVISION_TYPE_CM3) { board_model = 3; } else if ((mbox_board_rev & BOARD_REVISION_TYPE_MASK) == BOARD_REVISION_TYPE_PI4_B) { board_model = 4; } else if ((mbox_board_rev & BOARD_REVISION_TYPE_MASK) == BOARD_REVISION_TYPE_CM4) { board_model = 4; } else { // no Pi 2, we assume a Pi 1 board_model = 1; } } else { // if revision scheme is old, we assume a Pi 1 board_model = 1; } gDebug() << "board_model : " << board_model; plldfreq_mhz = 500; switch ( board_model ) { case 1: periph_virt_base = 0x20000000; periph_phys_base = 0x7e000000; mem_flag = MEM_FLAG_L1_NONALLOCATING | MEM_FLAG_ZERO; break; case 2: case 3: periph_virt_base = 0x3f000000; periph_phys_base = 0x7e000000; mem_flag = MEM_FLAG_L1_NONALLOCATING | MEM_FLAG_ZERO; break; case 4: periph_virt_base = 0xfe000000; periph_phys_base = 0x7e000000; plldfreq_mhz = 750; // max chan: 7 mem_flag = MEM_FLAG_L1_NONALLOCATING | MEM_FLAG_ZERO; break; default: gError() << "Unable to detect Board Model from board revision: " << mbox_board_rev; break; } } int DMArpi::mbox_open() { int file_desc; file_desc = open( "/dev/vcio", 0 ); if ( file_desc < 0 ) { gError() << "Failed to create mailbox device : " << strerror(errno); } return file_desc; } void* DMArpi::map_peripheral( uint32_t base, uint32_t len ) { int fd = open( "/dev/mem", O_RDWR | O_SYNC ); void * vaddr; if ( fd < 0 ) { gError() << "Failed to open /dev/mem : " << strerror(errno); } vaddr = mmap( nullptr, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, base ); if ( vaddr == MAP_FAILED ) { gError() << "pi-blaster: Failed to map peripheral at " << std::hex << base << " : " << strerror(errno); } close( fd ); return vaddr; }
9,404
C++
.cpp
260
34.323077
172
0.688159
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,768
SPI.cpp
dridri_bcflight/flight/boards/rpi/SPI.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <iostream> #include <sys/fcntl.h> #include <sys/ioctl.h> #include <linux/i2c-dev.h> #include <errno.h> #include <unistd.h> #include <string.h> #include <Debug.h> #include "SPI.h" #include "Board.h" using namespace std; SPI::SPI( const string& device, uint32_t speed_hz ) : Bus() , mDevice( device ) , mSpeedHz( speed_hz ) { fDebug( device, speed_hz ); } SPI::~SPI() { } int SPI::Connect() { fDebug( mDevice, mSpeedHz ); if ( mConnected ) { return 0; } errno = 0; mFD = open( mDevice.c_str(), O_RDWR ); if ( mFD < 0 ) { gError() << "fd : " << mFD << " (" << strerror(errno) << ")"; return -1; } uint8_t mode, lsb; mode = SPI_MODE_0; mBitsPerWord = 8; if ( ioctl( mFD, SPI_IOC_WR_MODE, &mode ) < 0 ) { gError() << "SPI wr_mode"; return -1; } if ( ioctl( mFD, SPI_IOC_RD_MODE, &mode ) < 0 ) { gError() << "SPI rd_mode"; return -1; } if ( ioctl( mFD, SPI_IOC_WR_BITS_PER_WORD, &mBitsPerWord ) < 0 ) { gError() << "SPI write bits_per_word"; return -1; } if ( ioctl( mFD, SPI_IOC_RD_BITS_PER_WORD, &mBitsPerWord ) < 0 ) { gError() << "SPI read bits_per_word"; return -1; } if ( ioctl( mFD, SPI_IOC_WR_MAX_SPEED_HZ, &mSpeedHz ) < 0 ) { gError() << "can't set max speed hz"; return -1; } if ( ioctl( mFD, SPI_IOC_RD_MAX_SPEED_HZ, &mSpeedHz ) < 0 ) { gError() << "SPI max_speed_hz"; return -1; } if ( ioctl( mFD, SPI_IOC_RD_LSB_FIRST, &lsb ) < 0 ) { gError() << "SPI rd_lsb_fist"; return -1; } gDebug() << mDevice.c_str() << ":" << mFD <<": spi mode " << (int)mode << ", " << mBitsPerWord << "bits " << ( lsb ? "(lsb first) " : "" ) << "per word, " << mSpeedHz << " Hz max"; memset( mXFer, 0, sizeof( mXFer ) ); for ( uint32_t i = 0; i < sizeof( mXFer ) / sizeof( struct spi_ioc_transfer ); i++) { mXFer[i].len = 0; mXFer[i].cs_change = 0; // Keep CS activated mXFer[i].delay_usecs = 0; mXFer[i].speed_hz = mSpeedHz; mXFer[i].bits_per_word = 8; } mConnected = true; return 0; } LuaValue SPI::infos() { LuaValue ret; ret["Type"] = "SPI"; ret["Device"] = mDevice; ret["Bitrate"] = to_string(mSpeedHz) + "Hz"; return ret; } const string& SPI::device() const { return mDevice; } int SPI::Transfer( void* tx, void* rx, uint32_t len ) { mTransferMutex.lock(); mXFer[0].tx_buf = (uintptr_t)tx; mXFer[0].len = len; mXFer[0].rx_buf = (uintptr_t)rx; int ret = ioctl( mFD, SPI_IOC_MESSAGE(1), mXFer ); mTransferMutex.unlock(); return ret; } int SPI::Read( void* buf, uint32_t len ) { uint8_t unused[256]; memset( unused, 0, len + 1 ); return Transfer( unused, buf, len ); } int SPI::Write( const void* buf, uint32_t len ) { uint8_t unused[256]; memset( unused, 0, len + 1 ); return Transfer( (void*)buf, unused, len ); } int SPI::Read( uint8_t reg, void* buf, uint32_t len ) { uint8_t tx[256]; uint8_t rx[256]; memset( tx, 0, len + 1 ); tx[0] = reg; int ret = Transfer( tx, rx, len + 1 ); memcpy( buf, rx + 1, len ); return ret - 1; } int SPI::Write( uint8_t reg, const void* buf, uint32_t len ) { uint8_t tx[256]; uint8_t rx[256]; tx[0] = reg; memcpy( tx + 1, buf, len ); return Transfer( tx, rx, len + 1 ) - 1; }
3,874
C++
.cpp
152
23.348684
184
0.635871
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,769
DShotDriver.cpp
dridri_bcflight/flight/boards/rpi/DShotDriver.cpp
#include <string.h> #include <sys/fcntl.h> #include <sys/mman.h> #include <unistd.h> #include <mutex> #include <GPIO.h> #include "Board.h" #include "DShotDriver.h" #include "Debug.h" #include "video/DRM.h" // TODO : ifdef PI_VARIANT = 4 #include <xf86drm.h> #include <xf86drmMode.h> extern std::mutex __global_rpi_drm_mutex; DShotDriver* DShotDriver::sInstance = nullptr; uint8_t DShotDriver::sDPIMode = 7; // Format : [ channel (R/G/B), pin bit ] uint8_t DShotDriver::sDPIPinMap[8][28][2] = { {}, // invalid {}, // unused { // mode 2, RGB565, total of 16 pins available {}, {}, {}, {}, // pins 0,1,2,3 unused { 0, 3 }, { 0, 4 }, { 0, 5 }, { 0, 6 }, { 0, 7 }, { 1, 2 }, { 1, 3 }, { 1, 4 }, { 1, 5 }, { 1, 6 }, { 1, 7 }, { 2, 3 }, { 2, 4 }, { 2, 5 }, { 2, 6 }, { 2, 7 } }, { // mode 3, RGB565, total of 16 pins available {}, {}, {}, {}, // pins 0,1,2,3 unused { 0, 3 }, { 0, 4 }, { 0, 5 }, { 0, 6 }, { 0, 7 }, {}, {}, {}, // pins 10,11,12 unused { 1, 2 }, { 1, 3 }, { 1, 4 }, { 1, 5 }, { 1, 6 }, { 1, 7 }, {}, {}, // pins 18,19 unused { 2, 3 }, { 2, 4 }, { 2, 5 }, { 2, 6 }, { 2, 7 } }, { // mode 4, RGB565, total of 16 pins available {}, {}, {}, {}, {}, // pins 0,1,2,3,4 unused { 0, 3 }, { 0, 4 }, { 0, 5 }, { 0, 6 }, { 0, 7 }, {}, {}, // pins 10,11 unused { 1, 2 }, { 1, 3 }, { 1, 4 }, { 1, 5 }, { 1, 6 }, { 1, 7 }, {}, {}, {}, // pins 18,19,20 unused { 2, 3 }, { 2, 4 }, { 2, 5 }, { 2, 6 }, { 2, 7 } }, { // mode 5, RGB666, total of 18 pins available {}, {}, {}, {}, // pins 0,1,2,3 unused { 0, 2 }, { 0, 3 }, { 0, 4 }, { 0, 5 }, { 0, 6 }, { 0, 7 }, { 1, 2 }, { 1, 3 }, { 1, 4 }, { 1, 5 }, { 1, 6 }, { 1, 7 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, { 2, 5 }, { 2, 6 }, { 2, 7 } }, { // mode 6, RGB666, total of 18 pins available {}, {}, {}, {}, // pins 0,1,2,3 unused { 0, 2 }, { 0, 3 }, { 0, 4 }, { 0, 5 }, { 0, 6 }, { 0, 7 }, {}, {}, // pins 10,11 unused { 1, 2 }, { 1, 3 }, { 1, 4 }, { 1, 5 }, { 1, 6 }, { 1, 7 }, {}, {}, // pins 18,19 unused { 2, 2 }, { 2, 3 }, { 2, 4 }, { 2, 5 }, { 2, 6 }, { 2, 7 } }, { // mode 7, RGB888, total of 24 pins available {}, {}, {}, {}, // pins 0,1,2,3 unused { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 0, 5 }, { 0, 6 }, { 0, 7 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, { 1, 3 }, { 1, 4 }, { 1, 5 }, { 1, 6 }, { 1, 7 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, { 2, 5 }, { 2, 6 }, { 2, 7 } }, }; bool DShotDriver::sKilled = false; DShotDriver* DShotDriver::instance( bool create_new ) { if ( !sInstance and create_new ) { sInstance = new DShotDriver(); } return sInstance; } DShotDriver::DShotDriver() { int fd = DRM::drmFd(); // Step 2 : find a suitable CRTC/Connector uint32_t crtc_id = 0xffffffff; //87; uint32_t connector_id = 0xffffffff; //89; drmModeRes* modes = drmModeGetResources(fd); for ( int32_t i = 0; i < modes->count_crtcs and crtc_id == 0xffffffff; i++ ) { drmModeCrtcPtr crtc = drmModeGetCrtc(fd, modes->crtcs[i]); if ( !strcmp( crtc->mode.name, "FIXED_MODE" ) and ( crtc->width == 32 or crtc->width == 512 or crtc->width == 1024 or crtc->width == 3072 ) ) { crtc_id = crtc->crtc_id; } drmModeFreeCrtc(crtc); } for ( int32_t i = 0; i < modes->count_connectors and connector_id == 0xffffffff; i++ ) { drmModeConnectorPtr connector = drmModeGetConnector(fd, modes->connectors[i]); drmModeEncoderPtr encoder = drmModeGetEncoder(fd, connector->encoders[0]); if ( connector->connection == DRM_MODE_CONNECTED and ( connector->connector_type == DRM_MODE_CONNECTOR_DPI or connector->connector_type == DRM_MODE_CONNECTOR_DSI ) and encoder->crtc_id == crtc_id ) { connector_id = connector->connector_id; } drmModeFreeEncoder(encoder); drmModeFreeConnector(connector); } drmModeFreeResources(modes); gDebug() << "CRTC : " << crtc_id; gDebug() << "Connector : " << connector_id; if ( crtc_id == 0xffffffff or connector_id == 0xffffffff ) { gError() << "No DPI CRTC/Connector found"; exit(3); } // Step 3 : Create and allocate buffer, then attach it to CRTC struct drm_mode_create_dumb creq; struct drm_mode_map_dumb mreq; uint32_t fb_id; drmModeCrtcPtr crtc_info = drmModeGetCrtc( fd, crtc_id ); memset( &creq, 0, sizeof(struct drm_mode_create_dumb) ); creq.width = crtc_info->mode.hdisplay; creq.height = crtc_info->mode.vdisplay; creq.bpp = 24; gDebug() << creq.width << " x " << creq.height; if ( drmIoctl( fd, DRM_IOCTL_MODE_CREATE_DUMB, &creq ) < 0 ) { gError() << "drmIoctl DRM_IOCTL_MODE_CREATE_DUMB failed : " << strerror(errno); exit(3); } gDebug() << "drmModeAddFB(" << fd << ", " << creq.width << ", " << creq.height << ", " << 24 << ", " << 24 << ", " << creq.pitch << ", " << creq.handle << ", &fb_id)"; if ( drmModeAddFB(fd, creq.width, creq.height, 24, 24, creq.pitch, creq.handle, &fb_id) ) { gError() << "drmModeAddFB failed : " << strerror(errno); exit(3); } gDebug() << "fb_id: " << fb_id; gDebug() << "pitch: " << creq.pitch; memset( &mreq, 0, sizeof(struct drm_mode_map_dumb) ); mreq.handle = creq.handle; if ( drmIoctl( fd, DRM_IOCTL_MODE_MAP_DUMB, &mreq ) ) { gError() << "drmIoctl DRM_IOCTL_MODE_MAP_DUMB failed : " << strerror(errno); exit(3); } if ( drmModeSetCrtc( fd, crtc_id, fb_id, 0, 0, &connector_id, 1, &crtc_info->mode ) ) { gError() << "drmModeSetCrtc() failed : " << strerror(errno); exit(3); } drmModeFreeCrtc(crtc_info); // TODO // struct sg_table * dma_buf_map_attachment(struct dma_buf_attachment * attach, enum dma_data_direction direction) // sg_table->dma_address should be the needed bus-address mDRMBuffer = (uint8_t*)mmap( 0, creq.size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, mreq.offset ); if ( mDRMBuffer == MAP_FAILED ) { gError() << "mmap fb failed : " << strerror(errno); exit(3); } mDRMPitch = creq.pitch; mDRMWidth = creq.width; mDRMHeight = creq.height; gDebug() << "DRM buffer : " << mDRMBuffer << "(" << mDRMWidth << "x" << mDRMHeight << ") [" << mDRMPitch << "]"; memset( mDRMBuffer, 0, mDRMPitch * mDRMHeight ); atexit( []() { DShotDriver::AtExit(); }); } DShotDriver::~DShotDriver() { } void DShotDriver::AtExit() { if ( sInstance ) { sInstance->Kill(); } } void DShotDriver::Kill() noexcept { fDebug(); sKilled = true; for ( uint8_t retry = 0; retry < 10; retry++ ) { for ( auto iter = mPinValues.begin(); iter != mPinValues.end(); ++iter ) { mFlatValues[iter->first] = true; mPinValues[iter->first] = 0; } _Update(); usleep( 1000 ); } memset( mDRMBuffer, 0, mDRMPitch * mDRMHeight ); } void DShotDriver::setPinValue( uint32_t pin, uint16_t value, bool telemetry ) { if ( mPinValues.find(pin) == mPinValues.end() ) { gDebug() << "Setting pin " << pin << " to Alt2"; GPIO::setMode( pin, GPIO::Alt2 ); GPIO::setPUD( pin, GPIO::PullDown ); } value = (value << 1) | telemetry; mPinValues[pin] = ( value << 4 ) | ( (value ^ (value >> 4) ^ (value >> 8)) & 0x0F ); mFlatValues[pin] = false; } void DShotDriver::disablePinValue( uint32_t pin ) { if ( mPinValues.find(pin) == mPinValues.end() ) { gDebug() << "Setting pin " << pin << " to Alt2"; GPIO::setMode( pin, GPIO::Alt2 ); GPIO::setPUD( pin, GPIO::PullDown ); } mFlatValues[pin] = true; mPinValues[pin] = 0xFFFFFFFF; } void DShotDriver::Update() { if ( sKilled ) { return; } _Update(); } void DShotDriver::_Update() { // uint16_t valueFlat[DSHOT_MAX_OUTPUTS] = { 0 }; uint16_t valueMap[DSHOT_MAX_OUTPUTS] = { 0 }; uint16_t channelMap[DSHOT_MAX_OUTPUTS] = { 0 }; uint16_t bitmaskMap[DSHOT_MAX_OUTPUTS] = { 0 }; uint8_t count = 0; for ( auto iter = mPinValues.begin(); iter != mPinValues.end(); ++iter ) { if ( iter->second == 0xFFFFFFFF ) { continue; } // valueFlat[count] = mFlatValues[iter->first]; valueMap[count] = uint16_t(iter->second); uint8_t* mapped = sDPIPinMap[sDPIMode][iter->first]; channelMap[count] = mapped[0]; bitmaskMap[count] = mapped[1]; count++; } const uint32_t bitwidth = 32; // mDRMWidth / 16; const uint32_t t0h = bitwidth * 1250 / 3333; uint8_t outbuf[16 * bitwidth * 3]; memset( outbuf, 0, 16 * bitwidth * 3 ); for ( uint32_t ivalue = 0; ivalue < count; ivalue++ ) { uint16_t value = valueMap[ivalue]; uintptr_t map = channelMap[ivalue]; uintptr_t bitmask = ( 1 << bitmaskMap[ivalue] ); uint8_t* bPointer = outbuf; for ( int8_t i = 15; i >= 0; i-- ) { uint8_t repeat = t0h << ((value >> i) & 1); uint8_t rep = repeat; while ( rep-- > 0 ) { *(bPointer + map) |= bitmask; bPointer += 3; } bPointer += 3 * (bitwidth - repeat); } } memcpy( mDRMBuffer, outbuf, 16 * bitwidth * 3 ); // for ( uint32_t y = 0; y < mDRMHeight; y++ ) { // memcpy( mDRMBuffer + y * mDRMPitch, outbuf, 16 * bitwidth * 3 ); // } }
8,722
C++
.cpp
241
33.767635
201
0.580114
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,770
GPIO.cpp
dridri_bcflight/flight/boards/rpi/GPIO.cpp
/* * BCFlight * Copyright (C) 2016 Adrien Aubry (drich) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <pigpio.h> // #include <wiringPi.h> #include <unistd.h> #include <sys/poll.h> #include <sys/ioctl.h> #include <sys/eventfd.h> #include <fcntl.h> // #include <softPwm.h> #include <Debug.h> #include "GPIO.h" map< int, list<pair<function<void()>,GPIO::ISRMode>> > GPIO::mInterrupts; map< int, GPIO::ISR* > GPIO::mThreads; void GPIO::setMode( int pin, GPIO::Mode mode ) { gpioSetMode( pin, mode ); // if ( mode == Output ) { // gpioSetMode( pin, PI_OUTPUT ); // } else { // gpioSetMode( pin, PI_INPUT ); // } } void GPIO::setPUD( int pin, PUDMode mode ) { gpioSetPullUpDown( pin, mode ); } void GPIO::setPWM( int pin, int initialValue, int pwmRange ) { // TODO : switch from wiringPi to pigpio // setMode( pin, Output ); // softPwmCreate( pin, initialValue, pwmRange ); } void GPIO::Write( int pin, bool en ) { gpioWrite( pin, en ); } bool GPIO::Read( int pin ) { return gpioRead( pin ); } // std::map< int, function<void()> > isrs; // static bool ok = false; void GPIO::SetupInterrupt( int pin, GPIO::ISRMode mode, function<void()> fct ) { /* isrs[pin] = fct; #define ISR( pin ) \ wiringPiISR( pin, INT_EDGE_RISING, [](){ \ if ( isrs[pin] ) { \ isrs[pin](); \ } \ }); if ( not ok ) { ISR( 22 ); ISR( 27 ); ok = true; } */ if ( mInterrupts.find( pin ) != mInterrupts.end() ) { mInterrupts.at( pin ).emplace_back( make_pair( fct, mode ) ); } else { list<pair<function<void()>,GPIO::ISRMode>> lst; lst.emplace_back( make_pair( fct, mode ) ); mInterrupts.emplace( make_pair( pin, lst ) ); system( ( "echo " + to_string( pin ) + " > /sys/class/gpio/export" ).c_str() ); int32_t fd = open( ( "/sys/class/gpio/gpio" + to_string( pin ) + "/value" ).c_str(), O_RDWR ); system( ( "echo both > /sys/class/gpio/gpio" + to_string( pin ) + "/edge" ).c_str() ); int count = 0; char c = 0; ioctl( fd, FIONREAD, &count ); for ( int i = 0; i < count; i++ ) { (void)read( fd, &c, 1 ); } ISR* isr = new ISR( pin, fd ); mThreads.emplace( make_pair( pin, isr ) ); isr->Start(); isr->setPriority( 99 ); } } GPIO::ISR::ISR( int pin, int fd ) : Thread( "GPIO::ISR_" + to_string(pin) ) , mPin( pin ) , mFD( fd ) , mReady( false ) { mExitFD = eventfd( 0, EFD_NONBLOCK ); if ( mExitFD < 0 ) { gDebug() << "Failed to create eventfd for GPIO ISR"; } } bool GPIO::ISR::run() { if ( not mReady ) { mReady = true; usleep( 1000 * 100 ); } struct pollfd fds[2]; char buffer[16]; list<pair<function<void()>,GPIO::ISRMode>>& fcts = mInterrupts.at( mPin ); fds[0].fd = mFD; fds[0].events = POLLPRI; fds[1].fd = mExitFD; fds[1].events = POLLIN; lseek( mFD, 0, SEEK_SET ); int rpoll = poll( fds, 2, -1 ); if ( rpoll >= 1 ) { if ( read( mExitFD, buffer, 16 ) > 0 and buffer[0] == 1 ) { return false; } if ( read( mFD, buffer, 2 ) > 0 ) { for ( pair<function<void()>,GPIO::ISRMode> fct : fcts ) { if ( buffer[0] == '1' and fct.second != Falling ) { fct.first(); } else if ( buffer[0] == '0' and fct.second != Rising ) { fct.first(); } } } } return true; } void GPIO::ISR::Stop() { Thread::Stop(); uint64_t val = 1; write( mExitFD, &val, sizeof(val) ); }
3,896
C++
.cpp
143
24.986014
96
0.63412
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
754,771
Mutex.cpp
dridri_bcflight/flight/boards/rpi/Mutex.cpp
#include "Mutex.h" Mutex::Mutex() { } Mutex::~Mutex() { } void Mutex::Lock() { mMutex.lock(); } void Mutex::Unlock() { mMutex.unlock(); } void Mutex::lock() { mMutex.lock(); } void Mutex::unlock() { mMutex.unlock(); }
233
C++
.cpp
23
8.478261
20
0.668342
dridri/bcflight
131
22
8
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false