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,772
Board.cpp
dridri_bcflight/flight/boards/rpi/Board.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 <time.h> #include <unistd.h> #include <stdio.h> #include <sys/time.h> #include <sys/signal.h> #include <arpa/inet.h> #include <net/if.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/fcntl.h> #include <sys/ioctl.h> #include <stdarg.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <execinfo.h> extern "C" { #include <interface/vmcs_host/vc_vchi_gencmd.h> #include <interface/vmcs_host/vc_vchi_bufman.h> #include <interface/vmcs_host/vc_tvservice.h> #include <interface/vmcs_host/vc_cecservice.h> #include <interface/vmcs_host/vcgencmd.h> #include <interface/vchiq_arm/vchiq_if.h> }; // #include <wiringPi.h> #include <pigpio.h> #include <fstream> #include <Main.h> #include "Board.h" #include "I2C.h" #include "PWM.h" #include "DShotDriver.h" #include "Debug.h" extern "C" void bcm_host_init( void ); extern "C" void bcm_host_deinit( void ); // extern "C" void OMX_Init(); uint64_t Board::mTicksBase = 0; uint64_t Board::mLastWorkJiffies = 0; uint64_t Board::mLastTotalJiffies = 0; bool Board::mUpdating = false; decltype(Board::mRegisters) Board::mRegisters = decltype(Board::mRegisters)(); HookThread<Board>* Board::mStatsThread = nullptr; uint32_t Board::mCPUTemp = 0; uint32_t Board::mCPULoad = 0; uint32_t Board::mMemoryUsage = 0; bool Board::mDiskFull = false; vector< string > Board::mBoardMessages; map< string, bool > Board::mDefectivePeripherals; VCHI_INSTANCE_T Board::global_initialise_instance = nullptr; VCHI_CONNECTION_T* Board::global_connection = nullptr; #include <signal.h> Board::Board( Main* main ) { bcm_host_init(); #ifdef CAMERA // OMX_Init(); #endif vc_gencmd_init(); // VCOSInit(); // wiringPiSetup(); // wiringPiSetupGpio(); gpioInitialise(); system( "modprobe i2c-dev" ); system( "mount -o remount,rw /var" ); system( "mkdir -p /var/VIDEO" ); atexit( &Board::AtExit ); struct sigaction sa; memset( &sa, 0, sizeof(sa) ); sa.sa_handler = &Board::SegFaultHandler; sigaction( 11, &sa, NULL ); ifstream file( "/var/flight/registers" ); string line; if ( file.is_open() ) { while ( getline( file, line, '\n' ) ) { string key = line.substr( 0, line.find( "=" ) ); string value = line.substr( line.find( "=" ) + 1 ); mRegisters[ key ] = value; } file.close(); } // gDebug() << readcmd( "iw list" ); if ( mStatsThread == nullptr ) { mStatsThread = new HookThread<Board>( "board_stats", this, &Board::StatsThreadRun ); mStatsThread->setFrequency( 1 ); mStatsThread->Start(); } } Board::~Board() { } void Board::AtExit() { PWM::terminate(0); } void Board::SegFaultHandler( int sig ) { string msg; char name[64] = ""; Thread* thread = Thread::currentThread(); if ( thread ) { thread->Stop(); msg = "Thread \"" + thread->name() + "\" crashed !"; } else { pthread_getname_np( pthread_self(), name, sizeof(name) ); if ( name[0] == '\0' or !strcmp( name, "flight" ) ) { msg = "Thread <unknown> crashed !"; } else { msg = "Thread \"" + string(name) + "\" crashed !"; } } mBoardMessages.emplace_back( msg ); gDebug() << "\e[0;41m" << msg << "\e[0m"; void* array[16]; size_t size; size = backtrace( array, 16 ); fprintf( stderr, "Error: signal %d :\n", sig ); char** trace = backtrace_symbols( array, size ); gDebug() << "\e[91mStack trace :\e[0m"; for ( size_t j = 0; j < size; j++ ) { gDebug() << "\e[91m" << trace[j] << "\e[0m"; } bool critical = false; if ( thread and thread->name() == "stabilizer" ) { gError() << "\e[93mStabilizer crashed, watch out your heads\e[0m"; critical = true; } if ( thread and thread->name() == "controller" ) { gError() << "\e[93mController crashed, watch out your heads\e[0m"; critical = true; } if ( critical ) { DShotDriver* d = DShotDriver::instance( false ); if ( d ) { d->Kill(); } PWM::terminate(0); exit(1); } else { // Try to restart the thread, but not too many times static uint32_t total_restarts = 0; if ( thread and total_restarts < 4 ) { total_restarts++; thread->Recover(); } } while ( 1 ) { usleep( 1000 * 1000 * 10 ); } } vector< string > Board::messages() { vector< string > msgs; for ( auto defect : mDefectivePeripherals ) { if ( defect.second == true ) { msgs.emplace_back( defect.first + " is defective !" ); } } if ( mDiskFull ) { msgs.emplace_back( "No free space on disk" ); } if ( mCPUTemp > 80 ) { msgs.emplace_back( "High CPU Temp (" + to_string(mCPUTemp) + "\xB0"" C)" ); } msgs.insert( msgs.end(), mBoardMessages.begin(), mBoardMessages.end() ); return msgs; } map< string, bool >& Board::defectivePeripherals() { return mDefectivePeripherals; } void Board::UpdateFirmwareData( const uint8_t* buf, uint32_t offset, uint32_t size ) { gDebug() << "Saving Flight Controller firmware update (" << size << " bytes at offset " << offset << ")"; if ( offset == 0 ) { system( "rm -f /tmp/flight_update" ); system( "touch /tmp/flight_update" ); } fstream firmware( "/tmp/flight_update", ios_base::in | ios_base::out | ios_base::binary ); firmware.seekg( offset, firmware.beg ); firmware.write( (char*)buf, size ); firmware.close(); } static uint32_t 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; } void Board::UpdateFirmwareProcess( uint32_t crc ) { if ( mUpdating ) { return; } gDebug() << "Updating Flight Controller firmware"; mUpdating = true; ifstream firmware( "/tmp/flight_update" ); if ( firmware.is_open() ) { firmware.seekg( 0, firmware.end ); int length = firmware.tellg(); uint8_t* buf = new uint8_t[ length + 1 ]; firmware.seekg( 0, firmware.beg ); firmware.read( (char*)buf, length ); buf[length] = 0; firmware.close(); if ( crc32( buf, length ) != crc ) { gDebug() << "ERROR : Wrong CRC32 for firmware upload, please retry"; mUpdating = false; return; } system( "rm -f /tmp/update.sh" ); ofstream file( "/tmp/update.sh" ); file << "#!/bin/bash\n\n"; file << "systemctl stop flight.service &\n"; file << "sleep 1\n"; file << "systemctl stop flight.service &\n"; file << "sleep 1\n"; file << "killall -9 flight\n"; file << "sleep 0.5\n"; file << "killall -9 flight\n"; file << "sleep 0.5\n"; file << "killall -9 flight\n"; file << "sleep 1\n"; file << "rm /var/flight/flight\n"; file << "cp /tmp/flight_update /var/flight/flight\n"; file << "sleep 2\n"; file << "rm /tmp/flight_update\n"; file << "sleep 1\n"; file << "chmod +x /var/flight/flight\n"; file << "sleep 1\n"; file << "systemctl start flight.service\n"; file.close(); system( "nohup sh /tmp/update.sh &" ); } } void Board::Reset() { gDebug() << "Restarting Flight Controller service"; system( "rm -f /tmp/reset.sh" ); ofstream file( "/tmp/reset.sh" ); file << "#!/bin/bash\n\n"; file << "systemctl stop flight.service &\n"; file << "sleep 1\n"; file << "systemctl stop flight.service &\n"; file << "sleep 1\n"; file << "killall -9 flight\n"; file << "sleep 0.5\n"; file << "killall -9 flight\n"; file << "sleep 0.5\n"; file << "killall -9 flight\n"; file << "sleep 1\n"; file << "systemctl start flight.service\n"; file.close(); system( "sh /tmp/reset.sh" ); } static string readproc( const string& filename, const string& entry = "", const string& delim = ":" ) { char buf[1024] = ""; string res = ""; ifstream file( filename ); if ( file.is_open() ) { if ( entry.length() == 0 or entry == "" ) { file.readsome( buf, sizeof( buf ) ); res = buf; } else { while ( file.good() ) { file.getline( buf, sizeof(buf), '\n' ); if ( strstr( buf, entry.c_str() ) ) { char* s = strstr( buf, delim.c_str() ) + delim.length(); while ( *s == ' ' or *s == '\t' ) { s++; } char* end = s; while ( *end != '\n' and *end++ ); *end = 0; res = string( s ); break; } } } file.close(); } return res; } string Board::readcmd( const string& cmd, const string& entry, const string& delim ) { char buf[1024] = ""; string res = ""; FILE* fp = popen( cmd.c_str(), "r" ); if ( !fp ) { printf( "popen failed : %s\n", strerror( errno ) ); return ""; } if ( entry.length() == 0 or entry == "" ) { while ( fgets( buf, sizeof(buf), fp ) ) { res += buf; } } else { while ( fgets( buf, sizeof(buf), fp ) ) { if ( strstr( buf, entry.c_str() ) ) { char* s = strstr( buf, delim.c_str() ) + delim.length(); while ( *s == ' ' or *s == '\t' ) { s++; } char* end = s; while ( *end != '\n' and *end++ ); *end = 0; res = string( s ); break; } } } pclose( fp ); return res; } string Board::infos() { string res = ""; res += "{\n"; res += "\t[\"Type\"] = \"" BOARD "\",\n"; res += "\t[\"Firmware version\"] = \"" VERSION_STRING "\",\n"; res += "\t[\"OS\"] = " + readproc( "/etc/os-release", "PRETTY_NAME", "=" ) + string( ",\n" ); res += "\t[\"Model\"] = \"" + readproc( "/proc/cpuinfo", "Model" ) + string( "\",\n" ); res += "\t[\"CPU\"] = \"" + readproc( "/proc/cpuinfo", "Hardware" ) + string( "\",\n" ); res += "\t[\"CPU cores count\"] = \"" + to_string( sysconf( _SC_NPROCESSORS_ONLN ) ) + string( "\",\n" ); res += "\t[\"CPU frequency\"] = \"" + to_string( atoi( readproc( "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq" ).c_str() ) / 1000 ) + string( "MHz\",\n" ); res += "\t[\"GPU frequency\"] = \"" + to_string( atoi( readcmd( "vcgencmd measure_clock core", "frequency", "=" ).c_str() ) / 1000000 ) + string( "MHz\",\n" ); res += "\t[\"SoC voltage\"] = \"" + readcmd( "vcgencmd measure_volts core", "volt", "=" ) + string( "\",\n" ); res += "\t[\"RAM\"] = \"" + readcmd( "vcgencmd get_mem arm", "arm", "=" ) + string( "\",\n" ); res += "\t[\"VRAM\"] = \"" + readcmd( "vcgencmd get_mem gpu", "gpu", "=" ) + string( "\",\n" ); res += "}"; return res; } void Board::InformLoading( int force_led ) { static uint64_t ticks = 0; static bool led_state = true; char cmd[256] = ""; if ( force_led == 0 or force_led == 1 or GetTicks() - ticks >= 1000 * 250 ) { ticks = GetTicks(); led_state = !led_state; if ( force_led == 0 or force_led == 1 ) { led_state = force_led; } sprintf( cmd, "echo %d > /sys/class/leds/ACT/brightness", led_state ); system( cmd ); } } void Board::LoadingDone() { InformLoading( 0 ); } void Board::setLocalTimestamp( uint32_t t ) { struct timespec ts; ts.tv_sec = t; clock_settime( CLOCK_REALTIME, &ts ); } Board::Date Board::localDate() { Date ret; struct tm* tm = nullptr; time_t tmstmp = time( nullptr ); tm = localtime( &tmstmp ); ret.year = 1900 + tm->tm_year; ret.month = tm->tm_mon; ret.day = tm->tm_mday; ret.hour = tm->tm_hour; ret.minute = tm->tm_min; ret.second = tm->tm_sec; return ret; } const uint32_t Board::LoadRegisterU32( const string& name, uint32_t def ) { string str = LoadRegister( name ); if ( str != "" and str.length() > 0 ) { return strtoul( str.c_str(), nullptr, 10 ); } return def; } const float Board::LoadRegisterFloat( const string& name, float def ) { string str = LoadRegister( name ); if ( str != "" and str.length() > 0 ) { return atof( str.c_str() ); } return def; } const string Board::LoadRegister( const string& name ) { if ( mRegisters.find( name ) != mRegisters.end() ) { return mRegisters[ name ]; } return ""; } int Board::SaveRegister( const string& name, const string& value ) { mRegisters[ name ] = value; ofstream file( "/var/flight/registers" ); if ( file.is_open() ) { for ( auto reg : mRegisters ) { string line = reg.first + "=" + reg.second + "\n"; file.write( line.c_str(), line.length() ); } file.flush(); file.close(); sync(); return 0; } return -1; } uint64_t Board::GetTicks() { if ( mTicksBase == 0 ) { struct timespec now; clock_gettime( CLOCK_MONOTONIC, &now ); mTicksBase = (uint64_t)now.tv_sec * 1000000ULL + (uint64_t)now.tv_nsec / 1000ULL; } struct timespec now; clock_gettime( CLOCK_MONOTONIC, &now ); return (uint64_t)now.tv_sec * 1000000ULL + (uint64_t)now.tv_nsec / 1000ULL - mTicksBase; } uint64_t Board::WaitTick( uint64_t ticks_p_second, uint64_t lastTick, int64_t sleep_bias ) { // fDebug( ticks_p_second, lastTick, sleep_bias ); uint64_t ticks = GetTicks(); if ( ( ticks - lastTick ) < ticks_p_second ) { int64_t t = (int64_t)ticks_p_second - ( (int64_t)ticks - (int64_t)lastTick ) + sleep_bias; if ( t < 0 ) { t = 0; } usleep( t ); } return GetTicks(); } void Board::VCOSInit() { VCHIQ_INSTANCE_T vchiq_instance; int success = -1; char response[ 128 ]; vcos_init(); if ( vchiq_initialise( &vchiq_instance ) != VCHIQ_SUCCESS ) { gDebug() << "* Failed to open vchiq instance"; exit(-1); } gDebug() << "vchi_initialise"; success = vchi_initialise( &global_initialise_instance ); vcos_assert(success == 0); vchiq_instance = (VCHIQ_INSTANCE_T)global_initialise_instance; global_connection = vchi_create_connection( single_get_func_table(), vchi_mphi_message_driver_func_table() ); gDebug() << "vchi_connect"; vchi_connect( &global_connection, 1, global_initialise_instance ); vc_vchi_gencmd_init( global_initialise_instance, &global_connection, 1 ); vc_vchi_dispmanx_init( global_initialise_instance, &global_connection, 1 ); vc_vchi_tv_init( global_initialise_instance, &global_connection, 1 ); vc_vchi_cec_init( global_initialise_instance, &global_connection, 1 ); if ( success == 0 ) { success = vc_gencmd( response, sizeof(response), "set_vll_dir /sd/vlls" ); vcos_assert( success == 0 ); } } bool Board::StatsThreadRun() { char cpu_temp[256]; vc_gencmd( cpu_temp, sizeof(cpu_temp)-1, "measure_temp" ); mCPUTemp = atoi( strchr( cpu_temp, '=' ) + 1 ); uint32_t jiffies[7]; stringstream ss; ss.str( readcmd( "cat /proc/stat | grep \"cpu \" | cut -d' ' -f2-", "", "" ) ); ss >> jiffies[0]; ss >> jiffies[1]; ss >> jiffies[2]; ss >> jiffies[3]; ss >> jiffies[4]; ss >> jiffies[5]; ss >> jiffies[6]; uint64_t work_jiffies = jiffies[0] + jiffies[1] + jiffies[2]; uint64_t total_jiffies = jiffies[0] + jiffies[1] + jiffies[2] + jiffies[3] + jiffies[4] + jiffies[5] + jiffies[6]; mCPULoad = ( work_jiffies - mLastWorkJiffies ) * 100 / ( total_jiffies - mLastTotalJiffies ); mLastWorkJiffies = work_jiffies; mLastTotalJiffies = total_jiffies; std::ifstream meminfo( "/proc/meminfo" ); std::string line; uint64_t totalMem = 0; uint64_t freeMem = 0; uint64_t buffers = 0; uint64_t cached = 0; while ( std::getline( meminfo, line ) ) { std::istringstream iss(line); std::string key; uint64_t value; std::string unit; iss >> key >> value >> unit; if (key == "MemTotal:") { totalMem = value; } else if (key == "MemFree:") { freeMem = value; } else if (key == "Buffers:") { buffers = value; } else if (key == "Cached:") { cached = value; } if ( totalMem > 0 and freeMem > 0 and buffers > 0 and cached > 0 ) { break; } } mMemoryUsage = ( totalMem - freeMem - buffers - cached ) * 100 / totalMem; return true; } uint32_t Board::CPULoad() { return mCPULoad; } uint32_t Board::CPUTemp() { return mCPUTemp; } uint32_t Board::MemoryUsage() { return mMemoryUsage; } uint32_t Board::FreeDiskSpace() { return strtoul( readproc( "df -P /data | tail -n1 | sed 's/ */ /g' | cut -d' ' -f4" ).c_str(), nullptr, 0 ); } void Board::setDiskFull() { mDiskFull = true; } static int tun_alloc( const char* dev ) { struct ifreq ifr; int fd, err; if ( ( fd = open( "/dev/net/tun", O_RDWR ) ) < 0 ) { printf( "open error : %s\n", strerror( errno ) ); return fd; } memset( &ifr, 0, sizeof(ifr) ); ifr.ifr_flags = 0x0001 | 0x1000; // ifr.ifr_flags = 0x0002; strncpy( ifr.ifr_name, dev, IFNAMSIZ ); if ( ( err = ioctl( fd, _IOW('T', 202, int), (void *) &ifr ) ) < 0 ) { printf( "ioctl error : %s\n", strerror( errno ) ); close( fd ); return err; } return fd; } static void cmd( const char* fmt, ... ) { char buffer[256]; va_list args; va_start( args, fmt ); vsnprintf( buffer, 256, fmt, args ); perror( buffer ); va_end( args ); system( buffer ); } /* #if ( BUILD_RAWWIFI == 1 ) typedef struct tun_args { int fd; rawwifi_t* rwifi; } tun_args; static void* thread_rx( void* argp ) { tun_args* args = (tun_args*)argp; uint8_t buffer[16384] = {0}; while ( 1 ) { uint32_t valid = 0; int nread = rawwifi_recv( args->rwifi, buffer, sizeof(buffer), &valid ); if ( nread > 0 ) { write( args->fd, buffer, nread ); } } return NULL; } static void* thread_tx( void* argp ) { tun_args* args = (tun_args*)argp; uint8_t buffer[16384] = {0}; while ( 1 ) { int nread = read( args->fd, buffer, sizeof(buffer) ); if ( nread < 0 ) { gDebug() << "Error reading from air0 interface"; close( args->fd ); break; } rawwifi_send_retry( args->rwifi, buffer, nread, 1 ); } return NULL; } #endif */ void Board::EnableTunDevice() { /* if ( true ) { // TODO : detect if rawwifi is currently in use #if ( BUILD_RAWWIFI == 1 ) int port = 128; // TODO : Dynamically find unused ports int fd = tun_alloc( "air0" ); // fcntl( fd, F_SETFL, O_NONBLOCK ); gDebug() << "tunnel fd ready"; rawwifi_t* rwifi = rawwifi_init( "wlan0", port, port + 1, 1, -1 ); // TODO : Use same device as RawWifi gDebug() << "tunnel rawwifi ready"; // TODO : use ThreadHooks tun_args* args = (tun_args*)malloc(sizeof(tun_args)); args->fd = fd; args->rwifi = rwifi; pthread_t thid1, thid2; pthread_create( &thid1, nullptr, thread_rx, (void*)args ); pthread_create( &thid2, nullptr, thread_tx, (void*)args ); // TODO : use libnl usleep( 1000 * 1000 ); cmd( "ip link set air0 up" ); usleep( 1000 * 500 ); cmd( "ip addr add 10.0.0.1/24 dev air0" ); #endif cmd( "systemctl start sshd.service" ); } else { // TODO } */ } void Board::DisableTunDevice() { // TODO } extern "C" uint32_t _mem_usage() { return 0; // TODO } uint16_t board_htons( uint16_t v ) { return htons( v ); } uint16_t board_ntohs( uint16_t v ) { return ntohs( v ); } uint32_t board_htonl( uint32_t v ) { return htonl( v ); } uint32_t board_ntohl( uint32_t v ) { return ntohl( v ); }
19,008
C++
.cpp
671
25.934426
166
0.633548
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,773
DShot_dead.cpp
dridri_bcflight/flight/boards/rpi/DShot_dead.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 BUILD_DShot #if 0 #define _POSIX_C_SOURCE 200809L #define _XOPEN_SOURCE 700 #include <execinfo.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <getopt.h> #include <errno.h> #include <stdarg.h> #include <stdint.h> #include <signal.h> #include <time.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include "mailbox.h" #include <Debug.h> #include "DShot.h" #include "GPIO.h" // pin2gpio array is not setup as empty to avoid locking all GPIO // inputs as PWM, they are set on the fly by the pin param passed. // static uint8_t pin2gpio[8]; #define DEVFILE "/dev/pi-blaster" #define DEVFILE_MBOX "/dev/pi-blaster-mbox" #define DEVFILE_VCIO "/dev/vcio" #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 PWM_BASE_OFFSET 0x0020C000 #define PWM_BASE (periph_virt_base + PWM_BASE_OFFSET) #define PWM_PHYS_BASE (periph_phys_base + PWM_BASE_OFFSET) #define PWM_LEN 0x28 #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_SRC_IGNORE (1<<11) #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 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 0 #define GPIO_MODE_OUT 1 #define PWM_CTL (0x00/4) #define PWM_PWMC (0x08/4) #define PWM_RNG1 (0x10/4) #define PWM_FIFO (0x18/4) #define PWMCLK_CNTL 40 #define PWMCLK_DIV 41 #define PWMCTL_MODE1 (1<<1) #define PWMCTL_PWEN1 (1<<0) #define PWMCTL_CLRF (1<<6) #define PWMCTL_USEF1 (1<<5) #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_PI3_B (8 << 4) #define BOARD_REVISION_TYPE_ALPHA (5 << 4) #define BOARD_REVISION_TYPE_CM (6 << 4) #define BOARD_REVISION_REV_MASK (0xF) #define LENGTH(x) (sizeof(x) / sizeof(x[0])) #define BUS_TO_PHYS(x) ((x)&~0xC0000000) #define DEBUG 1 #ifdef DEBUG #define dprintf(...) printf(__VA_ARGS__) #else #define dprintf(...) #endif map< uint8_t, uint16_t > DShot::mPins = map< uint8_t, uint16_t >(); bool DShot::mInitialized = false; uint32_t DShot::mNumSamples = 0; uint32_t DShot::mNumCBs = 0; uint32_t DShot::mNumPages = 0; uint32_t DShot::periph_virt_base = 0; uint32_t DShot::periph_phys_base = 0; uint32_t DShot::mem_flag = 0; volatile uint32_t* DShot::pcm_reg = 0; volatile uint32_t* DShot::pwm_reg = 0; volatile uint32_t* DShot::clk_reg = 0; volatile uint32_t* DShot::dma_virt_base = 0; /* base address of all PWM Channels */ volatile uint32_t* DShot::dma_reg = 0; /* pointer to the PWM Channel registers we are using */ volatile uint32_t* DShot::gpio_reg = 0; DShot::Mbox DShot::mMbox = { }; DShot::dma_ctl_t DShot::mCtls[2] = {}; static void fatal( const char *fmt, ... ) { va_list ap; va_start(ap, fmt); vfprintf(stdout, fmt, ap); va_end(ap); exit(0); } DShot::DShot( uint8_t pin ) : mPin( pin ) { if ( not mInitialized ) { mInitialized = true; // static int sig_list[] = { 2, 3, 4, 5, 6, 7, 8, 9, 11, 15, 16, 19, 20 }; static int sig_list[] = { 2 }; uint32_t i; for ( i = 0; i <= sizeof(sig_list)/sizeof(int); i++ ) { struct sigaction sa; memset( &sa, 0, sizeof(sa) ); sa.sa_handler = &DShot::terminate_dma; sigaction( sig_list[i], &sa, NULL ); } static const uint8_t channel = 6; mNumSamples = 16 * 3 * 2; mNumCBs = mNumSamples * 2; mNumPages = ( mNumCBs * sizeof(dma_cb_t) + mNumSamples * sizeof(uint32_t) + PAGE_SIZE - 1 ) >> PAGE_SHIFT; mMbox.handle = mbox_open(); if ( mMbox.handle < 0 ) { fatal("Failed to open mailbox\n"); } 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() << "DSHOT Channels Info: " << mbox_dma_channels << ", using PWM Channel: " << (int)channel; gDebug() << "DMA Base: " << DMA_BASE; // setup_sighandlers(); /* map the registers for all PWM Channels */ dma_virt_base = (uint32_t*)map_peripheral( DMA_BASE, ( DMA_CHAN_SIZE * ( DMA_CHAN_MAX + 1 ) ) ); /* set dma_reg to point to the PWM Channel we are using */ dma_reg = dma_virt_base + channel * ( DMA_CHAN_SIZE / sizeof(dma_reg) ); pwm_reg = (uint32_t*)map_peripheral( PWM_BASE, PWM_LEN ); pcm_reg = (uint32_t*)map_peripheral( PCM_BASE, PCM_LEN ); clk_reg = (uint32_t*)map_peripheral( CLK_BASE, CLK_LEN ); gpio_reg = (uint32_t*)map_peripheral( GPIO_BASE, GPIO_LEN ); gpio_reg[GPIO_CLR0] = 1 << pin; uint32_t fsel = gpio_reg[GPIO_FSEL0 + pin/10]; fsel &= ~(7 << ((pin % 10) * 3)); fsel |= GPIO_MODE_OUT << ((pin % 10) * 3); gpio_reg[GPIO_FSEL0 + pin/10] = fsel; /* Use the mailbox interface to the VC to ask for physical memory */ uint32_t cmd_count = 4; mMbox.mem_ref = mem_alloc( mMbox.handle, mNumPages * PAGE_SIZE * cmd_count, 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), mNumPages * PAGE_SIZE * cmd_count ); 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; mCtls[0].cb = (dma_cb_t*)( &mMbox.virt_addr[offset] ); offset += sizeof(dma_cb_t) * mNumSamples * 2; if ( (unsigned long)mMbox.virt_addr & ( PAGE_SIZE - 1 ) ) { fatal("pi-blaster: Virtual address is not page aligned\n"); } /* we are done with the mbox */ close( mMbox.handle ); mMbox.handle = -1; init_ctrl_data(); dprintf("Initializing PWM HW...\n"); /* // Initialise PWM pwm_reg[PWM_CTL] = 0; usleep(10); clk_reg[PWMCLK_CNTL] = 0x5A000006; // Source=PLLD (500MHz) usleep(100); clk_reg[PWMCLK_DIV] = 0x5A000000 | ( 550 << 12 ); usleep(100); clk_reg[PWMCLK_CNTL] = 0x5A000016; // Source=PLLD and enable usleep(100); pwm_reg[PWM_RNG1] = 1; usleep(10); pwm_reg[PWM_PWMC] = PWMPWMC_ENAB | PWMPWMC_THRSHLD; usleep(10); pwm_reg[PWM_CTL] = PWMCTL_CLRF; usleep(10); pwm_reg[PWM_CTL] = PWMCTL_USEF1 | PWMCTL_PWEN1; usleep(10); */ // Initialise PCM pcm_reg[PCM_CS_A] = 1; // Disable Rx+Tx, Enable PCM block usleep(100); clk_reg[PCMCLK_CNTL] = 0x5A000006; // Source=PLLD (500MHz) usleep(100); clk_reg[PCMCLK_DIV] = 0x5A000000 | (55<<12); // DSHOT150:55, DSHOT300:27 usleep(100); clk_reg[PCMCLK_CNTL] = 0x5A000016; // Source=PLLD and enable usleep(100); pcm_reg[PCM_TXC_A] = 0<<31 | 1<<30 | 0<<20 | 0<<16; // 1 channel, 8 bits usleep(100); pcm_reg[PCM_MODE_A] = (20 - 1) << 10; // 2=2x10 => 10 with 55 PCMCLK_DIV is way better than 1 with 550 PCMCLK_DIV, 2 is to get proper value.. ^^" usleep(100); pcm_reg[PCM_CS_A] |= 1<<4 | 1<<3; // Clear FIFOs usleep(100); pcm_reg[PCM_DREQ_A] = 64<<24 | 64<<8; // DMA Req when one slot is free? usleep(100); pcm_reg[PCM_CS_A] |= 1<<9; // Enable DMA // Initialise the DMA dma_reg[DMA_CS] = DMA_RESET; usleep(10); dma_reg[DMA_CS] = DMA_INT | DMA_END; dma_reg[DMA_CONBLK_AD] = mem_virt_to_phys(mCtls[0].cb); dma_reg[DMA_DEBUG] = 7; // clear debug error flags dma_reg[DMA_CS] = 0x10770001; // go, high priority, wait for outstanding writes pcm_reg[PCM_CS_A] |= 1<<2; // Enable Tx dprintf( "Ok\n" ); } GPIO::setPUD( pin, GPIO::PullDown ); GPIO::setMode( pin, GPIO::Output ); gpio_reg[GPIO_CLR0] = 1 << pin; uint32_t fsel = gpio_reg[GPIO_FSEL0 + pin/10]; fsel &= ~(7 << ((pin % 10) * 3)); fsel |= GPIO_MODE_OUT << ((pin % 10) * 3); gpio_reg[GPIO_FSEL0 + pin/10] = fsel; mPins.emplace( make_pair( mPin, 0 ) ); uint32_t mask = 0; for ( auto pin : mPins ) { mask |= 1 << pin.first; } uint32_t i; int test = 0; for (i = 0; i < 16 * 3; i++) { if ( i % 3 == 0 ) { test++; } if ( i % 3 == 1 and test % 2 == 0 ) { mCtls[0].sample[i] = 0; } else { mCtls[0].sample[i] = mask; } } mCtls[0].sample[i] = mask; } DShot::~DShot() { } void DShot::Disable() { } void DShot::Disarm() { } void DShot::setSpeedRaw( float speed, bool force_hw_update ) { } void DShot::terminate_dma( int sig ) { size_t i, j; printf( "pi-blaster::terminate( %d )\n", sig ); void* array[16]; size_t size; size = backtrace( array, 16 ); fprintf( stderr, "Error: signal %d :\n", sig ); char** trace = backtrace_symbols( array, size ); dprintf( "Resetting DMA...\n" ); if ( dma_reg && mMbox.virt_addr ) { dma_reg[DMA_CS] = DMA_RESET; usleep(10); } dprintf("Freeing mbox memory...\n"); if ( mMbox.virt_addr != NULL ) { unmapmem( mMbox.virt_addr, mNumPages * PAGE_SIZE ); if ( mMbox.handle <= 2 ) { mMbox.handle = mbox_open(); } mem_unlock( mMbox.handle, mMbox.mem_ref ); mem_free( mMbox.handle, mMbox.mem_ref ); // mbox_close( mMbox.handle ); } dprintf( "Unlink %s...\n", DEVFILE_MBOX ); unlink( DEVFILE_MBOX ); if ( sig == 2 ) { exit(0); } } void DShot::init_ctrl_data() { dprintf( "Initializing PWM ...\n" ); init_dma_ctl( &mCtls[0] ); // init_dma_ctl( &mCtls[1] ); dprintf( "Ok\n" ); } void DShot::init_dma_ctl( dma_ctl_t* ctl ) { dma_cb_t* cbp = ctl->cb; uint32_t phys_fifo_addr; uint32_t phys_gpclr0 = GPIO_PHYS_BASE + 0x28; uint32_t phys_gpset0 = GPIO_PHYS_BASE + 0x1c; uint32_t i; // uint32_t map = DMA_PER_MAP(5); // phys_fifo_addr = PWM_PHYS_BASE + 0x18; uint32_t map = DMA_PER_MAP(2); phys_fifo_addr = PCM_PHYS_BASE + 0x04; memset( ctl->sample, 0, sizeof(uint32_t)*mNumSamples ); /* Each bit is composed of 6 control blocks : * - GPIO set high * - timer wait * - GPIO set low/high depending on value * - timer wait * - GPIO set low * - timer wait */ for (i = 0; i < 16 * 3; i++) { // GPIO-Set/Clear command cbp->info = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP; // cbp->info = DMA_NO_WIDE_BURSTS | DMA_TDMODE; cbp->src = mem_virt_to_phys(ctl->sample + i); if ( i % 3 == 0 ) { cbp->dst = phys_gpset0; } else { cbp->dst = phys_gpclr0; } cbp->length = 4; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; // Timer trigger command cbp->info = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP | DMA_D_DREQ | map; // cbp->info = DMA_NO_WIDE_BURSTS | DMA_D_DREQ | map | DMA_TDMODE | DMA_SRC_IGNORE; cbp->src = mem_virt_to_phys(ctl->sample); // Any data will do cbp->dst = phys_fifo_addr; cbp->length = 4; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; } // Write a long LOW pulse to terminate current command { cbp->info = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP; // cbp->info = DMA_NO_WIDE_BURSTS | DMA_TDMODE; cbp->src = mem_virt_to_phys(ctl->sample + i); cbp->dst = phys_gpclr0; cbp->length = 4; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; cbp->info = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP | DMA_D_DREQ | map; // cbp->info = DMA_NO_WIDE_BURSTS | DMA_D_DREQ | map | DMA_TDMODE | DMA_SRC_IGNORE; cbp->src = mem_virt_to_phys(ctl->sample); // Any data will do cbp->dst = phys_fifo_addr; cbp->length = 20; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; } // Fence to prevent bugs caused by previous long pulse { cbp->info = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP; // cbp->info = DMA_NO_WIDE_BURSTS | DMA_TDMODE; cbp->src = mem_virt_to_phys(ctl->sample + i); cbp->dst = phys_gpclr0; cbp->length = 4; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; cbp->info = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP | DMA_D_DREQ | map; // cbp->info = DMA_NO_WIDE_BURSTS | DMA_D_DREQ | map | DMA_TDMODE | DMA_SRC_IGNORE; cbp->src = mem_virt_to_phys(ctl->sample); // Any data will do cbp->dst = phys_fifo_addr; cbp->length = 4; cbp->stride = 0; } cbp->next = mem_virt_to_phys(ctl->cb); // loop back to first control block ctl->cb[0].dst = phys_gpset0; dprintf( "Ok\n" ); } int DShot::mbox_open() { int file_desc; // try to use /dev/vcio first (kernel 4.1+) file_desc = open( DEVFILE_VCIO, 0 ); if ( file_desc < 0 ) { unlink( DEVFILE_MBOX ); if ( mknod( DEVFILE_MBOX, S_IFCHR | 0600, makedev( MAJOR_NUM, 0 ) ) < 0 ) { fatal("Failed to create mailbox device\n"); } file_desc = open( DEVFILE_MBOX, 0 ); if ( file_desc < 0 ) { printf( "Can't open device file: %s\n", DEVFILE_MBOX ); perror( NULL ); exit( -1 ); } } return file_desc; } uint32_t DShot::mem_virt_to_phys( void* virt ) { uint32_t offset = (uint8_t*)virt - mMbox.virt_addr; return mMbox.bus_addr + offset; } void DShot::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 { // no Pi 2 nor Pi 3, 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; 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; default: fatal( "Unable to detect Board Model from board revision: %#x", mbox_board_rev ); break; } } void* DShot::map_peripheral( uint32_t base, uint32_t len ) { int fd = open( "/dev/mem", O_RDWR | O_SYNC ); void * vaddr; if ( fd < 0 ) { fatal( "pi-blaster: Failed to open /dev/mem: %m\n" ); } vaddr = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, base ); if ( vaddr == MAP_FAILED ) { fatal("pi-blaster: Failed to map peripheral at 0x%08x: %m\n", base ); } close( fd ); return vaddr; } #endif // 0 #endif // BUILD_DShot
17,409
C++
.cpp
520
31.230769
172
0.659164
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,774
Thread.cpp
dridri_bcflight/flight/boards/rpi/Thread.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 <wiringPi.h> #include <iostream> #include "Thread.h" #include "Board.h" #include "Debug.h" #include "PID.h" Thread::Thread( const string& name ) : ThreadBase( name ) , mSpawned( false ) { mID = mThread; } Thread::~Thread() { } void Thread::setName( const string& name ) { mName = name; if ( mSpawned and mThread != 0 ) { pthread_setname_np( mThread, mName.substr( 0, 15 ).c_str() ); } } void Thread::Start() { fDebug( mName ); mStopped = false; mFinished = false; mIsRunning = false; if ( not mSpawned ) { void* (*ptr)(void*) = reinterpret_cast<void*(*)(void*)>((void*(*)(void*))&Thread::ThreadEntry); pthread_create( &mThread, nullptr, ptr, this ); pthread_setname_np( mThread, mName.substr( 0, 15 ).c_str() ); mSpawned = true; } mRunning = true; } Thread* Thread::currentThread() { for ( ThreadBase* th : threads() ) { if ( static_cast<Thread*>(th)->mThread == pthread_self() ) { return static_cast<Thread*>(th); } } return nullptr; } void Thread::Join() { fDebug(); uint64_t start_time = Board::GetTicks(); while ( mIsRunning and not mFinished ) { if ( Board::GetTicks() - start_time > 1000 * 1000 * 2 ) { gDebug() << "thread " << mName << " join timeout (2s), force killing"; pthread_cancel( mThread ); break; } usleep( 1000 * 10 ); } mSpawned = false; } void Thread::Recover() { gDebug() << "\e[93mRecovering thread " << mName << "\e[0m"; mRunning = false; mStopped = false; mIsRunning = false; mFinished = false; mPriority = 0; mAffinity = -1; pthread_create( &mThread, nullptr, (void*(*)(void*))&Thread::ThreadEntry, this ); pthread_setname_np( mThread, mName.substr( 0, 15 ).c_str() ); mID = mThread; mRunning = true; } void Thread::ThreadEntry() { do { while ( not mRunning and not mStopped ) { mIsRunning = false; usleep( 1000 * 100 ); } if ( mRunning ) { mIsRunning = true; if ( mSetPriority != mPriority ) { mPriority = mSetPriority; int algorithm = mPriorityFifo ? SCHED_FIFO : SCHED_RR; struct sched_param sched; memset( &sched, 0, sizeof(sched) ); if ( mPriority > sched_get_priority_max( algorithm ) ) { sched.sched_priority = sched_get_priority_max( algorithm ); } else { sched.sched_priority = mPriority; } sched_setscheduler( 0, algorithm, &sched ); } if ( mSetAffinity >= 0 and mSetAffinity != mAffinity and mSetAffinity < sysconf(_SC_NPROCESSORS_ONLN) ) { gDebug() << "Setting affinity to " << mSetAffinity << " for thread " << mName; mAffinity = mSetAffinity; cpu_set_t cpuset; CPU_ZERO( &cpuset ); CPU_SET( mAffinity, &cpuset ); sched_setaffinity( 0, sizeof(cpu_set_t), &cpuset ); } } if ( mFrequency > 0 ) { uint32_t div = 1000000L / mFrequency; int64_t drift = mFrequency >= 1000 ? -50 : -250; mFrequencyTick = Board::WaitTick( div, mFrequencyTick, drift ); } } while ( not mStopped and run() ); mIsRunning = false; mFinished = true; mSpawned = false; pthread_exit( nullptr ); } void Thread::msleep( uint32_t ms ) { ::usleep( ms * 1000 ); } void Thread::usleep( uint32_t us ) { ::usleep( us ); }
3,871
C++
.cpp
140
25.064286
108
0.672511
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,775
startup.cpp
dridri_bcflight/flight/boards/rpi/startup.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 <Main.h> int main( int ac, char** av ) { Debug::setDebugLevel( Debug::Verbose ); int ret = Main::flight_entry( ac, av ); if ( ret == 0 ) { while ( 1 ) { usleep( 1000 * 1000 * 100 ); } } return 0; }
938
C++
.cpp
29
30.137931
72
0.713496
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,776
Serial.cpp
dridri_bcflight/flight/boards/rpi/Serial.cpp
#include "Serial.h" #include <stdio.h> #include <unistd.h> #include <sys/fcntl.h> // #include <sys/ioctl.h> // #include <termios.h> #include <asm/termios.h> #include <map> #include "Debug.h" #include <poll.h> extern "C" int ioctl (int __fd, unsigned long int __request, ...) __THROW; static map< int, int > sSpeeds = { { 0, B0 }, { 50, B50 }, { 75, B75 }, { 110, B110 }, { 134, B134 }, { 150, B150 }, { 200, B200 }, { 300, B300 }, { 600, B600 }, { 1200, B1200 }, { 1800, B1800 }, { 2400, B2400 }, { 4800, B4800 }, { 9600, B9600 }, { 19200, B19200 }, { 38400, B38400 }, { 57600, B57600 }, { 115200, B115200 }, { 230400, B230400 }, { 460800, B460800 }, { 500000, B500000 }, { 576000, B576000 }, { 921600, B921600 }, { 1000000, B1000000 }, { 1152000, B1152000 }, { 1500000, B1500000 }, { 2000000, B2000000 }, { 2500000, B2500000 }, { 3000000, B3000000 }, { 3500000, B3500000 }, { 4000000, B4000000 } }; Serial::Serial( const string& device, int speed, int read_timeout ) : Bus() , mFD( -1 ) , mOptions( nullptr ) , mDevice( device ) , mSpeed( speed ) , mReadTimeout( read_timeout ) { } Serial::~Serial() { delete mOptions; } int Serial::Connect() { mFD = open( mDevice.c_str(), O_RDWR | O_NOCTTY ); if ( mFD < 0 ) { gError() << "Err0 : " << strerror(errno); return -1; } mOptions = new struct termios2; ioctl( mFD, TCGETS2, mOptions ); // Set stop bits to 1 mOptions->c_cflag &= ~CSTOPB; // Set parity options mOptions->c_cflag &= ~PARENB; // Disable parity mOptions->c_cflag &= ~PARODD; // Even parity mOptions->c_cflag |= CRTSCTS; // Set data bits mOptions->c_cflag &= ~CSIZE; mOptions->c_cflag |= CS8; // 8 data bits // Enable binary mode mOptions->c_iflag = 0; mOptions->c_oflag &= ~OPOST; mOptions->c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); mOptions->c_cc[VMIN] = 6; mOptions->c_cc[VTIME] = 0; mOptions->c_cflag &= ~CBAUD; mOptions->c_cflag |= BOTHER; mOptions->c_ispeed = mSpeed; mOptions->c_ospeed = mSpeed; int ret = ioctl( mFD, TCSETS2, mOptions ); if ( ret < 0 ) { gError() << "Err1 : " << errno << ", " << strerror(errno); return -1; } return 0; } std::string Serial::toString() { return mDevice; } void Serial::setStopBits( uint8_t count ) { if ( not mOptions ) { return; } ioctl( mFD, TCGETS2, mOptions ); if ( count == 2 ) { mOptions->c_cflag |= CSTOPB; } else if ( count == 1 ) { mOptions->c_cflag &= ~CSTOPB; } else { gWarning() << "Unhandled stop bits count (" << count << ")"; } int ret = ioctl( mFD, TCSETS2, mOptions ); if ( ret < 0 ) { gError() << "Err1 : " << errno << ", " << strerror(errno); } } int Serial::Read( uint8_t reg, void* buf, uint32_t len ) { return 0; } int Serial::Read( void* buf, uint32_t len ) { if ( mReadTimeout > 0 ) { struct pollfd pfd[1]; pfd[0].fd = mFD; pfd[0].events = POLLIN; int ret = poll( pfd, 1, mReadTimeout ); if ( ret <= 0 ) { return ret; } } int ret = read( mFD, buf, len ); if ( ret < 0 && errno != EAGAIN ) { gDebug() << errno << ", " << strerror(errno); } return ret; } int Serial::Write( const void* buf, uint32_t len ) { int ret = write( mFD, buf, len ); if ( ret < 0 ) { gDebug() << errno << ", " << strerror(errno); } return ret; } int Serial::Write( uint8_t reg, const void* buf, uint32_t len ) { return 0; }
3,338
C++
.cpp
147
20.591837
74
0.615921
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,777
GLContext.cpp
dridri_bcflight/flight/boards/rpi/GLContext.cpp
#include <iostream> #include <algorithm> #include "Debug.h" #include "GLContext.h" // #include <vc_dispmanx_types.h> #include <bcm_host.h> #include <fcntl.h> #include "Board.h" #define OPTIMUM_WIDTH 840 #define OPTIMUM_HEIGHT 480 GLContext* GLContext::sInstance = nullptr; GLContext* GLContext::instance() { if ( !sInstance ) { sInstance = new GLContext(); } return sInstance; } GLContext::GLContext() : Thread( "OpenGL" ) , mReady( false ) , mWidth( 0 ) , mHeight( 0 ) , mPreviousBo( nullptr ) , mSyncLastTick( 0 ) { Start(); } GLContext::~GLContext() { } const EGLDisplay GLContext::eglDisplay() const { return mEGLDisplay; } const EGLContext GLContext::eglContext() const { return mEGLContext; } bool GLContext::run() { if ( !mReady ) { mReady = true; Initialize( 1280, 720 ); } mContextQueueMutex.lock(); while ( mContextQueue.size() > 0 ) { std::function<void()> f = mContextQueue.front(); mContextQueue.pop_front(); mContextQueueMutex.unlock(); f(); mContextQueueMutex.lock(); } mContextQueueMutex.unlock(); glClear( GL_COLOR_BUFFER_BIT ); mLayersMutex.lock(); for ( const Layer& layer : mLayers ) { if ( layer.fct ) { layer.fct(); } else if ( layer.glId >= 0 ) { // TODO } } mLayersMutex.unlock(); SwapBuffers(); return true; } void GLContext::runOnGLThread( const std::function<void()>& f, bool wait ) { if ( wait ) { bool finished = false; mContextQueueMutex.lock(); mContextQueue.emplace_back([&finished, f]() { f(); finished = true; }); mContextQueueMutex.unlock(); while ( not finished ) { usleep( 10 * 1000 ); } } else { mContextQueueMutex.lock(); mContextQueue.emplace_back( f ); mContextQueueMutex.unlock(); } } uint32_t GLContext::addLayer( int32_t x, int32_t y, int32_t width, int32_t height, GLenum format, int32_t layerIndex ) { uint32_t tex = -1; runOnGLThread([&tex,format,width,height]() { printf("A\n"); glGenTextures( 1, &tex ); printf("B, %d\n", tex); glBindTexture( GL_TEXTURE_2D, tex ); glTexImage2D( GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, nullptr ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); // glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); // glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); }, true); Layer layer = { .index = layerIndex, .x = x, .y = y, .width = (uint32_t)width, .height = (uint32_t)height, .glId = tex }; mLayersMutex.lock(); mLayers.emplace_back( layer ); std::sort( mLayers.begin(), mLayers.end(), [](Layer& a, Layer& b) { return a.index < b.index; }); mLayersMutex.unlock(); return tex; } uint32_t GLContext::addLayer( const std::function<void ()>& f, int32_t layerIndex ) { Layer layer = { .index = layerIndex, .fct = f }; mLayersMutex.lock(); mLayers.emplace_back( layer ); std::sort( mLayers.begin(), mLayers.end(), [](Layer& a, Layer& b) { return a.index < b.index; }); mLayersMutex.unlock(); return 0; } EGLImageKHR GLContext::eglImage( uint32_t glImage ) { EGLImageKHR eglVideoImage = 0; runOnGLThread([&eglVideoImage,glImage]() { PFNEGLCREATEIMAGEKHRPROC eglCreateImage = (PFNEGLCREATEIMAGEKHRPROC)eglGetProcAddress("eglCreateImageKHR"); gDebug() << "eglCreateImage (" << glImage << ") : " << (uintptr_t)eglCreateImage; gDebug() << "eglGetCurrentDisplay : " << eglGetCurrentDisplay(); gDebug() << "eglGetCurrentContext : " << eglGetCurrentContext(); eglVideoImage = eglCreateImage( eglGetCurrentDisplay(), eglGetCurrentContext(), EGL_GL_TEXTURE_2D_KHR, reinterpret_cast<EGLClientBuffer>(glImage), nullptr ); gDebug() << "EGL error : " << eglGetError(); }, true); return eglVideoImage; } EGLConfig GLContext::getDisplay() { mRenderSurface = new DRMSurface( 100 ); mGbmDevice = gbm_create_device( DRM::drmFd() ); mGbmSurface = gbm_surface_create( mGbmDevice, mRenderSurface->mode()->hdisplay, mRenderSurface->mode()->vdisplay, GBM_FORMAT_ARGB8888, GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING ); return eglGetDisplay( reinterpret_cast<EGLNativeDisplayType>(mGbmDevice) ); } int32_t GLContext::Initialize( uint32_t width, uint32_t height ) { EGLint attribList[] = { // EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_COLOR_BUFFER_TYPE, EGL_RGB_BUFFER, // EGL_TRANSPARENT_TYPE, EGL_TRANSPARENT_RGB, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 16, EGL_STENCIL_SIZE, 0, // EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_NONE }; EGLint count; EGLint numConfigs; EGLint majorVersion; EGLint minorVersion; EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; mEGLDisplay = getDisplay(); eglInitialize( mEGLDisplay, &majorVersion, &minorVersion ); eglBindAPI( EGL_OPENGL_API ); /* eglGetConfigs( mEGLDisplay, nullptr, 0, &count ); EGLConfig* configs = (EGLConfig*)malloc( count * sizeof(count) ); eglChooseConfig( mEGLDisplay, attribList, configs, count, &numConfigs ); printf( "COUNT : %d\n", count ); for ( int i = 0; i < count; i++ ) { EGLint id; eglGetConfigAttrib( mEGLDisplay, configs[i], EGL_NATIVE_VISUAL_ID, &id ); printf( "CONFIG %d, %d\n", i, id ); } for ( int i = 0; i < count; i++ ) { EGLint id; if ( !eglGetConfigAttrib( mEGLDisplay, configs[i], EGL_NATIVE_VISUAL_ID, &id ) ) { continue; } if ( id == GBM_FORMAT_ARGB8888 ) { mEGLConfig = configs[i]; break; } } printf( "mEGLConfig : %p\n", mEGLConfig ); */ eglChooseConfig( mEGLDisplay, attribList, &mEGLConfig, 1, &numConfigs ); mEGLContext = eglCreateContext( mEGLDisplay, mEGLConfig, EGL_NO_CONTEXT, contextAttribs ); const EGLint egl_surface_attribs[] = { EGL_RENDER_BUFFER, EGL_BACK_BUFFER/* + 1 => disable double-buffer*/, EGL_NONE, }; mEGLSurface = eglCreateWindowSurface( mEGLDisplay, mEGLConfig, reinterpret_cast<EGLNativeWindowType>(mGbmSurface), egl_surface_attribs ); eglQuerySurface( mEGLDisplay, mEGLSurface, EGL_WIDTH, (EGLint*)&mWidth ); eglQuerySurface( mEGLDisplay, mEGLSurface, EGL_HEIGHT, (EGLint*)&mHeight ); eglMakeCurrent( mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext ); eglSwapInterval( mEGLDisplay, 1 ); std::cout << "OpenGL version : " << glGetString( GL_VERSION ) << "\n"; std::cout << "Framebuffer resolution : " << mWidth << " x " << mHeight << "\n"; glViewport( 0, 0, mWidth, mHeight ); // glViewport( 0, 0, OPTIMUM_WIDTH, OPTIMUM_HEIGHT ); glEnable( GL_CULL_FACE ); glFrontFace( GL_CCW ); glCullFace( GL_BACK ); glEnable( GL_DEPTH_TEST ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); return 0; } // TODO / TBD : keep framebuffers generated by drmModeAddFB2() to prevent constant re-creation void GLContext::SwapBuffers() { glFinish(); eglSwapBuffers( mEGLDisplay, mEGLSurface ); struct gbm_bo* bo = gbm_surface_lock_front_buffer( mGbmSurface ); DRMFrameBuffer* fb = nullptr; auto iter = mFrameBuffers.find( bo ); if ( iter == mFrameBuffers.end() ) { uint32_t handle = gbm_bo_get_handle(bo).u32; uint32_t width = gbm_bo_get_width(bo); uint32_t height = gbm_bo_get_height(bo); uint32_t stride = gbm_bo_get_stride(bo); fb = new DRMFrameBuffer( width, height, stride, GBM_FORMAT_ARGB8888, handle ); mFrameBuffers.emplace( std::make_pair( bo, fb ) ); } else { fb = (*iter).second; } mRenderSurface->Show( fb ); if ( mPreviousBo ) { gbm_surface_release_buffer( mGbmSurface, mPreviousBo ); } mPreviousBo = bo; mSyncLastTick = Board::WaitTick( 1000000L / 30, mSyncLastTick ); } uint32_t GLContext::glWidth() { return mWidth; } uint32_t GLContext::glHeight() { return mHeight; } uint32_t GLContext::displayWidth() { return 0; } uint32_t GLContext::displayHeight() { return 0; } uint32_t GLContext::displayFrameRate() { return 0; }
8,110
C++
.cpp
267
28.059925
180
0.704309
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,778
PWM.cpp
dridri_bcflight/flight/boards/rpi/PWM.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/>. **/ #define _POSIX_C_SOURCE 200809L #define _XOPEN_SOURCE 700 #include <execinfo.h> #include <signal.h> #include <sys/sysmacros.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <getopt.h> #include <errno.h> #include <stdarg.h> #include <stdint.h> #include <signal.h> #include <time.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include "mailbox.h" #include <Debug.h> #include <Config.h> #include "PWM.h" #include "GPIO.h" // pin2gpio array is not setup as empty to avoid locking all GPIO // inputs as PWM, they are set on the fly by the pin param passed. // static uint8_t pin2gpio[8]; #define DEVFILE "/dev/pi-blaster" #define DEVFILE_MBOX "/dev/pi-blaster-mbox" #define DEVFILE_VCIO "/dev/vcio" #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) #define DEBUG 1 #ifdef DEBUG #define dprintf(...) printf(__VA_ARGS__) #else #define dprintf(...) #endif #define MAX_MULTIPLEX_CHANNELS 4 vector< PWM::Channel* > PWM::mChannels = vector< PWM::Channel* >(); bool PWM::mSigHandlerOk = false; bool PWM::sTruePWM = false; static void fatal( const char *fmt, ... ) { va_list ap; va_start(ap, fmt); vfprintf(stdout, fmt, ap); va_end(ap); exit(0); } void PWM::EnableTruePWM() { int handle = open( DEVFILE_VCIO, 0 ); if ( handle < 0 ) { printf("Failed to open mailbox\n"); return; } uint32_t mbox_board_rev = get_board_revision( handle ); close( handle ); const uint32_t type = ( mbox_board_rev & BOARD_REVISION_TYPE_MASK ); if ( type != BOARD_REVISION_TYPE_PI4_B and type != BOARD_REVISION_TYPE_CM4 ) { gDebug() << "WARNING : TruePWM can only be enabled on Raspberry Pi >=4 models (older models only has 2 PWM channels)"; gDebug() << "Detected board revision : " << type; return; } sTruePWM = true; } bool PWM::HasTruePWM() { return sTruePWM; } PWM::PWM( uint32_t pin, uint32_t time_base, uint32_t period_time, uint32_t sample_time, PWMMode mode, bool loop ) : mChannel( nullptr ) , mPin( pin ) { fDebug( pin, time_base, period_time, sample_time, mode, loop ); if ( not mSigHandlerOk ) { mSigHandlerOk = true; // static int sig_list[] = { 2, 3, 4, 5, 6, 7, 8, 9, 11, 15, 16, 19, 20 }; /* static int sig_list[] = { 2 }; uint32_t i; for ( i = 0; i < sizeof(sig_list)/sizeof(int); i++ ) { struct sigaction sa; memset( &sa, 0, sizeof(sa) ); sa.sa_handler = &PWM::terminate; sigaction( sig_list[i], &sa, NULL ); } */ } if ( sTruePWM ) { int8_t engine = -1; if ( mPin == 12 or mPin == 13 or mPin == 18 or mPin == 19 or mPin == 45 ) { engine = 0; } else if ( mPin == 40 or mPin == 41 ) { engine = 1; } else { return; } for ( Channel* chan_ : mChannels ) { PWMChannel* chan = dynamic_cast< PWMChannel* >( chan_ ); if ( chan->mEngine == engine ) { mChannel = chan; } } if ( not mChannel ) { mChannel = new PWMChannel( engine, time_base, period_time, mode, loop ); mChannels.emplace_back( mChannel ); } } else { // uint8_t channel = 13; int8_t channel = 6; // DMA channels 7+ use LITE DMA engine, so we should use lowest channels for ( Channel* chan_ : mChannels ) { DMAChannel* chan = dynamic_cast< DMAChannel* >( chan_ ); if ( chan->mTimeBase == time_base and chan->mCycleTime == period_time and chan->mSampleTime == sample_time and chan->mLoop == loop ) { mChannel = chan; break; } channel = chan->mChannel - 1; if ( channel < 0 ) { break; } } if ( not mChannel and channel >= 0 ) { mChannel = new DMAChannel( channel, time_base, period_time, sample_time, mode, loop ); mChannels.emplace_back( mChannel ); } } mChannel->SetPWMValue( mPin, 0 ); } PWM::PWM( uint32_t pin, uint32_t time_base, uint32_t period_time, PWM::PWMMode mode, int32_t enablePin ) : mChannel( nullptr ) , mPin( pin ) { if ( !sTruePWM ) { gDebug() << "ERROR : TruePWM is not available !"; } int8_t engine = -1; if ( mPin == 12 or mPin == 13 or mPin == 18 or mPin == 19 or mPin == 45 ) { engine = 0; // } else if ( mPin == 40 or mPin == 41 ) { // engine = 1; } else { return; } for ( Channel* chan_ : mChannels ) { MultiplexPWMChannel* chan = dynamic_cast< MultiplexPWMChannel* >( chan_ ); if ( chan->mEngine ) { mChannel = chan; break; } } if ( !mChannel ) { mChannel = new MultiplexPWMChannel( time_base, period_time, mode ); mChannels.emplace_back( mChannel ); } const uint32_t alt = ( ( pin == 18 or pin == 19 ) ? GPIO_MODE_ALT5 : GPIO_MODE_ALT0 ); dynamic_cast<MultiplexPWMChannel*>(mChannel)->gpio_reg[GPIO_FSEL0 + pin/10] &= ~(7 << ((pin % 10) * 3)); dynamic_cast<MultiplexPWMChannel*>(mChannel)->gpio_reg[GPIO_FSEL0 + pin/10] |= alt << ((pin % 10) * 3); dynamic_cast<MultiplexPWMChannel*>(mChannel)->gpio_reg[GPIO_CLR0] = 1 << pin; const int32_t idx = dynamic_cast<MultiplexPWMChannel*>(mChannel)->mVirtualPins.size(); if ( enablePin >= 0 ) { dynamic_cast<MultiplexPWMChannel*>(mChannel)->gpio_reg[GPIO_CLR0] = (1 << enablePin); uint32_t fsel = dynamic_cast<MultiplexPWMChannel*>(mChannel)->gpio_reg[GPIO_FSEL0 + enablePin/10]; fsel &= ~(7 << ((enablePin % 10) * 3)); fsel |= GPIO_MODE_OUT << ((enablePin % 10) * 3); dynamic_cast<MultiplexPWMChannel*>(mChannel)->gpio_reg[GPIO_FSEL0 + enablePin/10] = fsel; dynamic_cast<MultiplexPWMChannel*>(mChannel)->mVirtualPins.emplace( std::make_pair(enablePin, MultiplexPWMChannel::VirtualPin(pin, enablePin, idx)) ); dynamic_cast<MultiplexPWMChannel*>(mChannel)->mSelectPinMasks[idx] = ( 1 << enablePin ); *dynamic_cast<MultiplexPWMChannel*>(mChannel)->mSelectPinResetMask |= ( 1 << enablePin ); } else { dynamic_cast<MultiplexPWMChannel*>(mChannel)->mVirtualPins.emplace( std::make_pair(pin, MultiplexPWMChannel::VirtualPin(pin, enablePin, idx)) ); } } PWM::~PWM() { } void PWM::SetPWMus( uint32_t width ) { fDebug( width ); if ( not mChannel ) { return; } mChannel->SetPWMValue( mPin, width ); } void PWM::SetPWMBuffer( uint8_t* buffer, uint32_t len ) { if ( not mChannel ) { return; } mChannel->SetPWMBuffer( mPin, buffer, len ); } void PWM::Update() { if ( not mChannel ) { return; } mChannel->Update(); } static inline uint32_t hzToDivider( uint64_t plldfreq_mhz, uint64_t hz ) { fDebug( plldfreq_mhz, hz ); const uint64_t pll = plldfreq_mhz * 1000000; const uint64_t ipart = pll / hz; const uint64_t fpart = ( pll * 2048 / hz ) - ipart * 2048; gDebug() << " → " << ipart << ", " << fpart; return ( ipart << 12 ) | fpart; } PWM::MultiplexPWMChannel::MultiplexPWMChannel( uint32_t time_base, uint32_t period, PWM::PWMMode mode ) : mMode( mode ) , mLoop( false ) { fDebug( time_base, period, mode ); int8_t dmaChannel = 5; // DMA channels 7+ use LITE DMA engine, so we should use lowest channels for ( Channel* chan_ : mChannels ) { DMAChannel* chan = dynamic_cast< DMAChannel* >( chan_ ); dmaChannel = chan->mChannel - 1; if ( dmaChannel < 0 ) { break; } } if ( dmaChannel < 0 ) { return; } mDMAChannel = dmaChannel; mNumOutputs = MAX_MULTIPLEX_CHANNELS; mNumCBs = mNumOutputs * 3; mNumPages = ( mNumCBs * sizeof(dma_cb_t) + ( mNumOutputs * 1 * sizeof(uint32_t) ) + PAGE_SIZE - 1 ) >> PAGE_SHIFT; mMbox.handle = mbox_open(); if ( mMbox.handle < 0 ) { fatal("Failed to open mailbox\n"); } 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 DMA Channel: " << (int)mDMAChannel; dma_virt_base = (uint32_t*)map_peripheral( DMA_BASE, ( DMA_CHAN_SIZE * ( DMA_CHAN_MAX + 1 ) ) ); dma_reg = dma_virt_base + mDMAChannel * ( DMA_CHAN_SIZE / sizeof(dma_reg) ); pwm_reg = (uint32_t*)map_peripheral( PWM0_BASE, PWM0_LEN ); pwm1_reg = (uint32_t*)map_peripheral( PWM1_BASE, PWM1_LEN ); clk_reg = (uint32_t*)map_peripheral( CLK_BASE, CLK_LEN ); gpio_reg = (uint32_t*)map_peripheral( GPIO_BASE, GPIO_LEN ); uint32_t cmd_count = 32; uint32_t sz = mNumPages * PAGE_SIZE * cmd_count; mMbox.mem_ref = mem_alloc( mMbox.handle, sz, 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 (sz = %d)\n", mMbox.bus_addr, sz ); mMbox.virt_addr = (uint8_t*)mapmem( BUS_TO_PHYS(mMbox.bus_addr), sz ); dprintf( "virt_addr %p\n", mMbox.virt_addr ); mCtls[0].sample = (uint32_t*)( mMbox.virt_addr ); mCtls[0].cb = (dma_cb_t*)( mMbox.virt_addr + sizeof(uint32_t)*16 ); /* mSelectPinResetMask = &mCtls[0].sample[0]; mSelectPinMasks = &mCtls[0].sample[1]; mPWMSamples = &mCtls[0].sample[1 + mNumOutputs]; memset( mPinsSamples, 0, sizeof(mPinsSamples) ); */ // Reset(); if ( (unsigned long)mMbox.virt_addr & ( PAGE_SIZE - 1 ) ) { fatal("pi-blaster: Virtual address is not page aligned\n"); } /* we are done with the mbox */ close( mMbox.handle ); mMbox.handle = -1; dma_ctl_t* ctl = &mCtls[0]; dma_cb_t* cbp = ctl->cb; uint32_t phys_fifo_addr; uint32_t phys_gpclr0 = GPIO_PHYS_BASE + 0x28; uint32_t phys_gpset0 = GPIO_PHYS_BASE + 0x1c; uint32_t i; phys_fifo_addr = PWM0_PHYS_BASE + 0x18; uint32_t phys_dat1_addr = PWM0_PHYS_BASE + 0x14; uint32_t phys_dat2_addr = PWM0_PHYS_BASE + 0x24; uint32_t pwm1_phys_fifo_addr = PWM1_PHYS_BASE + 0x18; uint32_t pwm1_phys_dat1_addr = PWM1_PHYS_BASE + 0x14; uint32_t pwm1_phys_dat2_addr = PWM1_PHYS_BASE + 0x24; /* TODO : Multiplexer PWM output : PWM0_0 as output : PWM1_0 as DMA timer ? : pins A, B, C, D to control external multiplexer DMA commands buffer: → reset switch pins (phys_gpclr0) → loop over all channels → set switch pins to pin X high (phys_gpset0) → TBD : wait for switch to physically rise ? (GPIO rise time + external multiplexer IC rise time) (Use builtin DMA_WAIT_RESP, and just run same command 2~3× to wait IC ?) → write to PWM0_0 FIFO channel X value (TBD) \ → use PWM1_0 to wait for PWM0_0 to output ? TBD : just wait for FIFO end trigger ? | → Reuse "// Timer trigger command" for both in one DMA command block (no need for PWM1_0) → reset switch pins (phys_gpclr0) → TBD : wait for switch to physically fall ? (GPIO fall time + external multiplexer IC fall time) (same as above) */ gpio_reg[GPIO_CLR0] = 1 << 6; uint32_t fsel = gpio_reg[GPIO_FSEL0 + 6/10]; fsel &= ~(7 << ((6 % 10) * 3)); fsel |= GPIO_MODE_OUT << ((6 % 10) * 3); gpio_reg[GPIO_FSEL0 + 6/10] = fsel; gpio_reg[GPIO_SET0] = 1 << 6; ctl->sample[0] = (1 << 6); ctl->sample[1] = 0; // 3 ctl->sample[2] = (1 << 6); // 0 ctl->sample[3] = 0; // 1 ctl->sample[4] = 0; // 2 ctl->sample[5] = 100; ctl->sample[6] = 500; ctl->sample[7] = 1000; ctl->sample[8] = 1500; ctl->sample[16] = 1; printf( "%p, %p, %p, %p\n", ctl->sample, ctl->cb, cbp, mPWMSamples ); /* // GPIO-Clear All command cbp->info = DMA_NO_WIDE_BURSTS; cbp->src = mem_virt_to_phys(&ctl->sample[0]); cbp->dst = phys_gpclr0; cbp->length = 4; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; */ for (i = 0; i < mNumOutputs; i++) { // GPIO-Set command cbp->info = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP | DMA_D_DREQ; cbp->src = mem_virt_to_phys(&ctl->sample[1 + i]); cbp->dst = phys_gpset0; cbp->length = 4; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; // Timer wait command cbp->info = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP | DMA_D_DREQ | DMA_PER_MAP(5) | DMA_TDMODE; cbp->src = mem_virt_to_phys(&ctl->sample[16]); cbp->dst = pwm1_phys_dat1_addr; cbp->length = 4; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; // Timer trigger command cbp->info = DMA_NO_WIDE_BURSTS | DMA_D_DREQ | DMA_PER_MAP(5); // cbp->info = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP | DMA_D_DREQ | DMA_PER_MAP(5) | DMA_TDMODE; cbp->src = mem_virt_to_phys(&ctl->sample[5 + i]); cbp->dst = phys_dat1_addr; cbp->length = 4; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; // Timer wait command cbp->info = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP | DMA_D_DREQ | DMA_PER_MAP(5) | DMA_TDMODE; cbp->src = mem_virt_to_phys(&ctl->sample[16]); cbp->dst = pwm1_phys_fifo_addr; cbp->length = 4; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; // GPIO-Clear All command cbp->info = DMA_NO_WIDE_BURSTS; cbp->src = mem_virt_to_phys(&ctl->sample[0]); cbp->dst = phys_gpclr0; cbp->length = 4; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; } cbp--; cbp->next = mem_virt_to_phys(ctl->cb); dprintf( "Ok\n" ); { pwm_reg[PWM_CTL] = 0; usleep(10); clk_reg[PWMCLK_CNTL] = 0x5A000006; // Source=PLLD (plldfreq_mhz MHz) usleep(100); clk_reg[PWMCLK_DIV] = 0x5A000000 | hzToDivider( plldfreq_mhz, time_base ); usleep(100); clk_reg[PWMCLK_CNTL] = 0x5A000016; // Source=PLLD (plldfreq_mhz MHz) and enable usleep(100); pwm_reg[PWM_RNG1] = period; usleep(10); pwm_reg[PWM_RNG2] = period; usleep(10); pwm_reg[PWM_DAT1] = 0; usleep(10); pwm_reg[PWM_DAT2] = 0; usleep(10); pwm_reg[PWM_PWMC] = 0; // pwm_reg[PWM_PWMC] = PWMPWMC_ENAB | PWMPWMC_THRSHLD; usleep(10); pwm_reg[PWM_CTL] = PWMCTL_CLRF; usleep(10); pwm_reg[PWM_CTL] = mPwmCtl = PWMCTL_MSEN1 | PWMCTL_MSEN2 | PWMCTL_PWEN1 | PWMCTL_PWEN2;// | PWMCTL_USEF1; usleep(10); } { pwm1_reg[PWM_CTL] = 0; usleep(10); clk_reg[PWMCLK_CNTL] = 0x5A000006; // Source=PLLD (plldfreq_mhz MHz) usleep(100); clk_reg[PWMCLK_DIV] = 0x5A000000 | hzToDivider( plldfreq_mhz, time_base ); usleep(100); clk_reg[PWMCLK_CNTL] = 0x5A000016; // Source=PLLD (plldfreq_mhz MHz) and enable usleep(100); pwm1_reg[PWM_RNG1] = period * 0.001; usleep(10); pwm1_reg[PWM_RNG2] = period; usleep(10); pwm1_reg[PWM_DAT1] = 0; usleep(10); pwm1_reg[PWM_DAT2] = 0; usleep(10); // pwm1_reg[PWM_PWMC] = 0; usleep(10); pwm1_reg[PWM_PWMC] = PWMPWMC_ENAB | PWMPWMC_THRSHLD; usleep(10); pwm1_reg[PWM_CTL] = PWMCTL_CLRF; usleep(10); pwm1_reg[PWM_CTL] = mPwmCtl = PWMCTL_MSEN1 | PWMCTL_MSEN2 | PWMCTL_PWEN1 | PWMCTL_PWEN2 | PWMCTL_USEF2; usleep(10); } // Initialise the DMA dma_reg[DMA_CS] = DMA_RESET; usleep(10); dma_reg[DMA_CS] = DMA_INT | DMA_END; dma_reg[DMA_CONBLK_AD] = mem_virt_to_phys(ctl->cb); dma_reg[DMA_DEBUG] = 7; // clear debug error flags // dma_reg[DMA_CS] = 0x10770001; // go, high priority, wait for outstanding writes dma_reg[DMA_CS] = 0x30770001; // go, high priority, disable debug stop, wait for outstanding writes } PWM::MultiplexPWMChannel::~MultiplexPWMChannel() noexcept { } void PWM::MultiplexPWMChannel::Reset() { /* *mSelectPinResetMask = 0; memset( mSelectPinMasks, 0, sizeof(uint32_t)*mNumOutputs ); memset( mPWMSamples, 0, sizeof(uint32_t)*mNumOutputs ); */ } void PWM::MultiplexPWMChannel::SetPWMBuffer( uint32_t pin, uint8_t* buffer, uint32_t len ) { (void)pin; (void)buffer; (void)len; // TODO } void PWM::MultiplexPWMChannel::SetPWMValue( uint32_t pin, uint32_t width ) { /* fDebug( pin, width ); VirtualPin* vpin = &mVirtualPins.at(pin); fDebug( vpin->pwmPin, vpin->enablePin, vpin->pwmIndex ); mPWMSamples[vpin->pwmIndex] = width; */ /* if ( pin == vpin->pwmPin ) { } else if ( pin == vpin->enablePin ) { } uint32_t* ptr = mPinsSamples[pin]; if ( ptr == nullptr ) { std::map< uint32_t*, bool > used; for ( uint32_t* ptr : mPinsSamples ) { if ( ptr ) { used.insert( std::make_pair( ptr, true ) ); } } for ( uint32_t i = 0; i < mNumOutputs; i++ ) { if ( used.find( &mPWMSamples[i] ) == used.end() ) { mPinsSamples[pin] = ptr = &mPWMSamples[i]; mSelectPinMasks[i] = (1 << pin); break; } } if ( ptr == nullptr ) { // No slot available ? ptr = (uint32_t*)0xDEADBEEF; } else { } } if ( ptr != (uint32_t*)0xDEADBEEF ) { *ptr = width; } */ } void PWM::MultiplexPWMChannel::Update() { } PWM::PWMChannel::PWMChannel( uint8_t engine, uint32_t time_base, uint32_t period, PWM::PWMMode mode, bool loop ) : mMode( mode ) , mLoop( loop ) { fDebug( (int)engine, time_base, period, mode, loop ); mMbox.handle = mbox_open(); if ( mMbox.handle < 0 ) { fatal("Failed to open mailbox\n"); } uint32_t mbox_board_rev = get_board_revision( mMbox.handle ); gDebug() << "MBox Board Revision: " << mbox_board_rev; get_model(mbox_board_rev); clk_reg = (uint32_t*)map_peripheral( CLK_BASE, CLK_LEN ); gpio_reg = (uint32_t*)map_peripheral( GPIO_BASE, GPIO_LEN ); if ( engine == 0 ) { pwm_reg = (uint32_t*)map_peripheral( PWM0_BASE, PWM0_LEN ); } else if ( engine == 1 ) { pwm_reg = (uint32_t*)map_peripheral( PWM0_BASE, 0x1000 ) + ( PWM1_BASE - PWM0_BASE ); } else { return; } pwm_reg[PWM_CTL] = 0; usleep(10); clk_reg[PWMCLK_CNTL] = 0x5A000006; // Source=PLLD (plldfreq_mhz MHz) usleep(100); clk_reg[PWMCLK_DIV] = 0x5A000000 | hzToDivider( plldfreq_mhz, time_base ); usleep(100); clk_reg[PWMCLK_CNTL] = 0x5A000016; // Source=PLLD (plldfreq_mhz MHz) and enable usleep(100); pwm_reg[PWM_RNG1] = period; usleep(10); pwm_reg[PWM_RNG2] = period; usleep(10); pwm_reg[PWM_DAT1] = 0; usleep(10); pwm_reg[PWM_DAT2] = 0; usleep(10); pwm_reg[PWM_PWMC] = 0; usleep(10); pwm_reg[PWM_CTL] = PWMCTL_CLRF; usleep(10); pwm_reg[PWM_CTL] = mPwmCtl = PWMCTL_MSEN1 | PWMCTL_MSEN2 | ( (mode == MODE_BUFFER) ? (PWMCTL_USEF1 | PWMCTL_USEF2) : 0 ); usleep(10); } PWM::PWMChannel::~PWMChannel() { } void PWM::PWMChannel::SetPWMValue( uint32_t pin, uint32_t width ) { fDebug( pin, width ); uint8_t chan = 0; if ( pin == 13 or pin == 19 or pin == 41 or pin == 45 ) { chan = 1; } else if ( pin != 12 and pin != 18 and pin != 40 ) { return; } if ( chan == 0 ) { if ( !( mPwmCtl & PWMCTL_PWEN1 ) ) { const uint32_t alt = ( ( pin == 18 or pin == 19 ) ? GPIO_MODE_ALT5 : GPIO_MODE_ALT0 ); gpio_reg[GPIO_FSEL0 + pin/10] &= ~(7 << ((pin % 10) * 3)); gpio_reg[GPIO_FSEL0 + pin/10] |= alt << ((pin % 10) * 3); gpio_reg[GPIO_CLR0] = 1 << pin; pwm_reg[PWM_CTL] = mPwmCtl |= PWMCTL_PWEN1; usleep(10); } pwm_reg[PWM_DAT1] = width; } else { if ( !( mPwmCtl & PWMCTL_PWEN2 ) ) { pwm_reg[PWM_CTL] = mPwmCtl |= PWMCTL_PWEN2; usleep(10); } pwm_reg[PWM_DAT2] = width; } } void PWM::PWMChannel::SetPWMBuffer( uint32_t pin, uint8_t* buffer, uint32_t len ) { // TODO (used by DSHOT) } void PWM::PWMChannel::Update() { // Nothing to do } void PWM::PWMChannel::Reset() { pwm_reg[PWM_CTL] &= ~( PWMCTL_PWEN1 | PWMCTL_PWEN2 ); pwm_reg[PWM_DAT1] = 0; pwm_reg[PWM_DAT2] = 0; } PWM::DMAChannel::DMAChannel( uint8_t channel, uint32_t time_base, uint32_t period_time, uint32_t sample_time, PWMMode mode, bool loop ) : mChannel( channel ) , mMode( mode ) , mLoop( loop ) , mPinsCount( 0 ) , mPinsMask( 0 ) , mTimeBase( time_base ) , mCycleTime( period_time ) , mSampleTime( sample_time ) , mNumSamples( mCycleTime / mSampleTime ) , mNumCBs( mNumSamples * ( 2 + ( mMode == MODE_BUFFER ) ) ) , mNumPages( ( mNumCBs * sizeof(dma_cb_t) + ( mNumSamples * 1 + ( mMode == MODE_BUFFER ) ) * sizeof(uint32_t) + PAGE_SIZE - 1 ) >> PAGE_SHIFT ) , mCurrentCtl( 0 ) { memset( mPins, 0xFF, sizeof(mPins) ); memset( mPinsPWMf, 0, sizeof(mPinsPWMf) ); memset( mPinsPWM, 0, sizeof(mPinsPWM) ); memset( mPinsBuffer, 0, sizeof(mPinsBuffer) ); memset( mPinsBufferLength, 0, sizeof(mPinsBufferLength) ); mMbox.handle = mbox_open(); if ( mMbox.handle < 0 ) { fatal("Failed to open mailbox\n"); } 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() << "Number of channels: " << (int)mPinsCount; gDebug() << "PWM frequency: " << time_base / mCycleTime; gDebug() << "PWM steps: " << mNumSamples; gDebug() << "PWM step : " << mSampleTime; gDebug() << "Maximum period (100 %%): " << mCycleTime; gDebug() << "Minimum period (" << 100.0 * mSampleTime / mCycleTime << "): " << mSampleTime; gDebug() << "DMA Base: " << DMA_BASE; // setup_sighandlers(); // map the registers for all PWM Channels dma_virt_base = (uint32_t*)map_peripheral( DMA_BASE, ( DMA_CHAN_SIZE * ( DMA_CHAN_MAX + 1 ) ) ); // set dma_reg to point to the PWM Channel we are using dma_reg = dma_virt_base + mChannel * ( DMA_CHAN_SIZE / sizeof(dma_reg) ); pwm_reg = (uint32_t*)map_peripheral( PWM_BASE, PWM_LEN ); pcm_reg = (uint32_t*)map_peripheral( PCM_BASE, PCM_LEN ); clk_reg = (uint32_t*)map_peripheral( CLK_BASE, CLK_LEN ); gpio_reg = (uint32_t*)map_peripheral( GPIO_BASE, GPIO_LEN ); /* Use the mailbox interface to the VC to ask for physical memory */ uint32_t cmd_count = 4 + ( mMode == MODE_BUFFER );// + ( mLoop == false ); mMbox.mem_ref = mem_alloc( mMbox.handle, mNumPages * PAGE_SIZE * cmd_count, 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), mNumPages * PAGE_SIZE * cmd_count ); 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"); } /* we are done with the mbox */ close( mMbox.handle ); mMbox.handle = -1; init_ctrl_data(); init_hardware( time_base ); update_pwm(); } void PWM::DMAChannel::Reset() { if ( dma_reg && mMbox.virt_addr ) { // for ( i = 0; i < mPinsCount; i++ ) { // mPinsPWM[i] = 0.0; // } // update_pwm(); // usleep( mCycleTime * 2 ); dma_reg[DMA_CS] = DMA_RESET; } } PWM::DMAChannel::~DMAChannel() { if ( mMbox.virt_addr != NULL ) { unmapmem( mMbox.virt_addr, mNumPages * PAGE_SIZE ); if ( mMbox.handle <= 2 ) { mMbox.handle = mbox_open(); } mem_unlock( mMbox.handle, mMbox.mem_ref ); mem_free( mMbox.handle, mMbox.mem_ref ); // mbox_close( mMbox.handle ); } } void PWM::terminate( int sig ) { fDebug(); if ( mChannels.size() == 0 ) { // Not needed return; } size_t i, j; void* array[16]; size_t size; size = backtrace( array, 16 ); fprintf( stderr, "Error: signal %d :\n", sig ); char** trace = backtrace_symbols( array, size ); dprintf( "Resetting PWM/DMA (%u)...\n", (uint32_t)mChannels.size() ); for ( j = 0; j < mChannels.size(); j++ ) { if ( mChannels[j] ) { mChannels[j]->Reset(); usleep(10); } } dprintf("Freeing mbox memory...\n"); for ( j = 0; j < mChannels.size(); j++ ) { if ( mChannels[j] ) { delete mChannels[j]; mChannels[j] = nullptr; } } mChannels.clear(); dprintf("Unlink %s...\n", DEVFILE_MBOX); unlink(DEVFILE_MBOX); } void PWM::DMAChannel::SetPWMValue( uint32_t pin, uint32_t width ) { bool found = false; uint32_t i = 0; for ( i = 0; i < mPinsCount; i++ ) { if ( mPins[i] == (int8_t)pin ) { found = true; break; } } if ( not found ) { i = mPinsCount; mPinsCount += 1; mPins[i] = pin; mPinsMask = mPinsMask | ( 1 << pin ); GPIO::setPUD( pin, GPIO::PullDown ); GPIO::setMode( pin, GPIO::Output ); gpio_reg[GPIO_CLR0] = 1 << pin; uint32_t fsel = gpio_reg[GPIO_FSEL0 + pin/10]; fsel &= ~(7 << ((pin % 10) * 3)); fsel |= GPIO_MODE_OUT << ((pin % 10) * 3); gpio_reg[GPIO_FSEL0 + pin/10] = fsel; } mPinsPWMf[i] = (float)width / (float)mCycleTime; mPinsPWM[i] = width * mNumSamples / mCycleTime; } void PWM::DMAChannel::SetPWMBuffer( uint32_t pin, uint8_t* buffer, uint32_t len ) { bool found = false; uint32_t i = 0; for ( i = 0; i < mPinsCount; i++ ) { if ( mPins[i] == (int8_t)pin ) { found = true; break; } } if ( not found ) { i = mPinsCount; mPinsCount += 1; mPins[i] = pin; mPinsMask = mPinsMask | ( 1 << pin ); gpio_reg[GPIO_CLR0] = 1 << pin; uint32_t fsel = gpio_reg[GPIO_FSEL0 + pin/10]; fsel &= ~(7 << ((pin % 10) * 3)); fsel |= GPIO_MODE_OUT << ((pin % 10) * 3); gpio_reg[GPIO_FSEL0 + pin/10] = fsel; } if ( mPinsBuffer[i] and mPinsBufferLength[i] < len ) { delete mPinsBuffer[i]; mPinsBuffer[i] = nullptr; } if ( not mPinsBuffer[i] ) { mPinsBuffer[i] = new uint8_t[ len ]; } memcpy( mPinsBuffer[i], buffer, len ); mPinsBufferLength[i] = len; } void PWM::DMAChannel::Update() { if ( mMode == MODE_PWM ) { update_pwm(); } else if ( mMode == MODE_BUFFER ) { update_pwm_buffer(); } } void PWM::DMAChannel::update_pwm() { uint32_t i, j; // uint32_t cmd_count = 2;// + ( mLoop == false ); uint32_t phys_gpclr0 = GPIO_PHYS_BASE + 0x28; uint32_t phys_gpset0 = GPIO_PHYS_BASE + 0x1c; uint32_t phys_gplev0 = GPIO_PHYS_BASE + 0x34; uint32_t mask; dma_ctl_t ctl = mCtls[0]; if ( mLoop ) { // ctl = mCtls[ ( mCurrentCtl + 1 ) % 2 ]; } // Wait until CMA_ACTIVE bit is false to prevent overlapping writes while ( mLoop == false and ( dma_reg[DMA_CS] & 1 ) ) { usleep(0); } ctl.cb[0].dst = phys_gpset0; mask = 0; for ( i = 0; i <= mPinsCount; i++ ) { if ( mPinsPWM[i] > 0 ) { mask |= 1 << mPins[i]; } } ctl.sample[0] = mask; for ( j = 1; j < mNumSamples; j++ ) { ctl.cb[j*2].dst = phys_gpclr0; mask = 0; for ( i = 0; i <= mPinsCount; i++ ) { if ( mPins[i] >= 0 and j > mPinsPWM[i] ) { mask |= 1 << mPins[i]; } } ctl.sample[j] = mask; } if ( mLoop == false ) { dma_reg[DMA_CS] = DMA_INT | DMA_END; dma_reg[DMA_CONBLK_AD] = mem_virt_to_phys(mCtls[0].cb); dma_reg[DMA_DEBUG] = 7; // clear debug error flags dma_reg[DMA_CS] = 0x10770001; // go, high priority, wait for outstanding writes } } void PWM::DMAChannel::update_pwm_buffer() { // uint32_t cmd_count = 3;// + ( mLoop == false ); // uint32_t phys_gpclr0 = GPIO_PHYS_BASE + 0x28; // uint32_t phys_gpset0 = GPIO_PHYS_BASE + 0x1c; uint32_t mask; dma_ctl_t ctl = mCtls[0]; // Wait until CMA_ACTIVE bit is false to prevent overlapping writes while ( mLoop == false and ( dma_reg[DMA_CS] & 1 ) ) { usleep(0); } uint32_t i, j; for ( j = 0; j < mNumSamples; j++ ) { // Clear bits { mask = 0; for ( i = 0; i <= mPinsCount; i++ ) { if ( mPins[i] >= 0 and mPinsBufferLength[i] < j and mPinsBuffer[i][j] == 0 ) { mask |= 1 << mPins[i]; } } ctl.sample[j] = mask; } // Set bits { mask = 0; for ( i = 0; i <= mPinsCount; i++ ) { if ( mPins[i] >= 0 and mPinsBufferLength[i] < j and mPinsBuffer[i][j] == 1 ) { mask |= 1 << mPins[i]; } } ctl.sample[mNumSamples + j] = mask; } } if ( mLoop == false ) { // mCurrentCtl = ( mCurrentCtl + 1 ) % 2; dma_reg[DMA_CS] = DMA_INT | DMA_END; dma_reg[DMA_CONBLK_AD] = mem_virt_to_phys(mCtls[0].cb); dma_reg[DMA_DEBUG] = 7; // clear debug error flags dma_reg[DMA_CS] = 0x10770001; // go, high priority, wait for outstanding writes } } void PWM::DMAChannel::init_ctrl_data() { dprintf( "Initializing PWM ...\n" ); init_dma_ctl( &mCtls[0] ); // init_dma_ctl( &mCtls[1] ); dprintf( "Ok\n" ); } /* TODO : Multiplexer PWM output : PWM0_0 as output : PWM1_0 as DMA timer ? : pins A, B, C, D to control external multiplexer DMA commands buffer: → reset switch pins (phys_gpclr0) → loop over all channels → set switch pins to pin X high (phys_gpset0) → TBD : wait for switch to physically rise ? (GPIO rise time + external multiplexer IC rise time) (Use builtin DMA_WAIT_RESP, and just run same command 2~3× to wait IC ?) → write to PWM0_0 FIFO channel X value (TBD) \ → use PWM1_0 to wait for PWM0_0 to output ? TBD : just wait for FIFO end trigger ? | → Reuse "// Timer trigger command" for both in one DMA command block (no need for PWM1_0) → reset switch pins (phys_gpclr0) → TBD : wait for switch to physically fall ? (GPIO fall time + external multiplexer IC fall time) (same as above) */ void PWM::DMAChannel::init_dma_ctl( dma_ctl_t* ctl ) { dma_cb_t* cbp = ctl->cb; uint32_t phys_fifo_addr; uint32_t phys_gpclr0 = GPIO_PHYS_BASE + 0x28; uint32_t phys_gpset0 = GPIO_PHYS_BASE + 0x1c; uint32_t phys_gplev0 = GPIO_PHYS_BASE + 0x34; uint32_t mask; uint32_t i; uint32_t map = DMA_PER_MAP(5); phys_fifo_addr = PWM_PHYS_BASE + 0x18; // uint32_t map = DMA_PER_MAP(2); // phys_fifo_addr = PCM_PHYS_BASE + 0x04; memset( ctl->sample, 0, sizeof(uint32_t)*mNumSamples ); mask = 0; // Calculate a mask to turn off everything if ( mMode == MODE_BUFFER ) { // Clear bits { for ( i = 0; i <= mPinsCount; i++ ) { mask |= 1 << mPins[i]; } for ( i = 0; i < mNumSamples; i++ ) { ctl->sample[i] = mask; } } // Set bits for ( i = 0; i < mNumSamples; i++ ) { ctl->sample[mNumSamples + i] = 0; } } else if ( mMode == MODE_PWM ) { for ( i = 0; i < mPinsCount; i++ ) { mask |= 1 << mPins[i]; } for ( i = 0; i < mNumSamples; i++ ) { ctl->sample[i] = mask; } } /* Initialize all the PWM commands. They come in pairs. * - 1st command copies a value from the sample memory to a destination * address which can be either the gpclr0 register or the gpset0 register * - 2nd command waits for a trigger from an PWM source * - 3rd command (optional) resets pins to 0 */ for (i = 0; i < mNumSamples; i++) { // GPIO-Clear command cbp->info = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP; // cbp->info = DMA_NO_WIDE_BURSTS | DMA_TDMODE; cbp->src = mem_virt_to_phys(ctl->sample + i); cbp->dst = phys_gpclr0; cbp->length = 4; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; if ( mMode == MODE_BUFFER ) { // GPIO-Set command // cbp->info = DMA_NO_WIDE_BURSTS; cbp->info = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP; cbp->src = mem_virt_to_phys(ctl->sample + mNumSamples + i); cbp->dst = phys_gpset0; cbp->length = 4; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; } // Timer trigger command cbp->info = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP | DMA_D_DREQ | map; // cbp->info = DMA_NO_WIDE_BURSTS | DMA_D_DREQ | DMA_PER_MAP(5) | DMA_TDMODE; cbp->src = mem_virt_to_phys(ctl->sample); // Any data will do cbp->dst = phys_fifo_addr; cbp->length = 4; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; /* if ( mLoop == false ) { // Third PWM command cbp->info = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP; cbp->src = mem_virt_to_phys(mPinsMask); cbp->dst = phys_gpclr0; cbp->length = 4; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; } */ } cbp--; if ( mLoop ) { cbp->next = mem_virt_to_phys(ctl->cb); } else { cbp->next = 0; } ctl->cb[0].dst = phys_gpset0; dprintf( "Ok\n" ); } static bool _init_ok = false; void PWM::DMAChannel::init_hardware( uint32_t time_base ) { if ( _init_ok ) { return; } _init_ok = true; dprintf("Initializing PWM HW...\n"); // Initialise PWM pwm_reg[PWM_CTL] = 0; usleep(10); clk_reg[PWMCLK_CNTL] = 0x5A000006; // Source=PLLD (500MHz) usleep(100); clk_reg[PWMCLK_DIV] = 0x5A000000 | ( ( 500000000 / time_base ) << 12 ); // setting pwm div to 500 gives 1MHz // clk_reg[PWMCLK_DIV] = 0x5A000000 | hzToDivider( plldfreq_mhz, time_base ); usleep(100); clk_reg[PWMCLK_CNTL] = 0x5A000016; // Source=PLLD and enable usleep(100); pwm_reg[PWM_RNG1] = ( mSampleTime - 1 ); usleep(10); pwm_reg[PWM_PWMC] = PWMPWMC_ENAB | PWMPWMC_THRSHLD; usleep(10); pwm_reg[PWM_CTL] = PWMCTL_CLRF; usleep(10); pwm_reg[PWM_CTL] = PWMCTL_USEF1 | PWMCTL_PWEN1; usleep(10); /* dprintf("Initializing PCM HW...\n"); // Initialise PCM pcm_reg[PCM_CS_A] = 1; // Disable Rx+Tx, Enable PCM block usleep(100); clk_reg[PCMCLK_CNTL] = 0x5A000006; // Source=PLLD (500MHz) usleep(100); clk_reg[PCMCLK_DIV] = 0x5A000000 | ( ( 500000000 / time_base ) << 12 ); usleep(100); clk_reg[PCMCLK_CNTL] = 0x5A000016; // Source=PLLD and enable usleep(100); pcm_reg[PCM_TXC_A] = 0<<31 | 1<<30 | 0<<20 | 0<<16; // 1 channel, 8 bits usleep(100); pcm_reg[PCM_MODE_A] = (mSampleTime - 1) << 10; usleep(100); pcm_reg[PCM_CS_A] |= 1<<4 | 1<<3; // Clear FIFOs usleep(100); pcm_reg[PCM_DREQ_A] = 64<<24 | 64<<8; // DMA Req when one slot is free? usleep(100); pcm_reg[PCM_CS_A] |= 1<<9; // Enable DMA */ // Initialise the DMA dma_reg[DMA_CS] = DMA_RESET; usleep(10); dma_reg[DMA_CS] = DMA_INT | DMA_END; dma_reg[DMA_CONBLK_AD] = mem_virt_to_phys(mCtls[0].cb); dma_reg[DMA_DEBUG] = 7; // clear debug error flags dma_reg[DMA_CS] = 0x10770001; // go, high priority, wait for outstanding writes // pcm_reg[PCM_CS_A] |= 1<<2; // Enable Tx dprintf( "Ok\n" ); } int PWM::Channel::mbox_open() { int file_desc; // try to use /dev/vcio first (kernel 4.1+) file_desc = open( DEVFILE_VCIO, 0 ); if ( file_desc < 0 ) { unlink( DEVFILE_MBOX ); if ( mknod( DEVFILE_MBOX, S_IFCHR | 0600, makedev( MAJOR_NUM, 0 ) ) < 0 ) { fatal("Failed to create mailbox device\n"); } file_desc = open( DEVFILE_MBOX, 0 ); if ( file_desc < 0 ) { printf( "Can't open device file: %s\n", DEVFILE_MBOX ); perror( NULL ); exit( -1 ); } } return file_desc; } uint32_t PWM::Channel::mem_virt_to_phys( void* virt ) { uintptr_t offset = (uintptr_t)virt - (uintptr_t)mMbox.virt_addr; return mMbox.bus_addr + offset; } void PWM::Channel::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: fatal( "Unable to detect Board Model from board revision: %#x", mbox_board_rev ); break; } } void* PWM::Channel::map_peripheral( uint32_t base, uint32_t len ) { int fd = open( "/dev/mem", O_RDWR | O_SYNC ); void * vaddr; if ( fd < 0 ) { fatal( "pi-blaster: Failed to open /dev/mem: %m\n" ); } vaddr = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, base ); if ( vaddr == MAP_FAILED ) { fatal("pi-blaster: Failed to map peripheral at 0x%08x: %m\n", base ); } close( fd ); return vaddr; }
41,379
C++
.cpp
1,255
30.564143
178
0.652844
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,779
I2C.cpp
dridri_bcflight/flight/boards/rpi/I2C.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 <Debug.h> #include "I2C.h" #include "Board.h" int I2C::mFD = -1; int I2C::mCurrAddr = -1; pthread_mutex_t I2C::mMutex = PTHREAD_MUTEX_INITIALIZER; I2C::I2C( int addr, bool slave ) : Bus() , mAddr( addr ) { } I2C::~I2C() { } int I2C::Connect() { pthread_mutex_lock( &mMutex ); if ( mFD < 0 ) { mFD = open( "/dev/i2c-1", O_RDWR ); gDebug() << "fd : " << mFD; } pthread_mutex_unlock( &mMutex ); return 0; } std::string I2C::toString() { string ret; ret += "{\n"; ret += "\t\"Type\": \"I2C\",\n"; ret += "\t\"Address\": " + to_string( mAddr ) + "\n"; ret += "}\n"; return ret; } LuaValue I2C::infos() { LuaValue ret; ret["Type"] = "I2C"; ret["Device"] = "/dev/i2c-1"; ret["Address"] = mAddr; return ret; } const int I2C::address() const { return mAddr; } int I2C::Read( void* buf, uint32_t len ) { pthread_mutex_lock( &mMutex ); if ( mCurrAddr != mAddr ) { mCurrAddr = mAddr; if ( ioctl( mFD, I2C_SLAVE, mAddr ) != 0 ) { return 0; } } int ret = read( mFD, buf, len ); pthread_mutex_unlock( &mMutex ); return ret; } int I2C::Write( const void* buf, uint32_t len ) { int ret; pthread_mutex_lock( &mMutex ); if ( mCurrAddr != mAddr ) { mCurrAddr = mAddr; if ( ioctl( mFD, I2C_SLAVE, mAddr ) != 0 ) { return 0; } } ret = write( mFD, buf, len ); pthread_mutex_unlock( &mMutex ); return ret; } int I2C::Read( uint8_t reg, void* buf, uint32_t len ) { pthread_mutex_lock( &mMutex ); if ( mCurrAddr != mAddr ) { mCurrAddr = mAddr; if ( ioctl( mFD, I2C_SLAVE, mAddr ) != 0 ) { return 0; } } write( mFD, &reg, 1 ); int ret = read( mFD, buf, len ); pthread_mutex_unlock( &mMutex ); return ret; } int I2C::Write( uint8_t reg, const void* _buf, uint32_t len ) { int ret; char buf[1024]; buf[0] = reg; memcpy( buf + 1, _buf, len ); pthread_mutex_lock( &mMutex ); if ( mCurrAddr != mAddr ) { mCurrAddr = mAddr; if ( ioctl( mFD, I2C_SLAVE, mAddr ) != 0 ) { return 0; } } ret = write( mFD, buf, len + 1 ); pthread_mutex_unlock( &mMutex ); return ret; } list< int > I2C::ScanAll() { list< int > ret; int fd = open( "/dev/i2c-1", O_RDWR ); if ( fd < 0 ) { gError() << "Cannot open " << string("/dev/i2c-1") << " : " << strerror(errno); return ret; } int res = 0; int byte_ = 0; for ( int i = 0; i < 128; i++ ) { if ( ioctl( fd, I2C_SLAVE, i ) < 0) { if ( errno == EBUSY ) { continue; } else { gError() << "Could not set address to " << i << " : " << strerror(errno); return ret; } } char buf[] = {1}; write( fd, buf, 1 ); res = read( fd, &byte_, 1 ); /* if ( ( i >= 0x30 && i <= 0x37 ) || ( i >= 0x50 && i <= 0x5F ) ) { res = read( fd, &byte_, 1 ); } else { byte_ = 0x0F; res = write( fd, &byte_, 1 ); } */ if ( res > 0 ) { ret.push_back( i ); } } close( fd ); if ( ret.size() >= 127 ) { gError() << "Defective I2C bus !"; Board::defectivePeripherals()["I2C"] = true; ret.clear(); } return ret; }
3,842
C++
.cpp
168
20.488095
81
0.611907
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,780
Bus.cpp
dridri_bcflight/flight/boards/common/Bus.cpp
#include "Bus.h" #include <Board.h> #include <Debug.h> Bus::Bus() : mConnected( false ) { } Bus::~Bus() { } int Bus::Read8( uint8_t reg, uint8_t* value ) { return Read( reg, value, 1 ); } int Bus::Read16( uint8_t reg, uint16_t* value, bool big_endian ) { int ret = Read( reg, value, 2 ); if ( big_endian ) { #ifdef bswap_16 *value = bswap_16( *value ); #elif defined( __bswap16 ) *value = __bswap16( *value ); #else *value = ( (*value) >> 8 ) | ( (*value) << 8 ); #endif } return ret; } int Bus::Read16( uint8_t reg, int16_t* value, bool big_endian ) { union { uint16_t u; int16_t s; } v; int ret = Read16( reg, &v.u, big_endian ); *value = v.s; return ret; } int Bus::Read24( uint8_t reg, uint32_t* value ) { uint8_t v[3] = { 0, 0, 0 }; int ret = Read( reg, v, 3 ); *value = ( ((uint32_t)v[0]) << 16 ) | ( ((uint32_t)v[1]) << 8 ) | ( ((uint32_t)v[2]) << 0 ); return ret; } int Bus::Read32( uint8_t reg, uint32_t* value ) { return Read( reg, value, 4 ); } int Bus::Write8( uint8_t reg, uint8_t value ) { return Write( reg, &value, 1 ); } int Bus::Write16( uint8_t reg, uint16_t value ) { return Write( reg, &value, 2 ); } int Bus::Write32( uint8_t reg, uint32_t value ) { return Write( reg, &value, 4 ); } int Bus::WriteFloat( uint8_t reg, float value ) { union { uint32_t u; float f; } v; v.f = value; return Write( reg, &v.u, 4 ); } int Bus::WriteVector3f( uint8_t reg, const Vector3f& vec ) { typedef union { uint32_t u; float f; } v; struct { v x, y, z; } __attribute__((packed)) uvec; uvec.x.f = vec.x; uvec.y.f = vec.y; uvec.z.f = vec.z; return Write( reg, &uvec.x.u, 4 * 3 ); }
1,661
C++
.cpp
84
17.869048
93
0.608247
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,781
ThreadBase.cpp
dridri_bcflight/flight/boards/common/ThreadBase.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 "ThreadBase.h" #include "Thread.h" #include "Board.h" #include "Debug.h" static list< ThreadBase* > mThreads; list< ThreadBase* >& ThreadBase::threads() { return mThreads; } ThreadBase::ThreadBase( const string& name ) : mName( name ) , mID( 0 ) , mRunning( false ) , mStopped( false ) , mIsRunning( false ) , mFinished( false ) , mPriority( 0 ) , mSetPriority( 0 ) , mAffinity( -1 ) , mSetAffinity( -1 ) , mPriorityFifo( false ) , mFrequency( 0 ) , mFrequencyTick( 0 ) { mThreads.emplace_back( this ); gDebug() << "New thread : " << name; } ThreadBase::~ThreadBase() { } const string& ThreadBase::name() const { return mName; } void ThreadBase::StopAll() { gDebug() << "Stopping all threads !"; // Stop ISRs first for ( ThreadBase* thread : mThreads ) { if ( not thread->mStopped and thread->name().find( "ISR" ) != string::npos ) { gDebug() << "Stopping ISR thread " << thread->mName; static_cast<Thread*>(thread)->Stop(); static_cast<Thread*>(thread)->Join(); } } for ( ThreadBase* thread : mThreads ) { if ( not thread->mStopped ) { gDebug() << "Stopping thread " << thread->mName; static_cast<Thread*>(thread)->Stop(); static_cast<Thread*>(thread)->Join(); } } gDebug() << "Stopped all threads !"; } uint64_t ThreadBase::GetTick() { return Board::GetTicks(); } float ThreadBase::GetSeconds() { return (float)( GetTick() / 1000 ) / 1000.0f; } void ThreadBase::Start() { mStopped = false; mFinished = false; mRunning = true; } void ThreadBase::Pause() { mRunning = false; } void ThreadBase::Stop() { mStopped = true; } void ThreadBase::Join() { while ( !mFinished ) { usleep( 1000 * 10 ); } } bool ThreadBase::running() const { return mIsRunning; } bool ThreadBase::stopped() const { return mStopped; } uint32_t ThreadBase::frequency() const { return mFrequency; } void ThreadBase::setMainPriority( int p ) { // piHiPri( p ); } void ThreadBase::setPriority( int p, int affinity, bool priorityFifo ) { mSetPriority = p; if ( affinity >= 0 ) { mSetAffinity = affinity; mPriorityFifo = priorityFifo; } } void ThreadBase::setFrequency( uint32_t hz ) { mFrequency = hz; }
2,924
C++
.cpp
128
20.84375
80
0.703046
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,782
Servo.cpp
dridri_bcflight/flight/boards/generic/Servo.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 <stdio.h> #include <string.h> #include <unistd.h> #include <stdint.h> #include "Servo.h" Servo::Servo( int pin, int us_min, int us_max ) : mID( pin ) , mMin( us_min ) , mMax( us_max ) , mRange( us_max - us_min ) { } Servo::~Servo() { } void Servo::setValue( float p, bool force_update ) { if ( p < 0.0f ) { p = 0.0f; } if ( p > 1.0f ) { p = 1.0f; } uint32_t us = mMin + (uint32_t)( mRange * p ); // Set PWM here. If 'force_update' indicates that the PWM should be updated now // (consistent only when the hardware/software implementation need an explicit call to update PWM) } void Servo::HardwareSync() { // ^ consistent only when the hardware/software implementation need an explicit call to update PWM } void Servo::Disarm() { // After calling this function, PWM should output a value below the minimum arming pulse width // This ensure that the motors will not start spinning at any time, letting user to touch them without risks } void Servo::Disable() { // After calling this function, PWM should not output anything and setting its pin to a 0V output // This is used to calibrate and configure ESCs }
1,886
C++
.cpp
59
30.118644
109
0.728926
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,783
SPI.cpp
dridri_bcflight/flight/boards/generic/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 ) { } SPI::~SPI() { } int SPI::Connect() { fDebug( mDevice ); return 0; } std::string SPI::toString() { return mDevice; } const string& SPI::device() const { return mDevice; } int SPI::Transfer( void* tx, void* rx, uint32_t len ) { mTransferMutex.lock(); int ret = len; // TODO : transfer here mTransferMutex.unlock(); return ret; } int SPI::Read( void* buf, uint32_t len ) { uint8_t unused[1024]; memset( unused, 0, len + 1 ); return Transfer( unused, buf, len ); } int SPI::Write( const void* buf, uint32_t len ) { uint8_t unused[1024]; 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[1024]; uint8_t rx[1024]; memset( tx, 0, len + 1 ); tx[0] = reg; int ret = Transfer( tx, rx, len + 1 ); memcpy( buf, rx + 1, len ); return ret; } int SPI::Write( uint8_t reg, const void* buf, uint32_t len ) { uint8_t tx[1024]; uint8_t rx[1024]; tx[0] = reg; memcpy( tx + 1, buf, len ); return Transfer( tx, rx, len + 1 ); }
2,074
C++
.cpp
86
22.337209
72
0.697509
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,784
DShotDriver.cpp
dridri_bcflight/flight/boards/generic/DShotDriver.cpp
#include "DShotDriver.h" DShotDriver* DShotDriver::instance( bool create_new ) { return nullptr; } DShotDriver::DShotDriver() { } DShotDriver::~DShotDriver() { } void DShotDriver::Kill() noexcept { } void DShotDriver::setPinValue( uint32_t pin, uint16_t value, bool telemetry ) { (void)pin; (void)value; (void)telemetry; } void DShotDriver::disablePinValue( uint32_t pin ) { (void)pin; } void DShotDriver::Update() { }
438
C++
.cpp
27
14.518519
77
0.765743
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,785
GPIO.cpp
dridri_bcflight/flight/boards/generic/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 "GPIO.h" void GPIO::setMode( int pin, GPIO::Mode mode ) { } void GPIO::setPWM( int pin, int initialValue, int pwmRange ) { // Unused for now, can be left empty } void GPIO::Write( int pin, bool en ) { } bool GPIO::Read( int pin ) { return false; } void GPIO::SetupInterrupt( int pin, GPIO::ISRMode mode, function<void()> fct ) { }
1,067
C++
.cpp
35
28.6
78
0.737512
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,787
Board.cpp
dridri_bcflight/flight/boards/generic/Board.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 <time.h> #include <sys/time.h> #include <fstream> #include <Main.h> #include <netinet/in.h> #include "Board.h" #include "I2C.h" uint64_t Board::mTicksBase = 0; decltype(Board::mRegisters) Board::mRegisters = decltype(Board::mRegisters)(); map< string, bool > Board::mDefectivePeripherals; Board::Board( Main* main ) { srand( time( nullptr ) ); // hardware-specific initialization should be done here or directly in startup.cpp // this->mRegisters should be loaded here } Board::~Board() { } static string readproc( const string& filename, const string& entry = "", const string& delim = ":" ) { char buf[1024] = ""; string res = ""; ifstream file( filename ); if ( entry.length() == 0 or entry == "" ) { file.readsome( buf, sizeof( buf ) ); res = buf; } else { while ( file.good() ) { file.getline( buf, sizeof(buf), '\n' ); if ( strstr( buf, entry.c_str() ) ) { char* s = strstr( buf, delim.c_str() ) + delim.length(); while ( *s == ' ' or *s == '\t' ) { s++; } char* end = s; while ( *end != '\n' and *end++ ); *end = 0; res = string( s ); break; } } } res = res.substr( 0, res.find( "\n" ) ); file.close(); return res; } static string readcmd( const string& cmd, const string& entry = "", const string& delim = ":" ) { char buf[1024] = ""; string res = ""; FILE* fp = popen( cmd.c_str(), "rb" ); if ( entry.length() == 0 or entry == "" ) { fread( buf, 1, sizeof( buf ), fp ); res = buf; } else { // TODO } pclose( fp ); return res; } map< string, bool >& Board::defectivePeripherals() { return mDefectivePeripherals; } string Board::infos() { string res = ""; res += "Type:" BOARD "\n"; res += "Firmware version:" VERSION_STRING "\n"; res += "CPU:" + readproc( "/proc/cpuinfo", "model name" ) + string( "\n" ); res += "CPU frequency:" + to_string( atoi( readproc( "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq" ).c_str() ) / 1000 ) + string( "MHz\n" ); res += "CPU cores count:" + to_string( sysconf( _SC_NPROCESSORS_ONLN ) ) + string( "\n" ); return res; } void Board::InformLoading( int force_led ) { // Controls loading LED. // if force_led != -1, then this function should turn on (1) or off (0) the led according to this variablezz // Otherwise, make it blink } void Board::LoadingDone() { InformLoading( true ); } void Board::setLocalTimestamp( uint32_t t ) { } Board::Date Board::localDate() { Date ret; memset( &ret, 0, sizeof(ret) ); return ret; } const uint32_t Board::LoadRegisterU32( const string& name, uint32_t def ) { string str = LoadRegister( name ); if ( str != "" and str.length() > 0 ) { return strtoul( str.c_str(), nullptr, 10 ); } return def; } const float Board::LoadRegisterFloat( const string& name, float def ) { string str = LoadRegister( name ); if ( str != "" and str.length() > 0 ) { return atof( str.c_str() ); } return def; } const string Board::LoadRegister( const string& name ) { if ( mRegisters.find( name ) != mRegisters.end() ) { return mRegisters[ name ]; } return ""; } int Board::SaveRegister( const string& name, const string& value ) { mRegisters[ name ] = value; // Save register(s) here, and return 0 on success or -1 on error return 0; } uint64_t Board::GetTicks() { if ( mTicksBase == 0 ) { struct timespec now; clock_gettime( CLOCK_MONOTONIC, &now ); mTicksBase = (uint64_t)now.tv_sec * 1000000ULL + (uint64_t)now.tv_nsec / 1000ULL; } struct timespec now; clock_gettime( CLOCK_MONOTONIC, &now ); return (uint64_t)now.tv_sec * 1000000ULL + (uint64_t)now.tv_nsec / 1000ULL - mTicksBase; } uint64_t Board::WaitTick( uint64_t ticks_p_second, uint64_t lastTick, uint64_t sleep_bias ) { uint64_t ticks = GetTicks(); if ( ( ticks - lastTick ) < ticks_p_second ) { int64_t t = (int64_t)ticks_p_second - ( (int64_t)ticks - (int64_t)lastTick ) + sleep_bias; if ( t < 0 ) { t = 0; } usleep( t ); } return GetTicks(); } string Board::readcmd( const string& cmd, const string& entry, const string& delim ) { char buf[1024] = ""; string res = ""; FILE* fp = popen( cmd.c_str(), "r" ); if ( !fp ) { printf( "popen failed : %s\n", strerror( errno ) ); return ""; } if ( entry.length() == 0 or entry == "" ) { fread( buf, 1, sizeof( buf ), fp ); res = buf; } else { while ( fgets( buf, sizeof(buf), fp ) ) { if ( strstr( buf, entry.c_str() ) ) { char* s = strstr( buf, delim.c_str() ) + delim.length(); while ( *s == ' ' or *s == '\t' ) { s++; } char* end = s; while ( *end != '\n' and *end++ ); *end = 0; res = string( s ); break; } } } pclose( fp ); return res; } uint32_t Board::CPULoad() { return 0; } uint32_t Board::CPUTemp() { return 0; } void Board::EnableTunDevice() { } void Board::DisableTunDevice() { } void Board::UpdateFirmwareData( const uint8_t* buf, uint32_t offset, uint32_t size ) { } void Board::UpdateFirmwareProcess( uint32_t crc ) { } void Board::Reset() { } void Board::setDiskFull() { } extern "C" uint32_t _mem_usage() { return 0; // TODO } uint16_t board_htons( uint16_t v ) { return htons( v ); } uint16_t board_ntohs( uint16_t v ) { return ntohs( v ); } uint32_t board_htonl( uint32_t v ) { return htonl( v ); } uint32_t board_ntohl( uint32_t v ) { return ntohl( v ); }
6,076
C++
.cpp
240
23.033333
151
0.649592
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,788
Thread.cpp
dridri_bcflight/flight/boards/generic/Thread.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 <wiringPi.h> #include <iostream> #include "Thread.h" #include "Board.h" #include "Debug.h" Thread::Thread( const string& name ) : ThreadBase( name ) , mSpawned( false ) { mID = mThread; } Thread::~Thread() { } void Thread::Start() { if ( not mSpawned ) { pthread_create( &mThread, nullptr, (void*(*)(void*))&Thread::ThreadEntry, this ); pthread_setname_np( mThread, mName.substr( 0, 15 ).c_str() ); mSpawned = true; } mRunning = true; } Thread* Thread::currentThread() { for ( ThreadBase* th : threads() ) { if ( static_cast<Thread*>(th)->mThread == pthread_self() ) { return static_cast<Thread*>(th); } } return nullptr; } void Thread::Join() { uint64_t start_time = Board::GetTicks(); while ( !mFinished ) { if ( Board::GetTicks() - start_time > 1000 * 1000 * 2 ) { gDebug() << "thread \"" << mName << "\" join timeout (2s), force killing"; pthread_cancel( mThread ); break; } usleep( 1000 * 10 ); } } void Thread::Recover() { gDebug() << "\e[93mRecovering thread \"" << mName << "\"\e[0m"; mRunning = false; mStopped = false; mIsRunning = false; mFinished = false; mPriority = 0; mAffinity = -1; pthread_create( &mThread, nullptr, (void*(*)(void*))&Thread::ThreadEntry, this ); pthread_setname_np( mThread, mName.substr( 0, 15 ).c_str() ); mID = mThread; mRunning = true; } void Thread::ThreadEntry() { do { while ( not mRunning and not mStopped ) { mIsRunning = false; usleep( 1000 * 100 ); } if ( mRunning ) { mIsRunning = true; if ( mSetPriority != mPriority ) { mPriority = mSetPriority; // piHiPri( mPriority ); TODO : set priority here } if ( mSetAffinity >= 0 and mSetAffinity != mAffinity ) { mAffinity = mSetAffinity; cpu_set_t cpuset; CPU_ZERO( &cpuset ); CPU_SET( mAffinity, &cpuset ); pthread_setaffinity_np( pthread_self(), sizeof(cpu_set_t), &cpuset ); } } if ( mFrequency > 0 ) { mFrequencyTick = Board::WaitTick( 1000000 / mFrequency, mFrequencyTick ); } } while ( not mStopped and run() ); mIsRunning = false; mFinished = true; } void Thread::msleep( uint32_t ms ) { ::usleep( ms * 1000 ); } void Thread::usleep( uint32_t us ) { ::usleep( us ); }
2,955
C++
.cpp
112
23.955357
83
0.674229
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,789
startup.cpp
dridri_bcflight/flight/boards/generic/startup.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 <Main.h> int main( int ac, char** av ) { // board-specific early initializations should be done here return Main::flight_entry( ac, av ); }
867
C++
.cpp
23
35.73913
72
0.745843
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,790
Serial.cpp
dridri_bcflight/flight/boards/generic/Serial.cpp
#include "Serial.h" #include <stdio.h> #include <unistd.h> #include <sys/fcntl.h> // #include <sys/ioctl.h> // #include <termios.h> #include <asm/termios.h> #include <map> #include "Debug.h" //#include <pigpio.h> extern "C" int ioctl (int __fd, unsigned long int __request, ...) __THROW; static map< int, int > sSpeeds = { { 0, B0 }, { 50, B50 }, { 75, B75 }, { 110, B110 }, { 134, B134 }, { 150, B150 }, { 200, B200 }, { 300, B300 }, { 600, B600 }, { 1200, B1200 }, { 1800, B1800 }, { 2400, B2400 }, { 4800, B4800 }, { 9600, B9600 }, { 19200, B19200 }, { 38400, B38400 }, { 57600, B57600 }, { 115200, B115200 }, { 230400, B230400 }, { 460800, B460800 }, { 500000, B500000 }, { 576000, B576000 }, { 921600, B921600 }, { 1000000, B1000000 }, { 1152000, B1152000 }, { 1500000, B1500000 }, { 2000000, B2000000 }, { 2500000, B2500000 }, { 3000000, B3000000 }, { 3500000, B3500000 }, { 4000000, B4000000 } }; Serial::Serial( const string& device, int speed ) : Bus() , mFD( -1 ) , mDevice( device ) { } Serial::~Serial() { } int Serial::Connect() { return 0; } std::string Serial::toString() { return mDevice; } void Serial::setStopBits( uint8_t count ) { (void)count; } int Serial::Read( uint8_t reg, void* buf, uint32_t len ) { return 0; } int Serial::Read( void* buf, uint32_t len ) { return 0; } int Serial::Write( const void* buf, uint32_t len ) { return 0; } int Serial::Write( uint8_t reg, const void* buf, uint32_t len ) { return 0; }
1,500
C++
.cpp
81
16.753086
74
0.636624
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,791
PWM.cpp
dridri_bcflight/flight/boards/generic/PWM.cpp
#include "PWM.h" #include <stdio.h> PWM::PWM( uint32_t pin, uint32_t time_base, uint32_t period_time_us, uint32_t sample_us, bool loop ) { } PWM::~PWM() { } void PWM::SetPWMus( uint32_t width_us ) { } void PWM::Update() { }
231
C++
.cpp
14
15
100
0.690476
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,792
I2C.cpp
dridri_bcflight/flight/boards/generic/I2C.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 <sstream> #include "I2C.h" I2C::I2C( int addr, bool slave ) : Bus() , mAddr( addr ) { } I2C::~I2C() { } int I2C::Connect() { return 0; } std::string I2C::toString() { stringstream ss; ss <<"I2C@0x" << std::hex << mAddr; return ss.str(); } const int I2C::address() const { return mAddr; } int I2C::Read( void* buf, uint32_t len ) { return 0; } int I2C::Write( const void* buf, uint32_t len ) { return 0; } int I2C::Read( uint8_t reg, void* buf, uint32_t len ) { return 0; } int I2C::Write( uint8_t reg, const void* _buf, uint32_t len ) { return 0; } list< int > I2C::ScanAll() { list< int > ret; // See boards/rpi/I2C.cpp implementation return ret; }
1,430
C++
.cpp
64
20.53125
72
0.710253
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,793
Debug.cpp
dridri_bcflight/libdebug/Debug.cpp
#include <time.h> #include <mutex> #include <map> #define __DBG_CLASS #include "Debug.h" #ifdef ANDROID #include <android/log.h> #endif pthread_t Debug::mMainThread = 0; bool Debug::mStoreLog = false; std::string Debug::mLog = std::string(); std::mutex Debug::mLogMutex; std::ofstream Debug::mLogFile; Debug::Level Debug::mDebugLevel = Debug::Warning; bool Debug::mColors = true; void Debug::log( int level, const std::string& s ) { #ifdef ANDROID __android_log_print( ANDROID_LOG_DEBUG + ( Level::Verbose - level ), "luaserver", "%s", s.c_str() ); #else if ( level <= Debug::Warning ) { std::cerr << s << std::flush; } else { std::cout << s << std::flush; } #endif if ( mStoreLog ) { mLogMutex.lock(); mLog += s; mLogMutex.unlock(); } if ( mLogFile.is_open() ) { mLogFile.write( s.c_str(), s.size() ); mLogFile.flush(); } }
857
C++
.cpp
35
22.571429
101
0.669951
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,794
LuaObject.cpp
dridri_bcflight/libluacore/src/LuaObject.cpp
#include "LuaObject.h" LuaObject::LuaObject( Lua* state ) : mState( state ) , mReference( 0 ) { if ( lua_type( state->state(), -1 ) == LUA_TUSERDATA ) { lua_pushvalue( state->state(), -1 ); mReference = luaL_ref( state->state(), LUA_REGISTRYINDEX ); // gDebug() << "mReference : " << mReference; } } LuaObject::~LuaObject() { }
341
C++
.cpp
14
22.428571
61
0.638889
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,795
Lua.cpp
dridri_bcflight/libluacore/src/Lua.cpp
#include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <dirent.h> #include <cmath> #include <algorithm> #include <dlfcn.h> #include <netdb.h> #include <netinet/in.h> #include "Lua.h" map< lua_State*, Lua* > Lua::mStates; LuaValue LuaValue::mNil; LuaValue LuaValue::Value( Lua* state, int32_t index ) { lua_State* L = state->state(); LuaValue ret; lua_pushvalue( L, index ); int32_t ref = luaL_ref( L, LUA_REGISTRYINDEX ); ret.mType = Reference; ret.mReference[L] = index; return ret; } LuaValue LuaValue::Registry( Lua* state, int32_t index ) { LuaValue ret; ret.mType = Reference; ret.mReference[state->state()] = index; return ret; } LuaValue LuaValue::fromReference( Lua* lua, lua_Integer ref ) { LuaValue v; v.mType = Reference; v.mReference[lua->state()] = ref; return v; } LuaValue LuaValue::fromReference( Lua* lua, LuaValue& val ) { LuaValue v; v.mType = Reference; v.mReference[lua->state()] = val.mReference[lua->state()]; return v; } LuaValue LuaValue::fromReference( Lua* lua, LuaValue* val ) { LuaValue v; v.mType = Reference; v.mReference[lua->state()] = val->mReference[lua->state()]; return v; } static int LuaPrint( lua_State* L ) { int nArgs = lua_gettop(L); lua_getglobal( L, "serialize" ); lua_getglobal( L, "tostring" ); string ret = ""; for ( int i = 1; i <= nArgs; i++ ) { if ( lua_type( L, i ) == LUA_TTABLE ) { lua_pushvalue( L, -2 ); } else { lua_pushvalue( L, -1 ); } lua_pushvalue( L, i ); lua_call( L, 1, 1 ); const char* s = lua_tostring( L, -1 ); if ( s == nullptr ) { break; } if ( i > 1 ) { ret += "\t"; } ret += s; lua_pop( L, 1 ); }; lua_pop( L, 1 ); lua_pop( L, 1 ); std::cout << "\x1B[93m[Lua]\x1B[0m " << ret << "\n"; return 0; } static int LuaDebugPrint( lua_State* L ) { int nArgs = lua_gettop(L); lua_getglobal( L, "tostring" ); // Debug::Level level = static_cast<Debug::Level>( lua_tointeger( L, 1 ) ); string ret = ""; for ( int i = 2; i <= nArgs; i++ ) { lua_pushvalue( L, -1 ); lua_pushvalue( L, i ); lua_call( L, 1, 1 ); const char* s = lua_tostring( L, -1 ); if ( s == nullptr ) { break; } if ( i > 2 ) { ret += "\t"; } ret += s; lua_pop( L, 1 ); }; std::cout << "\x1B[93m[Lua]\x1B[0m " << ret; return 0; } static int LuaDoFile( lua_State* L ) { int nArgs = lua_gettop(L); if ( nArgs == 0 ) { return -1; } const char* filename = lua_tostring( L, 1 ); string path = ""; lua_Debug entry; int depth = 1; while ( lua_getstack(L, depth, &entry) ) { lua_getinfo(L, "Slnu", &entry); // printf("%s(%d): %s\n", entry.source + 1, entry.currentline, entry.name ? entry.name : "?"); if ( entry.name and string(entry.name) == "loadtable" ) { depth++; continue; } string source = entry.source + 1; transform( source.begin(), source.end(), source.begin(), ::tolower ); // std::cout << "source : " << source; if ( source.find("/") != source.npos or source.find(".lua") != source.npos ) { path = entry.source + 1; auto end = path.rfind( "/" ); if ( end != path.npos ) { path = path.substr( 0, end ); } if ( path.rfind( "/" ) == path.npos ) { path = "."; } break; } depth++; } return Lua::states()[L]->do_file( filename, path ); } static uint32_t crc32_for_byte( uint32_t r ) { for( int j = 0; j < 8; ++j ) { r = ( r & 1 ? 0: (uint32_t)0xEDB88320L ) ^ r >> 1; } return r ^ (uint32_t)0xFF000000L; } static int LuaCRC32( lua_State* L ) { static uint32_t table[0x100] = { 0 }; if( !*table ) { for ( size_t i = 0; i < 0x100; ++i ) { table[i] = crc32_for_byte(i); } } size_t len = 0; uint8_t* data = (uint8_t*)lua_tolstring( L, 1, &len ); uint32_t crc = 0; for ( size_t i = 0; i < len; ++i ) { crc = table[ (uint8_t)crc ^ data[i] ] ^ crc >> 8; } lua_pushinteger( L, crc ); return 1; } static int LuaLoadFile( lua_State* L ) { int nArgs = lua_gettop(L); if ( nArgs == 0 ) { return -1; } const char* filename_ = lua_tostring( L, 1 ); string path = ""; lua_Debug entry; int depth = 1; while ( lua_getstack(L, depth, &entry) ) { lua_getinfo(L, "Sln", &entry); // printf("%s(%d): %s\n", entry.source + 1, entry.currentline, entry.name ? entry.name : "?"); if ( entry.name and string(entry.name) == "loadtable" ) { depth++; continue; } string source = entry.source + 1; transform( source.begin(), source.end(), source.begin(), ::tolower ); // std::cout << "source : " << source; if ( source.find("/") != source.npos or source.find(".lua") != source.npos ) { path = entry.source + 1; auto end = path.rfind( "/" ); if ( end != path.npos ) { path = path.substr( 0, end ); } if ( path.rfind( "/" ) == path.npos ) { path = "."; } break; } depth++; } int lua_top_base = lua_gettop( L ); string filename = filename_; if ( access( filename.c_str(), R_OK ) == -1 and filename[0] != '/' ) { if ( access( ( path + "/" + filename ).c_str(), R_OK ) == 0 ) { filename = path + "/" + filename; } else { filename = string("modules/") + filename; } } if ( access( filename.c_str(), R_OK ) == -1 ) { std::cout << "ERROR : " << "Cannot open file " << filename_ << " : " << strerror(errno); return -1; } int32_t ret = luaL_loadfilex( L, filename.c_str(), nullptr ); // printf("ret : %d\n", ret ); if ( ret != 0 ) { std::cout << "ERROR : " << lua_tostring( L, -1 ); return -1; } return 1; } int Lua::Traceback( lua_State* L ) { Lua* state = Lua::states()[L]; string trace_first = state->lastCallName(); auto print = [L, trace_first]( int depth, lua_Debug& entry ) { lua_getinfo( L, "Slnu", &entry ); string name = ( entry.name ? entry.name : ( trace_first == "" ? "??" : trace_first ) ); string args = ""; #ifdef LUAJIT_VERSION #else for ( uint32_t i = 0; i < entry.nparams; i++ ) { args += string(i == 0 ? "" : ", ") + lua_getlocal( L, &entry, i + 1 ); } #endif return string(" in ") + name + "(" + args + ") at " + entry.short_src + ":" + to_string(entry.currentline); }; std::cout << "ERROR : " << "Stack trace :"; lua_Debug entry; int depth = 1; while ( lua_getstack( L, depth, &entry ) ) { std::string line = print( depth, entry ); state->mLastError += line + "\n"; std::cout << "ERROR : " << line << "\n"; depth++; } // We did not unroll anything, so we print the very first entry if ( depth == 1 ) { int ret = lua_getstack( L, 1, &entry ); if ( ret == 1 ) { std::string line = print( 1, entry ); state->mLastError += line + "\n"; std::cout << "ERROR : " << line << "\n"; } } if ( Lua::states()[L]->exitOnError() ) { exit(0); } return 0; } int Lua::CallError( lua_State* L ) { // fDebug(); Lua* state = Lua::states()[L]; const char* message = lua_tostring( L, 1 ); std::cout << "ERROR : " << message << "\n"; state->mLastError += string(message) + "\n"; Lua::Traceback( L ); return 1; } LuaValue::FunctionRef::~FunctionRef() { // std::cout << "lua-function unref( " << mLua << ", LUA_REGISTRYINDEX, " << mRef << " )"; // mLua->mutex().lock(); luaL_unref( mLua->state(), LUA_REGISTRYINDEX, mRef ); // mLua->mutex().unlock(); } void LuaValue::FunctionRef::Unref() { mCounter--; if ( mCounter == 0 ) { delete this; } } LuaValue LuaValue::FunctionRef::Call( const vector<LuaValue>& args ) { return mLua->CallFunction( mRef, args ); } Lua::Lua( const string& load_path ) : mExitOnError( false ) { // fDebug( load_path ); mLuaState = luaL_newstate(); std::cout << "state : " << mLuaState; mStates.emplace( make_pair( mLuaState, this ) ); luaL_openlibs( mLuaState ); lua_register( mLuaState, "print", &LuaPrint ); lua_register( mLuaState, "debugprint", &LuaDebugPrint ); lua_register( mLuaState, "dofile", &LuaDoFile ); lua_register( mLuaState, "loadfile", &LuaLoadFile ); lua_register( mLuaState, "traceback", &Traceback ); lua_register( mLuaState, "call_error", &CallError ); lua_register( mLuaState, "crc32", &LuaCRC32 ); lua_register( mLuaState, "serialize", []( lua_State* L ) { LuaValue v = Lua::value( L, 1 ); LuaValue( v.serialize() ).push( L ); return 1; }); do_string( "package.path = \"lua/?.lua;\" .. package.path" ); do_string( "package.path = \"lua/?/init.lua;\" .. package.path" ); do_string( "package.path = \"lua/?/?/init.lua;\" .. package.path" ); do_string( "package.path = \"../lua/?.lua;\" .. package.path" ); do_string( "package.path = \"../lua/?/init.lua;\" .. package.path" ); do_string( "package.path = \"../lua/?/?/init.lua;\" .. package.path" ); do_string( "package.path = \"../libs/libluacore/lua/?.lua;\" .. package.path" ); do_string( "package.path = \"../libs/libluacore/lua/?/init.lua;\" .. package.path" ); do_string( "package.path = \"../libs/libluacore/lua/?/?/init.lua;\" .. package.path" ); do_string( "package.path = \"" + load_path + "/lua/?.lua;\" .. package.path" ); do_string( "package.path = \"" + load_path + "/lua/?/init.lua;\" .. package.path" ); do_string( "package.path = \"" + load_path + "/lua/?/?/init.lua;\" .. package.path" ); do_string( "package.path = \"" + load_path + "/../lua/?.lua;\" .. package.path" ); do_string( "package.path = \"" + load_path + "/../lua/?/init.lua;\" .. package.path" ); do_string( "package.path = \"" + load_path + "/../lua/?/?/init.lua;\" .. package.path" ); do_string( "package.path = \"" + load_path + "/../libs/libluacore/lua/?.lua;\" .. package.path" ); do_string( "package.path = \"" + load_path + "/../libs/libluacore/lua/?/init.lua;\" .. package.path" ); do_string( "package.path = \"" + load_path + "/../libs/libluacore/lua/?/?/init.lua;\" .. package.path" ); do_string( "package.path = \"" + load_path + "/../../libs/libluacore/lua/?.lua;\" .. package.path" ); do_string( "package.path = \"" + load_path + "/../../libs/libluacore/lua/?/init.lua;\" .. package.path" ); do_string( "package.path = \"" + load_path + "/../../libs/libluacore/lua/?/?/init.lua;\" .. package.path" ); do_string( "package.path = \"" + load_path + "/modules/?.lua;\" .. package.path" ); do_string( "package.path = \"" + load_path + "/../modules/?.lua;\" .. package.path" ); do_string( "package.path = \"modules/?.lua;\" .. package.path" ); do_string( "package.path = \"../modules/?.lua;\" .. package.path" ); if ( getenv("HOME") ) { do_string( std::string("package.path = \"") + getenv("HOME") + "/.luarocks/share/lua/5.1/?.lua;\" .. package.path" ); do_string( std::string("package.path = \"") + getenv("HOME") + "/.luarocks/share/lua/5.1/?/init.lua;\" .. package.path" ); do_string( std::string("package.path = \"") + getenv("HOME") + "/.luarocks/share/lua/5.1/?/?/init.lua;\" .. package.path" ); do_string( std::string("package.cpath = \"") + getenv("HOME") + "/.luarocks/lib/lua/5.1/?.so;\" .. package.cpath" ); } RegisterMember( "os", "sleep", []( const LuaValue& t ) { usleep( ( t.toNumber() * 1000.0f ) * 1000LLU ); return LuaValue(); }); RegisterMember( "io", "readFile", [this]( const LuaValue& filename ) { FILE* fp = fopen64( filename.toString().c_str(), "rb" ); if ( fp ) { fseeko64( fp, 0, SEEK_END ); size_t size = ftello64( fp ); fseeko64( fp, 0, SEEK_SET ); uint8_t* buf = new uint8_t[size]; fread( buf, 1, size, fp ); LuaValue ret = LuaValue( (const char*)buf, size ); delete[] buf; fclose( fp ); return ret; } return LuaValue(); }); RegisterMember( "string", "lower", [this]( const LuaValue& v ) { string s1 = v.toString(); string s2 = ""; unsigned char* data = (unsigned char*)s1.data(); for ( uint32_t i = 0; i < s1.length(); i++ ) { if ( data[i] >= 'A' and data[i] <= 'Z' ) { s2 += ( data[i] + 'a' - 'A' ); } else if ( data[i] == 0xC3 and data[i + 1] >= 0x80 and data[i + 1] <= 0x9F ) { s2 += 0xC3; s2 += data[i + 1] + 32; i++; } else { s2 += data[i]; } } return LuaValue( s2 ); }); RegisterMember( "string", "upper", [this]( const LuaValue& v ) { string s1 = v.toString(); string s2 = ""; unsigned char* data = (unsigned char*)s1.data(); for ( uint32_t i = 0; i < s1.length(); i++ ) { if ( data[i] >= 'a' and data[i] <= 'z' ) { s2 += ( data[i] + 'A' - 'a' ); } else if ( data[i] == 0xC3 and data[i + 1] >= 0xA0 and data[i + 1] <= 0xBF ) { s2 += 0xC3; s2 += data[i + 1] - 32; i++; } else { s2 += data[i]; } } return LuaValue( s2 ); }); Reload(); } Lua::~Lua() { } void Lua::Reload() { } vector<lua_Debug> Lua::trace() { const std::lock_guard<std::mutex> lock(mMutex); vector<lua_Debug> ret; lua_Debug entry; int depth = 0; while ( lua_getstack( mLuaState, depth, &entry ) ) { lua_getinfo( mLuaState, "nSlu", &entry ); ret.emplace_back( entry ); depth++; } return ret; } int32_t Lua::do_file( const string& filename_, const string& path_tip ) { // fDebug( filename_, path_tip ); // mMutex.lock(); string filename = filename_; if ( access( filename.c_str(), R_OK ) == -1 and filename[0] != '/' ) { list<string> pathTips = mPathTips; pathTips.push_back( path_tip ); bool found = false; for ( string tip : pathTips ) { std::cout << "Testing with '" << ( tip + "/" + filename ) << "' and '" << ( tip + filename ) << "'\n"; if ( access( ( tip + "/" + filename ).c_str(), R_OK ) == 0 ) { filename = tip + "/" + filename; found = true; break; } else if ( access( ( tip + filename ).c_str(), R_OK ) == 0 ) { filename = tip + filename; found = true; break; } } if ( not found ) { filename = string("modules/") + filename; } } lua_getglobal( mLuaState, "call_error" ); int lua_top_base = lua_gettop( mLuaState ); // fDebug( filename_, path_tip, " => " + filename ); if ( access( filename.c_str(), R_OK ) == -1 ) { std::cout << "ERROR : " << "Cannot open file " << filename_ << " : " << strerror(errno) << "\n"; mMutex.unlock(); return -1; } // std::cout << "luaL_loadfilex( mLuaState, " << filename << ", nullptr )"; int32_t ret = luaL_loadfilex( mLuaState, filename.c_str(), nullptr ); if ( ret != 0 ) { std::cout << "ERROR : " << lua_tostring( mLuaState, -1 ) << "\n"; mMutex.unlock(); return -1; } mLastCallName = ""; ret = lua_pcall( mLuaState, 0, LUA_MULTRET, -2 ); if ( ret != 0 ) { std::cout << "ERROR : " << lua_tostring( mLuaState, -1 ) << "\n"; mMutex.unlock(); return -1; } else { if ( mOpenedFiles.count( filename ) == 0 ) { mOpenedFiles.emplace( filename ); } int32_t ret = lua_gettop( mLuaState ) - lua_top_base; mMutex.unlock(); return ret; } // mMutex.unlock(); return ret; /* string filename = filename_; if ( access( filename.c_str(), F_OK ) == -1 and filename[0] != '/' ) { filename = string("modules/") + filename; } luaL_loadfilex( mLuaState, filename.c_str(), nullptr ); int32_t ret = lua_pcall( mLuaState, 0, LUA_MULTRET, 0 ); if ( ret != 0 ) { std::cout << "ERROR : " << lua_tostring( mLuaState, -1 ); return -1; } return ret; */ } int32_t Lua::do_string( const string& str ) { const std::lock_guard<std::mutex> lock(mMutex); lua_getglobal( mLuaState, "call_error" ); luaL_loadstring( mLuaState, str.c_str() ); mLastCallName = ""; int32_t ret = lua_pcall( mLuaState, 0, 0, -2 ); return ret; } LuaValue Lua::value( lua_State* L, int index ) { int type = lua_type( L, index ); if ( type == LUA_TNUMBER and fmod((float)lua_tonumber(L, index), 1.0f) == 0.0f ) { return LuaValue( lua_tointeger( L, index ) ); } else if ( type == LUA_TNUMBER ) { return lua_tonumber( L, index ); } else if ( type == LUA_TBOOLEAN ) { return LuaValue::boolean( lua_toboolean( L, index ) ); } else if ( type == LUA_TSTRING ) { size_t len = 0; auto ret = lua_tolstring( L, index, &len ); return LuaValue( ret, len ); } else if ( type == LUA_TFUNCTION ) { // mMutex.lock(); LuaValue ret; lua_pushvalue( L, index ); ret.setFunctionRef( mStates[L], luaL_ref( L, LUA_REGISTRYINDEX ) ); // mMutex.unlock(); return ret; } else if ( lua_iscfunction( L, index ) ) { } else if ( type == LUA_TUSERDATA or type == LUA_TLIGHTUSERDATA ) { LuaValue ret = lua_touserdata( L, index ); return ret; } else if ( type == LUA_TTABLE ) { LuaValue table = LuaValue(std::map<string, string>()); size_t len = lua_objlen( L, index ); if ( len > 0 ) { for ( size_t i = 1; i <= len; i++ ) { lua_rawgeti( L, index, i ); if ( not lua_isfunction( L, -1 ) ) { LuaValue v = value( L, -1 ); table[i] = v; } lua_pop( L, 1 ); } } else { bool istop = ( index > 0 ); if ( istop ) { lua_pushvalue( L, index ); } lua_pushnil( L ); while( lua_next( L, -2 ) != 0 ) { const char* key_ = lua_tostring( L, -2 ); if ( key_ ) { std::string key = key_; // bool dont_pop = lua_isfunction( L, -1 );// or lua_iscfunction( L, -1 ); // if ( /*not lua_isfunction( L, -1 ) and not lua_iscfunction( L, -1 ) and*/ key != "class" and key != "super" ) { if ( /*not lua_isfunction( L, -1 ) and not lua_iscfunction( L, -1 ) and*/ key != "super" and key != "self" and key.substr(0, 2) != "__" ) { table[key] = value( L, -1 ); } else { // dont_pop = false; } // if ( not dont_pop ) { lua_pop( L, 1 ); // } } } if ( istop ) { lua_pop( L, 1 ); } } return table; } return LuaValue(); } LuaValue Lua::value( const string& name ) { const std::lock_guard<std::mutex> lock(mMutex); int top = lua_gettop( mLuaState ); if ( LocateValue( name ) < 0 ) { // std::cout << "Lua variable \"" << name << "\" not found\n"; lua_settop( mLuaState, top ); return LuaValue(); } LuaValue ret = value( mLuaState, -1 ); lua_settop( mLuaState, top ); return ret; } LuaValue Lua::value( int index, lua_State* L ) { const std::lock_guard<std::mutex> lock(mMutex); if ( not L ) { L = mLuaState; } return value( L, index ); } std::vector<string> Lua::valueKeys( lua_State* L, int index ) { std::vector<string> ret; const auto listKeys = [L, &ret]() { lua_pushnil( L ); while ( lua_next( L, -2 ) != 0 ) { const char* key = lua_tostring( L, -2 ); ret.push_back( string(key) ); lua_pop( L, 1 ); } }; if ( lua_type( L, index ) == LUA_TTABLE ) { bool istop = ( index > 0 ); if ( istop ) { lua_pushvalue( L, index ); } listKeys(); if ( istop ) { lua_pop( L, 1 ); } } if ( lua_type( L, index ) == LUA_TTABLE or lua_type( L, index ) == LUA_TUSERDATA ) { lua_getmetatable( L, index ); if ( lua_type( L, -1 ) == LUA_TTABLE ) { lua_getfield( L, -1, "__index" ); if ( lua_type( L, -1 ) == LUA_TTABLE ) { listKeys(); } } lua_pop( L, 1 ); } return ret; } std::vector<string> Lua::valueKeys( const string& name ) { const std::lock_guard<std::mutex> lock(mMutex); if ( LocateValue( name ) < 0 ) { // std::cout << "Lua variable \"" << name << "\" not found\n"; return std::vector<string>(); } return valueKeys( mLuaState, -1 ); } int32_t _lua_bridge( lua_State* L ) { int32_t argc = lua_gettop(L); vector<LuaValue> args; args.resize( argc ); for ( int32_t i = 0; i < argc; i++ ) { // args[i] = mStates[L]->value( i + 1 ); lua_pushvalue( L, i + 1 ); bool dont_pop = lua_isfunction( L, -1 ); args[i] = Lua::states()[L]->value( -1 ); if ( not dont_pop ) { lua_pop( L, 1 ); } } const function<LuaValue(const vector<LuaValue>&)>& fnptr = *static_cast <const function<LuaValue(const vector<LuaValue>&)>*>( lua_touserdata( L, lua_upvalueindex(1) ) ); LuaValue ret = fnptr( args ); ret.push( L ); return 1; } int32_t _lua_bridge_raw( lua_State* L ) { const function<int(lua_State*)>& fnptr = *static_cast <const function<int(lua_State*)>*>( lua_touserdata( L, lua_upvalueindex(1) ) ); return fnptr( L ); } int32_t Lua::RegisterFunction( const string& name, const function<LuaValue(const vector<LuaValue>&)>& func ) { const std::lock_guard<std::mutex> lock(mMutex); new (lua_newuserdata( mLuaState, sizeof(function<LuaValue(const vector<LuaValue>&)>) ) ) function<LuaValue(const vector<LuaValue>&)> (func); lua_pushcclosure( mLuaState, &_lua_bridge, 1 ); lua_setglobal( mLuaState, name.c_str() ); return 0; } int32_t Lua::RegisterMember( const string& object, const string& name, const function<LuaValue(const vector<LuaValue>&)>& func ) { const std::lock_guard<std::mutex> lock(mMutex); if ( LocateValue( object ) < 0 ) { return -1; } new (lua_newuserdata( mLuaState, sizeof(function<LuaValue(const vector<LuaValue>&)>) ) ) function<LuaValue(const vector<LuaValue>&)> (func); lua_pushcclosure( mLuaState, &_lua_bridge, 1 ); lua_setfield( mLuaState, -2, name.c_str() ); return 0; } LuaValue Lua::CallFunction( const string& func, const vector<LuaValue>& args ) { const std::lock_guard<std::mutex> lock(mMutex); int nArgs = args.size(); char* funcname = strdup( func.c_str() ); lua_getglobal( mLuaState, "call_error" ); int lua_top_base = lua_gettop( mLuaState ); /* if ( !strchr(funcname, '.') && !strchr(funcname, ':') ) { lua_getglobal( mLuaState, funcname ); } else { char tmp[128]; int i, j, k; bool method = false; for ( i=0, j=0, k=0; funcname[i]; i++ ) { if ( funcname[i] == '.' || funcname[i] == ':' || funcname[i] == '[' || funcname[i] == ']' ) { if ( j == 0 ) { continue; } tmp[j] = 0; if ( k == 0 ) { lua_getglobal( mLuaState, tmp ); }else{ lua_getfield( mLuaState, -1, tmp ); // lua_remove( mLuaState, -2); } memset( tmp, 0, sizeof(tmp)); j = 0; k++; method = (funcname[i] == ':'); } else { tmp[j] = funcname[i]; j++; } } tmp[j] = 0; if ( j > 0 ) { lua_getfield( mLuaState, -1, tmp ); } else { lua_remove( mLuaState, -2 ); } if ( method ) { nArgs++; } } */ int found = LocateValue( func ); if ( found < 0 ) { std::cout << "WARNING : " << "Lua function not found : " << func; return LuaValue(); } for( const LuaValue& v : args ) { v.push( mLuaState ); } LuaValue value_ret; if ( strstr( funcname, ":" ) ) { strstr( funcname, ":" )[0] = 0; } mLastCallName = funcname; free( funcname ); int ret = lua_pcall( mLuaState, nArgs, LUA_MULTRET, -2 - nArgs ); if ( ret != 0 ) { std::cout << "ERROR : " << lua_tostring( mLuaState, -1 ); lua_pop( mLuaState, -1 ); } else { int32_t nRets = ( lua_gettop( mLuaState ) - 1 ) - lua_top_base; if ( nRets == 1 ) { value_ret = value( -1 ); } else if ( nRets > 1 ) { for ( int32_t i = 0; i < nRets; i++ ) { value_ret[nRets - i - 1] = value( -1 - i ); } } lua_pop( mLuaState, nRets ); } // lua_pop( mLuaState, -1 ); return value_ret; } LuaValue Lua::CallFunction( int32_t registry_index, const vector<LuaValue>& args ) { mMutex.lock(); int top = lua_gettop( mLuaState ); mLastError = ""; lua_getglobal( mLuaState, "call_error" ); int lua_top_base = lua_gettop( mLuaState ); int nArgs = args.size(); lua_rawgeti( mLuaState, LUA_REGISTRYINDEX, registry_index ); for( const LuaValue& v : args ) { v.push( mLuaState ); } LuaValue value_ret; /* lua_Debug dbg; lua_getstack( mLuaState, 0, &dbg ); if ( strstr( funcname, ":" ) ) { strstr( funcname, ":" )[0] = 0; } dbg.name = funcname; free( funcname ); */ mLastCallName = ""; int ret = lua_pcall( mLuaState, nArgs, LUA_MULTRET, -2 - nArgs ); if ( ret != 0 ) { // std::cout << "ERROR : " << "(" << ret << ") " << lua_tostring( mLuaState, -1 ); lua_pop( mLuaState, -1 ); } else { int32_t nRets = lua_gettop( mLuaState ) - lua_top_base; if ( nRets == 1 ) { value_ret = value( -1, mLuaState ); } else if ( nRets > 1 ) { for ( int32_t i = 0; i < nRets; i++ ) { value_ret[nRets - i - 1] = value( -1 - i, mLuaState ); printf( "value_ret[%d] = \"%s\"\n", nRets-i-1, value_ret[nRets - i - 1].toString().c_str() ); } } lua_pop( mLuaState, nRets ); } // lua_pop( mLuaState, -1 ); lua_settop( mLuaState, top ); mMutex.unlock(); return value_ret; } int Lua::LocateValue( const string& _name ) { const char* name = _name.c_str(); int top = lua_gettop( mLuaState ); if ( strchr( name, '.' ) == nullptr and strchr( name, ':' ) == nullptr and strchr( name, '[' ) == nullptr ) { lua_getglobal( mLuaState, name ); if ( lua_type( mLuaState, -1 ) == LUA_TNIL ) { lua_settop( mLuaState, top ); return -1; } } else { char tmp[128]; int i=0, j, k; bool in_table = false; for ( i = 0, j = 0, k = 0; name[i]; i++ ) { if ( name[i] == '.' or name[i] == ':' or name[i] == '[' or name[i] == ']' ) { tmp[j] = 0; if ( strlen(tmp) == 0 ) { j = 0; k++; continue; } if ( name[i] == '[' ) { in_table = true; } if ( in_table and name[i] == ']' and lua_istable( mLuaState, -1 ) ) { if ( tmp[0] >= '0' and tmp[0] <= '9' ) { lua_rawgeti( mLuaState, -1, atoi(tmp) ); } else { lua_getfield( mLuaState, -1, tmp ); } } else { if ( k == 0 ) { lua_getglobal( mLuaState, tmp ); } else { lua_getfield( mLuaState, -1, tmp ); } } if ( lua_type( mLuaState, -1 ) == LUA_TNIL ) { lua_settop( mLuaState, top ); return -1; } memset( tmp, 0, sizeof( tmp ) ); j = 0; k++; } else { tmp[j] = name[i]; j++; } } tmp[j] = 0; if ( tmp[0] != 0 ) { lua_getfield( mLuaState, -1, tmp ); if ( lua_type( mLuaState, -1 ) == LUA_TNIL ) { lua_settop( mLuaState, top ); return -1; } } } lua_pushvalue( mLuaState, -1 ); lua_replace( mLuaState, top + 1 ); lua_settop( mLuaState, top + 1 ); return 0; }
25,459
C++
.cpp
847
27.252656
170
0.58332
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,796
LuaInterface.cpp
dridri_bcflight/libluacore/src/LuaInterface.cpp
#include "LuaInterface.h" void LuaInterface::PreInit() { lua_State* L = mLua->state(); *reinterpret_cast<LuaInterface**>( lua_newuserdata( L, sizeof(LuaInterface*) ) ) = this; lua_pushvalue( L, -1 ); // mInstanceRef = luaL_ref( L, LUA_REGISTRYINDEX ); mType = Reference; mReference[L] = luaL_ref( L, LUA_REGISTRYINDEX ); lua_createtable( L, 0, 0 ); lua_createtable( L, 0, 0 ); lua_createtable( L, 0, 0 ); lua_getglobal( L, mClassName.c_str() ); lua_getfield( L, -1, "__index" ); lua_setfield( L, -3, "__index" ); lua_pop( L, 1 ); lua_setmetatable( L, -2 ); lua_setfield( L, -2, "__index" ); lua_getfield( L, -1, "__index" ); lua_setfield( L, -2, "__newindex" ); lua_setmetatable( L, -2 ); } LuaInterface::~LuaInterface() { } LuaValue LuaInterface::CallMember( const string& funcname, const vector<LuaValue>& args ) { lua_State* L = mLua->state(); mLua->mutex().lock(); int nArgs = args.size() + 1; lua_getglobal( L, "call_error" ); int lua_top_base = lua_gettop( L ); lua_rawgeti( L, LUA_REGISTRYINDEX, mReference[L] ); lua_getfield( L, -1, funcname.c_str() ); lua_pushvalue( L, -2 ); for( const LuaValue& v : args ) { v.push( L ); } LuaValue value_ret; int ret = lua_pcall( L, nArgs, LUA_MULTRET, -3 - nArgs ); if ( ret != 0 ) { std::cout << "ERROR : " << lua_tostring( L, -1 ); lua_pop( L, -1 ); } else { int32_t nRets = ( lua_gettop( L ) - 1 ) - lua_top_base; if ( nRets == 1 ) { value_ret = mLua->value( -1 ); } else if ( nRets > 1 ) { for ( int32_t i = 0; i < nRets; i++ ) { value_ret[nRets - i - 1] = mLua->value( -1 - i ); } } lua_pop( L, nRets ); } lua_pop( L, 1 ); // closing lua_rawgeti mLua->mutex().unlock(); return value_ret; }
1,742
C++
.cpp
58
27.310345
89
0.601796
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,797
main.cpp
dridri_bcflight/joystick/main.cpp
#include <iostream> #include <cmath> #include <unistd.h> #include <limits.h> #include <string.h> #include <fcntl.h> #include <linux/joystick.h> #include <linux/uinput.h> #include <libudev.h> #include "Socket.h" static int create_joystick() { int fd = open( "/dev/uinput", O_WRONLY | O_NONBLOCK ); ioctl( fd, UI_SET_EVBIT, EV_KEY ); ioctl( fd, UI_SET_KEYBIT, BTN_A ); ioctl( fd, UI_SET_EVBIT, EV_ABS ); ioctl( fd, UI_SET_ABSBIT, ABS_X ); ioctl( fd, UI_SET_ABSBIT, ABS_Y ); ioctl( fd, UI_SET_ABSBIT, ABS_Z ); ioctl( fd, UI_SET_ABSBIT, ABS_THROTTLE ); struct uinput_user_dev uidev; memset( &uidev, 0, sizeof(uidev) ); snprintf( uidev.name, UINPUT_MAX_NAME_SIZE, "BeyondChaos Flight Controller" ); uidev.id.bustype = BUS_USB; uidev.id.vendor = 3; uidev.id.product = 3; uidev.id.version = 2; for ( int i = 0; i < ABS_CNT; i++ ) { uidev.absmax[i] = 32767; uidev.absmin[i] = -32767; uidev.absfuzz[i] = 0; uidev.absflat[i] = 15; } write( fd, &uidev, sizeof(uidev) ); ioctl( fd, UI_DEV_CREATE ); return fd; } typedef struct { int8_t throttle; int8_t roll; int8_t pitch; int8_t yaw; } __attribute__((packed)) ControllerData; int main( int argc, char **argv ) { int uifd = create_joystick(); struct input_event evt; Socket* sock = new Socket( "192.168.32.2", 5000 ); ControllerData data; while ( 1 ) { while ( not sock->isConnected() and sock->Connect() < 0 ) { usleep( 1000 * 1000 * 4 ); } sock->Receive( &data, sizeof(data) ); memset( &evt, 0, sizeof(struct input_event) ); evt.type = EV_ABS; evt.code = ABS_THROTTLE; evt.value = ( (int16_t)data.throttle * 255 ) * 2 - 32767; write( uifd, &evt, sizeof(evt) ); memset( &evt, 0, sizeof(struct input_event) ); evt.type = EV_ABS; evt.code = ABS_X; evt.value = ( (int16_t)data.roll * 255 ); write( uifd, &evt, sizeof(evt) ); memset( &evt, 0, sizeof(struct input_event) ); evt.type = EV_ABS; evt.code = ABS_Y; evt.value = ( (int16_t)data.pitch * 255 ); write( uifd, &evt, sizeof(evt) ); memset( &evt, 0, sizeof(struct input_event) ); evt.type = EV_ABS; evt.code = ABS_Z; evt.value = ( (int16_t)data.yaw * 255 ); write( uifd, &evt, sizeof(evt) ); } return 0; }
2,201
C++
.cpp
77
26.220779
79
0.652587
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,798
Socket.cpp
dridri_bcflight/joystick/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 ) */ Socket::Socket() : mSocketType( Client ) , mPort( 0 ) , mPortType( TCP ) , mSocket( -1 ) { } Socket::Socket( uint16_t port, PortType type ) : mSocketType( Server ) , mPort( port ) , mPortType( type ) , mSocket( -1 ) { } Socket::Socket( const std::string& host, uint16_t port, PortType type ) : mSocketType( Client ) , mHost( host ) , mPort( port ) , mPortType( type ) , mSocket( -1 ) { } Socket::~Socket() { if ( mSocket >= 0 ) { shutdown( mSocket, 2 ); closesocket( mSocket ); } } bool Socket::isConnected() const { return ( mSocket >= 0 ); } int 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 << "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 << "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; } Socket* 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 ); if ( clientFD >= 0 ) { Socket* client = new Socket(); client->mSocket = clientFD; client->mSin = clientSin; return client; } } else { close( mSocket ); } } return nullptr; } int 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 << "Socket on port " << mPort << " disconnected ( " << ret << " : " << errno << ", " << strerror( errno ) << " )\n"; close( mSocket ); mSocket = -1; return -1; } return ret; } int 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 << "Socket on port " << mPort << " disconnected\n"; close( mSocket ); mSocket = -1; return -1; } return ret; }
4,937
C++
.cpp
173
25.878613
128
0.63139
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,799
Stream.cpp
dridri_bcflight/controller_pc/Stream.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 <GL/gl.h> #include <QtCore/QDebug> #include <QtGui/QPainter> #include "Stream.h" #include "MainWindow.h" #include "ControllerPC.h" #include "ui_mainWindow.h" #include "Socket.h" #if ( defined(WIN32) && !defined(glActiveTexture) ) PFNGLACTIVETEXTUREPROC glActiveTexture = 0; #endif Stream::Stream( QWidget* parent ) : QGLWidget( parent ) , mStreamThread( new StreamThread( this ) ) , mAudioThread( new AudioThread( this ) ) , mMainWindow( nullptr ) , mLink( nullptr ) , mAudioLink( nullptr ) , mSocketTellIPCounter( 0 ) , mWidth( 0 ) , mHeight( 0 ) , mShader( nullptr ) , mFpsCounter( 0 ) , mFps( 0 ) , mFpsTimer( QElapsedTimer() ) , mParentWidget( parent ) { memset( &mY, 0, sizeof(mY) ); memset( &mU, 0, sizeof(mU) ); memset( &mV, 0, sizeof(mV) ); #ifdef WIN32 if ( glActiveTexture == 0 ) { glActiveTexture = (PFNGLACTIVETEXTUREPROC)GetProcAddress( LoadLibrary("opengl32.dll"), "glActiveTexture" ); } #endif mAudioDevice = QAudioDeviceInfo::defaultOutputDevice(); mAudioFormat.setChannelCount( 1 ); mAudioFormat.setCodec( "audio/pcm" ); mAudioFormat.setSampleRate( 44100 ); mAudioFormat.setByteOrder( QAudioFormat::LittleEndian ); mAudioFormat.setSampleType( QAudioFormat::SignedInt ); mAudioFormat.setSampleSize( 16 ); mAudioOutput = new QAudioOutput( mAudioDevice, mAudioFormat ); mAudioStream = mAudioOutput->start(); mStreamThread->start(); mAudioThread->start(); mStreamThread->setPriority( QThread::TimeCriticalPriority ); mAudioThread->setPriority( QThread::TimeCriticalPriority ); connect( this, SIGNAL( repaintEmitter() ), this, SLOT( repaintReceiver() ) ); qDebug() << "WelsCreateDecoder :" << WelsCreateDecoder( &mDecoder ); SDecodingParam decParam; memset( &decParam, 0, sizeof (SDecodingParam) ); decParam.uiTargetDqLayer = UCHAR_MAX; decParam.eEcActiveIdc = ERROR_CON_SLICE_MV_COPY_CROSS_IDR_FREEZE_RES_CHANGE; //ERROR_CON_SLICE_MV_COPY_CROSS_IDR;//ERROR_CON_SLICE_COPY; decParam.sVideoProperty.eVideoBsType = VIDEO_BITSTREAM_AVC; qDebug() << "mDecoder->Initialize :" << mDecoder->Initialize( &decParam ); } Stream::~Stream() { mDecoder->Uninitialize(); WelsDestroyDecoder( mDecoder ); } void Stream::setMainWindow( MainWindow* win ) { mMainWindow = win; } void Stream::setLink( Link* l ) { mLink = l; } void Stream::setAudioLink( Link* l ) { mAudioLink = l; } int32_t Stream::fps() { return mFps; } void Stream::mouseDoubleClickEvent( QMouseEvent * e ) { if ( e->button() == Qt::LeftButton ) { if ( !isFullScreen() ) { setParent( nullptr ); showFullScreen(); mMainWindow->getUi()->tab->repaint(); } else { if ( mMainWindow ) { showNormal(); mMainWindow->getUi()->video_container->layout()->addWidget( this ); } } } } void Stream::closeEvent( QCloseEvent* e ) { if ( isFullScreen() and mMainWindow ) { showNormal(); mMainWindow->getUi()->video_container->layout()->addWidget( this ); } e->ignore(); } /* void Stream::paintEvent( QPaintEvent* ev ) { QPainter p( this ); // p.fillRect( QRect( 0, 0, width(), height() ), QBrush( QColor( 16, 16, 16 ) ) ); // mMutex.lock(); // p.drawImage( 0, 0, mImage ); // mMutex.unlock(); if ( mY.width > 0 and mY.height > 0 and mY.data != 0 ) { for ( int y = 0; y < mY.height; y++ ) { for ( int x = 0; x < mY.width; x++ ) { const int xx = x >> 1; const int yy = y >> 1; const int Y = mY.data[y * mY.stride + x] - 16; const int U = mU. data[yy * mU.stride + xx] - 128; const int V = mV.data[yy * mV.stride + xx] - 128; const int r = qBound(0, (298 * Y + 409 * V + 128) >> 8, 255); const int g = qBound(0, (298 * Y - 100 * U - 208 * V + 128) >> 8, 255); const int b = qBound(0, (298 * Y + 516 * U + 128) >> 8, 255); // p.setBrush( QBrush( QColor( r, g, b ) ) ); // p.drawPoint( x, y ); } } } } */ void Stream::paintGL() { if ( not mShader ) { mShader = new QGLShaderProgram(); mShader->addShaderFromSourceCode( QGLShader::Vertex, R"( attribute highp vec2 vertex; attribute highp vec2 tex; varying vec2 texcoords; void main(void) { texcoords = vec2( tex.s, 1.0 - tex.t ); gl_Position = vec4( vertex, 0.0, 1.0 ); })" ); mShader->addShaderFromSourceCode( QGLShader::Fragment, R"( uniform sampler2D texY; uniform sampler2D texU; // uniform sampler2D texV; uniform float exposure_value; uniform float gamma_compensation; varying vec2 texcoords; vec4 fetch( vec2 coords ) { float y = 2.0 * texture2D( texY, coords ).r; float u = 2.0 * (texture2D( texU, coords * vec2(1.0, 0.5) + vec2(0.0, 0.0) ).r - 0.5); float v = 2.0 * (texture2D( texU, coords * vec2(1.0, 0.5) + vec2(0.0, 0.5) ).r - 0.5); float r = (y/2.0 + 1.402/2.0 * v); float g = (y/2.0 - 0.344136 * u/2.0 - 0.714136 * v/2.0); float b = (y/2.0 + 1.773/2.0 * u); return clamp( vec4( r, g, b, 1.0 ), vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0) ); } void main(void) { vec4 color = fetch( texcoords.st ); // color.rgb = vec3(1.0) - exp( -color.rgb * vec3(exposure_value, exposure_value, exposure_value) ); // color.rgb = pow( color.rgb, vec3( 1.0 / gamma_compensation, 1.0 / gamma_compensation, 1.0 / gamma_compensation ) ); gl_FragColor = color; gl_FragColor.a = 1.0; })" ); /* mShader->addShaderFromSourceCode( QGLShader::Fragment, R"( uniform sampler2D texY; uniform sampler2D texU; // uniform sampler2D texV; uniform float exposure_value; uniform float gamma_compensation; varying vec2 texcoords; vec4 fetch( vec2 coords ) { float y = 2*texture2D( texY, coords ).r; float u = 2*(texture2D( texU, coords * vec2(1.0, 0.5) + vec2(0.0, 0.0) ).r - 0.5); float v = 2*(texture2D( texU, coords * vec2(1.0, 0.5) + vec2(0.0, 0.5) ).r - 0.5); float r = 2*(y/2 + 1.402/2 * v); float g = 2*(y/2 - 0.344136 * u/2 - 0.714136 * v/2); float b = 2*(y/2 + 1.773/2 * u); return clamp( vec4( r, g, b, 1.0 ), vec4(0.0), vec4(1.0) ); } void main(void) { vec4 center = fetch( texcoords.st ); // vec4 top = fetch( texcoords.st + vec2( 0.0, -0.00001 ) ); // vec4 bottom = fetch( texcoords.st + vec2( 0.0, +0.00001 ) ); // vec4 left = fetch( texcoords.st + vec2( -0.00001, 0.0 ) ); // vec4 right = fetch( texcoords.st + vec2( +0.00001, 0.0 ) ); gl_FragColor = center;// * 5.0 - top - left - bottom - right; gl_FragColor.rgb = vec3(1.0) - exp( -gl_FragColor.rgb * vec3(exposure_value) ); gl_FragColor.rgb = pow( gl_FragColor.rgb, vec3( 1.0 / gamma_compensation ) ); })" ); */ mShader->link(); mShader->bind(); mExposureID = mShader->uniformLocation( "exposure_value" ); mGammaID = mShader->uniformLocation( "gamma_compensation" ); } // if ( mY.tex == 0 and mU.tex == 0 and mV.tex == 0 and mY.stride > 0 and mY.height > 0 ) { if ( mY.tex == 0 or mU.tex == 0 or mY.stride != mWidth or mY.height != mHeight ) { if ( mY.tex ) { glDeleteTextures( 1, &mY.tex ); } if ( mU.tex ) { glDeleteTextures( 1, &mU.tex ); } mWidth = mY.stride; mHeight = mY.height; printf( "====> SIZE : %d x %d\n", mY.stride, mY.height ); glGenTextures( 1, &mY.tex ); glBindTexture( GL_TEXTURE_2D, mY.tex ); glTexImage2D( GL_TEXTURE_2D, 0, GL_R8, mY.stride, mY.height, 0, GL_RED, GL_UNSIGNED_BYTE, NULL ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); glGenTextures( 1, &mU.tex ); glBindTexture( GL_TEXTURE_2D, mU.tex ); glTexImage2D( GL_TEXTURE_2D, 0, GL_R8, mU.stride, mU.height + mV.height, 0, GL_RED, GL_UNSIGNED_BYTE, NULL ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); } glViewport( 0, 0, width(), height() ); glClear( GL_COLOR_BUFFER_BIT ); static float quadVertices[] = { // X, Y, U, V 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, }; quadVertices[2] = (float)mY.width / (float)mY.stride; quadVertices[6] = (float)mY.width / (float)mY.stride; mShader->bind(); glBindTexture( GL_TEXTURE_2D, 0 ); if ( not mY.data or not mU.data or not mV.data ) { return; } int vertexLocation = mShader->attributeLocation( "vertex" ); int texLocation = mShader->attributeLocation( "tex" ); mShader->enableAttributeArray( vertexLocation ); mShader->enableAttributeArray( texLocation ); mShader->setAttributeArray( vertexLocation, quadVertices, 2, sizeof(float)*4 ); mShader->setAttributeArray( texLocation, quadVertices + 2, 2, sizeof(float)*4 ); int loc_Y = mShader->uniformLocation( "texY" ); int loc_U = mShader->uniformLocation( "texU" ); // int loc_V = mShader->uniformLocation( "texV" ); mShader->setUniformValue( loc_Y, 0 ); mShader->setUniformValue( loc_U, 1 ); // mShader->setUniformValue( loc_V, 2 ); if ( mMainWindow and mMainWindow->controller() and mMainWindow->controller()->nightMode() ) { mShader->setUniformValue( mExposureID, 4.0f ); mShader->setUniformValue( mGammaID, 2.5f ); } else { mShader->setUniformValue( mExposureID, 1.0f ); mShader->setUniformValue( mGammaID, 1.0f ); } glActiveTexture( GL_TEXTURE0 ); glEnable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, mY.tex ); glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, mY.stride, mY.height, GL_RED, GL_UNSIGNED_BYTE, mY.data ); glActiveTexture( GL_TEXTURE1 ); glEnable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, mU.tex ); uint8_t* d = new uint8_t[ ( mU.stride * mU.height + mU.stride * mV.height ) * 2 ]; memcpy( d, mU.data, mU.stride * mU.height ); memcpy( d + mU.stride * mU.height, mV.data, mU.stride * mV.height ); glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, mU.stride, mU.height + mV.height, GL_RED, GL_UNSIGNED_BYTE, d ); delete d; glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); mShader->disableAttributeArray( vertexLocation ); mShader->disableAttributeArray( texLocation ); } void Stream::repaintReceiver() { repaint(); } bool Stream::run() { if ( not mLink ) { usleep( 1000 * 10 ); return true; } if ( not mLink->isConnected() ) { mLink->Connect(); if ( mLink->isConnected() ) { struct sched_param sched; memset( &sched, 0, sizeof(sched) ); sched.sched_priority = sched_get_priority_max( SCHED_RR ); sched_setscheduler( 0, SCHED_RR, &sched ); mFpsTimer.start(); } else { usleep( 1000 * 500 ); } return true; } if ( ( mSocketTellIPCounter = ( ( mSocketTellIPCounter + 1 ) % 16 ) ) == 1 ) { // Dummy write to tell own IP address in case of Socket if ( dynamic_cast<Socket*>( mLink ) ) { uint32_t uid = htonl( 0x12345678 ); mLink->Write( &uid, sizeof(uid), 0, -1 ); } } uint8_t data[65536 * 4] = { 0 }; int32_t size = mLink->Read( data, sizeof( data ), 50 ); if ( size > 0 ) { if ( size == 65000 ) { int32_t size2 = mLink->Read( &data[65000], sizeof( data ) - 65000, 50 ); size += size2; if ( size2 == 65000 ) { int32_t size3 = mLink->Read( &data[65000 * 2], sizeof( data ) - 65000 * 2, 50 ); size += size3; } } DecodeFrame( data, size ); if ( size > 41 ) { mFpsCounter++; } } if ( mFpsTimer.elapsed() >= 1000 ) { mFps = mFpsCounter; mFpsCounter = 0; mFpsTimer.restart(); } return true; } bool Stream::runAudio() { if ( not mAudioLink ) { usleep( 1000 * 10 ); return true; } if ( not mAudioLink->isConnected() ) { mAudioLink->Connect(); if ( mAudioLink->isConnected() ) { struct sched_param sched; memset( &sched, 0, sizeof(sched) ); sched.sched_priority = sched_get_priority_max( SCHED_RR ); sched_setscheduler( 0, SCHED_RR, &sched ); } else { usleep( 1000 * 500 ); } return true; } uint8_t data[65536] = { 0 }; int32_t size = mAudioLink->Read( data, sizeof( data ), 0 ); if ( size > 0 and mAudioStream != nullptr ) { mAudioStream->write( (const char*)data, size ); } return true; } void Stream::DecodeFrame( const uint8_t* src, size_t sliceSize ) { uint8_t* data[3]; SBufferInfo bufInfo; memset( data, 0, sizeof(data) ); memset( &bufInfo, 0, sizeof(SBufferInfo) ); DECODING_STATE ret = mDecoder->DecodeFrameNoDelay( src, (int)sliceSize, data, &bufInfo ); // printf( " DecodeFrameNoDelay returned %08X\n", ret ); if ( bufInfo.iBufferStatus == 1 ) { mY.stride = bufInfo.UsrData.sSystemBuffer.iStride[0]; mY.width = bufInfo.UsrData.sSystemBuffer.iWidth; mY.height = bufInfo.UsrData.sSystemBuffer.iHeight; mY.data = data[0]; mU.stride = bufInfo.UsrData.sSystemBuffer.iStride[1]; mU.width = bufInfo.UsrData.sSystemBuffer.iWidth / 2; mU.height = bufInfo.UsrData.sSystemBuffer.iHeight / 2; mU.data = data[1]; mV.stride = bufInfo.UsrData.sSystemBuffer.iStride[2]; mV.width = bufInfo.UsrData.sSystemBuffer.iWidth / 2; mV.height = bufInfo.UsrData.sSystemBuffer.iHeight / 2; mV.data = data[2]; /* QImage image( mY.width, mY.height, QImage::Format_RGB32 ); for ( int y = 0; y < mY.height; y++ ) { for ( int x = 0; x < mY.width; x++ ) { const int xx = x >> 1; const int yy = y >> 1; const int Y = data[0][y * bufInfo.UsrData.sSystemBuffer.iStride[0] + x] - 16; const int U = data[1][yy * bufInfo.UsrData.sSystemBuffer.iStride[1] + xx] - 128; const int V = data[2][yy * bufInfo.UsrData.sSystemBuffer.iStride[2] + xx] - 128; const int r = qBound(0, (298 * Y + 409 * V + 128) >> 8, 255); const int g = qBound(0, (298 * Y - 100 * U - 208 * V + 128) >> 8, 255); const int b = qBound(0, (298 * Y + 516 * U + 128) >> 8, 255); image.setPixel( x, y, QColor( r, g, b ).rgb() ); } } mMutex.lock(); mImage = image; mMutex.unlock(); */ emit repaintEmitter(); } }
14,670
C++
.cpp
411
32.907543
137
0.659744
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,800
ControllerPC.cpp
dridri_bcflight/controller_pc/ControllerPC.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 <QtCore/QDebug> #include <QtCore/QThread> #include <QDebug> #include "MainWindow.h" #include "ControllerPC.h" #ifdef WIN32 #include <windows.h> #endif ControllerPC::ControllerPC( Link* link, bool spectate ) : Controller( link, spectate ) , mThrust( 0.0f ) , mArmed( false ) , mMode( false ) , mNightMode( false ) , mRecording( false ) { #ifdef WIN32 initGamePad(); #endif } ControllerPC::~ControllerPC() { } #ifdef WIN32 void ControllerPC::initGamePad() { unsigned int maxGamepadId = joyGetNumDevs(); JOYINFOEX info; for (unsigned int id = 0; id < maxGamepadId; ++id) { MMRESULT result = joyGetPosEx(id, &info); bool isConnected = result == JOYERR_NOERROR ; if (isConnected) { qDebug() << "Gamepad detected !"; padinfo = info; gamepadid = id; padinfo.dwSize = sizeof(padinfo); padinfo.dwFlags = JOY_RETURNALL; break; } } } #endif void ControllerPC::setControlThrust( const float v ) { mThrust = v; } void ControllerPC::setArmed( const bool armed ) { mArmed = armed; } void ControllerPC::setModeSwitch( const Controller::Mode& mode ) { if ( mode == Controller::Stabilize ) { mMode = true; } else if ( mode == Controller::Rate ) { mMode = false; } } void ControllerPC::setNight( const bool night ) { mNightMode = night; } void ControllerPC::setRecording( const bool record ) { mRecording = record; } float ControllerPC::ReadThrust( float dt ) { #ifdef WIN32 if (gamepadid != -1) { // down : 18000 // up : 0 // Using the POV for the thrust joyGetPosEx(gamepadid, &padinfo); if (padinfo.dwPOV == 0 && mThrust < 1.0f) { mThrust += .001; } else if (padinfo.dwPOV == 18000 && mThrust > 0.0f) { mThrust -= .001; } } #endif return mThrust; } float ControllerPC::ReadRoll( float dt ) { #ifdef WIN32 if (gamepadid != -1) { joyGetPosEx(gamepadid, &padinfo); return ((((float)padinfo.dwXpos / (float)65535)*2) - 1)/2; } #endif return 0.0f; } float ControllerPC::ReadPitch( float dt ) { #ifdef WIN32 if (gamepadid != -1) { joyGetPosEx(gamepadid, &padinfo); return ((((float)padinfo.dwYpos / (float)65535)*2) - 1)/2; } #endif return 0.0f; } float ControllerPC::ReadYaw( float dt ) { #ifdef WIN32 joyGetPosEx(gamepadid, &padinfo); if (gamepadid != -1) { joyGetPosEx(gamepadid, &padinfo); return ((((float)padinfo.dwRpos / (float)65535)*2) - 1)/2; } #endif return 0.0f; } int8_t ControllerPC::ReadSwitch( uint32_t id ) { #ifdef WIN32 int armBtn = (padinfo.dwButtons & 0x00000002); // Button 2 if (armBtn) { // Security mThrust = 0.0f; setArmed(true); } int disArmBtn = (padinfo.dwButtons & 0x00000001); // Button 1 if (disArmBtn) { setArmed(false); } #endif if ( id == 9 ) { return mArmed; } if ( id == 5 ) { return mMode; } if ( id == 6 ) { return mNightMode; } if ( id == 10 ) { return mRecording; } return 0; } ControllerMonitor::ControllerMonitor( ControllerPC* controller ) : QThread() , mController( controller ) , mKnowConnected( false ) { } ControllerMonitor::~ControllerMonitor() { } void ControllerMonitor::run() { struct sched_param sched; memset( &sched, 0, sizeof(sched) ); sched.sched_priority = sched_get_priority_max( SCHED_RR ); sched_setscheduler( 0, SCHED_RR, &sched ); while ( 1 ) { if ( not mKnowConnected and mController->isConnected() ) { emit connected(); mKnowConnected = true; } usleep( 1000 * 50 ); } }
4,119
C++
.cpp
182
20.527473
72
0.70454
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,801
main.cpp
dridri_bcflight/controller_pc/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 <iostream> #include <QtWidgets/QApplication> #include <QtWidgets/QStyleFactory> #include <QtCore/QLoggingCategory> #include <QDebug> #include <stdio.h> #include <RawWifi.h> #include <Socket.h> #include <../libdebug/Debug.h> #include "ControllerPC.h" #include "MainWindow.h" void msgHandler( QtMsgType type, const QMessageLogContext& ctx, const QString& msg ) { printf( "%s\n", msg.toStdString().c_str() ); fflush( stdout ); } int main( int ac, char** av ) { #ifdef WIN32 WSADATA WSAData; WSAStartup( MAKEWORD(2,0), &WSAData ); #endif Debug::setDebugLevel( Debug::Verbose ); QApplication app( ac, av ); qInstallMessageHandler( msgHandler ); QLoggingCategory::defaultCategory()->setEnabled( QtDebugMsg, true ); MainWindow win; win.show(); return app.exec(); }
1,501
C++
.cpp
47
30.12766
84
0.752941
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,802
MainWindow.cpp
dridri_bcflight/controller_pc/MainWindow.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 <QtCore/QDebug> #include <QtCore/QThread> #include <QtCore/QTime> #include <QtWidgets/QScrollBar> #include <QtWidgets/QFileDialog> #include <QtWidgets/QTableWidgetItem> #include <QtWidgets/QHBoxLayout> #include <Qsci/qsciscintilla.h> #include <Qsci/qscilexerlua.h> #include <iostream> #include <fftw3.h> extern "C" { #include <luajit.h> #include <lua.h> #include <lualib.h> #include <lauxlib.h> }; #include <RawWifi.h> #include <Socket.h> #include <functional> #include "MainWindow.h" #include "ControllerPC.h" #include "Controller.h" #include "ui_mainWindow.h" #include "qcustomplot.h" #include "ui/HStatusBar.h" MainWindow::MainWindow() : QMainWindow() , mController( nullptr ) , mControllerMonitor( nullptr ) , mStreamLink( nullptr ) , mFirmwareUpdateThread( nullptr ) , motorSpeedLayout( nullptr ) , mRatesPlot( false ) , mDnfPlot( false ) , mRatesPlotSpectrum( false ) , mPIDsOk( false ) , mPIDsReading( true ) { ui = new Ui::MainWindow; ui->setupUi(this); mConfig = new Config(); connect( ui->actionSettings, SIGNAL( triggered(bool) ), mConfig, SLOT( show() ) ); mBlackBox = new BlackBox(); connect( ui->actionInspect_blackbox, SIGNAL( triggered(bool) ), mBlackBox, SLOT( show() ) ); mVideoEditor = new VideoEditor(); connect( ui->actionVideo_Editor, SIGNAL( triggered(bool) ), mVideoEditor, SLOT( show() ) ); Link* mControllerLink = nullptr; Link* mAudioLink = nullptr; if ( mConfig->value( "link/rawwifi", true ).toBool() == true ) { #ifndef NO_RAWWIFI std::string device = mConfig->value( "rawwifi/device", "" ).toString().toStdString(); if ( device != "" ) { RawWifi* controllerLink = new RawWifi( device, mConfig->value( "rawwifi/controller/outport", 0 ).toInt(), mConfig->value( "rawwifi/controller/inport", 1 ).toInt() ); mControllerLink = controllerLink; // controllerLink->SetChannel( mConfig->value( "rawwifi/channel", 9 ).toInt() ); // controllerLink->setRetriesCount( mConfig->value( "rawwifi/controller/retries", 1 ).toInt() ); // controllerLink->setCECMode( mConfig->value( "rawwifi/controller/cec", "" ).toString().toLower().toStdString() ); // controllerLink->setDropBroken( not mConfig->value( "rawwifi/controller/nodrop", false ).toBool() ); mStreamLink = new RawWifi( device, mConfig->value( "rawwifi/video/outport", 10 ).toInt(), mConfig->value( "rawwifi/video/inport", 11 ).toInt() ); // static_cast<RawWifi*>(mStreamLink)->SetChannel( mConfig->value( "rawwifi/channel", 9 ).toInt() ); // static_cast<RawWifi*>(mStreamLink)->setRetriesCount( mConfig->value( "rawwifi/video/retries", 1 ).toInt() ); // static_cast<RawWifi*>(mStreamLink)->setCECMode( mConfig->value( "rawwifi/video/cec", "" ).toString().toLower().toStdString() ); // static_cast<RawWifi*>(mStreamLink)->setDropBroken( not mConfig->value( "rawwifi/video/nodrop", false ).toBool() ); // mAudioLink = new RawWifi( device, mConfig->value( "rawwifi/audio/outport", 20 ).toInt(), mConfig->value( "rawwifi/audio/inport", 21 ).toInt() ); // static_cast<RawWifi*>(mAudioLink)->SetChannel( mConfig->value( "rawwifi/channel", 9 ).toInt() ); // static_cast<RawWifi*>(mAudioLink)->setRetriesCount( mConfig->value( "rawwifi/audio/retries", 1 ).toInt() ); // static_cast<RawWifi*>(mAudioLink)->setCECMode( mConfig->value( "rawwifi/audio/cec", "" ).toString().toLower().toStdString() ); // static_cast<RawWifi*>(mAudioLink)->setDropBroken( not mConfig->value( "rawwifi/audio/nodrop", false ).toBool() ); } #endif // NO_RAWWIFI } else { std::function<Socket::PortType(const QString&)> socket_type = [](const QString& type){ if ( type == "UDPLite" ) return Socket::UDPLite; else if ( type == "UDP" ) return Socket::UDP; else return Socket::TCP; }; mControllerLink = new Socket( mConfig->value( "tcpip/address", "192.168.32.1" ).toString().toStdString(), mConfig->value( "tcpip/controller/port", 2020 ).toInt(), socket_type( mConfig->value( "tcpip/controller/type", "TCP" ).toString() ) ); mStreamLink = new Socket( mConfig->value( "tcpip/address", "192.168.32.1" ).toString().toStdString(), mConfig->value( "tcpip/video/port", 2021 ).toInt(), socket_type( mConfig->value( "tcpip/video/type", "UDPLite" ).toString() ) ); mAudioLink = new Socket( mConfig->value( "tcpip/address", "192.168.32.1" ).toString().toStdString(), mConfig->value( "tcpip/audio/port", 2022 ).toInt(), socket_type( mConfig->value( "tcpip/audio/type", "TCP" ).toString() ) ); } uint8_t test[2048]; // mControllerLink->Read( test, 2048, 0 ); mController = new ControllerPC( mControllerLink, mConfig->value( "controller/spectate", false ).toBool() ); if ( mController ) { mControllerMonitor = new ControllerMonitor( mController ); connect( mControllerMonitor, SIGNAL( connected() ), this, SLOT( connected() ) ); mControllerMonitor->start(); } mUpdateTimer = new QTimer(); connect( mUpdateTimer, SIGNAL( timeout() ), this, SLOT( updateData() ) ); mUpdateTimer->setInterval( 20 ); mUpdateTimer->start(); QsciLexerLua* lexerLua = new QsciLexerLua; ui->config->setLexer( lexerLua ); ui->config->setFont( QFontDatabase::systemFont( QFontDatabase::FixedFont ) ); connect( ui->reset_battery, SIGNAL( pressed() ), this, SLOT( ResetBattery() ) ); connect( ui->calibrate, SIGNAL( pressed() ), this, SLOT( Calibrate() ) ); connect( ui->calibrate_all, SIGNAL( pressed() ), this, SLOT( CalibrateAll() ) ); connect( ui->calibrate_escs, SIGNAL( pressed() ), this, SLOT( CalibrateESCs() ) ); connect( ui->arm, SIGNAL( pressed() ), this, SLOT( ArmDisarm() ) ); connect( ui->throttle, SIGNAL( valueChanged(int) ), this, SLOT( throttleChanged(int) ) ); connect( ui->config_load, SIGNAL( pressed() ), this, SLOT( LoadConfig() ) ); connect( ui->config_save, SIGNAL( pressed() ), this, SLOT( SaveConfig() ) ); connect( ui->firmware_browse, SIGNAL( pressed() ), this, SLOT( FirmwareBrowse() ) ); connect( ui->firmware_upload, SIGNAL( pressed() ), this, SLOT( FirmwareUpload() ) ); connect( ui->tundev, SIGNAL( pressed() ), this, SLOT( tunDevice() ) ); connect( ui->stabilized_mode, SIGNAL( pressed() ), this, SLOT( ModeStabilized() ) ); connect( ui->rate_mode, SIGNAL( pressed() ), this, SLOT( ModeRate() ) ); connect( ui->brightness_dec, SIGNAL( pressed() ), this, SLOT( VideoBrightnessDecrease() ) ); connect( ui->brightness_inc, SIGNAL( pressed() ), this, SLOT( VideoBrightnessIncrease() ) ); connect( ui->contrast_dec, SIGNAL( pressed() ), this, SLOT( VideoContrastDecrease() ) ); connect( ui->contrast_inc, SIGNAL( pressed() ), this, SLOT( VideoContrastIncrease() ) ); connect( ui->saturation_dec, SIGNAL( pressed() ), this, SLOT( VideoSaturationDecrease() ) ); connect( ui->saturation_inc, SIGNAL( pressed() ), this, SLOT( VideoSaturationIncrease() ) ); connect( ui->record, SIGNAL( pressed() ), this, SLOT( VideoRecord() ) ); connect( ui->take_picture, SIGNAL( pressed() ), this, SLOT( VideoTakePicture() ) ); connect( ui->white_balance_lock, SIGNAL( pressed() ), this, SLOT( VideoWhiteBalanceLock() ) ); connect( ui->recordings_refresh, SIGNAL( pressed() ), this, SLOT( RecordingsRefresh() ) ); connect( ui->night_mode, SIGNAL( stateChanged(int) ), this, SLOT( SetNightMode(int) ) ); connect( ui->motorTestButton, SIGNAL(pressed()), this, SLOT(MotorTest())); connect( ui->motorsBeepStart, &QPushButton::pressed, [this]() { MotorsBeep(true); }); connect( ui->motorsBeepStop, &QPushButton::pressed, [this]() { MotorsBeep(false); }); connect( ui->gyroPlotButton, &QPushButton::pressed, [this]() { mRatesPlot = false; mDnfPlot = false; }); connect( ui->ratesPlotButton, &QPushButton::pressed, [this]() { mRatesPlot = true; mDnfPlot = false; }); connect( ui->dnfPlotButton, &QPushButton::pressed, [this]() { mDnfPlot = true; mRatesPlot = false; }); connect( ui->gyroSpectrumButton, &QCheckBox::stateChanged, [this](int state) { mRatesPlotSpectrum = ( state == Qt::Checked ); }); ui->statusbar->showMessage( "Disconnected" ); ui->cpu_load->setSuffix( "%" ); ui->temperature->setSuffix( "°C" ); ui->temperature->setMaxValue( 80 ); // Setup graphs std::list< QCustomPlot* > graphs; graphs.emplace_back( ui->rpy ); graphs.emplace_back( ui->rates ); graphs.emplace_back( ui->accelerometer ); graphs.emplace_back( ui->magnetometer ); graphs.emplace_back( ui->altitude ); // graphs.emplace_back( ui->gps ); graphs.emplace_back( ui->rates_dterm ); for ( QCustomPlot* graph : graphs ) { graph->setBackground( QBrush( QColor( 0, 0, 0, 0 ) ) ); graph->xAxis->setTickLabelColor( QColor( 255, 255, 255 ) ); graph->yAxis->setTickLabelColor( QColor( 255, 255, 255 ) ); graph->yAxis->setNumberFormat( "f" ); graph->yAxis->setNumberPrecision( 2 ); graph->xAxis->grid()->setPen( QPen( QBrush( QColor( 64, 64, 64 ) ), 1, Qt::DashDotDotLine ) ); graph->yAxis->grid()->setPen( QPen( QBrush( QColor( 64, 64, 64 ) ), 1, Qt::DashDotDotLine ) ); graph->yAxis->grid()->setZeroLinePen( QPen( QBrush( QColor( 96, 96, 96 ) ), 2, Qt::DashLine ) ); graph->yAxis->setRange( -1.0f, 1.0f ); graph->addGraph(); graph->addGraph(); graph->addGraph(); graph->graph(0)->setPen( QPen( QBrush( QColor( 255, 128, 128 ) ), 2 ) ); graph->graph(1)->setPen( QPen( QBrush( QColor( 128, 255, 128 ) ), 2 ) ); graph->graph(2)->setPen( QPen( QBrush( QColor( 128, 128, 255 ) ), 2 ) ); } mTicks.start(); ui->video->setMainWindow( this ); ui->video->setLink( mStreamLink ); ui->video->setAudioLink( mAudioLink ); } MainWindow::~MainWindow() { delete ui; delete mConfig; } static void Recurse( lua_State* L, QTreeWidgetItem* parent, QString name, int index = -1, int indent = 0 ) { std::cout << "Recurse( L, parent, " << name.toStdString() << ", " << index << ", " << indent << ")\n"; if ( name == "CurrentSensors" ) { name = "Current Sensors"; } QVariant data; QTreeWidgetItem* item = nullptr; for ( int32_t i = 0; i < parent->childCount(); i++ ) { if ( parent->child(i)->data( 0, 0 ) == name ) { item = parent->child(i); break; } } if ( not item ) { item = new QTreeWidgetItem(); item->setData( 0, 0, name ); parent->addChild( item ); } if ( indent == 0 ) { lua_getfield( L, LUA_GLOBALSINDEX, name.toLatin1().data() ); } std::cout << "lua_type( L, index ) = " << lua_type( L, index ) << "\n"; if ( lua_isnil( L, index ) ) { } else if ( lua_isnumber( L, index ) ) { data = lua_tonumber( L, index ); } else if ( lua_isboolean( L, index ) ) { data = ( lua_toboolean( L, index ) ? "true" : "false" ); } else if ( lua_isstring( L, index ) ) { data = lua_tostring( L, index ); } else if ( lua_iscfunction( L, index ) ) { } else if ( lua_isuserdata( L, index ) ) { } else if ( lua_istable( L, index ) ) { lua_pushnil( L ); while( lua_next( L, -2 ) != 0 ) { const char* key = lua_tostring( L, index-1 ); Recurse( L, item, key, index, indent + 1 ); lua_pop( L, 1 ); } } if ( data.isValid() ) { item->setData( 1, 0, data ); } } void MainWindow::appendDebugOutput( const QString& str ) { QTextCursor cursor( ui->terminal->textCursor() ); ui->terminal->setPlainText( ui->terminal->toPlainText() + str ); cursor.movePosition( QTextCursor::End ); ui->terminal->setTextCursor( cursor ); } void MainWindow::connected() { qDebug() << "Fetching board data"; ui->statusbar->showMessage( "Connected" ); if ( mController and not mController->isSpectate() ) { lua_State* L = luaL_newstate(); QString board_infos = QString::fromStdString( mController->getBoardInfos() ); std::cout << "Board infos: " << board_infos.toStdString() << "\n"; luaL_dostring( L, ("Board=" + board_infos.toUtf8()).data() ); Recurse( L, ui->system->findItems( "BCFlight", Qt::MatchCaseSensitive | Qt::MatchRecursive, 0 ).first(), "Board" ); QString sensors_infos = QString::fromStdString( mController->getSensorsInfos() ); std::cout << "sensors_infos : " << sensors_infos.toStdString() << "\n"; luaL_dostring( L, ("Sensors=" + sensors_infos.toUtf8()).data() ); Recurse( L, ui->system->findItems( "BCFlight", Qt::MatchCaseSensitive | Qt::MatchRecursive, 0 ).first(), "Sensors" ); QString cameras_infos = QString::fromStdString( mController->getCamerasInfos() ); std::cout << "cameras_infos : " << cameras_infos.toStdString() << "\n"; luaL_dostring( L, ("Cameras=" + cameras_infos.toUtf8()).data() ); Recurse( L, ui->system->findItems( "BCFlight", Qt::MatchCaseSensitive | Qt::MatchRecursive, 0 ).first(), "Cameras" ); lua_close(L); } ui->system->expandAll(); } void MainWindow::updateData() { if ( not mController or not mController->link() ) { if ( mStreamLink ) { ui->statusbar->showMessage( QString( "Camera : %1 KB/s | Quality : %2 % | %3 FPS" ).arg( mStreamLink->readSpeed() / 1024, 4, 10, QChar(' ') ).arg( mStreamLink->RxQuality(), 3, 10, QChar(' ') ).arg( ui->video->fps() ) ); } } else { QString conn = mController->isConnected() ? "Connected" : "Disconnected"; if ( mStreamLink ) { ui->statusbar->showMessage( conn + QString( " | RX Qual : %1 % (%2 dBm ) | TX Qual : %3 % | TX : %4 B/s | RX : %5 B/s | Camera :%6 KB/s (%7 KB/s |%8 % |%9 dBm ) | %10 FPS" ).arg( mController->link()->RxQuality(), 3, 10, QChar(' ') ).arg( mController->link()->RxLevel(), 3, 10, QChar(' ') ).arg( mController->droneRxQuality(), 3, 10, QChar(' ') ).arg( mController->link()->writeSpeed(), 4, 10, QChar(' ') ).arg( mController->link()->readSpeed(), 4, 10, QChar(' ') ).arg( mStreamLink->readSpeed() / 1024, 4, 10, QChar(' ') ).arg( mStreamLink->fullReadSpeed() / 1024, 4, 10, QChar(' ') ).arg( mStreamLink->RxQuality(), 3, 10, QChar(' ') ).arg( mStreamLink->RxLevel(), 3, 10, QChar(' ') ).arg( ui->video->fps() ) ); } else { ui->statusbar->showMessage( conn + QString( " | RX Qual : %1 % (%2 dBm ) | TX Qual : %3 % | TX : %4 B/s | RX : %5 B/s" ).arg( mController->link()->RxQuality(), 3, 10, QChar(' ') ).arg( mController->link()->RxLevel(), 3, 10, QChar(' ') ).arg( mController->droneRxQuality(), 3, 10, QChar(' ') ).arg( mController->link()->writeSpeed(), 4, 10, QChar(' ') ).arg( mController->link()->readSpeed(), 4, 10, QChar(' ') ) ); } if ( mController->ping() < 10000 ) { ui->latency->setText( QString::number( mController->ping() ) + " ms" ); } ui->voltage->setText( QString::number( mController->batteryVoltage(), 'f', 2 ) + " V" ); ui->current->setText( QString::number( mController->currentDraw(), 'f', 2 ) + " A" ); ui->current_total->setText( QString::number( mController->totalCurrent() ) + " mAh" ); ui->cpu_load->setValue( mController->CPULoad() ); ui->temperature->setValue( mController->CPUTemp() ); ui->stabilizer_frequency->setText( QString::number( mController->stabilizerFrequency() ) + " Hz" ); std::vector<float> motorSpeed = mController->motorsSpeed(); if (motorSpeed.size() > 0) { if ( motorSpeedLayout == nullptr ) { motorSpeedLayout = new QVBoxLayout; for ( float speed : motorSpeed ) { QProgressBar *progress = new QProgressBar(); motorSpeedProgress.append(progress); progress->setMaximum(100); progress->setMinimum(0); progress->setValue(speed); motorSpeedLayout->addWidget(progress); } ui->listMotors->setLayout(motorSpeedLayout); } else { for ( uint32_t i = 0; i < motorSpeed.size(); i++ ) { if ( i < motorSpeedProgress.size() and motorSpeedProgress.at(i) != nullptr ) { motorSpeedProgress.at(i)->setValue( motorSpeed.at(i) * 100 ); } } } } std::string dbg = mController->debugOutput(); if ( dbg != "" ) { QTextCursor cursor( ui->terminal->textCursor() ); bool move = true; //( ui->terminal->toPlainText().length() == 0 or cursor.position() == QTextCursor::End ); ui->terminal->setPlainText( ui->terminal->toPlainText() + QString::fromStdString( dbg ) ); if ( move ) { cursor.movePosition( QTextCursor::End ); ui->terminal->setTextCursor( cursor ); } } auto plot = []( QCustomPlot* graph, const std::list< vec4 >& values, QVector< double >& t, QVector< double >& x, QVector< double >& y, QVector< double >& z, bool rescale = true ) { t.clear(); x.clear(); y.clear(); z.clear(); for ( vec4 v : values ) { if ( std::isnan( v.x ) or std::isinf( v.x ) or fabsf( v.x ) > 1000.0f ) { v.x = 0.0f; } if ( std::isnan( v.y ) or std::isinf( v.y ) or fabsf( v.y ) > 1000.0f ) { v.y = 0.0f; } if ( std::isnan( v.z ) or std::isinf( v.z ) or fabsf( v.z ) > 1000.0f ) { v.z = 0.0f; } t.append( v.w ); x.append( v.x ); y.append( v.y ); z.append( v.z ); } graph->graph(0)->setData( t, x ); graph->graph(1)->setData( t, y ); graph->graph(2)->setData( t, z ); if ( rescale ) { graph->graph(0)->rescaleAxes(); graph->graph(1)->rescaleAxes( true ); graph->graph(2)->rescaleAxes( true ); } graph->xAxis->rescale(); graph->replot(); }; const std::list<vec4>& gyroData = mDnfPlot ? mController->dnfDftHistory() : (mRatesPlot ? mController->ratesHistory() : mController->gyroscopeHistory()); if ( mRatesPlotSpectrum && !mDnfPlot ) { int numSamples = std::min( gyroData.size(), 512UL ); if ( numSamples > 32 ) { float* input0 = (float*)fftwf_malloc( sizeof(float) * numSamples ); float* input1 = (float*)fftwf_malloc( sizeof(float) * numSamples ); float* input2 = (float*)fftwf_malloc( sizeof(float) * numSamples ); fftwf_complex* output0 = (fftwf_complex*)fftwf_malloc( sizeof(fftwf_complex) * ( numSamples / 2 + 1 ) ); fftwf_complex* output1 = (fftwf_complex*)fftwf_malloc( sizeof(fftwf_complex) * ( numSamples / 2 + 1 ) ); fftwf_complex* output2 = (fftwf_complex*)fftwf_malloc( sizeof(fftwf_complex) * ( numSamples / 2 + 1 ) ); auto plan0 = fftwf_plan_dft_r2c_1d( numSamples, input0, output0, FFTW_ESTIMATE ); auto plan1 = fftwf_plan_dft_r2c_1d( numSamples, input1, output1, FFTW_ESTIMATE ); auto plan2 = fftwf_plan_dft_r2c_1d( numSamples, input2, output2, FFTW_ESTIMATE ); int32_t n = numSamples - 1; double tMax = gyroData.back().w; double tMin = 0.0; std::vector<vec4> list; for ( vec4 v : gyroData ) { list.push_back(v); } for ( int32_t n = 0; n < numSamples; n++ ) { input0[n] = list[list.size() - 1 - n].x; input1[n] = list[list.size() - 1 - n].y; input2[n] = list[list.size() - 1 - n].z; tMin = list[list.size() - 1 - n].w; } float totalTime = tMax - tMin; // printf( "totalTime: %f\n", totalTime ); fftwf_execute( plan0 ); fftwf_execute( plan1 ); fftwf_execute( plan2 ); std::list<vec4> out; for ( uint32_t i = 0; i < numSamples / 2 + 1; i++ ) { vec4 v; v.x = std::abs( output0[i][0] ); v.y = std::abs( output1[i][0] ); v.z = std::abs( output2[i][0] ); v.w = i; // v.w = 2 * i * list.size() / numSamples; // TODO : use IMU freq instead out.push_back( v ); } ui->rates->yAxis->setRange( 0.0f, 128.0f ); plot( ui->rates, out, mDataTrates, mDataRatesX, mDataRatesY, mDataRatesZ, false ); fftwf_free( input0 ); fftwf_free( input1 ); fftwf_free( input2 ); fftwf_free( output0 ); fftwf_free( output1 ); fftwf_free( output2 ); } } else { if ( mDnfPlot ) { ui->rates->yAxis->setRange( 0.0f, 128.0f ); } plot( ui->rates, gyroData, mDataTrates, mDataRatesX, mDataRatesY, mDataRatesZ, mDnfPlot == false ); } plot( ui->rpy, mController->rpyHistory(), mDataTrpy, mDataR, mDataP, mDataY ); plot( ui->accelerometer, mController->accelerationHistory(), mDataTaccelerometer, mDataAccelerometerX, mDataAccelerometerY, mDataAccelerometerZ ); plot( ui->magnetometer, mController->magnetometerHistory(), mDataTmagnetometer, mDataMagnetometerX, mDataMagnetometerY, mDataMagnetometerZ ); plot( ui->rates_dterm, mController->ratesDerivativeHistory(), mDataTratesdterm, mDataRatesdtermX, mDataRatesdtermY, mDataRatesdtermZ ); mDataTAltitude.append( mController->altitudeHistory().back().y ); mDataAltitude.append( mController->altitudeHistory().back().x ); ui->altitude->graph(0)->setData( mDataTAltitude, mDataAltitude ); ui->altitude->graph(0)->rescaleAxes(); ui->altitude->xAxis->rescale(); ui->altitude->replot(); if ( mController->isConnected() and /*not mController->isSpectate() and*/ ( not mPIDsOk or ( ui->rateP->value() == 0.0f and ui->rateI->value() == 0.0f and ui->rateD->value() == 0.0f and ui->horizonP->value() == 0.0f and ui->horizonI->value() == 0.0f and ui->horizonD->value() == 0.0f ) ) ) { mPIDsReading = true; mController->ReloadPIDs(); ui->rateP->setValue( mController->rollPid().x ); ui->rateI->setValue( mController->rollPid().y ); ui->rateD->setValue( mController->rollPid().z ); ui->rateP_2->setValue( mController->pitchPid().x ); ui->rateI_2->setValue( mController->pitchPid().y ); ui->rateD_2->setValue( mController->pitchPid().z ); ui->rateP_3->setValue( mController->yawPid().x ); ui->rateI_3->setValue( mController->yawPid().y ); ui->rateD_3->setValue( mController->yawPid().z ); ui->horizonP->setValue( mController->outerPid().x ); ui->horizonI->setValue( mController->outerPid().y ); ui->horizonD->setValue( mController->outerPid().z ); connect( ui->rateP, SIGNAL( valueChanged(double) ), this, SLOT( setRatePIDRoll(double) ) ); connect( ui->rateI, SIGNAL( valueChanged(double) ), this, SLOT( setRatePIDRoll(double) ) ); connect( ui->rateD, SIGNAL( valueChanged(double) ), this, SLOT( setRatePIDRoll(double) ) ); connect( ui->rateP_2, SIGNAL( valueChanged(double) ), this, SLOT( setRatePIDPitch(double) ) ); connect( ui->rateI_2, SIGNAL( valueChanged(double) ), this, SLOT( setRatePIDPitch(double) ) ); connect( ui->rateD_2, SIGNAL( valueChanged(double) ), this, SLOT( setRatePIDPitch(double) ) ); connect( ui->rateP_3, SIGNAL( valueChanged(double) ), this, SLOT( setRatePIDYaw(double) ) ); connect( ui->rateI_3, SIGNAL( valueChanged(double) ), this, SLOT( setRatePIDYaw(double) ) ); connect( ui->rateD_3, SIGNAL( valueChanged(double) ), this, SLOT( setRatePIDYaw(double) ) ); connect( ui->horizonP, SIGNAL( valueChanged(double) ), this, SLOT( setHorizonP(double) ) ); connect( ui->horizonI, SIGNAL( valueChanged(double) ), this, SLOT( setHorizonI(double) ) ); connect( ui->horizonD, SIGNAL( valueChanged(double) ), this, SLOT( setHorizonD(double) ) ); mPIDsOk = true; mPIDsReading = false; } } } void MainWindow::ResetBattery() { if ( mController and not mController->isSpectate() ) { mController->ResetBattery(); } } void MainWindow::Calibrate() { if ( mController and not mController->isSpectate() ) { mController->Calibrate(); } } void MainWindow::CalibrateAll() { if ( mController and not mController->isSpectate() ) { mController->CalibrateAll(); } } void MainWindow::CalibrateESCs() { if ( mController and not mController->isSpectate() ) { mController->CalibrateESCs(); } } void MainWindow::ArmDisarm() { if ( mController and not mController->isSpectate() ) { if ( mController->armed() ) { std::cout << "Disarming...\n"; // mController->Disarm(); mController->setArmed( false ); ui->arm->setText( "Arm" ); } else { std::cout << "Arming...\n"; // mController->Arm(); mController->setArmed( true ); ui->arm->setText( "Disarm" ); } } } void MainWindow::throttleChanged( int throttle ) { if ( mController and not mController->isSpectate() ) { mController->setControlThrust( (double)throttle / 100.0f ); } } void MainWindow::LoadConfig() { if ( mController and not mController->isSpectate() ) { std::string conf = mController->getConfigFile(); ui->config->setText( QString::fromStdString( conf ) ); } } void MainWindow::SaveConfig() { if ( mController and not mController->isSpectate() and ui->config->text().length() > 0 ) { std::string conf = ui->config->text().toStdString(); mController->setConfigFile( conf ); } } void MainWindow::FirmwareBrowse() { QFileDialog* diag = new QFileDialog( this ); diag->setFileMode( QFileDialog::AnyFile ); diag->show(); connect( diag, SIGNAL( fileSelected(QString) ), this, SLOT( firmwareFileSelected(QString) ) ); } void MainWindow::firmwareFileSelected( QString path ) { ui->firmware_path->setText( path ); } void MainWindow::FirmwareUpload() { if ( mFirmwareUpdateThread ) { if ( mFirmwareUpdateThread->isRunning() ) { return; } delete mFirmwareUpdateThread; } mFirmwareUpdateThread = new FirmwareUpdateThread( this ); connect( this, SIGNAL( firmwareUpdateProgress(int) ), this, SLOT( setFirmwareUpdateProgress(int) ) ); connect( this, SIGNAL( debugOutput(QString) ), this, SLOT( appendDebugOutput(QString) ) ); mFirmwareUpdateThread->start(); } void MainWindow::setFirmwareUpdateProgress( int val ) { ui->firmware_progress->setValue( val ); } bool MainWindow::RunFirmwareUpdate() { if ( mController and not mController->isSpectate() ) { emit firmwareUpdateProgress( 0 ); if ( ui->firmware_path->text().length() > 0 and QFile::exists( ui->firmware_path->text() ) and mController->isConnected() ) { QFile f( ui->firmware_path->text() ); if ( !f.open( QFile::ReadOnly ) ) return false; QByteArray ba = f.readAll(); mController->UploadUpdateInit(); uint32_t chunk_size = 1024; // 2048 for ( uint32_t offset = 0; offset < (uint32_t)ba.size(); offset += chunk_size ) { uint32_t sz = chunk_size; if ( ba.size() - offset < chunk_size ) { sz = ba.size() - offset; } mController->UploadUpdateData( (const uint8_t*)&ba.constData()[offset], offset, sz ); emit firmwareUpdateProgress( offset * 100 / ba.size() + 1 ); QApplication::processEvents(); } emit debugOutput( "\n====> Applying firmware update and restarting service, please wait... <====\n" ); mController->UploadUpdateProcess( (const uint8_t*)ba.constData(), ba.size() ); } emit firmwareUpdateProgress( 0 ); } return false; } void MainWindow::tunDevice() { if ( ui->tundev->text().contains( "nable" ) ) { qDebug() << "Enabling tun dev..."; ui->tundev->setText( "Disable Tun Device" ); mController->EnableTunDevice(); } else { qDebug() << "Disabling tun dev..."; ui->tundev->setText( "Enable Tun Device" ); mController->DisableTunDevice(); } } void MainWindow::ModeRate() { if ( mController and not mController->isSpectate() ) { mController->setModeSwitch( Controller::Rate ); } } void MainWindow::ModeStabilized() { if ( mController and not mController->isSpectate() ) { mController->setModeSwitch( Controller::Stabilize ); } } void MainWindow::setRatePIDRoll( double v ) { if ( not mController/* or mController->isSpectate()*/ ) { return; } if ( mPIDsReading ) { return; } if ( mController->isConnected() ) { mPIDsOk = true; } vec3 vec; vec.x = ui->rateP->value(); vec.y = ui->rateI->value(); vec.z = ui->rateD->value(); mController->setRollPID( vec ); } void MainWindow::setRatePIDPitch( double v ) { if ( not mController/* or mController->isSpectate()*/ ) { return; } if ( mPIDsReading ) { return; } if ( mController->isConnected() ) { mPIDsOk = true; } vec3 vec; vec.x = ui->rateP_2->value(); vec.y = ui->rateI_2->value(); vec.z = ui->rateD_2->value(); mController->setPitchPID( vec ); } void MainWindow::setRatePIDYaw( double v ) { if ( not mController/* or mController->isSpectate()*/ ) { return; } if ( mPIDsReading ) { return; } if ( mController->isConnected() ) { mPIDsOk = true; } vec3 vec; vec.x = ui->rateP_3->value(); vec.y = ui->rateI_3->value(); vec.z = ui->rateD_3->value(); mController->setYawPID( vec ); } void MainWindow::setHorizonP( double v ) { if ( not mController/* or mController->isSpectate()*/ ) { return; } if ( mPIDsReading ) { return; } if ( mController->isConnected() ) { mPIDsOk = true; } vec3 vec = mController->outerPid(); vec.x = v; mController->setOuterPID( vec ); } void MainWindow::setHorizonI( double v ) { if ( not mController/* or mController->isSpectate()*/ ) { return; } if ( mPIDsReading ) { return; } if ( mController->isConnected() ) { mPIDsOk = true; } vec3 vec = mController->outerPid(); vec.y = v; mController->setOuterPID( vec ); } void MainWindow::setHorizonD( double v ) { if ( not mController/* or mController->isSpectate()*/ ) { return; } if ( mPIDsReading ) { return; } if ( mController->isConnected() ) { mPIDsOk = true; } vec3 vec = mController->outerPid(); vec.z = v; mController->setOuterPID( vec ); } void MainWindow::VideoBrightnessDecrease() { if ( mController and mController->isConnected() and not mController->isSpectate() ) { mController->VideoBrightnessDecrease(); } } void MainWindow::VideoBrightnessIncrease() { if ( mController and mController->isConnected() and not mController->isSpectate() ) { mController->VideoBrightnessIncrease(); } } void MainWindow::VideoContrastDecrease() { if ( mController and mController->isConnected() and not mController->isSpectate() ) { mController->VideoContrastDecrease(); } } void MainWindow::VideoContrastIncrease() { if ( mController and mController->isConnected() and not mController->isSpectate() ) { mController->VideoContrastIncrease(); } } void MainWindow::VideoSaturationDecrease() { if ( mController and mController->isConnected() and not mController->isSpectate() ) { mController->VideoSaturationDecrease(); } } void MainWindow::VideoSaturationIncrease() { if ( mController and mController->isConnected() and not mController->isSpectate() ) { mController->VideoSaturationIncrease(); } } void MainWindow::SetNightMode( int mode ) { if ( mController and mController->isConnected() and not mController->isSpectate() ) { mController->setNight( ( mode != 0 ) ); } } void MainWindow::VideoPause() { /* if ( not mController or mController->isSpectate() ) { return; } qDebug() << "VideoPause()" << ui->video_pause->text(); if ( ui->video_pause->text().mid( ui->video_pause->text().indexOf( "P" ) ) == QString( "Pause" ) ) { qDebug() << "VideoPause() Pause"; mController->VideoPause(); ui->video_pause->setText( "Resume" ); } else { qDebug() << "VideoPause() Resume"; mController->VideoResume(); ui->video_pause->setText( "Pause" ); } */ } void MainWindow::VideoTakePicture() { if ( mController and mController->isConnected() ) { mController->VideoTakePicture(); } } void MainWindow::VideoWhiteBalanceLock() { if ( mController and mController->isConnected() and not mController->isSpectate() ) { mController->VideoLockWhiteBalance(); } } void MainWindow::VideoRecord() { if ( not mController or mController->isSpectate() ) { return; } qDebug() << "VideoRecord()" << ui->record->text(); if ( ui->record->text().mid( ui->record->text().indexOf( "S" ) ) == QString( "Start" ) ) { qDebug() << "VideoRecord() Start"; mController->setRecording( true ); ui->record->setText( "Stop" ); } else { qDebug() << "VideoRecord() Stop"; mController->setRecording( false ); ui->record->setText( "Start" ); } } void MainWindow::RecordingsRefresh() { if ( not mController or mController->isSpectate() ) { return; } ui->recordings->clearContents(); ui->recordings->clear(); for ( int32_t i = ui->recordings->rowCount() - 1; i >= 0; i-- ) { ui->recordings->removeRow( i ); } std::vector< std::string > list = mController->recordingsList(); std::sort( list.begin(), list.end() ); for ( std::string input : list ) { QStringList split = QString::fromStdString(input).split( ":" ); QString filename = split[0]; QString size = split[1]; int snap_width = split[2].toInt(); int snap_height = split[3].toInt(); int snap_bpp = split[4].toInt(); QByteArray snap_raw = ( split.size() > 5 and split[5].length() > 0 ) ? QByteArray::fromBase64( split[5].toUtf8() ) : QByteArray(); uint32_t* snap_raw32 = ( snap_raw.size() > 0 ) ? (uint32_t*)snap_raw.constData() : nullptr; if ( filename[0] != '.' ) { QLabel* snapshot_label = new QLabel(); if ( snap_raw32 ) { QImage snapshot( snap_width, snap_height, QImage::Format_RGB16 ); for ( int y = 0; y < snap_height; y++ ) { for ( int x = 0; x < snap_width; x++ ) { snapshot.setPixel( x, y, snap_raw32[ y * snap_width + x ] ); } } snapshot_label->setPixmap( QPixmap::fromImage( snapshot ) ); } ui->recordings->insertRow( ui->recordings->rowCount() ); ui->recordings->setCellWidget( ui->recordings->rowCount() - 1, 0, snapshot_label ); ui->recordings->setCellWidget( ui->recordings->rowCount() - 1, 1, new QLabel( filename ) ); // QLabel* size_label = new QLabel( QString::number( size.toInt() / 1024 ) + " KB" ); QLabel* size_label = new QLabel( QLocale::system().toString( size.toInt() / 1024 ) + " KB" ); size_label->setAlignment( Qt::AlignRight ); ui->recordings->setCellWidget( ui->recordings->rowCount() - 1, 2, size_label ); QWidget* tools = new QWidget(); QHBoxLayout* layout = new QHBoxLayout(); tools->setLayout( layout ); QPushButton* btn_save = new QPushButton(); btn_save->setIcon( QIcon( ":icons/icon-download.png" ) ); QPushButton* btn_delete = new QPushButton(); btn_delete->setIcon( QIcon( ":icons/icon-delete.png" ) ); layout->addWidget( btn_save ); layout->addWidget( btn_delete ); ui->recordings->setCellWidget( ui->recordings->rowCount() - 1, 4, tools ); ui->recordings->setRowHeight( ui->recordings->rowCount() - 1, 42 ); } } QStringList headers; headers << "Snapshot" << "Filename" << "Size" << "Date" << "Actions"; ui->recordings->setHorizontalHeaderLabels( headers ); } void MainWindow::MotorTest() { if ( not mController or mController->isSpectate() ) { return; } int id = ui->motorTestSpinBox->value(); mController->MotorTest( id ); } void MainWindow::MotorsBeep( bool enabled ) { std::cout << "MotorsBeep(" << enabled << " )\n"; if ( not mController or mController->isSpectate() ) { return; } mController->MotorsBeep( enabled ); }
34,591
C++
.cpp
827
39
750
0.669402
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,805
Config.cpp
dridri_bcflight/controller_pc/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 <unistd.h> #include <sys/types.h> #ifdef WIN32 #else #include <sys/ioctl.h> #include <sys/socket.h> #include <linux/wireless.h> #include <ifaddrs.h> #endif #include <QtCore/QDebug> #include <QtCore/QProcess> #include "tinyxml2.h" #include "Config.h" #include "ui_config.h" Config::Config() : QDialog() , mSettings( new QSettings( "BeyondChaos", "Flight" ) ) { ui = new Ui::Config; ui->setupUi(this); connect( this, SIGNAL( accepted() ), this, SLOT( Save() ) ); QStringList wlanList; #ifdef WIN32 #else struct ifaddrs *ifa, *ifap; getifaddrs( &ifap ); ifa = ifap; while ( ifa != nullptr ) { // if ( ifa->ifa_addr == NULL or ifa->ifa_addr->sa_family != AF_PACKET ) continue; bool iswifi = false; int sock = -1; struct iwreq pwrq; memset( &pwrq, 0, sizeof(pwrq) ); strncpy( pwrq.ifr_name, ifa->ifa_name, IFNAMSIZ ); sock = socket( AF_INET, SOCK_STREAM, 0 ); if ( ioctl( sock, SIOCGIWNAME, &pwrq ) != -1 ) { iswifi = true; } ::close(sock); if ( iswifi ) { printf( "add %s\n", ifa->ifa_name ); fflush(stdout); wlanList.append( ifa->ifa_name ); } ifa = ifa->ifa_next; } freeifaddrs( ifap ); #endif wlanList.removeDuplicates(); for ( auto wlan : wlanList ) { #ifdef WIN32 #else QProcess process; process.start( QString( "lshw -xml -c network -quiet" ) ); process.waitForFinished( -1 ); QString data = process.readAllStandardOutput(); tinyxml2::XMLDocument doc; doc.Parse( data.toStdString().c_str() ); for ( tinyxml2::XMLNode* node = doc.FirstChildElement( "list" )->FirstChildElement( "node" ); node != nullptr; node = node->NextSiblingElement( "node" ) ) { if ( QString(node->FirstChildElement("logicalname")->GetText()) == wlan ) { tinyxml2::XMLElement* vendor = node->FirstChildElement("vendor"); tinyxml2::XMLElement* product = node->FirstChildElement("product"); bool par = false; if ( vendor ) { wlan = wlan + " (" + QString( vendor->GetText() ); par = true; } if ( product ) { wlan = wlan + ( par ? "" : " (" ) + QString( product->GetText() ); par = true; } if ( par ) { wlan = wlan + ")"; } break; } } #endif ui->rawwifi_device->addItem( wlan ); } // Set controller settings ui->spectate->setChecked( value( "controller/spectate", false ).toBool() ); // Set connection settings ui->rawwifi->setChecked( value( "link/rawwifi", true ).toBool() ); ui->tcpip->setChecked( value( "link/tcpip", false ).toBool() ); // Set RawWifi settings ui->rawwifi_device->setCurrentText( value( "rawwifi/device", ui->rawwifi_device->count() > 0 ? ui->rawwifi_device->itemText(0) : "" ).toString() ); ui->rawwifi_channel->setCurrentIndex( value( "rawwifi/channel", 9 ).toInt() - 1 ); ui->rawwifi_controller_inport->setValue( value( "rawwifi/controller/inport", 1 ).toInt() ); ui->rawwifi_controller_nodrop->setChecked( value( "rawwifi/controller/nodrop", true ).toBool() ); ui->rawwifi_controller_cec->setCurrentText( value( "rawwifi/controller/cec", "Weighted" ).toString() ); ui->rawwifi_controller_outport->setValue( value( "rawwifi/controller/outport", 0 ).toInt() ); ui->rawwifi_controller_retries->setValue( value( "rawwifi/controller/retries", 2 ).toInt() ); ui->rawwifi_video_inport->setValue( value( "rawwifi/video/inport", 11 ).toInt() ); ui->rawwifi_video_nodrop->setChecked( value( "rawwifi/video/nodrop", true ).toBool() ); ui->rawwifi_video_cec->setCurrentText( value( "rawwifi/video/cec", "Weighted" ).toString() ); ui->rawwifi_video_outport->setValue( value( "rawwifi/video/outport", 10 ).toInt() ); ui->rawwifi_video_retries->setValue( value( "rawwifi/video/retries", 1 ).toInt() ); // Set TCP/IP settings ui->tcpip_drone_address->setText( value( "tcpip/address", "192.168.32.1" ).toString() ); ui->tcpip_controller_type->setCurrentText( value( "tcpip/controller/type", "TCP" ).toString() ); ui->tcpip_controller_port->setValue( value( "tcpip/controller/port", 2020 ).toInt() ); ui->tcpip_video_type->setCurrentText( value( "tcpip/video/type", "UDPLite" ).toString() ); ui->tcpip_video_port->setValue( value( "tcpip/video/port", 2021 ).toInt() ); #ifdef NO_RAWWIFI ui->rawwifi->setText( "Raw Wifi (not compiled in this build)" ); ui->rawwifi->setChecked( false ); ui->tcpip->setChecked( true ); ui->rawwifi->setEnabled( false ); ui->rawwifi_settings->setEnabled( false ); #endif } Config::~Config() { delete ui; delete mSettings; } void Config::Save() { setValue( "controller/spectate", ui->spectate->isChecked() ); setValue( "link/rawwifi", ui->rawwifi->isChecked() ); setValue( "link/tcpip", ui->tcpip->isChecked() ); setValue( "rawwifi/device", ui->rawwifi_device->currentText().mid( 0, ui->rawwifi_device->currentText().indexOf( " " ) ) ); setValue( "rawwifi/channel", ui->rawwifi_channel->currentIndex() + 1 ); setValue( "rawwifi/controller/inport", ui->rawwifi_controller_inport->value() ); setValue( "rawwifi/controller/nodrop", ui->rawwifi_controller_nodrop->isChecked() ); setValue( "rawwifi/controller/cec", ui->rawwifi_controller_cec->currentText() ); setValue( "rawwifi/controller/outport", ui->rawwifi_controller_outport->value() ); setValue( "rawwifi/controller/retries", ui->rawwifi_controller_retries->value() ); setValue( "rawwifi/video/inport", ui->rawwifi_video_inport->value() ); setValue( "rawwifi/video/nodrop", ui->rawwifi_video_nodrop->isChecked() ); setValue( "rawwifi/video/cec", ui->rawwifi_video_cec->currentText() ); setValue( "rawwifi/video/outport", ui->rawwifi_video_outport->value() ); setValue( "rawwifi/video/retries", ui->rawwifi_video_retries->value() ); setValue( "tcpip/address", ui->tcpip_drone_address->text() ); setValue( "tcpip/controller/type", ui->tcpip_controller_type->currentText() ); setValue( "tcpip/controller/port", ui->tcpip_controller_port->value() ); setValue( "tcpip/video/type", ui->tcpip_video_type->currentText() ); setValue( "tcpip/video/port", ui->tcpip_video_port->value() ); mSettings->sync(); qDebug() << "Saved config"; } void Config::setValue( const QString& key, const QVariant& value ) { mSettings->setValue( key, value ); } QVariant Config::value( const QString& key, const QVariant& defaultValue ) const { return mSettings->value( key, defaultValue ); }
6,956
C++
.cpp
166
39.554217
158
0.697904
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,806
BlackBox.cpp
dridri_bcflight/controller_pc/BlackBox.cpp
#include "BlackBox.h" #include "ui_blackbox.h" #include <QFileDialog> #include <QTextStream> #include <QCheckBox> #include <QPalette> #include <QDebug> BlackBox::BlackBox() { ui = new Ui::BlackBox; ui->setupUi(this); connect( ui->open, SIGNAL(pressed()), this, SLOT(openFile()) ); mData = new BlackBoxData(ui->table); mData->table = ui->table; ui->table->setModel( mData ); } BlackBox::~BlackBox() { delete ui; } void BlackBox::openFile() { QString fileName = QFileDialog::getOpenFileName( this, "Open BlackBox", "", "*.csv" ); if ( fileName == "" ) { return; } QFile inputFile( fileName ); if ( not inputFile.open( QIODevice::ReadOnly ) ) { return; } QStringList& names = mData->names; QStringList& instantValues = mData->instantValues; QList< QPair< uint64_t, QStringList > >& values = mData->values; names.clear(); instantValues.clear(); values.clear(); names.append( "time (µs)" ); names.append( "log" ); instantValues.append( "" ); QStringList groups; groups.append( "log" ); QTextStream in( &inputFile ); while ( not in.atEnd() ) { instantValues[ names.indexOf("log") - 1 ] = ""; // Reset log for ( QString& value : instantValues ) { if ( value.startsWith( "\x11" ) ) { value = value.mid( 1 ); } } QString sline = in.readLine(); QStringList line; for ( int32_t i = 0; i < sline.size(); ) { if ( line.size() == 2 ) { QString s = sline.mid( i ); if ( s[0] == '"' ) { s = s.mid( 1 ); if ( s[s.length()-1] == '"' ) { s = s.mid( 0, s.length() - 1 ); } } line.append( s ); break; } int32_t end = i + 1; if ( sline[i] == '"' ) { end = sline.indexOf( "\"", end ); } end = sline.indexOf( ",", end ); if ( end < 0 ) { end = sline.size(); } QString s = sline.mid( i, end - i ); if ( s[0] == '"' ) { s = s.mid( 1 ); if ( s[s.length()-1] == '"' ) { s = s.mid( 0, s.length() - 1 ); } } line.append( s ); i = end + 1; } if ( not names.contains( line[1] ) ) { names.append( line[1] ); instantValues.append( QString("\x11") + line[2] ); QString group = line[1].split(":")[0]; if ( not groups.contains( group ) ) { groups.append( group ); } } else { instantValues[ names.indexOf( line[1] ) - 1 ] = QString("\x11") + line[2]; } values.append( qMakePair( line[0].toULongLong(), instantValues ) ); } inputFile.close(); mData->updated(); for ( QString group : groups ) { QCheckBox* check = new QCheckBox( group ); check->setChecked( true ); ui->groupsLayout->addWidget( check ); } for ( QString item : names ) { if ( item != "time (µs)" and item != "log" ) { QCheckBox* check = new QCheckBox( item ); check->setChecked( true ); // ui->itemsLayout->addWidget( check ); } } } BlackBoxData::BlackBoxData( QObject *parent ) : QAbstractTableModel(parent) { } void BlackBoxData::updated() { emit headerDataChanged( Qt::Horizontal, 0, names.size() ); } int BlackBoxData::rowCount( const QModelIndex& /*parent*/ ) const { return values.size(); } int BlackBoxData::columnCount( const QModelIndex& /*parent*/ ) const { return names.size(); } QVariant BlackBoxData::headerData( int section, Qt::Orientation orientation, int role ) const { if ( role == Qt::DisplayRole and orientation == Qt::Horizontal ) { return names.at( section ); } return QVariant(); } QVariant BlackBoxData::data( const QModelIndex& index, int role ) const { const QPair< uint64_t, QStringList >& data = values[index.row()]; if ( role == Qt::FontRole ) { QFont font; if ( index.column() > 0 and index.column() - 1 < data.second.size() and data.second[ index.column() - 1 ].startsWith("\x11") ) { font.setBold(true); } return font; } else if ( role == Qt::BackgroundColorRole ) { if ( index.column() > 0 and index.column() - 1 < data.second.size() and data.second[ index.column() - 1 ].startsWith("\x11") ) { return table->palette().color( QPalette::AlternateBase ); } } else if ( role == Qt::DisplayRole ) { if ( index.column() == 0 ) { QString str = QString::number( (qulonglong)data.first ); QString str2; for ( int32_t i = 1; i <= str.length(); i++ ) { str2.insert( 0, str[str.length() - i] ); if ( i % 3 == 0 ) { str2.insert( 0, ' ' ); } } return str2; } if ( index.column() - 1 < data.second.size() ) { QString str = data.second[ index.column() - 1 ]; if ( str.startsWith("\x11") ) { str = str.mid( 1 ); } return str; } } return QVariant(); }
4,541
C++
.cpp
166
24.277108
130
0.61216
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,807
VideoEditor.cpp
dridri_bcflight/controller_pc/VideoEditor.cpp
#include <unistd.h> #include <mp4v2/mp4v2.h> #include <QtWidgets/QFileDialog> #include <QtCore/QTextStream> #include <QtCore/QDebug> #include <iostream> #include "VideoEditor.h" #include "ui_videoEditor.h" #include "ui/VideoViewer.h" extern "C" { #include "../../external/openh264-master/codec/api/svc/codec_api.h" } VideoEditor::VideoEditor() : QMainWindow() , ui( new Ui::VideoEditor ) , mInputFile( nullptr ) , mLastTimestamp( 0 ) , mDecoder( nullptr ) , mEncoder( nullptr ) { ui->setupUi(this); connect( ui->btnOpen, SIGNAL(pressed()), this, SLOT(Open()) ); connect( ui->btnExport, SIGNAL(pressed()), this, SLOT(Export()) ); connect( ui->play, SIGNAL(pressed()), this, SLOT(Play()) ); connect( ui->temp, SIGNAL(valueChanged(int)), this, SLOT(setWhiteBalanceTemperature(int)) ); connect( ui->vibrance, SIGNAL(valueChanged(int)), this, SLOT(setVibrance(int)) ); mPlayer = new PlayerThread( this ); } VideoEditor::~VideoEditor() { delete ui; } void VideoEditor::Open() { QString fileName = QFileDialog::getOpenFileName( this, "Open record", "/mnt/data/drone", "*.csv" ); if ( fileName == "" ) { return; } mInputFilename = fileName; if ( mInputFile ) { mInputFile->close(); delete mInputFile; } mInputFile = new QFile( fileName ); if ( not mInputFile->open( QIODevice::ReadOnly ) ) { return; } for ( Track* track : mTracks ) { delete track; } mTracks.clear(); ui->tree->clear(); QTreeWidgetItem* itemInfos = addTreeRoot( "Infos" ); QTreeWidgetItem* itemTracks = addTreeRoot( "Tracks" ); QTextStream in( mInputFile ); while ( not in.atEnd() ) { QString sline = in.readLine(); QStringList line = sline.split( "," ); if ( line[0] == "new_track" ) { Track* track = new Track; track->file = nullptr; track->cacheFile = nullptr; track->id = line[1].toUInt(); track->filename = line[3]; track->format = line[3].split(".").last(); QStringList infos = track->filename.split( QRegExp( "_|\\." ) ); QTreeWidgetItem* itemTrack = addTreeChild( itemTracks, QString::number( track->id ) ); addTreeChild( itemTrack, "type", line[2] ); addTreeChild( itemTrack, "file", track->filename ); addTreeChild( itemTrack, "format", infos.last() ); if ( line[2] == "video" ) { track->type = TrackTypeVideo; track->width = infos[1].split("x")[0].toUInt(); track->height = infos[1].split("x")[1].toUInt(); track->framerate = infos[2].split("fps")[0].toUInt(); addTreeChild( itemTrack, "width", QString::number(track->width) + " px" ); addTreeChild( itemTrack, "height", QString::number(track->height) + " px" ); addTreeChild( itemTrack, "framerate", QString::number(track->framerate) + " fps" ); } else if ( line[2] == "audio" ) { track->type = TrackTypeAudio; track->samplerate = infos[1].split("hz")[0].toUInt(); track->channels = infos[2].split("ch")[0].toUInt(); addTreeChild( itemTrack, "samplerate", QString::number(track->samplerate) + " Hz" ); addTreeChild( itemTrack, "channels", QString::number(track->channels) ); } mTracks.emplace_back( track ); } else if ( sline[0] >= '0' and sline[0] <= '9' ) { mLastTimestamp = line[1].toUInt(); } } addTreeChild( itemInfos, "tracks", QString::number( mTracks.size() ) ); addTreeChild( itemInfos, "duration", "00m:00s" ); addTreeChild( itemInfos, "total size", "0 KB" ); ui->tree->expandAll(); mTimeline.clear(); mInputFile->seek( 0 ); in.seek( 0 ); uint64_t first_record_time = 0; while ( not in.atEnd() ) { QString sline = in.readLine(); QStringList line = sline.split( "," ); if ( sline[0] == '#' or line[0] == "new_track" ) { continue; } Timepoint point; point.id = line[0].toUInt(); point.time = line[1].toUInt(); point.offset = line[2].toUInt(); point.size = line[3].toUInt(); if ( first_record_time == 0 ) { first_record_time = point.time; } point.time -= first_record_time; mTimeline.push_back( point ); } if ( mDecoder ) { WelsDestroyDecoder( mDecoder ); mDecoder = nullptr; } qDebug() << "WelsCreateDecoder :" << WelsCreateDecoder( &mDecoder ); SDecodingParam decParam; memset( &decParam, 0, sizeof (SDecodingParam) ); decParam.uiTargetDqLayer = UCHAR_MAX; decParam.eEcActiveIdc = ERROR_CON_SLICE_MV_COPY_CROSS_IDR;//ERROR_CON_SLICE_COPY; decParam.sVideoProperty.eVideoBsType = VIDEO_BITSTREAM_AVC; qDebug() << "mDecoder->Initialize :" << mDecoder->Initialize( &decParam ); } void VideoEditor::setWhiteBalanceTemperature( int t ) { ui->preview->setWhiteBalanceTemperature( (float)t ); } void VideoEditor::setVibrance( int t ) { ui->preview->setVibrance( (float)t / 50.0f ); } void VideoEditor::Export() { QString fileName = QFileDialog::getSaveFileName( this, "Save record", "", "*.mp4" ); if ( fileName == "" ) { return; } // MP4LogSetLevel( MP4_LOG_VERBOSE4 ); MP4FileHandle handle = MP4Create( fileName.toUtf8().data(), 0 ); std::vector< MP4TrackId > trackIds; for ( Track* track : mTracks ) { MP4TrackId trackId; if ( track->type == TrackTypeVideo ) { if ( track->format == "h264" ) { trackId = MP4AddH264VideoTrack( handle, 90 * 1000, MP4_INVALID_DURATION, track->width, track->height, 0, 0, 0, 3 ); } } else if ( track->type == TrackTypeAudio ) { if ( track->format == "mp3" ) { trackId = MP4AddAudioTrack( handle, track->samplerate, MP4_INVALID_DURATION, MP4_MP3_AUDIO_TYPE ); MP4SetTrackName( handle, trackId, ".mp3" ); MP4SetTrackIntegerProperty( handle, trackId, "mdia.minf.stbl.stsd.mp4a.channels", track->channels ); } } trackIds.emplace_back( trackId ); } MP4Duration first_record_time = 0; mInputFile->seek( 0 ); QTextStream in( mInputFile ); while ( not in.atEnd() ) { QString sline = in.readLine(); QStringList line = sline.split( "," ); if ( sline[0] == '#' or line[0] == "new_track" ) { continue; } uint32_t iID = line[0].toUInt(); MP4Duration record_time = line[1].toUInt(); uint32_t offset = line[2].toUInt(); uint32_t size = line[3].toUInt(); MP4TrackId& trackId = trackIds[iID]; Track* track = mTracks[iID]; if ( not track->file ) { track->file = new QFile( mInputFilename.mid( 0, mInputFilename.lastIndexOf("/") + 1 ) + track->filename ); track->file->open( QIODevice::ReadOnly ); } ui->progress->setValue( record_time * 100 / mLastTimestamp ); if ( first_record_time == 0 ) { first_record_time = record_time; } record_time -= first_record_time; uint8_t* buf = new uint8_t[ size ]; track->file->seek( offset ); qint64 read_ret = track->file->read( (char*)buf, size ); MP4Duration duration = MP4_INVALID_DURATION; QString nextLine; qint64 lastpos = in.pos(); while ( not in.atEnd() ) { nextLine = in.readLine(); if ( nextLine[0] >= '0' and nextLine[0] <= '9' and nextLine.split(",")[0].toUInt() == iID ) { duration = ( (MP4Duration)nextLine.split(",")[1].toUInt() - first_record_time ) - record_time; break; } } in.seek( lastpos ); if ( track->type == TrackTypeAudio ) { if ( duration == MP4_INVALID_DURATION ) { printf( "invalid duration\n" ); // duration = 1152; } else { printf( "audio timestamp : %lu => %lu [%lu]\n", record_time, record_time * track->samplerate / 1000000, duration ); MP4WriteSample( handle, trackId, buf, size, duration * track->samplerate / 1000000, 0/*record_time * track->samplerate / 1000000*/, false ); } } else { if ( duration == MP4_INVALID_DURATION ) { printf( "invalid duration\n" ); } else { printf( "video timestamp : %lu => %lu [%lu]\n", record_time, record_time * 90000 / 1000000, duration ); MP4WriteSample( handle, trackId, buf, size, duration * 90000 / 1000000, 0/*record_time * 90000 / 1000000*/, true ); } } // getchar(); delete[] buf; } MP4Close( handle ); } QTreeWidgetItem* VideoEditor::addTreeRoot( const QString& name, const QString& value ) { QTreeWidgetItem* treeItem = new QTreeWidgetItem( ui->tree ); treeItem->setText( 0, name ); treeItem->setText( 1, value ); return treeItem; } QTreeWidgetItem* VideoEditor::addTreeChild( QTreeWidgetItem* parent, const QString& name, const QString& value ) { QTreeWidgetItem* treeItem = new QTreeWidgetItem(); treeItem->setText( 0, name ); treeItem->setText( 1, value ); parent->addChild( treeItem ); return treeItem; } void VideoEditor::Play() { for ( auto track : mTracks ) { if ( not track->cacheFile ) { std::string file = ( mInputFilename.mid( 0, mInputFilename.lastIndexOf("/") + 1 ) + track->filename ).toStdString(); track->cacheFile = new FileCache( file, 8 * 1024 * 1024 ); } else { track->cacheFile->seek( 0 ); } } mPlayerIdx = 0; mPlayer->start(); } bool VideoEditor::play() { uint8_t* data[3]; SBufferInfo bufInfo; memset( data, 0, sizeof(data) ); memset( &bufInfo, 0, sizeof(SBufferInfo) ); VideoViewer::Plane& mY = ui->preview->planeY(); VideoViewer::Plane& mU = ui->preview->planeU(); VideoViewer::Plane& mV = ui->preview->planeV(); uint8_t src[1024 * 512]; Timepoint& point = mTimeline[mPlayerIdx++]; Track* track = mTracks[point.id]; if ( mPlayerStartTime == 0 ) { mPlayerStartTime = GetTicks(); } // skip audio for new if ( track->type == TrackTypeAudio ) { return true; } mPlayerFPSCounter++; if ( GetTicks() - mPlayerFPSTimer >= 1000000 ) { mPlayerFPSTimer = GetTicks(); mPlayerFPS = mPlayerFPSCounter; mPlayerFPSCounter = 0; } // skip if underrun if ( GetTicks() >= mPlayerStartTime + point.time ) { printf( "underrun [%d]\n", mPlayerFPS ); // return true; } track->cacheFile->seek( point.offset ); track->cacheFile->read( src, point.size ); DECODING_STATE ret = mDecoder->DecodeFrameNoDelay( src, (int)point.size, data, &bufInfo ); printf( " DecodeFrameNoDelay returned %08X [%d]\n", ret, mPlayerFPS ); if ( bufInfo.iBufferStatus == 1 ) { mY.stride = bufInfo.UsrData.sSystemBuffer.iStride[0]; mY.width = bufInfo.UsrData.sSystemBuffer.iWidth; mY.height = bufInfo.UsrData.sSystemBuffer.iHeight; mY.data = data[0]; mU.stride = bufInfo.UsrData.sSystemBuffer.iStride[1]; mU.width = bufInfo.UsrData.sSystemBuffer.iWidth / 2; mU.height = bufInfo.UsrData.sSystemBuffer.iHeight / 2; mU.data = data[1]; mV.stride = bufInfo.UsrData.sSystemBuffer.iStride[1]; mV.width = bufInfo.UsrData.sSystemBuffer.iWidth / 2; mV.height = bufInfo.UsrData.sSystemBuffer.iHeight / 2; mV.data = data[2]; // WaitTick( mPlayerStartTime + point.time ); ui->preview->invalidate(); } return true; } uint64_t VideoEditor::GetTicks() { struct timespec now; clock_gettime( CLOCK_MONOTONIC, &now ); return (uint64_t)now.tv_sec * 1000000ULL + (uint64_t)now.tv_nsec / 1000ULL; } void VideoEditor::WaitTick( uint64_t final ) { if ( GetTicks() >= final ) { std::cout << "skip " << ( GetTicks() - final ) << " (" << ( final - mPlayerStartTime ) << ")" << "\n"; return; } usleep( final - GetTicks() - 10 ); }
10,901
C++
.cpp
312
32.153846
144
0.673855
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,808
HStatusBar.cpp
dridri_bcflight/controller_pc/ui/HStatusBar.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 <QtGui/QPainter> #include <QtGui/QPainterPath> #include <QtCore/QDebug> #include "HStatusBar.h" HStatusBar::HStatusBar( QWidget* parent ) : QWidget( parent ) , mValue( 50 ) , mMaxValue( 100 ) { } HStatusBar::~HStatusBar() { } void HStatusBar::setValue( int32_t v ) { mValue = v; // repaint(); } void HStatusBar::setMaxValue( int32_t v ) { mMaxValue = v; } void HStatusBar::setSuffix( const QString& sfx ) { mSuffix = sfx; } void HStatusBar::paintEvent( QPaintEvent* ev ) { QColor backGroundColor = palette().color( QPalette::Base ); QColor contourColor = palette().color( QPalette::Button ); QColor fillColor = palette().color( QPalette::Link ); QColor foreGroundColor = palette().color( QPalette::WindowText ); QPainter painter( this ); QPainterPath backpath; backpath.addRoundedRect( QRectF( 0, 0, width() - 1, height() - 1 ), 2, 2 ); painter.fillPath( backpath, backGroundColor ); painter.setPen( contourColor ); painter.drawPath( backpath ); QPainterPath path; path.addRoundedRect( QRectF( 2, 2, ( std::min( mValue, mMaxValue ) ) * ( width() - 4 ) / mMaxValue, height() - 4 ), 2, 2 ); painter.fillPath( path, fillColor/*QColor( 0, 64, 128 )*/ ); painter.setFont( QFont( "Helvetica", height() / 2 ) ); painter.setPen( foreGroundColor ); painter.drawText( QRect( 0, 0, width(), height() ), Qt::AlignCenter, QString::number( mValue ) + mSuffix ); }
2,111
C++
.cpp
62
32.16129
124
0.723697
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,809
VideoViewer.cpp
dridri_bcflight/controller_pc/ui/VideoViewer.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 <GL/gl.h> #include <QtCore/QDebug> #include <QtGui/QPainter> #include "VideoViewer.h" #if ( defined(WIN32) && !defined(glActiveTexture) ) PFNGLACTIVETEXTUREPROC glActiveTexture = 0; #endif VideoViewer::VideoViewer( QWidget* parent ) : QGLWidget( parent ) , mWidth( 0 ) , mHeight( 0 ) , mShader( nullptr ) , mFpsCounter( 0 ) , mFps( 0 ) , mFpsTimer( QElapsedTimer() ) , mParentWidget( parent ) , mVibrance( 0.0f ) , mTemperature( 0.0f ) { memset( &mY, 0, sizeof(mY) ); memset( &mU, 0, sizeof(mU) ); memset( &mV, 0, sizeof(mV) ); #ifdef WIN32 if ( glActiveTexture == 0 ) { glActiveTexture = (PFNGLACTIVETEXTUREPROC)GetProcAddress( LoadLibrary("opengl32.dll"), "glActiveTexture" ); } #endif connect( this, SIGNAL( repaintEmitter() ), this, SLOT( repaintReceiver() ) ); } VideoViewer::~VideoViewer() { } VideoViewer::Plane& VideoViewer::planeY() { return mY; } VideoViewer::Plane& VideoViewer::planeU() { return mU; } VideoViewer::Plane& VideoViewer::planeV() { return mV; } int32_t VideoViewer::fps() { return mFps; } void VideoViewer::invalidate() { emit repaintEmitter(); } void VideoViewer::repaintReceiver() { repaint(); } void VideoViewer::paintGL() { if ( not mShader ) { mShader = new QGLShaderProgram(); mShader->addShaderFromSourceCode( QGLShader::Vertex, R"( attribute highp vec2 vertex; attribute highp vec2 tex; varying vec2 texcoords; void main(void) { texcoords = vec2( tex.s, 1.0 - tex.t ); gl_Position = vec4( vertex, 0.0, 1.0 ); })" ); mShader->addShaderFromSourceCode( QGLShader::Fragment, R"( uniform sampler2D texY; uniform sampler2D texU; // uniform sampler2D texV; uniform float exposure_value; uniform float gamma_compensation; uniform float temperature; uniform float vibrance; varying vec2 texcoords; vec3 rgb2hsv(vec3 c) { vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)); vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); float d = q.x - min(q.w, q.y); float e = 1.0e-10; return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); } vec3 hsv2rgb(vec3 c) { vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); } vec4 fetch( vec2 coords ) { float y = 2.0 * texture2D( texY, coords ).r; float u = 2.0 * (texture2D( texU, coords * vec2(1.0, 0.5) + vec2(0.0, 0.0) ).r - 0.5); float v = 2.0 * (texture2D( texU, coords * vec2(1.0, 0.5) + vec2(0.0, 0.5) ).r - 0.5); float r = (y/2.0 + 1.402/2.0 * v); float g = (y/2.0 - 0.344136 * u/2.0 - 0.714136 * v/2.0); float b = (y/2.0 + 1.773/2.0 * u); return clamp( vec4( r, g, b, 1.0 ), vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0) ); } void main(void) { vec4 color = fetch( texcoords.st ); color.rgb = vec3(1.0) - exp( -color.rgb * vec3(exposure_value, exposure_value, exposure_value) ); color.rgb = pow( color.rgb, vec3( 1.0 / gamma_compensation, 1.0 / gamma_compensation, 1.0 / gamma_compensation ) ); vec3 hsv = rgb2hsv( color.rgb ); hsv.y *= vibrance; color.rgb = hsv2rgb( hsv ); gl_FragColor = color; gl_FragColor.a = 1.0; })" ); mShader->link(); mShader->bind(); mExposureID = mShader->uniformLocation( "exposure_value" ); mGammaID = mShader->uniformLocation( "gamma_compensation" ); mTemperatureID = mShader->uniformLocation( "temperature" ); mVibranceID = mShader->uniformLocation( "vibrance" ); } // if ( mY.tex == 0 and mU.tex == 0 and mV.tex == 0 and mY.stride > 0 and mY.height > 0 ) { if ( mY.tex == 0 or mU.tex == 0 or mY.stride != mWidth or mY.height != mHeight ) { if ( mY.tex ) { glDeleteTextures( 1, &mY.tex ); } if ( mU.tex ) { glDeleteTextures( 1, &mU.tex ); } mWidth = mY.stride; mHeight = mY.height; printf( "====> SIZE : %d x %d\n", mY.stride, mY.height ); glGenTextures( 1, &mY.tex ); glBindTexture( GL_TEXTURE_2D, mY.tex ); glTexImage2D( GL_TEXTURE_2D, 0, GL_R8, mY.stride, mY.height, 0, GL_RED, GL_UNSIGNED_BYTE, NULL ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); glGenTextures( 1, &mU.tex ); glBindTexture( GL_TEXTURE_2D, mU.tex ); glTexImage2D( GL_TEXTURE_2D, 0, GL_R8, mU.stride, mU.height + mV.height, 0, GL_RED, GL_UNSIGNED_BYTE, NULL ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); } glViewport( 0, 0, width(), height() ); glClear( GL_COLOR_BUFFER_BIT ); static float quadVertices[] = { // X, Y, U, V 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, }; quadVertices[2] = (float)mY.width / (float)mY.stride; quadVertices[6] = (float)mY.width / (float)mY.stride; mShader->bind(); glBindTexture( GL_TEXTURE_2D, 0 ); if ( not mY.data or not mU.data or not mV.data ) { return; } int vertexLocation = mShader->attributeLocation( "vertex" ); int texLocation = mShader->attributeLocation( "tex" ); mShader->enableAttributeArray( vertexLocation ); mShader->enableAttributeArray( texLocation ); mShader->setAttributeArray( vertexLocation, quadVertices, 2, sizeof(float)*4 ); mShader->setAttributeArray( texLocation, quadVertices + 2, 2, sizeof(float)*4 ); int loc_Y = mShader->uniformLocation( "texY" ); int loc_U = mShader->uniformLocation( "texU" ); // int loc_V = mShader->uniformLocation( "texV" ); mShader->setUniformValue( loc_Y, 0 ); mShader->setUniformValue( loc_U, 1 ); // mShader->setUniformValue( loc_V, 2 ); // night mode // mShader->setUniformValue( mExposureID, 4.0f ); // mShader->setUniformValue( mGammaID, 2.5f ); mShader->setUniformValue( mExposureID, 1.0f ); mShader->setUniformValue( mGammaID, 1.0f ); mShader->setUniformValue( mTemperatureID, mTemperature ); mShader->setUniformValue( mVibranceID, mVibrance ); glActiveTexture( GL_TEXTURE0 ); glEnable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, mY.tex ); glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, mY.stride, mY.height, GL_RED, GL_UNSIGNED_BYTE, mY.data ); glActiveTexture( GL_TEXTURE1 ); glEnable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, mU.tex ); uint8_t* d = new uint8_t[ ( mU.stride * mU.height + mU.stride * mV.height ) * 2 ]; memcpy( d, mU.data, mU.stride * mU.height ); memcpy( d + mU.stride * mU.height, mV.data, mU.stride * mV.height ); glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, mU.stride, mU.height + mV.height, GL_RED, GL_UNSIGNED_BYTE, d ); delete[] d; glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); mShader->disableAttributeArray( vertexLocation ); mShader->disableAttributeArray( texLocation ); }
7,895
C++
.cpp
211
34.701422
119
0.672896
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,810
RawWifiRx.cpp
dridri_bcflight/librawwifi++/RawWifiRx.cpp
#include <Debug.h> #include "RawWifi.h" #include "constants.h" #include "radiotap.h" #if __BYTE_ORDER == __LITTLE_ENDIAN #define le16_to_cpu(x) (x) #define le32_to_cpu(x) (x) #else #define le16_to_cpu(x) ((((x)&0xff)<<8)|(((x)&0xff00)>>8)) #define le32_to_cpu(x) \ ((((x)&0xff)<<24)|(((x)&0xff00)<<8)|(((x)&0xff0000)>>8)|(((x)&0xff000000)>>24)) #endif #define unlikely(x) (x) #ifdef __linux__ static uint64_t _rawwifi_get_tick() { struct timespec now; clock_gettime( CLOCK_MONOTONIC, &now ); return (uint64_t)now.tv_sec * 1000000ULL + (uint64_t)now.tv_nsec / 1000ULL; } #elif _WIN32 #endif using namespace rawwifi; RawWifi::PenumbraRadiotapData RawWifi::iterateIEEE80211Header( struct ieee80211_radiotap_header* payload, uint32_t payload_len ) { struct ieee80211_radiotap_iterator rti; PenumbraRadiotapData prd; int32_t ret; ret = ieee80211_radiotap_iterator_init( &rti, payload, payload_len ); if ( ret < 0 ) { throw std::runtime_error( "ieee80211_radiotap_iterator_init() failed : " + std::to_string( ret ) ); } // int link_update = 0; int n = 0; while ( ( n = ieee80211_radiotap_iterator_next(&rti) ) == 0 ) { switch ( rti.this_arg_index ) { case IEEE80211_RADIOTAP_RATE: { // rwifi->recv_link.rate = (*rti.this_arg); break; } case IEEE80211_RADIOTAP_CHANNEL: { // uint16_t channel = le16_to_cpu(*((uint16_t *)rti.this_arg)); uint16_t flags = le16_to_cpu(*((uint16_t *)(rti.this_arg + 2))); // rwifi->recv_link.channel = channel; prd.nChannelFlags = flags; break; } case IEEE80211_RADIOTAP_ANTENNA: { // rwifi->recv_link.antenna = (*rti.this_arg) + 1; break; } case IEEE80211_RADIOTAP_FLAGS: { prd.nRadiotapFlags = *rti.this_arg; break; } case IEEE80211_RADIOTAP_DBM_ANTSIGNAL: { // rwifi->recv_link.signal = (int8_t)(*rti.this_arg); break; } default: { break; } } } return prd; } int32_t RawWifi::ReceiveFrame( uint8_t buffer[1450*2], int32_t* valid, uint32_t timeout_ms ) { struct pcap_pkthdr* ppcapPacketHeader = nullptr; uint8_t* payload = 0; gDebug() << "pcap_next_ex() lock"; mRxMutex.lock(); gDebug() << "pcap_next_ex()"; int retval = pcap_next_ex( mRxPcap->getPcap(), &ppcapPacketHeader, (const uint8_t**)&payload ); gDebug() << "pcap_next_ex() retval = " << retval; if ( retval < 0 ) { gError() << "pcap_next_ex() failed : " << pcap_geterr( mRxPcap->getPcap() ); mRxMutex.unlock(); return retval; } if ( retval != 1 ) { if ( mBlocking ) { mRxMutex.unlock(); gError() << "pcap_next_ex() unexpected failure : " << pcap_geterr( mRxPcap->getPcap() ); return retval; } mRxMutex.unlock(); // Timeout return 0; } if ( payload == nullptr ) { gError() << "pcap_next_ex() returned a null payload"; mRxMutex.unlock(); return -1; } uint16_t u16HeaderLen = (payload[2] + (payload[3] << 8)); if ( ppcapPacketHeader->len < ( u16HeaderLen + mRxPcap->getHeaderLength() ) ) { gError() << "ppcapPacketHeader->len < ( u16HeaderLen + rwifi->n80211HeaderLength )"; mRxMutex.unlock(); return 0; } int32_t bytes = (int32_t)ppcapPacketHeader->len - (int32_t)( u16HeaderLen + mRxPcap->getHeaderLength() ); if ( bytes < 0 ) { gError() << "bytes < 0"; mRxMutex.unlock(); return 0; } const uint8_t* u8aIeeeHeader = payload + u16HeaderLen; uint8_t port = u8aIeeeHeader[sizeof(uint32_t) + sizeof(uint8_t)*6 + sizeof(uint8_t)*5]; if ( port != mRxPort ) { mRxMutex.unlock(); return 0; } PenumbraRadiotapData prd; try { prd = iterateIEEE80211Header( (struct ieee80211_radiotap_header*)payload, ppcapPacketHeader->len ); } catch ( std::exception& e ) { gError() << "iterateIEEE80211Header() failed : " << e.what(); mRxMutex.unlock(); return 0; } *valid = -1; if ( prd.nRadiotapFlags & IEEE80211_RADIOTAP_F_FCS ) { bytes -= 4; *valid = ( ( prd.nRadiotapFlags & IEEE80211_RADIOTAP_F_BADFCS ) == 0 ); } memcpy( buffer, payload + u16HeaderLen + mRxPcap->getHeaderLength(), bytes ); mRxMutex.unlock(); return bytes; } int32_t RawWifi::ProcessFrame( uint8_t frameBuffer[1450*2], uint32_t frameSize, uint8_t dataBuffer[1450*2], int32_t* frameValid ) { PacketHeader* frameHeader = (PacketHeader*)frameBuffer; uint8_t* pu8Payload = frameBuffer + sizeof( PacketHeader ); frameSize -= sizeof( PacketHeader ); if ( frameHeader->header_crc != crc16( (uint8_t*)frameHeader, sizeof(PacketHeader) - sizeof(uint16_t) ) ) { gError() << "Invalid header CRC, dropping ! [" << frameHeader->block_id << ":" << frameHeader->packet_id << "]"; return 0; } if ( frameHeader->packet_id >= frameHeader->packets_count || frameHeader->packet_id > RAWWIFI_MAX_PACKET_PER_BLOCK || frameHeader->packets_count > RAWWIFI_MAX_PACKET_PER_BLOCK ) { gError() << "Invalid packet_id/packets_count, dropping !\n" << "header = {\n" << " block_id = " << (int)frameHeader->block_id << "\n" << " packet_id = " << (int)frameHeader->packet_id << "\n" << " packets_count = " << (int)frameHeader->packets_count << "\n" << " retry_id = " << (int)frameHeader->retry_id << "\n" << " retries_count = " << (int)frameHeader->retries_count << "\n" << " block_flags = " << (int)frameHeader->block_flags << "\n" << "}\n"; return 0; } /* if ( rwifi->recv_last_returned >= header->block_id + 32 ) { // More than 32 underruns, TX has probably been resetted rwifi->recv_last_returned = 0; free( rwifi->recv_block ); rwifi->recv_block = NULL; } */ int32_t isValid = 0; if ( *frameValid == 0 ) { gTrace() << "pcap says frame's CRC is invalid"; } else if ( *frameValid == 1 ) { gTrace() << "pcap says frame's CRC is valid"; isValid = 1; } else if ( (int32_t)*frameValid < 0 ) { // pcap doesn't know if frame is valid, so check it uint32_t calculated_crc = crc32( pu8Payload, frameSize ); isValid = ( frameHeader->crc == calculated_crc ); if ( isValid == 0 ) { gWarning() << "Invalid CRC ! (" << std::hex << frameHeader->crc << " != " << calculated_crc << ")"; } } if ( frameHeader->block_id <= mRxLastCompletedBlockId ) { gTrace() << "Block " << frameHeader->block_id << " already completed"; return 0; } gTrace() << "header = {\n" << " block_id = " << (int)frameHeader->block_id << "\n" << " packet_id = " << (int)frameHeader->packet_id << "\n" << " packets_count = " << (int)frameHeader->packets_count << "\n" << " retry_id = " << (int)frameHeader->retry_id << "\n" << " retries_count = " << (int)frameHeader->retries_count << "\n" << " block_flags = " << (int)frameHeader->block_flags << "\n" << "}, valid = " << isValid; memcpy( dataBuffer, pu8Payload, frameSize ); *frameValid = isValid; return frameSize; } int32_t RawWifi::Receive( uint8_t* buffer, uint32_t maxBufferSize, bool* valid, uint32_t timeout_ms ) { uint64_t startTickMicros = _rawwifi_get_tick(); bool packetComplete = false; while ( ( timeout_ms == 0 and mBlocking ) or ( _rawwifi_get_tick() - startTickMicros < timeout_ms * 1000 and not packetComplete ) ) { uint8_t frameBuffer[1450*2] = { 0 }; int32_t frameValid = 0; int32_t frameSize = ReceiveFrame( frameBuffer, &frameValid, timeout_ms ); if ( frameSize < 0 ) { gError() << "ReceiveFrame() failed : " << frameSize; return frameSize; } if ( frameSize == 0 ) { continue; } if ( frameSize > RAWWIFI_MAX_USER_PACKET_LENGTH + 128 ) { gError() << "frameSize > RAWWIFI_MAX_USER_PACKET_LENGTH + 128"; continue; } PacketHeader* frameHeader = (PacketHeader*)frameBuffer; uint8_t dataBuffer[1450*2] = { 0 }; int32_t dataSize = ProcessFrame( frameBuffer, frameSize, dataBuffer, &frameValid ); if ( dataSize < 0 ) { gError() << "ProcessFrame() failed : " << dataSize; return dataSize; } if ( dataSize == 0 ) { continue; } // Simple case : only one packet in the block if ( frameHeader->packets_count == 1 ) { if ( frameValid ) { memcpy( buffer, dataBuffer, dataSize ); return dataSize; } continue; } // New block if ( frameHeader->block_id != mRxBlock.id ) { mRxBlock.id = frameHeader->block_id; mRxBlock.valid = 0; mRxBlock.ticks = _rawwifi_get_tick(); mRxBlock.packets_count = frameHeader->packets_count; memset( mRxBlock.packets, 0, sizeof( mRxBlock.packets ) ); } // Check if the packet is already valid, if not, store it if ( mRxBlock.packets[frameHeader->packet_id].size == 0 or not mRxBlock.packets[frameHeader->packet_id].valid ) { memcpy( mRxBlock.packets[frameHeader->packet_id].data, dataBuffer, dataSize ); mRxBlock.packets[frameHeader->packet_id].size = dataSize; mRxBlock.packets[frameHeader->packet_id].valid = frameValid; gTrace() << "set packet " << frameHeader->packet_id << "/" << frameHeader->packets_count << " data to " << (void*)mRxBlock.packets[frameHeader->packet_id].data; } else { gTrace() << "packet " << frameHeader->packet_id << "/" << frameHeader->packets_count << " already valid"; } // Check if the block is complete bool blockOk = true; for ( uint32_t i = 0; i < mRxBlock.packets_count; i++ ) { if ( mRxBlock.packets[i].size == 0 or not mRxBlock.packets[i].valid ) { blockOk = false; break; } } // All packets received, return the block as is even if it's not valid if ( !blockOk and ( frameHeader->packet_id >= mRxBlock.packets_count - 1 or mRxBlock.packets[mRxBlock.packets_count-1].size > 0 ) ) { gDebug() << "Block " << mRxBlock.id << " half empty, deal with it"; blockOk = true; } if ( blockOk ) { uint32_t allValid = 0; uint32_t offset = 0; for ( uint32_t i = 0; i < mRxBlock.packets_count; i++ ) { if ( mRxBlock.packets[i].size > 0 ) { if ( offset + mRxBlock.packets[i].size >= maxBufferSize - 1 ) { break; } gTrace() << "[" << i+1 << "/" << mRxBlock.packets_count << "] memcpy( " << (void*)(buffer + offset) << ", " << (void*)mRxBlock.packets[i].data << ", " << mRxBlock.packets[i].size << " ) [" << ( mRxBlock.packets[i].valid ? "valid" : "invalid" ) << "]"; memcpy( buffer + offset, mRxBlock.packets[i].data, mRxBlock.packets[i].size ); offset += mRxBlock.packets[i].size; allValid += ( mRxBlock.packets[i].valid != 0 ); } else { gDebug() << "Leak : packet " << i << "/" << mRxBlock.packets_count << " is missing, lost size is " << mRxBlock.packets[i].size << " bytes, filling with zeros"; // if ( i < mRxBlock.packets_count - 1 && rwifi->recv_recover == RAWWIFI_FILL_WITH_ZEROS ) { memset( buffer + offset, 0, RAWWIFI_MAX_USER_PACKET_LENGTH - mHeadersLenght ); offset += RAWWIFI_MAX_USER_PACKET_LENGTH - mHeadersLenght; // } } if ( offset >= maxBufferSize - 1 ) { break; } } mRxBlock.valid = ( allValid == mRxBlock.packets_count ); /* if ( mRxBlock.valid ) { rwifi->recv_perf_valid++; } else { rwifi->recv_perf_invalid++; } */ *valid = mRxBlock.valid; gTrace() << "block " << mRxBlock.id << " " << ( mRxBlock.valid ? "valid":"invalid" ) << " : " << offset << " bytes total"; mRxLastCompletedBlockId = mRxBlock.id; /* if ( frameHeader->block_flags & RAWWIFI_BLOCK_FLAGS_HAMMING84 ) { return rawwifi_hamming84_decode( pret, pret, offset ); } */ return offset; } } return 0; }
11,288
C++
.cpp
306
33.581699
164
0.638208
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,811
RawWifiTx.cpp
dridri_bcflight/librawwifi++/RawWifiTx.cpp
#include <Debug.h> #include "RawWifi.h" #include "constants.h" #include "ieee80211_radiotap.h" using namespace rawwifi; int32_t RawWifi::Send( const uint8_t* buffer, uint32_t size, uint8_t retries ) { fDebug( (void*)buffer, size, (int)retries ); if ( retries > 16 ) { gError() << "Too many retries asked (" << retries << ", max is 16)"; return -1; } int32_t sent = 0; int32_t remain = size; uint16_t packet_id = 0; const uint8_t* data = buffer; uint32_t datalen = size; /* if ( send_block_flags & RAWWIFI_BLOCK_FLAGS_HAMMING84 ) { data = (uint8_t*)malloc( datalen_ * 2 ); datalen = rawwifi_hamming84_encode( data, data_, datalen_ ); remain = datalen; } */ uint16_t packets_count = ( datalen / ( RAWWIFI_MAX_USER_PACKET_LENGTH - mHeadersLenght ) ) + 1; mSendBlockId++; while ( sent < (int32_t)datalen ) { int32_t len = RAWWIFI_MAX_USER_PACKET_LENGTH - mHeadersLenght; if ( len > remain ) { len = remain; } SendFrame( data + sent, len, mSendBlockId, BLOCK_FLAGS_NONE, packet_id, packets_count, retries ); packet_id++; sent += len; remain -= len; } /* if ( rwifi->send_block_flags & RAWWIFI_BLOCK_FLAGS_HAMMING84 ) { free( data ); } */ return sent; } int32_t RawWifi::SendFrame( const uint8_t* data, uint32_t datalen, uint32_t block_id, BlockFlags block_flags, uint16_t packet_id, uint16_t packets_count, uint32_t retries ) { mTxMutex.lock(); mTxBuffer[sizeof(RadiotapHeader) + sizeof(uint32_t) + sizeof(uint8_t)*6 + sizeof(uint8_t)*5 ] = mTxPort; mTxBuffer[sizeof(RadiotapHeader) + sizeof(uint32_t) + sizeof(uint8_t)*6 + sizeof(uint8_t)*6 + sizeof(uint8_t)*5 ] = mTxPort; PacketHeader* header = (PacketHeader*)( mTxBuffer + mHeadersLenght - sizeof( PacketHeader ) ); header->block_id = block_id; header->packet_id = packet_id; header->packets_count = packets_count; header->retries_count = retries; header->block_flags = block_flags; header->crc = crc32( data, datalen ); memcpy( mTxBuffer + mHeadersLenght, data, datalen ); int32_t plen = datalen + mHeadersLenght; int r = 0; for ( uint32_t i = 0; i < retries; i++ ) { header->retry_id = i; header->header_crc = crc16( (uint8_t*)header, sizeof(PacketHeader) - sizeof(PacketHeader::header_crc) ); r = pcap_inject( mTxPcap->getPcap(), mTxBuffer, plen ); if ( r != plen ) { char* err = pcap_geterr( mTxPcap->getPcap() ); gError() << "[" << i + 1 << "/" << retries << "] Trouble injecting packet : " << err << ". Sent " << r << " / " << plen; mTxMutex.unlock(); return -1; } else { gTrace() << "[" << block_id << ", " << packet_id << ", " << i + 1 << "/" << retries << "] Sent " << r << " / " << plen; } } mTxMutex.unlock(); return plen; } void RawWifi::initTxBuffer( uint8_t* buffer, uint32_t size ) { RadiotapHeader radiotapHeader; memset( &radiotapHeader, 0, sizeof(RadiotapHeader) ); radiotapHeader.version = 0; radiotapHeader.padding = 0; radiotapHeader.length = sizeof(RadiotapHeader); radiotapHeader.presence = /*(1 << IEEE80211_RADIOTAP_RATE) |*/ (1 << IEEE80211_RADIOTAP_TX_FLAGS); // radiotapHeader.rate = 54000000 / 500000; // 54mbps radiotapHeader.txFlags = /*IEEE80211_RADIOTAP_F_FCS | */IEEE80211_RADIOTAP_F_TX_NOACK; if ( true ) { radiotapHeader.presence |= (1 << IEEE80211_RADIOTAP_MCS); radiotapHeader.mcs.known = IEEE80211_RADIOTAP_MCS_HAVE_MCS | IEEE80211_RADIOTAP_MCS_HAVE_BW | IEEE80211_RADIOTAP_MCS_HAVE_GI | IEEE80211_RADIOTAP_MCS_HAVE_STBC | IEEE80211_RADIOTAP_MCS_HAVE_FEC ; radiotapHeader.mcs.modulationIndex = 3; radiotapHeader.mcs.flags = IEEE80211_RADIOTAP_MCS_BW_20; // radiotapHeader.mcs.flags |= IEEE80211_RADIOTAP_MCS_SGI; radiotapHeader.mcs.flags |= IEEE80211_RADIOTAP_MCS_FEC_LDPC; } /* Penumbra IEEE80211 header */ static uint8_t u8aIeeeHeader[] = { 0x08, 0x01, // Control fields 0x00, 0x00, // Duration 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x13, 0x22, 0x33, 0x44, 0x55, 0x66, 0x13, 0x22, 0x33, 0x44, 0x55, 0x66, // 0x10, 0x86, 0x00, 0x00, }; memcpy( buffer, &radiotapHeader, sizeof( radiotapHeader ) ); buffer += sizeof( radiotapHeader ); memcpy( buffer, u8aIeeeHeader, sizeof( u8aIeeeHeader ) ); buffer += sizeof( u8aIeeeHeader ); mHeadersLenght = sizeof( radiotapHeader ) + sizeof( u8aIeeeHeader ) + sizeof(PacketHeader); }
4,277
C++
.cpp
113
35.345133
172
0.684769
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,812
RawWifi.cpp
dridri_bcflight/librawwifi++/RawWifi.cpp
#include <Debug.h> #include "RawWifi.h" #include "constants.h" using namespace rawwifi; RawWifi::RawWifi( const std::string& device, uint8_t rx_port, uint8_t tx_port, bool blocking, int32_t read_timeout_ms ) : mDevice( device ) , mRxPort( rx_port ) , mTxPort( tx_port ) , mBlocking( blocking ) , mReadTimeoutMs( read_timeout_ms ) , mIwSocket( -1 ) , mRxPcap( nullptr ) , mRxFecMode( RxFecMode::RX_FAST ) , mRxBlockRecoverMode( RxBlockRecoverMode::FILL_WITH_ZEROS ) , mRxLastCompletedBlockId( 0 ) , mRxBlock({ 0xFFFFFFFF, 0, 0, 0 }) , mTxPcap( nullptr ) , mSendBlockId( 0 ) { fDebug( device, (int)rx_port, (int)tx_port, (int)blocking, read_timeout_ms ); mCompileMutex.lock(); try { mRxPcap = new PcapHandler( device, rx_port, blocking, read_timeout_ms ); mRxPcap->CompileFilter(); } catch ( std::exception& e ) { gError() << "Failed to setup RawWifi RX : " << e.what(); } try { mTxPcap = new PcapHandler( device, tx_port, false, 1 ); } catch ( std::exception& e ) { gError() << "Failed to setup RawWifi TX : " << e.what(); } if ( !mRxPcap or !mTxPcap ) { mCompileMutex.unlock(); throw std::runtime_error( "Failed to setup RX/TX" ); } initTxBuffer( mTxBuffer, sizeof( mTxBuffer ) ); mCompileMutex.unlock(); } RawWifi::~RawWifi() { if ( mRxPcap ) { delete mRxPcap; } if ( mTxPcap ) { delete mTxPcap; } } uint32_t RawWifi::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; } uint16_t RawWifi::crc16( const uint8_t* buf, uint32_t len ) { uint8_t x; uint16_t crc = 0xFFFF; while ( len-- ) { x = crc >> 8 ^ *buf++; x ^= x >> 4; crc = (crc << 8) ^ ((uint16_t)(x << 12)) ^ ((uint16_t)(x <<5)) ^ ((uint16_t)x); } return crc; }
1,890
C++
.cpp
72
23.986111
119
0.633889
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,813
WifiInterfaceLinux.cpp
dridri_bcflight/librawwifi++/WifiInterfaceLinux.cpp
#include <unistd.h> #include <dirent.h> #include <sys/fcntl.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <net/if.h> #include <netlink/genl/genl.h> #include <netlink/genl/family.h> #include <netlink/genl/ctrl.h> #include <netlink/msg.h> #include <netlink/attr.h> #include "WifiInterfaceLinux.h" #include "Debug.h" using namespace rawwifi; WifiInterfaceLinux::WifiInterfaceLinux( const std::string name, uint32_t channel, uint32_t txpower, uint32_t bHT, uint32_t bitrate ) : WifiInterface( name, channel, txpower, bHT, bitrate ) { fDebug( name, channel, txpower, bHT, bitrate ); int ret = 0; nl80211_state* state = (nl80211_state*)malloc( sizeof( nl80211_state ) ); strncpy( state->ifr, name.c_str(), sizeof(state->ifr) ); state->fd = socket( AF_INET, SOCK_DGRAM, 0 ); struct ifreq ifr; strcpy( ifr.ifr_name, name.c_str() ); ioctl( state->fd, SIOCGIFHWADDR, &ifr ); memcpy( state->hwaddr, ifr.ifr_hwaddr.sa_data, 6 ); char hwaddr[64] = ""; sprintf( hwaddr, "%02x:%02x:%02x:%02x:%02x:%02x", state->hwaddr[0], state->hwaddr[1], state->hwaddr[2], state->hwaddr[3], state->hwaddr[4], state->hwaddr[5] ); state->devidx = if_nametoindex( name.c_str() ); state->phyidx = phyMacToIndex( hwaddr ); if ( state->phyidx < 0 ) { throw std::runtime_error( "Error : interface '" + name + "' not found !" ); } gDebug() << "Interface " << name << ":\n" << " HWaddr = " << hwaddr << "\n" << " devidx = " << state->devidx << "\n" << " phyidx = " << state->phyidx; state->nl_sock = nl_socket_alloc(); if ( !state->nl_sock ) { throw std::runtime_error( "Error : Failed to allocate netlink socket." ); } if ( genl_connect( state->nl_sock ) ) { throw std::runtime_error( "Error : Failed to connect to generic netlink." ); } nl_socket_set_buffer_size( state->nl_sock, 8192, 8192 ); state->nl80211_id = genl_ctrl_resolve( state->nl_sock, "nl80211" ); if ( state->nl80211_id < 0 ) { throw std::runtime_error( "Error : nl80211 not found for interface '" + name + "'." ); } gDebug() << "Stopping interface..."; setFlags( state->fd, name, -IFF_UP ); gDebug() << "Setting monitor mode..."; setMonitor( state ); gDebug() << "Starting interface..."; setFlags( state->fd, name, IFF_UP ); if ( channel != 0 ) { enum nl80211_band band = ( channel <= 14 ? NL80211_BAND_2GHZ : NL80211_BAND_5GHZ ); int freq = ieee80211_channel_to_frequency( channel, band ); gDebug() << "Setting channel to " << channel << " (" << freq << "MHz)..."; if ( ( ret = setFrequency( state, freq, 0 ) < 0 ) ) { gError() << "Error : Failed to set frequency : " << ret; } } if ( txpower != 0 ) { gDebug() << "Setting TX power to " << txpower << "000mBm..."; if ( ( ret = setTxPower( state, txpower * 1000 ) < 0 ) ) { gWarning() << "Error : Failed to set TX power : " << ret; } } if ( bitrate != 0 ) { if ( bHT ) { gDebug() << "Setting bitrate to " << bitrate << " HT-MCS with " << bHT << "MHz bandwidth..."; } else { gDebug() << "Setting bitrate to " << bitrate << " Mbps..."; } if ( ( ret = setBitrate( state, bHT, bitrate ) < 0 ) ) { gError() << "Error : Failed to set bitrate : " << ret; } } close( state->fd ); } WifiInterfaceLinux::~WifiInterfaceLinux() { } int32_t WifiInterfaceLinux::setMonitor( WifiInterfaceLinux::nl80211_state* state ) { struct nl_msg* msg = nlMsgInit( state, NL80211_CMD_SET_INTERFACE ); struct nl_msg* flags = nlmsg_alloc(); nla_put_u32( msg, NL80211_ATTR_IFTYPE, NL80211_IFTYPE_MONITOR ); nla_put( flags, NL80211_MNTR_FLAG_FCSFAIL, 0, NULL ); nla_put( flags, NL80211_MNTR_FLAG_OTHER_BSS, 0, NULL ); nla_put_nested( msg, NL80211_ATTR_MNTR_FLAGS, flags ); nlmsg_free( flags ); nlMsgSend( state, msg ); return 0; } int32_t WifiInterfaceLinux::setFrequency( WifiInterfaceLinux::nl80211_state* state, int32_t freq, int32_t ht_bandwidth ) { struct nl_msg* msg = nlMsgInit( state, NL80211_CMD_SET_WIPHY ); nla_put_u32( msg, NL80211_ATTR_WIPHY_FREQ, freq ); if ( ht_bandwidth == 0 ) { nla_put_u32( msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE, NL80211_CHAN_NO_HT ); } else if ( ht_bandwidth == 20 ) { nla_put_u32( msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE, NL80211_CHAN_HT20 ); } else if ( ht_bandwidth == -40 ) { nla_put_u32( msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE, NL80211_CHAN_HT40MINUS ); } else if ( ht_bandwidth == 40 ) { nla_put_u32( msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE, NL80211_CHAN_HT40PLUS ); } return nlMsgSend( state, msg ); } int32_t WifiInterfaceLinux::setTxPower( nl80211_state* state, int32_t power_mbm ) { struct nl_msg* msg = nlMsgInit( state, NL80211_CMD_SET_WIPHY ); nla_put_u32( msg, NL80211_ATTR_WIPHY_TX_POWER_SETTING, NL80211_TX_POWER_FIXED ); nla_put_u32( msg, NL80211_ATTR_WIPHY_TX_POWER_LEVEL, power_mbm ); return nlMsgSend( state, msg ); } int32_t WifiInterfaceLinux::setBitrate( nl80211_state* state, uint32_t is_ht, uint32_t rate ) { struct nl_msg* msg = nlMsgInit( state, NL80211_CMD_SET_WIPHY ); struct nlattr* nl_rates = nla_nest_start( msg, NL80211_ATTR_TX_RATES ); struct nlattr* nl_band = nla_nest_start( msg, NL80211_BAND_2GHZ ); // nl_band = nla_nest_start(msg, NL80211_BAND_5GHZ); if ( is_ht ) { nla_put( msg, NL80211_TXRATE_HT, 1, &rate ); } else { nla_put( msg, NL80211_TXRATE_LEGACY, 1, &rate ); } // nla_put_u8( msg, NL80211_TXRATE_GI, NL80211_TXRATE_FORCE_SGI ); nla_put_u8( msg, NL80211_TXRATE_GI, NL80211_TXRATE_FORCE_LGI ); // Reduce data overlapping with other stations nla_nest_end( msg, nl_band ); nla_nest_end( msg, nl_rates ); return nlMsgSend( state, msg ); } int32_t WifiInterfaceLinux::ieee80211_channel_to_frequency( int chan, nl80211_band band ) { /* see 802.11 17.3.8.3.2 and Annex J * there are overlapping channel numbers in 5GHz and 2GHz bands */ if (chan <= 0) return 0; /* not supported */ switch (band) { case NL80211_BAND_2GHZ: if (chan == 14) return 2484; else if (chan < 14) return 2407 + chan * 5; break; case NL80211_BAND_5GHZ: if (chan >= 182 && chan <= 196) return 4000 + chan * 5; else return 5000 + chan * 5; break; case NL80211_BAND_60GHZ: if (chan < 5) return 56160 + chan * 2160; break; default: ; } return 0; /* not supported */ } int32_t WifiInterfaceLinux::setFlags( int32_t fd, const std::string& vname, int32_t value ) { struct ifreq ifreq; (void) strncpy( ifreq.ifr_name, vname.c_str(), sizeof(ifreq.ifr_name) ); if ( ioctl( fd, SIOCGIFFLAGS, &ifreq ) < 0 ) { return errno; } uint32_t flags = ifreq.ifr_flags; if ( value < 0 ) { value = -value; flags &= ~value; } else { flags |= value; } ifreq.ifr_flags = flags; if ( ioctl( fd, SIOCSIFFLAGS, &ifreq ) < 0 ) { return errno; } return 0; } struct nl_msg* WifiInterfaceLinux::nlMsgInit( nl80211_state* state, int cmd ) { struct nl_msg* msg = nlmsg_alloc(); genlmsg_put( msg, 0, 0, state->nl80211_id, 0, 0, cmd, 0 ); nla_put_u32( msg, NL80211_ATTR_IFINDEX, state->devidx ); nla_put_u32( msg, NL80211_ATTR_WIPHY, state->phyidx ); return msg; } int32_t WifiInterfaceLinux::nlMsgSend( nl80211_state* state, struct nl_msg* msg ) { static const auto error_handler = [](struct sockaddr_nl* nla, struct nlmsgerr* err, void* arg) { int* ret = reinterpret_cast<int*>(arg); *ret = err->error; return (int)NL_STOP; }; static const auto finish_handler = [](struct nl_msg* msg, void* arg) { int* ret = reinterpret_cast<int*>(arg); *ret = 0; return (int)NL_SKIP; }; static const auto ack_handler = [](struct nl_msg* msg, void* arg) { int* ret = reinterpret_cast<int*>(arg); *ret = 0; return (int)NL_STOP; }; static const auto valid_handler = [](struct nl_msg* msg, void* arg) { return (int)NL_OK; }; struct nl_cb* cb = nl_cb_alloc( NL_CB_DEFAULT ); struct nl_cb* s_cb = nl_cb_alloc( NL_CB_DEFAULT ); nl_socket_set_cb( state->nl_sock, s_cb ); int err = nl_send_auto_complete(state->nl_sock, msg); if ( err < 0 ) { nlmsg_free(msg); return err; } err = 1; nl_cb_err( cb, NL_CB_CUSTOM, error_handler, &err ); nl_cb_set( cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &err ); nl_cb_set( cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, &err ); nl_cb_set( cb, NL_CB_VALID, NL_CB_CUSTOM, valid_handler, NULL ); while ( err > 0 ) { nl_recvmsgs( state->nl_sock, cb ); } nl_cb_put(cb); nl_cb_put(s_cb); nlmsg_free(msg); return err; } int32_t WifiInterfaceLinux::phyMacToIndex( const std::string& hwaddr ) { char path[1024] = ""; char buf[64] = ""; struct dirent* ent; DIR* dir = opendir( "/sys/class/ieee80211" ); while ( dir && ( ent = readdir( dir ) ) != NULL ) { if ( ent->d_name[0] != '.' ) { sprintf( path, "/sys/class/ieee80211/%s/macaddress", ent->d_name ); int fd = open( path, O_RDONLY ); if ( fd > 0 ) { read( fd, buf, sizeof(buf) ); close( fd ); if ( strlen(buf) > 0 ) { buf[strlen(buf)-1] = 0; if ( !strcmp( buf, hwaddr.c_str() ) ) { sprintf( path, "/sys/class/ieee80211/%s/index", ent->d_name ); fd = open( path, O_RDONLY ); if ( fd > 0 ) { read( fd, buf, sizeof(buf) ); close( fd ); closedir( dir ); return atoi( buf ); } } } } } } if ( dir ) { closedir( dir ); } return -1; }
9,177
C++
.cpp
266
31.890977
160
0.651501
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,814
PcapHandler.cpp
dridri_bcflight/librawwifi++/PcapHandler.cpp
#include "PcapHandler.h" #include <stdexcept> #include <Debug.h> using namespace rawwifi; PcapHandler::PcapHandler( const std::string& device, uint8_t port, bool blocking, int32_t read_timeout_ms ) : mPcap( nullptr ) , mDevice( device ) , mPort( port ) , mBlocking( blocking ) , mHeaderLength( 0 ) { fDebug( device, (int)port, (int)blocking, read_timeout_ms ); char errbuf[PCAP_ERRBUF_SIZE]; mPcap = pcap_create( device.c_str(), errbuf ); if ( !mPcap ) { throw std::runtime_error( std::string( "Failed to create pcap handler: " ) + errbuf ); } if ( pcap_set_snaplen( mPcap, 4096 ) ) { throw std::runtime_error( "Failed to set snaplen" ); } if ( pcap_set_promisc( mPcap, 1 ) ) { throw std::runtime_error( "Failed to set promisc" ); } if ( read_timeout_ms >= 0 and pcap_set_timeout( mPcap, read_timeout_ms ) ) { throw std::runtime_error( "Failed to set timeout" ); } if ( pcap_set_immediate_mode( mPcap, 1 ) ) { throw std::runtime_error( "Failed to set immediate mode" ); } // TBD // pcap_set_buffer_size // pcap_set_tstamp_type // pcap_set_rfmon // pcap_setdirection if ( pcap_setnonblock( mPcap, !blocking, errbuf ) ) { throw std::runtime_error( std::string( "Failed to set blocking: " ) + errbuf ); } if ( pcap_activate( mPcap ) ) { throw std::runtime_error( "Failed to activate pcap handler" ); } } PcapHandler::~PcapHandler() { if ( mPcap ) { pcap_close( mPcap ); } } void PcapHandler::CompileFilter() { gDebug() << "Compiling PCAP filter for port " << (int)mPort << " on device " << mDevice; char program[512] = ""; struct bpf_program bpfprogram; switch ( pcap_datalink( mPcap ) ) { case DLT_PRISM_HEADER: gDebug() << "DLT_PRISM_HEADER Encap"; mHeaderLength = 0x20; // ieee80211 comes after this sprintf( program, "radio[0x4a:4]==0x13223344 && radio[0x4e:2] == 0x55%.2x", mPort ); break; case DLT_IEEE802_11_RADIO: gDebug() << "DLT_IEEE802_11_RADIO Encap"; mHeaderLength = 0x18; // ieee80211 comes after this sprintf( program, "ether[0x0a:4]==0x13223344 && ether[0x0e:2] == 0x55%.2x", mPort ); break; default: throw std::runtime_error( "Unknown encapsulation on " + mDevice ); } // return; uint32_t i = 0; uint32_t retries = 8; bool ok = false; for ( i = 0; i < retries and not ok; i++ ) { if ( pcap_compile( mPcap, &bpfprogram, program, 1, 0 ) >= 0 ) { ok = true; } } if ( !ok ) { throw std::runtime_error( std::string( "Failed to compile PCAP filter: " ) + pcap_geterr( mPcap ) ); } ok = false; for ( i = 0; i < retries and not ok; i++ ) { if ( pcap_setfilter( mPcap, &bpfprogram ) >= 0 ) { ok = true; } } if ( !ok ) { throw std::runtime_error( std::string( "Failed to set PCAP filter: " ) + pcap_geterr( mPcap ) ); } pcap_freecode( &bpfprogram ); }
2,791
C++
.cpp
89
28.842697
107
0.6566
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,815
Controller.cpp
dridri_bcflight/libcontroller/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 <fcntl.h> #include <string.h> #include <signal.h> #include <math.h> //#include <netinet/in.h> //#include <netinet/tcp.h> #include <stdio.h> #include <iostream> #include "Controller.h" #include "links/RawWifi.h" #include "Debug.h" Controller::Controller( Link* link, bool spectate ) : ControllerBase( link ) , Thread( "controller-tx" ) , mPing( 0 ) , mCalibrated( false ) , mCalibrating( false ) , mArmed( false ) , mTotalCurrent( 0 ) , mCurrentDraw( 0 ) , mBatteryVoltage( 0 ) , mBatteryLevel( 0 ) , mCPULoad( 0 ) , mCPUTemp( 0 ) , mAltitude( 0.0f ) , mThrust( 0.0f ) , mControlRPY{ 0.0f, 0.0f, 0.0f } , mPIDsLoaded( false ) , mDroneRxQuality( 0 ) , mDroneRxLevel( 0 ) , mNightMode( false ) , mCameraMissing( false ) , mUpdateFrequency( 100 ) , mDroneConnected( false ) , mSpectate( spectate ) , mTickBase( Thread::GetTick() ) , mPingTimer( 0 ) , mTelemetryTimer( 0 ) , mDataTimer( 0 ) , mMsCounter( 0 ) , mMsCounter50( 0 ) , mRequestAck( false ) , mBoardInfos( "" ) , mSensorsInfos( "" ) , mCamerasInfos( "" ) , mConfigFile( "" ) , mRecordingsList( "" ) , mUpdateUploadValid( false ) , mConfigUploadValid( false ) , mTicks( 0 ) , mSwitches{ 0 } , mVideoRecording( false ) , mVideoWhiteBalance( "" ) , mVideoExposureMode( "" ) , mVideoIso( -1 ) , mVideoShutterSpeed( -1 ) , mAcceleration( 0.0f ) , mLocalBatteryVoltage( 0 ) { mMode = Rate; memset( mSwitches, 0, sizeof( mSwitches ) ); memset( &mRollPID, 0, sizeof(mRollPID) ); memset( &mPitchPID, 0, sizeof(mPitchPID) ); memset( &mYawPID, 0, sizeof(mYawPID) ); memset( &mOuterPID, 0, sizeof(mOuterPID) ); memset( &mHorizonOffset, 0, sizeof(mHorizonOffset) ); memset( &mControls, 0, sizeof(mControls) ); #ifndef WIN32 signal( SIGPIPE, SIG_IGN ); #endif mRxThread = new HookThread<Controller>( "controller-rx", this, &Controller::RxRun ); mRxThread->setPriority( 99, 1 ); if ( spectate ) { Start(); mRxThread->Start(); } else { Start(); } } Controller::~Controller() { Stop(); mRxThread->Stop(); } void Controller::setUpdateFrequency( uint32_t freq_hz ) { mUpdateFrequency = freq_hz; } string Controller::debugOutput() { string ret = ""; mDebugMutex.lock(); ret = mDebug; mDebug = ""; mDebugMutex.unlock(); return ret; } bool Controller::run() { uint32_t ticks = Thread::GetTick(); if ( ticks - mTicks < 1000 / mUpdateFrequency ) { usleep( 1000 * max( 0U, 1000U / mUpdateFrequency - (int)( ticks - mTicks ) - 1U ) ); } float dt = ((float)( Thread::GetTick() - mTicks ) ) / 1000.0f; mTicks = Thread::GetTick(); uint64_t ticks0 = mTicks; if ( mLockState >= 1 ) { mLockState = 2; usleep( 1000 * 10 ); return true; } if ( not mLink ) { usleep( 1000 * 500 ); return true; } if ( not mLink->isConnected() ) { gDebug() << "Connecting..."; mConnected = ( mLink->Connect() == 0 ); if ( mConnected ) { setPriority( 99, 0 ); gDebug() << "Ok !" << flush; // uint32_t uid = htonl( 0x12345678 ); // mLink->Write( &uid, sizeof( uid ) ); } else { gDebug() << "Nope !" << flush; usleep( 1000 * 250 ); } return true; } // if ( not mDroneConnected ) { // return true; // } if ( mSpectate ) { mXferMutex.lock(); if ( mTxFrame.data().size() > 0 ) { gDebug() << "Sending " << mTxFrame.data().size()*4 << " bytes"; mLink->Write( &mTxFrame ); } mTxFrame = Packet(); mXferMutex.unlock(); mTicks = Thread::GetTick(); mMsCounter += ( mTicks - ticks0 ); usleep( 1000 * 1000 / 100 ); return true; } uint32_t oldswitch[12]; memcpy( oldswitch, mSwitches, sizeof(oldswitch) ); for ( uint32_t i = 0; i < 12; i++ ) { bool on = ReadSwitch( i ); if ( on and not mSwitches[i] ) { gDebug() << "Switch " << i << " on" << flush; } else if ( not on and mSwitches[i] ) { gDebug() << "Switch " << i << " off" << flush; } mSwitches[i] = on; } if ( mSwitches[1] and not oldswitch[1] ) { VideoTakePicture(); } bool arm = mSwitches[9]; if ( mSwitches[9] and not mArmed and mCalibrated ) { arm = true; Arm(); } else if ( not mSwitches[9] and mArmed ) { Disarm(); } if ( mSwitches[5] and mMode != Stabilize ) { setMode( Stabilize ); } else if ( not mSwitches[5] and mMode != Rate ) { setMode( Rate ); } if ( mSwitches[6] and mNightMode == false ) { gDebug() << "set night mode"; setNightMode( true ); } else if ( not mSwitches[6] and mNightMode == true ) { setNightMode( false ); } if ( mSwitches[10] and not mVideoRecording ) { gDebug() << "start recording"; mXferMutex.lock(); mTxFrame.WriteU16( VIDEO_START_RECORD ); mXferMutex.unlock(); } else if ( not mSwitches[10] and mVideoRecording ) { gDebug() << "stop recording"; mXferMutex.lock(); mTxFrame.WriteU16( VIDEO_STOP_RECORD ); mXferMutex.unlock(); } 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 ) { if ( fabsf( f_thrust ) <= 0.01f ) { f_thrust = 0.0f; } else if ( f_thrust < 0.0f ) { f_thrust += 0.01f; } else if ( f_thrust > 0.0f ) { f_thrust -= 0.01f; } f_thrust *= 1.0f / ( 1.0f - 0.01f ); mControls.thrust = (int16_t)( max( 0, min( 511, (int32_t)( f_thrust * 511.0f ) ) ) ); } if ( f_yaw >= -1.0f and f_yaw <= 1.0f ) { if ( fabsf( f_yaw ) <= 0.01f ) { f_yaw = 0.0f; } else if ( f_yaw < 0.0f ) { f_yaw += 0.01f; } else if ( f_yaw > 0.0f ) { f_yaw -= 0.01f; } f_yaw *= 1.0f / ( 1.0f - 0.01f ); mControls.yaw = (int16_t)( max( -511, min( 511, (int32_t)( f_yaw * 511.0f ) ) ) ); } if ( f_pitch >= -1.0f and f_pitch <= 1.0f ) { if ( fabsf( f_pitch ) <= 0.01f ) { f_pitch = 0.0f; } else if ( f_pitch < 0.0f ) { f_pitch += 0.01f; } else if ( f_pitch > 0.0f ) { f_pitch -= 0.01f; } f_pitch *= 1.0f / ( 1.0f - 0.01f ); mControls.pitch = (int16_t)( max( -511, min( 511, (int32_t)( f_pitch * 511.0f ) ) ) ); } if ( f_roll >= -1.0f and f_roll <= 1.0f ) { if ( fabsf( f_roll ) <= 0.01f ) { f_roll = 0.0f; } else if ( f_roll < 0.0f ) { f_roll += 0.01f; } else if ( f_roll > 0.0f ) { f_roll -= 0.01f; } f_roll *= 1.0f / ( 1.0f - 0.01f ); mControls.roll = (int16_t)( max( -511, min( 511, (int32_t)( f_roll * 511.0f ) ) ) ); } // gTrace() << "Controls : " << f_thrust << ", " << f_yaw << ", " << f_pitch << ", " << f_roll << "\n"; // gTrace() << "Controls : " << mControls.thrust << ", " << mControls.yaw << ", " << mControls.pitch << ", " << mControls.roll << "\n\n"; mControls.arm = arm; mTxFrame.WriteU8( CONTROLS ); mTxFrame.Write( (uint8_t*)&mControls, sizeof(mControls) ); bool request_ack = false; if ( Thread::GetTick() - mPingTimer >= 125 ) { request_ack = true; uint64_t ticks = Thread::GetTick(); mXferMutex.lock(); mTxFrame.WriteU8( PING ); mTxFrame.WriteU16( (uint16_t)( ticks & 0x0000FFFFL ) ); mTxFrame.WriteU16( mPing ); // Report current ping to drone mXferMutex.unlock(); if ( not mRxThread->running() ) { mRxThread->Start(); usleep( 1000 * 1000 ); mXferMutex.lock(); // mTxFrame.WriteU8( CONNECT ); mTxFrame.WriteU16( ROLL_PID_FACTORS ); mTxFrame.WriteU16( PITCH_PID_FACTORS ); mTxFrame.WriteU16( YAW_PID_FACTORS ); mTxFrame.WriteU16( OUTER_PID_FACTORS ); mTxFrame.WriteU16( HORIZON_OFFSET ); mTxFrame.WriteU16( VTX_GET_SETTINGS ); mXferMutex.unlock(); } if ( mUsername.length() == 0 ) { mXferMutex.lock(); mTxFrame.WriteU16( GET_USERNAME ); mXferMutex.unlock(); } mPingTimer = Thread::GetTick(); } if ( Thread::GetTick() - mTelemetryTimer >= 500 ) { request_ack = true; mXferMutex.lock(); mTxFrame.WriteU8( TELEMETRY ); mXferMutex.unlock(); mTelemetryTimer = Thread::GetTick(); } mXferMutex.lock(); if ( mTxFrame.data().size() > 0 ) { int ret = mLink->Write( &mTxFrame, mRequestAck ); mRequestAck = request_ack; } mTxFrame = Packet(); mXferMutex.unlock(); mMsCounter += ( Thread::GetTick() - ticks0 ); return true; } bool Controller::RxRun() { if ( mSpectate and not mLink->isConnected() ) { gDebug() << "Connecting..." << flush; mConnected = ( mLink->Connect() == 0 ); if ( mConnected ) { gDebug() << "Ok !" << flush; } else { gDebug() << "Nope !" << flush; usleep( 1000 * 250 ); } return true; } Packet telemetry; int rret = 0; if ( ( rret = mLink->Read( &telemetry ) ) <= 0 ) { gDebug() << "Controller Link read error : " << rret; usleep( 500 ); return true; } auto ReadCmd = []( Packet* telemetry, Cmd* cmd ) { uint8_t part1 = 0; uint8_t part2 = 0; if ( telemetry->ReadU8( &part1 ) == sizeof(uint8_t) ) { if ( ( part1 & SHORT_COMMAND ) == SHORT_COMMAND ) { *cmd = (Cmd)part1; return (int)sizeof(uint8_t); } if ( telemetry->ReadU8( &part2 ) == sizeof(uint8_t) ) { *cmd = (Cmd)ntohs( ( ((uint16_t)part2) << 8 ) | part1 ); return (int)sizeof(uint16_t); } } return 0; }; Cmd cmd = (Cmd)0; bool acknowledged = false; while ( ReadCmd( &telemetry, &cmd ) > 0 ) { // if ( cmd != PING and cmd != TELEMETRY and cmd != CONTROLS and cmd != STATUS ) { gTrace() << "Received command (" << hex << (int)cmd << dec << ") : " << mCommandsNames[(cmd)]; // } acknowledged = false; if ( ( cmd & ACK_ID ) == ACK_ID ) { uint16_t id = cmd & ~ACK_ID; gDebug() << "Received ACK with ID " << id; if ( id == mRXAckID ) { acknowledged = true; } mRXAckID = id; continue; } switch( cmd ) { case UNKNOWN : { break; } // case CONNECT : { // printf( "received CONNECT\n" ); // mDroneConnected = true; // if ( not mSpectate ) { // mXferMutex.lock(); // mTxFrame.WriteU8( CONNECT ); // mTxFrame.WriteU16( ROLL_PID_FACTORS ); // mTxFrame.WriteU16( PITCH_PID_FACTORS ); // mTxFrame.WriteU16( YAW_PID_FACTORS ); // mTxFrame.WriteU16( OUTER_PID_FACTORS ); // mTxFrame.WriteU16( HORIZON_OFFSET ); // mTxFrame.WriteU16( VTX_GET_SETTINGS ); // printf( "\n\n\nVTX_GET_SETTINGS sent\n" ); // mXferMutex.unlock(); // } // break; // } case PING : { uint32_t ret = telemetry.ReadU16(); uint32_t reported_ping = telemetry.ReadU16(); uint32_t curr = (uint32_t)( Thread::GetTick() & 0x0000FFFFL ); mPing = curr - ret; if ( mSpectate ) { mPing = reported_ping; } mConnectionEstablished = true; break; } case STATUS : { uint32_t status = 0; if ( telemetry.ReadU32( &status ) == sizeof(uint32_t) ) { mArmed = status & STATUS_ARMED; mCalibrated = status & STATUS_CALIBRATED; mCalibrating = status & STATUS_CALIBRATING; // mNightMode = status & STATUS_NIGHTMODE; } break; } case TELEMETRY : { Telemetry data; memset( &data, 0, sizeof(data) ); telemetry.Read( (uint8_t*)&data, sizeof(data) ); mBatteryVoltage = (float)(data.battery_voltage) / 100.0f; mTotalCurrent = (float)data.total_current; mCurrentDraw = (float)data.current_draw / 10.0f; mBatteryLevel = (float)(data.battery_level) / 100.0f; mCPULoad = data.cpu_load; mCPUTemp = data.cpu_temp; mDroneRxQuality = max( 0, min( 100, (int)data.rx_quality ) ); mDroneRxLevel = max( -127, min( 127, (int)data.rx_level ) ); break; } case DEBUG_OUTPUT : { mDebugMutex.lock(); string str = telemetry.ReadString(); gDebug() << str << flush; mDebug += str; mDebugMutex.unlock(); break; } case CALIBRATE : { uint32_t value = telemetry.ReadU32(); if ( value == 0 ) { mCalibrated = true; gDebug() << "Calibration success" << flush; } else if ( value == 2 ) { // This value is regularily sent to tell that the drone is still calibrated mCalibrated = true; } else if ( value == 3 ) { // This value is regularily sent to tell that the drone is not calibrated mCalibrated = false; } else { gDebug() << "WARNING : Calibration failed !" << flush; } break; } case CALIBRATING : { mCalibrating = telemetry.ReadU32(); break; } case ARM : { mArmed = telemetry.ReadU32(); break; } case DISARM : { mArmed = telemetry.ReadU32(); break; } case RESET_BATTERY : { uint32_t unused = telemetry.ReadU32(); (void)unused; break; } case GET_BOARD_INFOS : { mBoardInfos = telemetry.ReadString(); break; } case GET_SENSORS_INFOS : { mSensorsInfos = telemetry.ReadString(); break; } case GET_CAMERAS_INFOS : { mCamerasInfos = telemetry.ReadString(); break; } case GET_CONFIG_FILE : { uint32_t crc = telemetry.ReadU32(); string content = telemetry.ReadString(); if ( crc32( (uint8_t*)content.c_str(), content.length() ) == crc ) { mConfigFile = content; } else { gDebug() << "Received broken config flie, retrying..." << flush; mConfigFile = ""; } break; } case SET_CONFIG_FILE : { gDebug() << "SET_CONFIG_FILE"; mConfigUploadValid = ( telemetry.ReadU32() == 0 ); break; } case UPDATE_UPLOAD_DATA : { bool ok = ( telemetry.ReadU32() == 1 ); gDebug() << "UPDATE_UPLOAD_DATA : " << ok << "" << flush; mUpdateUploadValid = ok; break; } case VBAT : { mBatteryVoltage = telemetry.ReadFloat(); break; } case TOTAL_CURRENT : { uint32_t value = (uint32_t)( telemetry.ReadFloat() * 1000.0f ); if ( value < 1000000 ) { mTotalCurrent = value; } break; } case CURRENT_DRAW : { mCurrentDraw = telemetry.ReadFloat(); break; } case BATTERY_LEVEL : { float level = 0.0f; if ( telemetry.ReadFloat( &level ) == sizeof(float) ) { mBatteryLevel = level; } break; } case CPU_LOAD : { mCPULoad = telemetry.ReadU32(); break; } case CPU_TEMP : { mCPUTemp = telemetry.ReadU32(); break; } case RX_QUALITY : { uint32_t value = 0; if ( telemetry.ReadU32( &value ) == sizeof(uint32_t) ) { mDroneRxQuality = value; } break; } case RX_LEVEL : { uint32_t value = 0; if ( telemetry.ReadU32( &value ) == sizeof(uint32_t) ) { mDroneRxLevel = (int32_t)value; } break; } case STABILIZER_FREQUENCY : { uint32_t value = 0; if ( telemetry.ReadU32( &value ) == sizeof(uint32_t) ) { mStabilizerFrequency = value; } break; } case MOTORS_SPEED: { uint32_t size = telemetry.ReadU32(); mMotorsSpeed.clear(); for ( uint32_t i = 0; i < size; i++ ) { // mMotorsSpeed.push_back( telemetry.ReadFloat() ); (void)telemetry.ReadFloat(); } break; } case ROLL_PID_FACTORS : { mRollPID.x = telemetry.ReadFloat(); mRollPID.y = telemetry.ReadFloat(); mRollPID.z = telemetry.ReadFloat(); mPIDsLoaded = true; break; } case PITCH_PID_FACTORS : { mPitchPID.x = telemetry.ReadFloat(); mPitchPID.y = telemetry.ReadFloat(); mPitchPID.z = telemetry.ReadFloat(); mPIDsLoaded = true; break; } case YAW_PID_FACTORS : { mYawPID.x = telemetry.ReadFloat(); mYawPID.y = telemetry.ReadFloat(); mYawPID.z = telemetry.ReadFloat(); mPIDsLoaded = true; break; } case OUTER_PID_FACTORS : { mOuterPID.x = telemetry.ReadFloat(); mOuterPID.y = telemetry.ReadFloat(); mOuterPID.z = telemetry.ReadFloat(); mPIDsLoaded = true; break; } case HORIZON_OFFSET : { mHorizonOffset.x = telemetry.ReadFloat(); mHorizonOffset.y = telemetry.ReadFloat(); break; } case SET_ROLL_PID_P : { mRollPID.x = telemetry.ReadFloat(); break; } case SET_ROLL_PID_I : { mRollPID.y = telemetry.ReadFloat(); break; } case SET_ROLL_PID_D : { mRollPID.z = telemetry.ReadFloat(); break; } case SET_PITCH_PID_P : { mPitchPID.x = telemetry.ReadFloat(); break; } case SET_PITCH_PID_I : { mPitchPID.y = telemetry.ReadFloat(); break; } case SET_PITCH_PID_D : { mPitchPID.z = telemetry.ReadFloat(); break; } case SET_YAW_PID_P : { mYawPID.x = telemetry.ReadFloat(); break; } case SET_YAW_PID_I : { mYawPID.y = telemetry.ReadFloat(); break; } case SET_YAW_PID_D : { mYawPID.z = telemetry.ReadFloat(); break; } case SET_OUTER_PID_P : { mOuterPID.x = telemetry.ReadFloat(); break; } case SET_OUTER_PID_I : { mOuterPID.y = telemetry.ReadFloat(); break; } case SET_OUTER_PID_D : { mOuterPID.z = telemetry.ReadFloat(); break; } case SET_HORIZON_OFFSET : { mHorizonOffset.x = telemetry.ReadFloat(); mHorizonOffset.y = telemetry.ReadFloat(); break; } case SET_THRUST : { float value = telemetry.ReadFloat(); if ( mSpectate ) { mThrust = value; } break; } case ROLL_PITCH_YAW : { mRPY.x = telemetry.ReadFloat(); mRPY.y = telemetry.ReadFloat(); mRPY.z = telemetry.ReadFloat(); vec4 rpy; rpy.x = mRPY.x; rpy.y = mRPY.y; rpy.z = mRPY.z; rpy.w = (double)( Thread::GetTick() - mTickBase ) / 1000.0; mHistoryMutex.lock(); mRPYHistory.emplace_back( rpy ); if ( mRPYHistory.size() > 2048 ) { mRPYHistory.pop_front(); } mHistoryMutex.unlock(); break; } case GYRO : { vec4 gyro; gyro.x = telemetry.ReadFloat(); gyro.y = telemetry.ReadFloat(); gyro.z = telemetry.ReadFloat(); gyro.w = (double)( Thread::GetTick() - mTickBase ) / 1000.0; mHistoryMutex.lock(); mGyroscopeHistory.emplace_back( gyro ); if ( mGyroscopeHistory.size() > 2048 ) { mGyroscopeHistory.pop_front(); } mHistoryMutex.unlock(); break; } case RATES : { vec4 rates; rates.x = telemetry.ReadFloat(); rates.y = telemetry.ReadFloat(); rates.z = telemetry.ReadFloat(); rates.w = (double)( Thread::GetTick() - mTickBase ) / 1000.0; mHistoryMutex.lock(); mRatesHistory.emplace_back( rates ); if ( mRatesHistory.size() > 2048 ) { mRatesHistory.pop_front(); } mHistoryMutex.unlock(); break; } case GYRO_DTERM : { vec4 rates_dterm; rates_dterm.x = telemetry.ReadFloat(); rates_dterm.y = telemetry.ReadFloat(); rates_dterm.z = telemetry.ReadFloat(); rates_dterm.w = (double)( Thread::GetTick() - mTickBase ) / 1000.0; mHistoryMutex.lock(); mRatesDerivativeHistory.emplace_back( rates_dterm ); if ( mRatesDerivativeHistory.size() > 2048 ) { mRatesDerivativeHistory.pop_front(); } mHistoryMutex.unlock(); break; } case ACCEL : { vec4 accel; accel.x = telemetry.ReadFloat(); accel.y = telemetry.ReadFloat(); accel.z = telemetry.ReadFloat(); accel.w = (double)( Thread::GetTick() - mTickBase ) / 1000.0; mHistoryMutex.lock(); mAccelerationHistory.emplace_back( accel ); if ( mAccelerationHistory.size() > 2048 ) { mAccelerationHistory.pop_front(); } mHistoryMutex.unlock(); break; } case MAGN : { vec4 magn; magn.x = telemetry.ReadFloat(); magn.y = telemetry.ReadFloat(); magn.z = telemetry.ReadFloat(); magn.w = (double)( Thread::GetTick() - mTickBase ) / 1000.0; mHistoryMutex.lock(); mMagnetometerHistory.emplace_back( magn ); if ( mMagnetometerHistory.size() > 4096 ) { mMagnetometerHistory.pop_front(); } mHistoryMutex.unlock(); break; } case CURRENT_ACCELERATION : { mAcceleration = telemetry.ReadFloat(); break; } case ALTITUDE : { vec2 alt; alt.x = mAltitude; alt.y = (double)( Thread::GetTick() - mTickBase ) / 1000.0; mHistoryMutex.lock(); mAltitude = telemetry.ReadFloat(); mAltitudeHistory.emplace_back( alt ); if ( mAltitudeHistory.size() > 4096 ) { mAltitudeHistory.pop_front(); } mHistoryMutex.unlock(); break; } case RATE_DNF_DFT : { uint16_t size = telemetry.ReadU16(); vec4* data = new vec4[size / sizeof(vec4)]; telemetry.Read( reinterpret_cast<uint8_t*>(data), size ); mHistoryMutex.lock(); mDnfDft.clear(); for ( uint16_t i = 0; i < size / sizeof(vec4); i++ ) { vec4 v = data[i]; v.w = i; // v.w = i * 4000 / 512; // v.w = i * 4000 / 512; // v.w = 2 * i * 4000 / 512; mDnfDft.push_back( v ); } mHistoryMutex.unlock(); delete[] data; break; } case SET_MODE : { mMode = (Mode)telemetry.ReadU32(); break; } case VIDEO_WHITE_BALANCE : { mVideoWhiteBalance = telemetry.ReadString(); break; } case VIDEO_LOCK_WHITE_BALANCE : { mVideoWhiteBalance = telemetry.ReadString(); break; } case VIDEO_ISO : { mVideoIso = (int32_t)telemetry.ReadU32(); break; } case VIDEO_EXPOSURE_MODE : { mVideoExposureMode = telemetry.ReadString(); break; } case VIDEO_SHUTTER_SPEED : { mVideoShutterSpeed = (int32_t)telemetry.ReadU32(); break; } case VIDEO_LENS_SHADER : { mCameraLensShaderR.base = telemetry.ReadU8(); mCameraLensShaderR.radius = telemetry.ReadU8(); mCameraLensShaderR.strength = telemetry.ReadU8(); mCameraLensShaderG.base = telemetry.ReadU8(); mCameraLensShaderG.radius = telemetry.ReadU8(); mCameraLensShaderG.strength = telemetry.ReadU8(); mCameraLensShaderB.base = telemetry.ReadU8(); mCameraLensShaderB.radius = telemetry.ReadU8(); mCameraLensShaderB.strength = telemetry.ReadU8(); break; } case VIDEO_START_RECORD : { mVideoRecording = telemetry.ReadU32(); break; } case VIDEO_STOP_RECORD : { mVideoRecording = telemetry.ReadU32(); break; } case VIDEO_NIGHT_MODE : { uint32_t night = telemetry.ReadU32(); if ( night != mNightMode ) { mNightMode = night; gDebug() << "Video switched to " << ( mNightMode ? "night" : "day" ) << " mode"; } break; } case GET_RECORDINGS_LIST : { uint32_t crc = telemetry.ReadU32(); string content = telemetry.ReadString(); if ( crc32( (uint8_t*)content.c_str(), content.length() ) == crc ) { mRecordingsList = content; } else { gDebug() << "Received broken recordings list, retrying..."; mRecordingsList = "broken"; } break; } case GET_USERNAME : { mUsername = telemetry.ReadString(); break; } case VTX_GET_SETTINGS : { mVTXChannel = int8_t(telemetry.ReadU8()); mVTXFrequency = int16_t(telemetry.ReadU16()); mVTXPower = int8_t(telemetry.ReadU8()); mVTXPowerDbm = int8_t(telemetry.ReadU8()); printf( "\n\n\nVTX_GET_SETTINGS : %d\n", mVTXChannel ); uint8_t table_count = telemetry.ReadU8(); std::vector<int32_t> powerTable; if ( table_count > 0 ) { for ( uint8_t i = 0; i < table_count; i++ ) { powerTable.push_back( telemetry.ReadU8() ); } mVTXPowerTable = powerTable; } break; } case VTX_SET_POWER : { mVTXPower = int8_t(telemetry.ReadU8()); mVTXPowerDbm = int8_t(telemetry.ReadU8()); break; } case VTX_SET_CHANNEL : { mVTXChannel = int8_t(telemetry.ReadU8()); mVTXFrequency = int16_t(telemetry.ReadU16()); break; } // Errors case ERROR_CAMERA_MISSING : { mCameraMissing = true; break; } default : gDebug() << "WARNING : Received unknown command (" << (uint16_t)cmd << ") !" << flush; break; } } return true; } void Controller::Calibrate() { gDebug() << "Controller::Calibrate()"; if ( !mLink || !isConnected() ) { return; } struct { uint32_t cmd = 0; uint32_t full_recalibration = 0; float current_altitude = 0.0f; } calibrate_cmd; calibrate_cmd.cmd = htonl( CALIBRATE ); mCalibrated = false; mCalibrating = false; while ( not mCalibrating and not mCalibrated ) { mXferMutex.lock(); mTxFrame.Write( (uint8_t*)&calibrate_cmd, sizeof( calibrate_cmd ) ); mXferMutex.unlock(); usleep( 50 * 1000 ); if ( not mCalibrating and not mCalibrated ) { usleep( 1000 * 250 ); } } } void Controller::CalibrateAll() { gDebug() << "Controller::CalibrateAll()"; if ( !mLink || !isConnected() ) { return; } struct { uint32_t cmd = 0; uint32_t full_recalibration = 1; float current_altitude = 0.0f; } calibrate_cmd; calibrate_cmd.cmd = htonl( CALIBRATE ); mXferMutex.lock(); mTxFrame.Write( (uint8_t*)&calibrate_cmd, sizeof( calibrate_cmd ) ); mXferMutex.unlock(); } void Controller::CalibrateESCs() { if ( !mLink || !isConnected() ) { return; } mXferMutex.lock(); mTxFrame.WriteU16( CALIBRATE_ESCS ); mXferMutex.unlock(); } void Controller::setFullTelemetry( bool fullt ) { mXferMutex.lock(); for ( uint32_t retries = 0; retries < 8; retries++ ) { mTxFrame.WriteU16( SET_FULL_TELEMETRY ); mTxFrame.WriteU32( fullt ); } mXferMutex.unlock(); } void Controller::Arm() { /* if ( mCalibrated == false ) { return; } mXferMutex.lock(); for ( uint32_t retries = 0; retries < 1; retries++ ) { mTxFrame.WriteU16( ARM ); } mXferMutex.unlock(); */ } void Controller::Disarm() { /* mXferMutex.lock(); for ( uint32_t retries = 0; retries < 1; retries++ ) { mTxFrame.WriteU16( DISARM ); } mThrust = 0.0f; mXferMutex.unlock(); */ } void Controller::ResetBattery() { mXferMutex.lock(); for ( uint32_t retries = 0; retries < 1; retries++ ) { mTxFrame.WriteU16( RESET_BATTERY ); mTxFrame.WriteU32( 0U ); } mXferMutex.unlock(); } string Controller::getBoardInfos() { // Wait for data to be filled by RX Thread (RxRun()) while ( mBoardInfos.length() == 0 ) { mXferMutex.lock(); for ( uint32_t retries = 0; retries < 1; retries++ ) { mTxFrame.WriteU16( GET_BOARD_INFOS ); } mXferMutex.unlock(); usleep( 1000 * 250 ); } return mBoardInfos; } string Controller::getSensorsInfos() { // Wait for data to be filled by RX Thread (RxRun()) while ( mSensorsInfos.length() == 0 ) { mXferMutex.lock(); for ( uint32_t retries = 0; retries < 1; retries++ ) { mTxFrame.WriteU16( GET_SENSORS_INFOS ); } mXferMutex.unlock(); usleep( 1000 * 250 ); } return mSensorsInfos; } string Controller::getCamerasInfos() { // Wait for data to be filled by RX Thread (RxRun()) while ( mCamerasInfos.length() == 0 ) { mXferMutex.lock(); for ( uint32_t retries = 0; retries < 1; retries++ ) { mTxFrame.WriteU16( GET_CAMERAS_INFOS ); } mXferMutex.unlock(); usleep( 1000 * 250 ); } return mCamerasInfos; } string Controller::getConfigFile() { mConfigFile = ""; // Wait for data to be filled by RX Thread (RxRun()) while ( mConfigFile.length() == 0 ) { mXferMutex.lock(); mTxFrame.WriteU16( GET_CONFIG_FILE ); mXferMutex.unlock(); usleep( 1000 * 250 ); } return mConfigFile; } void Controller::setConfigFile( const string& content ) { gDebug() << "setConfigFile..." << flush; Packet packet( SET_CONFIG_FILE ); packet.WriteU32( crc32( (uint8_t*)content.c_str(), content.length() ) ); packet.WriteString( content ); mConfigUploadValid = false; while ( not mConfigUploadValid ) { mXferMutex.lock(); // mTxFrame.WriteU16( SET_CONFIG_FILE ); // mTxFrame.WriteString( content ); gDebug() << "Sending " << packet.data().size()*4 << " bytes"; mLink->Write( &packet ); mXferMutex.unlock(); usleep( 1000 * 250 ); }; mConfigFile = ""; gDebug() << "setConfigFile ok" << flush; } void Controller::UploadUpdateInit() { Packet init( UPDATE_UPLOAD_INIT ); for ( uint32_t retries = 0; retries < 8; retries++ ) { mXferMutex.lock(); mLink->Write( &init ); mXferMutex.unlock(); usleep( 1000 * 50 ); } } void Controller::UploadUpdateData( const uint8_t* buf, uint32_t offset, uint32_t size ) { Packet packet( UPDATE_UPLOAD_DATA ); packet.WriteU32( crc32( buf, size ) ); packet.WriteU32( offset ); packet.WriteU32( offset ); packet.WriteU32( size ); packet.WriteU32( size ); packet.Write( buf, size ); mUpdateUploadValid = false; mXferMutex.lock(); int retries = 1; mLink->retriesCount(); mLink->setRetriesCount( 1 ); do { mLink->Write( &packet ); usleep( 1000 * 50 ); if ( not mUpdateUploadValid ) { gDebug() << "Broken data received, retrying..." << flush; usleep( 1000 * 10 ); } } while ( not mUpdateUploadValid ); mLink->setRetriesCount( retries ); mXferMutex.unlock(); } void Controller::UploadUpdateProcess( const uint8_t* buf, uint32_t size ) { Packet process( UPDATE_UPLOAD_PROCESS ); process.WriteU32( crc32( buf, size ) ); for ( uint32_t retries = 0; retries < 8; retries++ ) { mXferMutex.lock(); mLink->Write( &process ); mXferMutex.unlock(); usleep( 1000 * 50 ); } } void Controller::EnableTunDevice() { mXferMutex.lock(); mTxFrame.WriteU16( ENABLE_TUN_DEVICE ); mXferMutex.unlock(); } void Controller::DisableTunDevice() { mXferMutex.lock(); mTxFrame.WriteU16( DISABLE_TUN_DEVICE ); mXferMutex.unlock(); } void Controller::ReloadPIDs() { for ( uint32_t retries = 0; retries < 4; retries++ ) { mXferMutex.lock(); mTxFrame.WriteU16( ROLL_PID_FACTORS ); mTxFrame.WriteU16( PITCH_PID_FACTORS ); mTxFrame.WriteU16( YAW_PID_FACTORS ); mTxFrame.WriteU16( OUTER_PID_FACTORS ); mXferMutex.unlock(); usleep( 1000 * 10 ); } } void Controller::setRollPID( const vec3& v ) { gDebug() << "setRollPID..." << flush; while ( mRollPID.x != v.x or mRollPID.y != v.y or mRollPID.z != v.z ) { mXferMutex.lock(); mTxFrame.WriteU16( SET_ROLL_PID_P ); mTxFrame.WriteFloat( v.x ); mTxFrame.WriteU16( SET_ROLL_PID_I ); mTxFrame.WriteFloat( v.y ); mTxFrame.WriteU16( SET_ROLL_PID_D ); mTxFrame.WriteFloat( v.z ); mXferMutex.unlock(); usleep( 1000 * 100 ); } gDebug() << "setRollPID ok" << flush; } void Controller::setPitchPID( const vec3& v ) { gDebug() << "setPitchPID..." << flush; while ( mPitchPID.x != v.x or mPitchPID.y != v.y or mPitchPID.z != v.z ) { mXferMutex.lock(); mTxFrame.WriteU16( SET_PITCH_PID_P ); mTxFrame.WriteFloat( v.x ); mTxFrame.WriteU16( SET_PITCH_PID_I ); mTxFrame.WriteFloat( v.y ); mTxFrame.WriteU16( SET_PITCH_PID_D ); mTxFrame.WriteFloat( v.z ); mXferMutex.unlock(); usleep( 1000 * 100 ); } gDebug() << "setPitchPID ok" << flush; } void Controller::setYawPID( const vec3& v ) { gDebug() << "setYawPID..." << flush; while ( mYawPID.x != v.x or mYawPID.y != v.y or mYawPID.z != v.z ) { mXferMutex.lock(); mTxFrame.WriteU16( SET_YAW_PID_P ); mTxFrame.WriteFloat( v.x ); mTxFrame.WriteU16( SET_YAW_PID_I ); mTxFrame.WriteFloat( v.y ); mTxFrame.WriteU16( SET_YAW_PID_D ); mTxFrame.WriteFloat( v.z ); mXferMutex.unlock(); usleep( 1000 * 100 ); } gDebug() << "setYawPID ok" << flush; } void Controller::setOuterPID( const vec3& v ) { gDebug() << "setOuterPID..." << flush; while ( mOuterPID.x != v.x or mOuterPID.y != v.y or mOuterPID.z != v.z ) { mXferMutex.lock(); mTxFrame.WriteU16( SET_OUTER_PID_P ); mTxFrame.WriteFloat( v.x ); mTxFrame.WriteU16( SET_OUTER_PID_I ); mTxFrame.WriteFloat( v.y ); mTxFrame.WriteU16( SET_OUTER_PID_D ); mTxFrame.WriteFloat( v.z ); mXferMutex.unlock(); usleep( 1000 * 100 ); } gDebug() << "setOuterPID ok" << flush; } void Controller::setHorizonOffset( const vec3& v ) { mXferMutex.lock(); mTxFrame.WriteU16( SET_HORIZON_OFFSET ); mTxFrame.WriteFloat( v.x ); mTxFrame.WriteFloat( v.y ); mXferMutex.unlock(); } void Controller::setThrust( const float& v ) { mXferMutex.lock(); mTxFrame.WriteU16( SET_THRUST ); mTxFrame.WriteFloat( v ); mXferMutex.unlock(); mThrust = v; } void Controller::setThrustRelative( const float& v ) { mXferMutex.lock(); mTxFrame.WriteU16( SET_THRUST ); mTxFrame.WriteFloat( mThrust + v ); mThrust += v; mXferMutex.unlock(); } void Controller::setRoll( const float& v ) { mXferMutex.lock(); mTxFrame.WriteU16( SET_ROLL ); mTxFrame.WriteFloat( v ); mControlRPY.x = v; mXferMutex.unlock(); } void Controller::setPitch( const float& v ) { mXferMutex.lock(); mTxFrame.WriteU16( SET_PITCH ); mTxFrame.WriteFloat( v ); mControlRPY.y = v; mXferMutex.unlock(); } void Controller::setYaw( const float& v ) { mXferMutex.lock(); mTxFrame.WriteU16( SET_YAW ); mTxFrame.WriteFloat( v ); mControlRPY.z = v; mXferMutex.unlock(); } void Controller::setMode( const Controller::Mode& mode ) { mXferMutex.lock(); mTxFrame.WriteU16( SET_MODE ); mTxFrame.WriteU32( (uint32_t)mode ); mXferMutex.unlock(); } void Controller::VideoPause() { mXferMutex.lock(); mTxFrame.WriteU16( VIDEO_PAUSE ); mXferMutex.unlock(); } void Controller::VideoResume() { mXferMutex.lock(); mTxFrame.WriteU16( VIDEO_RESUME ); mXferMutex.unlock(); } void Controller::VideoTakePicture() { mXferMutex.lock(); mTxFrame.WriteU16( VIDEO_TAKE_PICTURE ); mXferMutex.unlock(); } void Controller::VideoBrightnessIncrease() { mXferMutex.lock(); mTxFrame.WriteU16( VIDEO_BRIGHTNESS_INCR ); mXferMutex.unlock(); } void Controller::VideoBrightnessDecrease() { mXferMutex.lock(); mTxFrame.WriteU16( VIDEO_BRIGHTNESS_DECR ); mXferMutex.unlock(); } void Controller::VideoContrastIncrease() { mXferMutex.lock(); mTxFrame.WriteU16( VIDEO_CONTRAST_INCR ); mXferMutex.unlock(); } void Controller::VideoContrastDecrease() { mXferMutex.lock(); mTxFrame.WriteU16( VIDEO_CONTRAST_DECR ); mXferMutex.unlock(); } void Controller::VideoSaturationIncrease() { mXferMutex.lock(); mTxFrame.WriteU16( VIDEO_SATURATION_INCR ); mXferMutex.unlock(); } void Controller::VideoSaturationDecrease() { mXferMutex.lock(); mTxFrame.WriteU16( VIDEO_SATURATION_DECR ); mXferMutex.unlock(); } string Controller::VideoWhiteBalance() { mVideoWhiteBalance = ""; mXferMutex.lock(); uint16_t ack = ( mTXAckID = ( ( mTXAckID + 1 ) % 0x7F ) ); // mXferMutex.unlock(); uint32_t retry = 0; do { // mXferMutex.lock(); mTxFrame.WriteU16( ACK_ID | ack ); mTxFrame.WriteU16( VIDEO_WHITE_BALANCE ); mLink->Write( &mTxFrame ); mTxFrame = Packet(); // mXferMutex.unlock(); usleep( 125 * 1000 ); gDebug() << "lock " << retry << " ('" << mVideoWhiteBalance << "')"; retry++; } while ( retry < 32 and mVideoWhiteBalance == "" ); mXferMutex.unlock(); return mVideoWhiteBalance; } string Controller::VideoLockWhiteBalance() { mVideoWhiteBalance = ""; mXferMutex.lock(); uint16_t ack = ( mTXAckID = ( ( mTXAckID + 1 ) % 0x7F ) ); // mXferMutex.unlock(); uint32_t retry = 0; do { // mXferMutex.lock(); mTxFrame.WriteU16( ACK_ID | ack ); mTxFrame.WriteU16( VIDEO_LOCK_WHITE_BALANCE ); mLink->Write( &mTxFrame ); mTxFrame = Packet(); // mXferMutex.unlock(); usleep( 125 * 1000 ); gDebug() << "lock " << retry << " ('" << mVideoWhiteBalance << "')"; retry++; } while ( retry < 32 and mVideoWhiteBalance == "" ); mXferMutex.unlock(); return mVideoWhiteBalance; } string Controller::VideoExposureMode() { mVideoExposureMode = ""; mXferMutex.lock(); uint16_t ack = ( mTXAckID = ( ( mTXAckID + 1 ) % 0x7F ) ); // mXferMutex.unlock(); uint32_t retry = 0; do { // mXferMutex.lock(); mTxFrame.WriteU16( ACK_ID | ack ); mTxFrame.WriteU16( VIDEO_EXPOSURE_MODE ); mLink->Write( &mTxFrame ); mTxFrame = Packet(); // mXferMutex.unlock(); usleep( 125 * 1000 ); gDebug() << "lock " << retry << " ('" << mVideoExposureMode << "')"; retry++; } while ( mVideoExposureMode == "" ); mXferMutex.unlock(); return mVideoExposureMode; } int32_t Controller::VideoGetIso() { mVideoIso = -1; mXferMutex.lock(); uint16_t ack = ( mTXAckID = ( ( mTXAckID + 1 ) % 0x7F ) ); // mXferMutex.unlock(); uint32_t retry = 0; do { // mXferMutex.lock(); mTxFrame.WriteU16( ACK_ID | ack ); mTxFrame.WriteU16( VIDEO_ISO ); mLink->Write( &mTxFrame ); mTxFrame = Packet(); // mXferMutex.unlock(); usleep( 125 * 1000 ); gDebug() << "lock " << retry << " ('" << mVideoIso << "')"; retry++; } while ( mVideoIso == -1 ); mXferMutex.unlock(); return mVideoIso; } uint32_t Controller::VideoGetShutterSpeed() { mVideoShutterSpeed = -1; mXferMutex.lock(); uint16_t ack = ( mTXAckID = ( ( mTXAckID + 1 ) % 0x7F ) ); // mXferMutex.unlock(); uint32_t retry = 0; do { // mXferMutex.lock(); mTxFrame.WriteU16( ACK_ID | ack ); mTxFrame.WriteU16( VIDEO_SHUTTER_SPEED ); mLink->Write( &mTxFrame ); mTxFrame = Packet(); // mXferMutex.unlock(); usleep( 125 * 1000 ); gDebug() << "lock " << retry << " ('" << mVideoShutterSpeed << "')"; retry++; } while ( mVideoShutterSpeed == -1 ); mXferMutex.unlock(); return mVideoShutterSpeed; } void Controller::VideoIsoDecrease() { mXferMutex.lock(); mTxFrame.WriteU16( VIDEO_ISO_DECR ); mXferMutex.unlock(); } void Controller::VideoIsoIncrease() { mXferMutex.lock(); mTxFrame.WriteU16( VIDEO_ISO_INCR ); mXferMutex.unlock(); } void Controller::VideoShutterSpeedDecrease() { mXferMutex.lock(); mTxFrame.WriteU16( VIDEO_SHUTTER_SPEED_DECR ); mXferMutex.unlock(); } void Controller::VideoShutterSpeedIncrease() { mXferMutex.lock(); mTxFrame.WriteU16( VIDEO_SHUTTER_SPEED_INCR ); mXferMutex.unlock(); } void Controller::getCameraLensShader( CameraLensShaderColor* r, CameraLensShaderColor* g, CameraLensShaderColor* b ) { mCameraLensShaderR.base = 0; mCameraLensShaderG.base = 0; mCameraLensShaderB.base = 0; mXferMutex.lock(); uint16_t ack = ( mTXAckID = ( ( mTXAckID + 1 ) % 0x7F ) ); uint32_t retry = 0; do { mTxFrame.WriteU16( ACK_ID | ack ); mTxFrame.WriteU16( VIDEO_LENS_SHADER ); mLink->Write( &mTxFrame ); mTxFrame = Packet(); usleep( 125 * 1000 ); } while ( mCameraLensShaderR.base == 0 and mCameraLensShaderG.base == 0 and mCameraLensShaderB.base == 0 ); mXferMutex.unlock(); // wait until all the entries are filled usleep( 40 * 1000 ); *r = mCameraLensShaderR; *g = mCameraLensShaderG; *b = mCameraLensShaderB; } void Controller::setCameraLensShader( const CameraLensShaderColor& r, const CameraLensShaderColor& g, const CameraLensShaderColor& b ) { mXferMutex.lock(); uint16_t ack = ( mTXAckID = ( ( mTXAckID + 1 ) % 0x7F ) ); for ( uint32_t retry = 0; retry < 4; retry++ ) { mTxFrame.WriteU16( ACK_ID | ack ); mTxFrame.WriteU16( VIDEO_SET_LENS_SHADER ); mTxFrame.WriteU8( r.base ); mTxFrame.WriteU8( r.radius ); mTxFrame.WriteU8( r.strength ); mTxFrame.WriteU8( g.base ); mTxFrame.WriteU8( g.radius ); mTxFrame.WriteU8( g.strength ); mTxFrame.WriteU8( b.base ); mTxFrame.WriteU8( b.radius ); mTxFrame.WriteU8( b.strength ); mLink->Write( &mTxFrame ); mTxFrame = Packet(); usleep( 20 * 1000 ); }; mXferMutex.unlock(); } void Controller::setNightMode( const bool& night ) { mXferMutex.lock(); mTxFrame.WriteU16( VIDEO_NIGHT_MODE ); mTxFrame.WriteU32( night ); mXferMutex.unlock(); } void Controller::VTXGetSettings() { uint16_t ack = ( mTXAckID = ( ( mTXAckID + 1 ) % 0x7F ) ); uint32_t retry = 0; mXferMutex.lock(); do { for ( uint8_t i = 0; i < 2; i++ ) { mTxFrame.WriteU16( VTX_GET_SETTINGS ); mLink->Write( &mTxFrame ); usleep( 25 * 1000 ); mTxFrame = Packet(); } mTxFrame.WriteU16( ACK_ID | ack ); mLink->Write( &mTxFrame ); mTxFrame = Packet(); usleep( 25 * 1000 ); gDebug() << "lock " << retry << " (VTX get settings)"; printf( "ack : %d , %d\n", mTXAckID, mRXAckID ); retry++; } while ( retry < 4 and mRXAckID != mTXAckID ); mXferMutex.unlock(); } void Controller::VTXSetPower( uint8_t power ) { uint16_t ack = ( mTXAckID = ( ( mTXAckID + 1 ) % 0x7F ) ); uint32_t retry = 0; mXferMutex.lock(); do { for ( uint8_t i = 0; i < 1; i++ ) { mTxFrame.WriteU16( VTX_SET_POWER ); mTxFrame.WriteU8( power ); mLink->Write( &mTxFrame ); usleep( 25 * 1000 ); mTxFrame = Packet(); } mTxFrame.WriteU16( ACK_ID | ack ); mLink->Write( &mTxFrame ); mTxFrame = Packet(); usleep( 25 * 1000 ); gDebug() << "lock " << retry << " (VTX power " << power << ")"; printf( "ack : %d , %d\n", mTXAckID, mRXAckID ); retry++; } while ( retry < 4 and mRXAckID != mTXAckID ); mXferMutex.unlock(); } void Controller::VTXSetChannel( uint8_t channel ) { uint16_t ack = ( mTXAckID = ( ( mTXAckID + 1 ) % 0x7F ) ); uint32_t retry = 0; mXferMutex.lock(); do { for ( uint8_t i = 0; i < 1; i++ ) { mTxFrame.WriteU16( VTX_SET_CHANNEL ); mTxFrame.WriteU8( channel ); mLink->Write( &mTxFrame ); usleep( 25 * 1000 ); mTxFrame = Packet(); } mTxFrame.WriteU16( ACK_ID | ack ); mLink->Write( &mTxFrame ); mTxFrame = Packet(); usleep( 25 * 1000 ); gDebug() << "lock " << retry << " (VTX channel " << channel << ")"; printf( "ack : %d , %d\n", mTXAckID, mRXAckID ); retry++; } while ( retry < 4 and mRXAckID != mTXAckID ); mXferMutex.unlock(); } vector< string > Controller::recordingsList() { mRecordingsList = ""; // Wait for data to be filled by RX Thread (RxRun()) do { mXferMutex.lock(); mTxFrame.WriteU16( GET_RECORDINGS_LIST ); mXferMutex.unlock(); uint32_t retry = 0; while ( mRecordingsList.length() == 0 and retry++ < 1000 / 250 ) { usleep( 1000 * 250 ); } } while ( mRecordingsList == "broken" ); gDebug() << "mRecordingsList : " << mRecordingsList; vector< string > list; string full = mRecordingsList; while ( full.length() > 0 ) { list.emplace_back( full.substr( 0, full.find( ";" ) ) ); full = full.substr( full.find( ";" ) + 1 ); } return list; } float Controller::acceleration() const { return mAcceleration; } list< vec4 > Controller::rpyHistory() { mHistoryMutex.lock(); list< vec4 > ret = mRPYHistory; mHistoryMutex.unlock(); return ret; } list< vec4 > Controller::ratesHistory() { mHistoryMutex.lock(); list< vec4 > ret = mRatesHistory; mHistoryMutex.unlock(); return ret; } list< vec4 > Controller::ratesDerivativeHistory() { mHistoryMutex.lock(); list< vec4 > ret = mRatesDerivativeHistory; mHistoryMutex.unlock(); return ret; } list< vec4 > Controller::gyroscopeHistory() { mHistoryMutex.lock(); list< vec4 > ret = mGyroscopeHistory; mHistoryMutex.unlock(); return ret; } list< vec4 > Controller::accelerationHistory() { mHistoryMutex.lock(); list< vec4 > ret = mAccelerationHistory; mHistoryMutex.unlock(); return ret; } list< vec4 > Controller::magnetometerHistory() { mHistoryMutex.lock(); list< vec4 > ret = mMagnetometerHistory; mHistoryMutex.unlock(); return ret; } list< vec3 > Controller::outerPidHistory() { mHistoryMutex.lock(); list< vec3 > ret = mOuterPIDHistory; mHistoryMutex.unlock(); return ret; } list< vec2 > Controller::altitudeHistory() { mHistoryMutex.lock(); list< vec2 > ret = mAltitudeHistory; mHistoryMutex.unlock(); return ret; } list< vec4 > Controller::dnfDftHistory() { mHistoryMutex.lock(); list< vec4 > ret = mDnfDft; mHistoryMutex.unlock(); return ret; } float Controller::localBatteryVoltage() const { return mLocalBatteryVoltage; } 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; } void Controller::MotorTest( uint32_t id ) { if ( !mLink ) { return; } mXferMutex.lock(); mTxFrame.WriteU16( MOTOR_TEST ); mTxFrame.WriteU32( id ); mXferMutex.unlock(); } void Controller::MotorsBeep( bool enabled ) { if ( !mLink ) { return; } mXferMutex.lock(); mTxFrame.WriteU16( MOTORS_BEEP ); mTxFrame.WriteU16( enabled ); mXferMutex.unlock(); }
43,878
C++
.cpp
1,645
23.555623
138
0.649587
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,816
ControllerBase.cpp
dridri_bcflight/libcontroller/ControllerBase.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 <string.h> #include <signal.h> #include <math.h> //#include <netinet/in.h> //#include <netinet/tcp.h> #include <stdio.h> #include "ControllerBase.h" map< ControllerBase::Cmd, string > ControllerBase::mCommandsNames = { { ControllerBase::UNKNOWN, "Unknown" }, // Configure { ControllerBase::STATUS, "Status" }, { ControllerBase::PING, "Ping" }, { ControllerBase::TELEMETRY, "Telemetry" }, { ControllerBase::CONTROLS, "Controls" }, { ControllerBase::CALIBRATE, "Calibrate" }, { ControllerBase::SET_TIMESTAMP, "Set timestamp" }, { ControllerBase::ARM, "Arm" }, { ControllerBase::DISARM, "Disarm" }, { ControllerBase::RESET_BATTERY, "Reset battery" }, { ControllerBase::CALIBRATE_ESCS, "Calibrate ESCs" }, { ControllerBase::SET_FULL_TELEMETRY, "0x77" }, { ControllerBase::DEBUG_OUTPUT, "0x7A" }, { ControllerBase::GET_BOARD_INFOS, "Board infos" }, { ControllerBase::GET_SENSORS_INFOS, "Sensors infos" }, { ControllerBase::GET_CONFIG_FILE, "Get config file" }, { ControllerBase::SET_CONFIG_FILE, "Set config file" }, { ControllerBase::UPDATE_UPLOAD_INIT, "0x9A" }, { ControllerBase::UPDATE_UPLOAD_DATA, "0x9B" }, { ControllerBase::UPDATE_UPLOAD_PROCESS, "0x9C" }, // Getters { ControllerBase::PRESSURE, "Pressure" }, { ControllerBase::TEMPERATURE, "Temperature" }, { ControllerBase::ALTITUDE, "Altitude" }, { ControllerBase::ROLL, "Roll" }, { ControllerBase::PITCH, "Pitch" }, { ControllerBase::YAW, "Yaw" }, { ControllerBase::ROLL_PITCH_YAW, "Roll-Pitch-Yaw" }, { ControllerBase::ACCEL, "Acceleration" }, { ControllerBase::GYRO, "Gyroscope" }, { ControllerBase::MAGN, "Magnetometer" }, { ControllerBase::MOTORS_SPEED, "Motors speed" }, { ControllerBase::CURRENT_ACCELERATION, "Current acceleration" }, { ControllerBase::SENSORS_DATA, "Sensors data" }, { ControllerBase::PID_OUTPUT, "PID output" }, { ControllerBase::OUTER_PID_OUTPUT, "Outer PID output" }, { ControllerBase::ROLL_PID_FACTORS, "Roll PID factors" }, { ControllerBase::PITCH_PID_FACTORS, "Pitch PID factors" }, { ControllerBase::YAW_PID_FACTORS, "Yaw PID factors" }, { ControllerBase::OUTER_PID_FACTORS, "Outer PID factors" }, { ControllerBase::HORIZON_OFFSET, "Horizon offset" }, { ControllerBase::VBAT, "Battery voltage" }, { ControllerBase::TOTAL_CURRENT, "Total current draw" }, { ControllerBase::CURRENT_DRAW, "Current draw" }, { ControllerBase::BATTERY_LEVEL, "Battery level" }, { ControllerBase::CPU_LOAD, "CPU Load" }, { ControllerBase::CPU_TEMP, "CPU Temp" }, { ControllerBase::RX_QUALITY, "RX Quality" }, // Setters { ControllerBase::SET_ROLL, "Set roll" }, { ControllerBase::SET_PITCH, "Set pitch" }, { ControllerBase::SET_YAW, "Set yaw" }, { ControllerBase::SET_THRUST, "Set thrust" }, { ControllerBase::RESET_MOTORS, "Reset motors" }, { ControllerBase::SET_MODE, "Set mode" }, { ControllerBase::SET_ALTITUDE_HOLD, "Altitude hold" }, { ControllerBase::SET_ROLL_PID_P, "0x50" }, { ControllerBase::SET_ROLL_PID_I, "0x51" }, { ControllerBase::SET_ROLL_PID_D, "0x52" }, { ControllerBase::SET_PITCH_PID_P, "0x53" }, { ControllerBase::SET_PITCH_PID_I, "0x54" }, { ControllerBase::SET_PITCH_PID_D, "0x55" }, { ControllerBase::SET_YAW_PID_P, "0x56" }, { ControllerBase::SET_YAW_PID_I, "0x57" }, { ControllerBase::SET_YAW_PID_D, "0x58" }, { ControllerBase::SET_OUTER_PID_P, "0x59" }, { ControllerBase::SET_OUTER_PID_I, "0x5A" }, { ControllerBase::SET_OUTER_PID_D, "0x5B" }, { ControllerBase::SET_HORIZON_OFFSET, "Set horizon offset" }, // Video { ControllerBase::VIDEO_START_RECORD, "Start video record" }, { ControllerBase::VIDEO_STOP_RECORD, "Stop video record" }, { ControllerBase::VIDEO_BRIGHTNESS_INCR, "Increase video brightness" }, { ControllerBase::VIDEO_BRIGHTNESS_DECR, "Decrease video brightness" }, { ControllerBase::VIDEO_CONTRAST_INCR, "Increase video contrast" }, { ControllerBase::VIDEO_CONTRAST_DECR, "Decrease video contrast" }, { ControllerBase::VIDEO_SATURATION_INCR, "Increase video saturation" }, { ControllerBase::VIDEO_SATURATION_DECR, "Decrease video saturation" }, { ControllerBase::VIDEO_NIGHT_MODE, "Set video night mode" }, { ControllerBase::VIDEO_WHITE_BALANCE, "Switch video white balance" }, { ControllerBase::VIDEO_LOCK_WHITE_BALANCE, "Lock video white balance" }, // User datas { ControllerBase::GET_USERNAME, "Get username" }, // VTX { ControllerBase::VTX_GET_SETTINGS, "VTX get settings" }, { ControllerBase::VTX_SET_POWER, "VTX set power" }, { ControllerBase::VTX_SET_CHANNEL, "VTX set channel" }, // Testing { ControllerBase::MOTOR_TEST, "Motor test" }, { ControllerBase::MOTORS_BEEP, "Motors beep" }, }; ControllerBase::ControllerBase( Link* link ) : mLink( link ) , mConnected( false ) , mConnectionEstablished( false ) , mLockState( 0 ) , mTXAckID( 0 ) , mRXAckID( 0 ) { } ControllerBase::~ControllerBase() { }
5,578
C++
.cpp
131
40.664122
74
0.717935
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,817
Thread.cpp
dridri_bcflight/libcontroller/Thread.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 <sched.h> #include <string.h> #include <signal.h> #include <time.h> #include <sys/time.h> #ifdef WIN32 #include <windows.h> #endif #include "Thread.h" mutex Thread::mCriticalMutex; uint64_t Thread::mBaseTick = 0; Thread::Thread( const string& name ) : mName( name ) , mRunning( false ) , mIsRunning( false ) , mFinished( false ) , mPriority( 0 ) , mSetPriority( 0 ) , mAffinity( -1 ) , mSetAffinity( -1 ) , mTerminate( false ) { // pthread_attr_t attr; // pthread_attr_init( &attr ); // pthread_attr_setstacksize( &attr, 16 * 1024 * 1024 ); // pthread_create( &mThread, &attr, (void*(*)(void*))&Thread::sThreadEntry, this ); pthread_create( &mThread, nullptr, (void*(*)(void*))&Thread::sThreadEntry, this ); #ifndef WIN32 pthread_setname_np( mThread, name.substr( 0, 15 ).c_str() ); #endif } Thread::~Thread() { } void Thread::Start() { mRunning = true; } void Thread::Stop() { mTerminate = true; } void Thread::Pause() { mRunning = false; } void Thread::Join() { while ( !mFinished ) { usleep( 1000 * 10 ); } } bool Thread::running() { if ( pthread_kill( mThread, 0 ) == ESRCH ) { mIsRunning = false; } return mIsRunning; } void Thread::setPriority( int32_t p, int affinity ) { mSetPriority = p; #ifdef __linux__ if ( affinity >= 0 and affinity < sysconf(_SC_NPROCESSORS_ONLN) ) { mSetAffinity = affinity; } #endif } void Thread::sThreadEntry( void* argp ) { static_cast< Thread* >( argp )->ThreadEntry(); } void Thread::ThreadEntry() { do { while ( !mRunning ) { if ( mTerminate ) { return; } mIsRunning = false; usleep( 1000 * 100 ); } mIsRunning = true; if ( mSetPriority != mPriority ) { mPriority = mSetPriority; printf( "Thread '%s' priority set to %d\n", mName.c_str(), mPriority ); #ifdef __linux__ struct sched_param sched; memset( &sched, 0, sizeof(sched) ); if ( mPriority > sched_get_priority_max( SCHED_RR ) ) { sched.sched_priority = sched_get_priority_max( SCHED_RR ); } else{ sched.sched_priority = mPriority; } sched_setscheduler( 0, SCHED_RR, &sched ); #endif } if ( mSetAffinity >= 0 and mSetAffinity != mAffinity ) { mAffinity = mSetAffinity; #ifdef __linux__ printf( "Thread '%s' affinity set to %d\n", mName.c_str(), mAffinity ); cpu_set_t cpuset; CPU_ZERO( &cpuset ); CPU_SET( mAffinity, &cpuset ); pthread_setaffinity_np( pthread_self(), sizeof(cpu_set_t), &cpuset ); #endif } } while ( not mTerminate and run() ); mIsRunning = false; mFinished = true; } uint64_t Thread::GetTick() { uint64_t ret = 0; #ifdef WIN32 ret = timeGetTime(); #elif __APPLE__ struct timeval cTime; gettimeofday( &cTime, 0 ); ret = ( cTime.tv_sec * 1000 ) + ( cTime.tv_usec / 1000 ); #else struct timespec now; clock_gettime( CLOCK_MONOTONIC, &now ); ret = now.tv_sec * 1000 + now.tv_nsec / 1000000; #endif if ( mBaseTick == 0 ) { mBaseTick = ret; } return ret - mBaseTick; } float Thread::GetSeconds() { return (float)( GetTick() ) / 1000.0f; }
3,766
C++
.cpp
153
22.490196
84
0.684137
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,818
SX127x.cpp
dridri_bcflight/libcontroller/links/SX127x.cpp
#include <unistd.h> #include "SX127x.h" #include "SX127xRegs.h" #include "SX127xRegs-LoRa.h" #include <iostream> #include <cmath> #include <string.h> #include <Thread.h> #include <GPIO.h> #include <SPI.h> #include <Debug.h> #ifdef BOARD_rpi #include <pigpio.h> #endif #define TICKS Thread::GetTick() #define SX_TIMEOUT 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 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( const SX127x::Config& config ) : Link() , mDevice( config.device ) , mResetPin( config.resetPin ) , mTXPin( config.txPin ) , mRXPin( config.rxPin ) , mIRQPin( config.irqPin ) , mBlocking( config.blocking ) , mDropBroken( config.dropBroken ) , mModem( config.modem ) , mFrequency( config.frequency ) , mInputPort( config.inputPort ) , mOutputPort( config.outputPort ) , mRetries( config.retries ) , mReadTimeout( config.readTimeout ) , mBitrate( config.bitrate ) , mBandwidth( config.bandwidth ) , mBandwidthAfc( config.bandwidthAfc ) , mFdev( config.fdev ) , mSending( false ) , mSendingEnd( false ) , mReceiving( false ) , mSendTime( 0 ) , mRSSI( 0 ) , mRxQuality( 0 ) , mPerfTicks( 0 ) , mPerfLastRxBlock( 0 ) , mPerfValidBlocks( 0 ) , mPerfInvalidBlocks( 0 ) , mPerfBlocksPerSecond( 0 ) , mPerfMaxBlocksPerSecond( 0 ) , mTXBlockID( 0 ) { // mDropBroken = false; // TEST (using custom CRC instead) if ( mResetPin < 0 ) { std::cout << "WARNING : No Reset-pin specified for SX127x, cannot create link !\n"; return; } if ( mIRQPin < 0 ) { std::cout << "WARNING : No IRQ-pin specified for SX127x, cannot create link !\n"; return; } memset( &mRxBlock, 0, sizeof(mRxBlock) ); #ifdef BOARD_rpi gpioInitialise(); #endif // Setup SPI and GPIO mSPI = new SPI( mDevice, 8000000 ); GPIO::setMode( mResetPin, GPIO::Output ); GPIO::Write( mResetPin, false ); GPIO::setMode( mIRQPin, GPIO::Input ); GPIO::SetupInterrupt( mIRQPin, GPIO::Rising, [this](){ this->Interrupt(); } ); if ( mTXPin >= 0 ) { GPIO::Write( mTXPin, false ); GPIO::setMode( mTXPin, GPIO::Output ); } if ( mRXPin >= 0 ) { GPIO::Write( mRXPin, false ); GPIO::setMode( mRXPin, GPIO::Output ); } } SX127x::~SX127x() { } int SX127x::Connect() { // Reset chip reset(); if ( not ping() ) { std::cout << "SX127x not responding !\n"; return -1; } // Cut the PA just in case, RFO output, power = -1 dBm writeRegister( REG_PACONFIG, 0x00 ); { // Start calibration in LF band writeRegister ( REG_IMAGECAL, ( readRegister( REG_IMAGECAL ) & RF_IMAGECAL_IMAGECAL_MASK ) | RF_IMAGECAL_IMAGECAL_START ); while ( ( readRegister( REG_IMAGECAL ) & RF_IMAGECAL_IMAGECAL_RUNNING ) == RF_IMAGECAL_IMAGECAL_RUNNING ) { usleep( 10 ); } } { // Set frequency to mid-HF band setFrequency( 868000000 ); // Start calibration in HF band writeRegister( REG_IMAGECAL, ( readRegister( REG_IMAGECAL ) & RF_IMAGECAL_IMAGECAL_MASK ) | RF_IMAGECAL_IMAGECAL_START ); while ( ( readRegister( REG_IMAGECAL ) & RF_IMAGECAL_IMAGECAL_RUNNING ) == RF_IMAGECAL_IMAGECAL_RUNNING ) { usleep( 10 ); } } // Start module in sleep mode setOpMode( RF_OPMODE_SLEEP ); // Set modem setModem( mModem ); // Set frequency setFrequency( mFrequency ); bool boosted_module_20dbm = true; // Set PA to maximum => TODO : make it more configurable writeRegister( REG_PACONFIG, ( boosted_module_20dbm ? RF_PACONFIG_PASELECT_PABOOST : RF_PACONFIG_PASELECT_RFO ) | 0x70 | 0xF ); writeRegister( REG_PADAC, 0x80 | ( boosted_module_20dbm ? RF_PADAC_20DBM_ON : RF_PADAC_20DBM_OFF ) ); writeRegister( REG_OCP, RF_OCP_TRIM_240_MA | RF_OCP_OFF ); writeRegister( REG_PARAMP, RF_PARAMP_SHAPING_NONE | RF_PARAMP_0040_US | RF_PARAMP_LOWPNTXPLL_OFF ); // writeRegister( REG_PARAMP, RF_PARAMP_SHAPING_NONE | ( mModem == LoRa ? RF_PARAMP_0050_US : RF_PARAMP_0010_US ) | RF_PARAMP_LOWPNTXPLL_OFF ); // Set LNA writeRegister( REG_LNA, RF_LNA_GAIN_G1 | RF_LNA_BOOST_ON ); if ( mModem == FSK ) { // Set RX/Sync config // writeRegister( REG_RXCONFIG, RF_RXCONFIG_RESTARTRXONCOLLISION_ON | RF_RXCONFIG_AFCAUTO_OFF | RF_RXCONFIG_AGCAUTO_OFF ); writeRegister( REG_RXCONFIG, RF_RXCONFIG_RXTRIGER_PREAMBLEDETECT | RF_RXCONFIG_RESTARTRXONCOLLISION_ON | RF_RXCONFIG_AFCAUTO_OFF | RF_RXCONFIG_AGCAUTO_OFF ); writeRegister( REG_SYNCCONFIG, RF_SYNCCONFIG_SYNC_ON | RF_SYNCCONFIG_AUTORESTARTRXMODE_WAITPLL_ON | RF_SYNCCONFIG_PREAMBLEPOLARITY_AA | RF_SYNCCONFIG_SYNCSIZE_4 ); writeRegister( REG_SYNCVALUE1, 0x64 ); writeRegister( REG_SYNCVALUE2, 0x72 ); writeRegister( REG_SYNCVALUE3, 0x69 ); writeRegister( REG_SYNCVALUE4, 0x30 ); writeRegister( REG_PREAMBLEDETECT, RF_PREAMBLEDETECT_DETECTOR_ON | RF_PREAMBLEDETECT_DETECTORSIZE_1 | RF_PREAMBLEDETECT_DETECTORTOL_20 ); } // Set RSSI smoothing writeRegister( 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( 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( rxconf ); std::cout << "Module online : " << ping() << "\n"; std::cout << "Modem : " << ( ( readRegister( REG_OPMODE ) & RFLR_OPMODE_LONGRANGEMODE_ON ) ? "LoRa" : "FSK" ) << "\n"; std::cout << "Frequency : " << (uint32_t)((float)(((uint32_t)readRegister(REG_FRFMSB) << 16 ) | ((uint32_t)readRegister(REG_FRFMID) << 8 ) | ((uint32_t)readRegister(REG_FRFLSB) )) * FREQ_STEP) << "Hz\n"; std::cout << "PACONFIG : 0x" << std::hex << (int)readRegister( REG_PACONFIG ) << "\n"; std::cout << "PADAC : 0x" << std::hex << (int)readRegister( REG_PADAC ) << "\n"; std::cout << "PARAMP : 0x" << std::hex << (int)readRegister( REG_PARAMP ) << "\n"; std::cout << "OCP : 0x" << std::hex << (int)readRegister( REG_OCP ) << "\n"; std::cout << "RXCONFIG : " << std::hex << (int)readRegister( REG_RXCONFIG ) << "\n"; std::cout << "SYNCCONFIG : " << std::hex << (int)readRegister( REG_SYNCCONFIG ) << "\n"; startReceiving(); mConnected = true; return 0; } void SX127x::SetupTX( const TxConfig_t& conf ) { switch( mModem ) { case FSK : { uint32_t fdev = ( uint16_t )( ( double )conf.fdev / ( double )FREQ_STEP ); writeRegister( REG_FDEVMSB, ( uint8_t )( fdev >> 8 ) ); writeRegister( REG_FDEVLSB, ( uint8_t )( fdev & 0xFF ) ); uint32_t datarate = ( uint16_t )( ( double )XTAL_FREQ / ( double )conf.datarate ); writeRegister( REG_BITRATEMSB, ( uint8_t )( datarate >> 8 ) ); writeRegister( REG_BITRATELSB, ( uint8_t )( datarate & 0xFF ) ); writeRegister( REG_PREAMBLEMSB, ( conf.preambleLen >> 8 ) & 0x00FF ); writeRegister( REG_PREAMBLELSB, conf.preambleLen & 0xFF ); writeRegister( REG_PACKETCONFIG1, ( readRegister( REG_PACKETCONFIG1 ) & RF_PACKETCONFIG1_CRC_MASK & RF_PACKETCONFIG1_PACKETFORMAT_MASK ) | RF_PACKETCONFIG1_PACKETFORMAT_VARIABLE | ( conf.crcOn << 4 ) ); writeRegister( REG_PACKETCONFIG2, ( readRegister( 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 { std::cout << "ERROR: When using LoRa modem only bandwidths 125, 250 and 500 kHz are supported !\n"; return; } uint32_t spreading_factor = std::max( 6u, std::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( REG_LR_PLLHOP, ( readRegister( REG_LR_PLLHOP ) & RFLR_PLLHOP_FASTHOP_MASK ) | RFLR_PLLHOP_FASTHOP_ON ); writeRegister( REG_LR_HOPPERIOD, conf.hopPeriod ); } writeRegister( REG_LR_MODEMCONFIG1, ( readRegister( 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( REG_LR_MODEMCONFIG2, ( readRegister( REG_LR_MODEMCONFIG2 ) & RFLR_MODEMCONFIG2_SF_MASK & RFLR_MODEMCONFIG2_RXPAYLOADCRC_MASK ) | ( spreading_factor << 4 ) | ( conf.crcOn << 2 ) ); // writeRegister( REG_LR_MODEMCONFIG3, ( readRegister( REG_LR_MODEMCONFIG3 ) & RFLR_MODEMCONFIG3_LOWDATARATEOPTIMIZE_MASK ) | ( lowDatarateOptimize << 3 ) ); // writeRegister( REG_LR_PREAMBLEMSB, ( conf.preambleLen >> 8 ) & 0x00FF ); // writeRegister( REG_LR_PREAMBLELSB, conf.preambleLen & 0xFF ); if( spreading_factor == 6 ) { // writeRegister( REG_LR_DETECTOPTIMIZE, ( readRegister( REG_LR_DETECTOPTIMIZE ) & RFLR_DETECTIONOPTIMIZE_MASK ) | RFLR_DETECTIONOPTIMIZE_SF6 ); // writeRegister( REG_LR_DETECTIONTHRESHOLD, RFLR_DETECTIONTHRESH_SF6 ); } else { // writeRegister( REG_LR_DETECTOPTIMIZE, ( readRegister( REG_LR_DETECTOPTIMIZE ) & RFLR_DETECTIONOPTIMIZE_MASK ) | RFLR_DETECTIONOPTIMIZE_SF7_TO_SF12 ); // writeRegister( REG_LR_DETECTIONTHRESHOLD, RFLR_DETECTIONTHRESH_SF7_TO_SF12 ); } } break; } } void SX127x::SetupRX( const RxConfig_t& conf ) { switch( mModem ) { case FSK : { uint32_t datarate = ( uint32_t )( ( double )XTAL_FREQ / ( double )conf.datarate ); writeRegister( REG_BITRATEMSB, ( uint8_t )( datarate >> 8 ) ); writeRegister( REG_BITRATELSB, ( uint8_t )( datarate & 0xFF ) ); writeRegister( REG_RXBW, GetFskBandwidthRegValue( conf.bandwidth ) ); writeRegister( REG_AFCBW, GetFskBandwidthRegValue( conf.bandwidthAfc ) ); writeRegister( REG_PREAMBLEMSB, ( uint8_t )( ( conf.preambleLen >> 8 ) & 0xFF ) ); writeRegister( REG_PREAMBLELSB, ( uint8_t )( conf.preambleLen & 0xFF ) ); // writeRegister( REG_PAYLOADLENGTH, conf.payloadLen ); writeRegister( REG_PAYLOADLENGTH, 0xFF ); writeRegister( REG_PACKETCONFIG1, ( readRegister( REG_PACKETCONFIG1 ) & RF_PACKETCONFIG1_CRC_MASK & RF_PACKETCONFIG1_PACKETFORMAT_MASK ) | RF_PACKETCONFIG1_PACKETFORMAT_VARIABLE | ( conf.crcOn << 4 ) ); writeRegister( REG_PACKETCONFIG2, ( readRegister( 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 { std::cout << "ERROR: When using LoRa modem only bandwidths 125, 250 and 500 kHz are supported !\n"; return; } uint32_t spreading_factor = std::max( 6u, std::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( REG_LR_MODEMCONFIG1, ( readRegister( 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( REG_LR_MODEMCONFIG2, ( readRegister( 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( REG_LR_MODEMCONFIG3, ( readRegister( REG_LR_MODEMCONFIG3 ) & RFLR_MODEMCONFIG3_LOWDATARATEOPTIMIZE_MASK ) | ( lowDatarateOptimize << 3 ) ); // writeRegister( REG_LR_SYMBTIMEOUTLSB, ( uint8_t )( conf.symbTimeout & 0xFF ) ); // writeRegister( REG_LR_PREAMBLEMSB, ( uint8_t )( ( conf.preambleLen >> 8 ) & 0xFF ) ); // writeRegister( REG_LR_PREAMBLELSB, ( uint8_t )( conf.preambleLen & 0xFF ) ); if( conf.freqHopOn == true ) { writeRegister( REG_LR_PLLHOP, ( readRegister( REG_LR_PLLHOP ) & RFLR_PLLHOP_FASTHOP_MASK ) | RFLR_PLLHOP_FASTHOP_ON ); writeRegister( REG_LR_HOPPERIOD, conf.hopPeriod ); } if( ( bandwidth == 9 ) and ( mFrequency > 525000000 ) ) { // ERRATA 2.1 - Sensitivity Optimization with a 500 kHz Bandwidth // writeRegister( REG_LR_TEST36, 0x02 ); // writeRegister( REG_LR_TEST3A, 0x64 ); } else if( bandwidth == 9 ) { // ERRATA 2.1 - Sensitivity Optimization with a 500 kHz Bandwidth // writeRegister( REG_LR_TEST36, 0x02 ); // writeRegister( REG_LR_TEST3A, 0x7F ); } else { // ERRATA 2.1 - Sensitivity Optimization with a 500 kHz Bandwidth // writeRegister( REG_LR_TEST36, 0x03 ); } if( spreading_factor == 6 ) { // writeRegister( REG_LR_DETECTOPTIMIZE, ( readRegister( REG_LR_DETECTOPTIMIZE ) & RFLR_DETECTIONOPTIMIZE_MASK ) | RFLR_DETECTIONOPTIMIZE_SF6 ); // writeRegister( REG_LR_DETECTIONTHRESHOLD, RFLR_DETECTIONTHRESH_SF6 ); } else { // writeRegister( REG_LR_DETECTOPTIMIZE, ( readRegister( REG_LR_DETECTOPTIMIZE ) & RFLR_DETECTIONOPTIMIZE_MASK ) | RFLR_DETECTIONOPTIMIZE_SF7_TO_SF12 ); // writeRegister( REG_LR_DETECTIONTHRESHOLD, RFLR_DETECTIONTHRESH_SF7_TO_SF12 ); } } break; } } void SX127x::setFrequency( float f ) { uint32_t freq = (uint32_t)( (float)f / FREQ_STEP ); writeRegister( REG_FRFMSB, (uint8_t)( (freq >> 16) & 0xFF ) ); writeRegister( REG_FRFMID, (uint8_t)( (freq >> 8) & 0xFF ) ); writeRegister( REG_FRFLSB, (uint8_t)( freq & 0xFF ) ); } void SX127x::startReceiving() { mSending = false; mSendingEnd = false; if ( mTXPin >= 0 ) { GPIO::Write( mTXPin, false ); } if ( mRXPin >= 0 ) { GPIO::Write( mRXPin, true ); } if ( mModem == LoRa ) { writeRegister( REG_LR_INVERTIQ, ( ( readRegister( REG_LR_INVERTIQ ) & RFLR_INVERTIQ_TX_MASK & RFLR_INVERTIQ_RX_MASK ) | RFLR_INVERTIQ_RX_OFF | RFLR_INVERTIQ_TX_OFF ) ); writeRegister( REG_LR_INVERTIQ2, RFLR_INVERTIQ2_OFF ); writeRegister( REG_LR_IRQFLAGSMASK, RFLR_IRQFLAGS_VALIDHEADER | RFLR_IRQFLAGS_TXDONE | RFLR_IRQFLAGS_CADDONE | RFLR_IRQFLAGS_FHSSCHANGEDCHANNEL | RFLR_IRQFLAGS_CADDETECTED ); writeRegister( REG_DIOMAPPING1, ( readRegister( REG_DIOMAPPING1 ) & RFLR_DIOMAPPING1_DIO0_MASK ) | RFLR_DIOMAPPING1_DIO0_00 ); writeRegister( REG_LR_DETECTOPTIMIZE, readRegister( REG_LR_DETECTOPTIMIZE ) | 0x80 ); writeRegister( REG_LR_FIFORXBASEADDR, 0 ); writeRegister( REG_LR_FIFOADDRPTR, 0 ); } setOpMode( RF_OPMODE_RECEIVER ); writeRegister( REG_LNA, RF_LNA_GAIN_G1 | RF_LNA_BOOST_ON ); } void SX127x::startTransmitting() { mInterruptMutex.lock(); 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_00 ); } setOpMode( 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 1000ms mPerfMutex.lock(); uint64_t tick = TICKS; while ( mPerfHistory.size() > 0 and mPerfHistory.front() <= tick - ( 1000LLU / divider ) ) { mPerfValidBlocks = std::max( 0, mPerfValidBlocks - 1 ); mPerfHistory.pop_front(); } mPerfMutex.unlock(); mPerfBlocksPerSecond = mPerfValidBlocks * divider; mPerfMaxBlocksPerSecond = std::max( mPerfMaxBlocksPerSecond, mPerfBlocksPerSecond ); if ( mPerfBlocksPerSecond == 0 ) { mRxQuality = 0; } else if ( mPerfMaxBlocksPerSecond > 0 ) { mRxQuality = std::min( 100, 100 * ( mPerfBlocksPerSecond + 1 ) / mPerfMaxBlocksPerSecond ); } } int 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 ) { gDebug() << "timed out : " << (TICKS - started_waiting_at) << " > " << timeout; timedout = true; break; } PerfUpdate(); usleep( 100 ); } while ( mBlocking ); mRxQueueMutex.lock(); if ( mRxQueue.size() == 0 ) { mRxQueueMutex.unlock(); if ( timedout ) { return LINK_ERROR_TIMEOUT; } return 0; } std::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; } int SX127x::Write( const void* data, uint32_t len, bool ack, int32_t timeout ) { // printf( "SX127x::Write()\n" ); // while ( mSending ) { // usleep( 10 ); // } { std::unique_lock<std::mutex> lock(mReceivingMutex); if ( mReceiving ) { mReceivingCond.wait(lock, [this] { return mReceiving.load() == false; }); } } 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 ) ); // printf( "Sending ok\n" ); while ( mModem == LoRa and mSending ) { usleep( 1 ); } } if ( header->small_packet == 0 ) { header->packet_id++; } offset += plen; } return len; } int32_t 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 ) { Header* header = (Header*)buf; HeaderMini* small_header = (HeaderMini*)buf; uint8_t* data = buf + sizeof(Header); int final_size = 0; if ( buflen < sizeof(Header) && ( buflen < sizeof(HeaderMini) && header->small_packet ) ) { return -1; } uint32_t datalen = buflen - sizeof(Header); if ( header->small_packet ) { 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 " << (int)header->block_id << " already received"; return -1; } mRxBlock.block_id = small_header->block_id; mRxBlock.received = true; mPerfValidBlocks++; mPerfMutex.lock(); mPerfHistory.push_back( TICKS ); mPerfMutex.unlock(); memcpy( pRet, data, datalen ); return datalen; } if ( crc8( data, datalen ) != header->crc ) { std::cout << "Invalid CRC\n"; mPerfInvalidBlocks++; return -1; } if ( header->block_id == mRxBlock.block_id and mRxBlock.received ) { return -1; } 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() { uint64_t tick_ms = TICKS; mInterruptMutex.lock(); uint8_t opMode = getOpMode(); if ( opMode != RF_OPMODE_RECEIVER and opMode != RF_OPMODE_SYNTHESIZER_RX ) { // if ( opMode == RF_OPMODE_TRANSMITTER or opMode == RF_OPMODE_SYNTHESIZER_TX ) { // std::cout << "SX127x::Interrupt() SendTime : " << std::dec << TICKS - mSendTime << "\n"; if ( mSendingEnd ) { startReceiving(); } mSending = false; mInterruptMutex.unlock(); return; } // fDebug(); std::lock_guard<std::mutex> lock(mReceivingMutex); mReceiving = true; if ( mModem == FSK ) { mRSSI = -( readRegister( REG_RSSIVALUE ) >> 1 ); } else { mRSSI = -157 + readRegister( REG_LR_PKTRSSIVALUE ); // TBD : use REG_LR_RSSIVALUE ? } if( mDropBroken ) { bool crc_err = false; if ( mModem == LoRa ) { uint8_t irqFlags = readRegister( REG_LR_IRQFLAGS ); crc_err = ( ( irqFlags & RFLR_IRQFLAGS_PAYLOADCRCERROR_MASK ) == RFLR_IRQFLAGS_PAYLOADCRCERROR ); } else { uint8_t irqFlags = readRegister( REG_IRQFLAGS2 ); crc_err = ( ( irqFlags & RF_IRQFLAGS2_CRCOK ) != RF_IRQFLAGS2_CRCOK ); } if( crc_err ) { if ( mModem == LoRa ) { mReceiving = false; mInterruptMutex.unlock(); return; } // Clear Irqs writeRegister( REG_IRQFLAGS1, RF_IRQFLAGS1_RSSI | RF_IRQFLAGS1_PREAMBLEDETECT | RF_IRQFLAGS1_SYNCADDRESSMATCH ); writeRegister( REG_IRQFLAGS2, RF_IRQFLAGS2_FIFOOVERRUN ); // Continuous mode restart Rx chain // writeRegister( REG_RXCONFIG, readRegister( REG_RXCONFIG ) | RF_RXCONFIG_RESTARTRXWITHOUTPLLLOCK ); // Continuous mode restart Rx chain while ( writeRegister( REG_RXCONFIG, readRegister( REG_RXCONFIG ) | RF_RXCONFIG_RESTARTRXWITHOUTPLLLOCK ) == false and TICKS - tick_ms < 50 ) { usleep( 1 ); } mReceiving = false; 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( REG_LR_RXNBBYTES ); } else { len = readRegister( REG_FIFO ); } mSPI->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( std::make_pair( buf, ret ) ); mRxQueueMutex.unlock(); } else { delete[] buf; } /* uint8_t* buf = new uint8_t[len]; memcpy( buf, rx + 1, len ); mRxQueueMutex.lock(); mRxQueue.emplace_back( std::make_pair( buf, len ) ); mRxQueueMutex.unlock(); */ } if ( mModem == FSK ) { writeRegister( REG_RXCONFIG, readRegister( REG_RXCONFIG ) | RF_RXCONFIG_RESTARTRXWITHOUTPLLLOCK ); } mReceiving = false; mInterruptMutex.unlock(); } void SX127x::reset() { GPIO::Write( mResetPin, false ); usleep( 1000 * 50 ); GPIO::Write( mResetPin, true ); usleep( 1000 * 50 ); } bool SX127x::ping() { std::cout << "version : " << (int)readRegister(REG_VERSION) << "\n"; return readRegister(REG_VERSION) == SAMTEC_ID; } void SX127x::setModem( Modem modem ) { switch( modem ) { default: case FSK: setOpMode( RF_OPMODE_SLEEP ); writeRegister( REG_OPMODE, ( readRegister(REG_OPMODE) & RFLR_OPMODE_LONGRANGEMODE_MASK ) | RFLR_OPMODE_LONGRANGEMODE_OFF ); break; case LoRa: setOpMode( RF_OPMODE_SLEEP ); writeRegister( REG_OPMODE, ( readRegister(REG_OPMODE) & RFLR_OPMODE_LONGRANGEMODE_MASK ) | RFLR_OPMODE_LONGRANGEMODE_ON ); break; } writeRegister( REG_DIOMAPPING1, ( readRegister( REG_DIOMAPPING1 ) & RF_DIOMAPPING1_DIO0_MASK ) | RF_DIOMAPPING1_DIO0_00 ); writeRegister( REG_DIOMAPPING2, ( readRegister( REG_DIOMAPPING2 ) & RF_DIOMAPPING2_MAP_MASK ) | RF_DIOMAPPING2_MAP_PREAMBLEDETECT ); } uint32_t SX127x::getOpMode() { return readRegister(REG_OPMODE) & ~RF_OPMODE_MASK; } bool SX127x::setOpMode( uint32_t opMode ) { // std::cout << "setOpMode( " << opMode << " )\n"; writeRegister( REG_OPMODE, ( readRegister(REG_OPMODE) & RF_OPMODE_MASK ) | opMode ); uint64_t tick = TICKS; uint32_t retry_tick = TICKS; bool stalling = false; while ( getOpMode() != opMode and ( opMode == RF_OPMODE_RECEIVER or TICKS - tick < 250 ) ) { usleep( 1 ); if ( TICKS - tick > 100 ) { if ( not stalling ) { std::cout << "setOpMode(" << opMode << ") stalling !\n"; } stalling = true; } if ( TICKS - retry_tick > 100 ) { writeRegister( REG_OPMODE, ( readRegister(REG_OPMODE) & RF_OPMODE_MASK ) | opMode ); retry_tick = TICKS; } } if ( stalling ) { std::cout << "setOpMode(" << opMode << ") stalled (" << std::to_string(TICKS - tick) << "ms) !\n"; } if ( getOpMode() != opMode ) { std::cout << "ERROR : cannot set SX127x to opMode 0x" << std::hex << (int)opMode << " (0x" << (int)getOpMode() << ")" << std::dec << "\n"; return false; } else { // std::cout << "SX127x : opMode now set to 0x" << std::hex << (int)opMode << std::dec << "\n"; } return true; //time < SX_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 ) { std::cout << "Error while setting register " << GetRegName(address) << " to 0x" << std::hex << (int)value << " (0x" << (int)ret << ")" << std::dec << "\n"; 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]; } 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; }
33,725
C++
.cpp
960
32.502083
310
0.653016
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,819
Link.cpp
dridri_bcflight/libcontroller/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 <sys/time.h> #include <time.h> #include <string.h> #include "Link.h" Link::Link() : mConnected( false ) , mReadSpeed( 0 ) , mWriteSpeed( 0 ) , mReadSpeedCounter( 0 ) , mWriteSpeedCounter( 0 ) , mSpeedTick( 0 ) { } 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, 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 = 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 = htonl( v ); mData.insert( mData.end(), u.b, u.b + sizeof(uint32_t) ); } void Packet::WriteString( const std::string& str ) { Write( (const uint8_t*)str.c_str(), str.length()+1 ); } int32_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 = 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 = ntohl( ((uint32_t*)(mData.data() + mReadOffset))[0] ); 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; u.u = 0; 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; } std::string Packet::ReadString() { std::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; } int32_t Link::Read( Packet* p, int32_t timeout ) { uint8_t buffer[65536] = { 0 }; int32_t ret = Read( buffer, 65536, timeout ); if ( ret > 0 ) { p->Write( buffer, ret ); } return ret; } int32_t 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; } uint64_t Link::GetTicks() { struct timespec now; clock_gettime( CLOCK_MONOTONIC, &now ); return (uint64_t)now.tv_sec * 1000000ULL + (uint64_t)now.tv_nsec / 1000ULL; }
4,283
C++
.cpp
186
20.967742
92
0.648569
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,820
RawWifi.cpp
dridri_bcflight/libcontroller/links/RawWifi.cpp
#include "RawWifi.h" #include "../librawwifi++/RawWifi.h" #include "../librawwifi++/WifiInterfaceLinux.h" #include <Debug.h> RawWifi::RawWifi( const std::string& device, int16_t out_port, int16_t in_port, int read_timeout_ms ) : Link() { // Debug::setDebugLevel( Debug::Level::Trace ); try { mWifiInterface = new rawwifi::WifiInterfaceLinux( device, 11, 18, 20, 3 ); // mWifiInterface = new rawwifi::WifiInterfaceLinux( device, 11, 18, 0, 54 ); } catch ( std::exception& e ) { gError() << "Failed to create WifiInterface: " << e.what(); mWifiInterface = nullptr; } try { mRawWifi = new rawwifi::RawWifi( device, in_port, out_port, true, read_timeout_ms ); } catch ( std::exception& e ) { gError() << "Failed to create RawWifi: " << e.what(); mRawWifi = nullptr; } } RawWifi::~RawWifi() { } int RawWifi::Connect() { if ( not mRawWifi ) { return -1; } 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 0; } int32_t RawWifi::Frequency() { return 0; } int32_t RawWifi::RxQuality() { return 100; } int32_t RawWifi::RxLevel() { return -1; } int RawWifi::Read( void* buf, uint32_t len, int32_t timeout ) { bool valid = false; return mRawWifi->Receive( reinterpret_cast<uint8_t*>(buf), len, &valid, timeout ); } int RawWifi::Write( const void* buf, uint32_t len, bool ack, int32_t timeout ) { return mRawWifi->Send( reinterpret_cast<const uint8_t*>(buf), len, 1 ); } uint32_t RawWifi::fullReadSpeed() { return 0; }
1,639
C++
.cpp
73
20.60274
101
0.697795
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,821
Serial.cpp
dridri_bcflight/libcontroller/links/Serial.cpp
#include "Serial.h" Serial::Serial( const std::string& device, uint32_t baudrate ) { } Serial::~Serial() { } int Serial::setBlocking( bool blocking ) { (void)blocking; return 0; } void Serial::setRetriesCount( int retries ) { } int Serial::retriesCount() const { return 0; } int32_t Serial::Channel() { return 0; } int32_t Serial::Frequency() { return 0; } int32_t Serial::RxQuality() { return 0; } int32_t Serial::RxLevel() { return 0; } int Serial::Connect() { return 0; } int Serial::Read( void* buf, uint32_t len, int32_t timeout ) { return 0; } int Serial::Write( const void* buf, uint32_t len, bool ack, int32_t timeout ) { return 0; } int32_t Serial::WriteAck( const void* buf, uint32_t len ) { return 0; }
750
C++
.cpp
51
13
77
0.719585
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,822
nRF24L01.cpp
dridri_bcflight/libcontroller/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/>. **/ #include <cmath> #include <iostream> #include <string.h> #ifdef BOARD_rpi #include <pigpio.h> #include <GPIO.h> #endif #include "nRF24L01.h" #include <Thread.h> #define NRF_CONTINUE -2 nRF24L01::nRF24L01( const std::string& device, uint8_t cspin, uint8_t cepin, int8_t irqpin, uint8_t channel, uint32_t input_port, uint32_t output_port, bool drop_invalid_packets ) : Link() , mCSPin( cspin ) , mCEPin( cepin ) , mIRQPin( irqpin ) , mRadio( nullptr ) , mBlocking( true ) , mDropBroken( drop_invalid_packets ) , mChannel( std::max( 1u, std::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 ); #ifdef BOARD_rpi gpioInitialise(); mRadio->setGPIOFunctions( [](int pin, int value){ gpioWrite( pin, value ); }, [](int pin, int mode){ gpioSetMode( pin, mode ); } ); if ( mIRQPin >= 0 ) { GPIO::SetupInterrupt( mIRQPin, GPIO::Falling, [this](){ this->Interrupt(); } ); } #endif 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 ( Thread::GetTick() - mPerfTicks >= 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 = Thread::GetTick(); mPerfLastRxBlock = mRxBlock.block_id; mPerfValidBlocks = 0; mPerfInvalidBlocks = 0; } mPerfMutex.unlock(); } int nRF24L01::Read( void* pRet, uint32_t len, int32_t timeout ) { bool timedout = false; uint64_t started_waiting_at = Thread::GetTick(); 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 Thread::GetTick() - started_waiting_at > (uint32_t)timeout ) { timedout = true; break; } PerfUpdate(); usleep( 100 ); } while ( mBlocking ); PerfUpdate(); mRxQueueMutex.lock(); if ( mRxQueue.size() == 0 ) { mRxQueueMutex.unlock(); if ( timedout ) { // std::cout << "WARNING : Read timeout\n"; return LINK_ERROR_TIMEOUT; } return 0; } std::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; } int nRF24L01::Write( const void* data, uint32_t len, bool ack, int32_t timeout ) { return Send( data, len, ack ); } 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)std::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 NRF_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 ) { mPerfInvalidBlocks++; return NRF_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 ) { mRxQueueMutex.lock(); mRxQueue.emplace_back( std::make_pair( buf, ret ) ); mRxQueueMutex.unlock(); } else { delete buf; } } }
8,162
C++
.cpp
301
24.66113
179
0.678073
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,823
Socket.cpp
dridri_bcflight/libcontroller/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/>. **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <fcntl.h> #ifdef WIN32 #include <winsock2.h> #define socklen_t int #define DATATYPE char* #ifndef MSG_NOSIGNAL # define MSG_NOSIGNAL 0 #endif #else #define DATATYPE void* #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <unistd.h> /* close */ #include <netdb.h> /* gethostbyname */ #include <iwlib.h> #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; #endif #include <iostream> #include "Socket.h" #ifndef IPPROTO_UDPLITE #define IPPROTO_UDPLITE 136 #endif #define UDPLITE_SEND_CSCOV 10 /* sender partial coverage (as sent) */ #define UDPLITE_RECV_CSCOV 11 /* receiver partial coverage (threshold ) */ Socket::Socket( const std::string& host, uint16_t port, PortType type ) : mHost( host ) , mPort( port ) , mPortType( type ) , mSocket( -1 ) , mChannel( 0 ) { 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 ); } Socket::~Socket() { if ( mConnected and mSocket >= 0 ) { shutdown( mSocket, 2 ); closesocket( mSocket ); } } int32_t Socket::Channel() { return mChannel; } int32_t Socket::RxQuality() { iwstats stats; 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 ); return ret; } int32_t Socket::RxLevel() { iwstats stats; int32_t ret = 0; 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 ); return ret; } int Socket::Connect() { 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 = inet_addr( mHost.c_str() ); 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 ( mPortType == UDPLite ) { uint16_t checksum_coverage = 8; setsockopt( mSocket, IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, (DATATYPE)&checksum_coverage, sizeof(checksum_coverage) ); setsockopt( mSocket, IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, (DATATYPE)&checksum_coverage, sizeof(checksum_coverage) ); } if ( connect( mSocket, (SOCKADDR*)&mSin, sizeof(mSin) ) < 0 ) { std::cout << "Socket ( " << mPort << " ) connect error : " << strerror(errno) << "\n"; close( mSocket ); mSocket = -1; mConnected = false; return -1; } } mConnected = true; return 0; } int Socket::setBlocking( bool blocking ) { #ifdef WIN32 unsigned long nonblock = !blocking; return ( ioctlsocket( mSocket, FIONBIO, &nonblock ) == 0 ); #else int flags = fcntl( mSocket, F_GETFL, 0 ); flags = blocking ? ( flags & ~O_NONBLOCK) : ( flags | O_NONBLOCK ); return ( fcntl( mSocket, F_SETFL, flags ) == 0 ); #endif } int Socket::retriesCount() const { // TODO return 1; } void Socket::setRetriesCount( int retries ) { if ( mPortType == UDP or mPortType == UDPLite ) { // TODO : set retries count } } int Socket::Read( void* buf, uint32_t len, int timeout ) { if ( !mConnected ) { return -1; } int ret = 0; memset( buf, 0, len ); // timeout = 500; 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 ) { socklen_t fromsize = sizeof( mSin ); ret = recvfrom( mSocket, (DATATYPE)buf, len, 0, (SOCKADDR *)&mSin, &fromsize ); if ( ret <= 0 and errno != EAGAIN) { std::cout << "UDP disconnected ( " << ret << " : " << strerror( errno ) << " )\n"; mConnected = false; return -1; } // return -1; } else { ret = recv( mSocket, (DATATYPE)buf, len, MSG_NOSIGNAL ); // if ( ( ret <= 0 and errno != EAGAIN ) or ( errno == EAGAIN and timeout > 0 ) ) { if ( ret <= 0 ) { std::cout << "TCP disconnected ( " << strerror( errno ) << " )\n"; mConnected = false; mSocket = -1; return -1; } } if ( ret > 0 ) { mReadSpeedCounter += ret; } if ( GetTicks() - mSpeedTick >= 1000 * 1000 ) { mReadSpeed = mReadSpeedCounter; mWriteSpeed = mWriteSpeedCounter; mReadSpeedCounter = 0; mWriteSpeedCounter = 0; mSpeedTick = GetTicks(); } return ret; } int 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 ) { uint32_t sendsize = sizeof( mSin ); ret = sendto( mSocket, (DATATYPE)buf, len, 0, (SOCKADDR *)&mSin, sendsize ); } else { ret = send( mSocket, (DATATYPE)buf, len, 0 ); } if ( ret <= 0 and ( errno == EAGAIN or errno == -EAGAIN ) ) { return 0; } if ( ret < 0 and mPortType != UDP and mPortType != UDPLite ) { std::cout << "TCP disconnected\n"; mConnected = false; mSocket = -1; return -1; } if ( ret > 0 ) { mWriteSpeedCounter += ret; } if ( GetTicks() - mSpeedTick >= 1000 * 1000 ) { mReadSpeed = mReadSpeedCounter; mWriteSpeed = mWriteSpeedCounter; mReadSpeedCounter = 0; mWriteSpeedCounter = 0; mSpeedTick = GetTicks(); } return ret; }
7,056
C++
.cpp
247
26.303644
119
0.666765
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,825
spi.cpp
dridri_bcflight/libcontroller/links/RF24/utility/spi.cpp
#include "spi.h" #include <sys/fcntl.h> #include <sys/ioctl.h> #include <linux/i2c-dev.h> #include <pthread.h> #include <string.h> #include <errno.h> #include <iostream> static std::string mSPIDevice = ""; static pthread_mutex_t spiMutex = PTHREAD_MUTEX_INITIALIZER; static int mFD = -1; static int mBitsPerWord = 8; static struct spi_ioc_transfer mXFer[10]; nRF24::SPI::SPI() { } nRF24::SPI::~SPI() { } void nRF24::SPI::begin( const std::string& device ) { mSPIDevice = device; } void nRF24::SPI::end() { } void nRF24::SPI::beginTransaction( SPISettings settings ) { if ( mFD < 0 ) { 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; } mFD = open( mSPIDevice.c_str(), O_RDWR ); std::cout << "SPI fd (" << mSPIDevice << ") : " << mFD << "\n"; uint8_t mode, lsb=0; mode = SPI_MODE_0; 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 ) < 0 ) { std::cout << "can't set max speed hz\n"; } if ( ioctl( mFD, SPI_IOC_RD_MAX_SPEED_HZ, &speed ) < 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 " << mSPIDevice.c_str() << ":" << mFD <<": spi mode " << (int)mode << ", " << mBitsPerWord << "bits " << ( lsb ? "(lsb first) " : "" ) << "per word, " << speed << " 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; mXFer[i].bits_per_word = 8; } } pthread_mutex_lock( &spiMutex ); } void nRF24::SPI::endTransaction() { pthread_mutex_unlock( &spiMutex ); } 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; transfernb( (char*)&_data, (char*)&data, 1 ); return data; } void nRF24::SPI::transfernb( char* tbuf, char* rbuf, uint32_t len ) { mXFer[0].tx_buf = (uintptr_t)tbuf; mXFer[0].len = len; mXFer[0].rx_buf = (uintptr_t)rbuf; int ret = ioctl( mFD, SPI_IOC_MESSAGE(1), mXFer ); if ( ret <= 0 ) { printf( "transfernb failed : %d (%s)\n", errno, strerror(errno) ); } else { // printf( "transfernb(%p, %p, %d) ok : %d\n", tbuf, rbuf, len, ret ); } } void nRF24::SPI::transfern( char* buf, uint32_t len ) { char* rbuf = new char[len]; transfernb( buf, rbuf, len ); memcpy( buf, rbuf, len ); delete rbuf; }
3,998
C++
.cpp
161
21.863354
195
0.624606
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,826
RendererHUD.cpp
dridri_bcflight/libhud/RendererHUD.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/>. **/ #define GL_GLEXT_PROTOTYPES #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <string.h> #include <png.h> #include <iostream> #include <fstream> #include <sstream> #include <cmath> #include <Thread.h> #include "RendererHUD.h" #include "font32.h" static const char hud_flat_vertices_shader[] = R"( #version 100 precision mediump float; #define in attribute #define out varying #define ge_Position gl_Position in vec2 ge_VertexTexcoord; in vec2 ge_VertexPosition; uniform mat4 ge_ProjectionMatrix; uniform vec2 offset; uniform float scale; out vec2 ge_TextureCoord; void main() { ge_TextureCoord = ge_VertexTexcoord.xy; vec2 pos = offset + ge_VertexPosition.xy * scale; ge_Position = ge_ProjectionMatrix * vec4(pos, 0.0, 1.0); ge_Position.y = ge_Position.y * ( 720.0 / ( 1280.0 / 2.0 ) ); })" ; static const char hud_flat_fragment_shader[] = R"( #version 100 precision mediump float; #define in varying #define ge_FragColor gl_FragColor uniform sampler2D ge_Texture0; uniform float exposure_value; uniform float gamma_compensation; uniform vec4 color; in vec2 ge_TextureCoord; void main() { ge_FragColor = color * texture2D( ge_Texture0, ge_TextureCoord.xy ); return; // uniform float kernel[9] = float[]( 0, -1, 0, -1, 5, -1, 0, -1, 0 ); ge_FragColor = vec4(0.0); ge_FragColor += 5.0 * texture2D( ge_Texture0, ge_TextureCoord.xy ); ge_FragColor += -1.0 * texture2D( ge_Texture0, ge_TextureCoord.xy + vec2(-0.000976, 0.0 ) ); ge_FragColor += -1.0 * texture2D( ge_Texture0, ge_TextureCoord.xy + vec2( 0.001736, 0.0 ) ); ge_FragColor += -1.0 * texture2D( ge_Texture0, ge_TextureCoord.xy + vec2( 0.0,-0.000976 ) ); ge_FragColor += -1.0 * texture2D( ge_Texture0, ge_TextureCoord.xy + vec2( 0.0, 0.001736 ) ); // ge_FragColor += texture2D( ge_Texture0, ge_TextureCoord.xy ); ge_FragColor *= color; // ge_FragColor.a = 1.0; ge_FragColor.rgb = vec3(1.0) - exp( -ge_FragColor.rgb * vec3(exposure_value) ); ge_FragColor.rgb = pow( ge_FragColor.rgb, vec3( 1.0 / gamma_compensation ) ); })" ; static const char hud_text_vertices_shader[] = R"( #version 100 precision mediump float; #define in attribute #define out varying #define ge_Position gl_Position in vec2 ge_VertexTexcoord; in vec2 ge_VertexPosition; uniform mat4 ge_ProjectionMatrix; uniform vec2 offset; uniform float scale; uniform float distort; out vec2 ge_TextureCoord; vec2 VR_Distort( vec2 coords ) { vec2 ret = coords; vec2 ofs = vec2(1280.0/4.0, 720.0/2.0); if ( coords.x >= 1280.0/2.0 ) { ofs.x = 3.0 * 1280.0/4.0; } vec2 offset = coords - ofs; float r2 = dot( offset.xy, offset.xy ); float r = sqrt(r2); float k1 = 1.95304; k1 = k1 / ((1280.0 / 4.0)*(1280.0 / 4.0) * 16.0); ret = ofs + ( 1.0 - k1 * r * r ) * offset; return ret; } void main() { ge_TextureCoord = ge_VertexTexcoord.xy; vec2 pos = offset + ge_VertexPosition.xy * scale; if ( distort != 0.0 ) { pos = VR_Distort( pos ); } ge_Position = ge_ProjectionMatrix * vec4(pos, 0.0, 1.0); // ge_Position.y = ge_Position.y * ( 720.0 / ( 1280.0 / 2.0 ) ); })" ; static const char hud_text_fragment_shader[] = R"( #version 100 precision mediump float; #define in varying #define ge_FragColor gl_FragColor uniform sampler2D ge_Texture0; uniform vec4 color; in vec2 ge_TextureCoord; void main() { ge_FragColor = color * texture2D( ge_Texture0, ge_TextureCoord.xy ); })" ; Vector2f RendererHUD::VR_Distort( const Vector2f& coords ) { Vector2f ret = coords; Vector2f ofs = Vector2f( 1280.0 / 4.0, 720.0 / 2.0 ); if ( coords.x >= 1280.0 / 2.0 ) { ofs.x = 3.0 * 1280.0 / 4.0; } Vector2f offset = coords - ofs; float r2 = offset.x * offset.x + offset.y * offset.y; float r = std::sqrt( r2 ); float k1 = 1.95304; k1 = k1 / ( ( 1280.0 / 4.0 ) * ( 1280.0 / 4.0 ) * 16.0 ); ret = ofs + ( mBarrelCorrection ? ( 1.0f - k1 * r * r ) : 1.0f ) * offset; return ret; } void RendererHUD::DrawArrays( RendererHUD::Shader& shader, int mode, uint32_t ofs, uint32_t count, const Vector2f& offset ) { if ( mStereo ) { glViewport( mDisplayWidth / 2, 0, mDisplayWidth / 2, mDisplayHeight ); glUniform2f( shader.mOffsetID, 1280.0f * -m3DStrength + offset.x, offset.y ); glDrawArrays( mode, ofs, count ); glViewport( 0, 0, mDisplayWidth / 2, mDisplayHeight ); glUniform2f( shader.mOffsetID, 1280.0f * +m3DStrength + offset.x, offset.y ); glDrawArrays( mode, ofs, count ); } else { glViewport( 0, 0, mDisplayWidth, mDisplayHeight ); glUniform2f( shader.mOffsetID, offset.x, offset.y ); glDrawArrays( mode, ofs, count ); } } RendererHUD::RendererHUD( int width, int height, float ratio, uint32_t fontsize, Vector4i render_region, bool barrel_correction ) : mDisplayWidth( width ) , mDisplayHeight( height ) , mWidth( 1280 ) , mHeight( 720 ) , mBorderTop( render_region.x ) , mBorderBottom( mHeight - render_region.y ) , mBorderLeft( render_region.z ) , mBorderRight( mWidth - render_region.w ) , mStereo( true ) , mNightMode( false ) , mBarrelCorrection( barrel_correction ) , m3DStrength( 0.004f ) , mBlinkingViews( false ) , mHUDTick( 0 ) , mMatrixProjection( new Matrix() ) , mQuadVBO( 0 ) , mFlatShader( { 0 } ) , mFontTexture( nullptr ) , mFontSize( fontsize ) , mFontHeight( fontsize * 0.65f ) , mTextShader{ 0 } , mWhiteBalance( "auto" ) , mExposureMode( "auto" ) , mWhiteBalanceTick( 0.0f ) , mLastPhotoID( 0 ) , mPhotoTick( 0.0f ) { mWidth *= ratio; mBorderLeft *= ratio; mBorderRight *= ratio; mMatrixProjection->Orthogonal( 0.0, 1280 * ratio, 720, 0.0, -2049.0, 2049.0 ); glDisable( GL_DEPTH_TEST ); glActiveTexture( GL_TEXTURE0 ); glEnable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, 0 ); glLineWidth( 2.0f ); LoadVertexShader( &mFlatShader, hud_flat_vertices_shader, sizeof(hud_flat_vertices_shader) + 1 ); LoadFragmentShader( &mFlatShader, hud_flat_fragment_shader, sizeof(hud_flat_fragment_shader) + 1 ); createPipeline( &mFlatShader ); glUseProgram( mFlatShader.mShader ); glEnableVertexAttribArray( mFlatShader.mVertexTexcoordID ); glEnableVertexAttribArray( mFlatShader.mVertexPositionID ); mExposureID = glGetUniformLocation( mFlatShader.mShader, "exposure_value" ); mGammaID = glGetUniformLocation( mFlatShader.mShader, "gamma_compensation" ); std::cout << "mExposureID : " << mExposureID << "\n"; std::cout << "mGammaID : " << mGammaID << "\n"; std::cout << "mOffsetID : " << mFlatShader.mOffsetID << "\n"; glUseProgram( 0 ); LoadVertexShader( &mTextShader, hud_text_vertices_shader, sizeof(hud_text_vertices_shader) + 1 ); LoadFragmentShader( &mTextShader, hud_text_fragment_shader, sizeof(hud_text_fragment_shader) + 1 ); createPipeline( &mTextShader ); glUseProgram( mTextShader.mShader ); glEnableVertexAttribArray( mTextShader.mVertexTexcoordID ); glEnableVertexAttribArray( mTextShader.mVertexPositionID ); glUseProgram( 0 ); glGenBuffers( 1, &mQuadVBO ); glBindBuffer( GL_ARRAY_BUFFER, mQuadVBO ); glBufferData( GL_ARRAY_BUFFER, sizeof(FastVertex) * 6, nullptr, GL_STATIC_DRAW ); { std::cout << "mFontSize : " << mFontSize << "\n"; mFontTexture = LoadTexture( font32, sizeof(font32) ); const float rx = 1.0f / (float)mFontTexture->width; const float ry = 1.0f / (float)mFontTexture->height; FastVertex charactersBuffer[6 * 256]; memset( charactersBuffer, 0, sizeof( charactersBuffer ) ); for ( uint32_t i = 0; i < 256; i++ ) { uint8_t c = i; float sx = (float)( i % 16 ) * ( mFontTexture->width / 16 ) * rx; float sy = (float)( i / 16 ) * ( mFontTexture->height / 16 ) * ry; float width = CharacterWidth( mFontTexture, i ); float height = CharacterHeight( mFontTexture, i ); float texMaxX = width * rx; float texMaxY = height * ry; width *= mFontSize / 32.0f; height *= mFontSize / 32.0f; float fy = (float)0.0f;// - CharacterYOffset( mFontTexture, i ); mTextAdv[c] = (int)width + 1; charactersBuffer[i*6 + 0].u = sx; charactersBuffer[i*6 + 0].v = sy; charactersBuffer[i*6 + 0].x = 0.0f; charactersBuffer[i*6 + 0].y = fy; charactersBuffer[i*6 + 1].u = sx+texMaxX; charactersBuffer[i*6 + 1].v = sy+texMaxY; charactersBuffer[i*6 + 1].x = 0.0f+width; charactersBuffer[i*6 + 1].y = fy+height; charactersBuffer[i*6 + 2].u = sx+texMaxX; charactersBuffer[i*6 + 2].v = sy; charactersBuffer[i*6 + 2].x = 0.0f+width; charactersBuffer[i*6 + 2].y = fy; charactersBuffer[i*6 + 3].u = sx; charactersBuffer[i*6 + 3].v = sy; charactersBuffer[i*6 + 3].x = 0.0f; charactersBuffer[i*6 + 3].y = fy; charactersBuffer[i*6 + 4].u = sx; charactersBuffer[i*6 + 4].v = sy+texMaxY; charactersBuffer[i*6 + 4].x = 0.0f; charactersBuffer[i*6 + 4].y = fy+height; charactersBuffer[i*6 + 5].u = sx+texMaxX; charactersBuffer[i*6 + 5].v = sy+texMaxY; charactersBuffer[i*6 + 5].x = 0.0f+width; charactersBuffer[i*6 + 5].y = fy+height; } mTextAdv[' '] = mFontSize * 0.35f; glGenBuffers( 1, &mTextVBO ); glBindBuffer( GL_ARRAY_BUFFER, mTextVBO ); glBufferData( GL_ARRAY_BUFFER, sizeof(FastVertex) * 6 * 256, charactersBuffer, GL_STATIC_DRAW ); } } RendererHUD::~RendererHUD() { } void RendererHUD::PreRender() { if ( Thread::GetSeconds() - mHUDTick >= 1.0f ) { mBlinkingViews = !mBlinkingViews; mHUDTick = Thread::GetSeconds(); } glUseProgram( mFlatShader.mShader ); glUniform1f( mFlatShader.mDistorID, (float)mBarrelCorrection ); glUseProgram( mTextShader.mShader ); glUniform1f( mTextShader.mDistorID, (float)mBarrelCorrection ); glUseProgram( 0 ); } void RendererHUD::RenderImage( int x, int y, int width, int height, uintptr_t img ) { Texture* tex = reinterpret_cast<Texture*>( img ); RenderQuadTexture( tex->glID, x, y, width, height ); } void RendererHUD::RenderQuadTexture( GLuint textureID, int x, int y, int width, int height, bool hmirror, bool vmirror, const Vector4f& color ) { glUseProgram( mFlatShader.mShader ); glUniform4f( mFlatShader.mColorID, color.x, color.y, color.z, color.w ); glUniform1f( mFlatShader.mScaleID, 1.0f ); glBindTexture( GL_TEXTURE_2D, textureID ); glActiveTexture( GL_TEXTURE0 ); glEnable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, textureID ); if ( mNightMode ) { glUniform1f( mExposureID, 2.5f ); glUniform1f( mGammaID, 1.5f ); } else { glUniform1f( mExposureID, 1.0f ); glUniform1f( mGammaID, 1.0f ); } glBindBuffer( GL_ARRAY_BUFFER, mQuadVBO ); glVertexAttribPointer( mFlatShader.mVertexTexcoordID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertex ), (void*)( 0 ) ); glVertexAttribPointer( mFlatShader.mVertexPositionID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertex ), (void*)( sizeof( float ) * 2 ) ); float u = ( hmirror ? 1.0f : 0.0f ); float v = ( vmirror ? 1.0f : 0.0f ); float uend = ( hmirror ? 0.0f : 1.0f ); float vend = ( vmirror ? 0.0f : 1.0f ); FastVertex vertices[6]; vertices[0].u = u; vertices[0].v = v; vertices[0].x = x; vertices[0].y = y; vertices[1].u = uend; vertices[1].v = vend; vertices[1].x = x+width; vertices[1].y = y+height; vertices[2].u = uend; vertices[2].v = v; vertices[2].x = x+width; vertices[2].y = y; vertices[3].u = u; vertices[3].v = v; vertices[3].x = x; vertices[3].y = y; vertices[4].u = u; vertices[4].v = vend; vertices[4].x = x; vertices[4].y = y+height; vertices[5].u = uend; vertices[5].v = vend; vertices[5].x = x+width; vertices[5].y = y+height; glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(FastVertex) * 6, vertices ); DrawArrays( mFlatShader, GL_TRIANGLES, 0, 6 ); } void RendererHUD::RenderText( int x, int y, const std::string& text, uint32_t color, float size, TextAlignment halign, TextAlignment valign ) { RenderText( x, y, text, Vector4f( (float)( color & 0xFF ) / 256.0f, (float)( ( color >> 8 ) & 0xFF ) / 256.0f, (float)( ( color >> 16 ) & 0xFF ) / 256.0f, 1.0f ), size, halign, valign ); } void RendererHUD::RenderText( int x, int y, const std::string& text, const Vector4f& _color, float size, TextAlignment halign, TextAlignment valign ) { // y += mFontSize * size * 0.2f; glUseProgram( mTextShader.mShader ); Vector4f color = _color; if ( mNightMode ) { color.x *= 0.5f; color.y = std::min( 1.0f, color.y * 1.0f ); color.z *= 0.5f; } glUniform4f( mTextShader.mColorID, color.x, color.y, color.z, color.w ); glUniform1f( mTextShader.mScaleID, size ); glBindTexture( GL_TEXTURE_2D, mFontTexture->glID ); glActiveTexture( GL_TEXTURE0 ); glEnable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, mFontTexture->glID ); glBindBuffer( GL_ARRAY_BUFFER, mTextVBO ); glVertexAttribPointer( mTextShader.mVertexTexcoordID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertex ), (void*)( 0 ) ); glVertexAttribPointer( mTextShader.mVertexPositionID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertex ), (void*)( sizeof( float ) * 2 ) ); if ( halign == TextAlignment::CENTER ) { int w = 0; for ( uint32_t i = 0; i < text.length(); i++ ) { w += mTextAdv[ (uint8_t)( (int)text.data()[i] ) ] * size; } x -= w / 2.0f; } else if ( halign == TextAlignment::END ) { int w = 0; for ( uint32_t i = 0; i < text.length(); i++ ) { w += mTextAdv[ (uint8_t)( (int)text.data()[i] ) ] * size; } x -= w; } if ( valign == TextAlignment::CENTER ) { int h = mFontHeight * size; for ( uint32_t i = 0; i < text.length(); i++ ) { if ( text.data()[i] == '\n' ) { h += mFontHeight * size; } } y -= h / 2.0f; } else if ( valign == TextAlignment::END ) { int h = mFontHeight * size; for ( uint32_t i = 0; i < text.length(); i++ ) { if ( text.data()[i] == '\n' ) { h += mFontHeight * size; } } y -= h; } for ( uint32_t i = 0; i < text.length(); i++ ) { uint8_t c = (uint8_t)( (int)text.data()[i] ); // if ( c > 0 and c < 128 ) { DrawArrays( mTextShader, GL_TRIANGLES, c * 6, 6, Vector2f( x, y ) ); // } x += mTextAdv[ c ] * size; } } void RendererHUD::createPipeline( RendererHUD::Shader* target ) { if ( target->mShader ) { glDeleteProgram( target->mShader ); } target->mShader = glCreateProgram(); glAttachShader( target->mShader, target->mVertexShader ); glAttachShader( target->mShader, target->mFragmentShader ); glLinkProgram( target->mShader ); target->mVertexTexcoordID = glGetAttribLocation( target->mShader, "ge_VertexTexcoord" ); target->mVertexColorID = glGetAttribLocation( target->mShader, "ge_VertexColor" ); target->mVertexPositionID = glGetAttribLocation( target->mShader, "ge_VertexPosition" ); char log[4096] = ""; int logsize = 4096; glGetProgramInfoLog( target->mShader, logsize, &logsize, log ); std::cout << "program compile : " << log << "\n"; glUseProgram( target->mShader ); target->mMatrixProjectionID = glGetUniformLocation( target->mShader, "ge_ProjectionMatrix" ); target->mDistorID = glGetUniformLocation( target->mShader, "distort" ); target->mColorID = glGetUniformLocation( target->mShader, "color" ); target->mOffsetID = glGetUniformLocation( target->mShader, "offset" ); target->mScaleID = glGetUniformLocation( target->mShader, "scale" ); glUniformMatrix4fv( target->mMatrixProjectionID, 1, GL_FALSE, mMatrixProjection->constData() ); } int RendererHUD::LoadVertexShader( Shader* target, const void* data, size_t size ) { if ( target->mVertexShader ) { glDeleteShader( target->mVertexShader ); } target->mVertexShader = glCreateShader( GL_VERTEX_SHADER ); glShaderSource( target->mVertexShader, 1, (const char**)&data, NULL ); glCompileShader( target->mVertexShader ); char log[4096] = ""; int logsize = 4096; glGetShaderInfoLog( target->mVertexShader, logsize, &logsize, log ); std::cout << "vertex compile : " << log << "\n"; return 0; } int RendererHUD::LoadFragmentShader( Shader* target, const void* data, size_t size ) { if ( target->mFragmentShader ) { glDeleteShader( target->mFragmentShader ); } target->mFragmentShader = glCreateShader( GL_FRAGMENT_SHADER ); glShaderSource( target->mFragmentShader, 1, (const char**)&data, NULL ); glCompileShader( target->mFragmentShader ); char log[4096] = ""; int logsize = 4096; glGetShaderInfoLog( target->mFragmentShader, logsize, &logsize, log ); std::cout << "fragment compile : " << log << "\n"; return 0; } void RendererHUD::FontMeasureString( const std::string& str, int* width, int* height ) { int i = 0; int mx = 0; int x = 0; int y = 0; for ( i = 0; str[i]; i++ ) { if ( str[i] == '\n' ) { if ( x > mx ) { mx = x; } x = 0; y += mFontSize; continue; } x += mTextAdv[ (uint8_t)str[i] ]; } if ( x > mx ) { mx = x; } if ( mx == 0 ) { mx = x; } *width = mx; *height = y + mFontSize + ( mFontSize * 0.4 ); } int32_t RendererHUD::CharacterWidth( Texture* tex, unsigned char c ) { uint32_t xbase = ( tex->width / 16 ) * ( c % 16 ); uint32_t ybase = ( tex->height / 16 ) * ( c / 16 ); uint32_t xend = xbase + tex->width / 16; uint32_t yend = ybase + tex->height / 16; uint32_t xfirst = 0; uint32_t xlast = 0; for ( uint32_t y = ybase; y < yend; y++ ) { for ( uint32_t x = xbase; x < xend; x++ ) { if ( tex->data[x + y*tex->width] != 0x00000000 ) { if ( xfirst == 0 or x < xfirst ) { xfirst = x; } if ( x + 1 < xend and tex->data[x+1 + y*tex->width] == 0x00000000 ){ if ( xfirst != 0 and x > xlast ) { xlast = x; } } } } } if ( xfirst > 0 and xlast > 0 ) { return xlast - xfirst + 1; } return tex->width / 16; } int32_t RendererHUD::CharacterHeight( Texture* tex, unsigned char c ) { // TODO : calculate fine value return tex->height / 16; } int32_t RendererHUD::CharacterYOffset( Texture* tex, unsigned char c ) { uint32_t xbase = ( tex->width / 16 ) * ( c % 16 ); uint32_t ybase = ( tex->height / 16 ) * ( c / 16 ); uint32_t xend = xbase + tex->width / 16; uint32_t yend = ybase + tex->height / 16; for ( uint32_t y = ybase; y < yend; y++ ) { for ( uint32_t x = xbase; x < xend; x++ ) { if ( tex->data[x + y*tex->width] != 0x00000000 ) { return y - ybase; } } } return 0; } std::istringstream data(std::string(font32)); RendererHUD::Texture* RendererHUD::LoadTexture( const std::string& filename ) { std::string type = "none"; const char* dot = strrchr( filename.c_str(), '.' ); if ( dot ) { if ( strcmp( dot, ".png" ) == 0 or strcmp( dot, ".PNG" ) == 0 ) { type = "png"; } } if ( type == "none" ) { return nullptr; } Texture* tex = new Texture; memset( tex, 0, sizeof(Texture) ); if ( type == "png" ) { std::ifstream file( filename, std::ios_base::in | std::ios_base::binary ); LoadPNG( tex, file ); file.close(); } glActiveTexture( GL_TEXTURE0 ); glGenTextures( 1, &tex->glID ); glEnable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, tex->glID ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, tex->width, tex->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex->data ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); return tex; } RendererHUD::Texture* RendererHUD::LoadTexture( const uint8_t* data, uint32_t datalen ) { Texture* tex = new Texture; memset( tex, 0, sizeof(Texture) ); struct membuf : std::streambuf { membuf( const uint8_t* begin, const uint8_t* end ) { this->setg( (char*)begin, (char*)begin, (char*)end ); } }; membuf sbuf( data, data+datalen ); std::istream in_stream( &sbuf ); LoadPNG( tex, in_stream ); glActiveTexture( GL_TEXTURE0 ); glGenTextures( 1, &tex->glID ); glEnable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, tex->glID ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, tex->width, tex->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex->data ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); return tex; } static void png_read_from_ifstream( png_structp png_ptr, png_bytep data, png_size_t length ) { std::istream* file = ( std::istream* )png_get_io_ptr( png_ptr ); file->read( (char*)data, length ); } void RendererHUD::LoadPNG( Texture* tex, std::istream& file ) { png_structp png_ptr; png_infop info_ptr; png_uint_32 width, height, x, y; int bit_depth, color_type, interlace_type; uint32_t* line; // std::ifstream file( filename, std::ios_base::in | std::ios_base::binary ); /* #ifdef png_check_sig uint8_t magic[8] = { 0x0 }; file.read( (char*)magic, 8 ); file.seekg( 0, file.beg ); if ( !png_check_sig( magic, 8 ) ) { return; } #endif */ std::cout << "libpng version : " << PNG_LIBPNG_VER_STRING << "\n"; png_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr ); if ( png_ptr == nullptr ) { std::cout << "PNG Error: png_create_read_struct returned null\n"; return; } png_set_error_fn( png_ptr, nullptr, nullptr, nullptr ); png_set_read_fn( png_ptr, ( png_voidp* )&file, png_read_from_ifstream ); if ( ( info_ptr = png_create_info_struct( png_ptr ) ) == nullptr ) { png_destroy_read_struct( &png_ptr, nullptr, nullptr ); return; } // png_read_png( png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, nullptr ); png_read_info( png_ptr, info_ptr ); png_get_IHDR( png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, nullptr, nullptr ); tex->width = width; tex->height = height; tex->data = ( uint32_t* ) malloc( tex->width * tex->height * sizeof( uint32_t ) ); if ( !tex->data ) { free( tex->data ); png_destroy_read_struct( &png_ptr, nullptr, nullptr ); return; } png_set_strip_16( png_ptr ); png_set_packing( png_ptr ); if ( color_type == PNG_COLOR_TYPE_PALETTE ) png_set_palette_to_rgb( png_ptr ); if ( png_get_valid( png_ptr, info_ptr, PNG_INFO_tRNS ) ) png_set_tRNS_to_alpha( png_ptr ); png_set_filler( png_ptr, 0xff, PNG_FILLER_AFTER ); line = ( uint32_t* ) malloc( width * sizeof( uint32_t ) ); if ( !line ) { free( tex->data ); png_destroy_read_struct( &png_ptr, nullptr, nullptr ); return; } for ( y = 0; y < height; y++ ) { png_read_row( png_ptr, (uint8_t*)line, nullptr ); for ( x = 0; x < width; x++ ) { uint32_t color = line[x]; tex->data[ x + y * tex->width] = color; } } free( line ); png_read_end( png_ptr, info_ptr ); png_destroy_read_struct( &png_ptr, &info_ptr, nullptr ); }
23,152
C++
.cpp
647
33.313756
187
0.675143
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,827
RendererHUDNeo.cpp
dridri_bcflight/libhud/RendererHUDNeo.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/>. **/ /* TODO Add : * picture taken indicator * altitude [altitude hold] */ #include <cmath> #include <sstream> #include "RendererHUDNeo.h" #include "Controller.h" #define GL_GLEXT_PROTOTYPES #include <string.h> #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> static const char hud_vertices_shader[] = R"( #version 100 precision mediump float; #define in attribute #define out varying #define ge_Position gl_Position in vec2 ge_VertexTexcoord; in vec2 ge_VertexPosition; uniform mat4 ge_ProjectionMatrix; uniform vec2 offset; void main() { vec2 pos = offset + ge_VertexPosition.xy; ge_Position = ge_ProjectionMatrix * vec4(pos, 0.0, 1.0); // ge_Position.y = ge_Position.y * ( 720.0 / ( 1280.0 / 2.0 ) ); })" ; static const char hud_fragment_shader[] = R"( #version 100 precision mediump float; #define in varying #define ge_FragColor gl_FragColor uniform vec4 color; void main() { ge_FragColor = color; })" ; static const char hud_color_vertices_shader[] = R"( #version 100 precision mediump float; #define in attribute #define out varying #define ge_Position gl_Position in vec2 ge_VertexTexcoord; in vec4 ge_VertexColor; in vec2 ge_VertexPosition; uniform mat4 ge_ProjectionMatrix; uniform vec2 offset; out vec4 ge_Color; void main() { ge_Color = ge_VertexColor; vec2 pos = offset + ge_VertexPosition.xy; ge_Position = ge_ProjectionMatrix * vec4(pos, 0.0, 1.0); // ge_Position.y = ge_Position.y * ( 720.0 / ( 1280.0 / 2.0 ) ); })" ; static const char hud_color_fragment_shader[] = R"( #version 100 precision mediump float; #define in varying #define ge_FragColor gl_FragColor uniform vec4 color; in vec4 ge_Color; void main() { ge_FragColor = color * ge_Color; })" ; RendererHUDNeo::RendererHUDNeo( int width, int height, float ratio, uint32_t fontsize, Vector4i render_region, bool barrel_correction ) : RendererHUD( width, height, ratio, fontsize, render_region, barrel_correction ) , mSmoothRPY( Vector3f() ) , mShader{ 0 } , mColorShader{ 0 } , mSpeedometerSize( 65 * fontsize / 28 ) { // mIconNight = LoadTexture( "data/icon_night.png" ); // mIconPhoto = LoadTexture( "data/icon_photo.png" ); LoadVertexShader( &mShader, hud_vertices_shader, sizeof(hud_vertices_shader) + 1 ); LoadFragmentShader( &mShader, hud_fragment_shader, sizeof(hud_fragment_shader) + 1 ); createPipeline( &mShader ); glUseProgram( mShader.mShader ); glEnableVertexAttribArray( mShader.mVertexTexcoordID ); glEnableVertexAttribArray( mShader.mVertexPositionID ); glUseProgram( 0 ); LoadVertexShader( &mColorShader, hud_color_vertices_shader, sizeof(hud_color_vertices_shader) + 1 ); LoadFragmentShader( &mColorShader, hud_color_fragment_shader, sizeof(hud_color_fragment_shader) + 1 ); createPipeline( &mColorShader ); glUseProgram( mColorShader.mShader ); glEnableVertexAttribArray( mColorShader.mVertexTexcoordID ); glEnableVertexAttribArray( mColorShader.mVertexColorID ); glEnableVertexAttribArray( mColorShader.mVertexPositionID ); glUseProgram( 0 ); Compute(); } RendererHUDNeo::~RendererHUDNeo() { } void RendererHUDNeo::Render( DroneStats* dronestats, float localVoltage, VideoStats* videostats, LinkStats* iwstats ) { if ( dronestats and dronestats->username != "" ) { RenderText( mWidth * 0.5f, mBorderTop, dronestats->username, Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ), 1.0f, TextAlignment::CENTER ); } // Controls if ( dronestats ) { float thrust = dronestats->thrust; if ( not dronestats->armed ) { thrust = 0.0f; } float acceleration = dronestats->acceleration / 9.7f; // if ( dronestats->mode != DroneMode::Rate ) { RenderAttitude( dronestats->rpy ); // } RenderThrustAcceleration( thrust, acceleration / 5.0f ); DroneMode mode = dronestats->mode; Vector4f color_acro = Vector4f( 0.4f, 0.4f, 0.4f, 1.0f ); Vector4f color_hrzn = Vector4f( 0.4f, 0.4f, 0.4f, 1.0f ); if ( mode == DroneMode::Rate ) { color_acro.x = color_acro.y = color_acro.z = 1.0f; } else if ( mode == DroneMode::Stabilize ) { color_hrzn.x = color_hrzn.y = color_hrzn.z = 1.0f; } int w = 0, h = 0; FontMeasureString( "ACRO/HRZN", &w, &h ); int mode_x = mBorderRight - mSpeedometerSize * 0.7f - w * 0.45f * 0.5f; RenderText( mode_x, mBorderBottom - mSpeedometerSize * 0.29f, "ACRO", color_acro, 0.45f ); FontMeasureString( "ACRO", &w, &h ); RenderText( mode_x + w * 0.45f, mBorderBottom - mSpeedometerSize * 0.29f, "/", Vector4f( 0.65f, 0.65f, 0.65f, 1.0f ), 0.45f ); FontMeasureString( "ACRO/", &w, &h ); RenderText( mode_x + w * 0.45f, mBorderBottom - mSpeedometerSize * 0.29f, "HRZN", color_hrzn, 0.45f ); Vector4f color = Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ); std::string saccel = std::to_string( acceleration ); saccel = saccel.substr( 0, saccel.find( "." ) + 2 ); RenderText( mBorderRight - mSpeedometerSize * 0.7f, mBorderBottom - mSpeedometerSize * 0.575f, saccel + "g", color, 0.55f, TextAlignment::CENTER ); if ( dronestats->armed ) { RenderText( mBorderRight - mSpeedometerSize * 0.7f, mBorderBottom - mSpeedometerSize * 0.75f - mFontSize * 0.6f, std::to_string( (int)( thrust * 100.0f ) ) + "%", color, 1.0f, TextAlignment::CENTER ); } else { RenderText( mBorderRight - mSpeedometerSize * 0.7f, mBorderBottom - mSpeedometerSize * 0.75f - mFontSize * 0.6f * 0.6f, "disarmed", color, 0.6f, TextAlignment::CENTER ); } } int bottom_left_text_idx = 0; // Battery if ( dronestats ) { float level = dronestats->batteryLevel; RenderBattery( level ); if ( level <= 0.0f and mBlinkingViews ) { RenderText( mWidth * 0.5f, mBorderBottom - mHeight * 0.15f, "Battery dead", Vector4f( 1.0f, 0.5f, 0.5f, 1.0f ), 1.0f, TextAlignment::CENTER ); } else if ( level <= 0.15f and mBlinkingViews ) { RenderText( mWidth * 0.5f, mBorderBottom - mHeight * 0.15f, "Battery critical", Vector4f( 1.0f, 0.5f, 0.5f, 1.0f ), 1.0f, TextAlignment::CENTER ); } else if ( level <= 0.25f and mBlinkingViews ) { RenderText( mWidth * 0.5f, mBorderBottom - mHeight * 0.15f, "Battery low", Vector4f( 1.0f, 0.5f, 0.5f, 1.0f ), 1.0f, TextAlignment::CENTER ); } float battery_red = 1.0f - level; RenderText( mBorderLeft + 210, mBorderBottom - mFontHeight * 1, std::to_string( (int)( level * 100.0f ) ) + "%", Vector4f( 0.5f + 0.5f * battery_red, 1.0f - battery_red * 0.25f, 0.5f - battery_red * 0.5f, 1.0f ), 0.9 ); std::string svolt = std::to_string( dronestats->batteryVoltage ); svolt = svolt.substr( 0, svolt.find( "." ) + 3 ); RenderText( mBorderLeft, mBorderBottom - mFontHeight * 3, svolt + "V", Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ), 0.75f ); RenderText( mBorderLeft, mBorderBottom - mFontHeight * 2, std::to_string( dronestats->batteryTotalCurrent ) + "mAh", Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ), 0.9f ); bottom_left_text_idx = 4; if ( localVoltage > 0.0f ) { if ( localVoltage <= 11.0f and mBlinkingViews ) { RenderText( mWidth * 0.5f, mBorderBottom - mHeight * 0.15f - mFontSize, "Low Goggles Battery", Vector4f( 1.0f, 0.5f, 0.5f, 1.0f ), 1.0f, TextAlignment::CENTER ); } battery_red = 1.0f - ( ( localVoltage - 11.0f ) / 1.6f ); svolt = std::to_string( localVoltage ); svolt = svolt.substr( 0, svolt.find( "." ) + 3 ); RenderText( mBorderLeft, mBorderBottom - mFontHeight * 4, svolt + "V", Vector4f( 0.5f + 0.5f * battery_red, 1.0f - battery_red * 0.25f, 0.5f, 1.0f ), 0.75 ); bottom_left_text_idx++; } } // Blackbox and stats if ( dronestats ) { RenderText( mBorderLeft, mBorderBottom - mFontHeight * bottom_left_text_idx, "BB " + std::to_string(dronestats->blackBoxId), Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ), 0.75f ); bottom_left_text_idx++; RenderText( mBorderLeft, mBorderBottom - mFontHeight * bottom_left_text_idx, "CPU " + std::to_string(dronestats->cpuUsage) + "%", Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ), 0.75f ); bottom_left_text_idx++; RenderText( mBorderLeft, mBorderBottom - mFontHeight * bottom_left_text_idx, "MEM " + std::to_string(dronestats->memUsage) + "%", Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ), 0.75f ); bottom_left_text_idx++; if ( dronestats->memUsage > 75 ) { RenderText( mWidth * 0.5f, mBorderBottom - mHeight * 0.15f + mFontHeight, "High memory usage", Vector4f( 1.0f, 0.5f, 0.5f, 1.0f ), 1.0f, TextAlignment::CENTER ); } else if ( dronestats->cpuUsage > 75 ) { RenderText( mWidth * 0.5f, mBorderBottom - mHeight * 0.15f + mFontHeight, "High CPU usage", Vector4f( 1.0f, 0.5f, 0.5f, 1.0f ), 1.0f, TextAlignment::CENTER ); } } // Static elements if ( dronestats ) { glUseProgram( mColorShader.mShader ); if ( mNightMode ) { glUniform4f( mColorShader.mColorID, 0.4f, 1.0f, 0.4f, 1.0f ); } else { glUniform4f( mColorShader.mColorID, 1.0f, 1.0f, 1.0f, 1.0f ); } // Lines { glLineWidth( 2.0f ); glBindBuffer( GL_ARRAY_BUFFER, mStaticLinesVBO ); glVertexAttribPointer( mColorShader.mVertexTexcoordID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertexColor ), (void*)( 0 ) ); glVertexAttribPointer( mColorShader.mVertexColorID, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( FastVertexColor ), (void*)( sizeof( float ) * 2 ) ); glVertexAttribPointer( mColorShader.mVertexPositionID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertexColor ), (void*)( sizeof( float ) * 2 + sizeof( uint32_t ) ) ); DrawArrays( mColorShader, GL_LINES, 0, ( dronestats->mode == DroneMode::Rate ) ? mStaticLinesCountNoAttitude : mStaticLinesCount ); } // Circle { glLineWidth( 2.0f ); glBindBuffer( GL_ARRAY_BUFFER, mCircleVBO ); glVertexAttribPointer( mColorShader.mVertexTexcoordID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertexColor ), (void*)( 0 ) ); glVertexAttribPointer( mColorShader.mVertexColorID, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( FastVertexColor ), (void*)( sizeof( float ) * 2 ) ); glVertexAttribPointer( mColorShader.mVertexPositionID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertexColor ), (void*)( sizeof( float ) * 2 + sizeof( uint32_t ) ) ); /* glUniform2f( mColorShader.mOffsetID, 1280.0f * +m3DStrength, 0.0f ); if ( dronestats->mode != DroneMode::Rate ) { glDrawArrays( GL_LINE_STRIP, 0, 64 ); glDrawArrays( GL_LINE_STRIP, 64, 64 ); } glDrawArrays( GL_LINE_STRIP, 128, 65 ); if ( mStereo ) { glUniform2f( mColorShader.mOffsetID, 1280.0f * -m3DStrength + 1280.0f / 2.0f, 0.0f ); if ( dronestats->mode != DroneMode::Rate ) { glDrawArrays( GL_LINE_STRIP, 0, 64 ); glDrawArrays( GL_LINE_STRIP, 64, 64 ); } glDrawArrays( GL_LINE_STRIP, 128, 65 ); } */ if ( dronestats->mode != DroneMode::Rate ) { DrawArrays( mColorShader, GL_LINE_STRIP, 0, 64 ); DrawArrays( mColorShader, GL_LINE_STRIP, 64, 64 ); } DrawArrays( mColorShader, GL_LINE_STRIP, 128, 65 ); } } // Link status if ( iwstats ) { float level = ( iwstats->level != -200 ) ? ( ( (float)( 100 + iwstats->level ) * 100.0f / 50.0f ) / 100.0f ) : 0.8f; RenderLink( (float)iwstats->qual / 100.0f, level ); float link_red = 1.0f - ((float)iwstats->qual) / 100.0f; std::string channel_str = ( iwstats->channel > 400 ) ? ( std::to_string( iwstats->channel ) + "MHz" ) : ( "Ch" + std::to_string( iwstats->channel ) ); std::string level_str = ( iwstats->level != -200 ) ? ( std::to_string( iwstats->level ) + "dBm " ) : ""; std::string link_quality_str = channel_str + " " + level_str + std::to_string( iwstats->qual ) + "%"; RenderText( mBorderLeft, mBorderTop + 60, link_quality_str, Vector4f( 0.5f + 0.5f * link_red, 1.0f - link_red * 0.25f, 0.5f - link_red * 0.5f, 1.0f ), 0.9f ); } // video-infos + FPS if ( videostats ) { int w = 0, h = 0; std::string res_str = std::to_string( videostats->width ) + "x" + std::to_string( videostats->height ); FontMeasureString( res_str, &w, &h ); RenderText( (float)mBorderRight - w*0.775f, mBorderTop, res_str, Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ), 0.8f ); if ( videostats->fps != 0 ) { float fps_red = std::max( 0.0f, std::min( 1.0f, ((float)( 50 - videostats->fps ) ) / 50.0f ) ); std::string fps_str = std::to_string( videostats->fps ) + "fps"; FontMeasureString( fps_str, &w, &h ); RenderText( (float)mBorderRight - w*0.775f, mBorderTop + mFontHeight * 1.0f, fps_str, Vector4f( 0.5f + 0.5f * fps_red, 1.0f - fps_red * 0.25f, 0.5f - fps_red * 0.5f, 1.0f ), 0.8f ); } FontMeasureString( videostats->whitebalance, &w, &h ); RenderText( (float)mBorderRight - w*0.775f, mBorderTop + mFontHeight * 3.0f, videostats->whitebalance, Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ), 0.8f ); FontMeasureString( videostats->exposure, &w, &h ); RenderText( (float)mBorderRight - w*0.775f, mBorderTop + mFontHeight * 4.0f, videostats->exposure, Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ), 0.8f ); /* if ( mNightMode ) { RenderQuadTexture( mIconNight->glID, mBorderRight - mWidth * 0.04f, mHeight / 2 - mHeight * 0.15, mWidth * 0.04f, mWidth * 0.035f, false, false, { 1.0f, 1.0f, 1.0f, 1.0f } ); } else { RenderQuadTexture( mIconNight->glID, mBorderRight - mWidth * 0.04f, mHeight / 2 - mHeight * 0.15, mWidth * 0.04f, mWidth * 0.035f, false, false, { 0.5f, 0.5f, 0.5f, 0.5f } ); } */ /* float photo_alpha = 0.5f; float photo_burn = 1.0f; if ( videostats->photo_id != mLastPhotoID ) { mLastPhotoID = videostats->photo_id; mPhotoTick = Thread::GetSeconds(); } if ( mPhotoTick != 0.0f and Thread::GetSeconds() - mPhotoTick < 0.5f ) { float diff = Thread::GetSeconds() - mPhotoTick; photo_alpha += 0.75f * 2.0f * ( 0.5f - diff ); photo_burn += 2.0f * 2.0f * ( 0.5f - diff ); } RenderQuadTexture( mIconPhoto->glID, mBorderRight - mWidth * 0.04f, mHeight / 2 - mHeight * 0.07, mWidth * 0.04f, mWidth * 0.035f, false, false, { photo_burn, photo_burn, photo_burn, photo_alpha } ); */ if ( videostats->vtxFrequency > 0 ) { std::string text = std::to_string(videostats->vtxFrequency) + "MHz"; FontMeasureString( text, &w, &h ); RenderText( (float)mBorderRight - w*0.775f, mBorderTop + mFontHeight * 5.0f, text, Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ), 0.8f ); } if ( videostats->vtxPowerDbm >= 0 ) { std::string text = std::to_string(videostats->vtxPowerDbm) + "dBm"; FontMeasureString( text, &w, &h ); RenderText( (float)mBorderRight - w*0.775f, mBorderTop + mFontHeight * 6.0f, text, Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ), 0.8f ); } if ( videostats->vtxChannel > 0 ) { std::string text = ""; if ( strlen(videostats->vtxBand) > 0 ) { if ( videostats->vtxBand[0] == 'B' ) { text += std::string(&videostats->vtxBand[7], 1); } else { text += std::string(&videostats->vtxBand[0], 1); } } text += std::to_string(videostats->vtxChannel % 8 + 1); FontMeasureString( text, &w, &h ); RenderText( (float)mBorderRight - w*0.775f, mBorderTop + mFontHeight * 7.0f, text, Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ), 0.8f ); } } // Latency if ( dronestats ) { int w = 0, h = 0; float latency_red = std::min( 1.0f, ((float)dronestats->ping ) / 100.0f ); std::string latency_str = std::to_string( dronestats->ping / 2 ) + "ms"; FontMeasureString( latency_str, &w, &h ); RenderText( (float)mBorderRight - w*0.775f, mBorderTop + mFontHeight * 2.0f, latency_str, Vector4f( 0.5f + 0.5f * latency_red, 1.0f - latency_red * 0.25f, 0.5f - latency_red * 0.5f, 1.0f ), 0.8f ); if ( dronestats->ping > 50 ) { RenderText( mWidth * 0.5f, mBorderBottom - mHeight * 0.15f - mFontSize * 2, "High Latency", Vector4f( 1.0f, 0.5f, 0.5f, 1.0f ), 1.0f, TextAlignment::CENTER ); } } if ( dronestats and not std::isnan( dronestats->gpsSpeed ) ) { // Render dronestats->gpsSpeed as simple text, already in km/h std::string speed = std::to_string((int)dronestats->gpsSpeed) + "km/h"; std::string sats = std::to_string((int)dronestats->gpsSatellitesUsed) + "/" + std::to_string((int)dronestats->gpsSatellitesSeen); RenderText( mBorderRight, mBorderBottom - 256 - 46, speed, Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ), 0.75f, RendererHUD::END ); RenderText( mBorderRight, mBorderBottom - 256 - 6, sats, Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ), 0.75f, RendererHUD::END ); } int imsg = 0; for ( std::string msg : dronestats->messages ) { RenderText( mBorderLeft * 0.75f, mBorderTop + mFontSize * 0.75f * ( 3 + (imsg++) ), msg, Vector4f( 1.0f, 0.5f, 0.5f, 1.0f ), 0.75f ); } } void RendererHUDNeo::RenderThrustAcceleration( float thrust, float acceleration ) { if ( thrust < 0.0f ) { thrust = 0.0f; } if ( thrust > 1.0f ) { thrust = 1.0f; } if ( acceleration < 0.0f ) { acceleration = 0.0f; } if ( acceleration > 1.0f ) { acceleration = 1.0f; } glUseProgram( mShader.mShader ); { if ( mNightMode ) { glUniform4f( mShader.mColorID, 0.2f, 0.8f, 0.7f, 1.0f ); } else { glUniform4f( mShader.mColorID, 0.2f, 0.8f, 1.0f, 1.0f ); } glBindBuffer( GL_ARRAY_BUFFER, mThrustVBO ); glVertexAttribPointer( mShader.mVertexTexcoordID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertex ), (void*)( 0 ) ); glVertexAttribPointer( mShader.mVertexPositionID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertex ), (void*)( sizeof( float ) * 2 ) ); glDisable( GL_CULL_FACE ); DrawArrays( mShader, GL_TRIANGLE_STRIP, 0, 4 * std::min( 64, (int)( thrust * 64.0f ) ) ); } { if ( mNightMode ) { glUniform4f( mShader.mColorID, 0.2f, 0.7f, 0.65f, 1.0f ); } else { glUniform4f( mShader.mColorID, 0.3f, 0.75f, 0.7f, 1.0f ); } glBindBuffer( GL_ARRAY_BUFFER, mAccelerationVBO ); glVertexAttribPointer( mShader.mVertexTexcoordID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertex ), (void*)( 0 ) ); glVertexAttribPointer( mShader.mVertexPositionID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertex ), (void*)( sizeof( float ) * 2 ) ); glDisable( GL_CULL_FACE ); DrawArrays( mShader, GL_TRIANGLE_STRIP, 0, 4 * std::min( 32, (int)( acceleration * 32.0f ) ) ); } } void RendererHUDNeo::RenderLink( float quality, float level ) { if ( quality > 1.0f ) { quality = 1.0f; } if ( quality < 0.0f ) { quality = 0.0f; } if ( level > 1.0f ) { level = 1.0f; } if ( level < 0.0f ) { level = 0.0f; } glUseProgram( mColorShader.mShader ); glUniform4f( mColorShader.mColorID, 1.0f, 1.0f, 1.0f, 1.0f ); glBindBuffer( GL_ARRAY_BUFFER, mLinkVBO ); glVertexAttribPointer( mColorShader.mVertexTexcoordID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertexColor ), (void*)( 0 ) ); glVertexAttribPointer( mColorShader.mVertexColorID, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( FastVertexColor ), (void*)( sizeof( float ) * 2 ) ); glVertexAttribPointer( mColorShader.mVertexPositionID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertexColor ), (void*)( sizeof( float ) * 2 + sizeof( uint32_t ) ) ); FastVertexColor linkBuffer[6 * 16]; memset( linkBuffer, 0, sizeof( linkBuffer ) ); for ( uint32_t i = 0; i < 16; i++ ) { float height = std::exp( i * 0.1f ); int ofsy = level * height * 12.0f; int bar_width = 11.0f * mFontSize / 30.0f; float x = mBorderLeft + i * ( bar_width + 2 ); float y = mBorderTop + 60; linkBuffer[i*6 + 0].x = x; linkBuffer[i*6 + 0].y = y-ofsy; linkBuffer[i*6 + 1].x = x+bar_width; linkBuffer[i*6 + 1].y = y; linkBuffer[i*6 + 2].x = x+bar_width; linkBuffer[i*6 + 2].y = y-ofsy; linkBuffer[i*6 + 3].x = x; linkBuffer[i*6 + 3].y = y-ofsy; linkBuffer[i*6 + 4].x = x; linkBuffer[i*6 + 4].y = y; linkBuffer[i*6 + 5].x = x+bar_width; linkBuffer[i*6 + 5].y = y; Vector4f fcolor = Vector4f( 0.5f + 0.5f * 0.0625f * ( 15 - i ), 0.5f + 0.5f * 0.0625f * i, 0.5f, 1.0f ); uint32_t color = 0xFF7F0000 | ( (uint32_t)( fcolor.y * 255.0f ) << 8 ) | ( (uint32_t)( fcolor.x * 255.0f ) ); linkBuffer[i*6 + 0].color = linkBuffer[i*6 + 1].color = linkBuffer[i*6 + 2].color = linkBuffer[i*6 + 3].color = linkBuffer[i*6 + 4].color = linkBuffer[i*6 + 5].color = color; for ( int j = 0; j < 6; j++ ) { Vector2f vec = VR_Distort( Vector2f( linkBuffer[i*6 + j].x, linkBuffer[i*6 + j].y ) ); linkBuffer[i*6 + j].x = vec.x; linkBuffer[i*6 + j].y = vec.y; } } glBindBuffer( GL_ARRAY_BUFFER, mLinkVBO ); ::Thread::EnterCritical(); glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(linkBuffer), linkBuffer ); ::Thread::ExitCritical(); DrawArrays( mColorShader, GL_TRIANGLES, 0, 6 * std::min( 16, (int)( quality * 16.0f ) ) ); } void RendererHUDNeo::RenderBattery( float level ) { if ( level < 0.0f ) { level = 0.0f; } if ( level > 1.0f ) { level = 1.0f; } glUseProgram( mShader.mShader ); glUniform4f( mShader.mColorID, 1.0f - level * 0.5f, level, level * 0.5f, 1.0f ); // int ofsy = (int)( level * 96.0f ); FastVertex batteryBuffer[4*8]; Vector2f offset = Vector2f( mBorderLeft, mBorderBottom - 20 ); for ( uint32_t i = 0; i < 8; i++ ) { Vector2f p0 = offset + Vector2f( 200.0f * level * (float)( i + 0 ) / 8.0f, 0.0f ); Vector2f p1 = offset + Vector2f( 200.0f * level * (float)( i + 1 ) / 8.0f, 0.0f ); Vector2f p2 = offset + Vector2f( 200.0f * level * (float)( i + 0 ) / 8.0f, 20.0f ); Vector2f p3 = offset + Vector2f( 200.0f * level * (float)( i + 1 ) / 8.0f, 20.0f ); batteryBuffer[i*4 + 0].x = p0.x; batteryBuffer[i*4 + 0].y = p0.y; batteryBuffer[i*4 + 1].x = p1.x; batteryBuffer[i*4 + 1].y = p1.y; batteryBuffer[i*4 + 2].x = p2.x; batteryBuffer[i*4 + 2].y = p2.y; batteryBuffer[i*4 + 3].x = p3.x; batteryBuffer[i*4 + 3].y = p3.y; for ( int j = 0; j < 4; j++ ) { Vector2f vec = VR_Distort( Vector2f( batteryBuffer[i*4 + j].x, batteryBuffer[i*4 + j].y ) ); batteryBuffer[i*4 + j].x = vec.x; batteryBuffer[i*4 + j].y = vec.y; } } glBindBuffer( GL_ARRAY_BUFFER, mBatteryVBO ); ::Thread::EnterCritical(); glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(batteryBuffer), batteryBuffer ); ::Thread::ExitCritical(); glVertexAttribPointer( mShader.mVertexTexcoordID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertex ), (void*)( 0 ) ); glVertexAttribPointer( mShader.mVertexPositionID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertex ), (void*)( sizeof( float ) * 2 ) ); DrawArrays( mShader, GL_TRIANGLE_STRIP, 0, sizeof(batteryBuffer)/sizeof(FastVertex) ); } static Vector2f Rotate( const Vector2f& p0, float s, float c ) { Vector2f p; p.x = p0.x * c - p0.y * s; p.y = p0.x * s + p0.y * c; return p; } void RendererHUDNeo::RenderAttitude( const Vector3f& rpy ) { /* mSmoothRPY = mSmoothRPY + ( Vector3f( rpy.x, rpy.y, rpy.z ) - mSmoothRPY ) * 35.0f * ( 1.0f / 60.0f ); if ( std::abs( mSmoothRPY.x ) <= 0.15f ) { mSmoothRPY.x = 0.0f; } if ( std::abs( mSmoothRPY.y ) <= 0.15f ) { mSmoothRPY.y = 0.0f; } */ mSmoothRPY.x = rpy.x; mSmoothRPY.y = rpy.y; mSmoothRPY.z = rpy.z; glLineWidth( 2.0f ); glBindBuffer( GL_ARRAY_BUFFER, mLineVBO ); glVertexAttribPointer( mColorShader.mVertexTexcoordID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertexColor ), (void*)( 0 ) ); glVertexAttribPointer( mColorShader.mVertexColorID, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( FastVertexColor ), (void*)( sizeof( float ) * 2 ) ); glVertexAttribPointer( mColorShader.mVertexPositionID, 2, GL_FLOAT, GL_FALSE, sizeof( FastVertexColor ), (void*)( sizeof( float ) * 2 + sizeof( uint32_t ) ) ); glUseProgram( mColorShader.mShader ); uint32_t color = 0xFFFFFFFF; if ( mNightMode ) { color = 0xFF40FF40; } float xrot = -M_PI * ( mSmoothRPY.x / 180.0f ); float yofs = -( mHeight / 2.0f ) * ( mSmoothRPY.y / 180.0f ) * M_PI * 2.25f; float s = std::sin( xrot ); float c = std::cos( xrot ); float movingBarWidth = 0.4f; float staticBarWidth = (1.0f - movingBarWidth ) / 2.0f; float movingBarOffset = staticBarWidth; static FastVertexColor allLinesBuffer[2*4*64 + 16]; uint32_t total = 0; // Fixed lines { for ( uint32_t part = 0; part < 2; part++ ) { for ( uint32_t j = 0; j < 4; j++ ) { float xpos = ( part * ( staticBarWidth + movingBarWidth ) ) + staticBarWidth * (float)j / (float)4; float xpos1 = ( part * ( staticBarWidth + movingBarWidth ) ) + staticBarWidth * (float)(j + 1) / (float)4; allLinesBuffer[part * 2 + j * 4 + 0].x = xpos * mWidth; allLinesBuffer[part * 2 + j * 4 + 0].y = mHeight / 2.0f; allLinesBuffer[part * 2 + j * 4 + 0].color = color; allLinesBuffer[part * 2 + j * 4 + 1].x = xpos1 * mWidth; allLinesBuffer[part * 2 + j * 4 + 1].y = mHeight / 2.0f; allLinesBuffer[part * 2 + j * 4 + 1].color = color; total += 2; } } } if ( std::abs(mSmoothRPY.x) > 70.0f or std::abs(mSmoothRPY.y) > 70.0f ) { /* ::Thread::EnterCritical(); glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(FastVertexColor) * total, allLinesBuffer ); ::Thread::ExitCritical(); DrawArrays( mColorShader, GL_LINES, 0, total ); return; */ } // Attitude line { static FastVertexColor linesBuffer[8]; for ( uint32_t j = 0; j < sizeof(linesBuffer)/sizeof(FastVertexColor); j++ ) { float xpos = movingBarOffset + movingBarWidth * (float)j / (float)(sizeof(linesBuffer)/sizeof(FastVertexColor)-1); Vector2f p; Vector2f p0 = Vector2f( ( xpos - 0.5f ) * ( mWidth ), yofs ); p.x = mWidth / 2.0f + p0.x * c - p0.y * s; p.y = mHeight / 2.0f + p0.x * s + p0.y * c; p = VR_Distort( p ); // linesBuffer[j].x = std::min( std::max( p.x, 0.0f ), mWidth - 50.0f ); linesBuffer[j].x = p.x; linesBuffer[j].y = p.y; linesBuffer[j].color = color; } ::Thread::EnterCritical(); glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(linesBuffer), linesBuffer ); ::Thread::ExitCritical(); DrawArrays( mColorShader, GL_LINE_STRIP, 0, sizeof(linesBuffer)/sizeof(FastVertexColor) ); } // Degres lines { uint32_t i = total; for ( int32_t j = -3; j <= 3; j++ ) { if ( j == 0 ) { continue; } float y = 720.0f * 0.25f * ( (float)j / 2.0f ); if ( std::abs( Rotate( Vector2f( 0.0f, yofs + y ), s, c ).y ) >= 720.0f * 0.5f * 1.25f ) { continue; } float text_line = 720.0f * 0.0075f; if ( j > 0 ) { text_line = -text_line; } Vector2f p0 = VR_Distort( Vector2f( mWidth * 0.5f, 720.0 * 0.5f ) + Rotate( Vector2f( mWidth * 0.5f * 0.15f, yofs + y ), s, c ) ); Vector2f p1 = VR_Distort( Vector2f( mWidth * 0.5f, 720.0 * 0.5f ) + Rotate( Vector2f( mWidth * 0.5f * 0.225f, yofs + y ), s, c ) ); Vector2f p2 = VR_Distort( Vector2f( mWidth * 0.5f, 720.0 * 0.5f ) + Rotate( Vector2f( mWidth * 0.5f * 0.225f, yofs + y + text_line ), s, c ) ); allLinesBuffer[i].x = p0.x; allLinesBuffer[i].y = p0.y; allLinesBuffer[i++].color = color; allLinesBuffer[i].x = p1.x; allLinesBuffer[i].y = p1.y; allLinesBuffer[i++].color = color; allLinesBuffer[i].x = p1.x; allLinesBuffer[i].y = p1.y; allLinesBuffer[i++].color = color; allLinesBuffer[i].x = p2.x; allLinesBuffer[i].y = p2.y; allLinesBuffer[i++].color = color; Vector2f p3 = VR_Distort( Vector2f( mWidth * 0.5f, 720.0 * 0.5f ) + Rotate( Vector2f( mWidth * 0.5f * -0.15f, yofs + y ), s, c ) ); Vector2f p4 = VR_Distort( Vector2f( mWidth * 0.5f, 720.0 * 0.5f ) + Rotate( Vector2f( mWidth * 0.5f * -0.225f, yofs + y ), s, c ) ); Vector2f p5 = VR_Distort( Vector2f( mWidth * 0.5f, 720.0 * 0.5f ) + Rotate( Vector2f( mWidth * 0.5f * -0.225f, yofs + y + text_line ), s, c ) ); allLinesBuffer[i].x = p3.x; allLinesBuffer[i].y = p3.y; allLinesBuffer[i++].color = color; allLinesBuffer[i].x = p4.x; allLinesBuffer[i].y = p4.y; allLinesBuffer[i++].color = color; allLinesBuffer[i].x = p4.x; allLinesBuffer[i].y = p4.y; allLinesBuffer[i++].color = color; allLinesBuffer[i].x = p5.x; allLinesBuffer[i].y = p5.y; allLinesBuffer[i++].color = color; total += 8; } } ::Thread::EnterCritical(); glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(FastVertexColor) * total, allLinesBuffer ); ::Thread::ExitCritical(); DrawArrays( mColorShader, GL_LINES, 0, total ); } void RendererHUDNeo::Compute() { float thrust_outer = mSpeedometerSize; float thrust_out = mSpeedometerSize * 0.77f; float thrust_in = mSpeedometerSize * 0.54f; { const uint32_t steps_count = 64; FastVertex thrustBuffer[4 * steps_count * 4]; memset( thrustBuffer, 0, sizeof( thrustBuffer ) ); Vector2f offset = Vector2f( mBorderRight - thrust_outer * 0.7f, mBorderBottom - thrust_outer * 0.75f ); for ( uint32_t i = 0; i < steps_count; i++ ) { float angle0 = ( 0.1f + 0.775f * ( (float)i / (float)steps_count ) ) * M_PI * 2.0f - ( M_PI * 1.48f ); float angle1 = ( 0.1f + 0.775f * ( (float)( i + 1 ) / (float)steps_count ) ) * M_PI * 2.0f - ( M_PI * 1.48f ); Vector2f p0 = offset + thrust_in * Vector2f( std::cos( angle0 ), std::sin( angle0 ) ); Vector2f p1 = offset + thrust_out * Vector2f( std::cos( angle0 ), std::sin( angle0 ) ); Vector2f p2 = offset + thrust_in * Vector2f( std::cos( angle1 ), std::sin( angle1 ) ); Vector2f p3 = offset + thrust_out * Vector2f( std::cos( angle1 ), std::sin( angle1 ) ); thrustBuffer[i*4 + 0].x = p0.x; thrustBuffer[i*4 + 0].y = p0.y; thrustBuffer[i*4 + 1].x = p1.x; thrustBuffer[i*4 + 1].y = p1.y; thrustBuffer[i*4 + 2].x = p2.x; thrustBuffer[i*4 + 2].y = p2.y; thrustBuffer[i*4 + 3].x = p3.x; thrustBuffer[i*4 + 3].y = p3.y; for ( int j = 0; j < 4; j++ ) { Vector2f vec = VR_Distort( Vector2f( thrustBuffer[i*4 + j].x, thrustBuffer[i*4 + j].y ) ); thrustBuffer[i*4 + j].x = vec.x; thrustBuffer[i*4 + j].y = vec.y; } } glGenBuffers( 1, &mThrustVBO ); glBindBuffer( GL_ARRAY_BUFFER, mThrustVBO ); glBufferData( GL_ARRAY_BUFFER, sizeof(thrustBuffer), thrustBuffer, GL_STATIC_DRAW ); } { const uint32_t steps_count = 32; FastVertex accelerationBuffer[4 * steps_count * 8]; memset( accelerationBuffer, 0, sizeof( accelerationBuffer ) ); Vector2f offset = Vector2f( mBorderRight - thrust_outer * 0.7f, mBorderBottom - thrust_outer * 0.75f ); for ( uint32_t i = 0; i < steps_count; i++ ) { float angle0 = ( 0.1f + 0.265f * ( (float)i / (float)steps_count ) ) * M_PI * 2.0f - ( M_PI * 1.48f ); float angle1 = ( 0.1f + 0.265f * ( (float)( i + 1 ) / (float)steps_count ) ) * M_PI * 2.0f - ( M_PI * 1.48f ); Vector2f p0 = offset + ( thrust_out + 3.0f ) * Vector2f( std::cos( angle0 ), std::sin( angle0 ) ); Vector2f p1 = offset + ( thrust_outer - 4.0f ) * Vector2f( std::cos( angle0 ), std::sin( angle0 ) ); Vector2f p2 = offset + ( thrust_out + 3.0f ) * Vector2f( std::cos( angle1 ), std::sin( angle1 ) ); Vector2f p3 = offset + ( thrust_outer - 4.0f ) * Vector2f( std::cos( angle1 ), std::sin( angle1 ) ); accelerationBuffer[i*4 + 0].x = p0.x; accelerationBuffer[i*4 + 0].y = p0.y; accelerationBuffer[i*4 + 1].x = p1.x; accelerationBuffer[i*4 + 1].y = p1.y; accelerationBuffer[i*4 + 2].x = p2.x; accelerationBuffer[i*4 + 2].y = p2.y; accelerationBuffer[i*4 + 3].x = p3.x; accelerationBuffer[i*4 + 3].y = p3.y; for ( int j = 0; j < 4; j++ ) { Vector2f vec = VR_Distort( Vector2f( accelerationBuffer[i*4 + j].x, accelerationBuffer[i*4 + j].y ) ); accelerationBuffer[i*4 + j].x = vec.x; accelerationBuffer[i*4 + j].y = vec.y; } } glGenBuffers( 1, &mAccelerationVBO ); glBindBuffer( GL_ARRAY_BUFFER, mAccelerationVBO ); glBufferData( GL_ARRAY_BUFFER, sizeof(accelerationBuffer), accelerationBuffer, GL_STATIC_DRAW ); } { FastVertexColor linkBuffer[6 * 16 * 4]; memset( linkBuffer, 0, sizeof( linkBuffer ) ); /* for ( uint32_t i = 0; i < 16; i++ ) { float height = std::exp( i * 0.1f ); int ofsy = height * 12.0f; float x = 1280.0f / ( 1 + mStereo ) * 0.12f + i * ( 11 + 1 ); float y = 720.0f * 0.22f; linkBuffer[i*6 + 0].x = x; linkBuffer[i*6 + 0].y = y-ofsy; linkBuffer[i*6 + 1].x = x+11; linkBuffer[i*6 + 1].y = y; linkBuffer[i*6 + 2].x = x+11; linkBuffer[i*6 + 2].y = y-ofsy; linkBuffer[i*6 + 3].x = x; linkBuffer[i*6 + 3].y = y-ofsy; linkBuffer[i*6 + 4].x = x; linkBuffer[i*6 + 4].y = y; linkBuffer[i*6 + 5].x = x+11; linkBuffer[i*6 + 5].y = y; Vector4f fcolor = Vector4f( 0.5f + 0.5f * 0.0625f * ( 15 - i ), 0.5f + 0.5f * 0.0625f * i, 0.5f, 1.0f ); uint32_t color = 0xFF7F0000 | ( (uint32_t)( fcolor.y * 255.0f ) << 8 ) | ( (uint32_t)( fcolor.x * 255.0f ) ); linkBuffer[i*6 + 0].color = linkBuffer[i*6 + 1].color = linkBuffer[i*6 + 2].color = linkBuffer[i*6 + 3].color = linkBuffer[i*6 + 4].color = linkBuffer[i*6 + 5].color = color; for ( int j = 0; j < 6; j++ ) { Vector2f vec = VR_Distort( Vector2f( linkBuffer[i*6 + j].x, linkBuffer[i*6 + j].y ) ); linkBuffer[i*6 + j].x = vec.x; linkBuffer[i*6 + j].y = vec.y; } } */ glGenBuffers( 1, &mLinkVBO ); glBindBuffer( GL_ARRAY_BUFFER, mLinkVBO ); glBufferData( GL_ARRAY_BUFFER, sizeof(FastVertexColor) * 6 * 16 * 4, linkBuffer, GL_STATIC_DRAW ); } { glGenBuffers( 1, &mBatteryVBO ); glBindBuffer( GL_ARRAY_BUFFER, mBatteryVBO ); glBufferData( GL_ARRAY_BUFFER, sizeof(FastVertex) * 2048, nullptr, GL_DYNAMIC_DRAW ); } { glGenBuffers( 1, &mLineVBO ); glBindBuffer( GL_ARRAY_BUFFER, mLineVBO ); glBufferData( GL_ARRAY_BUFFER, sizeof(FastVertexColor) * 2048, nullptr, GL_DYNAMIC_DRAW ); } { FastVertexColor circleBuffer[2048]; uint32_t steps_count = 64; for ( uint32_t i = 0; i < steps_count; i++ ) { float angle = ( 0.1f + 0.8f * ( (float)i / (float)steps_count ) ) * M_PI; Vector2f pos = Vector2f( 150.0f * std::cos( angle ), 150.0f * std::sin( angle ) ); pos = VR_Distort( pos + Vector2f( mWidth / 2.0f, mHeight / 2.0f ) ); circleBuffer[i].x = pos.x; circleBuffer[i].y = pos.y; circleBuffer[i].color = 0xFFFFFFFF; if ( i <= 10 ) { circleBuffer[i].color = ( ( i * 255 / 10 ) << 24 ) | 0x00FFFFFF; } else if ( i >= 54 ) { circleBuffer[i].color = ( ( ( steps_count - i ) * 255 / 10 ) << 24 ) | 0x00FFFFFF; } memcpy( &circleBuffer[ steps_count + i ], &circleBuffer[i], sizeof( circleBuffer[i] ) ); circleBuffer[ steps_count + i ].y = 720.0f / 2.0f - ( pos.y - 720.0f / 2.0f ); } uint32_t i = 128; steps_count = 32; for ( uint32_t j = 0; j < steps_count; j++ ) { float angle = ( 0.1f + 0.8f * ( (float)j / (float)steps_count ) ) * M_PI * 2.0f - ( M_PI * 1.48f ); if ( j == 0 ) { Vector2f pos = VR_Distort( Vector2f( mBorderRight - thrust_outer * 0.7f + thrust_outer * std::cos( angle ), mBorderBottom - thrust_outer * 0.75f + thrust_outer * std::sin( angle ) ) ); circleBuffer[i].x = pos.x; circleBuffer[i].y = pos.y; circleBuffer[i].color = 0xFFFFFFFF; } Vector2f pos = Vector2f( mBorderRight - thrust_outer * 0.7f + thrust_in * std::cos( angle ), mBorderBottom - thrust_outer * 0.75f + thrust_in * std::sin( angle ) ); pos = VR_Distort( pos ); circleBuffer[++i].x = pos.x; circleBuffer[i].y = pos.y; circleBuffer[i].color = 0xFFFFFFFF; } for ( uint32_t j = 0; j < steps_count; j++ ) { float angle = ( 0.1f + 0.8f * ( (float)( 31 - j ) / (float)steps_count ) ) * M_PI * 2.0f - ( M_PI * 1.48f ); Vector2f pos = Vector2f( mBorderRight - thrust_outer * 0.7f + thrust_out * std::cos( angle ), mBorderBottom - thrust_outer * 0.75f + thrust_out * std::sin( angle ) ); pos = VR_Distort( pos ); circleBuffer[++i].x = pos.x; circleBuffer[i].y = pos.y; circleBuffer[i].color = 0xFFFFFFFF; } glGenBuffers( 1, &mCircleVBO ); glBindBuffer( GL_ARRAY_BUFFER, mCircleVBO ); glBufferData( GL_ARRAY_BUFFER, sizeof(circleBuffer), circleBuffer, GL_STATIC_DRAW ); } { FastVertexColor staticLinesBuffer[2048]; uint32_t i = 0; // G-force container { Vector2f p0 = Vector2f( mBorderRight - thrust_outer * 0.7f - thrust_outer * 0.3f, mBorderBottom - thrust_outer * 0.575f ); Vector2f p1 = Vector2f( mBorderRight - thrust_outer * 0.7f + thrust_outer * 0.3f, mBorderBottom - thrust_outer * 0.575f + mFontSize * 0.55f ); staticLinesBuffer[i].x = p0.x; staticLinesBuffer[i].y = p0.y; staticLinesBuffer[++i].x = p1.x; staticLinesBuffer[i].y = p0.y; staticLinesBuffer[++i].x = p1.x; staticLinesBuffer[i].y = p0.y; staticLinesBuffer[++i].x = p1.x; staticLinesBuffer[i].y = p1.y; staticLinesBuffer[++i].x = p0.x; staticLinesBuffer[i].y = p1.y; staticLinesBuffer[++i].x = p1.x; staticLinesBuffer[i].y = p1.y; staticLinesBuffer[++i].x = p0.x; staticLinesBuffer[i].y = p1.y; staticLinesBuffer[++i].x = p0.x; staticLinesBuffer[i].y = p0.y; } // Max G-circular-bar { Vector2f pos; float angle = M_PI * 1.25f; pos = Vector2f( mBorderRight - thrust_outer * 0.7f + thrust_out * std::cos( angle ), mBorderBottom - thrust_outer * 0.75f + thrust_out * std::sin( angle ) ); staticLinesBuffer[++i].x = pos.x; staticLinesBuffer[i].y = pos.y; pos = Vector2f( mBorderRight - thrust_outer * 0.7f + thrust_outer * std::cos( angle ), mBorderBottom - thrust_outer * 0.75f + thrust_outer * std::sin( angle ) ); staticLinesBuffer[++i].x = pos.x; staticLinesBuffer[i].y = pos.y; } // Battery container { Vector2f offset = Vector2f( mBorderLeft, mBorderBottom - 20 ); for ( uint32_t j = 0; j < 8; j++ ) { Vector2f p0 = offset + Vector2f( 200.0f * (float)( j + 0 ) / 8.0f, 0.0f ); Vector2f p1 = offset + Vector2f( 200.0f * (float)( j + 1 ) / 8.0f, 0.0f ); staticLinesBuffer[++i].x = p0.x; staticLinesBuffer[i].y = p0.y; staticLinesBuffer[++i].x = p1.x; staticLinesBuffer[i].y = p1.y; staticLinesBuffer[++i].x = p0.x; staticLinesBuffer[i].y = p0.y + 20.0f; staticLinesBuffer[++i].x = p1.x; staticLinesBuffer[i].y = p1.y + 20.0f; } Vector2f p0 = offset + Vector2f( 200.0f, 0.0f ); Vector2f p1 = offset + Vector2f( 200.0f, 20.0f ); staticLinesBuffer[++i].x = p0.x; staticLinesBuffer[i].y = p0.y; staticLinesBuffer[++i].x = p1.x; staticLinesBuffer[i].y = p1.y; p0.x = p1.x = offset.x; staticLinesBuffer[++i].x = p0.x; staticLinesBuffer[i].y = p0.y; staticLinesBuffer[++i].x = p1.x; staticLinesBuffer[i].y = p1.y; } mStaticLinesCountNoAttitude = i + 1; // Left lines { for ( uint32_t j = 0; j <= 12; j++ ) { if ( j <= 11 ) { staticLinesBuffer[++i].x = 0; staticLinesBuffer[i].y = 180.0f + ( 720.0f - 360.0f ) * ( (float)j / 12.0f ); staticLinesBuffer[++i].x = 0; staticLinesBuffer[i].y = 180.0f + ( 720.0f - 360.0f ) * ( (float)( j + 1 ) / 12.0f ); } staticLinesBuffer[++i].x = 0; staticLinesBuffer[i].y = 180.0f + ( 720.0f - 360.0f ) * ( (float)j / 12.0f ); staticLinesBuffer[++i].x = 1280.0f * 0.03f; staticLinesBuffer[i].y = 180.0f + ( 720.0f - 360.0f ) * ( (float)j / 12.0f ); } } /* // Right line { for ( uint32_t j = 0; j <= 6; j++ ) { staticLinesBuffer[++i].x = 1280.0f * 0.94f; staticLinesBuffer[i].y = 720.0f * 0.5f + 720.0f * 0.15f * ( (float)j / 6.0f - 0.5f ); staticLinesBuffer[++i].x = 1280.0f * 0.94f; staticLinesBuffer[i].y = 720.0f * 0.5f + 720.0f * 0.15f * ( (float)( j + 1 ) / 6.0f - 0.5f ); } } */ mStaticLinesCount = i + 1; for ( uint32_t i = 0; i < mStaticLinesCount; i++ ) { Vector2f pos = VR_Distort( Vector2f( staticLinesBuffer[i].x, staticLinesBuffer[i].y ) ); staticLinesBuffer[i].x = pos.x; staticLinesBuffer[i].y = pos.y; staticLinesBuffer[i].color = 0xFFFFFFFF; } glGenBuffers( 1, &mStaticLinesVBO ); glBindBuffer( GL_ARRAY_BUFFER, mStaticLinesVBO ); glBufferData( GL_ARRAY_BUFFER, sizeof(staticLinesBuffer), staticLinesBuffer, GL_STATIC_DRAW ); } }
39,694
C++
.cpp
875
42.181714
221
0.645031
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,829
Config.h
dridri_bcflight/controller_rc/Config.h
/* * 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/>. **/ #ifndef CONFIG_H #define CONFIG_H #include <string> #include <vector> #include <map> extern "C" { #include <luajit.h> #include <lua.h> #include <lualib.h> #include <lauxlib.h> }; class Config { public: Config( const std::string& filename ); ~Config(); void Reload(); void Save(); std::string string( const std::string& name, const std::string& def = "" ); int integer( const std::string& name, int def = 0 ); float number( const std::string& name, float def = 0.0f ); bool boolean( const std::string& name, bool def = false ); std::vector<int> integerArray( const std::string& name ); void DumpVariable( const std::string& name, int index = -1, int indent = 0 ); const bool setting( const std::string& name, const bool def ) const; const int setting( const std::string& name, const int def ) const; const float setting( const std::string& name, const float def ) const; const std::string& setting( const std::string& name, const std::string& def = "" ) const; void setSetting( const std::string& name, const bool v ); void setSetting( const std::string& name, const int v ); void setSetting( const std::string& name, const float v ); void setSetting( const std::string& name, const std::string& v ); void LoadSettings( const std::string& filename = "settings" ); void SaveSettings( const std::string& filename = "settings" ); std::string ReadFile(); void WriteFile( const std::string& content ); protected: std::string mFilename; lua_State* L; int LocateValue( const std::string& name ); std::map< std::string, std::string > mSettings; }; #endif // CONFIG_H
2,310
C++
.h
60
36.566667
90
0.723861
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,830
GlobalUI.h
dridri_bcflight/controller_rc/ui/GlobalUI.h
#ifndef GLOBALUI_H #define GLOBALUI_H #include <QtWidgets/QApplication> #include <Thread.h> class MainWindow; class Controller; class Config; class GlobalUI : public Thread { public: GlobalUI( Config* config, Controller* controller ); ~GlobalUI(); void Run() { while( run() ); } protected: virtual bool run(); private: QApplication* mApplication; Config* mConfig; Controller* mController; MainWindow* mMainWindow; }; #endif // GLOBALUI_H
454
C++
.h
22
18.909091
52
0.778302
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,831
MainWindow.h
dridri_bcflight/controller_rc/ui/MainWindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QtWidgets/QMainWindow> #include <QtCore/QTimer> #include <ControllerClient.h> namespace Ui { class MainWindow; class PageMain; class PageCalibrate; class PageCamera; class PageNetwork; class PageSettings; } class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow( Controller* controller ); ~MainWindow(); public slots: void Update(); void Home(); void Calibrate(); void Network(); void Camera(); void Settings(); void CalibrateGyro(); void CalibrateIMU(); void MotorsBeep(); void ResetBattery(); void CalibrationReset(); void CalibrationApply(); void VideoBrightnessIncrease(); void VideoBrightnessDecrease(); void VideoContrastIncrease(); void VideoContrastDecrease(); void VideoSaturationIncrease(); void VideoSaturationDecrease(); void VideoWhiteBalance(); void VideoLockWhiteBalance(); void VideoExposureMode(); void VideoIsoIncrease(); void VideoIsoDecrease(); // void VideoIsoAuto(); void VideoShutterSpeedIncrease(); void VideoShutterSpeedDecrease(); void VideoShutterSpeedAuto(); void SimulatorMode( bool enabled ); void VTXUpdate(); void VTXReset(); void VTXSet(); private: void CameraUpdateLensShader( bool send = true ); ControllerClient* mController; QTimer* mUpdateTimer; Ui::MainWindow* ui; Ui::PageMain* uiPageMain; Ui::PageCalibrate* uiPageCalibrate; Ui::PageCamera* uiPageCamera; Ui::PageNetwork* uiPageNetwork; Ui::PageSettings* uiPageSettings; QWidget* mPageMain; QWidget* mPageCalibrate; QWidget* mPageCamera; QWidget* mPageNetwork; QWidget* mPageSettings; typedef struct { uint16_t min; uint16_t center; uint16_t max; } CalibrationValues; CalibrationValues mCalibrationValues[4]; typedef struct { Controller::CameraLensShaderColor r; Controller::CameraLensShaderColor g; Controller::CameraLensShaderColor b; uint8_t grid[4 * 52 * 39]; } CameraLensShader; CameraLensShader mCameraLensShader; }; #endif // MAINWINDOW_H
1,990
C++
.h
81
22.493827
49
0.798417
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,832
MCP320x.h
dridri_bcflight/controller_rc/ADCs/MCP320x.h
/* * 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/>. **/ #ifndef MCP320X_H #define MCP320X_H #include <stdint.h> #include <SPI.h> #include <map> class MCP320x { public: MCP320x( const std::string& devfile ); ~MCP320x(); void setSmoothFactor( uint8_t channel, float f ); uint16_t Read( uint8_t channel, float dt = 0.0f ); private: SPI* mSPI; std::map< uint8_t, float > mSmoothFactor; std::map< uint8_t, float > mLastValue; }; #endif // MCP320X_H
1,116
C++
.h
35
30
72
0.740465
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,833
Socket.h
dridri_bcflight/controller_rc/boards/rpi/Socket.h
#ifndef SOCKET_H #define SOCKET_H #include <string> #include <netinet/in.h> namespace rpi { class Socket { public: typedef enum { Server, Client } SocketType; typedef enum { TCP, UDP, UDPLite } PortType; Socket(); Socket( uint16_t port, PortType type = TCP ); Socket( const std::string& host, uint16_t port, PortType type = TCP ); ~Socket(); bool isConnected() const; int Connect(); Socket* WaitClient(); int Receive( void* buf, uint32_t len, int32_t timeout = -1 ); int Send( const void* buf, uint32_t len, int32_t timeout = -1 ); protected: SocketType mSocketType; std::string mHost; uint16_t mPort; PortType mPortType; int mSocket; struct sockaddr_in mSin; struct sockaddr_in mClientSin; }; } // namespace rpi #endif // SOCKET_H
771
C++
.h
37
18.783784
71
0.726897
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,834
GPIO.h
dridri_bcflight/controller_rc/boards/rpi/GPIO.h
/* * 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/>. **/ #ifndef GPIO_H #define GPIO_H #include <stdint.h> #include <list> #include <map> #include <functional> class GPIO { public: typedef enum { Input, Output, Alt0=4, Alt1=5, Alt2=6, Alt3=7, Alt4=3, Alt5=2 } Mode; typedef enum { PullOff = 0, PullDown = 1, PullUp = 2, } PUDMode; typedef enum { Falling = 1, Rising = 2, Both = 3, } ISRMode; static void setPUD( int pin, PUDMode mode ); static void setMode( int pin, Mode mode ); static void setPWM( int pin, int initialValue, int pwmRange ); static void Write( int pin, bool en ); static bool Read( int pin ); static void SetupInterrupt( int pin, GPIO::ISRMode mode, std::function<void()> fct ); private: static std::map< int, std::list<std::pair<std::function<void()>,GPIO::ISRMode>> > mInterrupts; static void* ISR( void* argp ); }; #endif // GPIO_H
1,558
C++
.h
57
25.175439
95
0.719064
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,835
ControllerClient.h
dridri_bcflight/controller_rc/boards/rpi/ControllerClient.h
/* * 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/>. **/ #ifndef CONTROLLERPI_H #define CONTROLLERPI_H #include "../../libcontroller/Controller.h" #include <Link.h> #include "../../ADCs/MCP320x.h" #include "../../libcontroller/Filter.h" namespace rpi { class Socket; } class ControllerClient : public Controller { public: ControllerClient( Config* config, Link* link, bool spectate = false ); ~ControllerClient(); class Joystick { public: Joystick() : mADC( nullptr ), mADCChannel( 0 ), mCalibrated( false ), mInverse( false ), mThrustMode( false ), mMin( 0 ), mCenter( 0 ), mMax( 0 ), mLastRaw( 0 ), mFilter( nullptr ) {} Joystick( MCP320x* adc, int id, int channel, bool inverse = false, bool thrust_mode = false ); ~Joystick(); uint16_t ReadRaw( float dt ); uint16_t LastRaw() const { return mLastRaw; } float Read( float dt ); void SetCalibratedValues( uint16_t min, uint16_t center, uint16_t max ); void setFilter( Filter<float>* filter ) { mFilter = filter; } uint16_t max() const { return mMax; } uint16_t center() const { return mCenter; } uint16_t min() const { return mMin; } private: MCP320x* mADC; int mId; int mADCChannel; bool mCalibrated; bool mInverse; bool mThrustMode; uint16_t mMin; uint16_t mCenter; uint16_t mMax; uint16_t mLastRaw; Filter<float>* mFilter; }; Joystick* joystick( int x ) { return &mJoysticks[x]; } uint16_t rawThrust( float dt ) { return mJoysticks[0].ReadRaw( dt ); } uint16_t rawYaw( float dt ) { return mJoysticks[1].ReadRaw( dt ); } uint16_t rawRoll( float dt ) { return mJoysticks[3].ReadRaw( dt ); } uint16_t rawPitch( float dt ) { return mJoysticks[2].ReadRaw( dt ); } void SaveThrustCalibration( uint16_t min, uint16_t center, uint16_t max ); void SaveYawCalibration( uint16_t min, uint16_t center, uint16_t max ); void SavePitchCalibration( uint16_t min, uint16_t center, uint16_t max ); void SaveRollCalibration( uint16_t min, uint16_t center, uint16_t max ); bool SimulatorMode( bool enabled ); protected: virtual bool run(); bool RunSimulator(); float ReadThrust( float dt ); float ReadRoll( float dt ); float ReadPitch( float dt ); float ReadYaw( float dt ); int8_t ReadSwitch( uint32_t id ); static Config* mConfig; MCP320x* mADC; Joystick mJoysticks[4]; bool mSimulatorEnabled; HookThread<ControllerClient>* mSimulatorThread; rpi::Socket* mSimulatorSocketServer; rpi::Socket* mSimulatorSocket; uint64_t mSimulatorTicks; }; #endif // CONTROLLERPI_H
3,176
C++
.h
96
30.666667
96
0.72671
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,836
SPI.h
dridri_bcflight/controller_rc/boards/rpi/SPI.h
/* * 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/>. **/ #ifndef SPI_H #define SPI_H #include <stdint.h> #include <list> #include <string> #include <linux/spi/spidev.h> class SPI { public: SPI( const std::string& device, uint32_t speed_hz = 500000 ); ~SPI(); int Transfer( void* tx, void* rx, uint32_t len ); private: int mFD; int mBitsPerWord; struct spi_ioc_transfer mXFer[10]; }; #endif
1,059
C++
.h
35
28.4
72
0.743615
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,837
ControllerClient.h
dridri_bcflight/controller_rc/boards/generic/ControllerClient.h
/* * 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/>. **/ #ifndef CONTROLLERPI_H #define CONTROLLERPI_H #include <Controller.h> #include <Link.h> class ControllerClient : public Controller { public: ControllerClient( Config* config, Link* link, bool spectate = false ); ~ControllerClient(); protected: virtual bool run(); }; #endif // CONTROLLERPI_H
1,015
C++
.h
30
31.966667
72
0.760204
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,838
BlackBox.h
dridri_bcflight/flight/BlackBox.h
#ifndef BLACKBOX_H #define BLACKBOX_H #include <Thread.h> #include <mutex> #include "Config.h" #include "Vector.h" using namespace STD; LUA_CLASS class BlackBox : public Thread { public: LUA_EXPORT BlackBox(); ~BlackBox(); const uint32_t id() const; LUA_EXPORT void Enqueue( const string& data, const string& value ); template<typename T, int n> void Enqueue( const string& data, const Vector<T, n>& v ); void Enqueue( const string* data, const string* values, int n ); void Enqueue( const char* data[], const char* values[], int n ); template<typename T, int n> void Enqueue( const string* data, const Vector<T, n>* values, int m ) { if ( this == nullptr or not Thread::running() ) { return; } for ( int i = 0; i < m; i++ ) { Enqueue( data[i], values[i] ); } } LUA_PROPERTY("enabled") void Start( bool enabled = true ); protected: virtual bool run(); uint32_t mID; FILE* mFile; #ifdef SYSTEM_NAME_Linux mutex mQueueMutex; #endif list< string > mQueue; }; #endif // BLACKBOX_H
1,014
C++
.h
36
26.138889
100
0.698969
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,839
Vector.h
dridri_bcflight/flight/Vector.h
/* * 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/>. **/ #ifndef VECTOR_H #define VECTOR_H #include <cmath> #include <Lua.h> #define VECTOR_INLINE inline // #define VECTOR_INLINE #define VEC_OP( r, a, op, b ) \ r x = a x op b x; \ if ( n > 1 ) { \ r y = a y op b y; \ if ( n > 2 ) { \ r z = a z op b z; \ if ( n > 3 ) { \ r w = a w op b w; \ } \ } \ } #define VEC_IM( r, a, op, im ) \ r x = a x op im; \ if ( n > 1 ) { \ r y = a y op im; \ if ( n > 2 ) { \ r z = a z op im; \ if ( n > 3 ) { \ r w = a w op im; \ } \ } \ } #define VEC_ADD( r, a, op, b ) \ r += a x op b x; \ if ( n > 1 ) { \ r += a y op b y; \ if ( n > 2 ) { \ r += a z op b z; \ if ( n > 3 ) { \ r += a w op b w; \ } \ } \ } #define VEC_ADD_IM( r, a, op, im ) \ r += a x op im; \ if ( n > 1 ) { \ r += a y op im; \ if ( n > 2 ) { \ r += a z op im; \ if ( n > 3 ) { \ r += a w op im; \ } \ } \ } template <typename T, int n> class Vector { public: Vector() : x(0), y(0), z(0), w(0) {} Vector( T x ) : x(x), y(x), z(x), w(x) {} Vector( T x, T y ) : x(x), y(y), z(x), w(y) {} Vector( T x, T y, T z ) : x(x), y(y), z(z), w(0) {} Vector( T x, T y, T z, T w ) : x(x), y(y), z(z), w(w) {} Vector( const Vector<T,1>& v, T a = 0, T b = 0, T c = 0 ) : x(v.x), y(a), z(b), w(c) {} Vector( T a, const Vector<T,1>& v, T b = 0, T c = 0 ) : x(a), y(v.x), z(b), w(c) {} Vector( T a, T b, const Vector<T,1>& v, T c = 0 ) : x(a), y(b), z(v.x), w(c) {} Vector( T a, T b, T c, const Vector<T,1>& v ) : x(a), y(b), z(c), w(v.x) {} Vector( const Vector<T,2>& v, T a = 0, T b = 0 ) : x(v.x), y(v.z), z(a), w(b) {} Vector( T a, const Vector<T,2>& v, T b = 0 ) : x(a), y(v.x), z(v.y), w(b) {} Vector( T a, T b, const Vector<T,2>& v ) : x(a), y(b), z(v.x), w(v.y) {} Vector( const Vector<T,3>& v, T a = 0 ) : x(v.x), y(v.y), z(v.z), w(a) {} Vector(T a, const Vector<T,3>& v ) : x(a), y(v.x), z(v.y), w(v.z) {} Vector( const Vector<T,4>& v ) : x(v.x), y(v.y), z(v.z), w(v.w) {} Vector( float* v ) : x(v[0]), y(v[1]), z(v[2]), w(v[3]) {} explicit Vector( const LuaValue& v ) { if ( v.type() == LuaValue::Table ) { const std::map<std::string, LuaValue >& t = v.toTable(); try { x = t.at("x").toNumber(); y = t.at("y").toNumber(); z = t.at("z").toNumber(); w = t.at("w").toNumber(); } catch ( std::exception& e ) { } } } VECTOR_INLINE Vector<T,3> xyz() const { return Vector<T,3>( x, y, z ); } VECTOR_INLINE Vector<T,3> zyx() const { return Vector<T,3>( z, y, x ); } VECTOR_INLINE Vector<T,2> xy() const { return Vector<T,2>( x, y ); } VECTOR_INLINE Vector<T,2> xz() const { return Vector<T,2>( x, z ); } VECTOR_INLINE Vector<T,2> yz() const { return Vector<T,2>( y, z ); } constexpr int size() const { return n; } Vector<T,n>& operator=( const Vector< T, n >& other ) { VEC_IM( this-> , other. , + , 0 ); return *this; } Vector<T,n>& operator=( const T& v ) { for ( int i = 0; i < n; i++ ) { ptr[i] = v; } return *this; } void normalize() { T add = 0; VEC_ADD( add, this-> , * , this-> ); T l = sqrt( add ); if ( l > 0.00001f ) { T il = 1 / l; VEC_IM( this-> , this-> , * , il ); } } Vector<T,n> normalized() { Vector<T,n> ret; T add = 0; VEC_ADD( add, this-> , * , this-> ); T l = sqrt( add ); if ( l > 0.00001f ) { T il = 1 / l; VEC_IM( ret. , this-> , * , il ); } return ret; } T length() const { T add = 0; VEC_ADD( add, this-> , * , this-> ); return sqrt( add ); } VECTOR_INLINE T operator[]( int i ) const { return ptr[i]; } VECTOR_INLINE T& operator[]( int i ) { return ptr[i]; } VECTOR_INLINE void operator+=( const Vector<T,n>& v ) { VEC_OP( this-> , this-> , + , v. ); } VECTOR_INLINE void operator-=( const Vector<T,n>& v ) { VEC_OP( this-> , this-> , - , v. ); } VECTOR_INLINE void operator*=( T v ) { VEC_IM( this-> , this-> , * , v ); } VECTOR_INLINE void operator/=( T v ) { VEC_IM( this-> , this-> , / , v ); } VECTOR_INLINE void operator/=( const Vector<T,n>& v ) { VEC_OP( this-> , this-> , / , v. ); } VECTOR_INLINE Vector<T,n> operator-() const { Vector<T, n> ret; VEC_IM( ret. , - this-> , + , 0.0f ); return ret; } VECTOR_INLINE Vector<T,n> operator+( const Vector<T,n>& v ) const { Vector<T, n> ret; VEC_OP( ret. , this-> , + , v. ); return ret; } VECTOR_INLINE Vector<T,n> operator-( const Vector<T,n>& v ) const { Vector<T, n> ret; VEC_OP( ret. , this-> , - , v. ); return ret; } VECTOR_INLINE Vector<T,n> operator*( T im ) const { Vector<T, n> ret; VEC_IM( ret. , this-> , * , im ); return ret; } VECTOR_INLINE Vector<T,n> operator/( T im ) const { Vector<T, n> ret; VEC_IM( ret. , this-> , / , im ); return ret; } VECTOR_INLINE Vector<T,n> operator/( const Vector<T,n>& v ) const { Vector<T, n> ret; VEC_OP( ret. , this-> , / , v. ); return ret; } VECTOR_INLINE T operator&( const Vector<T,n>& v ) const { T ret = 0; VEC_ADD( ret, this-> , * , v. ); return ret; } VECTOR_INLINE Vector<T,n> operator*( const Vector<T,n>& v ) const { Vector<T,n> ret; VEC_OP( ret., this-> , * , v. ); return ret; } VECTOR_INLINE Vector<T,n> operator^( const Vector<T,n>& v ) const { Vector<T, n> ret; for ( int i = 0; i < n; i++ ) { T a = ptr[ ( i + 1 ) % n ]; T b = v.ptr[ ( i + 2 ) % n ]; T c = ptr[ ( i + 2 ) % n ]; T d = v.ptr[ ( i + 1 ) % n ]; ret.ptr[i] = a * b - c * d; } return ret; } friend std::ostream& operator<<(std::ostream& os, const Vector<T, n>& v) { os << "["; for ( int i = 0; i < n; i++ ) { os << v.ptr[i]; if ( i < n - 1 ) { os << ", "; } } os << "]"; return os; } public: union { struct { T x; T y; T z; T w; }; T ptr[std::max(n, 4)]; }; }; template <typename T, int n> Vector<T, n> operator*( T im, const Vector<T, n>& v ) { Vector<T, n> ret; for ( int i = 0; i < n; i++ ) { ret.ptr[i] = im * v.ptr[i]; } return ret; } template <typename T, int n> Vector<T, n> operator/( T im, const Vector<T, n>& v ) { Vector<T, n> ret; for ( int i = 0; i < n; i++ ) { ret.ptr[i] = im / v.ptr[i]; } return ret; } template <typename T, int n> bool operator==( const Vector<T, n>& v1, const Vector<T,n>& v2 ) { bool ret = true; for ( int i = 0; i < n; i++ ) { ret = ret && ( v1.ptr[i] == v2.ptr[i] ); } return ret; } template <typename T, int n> bool operator!=( const Vector<T, n>& v1, const Vector<T,n>& v2 ) { bool ret = true; for ( int i = 0; i < n; i++ ) { ret = ret && ( v1.ptr[i] != v2.ptr[i] ); } return ret; } namespace std { template <typename T, int n> Vector<T, n> cos( const Vector<T, n>& v ) { Vector<T, n> ret; for ( int i = 0; i < n; i++ ) { ret.ptr[i] = std::cos( v.ptr[i] ); } return ret; } template <typename T, int n> Vector<T, n> sin( const Vector<T, n>& v ) { Vector<T, n> ret; for ( int i = 0; i < n; i++ ) { ret.ptr[i] = std::sin( v.ptr[i] ); } return ret; } }; typedef Vector<int, 2> Vector2i; typedef Vector<int, 3> Vector3i; typedef Vector<int, 4> Vector4i; typedef Vector<float, 2> Vector2f; typedef Vector<float, 3> Vector3f; typedef Vector<float, 4> Vector4f; typedef Vector<double, 2> Vector2d; typedef Vector<double, 3> Vector3d; typedef Vector<double, 4> Vector4d; template<typename T> struct is_vector : std::false_type {}; template<typename T, int n> struct is_vector<Vector<T, n>> : std::true_type {}; #endif // VECTOR_H
8,152
C++
.h
296
24.837838
95
0.540118
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,840
Controller.h
dridri_bcflight/flight/Controller.h
/* * 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/>. **/ #ifndef CONTROLLER_H #define CONTROLLER_H #include <mutex> #include <map> #include <functional> #include <Thread.h> #include "Vector.h" #include "ControllerBase.h" #include "Lua.h" using namespace STD; class Main; class Link; LUA_CLASS class Controller : public ControllerBase, public Thread { public: LUA_EXPORT Controller(); ~Controller(); Link* link() const; void Start(); bool connected() const; // bool armed() const; uint32_t ping() const; // float thrust() const; // const Vector3f& RPY() const; LUA_EXPORT void onEvent( ControllerBase::Cmd cmdId, const std::function<void(const LuaValue& v)>& f ); void UpdateSmoothControl( const float& dt ); void Emergency(); void SendDebug( const string& s ); protected: virtual bool run(); bool TelemetryRun(); uint32_t crc32( const uint8_t* buf, uint32_t len ); void Arm(); void Disarm(); float setRoll( float value, bool raw = false ); float setPitch( float value, bool raw = false ); float setYaw( float value, bool raw = false ); float setThrust( float value, bool raw = false ); Main* mMain; #ifdef SYSTEM_NAME_Linux mutex mSendMutex; #endif bool mTimedOut; // bool mArmed; uint32_t mPing; LUA_PROPERTY("expo") Vector4f mExpo; LUA_PROPERTY("thrust_expo") Vector2f mThrustExpo; /* Vector3f mRPY; float mThrust; float mThrustAccum; */ Vector3f mSmoothRPY; uint64_t mTicks; HookThread< Controller >* mTelemetryThread; uint64_t mTelemetryTick; uint64_t mTelemetryCounter; uint64_t mEmergencyTick; LUA_PROPERTY("telemetry_rate") uint32_t mTelemetryFrequency; LUA_PROPERTY("full_telemetry") bool mTelemetryFull; std::map<uint16_t, std::function<void(const LuaValue& v)>> mEvents; }; #endif // CONTROLLER_H
2,417
C++
.h
80
28.3625
103
0.754303
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,841
Matrix.h
dridri_bcflight/flight/Matrix.h
/* * 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/>. **/ #ifndef MATRIX_H #define MATRIX_H #include "Vector.h" class Matrix { public: Matrix( int w = 4, int h = 4 ); Matrix( const Matrix& other ); virtual ~Matrix(); void Orthogonal( float left, float right, float bottom, float top, float zNear, float zFar ); float operator()( int x, int y ) const { return m[y * mWidth + x]; } float* data(); const float* constData() const; const int width() const; const int height() const; void Clear(); void Identity(); void RotateX( float a ); void RotateY( float a ); void RotateZ( float a ); Matrix Transpose(); Matrix Inverse(); void operator*=( const Matrix& other ); void operator=( const Matrix& other ); // protected: public: float* m; protected: int mWidth; int mHeight; }; Matrix operator+( const Matrix& m1, const Matrix& m2 ); Matrix operator-( const Matrix& m1, const Matrix& m2 ); Matrix operator*( const Matrix& m1, const Matrix& m2 ); Vector4f operator*( const Matrix& m, const Vector4f& v ); #endif // MATRIX_H
1,709
C++
.h
55
29.090909
94
0.726553
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,842
Console.h
dridri_bcflight/flight/Console.h
#ifndef CONSOLE_H #define CONSOLE_H #include <Thread.h> class Config; class Console : public Thread { public: Console( Config* config ); ~Console(); protected: virtual bool run(); bool alnum( char c ); bool luavar( char c ); Config* mConfig; vector<string> mFullHistory; }; #endif // CONSOLE_H
307
C++
.h
17
16.294118
29
0.742958
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,843
Config.h
dridri_bcflight/flight/Config.h
/* * 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/>. **/ #ifndef CONFIG_H #define CONFIG_H #include <string> #include <vector> #include <map> #include <Lua.h> using namespace STD; class Config { public: Config( const string& filename, const string& settings_filename = "" ); ~Config(); void Reload(); void Apply(); void Save(); void Execute( const string& code, bool silent = false ); string String( const string& name, const string& def = "" ); int Integer( const string& name, int def = 0 ); float Number( const string& name, float def = 0.0f ); bool Boolean( const string& name, bool def = false ); void* Object( const string& name, void* def = nullptr ); template<typename T> T* Object( const string& name, void* def = nullptr ) { return static_cast<T*>( Object( name, def ) ); } vector<int> IntegerArray( const string& name ); string DumpVariable( const string& name, int index = -1, int indent = 0 ); int ArrayLength( const string& name ); void setBoolean( const string& name, const bool v ); void setInteger( const string& name, const int v ); void setNumber( const string& name, const float v ); void setString( const string& name, const string& v ); string ReadFile(); void WriteFile( const string& content ); Lua* luaState() const; protected: int LocateValue( const string& name ); string mFilename; string mSettingsFilename; // lua_State* L; map< string, string > mSettings; Lua* mLua; }; #endif // CONFIG_H
2,122
C++
.h
60
33.3
76
0.727406
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,845
Main.h
dridri_bcflight/flight/Main.h
/* * 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/>. **/ #ifndef MAIN_H #define MAIN_H #include <stdint.h> #include <Board.h> #include "Debug.h" #include "PowerThread.h" #include "BlackBox.h" #include "Vector.h" #include "string" using namespace STD; class Config; class Console; class IMU; class Stabilizer; class Frame; class Controller; class Camera; class HUD; class Microphone; class Recorder; class Main { public: static int flight_entry( int ac, char** av ); Main(); ~Main(); const bool ready() const; string getRecordingsList() const; uint32_t loopFrequency() const; Config* config() const; Board* board() const; PowerThread* powerThread() const; BlackBox* blackbox() const; IMU* imu() const; Stabilizer* stabilizer() const; Frame* frame() const; Controller* controller() const; Camera* camera() const; HUD* hud() const; Microphone* microphone() const; const string& cameraType() const; const string& username() const; static string base64_encode( const uint8_t* buf, uint32_t size ); static Main* instance(); private: int flight_register(); void DetectDevices(); bool StabilizerThreadRun(); static Main* mInstance; bool mReady; HookThread< Main >* mStabilizerThread; uint32_t mLoopTime; uint64_t mTicks; uint64_t mWaitTicks; uint64_t mLPSTicks; uint32_t mLPS; uint32_t mLPSCounter; Config* mConfig; Console* mConsole; Board* mBoard; PowerThread* mPowerThread; BlackBox* mBlackBox; IMU* mIMU; Stabilizer* mStabilizer; Frame* mFrame; Controller* mController; Camera* mCamera; HUD* mHUD; Microphone* mMicrophone; Recorder* mRecorder; string mCameraType; string mUsername; }; #endif
2,306
C++
.h
91
23.472527
72
0.764759
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,846
PowerThread.h
dridri_bcflight/flight/PowerThread.h
/* * 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/>. **/ #ifndef POWERTHREAD_H #define POWERTHREAD_H #include <mutex> #include <vector> #include <Thread.h> using namespace STD; class Main; class Sensor; class PowerThread : public Thread { public: PowerThread( Main* main ); ~PowerThread(); void ResetFullBattery( uint32_t capacity_mah = 2500 ); float VBat() const; float CurrentTotal() const; float CurrentDraw() const; float BatteryLevel() const; protected: virtual bool run(); private: typedef enum { NONE = 0, VOLTAGE, CURRENT } SensorType; typedef struct { SensorType type; Sensor* sensor; int channel; float shift; float multiplier; } BatterySensor; Main* mMain; float mLowVoltageValue; int32_t mLowVoltageBuzzerPin; vector< uint32_t > mLowVoltageBuzzerPattern; uint64_t mLowVoltageTick; uint32_t mLowVoltagePatternCase; uint64_t mSaveTicks; uint64_t mTicks; uint32_t mCellsCount; float mLastVBat; float mVBat; float mCurrentTotal; float mCurrentDraw; float mBatteryLevel; float mBatteryCapacity; #ifdef SYSTEM_NAME_Linux mutex mCapacityMutex; #endif BatterySensor mVoltageSensor; BatterySensor mCurrentSensor; }; #endif // POWERTHREAD_H
1,861
C++
.h
72
23.75
72
0.779594
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,847
FilterChain.h
dridri_bcflight/flight/stabilizer/FilterChain.h
#pragma once #include <Vector.h> #include <Lua.h> #include <Debug.h> #include "Filter.h" template<typename V> class FilterChain : public Filter<V> { public: FilterChain() : mState( V() ) { fDebug(); } FilterChain( const std::list<Filter<V>*>& filters ) : mFilters( filters ), mState( V() ) { fDebug( mFilters.size() ); } virtual V filter( const V& input, float dt ) { V value = input; for ( auto f : mFilters ) { value = f->filter( value, dt ); } mState = value; return value; } virtual V state() { return mState; } const std::list< Filter<V>* >& filters() const { return mFilters; } protected: std::list< Filter<V>* > mFilters; V mState; }; LUA_CLASS class FilterChain_1 : public FilterChain<float> { public: LUA_EXPORT FilterChain_1( const LuaValue& filters ) : FilterChain( filters ) {} }; LUA_CLASS class FilterChain_2 : public FilterChain<Vector2f> { public: LUA_EXPORT FilterChain_2( const LuaValue& filters ) : FilterChain( filters ) {} }; LUA_CLASS class FilterChain_3 : public FilterChain<Vector3f> { public: LUA_EXPORT FilterChain_3( const LuaValue& filters ) : FilterChain( filters ) {} };
1,142
C++
.h
45
23.466667
91
0.702479
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,848
Stabilizer.h
dridri_bcflight/flight/stabilizer/Stabilizer.h
/* * 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/>. **/ #ifndef STABILIZER_H #define STABILIZER_H #include <Frame.h> #include "PID.h" class Main; LUA_CLASS class Stabilizer { public: typedef enum { Rate = 0, Stabilize = 1, ReturnToHome = 2, Follow = 3, } Mode; LUA_EXPORT Stabilizer(); ~Stabilizer(); virtual void setRollP( float p ); virtual void setRollI( float i ); virtual void setRollD( float d ); Vector3f getRollPID() const; virtual void setPitchP( float p ); virtual void setPitchI( float i ); virtual void setPitchD( float d ); Vector3f getPitchPID() const; virtual void setYawP( float p ); virtual void setYawI( float i ); virtual void setYawD( float d ); Vector3f getYawPID() const; virtual Vector3f lastPIDOutput() const; virtual void setHorizonOffset( const Vector3f& v ); virtual Vector3f horizonOffset() const; virtual void setMode( uint32_t mode ); virtual uint32_t mode() const; virtual void setAltitudeHold( bool enabled ); virtual bool altitudeHold() const; virtual bool armed() const; virtual float thrust() const; virtual const Vector3f& RPY() const; virtual const Vector3f& filteredRPYDerivative() const; virtual void Arm(); virtual void Disarm(); virtual void setRoll( float value ); virtual void setPitch( float value ); virtual void setYaw( float value ); virtual void setThrust( float value ); virtual void CalibrateESCs(); virtual void MotorTest(uint32_t id); virtual void Reset( const float& yaw ); virtual void Update( IMU* imu, float dt ); Frame* frame() const; void setFrame( Frame* frame ); protected: Main* mMain; LUA_PROPERTY("frame") Frame* mFrame; Mode mMode; LUA_PROPERTY("rate_speed") float mRateFactor; bool mAltitudeHold; LUA_PROPERTY("pid_roll") PID<float> mRateRollPID; LUA_PROPERTY("pid_pitch") PID<float> mRatePitchPID; LUA_PROPERTY("pid_yaw") PID<float> mRateYawPID; LUA_PROPERTY("pid_horizon_roll") PID<float> mRollHorizonPID; LUA_PROPERTY("pid_horizon_pitch") PID<float> mPitchHorizonPID; PID<float> mAltitudePID; float mAltitudeControl; LUA_PROPERTY("derivative_filter") Filter<Vector3f>* mDerivativeFilter; LUA_PROPERTY("tpa.multiplier") float mTPAMultiplier; LUA_PROPERTY("tpa.threshold") float mTPAThreshold; LUA_PROPERTY("anti_gravity.gain") float mAntiGravityGain; LUA_PROPERTY("anti_gravity.threshold") float mAntiGravityThreshold; LUA_PROPERTY("anti_gravity.decay") float mAntiGravityDecay; float mAntigravityThrustAccum; bool mArmed; Vector4f mExpo; Vector3f mRPY; Vector3f mFilteredRPYDerivative; float mThrust; float mPreviousThrust; int mLockState; LUA_PROPERTY("horizon_angles") Vector3f mHorizonMultiplier; LUA_PROPERTY("horizon_offset") Vector3f mHorizonOffset; LUA_PROPERTY("horizon_max_rate") Vector3f mHorizonMaxRate; }; #endif // STABILIZER_H
3,460
C++
.h
100
32.49
72
0.77236
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,849
EKF.h
dridri_bcflight/flight/stabilizer/EKF.h
/* * 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/>. **/ #ifndef EKF_H #define EKF_H #include <Matrix.h> class EKF { public: EKF( uint32_t n_inputs, uint32_t n_outputs ); ~EKF(); void setInputFilter( uint32_t row, float filter ); void setOutputFilter( uint32_t row, float filter ); void setSelector( uint32_t input_row, uint32_t output_row, float selector ); Vector4f state( uint32_t offset ) const; void UpdateInput( uint32_t row, float input ); void Process( float dt ); void DumpInput(); protected: uint32_t mInputsCount; uint32_t mOutputsCount; Matrix mQ; Matrix mR; Matrix mC; Matrix mSigma; Matrix mInput; Matrix mState; }; #endif // EKF_H
1,329
C++
.h
43
28.883721
77
0.750979
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,850
MahonyAHRS.h
dridri_bcflight/flight/stabilizer/MahonyAHRS.h
#pragma once #include "SensorFusion.h" #include <Vector.h> #include <Quaternion.h> #include <Matrix.h> #include "Lua.h" LUA_CLASS class MahonyAHRS : public SensorFusion<Vector3f> { public: LUA_EXPORT MahonyAHRS( float kp, float ki ); virtual ~MahonyAHRS(); virtual void UpdateInput( uint32_t row, const Vector3f& input ); virtual void Process( float dt ); virtual const Vector3f& state() const; protected: void computeMatrix(); Matrix mRotationMatrix; Quaternion mState; Vector3f mFinalState; Vector3f mIntegral; std::vector<Vector3f> mInputs; float mKp; float mKi; };
586
C++
.h
24
22.708333
65
0.781362
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,851
PT1.h
dridri_bcflight/flight/stabilizer/PT1.h
#pragma once #include "Lua.h" #include "Filter.h" #include "Debug.h" LUA_CLASS template<typename V> class PT1 : public Filter<V> { public: PT1( const V& cutoff ) : mCutOff( cutoff ), mState( V() ) { fDebug( V( cutoff ) ); } PT1( const LuaValue& cutoff ) : mCutOff( V(cutoff) ), mState( V() ) { fDebug( V( cutoff ) ); } virtual V filter( const V& input, float dt ) { V RC = 1.0f / ( float(2.0f * M_PI) * mCutOff ); V coeff = dt / ( RC + dt ); mState += coeff * ( input - mState ); return mState; } virtual V state() { return mState; } protected: V mCutOff; V mState; }; LUA_CLASS class PT1_1 : public PT1<float> { public: LUA_EXPORT PT1_1( float cutoff ) : PT1( cutoff ) {} }; LUA_CLASS class PT1_2 : public PT1<Vector2f> { public: LUA_EXPORT PT1_2( float cutoff_x, float cutoff_y ) : PT1( Vector2f( cutoff_x, cutoff_y ) ) {} }; LUA_CLASS class PT1_3 : public PT1<Vector3f> { public: LUA_EXPORT PT1_3( float cutoff_x, float cutoff_y, float cutoff_z ) : PT1( Vector3f( cutoff_x, cutoff_y, cutoff_z ) ) {} };
1,041
C++
.h
41
23.536585
120
0.653226
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,852
BiquadFilter.h
dridri_bcflight/flight/stabilizer/BiquadFilter.h
#pragma once #include "Lua.h" #include "Filter.h" #include "Debug.h" LUA_CLASS template<typename V> class BiquadFilter : public Filter<V> { public: typedef enum { LPF, NOTCH } Type; BiquadFilter( const float& q, const float& centerFreq = 0.0f ) : mType( NOTCH ) , mQ( q ) , mCenterFrequency(centerFreq) , mCenterFrequencyDtSmoothed(0) , mCenterFrequencyDtSmoothCutoff(1) , x1( V() ) , x2( V() ) , y1( V() ) , y2( V() ) { fDebug( mType, V( q ) ); } virtual V filter( const V& input, float dt ) { // mCenterFrequency = 2073; // mCenterFrequency = 100; // fDebug( input, dt ); // if ( mCenterFrequencyDtSmoothed == 0.0f ) { // mCenterFrequencyDtSmoothed = mCenterFrequency * dt; // } else { // mCenterFrequencyDtSmoothed = PT1Smooth( mCenterFrequencyDtSmoothed, mCenterFrequency * dt, dt ); // } // printf( "filter: %f, %f → %f\n", mCenterFrequency, dt, mCenterFrequencyDtSmoothed ); // V omega = 2.0f * float(M_PI) * mCenterFrequency * 0.000250f; //dt; float omega = 2.0f * float(M_PI) * mCenterFrequency * dt; // V omega = 2.0f * V(M_PI) * mCenterFrequencyDtSmoothed; float cs = std::cos( omega ); float alpha = std::sin( omega ) * ( 1.0f / ( 2.0f * mQ ) ); float a0, a1, a2; float b0, b1, b2; switch ( mType ) { case LPF: b1 = 1.0f - cs; b0 = b1 * 0.5f; b2 = b0; a0 = 1.0f + alpha; a1 = -2 * cs; a2 = 1.0f - alpha; break; case NOTCH: default: b0 = 1; b1 = -2 * cs; b2 = 1; a0 = 1.0f + alpha; a1 = b1; a2 = 1.0f - alpha; break; } float a0_inv = 1.0f / a0; b0 *= a0_inv; b1 *= a0_inv; b2 *= a0_inv; a1 *= a0_inv; a2 *= a0_inv; // printf( "coeffs : %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\n", a0, a1, a2, b0, b1, b2 ); // printf( "prev : %.2f, %.2f, %.2f, %.2f\n", x1, x2, y2, y1 ); V state = V(b0) * input + V(b1) * x1 + V(b2) * x2 - V(a1) * y1 - V(a2) * y2; bool isfinite = false; if constexpr ( std::is_same<V, float>::value ) { isfinite = std::isfinite(state); } else if constexpr ( is_vector<V>::value ) { isfinite = true; for ( uint8_t i = 0; i < state.size(); i++ ) { isfinite = isfinite && std::isfinite(state[i]); } } else { gError() << "Unhandled state type"; return input; } if ( !isfinite ) { gError() << "Numerical instability detected. Resetting state."; state = V(); x1 = V(); x2 = V(); y1 = V(); y2 = V(); return input; } x2 = x1; x1 = input; y2 = y1; y1 = state; return y1; } virtual V state() { return y1; } void setCenterFrequency( float centerFrequency, float smoothCutoff = V(1) ) { // fDebug( centerFrequency, smoothCutoff ); if ( mCenterFrequency == 0.0f ) { mCenterFrequency = centerFrequency; return; } // mCenterFrequency = centerFrequency; mCenterFrequencyDtSmoothCutoff = smoothCutoff; mCenterFrequency = PT1Smooth( mCenterFrequency, centerFrequency ); } const float centerFrequency() const { return mCenterFrequency; } protected: Type mType; float mQ; float mCenterFrequency; float mCenterFrequencyDtSmoothed; float mCenterFrequencyDtSmoothCutoff; V x1; V x2; V y1; V y2; float PT1Smooth( float state, float input ) { float gain = 2.0f * float(M_PI) * mCenterFrequencyDtSmoothCutoff; gain = 0.5f * ( gain / ( gain + 1.0f ) ); return state + gain * ( input - state ); } }; LUA_CLASS class BiquadFilter_1 : public BiquadFilter<float> { public: LUA_EXPORT BiquadFilter_1( const LuaValue& q, const LuaValue& centerFreq ) : BiquadFilter( q.toNumber(), centerFreq.toNumber() ) {} }; LUA_CLASS class BiquadFilter_2 : public BiquadFilter<Vector2f> { public: LUA_EXPORT BiquadFilter_2( const LuaValue& q, const LuaValue& centerFreq ) : BiquadFilter( q.toNumber(), centerFreq.toNumber() ) {} }; LUA_CLASS class BiquadFilter_3 : public BiquadFilter<Vector3f> { public: LUA_EXPORT BiquadFilter_3( const LuaValue& q, const LuaValue& centerFreq ) : BiquadFilter( q.toNumber(), centerFreq.toNumber() ) {} };
4,002
C++
.h
143
25
132
0.640365
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,853
Filter.h
dridri_bcflight/flight/stabilizer/Filter.h
#pragma once #include <Vector.h> template<typename V> class Filter { public: virtual ~Filter() {} virtual V filter( const V& input, float dt ) = 0; virtual V state() = 0; };
180
C++
.h
8
20.75
50
0.698225
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,854
IMU.h
dridri_bcflight/flight/stabilizer/IMU.h
/* * 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/>. **/ #ifndef IMU_H #define IMU_H #include <Main.h> #include <Vector.h> #include <EKF.h> #include <Filter.h> #include "SensorFusion.h" #include <list> #include <functional> class Gyroscope; class Accelerometer; class Magnetometer; class Altimeter; class GPS; #define IMU_RPY_SMOOTH_RATIO 0.02f LUA_CLASS class IMU { public: typedef enum { Off, Calibrating, CalibratingAll, CalibrationDone, Running } State; LUA_EXPORT IMU(); virtual ~IMU(); LUA_PROPERTY("filters.position.input") void setPositionFilterInput( const Vector3f& v ); LUA_PROPERTY("filters.position.output") void setPositionFilterOutput( const Vector3f& v ); const Vector3f acceleration() const; const Vector3f gyroscope() const; const Vector3f magnetometer() const; const State& state() const; const Vector3f RPY() const; const Vector3f dRPY() const; const Vector3f rate() const; const Vector3f velocity() const; const Vector3f position() const; const float altitude() const; const Vector3f gpsLocation() const; const float gpsSpeed() const; const uint32_t gpsSatellitesSeen() const; const uint32_t gpsSatellitesUsed() const; Filter<Vector3f>* ratesFilters() const { return mRatesFilter; } LUA_EXPORT void Recalibrate(); void RecalibrateAll(); void ResetRPY(); void ResetYaw(); void Loop( uint64_t tick, float dt ); void registerConsumer( const std::function<void(uint64_t, const Vector3f&, const Vector3f&)>& f ); protected: void Calibrate( float dt, bool all = false ); void UpdateSensors( uint64_t tick, bool gyro_only = false ); void UpdateAttitude( float dt ); void UpdateVelocity( float dt ); void UpdatePosition( float dt ); void UpdateGPS(); Main* mMain; uint32_t mSensorsUpdateSlow; bool mPositionUpdate; #ifdef SYSTEM_NAME_Linux mutex mPositionUpdateMutex; #endif LUA_PROPERTY("gyroscopes") std::list<Gyroscope*> mGyroscopes; LUA_PROPERTY("accelerometers") std::list<Accelerometer*> mAccelerometers; LUA_PROPERTY("magnetometers") std::list<Magnetometer*> mMagnetometers; LUA_PROPERTY("altimeters") std::list<Altimeter*> mAltimeters; LUA_PROPERTY("gps") std::list<GPS*> mGPSes; LUA_PROPERTY("filters.rates") Filter<Vector3f>* mRatesFilter; LUA_PROPERTY("filters.accelerometer") Filter<Vector3f>* mAccelerometerFilter; // Running states State mState; Vector3f mAcceleration; Vector3f mGyroscope; Vector3f mMagnetometer; Vector2f mGPSLocation; float mGPSSpeed; float mGPSAltitude; uint32_t mGPSSatellitesSeen; uint32_t mGPSSatellitesUsed; float mAltitudeOffset; float mProximity; Vector3f mRPY; Vector3f mdRPY; Vector3f mRate; Vector3f mAccelerationSmoothed; Vector3f mRPYOffset; Vector4f mAccelerometerOffset; // Calibration states uint32_t mCalibrationStep; uint64_t mCalibrationTimer; Vector4f mRPYAccum; Vector4f mdRPYAccum; Vector3f mGravity; // EKF mRates; // EKF mAccelerationSmoother; // EKF mAttitude; LUA_PROPERTY("filters.attitude") SensorFusion<Vector3f>* mAttitude; EKF mPosition; EKF mVelocity; Vector4f mLastAccelAttitude; Vector3f mVirtualNorth; Vector3f mLastAcceleration; uint32_t mAcroRPYCounter; // Error counters uint32_t mGyroscopeErrorCounter; std::list< std::function<void(uint64_t, const Vector3f&, const Vector3f&)> > mConsumers; }; #endif // IMU_H
3,967
C++
.h
126
29.436508
99
0.783918
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,855
SensorFusion.h
dridri_bcflight/flight/stabilizer/SensorFusion.h
#pragma once #include <stdint.h> template <typename V> class SensorFusion { public: virtual ~SensorFusion() {} virtual void UpdateInput( uint32_t row, const V& input ) = 0; virtual void Process( float dt ) = 0; virtual const V& state() const = 0; };
256
C++
.h
10
24
62
0.72541
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,856
PID.h
dridri_bcflight/flight/stabilizer/PID.h
/* * 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/>. **/ #ifndef PID_H #define PID_H #include <type_traits> #include "Vector.h" #include "PT1.h" #include "Main.h" #include "Config.h" template< typename T > class PID { public: PID() { mIntegral = 0; mLastDerivativeDelta = 0; mkPID = 0; mState = 0; mDeadBand = 0; } ~PID() { } PID( const LuaValue& v ) { if ( v.type() == LuaValue::Table ) { float kP = Main::instance()->config()->Number( "PID.pscale", 1.0f ); float kI = Main::instance()->config()->Number( "PID.iscale", 1.0f ); float kD = Main::instance()->config()->Number( "PID.dscale", 1.0f ); const std::map<std::string, LuaValue >& t = v.toTable(); mkPID.x = kP * t.at("p").toNumber(); mkPID.y = kI * t.at("i").toNumber(); mkPID.z = kD * t.at("d").toNumber(); } } void Reset() { mIntegral = 0; mLastDerivativeDelta = 0; mState = 0; } void setP( float p ) { mkPID.x = p; } void setI( float i ) { mkPID.y = i; } void setD( float d ) { mkPID.z = d; } void setDeadBand( const T& band ) { mDeadBand = band; } void Process( const T& deltaP, const T& deltaI, const T& deltaD, float dt, const Vector3f& gains = Vector3f( 1.0f, 1.0f, 1.0f ) ) { ApplyDeadBand( deltaP ); ApplyDeadBand( deltaI ); ApplyDeadBand( deltaD ); T proportional = deltaP; mIntegral += deltaI * dt; T derivative = ( deltaD - mLastDerivativeDelta ) / dt; float pGain = gains[0] * mkPID[0]; float iGain = gains[1] * mkPID[1]; float dGain = gains[2] * mkPID[2]; T output = proportional * pGain + mIntegral * iGain + derivative * dGain; mLastDerivativeDelta = deltaD; mState = output; } void Process( const T& command, const T& measured, float dt, const Vector3f& gains = Vector3f( 1.0f, 1.0f, 1.0f ) ) { T delta = command - measured; Process( delta, delta, delta, dt, gains ); } T state() const { return mState; } Vector3f getPID() const { return mkPID; } private: Vector3f ApplyDeadBand( const Vector3f& delta ) { Vector3f ret = delta; if ( abs( delta.x ) < mDeadBand.x ) { ret.x = 0.0f; } if ( abs( delta.y ) < mDeadBand.y ) { ret.y = 0.0f; } if ( abs( delta.z ) < mDeadBand.z ) { ret.z = 0.0f; } return ret; } Vector2f ApplyDeadBand( const Vector2f& delta ) { Vector2f ret = delta; if ( abs( delta.x ) < mDeadBand.x ) { ret.x = 0.0f; } if ( abs( delta.y ) < mDeadBand.y ) { ret.y = 0.0f; } return ret; } float ApplyDeadBand( const float& delta ) { float ret = delta; if ( abs( delta ) < mDeadBand ) { ret = 0.0f; } return ret; } T mIntegral; T mLastDerivativeDelta; Vector3f mkPID; T mState; T mDeadBand; }; #endif // PID_H
3,332
C++
.h
126
23.849206
132
0.657689
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,857
DynamicNotchFilter.h
dridri_bcflight/flight/stabilizer/DynamicNotchFilter.h
#pragma once #include <cassert> #include "Lua.h" #include "Filter.h" #include "Debug.h" #include <Thread.h> #include <BiquadFilter.h> typedef struct fftwf_plan_s* fftwf_plan; typedef float fftwf_complex[2]; #define DYNAMIC_NOTCH_COUNT 4 template<typename V> class _DynamicNotchFilterBase : public Filter<V> { public: _DynamicNotchFilterBase( uint8_t n ); virtual ~_DynamicNotchFilterBase() {} template<typename T, uint8_t N> Vector<T, N> filter( const Vector<T, N>& input, float dt ); virtual V state(); void Start(); template<typename T, uint8_t N> std::vector<Vector<T, N>> dftOutput() { assert(N == mN); std::vector<Vector<T, N>> ret; ret.reserve( mNumSamples / 2 + 1 ); for ( uint32_t j = 0; j < mNumSamples / 2 + 1; j++ ) { ret.push_back(Vector<T,N>()); #pragma GCC unroll 4 for ( uint8_t i = 0; i < N; i++ ) { ret[j][i] = mDFTs[i].magnitude[j]; } } return ret; } protected: typedef struct DFT { float* input; float* inputBuffer; fftwf_complex* output; fftwf_plan plan; float* magnitude; } DFT; typedef struct Peak { uint32_t dftIndex; float frequency; float magnitude; } Peak; typedef struct PeakFilter { // float centerFrequency; BiquadFilter<float>* filter; } PeakFilter; uint32_t mMinFreq; uint32_t mMaxFreq; uint8_t mN; V mState; float mFixedDt; uint32_t mNumSamples; uint32_t mSampleResolution; uint32_t mInputIndex; std::mutex mInputMutex; std::vector<DFT> mDFTs; std::vector<std::vector<PeakFilter>> mPeakFilters; HookThread<_DynamicNotchFilterBase<V>>* mAnalysisThread; bool analysisRun(); }; LUA_CLASS template<typename V> class DynamicNotchFilter : public _DynamicNotchFilterBase<V> { public: DynamicNotchFilter(); ~DynamicNotchFilter() {} void pushSample( const V& sample ); virtual V filter( const V& input, float dt ); }; // LUA_CLASS class DynamicNotchFilter_1 : public DynamicNotchFilter<float> // { // public: // LUA_EXPORT DynamicNotchFilter_1() : DynamicNotchFilter() {} // }; // // LUA_CLASS class DynamicNotchFilter_2 : public DynamicNotchFilter<Vector2f> // { // public: // LUA_EXPORT DynamicNotchFilter_2() : DynamicNotchFilter() {} // }; LUA_CLASS class DynamicNotchFilter_3 : public DynamicNotchFilter<Vector<float, 3>> { public: LUA_EXPORT DynamicNotchFilter_3(); LUA_PROPERTY("min_frequency") void setMinFrequency( uint32_t f ) { mMinFreq = f; } LUA_PROPERTY("max_frequency") void setMaxFrequency( uint32_t f ) { mMaxFreq = f; } };
2,465
C++
.h
88
25.886364
92
0.725847
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,858
DRM.h
dridri_bcflight/flight/video/DRM.h
#ifndef DRM_H #define DRM_H class DRM { public: static int drmFd(); protected: static int sDrmFd; }; #endif // DRM_H
122
C++
.h
10
10.7
20
0.743119
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,859
HUD.h
dridri_bcflight/flight/video/HUD.h
#ifndef HUD_H #define HUD_H #if ( BUILD_HUD == 1 ) #include <stdint.h> #include <Thread.h> #include <RendererHUD.h> #include <map> class GLContext; class SmartAudio; LUA_CLASS class HUD : public Thread { public: LUA_EXPORT typedef enum { START = 0, CENTER = 1, END = 2, } TextAlignment; LUA_EXPORT HUD(); ~HUD(); // Async GL calls LUA_EXPORT uintptr_t LoadImage( const std::string& path ); LUA_EXPORT void ShowImage( int32_t x, int32_t y, uint32_t w, uint32_t h, const uintptr_t img ); LUA_EXPORT void HideImage( const uintptr_t img ); LUA_EXPORT void AddLayer( const std::function<void()>& func ); // Sync GL calls LUA_EXPORT void PrintText( int32_t x, int32_t y, const std::string& text, uint32_t color = 0xFFFFFFFF, HUD::TextAlignment halign = HUD::TextAlignment::START, HUD::TextAlignment valign = HUD::TextAlignment::START ); virtual bool run(); private: GLContext* mGLContext; RendererHUD* mRendererHUD; LUA_PROPERTY("framerate") uint32_t mFrameRate; LUA_PROPERTY("night") bool mNightMode; uint32_t mHUDFramerate; uint64_t mWaitTicks; LUA_PROPERTY("show_frequency") bool mShowFrequency; float mAccelerationAccum; LUA_PROPERTY("top") int32_t mFrameTop; LUA_PROPERTY("bottom") int32_t mFrameBottom; LUA_PROPERTY("left") int32_t mFrameLeft; LUA_PROPERTY("right") int32_t mFrameRight; LUA_PROPERTY("ratio") int32_t mRatio; LUA_PROPERTY("fontsize") int32_t mFontSize; LUA_PROPERTY("correction") bool mCorrection; LUA_PROPERTY("stereo") bool mStereo; LUA_PROPERTY("stereo_strength") float mStereoStrength; typedef struct { uint64_t img; int32_t x; int32_t y; uint32_t width; uint32_t height; } Image; DroneStats mDroneStats; LinkStats mLinkStats; VideoStats mVideoStats; std::map< uintptr_t, Image > mImages; std::mutex mImagesMutex; bool mReady; SmartAudio* mVTX; }; #else // SYSTEM_NAME_Linux class HUD { public: }; #endif // ( BUILD_HUD == 1 ) #endif // HUD_H
1,932
C++
.h
67
26.80597
215
0.746486
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,860
V4L2Encoder.h
dridri_bcflight/flight/video/V4L2Encoder.h
#ifndef V4L2ENCODER_H #define V4L2ENCODER_H #include <queue> #include <mutex> #include <thread> #include <condition_variable> #include "Lua.h" #include "VideoEncoder.h" LUA_CLASS class V4L2Encoder : public VideoEncoder, protected Thread { public: LUA_EXPORT typedef enum { FORMAT_H264, FORMAT_MJPEG } Format; LUA_EXPORT V4L2Encoder(); ~V4L2Encoder(); virtual void EnqueueBuffer( size_t size, void* mem, int64_t timestamp_us, int fd = -1 ); protected: void Setup(); void SetupH264(); void SetupMJPEG(); virtual bool run(); typedef struct { void* mem; size_t size; } BufferDescription; typedef struct { void* mem; size_t bytes_used; size_t length; unsigned int index; bool keyframe; int64_t timestamp_us; } OutputItem; LUA_PROPERTY("video_device") std::string mVideoDevice; LUA_PROPERTY("format") V4L2Encoder::Format mFormat; LUA_PROPERTY("bitrate") int32_t mBitrate; LUA_PROPERTY("quality") int32_t mQuality; LUA_PROPERTY("width") int32_t mWidth; LUA_PROPERTY("height") int32_t mHeight; LUA_PROPERTY("framerate") int32_t mFramerate; bool mReady; int mFD; std::queue<int> mInputBuffersAvailable; std::mutex mInputBuffersAvailableMutex; int32_t mOutputBuffersCount; std::vector<BufferDescription> mOutputBuffers; std::queue<OutputItem> mOutputQueue; std::mutex mOutputMutex; std::condition_variable mOutputCondVar; }; #endif // V4L2ENCODER_H
1,397
C++
.h
53
24.264151
89
0.770787
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,861
RecorderAvformat.h
dridri_bcflight/flight/video/RecorderAvformat.h
#ifndef RECORDERAVFORMAT_H #define RECORDERAVFORMAT_H extern "C" { #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> }; #include "Recorder.h" #include "Thread.h" LUA_CLASS class RecorderAvformat : public Recorder, protected Thread { public: LUA_EXPORT RecorderAvformat(); ~RecorderAvformat(); LUA_EXPORT virtual bool recording(); LUA_EXPORT virtual void Stop(); LUA_EXPORT virtual void Start(); virtual uint32_t AddAudioTrack( const std::string& format, uint32_t channels, uint32_t sample_rate, const std::string& extension ); virtual uint32_t AddVideoTrack( const std::string& format, uint32_t width, uint32_t height, uint32_t average_fps, const std::string& extension ); virtual void WriteSample( uint32_t track_id, uint64_t record_time_us, void* buf, uint32_t buflen, bool keyframe = false ); virtual void WriteGyro( uint64_t record_time_us, const Vector3f& gyro, const Vector3f& accel = Vector3f() ); protected: typedef struct { uint32_t id; AVStream* stream; TrackType type; char format[32]; // video uint32_t width; uint32_t height; uint32_t average_fps; // audio uint32_t channels; uint32_t sample_rate; } Track; typedef struct { Track* track; uint64_t record_time_us; uint8_t* buf; uint32_t buflen; bool keyframe; } PendingSample; typedef struct { uint64_t t; float gx; float gy; float gz; float ax; float ay; float az; } PendingGyro; bool run(); void WriteSample( PendingSample* sample ); LUA_PROPERTY("base_directory") string mBaseDirectory; uint32_t mRecordId; uint64_t mRecordStartTick; uint64_t mRecordStartSystemTick; std::string mRecordFilename; bool mActive; std::mutex mActiveMutex; std::vector< Track* > mTracks; std::mutex mWriteMutex; std::list< PendingSample* > mPendingSamples; AVFormatContext* mOutputContext; bool mMuxerReady; bool mStopWrite; uint64_t mWriteTicks; std::vector< uint8_t > mVideoHeader; std::vector< uint8_t > mAudioHeader; uint8_t mOutputBuffer[1024 * 1024]; FILE* mOutputFile; FILE* mGyroFile; std::mutex mGyroMutex; std::list< PendingGyro* > mPendingGyros; bool mConsumerRegistered; }; #endif // RECORDERAVFORMAT_H
2,175
C++
.h
76
26.289474
146
0.76259
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,862
AvcodecEncoder.h
dridri_bcflight/flight/video/AvcodecEncoder.h
#ifndef AVCODECENCODER_H #define AVCODECENCODER_H #include "VideoEncoder.h" class AVCodec; class AVCodecContext; LUA_CLASS class AvcodecEncoder : public VideoEncoder { public: LUA_EXPORT typedef enum { FORMAT_H264, FORMAT_MJPEG } Format; LUA_EXPORT AvcodecEncoder(); ~AvcodecEncoder(); virtual void EnqueueBuffer( size_t size, void* mem, int64_t timestamp_us, int fd ); protected: virtual void Setup(); LUA_PROPERTY("format") AvcodecEncoder::Format mFormat; LUA_PROPERTY("bitrate") int32_t mBitrate; LUA_PROPERTY("quality") int32_t mQuality; LUA_PROPERTY("width") int32_t mWidth; LUA_PROPERTY("height") int32_t mHeight; LUA_PROPERTY("framerate") int32_t mFramerate; bool mReady; AVCodec* mCodec; AVCodecContext* mCodecContext; }; #endif // AVCODECENCODER_H
785
C++
.h
28
26.035714
84
0.784759
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,863
DRMSurface.h
dridri_bcflight/flight/video/DRMSurface.h
#ifndef DRMSURFACE_H #define DRMSURFACE_H #include <stdint.h> #include <xf86drmMode.h> #include "DRM.h" #include "DRMFrameBuffer.h" class DRMSurface : public DRM { public: DRMSurface( int32_t zindex = 0 ); ~DRMSurface(); void Show( DRMFrameBuffer* fb ); const drmModeModeInfo* mode() const; protected: uint32_t mConnectorId; uint32_t mCrtcId; uint32_t mPlaneId; drmModeModeInfo mMode; int32_t mZindex; bool mKmsSet; }; #endif // DRMSURFACE_H
459
C++
.h
22
19.090909
37
0.774419
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,864
Camera.h
dridri_bcflight/flight/video/Camera.h
/* * 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/>. **/ #ifndef CAMERA_H #define CAMERA_H #include <stdint.h> #include <string> #include "VideoEncoder.h" using namespace std; class Camera { public: Camera(); ~Camera(); typedef struct { uint8_t base; uint8_t radius; int8_t strength; } LensShaderColor; virtual void Start() = 0; virtual void Pause() = 0; virtual void Resume() = 0; virtual void StartRecording() = 0; virtual void StopRecording() = 0; virtual void TakePicture() = 0; virtual const uint32_t width() = 0; virtual const uint32_t height() = 0; LUA_PROPERTY("framerate") virtual const uint32_t framerate() = 0; virtual const float brightness() = 0; virtual const float contrast() = 0; virtual const float saturation() = 0; virtual const int32_t ISO() = 0; virtual const uint32_t shutterSpeed() = 0; virtual const bool nightMode() = 0; virtual const string whiteBalance() = 0; virtual const string exposureMode() = 0; virtual const bool recording() = 0; virtual const string recordFilename() = 0; virtual void setBrightness( float value ) = 0; virtual void setContrast( float value ) = 0; virtual void setSaturation( float value ) = 0; virtual void setISO( int32_t value ) = 0; virtual void setShutterSpeed( uint32_t value ) = 0; // virtual void setNightMode( bool night_mode ) = 0; virtual string switchWhiteBalance() = 0; virtual string lockWhiteBalance() = 0; virtual string switchExposureMode() = 0; virtual void setLensShader( const LensShaderColor& r, const LensShaderColor& g, const LensShaderColor& b ) = 0; virtual void getLensShader( LensShaderColor* r, LensShaderColor* g, LensShaderColor* b ) = 0; virtual uint32_t getLastPictureID() = 0; virtual uint32_t* getFileSnapshot( const string& filename, uint32_t* width, uint32_t* height, uint32_t* bpp ) = 0; virtual LuaValue infos() { return LuaValue(); } static LuaValue infosAll(); protected: LUA_PROPERTY("preview_output") VideoEncoder* mLiveEncoder; LUA_PROPERTY("video_output") VideoEncoder* mVideoEncoder; // _LUA_PROPERTY("still_output") ImageEncoder* mStillEncoder; static list<Camera*> sCameras; }; #endif // CAMERA_H
2,813
C++
.h
74
35.959459
115
0.746882
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,865
Recorder.h
dridri_bcflight/flight/video/Recorder.h
#ifndef RECORDER_H #define RECORDER_H #ifdef SYSTEM_NAME_Linux #include <mutex> #include <set> #include <list> #include <vector> #include <stdint.h> #include "Vector.h" class Recorder { public: typedef enum { TrackTypeVideo, TrackTypeAudio, } TrackType; Recorder(); ~Recorder(); LUA_EXPORT virtual void Start() = 0; LUA_EXPORT virtual void Stop() = 0; LUA_EXPORT virtual bool recording() = 0; virtual uint32_t AddVideoTrack( const std::string& format, uint32_t width, uint32_t height, uint32_t average_fps, const string& extension ) = 0; virtual uint32_t AddAudioTrack( const std::string& format, uint32_t channels, uint32_t sample_rate, const string& extension ) = 0; virtual void WriteSample( uint32_t track_id, uint64_t record_time_us, void* buf, uint32_t buflen, bool keyframe = false ) = 0; virtual void WriteGyro( uint64_t record_time_us, const Vector3f& gyro, const Vector3f& accel = Vector3f() ) = 0; static const std::set<Recorder*>& recorders(); protected: static std::set<Recorder*> sRecorders; }; #else // SYSTEM_NAME_Linux class Recorder { public: void Start() {} }; #endif // SYSTEM_NAME_Linux #endif // RECORDER_H
1,160
C++
.h
37
29.513514
145
0.745946
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,866
RecorderBasic.h
dridri_bcflight/flight/video/RecorderBasic.h
#ifndef RECORDERBASIC_H #define RECORDERBASIC_H #include "Recorder.h" #include "Thread.h" LUA_CLASS class RecorderBasic : public Recorder, protected Thread { public: LUA_EXPORT RecorderBasic(); ~RecorderBasic(); virtual void Start(); virtual void Stop(); virtual bool recording(); virtual uint32_t AddVideoTrack( const std::string& format, uint32_t width, uint32_t height, uint32_t average_fps, const string& extension ); virtual uint32_t AddAudioTrack( const std::string& format, uint32_t channels, uint32_t sample_rate, const string& extension ); virtual void WriteSample( uint32_t track_id, uint64_t record_time_us, void* buf, uint32_t buflen, bool keyframe = false ); virtual void WriteGyro( uint64_t record_time_us, const Vector3f& gyro, const Vector3f& accel = Vector3f() ); protected: bool run(); typedef struct { uint32_t id; TrackType type; char format[32]; char filename[256]; FILE* file; char extension[8]; uint64_t recordStart; // video uint32_t width; uint32_t height; uint32_t average_fps; // audio uint32_t channels; uint32_t sample_rate; } Track; typedef struct { Track* track; uint64_t record_time_us; uint8_t* buf; uint32_t buflen; } PendingSample; LUA_PROPERTY("base_directory") string mBaseDirectory; mutex mWriteMutex; vector< Track* > mTracks; list< PendingSample* > mPendingSamples; uint32_t mRecordId; FILE* mRecordFile; uint32_t mRecordSyncCounter; }; #endif // RECORDERBASIC_H
1,469
C++
.h
49
27.632653
141
0.75691
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,867
VideoEncoder.h
dridri_bcflight/flight/video/VideoEncoder.h
#ifndef VIDEOENCODER_H #define VIDEOENCODER_H #include <stdint.h> #include "Lua.h" #include "Link.h" #include "Recorder.h" class VideoEncoder { public: VideoEncoder(); ~VideoEncoder(); virtual void Setup() = 0; virtual void EnqueueBuffer( size_t size, void* mem, int64_t timestamp_us, int fd = -1 ) = 0; virtual void SetInputResolution( int width, int height ); protected: LUA_PROPERTY("recorder") Recorder* mRecorder; LUA_PROPERTY("link") Link* mLink; uint32_t mRecorderTrackId; uint32_t mInputWidth; uint32_t mInputHeight; }; #endif // VIDEOENCODER_H
567
C++
.h
22
24.136364
93
0.761553
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,868
DRMFrameBuffer.h
dridri_bcflight/flight/video/DRMFrameBuffer.h
#ifndef DRMFRAMEBUFFER_H #define DRMFRAMEBUFFER_H #include <stdint.h> #include <drm_fourcc.h> #include "DRM.h" class DRMFrameBuffer : public DRM { public: DRMFrameBuffer( uint32_t width, uint32_t height, uint32_t stride, uint32_t format = DRM_FORMAT_YUV420, uint32_t bufferObjectHandle = 0, int dmaFd = -1 ); ~DRMFrameBuffer(); const uint32_t handle() const; const uint32_t width() const; const uint32_t height() const; protected: uint32_t mWidth; uint32_t mHeight; int mDmaFd; uint32_t mBufferObjectHandle; uint32_t mFrameBufferHandle; }; #endif // DRMFRAMEBUFFER_H
582
C++
.h
21
26
154
0.77518
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,869
LiveOutput.h
dridri_bcflight/flight/video/LiveOutput.h
#ifndef LIVEOUTPUT_H #define LIVEOUTPUT_H #include "VideoEncoder.h" LUA_CLASS class LiveOutput : public VideoEncoder { public: LUA_EXPORT LiveOutput(); ~LiveOutput(); void Setup(); void EnqueueBuffer( size_t size, void* mem, int64_t timestamp_us, int fd = -1 ); }; #endif // LIVEOUTPUT_H
296
C++
.h
12
23
81
0.753571
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,870
LinuxCamera.h
dridri_bcflight/flight/video/LinuxCamera.h
#ifndef LINUXCAMERA_H #define LINUXCAMERA_H #include <libcamera/libcamera.h> #include "DRMFrameBuffer.h" #include "DRMSurface.h" #include <Thread.h> #include "Camera.h" #include "Lua.h" #include <set> LUA_CLASS class LinuxCamera : public Camera { public: LUA_EXPORT LinuxCamera(); virtual ~LinuxCamera(); virtual void Start(); void Stop(); virtual void Pause(); virtual void Resume(); virtual void StartRecording(); virtual void StopRecording(); virtual void TakePicture(); virtual const uint32_t width(); virtual const uint32_t height(); virtual const uint32_t framerate(); virtual const float brightness(); virtual const float contrast(); virtual const float saturation(); virtual const int32_t ISO(); virtual const uint32_t shutterSpeed(); virtual const bool nightMode(); virtual const string whiteBalance(); virtual const string exposureMode(); virtual const bool recording(); virtual const string recordFilename(); LUA_EXPORT virtual void setBrightness( float value ); LUA_EXPORT virtual void setContrast( float value ); LUA_EXPORT virtual void setSaturation( float value ); LUA_EXPORT virtual void setISO( int32_t value ); virtual void setShutterSpeed( uint32_t value ); // virtual void setNightMode( bool night_mode ); LUA_EXPORT virtual void updateSettings(); virtual void setHDR( bool hdr, bool force = false ); virtual string switchWhiteBalance(); virtual string lockWhiteBalance(); virtual string switchExposureMode(); virtual void setLensShader( const LensShaderColor& R, const LensShaderColor& G, const LensShaderColor& B ); virtual void getLensShader( LensShaderColor* r, LensShaderColor* g, LensShaderColor* b ); virtual uint32_t getLastPictureID(); virtual uint32_t* getFileSnapshot( const string& filename, uint32_t* width, uint32_t* height, uint32_t* bpp ); virtual LuaValue infos(); protected: bool mLivePreview; // _LUA_PROPERTY("sensor_mode") int32_t mSensorMode; LUA_PROPERTY("width") int32_t mWidth; LUA_PROPERTY("height") int32_t mHeight; LUA_PROPERTY("framerate") int32_t mFps; LUA_PROPERTY("hdr") bool mHDR; // _LUA_PROPERTY("exposure") int32_t mExposure; // _LUA_PROPERTY("iso") int32_t mIso; LUA_PROPERTY("shutter_speed") int32_t mShutterSpeed; LUA_PROPERTY("iso") uint32_t mISO; // _LUA_PROPERTY("analogue_gain") float mAnalogueGain; // _LUA_PROPERTY("digital_gain") float mDigitalGain; LUA_PROPERTY("sharpness") float mSharpness; LUA_PROPERTY("brightness") float mBrightness; LUA_PROPERTY("contrast") float mContrast; LUA_PROPERTY("saturation") float mSaturation; LUA_PROPERTY("vflip") bool mVflip; LUA_PROPERTY("hflip") bool mHflip; LUA_PROPERTY("white_balance") std::string mWhiteBalance; LUA_PROPERTY("exposure") std::string mExposureMode; // _LUA_PROPERTY("stabilisation") bool mStabilisation; // _LUA_PROPERTY("night_fps") int32_t mNightFps; LUA_PROPERTY("night_iso") uint32_t mNightISO; LUA_PROPERTY("night_brightness") float mNightBrightness; LUA_PROPERTY("night_contrast") float mNightContrast; LUA_PROPERTY("night_saturation") float mNightSaturation; int64_t mCurrentFramerate; int64_t mExposureTime; libcamera::Span<const float, 2> mAwbGains; int32_t mColorTemperature; bool mNightMode; static std::unique_ptr<libcamera::CameraManager> sCameraManager; std::shared_ptr<libcamera::Camera> mCamera; std::unique_ptr<libcamera::CameraConfiguration> mCameraConfiguration; std::vector<std::unique_ptr<libcamera::Request>> mRequests; std::set<const libcamera::Request*> mRequestsAlive; std::mutex mRequestsAliveMutex; libcamera::StreamConfiguration* mRawStreamConfiguration; libcamera::StreamConfiguration* mPreviewStreamConfiguration; libcamera::StreamConfiguration* mVideoStreamConfiguration; libcamera::StreamConfiguration* mStillStreamConfiguration; std::map< const libcamera::Stream*, libcamera::ControlList > mControlListQueue; std::mutex mControlListQueueMutex; libcamera::FrameBufferAllocator* mAllocator; libcamera::ControlList mAllControls; std::map<libcamera::FrameBuffer*, uint8_t* > mPlaneBuffers; std::map<libcamera::FrameBuffer*, DRMFrameBuffer*> mPreviewFrameBuffers; DRMSurface* mPreviewSurface; bool mPreviewSurfaceSet; HookThread<LinuxCamera>* mLiveThread; bool mStopping; bool setWhiteBalance( const std::string& mode, libcamera::ControlList* controlsList = nullptr ); void requestComplete( libcamera::Request* request ); void pushControlList( const libcamera::ControlList& list ); bool LiveThreadRun(); bool RecordThreadRun(); bool TakePictureThreadRun(); }; #endif // LINUXCAMERA_H
4,539
C++
.h
110
39.327273
111
0.792299
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,871
Frame.h
dridri_bcflight/flight/frames/Frame.h
/* * 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/>. **/ #ifndef FRAME_H #define FRAME_H #include <vector> #include <string> #include <map> #include <functional> #include <stdint.h> #include <Motor.h> #include <Vector.h> #include <Thread.h> class IMU; class Controller; class Config; class Frame { public: Frame(); virtual ~Frame(); vector< Motor* >* motors(); virtual void Arm(); virtual void Disarm() = 0; virtual void WarmUp() = 0; virtual bool Stabilize( const Vector3f& pid_output, float thrust ) = 0; void CalibrateESCs(); void MotorTest( uint32_t id ); void MotorsBeep( bool enabled ); bool armed() const; bool airMode() const; static void RegisterFrame( const string& name, function< Frame* ( Config* ) > instanciate ); static const map< string, function< Frame* ( Config* ) > > knownFrames() { return mKnownFrames; } protected: LUA_PROPERTY("motors") vector< Motor* > mMotors; bool mArmed; bool mAirMode; bool mMotorsBeep; uint8_t mMotorBeepMode; HookThread< Frame >* mMotorsBeepThread; bool MotorsBeepRun(); private: static map< string, function< Frame* ( Config* ) > > mKnownFrames; }; #endif // FRAME_H
1,808
C++
.h
59
28.728814
98
0.742363
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,872
Multicopter.h
dridri_bcflight/flight/frames/Multicopter.h
#ifndef MULTICOPTER_H #define MULTICOPTER_H #include "Frame.h" class Main; LUA_CLASS class Multicopter : public Frame { public: LUA_EXPORT Multicopter(); ~Multicopter(); void Arm(); void Disarm(); void WarmUp(); virtual bool Stabilize( const Vector3f& pid_output, float thrust ); protected: vector< float > mStabSpeeds; LUA_PROPERTY("maxspeed") float mMaxSpeed; LUA_PROPERTY("test") float mTest; LUA_PROPERTY("air_mode.trigger") float mAirModeTrigger; LUA_PROPERTY("air_mode.speed") float mAirModeSpeed; LUA_PROPERTY("matrix") std::vector<Vector4f> mMatrix; }; #endif // MULTICOPTER_H
603
C++
.h
22
25.590909
68
0.770435
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,873
SBUS.h
dridri_bcflight/flight/links/SBUS.h
/* * 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/>. **/ #ifndef SBUS_H #define SBUS_H #include "Link.h" #include "Serial.h" class Main; class SBUS : public Link { public: SBUS( const string& device, int speed = 100000, uint8_t armChannel = 4, uint8_t thrustChannel = 0, uint8_t rollChannel = 1, uint8_t pitchChannel = 2, uint8_t yawChannel = 3 ); virtual ~SBUS(); int Connect(); int setBlocking( bool blocking ); void setRetriesCount( int retries ); int retriesCount() const; int32_t Channel(); int32_t RxQuality(); int32_t RxLevel(); SyncReturn Read( void* buf, uint32_t len, int32_t timeout ); SyncReturn Write( const void* buf, uint32_t len, bool ack = false, int32_t timeout = -1 ); static int flight_register( Main* main ); protected: static Link* Instanciate( Config* config, const string& lua_object ); Serial* mSerial; // vector<uint8_t> mBuffer; int32_t mChannels[32]; bool mFailsafe; uint8_t mArmChannel; uint8_t mThrustChannel; uint8_t mRollChannel; uint8_t mPitchChannel; uint8_t mYawChannel; bool mCalibrating; }; #endif // SBUS_H
1,735
C++
.h
51
32.039216
176
0.74552
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,874
Socket.h
dridri_bcflight/flight/links/Socket.h
/* * 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/>. **/ #ifndef SOCKET_H #define SOCKET_H #if ( BUILD_SOCKET == 1 ) #include <netinet/in.h> #include "Link.h" #include "Config.h" class Main; LUA_CLASS class Socket : public Link { public: LUA_EXPORT typedef enum { TCP, UDP, UDPLite } PortType; Socket(); Socket( uint16_t port, Socket::PortType type = TCP, bool broadcast = false, uint32_t timeout = 0 ); virtual ~Socket(); int Connect(); int setBlocking( bool blocking ); void setRetriesCount( int retries ); int retriesCount() const; int32_t Channel(); int32_t RxQuality(); int32_t RxLevel(); SyncReturn Read( void* buf, uint32_t len, int32_t timeout ); SyncReturn Write( const void* buf, uint32_t len, bool ack = false, int32_t timeout = -1 ); string name() const { return "Socket"; } LuaValue infos() const; protected: LUA_PROPERTY("port") uint16_t mPort; LUA_PROPERTY("type") Socket::PortType mPortType; LUA_PROPERTY("broadcast") bool mBroadcast; LUA_PROPERTY("read_timeout") uint32_t mTimeout; int mSocket; struct sockaddr_in mSin; int mClientSocket; struct sockaddr_in mClientSin; // Stats int32_t mChannel; }; #else class Socket { public: static int flight_register( Main* main ) { return 0; } }; #endif // ( BUILD_SOCKET == 1 ) #endif // SOCKET_H
1,961
C++
.h
65
28.138462
100
0.73617
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,875
SX127xRegs-LoRa.h
dridri_bcflight/flight/links/SX127xRegs-LoRa.h
/* / _____) _ | | ( (____ _____ ____ _| |_ _____ ____| |__ \____ \| ___ | (_ _) ___ |/ ___) _ \ _____) ) ____| | | || |_| ____( (___| | | | (______/|_____)_|_|_| \__)_____)\____)_| |_| (C) 2014 Semtech Description: SX1276 LoRa modem registers and bits definitions License: Revised BSD License, see LICENSE.TXT file include in the project Maintainer: Miguel Luis and Gregory Cristian */ #ifndef __SX1276_REGS_LORA_H__ #define __SX1276_REGS_LORA_H__ /*! * ============================================================================ * SX1276 Internal registers Address * ============================================================================ */ #define REG_LR_FIFO 0x00 // Common settings #define REG_LR_OPMODE 0x01 #define REG_LR_FRFMSB 0x06 #define REG_LR_FRFMID 0x07 #define REG_LR_FRFLSB 0x08 // Tx settings #define REG_LR_PACONFIG 0x09 #define REG_LR_PARAMP 0x0A #define REG_LR_OCP 0x0B // Rx settings #define REG_LR_LNA 0x0C // LoRa registers #define REG_LR_FIFOADDRPTR 0x0D #define REG_LR_FIFOTXBASEADDR 0x0E #define REG_LR_FIFORXBASEADDR 0x0F #define REG_LR_FIFORXCURRENTADDR 0x10 #define REG_LR_IRQFLAGSMASK 0x11 #define REG_LR_IRQFLAGS 0x12 #define REG_LR_RXNBBYTES 0x13 #define REG_LR_RXHEADERCNTVALUEMSB 0x14 #define REG_LR_RXHEADERCNTVALUELSB 0x15 #define REG_LR_RXPACKETCNTVALUEMSB 0x16 #define REG_LR_RXPACKETCNTVALUELSB 0x17 #define REG_LR_MODEMSTAT 0x18 #define REG_LR_PKTSNRVALUE 0x19 #define REG_LR_PKTRSSIVALUE 0x1A #define REG_LR_RSSIVALUE 0x1B #define REG_LR_HOPCHANNEL 0x1C #define REG_LR_MODEMCONFIG1 0x1D #define REG_LR_MODEMCONFIG2 0x1E #define REG_LR_SYMBTIMEOUTLSB 0x1F #define REG_LR_PREAMBLEMSB 0x20 #define REG_LR_PREAMBLELSB 0x21 #define REG_LR_PAYLOADLENGTH 0x22 #define REG_LR_PAYLOADMAXLENGTH 0x23 #define REG_LR_HOPPERIOD 0x24 #define REG_LR_FIFORXBYTEADDR 0x25 #define REG_LR_MODEMCONFIG3 0x26 #define REG_LR_FEIMSB 0x28 #define REG_LR_FEIMID 0x29 #define REG_LR_FEILSB 0x2A #define REG_LR_RSSIWIDEBAND 0x2C #define REG_LR_TEST2F 0x2F #define REG_LR_TEST30 0x30 #define REG_LR_DETECTOPTIMIZE 0x31 #define REG_LR_INVERTIQ 0x33 #define REG_LR_TEST36 0x36 #define REG_LR_DETECTIONTHRESHOLD 0x37 #define REG_LR_SYNCWORD 0x39 #define REG_LR_TEST3A 0x3A #define REG_LR_INVERTIQ2 0x3B // end of documented register in datasheet // I/O settings #define REG_LR_DIOMAPPING1 0x40 #define REG_LR_DIOMAPPING2 0x41 // Version #define REG_LR_VERSION 0x42 // Additional settings #define REG_LR_PLLHOP 0x44 #define REG_LR_TCXO 0x4B #define REG_LR_PADAC 0x4D #define REG_LR_FORMERTEMP 0x5B #define REG_LR_BITRATEFRAC 0x5D #define REG_LR_AGCREF 0x61 #define REG_LR_AGCTHRESH1 0x62 #define REG_LR_AGCTHRESH2 0x63 #define REG_LR_AGCTHRESH3 0x64 #define REG_LR_PLL 0x70 /*! * ============================================================================ * SX1276 LoRa bits control definition * ============================================================================ */ /*! * RegFifo */ /*! * RegOpMode */ #define RFLR_OPMODE_LONGRANGEMODE_MASK 0x7F #define RFLR_OPMODE_LONGRANGEMODE_OFF 0x00 // Default #define RFLR_OPMODE_LONGRANGEMODE_ON 0x80 #define RFLR_OPMODE_ACCESSSHAREDREG_MASK 0xBF #define RFLR_OPMODE_ACCESSSHAREDREG_ENABLE 0x40 #define RFLR_OPMODE_ACCESSSHAREDREG_DISABLE 0x00 // Default #define RFLR_OPMODE_FREQMODE_ACCESS_MASK 0xF7 #define RFLR_OPMODE_FREQMODE_ACCESS_LF 0x08 // Default #define RFLR_OPMODE_FREQMODE_ACCESS_HF 0x00 #define RFLR_OPMODE_MASK 0xF8 #define RFLR_OPMODE_SLEEP 0x00 #define RFLR_OPMODE_STANDBY 0x01 // Default #define RFLR_OPMODE_SYNTHESIZER_TX 0x02 #define RFLR_OPMODE_TRANSMITTER 0x03 #define RFLR_OPMODE_SYNTHESIZER_RX 0x04 #define RFLR_OPMODE_RECEIVER 0x05 // LoRa specific modes #define RFLR_OPMODE_RECEIVER_SINGLE 0x06 #define RFLR_OPMODE_CAD 0x07 /*! * RegFrf (MHz) */ #define RFLR_FRFMSB_434_MHZ 0x6C // Default #define RFLR_FRFMID_434_MHZ 0x80 // Default #define RFLR_FRFLSB_434_MHZ 0x00 // Default /*! * RegPaConfig */ #define RFLR_PACONFIG_PASELECT_MASK 0x7F #define RFLR_PACONFIG_PASELECT_PABOOST 0x80 #define RFLR_PACONFIG_PASELECT_RFO 0x00 // Default #define RFLR_PACONFIG_MAX_POWER_MASK 0x8F #define RFLR_PACONFIG_OUTPUTPOWER_MASK 0xF0 /*! * RegPaRamp */ #define RFLR_PARAMP_TXBANDFORCE_MASK 0xEF #define RFLR_PARAMP_TXBANDFORCE_BAND_SEL 0x10 #define RFLR_PARAMP_TXBANDFORCE_AUTO 0x00 // Default #define RFLR_PARAMP_MASK 0xF0 #define RFLR_PARAMP_3400_US 0x00 #define RFLR_PARAMP_2000_US 0x01 #define RFLR_PARAMP_1000_US 0x02 #define RFLR_PARAMP_0500_US 0x03 #define RFLR_PARAMP_0250_US 0x04 #define RFLR_PARAMP_0125_US 0x05 #define RFLR_PARAMP_0100_US 0x06 #define RFLR_PARAMP_0062_US 0x07 #define RFLR_PARAMP_0050_US 0x08 #define RFLR_PARAMP_0040_US 0x09 // Default #define RFLR_PARAMP_0031_US 0x0A #define RFLR_PARAMP_0025_US 0x0B #define RFLR_PARAMP_0020_US 0x0C #define RFLR_PARAMP_0015_US 0x0D #define RFLR_PARAMP_0012_US 0x0E #define RFLR_PARAMP_0010_US 0x0F /*! * RegOcp */ #define RFLR_OCP_MASK 0xDF #define RFLR_OCP_ON 0x20 // Default #define RFLR_OCP_OFF 0x00 #define RFLR_OCP_TRIM_MASK 0xE0 #define RFLR_OCP_TRIM_045_MA 0x00 #define RFLR_OCP_TRIM_050_MA 0x01 #define RFLR_OCP_TRIM_055_MA 0x02 #define RFLR_OCP_TRIM_060_MA 0x03 #define RFLR_OCP_TRIM_065_MA 0x04 #define RFLR_OCP_TRIM_070_MA 0x05 #define RFLR_OCP_TRIM_075_MA 0x06 #define RFLR_OCP_TRIM_080_MA 0x07 #define RFLR_OCP_TRIM_085_MA 0x08 #define RFLR_OCP_TRIM_090_MA 0x09 #define RFLR_OCP_TRIM_095_MA 0x0A #define RFLR_OCP_TRIM_100_MA 0x0B // Default #define RFLR_OCP_TRIM_105_MA 0x0C #define RFLR_OCP_TRIM_110_MA 0x0D #define RFLR_OCP_TRIM_115_MA 0x0E #define RFLR_OCP_TRIM_120_MA 0x0F #define RFLR_OCP_TRIM_130_MA 0x10 #define RFLR_OCP_TRIM_140_MA 0x11 #define RFLR_OCP_TRIM_150_MA 0x12 #define RFLR_OCP_TRIM_160_MA 0x13 #define RFLR_OCP_TRIM_170_MA 0x14 #define RFLR_OCP_TRIM_180_MA 0x15 #define RFLR_OCP_TRIM_190_MA 0x16 #define RFLR_OCP_TRIM_200_MA 0x17 #define RFLR_OCP_TRIM_210_MA 0x18 #define RFLR_OCP_TRIM_220_MA 0x19 #define RFLR_OCP_TRIM_230_MA 0x1A #define RFLR_OCP_TRIM_240_MA 0x1B /*! * RegLna */ #define RFLR_LNA_GAIN_MASK 0x1F #define RFLR_LNA_GAIN_G1 0x20 // Default #define RFLR_LNA_GAIN_G2 0x40 #define RFLR_LNA_GAIN_G3 0x60 #define RFLR_LNA_GAIN_G4 0x80 #define RFLR_LNA_GAIN_G5 0xA0 #define RFLR_LNA_GAIN_G6 0xC0 #define RFLR_LNA_BOOST_LF_MASK 0xE7 #define RFLR_LNA_BOOST_LF_DEFAULT 0x00 // Default #define RFLR_LNA_BOOST_HF_MASK 0xFC #define RFLR_LNA_BOOST_HF_OFF 0x00 // Default #define RFLR_LNA_BOOST_HF_ON 0x03 /*! * RegFifoAddrPtr */ #define RFLR_FIFOADDRPTR 0x00 // Default /*! * RegFifoTxBaseAddr */ #define RFLR_FIFOTXBASEADDR 0x80 // Default /*! * RegFifoTxBaseAddr */ #define RFLR_FIFORXBASEADDR 0x00 // Default /*! * RegFifoRxCurrentAddr (Read Only) */ /*! * RegIrqFlagsMask */ #define RFLR_IRQFLAGS_RXTIMEOUT_MASK 0x80 #define RFLR_IRQFLAGS_RXDONE_MASK 0x40 #define RFLR_IRQFLAGS_PAYLOADCRCERROR_MASK 0x20 #define RFLR_IRQFLAGS_VALIDHEADER_MASK 0x10 #define RFLR_IRQFLAGS_TXDONE_MASK 0x08 #define RFLR_IRQFLAGS_CADDONE_MASK 0x04 #define RFLR_IRQFLAGS_FHSSCHANGEDCHANNEL_MASK 0x02 #define RFLR_IRQFLAGS_CADDETECTED_MASK 0x01 /*! * RegIrqFlags */ #define RFLR_IRQFLAGS_RXTIMEOUT 0x80 #define RFLR_IRQFLAGS_RXDONE 0x40 #define RFLR_IRQFLAGS_PAYLOADCRCERROR 0x20 #define RFLR_IRQFLAGS_VALIDHEADER 0x10 #define RFLR_IRQFLAGS_TXDONE 0x08 #define RFLR_IRQFLAGS_CADDONE 0x04 #define RFLR_IRQFLAGS_FHSSCHANGEDCHANNEL 0x02 #define RFLR_IRQFLAGS_CADDETECTED 0x01 /*! * RegFifoRxNbBytes (Read Only) */ /*! * RegRxHeaderCntValueMsb (Read Only) */ /*! * RegRxHeaderCntValueLsb (Read Only) */ /*! * RegRxPacketCntValueMsb (Read Only) */ /*! * RegRxPacketCntValueLsb (Read Only) */ /*! * RegModemStat (Read Only) */ #define RFLR_MODEMSTAT_RX_CR_MASK 0x1F #define RFLR_MODEMSTAT_MODEM_STATUS_MASK 0xE0 /*! * RegPktSnrValue (Read Only) */ /*! * RegPktRssiValue (Read Only) */ /*! * RegRssiValue (Read Only) */ /*! * RegHopChannel (Read Only) */ #define RFLR_HOPCHANNEL_PLL_LOCK_TIMEOUT_MASK 0x7F #define RFLR_HOPCHANNEL_PLL_LOCK_FAIL 0x80 #define RFLR_HOPCHANNEL_PLL_LOCK_SUCCEED 0x00 // Default #define RFLR_HOPCHANNEL_CRCONPAYLOAD_MASK 0xBF #define RFLR_HOPCHANNEL_CRCONPAYLOAD_ON 0x40 #define RFLR_HOPCHANNEL_CRCONPAYLOAD_OFF 0x00 // Default #define RFLR_HOPCHANNEL_CHANNEL_MASK 0x3F /*! * RegModemConfig1 */ #define RFLR_MODEMCONFIG1_BW_MASK 0x0F #define RFLR_MODEMCONFIG1_BW_7_81_KHZ 0x00 #define RFLR_MODEMCONFIG1_BW_10_41_KHZ 0x10 #define RFLR_MODEMCONFIG1_BW_15_62_KHZ 0x20 #define RFLR_MODEMCONFIG1_BW_20_83_KHZ 0x30 #define RFLR_MODEMCONFIG1_BW_31_25_KHZ 0x40 #define RFLR_MODEMCONFIG1_BW_41_66_KHZ 0x50 #define RFLR_MODEMCONFIG1_BW_62_50_KHZ 0x60 #define RFLR_MODEMCONFIG1_BW_125_KHZ 0x70 // Default #define RFLR_MODEMCONFIG1_BW_250_KHZ 0x80 #define RFLR_MODEMCONFIG1_BW_500_KHZ 0x90 #define RFLR_MODEMCONFIG1_CODINGRATE_MASK 0xF1 #define RFLR_MODEMCONFIG1_CODINGRATE_4_5 0x02 #define RFLR_MODEMCONFIG1_CODINGRATE_4_6 0x04 // Default #define RFLR_MODEMCONFIG1_CODINGRATE_4_7 0x06 #define RFLR_MODEMCONFIG1_CODINGRATE_4_8 0x08 #define RFLR_MODEMCONFIG1_IMPLICITHEADER_MASK 0xFE #define RFLR_MODEMCONFIG1_IMPLICITHEADER_ON 0x01 #define RFLR_MODEMCONFIG1_IMPLICITHEADER_OFF 0x00 // Default /*! * RegModemConfig2 */ #define RFLR_MODEMCONFIG2_SF_MASK 0x0F #define RFLR_MODEMCONFIG2_SF_6 0x60 #define RFLR_MODEMCONFIG2_SF_7 0x70 // Default #define RFLR_MODEMCONFIG2_SF_8 0x80 #define RFLR_MODEMCONFIG2_SF_9 0x90 #define RFLR_MODEMCONFIG2_SF_10 0xA0 #define RFLR_MODEMCONFIG2_SF_11 0xB0 #define RFLR_MODEMCONFIG2_SF_12 0xC0 #define RFLR_MODEMCONFIG2_TXCONTINUOUSMODE_MASK 0xF7 #define RFLR_MODEMCONFIG2_TXCONTINUOUSMODE_ON 0x08 #define RFLR_MODEMCONFIG2_TXCONTINUOUSMODE_OFF 0x00 #define RFLR_MODEMCONFIG2_RXPAYLOADCRC_MASK 0xFB #define RFLR_MODEMCONFIG2_RXPAYLOADCRC_ON 0x04 #define RFLR_MODEMCONFIG2_RXPAYLOADCRC_OFF 0x00 // Default #define RFLR_MODEMCONFIG2_SYMBTIMEOUTMSB_MASK 0xFC #define RFLR_MODEMCONFIG2_SYMBTIMEOUTMSB 0x00 // Default /*! * RegSymbTimeoutLsb */ #define RFLR_SYMBTIMEOUTLSB_SYMBTIMEOUT 0x64 // Default /*! * RegPreambleLengthMsb */ #define RFLR_PREAMBLELENGTHMSB 0x00 // Default /*! * RegPreambleLengthLsb */ #define RFLR_PREAMBLELENGTHLSB 0x08 // Default /*! * RegPayloadLength */ #define RFLR_PAYLOADLENGTH 0x0E // Default /*! * RegPayloadMaxLength */ #define RFLR_PAYLOADMAXLENGTH 0xFF // Default /*! * RegHopPeriod */ #define RFLR_HOPPERIOD_FREQFOPPINGPERIOD 0x00 // Default /*! * RegFifoRxByteAddr (Read Only) */ /*! * RegModemConfig3 */ #define RFLR_MODEMCONFIG3_LOWDATARATEOPTIMIZE_MASK 0xF7 #define RFLR_MODEMCONFIG3_LOWDATARATEOPTIMIZE_ON 0x08 #define RFLR_MODEMCONFIG3_LOWDATARATEOPTIMIZE_OFF 0x00 // Default #define RFLR_MODEMCONFIG3_AGCAUTO_MASK 0xFB #define RFLR_MODEMCONFIG3_AGCAUTO_ON 0x04 // Default #define RFLR_MODEMCONFIG3_AGCAUTO_OFF 0x00 /*! * RegFeiMsb (Read Only) */ /*! * RegFeiMid (Read Only) */ /*! * RegFeiLsb (Read Only) */ /*! * RegRssiWideband (Read Only) */ /*! * RegDetectOptimize */ #define RFLR_DETECTIONOPTIMIZE_MASK 0xF8 #define RFLR_DETECTIONOPTIMIZE_SF7_TO_SF12 0x03 // Default #define RFLR_DETECTIONOPTIMIZE_SF6 0x05 /*! * RegInvertIQ */ #define RFLR_INVERTIQ_RX_MASK 0xBF #define RFLR_INVERTIQ_RX_OFF 0x00 #define RFLR_INVERTIQ_RX_ON 0x40 #define RFLR_INVERTIQ_TX_MASK 0xFE #define RFLR_INVERTIQ_TX_OFF 0x01 #define RFLR_INVERTIQ_TX_ON 0x00 /*! * RegDetectionThreshold */ #define RFLR_DETECTIONTHRESH_SF7_TO_SF12 0x0A // Default #define RFLR_DETECTIONTHRESH_SF6 0x0C /*! * RegInvertIQ2 */ #define RFLR_INVERTIQ2_ON 0x19 #define RFLR_INVERTIQ2_OFF 0x1D /*! * RegDioMapping1 */ #define RFLR_DIOMAPPING1_DIO0_MASK 0x3F #define RFLR_DIOMAPPING1_DIO0_00 0x00 // Default #define RFLR_DIOMAPPING1_DIO0_01 0x40 #define RFLR_DIOMAPPING1_DIO0_10 0x80 #define RFLR_DIOMAPPING1_DIO0_11 0xC0 #define RFLR_DIOMAPPING1_DIO1_MASK 0xCF #define RFLR_DIOMAPPING1_DIO1_00 0x00 // Default #define RFLR_DIOMAPPING1_DIO1_01 0x10 #define RFLR_DIOMAPPING1_DIO1_10 0x20 #define RFLR_DIOMAPPING1_DIO1_11 0x30 #define RFLR_DIOMAPPING1_DIO2_MASK 0xF3 #define RFLR_DIOMAPPING1_DIO2_00 0x00 // Default #define RFLR_DIOMAPPING1_DIO2_01 0x04 #define RFLR_DIOMAPPING1_DIO2_10 0x08 #define RFLR_DIOMAPPING1_DIO2_11 0x0C #define RFLR_DIOMAPPING1_DIO3_MASK 0xFC #define RFLR_DIOMAPPING1_DIO3_00 0x00 // Default #define RFLR_DIOMAPPING1_DIO3_01 0x01 #define RFLR_DIOMAPPING1_DIO3_10 0x02 #define RFLR_DIOMAPPING1_DIO3_11 0x03 /*! * RegDioMapping2 */ #define RFLR_DIOMAPPING2_DIO4_MASK 0x3F #define RFLR_DIOMAPPING2_DIO4_00 0x00 // Default #define RFLR_DIOMAPPING2_DIO4_01 0x40 #define RFLR_DIOMAPPING2_DIO4_10 0x80 #define RFLR_DIOMAPPING2_DIO4_11 0xC0 #define RFLR_DIOMAPPING2_DIO5_MASK 0xCF #define RFLR_DIOMAPPING2_DIO5_00 0x00 // Default #define RFLR_DIOMAPPING2_DIO5_01 0x10 #define RFLR_DIOMAPPING2_DIO5_10 0x20 #define RFLR_DIOMAPPING2_DIO5_11 0x30 #define RFLR_DIOMAPPING2_MAP_MASK 0xFE #define RFLR_DIOMAPPING2_MAP_PREAMBLEDETECT 0x01 #define RFLR_DIOMAPPING2_MAP_RSSI 0x00 // Default /*! * RegVersion (Read Only) */ /*! * RegPllHop */ #define RFLR_PLLHOP_FASTHOP_MASK 0x7F #define RFLR_PLLHOP_FASTHOP_ON 0x80 #define RFLR_PLLHOP_FASTHOP_OFF 0x00 // Default /*! * RegTcxo */ #define RFLR_TCXO_TCXOINPUT_MASK 0xEF #define RFLR_TCXO_TCXOINPUT_ON 0x10 #define RFLR_TCXO_TCXOINPUT_OFF 0x00 // Default /*! * RegPaDac */ #define RFLR_PADAC_20DBM_MASK 0xF8 #define RFLR_PADAC_20DBM_ON 0x07 #define RFLR_PADAC_20DBM_OFF 0x04 // Default /*! * RegFormerTemp */ /*! * RegBitrateFrac */ #define RF_BITRATEFRAC_MASK 0xF0 /*! * RegAgcRef */ /*! * RegAgcThresh1 */ /*! * RegAgcThresh2 */ /*! * RegAgcThresh3 */ /*! * RegPll */ #define RF_PLL_BANDWIDTH_MASK 0x3F #define RF_PLL_BANDWIDTH_75 0x00 #define RF_PLL_BANDWIDTH_150 0x40 #define RF_PLL_BANDWIDTH_225 0x80 #define RF_PLL_BANDWIDTH_300 0xC0 // Default #endif // __SX1276_REGS_LORA_H__
19,994
C++
.h
482
39.390041
79
0.529607
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,876
SX127x.h
dridri_bcflight/flight/links/SX127x.h
#ifndef SX127X_H #define SX127X_H #include <atomic> #include <Mutex.h> #include <list> #include "Link.h" #include "Config.h" class Main; class SPI; LUA_CLASS class SX127x : public Link { public: typedef enum { FSK, LoRa, } Modem; LUA_EXPORT SX127x(); ~SX127x(); int Connect(); void setFrequency( float f ); int setBlocking( bool blocking ); void setRetriesCount( int retries ); int retriesCount() const; int32_t Channel(); int32_t Frequency(); int32_t RxQuality(); int32_t RxLevel(); uint32_t fullReadSpeed(); SyncReturn Write( const void* buf, uint32_t len, bool ack = false, int32_t timeout = -1 ); SyncReturn Read( void* buf, uint32_t len, int32_t timeout ); SyncReturn WriteAck( const void* buf, uint32_t len ); virtual string name() const; virtual LuaValue infos() const; protected: void init(); typedef struct __attribute__((packed)) { uint8_t small_packet : 1; uint8_t block_id : 7; uint8_t packet_id; uint8_t packets_count; uint8_t crc; } Header; typedef struct __attribute__((packed)) { uint8_t small_packet : 1; uint8_t block_id : 7; uint8_t crc; } HeaderMini; typedef struct RxConfig_t { uint32_t bandwidth; uint32_t datarate; uint8_t coderate; uint32_t bandwidthAfc; uint16_t preambleLen; uint16_t symbTimeout; uint8_t payloadLen; bool crcOn; bool freqHopOn; uint8_t hopPeriod; bool iqInverted; } RxConfig_t; typedef struct TxConfig_t { uint32_t fdev; uint32_t bandwidth; uint32_t datarate; uint8_t coderate; uint16_t preambleLen; bool crcOn; bool freqHopOn; uint8_t hopPeriod; bool iqInverted; uint32_t timeout; } TxConfig_t; int32_t Setup( SPI* spi ); void SetupRX( SPI* spi, const RxConfig_t& conf ); void SetupTX( SPI* spi, const TxConfig_t& conf ); void Interrupt( SPI* spi, int32_t ledPin = -1 ); void reset(); bool ping( SPI* spi = nullptr ); void setFrequency( SPI* spi, float f ); void startReceiving( SPI* spi = nullptr ); void startTransmitting(); void setModem( SPI* spi, Modem modem ); uint32_t getOpMode( SPI* spi ); bool setOpMode( SPI* spi, uint32_t mode ); uint8_t readRegister( uint8_t reg ); bool writeRegister( uint8_t reg, uint8_t value ); uint8_t readRegister( SPI* spi, uint8_t reg ); bool writeRegister( SPI* spi, uint8_t reg, uint8_t value ); SPI* mSPI; bool mReady; LUA_PROPERTY("device") string mDevice; LUA_PROPERTY("resetpin") int32_t mResetPin; LUA_PROPERTY("txpin") int32_t mTXPin; LUA_PROPERTY("rxpin") int32_t mRXPin; LUA_PROPERTY("irqpin") int32_t mIRQPin; LUA_PROPERTY("ledpin") int32_t mLedPin; LUA_PROPERTY("blocking") bool mBlocking; LUA_PROPERTY("drop") bool mDropBroken; bool mEnableTCXO; Modem mModem; LUA_PROPERTY("frequency") uint32_t mFrequency; int32_t mInputPort; int32_t mOutputPort; int32_t mRetries; LUA_PROPERTY("read_timeout") int32_t mReadTimeout; LUA_PROPERTY("bitrate") uint32_t mBitrate; LUA_PROPERTY("bandwidth") uint32_t mBandwidth; LUA_PROPERTY("bandwidthAfc") uint32_t mBandwidthAfc; LUA_PROPERTY("fdev") uint32_t mFdev; atomic_bool mSending; atomic_bool mSendingEnd; uint64_t mSendTime; void PerfUpdate(); Mutex mPerfMutex; int32_t mRSSI; int32_t mRxQuality; int32_t mPerfTicks; int32_t mPerfLastRxBlock; int32_t mPerfValidBlocks; int32_t mPerfInvalidBlocks; int32_t mPerfBlocksPerSecond; int32_t mPerfMaxBlocksPerSecond; list< uint64_t > mTotalHistory; // [ticks] list< uint64_t > mMissedHistory; // [ticks]MissedBlocks list< uint64_t > mPerfHistory; // [ticks]ValidBlocks int32_t mPerfTotalBlocks; int32_t mPerfMissedBlocks; SPI* mDiversitySpi; LUA_PROPERTY("diversity.device") string mDiversityDevice; LUA_PROPERTY("diversity.resetpin") int32_t mDiversityResetPin; LUA_PROPERTY("diversity.irqpin") int32_t mDiversityIrqPin; LUA_PROPERTY("diversity.ledpin") int32_t mDiversityLedPin; Mutex mInterruptMutex; // TX uint8_t mTXBlockID; // RX int Receive( uint8_t* data, uint32_t datalen, void* pRet, uint32_t len ); typedef struct { uint8_t data[32]; uint8_t size; bool valid; } Packet; typedef struct { uint8_t block_id; uint8_t packets_count; Packet packets[256]; bool received; } Block; Block mRxBlock; list<pair<uint8_t*, uint32_t>> mRxQueue; Mutex mRxQueueMutex; }; #endif // SX127X_H
4,258
C++
.h
155
25.2
91
0.744123
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,877
Link.h
dridri_bcflight/flight/links/Link.h
/* * 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/>. **/ #ifndef LINK_H #define LINK_H #include <stdlib.h> #include <stdint.h> #include <stdarg.h> #include <math.h> #include <string> #include <map> #include <functional> #include <vector> #include <Board.h> #include <ThreadBase.h> #include <Lua.h> class Config; class Packet { public: Packet() : mReadOffset( 0 ) {} Packet( uint32_t id ) { WriteU16( id ); } void Write( const uint8_t* data, uint32_t bytes ); void WriteU8( uint8_t v ); void WriteU16( uint16_t v ); void WriteU32( uint32_t v ); void WriteFloat( float v ) { union { float f; uint32_t u; } u; u.f = v; WriteU32( u.u ); } void WriteString( const string& str ); uint32_t Read( uint8_t* data, uint32_t bytes ); uint32_t ReadU8( uint8_t* u ); uint32_t ReadU16( uint16_t* u ); uint32_t ReadU32( uint32_t* u ); uint32_t ReadFloat( float* f ); uint8_t ReadU8(); uint16_t ReadU16(); uint32_t ReadU32(); float ReadFloat(); string ReadString(); const vector< uint8_t >& data() const { return mData; } private: vector< uint8_t > mData; uint32_t mReadOffset; }; class Link { public: static Link* Create( Config* config, const string& config_object ); Link(); virtual ~Link(); bool isConnected() const; virtual int Connect() = 0; virtual int setBlocking( bool blocking ) = 0; virtual void setRetriesCount( int retries ) = 0; virtual int retriesCount() const = 0; virtual int32_t Channel() { return 0; } virtual int32_t Frequency() { return 0; } virtual int32_t RxQuality() { return 100; } virtual int32_t RxLevel() { return -1; } SyncReturn Read( Packet* p, int32_t timeout = -1 ); SyncReturn Write( const Packet* p, bool ack = false, int32_t timeout = -1 ); virtual SyncReturn Read( void* buf, uint32_t len, int32_t timeout ) = 0; virtual SyncReturn Write( const void* buf, uint32_t len, bool ack = false, int32_t timeout = -1 ) = 0; virtual SyncReturn WriteAck( const void* buf, uint32_t len ) { return Write( buf, len, false, -1 ); } virtual string name() const { return "Link"; } virtual LuaValue infos() const { return LuaValue(); } static const map< string, function< Link* ( Config*, const string& ) > >& knownLinks() { return mKnownLinks; } static list< Link* > links() { return sLinks; } static LuaValue infosAll(); protected: bool mConnected; static void RegisterLink( const string& name, function< Link* ( Config*, const string& ) > instanciate ); static map< string, function< Link* ( Config*, const string& ) > > mKnownLinks; static list< Link* > sLinks; }; #endif // LINK_H
3,213
C++
.h
89
34.146067
111
0.71134
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