id
int64
0
877k
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
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 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
1,539,904
project3dform.h
fafa1899_SinianGIS/SinianGIS/project3dform.h
#ifndef PROJECT3DFORM_H #define PROJECT3DFORM_H #include "sceneproject3d.h" #include <QWidget> #include <QTreeWidgetItem> namespace Ui { class Project3DForm; } class Project3DForm : public QWidget { Q_OBJECT public: explicit Project3DForm(QWidget *parent = nullptr); ~Project3DForm(); void LoadProject3d(std::shared_ptr<SceneProject3D> sceneProject3D); void AddTerrain(std::string fileName); void AddImage(std::string fileName); void AddVector(std::string fileName); void AddTiltingData(std::string fileName); std::string GetName(){return sceneProject3D?sceneProject3D->getFileName():"";} signals: void signalViewPoint(std::string name); void signalTerrainViewPoint(); void signalImageViewPoint(); void signalTiltingDataViewPoint(); protected: QTreeWidgetItem* terrainItem; QTreeWidgetItem* imageItem; QTreeWidgetItem* vectorItem; QTreeWidgetItem* tiltingDataItem; std::shared_ptr<SceneProject3D> sceneProject3D; QIcon mainIcon; QIcon terrainIcon; QIcon imageIcon; QIcon vectorIcon; QIcon tiltingDataIcon; private slots: void on_treeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column); private: Ui::Project3DForm *ui; }; #endif // PROJECT3DFORM_H
1,273
C++
.h
42
26.5
82
0.770816
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,905
GoogleMapTiles.h
fafa1899_SinianGIS/SinianGIS/GoogleMapTiles.h
#pragma once #include "WebTilesClass.h" class GoogleMapTiles : public WebTilesClass { public: GoogleMapTiles(); virtual ~GoogleMapTiles(); virtual bool GetTiles(double left, double top, double right, double bottom, int li, std::vector<OneTile> &tiles); virtual bool WriteGeoInfo(std::string imgName, OneTile& tile); protected: std::string uri; };
360
C++
.h
13
25.769231
115
0.785924
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,906
regedit.h
fafa1899_SinianGIS/SinianGIS/regedit.h
#ifndef REGEDIT_H #define REGEDIT_H #include <QString> /******************************************************************* * 注册文件关联 * * className // 自定义的类别 * appPath // 关联的程序目录 * ext // 关联的文件类型 * extDes // 该文件类型描述 * *******************************************************************/ void registerFileRelation(const QString& className,const QString& appPath,const QString& ext,const QString& extDes); #endif // REGEDIT_H
486
C++
.h
14
31.142857
116
0.481651
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,907
mapdownloaddialog.h
fafa1899_SinianGIS/SinianGIS/mapdownloaddialog.h
#ifndef MAPDOWNLOADDIALOG_H #define MAPDOWNLOADDIALOG_H #include <QDialog> namespace Ui { class MapDownloadDialog; } class MapDownloadDialog : public QDialog { Q_OBJECT public: explicit MapDownloadDialog(QWidget *parent = nullptr); ~MapDownloadDialog(); protected: void SaveIniConfig(); private slots: void on_pBOK_clicked(); void on_pBCancel_clicked(); void on_pBOutDir_clicked(); private: Ui::MapDownloadDialog *ui; }; #endif // MAPDOWNLOADDIALOG_H
493
C++
.h
22
19.5
58
0.765727
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,909
duilib.cpp
thebookisclosed_shsxs/duilib.cpp
#include "duilib.h" HMODULE g_twinUI; RP_CDUIContext* g_DUIContext; HRESULT CDUIResourceManager::_RegisterElements() { HRESULT result = 0; for (DWORD i = 0; i < this->_cRegister; i++) { result = ((VoidCall)this->_rgRegister[i])(); if (result < 0) break; } return result; } HRESULT CDUIResourceManager::_DebugGetDUIPath(LPWSTR* pszDUIPath) { HKEY regKey; HRESULT result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced", 0, KEY_QUERY_VALUE, &regKey); if (result) return result; DWORD pathSize; RegQueryValueEx(regKey, _pszMarkupOverrideRegValue, NULL, NULL, NULL, &pathSize); if (!pathSize) return E_FAIL; *pszDUIPath = new WCHAR[pathSize]; result = RegQueryValueEx(regKey, _pszMarkupOverrideRegValue, NULL, NULL, (LPBYTE)*pszDUIPath, &pathSize); if (result) { delete[] *pszDUIPath; *pszDUIPath = NULL; } RegCloseKey(regKey); return result; } HRESULT CDUIResourceManager::s_DebugGetDUIFileLastWrite(LPWSTR szDUIPath, FILETIME* writeTime) { (*writeTime).dwLowDateTime = 0; (*writeTime).dwHighDateTime = 0; WIN32_FILE_ATTRIBUTE_DATA attribData; if (GetFileAttributesEx(szDUIPath, GetFileExInfoStandard, &attribData)) { *writeTime = attribData.ftLastWriteTime; return ERROR_SUCCESS; } return HRESULT_FROM_WIN32(GetLastError()); } HRESULT CDUIResourceManager::GetModuleResourceData(HINSTANCE hModule, LPCWSTR pwszName, LPCWSTR pwszType, LPCSTR* prgb, DWORD* pcb) { HRSRC resource; DWORD resSize; HGLOBAL resGlobal; LPCSTR resLockStr; if ((resource = FindResource(hModule, pwszName, pwszType)) && (resSize = SizeofResource(hModule, resource)) && (resGlobal = LoadResource(hModule, resource)) && (resLockStr = (LPCSTR)LockResource(resGlobal))) { *prgb = resLockStr; *pcb = resSize; return ERROR_SUCCESS; } return HRESULT_FROM_WIN32(GetLastError()); } HRESULT CDUIResourceManager::s_DebugPrettyPrintXMLToFile(LPCSTR pszXML, IStream* stream, DWORD resSize) { ULARGE_INTEGER zero = { 0 }; HRESULT comResult = stream->SetSize(zero); if (!SUCCEEDED(comResult)) return comResult; DWORD indentLevel = 0; LPCSTR xmlEnd = pszXML + resSize - 1; LPCSTR pszNextElement = pszXML; while (true) { LPSTR pszElementStart = StrPBrkA(pszNextElement, "<"); if (!pszElementStart) return comResult; pszNextElement = 0; CHAR nextChar = *(pszElementStart + 1); if (nextChar == '/') --indentLevel; for (DWORD i = 0; i < indentLevel; i++) { comResult = stream->Write(" ", 3, NULL); if (!SUCCEEDED(comResult)) return comResult; } if (nextChar != '/' && nextChar != '!') ++indentLevel; LPSTR pszElementEnd = pszElementStart; while (true) { if (pszNextElement || !pszElementEnd) { comResult = stream->Write(pszElementStart, (ULONG)(pszNextElement - pszElementStart), NULL); if (!SUCCEEDED(comResult)) return comResult; if (pszNextElement >= xmlEnd) break; comResult = stream->Write("\r\n", 2, NULL); if (!SUCCEEDED(comResult)) return comResult; break; } // Find one of the following: " > \ / pszElementEnd = StrPBrkA(pszElementEnd, "\">\\/"); CHAR chElementEnd = *pszElementEnd; if (chElementEnd == '\\') pszElementEnd += 2; else if (chElementEnd == '>') pszNextElement = pszElementEnd + 1; else if (chElementEnd == '/' && *(pszElementEnd + 1) == '>') { --indentLevel; pszNextElement = pszElementEnd + 2; } else { if (chElementEnd == '\\') pszElementEnd += 2; ++pszElementEnd; } } if (pszNextElement >= xmlEnd) break; } if (!SUCCEEDED(comResult)) return comResult; return stream->Commit(STGC_DEFAULT); } HRESULT CDUIResourceManager::_DebugSaveDUIResourceToFile(LPWSTR szDUIPath) { LPCSTR pszXML; DWORD cbXMLSize; HRESULT result = GetModuleResourceData(_hInst, (LPCWSTR)_uResourceID, L"UIFILE", &pszXML, &cbXMLSize); if (!SUCCEEDED(result)) return result; CComPtr<IStream> stream; result = SHCreateStreamOnFileW(szDUIPath, STGM_CREATE | STGM_SHARE_EXCLUSIVE | STGM_READWRITE, &stream); if (SUCCEEDED(result)) result = s_DebugPrettyPrintXMLToFile(pszXML, stream, cbXMLSize); return result; } HRESULT CDUIResourceManager::_DebugEnsureDUIFile(LPWSTR* ppszPath, FILETIME* pftLastWrite) { LPWSTR filePath; HRESULT result = _DebugGetDUIPath(&filePath); if (!SUCCEEDED(result)) return result; FILETIME lastWrite; result = s_DebugGetDUIFileLastWrite(filePath, &lastWrite); if (result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) { result = _DebugSaveDUIResourceToFile(filePath); if (!SUCCEEDED(result)) { delete[] filePath; return result; } result = s_DebugGetDUIFileLastWrite(filePath, &lastWrite); } if (!SUCCEEDED(result)) { delete[] filePath; return result; } *ppszPath = filePath; *pftLastWrite = lastWrite; return result; } HRESULT CDUIResourceManager::s_DebugLoadFileToMemory(LPCWSTR pszFile, LPWSTR* ppszOutBuf) { CComPtr<IStream> stream; HRESULT result = SHCreateStreamOnFile(pszFile, STGM_READ, &stream); if (!SUCCEEDED(result)) return result; STATSTG stats = { 0 }; result = stream->Stat(&stats, STATFLAG_DEFAULT); if (!SUCCEEDED(result)) return result; if (stats.cbSize.HighPart) return E_FAIL; DWORD ansiSize = stats.cbSize.LowPart + 1; if (ansiSize < stats.cbSize.LowPart) return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); LPSTR ansiBuf = new CHAR[ansiSize]; DWORD readBytes = 0; result = stream->Read(ansiBuf, stats.cbSize.LowPart, &readBytes); if (stats.cbSize.LowPart != readBytes) { delete[] ansiBuf; return E_FAIL; } ansiBuf[stats.cbSize.LowPart] = 0; DWORD uniSize = ansiSize * 2; if (uniSize < ansiSize) return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); *ppszOutBuf = new WCHAR[uniSize]; SHAnsiToUnicode(ansiBuf, *ppszOutBuf, ansiSize); delete[] ansiBuf; return result; } HMODULE CDUIResourceManager::GetShellStyleHInstance() { HMODULE hInst = NULL; LPWSTR pszThemeFileName = new WCHAR[MAX_PATH]; LPWSTR pszColorBuff = new WCHAR[100]; if (!GetCurrentThemeName(pszThemeFileName, MAX_PATH, pszColorBuff, 100, NULL, 0)) { PathAppendW(pszThemeFileName, L"Shell"); PathAppendW(pszThemeFileName, pszColorBuff); PathAppendW(pszThemeFileName, L"ShellStyle.dll"); hInst = LoadLibraryExW(pszThemeFileName, 0i64, 2u); } if (!hInst) { ExpandEnvironmentStringsW(L"%SystemRoot%\\System32\\ShellStyle.dll", pszThemeFileName, 0x104u); hInst = LoadLibraryExW(pszThemeFileName, 0i64, 2u); } delete[] pszThemeFileName; delete[] pszColorBuff; return hInst; } HRESULT CDUIResourceManager::_DebugLoadParser(LPCWSTR pszPath, LPVOID** parser) { LPWSTR uiFile; HRESULT result = s_DebugLoadFileToMemory(pszPath, &uiFile); if (SUCCEEDED(result)) { if (g_DUIContext) result = g_DUIContext->CreateParser(parser); else result = DirectUI::DUIXmlParser::Create((DirectUI::DUIXmlParser**)parser, NULL, NULL, NULL, NULL); if (SUCCEEDED(result)) { HMODULE shellStyle = GetShellStyleHInstance(); BOOL unloadLater = TRUE; if (!shellStyle) { shellStyle = _hInst; unloadLater = FALSE; } if (g_DUIContext) result = g_DUIContext->Parser_SetXML(*parser, uiFile, shellStyle); else result = ((DirectUI::DUIXmlParser*)*parser)->SetXML((unsigned const short*)uiFile, shellStyle, g_twinUI); if (!SUCCEEDED(result)) { if (g_DUIContext) g_DUIContext->Parser_Destroy(*parser); else ((DirectUI::DUIXmlParser*)*parser)->Destroy(); *parser = 0; } if (unloadLater) FreeLibrary(shellStyle); } delete[] uiFile; } return result; } HRESULT CDUIResourceManager::DUI_LoadUIFileFromResources(HINSTANCE hModuleInstance, DWORD uFileID, LPWSTR* ppszUIFile) { LPCSTR ansiBuf; DWORD ansiSize; HRESULT result = GetModuleResourceData(hModuleInstance, (LPCWSTR)uFileID, L"UIFILE", &ansiBuf, &ansiSize); if (!SUCCEEDED(result)) return result; DWORD uniSize = (ansiSize + 1) * 2; if (uniSize < ansiSize) return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); *ppszUIFile = (LPWSTR)LocalAlloc(LMEM_ZEROINIT, uniSize); if (!*ppszUIFile) return HRESULT_FROM_WIN32(GetLastError()); SHAnsiToUnicode(ansiBuf, *ppszUIFile, uniSize); return result; } HRESULT CDUIResourceManager::DUI_CreateParserFromResource(HINSTANCE hinst, DWORD uID, LPVOID** ppParser) { HMODULE shellStyle = GetShellStyleHInstance(); BOOL unloadLater = TRUE; if (!shellStyle) { shellStyle = _hInst; unloadLater = FALSE; } LPWSTR uiFile; HRESULT result = DUI_LoadUIFileFromResources(hinst, uID, &uiFile); if (SUCCEEDED(result)) { if (g_DUIContext) result = g_DUIContext->CreateParser(ppParser); else result = DirectUI::DUIXmlParser::Create((DirectUI::DUIXmlParser**)ppParser, NULL, NULL, NULL, NULL); if (SUCCEEDED(result)) { if (g_DUIContext) result = g_DUIContext->Parser_SetXML(*ppParser, uiFile, shellStyle); else result = ((DirectUI::DUIXmlParser*)*ppParser)->SetXML((unsigned const short*)uiFile, shellStyle, g_twinUI); } } if (uiFile) LocalFree((HLOCAL)uiFile); if (unloadLater) FreeLibrary(shellStyle); if (!SUCCEEDED(result) && *ppParser) { if (g_DUIContext) g_DUIContext->Parser_Destroy(*ppParser); else ((DirectUI::DUIXmlParser*)*ppParser)->Destroy(); *ppParser = 0; } return result; } HRESULT CDUIResourceManager::_DebugCreateParser(REFCOUNTEDPARSER* prcp, LPVOID** ppParser) { LPWSTR debugUiFilePath; FILETIME debugUiFileLastWrite; if (SUCCEEDED(_DebugEnsureDUIFile(&debugUiFilePath, &debugUiFileLastWrite))) { HRESULT result = _DebugLoadParser(debugUiFilePath, ppParser); if (SUCCEEDED(result)) { if (prcp->spszDUIPath) delete[] prcp->spszDUIPath; prcp->spszDUIPath = debugUiFilePath; prcp->ftDUILastWrite = debugUiFileLastWrite; return result; } } return DUI_CreateParserFromResource(_hInst, _uResourceID, ppParser); } HRESULT CDUIResourceManager::_InitParserForThread() { REFCOUNTEDPARSER* rcp = (REFCOUNTEDPARSER*)TlsGetValue(this->_tlsParser); if (rcp) { ++_uInitCount; return ERROR_SUCCESS; } rcp = new REFCOUNTEDPARSER(); LPVOID* pParser = 0; HRESULT result = _DebugCreateParser(rcp, &pParser); if (SUCCEEDED(result)) { rcp->cRefCount = 1; rcp->pParser = pParser; result = TlsSetValue(_tlsParser, rcp) == 0 ? E_FAIL : 0; if (SUCCEEDED(result)) return result; if (g_DUIContext) g_DUIContext->Parser_Destroy(pParser); else ((DirectUI::DUIXmlParser*)pParser)->Destroy(); } if (rcp) { if (rcp->spszDUIPath) delete[] rcp->spszDUIPath; delete rcp; } TlsSetValue(_tlsParser, NULL); return result; } void CDUIResourceManager::_UninitParserForThread() { REFCOUNTEDPARSER* rcp = ((REFCOUNTEDPARSER*)TlsGetValue(_tlsParser)); if (--rcp->cRefCount == 1) { if (g_DUIContext) g_DUIContext->Parser_Destroy(rcp->pParser); else ((DirectUI::DUIXmlParser*)rcp->pParser)->Destroy(); if (rcp->spszDUIPath) delete[] rcp->spszDUIPath; delete rcp; TlsSetValue(_tlsParser, NULL); } } void CDUIResourceManager::Initialize(HINSTANCE hInst, DWORD uResourceID, LPCVOID *rgRegister, DWORD cRegister, LPCWSTR pszMarkupOverrideRegValue, BOOL fDebug) { _hInst = hInst; _uInitCount = 0; _tlsParser = -1; _uResourceID = uResourceID; _rgRegister = rgRegister; _cRegister = cRegister; _pszMarkupOverrideRegValue = pszMarkupOverrideRegValue; _fDebug = fDebug; InitializeSRWLock(&this->_srwlock); } HRESULT CDUIResourceManager::InitThread() { ExclusiveSRW scopeLock(&this->_srwlock); HRESULT result = 0; if (!this->_uInitCount) { if (g_DUIContext) result = g_DUIContext->InitProcess(); else result = InitProcessPriv(9, g_twinUI, 1, 1, FALSE); if (!SUCCEEDED(result)) return result; result = _RegisterElements(); if (!SUCCEEDED(result)) return result; _tlsParser = TlsAlloc(); if (_tlsParser == TLS_OUT_OF_INDEXES) { if (g_DUIContext) g_DUIContext->UnInitProcess(); else UnInitProcessPriv(g_twinUI); return E_FAIL; } } if (g_DUIContext) result = g_DUIContext->InitThread(); else result = ::InitThread(2); if (!SUCCEEDED(result)) return result; result = _InitParserForThread(); if (SUCCEEDED(result)) { ++_uInitCount; return result; } if (g_DUIContext) g_DUIContext->UnInitThread(); else ::UnInitThread(); if (!_uInitCount) { TlsFree(_tlsParser); _tlsParser = -1; if (g_DUIContext) g_DUIContext->UnInitProcess(); else UnInitProcessPriv(g_twinUI); } return result; } void CDUIResourceManager::UnInitThread() { ExclusiveSRW scopeLock(&this->_srwlock); --_uInitCount; _UninitParserForThread(); if (g_DUIContext) g_DUIContext->UnInitThread(); else ::UnInitThread(); if (!_uInitCount) { TlsFree(_tlsParser); _tlsParser = -1; if (g_DUIContext) g_DUIContext->UnInitProcess(); else UnInitProcessPriv(g_twinUI); } } LPVOID CDUIResourceManager::GetParserForThread() { return ((REFCOUNTEDPARSER*)TlsGetValue(_tlsParser))->pParser; } HRESULT CDUIResourceManager::ReloadParser(LPVOID* ppParser) { REFCOUNTEDPARSER* rcp = (REFCOUNTEDPARSER*)TlsGetValue(_tlsParser); if (!rcp) return E_FAIL; LPVOID* pParser; HRESULT result = _DebugCreateParser(rcp, &pParser); if (SUCCEEDED(result)) { if (rcp->pParser) { if (g_DUIContext) g_DUIContext->Parser_Destroy(rcp->pParser); else ((DirectUI::DUIXmlParser*)rcp->pParser)->Destroy(); } rcp->pParser = pParser; ppParser = pParser; } return result; } BOOL CDUIResourceManager::DebugReloadParser() { REFCOUNTEDPARSER* rcp = (REFCOUNTEDPARSER*)TlsGetValue(_tlsParser); if (!rcp) return FALSE; LPWSTR debugUiFilePath; FILETIME debugUiFileLastWrite; LPVOID* pParser; if (SUCCEEDED(_DebugEnsureDUIFile(&debugUiFilePath, &debugUiFileLastWrite))) { // Debug file is the same, or we failed loading using a newer one if (rcp->spszDUIPath && !StrCmpIW(rcp->spszDUIPath, debugUiFilePath) && !CompareFileTime(&rcp->ftDUILastWrite, &debugUiFileLastWrite) || !SUCCEEDED(_DebugLoadParser(debugUiFilePath, &pParser))) { delete[] debugUiFilePath; return FALSE; } // Loaded using a newer debug file if (rcp->spszDUIPath) delete[] rcp->spszDUIPath; rcp->spszDUIPath = debugUiFilePath; } else { // Debug file wasn't used or regular DLL resource failed if (!rcp->spszDUIPath || !SUCCEEDED(DUI_CreateParserFromResource(_hInst, _uResourceID, &pParser))) return FALSE; // Loaded using regular DLL resource after a debug one was used delete[] rcp->spszDUIPath; debugUiFileLastWrite.dwLowDateTime = 0; debugUiFileLastWrite.dwHighDateTime = 0; } rcp->ftDUILastWrite = debugUiFileLastWrite; if (g_DUIContext) g_DUIContext->Parser_Destroy(rcp->pParser); else ((DirectUI::DUIXmlParser*)rcp->pParser)->Destroy(); rcp->pParser = pParser; return TRUE; }
14,732
C++
.cpp
529
25.187146
158
0.737837
thebookisclosed/shsxs
38
1
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,910
shsxs.cpp
thebookisclosed_shsxs/shsxs.cpp
// shsxs.cpp : Defines the exported functions for the DLL application. // #include "common.h" #include <ShlObj.h> #include "duilib.h" #include "rpenum.h" #include "rpstructclass.h" #include "rpcom.h" #include "rpdatablob.h" extern "C" HRESULT __stdcall RP_CFolderThumbnail_GetCoordinates(POSITION pos, DWORD *x, DWORD *y) { switch (pos) { default: *x = 0; *y = 0; break; case POSITION_TOP_RIGHT: *x = 176; *y = 0; break; case POSITION_MIDDLE_RIGHT: *x = 176; *y = 88; break; case POSITION_BOTTOM_RIGHT: *x = 176; *y = 176; break; case POSITION_BOTTOM_CENTER: *x = 88; *y = 176; break; case POSITION_BOTTOM_LEFT: *x = 0; *y = 176; break; } return ERROR_SUCCESS; } extern "C" void __stdcall RP_CFolderThumbnail_GetSize(POSITION pos, SIZE *sizeOut, BYTE smallSize) { DWORD result; if (pos) result = smallSize ? 32 : 80; else result = smallSize ? 64 : 168; (*sizeOut).cx = result; (*sizeOut).cy = result; //return result; } extern "C" void __stdcall RP_CFolderThumbnail_ReadSettingsFromRegistry() { } extern "C" LPVOID __stdcall RP_CallScheduleGadgetTransitions(CScheduleGadgetTransitionsContext* context) { return context->Invoke(context->GetTransitionContext()); } extern "C" HRESULT __stdcall RP_CreateSettingsWindow(LPCWSTR lpTitle, HWND* hwnd, LPVOID prevPopup, IPopupWindow **popup) { *popup = 0; if (!lpTitle) return E_INVALIDARG; CComPtr<ICharmsWindowFactory> icwf; HRESULT comResult = CoCreateInstance(CLSID_CharmsWindowFactory, NULL, 1, IID_PPV_ARGS(&icwf)); if (SUCCEEDED(comResult)) { CComPtr<ICharmWindow> icw; comResult = icwf->CreateCharmWindow(hwnd, CHARMS_SIZE_NARROW, &icw); if (SUCCEEDED(comResult)) { IPopupWindow *ipw; comResult = icw->QueryInterface(IID_PPV_ARGS(&ipw)); if (SUCCEEDED(comResult)) { ipw->put_Title(lpTitle); icw->put_PreviousPopup(prevPopup); *popup = ipw; } } } return comResult; } extern "C" HRESULT __stdcall RP_CreateVANWindow(ICharmWindow **charm, IPopupWindow **popup, HWND* hwnd) { *charm = 0; *popup = 0; *hwnd = 0; CComPtr<ICharmsWindowFactory> icwf; HRESULT comResult = CoCreateInstance(CLSID_CharmsWindowFactory, NULL, 1, IID_PPV_ARGS(&icwf)); if (SUCCEEDED(comResult)) { comResult = icwf->CreateCharmWindow(NULL, CHARMS_SIZE_NARROW, &*charm); if (SUCCEEDED(comResult)) { CComPtr<IOleWindow> iow; comResult = (*charm)->QueryInterface(IID_PPV_ARGS(&iow)); if (SUCCEEDED(comResult)) { iow->GetWindow(hwnd); if (SUCCEEDED(comResult)) { comResult = (*charm)->QueryInterface(IID_PPV_ARGS(&*popup)); } } } } return comResult; } extern "C" HRESULT __stdcall RP_Enabled() { return 1; } extern "C" HRESULT __stdcall RP_GetCharmBarItemArray(DWORD type, DWORD *&charmResources, LPVOID *charmCount) { charmResources = (DWORD*)*&g_Charms; *charmCount = (LPVOID)5; return ERROR_SUCCESS; } extern "C" HRESULT __stdcall RP_GetCharmBarItemArray1(DWORD *&charmResources, LPVOID *charmCount) { charmResources = (DWORD*)*&g_Charms1; *charmCount = (LPVOID)6; return ERROR_SUCCESS; } extern "C" HRESULT __stdcall RP_GetCharmBarItemArray2(DWORD type, DWORD *&charmResources, LPVOID *charmCount) { if (type == 1) charmResources = (DWORD*)*&g_Charms2_Bottom; else charmResources = (DWORD*)*&g_Charms2_Right; *charmCount = (LPVOID)5; return ERROR_SUCCESS; } extern "C" HRESULT __stdcall RP_GetCharmBarItemArray3(DWORD type, DWORD *&charmResources, LPVOID *charmCount) { if (type == 1) charmResources = (DWORD*)*&g_Charms3_Bottom; else charmResources = (DWORD*)*&g_Charms3_Right; *charmCount = (LPVOID)5; return ERROR_SUCCESS; } extern "C" LPCWSTR __stdcall RP_GetDDClassName() { return L"Snapped Desktop"; } extern "C" float __stdcall RP_GetKeyboardThumbKeyWidthRatio(int a1, int a2, float a3) { float result = (float)a1 / ((float)a2 * a3); if (result > 900.0) return (float)900.0 / result; else return 1.0; } extern "C" float __stdcall RP_GetKeyboardThumbKeyWidthRatio2(int a1, float a2, int a3, float a4) { int result = (int)(a1 / (a2 * a4)); if (result > a3) return (float)a3 / (float)result; else return 1.0; } extern "C" int __stdcall RP_GetKeyboardThumbRowHeight(int a1, float a2) { if ((float)a1 / a2 > 1200.0) return (int)(a2 * 1200.0); else return a1; } extern "C" int __stdcall RP_GetKeyboardThumbRowHeight2(int a1, int a2, float a3, BYTE a4) { float result = a2 * a3; if ((int)result < a1) a1 = (int)result; if (a4) a1 = (int)(a1 * 1.13824); return a1; } EXTERN_C IMAGE_DOS_HEADER __ImageBase; #define HINST_THISCOMPONENT ((HINSTANCE)&__ImageBase) extern "C" HRESULT __stdcall RP_InitCam() { HRESULT duiCallRes = ERROR_SUCCESS; if (InitProcessPriv(13, HINST_THISCOMPONENT, 1, 1, 0) >= 0 || InitProcessPriv(14, HINST_THISCOMPONENT, 1, 1, 0) >= 0) { duiCallRes = InitThread(0x10002); if (duiCallRes < 0) { UnInitProcessPriv(HINST_THISCOMPONENT); } } return duiCallRes; } extern "C" HRESULT __stdcall RP_InitLauncherDataLayer(ICondition *condition, LPCWSTR lpName, IShellItem **shellItem) { *shellItem = 0; CComPtr<ISearchFolderItemFactoryPrivEx> sfifEx; HRESULT comResult = CoCreateInstance(CLSID_SearchFolderItemFactory, NULL, 3, IID_PPV_ARGS(&sfifEx)); if (SUCCEEDED(comResult)) { CComPtr<IScopeFactory> sf; comResult = CoCreateInstance(CLSID_ScopeFactory, NULL, 3, IID_PPV_ARGS(&sf)); if (SUCCEEDED(comResult)) { CComPtr<IScope> scope; comResult = sf->CreateScope(IID_PPV_ARGS(&scope)); if (SUCCEEDED(comResult)) { CComPtr<IScopeItem> appsScopeItem; comResult = sf->CreateScopeItemFromKnownFolder(FOLDERID_AppsFolder, SI_TYPE_INCLUDE, SI_DEPTH_SHALLOW, SI_FLAG_FORCEEXHAUSTIVE, IID_PPV_ARGS(&appsScopeItem)); if (SUCCEEDED(comResult)) comResult = scope->AddScopeItem(appsScopeItem); if (SUCCEEDED(comResult)) { CComPtr<IShellItem> startMenuLauncherProvider; if (SHCreateItemFromParsingName(L"shell:::{98F275B4-4FFF-11E0-89E2-7B86DFD72085}", NULL, IID_PPV_ARGS(&startMenuLauncherProvider))) { SFGAOF attribs; if (startMenuLauncherProvider->GetAttributes(SFGAO_FOLDER, &attribs) && attribs) { CComPtr<IScopeItem> launchProvScopeItem; comResult = sf->CreateScopeItemFromShellItem(startMenuLauncherProvider, SI_TYPE_INCLUDE, SI_DEPTH_SHALLOW, SI_FLAG_FORCEEXHAUSTIVE, IID_PPV_ARGS(&launchProvScopeItem)); if (SUCCEEDED(comResult)) scope->AddScopeItem(launchProvScopeItem); } } sfifEx->SetScopeDirect(scope); } } } if (SUCCEEDED(comResult)) { CComPtr<ISearchFolderItemFactory> sfif; comResult = sfifEx->QueryInterface(IID_PPV_ARGS(&sfif)); if (SUCCEEDED(comResult)) { if (condition) comResult = sfif->SetCondition(condition); if (SUCCEEDED(comResult)) { comResult = sfif->SetDisplayName(lpName); if (SUCCEEDED(comResult)) comResult = sfif->GetShellItem(IID_PPV_ARGS(&*shellItem)); } } } } else if (comResult == REGDB_E_CLASSNOTREG || comResult == E_NOINTERFACE) { CComPtr<ISearchFolderItemFactory> sfif; comResult = CoCreateInstance(CLSID_SearchFolderItemFactory, NULL, 3, IID_PPV_ARGS(&sfif)); if (SUCCEEDED(comResult)) { CComPtr<IShellItem> isi; comResult = SHGetKnownFolderItem(FOLDERID_AppsFolder, KF_FLAG_DONT_VERIFY, NULL, IID_PPV_ARGS(&isi)); if (SUCCEEDED(comResult)) { CComPtr<IShellItemArray> isia; comResult = SHCreateShellItemArrayFromShellItem(isi, IID_PPV_ARGS(&isia)); if (SUCCEEDED(comResult)) { CComPtr<ISearchFolderItemFactoryPriv> isfifp; comResult = sfif->QueryInterface(IID_PPV_ARGS(&isfifp)); if (SUCCEEDED(comResult)) { comResult = isfifp->SetScopeWithDepth(isia, SI_DEPTH_SHALLOW); if (SUCCEEDED(comResult)) { if (condition) comResult = sfif->SetCondition(condition); if (SUCCEEDED(comResult)) { comResult = sfif->SetDisplayName(lpName); if (SUCCEEDED(comResult)) comResult = sfif->GetShellItem(IID_PPV_ARGS(&*shellItem)); } } } } } } } return comResult; } extern "C" HRESULT __stdcall RP_InitLauncherDataLayer2(IShellItem **shellItem) { *shellItem = 0; CComPtr<ISearchFolderItemFactoryPrivEx> sfifEx; HRESULT comResult = CoCreateInstance(CLSID_SearchFolderItemFactory, NULL, 3, IID_PPV_ARGS(&sfifEx)); if (SUCCEEDED(comResult)) { CComPtr<IScopeFactory> sf; comResult = CoCreateInstance(CLSID_ScopeFactory, NULL, 3, IID_PPV_ARGS(&sf)); if (SUCCEEDED(comResult)) { CComPtr<IScope> scope; comResult = sf->CreateScope(IID_PPV_ARGS(&scope)); if (SUCCEEDED(comResult)) { CComPtr<IScopeItem> appsScopeItem; comResult = sf->CreateScopeItemFromKnownFolder(FOLDERID_AppsFolder, SI_TYPE_INCLUDE, SI_DEPTH_SHALLOW, SI_FLAG_FORCEEXHAUSTIVE, IID_PPV_ARGS(&appsScopeItem)); if (SUCCEEDED(comResult)) comResult = scope->AddScopeItem(appsScopeItem); if (SUCCEEDED(comResult)) { CComPtr<IShellItem> startMenuLauncherProvider; if (SHCreateItemFromParsingName(L"shell:::{98F275B4-4FFF-11E0-89E2-7B86DFD72085}", NULL, IID_PPV_ARGS(&startMenuLauncherProvider))) { SFGAOF attribs; if (startMenuLauncherProvider->GetAttributes(SFGAO_FOLDER, &attribs) && attribs) { CComPtr<IScopeItem> launchProvScopeItem; comResult = sf->CreateScopeItemFromShellItem(startMenuLauncherProvider, SI_TYPE_INCLUDE, SI_DEPTH_SHALLOW, SI_FLAG_FORCEEXHAUSTIVE, IID_PPV_ARGS(&launchProvScopeItem)); if (SUCCEEDED(comResult)) scope->AddScopeItem(launchProvScopeItem); } } sfifEx->SetScopeDirect(scope); } } } if (SUCCEEDED(comResult)) { CComPtr<ISearchFolderItemFactory> sfif; comResult = sfifEx->QueryInterface(IID_PPV_ARGS(&sfif)); if (SUCCEEDED(comResult)) comResult = sfif->GetShellItem(IID_PPV_ARGS(&*shellItem)); } } return comResult; } extern "C" HRESULT __stdcall RP_InitLauncherDataLaye0(IShellItem **shellItem) { *shellItem = 0; CComPtr<ISearchFolderItemFactory> sfif; HRESULT comResult = CoCreateInstance(CLSID_SearchFolderItemFactory, NULL, 3, IID_PPV_ARGS(&sfif)); if (SUCCEEDED(comResult)) { CComPtr<IShellItem> isi; comResult = SHGetKnownFolderItem(FOLDERID_AppsFolder, KF_FLAG_DONT_VERIFY, NULL, IID_PPV_ARGS(&isi)); if (SUCCEEDED(comResult)) { CComPtr<IShellItemArray> isia; comResult = SHCreateShellItemArrayFromShellItem(isi, IID_PPV_ARGS(&isia)); if (SUCCEEDED(comResult)) { CComPtr<ISearchFolderItemFactoryPriv> isfifp; comResult = sfif->QueryInterface(IID_PPV_ARGS(&isfifp)); if (SUCCEEDED(comResult)) { comResult = isfifp->SetScopeWithDepth(isia, SI_DEPTH_SHALLOW); if (SUCCEEDED(comResult)) comResult = sfif->GetShellItem(IID_PPV_ARGS(&*shellItem)); } } } } return comResult; } extern "C" HRESULT __stdcall RP_InitSystemSetting() { HMODULE dui70 = GetModuleHandle(L"dui70.dll"); if (!dui70) return HRESULT_FROM_WIN32(GetLastError()); VoidCall RegisterPVLBehaviorFactory = (VoidCall)GetProcAddress(dui70, "RegisterPVLBehaviorFactory"); if (!RegisterPVLBehaviorFactory) return HRESULT_FROM_WIN32(GetLastError()); HRESULT duiCallRes = ERROR_SUCCESS; if (InitProcessPriv(13, HINST_THISCOMPONENT, 1, 1, 0) >= 0 || InitProcessPriv(14, HINST_THISCOMPONENT, 1, 1, 0) >= 0) { duiCallRes = InitThread(0x10002); if (duiCallRes < 0) { UnInitProcessPriv(HINST_THISCOMPONENT); return duiCallRes; } duiCallRes = RegisterPVLBehaviorFactory(); if (duiCallRes < 0) { UnInitThread(); UnInitProcessPriv(HINST_THISCOMPONENT); } } return duiCallRes; } extern "C" int __stdcall RP_InitializeFeedbackRegion(HDC hDC, const RECT* lprc, COLORREF cRef) { BITMAPINFO bmi; memset(&bmi, 0, sizeof(BITMAPINFO)); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = 1; bmi.bmiHeader.biHeight = 1; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; BYTE alpha = (cRef >> 24) & 0xFF; RGBQUAD color; color.rgbRed = alpha * GetRValue(cRef) / 0xFF; color.rgbGreen = alpha * GetGValue(cRef) / 0xFF; color.rgbBlue = alpha * GetBValue(cRef) / 0xFF; color.rgbReserved = alpha; return StretchDIBits(hDC, lprc->left, lprc->top, lprc->right - lprc->left, lprc->bottom - lprc->top, 0, 0, 1, 1, &color, &bmi, 0, SRCCOPY); } extern "C" UINT __stdcall RP_PrivateExtractIconsW(LPCWSTR szFileName, int nIconIndex, int cxIcon, int cyIcon, HICON *phicon, UINT *piconid, UINT nIcons, int flags) { if (nIconIndex != -162 && (nIconIndex <= -7 || nIconIndex > -3)) return PrivateExtractIconsW(szFileName, nIconIndex, cxIcon, cyIcon, phicon, piconid, nIcons, flags); if (StrCmpIW(PathFindFileNameW(szFileName), L"imageres.dll")) return PrivateExtractIconsW(szFileName, nIconIndex, cxIcon, cyIcon, phicon, piconid, nIcons, flags); HMODULE phModule; if (!GetModuleHandleExW(6, (LPCWSTR)RP_PrivateExtractIconsW, &phModule)) return PrivateExtractIconsW(szFileName, nIconIndex, cxIcon, cyIcon, phicon, piconid, nIcons, flags); WCHAR Filename[MAX_PATH]; if (GetModuleFileNameW(phModule, Filename, MAX_PATH)) { UINT localExtractResult = PrivateExtractIconsW(Filename, nIconIndex, cxIcon, cyIcon, phicon, piconid, nIcons, flags); if (localExtractResult > 0) return localExtractResult; } return PrivateExtractIconsW(szFileName, nIconIndex, cxIcon, cyIcon, phicon, piconid, nIcons, flags); } extern "C" HRESULT __stdcall RP_SetTimestampForApp(IImmersiveApplication *app, FILETIME *time) { CComPtr<IPropertyStore> ps; HRESULT comResult = app->OpenPropertyStore(IAGPS_DEFAULT, IID_PPV_ARGS(&ps)); if ((comResult & 0x80000000) == 0) { PROPVARIANT pv = {}; pv.vt = VT_FILETIME; pv.filetime = *time; ps->SetValue(PKEY_ImmersiveApplication_VisibleTime, pv); } return comResult; } extern "C" DWORD __stdcall RP_VersionCheck() { DWORD version = 26; HKEY optKey; if (!RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer", 0, KEY_QUERY_VALUE, &optKey)) { DWORD dwData; DWORD cbData = sizeof(DWORD); if (!RegQueryValueEx(optKey, L"RPVersion", NULL, NULL, (LPBYTE)&dwData, &cbData)) version = dwData; RegCloseKey(optKey); } return version; } extern "C" void __stdcall RP_PickerSetDUIContext(RP_CDUIContext *pDUIContext) { g_DUIContext = pDUIContext; } CDUIResourceManager* PickerDUIResourceManager; extern "C" HRESULT __stdcall RP_InitializePickerDUIResourceManager(HINSTANCE hInstance, DWORD uResourceID, LPCVOID* rgRegister, DWORD cRegister, LPCWSTR pszMarkupOverrideRegValue, BOOL fDebug) { if (!g_DUIContext) g_twinUI = GetModuleHandleW(L"twinui.dll"); static CDUIResourceManager pickerMgr; pickerMgr.Initialize(hInstance, uResourceID, rgRegister, cRegister, pszMarkupOverrideRegValue, fDebug); PickerDUIResourceManager = &pickerMgr; return ERROR_SUCCESS; } extern "C" HRESULT __stdcall RP_GetPickerDUIResourceManager(CDUIResourceManager *&resMgr) { resMgr = PickerDUIResourceManager; return ERROR_SUCCESS; } extern "C" DWORD __stdcall RP_GetLayoutManagerBandDependencies(BAND_DEPENDENCY *&pprgBandDeps, int *pcDeps) { HLOCAL mem = LocalAlloc(0, 10*sizeof(BAND_DEPENDENCY)); memcpy(mem, (DWORD*)*&g_BandDeps, 10*sizeof(BAND_DEPENDENCY)); pprgBandDeps = (BAND_DEPENDENCY*)*&mem; *pcDeps = 10; return ERROR_SUCCESS; }
15,294
C++
.cpp
475
29.172632
192
0.734208
thebookisclosed/shsxs
38
1
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,911
rpcom.h
thebookisclosed_shsxs/rpcom.h
MIDL_INTERFACE("137BD0F9-6676-41DE-ACC7-D37DD20272D3") ICharmWindow : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE put_PreviousPopup(LPVOID popup) = 0; }; MIDL_INTERFACE("C7A0FC17-C704-491B-AC4A-DF596D71BD5A") IPopupWindow : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE get_Title(LPWSTR title) = 0; virtual HRESULT STDMETHODCALLTYPE put_Title(LPCWSTR title) = 0; }; MIDL_INTERFACE("9812962F-B8B4-4B38-BB03-21F07975361A") ICharmsWindowFactory : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE CreateCharmWindow(HWND* hwnd, CHARMS_SIZE charmSize, ICharmWindow **charm) = 0; }; //c153e702-afcc-4f45-9a75-a70217f72db8 static const CLSID CLSID_CharmsWindowFactory = { 0xc153e702, 0xafcc, 0x4f45, { 0x9a, 0x75, 0xa7, 0x02, 0x17, 0xf7, 0x2d, 0xb8 } }; MIDL_INTERFACE("54410B83-6787-4418-9735-5AAAABE83A9A") IScopeFactory : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE CreateScope(const IID &riid, LPVOID *ppv) = 0; virtual HRESULT STDMETHODCALLTYPE CreateScopeFromShellItemArray() = 0; virtual HRESULT STDMETHODCALLTYPE CreateScopeFromIDLists() = 0; virtual HRESULT STDMETHODCALLTYPE CreateScopeItemFromIDList() = 0; virtual HRESULT STDMETHODCALLTYPE CreateScopeItemFromKnownFolder(const IID &id1, SCOPE_ITEM_TYPE type, SCOPE_ITEM_DEPTH depth, SCOPE_ITEM_FLAGS flags, const IID &id2, LPVOID *ppv) = 0; virtual HRESULT STDMETHODCALLTYPE CreateScopeItemFromShellItem(IShellItem *si, SCOPE_ITEM_TYPE type, SCOPE_ITEM_DEPTH depth, SCOPE_ITEM_FLAGS flags, const IID &id2, LPVOID *ppv) = 0; }; //6746C347-576B-4F73-9012-CDFEEA251BC4 static const CLSID CLSID_ScopeFactory = { 0x6746C347, 0x576B, 0x4F73, { 0x90, 0x12, 0xCD, 0xFE, 0xEA, 0x25, 0x1B, 0xC4 } }; MIDL_INTERFACE("DD400FF4-A119-405F-970E-A9A5E7E828C0") IScopeItem : public IUnknown { }; MIDL_INTERFACE("655D1685-2BFD-4F7F-AD22-5AB61C8D8798") IScope : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE AddScopeItem(IScopeItem *scopeItem) = 0; }; MIDL_INTERFACE("BD59C2F9-F763-400D-A76E-028C35D047B8") ISearchFolderItemFactoryPrivEx : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE SetScopeWithDepth(IShellItemArray* scope, SCOPE_ITEM_DEPTH depth) = 0; virtual HRESULT STDMETHODCALLTYPE SetScopeDirect(IScope *scope) = 0; }; MIDL_INTERFACE("18455d05-d8f8-47f0-ba4c-c3aaf9c7035f") ISearchFolderItemFactoryPriv : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE SetScopeWithDepth(IShellItemArray* scope, SCOPE_ITEM_DEPTH depth) = 0; }; //1E87508D-89C2-42F0-8A7E-645A0F50CA58 static const CLSID FOLDERID_AppsFolder = { 0x1E87508D, 0x89C2, 0x42F0, { 0x8A, 0x7E, 0x64, 0x5A, 0x0F, 0x50, 0xCA, 0x58 } }; MIDL_INTERFACE("5CEC3DE3-0905-4301-955B-C871C0FFEE84") IImmersiveApplication : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Hide() = 0; virtual HRESULT STDMETHODCALLTYPE Show() = 0; virtual HRESULT STDMETHODCALLTYPE Activate() = 0; virtual HRESULT STDMETHODCALLTYPE SetPos() = 0; virtual HRESULT STDMETHODCALLTYPE MoveMonitor() = 0; virtual HRESULT STDMETHODCALLTYPE LockPresentation() = 0; virtual HRESULT STDMETHODCALLTYPE UnlockPresentation() = 0; virtual HRESULT STDMETHODCALLTYPE GetWindow() = 0; virtual HRESULT STDMETHODCALLTYPE GetApplicationId() = 0; virtual HRESULT STDMETHODCALLTYPE OpenPropertyStore(IMMAPPPROPERTYSTOREFLAGS flags, const IID &iid, LPVOID *ppv) = 0; }; const PROPERTYKEY PKEY_ImmersiveApplication_VisibleTime = { { 0xD33EA413, 0xDB44, 0x4CDC, { 0x88, 0xE6, 0xD2, 0x83, 0xAA, 0x98, 0x5A, 0xEF } }, 8 };
3,514
C++
.h
78
43.589744
185
0.806188
thebookisclosed/shsxs
38
1
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,912
rpenum.h
thebookisclosed_shsxs/rpenum.h
enum POSITION { POSITION_TOP_LEFT = 0, POSITION_TOP_RIGHT = 1, POSITION_MIDDLE_RIGHT = 2, POSITION_BOTTOM_RIGHT = 3, POSITION_BOTTOM_CENTER = 4, POSITION_BOTTOM_LEFT = 5, POSITION_MAX = 6, }; enum CHARMS_SIZE { CHARMS_SIZE_DEFAULT = 0, CHARMS_SIZE_FIRST = 0, CHARMS_SIZE_NARROW = 1, CHARMS_SIZE_WIDE = 2, CHARMS_SIZE_LAST = 2 }; enum SCOPE_ITEM_TYPE { SI_TYPE_INVALID = 0, SI_TYPE_INCLUDE = 1, SI_TYPE_EXCLUDE = 2, }; enum SCOPE_ITEM_DEPTH { SI_DEPTH_INVALID = 0, SI_DEPTH_SHALLOW = 1, SI_DEPTH_DEEP = 2, }; enum SCOPE_ITEM_FLAGS { SI_FLAG_DEFAULT = 0, SI_FLAG_FORCEEXHAUSTIVE = 1, SI_FLAG_KNOWNFOLDER = 2, SI_FLAG_FASTPROPERTIESONLY = 4, SI_FLAG_FASTITEMSONLY = 8, SI_FLAG_NOINFOBAR = 16, SI_FLAG_USECHILDSCOPES = 32, SI_FLAG_FASTPROVIDERSONLY = 64, SI_FLAG_OVERRIDE_FOLDER_BEHAVIOR = 128, }; enum IMMAPPPROPERTYSTOREFLAGS { IAGPS_DEFAULT = 0 }; enum ZBID { ZBID_DEFAULT = 0, ZBID_DESKTOP = 1, ZBID_UIACCESS = 2, ZBID_IMMERSIVE_IHM = 3, ZBID_IMMERSIVE_NOTIFICATION = 4, ZBID_IMMERSIVE_HORIZON = 5, ZBID_IMMERSIVE_DOWNSPACE = 6, ZBID_IMMERSIVE_MOGO = 7, ZBID_IMMERSIVE_ACTION_SPACE = 8, ZBID_IMMERSIVE_MOBODY = 9, ZBID_IMMERSIVE_DOCK = 10, ZBID_IMMERSIVE_BACKGROUND = 11, ZBID_IMMERSIVE_COMPANION = 12, ZBID_IMMERSIVE_STAGING = 13, ZBID_IMMERSIVE_ALTER_EGO = 14, };
1,351
C++
.h
62
19.419355
41
0.71028
thebookisclosed/shsxs
38
1
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,913
rpstructclass.h
thebookisclosed_shsxs/rpstructclass.h
struct BAND_DEPENDENCY { enum ZBID zbid; enum ZBID rgBandDeps[15]; }; class CScheduleGadgetTransitionsContext { public: virtual LPVOID GetTransitionContext() = 0; virtual LPVOID Invoke(LPVOID transition) = 0; };
218
C++
.h
11
18.272727
46
0.801932
thebookisclosed/shsxs
38
1
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,914
rpdatablob.h
thebookisclosed_shsxs/rpdatablob.h
static const DWORD g_Charms[30] = { 0, 7101, 7106, 7111, 7201, 2, 1, 7103, 7108, 7113, 7203, 2, 2, 7105, 7110, 7116, 7206, 1, 3, 7104, 7109, 7114, 7204, 2, 4, 7102, 7107, 7112, 7202, 2 }; static const DWORD g_Charms1[30] = { 6, 7106, 7116, 7206, 1, 5, 7105, 7115, 7205, 1, 2, 7101, 7111, 7201, 2, 1, 7103, 7113, 7203, 2, 4, 7104, 7114, 7204, 2, 3, 7102, 7112, 7202, 2 }; static const DWORD g_Charms2_Bottom[40] = { 4, 7102, 7107, 7112, 2, 7212, 7217, 7222, 3, 7104, 7109, 7114, 2, 7210, 7215, 7220, 1, 7103, 7108, 7113, 2, 7213, 7218, 7223, 0, 7101, 7106, 7111, 2, 7211, 7216, 7221, 2, 7105, 7110, 7116, 1, 7214, 7219, 7224 }; static const DWORD g_Charms2_Right[40] = { 0, 7101, 7106, 7111, 2, 7221, 7226, 7231, 1, 7103, 7108, 7113, 2, 7223, 7228, 7234, 2, 7105, 7110, 7116, 1, 7224, 7229, 7235, 3, 7104, 7109, 7114, 2, 7220, 7225, 7230, 4, 7102, 7107, 7112, 2, 7222, 7227, 7233 }; static const DWORD g_Charms3_Bottom[40] = { 4, 7102, 7107, 7112, 2, 7212, 7217, 7238, 3, 7104, 7109, 7114, 2, 7210, 7215, 7236, 1, 7103, 7108, 7113, 2, 7213, 7218, 7239, 0, 7101, 7106, 7111, 2, 7211, 7216, 7237, 2, 7105, 7110, 7116, 1, 7214, 7219, 7240 }; static const DWORD g_Charms3_Right[40] = { 0, 7101, 7106, 7111, 2, 7221, 7226, 7231, 1, 7103, 7108, 7113, 2, 7223, 7228, 7234, 2, 7105, 7110, 7116, 1, 7224, 7229, 7235, 3, 7104, 7109, 7114, 2, 7220, 7225, 7230, 4, 7102, 7107, 7112, 2, 7222, 7227, 7233, }; static const BAND_DEPENDENCY g_BandDeps[10] = { { ZBID_IMMERSIVE_HORIZON, {}}, { ZBID_IMMERSIVE_NOTIFICATION, {ZBID_IMMERSIVE_HORIZON}}, { ZBID_IMMERSIVE_DOWNSPACE, {ZBID_IMMERSIVE_HORIZON}}, { ZBID_IMMERSIVE_COMPANION, {ZBID_IMMERSIVE_HORIZON}}, { ZBID_IMMERSIVE_DOCK, {ZBID_IMMERSIVE_HORIZON}}, { ZBID_IMMERSIVE_MOGO, {ZBID_IMMERSIVE_COMPANION, ZBID_IMMERSIVE_HORIZON}}, { ZBID_IMMERSIVE_ACTION_SPACE, {ZBID_IMMERSIVE_HORIZON}}, { ZBID_IMMERSIVE_STAGING, {}}, { ZBID_IMMERSIVE_MOBODY, {ZBID_IMMERSIVE_HORIZON, ZBID_IMMERSIVE_DOCK, ZBID_IMMERSIVE_COMPANION}}, { ZBID_IMMERSIVE_BACKGROUND, {}} };
2,037
C++
.h
55
35.2
99
0.666161
thebookisclosed/shsxs
38
1
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,915
common.h
thebookisclosed_shsxs/common.h
#ifndef COMMON_H #define COMMON_H #include <windows.h> #include <atlcomcli.h> #include <Shlwapi.h> #include "external\dui70.h" typedef HRESULT (WINAPI *VoidCall)(); #endif
174
C++
.h
8
20.5
37
0.77439
thebookisclosed/shsxs
38
1
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,916
duilib.h
thebookisclosed_shsxs/duilib.h
#ifndef DUILIB_H #define DUILIB_H #include "common.h" #include <Uxtheme.h> struct ExclusiveSRW { ExclusiveSRW(SRWLOCK* lock) : lock(lock) { AcquireSRWLockExclusive(lock); } ~ExclusiveSRW() { ReleaseSRWLockExclusive(lock); } private: SRWLOCK* lock; }; class RP_CDUIContext { public: virtual HRESULT InitProcess() = 0; virtual HRESULT UnInitProcess() = 0; virtual HRESULT InitThread() = 0; virtual HRESULT UnInitThread() = 0; virtual HRESULT CreateParser(LPVOID** ppParser) = 0; virtual HRESULT Parser_SetXML(LPVOID* pParser, LPCWSTR xml, HINSTANCE inst) = 0; virtual HRESULT Parser_Destroy(LPVOID* pParser) = 0; }; extern HMODULE g_twinUI; extern RP_CDUIContext* g_DUIContext; class CDUIResourceManager { RTL_SRWLOCK _srwlock; HINSTANCE _hInst; DWORD _uInitCount; DWORD _tlsParser; DWORD _uResourceID; LPCVOID* _rgRegister; DWORD _cRegister; LPCWSTR _pszMarkupOverrideRegValue; BOOL _fDebug; struct REFCOUNTEDPARSER { LPVOID* pParser; DWORD cRefCount; LPWSTR spszDUIPath; FILETIME ftDUILastWrite; }; HRESULT _RegisterElements(); HRESULT _DebugGetDUIPath(LPWSTR* pszDUIPath); HRESULT s_DebugGetDUIFileLastWrite(LPWSTR szDUIPath, FILETIME* writeTime); HRESULT GetModuleResourceData(HINSTANCE hModule, LPCWSTR pwszName, LPCWSTR pwszType, LPCSTR* prgb, DWORD* pcb); HRESULT s_DebugPrettyPrintXMLToFile(LPCSTR pszXML, IStream* stream, DWORD resSize); HRESULT _DebugSaveDUIResourceToFile(LPWSTR szDUIPath); HRESULT _DebugEnsureDUIFile(LPWSTR* ppszPath, FILETIME* pftLastWrite); HRESULT s_DebugLoadFileToMemory(LPCWSTR pszFile, LPWSTR* ppszOutBuf); HMODULE GetShellStyleHInstance(); HRESULT _DebugLoadParser(LPCWSTR pszPath, LPVOID** parser); HRESULT DUI_LoadUIFileFromResources(HINSTANCE hModuleInstance, DWORD uFileID, LPWSTR* ppszUIFile); HRESULT DUI_CreateParserFromResource(HINSTANCE hinst, DWORD uID, LPVOID** ppParser); HRESULT _DebugCreateParser(REFCOUNTEDPARSER* prcp, LPVOID** ppParser); HRESULT _InitParserForThread(); void _UninitParserForThread(); public: virtual void Initialize(HINSTANCE hInst, DWORD uResourceID, LPCVOID *rgRegister, DWORD cRegister, LPCWSTR pszMarkupOverrideRegValue, BOOL fDebug); virtual HRESULT InitThread(); virtual void UnInitThread(); virtual LPVOID GetParserForThread(); virtual HRESULT ReloadParser(LPVOID* ppParser); virtual BOOL DebugReloadParser(); }; #endif
2,392
C++
.h
72
30.888889
147
0.79974
thebookisclosed/shsxs
38
1
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,917
dui70.h
thebookisclosed_shsxs/external/dui70.h
#ifndef DUI70_H #define DUI70_H extern "C" __declspec(dllimport) HRESULT __stdcall UnInitThread(); extern "C" __declspec(dllimport) HRESULT __stdcall InitThread(DWORD nThreadMode); extern "C" __declspec(dllimport) HRESULT __stdcall UnInitProcessPriv(HINSTANCE hModule); extern "C" __declspec(dllimport) HRESULT __stdcall InitProcessPriv(DWORD dwExpectedVersion, HINSTANCE a2, CHAR fRegisterControls, CHAR fEnableUIAutomationProvider, BOOL fInitCommctl); class DirectUI { public: class Value; class DUIXmlParser { public: __declspec(dllimport) static long Create(DUIXmlParser** ppParserOut, Value* pfnGetSheetCallback(unsigned short const *,void *), void* pGetSheetContext, void pfnErrorCallback(unsigned short const*, unsigned short const *, int, void*), void* pErrorContext); __declspec(dllimport) long SetXML(unsigned short const* pBuffer, HINSTANCE hResourceInstance, HINSTANCE hControlsInstance); __declspec(dllimport) void Destroy(); }; }; #endif
969
C++
.h
17
55
258
0.794521
thebookisclosed/shsxs
38
1
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,918
box.cpp
be1_qspeakers/box.cpp
#include <QDebug> #include "box.h" QDomElement Box::toDomElement(QDomDocument& doc) const { QDomElement e = doc.createElement("box"); return e; } void Box::fromDomElement(const QDomElement &e) { if (e.tagName() != "box") qWarning() << __func__ << "wrong tag name while importing box!"; }
311
C++
.cpp
12
23
72
0.675676
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,919
importexport.cpp
be1_qspeakers/importexport.cpp
#include <QtCore> #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) #include <QStandardPaths> #endif #include <QDesktopServices> #include <QDir> #include <QDebug> #include "importexport.h" QString ImportExport::savePath; QString ImportExport::getSavePath(void) { if (!ImportExport::savePath.isNull() && !ImportExport::savePath.isEmpty()) { return ImportExport::savePath; } #if QT_VERSION >= QT_VERSION_CHECK(6,0,0) QString prefix = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation); #elif QT_VERSION >= QT_VERSION_CHECK(5,0,0) QString prefix = QStandardPaths::writableLocation(QStandardPaths::DataLocation); #else QString prefix = QDesktopServices::storageLocation(QDesktopServices::DataLocation); #endif QDir dir(prefix); if (!dir.exists()) dir.mkpath(prefix); QString path = prefix + QDir::separator() + SAVE_FILENAME; return path; } bool ImportExport::saveProject(const Speaker &speaker, const SealedBox &sbox, const PortedBox &pbox, const BandPassBox &bpbox, int number, int tab) { QString path = ImportExport::getSavePath(); qDebug() << "exporting" << path; QFile file(path); /* do not test if it exists, just override it */ return exportProject(file, speaker, sbox, pbox, bpbox, number, tab); } bool ImportExport::restoreProject(Speaker &speaker, SealedBox &sbox, PortedBox &pbox, BandPassBox &bpbox, int* number, int* tab) { QString path = ImportExport::getSavePath(); qDebug() << "importing" << path; QFile file(path); return importProject(speaker, sbox, pbox, bpbox, number, tab, file); } bool ImportExport::exportProject(QFile &file, const Speaker &speaker, const SealedBox &sbox, const PortedBox &pbox, const BandPassBox &bpbox, int number, int tab) { QDomDocument xml("QSpeakersProject"); QDomElement root = xml.createElement("project"); xml.appendChild(root); QDomElement spk = speaker.toDomElement(xml); root.appendChild(spk); QDomElement xsbox = sbox.toDomElement(xml); root.appendChild(xsbox); QDomElement xpbox = pbox.toDomElement(xml); root.appendChild(xpbox); QDomElement xbpbox = bpbox.toDomElement(xml); root.appendChild(xbpbox); QDomElement xlayout = xml.createElement("layout"); xlayout.setAttribute("sibling", number); root.appendChild(xlayout); QDomElement xstate = xml.createElement("state"); xstate.setAttribute("tab", tab); root.appendChild(xstate); if (!file.open(QIODevice::WriteOnly)) return false; if (!file.write(xml.toByteArray())) { file.close(); return false; } file.close(); return true; } bool ImportExport::importProject(Speaker &speaker, SealedBox &sbox, PortedBox &pbox, BandPassBox &bpbox, int *number, int *tab, QFile &file) { QDomDocument doc("QSpeakersProject"); if (!file.exists()) return false; if (!file.open(QIODevice::ReadOnly)) return false; if (!doc.setContent(&file)) { file.close(); return false; } file.close(); QDomElement root = doc.firstChildElement("project"); QDomNodeList speakers = root.elementsByTagName("speaker"); /* for now, only one speaker is considered */ QDomElement spk = speakers.at(0).toElement(); if (!spk.isNull()) speaker.fromDomElement(spk); /* crawl 1st level boxes */ QDomElement box = root.firstChildElement("box"); while (!box.isNull()) { if (box.attribute("type") == "sealed") sbox.fromDomElement(box); else if (box.attribute("type") == "ported") pbox.fromDomElement(box); else if (box.attribute("type") == "bandpass") bpbox.fromDomElement(box); else qWarning() << __func__ << "unrecognized box type"; box = box.nextSiblingElement("box"); } if (number != nullptr) { QDomElement layout = root.firstChildElement("layout"); if (layout.isNull()) *number = 1; /* default */ else *number = layout.attribute("sibling", "1").toInt(); } if (tab != nullptr) { QDomElement state = root.firstChildElement("state"); if (state.isNull()) *tab = 0; else *tab = state.attribute("tab", "0").toInt(); } return true; } void ImportExport::setSavePath(const QString &path) { ImportExport::savePath = path; }
4,421
C++
.cpp
121
31.07438
162
0.674555
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,920
plot.cpp
be1_qspeakers/plot.cpp
#include "plot.h" #include <QtCharts/QtCharts> #if QT_VERSION < QT_VERSION_CHECK(6,0,0) using namespace QtCharts; #endif Plot::Plot(QWidget *parent) : QChartView(parent), xmin(10.0), xmax(1000.0), vLine(nullptr), vLine3db(nullptr), vLabel3db(nullptr) { setCursor(Qt::CrossCursor); initializeChart(); initializeCurve(); initializeScales(); } Plot::Plot(QString title, QWidget *parent) : QChartView(parent), xmin(10.0), xmax(1000.0), vLine(nullptr), vLine3db(nullptr), vLabel3db(nullptr) { setCursor(Qt::CrossCursor); initializeChart(title); initializeCurve(); initializeScales(); } Plot::~Plot() { curve->clear(); delete curve; delete chart; delete vLine; delete vLine3db; delete vLabel3db; } void Plot::appendPointF(const QPointF &pointf) { curve->append(pointf); } void Plot::plot(const QList<double> x, QList<double> y) { QList<QPointF> samples; for (int i = 0; i < x.size(); i++) { QPointF p(x[i], y[i]); curve->append(p); } } void Plot::clear() { curve->clear(); } void Plot::setUseOpenGL(bool enable) { curve->setUseOpenGL(enable); } void Plot::initializeCurve() { curve = new QLineSeries(chart); chart->addSeries(curve); } void Plot::draw3dbVLine() { double x = curveXfromY(-3.0); double y1 = 10.0, y2 = -40.0; QPointF value1(x, y1); QPointF point1 = chart->mapToPosition(value1); QPointF value2 = QPointF(x, y2); QPointF point2 = chart->mapToPosition(value2); QLineF line (point1, point2); if (vLine3db) { this->scene()->removeItem(vLine3db); delete vLine3db; } vLine3db = this->scene()->addLine(line, QPen(Qt::DashLine)); if (vLabel3db) { this->scene()->removeItem(vLabel3db); delete vLabel3db; } QString label = QString(tr("%1 dB at %2 Hz")).arg(-3.0).arg(x); vLabel3db = this->scene()->addSimpleText(label); QPointF pos = chart->mapToPosition(value1); vLabel3db->setPos(pos); } void Plot::resizeEvent(QResizeEvent *event) { QChartView::resizeEvent(event); draw3dbVLine(); } bool Plot::viewportEvent(QEvent *event) { switch (event->type()) { case QEvent::ToolTip: return false; default: break; } return QChartView::viewportEvent(event); } void Plot::mouseMoveEvent(QMouseEvent *event) { if (event->buttons() != Qt::LeftButton) return; QPoint pos = event->pos(); QPointF val = chart->mapToValue(pos); double y = curveYfromX(val.x()); QString label = QString(tr("%1 dB at %2 Hz")).arg(y).arg(val.x()); #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) QToolTip::showText(event->globalPos(), label, this, QRect(), 10000); #else QToolTip::showText(event->globalPosition().toPoint(), label, this, QRect(), 10000); #endif drawVLine(pos); event->accept(); } void Plot::mousePressEvent(QMouseEvent *event) { if (event->buttons() != Qt::LeftButton) return; QPoint pos = event->pos(); QPointF val = chart->mapToValue(pos); double y = curveYfromX(val.x()); QString label = QString(tr("%1 dB at %2 Hz")).arg(round(y)).arg(round(val.x())); #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) QToolTip::showText(event->globalPos(), label, this, QRect(), 10000); #else QToolTip::showText(event->globalPosition().toPoint(), label, this, QRect(), 10000); #endif drawVLine(pos); event->accept(); } void Plot::mouseReleaseEvent(QMouseEvent *event) { if (vLine) { this->scene()->removeItem(vLine); delete vLine; vLine = nullptr; } event->accept(); } double Plot::curveXfromY(double y) { double x = 1.0; QList<QPointF> list = curve->points(); for (int i = 0; i < list.size() - 1; i++) { QPointF p1 = list.at(i); QPointF p2 = list.at(i+1); if (p1.y() <= y && p2.y() > y) { x = p1.x(); break; } } return x; } double Plot::curveYfromX(double x) { double y = 0.0; QList<QPointF> list = curve->points(); for (int i = 0; i < list.size() - 1; i++) { QPointF p1 = list.at(i); QPointF p2 = list.at(i+1); if (p1.x() <= x && p2.x() > x) { y = p1.y(); break; } } return y; } void Plot::drawVLine(QPoint pos) { QPointF val = chart->mapToValue(pos); /* redraw dashed vertical line */ double x = val.x(); QValueAxis* yaxis0 = qobject_cast<QValueAxis*>(chart->axes(Qt::Vertical, curve).at(0)); double ymin = yaxis0->min(); double ymax = yaxis0->max(); QPointF value1(x, ymin); QPointF point1 = chart->mapToPosition(value1); QPointF value2(x, ymax); QPointF point2 = chart->mapToPosition(value2); QLineF line (point1, point2); if (vLine) { this->scene()->removeItem(vLine); delete vLine; } vLine = this->scene()->addLine(line, QPen(Qt::DashLine)); } double Plot::getXmax() const { return xmax; } QLineSeries* Plot::series() const { return curve; } double Plot::getXmin() const { return xmin; } void Plot::initializeChart(const QString& title) { chart = new QChart(); chart->setTitle(title); chart->legend()->hide(); this->setChart(chart); this->setRenderHint(QPainter::Antialiasing); } void Plot::initializeScales() { QLogValueAxis *XAxis = new QLogValueAxis(); XAxis->setBase(10.0); XAxis->setLabelFormat("%g"); XAxis->setTitleText(tr("Frequency [Hz]")); XAxis->setMax(xmax); XAxis->setMin(xmin); XAxis->setMinorTickCount(8); chart->addAxis(XAxis, Qt::AlignBottom); curve->attachAxis(XAxis); QValueAxis *YAxis = new QValueAxis(); YAxis->setTitleText(tr("Sound pressure [dB]")); YAxis->setLabelFormat("%g"); YAxis->setMax(10); YAxis->setMin(-40); YAxis->setTickCount(6); YAxis->setMinorTickCount(1); chart->addAxis(YAxis, Qt::AlignLeft); curve->attachAxis(YAxis); }
6,026
C++
.cpp
231
21.619048
91
0.63167
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,921
portedbox.cpp
be1_qspeakers/portedbox.cpp
#include <QLocale> #include <QDebug> #include <math.h> #include "portedbox.h" PortedBox::PortedBox(double volume, double resfreq, unsigned int portnum, double portdiam, double portlen) : box(volume) { setResFreq(resfreq); portNum = portnum; setPortDiam(portdiam); setPortLen(portlen); slotActivated = false; } void PortedBox::setBoxVolume(double vol) { box.setVolume(vol); } void PortedBox::setPortNum(unsigned int value) { portNum = value; } void PortedBox::setPortLen(double len) { portLen = double ((int)(len * 100) / 100.0); } void PortedBox::setPortDiam(double diam) { portDiam = double ((int)(diam * 100) / 100.0); } void PortedBox::setSlotWidth(double width) { slotWidth = double ((int)(width * 100) / 100.0); } void PortedBox::setResFreq(double value) { resFreq = double ((int)(value * 100) / 100.0); } void PortedBox::setSlotPortActivated(bool enable) { slotActivated = enable; } double PortedBox::getBoxVolume() const { return box.getVolume(); } unsigned int PortedBox::getPortNum() const { return portNum; } double PortedBox::getPortLen() const { if (!slotActivated) return portLen; double x = getSlotWidth() / getSlotHeight(); if (x < 1) { x = getSlotHeight() / getSlotWidth(); } /* estimated from https://sites.google.com/site/francisaudio69/ */ return double ((int)((1.1 - log10(x + 1.1) * 0.35) * portLen * 100) / 100.0); } double PortedBox::getPortDiam() const { return portDiam; } bool PortedBox::getSlotPortActivated() const { return slotActivated; } double PortedBox::getSlotWidth() const { return slotWidth; } double PortedBox::getSlotHeight() const { /* width is manual, height is computed from eq. diam. */ return double ((int)((PI * pow(portDiam, 2.0)) / (4.0 * slotWidth) * 100) / 100.0); } double PortedBox::getResFreq() const { return resFreq; } void PortedBox::updatePorts(double sd, double xmax) { /* compute minimum port diameter and optionaly set it */ double vol = sd * xmax * 0.001; /* m³ */ double dmin = 100 * (20.3 * pow((pow(vol, 2.0) / getResFreq()), 0.25)) / sqrt(getPortNum()); /* cm */ setPortDiam(dmin); updateSlots(); updatePortsLength(); } void PortedBox::updateSlots() { /* compute square slot */ double diam = getPortDiam(); double s = sqrt(PI * pow(diam, 2.0) / 4.0); /* consider "width" over "height" and reset if too small */ if (slotWidth == 0.0) slotWidth = double ((int)(s * 100) / 100.0); } void PortedBox::updatePortsLength() { /* compute resulting length */ double diam = getPortDiam(); double res = getResFreq(); double vol = getBoxVolume(); double num = getPortNum(); double plen = ((23562.5 * pow(diam, 2.0)) * num / (vol * pow(res, 2.0))) - (K * diam); setPortLen(plen); } QDomElement PortedBox::toDomElement(QDomDocument& doc) const { QLocale c(QLocale::C); QDomElement e = Box::toDomElement(doc); e.setAttribute("type", "ported"); e.setAttribute("res", c.toString(resFreq)); QDomElement b = box.toDomElement(doc); e.appendChild(b); QDomElement p = doc.createElement("port"); p.setAttribute("num", c.toString(portNum)); p.setAttribute("len", c.toString(portLen)); p.setAttribute("diam", c.toString(portDiam)); p.setAttribute("width", c.toString(slotWidth)); p.setAttribute("slot", c.toString(slotActivated ? 1 : 0)); e.appendChild(p); return e; } void PortedBox::fromDomElement(const QDomElement &e) { QLocale c(QLocale::C); Box::fromDomElement(e); if (e.attribute("type") != "ported") { qWarning() << __func__ << "wrong box type! (not ported, giving up)"; return; } resFreq = c.toDouble(e.attribute("res")); QDomElement b = e.elementsByTagName("box").at(0).toElement(); box.fromDomElement(b); QDomElement p = e.elementsByTagName("port").at(0).toElement(); portNum = c.toUInt(p.attribute("num")); portLen = c.toDouble(p.attribute("len")); portDiam = c.toDouble(p.attribute("diam")); slotWidth = c.toDouble(p.attribute("width")); slotActivated = c.toUInt(p.attribute("slot")); } void PortedBox::render(QPainter *painter, const QRectF &area) const { if (!painter) return; #define PORTED_PARAMS 5 QString params[PORTED_PARAMS]; qreal tab = area.left(); painter->drawRoundedRect(area.toRect(), 5, 5); params[0] = QObject::tr("Vol. %1 L").arg(getBoxVolume()); if (!slotActivated) { params[1] = QObject::tr("Port Diam. %1 cm").arg(getPortDiam()); } else { params[1] = QObject::tr("Slot port %1 x %2 cm").arg(QString::number(getSlotWidth(), 'f', 2), QString::number(getSlotHeight(), 'f', 2)); } params[2] = QObject::tr("Port Len. %1 cm").arg(QString::number(getPortLen(), 'f', 2)); params[3] = QObject::tr("Port Num. %1").arg(QString::number(getPortNum())); params[4] = QObject::tr("Fb %1 Hz").arg(QString::number(getResFreq())); for (int i = 0; i < PORTED_PARAMS; i++) { QString text = params[i]; QRectF where(tab, area.top(), area.width() / PORTED_PARAMS, area.height()); QTextOption option(Qt::AlignVCenter|Qt::AlignLeft); painter->drawText(where, text, option); tab += area.width() / PORTED_PARAMS; } }
5,351
C++
.cpp
169
27.757396
143
0.657521
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,922
speakerdb.cpp
be1_qspeakers/speakerdb.cpp
#include "speakerdb.h" #include <iostream> #include <algorithm> #include <QDebug> #include <QString> #include <QList> #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) #include <QStandardPaths> #endif #include <QCoreApplication> #include <QDesktopServices> #include <QDir> #include <QFile> #include <QDomDocument> #include <QDomElement> #include <QDomNodeList> #include <QDomNode> #include <QDateTime> QString SpeakerDb::getPath(void) { #if QT_VERSION >= QT_VERSION_CHECK(6,0,0) QString prefix = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation); #elif QT_VERSION >= QT_VERSION_CHECK(5,0,0) QString prefix = QStandardPaths::writableLocation(QStandardPaths::DataLocation); #else QString prefix = QDesktopServices::storageLocation(QDesktopServices::DataLocation); #endif QDir dir(prefix); if (!dir.exists()) dir.mkpath(prefix); QString path = prefix + QDir::separator() + DB_FILENAME; return path; } QDomDocument SpeakerDb::getDoc(void) { QDomImplementation impl = QDomDocument().implementation(); QString name = "QSpeakers"; QString publicId = "-//HEREWE//DTD QSpeakers 1.0 //EN"; QString systemId = "http://def.herewe.org/DTD/qspeakers1.dtd"; QDomDocument doc(impl.createDocumentType(name, publicId, systemId)); doc.appendChild(doc.createComment("QSpeakers db of Thiele-Small parameters")); return doc; } QString SpeakerDb::getPkgDbPath() { #ifdef __mswin return QCoreApplication::applicationDirPath() + QDir::separator() + DB_FILENAME; #else return PKG_DB; #endif } QList<QString> SpeakerDb::getModelsByVendor(const QString& vendor, int *maxchars) { int len = 0; QString path = getPath(); QFile file(path); QDomDocument doc = getDoc(); if (file.exists()) { file.open(QIODevice::ReadOnly); doc.setContent(&file); file.close(); } QDomNodeList speakers = doc.elementsByTagName("speaker"); QList<QString> list; for (int i = 0; i < speakers.size(); i++) { QDomNode s = speakers.at(i); QDomElement spk = s.toElement(); QString vnd = spk.attribute("vendor"); QString mdl = spk.attribute("model"); if (vnd == vendor) list.append(mdl); if (mdl.length() > len) len = mdl.length(); } if (maxchars) *maxchars = len; std::sort(list.begin(), list.end()); return list; } QList<Speaker> SpeakerDb::getByVendor(const QString &vendor) { QString path = getPath(); QFile file(path); QDomDocument doc = getDoc(); if (file.exists()) { file.open(QIODevice::ReadOnly); doc.setContent(&file); file.close(); } QDomNodeList xspeakers = doc.elementsByTagName("speaker"); QList<Speaker> speakers; for (int i = 0; i < xspeakers.size(); i++) { QDomNode s = xspeakers.at(i); QDomElement spk = s.toElement(); if (spk.attribute("vendor") == vendor) { Speaker speaker; speaker.fromDomElement(spk); speakers.append(speaker); } } return speakers; } QList<Speaker> SpeakerDb::getByValue(QString var, double min, double max) { QString path = getPath(); QFile file(path); QDomDocument doc = getDoc(); if (file.exists()) { file.open(QIODevice::ReadOnly); doc.setContent(&file); file.close(); } QDomNodeList xspeakers = doc.elementsByTagName("speaker"); QList<Speaker> speakers; for (int i = 0; i < xspeakers.size(); i++) { QDomNode s = xspeakers.at(i); QDomElement spk = s.toElement(); QLocale c(QLocale::C); if (c.toDouble(spk.attribute(var)) >= min && c.toDouble(spk.attribute(var)) <= max) { Speaker speaker; speaker.fromDomElement(spk); speakers.append(speaker); } } return speakers; } /* two-way merge, where user db is prioritized (return true if had to resolve conflict) */ bool SpeakerDb::merge(QFile &with) { if (!with.exists()) return false; bool ret = false; QString path = getPath(); QFile file(path); QDomDocument doc = getDoc(); QDomDocument xml = getDoc(); if (file.exists()) { file.open(QIODevice::ReadOnly); doc.setContent(&file); file.close(); } with.open(QIODevice::ReadOnly); xml.setContent(&with); with.close(); QDomNodeList speakerlist = doc.elementsByTagName("speaker"); QDomNodeList withlist = xml.elementsByTagName("speaker"); QDomDocument temp = getDoc(); QDomElement troot = temp.createElement("speakers"); temp.appendChild(troot); /* first way */ qDebug() << "looking " + with.fileName(); for (int i = 0; i < withlist.size(); i++) { bool conflict = false; QDomNode s_ = withlist.at(i); QDomElement spk_ = s_.toElement(); QString vnd_ = spk_.attribute("vendor"); QString mdl_ = spk_.attribute("model"); qDebug() << " element " + with.fileName() + ": " + vnd_ + ":" + mdl_; qDebug() << " looking " + file.fileName(); for (int j = 0; j < speakerlist.size(); j++) { QDomNode s = speakerlist.at(j); QDomElement spk = s.toElement(); QString vnd = spk.attribute("vendor"); QString mdl = spk.attribute("model"); //qDebug() << " element " + file.fileName() + ": " + vnd + ":" + mdl; if ((vnd.toUpper() == vnd_.toUpper()) && (mdl.toUpper() == mdl_.toUpper())) { qDebug() << " CONFLICT!"; conflict = true; ret = true; /* copy the element from user's db to the temporary xml */ qDebug() << " import " + vnd + ":" + mdl; QDomElement t = spk.cloneNode(true).toElement(); t.normalize(); troot.appendChild(t); break; } } if (conflict) continue; /* no conflict, so append the new speaker */ qDebug() << " import " + vnd_ + ":" + mdl_; QDomElement t_ = spk_.cloneNode(true).toElement(); t_.normalize(); troot.appendChild(t_); } /* prepend temp in merged */ QDomDocument merged(temp); QDomElement mroot = merged.firstChildElement("speakers"); QDomNodeList templist = temp.elementsByTagName("speaker"); /* second way */ qDebug() << "looking " + file.fileName(); for (int i = 0; i < speakerlist.size(); i++) { bool already = false; QDomNode s = speakerlist.at(i); QDomElement spk = s.toElement(); QString vnd = spk.attribute("vendor"); QString mdl = spk.attribute("model"); qDebug() << " element " + file.fileName() + ": " + vnd + ":" + mdl; qDebug() << " looking " + with.fileName(); for (int j = 0; j < templist.size(); j++) { QDomNode s_ = templist.at(j); QDomElement spk_ = s_.toElement(); QString vnd_ = spk_.attribute("vendor"); QString mdl_ = spk_.attribute("model"); //qDebug() << " element " + with.fileName() + ": " + vnd_ + ":" + mdl_; if ((vnd.toUpper() == vnd_.toUpper()) && (mdl.toUpper() == mdl_.toUpper())) { already = true; qDebug() << " ALREADY!"; break; } } if (already) continue; /* not already inserted, so append the old speaker */ qDebug() << " import " + vnd + ":" + mdl; QDomElement m = spk.cloneNode(true).toElement(); m.normalize(); mroot.appendChild(m); } QDomNodeList mergedlist = merged.elementsByTagName("speaker"); /* write back */ QFile wfile(path); wfile.open(QIODevice::WriteOnly); wfile.write(merged.toByteArray()); wfile.close(); return ret; } QDateTime SpeakerDb::lastModified() { QFileInfo info(getPath()); qDebug() << info.filePath() + ":" + info.lastModified().toString(); return info.lastModified(); } QDateTime SpeakerDb::pkgInstalled() { QFile pkg_db(getPkgDbPath()); if (pkg_db.exists()) { QFileInfo info(PKG_DB); qDebug() << info.filePath() + ": " + info.lastModified().toString(); return info.lastModified(); } /* necessary if app not 'prod' installed */ QFile cwd_db("./" DB_FILENAME); if (cwd_db.exists()) { QFileInfo info("./" DB_FILENAME); qDebug() << info.filePath() + ": " + info.lastModified().toString(); return info.lastModified(); } /* necessary if app not 'prod' installed, but in my qspeakers source dir */ QFile source_db("../qspeakers/" DB_FILENAME); if (source_db.exists()) { QFileInfo info("../qspeakers/" DB_FILENAME); qDebug() << info.filePath() + ":" + info.lastModified().toString(); return info.lastModified(); } qWarning() << "no pkg db found, returning current datetime as db access!"; return QDateTime(); } QString SpeakerDb::pkgPath() { QFile pkg_db(getPkgDbPath()); if (pkg_db.exists()) return getPkgDbPath(); /* necessary if not 'prod' installed */ QFile cwd_db("./" DB_FILENAME); if (cwd_db.exists()) return "./" DB_FILENAME; /* necessary if not 'prod' installed, but in qspeakers source dir */ QFile source_db("../qspeakers/" DB_FILENAME); if (source_db.exists()) return "../qspeakers/" DB_FILENAME; qWarning() << "no pkg db found, return empty path!"; return QString(); } QList<Speaker> SpeakerDb::getByFs(double min, double max) { return getByValue("fs", min, max); } QList<Speaker> SpeakerDb::getByDia(double min, double max) { return getByValue("dia", min, max); } QList<Speaker> SpeakerDb::getByZ(double min, double max) { return getByValue("z", min, max); } QList<Speaker> SpeakerDb::getBySd(double min, double max) { return getByValue("sd", min, max); } QList<Speaker> SpeakerDb::getByVas(double min, double max) { return getByValue("vas", min, max); } QList<Speaker> SpeakerDb::getByQts(double min, double max) { return getByValue("qts", min, max); } QList<Speaker> SpeakerDb::getByQes(double min, double max) { return getByValue("qes", min, max); } QList<Speaker> SpeakerDb::getByQms(double min, double max) { return getByValue("qms", min, max); } QList<Speaker> SpeakerDb::getByRe(double min, double max) { return getByValue("re", min, max); } QList<Speaker> SpeakerDb::getByXmax(double min, double max) { return getByValue("xmax", min, max); } QList<Speaker> SpeakerDb::getBySpl(double min, double max) { return getByValue("spl", min, max); } QList<Speaker> SpeakerDb::getByPe(double min, double max) { return getByValue("pe", min, max); } QList<Speaker> SpeakerDb::getByBL(double min, double max) { return getByValue("bl", min, max); } QList<Speaker> SpeakerDb::getByVc(int min, int max) { return getByValue("vc", min, max); } QList<QString> SpeakerDb::getVendors(int* maxchars) { int len = 0; QString path = getPath(); QFile file(path); QDomDocument doc= getDoc(); if (file.exists()) { file.open(QIODevice::ReadOnly); doc.setContent(&file); file.close(); } QDomNodeList speakers = doc.elementsByTagName("speaker"); QList<QString> list; for (int i = 0; i < speakers.size(); i++) { QDomNode s = speakers.at(i); QDomElement spk = s.toElement(); QString vnd = spk.attribute("vendor"); if (list.contains(vnd)) /* avoid duplicates */ continue; list.append(vnd); if (vnd.length() > len) len = vnd.length(); } if (maxchars) *maxchars = len; std::sort(list.begin(), list.end()); return list; } bool SpeakerDb::exists() { QString path = getPath(); QFile file(path); return file.exists(); } void SpeakerDb::insertOrReplace(const QString& vendor, const QString& model, const Speaker& speaker) { QString path = getPath(); QFile file(path); QDomDocument doc = getDoc(); QDomDocument xml = getDoc(); QDomElement wroot = xml.createElement("speakers"); xml.appendChild(wroot); if (file.exists()) { file.open(QIODevice::ReadOnly); doc.setContent(&file); file.close(); } QDomNodeList speakerlist = doc.elementsByTagName("speaker"); for (int i = 0; i < speakerlist.size(); i++) { QDomNode s = speakerlist.at(i); QDomElement spk = s.toElement(); QString vnd = spk.attribute("vendor"); QString mdl = spk.attribute("model"); if ((vnd == vendor) && (mdl == model)) /* 'delete' it for future insert */ continue; /* copy the element to the writeable xml, otherwise we will have a messy loop */ QDomElement w = spk.cloneNode(true).toElement(); w.normalize(); wroot.appendChild(w); } if (speaker.isValid()) { /* append the new speaker */ QDomElement n = speaker.toDomElement(xml); if (speaker.getVendor() != vendor || speaker.getModel() != model) qDebug() << "inserted/updated speaker vendor or name changed."; n.normalize(); wroot.appendChild(n); } /* write back */ QFile wfile(path); wfile.open(QIODevice::WriteOnly); wfile.write(xml.toByteArray()); wfile.close(); } void SpeakerDb::removeByVendorAndModel(const QString &vendor, const QString &model) { return insertOrReplace(vendor, model, Speaker()); } Speaker SpeakerDb::getByVendorAndModel(const QString &vendor, const QString &model) { QString path = getPath(); QFile file(path); QDomDocument doc = getDoc(); if (file.exists()) { file.open(QIODevice::ReadOnly); doc.setContent(&file); file.close(); } QDomNodeList speakers = doc.elementsByTagName("speaker"); Speaker speaker; for (int i = 0; i < speakers.size(); i++) { QDomNode s = speakers.at(i); QDomElement spk = s.toElement(); QString vnd = spk.attribute("vendor"); QString mdl = spk.attribute("model"); if ((vnd == vendor) && (mdl == model)) { speaker.fromDomElement(spk); break; } } return speaker; }
14,383
C++
.cpp
433
27.122402
100
0.613564
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,923
bandpassdialog.cpp
be1_qspeakers/bandpassdialog.cpp
#include "bandpassdialog.h" #include "ui_bandpassdialog.h" BandpassDialog::BandpassDialog(QWidget *parent) : QDialog(parent), ui(new Ui::BandpassDialog) { ui->setupUi(this); connect(this, &BandpassDialog::accepted, this, &BandpassDialog::onAccepted); connect(this, &BandpassDialog::rejected, this, &BandpassDialog::onRejected); } BandpassDialog::~BandpassDialog() { delete ui; } void BandpassDialog::onAccepted() { double s, pa; s = ui->rippleDoubleSpinBox->value(); pa = ui->gainSpinBox->value(); emit optimizeRequested(s, pa); } void BandpassDialog::onRejected() { emit optimizeCancelled(); }
644
C++
.cpp
25
22.8
80
0.73127
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,924
sealedbox.cpp
be1_qspeakers/sealedbox.cpp
#include <QLocale> #include <QDebug> #include "sealedbox.h" SealedBox::SealedBox(double vol) { setVolume(vol); } void SealedBox::setVolume(double vol) { volume = double ((int)(vol * 100) / 100.0); } double SealedBox::getVolume() const { return volume; } QDomElement SealedBox::toDomElement(QDomDocument& doc) const { QDomElement e = Box::toDomElement(doc); e.setAttribute("type", "sealed"); QLocale c(QLocale::C); e.setAttribute("volume", c.toString(volume)); return e; } void SealedBox::fromDomElement(const QDomElement &e) { Box::fromDomElement(e); if (e.attribute("type") != "sealed") { qWarning() << __func__ << "wrong box type! (not sealed, giving up)"; return; } QLocale c(QLocale::C); volume = c.toDouble(e.attribute("volume")); } void SealedBox::render(QPainter *painter, const QRectF &area) const { if (!painter) return; painter->drawRoundedRect(area.toRect(), 5, 5); QString text = QObject::tr("Vol. %1 L").arg(getVolume()); QRectF where(area.left(), area.top(), area.width(), area.height()); QTextOption option(Qt::AlignVCenter|Qt::AlignLeft); painter->drawText(where, text, option); }
1,213
C++
.cpp
43
24.511628
76
0.670984
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,925
main.cpp
be1_qspeakers/main.cpp
#include "mainwindow.h" #include "importexport.h" #include <QApplication> #include <QTranslator> #include <QLibraryInfo> #include <QLocale> #include "config.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); a.setOrganizationName("Herewe"); a.setApplicationName("QSpeakers"); a.setApplicationVersion(VERSION " (" REVISION ")"); QString locale = QLocale::system().name(); QTranslator qtTranslator; #if QT_VERSION >= QT_VERSION_CHECK(6,0,0) if (qtTranslator.load(QLocale::system(), u"qtbase"_qs, u"_"_qs, QLibraryInfo::path(QLibraryInfo::TranslationsPath))) a.installTranslator(&qtTranslator); #else qtTranslator.load("qt_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)); a.installTranslator(&qtTranslator); #endif QTranslator qspeakersTranslator; if (qspeakersTranslator.load(TARGET "_" + locale, "locale")) a.installTranslator(&qspeakersTranslator); #ifdef __mswin else if (qspeakersTranslator.load(TARGET "_" + locale, QCoreApplication::applicationDirPath() + QDir::separator() + "locale")) #else else if (qspeakersTranslator.load(TARGET "_" + locale, DATADIR "/" TARGET "/locale")) #endif a.installTranslator(&qspeakersTranslator); QCommandLineParser parser; parser.setApplicationDescription(QObject::tr("Loudspeaker enclosure computation program.")); parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument("project", QCoreApplication::translate("main", "Project file to work on.")); parser.process(a); const QStringList args = parser.positionalArguments(); if (args.length() > 0) ImportExport::setSavePath(args.at(0)); MainWindow w; /* must be created _after_ setSavePath */ #ifdef __mswin QString iconpath = QCoreApplication::applicationDirPath() + QDir::separator() + TARGET + ".png"; #else QString iconpath = QString(DATADIR "/icons/hicolor/scalable/apps/" TARGET ".svg"); #endif #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) if (QFileInfo::exists(iconpath)) #else if ((QFileInfo(iconpath)).exists()) #endif w.setWindowIcon(QIcon(iconpath)); else w.setWindowIcon(QIcon(TARGET ".png")); if (argc > 1) w.setWindowFilePath(argv[argc - 1]); w.show(); return a.exec(); }
2,352
C++
.cpp
61
33.868852
130
0.701754
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,926
mainwindow.cpp
be1_qspeakers/mainwindow.cpp
#include <iostream> #include <QtCore> #include <QDebug> #include <QMessageBox> #include <QPrintDialog> #include <QPrinter> #include <QPrinterInfo> #include <QPainter> #include <QUndoStack> #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) #include <QStandardPaths> #endif #include <QDesktopServices> #include "mainwindow.h" #include "ui_mainwindow.h" #include "config.h" #include "speaker.h" #include "speakerdb.h" #include "importexport.h" #include "plot.h" #include "searchdialog.h" #include "listdialog.h" #include "system.h" #include "optimizer.h" #include "undocommands.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), projectSaved(true), isModifying(false), spkDialog(nullptr), fileDialog(nullptr), searchDialog(nullptr), listDialog(nullptr), bandpassDialog(nullptr), currentSpeakerNumber(0), currentTabIndex(-1), sealedPlot(nullptr), portedPlot(nullptr), bandpassPlot(nullptr), notInDbSpeaker(nullptr), commandStack(new QUndoStack(this)) { ui->setupUi(this); /* setup recently opened menu */ for (int i = 0; i < MaxRecentFiles; ++i) { recentFileActs[i] = new QAction(this); recentFileActs[i]->setVisible(false); connect(recentFileActs[i], &QAction::triggered, this, &MainWindow::onOpenRecentActionTriggered); } QMenu* sub = new QMenu(tr("Recently opened"), ui->menuProject); ui->menuProject->insertMenu(ui->actionProjectSave, sub); for (int i = 0; i < MaxRecentFiles; ++i) sub->addAction(recentFileActs[i]); updateRecentFileActions(); /* setup maximums of spinbox */ ui->numberSpinBox->setMaximum(std::numeric_limits<int>::max()); ui->sealedVolumeDoubleSpinBox->setMaximum(std::numeric_limits<double>::max()); ui->portedPortsNumberSpinBox->setMaximum(std::numeric_limits<int>::max()); ui->portedVolumeDoubleSpinBox->setMaximum(std::numeric_limits<double>::max()); ui->portedPortDiameterDoubleSpinBox->setMaximum(std::numeric_limits<double>::max()); ui->portedPortSlotWidthDoubleSpinBox->setMaximum(std::numeric_limits<double>::max()); ui->bandPassSealedVolumeDoubleSpinBox->setMaximum(std::numeric_limits<double>::max()); ui->bandPassPortedVolumeDoubleSpinBox->setMaximum(std::numeric_limits<double>::max()); ui->bandPassPortsNumberSpinBox->setMaximum(std::numeric_limits<int>::max()); ui->bandPassPortDiameterDoubleSpinBox->setMaximum(std::numeric_limits<double>::max()); ui->bandpassPortSlotWidthDoubleSpinBox->setMaximum(std::numeric_limits<double>::max()); /* fix minimum width */ setMinimumWidth(800); ui->menuBar->setMinimumWidth(800); /* insert QChartView plotters in ui */ QHBoxLayout *ly1 = new QHBoxLayout(ui->sealedVolumePlotWidget); sealedPlot = new Plot(tr("Sealed volume frequency response"), ui->sealedVolumePlotWidget); sealedPlot->setMinimumSize(400, 300); //sealedPlot->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Expanding); ly1->insertWidget(0, sealedPlot); QHBoxLayout *ly2 = new QHBoxLayout(ui->portedPlotWidget); portedPlot = new Plot(tr("Ported volume frequency response"), ui->portedPlotWidget); portedPlot->setMinimumSize(400, 300); //portedPlot->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Expanding); ly2->insertWidget(0, portedPlot); QHBoxLayout *ly3 = new QHBoxLayout(ui->bandpassPlotWidget); bandpassPlot = new Plot(tr("Bandpass volumes frequency response"), ui->bandpassPlotWidget); bandpassPlot->setMinimumSize(400, 300); //bandpassPlot->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Expanding); ly3->insertWidget(0, bandpassPlot); /* test db */ if (!SpeakerDb::exists() || (SpeakerDb::lastModified() <= SpeakerDb::pkgInstalled())) { QFile pkg_db(SpeakerDb::pkgPath()); if (SpeakerDb::merge(pkg_db)) qDebug() << "merged db"; } /* fill speaker combos */ ui->vendorComboBox->addItems(SpeakerDb::getVendors()); ui->vendorComboBox->setSizeAdjustPolicy(QComboBox::SizeAdjustPolicy::AdjustToContents); ui->modelComboBox->addItems(SpeakerDb::getModelsByVendor(ui->vendorComboBox->currentText())); ui->modelComboBox->setSizeAdjustPolicy(QComboBox::SizeAdjustPolicy::AdjustToContents); /* undo history is empty */ this->ui->actionUndo->setEnabled(false); this->ui->actionRedo->setEnabled(false); /* restore last saved project... */ if (loadFile(ImportExport::getSavePath())) projectSaved = true; else { //projectSaved = false; currentSpeakerNumber = 1; currentTabIndex = 0; } /* on first run, no speaker. reset to the speaker of the combos if needed */ if (!currentSpeaker.isValid()) { currentSpeaker = SpeakerDb::getByVendorAndModel(ui->vendorComboBox->currentText(), ui->modelComboBox->currentText()); } /* display sibling number */ ui->numberSpinBox->setValue(currentSpeakerNumber); /* select restored tab */ ui->tabWidget->setCurrentIndex(currentTabIndex); /* tab index change is not connected yet, do menu modifications manually */ if (currentTabIndex != 1) { /* index != 1 needs to deactivate the ported alignments menu */ setActivateActions(ui->menuPorted_alignments->actions(), false); } if (currentTabIndex != 2) { /* index != 2 needs to deactivate the bandpass alignment menu */ ui->actionBandpass_alignment->setEnabled(false); } syncUiFromCurrentSpeaker(currentSpeaker); syncUiFromCurrentSealedBox(currentSealedBox); syncUiFromCurrentPortedBox(currentPortedBox); syncUiFromCurrentBandPassBox(currentBandPassBox); /* * connections */ /* menu actions */ linkMenus(); /* tabs actions */ linkTabs(); /* non-graphic */ linkInternals(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::onProjectSave() { if(ImportExport::saveProject(currentSpeaker, currentSealedBox, currentPortedBox, currentBandPassBox, currentSpeakerNumber, currentTabIndex)) { projectSaved = true; #if QT_VERSION >= QT_VERSION_CHECK(6,0,0) QString prefix = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation); #elif QT_VERSION >= QT_VERSION_CHECK(5,0,0) QString prefix = QStandardPaths::writableLocation(QStandardPaths::DataLocation); #else QString prefix = QDesktopServices::storageLocation(QDesktopServices::DataLocation); #endif if (!ImportExport::getSavePath().startsWith(prefix)) setRecentFile(ImportExport::getSavePath(), true); } } void MainWindow::onProjectExport() { QString home = MainWindow::getHome(); QString fileName = QFileDialog::getSaveFileName(this, tr("Export File"), home + QDir::separator() + tr("untitled.qsp"), tr("QSpeakers project (*.qsp)")); /* user cancelled */ if (fileName.isEmpty()) return; if (!fileName.endsWith(".qsp")) fileName += ".qsp"; QFile file(fileName); if(ImportExport::exportProject(file, currentSpeaker, currentSealedBox, currentPortedBox, currentBandPassBox, currentSpeakerNumber, currentTabIndex)) { setRecentFile(fileName, true); } } void MainWindow::onProjectImport() { if (!projectSaved) { QMessageBox::StandardButton pressed = QMessageBox::question(this, tr("Project not saved"), tr("The current project has not been saved. Continue anyway?"), QMessageBox::Yes|QMessageBox::No); if (pressed == QMessageBox::No) return; } QString home = MainWindow::getHome(); QString fileName = QFileDialog::getOpenFileName(this, tr("Import File"), home, tr("QSpeakers project (*.qsp)")); /* user cancelled */ if (fileName.isEmpty()) return; if (!loadFile(fileName)) { QMessageBox::warning(this, tr("Warning"), tr("Could not open project!")); } } void MainWindow::onOpenRecentActionTriggered() { QAction *action = qobject_cast<QAction *>(sender()); if (action) { if (!loadFile(action->data().toString())) { QMessageBox::warning(this, tr("Warning"), tr("Could not open project!")); } } } QString MainWindow::strippedName(const QString& fullFileName) { return QFileInfo(fullFileName).fileName(); } void MainWindow::updateRecentFileActions() { QSettings settings(SETTINGS_DOMAIN, SETTINGS_APP); QStringList files = settings.value("recentFileList").toStringList(); int numRecentFiles = qMin(files.size(), (int)MaxRecentFiles); for (int i = 0; i < numRecentFiles; ++i) { QString text("&%1 %2"); text = text.arg(i + 1).arg(strippedName(files[i])); recentFileActs[i]->setText(text); recentFileActs[i]->setData(files[i]); recentFileActs[i]->setVisible(true); } for (int j = numRecentFiles; j < MaxRecentFiles; ++j) recentFileActs[j]->setVisible(false); } void MainWindow::setRecentFile(const QString& fileName, bool ok) { QSettings settings(SETTINGS_DOMAIN, SETTINGS_APP); QStringList files = settings.value("recentFileList").toStringList(); files.removeAll(fileName); if (ok) files.prepend(fileName); while (files.size() > MaxRecentFiles) files.removeLast(); settings.setValue("recentFileList", files); updateRecentFileActions(); } bool MainWindow::loadFile(const QString& fileName) { /* clear undo history */ this->commandStack->clear(); unlinkInternals(); unlinkTabs(); QFile file(fileName); if (!ImportExport::importProject(currentSpeaker, currentSealedBox, currentPortedBox, currentBandPassBox, &currentSpeakerNumber, &currentTabIndex, file)) { setRecentFile(fileName, false); linkInternals(); linkTabs(); return false; } #if QT_VERSION >= QT_VERSION_CHECK(6,0,0) QString prefix = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation); #elif QT_VERSION >= QT_VERSION_CHECK(5,0,0) QString prefix = QStandardPaths::writableLocation(QStandardPaths::DataLocation); #else QString prefix = QDesktopServices::storageLocation(QDesktopServices::DataLocation); #endif if (!fileName.startsWith(prefix)) setRecentFile(fileName, true); ImportExport::setSavePath(fileName); setWindowFilePath(ImportExport::getSavePath()); syncUiFromCurrentSpeaker(currentSpeaker); syncUiFromCurrentSealedBox(currentSealedBox); syncUiFromCurrentPortedBox(currentPortedBox); syncUiFromCurrentBandPassBox(currentBandPassBox); linkInternals(); linkTabs(); ui->tabWidget->setCurrentIndex(currentTabIndex); if (notInDbSpeaker) onSpeakerModify(); return true; } void MainWindow::onProjectQuit() { if (projectSaved) { this->close(); return; } if (!currentSpeaker.isValid()) { this->close(); return; } QMessageBox::StandardButton pressed = QMessageBox::question(this, tr("Project not saved"), tr("The current project has not been saved. Exit anyway?"), QMessageBox::Yes|QMessageBox::No); if (pressed == QMessageBox::Yes) this->close(); } void MainWindow::syncUiFromCurrentSpeaker(const Speaker& spk) { if (!spk.isValid()) return; /* look if vendor is in the db */ QList<Speaker> speakers = SpeakerDb::getByVendor(spk.getVendor()); unlinkTabs(); if (speakers.count() == 0) { /* if this is an unknown vendor, insert in combo */ ui->vendorComboBox->insertItem(0, spk.getVendor()); ui->vendorComboBox->setCurrentIndex(0); ui->modelComboBox->clear(); /* this means also a new model */ ui->modelComboBox->insertItem(0, spk.getModel()); ui->modelComboBox->setCurrentIndex(0); notInDbSpeaker = &spk; } else { /* select correct vendor */ ui->vendorComboBox->setCurrentIndex(ui->vendorComboBox->findText(spk.getVendor())); /* fill speakers of this vendor */ ui->modelComboBox->clear(); ui->modelComboBox->addItems(SpeakerDb::getModelsByVendor(spk.getVendor())); int i = 0; for (i = 0; i < speakers.count(); i++) { Speaker speaker = speakers[i]; if (speaker.getModel() == spk.getModel()) { if (speaker != spk) { /* speaker conflict, renaming */ currentSpeaker.setModel(speaker.getModel() + "*"); ui->modelComboBox->addItem(spk.getModel()); ui->modelComboBox->setCurrentIndex(ui->modelComboBox->findText(spk.getModel())); notInDbSpeaker = &spk; } else { /* okay, select correct combo */ ui->modelComboBox->setCurrentIndex(ui->modelComboBox->findText(spk.getModel())); notInDbSpeaker = nullptr; } break; } } if (i == speakers.count()) { /* vendor was ok but model was not in DB */ ui->modelComboBox->addItem(spk.getModel()); ui->modelComboBox->setCurrentIndex(ui->modelComboBox->findText(spk.getModel())); notInDbSpeaker = &spk; } } ui->numberSpinBox->setValue(currentSpeakerNumber); /* display speaker's values */ ui->splValueLabel->setNum(currentSpeaker.getSpl()); ui->fsValueLabel->setNum(currentSpeaker.getFs()); ui->qtsValueLabel->setNum(currentSpeaker.getQts()); ui->vasValueLabel->setNum(currentSpeaker.getVas()); ui->diaValueLabel->setNum(currentSpeaker.getDia()); ui->zValueLabel->setNum(currentSpeaker.getZ()); ui->vcValueLabel->setNum(currentSpeaker.getVc()); linkTabs(); } void MainWindow::syncUiFromCurrentSealedBox(const SealedBox& box) { unlinkTabs(); ui->sealedVolumeDoubleSpinBox->setValue(box.getVolume()); System s(currentSpeaker, &box, currentSpeakerNumber); sealedPlot->clear(); for (double f = sealedPlot->getXmin(); f < portedPlot->getXmax(); f *= pow(10, 1.0/100.0)) { double db = s.response(f); sealedPlot->appendPointF(QPointF(f, db)); } sealedPlot->draw3dbVLine(); linkTabs(); } void MainWindow::syncUiFromCurrentPortedBox(const PortedBox& box) { unlinkTabs(); ui->portedVolumeDoubleSpinBox->setValue(box.getBoxVolume()); ui->portedResonancedoubleSpinBox->setValue(box.getResFreq()); ui->portedPortsNumberSpinBox->setValue(box.getPortNum()); ui->portedPortDiameterDoubleSpinBox->setValue(box.getPortDiam()); bool slotPortActivated = box.getSlotPortActivated(); ui->portedPortSlotWidthButton->setChecked(slotPortActivated); ui->portedPortSlotWidthButton->clicked(slotPortActivated); ui->portedPortSlotWidthDoubleSpinBox->setEnabled(slotPortActivated); ui->portedPortSlotHeightLineEdit->setEnabled(slotPortActivated); ui->portedPortSlotWidthDoubleSpinBox->setValue(box.getSlotWidth()); ui->portedPortSlotHeightLineEdit->setText(QString::number(box.getSlotHeight(), 'f', 1)); ui->portedPortLengthLineEdit->setText(QString::number(box.getPortLen(), 'f', 1)); System s(currentSpeaker, &box, currentSpeakerNumber); portedPlot->clear(); for (double f = portedPlot->getXmin(); f < portedPlot->getXmax(); f *= pow(10, 1.0/100.0)) { double db = s.response(f); portedPlot->appendPointF(QPointF(f, db)); } portedPlot->draw3dbVLine(); linkTabs(); } void MainWindow::syncUiFromCurrentBandPassBox(const BandPassBox& box) { unlinkTabs(); ui->bandPassSealedVolumeDoubleSpinBox->setValue(box.getSealedBoxVolume()); ui->bandPassPortedVolumeDoubleSpinBox->setValue(box.getPortedBoxVolume()); ui->bandPassPortedResonanceDoubleSpinBox->setValue(box.getPortedBoxResFreq()); ui->bandPassPortsNumberSpinBox->setValue(box.getPortedBoxPortNum()); ui->bandPassPortDiameterDoubleSpinBox->setValue(box.getPortedBoxPortDiam()); bool slotPortActivated = box.getPortedBoxSlotPortActivated(); ui->bandpassPortSlotWidthButton->setChecked(slotPortActivated); ui->bandpassPortSlotWidthButton->clicked(slotPortActivated); ui->bandpassPortSlotWidthDoubleSpinBox->setEnabled(slotPortActivated); ui->bandpassPortSlotHeightLineEdit->setEnabled(slotPortActivated); ui->bandpassPortSlotWidthDoubleSpinBox->setValue(box.getPortedBoxSlotWidth()); ui->bandpassPortSlotHeightLineEdit->setText(QString::number(box.getPortedBoxSlotHeight(), 'f', 1)); ui->bandPassPortLengthLineEdit->setText(QString::number(box.getPortedBoxPortLen(), 'f', 1)); System s(currentSpeaker, &box, currentSpeakerNumber); bandpassPlot->clear(); for (double f = bandpassPlot->getXmin(); f < bandpassPlot->getXmax(); f *= pow(10, 1.0/100.0)) { double db = s.response(f); bandpassPlot->appendPointF(QPointF(f, db)); } bandpassPlot->draw3dbVLine(); linkTabs(); } void MainWindow::setCurrentSpeaker(const Speaker &spk) { if ((currentSpeaker.getVendor() == spk.getVendor()) && (currentSpeaker.getModel() == spk.getModel())) return; currentSpeaker = spk; emit currentSpeakerChanged(spk); } bool MainWindow::print(QPrinter *printer) { QPainter painter; if (!painter.begin(printer)) return false; QRect page = printer->pageLayout().paintRectPixels(printer->resolution()); qreal step = page.height() / 4.0; if (ui->tabWidget->currentWidget() == ui->sealedTab) { System s(currentSpeaker, &currentSealedBox, currentSpeakerNumber); s.render(&painter, QRectF(page.left(), page.top(), page.width(), step)); sealedPlot->render(&painter, QRectF(page.left(), page.top() + step, page.width(), page.height() - step)); } else if (ui->tabWidget->currentWidget() == ui->portedTab) { System s(currentSpeaker, &currentPortedBox, currentSpeakerNumber); s.render(&painter, QRectF(page.left(), page.top(), page.width(), step)); portedPlot->render(&painter, QRectF(page.left(), page.top() + step, page.width(), page.height() - step)); } else { System s(currentSpeaker, &currentBandPassBox, currentSpeakerNumber); s.render(&painter, QRectF(page.left(), page.top(), page.width(), step)); bandpassPlot->render(&painter, QRectF(page.left(), page.top() + step, page.width(), page.height() - step)); } painter.end(); return true; } QString MainWindow::getHome() { QString home; #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) home = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); #else home = QDesktopServices::storageLocation(QDesktopServices::HomeLocation); #endif return home; } void MainWindow::onBandpassAlignment() { bandpassDialog = new BandpassDialog(this); connect(bandpassDialog, &BandpassDialog::optimizeRequested, this, &MainWindow::onBandpassOptimizeRequested); connect(bandpassDialog, &BandpassDialog::optimizeCancelled, this, &MainWindow::onBandpassOptimizeCancelled); bandpassDialog->show(); } void MainWindow::onBandpassOptimizeRequested(double s, double pa) { if (ui->tabWidget->currentWidget() == ui->bandpassTab) { Optimizer optimizer(currentSpeaker, &currentBandPassBox, currentSpeakerNumber, this); optimizer.bandpassAlignS_Pa(s, pa); emit currentBandPassBoxChanged(currentBandPassBox); } disconnect(bandpassDialog, &BandpassDialog::optimizeRequested, this, &MainWindow::onBandpassOptimizeRequested); disconnect(bandpassDialog, &BandpassDialog::optimizeCancelled, this, &MainWindow::onBandpassOptimizeCancelled); bandpassDialog->close(); bandpassDialog->deleteLater(); bandpassDialog = nullptr; } void MainWindow::onBandpassOptimizeCancelled() { disconnect(bandpassDialog, &BandpassDialog::optimizeRequested, this, &MainWindow::onBandpassOptimizeRequested); disconnect(bandpassDialog, &BandpassDialog::optimizeCancelled, this, &MainWindow::onBandpassOptimizeCancelled); bandpassDialog->close(); bandpassDialog->deleteLater(); bandpassDialog = nullptr; } void MainWindow::onCurvePlot() { QString home = getHome(); QString box = ui->tabWidget->currentWidget()->objectName().replace("Tab", "Box"); QString f = QString("QSpeakers %1 %2").arg(currentSpeaker.getModel()).arg(box); f.replace(' ', '_'); QString fileName = QFileDialog::getSaveFileName(this, tr("Export for Gnuplot"), home + QDir::separator() + f + ".dat", tr("Gnuplot data (*.dat)")); /* user cancelled */ if (fileName.isEmpty()) return; exportPlot(fileName, currentTabIndex); } void MainWindow::on3DScadExport() { QString home = getHome(); QString box = ui->tabWidget->currentWidget()->objectName().replace("Tab", "Box"); QString f = QString("QSpeakers %1 %2 3D").arg(currentSpeaker.getModel()).arg(box); f.replace(' ', '_'); QString fileName = QFileDialog::getSaveFileName(this, tr("Export for 3D OpenSCAD"), home + QDir::separator() + f + ".scad", tr("OpenSCAD script (*.scad)")); /* user cancelled */ if (fileName.isEmpty()) return; exportScad3D(fileName, currentTabIndex); } void MainWindow::on2DScadExport() { QString home = getHome(); QString box = ui->tabWidget->currentWidget()->objectName().replace("Tab", "Box"); QString f = QString("QSpeakers %1 %2 2D").arg(currentSpeaker.getModel()).arg(box); f.replace(' ', '_'); QString fileName = QFileDialog::getSaveFileName(this, tr("Export for 2D OpenSCAD"), home + QDir::separator() + f + ".scad", tr("OpenSCAD script (*.scad)")); /* user cancelled */ if (fileName.isEmpty()) return; exportScad2D(fileName, currentTabIndex); } void MainWindow::exportPlot(const QString& outfileName, int tabindex) { QFile file(outfileName); QString f("# QSpeakers plot: "); f += currentSpeaker.getModel() + "\n"; f += "# freq., dB.\n"; QLineSeries* series; switch (tabindex) { case 0: /* closed box */ series = sealedPlot->series(); break; case 1: /* vented box */ series = portedPlot->series(); break; case 2: /* bandpass box */ series = bandpassPlot->series(); break; default: return; } QList<QPointF> points = series->points(); int len = points.length(); QString line; for (int i = 0; i < len; i++) { line.clear(); QPointF p = points.at(i); line += QString("%1 %2 ").arg(p.x()).arg(p.y()); line.chop(1); line.append('\n'); f.append(line); } file.open(QIODevice::WriteOnly); file.write(f.toUtf8()); file.close(); } /* FIXME: should be taken from a popup before to export */ #define MARGIN 50 /* mm */ #define WOODTHICK 20 /* mm */ #define SAWTHICK 1 /* mm */ void MainWindow::exportScad(const QString& scad, const QString &outfileName, int tabindex) { QFile templ(scad); templ.open(QIODevice::ReadOnly); QString s = templ.readAll(); s.replace("__MODEL__", currentSpeaker.getModel()); s.replace("__NUMBER__", QString::number(currentSpeakerNumber)); s.replace("__MARGIN__", QString::number(MARGIN)); s.replace("__DIAMETER__", QString::number(currentSpeaker.getDia() * 1000)); /* mm */ s.replace("__WOODTHICK__", QString::number(WOODTHICK)); s.replace("__SAWTHICK__", QString::number(SAWTHICK)); if (tabindex == 0) { s.replace("__SEALEDBOXVOLUME__", QString::number(currentSealedBox.getVolume())); } else if (tabindex == 1) { s.replace("__PORTEDBOXVOLUME__", QString::number(currentPortedBox.getBoxVolume())); s.replace("__PORTEDBOXPORTNUMBER__", QString::number(currentPortedBox.getPortNum())); } else if (tabindex == 2) { s.replace("__SEALEDBOXVOLUME__", QString::number(currentBandPassBox.getSealedBoxVolume())); s.replace("__PORTEDBOXVOLUME__", QString::number(currentBandPassBox.getPortedBoxVolume())); s.replace("__PORTEDBOXPORTNUMBER__", QString::number(currentBandPassBox.getPortedBoxPortNum())); } if (tabindex == 1) { if (currentPortedBox.getSlotPortActivated()) { s.replace("__PORTEDBOXPORTSLOTACTIVATED__", "true"); s.replace("__PORTEDBOXPORTSLOTWIDTH__", QString::number(currentPortedBox.getSlotWidth() * 10)); /* mm */ s.replace("__PORTEDBOXPORTSLOTHEIGHT__", QString::number(currentPortedBox.getSlotHeight() * 10)); /* mm */ } else { s.replace("__PORTEDBOXPORTSLOTACTIVATED__", "false"); s.replace("__PORTEDBOXPORTSLOTWIDTH__", "0"); s.replace("__PORTEDBOXPORTSLOTHEIGHT__", "0"); } s.replace("__PORTEDBOXPORTDIAMETER__", QString::number(currentPortedBox.getPortDiam() * 10)); /* mm */ s.replace("__PORTEDBOXPORTLENGTH__", QString::number(currentPortedBox.getPortLen() * 10)); /* mm */ } else if (tabindex == 2) { if (currentBandPassBox.getPortedBoxSlotPortActivated()) { s.replace("__PORTEDBOXPORTSLOTACTIVATED__", "true"); s.replace("__PORTEDBOXPORTSLOTWIDTH__", QString::number(currentBandPassBox.getPortedBoxSlotWidth() * 10)); /* mm */ s.replace("__PORTEDBOXPORTSLOTHEIGHT__", QString::number(currentBandPassBox.getPortedBoxSlotHeight() * 10)); /* mm */ } else { s.replace("__PORTEDBOXPORTSLOTACTIVATED__", "false"); s.replace("__PORTEDBOXPORTSLOTWIDTH__", "0"); s.replace("__PORTEDBOXPORTSLOTHEIGHT__", "0"); } s.replace("__PORTEDBOXPORTDIAMETER__", QString::number(currentBandPassBox.getPortedBoxPortDiam() * 10)); /* mm */ s.replace("__PORTEDBOXPORTLENGTH__", QString::number(currentBandPassBox.getPortedBoxPortLen() * 10)); /* mm */ } QFile f(outfileName); f.open(QIODevice::WriteOnly); f.write(s.toUtf8()); f.close(); } void MainWindow::exportScad3D(const QString &outfileName, int tabindex) { QFile file(outfileName); QString scad; switch (tabindex) { case 0: /* closed box */ /* non-prod version: */ scad = "../qspeakers/sealedbox_template.scad"; if (!QFileInfo::exists(scad)) #ifdef __mswin scad = (QCoreApplication::applicationDirPath() + QDir::separator() + "sealedbox_template.scad"); #else scad = (DATADIR "/" TARGET "/sealedbox_template.scad"); #endif break; case 1: /* vented box */ /* non-prod version: */ scad = "../qspeakers/portedbox_template.scad"; if (!QFileInfo::exists(scad)) #ifdef __mswin scad = (QCoreApplication::applicationDirPath() + QDir::separator() + "sealedbox_template.scad"); #else scad = (DATADIR "/" TARGET "/portedbox_template.scad"); #endif break; case 2: /* bandpass box */ /* non-prod version: */ scad = "../qspeakers/bandpassbox_template.scad"; if (!QFileInfo::exists(scad)) #ifdef __mswin scad = (QCoreApplication::applicationDirPath() + QDir::separator() + "sealedbox_template.scad"); #else scad = (DATADIR "/" TARGET "/bandpassbox_template.scad"); #endif break; default: return; } exportScad(scad, outfileName, tabindex); } void MainWindow::exportScad2D(const QString &outfileName, int tabindex) { QFile file(outfileName); QString scad; switch (tabindex) { case 0: /* closed box */ /* non-prod version: */ scad = "../qspeakers/sealedbox_cutting_template.scad"; if (!QFileInfo::exists(scad)) #ifdef __mswin scad = (QCoreApplication::applicationDirPath() + QDir::separator() + "sealedbox_cutting_template.scad"); #else scad = (DATADIR "/" TARGET "/sealedbox_cutting_template.scad"); #endif break; case 1: /* vented box */ /* non-prod version: */ scad = "../qspeakers/portedbox_cutting_template.scad"; if (!QFileInfo::exists(scad)) #ifdef __mswin scad = (QCoreApplication::applicationDirPath() + QDir::separator() + "sealedbox_cutting_template.scad"); #else scad = (DATADIR "/" TARGET "/portedbox_cutting_template.scad"); #endif break; case 2: /* bandpass box */ /* non-prod version: */ scad = "../qspeakers/bandpassbox_cutting_template.scad"; if (!QFileInfo::exists(scad)) #ifdef __mswin scad = (QCoreApplication::applicationDirPath() + QDir::separator() + "sealedbox_cutting_template.scad"); #else scad = (DATADIR "/" TARGET "/bandpassbox_cutting_template.scad"); #endif break; default: return; } exportScad(scad, outfileName, tabindex); } void MainWindow::linkMenus() { connect(ui->actionProjectSave, &QAction::triggered, this, &MainWindow::onProjectSave); connect(ui->actionProjectQuit, &QAction::triggered, this, &MainWindow::onProjectQuit); connect(ui->actionSpeakerNew, &QAction::triggered, this, &MainWindow::onSpeakerNew); connect(ui->actionSpeakerModify, &QAction::triggered, this, &MainWindow::onSpeakerModify); connect(ui->actionSpeakerRemove, &QAction::triggered, this, &MainWindow::onSpeakerRemove); connect(ui->actionProjectExport, &QAction::triggered, this, &MainWindow::onProjectExport); connect(ui->actionProjectImport, &QAction::triggered, this, &MainWindow::onProjectImport); connect(ui->actionEditOptimize, &QAction::triggered, this, &MainWindow::onEditOptimize); connect(ui->actionSpeakerSearch, &QAction::triggered, this, &MainWindow::onSpeakerSearch); connect(ui->actionProjectPrint, &QAction::triggered, this, &MainWindow::onProjectPrint); connect(ui->actionUndo, &QAction::triggered, this, &MainWindow::onUndo); connect(ui->actionRedo, &QAction::triggered, this, &MainWindow::onRedo); connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::onAboutAbout); /* ported alignments sub-menu */ connect(ui->actionModerate_Inf, &QAction::triggered, this, &MainWindow::onAlignModerate_Inf); connect(ui->actionLegendre, &QAction::triggered, this, &MainWindow::onAlignLegendre); connect(ui->actionBessel, &QAction::triggered, this, &MainWindow::onAlignBessel); connect(ui->actionBullock, &QAction::triggered, this, &MainWindow::onAlignBullock); connect(ui->actionKeele_Hoge, &QAction::triggered, this, &MainWindow::onAlignKeele_Hoge); /* bandpass alignment */ connect(ui->actionBandpass_alignment, &QAction::triggered, this, &MainWindow::onBandpassAlignment); /* exports menu */ connect(ui->actionCurve_Plot, &QAction::triggered, this, &MainWindow::onCurvePlot); connect(ui->action3D_OpenScad, &QAction::triggered, this, &MainWindow::on3DScadExport); connect(ui->action2D_OpenScad, &QAction::triggered, this, &MainWindow::on2DScadExport); } void MainWindow::linkTabs() { connect(ui->tabWidget, &QTabWidget::currentChanged, this, &MainWindow::onCurrentTabChanged); /* spk combos action */ connect(ui->vendorComboBox, &QComboBox::textActivated, this, &MainWindow::onVendorChanged); connect(ui->modelComboBox, &QComboBox::textActivated, this, &MainWindow::onModelChanged); /* drivers number spin action */ connect(ui->numberSpinBox, QOverload<int>::of(&QSpinBox::valueChanged), this, &MainWindow::onNumberSpinChanged); connect(ui->sealedVolumeDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onSealedVolumeDoubleSpinChanged); connect(ui->portedVolumeDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onPortedVolumeDoubleSpinChanged); connect(ui->portedResonancedoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onPortedResonanceDoubleSpinChanged); connect(ui->portedPortsNumberSpinBox, QOverload<int>::of(&QSpinBox::valueChanged), this, &MainWindow::onPortedPortsNumberSpinChanged); connect(ui->portedPortDiameterDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onPortedPortDiameterDoubleSpinChanged); connect(ui->portedPortSlotWidthButton, &QPushButton::clicked, this, &MainWindow::onPortedSlotPortActivated); connect(ui->portedPortSlotWidthDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onPortedSlotWidthDoubleSpinChanged); connect(ui->bandPassSealedVolumeDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onBandPassSealedVolumeDoubleSpinChanged); connect(ui->bandPassPortedVolumeDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onBandPassPortedVolumeDoubleSpinChanged); connect(ui->bandPassPortedResonanceDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onBandPassPortedResonanceDoubleSpinChanged); connect(ui->bandPassPortsNumberSpinBox, QOverload<int>::of(&QSpinBox::valueChanged), this, &MainWindow::onBandPassPortNumSpinChanged); connect(ui->bandPassPortDiameterDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onBandPassPortDiameterDoubleSpinChanged); connect(ui->bandpassPortSlotWidthButton, &QPushButton::clicked, this, &MainWindow::onBandPassSlotPortActivated); connect(ui->bandpassPortSlotWidthDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onBandPassSlotWidthDoubleSpinChanged); } void MainWindow::linkInternals() { connect(this, &MainWindow::currentSpeakerChanged, this, &MainWindow::onCurrentSpeakerChanged); connect(this, &MainWindow::currentSealedBoxChanged, this, &MainWindow::onCurrentSealedBoxChanged); connect(this, &MainWindow::currentPortedBoxChanged, this, &MainWindow::onCurrentPortedBoxChanged); connect(this, &MainWindow::currentBandPassBoxChanged, this, &MainWindow::onCurrentBandPassBoxChanged); connect(this->commandStack, &QUndoStack::canUndoChanged, ui->actionUndo, &QAction::setEnabled); connect(this->commandStack, &QUndoStack::canRedoChanged, ui->actionRedo, &QAction::setEnabled); } void MainWindow::unlinkMenus() { disconnect(ui->actionProjectSave, &QAction::triggered, this, &MainWindow::onProjectSave); disconnect(ui->actionProjectQuit, &QAction::triggered, this, &MainWindow::onProjectQuit); disconnect(ui->actionSpeakerNew, &QAction::triggered, this, &MainWindow::onSpeakerNew); disconnect(ui->actionSpeakerModify, &QAction::triggered, this, &MainWindow::onSpeakerModify); disconnect(ui->actionSpeakerRemove, &QAction::triggered, this, &MainWindow::onSpeakerRemove); disconnect(ui->actionProjectExport, &QAction::triggered, this, &MainWindow::onProjectExport); disconnect(ui->actionProjectImport, &QAction::triggered, this, &MainWindow::onProjectImport); disconnect(ui->actionEditOptimize, &QAction::triggered, this, &MainWindow::onEditOptimize); disconnect(ui->actionSpeakerSearch, &QAction::triggered, this, &MainWindow::onSpeakerSearch); disconnect(ui->actionProjectPrint, &QAction::triggered, this, &MainWindow::onProjectPrint); disconnect(ui->actionAbout, &QAction::triggered, this, &MainWindow::onAboutAbout); /* ported alignments sub-menu */ disconnect(ui->actionModerate_Inf, &QAction::triggered, this, &MainWindow::onAlignModerate_Inf); disconnect(ui->actionLegendre, &QAction::triggered, this, &MainWindow::onAlignLegendre); disconnect(ui->actionBessel, &QAction::triggered, this, &MainWindow::onAlignBessel); disconnect(ui->actionBullock, &QAction::triggered, this, &MainWindow::onAlignBullock); disconnect(ui->actionKeele_Hoge, &QAction::triggered, this, &MainWindow::onAlignKeele_Hoge); /* bandpass alignment */ disconnect(ui->actionBandpass_alignment, &QAction::triggered, this, &MainWindow::onBandpassAlignment); } void MainWindow::unlinkTabs() { disconnect(ui->tabWidget, &QTabWidget::currentChanged, this, &MainWindow::onCurrentTabChanged); /* spk combos action */ disconnect(ui->vendorComboBox, &QComboBox::textActivated, this, &MainWindow::onVendorChanged); disconnect(ui->modelComboBox, &QComboBox::textActivated, this, &MainWindow::onModelChanged); disconnect(ui->numberSpinBox, QOverload<int>::of(&QSpinBox::valueChanged), this, &MainWindow::onNumberSpinChanged); disconnect(ui->sealedVolumeDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onSealedVolumeDoubleSpinChanged); disconnect(ui->portedVolumeDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onPortedVolumeDoubleSpinChanged); disconnect(ui->portedResonancedoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onPortedResonanceDoubleSpinChanged); disconnect(ui->portedPortsNumberSpinBox, QOverload<int>::of(&QSpinBox::valueChanged), this, &MainWindow::onPortedPortsNumberSpinChanged); disconnect(ui->portedPortDiameterDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onPortedPortDiameterDoubleSpinChanged); disconnect(ui->portedPortSlotWidthButton, &QPushButton::clicked, this, &MainWindow::onPortedSlotPortActivated); disconnect(ui->portedPortSlotWidthDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onPortedSlotWidthDoubleSpinChanged); disconnect(ui->bandPassSealedVolumeDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onBandPassSealedVolumeDoubleSpinChanged); disconnect(ui->bandPassPortedVolumeDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onBandPassPortedVolumeDoubleSpinChanged); disconnect(ui->bandPassPortedResonanceDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onBandPassPortedResonanceDoubleSpinChanged); disconnect(ui->bandPassPortsNumberSpinBox, QOverload<int>::of(&QSpinBox::valueChanged), this, &MainWindow::onBandPassPortNumSpinChanged); disconnect(ui->bandPassPortDiameterDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onBandPassPortDiameterDoubleSpinChanged); disconnect(ui->bandpassPortSlotWidthButton, &QPushButton::clicked, this, &MainWindow::onBandPassSlotPortActivated); disconnect(ui->bandpassPortSlotWidthDoubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::onBandPassSlotWidthDoubleSpinChanged); } void MainWindow::unlinkInternals() { disconnect(this, &MainWindow::currentSpeakerChanged, this, &MainWindow::onCurrentSpeakerChanged); disconnect(this, &MainWindow::currentSealedBoxChanged, this, &MainWindow::onCurrentSealedBoxChanged); disconnect(this, &MainWindow::currentPortedBoxChanged, this, &MainWindow::onCurrentPortedBoxChanged); disconnect(this, &MainWindow::currentBandPassBoxChanged, this, &MainWindow::onCurrentBandPassBoxChanged); } void MainWindow::onSpeakerNew() { isModifying = false; spkDialog = new SpeakerDialog(this); connect(spkDialog, &SpeakerDialog::speakerInserted, this, &MainWindow::onSpeakerInserted); connect(spkDialog, &SpeakerDialog::speakerCancelled, this, &MainWindow::onSpeakerCancelled); spkDialog->show(); } void MainWindow::onSpeakerRemove() { QMessageBox::StandardButton pressed = QMessageBox::question(this, tr("Removal confirmation"), tr("Do you really want to remove this loudspeaker from the database?"), QMessageBox::Yes|QMessageBox::No); if (pressed == QMessageBox::No) return; QString vendor = currentSpeaker.getVendor(); QString model = currentSpeaker.getModel(); int num = SpeakerDb::getModelsByVendor(currentSpeaker.getVendor()).size(); ui->modelComboBox->removeItem(ui->modelComboBox->currentIndex()); if (num == 1) { ui->vendorComboBox->removeItem(ui->vendorComboBox->currentIndex()); } SpeakerDb::removeByVendorAndModel(vendor, model); /* fill speakers of automatically reselected vendor */ QString v = ui->vendorComboBox->currentText(); ui->modelComboBox->clear(); ui->modelComboBox->addItems(SpeakerDb::getModelsByVendor(v)); /* insert a fake speaker to let the choice to the user */ ui->modelComboBox->insertItem(0, "?"); ui->modelComboBox->setCurrentIndex(0); setCurrentSpeaker(Speaker()); } void MainWindow::onSpeakerModify() { isModifying = true; spkDialog = new SpeakerDialog(currentSpeaker, this); connect(spkDialog, &SpeakerDialog::speakerInserted, this, &MainWindow::onSpeakerInserted); connect(spkDialog, &SpeakerDialog::speakerCancelled, this,&MainWindow:: onSpeakerCancelled); spkDialog->show(); } void MainWindow::onSpeakerInserted(Speaker spk) { if (isModifying) { int idx; idx = ui->vendorComboBox->currentIndex(); ui->vendorComboBox->setItemText(idx, spk.getVendor()); idx = ui->modelComboBox->currentIndex(); ui->modelComboBox->setItemText(idx, spk.getModel()); currentSpeaker = spk; emit currentSpeakerChanged(currentSpeaker); } else { int idx = ui->vendorComboBox->findText(spk.getVendor()); if (idx == -1) ui->vendorComboBox->addItem(spk.getVendor()); else if (idx == ui->vendorComboBox->currentIndex()) ui->modelComboBox->addItem(spk.getModel()); } /* spk has been inserted or modified: remove anyway notInDbSpeaker */ notInDbSpeaker = nullptr; disconnect(spkDialog, &SpeakerDialog::speakerInserted, this, &MainWindow::onSpeakerInserted); disconnect(spkDialog, &SpeakerDialog::speakerCancelled, this, &MainWindow::onSpeakerCancelled); spkDialog->close(); spkDialog->deleteLater(); spkDialog = nullptr; } void MainWindow::onSpeakerCancelled() { disconnect(spkDialog, &SpeakerDialog::speakerInserted, this, &MainWindow::onSpeakerInserted); disconnect(spkDialog, &SpeakerDialog::speakerCancelled, this, &MainWindow::onSpeakerCancelled); spkDialog->close(); spkDialog->deleteLater(); spkDialog = nullptr; } void MainWindow::onEditOptimize() { if (ui->tabWidget->currentWidget() == ui->sealedTab) { Optimizer optimizer(currentSpeaker, &currentSealedBox, currentSpeakerNumber, this); optimizer.genericOptimizeBox(); emit currentSealedBoxChanged(currentSealedBox); } else if (ui->tabWidget->currentWidget() == ui->portedTab) { Optimizer optimizer(currentSpeaker, &currentPortedBox, currentSpeakerNumber, this); optimizer.genericOptimizeBox(); emit currentPortedBoxChanged(currentPortedBox); } else { Optimizer optimizer(currentSpeaker, &currentBandPassBox, currentSpeakerNumber, this); optimizer.genericOptimizeBox(); emit currentBandPassBoxChanged(currentBandPassBox); } } void MainWindow::onAlignModerate_Inf() { if (ui->tabWidget->currentWidget() == ui->portedTab) { Optimizer optimzer(currentSpeaker, &currentPortedBox, currentSpeakerNumber, this); optimzer.portedAlignModerate_Inf(); emit currentPortedBoxChanged(currentPortedBox); } } void MainWindow::onAlignLegendre() { if (ui->tabWidget->currentWidget() == ui->portedTab) { Optimizer optimizer(currentSpeaker, &currentPortedBox, currentSpeakerNumber, this); optimizer.portedAlignLegendre(); emit currentPortedBoxChanged(currentPortedBox); } } void MainWindow::onAlignBessel() { if (ui->tabWidget->currentWidget() == ui->portedTab) { Optimizer optimzer(currentSpeaker, &currentPortedBox, currentSpeakerNumber, this); optimzer.portedAlignBessel(); emit currentPortedBoxChanged(currentPortedBox); } } void MainWindow::onAlignKeele_Hoge() { /* BB4 */ if (ui->tabWidget->currentWidget() == ui->portedTab) { Optimizer optimizer(currentSpeaker, &currentPortedBox, currentSpeakerNumber, this); optimizer.portedAlignKeele_Hoge(); emit currentPortedBoxChanged(currentPortedBox); } } void MainWindow::onAlignBullock() { /* SBB4 */ if (ui->tabWidget->currentWidget() == ui->portedTab) { Optimizer optimizer(currentSpeaker, &currentPortedBox, currentSpeakerNumber, this); optimizer.portedAlignBullock(); emit currentPortedBoxChanged(currentPortedBox); } } void MainWindow::onSpeakerSearch() { searchDialog = new SearchDialog(this); connect(searchDialog, &SearchDialog::searchRequested, this, &MainWindow::onSearchRequested); connect(searchDialog,&SearchDialog::searchCancelled, this, &MainWindow::onSearchCancelled); searchDialog->show(); } void MainWindow::onProjectPrint() { QPrinter printer; printer.setCreator("QSpeakers"); printer.setDocName("qspeakers_project"); printer.setPageOrientation(QPageLayout::Landscape); QPrintDialog dialog(&printer, this); if (dialog.exec() == QDialog::Accepted) { if (printer.isValid()) { if (!print(&printer)) { QPrinterInfo info(printer); qWarning() << "printerinfo definition null:" << info.isNull(); qWarning() << "printerinfo state error:" << (info.state() == QPrinter::Error); } } else { qWarning() << "invalid printer object"; } } } void MainWindow::onUndo() { if (this->commandStack->canUndo()) this->commandStack->undo(); } void MainWindow::onRedo() { if (this->commandStack->canRedo()) this->commandStack->redo(); } void MainWindow::onAboutAbout() { QMessageBox::about(this, tr("About QSpeakers"), tr("QSpeakers version %1 (%2)\n\n" "This program simulates common acoustical enclosures " "behaviour to help designing loudspeaker systems.\n\n" "This program is free software, copyright (C) 2014 " "Benoit Rouits <brouits@free.fr> and released under the " "GNU General Public Lisence version 3. It is delivered " "as is in the hope it can be useful, but with no warranty at all.").arg(VERSION, REVISION)); } void MainWindow::onSearchRequested(const QString& param, double min, double max) { disconnect(searchDialog, &SearchDialog::searchRequested, this, &MainWindow::onSearchRequested); disconnect(searchDialog, &SearchDialog::searchCancelled, this, &MainWindow::onSearchCancelled); searchDialog->close(); searchDialog->deleteLater(); searchDialog = nullptr; QList<Speaker> speakers = SpeakerDb::getByValue(param, min, max); listDialog = new ListDialog(speakers, this); connect(listDialog, &ListDialog::speakerItemSelected, this, &MainWindow::onSpeakerItemSelected); connect(listDialog, &ListDialog::speakerItemCancelled, this, &MainWindow::onSpeakerItemCancelled); listDialog->show(); } void MainWindow::onSearchCancelled() { disconnect(searchDialog, &SearchDialog::searchRequested, this, &MainWindow::onSearchRequested); disconnect(searchDialog, &SearchDialog::searchCancelled, this, &MainWindow::onSearchCancelled); searchDialog->close(); searchDialog->deleteLater(); searchDialog = nullptr; } void MainWindow::onSpeakerItemSelected(QString title, const Speaker& speaker) { qDebug() << title; if (speaker.isValid()) { setCurrentSpeaker(speaker); syncUiFromCurrentSpeaker(speaker); } disconnect(listDialog, &ListDialog::speakerItemSelected, this, &MainWindow::onSpeakerItemSelected); disconnect(listDialog, &ListDialog::speakerItemCancelled, this, &MainWindow::onSpeakerItemCancelled); listDialog->close(); listDialog->deleteLater(); listDialog = nullptr; } void MainWindow::onSpeakerItemCancelled() { disconnect(listDialog, &ListDialog::speakerItemSelected, this, &MainWindow::onSpeakerItemSelected); disconnect(listDialog, &ListDialog::speakerItemCancelled, this, &MainWindow::onSpeakerItemCancelled); listDialog->close(); listDialog->deleteLater(); listDialog = nullptr; } void MainWindow::setActivateActions(QList<QAction*> actions, bool enable) { for (int i = 0; i < actions.count(); i++) { actions[i]->setEnabled(enable); } } void MainWindow::onCurrentTabChanged(int tab) { this->commandStack->clear(); QList<QAction*> alignments = ui->menuPorted_alignments->actions(); currentTabIndex = tab; switch (tab) { case 0: { setActivateActions(alignments, false); ui->actionBandpass_alignment->setEnabled(false); syncUiFromCurrentSealedBox(currentSealedBox); break; } case 1: { setActivateActions(alignments, true); ui->actionBandpass_alignment->setEnabled(false); syncUiFromCurrentPortedBox(currentPortedBox); break; } case 2: { setActivateActions(alignments, false); ui->actionBandpass_alignment->setEnabled(true); syncUiFromCurrentBandPassBox(currentBandPassBox); break; } default: break; } } void MainWindow::onNumberSpinChanged(int number) { if (currentSpeakerNumber == number) return; NumberCommand* com = new NumberCommand (currentSpeakerNumber, number, this); this->commandStack->push(com); } void MainWindow::changeSpeakerNumber(int number) { /* order is very important to avoid crash loop */ currentSpeakerNumber = number; ui->numberSpinBox->setValue(number); /* the user may have used the "?" fake speaker */ if (!currentSpeaker.isValid()) { qDebug() << "invalid speaker, not computing."; return; } projectSaved = false; syncUiFromCurrentSealedBox(currentSealedBox); syncUiFromCurrentPortedBox(currentPortedBox); syncUiFromCurrentBandPassBox(currentBandPassBox); } void MainWindow::onVendorChanged(QString vendor) { if (currentSpeaker.getVendor() == vendor) return; if (notInDbSpeaker) { if (vendor == notInDbSpeaker->getVendor()) return; QMessageBox::StandardButton pressed = QMessageBox::question(this, tr("Unsaved speaker"), tr("This speaker is not present in the database. Would you like to insert it before to continue?"), QMessageBox::Yes|QMessageBox::No); if (pressed == QMessageBox::Yes) { SpeakerDb::insertOrReplace(notInDbSpeaker->getVendor(), notInDbSpeaker->getModel(), *notInDbSpeaker); notInDbSpeaker = nullptr; } else /* no insert wanted */ { if (0 == SpeakerDb::getByVendor(notInDbSpeaker->getVendor()).count()) { /* forget entries */ ui->vendorComboBox->removeItem(ui->vendorComboBox->findText(notInDbSpeaker->getVendor())); ui->modelComboBox->removeItem(ui->modelComboBox->findText(notInDbSpeaker->getModel())); } else { /* forget model */ ui->modelComboBox->removeItem(ui->modelComboBox->findText(notInDbSpeaker->getModel())); } notInDbSpeaker = nullptr; } } this->commandStack->beginMacro("changing loudspeaker"); VendorCommand* com = new VendorCommand (currentSpeaker.getVendor(), vendor, currentSpeaker, this); this->commandStack->push(com); } void MainWindow::changeVendor(const QString& vendor, const Speaker& oldspeaker) { ui->vendorComboBox->setCurrentIndex(ui->vendorComboBox->findText(vendor)); /* fill speakers of this vendor */ ui->modelComboBox->clear(); ui->modelComboBox->addItems(SpeakerDb::getModelsByVendor(vendor)); /* if we come back to a previous vendor, set last vendor's selected speaker */ if (oldspeaker.getVendor() == vendor) { ui->modelComboBox->setCurrentIndex(ui->modelComboBox->findText(oldspeaker.getModel())); setCurrentSpeaker(SpeakerDb::getByVendorAndModel(vendor, oldspeaker.getModel())); } else { /* insert a fake speaker to let the choice to the user */ ui->modelComboBox->insertItem(0, "?"); ui->modelComboBox->setCurrentIndex(0); setCurrentSpeaker(Speaker()); } } void MainWindow::onModelChanged(QString model) { if (model.isNull() || model.isEmpty()) return; if (currentSpeaker.getModel() == model) return; if (notInDbSpeaker) { if (model == notInDbSpeaker->getModel()) return; QMessageBox::StandardButton pressed = QMessageBox::question(this, tr("Unsaved speaker"), tr("This speaker is not present in the database. Would you like to insert it before to continue?"), QMessageBox::Yes|QMessageBox::No); if (pressed == QMessageBox::Yes) { SpeakerDb::insertOrReplace(notInDbSpeaker->getVendor(), notInDbSpeaker->getModel(), *notInDbSpeaker); notInDbSpeaker = nullptr; } else /* no insert wanted */ { if (0 == SpeakerDb::getByVendor(notInDbSpeaker->getVendor()).count()) { /* forget entries */ ui->vendorComboBox->removeItem(ui->vendorComboBox->findText(notInDbSpeaker->getVendor())); ui->modelComboBox->removeItem(ui->modelComboBox->findText(notInDbSpeaker->getModel())); } else { /* forget model */ ui->modelComboBox->removeItem(ui->modelComboBox->findText(notInDbSpeaker->getModel())); } notInDbSpeaker = nullptr; } } oldSpeaker = currentSpeaker; ModelCommand* com = new ModelCommand (currentSpeaker.getModel(), model, this); this->commandStack->push(com); if (oldSpeaker.getVendor() != currentSpeaker.getVendor()) { oldSpeaker = currentSpeaker; this->commandStack->endMacro(); } } void MainWindow::changeModel(const QString& model) { ui->modelComboBox->setCurrentIndex(ui->modelComboBox->findText(model)); /* change model */ if ((ui->modelComboBox->findText("?") == 0) && (ui->modelComboBox->currentIndex() != 0)) { /* user choose a speaker; safely remove fake speaker */ ui->modelComboBox->removeItem(0); } QString vendor = ui->vendorComboBox->currentText(); setCurrentSpeaker(SpeakerDb::getByVendorAndModel(vendor, model)); } void MainWindow::onCurrentSpeakerChanged(const Speaker &spk) { ui->splValueLabel->setNum(spk.getSpl()); ui->fsValueLabel->setNum(spk.getFs()); ui->qtsValueLabel->setNum(spk.getQts()); ui->vasValueLabel->setNum(spk.getVas()); ui->diaValueLabel->setNum(spk.getDia()); ui->zValueLabel->setNum(spk.getZ()); ui->vcValueLabel->setNum(spk.getVc()); /* the user may have activated the "?" fake speaker */ if (!spk.isValid()) { qDebug() << "invalid speaker, not computing."; return; } projectSaved = false; syncUiFromCurrentSealedBox(currentSealedBox); syncUiFromCurrentPortedBox(currentPortedBox); syncUiFromCurrentBandPassBox(currentBandPassBox); } void MainWindow::onSealedVolumeDoubleSpinChanged(double val) { SealedVolumeCommand* com = new SealedVolumeCommand (currentSealedBox.getVolume(), val, this); this->commandStack->push(com); } void MainWindow::changeSealedVolume(double val) { currentSealedBox.setVolume(val); syncUiFromCurrentSealedBox(currentSealedBox); } void MainWindow::onCurrentSealedBoxChanged(const SealedBox &box) { if (!currentSpeaker.isValid()) return; projectSaved = false; syncUiFromCurrentSealedBox(box); } void MainWindow::onPortedVolumeDoubleSpinChanged(double val) { PortedVolumeCommand* com = new PortedVolumeCommand (currentPortedBox.getBoxVolume(), val, this); this->commandStack->push(com); } void MainWindow::changePortedVolume(double val) { currentPortedBox.setBoxVolume(val); currentPortedBox.updatePorts(currentSpeaker.getSd() * currentSpeakerNumber, currentSpeaker.getXmax()); syncUiFromCurrentPortedBox(currentPortedBox); } void MainWindow::onPortedResonanceDoubleSpinChanged(double val) { PortedResFreqCommand* com = new PortedResFreqCommand (currentPortedBox.getResFreq(), val, this); this->commandStack->push(com); } void MainWindow::changePortedResFreq(double val) { currentPortedBox.setResFreq(val); currentPortedBox.updatePorts(currentSpeaker.getSd() * currentSpeakerNumber, currentSpeaker.getXmax()); syncUiFromCurrentPortedBox(currentPortedBox); } void MainWindow::onPortedPortsNumberSpinChanged(int val) { PortedPortNumberCommand* com = new PortedPortNumberCommand (currentPortedBox.getPortNum(), val, this); this->commandStack->push(com); } void MainWindow::changePortedPortNumber(unsigned int val) { currentPortedBox.setPortNum(val); currentPortedBox.updatePorts(currentSpeaker.getSd()* currentSpeakerNumber, currentSpeaker.getXmax()); syncUiFromCurrentPortedBox(currentPortedBox); } void MainWindow::onPortedPortDiameterDoubleSpinChanged(double val) { /* allow manual decrease/increase of port diameter */ PortedPortDiamCommand* com = new PortedPortDiamCommand (currentPortedBox.getPortDiam(), val, this); this->commandStack->push(com); } void MainWindow::changePortedPortDiam(double val) { currentPortedBox.setPortDiam(val); currentPortedBox.updateSlots(); currentPortedBox.updatePortsLength(); syncUiFromCurrentPortedBox(currentPortedBox); } void MainWindow::onPortedSlotPortActivated(bool checked) { PortedSlotPortCommand* com = new PortedSlotPortCommand (this->currentPortedBox.getSlotPortActivated(), checked, this); this->commandStack->push(com); } void MainWindow::changePortedSlotPortActivation(bool checked) { currentPortedBox.setSlotPortActivated(checked); ui->portedPortSlotWidthDoubleSpinBox->setEnabled(checked); ui->portedPortSlotHeightLineEdit->setEnabled(checked); syncUiFromCurrentPortedBox(currentPortedBox); } void MainWindow::onPortedSlotWidthDoubleSpinChanged(double val) { PortedSlotWidthCommand* com = new PortedSlotWidthCommand (currentPortedBox.getSlotWidth(), val, this); this->commandStack->push(com); } void MainWindow::changePortedSlotWidth(double val) { currentPortedBox.setSlotWidth(val); syncUiFromCurrentPortedBox(currentPortedBox); } void MainWindow::onCurrentPortedBoxChanged(const PortedBox &box) { if (!currentSpeaker.isValid()) return; projectSaved = false; syncUiFromCurrentPortedBox(box); } void MainWindow::onBandPassSealedVolumeDoubleSpinChanged(double val) { BPSealedVolumeCommand* com = new BPSealedVolumeCommand (currentBandPassBox.getSealedBoxVolume(), val, this); this->commandStack->push(com); } void MainWindow::changeBPSealedVolume(double val) { currentBandPassBox.setSealedBoxVolume(val); syncUiFromCurrentBandPassBox(currentBandPassBox); } void MainWindow::onBandPassPortedVolumeDoubleSpinChanged(double val) { BPPortedVolumeCommand* com = new BPPortedVolumeCommand (currentBandPassBox.getPortedBoxVolume(), val, this); this->commandStack->push(com); } void MainWindow::changeBPPortedVolume(double val) { currentBandPassBox.setPortedBoxVolume(val); currentBandPassBox.updatePortedBoxPorts(currentSpeaker.getSd() * currentSpeakerNumber, currentSpeaker.getXmax()); syncUiFromCurrentBandPassBox(currentBandPassBox); } void MainWindow::onBandPassPortedResonanceDoubleSpinChanged(double val) { BPPortedResFreqCommand* com = new BPPortedResFreqCommand (currentBandPassBox.getPortedBoxResFreq(), val, this); this->commandStack->push(com); } void MainWindow::changeBPPortedResFreq(double val) { currentBandPassBox.setPortedBoxResFreq(val); currentBandPassBox.updatePortedBoxPorts(currentSpeaker.getSd() * currentSpeakerNumber, currentSpeaker.getXmax()); syncUiFromCurrentBandPassBox(currentBandPassBox); } void MainWindow::onBandPassPortNumSpinChanged(int val) { BPPortedPortNumberCommand* com = new BPPortedPortNumberCommand (currentBandPassBox.getPortedBoxPortNum(), val, this); this->commandStack->push(com); } void MainWindow::changeBPPortedPortNumber(double val) { currentBandPassBox.setPortedBoxPortNum(val); currentBandPassBox.updatePortedBoxPorts(currentSpeaker.getSd() * currentSpeakerNumber, currentSpeaker.getXmax()); syncUiFromCurrentBandPassBox(currentBandPassBox); } void MainWindow::onBandPassPortDiameterDoubleSpinChanged(double val) { /* allow manual decrease/increase of port diameter */ BPPortedPortDiamCommand* com = new BPPortedPortDiamCommand (currentBandPassBox.getPortedBoxPortDiam(), val, this); this->commandStack->push(com); } void MainWindow::changeBPPortedPortDiam(double val) { currentBandPassBox.setPortedBoxPortDiam(val); currentBandPassBox.updatePortedBoxPortsLength(); syncUiFromCurrentBandPassBox(currentBandPassBox); } void MainWindow::onBandPassSlotPortActivated(bool checked) { BPPortedSlotPortCommand* com = new BPPortedSlotPortCommand (this->currentBandPassBox.getPortedBoxSlotPortActivated(), checked, this); this->commandStack->push(com); } void MainWindow::changeBPPortedSlotPortActivation(bool checked) { currentBandPassBox.setPortedBoxSlotPortActivated(checked); ui->bandpassPortSlotWidthDoubleSpinBox->setEnabled(checked); ui->bandpassPortSlotHeightLineEdit->setEnabled(checked); syncUiFromCurrentBandPassBox(currentBandPassBox); } void MainWindow::changeBPPortedSlotWidth(double val) { currentBandPassBox.setPortedBoxSlotWidth(val); syncUiFromCurrentBandPassBox(currentBandPassBox); } void MainWindow::onBandPassSlotWidthDoubleSpinChanged(double val) { BPPortedSlotWidthCommand* com = new BPPortedSlotWidthCommand (currentBandPassBox.getPortedBoxSlotWidth(), val, this); this->commandStack->push(com); } void MainWindow::onCurrentBandPassBoxChanged(const BandPassBox &box) { if (!currentSpeaker.isValid()) return; projectSaved = false; syncUiFromCurrentBandPassBox(box); }
62,292
C++
.cpp
1,356
40.101032
174
0.713846
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,927
system.cpp
be1_qspeakers/system.cpp
#include <QDebug> #include <QObject> #include <math.h> #include "system.h" #define Q 7 /* common ported box resonance quality loss */ #define QL 10000 /* common box losses */ System::System(const Speaker& s, const SealedBox *b, unsigned int number) : speaker(s), box(b), type(BOX_SEALED), sibling(number) { } System::System(const Speaker& s, const PortedBox *b, unsigned int number) : speaker(s), box(b), type(BOX_PORTED), sibling(number) { } System::System(const Speaker& s, const BandPassBox *b, unsigned int number) : speaker(s), box(b), type(BOX_BANDPASS), sibling(number) { } double System::response(double f) { if (type == BOX_SEALED) { SealedBox *b = (SealedBox *)box; double vr = speaker.getVas() * sibling / b->getVolume(); double qr = sqrt(vr + 1.0); double qtc = qr * speaker.getQts(); double fb = qr * speaker.getFs(); double fr = pow(f / fb, 2.0); double db = 10 * log10(pow(fr, 2.0) / (pow(fr - 1, 2.0) + fr/pow(qtc, 2.0))); return db; } else if (type == BOX_PORTED) { PortedBox *b = (PortedBox *)box; double A = pow(b->getResFreq() / speaker.getFs(), 2.0); double B = A / speaker.getQts() + b->getResFreq() / (Q * speaker.getFs() * speaker.getQts()); double C = 1.0 + A + (speaker.getVas() * sibling / b->getBoxVolume()) + b->getResFreq() / (Q * speaker.getFs() * speaker.getQts()); double D = 1.0 / speaker.getQts() + b->getResFreq() / (Q * speaker.getFs()); double fn2 = pow(f / speaker.getFs(), 2.0); double fn4 = pow(fn2, 2.0); double db = 10 * log10(pow(fn4, 2.0) / (pow(fn4 - C * fn2 + A, 2.0) + fn2 * pow(D * fn2 - B, 2.0))); return db; } else { BandPassBox *b = (BandPassBox *)box; double A = pow(1.0 / (b->getPortedBoxResFreq()), 2.0) * pow(f, 4.0); double B = ((1 / QL + (speaker.getFs() / b->getPortedBoxResFreq()) / speaker.getQts()) / b->getPortedBoxResFreq()) * pow(f, 3.0); double C = (((1 + speaker.getVas() * sibling / b->getSealedBoxVolume() + speaker.getVas() * sibling / b->getPortedBoxVolume()) * speaker.getFs() / b->getPortedBoxResFreq() + (1 / speaker.getQts()) / QL) * speaker.getFs() / b->getPortedBoxResFreq() + 1) * pow(f, 2.0); double D = ((1 / speaker.getQts() + (speaker.getFs() / b->getPortedBoxResFreq()) / QL * (speaker.getVas() * sibling / b->getSealedBoxVolume() + 1)) * speaker.getFs()) * f; double E = (speaker.getVas() * sibling / b->getSealedBoxVolume() + 1) * pow(speaker.getFs(), 2); double G = A - C + E; double H = -B + D; double db = 20 * log10(pow(f, 2.0) / sqrt(pow(G, 2.0) + pow(H, 2.0))); return db; } } void System::render(QPainter *painter, const QRectF& area) { qreal x1, y1, x2, y2; qreal w, h; area.getCoords(&x1, &y1, &x2, &y2); w = x2 - x1; h = y2 - y1; qreal ytab = h / 3.0; QRectF a(x1, y1, w, ytab); QString text = QObject::tr("Driver(s) number: ") + QString::number(sibling); QTextOption option(Qt::AlignLeft); painter->drawText(a, text, option); y1 += ytab; a.setY(y1); a.setHeight(ytab); speaker.render(painter, a); y1 += ytab; a.setY(y1); a.setHeight(ytab); box->render(painter, a); }
3,384
C++
.cpp
85
33.858824
159
0.573471
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,928
bandpassbox.cpp
be1_qspeakers/bandpassbox.cpp
#include <QDebug> #include <QObject> #include "bandpassbox.h" BandPassBox::BandPassBox(double svol, double pvol, double pfreq, unsigned int pnum, double plen, double pdiam) : sealedBox(svol), portedBox(pvol, pfreq, pnum, plen, pdiam) { } void BandPassBox::setSealedBoxVolume(double vol) { sealedBox.setVolume(vol); } void BandPassBox::setPortedBoxVolume(double vol) { portedBox.setBoxVolume(vol); } void BandPassBox::setPortedBoxPortNum(unsigned int val) { portedBox.setPortNum(val); } void BandPassBox::setPortedBoxPortLen(double len) { portedBox.setPortLen(len); } void BandPassBox::setPortedBoxPortDiam(double diam) { portedBox.setPortDiam(diam); } void BandPassBox::setPortedBoxSlotWidth(double width) { portedBox.setSlotWidth(width); } void BandPassBox::setPortedBoxResFreq(double freq) { portedBox.setResFreq(freq); } void BandPassBox::setPortedBoxSlotPortActivated(bool enable) { portedBox.setSlotPortActivated(enable); } void BandPassBox::updatePortedBoxPorts(double sd, double xmax) { portedBox.updatePorts(sd, xmax); } void BandPassBox::updatePortedBoxPortsLength() { portedBox.updatePortsLength(); } void BandPassBox::updatePortedBoxSlots() { portedBox.updateSlots(); } double BandPassBox::getSealedBoxVolume() const { return sealedBox.getVolume(); } double BandPassBox::getPortedBoxVolume() const { return portedBox.getBoxVolume(); } unsigned int BandPassBox::getPortedBoxPortNum() const { return portedBox.getPortNum(); } double BandPassBox::getPortedBoxPortLen() const { return portedBox.getPortLen(); } double BandPassBox::getPortedBoxPortDiam() const { return portedBox.getPortDiam(); } bool BandPassBox::getPortedBoxSlotPortActivated() const { return portedBox.getSlotPortActivated(); } double BandPassBox::getPortedBoxSlotWidth() const { return portedBox.getSlotWidth(); } double BandPassBox::getPortedBoxSlotHeight() const { return portedBox.getSlotHeight(); } double BandPassBox::getPortedBoxResFreq(void) const { return portedBox.getResFreq(); } QDomElement BandPassBox::toDomElement(QDomDocument &doc) const { QDomElement e = Box::toDomElement(doc); e.setAttribute("type", "bandpass"); QDomElement b = sealedBox.toDomElement(doc); e.appendChild(b); QDomElement c = portedBox.toDomElement(doc); e.appendChild(c); return e; } void BandPassBox::fromDomElement(const QDomElement &e) { Box::fromDomElement(e); if (e.attribute("type") != "bandpass") { qWarning() << __func__ << "wrong box type! (not bandpass, giving up)"; return; } QDomElement b = e.firstChildElement("box"); while (!b.isNull()) { if (b.attribute("type") == "sealed") sealedBox.fromDomElement(b); else if (b.attribute("type") == "ported") portedBox.fromDomElement(b); b = b.nextSiblingElement("box"); } } void BandPassBox::render(QPainter *painter, const QRectF &area) const { if (!painter) return; QString params[6]; qreal tab = area.left(); painter->drawRoundedRect(area.toRect(), 5, 5); params[0] = QObject::tr("Sealed Vol. %1 L").arg(getSealedBoxVolume()); params[1] = QObject::tr("Ported Vol. %1 L").arg(getPortedBoxVolume()); if (!getPortedBoxSlotPortActivated()) { params[2] = QObject::tr("Port Diam. %1 cm").arg(getPortedBoxPortDiam()); } else { params[2] = QObject::tr("Slot port %1 x %2 cm").arg(QString::number(getPortedBoxSlotWidth(), 'f', 2), QString::number(getPortedBoxSlotHeight(), 'f', 2)); } params[3] = QObject::tr("Port Len. %1 cm").arg(QString::number(getPortedBoxPortLen(), 'f', 2)); params[4] = QObject::tr("Port Num. %1").arg(getPortedBoxPortNum()); params[5] = QObject::tr("Fb %1 Hz").arg(getPortedBoxResFreq()); for (int i = 0; i < 6; i++) { QString text = params[i]; QRectF where(tab, area.top(), area.width() / 6, area.height()); QTextOption option(Qt::AlignVCenter|Qt::AlignLeft); painter->drawText(where, text, option); tab += area.width() / 6; } }
4,122
C++
.cpp
139
26.071942
161
0.713526
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,929
searchdialog.cpp
be1_qspeakers/searchdialog.cpp
#include "searchdialog.h" #include "ui_searchdialog.h" #include "speakerdb.h" SearchDialog::SearchDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SearchDialog) { ui->setupUi(this); QStringList params = QString("Fs,Qts,Vas,Dia,Z,Sd,Re,Xmax,Le,Qms,Qes,Spl,Pe,BL").split(','); ui->searchComboBox->addItems(params); connect(this, &SearchDialog::accepted, this, &SearchDialog::onAccepted); connect(this, &SearchDialog::rejected, this, &SearchDialog::onRejected); } SearchDialog::~SearchDialog() { delete ui; } void SearchDialog::onAccepted() { QString param = ui->searchComboBox->currentText(); double min = ui->searchMinDoubleSpinBox->value(); double max = ui->searchMaxdoubleSpinBox->value(); QString p = param.toLower(); emit searchRequested(p, min, max); } void SearchDialog::onRejected() { emit searchCancelled(); }
888
C++
.cpp
29
27.344828
96
0.722026
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,930
speakerdialog.cpp
be1_qspeakers/speakerdialog.cpp
#include <QPushButton> #include <QDebug> #include "speakerdialog.h" #include "ui_speakerdialog.h" #include "speaker.h" #include "speakerdb.h" SpeakerDialog::SpeakerDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SpeakerDialog) { ui->setupUi(this); /* do not enable 'ok' since model and vendor are empty */ ui->speakerButtonBox->button(QDialogButtonBox::Ok)->setEnabled(false); connect(this, &SpeakerDialog::accepted, this, &SpeakerDialog::onSpeakerAccepted); connect(this, &SpeakerDialog::rejected, this, &SpeakerDialog::onSpeakerRejected); connect(ui->vendorLineEdit, &QLineEdit::textChanged, this, &SpeakerDialog::onVendorTextChanged); connect(ui->modelLineEdit, &QLineEdit::textChanged, this, &SpeakerDialog::onModelTextChanged); } SpeakerDialog::SpeakerDialog(const Speaker &edit, QWidget *parent) : QDialog(parent), ui(new Ui::SpeakerDialog) { ui->setupUi(this); ui->fsDoubleSpinBox->setValue(edit.getFs()); ui->qtsDoubleSpinBox->setValue(edit.getQts()); ui->vasDoubleSpinBox->setValue(edit.getVas()); ui->zDoubleSpinBox->setValue(edit.getZ()); ui->diaDoubleSpinBox->setValue(edit.getDia()); ui->reDoubleSpinBox->setValue(edit.getRe()); ui->sdDoubleSpinBox->setValue(edit.getSd()); ui->xmaxDoubleSpinBox->setValue(edit.getXmax()); ui->leDoubleSpinBox->setValue(edit.getLe()); ui->qmsDoubleSpinBox->setValue(edit.getQms()); ui->qesDoubleSpinBox->setValue(edit.getQes()); ui->splDoubleSpinBox->setValue(edit.getSpl()); ui->peDoubleSpinBox->setValue(edit.getPe()); ui->blDoubleSpinBox->setValue(edit.getBL()); ui->vcSpinBox->setValue(edit.getVc()); oldVendor = edit.getVendor(); oldModel = edit.getModel(); ui->vendorLineEdit->setText(oldVendor); ui->modelLineEdit->setText(oldModel); connect(this, &SpeakerDialog::accepted, this, &SpeakerDialog::onSpeakerAccepted); connect(this, &SpeakerDialog::rejected, this, &SpeakerDialog::onSpeakerRejected); connect(ui->vendorLineEdit, &QLineEdit::textChanged, this, &SpeakerDialog::onVendorTextChanged); connect(ui->modelLineEdit, &QLineEdit::textChanged, this, &SpeakerDialog::onModelTextChanged); } SpeakerDialog::~SpeakerDialog() { delete ui; } void SpeakerDialog::onVendorTextChanged(QString text) { if (text.isNull() || text.isEmpty()) ui->speakerButtonBox->button(QDialogButtonBox::Ok)->setEnabled(false); else if (!ui->modelLineEdit->text().isNull() && !ui->modelLineEdit->text().isEmpty()) ui->speakerButtonBox->button(QDialogButtonBox::Ok)->setEnabled(true); } void SpeakerDialog::onModelTextChanged(QString text) { if (text.isNull() || text.isEmpty()) ui->speakerButtonBox->button(QDialogButtonBox::Ok)->setEnabled(false); else if (!ui->vendorLineEdit->text().isNull() && !ui->vendorLineEdit->text().isEmpty()) ui->speakerButtonBox->button(QDialogButtonBox::Ok)->setEnabled(true); } void SpeakerDialog::onSpeakerAccepted() { Speaker spk; QString vendor = ui->vendorLineEdit->text(); QString model = ui->modelLineEdit->text(); spk.setVendor(vendor); spk.setModel(model); spk.setFs(ui->fsDoubleSpinBox->value()); spk.setVas(ui->vasDoubleSpinBox->value()); spk.setQts(ui->qtsDoubleSpinBox->value()); spk.setZ(ui->zDoubleSpinBox->value()); spk.setDia(ui->diaDoubleSpinBox->value()); spk.setRe(ui->reDoubleSpinBox->value()); spk.setSd(ui->sdDoubleSpinBox->value()); spk.setXmax(ui->xmaxDoubleSpinBox->value()); spk.setLe(ui->leDoubleSpinBox->value()); spk.setQms(ui->qmsDoubleSpinBox->value()); spk.setQes(ui->qesDoubleSpinBox->value()); spk.setSpl(ui->splDoubleSpinBox->value()); spk.setPe(ui->peDoubleSpinBox->value()); spk.setBL(ui->blDoubleSpinBox->value()); spk.setVc(ui->vcSpinBox->value()); if (oldVendor.isNull() || oldModel.isNull()) { SpeakerDb::insertOrReplace(vendor, model, spk); } else { SpeakerDb::insertOrReplace(oldVendor, oldModel, spk); } emit speakerInserted(spk); } void SpeakerDialog::onSpeakerRejected() { emit speakerCancelled(); }
4,136
C++
.cpp
98
37.887755
100
0.720219
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,931
optimizer.cpp
be1_qspeakers/optimizer.cpp
#include <math.h> #include "optimizer.h" #include "mainwindow.h" #include "undocommands.h" Optimizer::Optimizer(const Speaker& speaker, SealedBox *box, int sibling, QObject* parent) : speaker(speaker), box(box), type(BOX_SEALED), sibling(sibling), mainwindow(static_cast<MainWindow*>(parent)) { } Optimizer::Optimizer(const Speaker &speaker, PortedBox *box, int sibling, QObject *parent) : speaker(speaker), box(box), type(BOX_PORTED), sibling(sibling), mainwindow(static_cast<MainWindow*>(parent)) { } Optimizer::Optimizer(const Speaker &speaker, BandPassBox *box, int sibling, QObject *parent) : speaker(speaker), box(box), type(BOX_BANDPASS), sibling(sibling), mainwindow(static_cast<MainWindow*>(parent)) { } void Optimizer::genericOptimizeBox() { if (type == BOX_SEALED) { SealedBox *b = (SealedBox *)box; double qr = 0.707 / speaker.getQts(); double vr = pow(qr, 2.0) - 1; if (nullptr == mainwindow) { b->setVolume(speaker.getVas() * sibling / vr); } else { SealedVolumeCommand* com = new SealedVolumeCommand(b->getVolume(), speaker.getVas() * sibling / vr, mainwindow); mainwindow->getCommandStack()->beginMacro(QObject::tr("optimizing sealed box")); mainwindow->getCommandStack()->push(com); mainwindow->getCommandStack()->endMacro(); } } else if (type == BOX_PORTED) { /* approx. "natural max flat", a good starting point */ double vb = (20 * speaker.getVas() * sibling * pow(speaker.getQts(), 3.3)); double fb = speaker.getFs() * pow(speaker.getVas() * sibling / vb, 0.31); portedAlignVb_Fb(vb, fb, QObject::tr("applying 'max flat' alignment")); } else { /* default optimization for 0dB ripple (s) and 0dB gain (pa)*/ double s = 0.7; double pa = 0.0; bandpassAlignS_Pa(s, pa); } } void Optimizer::portedAlignBessel() { double vb = 8.0707 * pow(speaker.getQts(), 2.5848) * speaker.getVas() * sibling; double fb = 0.3552 * pow(speaker.getQts(), -0.9649) * speaker.getFs(); portedAlignVb_Fb(vb, fb, QObject::tr("applying Bessel alignment")); } void Optimizer::portedAlignBullock() { double qts = speaker.getQts(); double vb = qts * speaker.getVas() * sibling * (4.96 * qts - 0.136); double fb = speaker.getFs(); portedAlignVb_Fb(vb, fb, QObject::tr("applying Bullock alignment")); } void Optimizer::portedAlignKeele_Hoge() { double vb = speaker.getVas() * sibling * 5.2358 * pow(speaker.getQts(), 2.1687); double fb = speaker.getFs(); portedAlignVb_Fb(vb, fb, QObject::tr("applying Keele & Hoge alignment")); } void Optimizer::portedAlignLegendre() { double vb = 10.728 * pow(speaker.getQts(), 2.4186) * speaker.getVas() * sibling; double fb = 0.3802 * pow(speaker.getQts(), -1.0657) * speaker.getFs(); portedAlignVb_Fb(vb, fb, QObject::tr("applying Legendre alignment")); } void Optimizer::portedAlignModerate_Inf() { /* use M4 Moderate alignment (see http://www.mzbinden.ch/ventedalignments/index.html) */ double vb = (2.52 * speaker.getQts() - 0.35) * speaker.getVas() * sibling; double fb = 0.32 * sqrt((1.0/pow(speaker.getQts(), 2.0)) + 3.38) * speaker.getFs(); portedAlignVb_Fb(vb, fb, QObject::tr("applying Zbinden alignment")); } void Optimizer::portedAlignVb_Fb(double vb, double fb, const QString& title) { PortedBox *b = (PortedBox *)box; if (nullptr == mainwindow) { b->setBoxVolume(vb); b->setResFreq(fb); b->updatePorts(speaker.getSd() * sibling, speaker.getXmax()); } else { QUndoStack* stack = mainwindow->getCommandStack(); stack->beginMacro(title); PortedVolumeCommand* com1 = new PortedVolumeCommand(b->getBoxVolume(), vb, mainwindow); stack->push(com1); PortedResFreqCommand* com2 = new PortedResFreqCommand(b->getResFreq(), fb, mainwindow); stack->push(com2); stack->endMacro(); } } void Optimizer::bandpassAlignS_Pa(double s, double pa) { BandPassBox *b = (BandPassBox *)box; /* see http://www.diysubwoofers.org/bnd/4thord1.htm */ double qbp = pow((pow(10.0,(-pa/40.0)) * 2 * s ), -1); double fb = qbp * speaker.getFs() / speaker.getQts(); double vf = pow(2 * s * speaker.getQts(), 2) * speaker.getVas() * sibling; double vr = speaker.getVas() * sibling / (pow(qbp / speaker.getQts(), 2) - 1); if (nullptr == mainwindow) { b->setSealedBoxVolume(vr); b->setPortedBoxVolume(vf); b->setPortedBoxResFreq(fb); b->updatePortedBoxPorts(speaker.getSd() * sibling, speaker.getXmax()); } else { QUndoStack* stack = mainwindow->getCommandStack(); stack->beginMacro(QObject::tr("applying bandpass box alignment")); BPSealedVolumeCommand* com1 = new BPSealedVolumeCommand(b->getSealedBoxVolume(), vr, mainwindow); stack->push(com1); BPPortedVolumeCommand* com2 = new BPPortedVolumeCommand(b->getPortedBoxVolume(), vf, mainwindow); stack->push(com2); BPPortedResFreqCommand* com3 = new BPPortedResFreqCommand(b->getPortedBoxResFreq(), fb, mainwindow); stack->push(com3); stack->endMacro(); } }
5,278
C++
.cpp
128
35.8125
124
0.654595
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,932
listdialog.cpp
be1_qspeakers/listdialog.cpp
#include <QDebug> #include <QVariant> #include "listdialog.h" #include "ui_listdialog.h" SpeakerListModel::SpeakerListModel(const QList<Speaker> &speakers, QWidget *parent) : QAbstractListModel(parent) { this->speakers = speakers; } SpeakerListModel::~SpeakerListModel() { } int SpeakerListModel::rowCount(const QModelIndex &parent) const { if (!parent.isValid()) return speakers.size(); if (parent.row() > 0) return 0; return speakers.size(); } QVariant SpeakerListModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() >= speakers.size()) return QVariant(); if (role == Qt::DisplayRole) { return QVariant(speakers.at(index.row()).getVendor() + " - " + speakers.at(index.row()).getModel()); } else if (role == Qt::UserRole){ return QVariant::fromValue<Speaker>(speakers.at(index.row())); } else { return QVariant(); } } void SpeakerListModel::clear() { speakers.clear(); } ListDialog::ListDialog(const QList<Speaker> &speakers, QWidget *parent) : QDialog(parent), ui(new Ui::ListDialog), model(nullptr) { ui->setupUi(this); setSpeakerItems(speakers); connect(this, &ListDialog::accepted, this, &ListDialog::onAccepted); connect(this, &ListDialog::rejected, this, &ListDialog::onRejected); } ListDialog::~ListDialog() { delete ui; if (model != nullptr) delete model; } void ListDialog::setSpeakerItems(const QList<Speaker> &speakers) { if (model != nullptr) { model->clear(); delete model; } model = new SpeakerListModel(speakers, this); ui->listDialogListView->setModel(model); } void ListDialog::clear() { model->clear(); } void ListDialog::onAccepted() { QString title = model->data(QModelIndex(ui->listDialogListView->currentIndex()), Qt::DisplayRole).toString(); Speaker s = static_cast<Speaker> (model->data(QModelIndex(ui->listDialogListView->currentIndex()), Qt::UserRole).value<Speaker>()); emit speakerItemSelected(title, s); } void ListDialog::onRejected() { emit speakerItemCancelled(); }
2,160
C++
.cpp
75
25.12
135
0.695358
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,933
speaker.cpp
be1_qspeakers/speaker.cpp
#include "speaker.h" #include <QDebug> #include <QLocale> #include <cmath> #include <cfloat> Speaker::Speaker() : fs(0.0), vas(0.0), re(0.0), qts(0.0), sd(0.0), z(0.0), qms(0.0), qes(0.0), spl(0.0), pe(0.0), le(0.0), xmax(0.0), bl(0.0), vc(1), dia(0.0) { } Speaker::Speaker(const Speaker &copy) { this->fs = copy.getFs(); this->vas = copy.getVas(); this->re = copy.getRe(); this->qts = copy.getQts(); this->sd = copy.getSd(); this->z = copy.getZ(); this->qms = copy.getQms(); this->qes = copy.getQes(); this->spl = copy.getSpl(); this->pe = copy.getPe(); this->le = copy.getLe(); this->xmax = copy.getXmax(); this->bl = copy.getBL(); this->vc = copy.getVc(); this->dia = copy.getDia(); this->vendor = copy.getVendor(); this->model = copy.getModel(); } Speaker::~Speaker() { /* nothing to do, just for QMetatype */ } Speaker &Speaker::operator=(const Speaker &copy) { this->fs = copy.getFs(); this->vas = copy.getVas(); this->re = copy.getRe(); this->qts = copy.getQts(); this->sd = copy.getSd(); this->z = copy.getZ(); this->qms = copy.getQms(); this->qes = copy.getQes(); this->spl = copy.getSpl(); this->pe = copy.getPe(); this->le = copy.getLe(); this->xmax = copy.getXmax(); this->bl = copy.getBL(); this->vc = copy.getVc(); this->dia = copy.getDia(); this->vendor = copy.getVendor(); this->model = copy.getModel(); return *this; } /* https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ */ static bool almostEqualRelative(double a, double b, double maxRelDiff = DBL_EPSILON) { double diff = fabs(a - b); a = fabs(a); b = fabs(b); double largest = (b > a) ? b : a; if (diff <= largest * maxRelDiff) return true; return false; } bool Speaker::operator==(const Speaker& r) const { return almostEqualRelative(fs, r.getFs()) && almostEqualRelative(vas, r.getVas()) && almostEqualRelative(re, r.getRe()) && almostEqualRelative(qts, r.getQts()) && almostEqualRelative(sd, r.getSd()) && almostEqualRelative(z, r.getZ()) && almostEqualRelative(qms, r.getQms()) && almostEqualRelative(qes, r.getQes()) && almostEqualRelative(spl, r.getSpl()) && almostEqualRelative(pe, r.getPe()) && almostEqualRelative(le, r.getLe()) && almostEqualRelative(xmax, r.getXmax()) && almostEqualRelative(bl, r.getBL()) && almostEqualRelative(dia, r.getDia()) && vc == r.getVc(); } bool Speaker::operator!=(const Speaker& r) const { return !(*this == r); } bool Speaker::isValid() const { return !vendor.isNull() && !model.isNull(); } void Speaker::setVendor(const QString &vnd) { vendor = vnd; } void Speaker::setModel(const QString &mdl) { model = mdl; } void Speaker::setFs(double val) { fs = val; } void Speaker::setVas(double val) { vas = val; } void Speaker::setRe(double val) { re = val; } void Speaker::setQts(double val) { qts = val; } void Speaker::setSd(double val) { sd = val; } void Speaker::setXmax(double val) { xmax = val; } void Speaker::setZ(double val) { z = val; } void Speaker::setLe(double val) { le = val; } void Speaker::setQms(double val) { qms = val; } void Speaker::setQes(double val) { qes = val; } void Speaker::setSpl(double val) { spl = val; } void Speaker::setPe(double val) { pe = val; } void Speaker::setBL(double val) { bl = val; } void Speaker::setDia(double val) { dia = val; } void Speaker::setVc(int val) { vc = val; } QString Speaker::getVendor() const { return vendor; } QString Speaker::getModel() const { return model; } double Speaker::getFs() const { return fs; } double Speaker::getVas() const { return vas; } double Speaker::getRe() const { return re; } double Speaker::getQts() const { return qts; } double Speaker::getSd() const { return sd; } double Speaker::getXmax() const { return xmax; } double Speaker::getZ() const { return z; } double Speaker::getLe() const { return le; } double Speaker::getQms() const { return qms; } double Speaker::getQes() const { return qes; } double Speaker::getSpl() const { return spl; } double Speaker::getPe() const { return pe; } double Speaker::getBL() const { return bl; } double Speaker::getDia() const { return dia; } int Speaker::getVc() const { return vc; } QDomElement Speaker::toDomElement(QDomDocument &doc) const { QDomElement e = doc.createElement("speaker"); e.setAttribute("vendor", vendor); e.setAttribute("model", model); QLocale c(QLocale::C); e.setAttribute("fs", c.toString(fs)); e.setAttribute("vas", c.toString(vas)); e.setAttribute("re", c.toString(re)); e.setAttribute("qts", c.toString(qts)); e.setAttribute("sd", c.toString(sd)); e.setAttribute("xmax", c.toString(xmax)); e.setAttribute("z", c.toString(z)); e.setAttribute("le", c.toString(le)); e.setAttribute("qms", c.toString(qms)); e.setAttribute("qes", c.toString(qes)); e.setAttribute("spl", c.toString(spl)); e.setAttribute("pe", c.toString(pe)); e.setAttribute("bl", c.toString(bl)); e.setAttribute("dia", c.toString(dia)); e.setAttribute("vc", c.toString(vc)); return e; } void Speaker::fromDomElement(const QDomElement &el) { vendor = el.attribute("vendor"); model = el.attribute("model"); QLocale c(QLocale::C); fs = c.toDouble(el.attribute("fs")); vas = c.toDouble(el.attribute("vas")); re = c.toDouble(el.attribute("re")); qts = c.toDouble(el.attribute("qts")); sd = c.toDouble(el.attribute("sd")); xmax = c.toDouble(el.attribute("xmax")); z = c.toDouble(el.attribute("z")); le = c.toDouble(el.attribute("le")); qms = c.toDouble(el.attribute("qms")); qes = c.toDouble(el.attribute("qes")); spl = c.toDouble(el.attribute("spl")); pe = c.toDouble(el.attribute("pe")); bl = c.toDouble(el.attribute("bl")); dia = c.toDouble(el.attribute("dia")); vc = c.toInt(el.attribute("vc")); /* for older db compatibility */ vc = vc ? vc : 1; } void Speaker::render(QPainter *painter, const QRectF &area) { if (!painter) return; painter->drawRoundedRect(area.toRect(), 5, 5); #define PARAMLEN 10 QString params[PARAMLEN]; params[0] = QString::fromUtf8("Spl: %1 dB").arg(getSpl()); params[1] = QString::fromUtf8("Fs: %1 Hz").arg(getFs()); params[2] = QString::fromUtf8("Qts: %1").arg(getQts()); params[3] = QString::fromUtf8("Vas: %1 L").arg(getVas()); params[4] = QString::fromUtf8("Dia: %1 m").arg(getDia()); params[5] = QString::fromUtf8("Sd: %1 m²").arg(getSd()); params[6] = QString::fromUtf8("Xmax: %1 mm").arg(getXmax()); params[7] = QString::fromUtf8("Z: %1 Ohm").arg(getZ()); params[8] = QString::fromUtf8("Re: %1 Ohm").arg(getRe()); params[9] = QString::fromUtf8("Vc: %1").arg(getVc()); qreal tab = area.left(); QString text = getVendor() + " " + getModel(); QRectF where(area.left(), area.top(), area.width(), area.height() / 2); QTextOption option(Qt::AlignCenter); painter->drawText(where, text, option); for (int i = 0; i < PARAMLEN; i++) { where.setRect(tab, area.top() + area.height() / 2, area.width() / PARAMLEN, area.height() / 2); text = params[i]; option.setAlignment(Qt::AlignVCenter|Qt::AlignLeft); painter->drawText(where, text, option); tab += area.width() / PARAMLEN; } }
7,770
C++
.cpp
317
20.662461
103
0.622057
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,934
portedbox.h
be1_qspeakers/portedbox.h
#ifndef PORTEDBOX_H #define PORTEDBOX_H #include <QDomElement> #include <QDomDocument> #include <QRectF> #include <QPainter> #include "sealedbox.h" #define K 0.732 /* correction factor for a half flanged disposed port */ class PortedBox : public Box { public: PortedBox(double volume = 0.01, double resfreq = 1, unsigned int portnum = 1, double portdiam = 0, double portlen = 0); void setBoxVolume(double vol); void setPortNum(unsigned int value); void setPortLen(double len); void setPortDiam(double diam); void setSlotWidth(double width); void setResFreq(double value); void setSlotPortActivated(bool enable); double getBoxVolume(void) const; unsigned int getPortNum() const; double getPortLen(void) const; double getPortDiam(void) const; bool getSlotPortActivated(void) const; double getSlotWidth() const; double getSlotHeight() const; double getResFreq() const; void updateSlots(); void updatePorts(double sd, double xmax); void updatePortsLength(); QDomElement toDomElement(QDomDocument& doc) const; void fromDomElement(const QDomElement& e); void render(QPainter *painter, const QRectF& area) const; private: SealedBox box; double resFreq; unsigned int portNum; double portLen; double portDiam; double slotWidth; bool slotActivated; }; #endif // PORTEDBOX_H
1,389
C++
.h
43
28.395349
123
0.742708
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,936
listdialog.h
be1_qspeakers/listdialog.h
#ifndef LISTDIALOG_H #define LISTDIALOG_H #include <QDialog> #include <QAbstractListModel> #include "speaker.h" class SpeakerListModel : public QAbstractListModel { Q_OBJECT public: explicit SpeakerListModel(const QList<Speaker> &speakers, QWidget *parent = 0); ~SpeakerListModel(); int rowCount(const QModelIndex &parent = QModelIndex()) const; QVariant data(const QModelIndex &index, int role) const; void clear(void); private: QList<Speaker> speakers; }; namespace Ui { class ListDialog; } class ListDialog : public QDialog { Q_OBJECT public: explicit ListDialog(const QList<Speaker>& speakers, QWidget *parent = 0); ~ListDialog(); void setSpeakerItems(const QList<Speaker> &speakers); void clear(void); signals: void speakerItemSelected(QString title, const Speaker &speaker); void speakerItemCancelled(); private slots: void onAccepted(); void onRejected(); private: Ui::ListDialog *ui; SpeakerListModel *model; }; #endif // LISTDIALOG_H
1,029
C++
.h
39
23.179487
83
0.751025
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,937
system.h
be1_qspeakers/system.h
#ifndef SYSTEM_H #define SYSTEM_H #include "speaker.h" #include "box.h" #include "sealedbox.h" #include "portedbox.h" #include "bandpassbox.h" class System { public: System(const Speaker &s, const SealedBox *b, unsigned int number = 1); System(const Speaker &s, const PortedBox *b, unsigned int number = 1); System(const Speaker &s, const BandPassBox *b, unsigned int number = 1); double response(double f); void render(QPainter *painter, const QRectF& area); private: Speaker speaker; const Box* box; int type; int sibling; /* number of same drivers (not for push-pull!) */ }; #endif // SYSTEM_H
637
C++
.h
22
26.136364
76
0.711948
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,938
speakerdialog.h
be1_qspeakers/speakerdialog.h
#ifndef SPEAKERDIALOG_H #define SPEAKERDIALOG_H #include <QDialog> #include "speaker.h" namespace Ui { class SpeakerDialog; } class SpeakerDialog : public QDialog { Q_OBJECT public: explicit SpeakerDialog(QWidget *parent = 0); SpeakerDialog(const Speaker& edit, QWidget *parent = 0); ~SpeakerDialog(); signals: void speakerInserted(Speaker spk); void speakerCancelled(); private slots: void onVendorTextChanged(QString text); void onModelTextChanged(QString text); void onSpeakerAccepted(); void onSpeakerRejected(); private: Ui::SpeakerDialog *ui; QString oldVendor; QString oldModel; }; #endif // SPEAKERDIALOG_H
676
C++
.h
28
20.964286
60
0.757433
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,939
plot.h
be1_qspeakers/plot.h
#ifndef PLOT_H #define PLOT_H #include <QtCharts/QtCharts> class Plot : public QChartView { Q_OBJECT public: Plot(QWidget *parent = 0); Plot(QString title, QWidget *parent = 0); ~Plot(); void appendPointF(const QPointF& pointf); void plot(const QList<double> x, QList<double>y); void clear(void); void setUseOpenGL(bool enable = true); void draw3dbVLine(); double getXmin() const; double getXmax() const; QLineSeries* series() const; protected: void initializeScales(); void initializeChart(const QString& title = nullptr); void initializeCurve(); void resizeEvent(QResizeEvent *event); bool viewportEvent(QEvent *event); void mouseMoveEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent* event); void mouseReleaseEvent(QMouseEvent* event); double curveXfromY(double y); double curveYfromX(double x); void drawVLine(QPoint pos); private: QLineSeries *curve; QChart *chart; double xmin; double xmax; QGraphicsSimpleTextItem *pointerLabel; QGraphicsLineItem *vLine; QGraphicsLineItem *vLine3db; QGraphicsSimpleTextItem *vLabel3db; }; #endif // PLOT_H
1,187
C++
.h
41
24.780488
57
0.726316
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,940
box.h
be1_qspeakers/box.h
#ifndef BOX_H #define BOX_H #include <QDomElement> #include <QDomDocument> #include <QRectF> #include <QPainter> #define PI 3.1415927 #define BOX_SEALED 0 #define BOX_PORTED 1 #define BOX_BANDPASS 2 class Box { public: QDomElement toDomElement(QDomDocument& doc) const; void fromDomElement(const QDomElement& e); virtual void render(QPainter *painter, const QRectF& area) const = 0; }; #endif // BOX_H
420
C++
.h
18
21.333333
73
0.770202
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,941
sealedbox.h
be1_qspeakers/sealedbox.h
#ifndef SEALEDBOX_H #define SEALEDBOX_H #include <QDomElement> #include <QDomDocument> #include <QRectF> #include <QPainter> #include "box.h" class SealedBox : public Box { public: SealedBox(double vol = 0.01); void setVolume(double vol); double getVolume(void) const; QDomElement toDomElement(QDomDocument& doc) const; void fromDomElement(const QDomElement& e); void render(QPainter *painter, const QRectF& area) const; private: double volume; }; #endif // SEALEDBOX_H
503
C++
.h
20
22.5
61
0.75523
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,942
speakerdb.h
be1_qspeakers/speakerdb.h
#ifndef SPEAKERDB_H #define SPEAKERDB_H #include <QDomDocument> #include <QDateTime> #include <QString> #include <QList> #include <QFile> #include "speaker.h" #include "config.h" class SpeakerDb { public: static bool exists(void); static void insertOrReplace(const QString& vendor, const QString& name, const Speaker& speaker); static void removeByVendorAndModel(const QString& vendor, const QString& model); static Speaker getByVendorAndModel(const QString& vendor, const QString& model); static QList<QString> getVendors(int *maxchars = nullptr); static QList<QString> getModelsByVendor(const QString& vendor, int* maxchars = nullptr); static QList<Speaker> getByVendor(const QString& vendor); static QList<Speaker> getByFs(double min, double max); static QList<Speaker> getByDia(double min, double max); static QList<Speaker> getByZ(double min, double max); static QList<Speaker> getBySd(double min, double max); static QList<Speaker> getByVas(double min, double max); static QList<Speaker> getByQts(double min, double max); static QList<Speaker> getByQes(double min, double max); static QList<Speaker> getByQms(double min, double max); static QList<Speaker> getByRe(double min, double max); static QList<Speaker> getByXmax(double min, double max); static QList<Speaker> getBySpl(double min, double max); static QList<Speaker> getByPe(double min, double max); static QList<Speaker> getByBL(double min, double max); static QList<Speaker> getByVc(int min, int max); static QList<Speaker> getByValue(QString var, double min, double max); static bool merge(QFile& with); static QDateTime lastModified(void); static QDateTime pkgInstalled(void); static QString pkgPath(void); private: static QString getPath(void); static QDomDocument getDoc(void); static QString getPkgDbPath(void); #define DB_FILENAME "qspeakers_db.xml" #define PKG_DB DATADIR "/qspeakers/" DB_FILENAME }; #endif // SPEAKERDB_H
2,021
C++
.h
46
40.195652
100
0.757761
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,943
importexport.h
be1_qspeakers/importexport.h
#ifndef IMPORTEXPORT_H #define IMPORTEXPORT_H #include <QFile> #include "speaker.h" #include "sealedbox.h" #include "portedbox.h" #include "bandpassbox.h" class ImportExport { public: /* save the project state into a unique dotfile */ static bool saveProject(const Speaker& speaker, const SealedBox& sbox, const PortedBox& pbox, const BandPassBox& bpbox, int number = 1, int tab = 0); /* restore the saved project from the dotfile */ static bool restoreProject(Speaker& speaker, SealedBox& sbox, PortedBox& pbox, BandPassBox& bpbox, int *number, int *tab); /* in: speaker, sbox, pbox, bpbox, number, tab * out: file */ static bool exportProject(QFile& file, const Speaker& speaker, const SealedBox& sbox, const PortedBox& pbox, const BandPassBox& bpbox, int number = 1, int tab = 0); /* in: file * out: speaker, sbox, pbox, bpbox */ static bool importProject(Speaker& speaker, SealedBox& sbox, PortedBox& pbox, BandPassBox& bpbox, int *number, int *tab, QFile &file); static void setSavePath(const QString& path); static QString getSavePath(void); private: static QString savePath; #define SAVE_FILENAME "qspeakers_save.xml" }; #endif // IMPORTEXPORT_H
1,226
C++
.h
29
38.758621
168
0.726431
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,944
mainwindow.h
be1_qspeakers/mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QFileDialog> #include <QPrinter> #include "speakerdialog.h" #include "searchdialog.h" #include "listdialog.h" #include "bandpassdialog.h" #include "speaker.h" #include "sealedbox.h" #include "portedbox.h" #include "bandpassbox.h" #include "plot.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); QUndoStack* getCommandStack() { return this->commandStack; }; void changeSpeakerNumber(int number); void changeVendor(const QString &vendor, const Speaker& oldspeaker); void changeModel(const QString &model); void changeSealedVolume(double val); void changePortedVolume(double val); void changePortedResFreq(double val); void changePortedPortNumber(unsigned int val); void changePortedPortDiam(double val); void changePortedSlotPortActivation(bool checked); void changePortedSlotWidth(double val); void changeBPSealedVolume(double val); void changeBPPortedVolume(double val); void changeBPPortedResFreq(double val); void changeBPPortedPortNumber(double val); void changeBPPortedPortDiam(double val); void changeBPPortedSlotPortActivation(bool checked); void changeBPPortedSlotWidth(double val); void exportPlot(const QString& outfileName, int tabindex); void exportScad3D(const QString& outfileName, int tabindex); void exportScad2D(const QString& outfileName, int tabindex); void exportScad(const QString &scad, const QString& outfileName, int tabindex); signals: void currentSpeakerChanged(Speaker spk); void currentSealedBoxChanged(SealedBox box); void currentPortedBoxChanged(PortedBox box); void currentBandPassBoxChanged(BandPassBox box); public slots: void onProjectSave(); void onProjectExport(); void onProjectImport(); void onOpenRecentActionTriggered(); void onProjectQuit(); void onSpeakerNew(); void onSpeakerRemove(); void onSpeakerModify(); void onSpeakerInserted(Speaker spk); void onSpeakerCancelled(); void onEditOptimize(); void onSpeakerSearch(); void onProjectPrint(); void onUndo(); void onRedo(); void onAboutAbout(); void onSearchRequested(const QString& param, double min, double max); void onSearchCancelled(); void onSpeakerItemSelected(QString title, const Speaker &speaker); void onSpeakerItemCancelled(); void onCurrentTabChanged(int tab); void onNumberSpinChanged(int number); void onVendorChanged(QString vendor); void onModelChanged(QString model); void onCurrentSpeakerChanged(const Speaker& spk); void onCurrentSealedBoxChanged(const SealedBox& box); void onCurrentPortedBoxChanged(const PortedBox& box); void onCurrentBandPassBoxChanged(const BandPassBox& box); void onSealedVolumeDoubleSpinChanged(double val); void onPortedVolumeDoubleSpinChanged(double val); void onPortedResonanceDoubleSpinChanged(double val); void onPortedPortsNumberSpinChanged(int val); void onPortedPortDiameterDoubleSpinChanged(double val); void onPortedSlotWidthDoubleSpinChanged(double val); void onPortedSlotPortActivated(bool checked); void onBandPassSealedVolumeDoubleSpinChanged(double val); void onBandPassPortedVolumeDoubleSpinChanged(double val); void onBandPassPortedResonanceDoubleSpinChanged(double val); void onBandPassPortNumSpinChanged(int val); void onBandPassPortDiameterDoubleSpinChanged(double val); void onBandPassSlotWidthDoubleSpinChanged(double val); void onBandPassSlotPortActivated(bool checked); void onAlignModerate_Inf(); void onAlignLegendre(); void onAlignBessel(); void onAlignBullock(); void onAlignKeele_Hoge(); void onBandpassAlignment(); void onBandpassOptimizeRequested(double s, double pa); void onBandpassOptimizeCancelled(); void onCurvePlot(); void on3DScadExport(); void on2DScadExport(); protected: QString strippedName(const QString& fullFileName); void updateRecentFileActions(); void setRecentFile(const QString& fileName, bool ok); bool loadFile(const QString& fileName); void linkMenus(); void linkTabs(); void linkInternals(); void unlinkMenus(); void unlinkTabs(); void unlinkInternals(); bool print(QPrinter* printer); void syncUiFromCurrentSpeaker(const Speaker &spk); void syncUiFromCurrentSealedBox(const SealedBox& box); void syncUiFromCurrentPortedBox(const PortedBox& box); void syncUiFromCurrentBandPassBox(const BandPassBox& box); void setActivateActions(QList<QAction *> actions, bool enable); void setCurrentSpeaker(const Speaker& spk); private: static QString getHome(); Ui::MainWindow *ui; bool projectSaved; bool isModifying; SpeakerDialog *spkDialog; QFileDialog *fileDialog; SearchDialog *searchDialog; ListDialog *listDialog; BandpassDialog *bandpassDialog; Speaker oldSpeaker; Speaker currentSpeaker; int currentSpeakerNumber; SealedBox currentSealedBox; PortedBox currentPortedBox; BandPassBox currentBandPassBox; int currentTabIndex; Plot *sealedPlot; Plot *portedPlot; Plot *bandpassPlot; const Speaker *notInDbSpeaker; QUndoStack *commandStack; enum { MaxRecentFiles = 5 }; QAction *recentFileActs[MaxRecentFiles]; }; #endif // MAINWINDOW_H
5,529
C++
.h
150
32.306667
83
0.77192
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,945
undocommands.h
be1_qspeakers/undocommands.h
#ifndef UNDOCOMMANDS_H #define UNDOCOMMANDS_H #include <QUndoCommand> #include "mainwindow.h" class GenericCommand: public QUndoCommand { public: GenericCommand(QObject *parent) : manual(true), mainwindow(static_cast<MainWindow*>(parent)) {} void undo() override { this->manual = false; } void redo() override { this->manual = false; } protected: bool manual; MainWindow* mainwindow; }; class NumberCommand: public GenericCommand { public: NumberCommand(int older, int newer, QObject *parent) : GenericCommand(parent) { this->older = older; this->newer = newer; }; void undo() override { this->mainwindow->changeSpeakerNumber(older); GenericCommand::undo(); }; void redo() override { this->mainwindow->changeSpeakerNumber(newer); GenericCommand::redo(); }; private: int older; int newer; }; class VendorCommand: public GenericCommand { public: VendorCommand(const QString& older, const QString& newer, const Speaker& oldspeaker, QObject *parent) : GenericCommand(parent) { this->oldspeaker = oldspeaker; this->older = older; this->newer = newer; }; void undo() override { this->mainwindow->changeVendor(older, oldspeaker); GenericCommand::undo(); }; void redo() override { this->mainwindow->changeVendor(newer, Speaker()); GenericCommand::redo(); }; private: Speaker oldspeaker; QString older; QString newer; }; class ModelCommand: public GenericCommand { public: ModelCommand(const QString& older, const QString& newer, QObject *parent) : GenericCommand(parent) { this->older = older; this->newer = newer; }; void undo() override { this->mainwindow->changeModel(older); GenericCommand::undo(); }; void redo() override { this->mainwindow->changeModel(newer); GenericCommand::redo(); }; private: QString older; QString newer; }; class SealedVolumeCommand: public GenericCommand { public: SealedVolumeCommand(double older, double newer, QObject *parent) : GenericCommand(parent) { this->older = older; this->newer = newer; }; void undo() override { this->mainwindow->changeSealedVolume(older); GenericCommand::undo(); }; void redo() override { this->mainwindow->changeSealedVolume(newer); GenericCommand::redo(); }; protected: double older; double newer; }; class PortedVolumeCommand: public GenericCommand { public: PortedVolumeCommand(double older, double newer, QObject *parent) : GenericCommand(parent) { this->older = older; this->newer = newer; }; void undo() override { this->mainwindow->changePortedVolume(older); GenericCommand::undo(); }; void redo() override { this->mainwindow->changePortedVolume(newer); GenericCommand::redo(); }; protected: double older; double newer; }; class PortedResFreqCommand: public GenericCommand { public: PortedResFreqCommand(double older, double newer, QObject *parent) : GenericCommand(parent) { this->older = older; this->newer = newer; }; void undo() override { this->mainwindow->changePortedResFreq(older); GenericCommand::undo(); }; void redo() override { this->mainwindow->changePortedResFreq(newer); GenericCommand::redo(); }; protected: double older; double newer; }; class PortedPortNumberCommand: public GenericCommand { public: PortedPortNumberCommand(unsigned int older, unsigned int newer, QObject *parent) : GenericCommand(parent) { this->older = older; this->newer = newer; }; void undo() override { this->mainwindow->changePortedPortNumber(older); GenericCommand::undo(); }; void redo() override { this->mainwindow->changePortedPortNumber(newer); GenericCommand::redo(); }; protected: unsigned int older; unsigned int newer; }; class PortedPortDiamCommand: public GenericCommand { public: PortedPortDiamCommand(double older, double newer, QObject *parent) : GenericCommand(parent) { this->older = older; this->newer = newer; }; void undo() override { this->mainwindow->changePortedPortDiam(older); GenericCommand::undo(); }; void redo() override { this->mainwindow->changePortedPortDiam(newer); GenericCommand::redo(); }; protected: double older; double newer; }; class PortedSlotPortCommand: public GenericCommand { public: PortedSlotPortCommand(bool older, bool newer, QObject *parent) : GenericCommand(parent) { this->older = older; this->newer = newer; }; void undo() override { this->mainwindow->changePortedSlotPortActivation(older); GenericCommand::undo(); }; void redo() override { this->mainwindow->changePortedSlotPortActivation(newer); GenericCommand::redo(); }; protected: bool older; bool newer; }; class PortedSlotWidthCommand: public GenericCommand { public: PortedSlotWidthCommand(double older, double newer, QObject *parent) : GenericCommand(parent) { this->older = older; this->newer = newer; }; void undo() override { this->mainwindow->changePortedSlotWidth(older); GenericCommand::undo(); }; void redo() override { this->mainwindow->changePortedSlotWidth(newer); GenericCommand::redo(); }; protected: double older; double newer; }; class BPSealedVolumeCommand: public SealedVolumeCommand { public: BPSealedVolumeCommand(double older, double newer, QObject *parent) : SealedVolumeCommand(older, newer, parent) {}; void undo() override { this->mainwindow->changeBPSealedVolume(this->older); GenericCommand::undo(); }; void redo() override { this->mainwindow->changeBPSealedVolume(this->newer); GenericCommand::redo(); }; }; class BPPortedVolumeCommand: public PortedVolumeCommand { public: BPPortedVolumeCommand(double older, double newer, QObject *parent) :PortedVolumeCommand(older, newer, parent) {}; void undo() override { this->mainwindow->changeBPPortedVolume(older); GenericCommand::undo(); }; void redo() override { this->mainwindow->changeBPPortedVolume(newer); GenericCommand::redo(); }; }; class BPPortedResFreqCommand: public PortedResFreqCommand { public: BPPortedResFreqCommand(double older, double newer, QObject *parent) : PortedResFreqCommand(older, newer, parent) {}; void undo() override { this->mainwindow->changeBPPortedResFreq(older); GenericCommand::undo(); }; void redo() override { this->mainwindow->changeBPPortedResFreq(newer); GenericCommand::redo(); }; }; class BPPortedPortNumberCommand: public PortedPortNumberCommand { public: BPPortedPortNumberCommand(unsigned int older, unsigned int newer, QObject *parent) : PortedPortNumberCommand(older, newer, parent) {}; void undo() override { this->mainwindow->changeBPPortedPortNumber(older); GenericCommand::undo(); }; void redo() override { this->mainwindow->changeBPPortedPortNumber(newer); GenericCommand::redo(); }; }; class BPPortedPortDiamCommand: public PortedPortDiamCommand { public: BPPortedPortDiamCommand(double older, double newer, QObject *parent) : PortedPortDiamCommand(older, newer, parent) {}; void undo() override { this->mainwindow->changeBPPortedPortDiam(older); GenericCommand::undo(); }; void redo() override { this->mainwindow->changeBPPortedPortDiam(newer); GenericCommand::redo(); }; }; class BPPortedSlotPortCommand: public PortedSlotPortCommand { public: BPPortedSlotPortCommand(bool older, bool newer, QObject* parent) : PortedSlotPortCommand(older, newer, parent) {}; void undo() override { this->mainwindow->changeBPPortedSlotPortActivation(older); GenericCommand::undo(); }; void redo() override { this->mainwindow->changeBPPortedSlotPortActivation(newer); GenericCommand::redo(); }; }; class BPPortedSlotWidthCommand: public PortedSlotWidthCommand { public: BPPortedSlotWidthCommand(double older, double newer, QObject* parent) : PortedSlotWidthCommand(older, newer, parent) {}; void undo() override { this->mainwindow->changeBPPortedSlotWidth(older); GenericCommand::undo(); }; void redo() override { this->mainwindow->changeBPPortedSlotWidth(newer); GenericCommand::redo(); }; }; #endif // UNDOCOMMANDS_H
8,973
C++
.h
327
22.211009
105
0.677116
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,946
speaker.h
be1_qspeakers/speaker.h
#ifndef SPEAKER_H #define SPEAKER_H #include <QString> #include <QMetaType> #include <QDomNode> #include <QDomElement> #include <QDomDocument> #include <QPainter> #include <QRectF> class Speaker { public: Speaker(); Speaker(const Speaker& copy); ~Speaker(); Speaker& operator=(const Speaker& copy); bool operator!=(const Speaker& r) const; bool operator==(const Speaker& r) const; bool isValid(void) const; void setVendor(const QString& vnd); void setModel(const QString& mdl); void setFs(double val); void setVas(double val); void setRe(double val); void setQts(double val); void setSd(double val); void setXmax(double val); void setZ(double val); void setLe(double val); void setQms(double val); void setQes(double val); void setSpl(double val); void setPe(double val); void setBL(double val); void setDia(double val); void setVc(int val); QString getVendor() const; QString getModel() const; double getFs(void) const; double getVas(void) const; double getRe(void) const; double getQts(void) const; double getSd(void) const; double getXmax() const; double getZ() const; double getLe() const; double getQms() const; double getQes() const; double getSpl() const; double getPe() const; double getBL() const; double getDia() const; int getVc() const; QDomElement toDomElement(QDomDocument& doc) const; void fromDomElement(const QDomElement& el); void render(QPainter *painter, const QRectF& area); private: QString vendor; QString model; // TSPs double fs; // Hz (resonance frequency) double vas; // L (equivalent volume of air) double re; // Ohm (DC resistance) double qts; // unitless (total Q) double sd; // m² (effective piston area) double z; // Ohm (nominal impedance) double qms; // unitless (mechanical Q) double qes; // unitless (electrical Q) double spl; // dB (sensitivity at 1W power input, in 1m distance) // Voice coil parameters double pe; // W (max power in normal use) double le; // mH (voice coil inductance) double xmax; // mm (linear excursion) double bl; // Tm (force factor) int vc; // number of voice coils // Mechanical data double dia; // m (cutout diameter) }; Q_DECLARE_METATYPE(Speaker) #endif // SPEAKER_H
2,405
C++
.h
80
25.675
69
0.68355
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,947
optimizer.h
be1_qspeakers/optimizer.h
#ifndef OPTIMIZER_H #define OPTIMIZER_H #include "mainwindow.h" #include "speaker.h" #include "box.h" #include "sealedbox.h" #include "portedbox.h" #include "bandpassbox.h" class Optimizer { public: Optimizer(const Speaker &speaker, SealedBox *box, int sibling, QObject* parent = nullptr); Optimizer(const Speaker &speaker, PortedBox *box, int sibling, QObject* parent = nullptr); Optimizer(const Speaker &speaker, BandPassBox *box, int sibling, QObject* parent = nullptr); void genericOptimizeBox(); void portedAlignModerate_Inf(); void portedAlignLegendre(); void portedAlignBessel(); void portedAlignBullock(); void portedAlignKeele_Hoge(); void bandpassAlignS_Pa(double s, double pa); void portedAlignVb_Fb(double vb, double fb, const QString &title); private: Speaker speaker; Box *box; int type; int sibling; /* number of speakers (not push-pull!) */ MainWindow* mainwindow; }; #endif // OPTIMIZER_H
976
C++
.h
30
29.2
96
0.73617
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,948
bandpassbox.h
be1_qspeakers/bandpassbox.h
#ifndef BANDPASSBOX_H #define BANDPASSBOX_H #include <QDomElement> #include <QDomDocument> #include <QPainter> #include <QRectF> #include "box.h" #include "sealedbox.h" #include "portedbox.h" class BandPassBox : public Box { public: BandPassBox(double svol = 0.1, double pvol = 0.01, double pfreq = 1, unsigned int pnum = 1, double plen = 0, double pdiam = 0); void setSealedBoxVolume(double vol); void setPortedBoxVolume(double vol); void setPortedBoxPortNum(unsigned int val); void setPortedBoxPortLen(double len); void setPortedBoxPortDiam(double diam); void setPortedBoxSlotWidth(double width); void setPortedBoxResFreq(double freq); void setPortedBoxSlotPortActivated(bool enable); void updatePortedBoxPorts(double sd, double xmax); void updatePortedBoxPortsLength(); void updatePortedBoxSlots(); double getSealedBoxVolume(void) const; double getPortedBoxVolume(void) const; unsigned int getPortedBoxPortNum(void) const; double getPortedBoxPortLen(void) const; double getPortedBoxPortDiam(void) const; bool getPortedBoxSlotPortActivated(void) const; double getPortedBoxSlotWidth() const; double getPortedBoxSlotHeight() const; double getPortedBoxResFreq(void) const; QDomElement toDomElement(QDomDocument& doc) const; void fromDomElement(const QDomElement &e); void render(QPainter *painter, const QRectF& area) const; private: SealedBox sealedBox; PortedBox portedBox; }; #endif // BANDPASSBOX_H
1,517
C++
.h
41
33.195122
131
0.773161
be1/qspeakers
37
5
1
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,950
Coeff_vector_gen.cpp
gnuradio_gr-dpd/examples/Data_Files/Coeff_vector_gen.cpp
#include <bits/stdc++.h> #include<armadillo> using namespace std; #define ll long long #define ld long double int main() { ifstream a,b; ofstream c; ld x, y; a.open("pa_coeff_img.txt", ios::in); b.open("pa_coeff_real.txt", ios::in); c.open("pa_coeff.txt", ios::app); c << "( "; for(ll i=0;i<28;i++) { a >> x; b >> y; c << y; if(x>=0) c << " + "; c << x << "j, "; } c << ")"; a.close(); b.close(); c.close(); a.open("dpd_img.txt", ios::in); b.open("dpd_real.txt", ios::in); c.open("dpd_coeff.txt", ios::app); c << "( "; for(ll i=0;i<28;i++) { a >> x; b >> y; c << y; if(x>=0) c << " + "; c << x << "j, "; } c << ")"; a.close(); b.close(); c.close(); }
703
C++
.cpp
45
13.466667
38
0.503794
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,951
LMS_coeff_estimation.cpp
gnuradio_gr-dpd/raw/Prototype_Codes/LMS_coeff_estimation.cpp
// Implementation of LMS based coefficient estimator /* ------------------------------------------------------------------------------------------------------------| Terminal Command to build this file: g++ LMS_coeff_estimation.cpp -O1 -llapack -lblas -larmadillo Example Input Format: ------------------------------------------------------------------------------------------------------------| Estimate coefficients: y/n y Enter PA_input(pre-distorted) - Real and Imag. parts: | 1.5 2.0 Enter PA_output (Gain phase-calibrated) - Real and Imag. parts: 1.0 1.7 | K_a, L_a, K_b, M_b and L_b Parameters of PA model for postdistorter: 2 3 2 2 2 Enter the mode of LMS predistortion: | Type Newton or EMA | Newton Error before Updation of weights: (0.300000,0.000000) | Taps: (+1.110e+00,+0.000e+00) | (-1.027e-02,+0.000e+00) (-1.027e-02,+0.000e+00) (+1.299e-02,+0.000e+00) | (-1.027e-02,+0.000e+00) (-1.027e-02,+0.000e+00) (-1.027e-02,+0.000e+00) | (-1.027e-02,+0.000e+00) (-1.027e-02,+0.000e+00) (-1.027e-02,+0.000e+00) | (-1.027e-02,+0.000e+00) (-1.027e-02,+0.000e+00) (-1.027e-02,+0.000e+00) | (-1.027e-02,+0.000e+00) Error after Updation of weights: (0.075000,0.000000) | Estimate coefficients: y/n ------------------------------------------------------------------------------------------------------------| */ #include<iostream> #define ARMA_DONT_PRINT_ERRORS #include<armadillo> #include<vector> #include<string> #include<complex> using namespace arma; typedef std::complex <double> gr_complexd; typedef std::complex <float> gr_complex; std::vector<int> dpd_params(5); int K_a, K_b, L_a, L_b, M_b; int M; int iter_limit; std::string str; int iteration; cx_mat w_iMinus1; const int sreg_len = 50; gr_complexd sreg[50]; const gr_complexd* ptr_sreg = sreg; gr_complexd pa_input, error; std::vector<gr_complexd> taps; cx_mat ls_estimation(cx_mat A, gr_complexd y) { cx_mat lambda(size(A*(A.t()))); lambda.fill(0.001); // lambda(0, 0) = 0.001; cx_mat yy(1, 1); yy(0, 0) = y; // cx_mat den = A * yy; // cx_mat num = A * (A.t()); // num = num + lambda*eye<cx_mat>( size(A*(A.t())) ); cx_mat ls_result = solve((A*(A.t()) + lambda*eye<cx_mat>( size(A*(A.t())) )), A * yy); // cx_mat ls_result(size(w_iMinus1), fill::zeros); return ls_result; } // Function to form a shift structure GMP vector void gen_GMPvector(const gr_complexd* const in, int item, int K_a, int L_a, int K_b, int M_b, int L_b, cx_colvec& GMP_vector) { /* Signal-and-Aligned Envelope */ // stacking L_a elements in reverse order cx_colvec y_vec_arma1(L_a, fill::zeros); for (int ii = L_a - 1; ii >= 0; ii--) y_vec_arma1(ii) = in[item - ii]; GMP_vector.rows(0, L_a - 1) = y_vec_arma1; // store abs() of y_vec_arma1 cx_colvec abs_y_vec_arma1(size(y_vec_arma1), fill::zeros); abs_y_vec_arma1.set_real(abs(y_vec_arma1)); cx_colvec yy_temp; yy_temp = y_vec_arma1 % abs_y_vec_arma1; if (K_a > 1) GMP_vector.rows(L_a, 2 * L_a - 1) = yy_temp; for (int kk = 2; kk < K_a; kk++) { // perform element-wise product using the overloaded % operator yy_temp = yy_temp % abs_y_vec_arma1; GMP_vector.rows(kk * L_a, (kk + 1) * L_a - 1) = yy_temp; } /* Signal-and-Delayed Envelope */ // stacking L_b+M_b elements in reverse order cx_colvec y_vec_arma23(L_b + M_b, fill::zeros); for (int ii = L_b + M_b - 1; ii >= 0; ii--) y_vec_arma23(ii) = in[item - ii]; // L_b signal elements cx_colvec y_vec_arma2 = y_vec_arma23.rows(0, L_b - 1); // store abs() of y_vec_arma23 cx_colvec abs_y_vec_arma23(size(y_vec_arma23), fill::zeros); abs_y_vec_arma23.set_real(abs(y_vec_arma23)); for (int mm = 1; mm < M_b + 1; mm++) { // stacking L_b delayed signal-envelope elements cx_colvec abs_y_vec_arma3 = abs_y_vec_arma23.rows(mm, L_b + mm - 1); cx_colvec yy_temp; yy_temp = y_vec_arma2 % abs_y_vec_arma3; GMP_vector.rows(K_a * L_a + (mm - 1) * K_b * L_b, K_a * L_a + (mm - 1) * K_b * L_b + L_b - 1) = yy_temp; for (int kk = 2; kk < K_b + 1; kk++) { // perform element-wise product using the overloaded % operator yy_temp = yy_temp % abs_y_vec_arma3; GMP_vector.rows(K_a * L_a + (mm - 1) * K_b * L_b + (kk - 1) * L_b, K_a * L_a + (mm - 1) * K_b * L_b + kk * L_b - 1) = yy_temp; } } } // Initialise Parameters, weight vectors void Init() { iteration = 1; for (int ii = 0; ii < sreg_len; ii++) sreg[ii]=0.0; // taps or weight-vector w_iMinus1.set_size(M, 1); w_iMinus1 = zeros<cx_mat>(M, 1); w_iMinus1(0, 0) = gr_complex(1.0, 0.0); } int main() { while(1) { std::cout << "Estimate coefficients: y/n \n"; char c; std::cin >> c; if(c=='n') break; double x,z; std::cout << "Enter PA_input(pre-distorted) - Real and Imag. parts: \n"; std::cin >> x >> z; std::complex <double> PA_input = (x, z); std::cout << "Enter PA_output (Gain phase-calibrated) - Real and Imag. parts: \n"; std::cin >> x >> z; std::complex <double> Gain_cal_PA_output = (x, z); std::cout << "K_a, L_a, K_b, M_b and L_b Parameters of PA model for postdistorter:\n"; std::cin >> dpd_params[0] >> dpd_params[1] >> dpd_params[2] >> dpd_params[3] >> dpd_params[4]; K_a = dpd_params[0]; L_a = dpd_params[1]; K_b = dpd_params[2]; M_b = dpd_params[3]; L_b = dpd_params[4]; M = dpd_params[0]*dpd_params[1] + dpd_params[2]*dpd_params[3]*dpd_params[4]; // std::cout << "Enter number of Iterations:\n"; // std::cin >> iter_limit; std::cout << "Enter the mode of LMS predistortion:\n \nType Newton or EMA\n \n"; std::cin >> str; Init(); pa_input = PA_input; sreg[49] = Gain_cal_PA_output; // extracting the PA output and arranging into a shift-structured GMP vector cx_colvec GMP_vector(M); gen_GMPvector(ptr_sreg, 49, K_a, L_a, K_b, M_b, L_b, GMP_vector); cx_mat pa_output = GMP_vector; cx_mat pa_output_t = GMP_vector.t(); for (int ii = 1; ii < sreg_len; ii++) sreg[ii - 1] = sreg[ii]; cx_mat learning_rate = {0.75}; cx_mat learning_rate_1_minus = {0.25}; cout << std::fixed; // adaptation error error = pa_input - as_scalar(pa_output_t * w_iMinus1); cout << "\nError before Updation of weights: " << error << "\n"; if(str == "Newton") { error = pa_input - as_scalar(pa_output_t * w_iMinus1); cx_mat ls_result = ls_estimation(pa_output, error); // update weight-vector w_iMinus1 = w_iMinus1 + (ls_result * learning_rate); } if(str == "EMA") { cx_mat ls_result = ls_estimation(pa_output, pa_input); // update weight-vector w_iMinus1 = (w_iMinus1 * learning_rate_1_minus) + (ls_result * learning_rate); } w_iMinus1.print("\nTaps: "); error = pa_input - as_scalar(pa_output_t * w_iMinus1); cout << "\nError after Updation of weights: " << error << "\n"; } }
8,856
C++
.cpp
199
34.924623
110
0.461848
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,952
RLS_coeff_estimation.cpp
gnuradio_gr-dpd/raw/Prototype_Codes/RLS_coeff_estimation.cpp
// Implementation of RLS based coefficient estimator /* ------------------------------------------------------------------------------------------------------------| Terminal Command to build this file: g++ RLS_coeff_estimation.cpp -O1 -llapack -lblas -larmadillo Example Input Format: ------------------------------------------------------------------------------------------------------------| Estimate coefficients: y/n y Enter PA_input(pre-distorted) - Real and Imag. parts: | 1.5 2.0 Enter PA_output (Gain phase-calibrated) - Real and Imag. parts: 1.0 1.7 | K_a, L_a, K_b, M_b and L_b Parameters of PA model for postdistorter: 2 3 2 2 2 Enter number of Iterations: | 10 inv_sqrt_gamma_iMinus1: 858.336 Error before Updation of weights: (-1.7,0) | Taps: (+7.429e-01,+0.000e+00) (0,0) | (0,0) (-4.370e-01,+0.000e+00) (0,0) | (0,0) (0,0) (0,0) | (0,0) (0,0) (0,0) | (0,0) (0,0) (0,0) | Error after Updation of weights: (-2.30746e-06,0) Estimate coefficients: y/n | ------------------------------------------------------------------------------------------------------------ */ #include<iostream> #include<armadillo> #include<vector> #include<string> #include<complex> using namespace arma; typedef std::complex <double> gr_complexd; typedef std::complex <float> gr_complex; std::vector<int> dpd_params(5); gr_complexd pa_input, error; gr_complexd pa_input_smooth, pa_output_smooth; gr_complexd sr1[10], sr2[10]; int K_a, L_a, K_b, M_b, L_b, M, M_bar; const int sreg_len = 50; gr_complex sreg[50]; const gr_complex *ptr_sreg = sreg; std::vector<gr_complexd> taps; int iteration, iter_limit; // Fast-RLS parameter declaration double lambda, one_over_sqrt_lambda, eta, inv_sqrt_gamma_iMinus1; cx_mat g_vec_iMinus1, g_vec_i, L_bar_iMinus1, w_i, w_iMinus1, A_mat, B_mat, g; cx_fcolvec yy_cx_fcolvec; cx_frowvec yy_cx_frowvec; cx_fmat y; cx_fmat y_in; //Function to update the postdistorted PA output dimensions void extract_postdistorted_y(cx_fmat &y_in, cx_fmat &y, int K_a, int L_a, int K_b, int M_b, int L_b, int M) { cx_fmat y_vec_1( 1, K_a*L_a, fill::zeros); cx_fmat y_tmp1 = y_in( 0, span(0, K_a*(L_a+1)-1) ); y_tmp1.reshape(L_a+1, K_a); y_tmp1.shed_row(L_a); y_vec_1 = vectorise(y_tmp1, 0); cx_fmat y_vec_2_tmp(K_b*L_b, M_b, fill::zeros); for (int mm = 1; mm < M_b+1; mm++) { int index1 = K_a*(L_a+1) + (mm-1)*K_b*(L_b+1); int index2 = K_a*(L_a+1) + (mm-1)*K_b*(L_b+1)+K_b*(L_b+1); cx_fmat y_tmp3 = y_in( 0, span(index1, index2-1) ); y_tmp3.reshape(L_b+1, K_b); y_tmp3.shed_row(L_b); y_vec_2_tmp.col(mm-1) = vectorise(y_tmp3, 0); } cx_fmat y_vec_2 = vectorise(y_vec_2_tmp, 0); y.cols(0, K_a*L_a-1) = strans(y_vec_1); y.cols(K_a*L_a, M-1) = strans(y_vec_2); } // Function for Time-update of gain vector - g void extract_g_vecs(cx_mat &g, cx_mat &g_vec_iMinus1, cx_mat &g_vec_i, int K_a, int L_a, int K_b, int M_b, int L_b, int M, int M_bar) { cx_mat g_vec_i1( K_a*L_a, 1, fill::zeros); cx_mat g_tmp1 = g( span(0, K_a*(L_a+1)-1), 0); g_tmp1.reshape(L_a+1, K_a); g_tmp1.shed_row(L_a); g_vec_i1 = vectorise(g_tmp1, 0); g_tmp1.insert_rows(0, 1); cx_mat g_vec_iMinus1_a = vectorise(g_tmp1, 0); cx_mat g_vec_i2_tmp(K_b*L_b, M_b, fill::zeros); cx_mat g_vec_iMinus1_b_tmp(K_b*(L_b+1), M_b, fill::zeros); for (int mm = 1; mm < M_b+1; mm++) { int index1 = K_a*(L_a+1) + (mm-1)*K_b*(L_b+1); int index2 = K_a*(L_a+1) + (mm-1)*K_b*(L_b+1)+K_b*(L_b+1); cx_mat g_tmp3 = g( span(index1, index2-1), 0); g_tmp3.reshape(L_b+1, K_b); g_tmp3.shed_row(L_b); g_vec_i2_tmp.col(mm-1) = vectorise(g_tmp3, 0); g_tmp3.insert_rows(0, 1); g_vec_iMinus1_b_tmp.col(mm-1) = vectorise(g_tmp3, 0); } cx_mat g_vec_i2 = vectorise(g_vec_i2_tmp, 0); cx_mat g_vec_iMinus1_b = vectorise(g_vec_iMinus1_b_tmp, 0); g_vec_i.rows(0, K_a*L_a-1) = g_vec_i1; g_vec_i.rows(K_a*L_a, M-1) = g_vec_i2; g_vec_iMinus1.rows(0, K_a*(L_a+1)-1) = g_vec_iMinus1_a; g_vec_iMinus1.rows(K_a*(L_a+1), M_bar-1) = g_vec_iMinus1_b; } // Function to form a shift structure GMP vector void gen_GMPvector(const gr_complex *const in, int item, int K_a, int L_a, int K_b, int M_b, int L_b, cx_fcolvec &GMP_vector) { /* Signal-and-Aligned Envelope */ // stacking L_a elements in reverse order cx_fcolvec y_vec_arma1(L_a, fill::zeros); for (int ii = L_a-1; ii >= 0; ii--) y_vec_arma1(ii) = in[item-ii]; GMP_vector.rows(0, L_a-1) = y_vec_arma1; //store abs() of y_vec_arma1 cx_fcolvec abs_y_vec_arma1( size(y_vec_arma1), fill::zeros ); abs_y_vec_arma1.set_real( abs(y_vec_arma1) ); cx_fcolvec yy_temp; yy_temp = y_vec_arma1%abs_y_vec_arma1; GMP_vector.rows(L_a, 2*L_a-1) = yy_temp; for (int kk = 2; kk<K_a; kk++) { // perform element-wise product using the overloaded % operator yy_temp = yy_temp%abs_y_vec_arma1; GMP_vector.rows(kk*L_a, (kk+1)*L_a-1) = yy_temp; } /* Signal-and-Delayed Envelope */ // stacking L_b+M_b elements in reverse order cx_fcolvec y_vec_arma23(L_b+M_b, fill::zeros); for (int ii = L_b+M_b-1; ii >= 0; ii--) y_vec_arma23(ii) = in[item-ii]; // L_b signal elements cx_fcolvec y_vec_arma2 = y_vec_arma23.rows(0, L_b-1); // store abs() of y_vec_arma23 cx_fcolvec abs_y_vec_arma23( size(y_vec_arma23), fill::zeros ); abs_y_vec_arma23.set_real( abs(y_vec_arma23) ); for (int mm = 1; mm < M_b+1; mm++) { // stacking L_b delayed signal-envelope elements cx_fcolvec abs_y_vec_arma3 = abs_y_vec_arma23.rows(mm, L_b+mm-1); cx_fcolvec yy_temp; yy_temp = y_vec_arma2%abs_y_vec_arma3; GMP_vector.rows(K_a*L_a+(mm-1)*K_b*L_b, K_a*L_a+(mm-1)*K_b*L_b+L_b-1) = yy_temp; for (int kk = 2; kk<K_b+1; kk++) { // perform element-wise product using the overloaded % operator yy_temp = yy_temp%abs_y_vec_arma3; GMP_vector.rows(K_a*L_a+(mm-1)*K_b*L_b+(kk-1)*L_b, K_a*L_a+(mm-1)*K_b*L_b+kk*L_b-1) = yy_temp; } } } bool almost_equal(double a, double b, double tol) { // calculate the difference double diff_ab = fabs(a - b); if (diff_ab <= tol*std::numeric_limits<double>::epsilon()) return true; return false; } void givens_rotate(const cx_mat & in, cx_mat & out) { const static gr_complexd minus_1i(0, -1); cx_mat theta(2, 2, fill::zeros); gr_complexd alpha; double scale, norm; cx_mat g(2, 2, fill::ones); // algorithm similar to LAPACK's crotg() // except for the application of scale adjustment matrix, g double a = abs(in(0, 0)); double b = abs(in(0, 1)); if (almost_equal(b, 0.0, 100.0)) { theta(0,0) = 1.0; theta(1,1) = 1.0; // scale adjustment matrix to make the first element of post-array real g(0, 0) = std::exp(minus_1i*std::arg(in(0, 0))); g(0, 1) = gr_complexd(0.0, 0.0); g(1, 0) = gr_complexd(0.0, 0.0); g(1, 1) = g(0, 0); } else if (almost_equal(a, 0.0, 100.0)) { theta(0,1) = 1.0; theta(1,0) = -1.0; // scale adjustment matrix to make the first element of post-array real g(0, 1) = std::exp(minus_1i*std::arg(in(0, 1))); g(1, 0) = g(0,1); } else { scale = a+b; norm = scale*sqrt(pow(abs(in(0, 0)/scale), 2)+ pow(abs(in(0, 1)/scale), 2)); alpha = in(0, 0)/a; theta(0,0) = a/norm; theta(1,1) = theta(0,0); theta(1,0) = alpha*conj(in(0, 1))/norm; theta(0,1) = -conj(theta(1,0)); // scale adjustment matrix to make the first element of post-array real g(0, 0) = std::exp(minus_1i*std::arg(in(0, 0))); g(0, 1) = g(0,0); g(1, 0) = g(0,0); g(1, 1) = g(0,0); } theta = g%theta; // form post-array out = in*theta; } void hgivens_rotate(const cx_mat & in, cx_mat & out) { const static gr_complexd minus_1i(0, -1); int flip; gr_complexd a, b, c, d1, d2, x, y, z, conj_a, conj_b, p, q; double scale, angle_a; x = in(0, 0); y = in(0, 1); if (almost_equal(abs(x), 0.0, 100.0)) { angle_a = std::arg(in(0, 1)); out = std::exp(minus_1i*angle_a)*in; } else if (almost_equal(abs(y), 0.0, 100.0)) { angle_a = std::arg(in(0, 0)); out = std::exp(minus_1i*angle_a)*in; } else { b = in(0, 1); a = in(0, 0); conj_a = conj(a); conj_b = conj(b); if ( abs(in(0, 0)) > abs(in(0, 1)) ) { flip = 0; scale = abs(a)/sqrt((abs(a) - abs(b)) * (abs(a) + abs(b))); d1 = (conj_a-conj_b)/conj_a; p = (a+b)/a; q = (conj_a+conj_b)/conj_a; } else { flip = 1; scale = abs(b)/sqrt((abs(b) - abs(a)) * (abs(a) + abs(b))); d1 = (b-a)/b; p = (conj_a+conj_b)/conj_b; q = (a+b)/b; } // Algorithm adapted from H-procedure described in 2.6.4 and 2.A of // Fast Reliable Algorithms for Matrices with Structure - Edited by Sayed and Kailath for (int ii = 0; ii < in.n_rows; ii++) { if ( almost_equal(abs(in(ii, 0)), 0.0, 100.0) && almost_equal(abs(in(ii, 1)), 0.0, 100.0) ) { out(ii, 0) = in(ii, 0); out(ii, 1) = in(ii, 1); } else { x = in(ii, 0); y = in(ii, 1); if ( !almost_equal(abs(in(ii, 0)), 0.0, 100.0) ) { d2 = (x-y)/x; z = d1+d2-d1*d2; out(ii, 0) = scale * x * z; out(ii, 1) = out(ii, 0) - scale*( p*x - q*y ); } else { out(ii, 0) = -scale*y*(q-gr_complexd(1.0, 0.0)); out(ii, 1) = scale*y; } } } if (flip == 0) out = std::exp(minus_1i*std::arg(out(0,0)))*out; else out = std::exp(minus_1i*std::arg(out(0,1)))*out; } } void apply_rotations(const cx_mat & A, cx_mat & B) { cx_mat A_bar = A; for (int i = 1; i < A_bar.n_cols; i++) { cx_mat z(A_bar.n_rows, 2, fill::zeros); z.col(0) = A_bar.col(0); z.col(1) = A_bar.col(i); cx_mat rotated_z(z.n_rows, 2, fill::zeros); switch( i%2 ) { case 1: // apply Givens rotation to z givens_rotate(z, rotated_z); break; case 0: // apply Hyperbolic-Givens rotation to z hgivens_rotate(z, rotated_z); break; } B.col(0) = rotated_z.col(0); if ( i>1 && i<A_bar.n_cols-1 ) { B.cols(1, i-1) = A_bar.cols(1, i-1); B.col(i) = rotated_z.col(1); B.cols(i+1, B.n_cols-1) = A_bar.cols(i+1, A_bar.n_cols-1); } else if ( i==1 ) { B.col(1) = rotated_z.col(1); B.cols(2, B.n_cols-1) = A_bar.cols(2, A_bar.n_cols-1); } else if ( i==A_bar.n_cols-1 ) { B.cols(1, B.n_cols-2) = A_bar.cols(1, A_bar.n_cols-2); B.col(B.n_cols-1) = rotated_z.col(1); } A_bar = B; } } // Initialise Parameters, weight, gain and conversion vectors void Init() { iteration = 1; for (int ii = 0; ii < sreg_len; ii++) sreg[ii]=0.0; for (int ii=0; ii < 10; ii++) { sr1[ii]=gr_complexd(0.0,0.0); sr2[ii]=gr_complexd(0.0,0.0); } // constants int k = 16; lambda = 1-pow(2, 1-k); one_over_sqrt_lambda = 1.0/sqrt(lambda); eta = pow(2, k); g_vec_iMinus1.set_size(M+M_bar, 1); g_vec_i.set_size(M, 1); L_bar_iMinus1.set_size(M+M_bar, M_bar*2); w_i.set_size(M, 1); w_iMinus1.set_size(M, 1); // inverse of square-root of gamma inv_sqrt_gamma_iMinus1 = 1; // g vector g_vec_iMinus1 = zeros<cx_mat>(M+M_bar, 1); // L-bar matrix cx_mat temp_cx_mat1(L_a+1, 2, fill::zeros); temp_cx_mat1(0, 0) = gr_complexd(sqrt(eta*lambda), 0); temp_cx_mat1(L_a, 1) = sqrt(eta*lambda)*pow(lambda, 0.5*L_a); cx_mat eye_K_a(K_a, K_a, fill::eye); cx_mat L_bar_iMinus1_a = kron(eye_K_a, temp_cx_mat1); cx_mat temp_cx_mat2(L_b+1, 2, fill::zeros); temp_cx_mat2(0, 0) = gr_complexd(sqrt(eta*lambda), 0); temp_cx_mat2(L_b, 1) = sqrt(eta*lambda)*pow(lambda, 0.5*L_b); cx_mat eye_K_bM_b(K_b*M_b, K_b*M_b, fill::eye); cx_mat L_bar_iMinus1_b = kron(eye_K_bM_b, temp_cx_mat2); L_bar_iMinus1 = zeros<cx_mat>(K_a*(L_a+1)+K_b*M_b*(L_b+1), (K_a+K_b*M_b)*2); L_bar_iMinus1( span(0, K_a*(L_a+1)-1), span(0, K_a*2-1) ) = L_bar_iMinus1_a; L_bar_iMinus1( span(K_a*(L_a+1), K_a*(L_a+1)+K_b*M_b*(L_b+1)-1), span(K_a*2, (K_a+K_b*M_b)*2-1) ) = L_bar_iMinus1_b; //weight-vector w_iMinus1 = zeros<cx_mat>(M, 1); w_iMinus1(0,0) = gr_complexd(1.0, 0.0); // A and B matrices A_mat.set_size(M+M_bar+1, M_bar*2+1); B_mat.set_size(M+M_bar+1, M_bar*2+1); yy_cx_fcolvec.set_size(M+M_bar); yy_cx_frowvec.set_size(M+M_bar); y.set_size(1, M); g.set_size(M+M_bar-1, 1); } // void gauss_smooth(gr_complexd *sr, gr_complexd &out) // { // // Gaussian smoothing // out = gr_complexd(0.0, 0.0); // for (int ii = 0; ii < sr_len; ii++) // out += sr[ii]*w[ii]; // // shift the register contents // for (int jj = sr_len-1; jj > 0; jj--) // sr[jj] = sr[jj-1]; // } int main() { while(1) { std::cout << "Estimate coefficients: y/n \n"; char c; std::cin >> c; if(c=='n') break; double x,z; std::cout << "Enter PA_input(pre-distorted) - Real and Imag. parts: \n"; std::cin >> x >> z; std::complex <double> PA_input = (x, z); std::cout << "Enter PA_output (Gain phase-calibrated) - Real and Imag. parts: \n"; std::cin >> x >> z; std::complex <double> Gain_cal_PA_output = (x, z); std::cout << "K_a, L_a, K_b, M_b and L_b Parameters of PA model for postdistorter:\n"; std::cin >> dpd_params[0] >> dpd_params[1] >> dpd_params[2] >> dpd_params[3] >> dpd_params[4]; K_a = dpd_params[0]; L_a = dpd_params[1]; K_b = dpd_params[2]; M_b = dpd_params[3]; L_b = dpd_params[4]; M = dpd_params[0]*dpd_params[1] + dpd_params[2]*dpd_params[3]*dpd_params[4]; M_bar = dpd_params[0] + dpd_params[2]*dpd_params[3]; // std::cout << "Enter number of Iterations:\n"; // std::cin >> iter_limit; Init(); // sr1[0] = pa_input; // gauss_smooth(sr1, pa_input_smooth); // sr2[0] = Gain_cal_PA_output; // gauss_smooth(sr2, pa_output_smooth); // sreg[49] = pa_output_smooth; // extracting the PA output and arranging into a shift-structured GMP vector pa_input = PA_input; sreg[49] = Gain_cal_PA_output; gen_GMPvector(ptr_sreg, 49, K_a, L_a+1, K_b, M_b, L_b+1, yy_cx_fcolvec); yy_cx_frowvec = yy_cx_fcolvec.st(); // yy = conv_to<cx_fmat>::from(yy_cx_frowvec); for (int ii = 1; ii < sreg_len; ii++) sreg[ii-1] = sreg[ii]; // A-matrix A_mat.submat(0, 0, 0, 0) = inv_sqrt_gamma_iMinus1; A_mat.submat(0, 1, 0, M_bar*2) = yy_cx_frowvec*L_bar_iMinus1; A_mat.submat(1, 0, M+M_bar, 0) = g_vec_iMinus1; A_mat.submat(1, 1, M+M_bar, M_bar*2) = L_bar_iMinus1; // obtain B-matrix by performing Givens and Hyperbolic Givens rotations apply_rotations(A_mat, B_mat); // time-update for 1/sqrt(gamma) inv_sqrt_gamma_iMinus1 = real(B_mat(0, 0)); // imag(B_mat(0, 0)) will be ~= 0.0 std::cout << "inv_sqrt_gamma_iMinus1: " << inv_sqrt_gamma_iMinus1 << std::endl; // time-update for g-vector g = B_mat(span(1, M+M_bar), 0); extract_g_vecs(g, g_vec_iMinus1, g_vec_i, K_a, L_a, K_b, M_b, L_b, M, M+M_bar); // adjust post-distorted PA output dimensions extract_postdistorted_y(yy_cx_frowvec, y, K_a, L_a, K_b, M_b, L_b, M); cout << std::fixed; // adaptation error error = pa_input - as_scalar(y*w_iMinus1); cout << "Error before Updation of weights: " << error << "\n"; // update weight-vector w_iMinus1 = w_iMinus1+(error/inv_sqrt_gamma_iMinus1)*g_vec_i; // prepare L_bar for next iteration L_bar_iMinus1 = gr_complexd(one_over_sqrt_lambda, 0.0) * B_mat( span(1, M+M_bar), span(1, 2*M_bar) ); w_iMinus1.print("Taps: "); error = pa_input - as_scalar(y*w_iMinus1); cout << "\n Error after Updation of weights: " << error << "\n"; } }
17,463
C++
.cpp
437
33.466819
136
0.51524
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,954
RLS_postdistorter_impl.cc
gnuradio_gr-dpd/lib/RLS_postdistorter_impl.cc
/* -*- c++ -*- */ /* * Copyright 2020 Alekh Gupta * * SPDX-License-Identifier: GPL-3.0-or-later */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "RLS_postdistorter_impl.h" #include <gnuradio/io_signature.h> #include <armadillo> #include <string> #define COPY_MEM false // Do not copy matrices into separate memory #define FIX_SIZE true // Keep dimensions of matrices constant using namespace std; using std::string; using namespace arma; namespace gr { namespace dpd { RLS_postdistorter::sptr RLS_postdistorter::make(const std::vector<int>& dpd_params, int iter_limit) { return gnuradio::get_initial_sptr(new RLS_postdistorter_impl(dpd_params, iter_limit)); } /* * The private constructor */ RLS_postdistorter_impl::RLS_postdistorter_impl(const std::vector<int>& dpd_params, int iter_limit) : gr::sync_block("RLS_postdistorter", gr::io_signature::make(3, 3, sizeof(gr_complex)), gr::io_signature::make(0, 0, 0)), d_dpd_params(dpd_params), K_a(d_dpd_params[0]), L_a(d_dpd_params[1]), K_b(d_dpd_params[2]), M_b(d_dpd_params[3]), L_b(d_dpd_params[4]), M(dpd_params[0] * dpd_params[1] + dpd_params[2] * dpd_params[3] * dpd_params[4]), M_bar(dpd_params[0] + dpd_params[2] * dpd_params[3]), d_iter_limit(iter_limit) { d_ack_predistorter_updated = false; // setup output message port message_port_register_out(pmt::mp("taps")); iteration = 1; for (int ii = 0; ii < sreg_len; ii++) sreg[ii] = 0.0; for (int ii = 0; ii < 10; ii++) { sr1[ii] = gr_complexd(0.0, 0.0); sr2[ii] = gr_complexd(0.0, 0.0); } // constants int k = 16; lambda = 1 - pow(2, 1 - k); one_over_sqrt_lambda = 1.0 / sqrt(lambda); eta = pow(2, k); g_vec_iMinus1.set_size(M + M_bar, 1); g_vec_i.set_size(M, 1); L_bar_iMinus1.set_size(M + M_bar, M_bar * 2); w_i.set_size(M, 1); w_iMinus1.set_size(M, 1); // inverse of square-root of gamma inv_sqrt_gamma_iMinus1 = 1; // g vector g_vec_iMinus1 = zeros<cx_mat>(M + M_bar, 1); // L-bar matrix cx_mat temp_cx_mat1(L_a + 1, 2, fill::zeros); temp_cx_mat1(0, 0) = gr_complexd(sqrt(eta * lambda), 0); temp_cx_mat1(L_a, 1) = sqrt(eta * lambda) * pow(lambda, 0.5 * L_a); cx_mat eye_K_a(K_a, K_a, fill::eye); cx_mat L_bar_iMinus1_a = kron(eye_K_a, temp_cx_mat1); cx_mat temp_cx_mat2(L_b + 1, 2, fill::zeros); temp_cx_mat2(0, 0) = gr_complexd(sqrt(eta * lambda), 0); temp_cx_mat2(L_b, 1) = sqrt(eta * lambda) * pow(lambda, 0.5 * L_b); cx_mat eye_K_bM_b(K_b * M_b, K_b * M_b, fill::eye); cx_mat L_bar_iMinus1_b = kron(eye_K_bM_b, temp_cx_mat2); L_bar_iMinus1 = zeros<cx_mat>(K_a * (L_a + 1) + K_b * M_b * (L_b + 1), (K_a + K_b * M_b) * 2); L_bar_iMinus1(span(0, K_a * (L_a + 1) - 1), span(0, K_a * 2 - 1)) = L_bar_iMinus1_a; L_bar_iMinus1(span(K_a * (L_a + 1), K_a * (L_a + 1) + K_b * M_b * (L_b + 1) - 1), span(K_a * 2, (K_a + K_b * M_b) * 2 - 1)) = L_bar_iMinus1_b; // weight-vector w_iMinus1 = zeros<cx_mat>(M, 1); w_iMinus1(0, 0) = gr_complexd(1.0, 0.0); // A and B matrices A_mat.set_size(M + M_bar + 1, M_bar * 2 + 1); B_mat.set_size(M + M_bar + 1, M_bar * 2 + 1); yy_cx_fcolvec.set_size(M + M_bar); yy_cx_frowvec.set_size(M + M_bar); y.set_size(1, M); g.set_size(M + M_bar - 1, 1); } /* * Our virtual destructor. */ RLS_postdistorter_impl::~RLS_postdistorter_impl() {} bool RLS_postdistorter_impl::almost_equal(double a, double b, double tol) { // calculate the difference double diff_ab = fabs(a - b); if (diff_ab <= tol * std::numeric_limits<double>::epsilon()) return true; return false; } void RLS_postdistorter_impl::givens_rotate(const cx_mat& in, cx_mat& out) { const static gr_complexd minus_1i(0, -1); cx_mat theta(2, 2, fill::zeros); gr_complexd alpha; double scale, norm; cx_mat g(2, 2, fill::ones); // algorithm similar to LAPACK's crotg() // except for the application of scale adjustment matrix, g double a = abs(in(0, 0)); double b = abs(in(0, 1)); if (almost_equal(b, 0.0, 100.0)) { theta(0, 0) = 1.0; theta(1, 1) = 1.0; // scale adjustment matrix to make the first element of post-array real g(0, 0) = std::exp(minus_1i * std::arg(in(0, 0))); g(0, 1) = gr_complexd(0.0, 0.0); g(1, 0) = gr_complexd(0.0, 0.0); g(1, 1) = g(0, 0); } else if (almost_equal(a, 0.0, 100.0)) { theta(0, 1) = 1.0; theta(1, 0) = -1.0; // scale adjustment matrix to make the first element of post-array real g(0, 1) = std::exp(minus_1i * std::arg(in(0, 1))); g(1, 0) = g(0, 1); } else { scale = a + b; norm = scale * sqrt(pow(abs(in(0, 0) / scale), 2) + pow(abs(in(0, 1) / scale), 2)); alpha = in(0, 0) / a; theta(0, 0) = a / norm; theta(1, 1) = theta(0, 0); theta(1, 0) = alpha * conj(in(0, 1)) / norm; theta(0, 1) = -conj(theta(1, 0)); // scale adjustment matrix to make the first element of post-array real g(0, 0) = std::exp(minus_1i * std::arg(in(0, 0))); g(0, 1) = g(0, 0); g(1, 0) = g(0, 0); g(1, 1) = g(0, 0); } theta = g % theta; // form post-array out = in * theta; } void RLS_postdistorter_impl::hgivens_rotate(const cx_mat& in, cx_mat& out) { const static gr_complexd minus_1i(0, -1); int flip; gr_complexd a, b, c, d1, d2, x, y, z, conj_a, conj_b, p, q; double scale, angle_a; x = in(0, 0); y = in(0, 1); if (almost_equal(abs(x), 0.0, 100.0)) { angle_a = std::arg(in(0, 1)); out = std::exp(minus_1i * angle_a) * in; } else if (almost_equal(abs(y), 0.0, 100.0)) { angle_a = std::arg(in(0, 0)); out = std::exp(minus_1i * angle_a) * in; } else { b = in(0, 1); a = in(0, 0); conj_a = conj(a); conj_b = conj(b); if (abs(in(0, 0)) > abs(in(0, 1))) { flip = 0; scale = abs(a) / sqrt((abs(a) - abs(b)) * (abs(a) + abs(b))); d1 = (conj_a - conj_b) / conj_a; p = (a + b) / a; q = (conj_a + conj_b) / conj_a; } else { flip = 1; scale = abs(b) / sqrt((abs(b) - abs(a)) * (abs(a) + abs(b))); d1 = (b - a) / b; p = (conj_a + conj_b) / conj_b; q = (a + b) / b; } // Algorithm adapted from H-procedure described in 2.6.4 and 2.A of // Fast Reliable Algorithms for Matrices with Structure - Edited by Sayed and // Kailath for (int ii = 0; ii < in.n_rows; ii++) { if (almost_equal(abs(in(ii, 0)), 0.0, 100.0) && almost_equal(abs(in(ii, 1)), 0.0, 100.0)) { out(ii, 0) = in(ii, 0); out(ii, 1) = in(ii, 1); } else { x = in(ii, 0); y = in(ii, 1); if (!almost_equal(abs(in(ii, 0)), 0.0, 100.0)) { d2 = (x - y) / x; z = d1 + d2 - d1 * d2; out(ii, 0) = scale * x * z; out(ii, 1) = out(ii, 0) - scale * (p * x - q * y); } else { out(ii, 0) = -scale * y * (q - gr_complexd(1.0, 0.0)); out(ii, 1) = scale * y; } } } if (flip == 0) out = std::exp(minus_1i * std::arg(out(0, 0))) * out; else out = std::exp(minus_1i * std::arg(out(0, 1))) * out; } } void RLS_postdistorter_impl::extract_g_vecs(cx_mat& g, cx_mat& g_vec_iMinus1, cx_mat& g_vec_i, int K_a, int L_a, int K_b, int M_b, int L_b, int M, int M_bar) { cx_mat g_vec_i1(K_a * L_a, 1, fill::zeros); cx_mat g_tmp1 = g(span(0, K_a * (L_a + 1) - 1), 0); g_tmp1.reshape(L_a + 1, K_a); g_tmp1.shed_row(L_a); g_vec_i1 = vectorise(g_tmp1, 0); g_tmp1.insert_rows(0, 1); cx_mat g_vec_iMinus1_a = vectorise(g_tmp1, 0); cx_mat g_vec_i2_tmp(K_b * L_b, M_b, fill::zeros); cx_mat g_vec_iMinus1_b_tmp(K_b * (L_b + 1), M_b, fill::zeros); for (int mm = 1; mm < M_b + 1; mm++) { int index1 = K_a * (L_a + 1) + (mm - 1) * K_b * (L_b + 1); int index2 = K_a * (L_a + 1) + (mm - 1) * K_b * (L_b + 1) + K_b * (L_b + 1); cx_mat g_tmp3 = g(span(index1, index2 - 1), 0); g_tmp3.reshape(L_b + 1, K_b); g_tmp3.shed_row(L_b); g_vec_i2_tmp.col(mm - 1) = vectorise(g_tmp3, 0); g_tmp3.insert_rows(0, 1); g_vec_iMinus1_b_tmp.col(mm - 1) = vectorise(g_tmp3, 0); } cx_mat g_vec_i2 = vectorise(g_vec_i2_tmp, 0); cx_mat g_vec_iMinus1_b = vectorise(g_vec_iMinus1_b_tmp, 0); g_vec_i.rows(0, K_a * L_a - 1) = g_vec_i1; g_vec_i.rows(K_a * L_a, M - 1) = g_vec_i2; g_vec_iMinus1.rows(0, K_a * (L_a + 1) - 1) = g_vec_iMinus1_a; g_vec_iMinus1.rows(K_a * (L_a + 1), M_bar - 1) = g_vec_iMinus1_b; } void RLS_postdistorter_impl::extract_postdistorted_y( cx_fmat& y_in, cx_fmat& y, int K_a, int L_a, int K_b, int M_b, int L_b, int M) { cx_fmat y_vec_1(1, K_a * L_a, fill::zeros); cx_fmat y_tmp1 = y_in(0, span(0, K_a * (L_a + 1) - 1)); y_tmp1.reshape(L_a + 1, K_a); y_tmp1.shed_row(L_a); y_vec_1 = vectorise(y_tmp1, 0); cx_fmat y_vec_2_tmp(K_b * L_b, M_b, fill::zeros); for (int mm = 1; mm < M_b + 1; mm++) { int index1 = K_a * (L_a + 1) + (mm - 1) * K_b * (L_b + 1); int index2 = K_a * (L_a + 1) + (mm - 1) * K_b * (L_b + 1) + K_b * (L_b + 1); cx_fmat y_tmp3 = y_in(0, span(index1, index2 - 1)); y_tmp3.reshape(L_b + 1, K_b); y_tmp3.shed_row(L_b); y_vec_2_tmp.col(mm - 1) = vectorise(y_tmp3, 0); } cx_fmat y_vec_2 = vectorise(y_vec_2_tmp, 0); y.cols(0, K_a * L_a - 1) = strans(y_vec_1); y.cols(K_a * L_a, M - 1) = strans(y_vec_2); } void RLS_postdistorter_impl::apply_rotations(const cx_mat& A, cx_mat& B) { cx_mat A_bar = A; for (int i = 1; i < A_bar.n_cols; i++) { cx_mat z(A_bar.n_rows, 2, fill::zeros); z.col(0) = A_bar.col(0); z.col(1) = A_bar.col(i); cx_mat rotated_z(z.n_rows, 2, fill::zeros); switch (i % 2) { case 1: // apply Givens rotation to z givens_rotate(z, rotated_z); break; case 0: // apply Hyperbolic-Givens rotation to z hgivens_rotate(z, rotated_z); break; } B.col(0) = rotated_z.col(0); if (i > 1 && i < A_bar.n_cols - 1) { B.cols(1, i - 1) = A_bar.cols(1, i - 1); B.col(i) = rotated_z.col(1); B.cols(i + 1, B.n_cols - 1) = A_bar.cols(i + 1, A_bar.n_cols - 1); } else if (i == 1) { B.col(1) = rotated_z.col(1); B.cols(2, B.n_cols - 1) = A_bar.cols(2, A_bar.n_cols - 1); } else if (i == A_bar.n_cols - 1) { B.cols(1, B.n_cols - 2) = A_bar.cols(1, A_bar.n_cols - 2); B.col(B.n_cols - 1) = rotated_z.col(1); } A_bar = B; } } void RLS_postdistorter_impl::gen_GMPvector(const gr_complex* const in, int item, int K_a, int L_a, int K_b, int M_b, int L_b, cx_fcolvec& GMP_vector) { /* Signal-and-Aligned Envelope */ // stacking L_a elements in reverse order cx_fcolvec y_vec_arma1(L_a, fill::zeros); for (int ii = L_a - 1; ii >= 0; ii--) y_vec_arma1(ii) = in[item - ii]; GMP_vector.rows(0, L_a - 1) = y_vec_arma1; // store abs() of y_vec_arma1 cx_fcolvec abs_y_vec_arma1(size(y_vec_arma1), fill::zeros); abs_y_vec_arma1.set_real(abs(y_vec_arma1)); cx_fcolvec yy_temp; yy_temp = y_vec_arma1 % abs_y_vec_arma1; if (K_a > 1) GMP_vector.rows(L_a, 2 * L_a - 1) = yy_temp; for (int kk = 2; kk < K_a; kk++) { // perform element-wise product using the overloaded % operator yy_temp = yy_temp % abs_y_vec_arma1; GMP_vector.rows(kk * L_a, (kk + 1) * L_a - 1) = yy_temp; } /* Signal-and-Delayed Envelope */ // stacking L_b+M_b elements in reverse order cx_fcolvec y_vec_arma23(L_b + M_b, fill::zeros); for (int ii = L_b + M_b - 1; ii >= 0; ii--) y_vec_arma23(ii) = in[item - ii]; // L_b signal elements cx_fcolvec y_vec_arma2 = y_vec_arma23.rows(0, L_b - 1); // store abs() of y_vec_arma23 cx_fcolvec abs_y_vec_arma23(size(y_vec_arma23), fill::zeros); abs_y_vec_arma23.set_real(abs(y_vec_arma23)); for (int mm = 1; mm < M_b + 1; mm++) { // stacking L_b delayed signal-envelope elements cx_fcolvec abs_y_vec_arma3 = abs_y_vec_arma23.rows(mm, L_b + mm - 1); cx_fcolvec yy_temp; yy_temp = y_vec_arma2 % abs_y_vec_arma3; GMP_vector.rows(K_a * L_a + (mm - 1) * K_b * L_b, K_a * L_a + (mm - 1) * K_b * L_b + L_b - 1) = yy_temp; for (int kk = 2; kk < K_b + 1; kk++) { // perform element-wise product using the overloaded % operator yy_temp = yy_temp % abs_y_vec_arma3; GMP_vector.rows(K_a * L_a + (mm - 1) * K_b * L_b + (kk - 1) * L_b, K_a * L_a + (mm - 1) * K_b * L_b + kk * L_b - 1) = yy_temp; } } } int RLS_postdistorter_impl::work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items) { const gr_complex* in1 = (const gr_complex*)input_items[0]; // PA_output (gain phase calibrated) const gr_complex* in2 = (const gr_complex*)input_items[1]; // PA input or Predistorter output const gr_complex* flag = (const gr_complex*)input_items[2]; // Do <+signal processing+> // copy private variables accessed by the asynchronous message handler block for (int item = 0; item < noutput_items; item++) { // get number of samples consumed since the beginning of time by this block // from port 0 const uint64_t nread = this->nitems_read(0); // If flag is not set then no coeff. estimation is performed if(flag[item] == gr_complex(0.0, 0.0)) continue; if (iteration == d_iter_limit) { taps = conv_to<vector<gr_complexd>>::from(w_iMinus1); pmt::pmt_t P_c32vector_taps = pmt::init_c64vector(M, taps); message_port_pub(pmt::mp("taps"), P_c32vector_taps); continue; } pa_input = in2[item]; sreg[49] = in1[item]; // extracting the PA output and arranging into a shift-structured GMP vector gen_GMPvector(ptr_sreg, 49, K_a, L_a + 1, K_b, M_b, L_b + 1, yy_cx_fcolvec); yy_cx_frowvec = yy_cx_fcolvec.st(); for (int ii = 1; ii < sreg_len; ii++) sreg[ii - 1] = sreg[ii]; // A-matrix A_mat.submat(0, 0, 0, 0) = inv_sqrt_gamma_iMinus1; A_mat.submat(0, 1, 0, M_bar * 2) = yy_cx_frowvec * L_bar_iMinus1; A_mat.submat(1, 0, M + M_bar, 0) = g_vec_iMinus1; A_mat.submat(1, 1, M + M_bar, M_bar * 2) = L_bar_iMinus1; // obtain B-matrix by performing Givens and Hyperbolic Givens rotations apply_rotations(A_mat, B_mat); // time-update for 1/sqrt(gamma) inv_sqrt_gamma_iMinus1 = real(B_mat(0, 0)); // imag(B_mat(0, 0)) will be ~= 0.0 // time-update for g-vector g = B_mat(span(1, M + M_bar), 0); extract_g_vecs(g, g_vec_iMinus1, g_vec_i, K_a, L_a, K_b, M_b, L_b, M, M + M_bar); // adjust post-distorted PA output dimensions extract_postdistorted_y(yy_cx_frowvec, y, K_a, L_a, K_b, M_b, L_b, M); // adaptation error error = pa_input - as_scalar(y * w_iMinus1); // update weight-vector w_iMinus1 = w_iMinus1 + (error / inv_sqrt_gamma_iMinus1) * g_vec_i; // prepare L_bar for next iteration L_bar_iMinus1 = gr_complexd(one_over_sqrt_lambda, 0.0) * B_mat(span(1, M + M_bar), span(1, 2 * M_bar)); // send weight-vector to predistorter block in a message taps = conv_to<vector<gr_complexd>>::from(w_iMinus1); pmt::pmt_t P_c32vector_taps = pmt::init_c64vector(M, taps); message_port_pub(pmt::mp("taps"), P_c32vector_taps); iteration++; } // Tell runtime system how many output items we produced. return noutput_items; } } /* namespace dpd */ } /* namespace gr */
17,376
C++
.cc
414
32.705314
99
0.504324
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,955
stream_to_gmp_vector_impl.cc
gnuradio_gr-dpd/lib/stream_to_gmp_vector_impl.cc
/* -*- c++ -*- */ /* * Copyright 2020 Alekh Gupta * * SPDX-License-Identifier: GPL-3.0-or-later */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "stream_to_gmp_vector_impl.h" #include <gnuradio/io_signature.h> #include <math.h> #include <algorithm> #include <armadillo> #define COPY_MEM false // Do not copy vectors into separate memory #define FIX_SIZE true // Keep dimensions of vectors constant using std::vector; using namespace arma; namespace gr { namespace dpd { stream_to_gmp_vector::sptr stream_to_gmp_vector::make(const std::vector<int>& dpd_params) { return gnuradio::get_initial_sptr(new stream_to_gmp_vector_impl(dpd_params)); } /* * The private constructor */ stream_to_gmp_vector_impl::stream_to_gmp_vector_impl(const std::vector<int>& dpd_params) : gr::sync_block( "stream_to_gmp_vector", gr::io_signature::make(1, 1, sizeof(gr_complex)), gr::io_signature::make(1, 1, (dpd_params[0] * dpd_params[1] + dpd_params[2] * dpd_params[3] * dpd_params[4]) * sizeof(gr_complex))), d_dpd_params(dpd_params), K_a(d_dpd_params[0]), L_a(d_dpd_params[1]), K_b(d_dpd_params[2]), M_b(d_dpd_params[3]), L_b(d_dpd_params[4]), M(dpd_params[0] * dpd_params[1] + dpd_params[2] * dpd_params[3] * dpd_params[4]) { set_history(std::max(L_a, M_b + L_b)); } /* * Our virtual destructor. */ stream_to_gmp_vector_impl::~stream_to_gmp_vector_impl() {} void stream_to_gmp_vector_impl::gen_GMPvector(const gr_complex* const in, int item, int K_a, int L_a, int K_b, int M_b, int L_b, cx_fcolvec& GMP_vector) { /* Signal-and-Aligned Envelope */ // stacking L_a elements in reverse order cx_fcolvec y_vec_arma1(L_a, fill::zeros); for (int ii = L_a - 1; ii >= 0; ii--) { y_vec_arma1(ii) = in[item - ii]; } GMP_vector.rows(0, L_a - 1) = y_vec_arma1; // store abs() of y_vec_arma1 cx_fcolvec abs_y_vec_arma1(size(y_vec_arma1), fill::zeros); abs_y_vec_arma1.set_real(abs(y_vec_arma1)); cx_fcolvec yy_temp; yy_temp = y_vec_arma1 % abs_y_vec_arma1; if (K_a > 1) GMP_vector.rows(L_a, 2 * L_a - 1) = yy_temp; for (int kk = 2; kk < K_a; kk++) { // perform element-wise product using the overloaded % operator yy_temp = yy_temp % abs_y_vec_arma1; GMP_vector.rows(kk * L_a, (kk + 1) * L_a - 1) = yy_temp; } /* Signal-and-Delayed Envelope */ // stacking L_b+M_b elements in reverse order cx_fcolvec y_vec_arma23(L_b + M_b, fill::zeros); for (int ii = L_b + M_b - 1; ii >= 0; ii--) y_vec_arma23(ii) = in[item - ii]; // L_b signal elements cx_fcolvec y_vec_arma2 = y_vec_arma23.rows(0, L_b - 1); // store abs() of y_vec_arma23 cx_fcolvec abs_y_vec_arma23(size(y_vec_arma23), fill::zeros); abs_y_vec_arma23.set_real(abs(y_vec_arma23)); for (int mm = 1; mm < M_b + 1; mm++) { // stacking L_b delayed signal-envelope elements cx_fcolvec abs_y_vec_arma3 = abs_y_vec_arma23.rows(mm, L_b + mm - 1); cx_fcolvec yy_temp; yy_temp = y_vec_arma2 % abs_y_vec_arma3; GMP_vector.rows(K_a * L_a + (mm - 1) * K_b * L_b, K_a * L_a + (mm - 1) * K_b * L_b + L_b - 1) = yy_temp; for (int kk = 2; kk < K_b + 1; kk++) { // perform element-wise product using the overloaded % operator yy_temp = yy_temp % abs_y_vec_arma3; GMP_vector.rows(K_a * L_a + (mm - 1) * K_b * L_b + (kk - 1) * L_b, K_a * L_a + (mm - 1) * K_b * L_b + kk * L_b - 1) = yy_temp; } } } int stream_to_gmp_vector_impl::work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items) { // const <+ITYPE+> *in = (const <+ITYPE+> *) input_items[0]; // <+OTYPE+> *out = (<+OTYPE+> *) output_items[0]; // Do <+signal processing+> for (int item = history() - 1; item < noutput_items + history() - 1; item++) { cx_fcolvec GMP_vector(((gr_complex*)output_items[0]) + (item - history() + 1) * (M), M, COPY_MEM, FIX_SIZE); gen_GMPvector( (const gr_complex*)input_items[0], item, K_a, L_a, K_b, M_b, L_b, GMP_vector); } // Tell runtime system how many output items we produced. return noutput_items; } } /* namespace dpd */ } /* namespace gr */
5,010
C++
.cc
124
30.395161
90
0.516036
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,956
MP_model_PA_impl.cc
gnuradio_gr-dpd/lib/MP_model_PA_impl.cc
/* -*- c++ -*- */ /* * Copyright 2020 Alekh Gupta * * SPDX-License-Identifier: GPL-3.0-or-later */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "MP_model_PA_impl.h" #include <gnuradio/io_signature.h> #include <math.h> #include <algorithm> #include <armadillo> using std::vector; using namespace arma; // Legacy Coefficents Default Values: // // cx_fmat coeff = { // { { 0.9295, -0.0001 }, // { 0.2939, 0.0005 }, // { -0.1270, 0.0034 }, // { 0.0741, 0.0018 } }, // 1st order coeffs // { { 0.9295, -0.0001 }, { 0.2939, 0.0005 }, { -0.1270, 0.0034 }, { 0.0741, 0.0018 } // }, { { 0.1419, -0.0008 }, // { -0.0735, 0.0833 }, // { -0.0535, 0.0004 }, // { 0.0908, -0.0473 } }, // 3rd order coeffs // { { 0.1419, -0.0008 }, // { -0.0735, 0.0833 }, // { -0.0535, 0.0004 }, // { 0.0908, -0.0473 } }, // { { 0.0084, -0.0569 }, // { -0.4610, 0.0274 }, // { -0.3011, -0.1403 }, // { -0.0623, -0.0269 } }, // 5th order coeffs // { { 0.0084, -0.0569 }, // { -0.4610, 0.0274 }, // { -0.3011, -0.1403 }, // { -0.0623, -0.0269 } }, // { { 0.1774, 0.0265 }, { 0.0848, 0.0613 }, { -0.0362, -0.0307 }, { 0.0415, 0.0429 } // } // }; // 7th order coeffs namespace gr { namespace dpd { MP_model_PA::sptr MP_model_PA::make(int Order, int Mem_Depth, std::string Mode, const std::vector<gr_complex>& Coeff) { return gnuradio::get_initial_sptr( new MP_model_PA_impl(Order, Mem_Depth, Mode, Coeff)); } /* * The private constructor */ MP_model_PA_impl::MP_model_PA_impl(int Order, int Mem_Depth, std::string Mode, const std::vector<gr_complex>& Coeff) : gr::sync_block("MP_model_PA", gr::io_signature::make(1, 1, sizeof(gr_complex)), gr::io_signature::make(1, 1, sizeof(gr_complex))), K_a(Order), // Max. Order limited to 7 L_a(Mem_Depth), // Max no. of taps or memory depth limited to 4 Mode_val(Mode) // Mode of operation, i.e., Even, Odd or Both { set_history(L_a); coeff = cx_fmat(K_a, L_a, fill::zeros); initialise_Coefficients(Coeff); } /* * Our virtual destructor. */ MP_model_PA_impl::~MP_model_PA_impl() {} void MP_model_PA_impl::initialise_Coefficients(const std::vector<gr_complex>& Coeff) { int inx = 0; // Initialise coefficients of signal-and-aligned envelope for (int i = 0; i < K_a; i++) { for (int j = 0; j < L_a; j++) { coeff(i, j) = Coeff[inx]; inx++; } } } void MP_model_PA_impl::gen_MP_vector( const gr_complex* in, int item, int K_a, int L_a, cx_fcolvec& MP_vector) { /* Signal-and-Aligned Envelope */ // stacking L_a elements in reverse order cx_fcolvec y_vec_arma1(L_a, fill::zeros); for (int ii = L_a - 1; ii >= 0; ii--) { y_vec_arma1(ii) = in[item - ii]; } MP_vector.rows(0, L_a - 1) = y_vec_arma1; // store abs() of y_vec_arma1 cx_fcolvec abs_y_vec_arma1(size(y_vec_arma1), fill::zeros); abs_y_vec_arma1.set_real(abs(y_vec_arma1)); cx_fcolvec yy_temp; yy_temp = y_vec_arma1 % abs_y_vec_arma1; if (K_a > 1) MP_vector.rows(L_a, 2 * L_a - 1) = yy_temp; for (int kk = 2; kk < K_a; kk++) { // perform element-wise product using the overloaded % operator yy_temp = yy_temp % abs_y_vec_arma1; MP_vector.rows(kk * L_a, (kk + 1) * L_a - 1) = yy_temp; } } int MP_model_PA_impl::work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items) { const gr_complex* in = (const gr_complex*)input_items[0]; gr_complex* out = (gr_complex*)output_items[0]; // Do <+signal processing+> for (int item = history() - 1; item < noutput_items + history() - 1; item++) { out[item - history() + 1] = { 0, 0 }; // Converting stream to MP vector cx_fcolvec MP_vector(K_a * L_a); gen_MP_vector((const gr_complex*)in, item, K_a, L_a, MP_vector); for (int K = 0; K < K_a; K++) { int L_st = (K * L_a); int L_en = ((K + 1) * L_a); // Include terms in output according to Mode of Operation value if ((K % 2) == 0 && Mode_val == "Even") continue; else if ((K % 2) && Mode_val == "Odd") continue; for (int L = L_st; L < L_en; L++) { gr_complex a = MP_vector(L); gr_complex b = coeff(K, (L - L_st)); out[item - history() + 1] += (a * b); } } } // Tell runtime system how many output items we produced. return noutput_items; } } // namespace dpd } // namespace gr /* namespace gr */
4,996
C++
.cc
142
28.697183
89
0.514682
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,957
predistorter_training_impl.cc
gnuradio_gr-dpd/lib/predistorter_training_impl.cc
/* -*- c++ -*- */ /* * Copyright 2020 Alekh Gupta * * SPDX-License-Identifier: GPL-3.0-or-later */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "predistorter_training_impl.h" #include <gnuradio/io_signature.h> #include <armadillo> #include <ctime> #include <string> #define COPY_MEM false // Do not copy vectors into separate memory #define FIX_SIZE true // Keep dimensions of vectors constant using std::vector; using namespace arma; namespace gr { namespace dpd { predistorter_training::sptr predistorter_training::make(const std::vector<int>& dpd_params, std::string mode, const std::vector<gr_complex>& taps) { return gnuradio::get_initial_sptr( new predistorter_training_impl(dpd_params, mode, taps)); } /* * The private constructor */ predistorter_training_impl::predistorter_training_impl( const std::vector<int>& dpd_params, std::string mode, const std::vector<gr_complex>& taps) : gr::sync_block("predistorter_training", gr::io_signature::make(1, 1, sizeof(gr_complex)), gr::io_signature::make(1, 2, sizeof(gr_complex))), K_a(dpd_params[0]), L_a(dpd_params[1]), K_b(dpd_params[2]), M_b(dpd_params[3]), L_b(dpd_params[4]), d_M(dpd_params[0] * dpd_params[1] + dpd_params[2] * dpd_params[3] * dpd_params[4]), d_mode(mode) { d_update_predistorter_training = true; d_predistorter_training_colvec.set_size(d_M); d_predistorter_training_colvec.zeros(); d_predistorter_training_colvec(0) = gr_complex(1.0, 0.0); set_history(std::max(L_a, M_b + L_b)); // setup output message port for // sending predistorted PA input to the postdistorter // message_port_register_out(pmt::mp("PA_input")); if (mode == "static") for (int i = 0; i < taps.size(); i++) { d_predistorter_training_colvec(i) = taps[i]; } // setup input message port message_port_register_in(pmt::mp("taps")); set_msg_handler(pmt::mp("taps"), boost::bind(&predistorter_training_impl::get_taps, this, _1)); } /* * Our virtual destructor. */ predistorter_training_impl::~predistorter_training_impl() {} void predistorter_training_impl::get_taps(pmt::pmt_t P) { d_update_predistorter_training = true; // extract predistorter_training weight vector from the message for (int i = 0; i < pmt::length(P); i++) d_predistorter_training_colvec(i) = pmt::c64vector_ref(P, i); } void predistorter_training_impl::gen_GMPvector(const gr_complex* const in, int item, int K_a, int L_a, int K_b, int M_b, int L_b, cx_fcolvec& GMP_vector) { /* Signal-and-Aligned Envelope */ // stacking L_a elements in reverse order cx_fcolvec y_vec_arma1(L_a, fill::zeros); for (int ii = L_a - 1; ii >= 0; ii--) { y_vec_arma1(ii) = in[item - ii]; } GMP_vector.rows(0, L_a - 1) = y_vec_arma1; // store abs() of y_vec_arma1 cx_fcolvec abs_y_vec_arma1(size(y_vec_arma1), fill::zeros); abs_y_vec_arma1.set_real(abs(y_vec_arma1)); cx_fcolvec yy_temp; yy_temp = y_vec_arma1 % abs_y_vec_arma1; if (K_a > 1) GMP_vector.rows(L_a, 2 * L_a - 1) = yy_temp; for (int kk = 2; kk < K_a; kk++) { // perform element-wise product using the overloaded % operator yy_temp = yy_temp % abs_y_vec_arma1; GMP_vector.rows(kk * L_a, (kk + 1) * L_a - 1) = yy_temp; } if(K_b == 0) return; /* Signal-and-Delayed Envelope */ // stacking L_b+M_b elements in reverse order cx_fcolvec y_vec_arma23(L_b + M_b, fill::zeros); for (int ii = L_b + M_b - 1; ii >= 0; ii--) y_vec_arma23(ii) = in[item - ii]; // L_b signal elements cx_fcolvec y_vec_arma2 = y_vec_arma23.rows(0, L_b - 1); // store abs() of y_vec_arma23 cx_fcolvec abs_y_vec_arma23(size(y_vec_arma23), fill::zeros); abs_y_vec_arma23.set_real(abs(y_vec_arma23)); for (int mm = 1; mm < M_b + 1; mm++) { // stacking L_b delayed signal-envelope elements cx_fcolvec abs_y_vec_arma3 = abs_y_vec_arma23.rows(mm, L_b + mm - 1); cx_fcolvec yy_temp; yy_temp = y_vec_arma2 % abs_y_vec_arma3; GMP_vector.rows(K_a * L_a + (mm - 1) * K_b * L_b, K_a * L_a + (mm - 1) * K_b * L_b + L_b - 1) = yy_temp; for (int kk = 2; kk < K_b + 1; kk++) { // perform element-wise product using the overloaded % operator yy_temp = yy_temp % abs_y_vec_arma3; GMP_vector.rows(K_a * L_a + (mm - 1) * K_b * L_b + (kk - 1) * L_b, K_a * L_a + (mm - 1) * K_b * L_b + kk * L_b - 1) = yy_temp; } } } int predistorter_training_impl::work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items) { gr_complex* out = (gr_complex*)output_items[0]; gr_complex* flag = (gr_complex*)output_items[1]; predistorter_training_colvec = d_predistorter_training_colvec; // Do <+signal processing+> for (int item = history() - 1; item < noutput_items + history() - 1; item++) { update_predistorter_training = d_update_predistorter_training; // get PA input which has been arranged in a GMP vector format // for predistortion cx_fcolvec GMP_vector(d_M); gen_GMPvector( (const gr_complex*)input_items[0], item, K_a, L_a, K_b, M_b, L_b, GMP_vector); cx_fmat yy_cx_rowvec = GMP_vector.st(); // apply predistortion and send the PA input to postdistorter out[item - history() + 1] = as_scalar( conv_to<cx_fmat>::from(yy_cx_rowvec * predistorter_training_colvec)); // Flag output only if mode of operation is 'static' if(d_mode == "static") { continue; } // Setting flag output according to whether 'taps' are recieved // or not if(update_predistorter_training || item == history() - 1) { flag[item - history() + 1] = gr_complex(1.0, 0.0); } else flag[item - history() + 1] = gr_complex(0.0, 0.0); d_update_predistorter_training = false; } // Tell runtime system how many output items we produced. return noutput_items; } } /* namespace dpd */ } /* namespace gr */
6,787
C++
.cc
168
31.755952
90
0.566216
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,958
GMP_model_PA_impl.cc
gnuradio_gr-dpd/lib/GMP_model_PA_impl.cc
/* -*- c++ -*- */ /* * Copyright 2020 Alekh Gupta * * SPDX-License-Identifier: GPL-3.0-or-later */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "GMP_model_PA_impl.h" #include <gnuradio/io_signature.h> #include <math.h> #include <algorithm> #include <armadillo> using std::vector; using namespace arma; // Legacy Coefficients Default Values: // // cx_fmat coeff1 = { // { { 0.9295, -0.0001 }, // { 0.2939, 0.0005 }, // { -0.1270, 0.0034 }, // { 0.0741, 0.0018 } }, // 1st order coeffs // { { 0.8295, -0.0001 }, { 0.1939, 0.0005 }, { -0.0270, 0.0014 }, { 0.0341, 0.0008 } // }, { { 0.1419, -0.0008 }, // { -0.0735, 0.0833 }, // { -0.0535, 0.0004 }, // { 0.0908, -0.0473 } }, // 3rd order coeffs // { { 0.0719, -0.0004 }, // { -0.0735, 0.0333 }, // { -0.0535, 0.0002 }, // { 0.0908, -0.0273 } }, // { { 0.0084, -0.0569 }, // { -0.4610, 0.0274 }, // { -0.3011, -0.1403 }, // { -0.0623, -0.0269 } }, // 5th order coeffs // { { 0.0044, -0.0369 }, // { -0.2610, 0.0174 }, // { -0.1511, -0.0703 }, // { -0.0323, -0.0169 } }, // { { 0.1774, 0.0265 }, { 0.0848, 0.0613 }, { -0.0362, -0.0307 }, { 0.0415, 0.0429 } // } // }; // 7th order coeffs // cx_fmat coef = { { { 0.2000, 0.0500 }, { 0.1000, -0.0050 }, { 0.0100, 0.0010 } }, // { { 0.2000, -0.0500 }, { 0.1000, 0.0050 }, { 0.0100, -0.0010 } }, // { { 0.2000, 0.0500 }, { 0.1000, -0.0050 }, { 0.0100, 0.0010 } } }; // cx_fcube coeff2(3, 3, 3); namespace gr { namespace dpd { GMP_model_PA::sptr GMP_model_PA::make(int model_param1, int model_param2, int model_param3, int model_param4, int model_param5, std::string mode, const std::vector<gr_complex>& coeff1, const std::vector<gr_complex>& coeff2) { return gnuradio::get_initial_sptr(new GMP_model_PA_impl(model_param1, model_param2, model_param3, model_param4, model_param5, mode, coeff1, coeff2)); } /* * The private constructor */ GMP_model_PA_impl::GMP_model_PA_impl(int model_param1, int model_param2, int model_param3, int model_param4, int model_param5, std::string mode, const std::vector<gr_complex>& coeff1, const std::vector<gr_complex>& coeff2) : gr::sync_block("GMP_model_PA", gr::io_signature::make(1, 1, sizeof(gr_complex)), gr::io_signature::make(1, 1, sizeof(gr_complex))), K_a(model_param1), L_a(model_param2), K_b(model_param3), M_b(model_param4), L_b(model_param5), M(model_param1 * model_param2 + model_param3 * model_param4 * model_param5), Mode_vl(mode) { set_history(std::max(L_a, M_b + L_b)); coeff_1 = cx_fmat(K_a, L_a, fill::zeros); coeff_2 = cx_fcube(K_b, M_b, L_b, fill::zeros); initialise_Coefficients(coeff1, coeff2); } /* * Our virtual destructor. */ GMP_model_PA_impl::~GMP_model_PA_impl() {} void GMP_model_PA_impl::initialise_Coefficients(const std::vector<gr_complex>& coeff1, const std::vector<gr_complex>& coeff2) { int inx = 0; // Initialise coefficients of signal-and-aligned envelope for (int i = 0; i < K_a; i++) { for (int j = 0; j < L_a; j++) { coeff_1(i, j) = coeff1[inx]; inx++; } } inx = 0; // Initialise coefficients of signal-and-lagging envelope for (int i = 0; i < K_b; i++) { for (int j = 0; j < M_b; j++) { for (int k = 0; k < L_b; k++) { coeff_2(i, j, k) = coeff2[inx]; } } } } void GMP_model_PA_impl::gen_GMP_vector(const gr_complex* const in, int item, int K_a, int L_a, int K_b, int M_b, int L_b, cx_fcolvec& GMP_vector) { /* Signal-and-Aligned Envelope */ // stacking L_a elements in reverse order cx_fcolvec y_vec_arma1(L_a, fill::zeros); for (int ii = L_a - 1; ii >= 0; ii--) { y_vec_arma1(ii) = in[item - ii]; } GMP_vector.rows(0, L_a - 1) = y_vec_arma1; // store abs() of y_vec_arma1 cx_fcolvec abs_y_vec_arma1(size(y_vec_arma1), fill::zeros); abs_y_vec_arma1.set_real(abs(y_vec_arma1)); cx_fcolvec yy_temp; yy_temp = y_vec_arma1 % abs_y_vec_arma1; if (K_a > 1) GMP_vector.rows(L_a, 2 * L_a - 1) = yy_temp; for (int kk = 2; kk < K_a; kk++) { // perform element-wise product using the overloaded % operator yy_temp = yy_temp % abs_y_vec_arma1; GMP_vector.rows(kk * L_a, (kk + 1) * L_a - 1) = yy_temp; } if(K_b == 0) return; /* Signal-and-Delayed Envelope */ // stacking L_b+M_b elements in reverse order cx_fcolvec y_vec_arma23(L_b + M_b, fill::zeros); for (int ii = L_b + M_b - 1; ii >= 0; ii--) y_vec_arma23(ii) = in[item - ii]; // L_b signal elements cx_fcolvec y_vec_arma2 = y_vec_arma23.rows(0, L_b - 1); // store abs() of y_vec_arma23 cx_fcolvec abs_y_vec_arma23(size(y_vec_arma23), fill::zeros); abs_y_vec_arma23.set_real(abs(y_vec_arma23)); for (int mm = 1; mm < M_b + 1; mm++) { // stacking L_b delayed signal-envelope elements cx_fcolvec abs_y_vec_arma3 = abs_y_vec_arma23.rows(mm, L_b + mm - 1); cx_fcolvec yy_temp; yy_temp = y_vec_arma2 % abs_y_vec_arma3; GMP_vector.rows(K_a * L_a + (mm - 1) * K_b * L_b, K_a * L_a + (mm - 1) * K_b * L_b + L_b - 1) = yy_temp; for (int kk = 2; kk < K_b + 1; kk++) { // perform element-wise product using the overloaded % operator yy_temp = yy_temp % abs_y_vec_arma3; GMP_vector.rows(K_a * L_a + (mm - 1) * K_b * L_b + (kk - 1) * L_b, K_a * L_a + (mm - 1) * K_b * L_b + kk * L_b - 1) = yy_temp; } } } int GMP_model_PA_impl::work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items) { const gr_complex* in = (const gr_complex*)input_items[0]; gr_complex* out = (gr_complex*)output_items[0]; // Do <+signal processing+> for (int item = history() - 1; item < noutput_items + history() - 1; item++) { out[item - history() + 1] = { 0, 0 }; // Converting stream to MP vector cx_fcolvec GMP_vector(K_a * L_a + K_b * L_b * M_b); gen_GMP_vector((const gr_complex*)in, item, K_a, L_a, K_b, M_b, L_b, GMP_vector); for (int K = 0; K < K_a; K++) { int L_st = (K * L_a); int L_en = ((K + 1) * L_a); // Include terms in output according to Mode of Operation value if ((K % 2) == 0 && Mode_vl == "Even") continue; else if ((K % 2) && Mode_vl == "Odd") continue; for (int L = L_st; L < L_en; L++) { gr_complex a = GMP_vector(L); gr_complex b = coeff_1(K, (L - L_st)); out[item - history() + 1] += (a * b); // std::cout << a << " " << << "\n"; } } for (int m = 0; m < M_b; m++) { for (int k = 0; k < K_b; k++) { // Include terms in output according to Mode of Operation value if ((k % 2) == 0 && Mode_vl == "Odd") continue; else if ((k % 2) && Mode_vl == "Even") continue; int L_st = (m * L_b * K_b) + (K_a * L_a) + k * L_b; int L_en = (m * L_b * K_b) + (K_a * L_a) + (k + 1) * L_b; for (int l = L_st; l < L_en; l++) { gr_complex a = GMP_vector(l); gr_complex b = coeff_2(k, m, l - L_st); out[item - history() + 1] += (a * b); } } } } // Tell runtime system how many output items we produced. return noutput_items; } } /* namespace dpd */ } /* namespace gr */
9,159
C++
.cc
223
29.278027
89
0.440651
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,959
LMS_postdistorter_impl.cc
gnuradio_gr-dpd/lib/LMS_postdistorter_impl.cc
/* -*- c++ -*- */ /* * Copyright 2020 gr-dpd author. * * This 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, or (at your option) * any later version. * * This software 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 software; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #define ARMA_DONT_PRINT_ERRORS #include "LMS_postdistorter_impl.h" #include <gnuradio/io_signature.h> #include <armadillo> #include <string> #define COPY_MEM false // Do not copy matrices into separate memory #define FIX_SIZE true // Keep dimensions of matrices constant using namespace std; using std::string; using namespace arma; namespace gr { namespace dpd { LMS_postdistorter::sptr LMS_postdistorter::make(const std::vector<int>& dpd_params, int iter_limit, std::string method, gr_complexd learning_rate) { return gnuradio::get_initial_sptr( new LMS_postdistorter_impl(dpd_params, iter_limit, method, learning_rate)); } /* * The private constructor */ LMS_postdistorter_impl::LMS_postdistorter_impl(const std::vector<int>& dpd_params, int iter_limit, std::string method, gr_complexd learning_rate) : gr::sync_block("LMS_postdistorter", gr::io_signature::make(3, 3, sizeof(gr_complex)), gr::io_signature::make(0, 0, 0)), d_dpd_params(dpd_params), K_a(d_dpd_params[0]), L_a(d_dpd_params[1]), K_b(d_dpd_params[2]), M_b(d_dpd_params[3]), L_b(d_dpd_params[4]), M(dpd_params[0] * dpd_params[1] + dpd_params[2] * dpd_params[3] * dpd_params[4]), d_iter_limit(iter_limit), str(method), learning_rate(learning_rate) { // set_history(std::max(L_a, L_b + M_b)); iteration = 1; for (int ii = 0; ii < sreg_len; ii++) sreg[ii] = 0.0; // setup output message port message_port_register_out(pmt::mp("taps")); // lambda = 1 - pow(2, 1 - k); // taps or weight-vector w_iMinus1.set_size(M, 1); w_iMinus1 = zeros<cx_mat>(M, 1); w_iMinus1(0, 0) = gr_complex(1.0, 0.0); } /* * Our virtual destructor. */ LMS_postdistorter_impl::~LMS_postdistorter_impl() {} cx_mat LMS_postdistorter_impl::ls_estimation(cx_mat A, gr_complexd y) { cx_mat lambda(size(A * (A.t()))); lambda.fill(0.001); // lambda(0, 0) = 0.001; cx_mat yy(1, 1); yy(0, 0) = y; cx_mat den = A * yy; cx_mat num = A * (A.t()); num = num + lambda * eye<cx_mat>(size(A * (A.t()))); cx_mat ls_result = solve((A * (A.t()) + lambda * eye<cx_mat>(size(A * (A.t())))), A * yy); // cx_mat ls_result(size(w_iMinus1), fill::zeros); return ls_result; } void LMS_postdistorter_impl::gen_GMPvector(const gr_complexd* const in, int item, int K_a, int L_a, int K_b, int M_b, int L_b, cx_colvec& GMP_vector) { /* Signal-and-Aligned Envelope */ // stacking L_a elements in reverse order cx_colvec y_vec_arma1(L_a, fill::zeros); for (int ii = L_a - 1; ii >= 0; ii--) y_vec_arma1(ii) = in[item - ii]; GMP_vector.rows(0, L_a - 1) = y_vec_arma1; // store abs() of y_vec_arma1 cx_colvec abs_y_vec_arma1(size(y_vec_arma1), fill::zeros); abs_y_vec_arma1.set_real(abs(y_vec_arma1)); cx_colvec yy_temp; yy_temp = y_vec_arma1 % abs_y_vec_arma1; if (K_a > 1) GMP_vector.rows(L_a, 2 * L_a - 1) = yy_temp; for (int kk = 2; kk < K_a; kk++) { // perform element-wise product using the overloaded % operator yy_temp = yy_temp % abs_y_vec_arma1; GMP_vector.rows(kk * L_a, (kk + 1) * L_a - 1) = yy_temp; } /* Signal-and-Delayed Envelope */ // stacking L_b+M_b elements in reverse order cx_colvec y_vec_arma23(L_b + M_b, fill::zeros); for (int ii = L_b + M_b - 1; ii >= 0; ii--) y_vec_arma23(ii) = in[item - ii]; // L_b signal elements cx_colvec y_vec_arma2 = y_vec_arma23.rows(0, L_b - 1); // store abs() of y_vec_arma23 cx_colvec abs_y_vec_arma23(size(y_vec_arma23), fill::zeros); abs_y_vec_arma23.set_real(abs(y_vec_arma23)); for (int mm = 1; mm < M_b + 1; mm++) { // stacking L_b delayed signal-envelope elements cx_colvec abs_y_vec_arma3 = abs_y_vec_arma23.rows(mm, L_b + mm - 1); cx_colvec yy_temp; yy_temp = y_vec_arma2 % abs_y_vec_arma3; GMP_vector.rows(K_a * L_a + (mm - 1) * K_b * L_b, K_a * L_a + (mm - 1) * K_b * L_b + L_b - 1) = yy_temp; for (int kk = 2; kk < K_b + 1; kk++) { // perform element-wise product using the overloaded % operator yy_temp = yy_temp % abs_y_vec_arma3; GMP_vector.rows(K_a * L_a + (mm - 1) * K_b * L_b + (kk - 1) * L_b, K_a * L_a + (mm - 1) * K_b * L_b + kk * L_b - 1) = yy_temp; } } } int LMS_postdistorter_impl::work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items) { const gr_complex* in1 = (const gr_complex*)input_items[0]; // PA_output (gain phase calibrated) const gr_complex* in2 = (const gr_complex*)input_items[1]; // PA input or Predistorter output const gr_complex* flag = (const gr_complex*)input_items[2]; // Do <+signal processing+> for (int item = 0; item < noutput_items; item++) { // get number of samples consumed since the beginning of time by this block // from port 0 const uint64_t nread = this->nitems_read(0); // If flag is not set then no coeff. estimation is performed if(flag[item] == gr_complex(0.0, 0.0)) continue; if (iteration == d_iter_limit) { taps = conv_to<vector<gr_complexd>>::from(w_iMinus1); pmt::pmt_t P_c32vector_taps = pmt::init_c64vector(M, taps); message_port_pub(pmt::mp("taps"), P_c32vector_taps); continue; } pa_input = in2[item]; sreg[49] = in1[item]; // extracting the PA output and arranging into a shift-structured GMP vector cx_colvec GMP_vector(M); gen_GMPvector(ptr_sreg, 49, K_a, L_a, K_b, M_b, L_b, GMP_vector); cx_mat pa_output = GMP_vector; cx_mat pa_output_t = GMP_vector.t(); for (int ii = 1; ii < sreg_len; ii++) sreg[ii - 1] = sreg[ii]; cx_mat l_rate(1, 1, fill::zeros); l_rate(0, 0) = learning_rate; cx_mat l_rate_1_minus(1, 1, fill::zeros); l_rate_1_minus(0, 0) = gr_complexd(1.0, 0.0) - learning_rate; if (str == "newton") { error = pa_input - as_scalar(pa_output_t * w_iMinus1); cx_mat ls_result = ls_estimation(pa_output, error); w_iMinus1 = w_iMinus1 + (ls_result * l_rate); } if (str == "ema") { cx_mat ls_result = ls_estimation(pa_output, pa_input); w_iMinus1 = (w_iMinus1 * l_rate_1_minus) + (ls_result * l_rate); } // send weight-vector to predistorter block in a message taps = conv_to<vector<gr_complexd>>::from(w_iMinus1); pmt::pmt_t P_c32vector_taps = pmt::init_c64vector(M, taps); message_port_pub(pmt::mp("taps"), P_c32vector_taps); iteration++; } // Tell runtime system how many output items we produced. return noutput_items; } } /* namespace dpd */ } /* namespace gr */
8,448
C++
.cc
200
33.22
99
0.558046
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,960
gain_phase_calibrate_impl.cc
gnuradio_gr-dpd/lib/gain_phase_calibrate_impl.cc
/* -*- c++ -*- */ /* * Copyright 2020 Alekh Gupta * * SPDX-License-Identifier: GPL-3.0-or-later */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gain_phase_calibrate_impl.h" #include <gnuradio/io_signature.h> namespace gr { namespace dpd { gain_phase_calibrate::sptr gain_phase_calibrate::make() { return gnuradio::get_initial_sptr(new gain_phase_calibrate_impl()); } /* * The private constructor */ gain_phase_calibrate_impl::gain_phase_calibrate_impl() : gr::block("gain_phase_calibrate", gr::io_signature::make(3, 3, sizeof(gr_complex)), gr::io_signature::make(1, 1, sizeof(gr_complex))) { previous_cfactor = gr_complex(0.0, 0.0); d_reference_acquired = false; d_sample = gr_complex(0.0, 0.0); } /* * Our virtual destructor. */ gain_phase_calibrate_impl::~gain_phase_calibrate_impl() {} bool gain_phase_calibrate_impl::almost_equals_zero(double a, int num_digits) { // identify the first few significant digits int na = floor(fabs(a) * pow(10.0, num_digits)); if (na == 0) return true; return false; } int gain_phase_calibrate_impl::general_work(int noutput_items, gr_vector_int& ninput_items_, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items) { const gr_complex* in1 = (const gr_complex*)input_items[0]; // PA_output const gr_complex* in2 = (const gr_complex*)input_items[1]; // Input Sample const gr_complex* in3 = (const gr_complex*)input_items[2]; // PA_DPD gr_complex* out = (gr_complex*)output_items[0]; // Do <+signal processing+> ninput_items = std::min(ninput_items_[0], noutput_items); item = 0; gr_complex cfactor_avg_sum = gr_complex(0.0, 0.0); while (item < ninput_items) { sample = in2[item]; current_cfactor = sample / in1[item]; // Inverse of PA gain if (previous_cfactor != gr_complex(0.0, 0.0)) { cfactor_avg_sum = cfactor_avg_sum + current_cfactor; cfactor = cfactor_avg_sum / gr_complex(item + 1.0); } else cfactor = current_cfactor; // cfactor = gr_complex(0.5, 0.0) * (previous_cfactor + current_cfactor); if (!almost_equals_zero(std::real(in1[item]), 5) && !almost_equals_zero(std::imag(in1[item]), 5)) previous_cfactor = cfactor; out[item] = cfactor * in3[item]; item++; } // Tell runtime system how many input items we consumed on // each input stream. consume_each(noutput_items); // Tell runtime system how many output items we produced. return ninput_items; } } /* namespace dpd */ } /* namespace gr */
2,790
C++
.cc
77
29.805195
83
0.616698
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,961
GMP_model_PA_impl.h
gnuradio_gr-dpd/lib/GMP_model_PA_impl.h
/* -*- c++ -*- */ /* * Copyright 2020 Alekh Gupta * * SPDX-License-Identifier: GPL-3.0-or-later */ #ifndef INCLUDED_DPD_GMP_MODEL_PA_IMPL_H #define INCLUDED_DPD_GMP_MODEL_PA_IMPL_H #include <dpd/GMP_model_PA.h> #include <math.h> #include <algorithm> #include <armadillo> using std::vector; using namespace arma; namespace gr { namespace dpd { class GMP_model_PA_impl : public GMP_model_PA { private: int K_a; // Order I int L_a; // Memory Depth I int K_b; // Order II int M_b; // Cross-Terms Index int L_b; // Memory Depth II int M; // No. of Coefficients std::string Mode_vl; // Mode of Operation cx_fmat coeff_1; // Coefficient Vector for signal-and-aligned envelope cx_fcube coeff_2; // Coefficient Vector for signal-and-lagging envelope public: GMP_model_PA_impl(int model_param1, int model_param2, int model_param3, int model_param4, int model_param5, std::string mode, const std::vector<gr_complex>& coeff1, const std::vector<gr_complex>& coeff2); ~GMP_model_PA_impl(); // Where all the action really happens int work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items); // Copies Coefficient vectors into local variable vectors void initialise_Coefficients(const std::vector<gr_complex>& coeff1, const std::vector<gr_complex>& coeff2); // Generates of shift-structured GMP vector void gen_GMP_vector(const gr_complex* const in, int item, int K_a, int L_a, int K_b, int M_b, int L_b, cx_fcolvec& GMP_vector); }; } // namespace dpd } // namespace gr #endif /* INCLUDED_DPD_GMP_MODEL_PA_IMPL_H */
2,085
C++
.h
58
27
78
0.553244
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,962
stream_to_gmp_vector_impl.h
gnuradio_gr-dpd/lib/stream_to_gmp_vector_impl.h
/* -*- c++ -*- */ /* * Copyright 2020 Alekh Gupta * * SPDX-License-Identifier: GPL-3.0-or-later */ #ifndef INCLUDED_DPD_STREAM_TO_GMP_VECTOR_IMPL_H #define INCLUDED_DPD_STREAM_TO_GMP_VECTOR_IMPL_H #include <dpd/stream_to_gmp_vector.h> #include <armadillo> using namespace arma; namespace gr { namespace dpd { class stream_to_gmp_vector_impl : public stream_to_gmp_vector { private: std::vector<int> d_dpd_params; // consts to be assigned values in the constructor initialization list const int K_a; const int L_a; const int K_b; const int M_b; const int L_b; const int M; public: stream_to_gmp_vector_impl(const std::vector<int>& dpd_params); ~stream_to_gmp_vector_impl(); // Genrates shift-structured GMP vector based on the parameters void gen_GMPvector(const gr_complex* const in, int item, int K_a, int L_a, int K_b, int M_b, int L_b, cx_fcolvec& GMP_vector); // Where all the action really happens int work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items); }; } // namespace dpd } // namespace gr #endif /* INCLUDED_DPD_STREAM_TO_GMP_VECTOR_IMPL_H */
1,358
C++
.h
44
24.022727
74
0.61273
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,963
LMS_postdistorter_impl.h
gnuradio_gr-dpd/lib/LMS_postdistorter_impl.h
/* -*- c++ -*- */ /* * Copyright 2020 gr-dpd author. * * This 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, or (at your option) * any later version. * * This software 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 software; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DPD_LMS_POSTDISTORTER_IMPL_H #define INCLUDED_DPD_LMS_POSTDISTORTER_IMPL_H #include <dpd/LMS_postdistorter.h> #include <armadillo> using namespace arma; namespace gr { namespace dpd { class LMS_postdistorter_impl : public LMS_postdistorter { private: std::vector<int> d_dpd_params; int K_a, K_b, L_a, L_b, M_b; int M; int d_iter_limit; std::string str; int iteration; cx_mat w_iMinus1; const int sreg_len = 50; gr_complexd sreg[50]; const gr_complexd* ptr_sreg = sreg; gr_complexd pa_input, error, learning_rate; std::vector<gr_complexd> taps; public: LMS_postdistorter_impl(const std::vector<int>& dpd_params, int iter_limit, std::string method, gr_complexd learning_rate); ~LMS_postdistorter_impl(); // Least Squares Estimation utility cx_mat ls_estimation(cx_mat A, gr_complexd y); // Genrates shift-structured GMP vector void gen_GMPvector(const gr_complexd* const in, int item, int K_a, int L_a, int K_b, int M_b, int L_b, cx_colvec& GMP_vector); // Where all the action really happens int work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items); }; } // namespace dpd } // namespace gr #endif /* INCLUDED_DPD_LMS_POSTDISTORTER_IMPL_H */
2,332
C++
.h
66
28.651515
71
0.64273
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,964
MP_model_PA_impl.h
gnuradio_gr-dpd/lib/MP_model_PA_impl.h
/* -*- c++ -*- */ /* * Copyright 2020 Alekh Gupta * * SPDX-License-Identifier: GPL-3.0-or-later */ #ifndef INCLUDED_DPD_MP_MODEL_PA_IMPL_H #define INCLUDED_DPD_MP_MODEL_PA_IMPL_H #include <dpd/MP_model_PA.h> #include <math.h> #include <algorithm> #include <armadillo> using std::vector; using namespace arma; namespace gr { namespace dpd { class MP_model_PA_impl : public MP_model_PA { private: // No. of channels or order of PA model int K_a; // No. of taps or memory-depth int L_a; std::string Mode_val; cx_fmat coeff; public: MP_model_PA_impl(int Order, int Mem_Depth, std::string Mode, const std::vector<gr_complex>& Coeff); ~MP_model_PA_impl(); // Where all the action or processing really happens int work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items); // Copies the GRC block coefficients parameters into class variable coeff void initialise_Coefficients(const std::vector<gr_complex>& Coeff); // Generates a shift-structured MP model based vector void gen_MP_vector( const gr_complex* in, int item, int K_a, int L_a, cx_fcolvec& MP_vector); }; } // namespace dpd } // namespace gr #endif /* INCLUDED_DPD_MP_MODEL_PA_IMPL_H */
1,347
C++
.h
44
25.863636
81
0.659459
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,965
predistorter_training_impl.h
gnuradio_gr-dpd/lib/predistorter_training_impl.h
/* -*- c++ -*- */ /* * Copyright 2020 Alekh Gupta * * SPDX-License-Identifier: GPL-3.0-or-later */ #ifndef INCLUDED_DPD_PREDISTORTER_TRAINING_IMPL_H #define INCLUDED_DPD_PREDISTORTER_TRAINING_IMPL_H #include <dpd/predistorter_training.h> #include <armadillo> namespace gr { namespace dpd { class predistorter_training_impl : public predistorter_training { private: // Nothing to declare in this block. const int K_a; const int L_a; const int K_b; const int M_b; const int L_b; const int d_M; std::string d_mode; bool d_update_predistorter_training, update_predistorter_training; arma::cx_colvec d_predistorter_training_colvec, predistorter_training_colvec; public: predistorter_training_impl(const std::vector<int>& dpd_params, std::string mode, const std::vector<gr_complex>& taps); ~predistorter_training_impl(); // Copies 'taps' from message PMT to local colvec variable void get_taps(pmt::pmt_t P); // Generates shift-structured GMP vector based on parameters void gen_GMPvector(const gr_complex* const in, int item, int K_a, int L_a, int K_b, int M_b, int L_b, arma::cx_fcolvec& GMP_vector); // Where all the action really happens int work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items); }; } // namespace dpd } // namespace gr #endif /* INCLUDED_DPD_PREDISTORTER_TRAINING_IMPL_H */
1,667
C++
.h
49
26.244898
81
0.617629
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,966
RLS_postdistorter_impl.h
gnuradio_gr-dpd/lib/RLS_postdistorter_impl.h
/* -*- c++ -*- */ /* * Copyright 2020 Alekh Gupta * * SPDX-License-Identifier: GPL-3.0-or-later */ #ifndef INCLUDED_DPD_RLS_POSTDISTORTER_IMPL_H #define INCLUDED_DPD_RLS_POSTDISTORTER_IMPL_H #include <dpd/RLS_postdistorter.h> #include <armadillo> using namespace arma; namespace gr { namespace dpd { class RLS_postdistorter_impl : public RLS_postdistorter { private: // Nothing to declare in this block. std::vector<int> d_dpd_params; gr_complexd d_pa_input, pa_input, error; gr_complexd pa_input_smooth, pa_output_smooth; gr_complexd sr1[10], sr2[10]; bool d_ack_predistorter_updated, ack_predistorter_updated; const int K_a, L_a, K_b, M_b, L_b, M, M_bar; const int sreg_len = 50; gr_complex sreg[50]; const gr_complex* ptr_sreg = sreg; std::vector<gr_complexd> taps; int iteration, d_iter_limit; // Fast-RLS parameter declaration double lambda, one_over_sqrt_lambda, eta, inv_sqrt_gamma_iMinus1; cx_mat g_vec_iMinus1, g_vec_i, L_bar_iMinus1, w_i, w_iMinus1, A_mat, B_mat, g; cx_fcolvec yy_cx_fcolvec; cx_frowvec yy_cx_frowvec; cx_fmat y; public: RLS_postdistorter_impl(const std::vector<int>& dpd_params, int iter_limit); ~RLS_postdistorter_impl(); // Decides closeness to zero or null bool almost_equal(double a, double b, double tol); // Givens rotation utility void givens_rotate(const cx_mat& in, cx_mat& out); // Hyperbolics givens rotation utility void hgivens_rotate(const cx_mat& in, cx_mat& out); // Extract g-vec after hyperbolics and givens rotation void extract_g_vecs(cx_mat& g, cx_mat& g_vec_iMinus1, cx_mat& g_vec_i, int K_a, int L_a, int K_b, int M_b, int L_b, int M, int M_bar); // Extract calibrated PA_output in a shift-structured GMP vector void extract_postdistorted_y( cx_fmat& y_in, cx_fmat& y, int K_a, int L_a, int K_b, int M_b, int L_b, int M); // Use hyperbolics and givens rotation accordingly void apply_rotations(const cx_mat& A, cx_mat& B); // Genrates shift-structured GMP vector void gen_GMPvector(const gr_complex* const in, int item, int K_a, int L_a, int K_b, int M_b, int L_b, cx_fcolvec& GMP_vector); // Where all the action really happens int work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items); }; } // namespace dpd } // namespace gr #endif /* INCLUDED_DPD_RLS_POSTDISTORTER_IMPL_H */
2,843
C++
.h
76
28.934211
87
0.597897
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,967
gain_phase_calibrate_impl.h
gnuradio_gr-dpd/lib/gain_phase_calibrate_impl.h
/* -*- c++ -*- */ /* * Copyright 2020 Alekh Gupta * * SPDX-License-Identifier: GPL-3.0-or-later */ #ifndef INCLUDED_DPD_GAIN_PHASE_CALIBRATE_IMPL_H #define INCLUDED_DPD_GAIN_PHASE_CALIBRATE_IMPL_H #include <dpd/gain_phase_calibrate.h> namespace gr { namespace dpd { class gain_phase_calibrate_impl : public gain_phase_calibrate { private: gr_complex cfactor, previous_cfactor, current_cfactor; int ninput_items, item; bool d_reference_acquired, reference_acquired; gr_complex d_sample, sample; public: gain_phase_calibrate_impl(); ~gain_phase_calibrate_impl(); // Decides closeness to zero or null bool almost_equals_zero(double a, int num_digits); // Where all the action really happens int general_work(int noutput_items, gr_vector_int& ninput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items); }; } // namespace dpd } // namespace gr #endif /* INCLUDED_DPD_GAIN_PHASE_CALIBRATE_IMPL_H */
1,039
C++
.h
32
27.84375
61
0.690381
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,970
RLS_postdistorter.h
gnuradio_gr-dpd/include/dpd/RLS_postdistorter.h
/* -*- c++ -*- */ /* * Copyright 2020 Alekh Gupta * * SPDX-License-Identifier: GPL-3.0-or-later */ #ifndef INCLUDED_DPD_RLS_POSTDISTORTER_H #define INCLUDED_DPD_RLS_POSTDISTORTER_H #include <gnuradio/sync_block.h> #include <dpd/api.h> namespace gr { namespace dpd { /*! * \brief RLS based Algorithm implemented to estimate the coefficients of the * behaviorial model (GMP) of the Power Amplifier and thus predistorter taps. * \ingroup dpd * * \details * It estimates the coefficients based on the PA_output and PA_input. * * It has two input ports, one for the PA_output (gain phase calibrated) and * other for the PA_input (or predistorter output). * * The coefficients estimated are passed as messages through message output * port 'taps'. * Both Input ports are only for Complex Data Type. * * The Fast RLS Algorithm used in coefficient estimations is referenced from the * publication: S. Pagadarai, R. Grover, S. J. Macmullan and A. M. Wyglinski, * "Digital Predistortion of Power Amplifiers for Spectrally Agile Wireless * Transmitters." */ class DPD_API RLS_postdistorter : virtual public gr::sync_block { public: typedef boost::shared_ptr<RLS_postdistorter> sptr; /*! * \brief Make RLS_postdistorter block * * \param dpd_params The (K_a, L_a, K_b, L_b, M_b) int_vector denoting the * GMP model parameters used for predistorter coefficients estimations. * Total No. of coefficients = ((K_a * L_a) + (K_b * M_b * L_b)) * \param iter_limit Iteration limit or Max. number of iterations of training * to be performed for predistorter DPD coefficients estimation. * * */ static sptr make(const std::vector<int>& dpd_params, int iter_limit); }; } // namespace dpd } // namespace gr #endif /* INCLUDED_DPD_RLS_POSTDISTORTER_H */
1,835
C++
.h
52
32.519231
81
0.714527
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,974
MP_model_PA.h
gnuradio_gr-dpd/include/dpd/MP_model_PA.h
/* -*- c++ -*- */ /* * Copyright 2020 Alekh Gupta * * SPDX-License-Identifier: GPL-3.0-or-later * * This 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, or (at your option) * any later version. * * This software 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 software; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DPD_MP_MODEL_PA_H #define INCLUDED_DPD_MP_MODEL_PA_H #include <gnuradio/sync_block.h> #include <dpd/api.h> namespace gr { namespace dpd { /*! * \brief Implementation of Memory Polynomial model based * Power Amplifier. (Complex input, Complex output) * \ingroup dpd * * \details * It produces an output based on the Memory Polynomial (MP) * model formed using the current block parameters for * each input. * * Function to describe relation between Input & Output * of MP based model: * \f[ * y[n] = \sum\limits_{k=1}^{K}(\sum\limits_{m=0}^{M} a_{km} x(n-m) |x(n-m)|^{k-1}) * \f] * * Where x is the input, y is the output, K is the maximum power order, * M is the maximum memory depth and \f$a_{km}\f$ is the coefficients (kernels) * of the system. * */ class DPD_API MP_model_PA : virtual public gr::sync_block { public: // gr::dpd::MP_model_PA typedef boost::shared_ptr<MP_model_PA> sptr; /*! * \brief Make a MP_model_PA block * * \param Order Maximum Power Order (K) or Nonlinearity * Order of Memory Polynomial (MP). * \param Mem_Depth Memory Depth (M) * or Maximum no. of terms of each order in MP. * \param Mode Mode of Operation, i.e., Odd Order Terms Only * or Even Order Terms Only or Both Terms. * \param Coeff A shift-structured coefficient vector * of complex data types of order (K x M) containing the coefficients for the MP * Model. */ static sptr make(int Order, int Mem_Depth, std::string Mode, const std::vector<gr_complex>& Coeff); }; } // namespace dpd } // namespace gr #endif /* INCLUDED_DPD_MP_MODEL_PA_H */
2,547
C++
.h
74
30.918919
86
0.679643
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,975
GMP_model_PA.h
gnuradio_gr-dpd/include/dpd/GMP_model_PA.h
/* -*- c++ -*- */ /* * Copyright 2020 Alekh Gupta * * SPDX-License-Identifier: GPL-3.0-or-later */ #ifndef INCLUDED_DPD_GMP_MODEL_PA_H #define INCLUDED_DPD_GMP_MODEL_PA_H #include <gnuradio/sync_block.h> #include <dpd/api.h> namespace gr { namespace dpd { /*! * \brief Implementation of Generalised Memory Polynomial model * based Power Amplifier. (Complex input, Complex output) * \ingroup dpd * * \details * It produces an output based on the * Generalised Memory Polynomial model formed using the current * block parameters for each input. * * Function to describe relation between Input and Output * of GMP based model: * \f[ * y[n] = \sum\limits_{k=0}^{K_a-1}(\sum\limits_{l=0}^{L_a-1} a_{kl} x(n-l) * |x(n-l)|^{k}) + \\ * \sum\limits_{k=1}^{K_b}(\sum\limits_{m=1}^{M_b}(\sum\limits_{l=0}^{L_b-1} * b_{kml} x(n-l) |x(n-l-m)|^{k})) \f] The representation on the right consists of two * components, namely, the signed-aligned-envelope component and signal-and-lagging * component. The number of coefficients to be estimated are: \f$M = K_a L_a + K_b M_b * L_b\f$ across across \f$K_a + K_b M_b\f$ channels. */ class DPD_API GMP_model_PA : virtual public gr::sync_block { public: typedef boost::shared_ptr<GMP_model_PA> sptr; /*! * \brief Make a GMP_model_PA block * * \param model_param1 Maximum Power Order(K_a) in the * signal-and-aligned-envelope component of the GMP Model. * \param model_param2 Memory Depth(L_a) or * Maximum number of terms of each power order in the * signal-and-aligned-envelope component of the GMP Model. * \param model_param3 Maximum Power Order(K_b) in the * signal-and-lagging-envelope component of the GMP Model. * \param model_param4 Lagging Cross-Terms Index(M_b) or * Maximum number of terms due to Lagging Cross Terms for * each memory depth in the signal-and-lagging-envelope * component of the GMP Model. * \param model_param5 Memory-Depth(L_b) or * Maximum number of terms of each power order in the * signal-and-lagging-envelope component of the GMP Model. * \param mode Mode of Operation, i.e., Odd Order Terms Only * or Even Order Terms Only or Both Terms. * \param coeff1 A shift-structured coefficients vector of * complex data types of order (K_a x L_a) for the * signal-and-aligned-envelope component. * \param coeff2 A shift-structured coefficients vector of * complex data types of order (K_b x L_b x M_b) for the * signal-and-lagging-envelope component. */ static sptr make(int model_param1, int model_param2, int model_param3, int model_param4, int model_param5, std::string mode, const std::vector<gr_complex>& coeff1, const std::vector<gr_complex>& coeff2); }; } // namespace dpd } // namespace gr #endif /* INCLUDED_DPD_GMP_MODEL_PA_H */
3,042
C++
.h
75
35.36
86
0.652703
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,976
predistorter_training.h
gnuradio_gr-dpd/include/dpd/predistorter_training.h
/* -*- c++ -*- */ /* * Copyright 2020 Alekh Gupta * * SPDX-License-Identifier: GPL-3.0-or-later */ #ifndef INCLUDED_DPD_PREDISTORTER_TRAINING_H #define INCLUDED_DPD_PREDISTORTER_TRAINING_H #include <gnuradio/sync_block.h> #include <dpd/api.h> namespace gr { namespace dpd { /*! * \brief Performs predistortion of the input stream to be fed to * the Power Amplifier (PA). * \ingroup dpd * * \details * It has to be necessarily supplied with the parameters * (as complex vector) of the behavioral model (GMP) used for * estimation of the PA model coefficients or predistortion * coefficients (inverse of PA model estimated). * * It can operate in both Static and Training modes of predistortion. * * * In static mode, predistortion coefficients are given by user * as complex_vector parameter. * * In training mode, it is necessary to connect 'taps' input * message-port to a postdistorter block passing message 'taps' * after adaptive-estimation. * * It multiplies GMP row vector for each input complex value with * predistorter coefficients column vector (of same order) to give a * predistorted input to PA. * * Mathematically, Output[m] = Input[m] * taps * (where Input[m] is input GMP vector(row) and 'taps' is weight vector(col)). */ class DPD_API predistorter_training : virtual public gr::sync_block { public: typedef boost::shared_ptr<predistorter_training> sptr; /*! * \brief Make a predistorter_training block * * \param dpd_params The (K_a, L_a, K_b, L_b, M_b) int_vector denoting the GMP model * parameters or DPD parameters. Used to determine the order of GMP vector generated * for each input for its predistortion. \param mode Modes of Operation, i.e., * Training or Static. \param taps Predistortion coefficients or taps as * complex_vector (Optional ,i.e., Parameter only in static mode). * */ static sptr make(const std::vector<int>& dpd_params, std::string mode, const std::vector<gr_complex>& taps); }; } // namespace dpd } // namespace gr #endif /* INCLUDED_DPD_PREDISTORTER_TRAINING_H */
2,161
C++
.h
59
33.338983
88
0.709308
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,977
api.h
gnuradio_gr-dpd/include/dpd/api.h
/* * Copyright 2011 Free Software Foundation, Inc. * * This file was generated by gr_modtool, a tool from the GNU Radio framework * This file is a part of gr-dpd * * SPDX-License-Identifier: GPL-3.0-or-later * */ #ifndef INCLUDED_DPD_API_H #define INCLUDED_DPD_API_H #include <gnuradio/attributes.h> #ifdef gnuradio_dpd_EXPORTS #define DPD_API __GR_ATTR_EXPORT #else #define DPD_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_DPD_API_H */
451
C++
.h
18
23.388889
77
0.748252
gnuradio/gr-dpd
36
16
6
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,539,978
test_decoders.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_decoders/test_decoders.cpp
#include <Arduino.h> #include <unity.h> #include "missing_tooth/missing_tooth.h" #include "dual_wheel/dual_wheel.h" void setup() { pinMode(LED_BUILTIN, OUTPUT); // NOTE!!! Wait for >2 secs // if board doesn't support software reset via Serial.DTR/RTS delay(2000); UNITY_BEGIN(); // IMPORTANT LINE! testMissingTooth(); testDualWheel(); UNITY_END(); // stop unit testing } void loop() { // Blink to indicate end of test digitalWrite(LED_BUILTIN, HIGH); delay(250); digitalWrite(LED_BUILTIN, LOW); delay(250); }
571
C++
.cpp
23
21.26087
65
0.674677
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,979
missing_tooth.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_decoders/missing_tooth/missing_tooth.cpp
#include <decoders.h> #include <globals.h> #include <unity.h> #include "missing_tooth.h" void test_setup_36_1() { //Setup a 36-1 wheel configPage4.triggerTeeth = 36; configPage4.triggerMissingTeeth = 1; configPage4.TrigSpeed = CRANK_SPEED; configPage4.trigPatternSec = SEC_TRIGGER_SINGLE; triggerSetup_missingTooth(); } void test_setup_60_2() { //Setup a 60-2 wheel configPage4.triggerTeeth = 60; configPage4.triggerMissingTeeth = 2; configPage4.TrigSpeed = CRANK_SPEED; configPage4.trigPatternSec = SEC_TRIGGER_SINGLE; triggerSetup_missingTooth(); } //************************************** Begin the new ignition setEndTooth tests ************************************** void test_missingtooth_newIgn_36_1_trig0_1() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=0 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = 0; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(34, ignition1EndTooth); } void test_missingtooth_newIgn_36_1_trig90_1() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=90 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = 90; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(25, ignition1EndTooth); } void test_missingtooth_newIgn_36_1_trig180_1() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=180 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = 180; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(16, ignition1EndTooth); } void test_missingtooth_newIgn_36_1_trig270_1() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=270 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = 270; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(7, ignition1EndTooth); } void test_missingtooth_newIgn_36_1_trig360_1() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=360 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = 360; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(34, ignition1EndTooth); } void test_missingtooth_newIgn_36_1_trigNeg90_1() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=-90 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = -90; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(7, ignition1EndTooth); } void test_missingtooth_newIgn_36_1_trigNeg180_1() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=-180 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = -180; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(16, ignition1EndTooth); } void test_missingtooth_newIgn_36_1_trigNeg270_1() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=-270 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = -270; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(25, ignition1EndTooth); } void test_missingtooth_newIgn_36_1_trigNeg360_1() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=-360 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = -360; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(34, ignition1EndTooth); } // ******* CHannel 2 ******* void test_missingtooth_newIgn_36_1_trig0_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=0 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = 0; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(16, ignition2EndTooth); } void test_missingtooth_newIgn_36_1_trig90_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=90 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = 90; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(7, ignition2EndTooth); } void test_missingtooth_newIgn_36_1_trig180_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=180 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = 180; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(34, ignition2EndTooth); } void test_missingtooth_newIgn_36_1_trig270_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=270 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = 270; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(25, ignition2EndTooth); } void test_missingtooth_newIgn_36_1_trig360_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=360 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = 360; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(16, ignition2EndTooth); } void test_missingtooth_newIgn_36_1_trigNeg90_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=-90 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = -90; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(25, ignition2EndTooth); } void test_missingtooth_newIgn_36_1_trigNeg180_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=-180 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = -180; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(34, ignition2EndTooth); } void test_missingtooth_newIgn_36_1_trigNeg270_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=-270 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = -270; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(7, ignition2EndTooth); } void test_missingtooth_newIgn_36_1_trigNeg360_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=-360 test_setup_36_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = -360; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(16, ignition2EndTooth); } void test_missingtooth_newIgn_60_2_trig0_2() { //Test the set end tooth function. Conditions: //Trigger: 60-2 //Advance: 10 //triggerAngle=300 test_setup_60_2(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = 0; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(57, ignition2EndTooth); } void test_missingtooth_newIgn_60_2_trig181_2() { //Test the set end tooth function. Conditions: //Trigger: 60-2 //Advance: 10 //triggerAngle=300 test_setup_60_2(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = 181; //No trigger offset triggerSetEndTeeth_missingTooth(); TEST_ASSERT_EQUAL(58, ignition2EndTooth); } void test_missingtooth_newIgn_2() { } void test_missingtooth_newIgn_3() { } void test_missingtooth_newIgn_4() { } void testMissingTooth() { RUN_TEST(test_missingtooth_newIgn_36_1_trig0_1); RUN_TEST(test_missingtooth_newIgn_36_1_trig90_1); RUN_TEST(test_missingtooth_newIgn_36_1_trig180_1); RUN_TEST(test_missingtooth_newIgn_36_1_trig270_1); RUN_TEST(test_missingtooth_newIgn_36_1_trig360_1); RUN_TEST(test_missingtooth_newIgn_36_1_trigNeg90_1); RUN_TEST(test_missingtooth_newIgn_36_1_trigNeg180_1); RUN_TEST(test_missingtooth_newIgn_36_1_trigNeg270_1); RUN_TEST(test_missingtooth_newIgn_36_1_trigNeg360_1); RUN_TEST(test_missingtooth_newIgn_36_1_trig0_2); RUN_TEST(test_missingtooth_newIgn_36_1_trig90_2); RUN_TEST(test_missingtooth_newIgn_36_1_trig180_2); RUN_TEST(test_missingtooth_newIgn_36_1_trig270_2); RUN_TEST(test_missingtooth_newIgn_36_1_trig360_2); RUN_TEST(test_missingtooth_newIgn_36_1_trigNeg90_2); RUN_TEST(test_missingtooth_newIgn_36_1_trigNeg180_2); RUN_TEST(test_missingtooth_newIgn_36_1_trigNeg270_2); RUN_TEST(test_missingtooth_newIgn_36_1_trigNeg360_2); //RUN_TEST(test_missingtooth_newIgn_60_2_trig181_2); //RUN_TEST(test_missingtooth_newIgn_60_2_trig182_2); }
10,731
C++
.cpp
316
29.731013
120
0.713605
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,980
dual_wheel.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_decoders/dual_wheel/dual_wheel.cpp
#include <decoders.h> #include <globals.h> #include <unity.h> #include "dual_wheel.h" void test_setup_dualwheel_12_1() { //Setup a 36-1 wheel configPage4.triggerTeeth = 12; //configPage4.triggerMissingTeeth = 1; configPage4.TrigSpeed = CRANK_SPEED; configPage4.trigPatternSec = SEC_TRIGGER_SINGLE; triggerSetup_missingTooth(); } void test_setup_dualwheel_60_2() { //Setup a 60-2 wheel configPage4.triggerTeeth = 60; configPage4.triggerMissingTeeth = 2; configPage4.TrigSpeed = CRANK_SPEED; configPage4.trigPatternSec = SEC_TRIGGER_SINGLE; triggerSetup_missingTooth(); } //************************************** Begin the new ignition setEndTooth tests ************************************** void test_dualwheel_newIgn_12_1_trig0_1() { //Test the set end tooth function. Conditions: //Trigger: 12/1 //Advance: 10 //triggerAngle=0 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = 0; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(11, ignition1EndTooth); //Test again with 0 degrees advance ignition1EndAngle = 360 - 0; //Set 0 degrees advance triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(12, ignition1EndTooth); //Test again with 35 degrees advance ignition1EndAngle = 360 - 35; //Set 35 degrees advance triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(10, ignition1EndTooth); } void test_dualwheel_newIgn_12_1_trig90_1() { //Test the set end tooth function. Conditions: //Trigger: 12/1 //Advance: 10 //triggerAngle=90 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = 90; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(8, ignition1EndTooth); } void test_dualwheel_newIgn_12_1_trig180_1() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=180 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = 180; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(5, ignition1EndTooth); } void test_dualwheel_newIgn_12_1_trig270_1() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=270 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = 270; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(2, ignition1EndTooth); } void test_dualwheel_newIgn_12_1_trig360_1() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=360 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = 360; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(12, ignition1EndTooth); } void test_dualwheel_newIgn_12_1_trigNeg90_1() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=-90 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = -90; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(2, ignition1EndTooth); } void test_dualwheel_newIgn_12_1_trigNeg180_1() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=-180 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = -180; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(5, ignition1EndTooth); } void test_dualwheel_newIgn_12_1_trigNeg270_1() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=-270 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = -270; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(8, ignition1EndTooth); } void test_dualwheel_newIgn_12_1_trigNeg360_1() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=-360 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition1EndAngle = 360 - 10; //Set 10 degrees advance configPage4.triggerAngle = -360; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(11, ignition1EndTooth); } // ******* CHannel 2 ******* void test_dualwheel_newIgn_12_1_trig0_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=0 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = 0; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(16, ignition2EndTooth); } void test_dualwheel_newIgn_12_1_trig90_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=90 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = 90; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(7, ignition2EndTooth); } void test_dualwheel_newIgn_12_1_trig180_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=180 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = 180; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(34, ignition2EndTooth); } void test_dualwheel_newIgn_12_1_trig270_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=270 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = 270; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(25, ignition2EndTooth); } void test_dualwheel_newIgn_12_1_trig360_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=360 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = 360; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(16, ignition2EndTooth); } void test_dualwheel_newIgn_12_1_trigNeg90_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=-90 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = -90; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(25, ignition2EndTooth); } void test_dualwheel_newIgn_12_1_trigNeg180_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=-180 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = -180; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(34, ignition2EndTooth); } void test_dualwheel_newIgn_12_1_trigNeg270_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=-270 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = -270; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(7, ignition2EndTooth); } void test_dualwheel_newIgn_12_1_trigNeg360_2() { //Test the set end tooth function. Conditions: //Trigger: 36-1 //Advance: 10 //triggerAngle=-360 test_setup_dualwheel_12_1(); configPage4.sparkMode = IGN_MODE_WASTED; ignition2EndAngle = 180 - 10; //Set 10 degrees advance configPage4.triggerAngle = -360; //No trigger offset triggerSetEndTeeth_DualWheel(); TEST_ASSERT_EQUAL(16, ignition2EndTooth); } void test_dualwheel_newIgn_2() { } void test_dualwheel_newIgn_3() { } void test_dualwheel_newIgn_4() { } void testDualWheel() { RUN_TEST(test_dualwheel_newIgn_12_1_trig0_1); RUN_TEST(test_dualwheel_newIgn_12_1_trig90_1); RUN_TEST(test_dualwheel_newIgn_12_1_trig180_1); RUN_TEST(test_dualwheel_newIgn_12_1_trig270_1); RUN_TEST(test_dualwheel_newIgn_12_1_trig360_1); RUN_TEST(test_dualwheel_newIgn_12_1_trigNeg90_1); RUN_TEST(test_dualwheel_newIgn_12_1_trigNeg180_1); RUN_TEST(test_dualwheel_newIgn_12_1_trigNeg270_1); RUN_TEST(test_dualwheel_newIgn_12_1_trigNeg360_1); /* RUN_TEST(test_dualwheel_newIgn_12_1_trig0_2); RUN_TEST(test_dualwheel_newIgn_12_1_trig90_2); RUN_TEST(test_dualwheel_newIgn_12_1_trig180_2); RUN_TEST(test_dualwheel_newIgn_12_1_trig270_2); RUN_TEST(test_dualwheel_newIgn_12_1_trig360_2); RUN_TEST(test_dualwheel_newIgn_12_1_trigNeg90_2); RUN_TEST(test_dualwheel_newIgn_12_1_trigNeg180_2); RUN_TEST(test_dualwheel_newIgn_12_1_trigNeg270_2); RUN_TEST(test_dualwheel_newIgn_12_1_trigNeg360_2); */ //RUN_TEST(test_dualwheel_newIgn_60_2_trig181_2); //RUN_TEST(test_dualwheel_newIgn_60_2_trig182_2); }
10,243
C++
.cpp
300
29.943333
120
0.71241
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,981
tests_misc.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_misc/tests_misc.cpp
#include <Arduino.h> #include <unity.h> #include "tests_init.h" #include "tests_tables.h" #include "test_table2d.h" #include "tests_maths.h" #define UNITY_EXCLUDE_DETAILS void setup() { pinMode(LED_BUILTIN, OUTPUT); // NOTE!!! Wait for >2 secs // if board doesn't support software reset via Serial.DTR/RTS delay(2000); UNITY_BEGIN(); // IMPORTANT LINE! testInitialisation(); testTables(); testTable2d(); testMaths(); UNITY_END(); // stop unit testing } void loop() { // Blink to indicate end of test digitalWrite(LED_BUILTIN, HIGH); delay(250); digitalWrite(LED_BUILTIN, LOW); delay(250); }
661
C++
.cpp
28
20.214286
65
0.677316
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,982
test_table2d.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_misc/test_table2d.cpp
#include <string.h> // memcpy #include <unity.h> #include <stdio.h> typedef uint8_t byte; #include "test_table2d.h" #include "table2d.h" static constexpr uint8_t TEST_TABLE2D_SIZE = 9; static uint8_t table2d_data_u8[TEST_TABLE2D_SIZE] = { 251, 211, 199, 167, 127, 101, 59, 23, 5 }; static int16_t table2d_data_s16[TEST_TABLE2D_SIZE] = { 32029, 26357, 21323, 16363, 11329, 7537, 5531, 2539, 1237 }; static uint8_t table2d_axis_u8[TEST_TABLE2D_SIZE] { 5, 23, 59, 101, 127, 167, 199, 211, 251, }; static int16_t table2d_axis_s16[TEST_TABLE2D_SIZE] = { 123, 2539, 5531, 7537, 11329, 16363, 21323, 26357, 32029, }; static table2D table2d_u8_u8; static table2D table2d_u8_s16; static table2D table2d_s16_u8; static table2D table2d_s16_s16; template <typename dataT, typename axisT> void setup_test_subject(table2D &table, dataT *data, axisT *axis) { table.valueSize = sizeof(dataT)*CHAR_BIT; table.axisSize = sizeof(axisT)*CHAR_BIT; table.xSize = TEST_TABLE2D_SIZE; table.values = data; table.axisX = axis; } static void setup_test_subjects(void) { setup_test_subject(table2d_u8_u8, table2d_data_u8, table2d_axis_u8); setup_test_subject(table2d_u8_s16, table2d_data_u8, table2d_axis_s16); setup_test_subject(table2d_s16_u8, table2d_data_s16, table2d_axis_u8); setup_test_subject(table2d_s16_s16, table2d_data_s16, table2d_axis_s16); } void test_table2dLookup_50pct(void) { setup_test_subjects(); uint8_t u8_u8_result = table2D_getValue(&table2d_u8_u8, table2d_axis_u8[3]+((table2d_axis_u8[4]-table2d_axis_u8[3])/2)); TEST_ASSERT_EQUAL(147, u8_u8_result); TEST_ASSERT_EQUAL(4, table2d_u8_u8.lastXMax); uint8_t u8_s16_result = table2D_getValue(&table2d_u8_s16, table2d_axis_s16[6]+((table2d_axis_s16[7]-table2d_axis_s16[6])/2)); TEST_ASSERT_EQUAL(41, u8_s16_result); TEST_ASSERT_EQUAL(7, table2d_u8_s16.lastXMax); int16_t s16_u8_result = table2D_getValue(&table2d_s16_u8, table2d_axis_u8[3]+((table2d_axis_u8[4]-table2d_axis_u8[3])/2)); TEST_ASSERT_EQUAL(13846, s16_u8_result); TEST_ASSERT_EQUAL(4, table2d_s16_u8.lastXMax); int16_t s16_s16_result = table2D_getValue(&table2d_s16_s16, table2d_axis_s16[3]+((table2d_axis_s16[4]-table2d_axis_s16[3])/2)); TEST_ASSERT_EQUAL(13846, s16_s16_result); TEST_ASSERT_EQUAL(4, table2d_s16_s16.lastXMax); } void test_table2dLookup_exactAxis(void) { setup_test_subjects(); uint8_t u8_u8_result = table2D_getValue(&table2d_u8_u8, table2d_axis_u8[7]); TEST_ASSERT_EQUAL(23, u8_u8_result); // TEST_ASSERT_EQUAL(7, table2d_u8_u8.lastXMax); uint8_t u8_s16_result = table2D_getValue(&table2d_u8_s16, table2d_axis_s16[1]); TEST_ASSERT_EQUAL(211, u8_s16_result); // TEST_ASSERT_EQUAL(7, table2d_u8_s16.lastXMax); int16_t s16_u8_result = table2D_getValue(&table2d_s16_u8, table2d_axis_u8[2]); TEST_ASSERT_EQUAL(21323, s16_u8_result); // TEST_ASSERT_EQUAL(4, table2d_s16_u8.lastXMax); int16_t s16_s16_result = table2D_getValue(&table2d_s16_s16, table2d_axis_s16[5]); TEST_ASSERT_EQUAL(7537, s16_s16_result); // TEST_ASSERT_EQUAL(4, table2d_s16_s16.lastXMax); } void test_table2dLookup_overMax(void) { setup_test_subjects(); uint8_t u8_u8_result = table2D_getValue(&table2d_u8_u8, table2d_axis_u8[TEST_TABLE2D_SIZE-1]+1); TEST_ASSERT_EQUAL(5, u8_u8_result); // TEST_ASSERT_EQUAL(8, table2d_u8_u8.lastXMax); uint8_t u8_s16_result = table2D_getValue(&table2d_u8_s16, table2d_axis_s16[TEST_TABLE2D_SIZE-1]+1); TEST_ASSERT_EQUAL(5, u8_s16_result); // TEST_ASSERT_EQUAL(8, table2d_u8_s16.lastXMax); int16_t s16_u8_result = table2D_getValue(&table2d_s16_u8, table2d_axis_u8[TEST_TABLE2D_SIZE-1]+1); TEST_ASSERT_EQUAL(1237, s16_u8_result); // TEST_ASSERT_EQUAL(8, table2d_s16_u8.lastXMax); int16_t s16_s16_result = table2D_getValue(&table2d_s16_s16, table2d_axis_s16[TEST_TABLE2D_SIZE-1]+1); TEST_ASSERT_EQUAL(1237, s16_s16_result); // TEST_ASSERT_EQUAL(8, table2d_s16_s16.lastXMax); } void test_table2dLookup_underMin(void) { setup_test_subjects(); uint8_t u8_u8_result = table2D_getValue(&table2d_u8_u8, table2d_axis_u8[0]-1); TEST_ASSERT_EQUAL(251, u8_u8_result); // TEST_ASSERT_EQUAL(0, table2d_u8_u8.lastXMax); uint8_t u8_s16_result = table2D_getValue(&table2d_u8_s16, table2d_axis_s16[0]-1); TEST_ASSERT_EQUAL(251, u8_s16_result); // TEST_ASSERT_EQUAL(0, table2d_u8_s16.lastXMax); int16_t s16_u8_result = table2D_getValue(&table2d_s16_u8, table2d_axis_u8[0]-1); TEST_ASSERT_EQUAL(32029, s16_u8_result); // TEST_ASSERT_EQUAL(0, table2d_s16_u8.lastXMax); int16_t s16_s16_result = table2D_getValue(&table2d_s16_s16, table2d_axis_s16[0]-1); TEST_ASSERT_EQUAL(32029, s16_s16_result); // TEST_ASSERT_EQUAL(0, table2d_s16_s16.lastXMax); } void test_table2d_all_decrementing(void) { setup_test_subjects(); uint8_t u8_u8_result_last = UINT8_MAX; for (uint8_t loop=table2d_axis_u8[0]; loop<=table2d_axis_u8[TEST_TABLE2D_SIZE-1]; ++loop) { uint8_t u8_u8_result = table2D_getValue(&table2d_u8_u8, loop); TEST_ASSERT_LESS_OR_EQUAL(u8_u8_result_last, u8_u8_result); u8_u8_result_last = u8_u8_result; } } void testTable2d() { RUN_TEST(test_table2dLookup_50pct); RUN_TEST(test_table2dLookup_exactAxis); RUN_TEST(test_table2dLookup_overMax); RUN_TEST(test_table2dLookup_underMin); RUN_TEST(test_table2d_all_decrementing); }
5,496
C++
.cpp
122
41
131
0.706477
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,983
tests_init.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_misc/tests_init.cpp
#include <globals.h> #include <init.h> #include <unity.h> #include "tests_init.h" void testInitialisation() { RUN_TEST(test_initialisation_complete); RUN_TEST(test_initialisation_ports); RUN_TEST(test_initialisation_outputs_V03); RUN_TEST(test_initialisation_outputs_V04); RUN_TEST(test_initialisation_outputs_MX5_8995); } void test_initialisation_complete(void) { initialiseAll(); //Run the main initialise function TEST_ASSERT_EQUAL(true, initialisationComplete); } void test_initialisation_ports(void) { //Test that all the port values have been set initialiseAll(); //Run the main initialise function TEST_ASSERT_NOT_EQUAL(0, inj1_pin_port); TEST_ASSERT_NOT_EQUAL(0, inj2_pin_port); TEST_ASSERT_NOT_EQUAL(0, inj3_pin_port); TEST_ASSERT_NOT_EQUAL(0, inj4_pin_port); TEST_ASSERT_NOT_EQUAL(0, ign1_pin_port); TEST_ASSERT_NOT_EQUAL(0, ign2_pin_port); TEST_ASSERT_NOT_EQUAL(0, ign3_pin_port); TEST_ASSERT_NOT_EQUAL(0, ign4_pin_port); } //Test that all mandatory output pins have their mode correctly set to output void test_initialisation_outputs_V03(void) { configPage2.pinMapping = 2; //Set the board number to test initialiseAll(); //Run the main initialise function TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil1), "Coil1"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil2), "Coil2"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil3), "Coil3"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil4), "Coil4"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector1), "Injector 1"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector2), "Injector 2"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector3), "Injector 3"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector4), "Injector 4"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinTachOut), "Tacho Out"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinIdle1), "Idle 1"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinIdle2), "Idle 2"); //if(configPage2.idleUpOutputEnabled) { TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinIdleUpOutput), "Idle Up"); } //This needs to have a default pin set TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinFuelPump), "Fuel Pump"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinFan), "Fan"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinStepperDir), "Stepper Dir"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinStepperStep), "Stepper Step"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinStepperEnable), "Stepper Enable"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinBoost), "Boost"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinVVT_1), "VVT1"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinVVT_2), "VVT2"); } //Test that all mandatory output pins have their mode correctly set to output void test_initialisation_outputs_V04(void) { configPage2.pinMapping = 3; //Set the board number to test initialiseAll(); //Run the main initialise function TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil1), "Coil1"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil2), "Coil2"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil3), "Coil3"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil4), "Coil4"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector1), "Injector 1"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector2), "Injector 2"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector3), "Injector 3"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector4), "Injector 4"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinTachOut), "Tacho Out"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinIdle1), "Idle 1"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinIdle2), "Idle 2"); //if(configPage2.idleUpOutputEnabled) { TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinIdleUpOutput), "Idle Up"); } //This needs to have a default pin set TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinFuelPump), "Fuel Pump"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinFan), "Fan"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinStepperDir), "Stepper Dir"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinStepperStep), "Stepper Step"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinStepperEnable), "Stepper Enable"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinBoost), "Boost"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinVVT_1), "VVT1"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinVVT_2), "VVT2"); } //Test that all mandatory output pins have their mode correctly set to output void test_initialisation_outputs_MX5_8995(void) { configPage2.pinMapping = 9; //Set the board number to test initialiseAll(); //Run the main initialise function TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil1), "Coil1"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil2), "Coil2"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil3), "Coil3"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil4), "Coil4"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector1), "Injector 1"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector2), "Injector 2"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector3), "Injector 3"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector4), "Injector 4"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinTachOut), "Tacho Out"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinIdle1), "Idle 1"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinIdle2), "Idle 2"); //if(configPage2.idleUpOutputEnabled) { TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinIdleUpOutput), "Idle Up"); } //This needs to have a default pin set TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinFuelPump), "Fuel Pump"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinFan), "Fan"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinStepperDir), "Stepper Dir"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinStepperStep), "Stepper Step"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinStepperEnable), "Stepper Enable"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinBoost), "Boost"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinVVT_1), "VVT1"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinVVT_2), "VVT2"); } uint8_t getPinMode(uint8_t pin) { uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); // I don't see an option for mega to return this, but whatever... if (NOT_A_PIN == port) return UNKNOWN_PIN; // Is there a bit we can check? if (0 == bit) return UNKNOWN_PIN; // Is there only a single bit set? if (bit & (bit - 1)) return UNKNOWN_PIN; volatile uint8_t *reg, *out; reg = portModeRegister(port); out = portOutputRegister(port); if (*reg & bit) return OUTPUT; else if (*out & bit) return INPUT_PULLUP; else return INPUT; }
6,908
C++
.cpp
128
51.21875
157
0.760574
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,984
tests_maths.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_misc/tests_maths.cpp
//#include <Arduino.h> #include <string.h> // memcpy #include <unity.h> #include <stdio.h> #include "tests_maths.h" #include "maths.h" void testMaths() { RUN_TEST(test_maths_percent_U8); RUN_TEST(test_maths_percent_U16); RUN_TEST(test_maths_percent_U32); RUN_TEST(test_maths_halfpercent_U8); RUN_TEST(test_maths_halfpercent_U16); RUN_TEST(test_maths_halfpercent_U32); RUN_TEST(test_maths_div100_U8); RUN_TEST(test_maths_div100_U16); RUN_TEST(test_maths_div100_U32); RUN_TEST(test_maths_div100_S8); RUN_TEST(test_maths_div100_S16); RUN_TEST(test_maths_div100_S32); RUN_TEST(test_maths_div10_U8); RUN_TEST(test_maths_div10_U16); RUN_TEST(test_maths_div10_U32); } void test_maths_percent_U8(void) { uint8_t percentOf = 200; TEST_ASSERT_EQUAL(percentage(50, percentOf), 100); TEST_ASSERT_EQUAL(percentage(75, percentOf), 150); TEST_ASSERT_EQUAL(percentage(0, percentOf), 0); TEST_ASSERT_EQUAL(percentage(100, percentOf), 200); TEST_ASSERT_EQUAL(percentage(125, percentOf), 250); } void test_maths_percent_U16(void) { uint16_t percentOf = 20000; TEST_ASSERT_EQUAL(percentage(50, percentOf), 10000); TEST_ASSERT_EQUAL(percentage(75, percentOf), 15000); TEST_ASSERT_EQUAL(percentage(0, percentOf), 0); TEST_ASSERT_EQUAL(percentage(100, percentOf), 20000); TEST_ASSERT_EQUAL(percentage(125, percentOf), 25000); } void test_maths_percent_U32(void) { uint32_t percentOf = 20000000UL; TEST_ASSERT_EQUAL(percentage(50, percentOf), 10000000UL); TEST_ASSERT_EQUAL(percentage(75, percentOf), 15000000UL); TEST_ASSERT_EQUAL(percentage(0, percentOf), 0); TEST_ASSERT_EQUAL(percentage(100, percentOf), 20000000UL); TEST_ASSERT_EQUAL(percentage(125, percentOf), 25000000UL); } void test_maths_halfpercent_U8(void) { uint8_t percentOf = 200; TEST_ASSERT_EQUAL(halfPercentage(50, percentOf), 50); TEST_ASSERT_EQUAL(halfPercentage(75, percentOf), 75); TEST_ASSERT_EQUAL(halfPercentage(0, percentOf), 0); TEST_ASSERT_EQUAL(halfPercentage(100, percentOf), 100); TEST_ASSERT_EQUAL(halfPercentage(125, percentOf), 125); } void test_maths_halfpercent_U16(void) { uint16_t percentOf = 20000; TEST_ASSERT_EQUAL(halfPercentage(50, percentOf), 5000); TEST_ASSERT_EQUAL(halfPercentage(75, percentOf), 7500); TEST_ASSERT_EQUAL(halfPercentage(0, percentOf), 0); TEST_ASSERT_EQUAL(halfPercentage(100, percentOf), 10000); TEST_ASSERT_EQUAL(halfPercentage(125, percentOf), 12500); } void test_maths_halfpercent_U32(void) { uint32_t percentOf = 20000000UL; TEST_ASSERT_EQUAL(halfPercentage(50, percentOf), 5000000UL); TEST_ASSERT_EQUAL(halfPercentage(75, percentOf), 7500000UL); TEST_ASSERT_EQUAL(halfPercentage(0, percentOf), 0); TEST_ASSERT_EQUAL(halfPercentage(100, percentOf), 10000000UL); TEST_ASSERT_EQUAL(halfPercentage(125, percentOf), 12500000UL); } void test_maths_div100_U8(void) { TEST_ASSERT_EQUAL(divu100(100), 1); TEST_ASSERT_EQUAL(divu100(200), 2); TEST_ASSERT_EQUAL(divu100(0), 0); TEST_ASSERT_EQUAL(divu100(50), 0); TEST_ASSERT_EQUAL(divu100(250), 2); } void test_maths_div100_U16(void) { TEST_ASSERT_EQUAL(divu100(10000), 100); TEST_ASSERT_EQUAL(divu100(40000), 400); } void test_maths_div100_U32(void) { TEST_ASSERT_EQUAL(divu100(100000000UL), 1000000UL); TEST_ASSERT_EQUAL(divu100(200000000UL), 2000000UL); } void test_maths_div100_S8(void) { //Check both the signed and unsigned results TEST_ASSERT_EQUAL(divs100(100), 1); TEST_ASSERT_EQUAL(divs100(0), 0); TEST_ASSERT_EQUAL(divs100(50), 0); TEST_ASSERT_EQUAL(divs100(-100), -1); TEST_ASSERT_EQUAL(divs100(-50), 0); TEST_ASSERT_EQUAL(divs100(-120), -1); } void test_maths_div100_S16(void) { //Check both the signed and unsigned results TEST_ASSERT_EQUAL(divs100(10000), 100); TEST_ASSERT_EQUAL(divs100(0), 0); TEST_ASSERT_EQUAL(divs100(50), 0); TEST_ASSERT_EQUAL(divs100(-10000), -100); TEST_ASSERT_EQUAL(divs100(-50), 0); TEST_ASSERT_EQUAL(divs100(-120), -1); } void test_maths_div100_S32(void) { //Check both the signed and unsigned results TEST_ASSERT_EQUAL(divs100(100000000L), 1000000L); TEST_ASSERT_EQUAL(divs100(0), 0); TEST_ASSERT_EQUAL(divs100(50), 0); TEST_ASSERT_EQUAL(divs100(-100000000L), -1000000L); TEST_ASSERT_EQUAL(divs100(-50), 0); TEST_ASSERT_EQUAL(divs100(-120), -1); } void test_maths_div10_U8(void) { TEST_ASSERT_EQUAL(divu10(100), 10); TEST_ASSERT_EQUAL(divu10(200), 20); TEST_ASSERT_EQUAL(divu10(0), 0); TEST_ASSERT_EQUAL(divu10(50), 5); TEST_ASSERT_EQUAL(divu10(250), 25); } void test_maths_div10_U16(void) { TEST_ASSERT_EQUAL(divu10(10000), 1000); TEST_ASSERT_EQUAL(divu10(40000), 4000); TEST_ASSERT_EQUAL(divu10(0), 0); TEST_ASSERT_EQUAL(divu10(50), 5); TEST_ASSERT_EQUAL(divu10(250), 25); } void test_maths_div10_U32(void) { TEST_ASSERT_EQUAL(divu10(100000000UL), 10000000UL); TEST_ASSERT_EQUAL(divu10(400000000UL), 40000000UL); TEST_ASSERT_EQUAL(divu10(0), 0); TEST_ASSERT_EQUAL(divu10(50), 5); TEST_ASSERT_EQUAL(divu10(250), 25); }
5,019
C++
.cpp
150
31.026667
64
0.742055
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,985
tests_tables.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_misc/tests_tables.cpp
//#include <Arduino.h> #include <string.h> // memcpy #include <unity.h> #include <stdio.h> #include "tests_tables.h" #include "table3d.h" #define _countof(x) (sizeof(x) / sizeof (x[0])) #if defined(PROGMEM) const PROGMEM byte values[] = { #else const byte values[] = { #endif //0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 109, 111, 112, 113, 114, 114, 114, 115, 115, 115, 114, 114, 114, 114, 114, 114, 104, 106, 107, 108, 109, 109, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 98, 101, 103, 103, 104, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 93, 96, 98, 99, 99, 100, 100, 101, 101, 101, 101, 101, 101, 101, 101, 101, 81, 86, 88, 89, 90, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 74, 80, 83, 84, 85, 86, 86, 86, 87, 87, 87, 87, 87, 87, 87, 87, 68, 75, 78, 79, 81, 81, 81, 82, 82, 82, 82, 82, 82, 82, 82, 82, 61, 69, 72, 74, 76, 76, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 54, 62, 66, 69, 71, 71, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 48, 56, 60, 64, 66, 66, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 42, 49, 54, 58, 61, 62, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 38, 43, 48, 52, 55, 56, 57, 58, 58, 58, 58, 58, 58, 58, 58, 58, 36, 39, 42, 46, 50, 51, 52, 53, 53, 53, 53, 53, 53, 53, 53, 53, 35, 36, 38, 41, 44, 46, 47, 48, 48, 49, 49, 49, 49, 49, 49, 49, 34, 35, 36, 37, 39, 41, 42, 43, 43, 44, 44, 44, 44, 44, 44, 44, 34, 34, 34, 34, 34, 34, 34, 34, 34, 35, 35, 35, 35, 35, 35, 35, }; static const table3d_axis_t tempXAxis[] = {500,700, 900, 1200, 1600, 2000, 2500, 3100, 3500, 4100, 4700, 5300, 5900, 6500, 6750, 7000}; static const table3d_axis_t xMin = tempXAxis[0]; static const table3d_axis_t xMax = tempXAxis[_countof(tempXAxis)-1]; static const table3d_axis_t tempYAxis[] = {100, 96, 90, 86, 76, 70, 66, 60, 56, 50, 46, 40, 36, 30, 26, 16}; static const table3d_axis_t yMin = tempYAxis[_countof(tempYAxis)-1]; static const table3d_axis_t yMax = tempYAxis[0]; static table3d16RpmLoad testTable; void setup_TestTable(void) { //Setup the fuel table with some sane values for testing //Table is setup per the below /* 100 | 109 | 111 | 112 | 113 | 114 | 114 | 114 | 115 | 115 | 115 | 114 | 114 | 113 | 112 | 111 | 111 96 | 104 | 106 | 107 | 108 | 109 | 109 | 110 | 110 | 110 | 110 | 110 | 109 | 108 | 107 | 107 | 106 90 | 98 | 101 | 103 | 103 | 104 | 105 | 105 | 105 | 105 | 105 | 105 | 104 | 104 | 103 | 102 | 102 86 | 93 | 96 | 98 | 99 | 99 | 100 | 100 | 101 | 101 | 101 | 100 | 100 | 99 | 98 | 98 | 97 76 | 81 | 86 | 88 | 89 | 90 | 91 | 91 | 91 | 91 | 91 | 91 | 90 | 90 | 89 | 89 | 88 70 | 74 | 80 | 83 | 84 | 85 | 86 | 86 | 86 | 87 | 86 | 86 | 86 | 85 | 84 | 84 | 84 65 | 68 | 75 | 78 | 79 | 81 | 81 | 81 | 82 | 82 | 82 | 82 | 81 | 81 | 80 | 79 | 79 60 | 61 | 69 | 72 | 74 | 76 | 76 | 77 | 77 | 77 | 77 | 77 | 76 | 76 | 75 | 75 | 74 56 | 54 | 62 | 66 | 69 | 71 | 71 | 72 | 72 | 72 | 72 | 72 | 72 | 71 | 71 | 70 | 70 50 | 48 | 56 | 60 | 64 | 66 | 66 | 68 | 68 | 68 | 68 | 67 | 67 | 67 | 66 | 66 | 65 46 | 42 | 49 | 54 | 58 | 61 | 62 | 62 | 63 | 63 | 63 | 63 | 62 | 62 | 61 | 61 | 61 40 | 38 | 43 | 48 | 52 | 55 | 56 | 57 | 58 | 58 | 58 | 58 | 58 | 57 | 57 | 57 | 56 36 | 36 | 39 | 42 | 46 | 50 | 51 | 52 | 53 | 53 | 53 | 53 | 53 | 53 | 52 | 52 | 52 30 | 35 | 36 | 38 | 41 | 44 | 46 | 47 | 48 | 48 | 49 | 48 | 48 | 48 | 48 | 47 | 47 26 | 34 | 35 | 36 | 37 | 39 | 41 | 42 | 43 | 43 | 44 | 44 | 44 | 43 | 43 | 43 | 43 16 | 34 | 34 | 34 | 34 | 34 | 34 | 34 | 34 | 34 | 35 | 34 | 34 | 34 | 34 | 34 | 34 ---------------------------------------------------------------------------------------------------------------- 500 | 700 | 900 | 1200 | 1600 | 2000 | 2500 | 3100 | 3500 | 4100 | 4700 | 5300 | 5900 | 6500 | 6750 | 7000 */ memcpy(testTable.axisX.axis, tempXAxis, sizeof(testTable.axisX)); memcpy(testTable.axisY.axis, tempYAxis, sizeof(testTable.axisY)); #if defined(PROGMEM) memcpy_P #else memcpy #endif (testTable.values.values, values, sizeof(testTable.values)); } void testTables() { RUN_TEST(test_tableLookup_50pct); RUN_TEST(test_tableLookup_exact1Axis); RUN_TEST(test_tableLookup_exact2Axis); RUN_TEST(test_tableLookup_overMaxX); RUN_TEST(test_tableLookup_overMaxY); RUN_TEST(test_tableLookup_underMinX); RUN_TEST(test_tableLookup_underMinY); RUN_TEST(test_tableLookup_roundUp); //RUN_TEST(test_all_incrementing); } void test_tableLookup_50pct(void) { //Tests a lookup that is exactly 50% of the way between cells on both the X and Y axis setup_TestTable(); uint16_t tempVE = get3DTableValue(&testTable, 53, 2250); //Perform lookup into fuel map for RPM vs MAP value TEST_ASSERT_EQUAL(tempVE, 69); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastXBinMax, (table3d_dim_t)6); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastYBinMax, (table3d_dim_t)8); } void test_tableLookup_exact1Axis(void) { //Tests a lookup that exactly matches on the X axis and 50% of the way between cells on the Y axis setup_TestTable(); uint16_t tempVE = get3DTableValue(&testTable, 48, testTable.axisX.axis[6]); //Perform lookup into fuel map for RPM vs MAP value TEST_ASSERT_EQUAL(tempVE, 65); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastXBinMax, (table3d_dim_t)6); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastYBinMax, (table3d_dim_t)9); } void test_tableLookup_exact2Axis(void) { //Tests a lookup that exactly matches on both the X and Y axis setup_TestTable(); uint16_t tempVE = get3DTableValue(&testTable, testTable.axisY.axis[5], testTable.axisX.axis[6]); //Perform lookup into fuel map for RPM vs MAP value TEST_ASSERT_EQUAL(tempVE, 86); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastXBinMax, (table3d_dim_t)6); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastYBinMax, (table3d_dim_t)5); } void test_tableLookup_overMaxX(void) { //Tests a lookup where the RPM exceeds the highest value in the table. The Y value is a 50% match setup_TestTable(); uint16_t tempVE = get3DTableValue(&testTable, 73, xMax+100); //Perform lookup into fuel map for RPM vs MAP value TEST_ASSERT_EQUAL(tempVE, 89); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastXBinMax, (table3d_dim_t)15); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastYBinMax, (table3d_dim_t)4); } void test_tableLookup_overMaxY(void) { //Tests a lookup where the load value exceeds the highest value in the table. The X value is a 50% match setup_TestTable(); uint16_t tempVE = get3DTableValue(&testTable, yMax+10, 600); //Perform lookup into fuel map for RPM vs MAP value TEST_ASSERT_EQUAL(tempVE, 110); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastXBinMax, (table3d_dim_t)1); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastYBinMax, (table3d_dim_t)0); } void test_tableLookup_underMinX(void) { //Tests a lookup where the RPM value is below the lowest value in the table. The Y value is a 50% match setup_TestTable(); uint16_t tempVE = get3DTableValue(&testTable, 38, xMin-100); //Perform lookup into fuel map for RPM vs MAP value TEST_ASSERT_EQUAL(tempVE, 37); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastXBinMax, (table3d_dim_t)1); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastYBinMax, (table3d_dim_t)11); } void test_tableLookup_underMinY(void) { //Tests a lookup where the load value is below the lowest value in the table. The X value is a 50% match setup_TestTable(); uint16_t tempVE = get3DTableValue(&testTable, yMin-5, 600); //Perform lookup into fuel map for RPM vs MAP value TEST_ASSERT_EQUAL(tempVE, 34); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastXBinMax, (table3d_dim_t)1); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastYBinMax, (table3d_dim_t)14); } void test_tableLookup_roundUp(void) { // Tests a lookup where the inputs result in a value that is outside the table range // due to fixed point rounding // Issue #726 setup_TestTable(); uint16_t tempVE = get3DTableValue(&testTable, 17, 600); TEST_ASSERT_EQUAL(tempVE, 34); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastXBinMax, (table3d_dim_t)1); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastYBinMax, (table3d_dim_t)14); } void test_all_incrementing(void) { //Test the when going up both the load and RPM axis that the returned value is always equal or higher to the previous one //Tests all combinations of load/rpm from between 0-200 load and 0-9000 rpm //WARNING: This can take a LONG time to run. It is disabled by default for this reason uint16_t tempVE = 0; for(uint16_t rpm = 0; rpm<xMax+1000; rpm+=100) { tempVE = 0; for(uint8_t load = 0; load<yMax+10; load++) { uint16_t newVE = get3DTableValue(&testTable, load, rpm); // char buffer[256]; // sprintf(buffer, "%d, %d" // ", %d, %d, %d, %d" // ", %d, %d, %d, %d" // ", %d", // rpm, load, // testTable.get_value_cache.lastXMin, testTable.get_value_cache.lastXBinMax, // tempXAxis[testTable.get_value_cache.lastXMin], tempXAxis[testTable.get_value_cache.lastXBinMax], // testTable.get_value_cache.lastYMin, testTable.get_value_cache.lastYBinMax, // tempYAxis[testTable.get_value_cache.lastYMin], tempYAxis[testTable.get_value_cache.lastYBinMax], // newVE); // TEST_MESSAGE(buffer); TEST_ASSERT_GREATER_OR_EQUAL(tempVE, newVE); tempVE = newVE; } } }
10,168
C++
.cpp
185
52
150
0.59598
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,986
test_corrections.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_fuel/test_corrections.cpp
#include <globals.h> #include <corrections.h> #include <unity.h> #include "test_corrections.h" void testCorrections() { test_corrections_WUE(); test_corrections_dfco(); /* RUN_TEST(test_corrections_cranking); //Not written yet RUN_TEST(test_corrections_ASE); //Not written yet RUN_TEST(test_corrections_floodclear); //Not written yet RUN_TEST(test_corrections_closedloop); //Not written yet RUN_TEST(test_corrections_flex); //Not written yet RUN_TEST(test_corrections_bat); //Not written yet RUN_TEST(test_corrections_iatdensity); //Not written yet RUN_TEST(test_corrections_baro); //Not written yet RUN_TEST(test_corrections_launch); //Not written yet RUN_TEST(test_corrections_dfco); //Not written yet */ } void test_corrections_WUE_active(void) { //Check for WUE being active currentStatus.coolant = 0; ((uint8_t*)WUETable.axisX)[9] = 120 + CALIBRATION_TEMPERATURE_OFFSET; //Set a WUE end value of 120 correctionWUE(); TEST_ASSERT_BIT_HIGH(BIT_ENGINE_WARMUP, currentStatus.engine); } void test_corrections_WUE_inactive(void) { //Check for WUE being inactive due to the temp being too high currentStatus.coolant = 200; ((uint8_t*)WUETable.axisX)[9] = 120 + CALIBRATION_TEMPERATURE_OFFSET; //Set a WUE end value of 120 correctionWUE(); TEST_ASSERT_BIT_LOW(BIT_ENGINE_WARMUP, currentStatus.engine); } void test_corrections_WUE_inactive_value(void) { //Check for WUE being set to the final row of the WUE curve if the coolant is above the max WUE temp currentStatus.coolant = 200; ((uint8_t*)WUETable.axisX)[9] = 100; ((uint8_t*)WUETable.values)[9] = 123; //Use a value other than 100 here to ensure we are using the non-default value //Force invalidate the cache WUETable.cacheTime = currentStatus.secl - 1; TEST_ASSERT_EQUAL(123, correctionWUE() ); } void test_corrections_WUE_active_value(void) { //Check for WUE being made active and returning a correct interpolated value currentStatus.coolant = 80; //Set some fake values in the table axis. Target value will fall between points 6 and 7 ((uint8_t*)WUETable.axisX)[0] = 0; ((uint8_t*)WUETable.axisX)[1] = 0; ((uint8_t*)WUETable.axisX)[2] = 0; ((uint8_t*)WUETable.axisX)[3] = 0; ((uint8_t*)WUETable.axisX)[4] = 0; ((uint8_t*)WUETable.axisX)[5] = 0; ((uint8_t*)WUETable.axisX)[6] = 70 + CALIBRATION_TEMPERATURE_OFFSET; ((uint8_t*)WUETable.axisX)[7] = 90 + CALIBRATION_TEMPERATURE_OFFSET; ((uint8_t*)WUETable.axisX)[8] = 100 + CALIBRATION_TEMPERATURE_OFFSET; ((uint8_t*)WUETable.axisX)[9] = 120 + CALIBRATION_TEMPERATURE_OFFSET; ((uint8_t*)WUETable.values)[6] = 120; ((uint8_t*)WUETable.values)[7] = 130; //Force invalidate the cache WUETable.cacheTime = currentStatus.secl - 1; //Value should be midway between 120 and 130 = 125 TEST_ASSERT_EQUAL(125, correctionWUE() ); } void test_corrections_WUE(void) { RUN_TEST(test_corrections_WUE_active); RUN_TEST(test_corrections_WUE_inactive); RUN_TEST(test_corrections_WUE_active_value); RUN_TEST(test_corrections_WUE_inactive_value); } void test_corrections_cranking(void) { } void test_corrections_ASE(void) { } void test_corrections_floodclear(void) { } void test_corrections_closedloop(void) { } void test_corrections_flex(void) { } void test_corrections_bat(void) { } void test_corrections_iatdensity(void) { } void test_corrections_baro(void) { } void test_corrections_launch(void) { } void setup_DFCO_on() { //Sets all the required conditions to have the DFCO be active configPage2.dfcoEnabled = 1; //Ensure DFCO option is turned on currentStatus.RPM = 4000; //Set the current simulated RPM to a level above the DFCO rpm threshold currentStatus.TPS = 0; //Set the simulated TPS to 0 currentStatus.coolant = 80; configPage4.dfcoRPM = 150; //DFCO enable RPM = 1500 configPage4.dfcoTPSThresh = 1; configPage4.dfcoHyster = 50; configPage2.dfcoMinCLT = 40; //Actually 0 with offset configPage2.dfcoDelay = 10; runSecsX10 = 1; correctionDFCO(); runSecsX10 = 20; } void test_corrections_dfco_on(void) { //Test under ideal conditions that DFCO goes active setup_DFCO_on(); TEST_ASSERT_TRUE(correctionDFCO()); } void test_corrections_dfco_off_RPM() { //Test that DFCO comes on and then goes off when the RPM drops below threshold setup_DFCO_on(); TEST_ASSERT_TRUE(correctionDFCO()); //Make sure DFCO is on initially currentStatus.RPM = 1000; //Set the current simulated RPM below the threshold + hyster TEST_ASSERT_FALSE(correctionDFCO()); //Test DFCO is now off } void test_corrections_dfco_off_TPS() { //Test that DFCO comes on and then goes off when the TPS goes above the required threshold (ie not off throttle) setup_DFCO_on(); TEST_ASSERT_TRUE(correctionDFCO()); //Make sure DFCO is on initially currentStatus.TPS = 10; //Set the current simulated TPS to be above the threshold TEST_ASSERT_FALSE(correctionDFCO()); //Test DFCO is now off } void test_corrections_dfco_off_delay() { //Test that DFCO comes will not activate if there has not been a long enough delay //The steup function below simulates a 2 second delay setup_DFCO_on(); //Set the threshold to be 2.5 seconds, above the simulated delay of 2s configPage2.dfcoDelay = 250; TEST_ASSERT_FALSE(correctionDFCO()); //Make sure DFCO does not come on } void test_corrections_dfco() { RUN_TEST(test_corrections_dfco_on); RUN_TEST(test_corrections_dfco_off_RPM); RUN_TEST(test_corrections_dfco_off_TPS); RUN_TEST(test_corrections_dfco_off_delay); }
5,518
C++
.cpp
157
32.77707
118
0.747137
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,987
test_PW.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_fuel/test_PW.cpp
#include <globals.h> #include <speeduino.h> #include <unity.h> #include "test_PW.h" #define PW_ALLOWED_ERROR 30 void testPW(void) { RUN_TEST(test_PW_No_Multiply); RUN_TEST(test_PW_MAP_Multiply); RUN_TEST(test_PW_MAP_Multiply_Compatibility); RUN_TEST(test_PW_AFR_Multiply); RUN_TEST(test_PW_Large_Correction); RUN_TEST(test_PW_Very_Large_Correction); } int16_t REQ_FUEL; byte VE; long MAP; uint16_t corrections; int injOpen; void test_PW_setCommon() { REQ_FUEL = 1060; VE = 130; MAP = 94; corrections = 113; injOpen = 1000; } void test_PW_No_Multiply() { test_PW_setCommon(); configPage2.multiplyMAP = 0; configPage2.includeAFR = 0; configPage2.incorporateAFR = 0; configPage2.aeApplyMode = 0; uint16_t result = PW(REQ_FUEL, VE, MAP, corrections, injOpen); TEST_ASSERT_UINT16_WITHIN(PW_ALLOWED_ERROR, 2557, result); } void test_PW_MAP_Multiply() { test_PW_setCommon(); configPage2.multiplyMAP = 1; currentStatus.baro = 103; configPage2.includeAFR = 0; configPage2.incorporateAFR = 0; configPage2.aeApplyMode = 0; uint16_t result = PW(REQ_FUEL, VE, MAP, corrections, injOpen); TEST_ASSERT_UINT16_WITHIN(PW_ALLOWED_ERROR, 2400, result); } void test_PW_MAP_Multiply_Compatibility() { test_PW_setCommon(); configPage2.multiplyMAP = 2; //Divide MAP reading by 100 rather than by Baro reading currentStatus.baro = 103; configPage2.includeAFR = 0; configPage2.incorporateAFR = 0; configPage2.aeApplyMode = 0; uint16_t result = PW(REQ_FUEL, VE, MAP, corrections, injOpen); TEST_ASSERT_UINT16_WITHIN(PW_ALLOWED_ERROR, 2449, result); } void test_PW_AFR_Multiply() { test_PW_setCommon(); configPage2.multiplyMAP = 0; currentStatus.baro = 100; configPage2.includeAFR = 1; configPage2.incorporateAFR = 0; configPage2.aeApplyMode = 0; configPage6.egoType = 2; //Set O2 sensor type to wideband currentStatus.runSecs = 20; configPage6.ego_sdelay = 10; //Ensure that the run time is longer than the O2 warmup time currentStatus.O2 = 150; currentStatus.afrTarget = 147; uint16_t result = PW(REQ_FUEL, VE, MAP, corrections, injOpen); TEST_ASSERT_UINT16_WITHIN(PW_ALLOWED_ERROR, 2588, result); } /* To avoid overflow errors, the PW() function reduces accuracy slightly when the corrections figure becomes large. There are 3 levels of this: 1) Corrections below 511 - No change in accuracy 2) Corrections between 512 and 1023 - Minor reduction to accuracy 3) Corrections above 1023 - Further reduction to accuracy */ void test_PW_Large_Correction() { //This is the same as the test_PW_No_Multiply, but with correction changed to 600 test_PW_setCommon(); corrections = 600; configPage2.multiplyMAP = 0; configPage2.includeAFR = 0; configPage2.incorporateAFR = 0; configPage2.aeApplyMode = 0; uint16_t result = PW(REQ_FUEL, VE, MAP, corrections, injOpen); TEST_ASSERT_UINT16_WITHIN(PW_ALLOWED_ERROR, 9268, result); } void test_PW_Very_Large_Correction() { //This is the same as the test_PW_No_Multiply, but with correction changed to 1500 test_PW_setCommon(); corrections = 1500; configPage2.multiplyMAP = 0; configPage2.includeAFR = 0; configPage2.incorporateAFR = 0; configPage2.aeApplyMode = 0; uint16_t result = PW(REQ_FUEL, VE, MAP, corrections, injOpen); TEST_ASSERT_UINT16_WITHIN(PW_ALLOWED_ERROR+30, 21670, result); //Additional allowed error here }
3,396
C++
.cpp
105
29.809524
119
0.749771
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,988
test_fuel.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_fuel/test_fuel.cpp
#include <globals.h> #include <init.h> #include <Arduino.h> #include <unity.h> #include "test_corrections.h" #include "test_PW.h" #define UNITY_EXCLUDE_DETAILS void setup() { pinMode(LED_BUILTIN, OUTPUT); // NOTE!!! Wait for >2 secs // if board doesn't support software reset via Serial.DTR/RTS delay(2000); UNITY_BEGIN(); // IMPORTANT LINE! initialiseAll(); //Run the main initialise function testCorrections(); testPW(); UNITY_END(); // stop unit testing } void loop() { // Blink to indicate end of test digitalWrite(LED_BUILTIN, HIGH); delay(250); digitalWrite(LED_BUILTIN, LOW); delay(250); }
663
C++
.cpp
27
21.222222
65
0.682035
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,989
test_accuracy_duration.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_schedules/test_accuracy_duration.cpp
#include <Arduino.h> #include <unity.h> #include "scheduler.h" #define TIMEOUT 1000 #define DURATION 1000 #define DELTA 20 static uint32_t start_time, end_time; static void startCallback(void) { start_time = micros(); } static void endCallback(void) { end_time = micros(); } void test_accuracy_duration_inj1(void) { initialiseSchedulers(); setFuelSchedule1(TIMEOUT, DURATION); while(fuelSchedule1.Status == PENDING) /*Wait*/ ; start_time = micros(); while(fuelSchedule1.Status == RUNNING) /*Wait*/ ; end_time = micros(); TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time); } void test_accuracy_duration_inj2(void) { initialiseSchedulers(); setFuelSchedule2(TIMEOUT, DURATION); while(fuelSchedule2.Status == PENDING) /*Wait*/ ; start_time = micros(); while(fuelSchedule2.Status == RUNNING) /*Wait*/ ; end_time = micros(); TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time); } void test_accuracy_duration_inj3(void) { initialiseSchedulers(); setFuelSchedule3(TIMEOUT, DURATION); while(fuelSchedule3.Status == PENDING) /*Wait*/ ; start_time = micros(); while(fuelSchedule3.Status == RUNNING) /*Wait*/ ; end_time = micros(); TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time); } void test_accuracy_duration_inj4(void) { initialiseSchedulers(); setFuelSchedule4(TIMEOUT, DURATION); while(fuelSchedule4.Status == PENDING) /*Wait*/ ; start_time = micros(); while(fuelSchedule4.Status == RUNNING) /*Wait*/ ; end_time = micros(); TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time); } void test_accuracy_duration_inj5(void) { #if INJ_CHANNELS >= 5 initialiseSchedulers(); setFuelSchedule5(TIMEOUT, DURATION); while(fuelSchedule5.Status == PENDING) /*Wait*/ ; start_time = micros(); while(fuelSchedule5.Status == RUNNING) /*Wait*/ ; end_time = micros(); TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time); #endif } void test_accuracy_duration_inj6(void) { #if INJ_CHANNELS >= 6 initialiseSchedulers(); setFuelSchedule6(TIMEOUT, DURATION); while(fuelSchedule6.Status == PENDING) /*Wait*/ ; start_time = micros(); while(fuelSchedule6.Status == RUNNING) /*Wait*/ ; end_time = micros(); TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time); #endif } void test_accuracy_duration_inj7(void) { #if INJ_CHANNELS >= 7 initialiseSchedulers(); setFuelSchedule7(TIMEOUT, DURATION); while(fuelSchedule7.Status == PENDING) /*Wait*/ ; start_time = micros(); while(fuelSchedule7.Status == RUNNING) /*Wait*/ ; end_time = micros(); TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time); #endif } void test_accuracy_duration_inj8(void) { #if INJ_CHANNELS >= 8 initialiseSchedulers(); setFuelSchedule8(TIMEOUT, DURATION); while(fuelSchedule8.Status == PENDING) /*Wait*/ ; start_time = micros(); while(fuelSchedule8.Status == RUNNING) /*Wait*/ ; end_time = micros(); TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time); #endif } void test_accuracy_duration_ign1(void) { initialiseSchedulers(); setIgnitionSchedule1(startCallback, TIMEOUT, DURATION, endCallback); while( (ignitionSchedule1.Status == PENDING) || (ignitionSchedule1.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time); } void test_accuracy_duration_ign2(void) { initialiseSchedulers(); setIgnitionSchedule2(startCallback, TIMEOUT, DURATION, endCallback); while( (ignitionSchedule2.Status == PENDING) || (ignitionSchedule2.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); } void test_accuracy_duration_ign3(void) { initialiseSchedulers(); setIgnitionSchedule3(startCallback, TIMEOUT, DURATION, endCallback); while( (ignitionSchedule3.Status == PENDING) || (ignitionSchedule3.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); } void test_accuracy_duration_ign4(void) { initialiseSchedulers(); setIgnitionSchedule4(startCallback, TIMEOUT, DURATION, endCallback); while( (ignitionSchedule4.Status == PENDING) || (ignitionSchedule4.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); } void test_accuracy_duration_ign5(void) { #if IGN_CHANNELS >= 5 initialiseSchedulers(); setIgnitionSchedule5(startCallback, TIMEOUT, DURATION, endCallback); while( (ignitionSchedule5.Status == PENDING) || (ignitionSchedule5.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); #endif } void test_accuracy_duration_ign6(void) { #if INJ_CHANNELS >= 6 initialiseSchedulers(); setIgnitionSchedule6(startCallback, TIMEOUT, DURATION, endCallback); while( (ignitionSchedule6.Status == PENDING) || (ignitionSchedule6.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); #endif } void test_accuracy_duration_ign7(void) { #if INJ_CHANNELS >= 7 initialiseSchedulers(); setIgnitionSchedule7(startCallback, TIMEOUT, DURATION, endCallback); while( (ignitionSchedule7.Status == PENDING) || (ignitionSchedule7.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); #endif } void test_accuracy_duration_ign8(void) { #if INJ_CHANNELS >= 8 initialiseSchedulers(); setIgnitionSchedule8(startCallback, TIMEOUT, DURATION, endCallback); while( (ignitionSchedule8.Status == PENDING) || (ignitionSchedule8.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); #endif } void test_accuracy_duration(void) { RUN_TEST(test_accuracy_duration_inj1); RUN_TEST(test_accuracy_duration_inj2); RUN_TEST(test_accuracy_duration_inj3); RUN_TEST(test_accuracy_duration_inj4); RUN_TEST(test_accuracy_duration_inj5); RUN_TEST(test_accuracy_duration_inj6); RUN_TEST(test_accuracy_duration_inj7); RUN_TEST(test_accuracy_duration_inj8); RUN_TEST(test_accuracy_duration_ign1); RUN_TEST(test_accuracy_duration_ign2); RUN_TEST(test_accuracy_duration_ign3); RUN_TEST(test_accuracy_duration_ign4); RUN_TEST(test_accuracy_duration_ign5); RUN_TEST(test_accuracy_duration_ign6); RUN_TEST(test_accuracy_duration_ign7); RUN_TEST(test_accuracy_duration_ign8); }
6,538
C++
.cpp
180
32.877778
102
0.722292
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,990
test_status_pending_to_running.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_schedules/test_status_pending_to_running.cpp
#include <Arduino.h> #include <unity.h> #include "scheduler.h" #define TIMEOUT 1000 #define DURATION 1000 static void emptyCallback(void) { } void test_status_pending_to_running_inj1(void) { initialiseSchedulers(); setFuelSchedule1(TIMEOUT, DURATION); while(fuelSchedule1.Status == PENDING) /*Wait*/ ; TEST_ASSERT_EQUAL(RUNNING, fuelSchedule1.Status); } void test_status_pending_to_running_inj2(void) { initialiseSchedulers(); setFuelSchedule2(TIMEOUT, DURATION); while(fuelSchedule2.Status == PENDING) /*Wait*/ ; TEST_ASSERT_EQUAL(RUNNING, fuelSchedule2.Status); } void test_status_pending_to_running_inj3(void) { initialiseSchedulers(); setFuelSchedule3(TIMEOUT, DURATION); while(fuelSchedule3.Status == PENDING) /*Wait*/ ; TEST_ASSERT_EQUAL(RUNNING, fuelSchedule3.Status); } void test_status_pending_to_running_inj4(void) { initialiseSchedulers(); setFuelSchedule4(TIMEOUT, DURATION); while(fuelSchedule4.Status == PENDING) /*Wait*/ ; TEST_ASSERT_EQUAL(RUNNING, fuelSchedule4.Status); } void test_status_pending_to_running_inj5(void) { #if INJ_CHANNELS >= 5 initialiseSchedulers(); setFuelSchedule5(TIMEOUT, DURATION); while(fuelSchedule5.Status == PENDING) /*Wait*/ ; TEST_ASSERT_EQUAL(RUNNING, fuelSchedule5.Status); #endif } void test_status_pending_to_running_inj6(void) { #if INJ_CHANNELS >= 6 initialiseSchedulers(); setFuelSchedule6(TIMEOUT, DURATION); while(fuelSchedule6.Status == PENDING) /*Wait*/ ; TEST_ASSERT_EQUAL(RUNNING, fuelSchedule6.Status); #endif } void test_status_pending_to_running_inj7(void) { #if INJ_CHANNELS >= 7 initialiseSchedulers(); setFuelSchedule7(TIMEOUT, DURATION); while(fuelSchedule7.Status == PENDING) /*Wait*/ ; TEST_ASSERT_EQUAL(RUNNING, fuelSchedule7.Status); #endif } void test_status_pending_to_running_inj8(void) { #if INJ_CHANNELS >= 8 initialiseSchedulers(); setFuelSchedule8(TIMEOUT, DURATION); while(fuelSchedule8.Status == PENDING) /*Wait*/ ; TEST_ASSERT_EQUAL(RUNNING, fuelSchedule8.Status); #endif } void test_status_pending_to_running_ign1(void) { initialiseSchedulers(); setIgnitionSchedule1(emptyCallback, TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule1.Status == PENDING) /*Wait*/ ; TEST_ASSERT_EQUAL(RUNNING, ignitionSchedule1.Status); } void test_status_pending_to_running_ign2(void) { initialiseSchedulers(); setIgnitionSchedule2(emptyCallback, TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule2.Status == PENDING) /*Wait*/ ; TEST_ASSERT_EQUAL(RUNNING, ignitionSchedule2.Status); } void test_status_pending_to_running_ign3(void) { initialiseSchedulers(); setIgnitionSchedule3(emptyCallback, TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule3.Status == PENDING) /*Wait*/ ; TEST_ASSERT_EQUAL(RUNNING, ignitionSchedule3.Status); } void test_status_pending_to_running_ign4(void) { initialiseSchedulers(); setIgnitionSchedule4(emptyCallback, TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule4.Status == PENDING) /*Wait*/ ; TEST_ASSERT_EQUAL(RUNNING, ignitionSchedule4.Status); } void test_status_pending_to_running_ign5(void) { #if IGN_CHANNELS >= 5 initialiseSchedulers(); setIgnitionSchedule5(emptyCallback, TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule5.Status == PENDING) /*Wait*/ ; TEST_ASSERT_EQUAL(RUNNING, ignitionSchedule5.Status); #endif } void test_status_pending_to_running_ign6(void) { #if INJ_CHANNELS >= 6 initialiseSchedulers(); setIgnitionSchedule6(emptyCallback, TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule6.Status == PENDING) /*Wait*/ ; TEST_ASSERT_EQUAL(RUNNING, ignitionSchedule6.Status); #endif } void test_status_pending_to_running_ign7(void) { #if INJ_CHANNELS >= 7 initialiseSchedulers(); setIgnitionSchedule7(emptyCallback, TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule7.Status == PENDING) /*Wait*/ ; TEST_ASSERT_EQUAL(RUNNING, ignitionSchedule7.Status); #endif } void test_status_pending_to_running_ign8(void) { #if INJ_CHANNELS >= 8 initialiseSchedulers(); setIgnitionSchedule8(emptyCallback, TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule8.Status == PENDING) /*Wait*/ ; TEST_ASSERT_EQUAL(RUNNING, ignitionSchedule8.Status); #endif } void test_status_pending_to_running(void) { RUN_TEST(test_status_pending_to_running_inj1); RUN_TEST(test_status_pending_to_running_inj2); RUN_TEST(test_status_pending_to_running_inj3); RUN_TEST(test_status_pending_to_running_inj4); RUN_TEST(test_status_pending_to_running_inj5); RUN_TEST(test_status_pending_to_running_inj6); RUN_TEST(test_status_pending_to_running_inj7); RUN_TEST(test_status_pending_to_running_inj8); RUN_TEST(test_status_pending_to_running_ign1); RUN_TEST(test_status_pending_to_running_ign2); RUN_TEST(test_status_pending_to_running_ign3); RUN_TEST(test_status_pending_to_running_ign4); RUN_TEST(test_status_pending_to_running_ign5); RUN_TEST(test_status_pending_to_running_ign6); RUN_TEST(test_status_pending_to_running_ign7); RUN_TEST(test_status_pending_to_running_ign8); }
5,244
C++
.cpp
153
31.03268
74
0.755525
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,991
test_accuracy_timeout.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_schedules/test_accuracy_timeout.cpp
#include <Arduino.h> #include <unity.h> #include "scheduler.h" #include "scheduledIO.h" #define TIMEOUT 1000 #define DURATION 1000 #define DELTA 24 static uint32_t start_time, end_time; static void startCallback(void) { end_time = micros(); } static void endCallback(void) { /*Empty*/ } void test_accuracy_timeout_inj1(void) { initialiseSchedulers(); start_time = micros(); setFuelSchedule1(TIMEOUT, DURATION); while(fuelSchedule1.Status == PENDING) /*Wait*/ ; end_time = micros(); TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); } void test_accuracy_timeout_inj2(void) { initialiseSchedulers(); start_time = micros(); setFuelSchedule2(TIMEOUT, DURATION); while(fuelSchedule2.Status == PENDING) /*Wait*/ ; end_time = micros(); TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); } void test_accuracy_timeout_inj3(void) { initialiseSchedulers(); start_time = micros(); setFuelSchedule3(TIMEOUT, DURATION); while(fuelSchedule3.Status == PENDING) /*Wait*/ ; end_time = micros(); TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); } void test_accuracy_timeout_inj4(void) { initialiseSchedulers(); start_time = micros(); setFuelSchedule4(TIMEOUT, DURATION); while(fuelSchedule4.Status == PENDING) /*Wait*/ ; end_time = micros(); TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); } void test_accuracy_timeout_inj5(void) { #if INJ_CHANNELS >= 5 initialiseSchedulers(); start_time = micros(); setFuelSchedule5(TIMEOUT, DURATION); while(fuelSchedule5.Status == PENDING) /*Wait*/ ; end_time = micros(); TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); #endif } void test_accuracy_timeout_inj6(void) { #if INJ_CHANNELS >= 6 initialiseSchedulers(); start_time = micros(); setFuelSchedule6(TIMEOUT, DURATION); while(fuelSchedule6.Status == PENDING) /*Wait*/ ; end_time = micros(); TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); #endif } void test_accuracy_timeout_inj7(void) { #if INJ_CHANNELS >= 7 initialiseSchedulers(); start_time = micros(); setFuelSchedule7(TIMEOUT, DURATION); while(fuelSchedule7.Status == PENDING) /*Wait*/ ; end_time = micros(); TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); #endif } void test_accuracy_timeout_inj8(void) { #if INJ_CHANNELS >= 8 initialiseSchedulers(); start_time = micros(); setFuelSchedule8(TIMEOUT, DURATION); while(fuelSchedule8.Status == PENDING) /*Wait*/ ; end_time = micros(); TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); #endif } void test_accuracy_timeout_ign1(void) { initialiseSchedulers(); start_time = micros(); setIgnitionSchedule1(startCallback, TIMEOUT, DURATION, endCallback); while(ignitionSchedule1.Status == PENDING) /*Wait*/ ; TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); } void test_accuracy_timeout_ign2(void) { initialiseSchedulers(); start_time = micros(); setIgnitionSchedule2(startCallback, TIMEOUT, DURATION, endCallback); while(ignitionSchedule2.Status == PENDING) /*Wait*/ ; TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); } void test_accuracy_timeout_ign3(void) { initialiseSchedulers(); start_time = micros(); setIgnitionSchedule3(startCallback, TIMEOUT, DURATION, endCallback); while(ignitionSchedule3.Status == PENDING) /*Wait*/ ; TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); } void test_accuracy_timeout_ign4(void) { initialiseSchedulers(); start_time = micros(); setIgnitionSchedule4(startCallback, TIMEOUT, DURATION, endCallback); while(ignitionSchedule4.Status == PENDING) /*Wait*/ ; TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); } void test_accuracy_timeout_ign5(void) { #if IGN_CHANNELS >= 5 initialiseSchedulers(); start_time = micros(); setIgnitionSchedule5(startCallback, TIMEOUT, DURATION, endCallback); while(ignitionSchedule5.Status == PENDING) /*Wait*/ ; TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); #endif } void test_accuracy_timeout_ign6(void) { #if INJ_CHANNELS >= 6 initialiseSchedulers(); start_time = micros(); setIgnitionSchedule6(startCallback, TIMEOUT, DURATION, endCallback); while(ignitionSchedule6.Status == PENDING) /*Wait*/ ; TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); #endif } void test_accuracy_timeout_ign7(void) { #if INJ_CHANNELS >= 7 initialiseSchedulers(); start_time = micros(); setIgnitionSchedule7(startCallback, TIMEOUT, DURATION, endCallback); while(ignitionSchedule7.Status == PENDING) /*Wait*/ ; TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); #endif } void test_accuracy_timeout_ign8(void) { #if INJ_CHANNELS >= 8 initialiseSchedulers(); start_time = micros(); setIgnitionSchedule8(startCallback, TIMEOUT, DURATION, endCallback); while(ignitionSchedule8.Status == PENDING) /*Wait*/ ; TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time); #endif } void test_accuracy_timeout(void) { RUN_TEST(test_accuracy_timeout_inj1); RUN_TEST(test_accuracy_timeout_inj2); RUN_TEST(test_accuracy_timeout_inj3); RUN_TEST(test_accuracy_timeout_inj4); RUN_TEST(test_accuracy_timeout_inj5); RUN_TEST(test_accuracy_timeout_inj6); RUN_TEST(test_accuracy_timeout_inj7); RUN_TEST(test_accuracy_timeout_inj8); RUN_TEST(test_accuracy_timeout_ign1); RUN_TEST(test_accuracy_timeout_ign2); RUN_TEST(test_accuracy_timeout_ign3); RUN_TEST(test_accuracy_timeout_ign4); RUN_TEST(test_accuracy_timeout_ign5); RUN_TEST(test_accuracy_timeout_ign6); RUN_TEST(test_accuracy_timeout_ign7); RUN_TEST(test_accuracy_timeout_ign8); }
5,931
C++
.cpp
181
29.342541
72
0.723241
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,992
test_schedules.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_schedules/test_schedules.cpp
#include <Arduino.h> #include <unity.h> #include <init.h> #include "test_schedules.h" void setup() { pinMode(LED_BUILTIN, OUTPUT); delay(2000); UNITY_BEGIN(); // start unit testing initialiseAll(); //Run the main initialise function test_status_initial_off(); //test_status_off_to_pending(); //test_status_pending_to_running(); //test_status_running_to_pending(); //test_status_running_to_off(); test_accuracy_timeout(); test_accuracy_duration(); UNITY_END(); // stop unit testing } void loop() { digitalWrite(LED_BUILTIN, HIGH); delay(250); digitalWrite(LED_BUILTIN, LOW); delay(250); }
634
C++
.cpp
26
21.615385
53
0.700997
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,993
test_status_off_to_pending.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_schedules/test_status_off_to_pending.cpp
#include <Arduino.h> #include <unity.h> #include "scheduler.h" #define TIMEOUT 1000 #define DURATION 1000 static void emptyCallback(void) { } void test_status_off_to_pending_inj1(void) { initialiseSchedulers(); setFuelSchedule1(TIMEOUT, DURATION); TEST_ASSERT_EQUAL(PENDING, fuelSchedule1.Status); } void test_status_off_to_pending_inj2(void) { initialiseSchedulers(); setFuelSchedule2(TIMEOUT, DURATION); TEST_ASSERT_EQUAL(PENDING, fuelSchedule2.Status); } void test_status_off_to_pending_inj3(void) { initialiseSchedulers(); setFuelSchedule3(TIMEOUT, DURATION); TEST_ASSERT_EQUAL(PENDING, fuelSchedule3.Status); } void test_status_off_to_pending_inj4(void) { initialiseSchedulers(); setFuelSchedule4(TIMEOUT, DURATION); TEST_ASSERT_EQUAL(PENDING, fuelSchedule4.Status); } void test_status_off_to_pending_inj5(void) { #if INJ_CHANNELS >= 5 initialiseSchedulers(); setFuelSchedule5(TIMEOUT, DURATION); TEST_ASSERT_EQUAL(PENDING, fuelSchedule5.Status); #endif } void test_status_off_to_pending_inj6(void) { #if INJ_CHANNELS >= 6 initialiseSchedulers(); setFuelSchedule6(TIMEOUT, DURATION); TEST_ASSERT_EQUAL(PENDING, fuelSchedule6.Status); #endif } void test_status_off_to_pending_inj7(void) { #if INJ_CHANNELS >= 7 initialiseSchedulers(); setFuelSchedule7(TIMEOUT, DURATION); TEST_ASSERT_EQUAL(PENDING, fuelSchedule7.Status); #endif } void test_status_off_to_pending_inj8(void) { #if INJ_CHANNELS >= 8 initialiseSchedulers(); setFuelSchedule8(TIMEOUT, DURATION); TEST_ASSERT_EQUAL(PENDING, fuelSchedule8.Status); #endif } void test_status_off_to_pending_ign1(void) { initialiseSchedulers(); setIgnitionSchedule1(emptyCallback, TIMEOUT, DURATION, emptyCallback); TEST_ASSERT_EQUAL(PENDING, ignitionSchedule1.Status); } void test_status_off_to_pending_ign2(void) { initialiseSchedulers(); setIgnitionSchedule2(emptyCallback, TIMEOUT, DURATION, emptyCallback); TEST_ASSERT_EQUAL(PENDING, ignitionSchedule2.Status); } void test_status_off_to_pending_ign3(void) { initialiseSchedulers(); setIgnitionSchedule3(emptyCallback, TIMEOUT, DURATION, emptyCallback); TEST_ASSERT_EQUAL(PENDING, ignitionSchedule3.Status); } void test_status_off_to_pending_ign4(void) { initialiseSchedulers(); setIgnitionSchedule4(emptyCallback, TIMEOUT, DURATION, emptyCallback); TEST_ASSERT_EQUAL(PENDING, ignitionSchedule4.Status); } void test_status_off_to_pending_ign5(void) { #if IGN_CHANNELS >= 5 initialiseSchedulers(); setIgnitionSchedule5(emptyCallback, TIMEOUT, DURATION, emptyCallback); TEST_ASSERT_EQUAL(PENDING, ignitionSchedule5.Status); #endif } void test_status_off_to_pending_ign6(void) { #if INJ_CHANNELS >= 6 initialiseSchedulers(); setIgnitionSchedule6(emptyCallback, TIMEOUT, DURATION, emptyCallback); TEST_ASSERT_EQUAL(PENDING, ignitionSchedule6.Status); #endif } void test_status_off_to_pending_ign7(void) { #if INJ_CHANNELS >= 7 initialiseSchedulers(); setIgnitionSchedule7(emptyCallback, TIMEOUT, DURATION, emptyCallback); TEST_ASSERT_EQUAL(PENDING, ignitionSchedule7.Status); #endif } void test_status_off_to_pending_ign8(void) { #if INJ_CHANNELS >= 8 initialiseSchedulers(); setIgnitionSchedule8(emptyCallback, TIMEOUT, DURATION, emptyCallback); TEST_ASSERT_EQUAL(PENDING, ignitionSchedule8.Status); #endif } void test_status_off_to_pending(void) { RUN_TEST(test_status_off_to_pending_inj1); RUN_TEST(test_status_off_to_pending_inj2); RUN_TEST(test_status_off_to_pending_inj3); RUN_TEST(test_status_off_to_pending_inj4); RUN_TEST(test_status_off_to_pending_inj5); RUN_TEST(test_status_off_to_pending_inj6); RUN_TEST(test_status_off_to_pending_inj7); RUN_TEST(test_status_off_to_pending_inj8); RUN_TEST(test_status_off_to_pending_ign1); RUN_TEST(test_status_off_to_pending_ign2); RUN_TEST(test_status_off_to_pending_ign3); RUN_TEST(test_status_off_to_pending_ign4); RUN_TEST(test_status_off_to_pending_ign5); RUN_TEST(test_status_off_to_pending_ign6); RUN_TEST(test_status_off_to_pending_ign7); RUN_TEST(test_status_off_to_pending_ign8); }
4,216
C++
.cpp
137
27.737226
74
0.765533
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,994
test_status_initial_off.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_schedules/test_status_initial_off.cpp
#include <Arduino.h> #include <unity.h> #include "scheduler.h" void test_status_initial_off_inj1(void) { initialiseSchedulers(); TEST_ASSERT_EQUAL(OFF, fuelSchedule1.Status); } void test_status_initial_off_inj2(void) { initialiseSchedulers(); TEST_ASSERT_EQUAL(OFF, fuelSchedule2.Status); } void test_status_initial_off_inj3(void) { initialiseSchedulers(); TEST_ASSERT_EQUAL(OFF, fuelSchedule3.Status); } void test_status_initial_off_inj4(void) { initialiseSchedulers(); TEST_ASSERT_EQUAL(OFF, fuelSchedule4.Status); } void test_status_initial_off_inj5(void) { initialiseSchedulers(); TEST_ASSERT_EQUAL(OFF, fuelSchedule5.Status); } void test_status_initial_off_inj6(void) { initialiseSchedulers(); TEST_ASSERT_EQUAL(OFF, fuelSchedule6.Status); } void test_status_initial_off_inj7(void) { initialiseSchedulers(); TEST_ASSERT_EQUAL(OFF, fuelSchedule7.Status); } void test_status_initial_off_inj8(void) { initialiseSchedulers(); TEST_ASSERT_EQUAL(OFF, fuelSchedule8.Status); } void test_status_initial_off_ign1(void) { initialiseSchedulers(); TEST_ASSERT_EQUAL(OFF, ignitionSchedule1.Status); } void test_status_initial_off_ign2(void) { initialiseSchedulers(); TEST_ASSERT_EQUAL(OFF, ignitionSchedule2.Status); } void test_status_initial_off_ign3(void) { initialiseSchedulers(); TEST_ASSERT_EQUAL(OFF, ignitionSchedule3.Status); } void test_status_initial_off_ign4(void) { initialiseSchedulers(); TEST_ASSERT_EQUAL(OFF, ignitionSchedule4.Status); } void test_status_initial_off_ign5(void) { initialiseSchedulers(); TEST_ASSERT_EQUAL(OFF, ignitionSchedule5.Status); } void test_status_initial_off_ign6(void) { initialiseSchedulers(); TEST_ASSERT_EQUAL(OFF, ignitionSchedule6.Status); } void test_status_initial_off_ign7(void) { initialiseSchedulers(); TEST_ASSERT_EQUAL(OFF, ignitionSchedule7.Status); } void test_status_initial_off_ign8(void) { initialiseSchedulers(); TEST_ASSERT_EQUAL(OFF, ignitionSchedule8.Status); } void test_status_initial_off(void) { RUN_TEST(test_status_initial_off_inj1); RUN_TEST(test_status_initial_off_inj2); RUN_TEST(test_status_initial_off_inj3); RUN_TEST(test_status_initial_off_inj4); RUN_TEST(test_status_initial_off_inj5); RUN_TEST(test_status_initial_off_inj6); RUN_TEST(test_status_initial_off_inj7); RUN_TEST(test_status_initial_off_inj8); RUN_TEST(test_status_initial_off_ign1); RUN_TEST(test_status_initial_off_ign2); RUN_TEST(test_status_initial_off_ign3); RUN_TEST(test_status_initial_off_ign4); RUN_TEST(test_status_initial_off_ign5); RUN_TEST(test_status_initial_off_ign6); RUN_TEST(test_status_initial_off_ign7); RUN_TEST(test_status_initial_off_ign8); }
2,810
C++
.cpp
102
24.470588
53
0.753348
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,995
test_status_running_to_pending.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_schedules/test_status_running_to_pending.cpp
#include <Arduino.h> #include <unity.h> #include "scheduler.h" #define TIMEOUT 1000 #define DURATION 1000 static void emptyCallback(void) { } void test_status_running_to_pending_inj1(void) { initialiseSchedulers(); setFuelSchedule1(TIMEOUT, DURATION); while(fuelSchedule1.Status == PENDING) /*Wait*/ ; setFuelSchedule1(2*TIMEOUT, DURATION); while(fuelSchedule1.Status == RUNNING) /*Wait*/ ; TEST_ASSERT_EQUAL(PENDING, fuelSchedule1.Status); } void test_status_running_to_pending_inj2(void) { initialiseSchedulers(); setFuelSchedule2(TIMEOUT, DURATION); while(fuelSchedule2.Status == PENDING) /*Wait*/ ; setFuelSchedule2(2*TIMEOUT, DURATION); while(fuelSchedule2.Status == RUNNING) /*Wait*/ ; TEST_ASSERT_EQUAL(PENDING, fuelSchedule2.Status); } void test_status_running_to_pending_inj3(void) { initialiseSchedulers(); setFuelSchedule3(TIMEOUT, DURATION); while(fuelSchedule3.Status == PENDING) /*Wait*/ ; setFuelSchedule3(2*TIMEOUT, DURATION); while(fuelSchedule3.Status == RUNNING) /*Wait*/ ; TEST_ASSERT_EQUAL(PENDING, fuelSchedule3.Status); } void test_status_running_to_pending_inj4(void) { initialiseSchedulers(); setFuelSchedule4(TIMEOUT, DURATION); while(fuelSchedule4.Status == PENDING) /*Wait*/ ; setFuelSchedule4(2*TIMEOUT, DURATION); while(fuelSchedule4.Status == RUNNING) /*Wait*/ ; TEST_ASSERT_EQUAL(PENDING, fuelSchedule4.Status); } void test_status_running_to_pending_inj5(void) { #if INJ_CHANNELS >= 5 initialiseSchedulers(); setFuelSchedule5(TIMEOUT, DURATION); while(fuelSchedule5.Status == PENDING) /*Wait*/ ; setFuelSchedule5(2*TIMEOUT, DURATION); while(fuelSchedule5.Status == RUNNING) /*Wait*/ ; TEST_ASSERT_EQUAL(PENDING, fuelSchedule5.Status); #endif } void test_status_running_to_pending_inj6(void) { #if INJ_CHANNELS >= 6 initialiseSchedulers(); setFuelSchedule6(TIMEOUT, DURATION); while(fuelSchedule6.Status == PENDING) /*Wait*/ ; setFuelSchedule6(2*TIMEOUT, DURATION); while(fuelSchedule6.Status == RUNNING) /*Wait*/ ; TEST_ASSERT_EQUAL(PENDING, fuelSchedule6.Status); #endif } void test_status_running_to_pending_inj7(void) { #if INJ_CHANNELS >= 7 initialiseSchedulers(); setFuelSchedule7(TIMEOUT, DURATION); while(fuelSchedule7.Status == PENDING) /*Wait*/ ; setFuelSchedule7(2*TIMEOUT, DURATION); while(fuelSchedule7.Status == RUNNING) /*Wait*/ ; TEST_ASSERT_EQUAL(PENDING, fuelSchedule7.Status); #endif } void test_status_running_to_pending_inj8(void) { #if INJ_CHANNELS >= 8 initialiseSchedulers(); setFuelSchedule8(TIMEOUT, DURATION); while(fuelSchedule8.Status == PENDING) /*Wait*/ ; setFuelSchedule8(2*TIMEOUT, DURATION); while(fuelSchedule8.Status == RUNNING) /*Wait*/ ; TEST_ASSERT_EQUAL(PENDING, fuelSchedule8.Status); #endif } void test_status_running_to_pending_ign1(void) { initialiseSchedulers(); setIgnitionSchedule1(emptyCallback, TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule1.Status == PENDING) /*Wait*/ ; setIgnitionSchedule1(emptyCallback, 2*TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule1.Status == RUNNING) /*Wait*/ ; TEST_ASSERT_EQUAL(PENDING, ignitionSchedule1.Status); } void test_status_running_to_pending_ign2(void) { initialiseSchedulers(); setIgnitionSchedule2(emptyCallback, TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule2.Status == PENDING) /*Wait*/ ; setIgnitionSchedule2(emptyCallback, 2*TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule2.Status == RUNNING) /*Wait*/ ; TEST_ASSERT_EQUAL(PENDING, ignitionSchedule2.Status); } void test_status_running_to_pending_ign3(void) { initialiseSchedulers(); setIgnitionSchedule3(emptyCallback, TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule3.Status == PENDING) /*Wait*/ ; setIgnitionSchedule3(emptyCallback, 2*TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule3.Status == RUNNING) /*Wait*/ ; TEST_ASSERT_EQUAL(PENDING, ignitionSchedule3.Status); } void test_status_running_to_pending_ign4(void) { initialiseSchedulers(); setIgnitionSchedule4(emptyCallback, TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule4.Status == PENDING) /*Wait*/ ; setIgnitionSchedule4(emptyCallback, 2*TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule4.Status == RUNNING) /*Wait*/ ; TEST_ASSERT_EQUAL(PENDING, ignitionSchedule4.Status); } void test_status_running_to_pending_ign5(void) { #if IGN_CHANNELS >= 5 initialiseSchedulers(); setIgnitionSchedule5(emptyCallback, TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule5.Status == PENDING) /*Wait*/ ; setIgnitionSchedule5(emptyCallback, 2*TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule5.Status == RUNNING) /*Wait*/ ; TEST_ASSERT_EQUAL(PENDING, ignitionSchedule5.Status); #endif } void test_status_running_to_pending_ign6(void) { #if INJ_CHANNELS >= 6 initialiseSchedulers(); setIgnitionSchedule6(emptyCallback, TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule6.Status == PENDING) /*Wait*/ ; setIgnitionSchedule6(emptyCallback, 2*TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule6.Status == RUNNING) /*Wait*/ ; TEST_ASSERT_EQUAL(PENDING, ignitionSchedule6.Status); #endif } void test_status_running_to_pending_ign7(void) { #if INJ_CHANNELS >= 7 initialiseSchedulers(); setIgnitionSchedule7(emptyCallback, TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule7.Status == PENDING) /*Wait*/ ; setIgnitionSchedule7(emptyCallback, 2*TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule7.Status == RUNNING) /*Wait*/ ; TEST_ASSERT_EQUAL(PENDING, ignitionSchedule7.Status); #endif } void test_status_running_to_pending_ign8(void) { #if INJ_CHANNELS >= 8 initialiseSchedulers(); setIgnitionSchedule8(emptyCallback, TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule8.Status == PENDING) /*Wait*/ ; setIgnitionSchedule8(emptyCallback, 2*TIMEOUT, DURATION, emptyCallback); while(ignitionSchedule8.Status == RUNNING) /*Wait*/ ; TEST_ASSERT_EQUAL(PENDING, ignitionSchedule8.Status); #endif } void test_status_running_to_pending(void) { RUN_TEST(test_status_running_to_pending_inj1); RUN_TEST(test_status_running_to_pending_inj2); RUN_TEST(test_status_running_to_pending_inj3); RUN_TEST(test_status_running_to_pending_inj4); RUN_TEST(test_status_running_to_pending_inj5); RUN_TEST(test_status_running_to_pending_inj6); RUN_TEST(test_status_running_to_pending_inj7); RUN_TEST(test_status_running_to_pending_inj8); RUN_TEST(test_status_running_to_pending_ign1); RUN_TEST(test_status_running_to_pending_ign2); RUN_TEST(test_status_running_to_pending_ign3); RUN_TEST(test_status_running_to_pending_ign4); RUN_TEST(test_status_running_to_pending_ign5); RUN_TEST(test_status_running_to_pending_ign6); RUN_TEST(test_status_running_to_pending_ign7); RUN_TEST(test_status_running_to_pending_ign8); }
7,100
C++
.cpp
185
34.832432
76
0.75058
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,996
test_status_running_to_off.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_schedules/test_status_running_to_off.cpp
#include <Arduino.h> #include <unity.h> #include "scheduler.h" #define TIMEOUT 1000 #define DURATION 1000 static void emptyCallback(void) { } void test_status_running_to_off_inj1(void) { initialiseSchedulers(); setFuelSchedule1(TIMEOUT, DURATION); while( (fuelSchedule1.Status == PENDING) || (fuelSchedule1.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_EQUAL(OFF, fuelSchedule1.Status); } void test_status_running_to_off_inj2(void) { initialiseSchedulers(); setFuelSchedule2(TIMEOUT, DURATION); while( (fuelSchedule2.Status == PENDING) || (fuelSchedule2.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_EQUAL(OFF, fuelSchedule2.Status); } void test_status_running_to_off_inj3(void) { initialiseSchedulers(); setFuelSchedule3(TIMEOUT, DURATION); while( (fuelSchedule3.Status == PENDING) || (fuelSchedule3.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_EQUAL(OFF, fuelSchedule3.Status); } void test_status_running_to_off_inj4(void) { initialiseSchedulers(); setFuelSchedule4(TIMEOUT, DURATION); while( (fuelSchedule4.Status == PENDING) || (fuelSchedule4.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_EQUAL(OFF, fuelSchedule4.Status); } void test_status_running_to_off_inj5(void) { #if INJ_CHANNELS >= 5 initialiseSchedulers(); setFuelSchedule5(TIMEOUT, DURATION); while( (fuelSchedule5.Status == PENDING) || (fuelSchedule5.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_EQUAL(OFF, fuelSchedule5.Status); #endif } void test_status_running_to_off_inj6(void) { #if INJ_CHANNELS >= 6 initialiseSchedulers(); setFuelSchedule6(TIMEOUT, DURATION); while( (fuelSchedule6.Status == PENDING) || (fuelSchedule6.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_EQUAL(OFF, fuelSchedule6.Status); #endif } void test_status_running_to_off_inj7(void) { #if INJ_CHANNELS >= 7 initialiseSchedulers(); setFuelSchedule7(TIMEOUT, DURATION); while( (fuelSchedule7.Status == PENDING) || (fuelSchedule7.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_EQUAL(OFF, fuelSchedule7.Status); #endif } void test_status_running_to_off_inj8(void) { #if INJ_CHANNELS >= 8 initialiseSchedulers(); setFuelSchedule8(TIMEOUT, DURATION); while( (fuelSchedule8.Status == PENDING) || (fuelSchedule8.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_EQUAL(OFF, fuelSchedule8.Status); #endif } void test_status_running_to_off_ign1(void) { initialiseSchedulers(); setIgnitionSchedule1(emptyCallback, TIMEOUT, DURATION, emptyCallback); while( (ignitionSchedule1.Status == PENDING) || (ignitionSchedule1.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_EQUAL(OFF, ignitionSchedule1.Status); } void test_status_running_to_off_ign2(void) { initialiseSchedulers(); setIgnitionSchedule2(emptyCallback, TIMEOUT, DURATION, emptyCallback); while( (ignitionSchedule2.Status == PENDING) || (ignitionSchedule2.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_EQUAL(OFF, ignitionSchedule2.Status); } void test_status_running_to_off_ign3(void) { initialiseSchedulers(); setIgnitionSchedule3(emptyCallback, TIMEOUT, DURATION, emptyCallback); while( (ignitionSchedule3.Status == PENDING) || (ignitionSchedule3.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_EQUAL(OFF, ignitionSchedule3.Status); } void test_status_running_to_off_ign4(void) { initialiseSchedulers(); setIgnitionSchedule4(emptyCallback, TIMEOUT, DURATION, emptyCallback); while( (ignitionSchedule4.Status == PENDING) || (ignitionSchedule4.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_EQUAL(OFF, ignitionSchedule4.Status); } void test_status_running_to_off_ign5(void) { #if IGN_CHANNELS >= 5 initialiseSchedulers(); setIgnitionSchedule5(emptyCallback, TIMEOUT, DURATION, emptyCallback); while( (ignitionSchedule5.Status == PENDING) || (ignitionSchedule5.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_EQUAL(OFF, ignitionSchedule5.Status); #endif } void test_status_running_to_off_ign6(void) { #if IGN_CHANNELS >= 6 initialiseSchedulers(); setIgnitionSchedule6(emptyCallback, TIMEOUT, DURATION, emptyCallback); while( (ignitionSchedule6.Status == PENDING) || (ignitionSchedule6.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_EQUAL(OFF, ignitionSchedule6.Status); #endif } void test_status_running_to_off_ign7(void) { #if IGN_CHANNELS >= 7 initialiseSchedulers(); setIgnitionSchedule7(emptyCallback, TIMEOUT, DURATION, emptyCallback); while( (ignitionSchedule7.Status == PENDING) || (ignitionSchedule7.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_EQUAL(OFF, ignitionSchedule7.Status); #endif } void test_status_running_to_off_ign8(void) { #if IGN_CHANNELS >= 8 initialiseSchedulers(); setIgnitionSchedule8(emptyCallback, TIMEOUT, DURATION, emptyCallback); while( (ignitionSchedule8.Status == PENDING) || (ignitionSchedule8.Status == RUNNING) ) /*Wait*/ ; TEST_ASSERT_EQUAL(OFF, ignitionSchedule8.Status); #endif } void test_status_running_to_off(void) { RUN_TEST(test_status_running_to_off_inj1); RUN_TEST(test_status_running_to_off_inj2); RUN_TEST(test_status_running_to_off_inj3); RUN_TEST(test_status_running_to_off_inj4); RUN_TEST(test_status_running_to_off_inj5); RUN_TEST(test_status_running_to_off_inj6); RUN_TEST(test_status_running_to_off_inj7); RUN_TEST(test_status_running_to_off_inj8); RUN_TEST(test_status_running_to_off_ign1); RUN_TEST(test_status_running_to_off_ign2); RUN_TEST(test_status_running_to_off_ign3); RUN_TEST(test_status_running_to_off_ign4); RUN_TEST(test_status_running_to_off_ign5); RUN_TEST(test_status_running_to_off_ign6); RUN_TEST(test_status_running_to_off_ign7); RUN_TEST(test_status_running_to_off_ign8); }
5,736
C++
.cpp
153
34.248366
102
0.733993
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,997
table3d_interpolate.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/table3d_interpolate.cpp
#include "table3d_interpolate.h" // ============================= Axis Bin Searching ========================= static inline bool is_in_bin(const table3d_axis_t &testValue, const table3d_axis_t &min, const table3d_axis_t &max) { return testValue > min && testValue <= max; } // Find the axis index for the top of the bin that covers the test value. // E.g. 4 in { 1, 3, 5, 7, 9 } would be 2 // We assume the axis is in order. static inline table3d_dim_t find_bin_max( table3d_axis_t &value, // Value to search for const table3d_axis_t *pAxis, // The axis to search table3d_dim_t minElement, // Axis index of the element with the lowest value (at one end of the array) table3d_dim_t maxElement, // Axis index of the element with the highest value (at the other end of the array) table3d_dim_t lastBinMax) // The last result from this call - used to speed up searches { // Direction to search (1 coventional, -1 to go backwards from pAxis) int8_t stride = maxElement>minElement ? 1 : -1; // It's quicker to increment/adjust this pointer than to repeatedly // index the array - minimum 2%, often >5% const table3d_axis_t *pMax = nullptr; // minElement is at one end of the array, so the "lowest" bin // is [minElement, minElement+stride]. Since we're working with the upper // index of the bin pair, we can't go below minElement + stride. table3d_dim_t minBinIndex = minElement + stride; // Check the cached last bin and either side first - it's likely that this will give a hit under // real world conditions // Check if we're still in the same bin as last time pMax = pAxis + lastBinMax; if (is_in_bin(value, *(pMax - stride), *pMax)) { return lastBinMax; } // Check the bin above the last one pMax = pMax - stride; if (lastBinMax!=minBinIndex && is_in_bin(value, *(pMax - stride), *pMax)) { return lastBinMax-stride; } // Check the bin below the last one pMax += stride*2; if (lastBinMax!=maxElement && is_in_bin(value, *(pMax - stride), *pMax)) { return lastBinMax+stride; } // Check if outside array limits - won't happen often in the real world // so check after the cache check // At or above maximum - clamp to final value if (value>=pAxis[maxElement]) { value = pAxis[maxElement]; return maxElement; } // At or below minimum - clamp to lowest value if (value<=pAxis[minElement]) { value = pAxis[minElement]; return minElement+stride; } // No hits above, so run a linear search. // We start at the maximum & work down, rather than looping from [0] up to [max] // This is because the important tables (fuel and injection) will have the highest // RPM at the top of the X axis, so starting there will mean the best case occurs // when the RPM is highest (and hence the CPU is needed most) lastBinMax = maxElement; pMax = pAxis + lastBinMax; while (lastBinMax!=minBinIndex && !is_in_bin(value, *(pMax - stride), *pMax)) { lastBinMax -= stride; pMax -= stride; } return lastBinMax; } table3d_dim_t find_xbin(table3d_axis_t &value, const table3d_axis_t *pAxis, table3d_dim_t size, table3d_dim_t lastBin) { return find_bin_max(value, pAxis, 0, size-1, lastBin); } table3d_dim_t find_ybin(table3d_axis_t &value, const table3d_axis_t *pAxis, table3d_dim_t size, table3d_dim_t lastBin) { // Y axis is stored in reverse for performance purposes (not sure that's still valid). // The minimum value is at the end & max at the start. So need to adjust for that. return find_bin_max(value, pAxis, size-1, 0, lastBin); } // ========================= Fixed point math ========================= // An unsigned fixed point number type with 1 integer bit & 8 fractional bits. // See https://en.wikipedia.org/wiki/Q_(number_format). // This is specialized for the number range 0..1 - a generic fixed point // class would miss some important optimizations. Specifically, we can avoid // type promotion during multiplication. typedef uint16_t QU1X8_t; static constexpr uint8_t QU1X8_INTEGER_SHIFT = 8; static constexpr QU1X8_t QU1X8_ONE = 1U << QU1X8_INTEGER_SHIFT; static constexpr QU1X8_t QU1X8_HALF = 1U << (QU1X8_INTEGER_SHIFT-1); inline QU1X8_t mulQU1X8(QU1X8_t a, QU1X8_t b) { // 1x1 == 1....but the real reason for this is to avoid 16-bit multiplication overflow. // // We are using uint16_t as our underlying fixed point type. If we follow the regular // code path, we'd need to promote to uint32_t to avoid overflow. // // The overflow can only happen when *both* the X & Y inputs // are at the edge of a bin. // // This is a rare condition, so most of the time we can use 16-bit mutiplication and gain performance if (a==QU1X8_ONE && b==QU1X8_ONE) { return QU1X8_ONE; } // Add the equivalent of 0.5 to the final calculation pre-rounding. // This will have the effect of rounding to the nearest integer, rather // than always rounding down. return ((a * b) + QU1X8_HALF) >> QU1X8_INTEGER_SHIFT; } // ============================= Axis value to bin % ========================= static inline QU1X8_t compute_bin_position(table3d_axis_t value, const table3d_dim_t &bin, int8_t stride, const table3d_axis_t *pAxis) { table3d_axis_t binMinValue = pAxis[bin-stride]; if (value==binMinValue) { return 0; } table3d_axis_t binMaxValue = pAxis[bin]; if (value==binMaxValue) { return QU1X8_ONE; } table3d_axis_t binWidth = binMaxValue-binMinValue; // Since we can have bins of any width, we need to use // 24.8 fixed point to avoid overflow uint32_t p = (uint32_t)(value - binMinValue) << QU1X8_INTEGER_SHIFT; // But since we are computing the ratio (0 to 1), p is guarenteed to be // less than binWidth and thus the division below will result in a value // <=1. So we can reduce the data type from 24.8 (uint32_t) to 1.8 (uint16_t) return p / binWidth; } // ============================= End internal support functions ========================= //This function pulls a value from a 3D table given a target for X and Y coordinates. //It performs a 2D linear interpolation as described in: www.megamanual.com/v22manual/ve_tuner.pdf table3d_value_t get3DTableValue(struct table3DGetValueCache *pValueCache, table3d_dim_t axisSize, const table3d_value_t *pValues, const table3d_axis_t *pXAxis, const table3d_axis_t *pYAxis, table3d_axis_t Y_in, table3d_axis_t X_in) { //0th check is whether the same X and Y values are being sent as last time. // If they are, this not only prevents a lookup of the axis, but prevents the //interpolation calcs being performed if( X_in == pValueCache->last_lookup.x && Y_in == pValueCache->last_lookup.y) { return pValueCache->lastOutput; } // Assign this here, as we might modify coords below. pValueCache->last_lookup.x = X_in; pValueCache->last_lookup.y = Y_in; // Figure out where on the axes the incoming coord are pValueCache->lastXBinMax = find_xbin(X_in, pXAxis, axisSize, pValueCache->lastXBinMax); pValueCache->lastYBinMax = find_ybin(Y_in, pYAxis, axisSize, pValueCache->lastYBinMax); /* At this point we have the 4 corners of the map where the interpolated value will fall in Eg: (yMax,xMin) (yMax,xMax) (yMin,xMin) (yMin,xMax) In the following calculation the table values are referred to by the following variables: A B C D */ table3d_dim_t rowMax = pValueCache->lastYBinMax * axisSize; table3d_dim_t rowMin = (pValueCache->lastYBinMax+1) * axisSize; table3d_value_t A = pValues[rowMax + pValueCache->lastXBinMax-1]; table3d_value_t B = pValues[rowMax + pValueCache->lastXBinMax]; table3d_value_t C = pValues[rowMin + pValueCache->lastXBinMax-1]; table3d_value_t D = pValues[rowMin + pValueCache->lastXBinMax]; //Check that all values aren't just the same (This regularly happens with things like the fuel trim maps) if( (A == B) && (A == C) && (A == D) ) { pValueCache->lastOutput = A; } else { //Create some normalised position values //These are essentially percentages (between 0 and 1) of where the desired value falls between the nearest bins on each axis const QU1X8_t p = compute_bin_position(X_in, pValueCache->lastXBinMax, 1, pXAxis); const QU1X8_t q = compute_bin_position(Y_in, pValueCache->lastYBinMax, -1, pYAxis); const QU1X8_t m = mulQU1X8(QU1X8_ONE-p, q); const QU1X8_t n = mulQU1X8(p, q); const QU1X8_t o = mulQU1X8(QU1X8_ONE-p, QU1X8_ONE-q); const QU1X8_t r = mulQU1X8(p, QU1X8_ONE-q); pValueCache->lastOutput = ( (A * m) + (B * n) + (C * o) + (D * r) ) >> QU1X8_INTEGER_SHIFT; } return pValueCache->lastOutput; }
8,900
C++
.cpp
183
44.344262
134
0.674568
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,998
table3d_axes.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/table3d_axes.cpp
#include <stdlib.h> #include "table3d_axes.h" constexpr int16_ref::scalar table3d_axis_base::scalar_100; constexpr int16_ref::scalar table3d_axis_base::scalar_2; constexpr int16_ref::scalar table3d_axis_base::scalar_1;
219
C++
.cpp
5
42.8
58
0.794393
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,539,999
newComms.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/newComms.cpp
/* Speeduino - Simple engine management for the Arduino Mega 2560 platform Copyright (C) Josh Stewart A full copy of the license may be found in the projects root directory */ /** @file * Process Incoming and outgoing serial communications. */ #include "globals.h" #include "newComms.h" #include "cancomms.h" #include "storage.h" #include "maths.h" #include "utilities.h" #include "decoders.h" #include "TS_CommandButtonHandler.h" #include "errors.h" #include "pages.h" #include "page_crc.h" #include "logger.h" #include "comms.h" #include "src/FastCRC/FastCRC.h" #ifdef RTC_ENABLED #include "rtc_common.h" #endif #ifdef SD_LOGGING #include "SD_logger.h" #endif uint16_t serialPayloadLength = 0; bool serialReceivePending = false; /**< Whether or not a serial request has only been partially received. This occurs when a the length has been received in the serial buffer, but not all of the payload or CRC has yet been received. */ uint16_t serialBytesReceived = 0; /**< The number of bytes received in the serial buffer during the current command. */ uint32_t serialCRC = 0; uint8_t serialPayload[SERIAL_BUFFER_SIZE]; /**< Serial payload buffer. */ bool serialWriteInProgress = false; uint16_t serialBytesTransmitted = 0; uint32_t serialReceiveStartTime = 0; /**< The time at which the serial receive started. Used for calculating whether a timeout has occurred */ #ifdef RTC_ENABLED uint8_t serialSDTransmitPayload[SD_FILE_TRANSMIT_BUFFER_SIZE]; uint16_t SDcurrentDirChunk; uint32_t SDreadStartSector; uint32_t SDreadNumSectors; uint32_t SDreadCompletedSectors = 0; #endif /** Processes the incoming data on the serial buffer based on the command sent. Can be either data for a new command or a continuation of data for command that is already in progress: - cmdPending = If a command has started but is wairing on further data to complete - chunkPending = Specifically for the new receive value method where TS will send a known number of contiguous bytes to be written to a table Comands are single byte (letter symbol) commands. */ void parseSerial() { //Check for an existing legacy command in progress if(cmdPending == true) { command(); return; } if (serialReceivePending == false) { serialBytesReceived = 0; //Reset the number of bytes received as we're starting a new command //New command received //Need at least 2 bytes to read the length of the command serialReceivePending = true; //Flag the serial receive as being in progress byte lowByte = Serial.read(); //Check if the command is legacy using the call/response mechanism if((lowByte >= 'A') && (lowByte <= 'z') ) { //Handle legacy cases here serialReceivePending = false; //Make sure new serial handling does not interfere with legacy handling legacySerial = true; currentCommand = lowByte; command(); } else { while(Serial.available() == 0) { } //Wait for the 2nd byte to be received (This will almost never happen) byte highByte = Serial.read(); serialPayloadLength = word(lowByte, highByte); serialBytesReceived = 2; cmdPending = false; // Make sure legacy handling does not interfere with new serial handling serialReceiveStartTime = millis(); } } //If there is a serial receive in progress, read as much from the buffer as possible or until we receive all bytes while( (Serial.available() > 0) && (serialReceivePending == true) ) { if (serialBytesReceived < (serialPayloadLength + SERIAL_LEN_SIZE) ) { serialPayload[(serialBytesReceived - SERIAL_LEN_SIZE)] = Serial.read(); serialBytesReceived++; } else if (Serial.available() >= SERIAL_CRC_LENGTH) { uint32_t crc1 = Serial.read(); uint32_t crc2 = Serial.read(); uint32_t crc3 = Serial.read(); uint32_t crc4 = Serial.read(); serialCRC = (crc1<<24) | (crc2<<16) | (crc3<<8) | crc4; serialReceivePending = false; //The serial receive is now complete //Test the CRC uint32_t receivedCRC = CRC32.crc32(serialPayload, serialPayloadLength); //receivedCRC++; if(serialCRC != receivedCRC) { //CRC Error. Need to send an error message sendSerialReturnCode(SERIAL_RC_CRC_ERR); } else { //CRC is correct. Process the command processSerialCommand(); } //CRC match } //CRC received in full //Check for a timeout if( (millis() - serialReceiveStartTime) > SERIAL_TIMEOUT) { //Timeout occurred serialReceivePending = false; //Reset the serial receive sendSerialReturnCode(SERIAL_RC_TIMEOUT); //Flush the serial buffer while(Serial.available() > 0) { Serial.read(); } } //Timeout } //Data in serial buffer and serial receive in progress } void sendSerialReturnCode(byte returnCode) { Serial.write((uint8_t)0); Serial.write((uint8_t)1); //Size is always 1 Serial.write(returnCode); //Calculate and send CRC uint32_t CRC32_val = CRC32.crc32(&returnCode, 1); Serial.write( ((CRC32_val >> 24) & 255) ); Serial.write( ((CRC32_val >> 16) & 255) ); Serial.write( ((CRC32_val >> 8) & 255) ); Serial.write( (CRC32_val & 255) ); } void sendSerialPayload(void *payload, uint16_t payloadLength) { //Start new transmission session serialBytesTransmitted = 0; serialWriteInProgress = false; uint16_t totalPayloadLength = payloadLength; Serial.write(totalPayloadLength >> 8); Serial.write(totalPayloadLength); //Need to handle serial buffer being full. This is just for testing serialPayloadLength = payloadLength; //Save the payload length incase we need to transmit in multiple steps for(uint16_t i = 0; i < payloadLength; i++) { Serial.write(((uint8_t*)payload)[i]); serialBytesTransmitted++; if(Serial.availableForWrite() == 0) { //Serial buffer is full. Need to wait for it to be free serialWriteInProgress = true; break; } } if(serialWriteInProgress == false) { //All data transmitted. Send the CRC uint32_t CRC32_val = CRC32.crc32((uint8_t*)payload, payloadLength); Serial.write( ((CRC32_val >> 24) & 255) ); Serial.write( ((CRC32_val >> 16) & 255) ); Serial.write( ((CRC32_val >> 8) & 255) ); Serial.write( (CRC32_val & 255) ); } } void continueSerialTransmission() { if(serialWriteInProgress == true) { serialWriteInProgress = false; //Assume we will reach the end of the serial buffer. If we run out of buffer, this will be set to true below //Serial buffer is free. Continue sending the data for(uint16_t i = serialBytesTransmitted; i < serialPayloadLength; i++) { Serial.write(serialPayload[i]); serialBytesTransmitted++; if(Serial.availableForWrite() == 0) { //Serial buffer is full. Need to wait for it to be free serialWriteInProgress = true; break; } } if(serialWriteInProgress == false) { //All data transmitted. Send the CRC uint32_t CRC32_val = CRC32.crc32(serialPayload, serialPayloadLength); Serial.write( ((CRC32_val >> 24) & 255) ); Serial.write( ((CRC32_val >> 16) & 255) ); Serial.write( ((CRC32_val >> 8) & 255) ); Serial.write( (CRC32_val & 255) ); } } } void processSerialCommand() { currentCommand = serialPayload[0]; switch (currentCommand) { case 'A': // send x bytes of realtime values //sendValues(0, LOG_ENTRY_SIZE, 0x31, 0); //send values to serial0 generateLiveValues(0, LOG_ENTRY_SIZE); break; case 'b': // New EEPROM burn command to only burn a single page at a time if(isEepromWritePending()) { //There is already a write pending, force it through. sendSerialReturnCode(SERIAL_RC_BUSY_ERR); enableForceBurn(); writeAllConfig(); disableForceBurn(); break; } writeConfig(serialPayload[2]); //Read the table number and perform burn. Note that byte 1 in the array is unused sendSerialReturnCode(SERIAL_RC_BURN_OK); break; case 'C': // test communications. This is used by Tunerstudio to see whether there is an ECU on a given serial port { uint8_t tempPayload[] = {SERIAL_RC_OK, currentStatus.secl}; sendSerialPayload(&tempPayload, 2); break; } case 'd': // Send a CRC32 hash of a given page { uint32_t CRC32_val = calculatePageCRC32( serialPayload[2] ); uint8_t payloadCRC32[5]; //First byte is the flag payloadCRC32[0] = SERIAL_RC_OK; //Split the 4 bytes of the CRC32 value into individual bytes and send payloadCRC32[1] = ((CRC32_val >> 24) & 255); payloadCRC32[2] = ((CRC32_val >> 16) & 255); payloadCRC32[3] = ((CRC32_val >> 8) & 255); payloadCRC32[4] = (CRC32_val & 255); sendSerialPayload( &payloadCRC32, 5); break; } case 'E': // receive command button commands { uint16_t cmdCombined = word(serialPayload[1], serialPayload[2]); if ( ((cmdCombined >= TS_CMD_INJ1_ON) && (cmdCombined <= TS_CMD_IGN8_50PC)) || (cmdCombined == TS_CMD_TEST_ENBL) || (cmdCombined == TS_CMD_TEST_DSBL) ) { //Hardware test buttons if (currentStatus.RPM == 0) { TS_CommandButtonsHandler(cmdCombined); } } else if( (cmdCombined >= TS_CMD_VSS_60KMH) && (cmdCombined <= TS_CMD_VSS_RATIO6) ) { //VSS Calibration commands TS_CommandButtonsHandler(cmdCombined); } else if( (cmdCombined >= TS_CMD_STM32_REBOOT) && (cmdCombined <= TS_CMD_STM32_BOOTLOADER) ) { //STM32 DFU mode button TS_CommandButtonsHandler(cmdCombined); } else if( (cmdCombined >= TS_CMD_SD_FORMAT) && (cmdCombined <= TS_CMD_SD_FORMAT) ) { //SD Commands TS_CommandButtonsHandler(cmdCombined); } sendSerialReturnCode(SERIAL_RC_OK); break; } case 'F': // send serial protocol version { byte serialVersion[] = {SERIAL_RC_OK, '0', '0', '2'}; sendSerialPayload(&serialVersion, 4); break; } case 'H': //Start the tooth logger currentStatus.toothLogEnabled = true; currentStatus.compositeLogEnabled = false; //Safety first (Should never be required) toothLogSendInProgress = false; BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY); toothHistoryIndex = 0; //Disconnect the standard interrupt and add the logger version detachInterrupt( digitalPinToInterrupt(pinTrigger) ); attachInterrupt( digitalPinToInterrupt(pinTrigger), loggerPrimaryISR, CHANGE ); detachInterrupt( digitalPinToInterrupt(pinTrigger2) ); attachInterrupt( digitalPinToInterrupt(pinTrigger2), loggerSecondaryISR, CHANGE ); sendSerialReturnCode(SERIAL_RC_OK); break; case 'h': //Stop the tooth logger currentStatus.toothLogEnabled = false; //Disconnect the logger interrupts and attach the normal ones detachInterrupt( digitalPinToInterrupt(pinTrigger) ); attachInterrupt( digitalPinToInterrupt(pinTrigger), triggerHandler, primaryTriggerEdge ); detachInterrupt( digitalPinToInterrupt(pinTrigger2) ); attachInterrupt( digitalPinToInterrupt(pinTrigger2), triggerSecondaryHandler, secondaryTriggerEdge ); sendSerialReturnCode(SERIAL_RC_OK); break; case 'I': // send CAN ID { byte serialVersion[] = {SERIAL_RC_OK, 0}; sendSerialPayload(&serialVersion, 2); break; } case 'J': //Start the composite logger currentStatus.compositeLogEnabled = true; currentStatus.toothLogEnabled = false; //Safety first (Should never be required) BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY); toothHistoryIndex = 0; //Disconnect the standard interrupt and add the logger version detachInterrupt( digitalPinToInterrupt(pinTrigger) ); attachInterrupt( digitalPinToInterrupt(pinTrigger), loggerPrimaryISR, CHANGE ); detachInterrupt( digitalPinToInterrupt(pinTrigger2) ); attachInterrupt( digitalPinToInterrupt(pinTrigger2), loggerSecondaryISR, CHANGE ); sendSerialReturnCode(SERIAL_RC_OK); break; case 'j': //Stop the composite logger currentStatus.compositeLogEnabled = false; //Disconnect the logger interrupts and attach the normal ones detachInterrupt( digitalPinToInterrupt(pinTrigger) ); attachInterrupt( digitalPinToInterrupt(pinTrigger), triggerHandler, primaryTriggerEdge ); detachInterrupt( digitalPinToInterrupt(pinTrigger2) ); attachInterrupt( digitalPinToInterrupt(pinTrigger2), triggerSecondaryHandler, secondaryTriggerEdge ); sendSerialReturnCode(SERIAL_RC_OK); break; case 'M': { //New write command //7 bytes required: //2 - Page identifier //2 - offset //2 - Length //1 - 1st New value byte offset1, offset2, length1, length2; uint8_t currentPage = serialPayload[2]; //Page ID is 2 bytes, but as the first byte is always 0 it can be ignored offset1 = serialPayload[3]; offset2 = serialPayload[4]; uint16_t valueOffset = word(offset2, offset1); length1 = serialPayload[5]; length2 = serialPayload[6]; uint16_t chunkSize = word(length2, length1); if( (valueOffset + chunkSize) > getPageSize(currentPage)) { //This should never happen, but just incase sendSerialReturnCode(SERIAL_RC_RANGE_ERR); break; } if(isEepromWritePending()) { enableForceBurn(); writeConfig(currentPage); disableForceBurn(); } //page_iterator_t entity = map_page_offset_to_entity(currentPage, valueOffset); for(uint16_t i = 0; i < chunkSize; i++) { setPageValue(currentPage, (valueOffset + i), serialPayload[7 + i]); } { //enableForceBurn(); writeConfig(currentPage); //disableForceBurn(); } sendSerialReturnCode(SERIAL_RC_OK); break; } /* * New method for sending page values (MS command equivalent is 'r') */ case 'p': { //6 bytes required: //2 - Page identifier //2 - offset //2 - Length byte offset1, offset2, length1, length2; int length; byte tempPage; tempPage = serialPayload[2]; offset1 = serialPayload[3]; offset2 = serialPayload[4]; valueOffset = word(offset2, offset1); length1 = serialPayload[5]; length2 = serialPayload[6]; length = word(length2, length1); //Setup the transmit buffer serialPayload[0] = SERIAL_RC_OK; for(int i = 0; i < length; i++) { serialPayload[i+1] = getPageValue(tempPage, valueOffset + i); } sendSerialPayload(&serialPayload, (length + 1)); break; } case 'Q': // send code version { //char productString[] = { SERIAL_RC_OK, 's','p','e','e','d','u','i','n','o',' ','2','0','2','1','0','9','-','d','e','v'} ; //Note no null terminator in array and statu variable at the start char productString[] = { SERIAL_RC_OK, 's','p','e','e','d','u','i','n','o',' ','2','0','2','2','0','2'} ; //Note no null terminator in array and statu variable at the start sendSerialPayload(&productString, sizeof(productString)); break; } case 'r': //New format for the optimised OutputChannels { uint8_t cmd = serialPayload[2]; uint16_t offset = word(serialPayload[4], serialPayload[3]); uint16_t length = word(serialPayload[6], serialPayload[5]); #ifdef RTC_ENABLED uint16_t SD_arg1 = word(serialPayload[3], serialPayload[4]); uint16_t SD_arg2 = word(serialPayload[5], serialPayload[6]); #endif if(cmd == 0x30) //Send output channels command 0x30 is 48dec { generateLiveValues(offset, length); sendSerialPayload(&serialPayload, (length + 1)); } #ifdef RTC_ENABLED else if(cmd == SD_RTC_PAGE) //Request to read SD card RTC { serialPayload[0] = SERIAL_RC_OK; serialPayload[1] = rtc_getSecond(); //Seconds serialPayload[2] = rtc_getMinute(); //Minutes serialPayload[3] = rtc_getHour(); //Hours serialPayload[4] = rtc_getDOW(); //Day of week serialPayload[5] = rtc_getDay(); //Day of month serialPayload[6] = rtc_getMonth(); //Month serialPayload[7] = highByte(rtc_getYear()); //Year serialPayload[8] = lowByte(rtc_getYear()); //Year sendSerialPayload(&serialPayload, 9); } else if(cmd == SD_READWRITE_PAGE) //Request SD card extended parameters { //SD read commands use the offset and length fields to indicate the request type if((SD_arg1 == SD_READ_STAT_ARG1) && (SD_arg2 == SD_READ_STAT_ARG2)) { //Read the status of the SD card serialPayload[0] = SERIAL_RC_OK; serialPayload[1] = currentStatus.TS_SD_Status; serialPayload[2] = 0; //Error code //Sector size = 512 serialPayload[3] = 2; serialPayload[4] = 0; //Max blocks (4 bytes) uint32_t sectors = sectorCount(); serialPayload[5] = ((sectors >> 24) & 255); serialPayload[6] = ((sectors >> 16) & 255); serialPayload[7] = ((sectors >> 8) & 255); serialPayload[8] = (sectors & 255); /* serialPayload[5] = 0; serialPayload[6] = 0x20; //1gb dummy card serialPayload[7] = 0; serialPayload[8] = 0; */ //Max roots (Number of files) uint16_t numLogFiles = getNextSDLogFileNumber() - 2; // -1 because this returns the NEXT file name not the current one and -1 because TS expects a 0 based index serialPayload[9] = highByte(numLogFiles); serialPayload[10] = lowByte(numLogFiles); //Dir Start (4 bytes) serialPayload[11] = 0; serialPayload[12] = 0; serialPayload[13] = 0; serialPayload[14] = 0; //Unkown purpose for last 2 bytes serialPayload[15] = 0; serialPayload[16] = 0; sendSerialPayload(&serialPayload, 17); } else if((SD_arg1 == SD_READ_DIR_ARG1) && (SD_arg2 == SD_READ_DIR_ARG2)) { //Send file details serialPayload[0] = SERIAL_RC_OK; uint16_t logFileNumber = (SDcurrentDirChunk * 16) + 1; uint8_t filesInCurrentChunk = 0; uint16_t payloadIndex = 1; while((filesInCurrentChunk < 16) && (getSDLogFileDetails(&serialPayload[payloadIndex], logFileNumber) == true)) { logFileNumber++; filesInCurrentChunk++; payloadIndex += 32; } serialPayload[payloadIndex] = lowByte(SDcurrentDirChunk); serialPayload[payloadIndex + 1] = highByte(SDcurrentDirChunk); //Serial.print("Index:"); //Serial.print(payloadIndex); sendSerialPayload(&serialPayload, (payloadIndex + 2)); } } else if(cmd == SD_READFILE_PAGE) { //Fetch data from file if(SD_arg2 == SD_READ_COMP_ARG2) { //arg1 is the block number to return serialSDTransmitPayload[0] = SERIAL_RC_OK; serialSDTransmitPayload[1] = highByte(SD_arg1); serialSDTransmitPayload[2] = lowByte(SD_arg1); uint32_t currentSector = SDreadStartSector + (SD_arg1 * 4); int32_t numSectorsToSend = 0; if(SDreadNumSectors > SDreadCompletedSectors) { numSectorsToSend = SDreadNumSectors - SDreadCompletedSectors; if(numSectorsToSend > 4) //Maximum of 4 sectors at a time { numSectorsToSend = 4; } } SDreadCompletedSectors += numSectorsToSend; if(numSectorsToSend <= 0) { sendSerialReturnCode(SERIAL_RC_OK); } else { readSDSectors(&serialSDTransmitPayload[3], currentSector, numSectorsToSend); sendSerialPayload(&serialSDTransmitPayload, (numSectorsToSend * SD_SECTOR_SIZE + 3)); } } } #endif else { //No other r/ commands should be called } cmdPending = false; break; } case 'S': // send code version { //byte productString[] = { SERIAL_RC_OK, 'S', 'p', 'e', 'e', 'd', 'u', 'i', 'n', 'o', ' ', '2', '0', '2', '1', '.', '0', '9', '-', 'd', 'e', 'v'}; byte productString[] = { SERIAL_RC_OK, 'S', 'p', 'e', 'e', 'd', 'u', 'i', 'n', 'o', ' ', '2', '0', '2', '2', '0', '2'}; sendSerialPayload(&productString, sizeof(productString)); currentStatus.secl = 0; //This is required in TS3 due to its stricter timings break; } case 'T': //Send 256 tooth log entries to Tuner Studios tooth logger if(currentStatus.toothLogEnabled == true) { sendToothLog(0); } //Sends tooth log values as ints else if (currentStatus.compositeLogEnabled == true) { sendCompositeLog(0); } break; case 't': // receive new Calibration info. Command structure: "t", <tble_idx> <data array>. { uint8_t cmd = serialPayload[2]; uint16_t valueOffset = word(serialPayload[3], serialPayload[4]); uint16_t calibrationLength = word(serialPayload[5], serialPayload[6]); // Should be 256 if(cmd == O2_CALIBRATION_PAGE) { //TS sends a total of 1024 bytes of calibration data, broken up into 256 byte chunks //As we're using an interpolated 2D table, we only need to store 32 values out of this 1024 void* pnt_TargetTable_values = (uint8_t *)&o2Calibration_values; //Pointer that will be used to point to the required target table values uint16_t* pnt_TargetTable_bins = (uint16_t *)&o2Calibration_bins; //Pointer that will be used to point to the required target table bins //Read through the current chunk (Should be 256 bytes long) for(uint16_t x = 0; x < calibrationLength; x++) { //Only apply every 32nd value if( (x % 32) == 0 ) { uint16_t totalOffset = valueOffset + x; ((uint8_t*)pnt_TargetTable_values)[(totalOffset/32)] = serialPayload[x+7]; //O2 table stores 8 bit values pnt_TargetTable_bins[(totalOffset/32)] = (totalOffset); } } sendSerialReturnCode(SERIAL_RC_OK); Serial.flush(); //This is safe because engine is assumed to not be running during calibration //Check if this is the final chunk of calibration data #ifdef CORE_STM32 //STM32 requires TS to send 16 x 64 bytes chunk rather than 4 x 256 bytes. if(valueOffset == (64*15)) { writeCalibrationPage(cmd); } //Store received values in EEPROM if this is the final chunk of calibration #else if(valueOffset == (256*3)) { writeCalibrationPage(cmd); } //Store received values in EEPROM if this is the final chunk of calibration #endif } else if(cmd == IAT_CALIBRATION_PAGE) { void* pnt_TargetTable_values = (uint16_t *)&iatCalibration_values; uint16_t* pnt_TargetTable_bins = (uint16_t *)&iatCalibration_bins; //Temperature calibrations are sent as 32 16-bit values (ie 64 bytes total) if(calibrationLength == 64) { for (uint16_t x = 0; x < 32; x++) { int16_t tempValue = (int16_t)(word(serialPayload[((2 * x) + 8)], serialPayload[((2 * x) + 7)])); //Combine the 2 bytes into a single, signed 16-bit value tempValue = div(tempValue, 10).quot; //TS sends values multipled by 10 so divide back to whole degrees. tempValue = ((tempValue - 32) * 5) / 9; //Convert from F to C //Apply the temp offset and check that it results in all values being positive tempValue = tempValue + CALIBRATION_TEMPERATURE_OFFSET; if (tempValue < 0) { tempValue = 0; } ((uint16_t*)pnt_TargetTable_values)[x] = tempValue; //Both temp tables have 16-bit values pnt_TargetTable_bins[x] = (x * 32U); } writeCalibration(); sendSerialReturnCode(SERIAL_RC_OK); } else { sendSerialReturnCode(SERIAL_RC_RANGE_ERR); } } else if(cmd == CLT_CALIBRATION_PAGE) { void* pnt_TargetTable_values = (uint16_t *)&cltCalibration_values; uint16_t* pnt_TargetTable_bins = (uint16_t *)&cltCalibration_bins; //Temperature calibrations are sent as 32 16-bit values if(calibrationLength == 64) { for (uint16_t x = 0; x < 32; x++) { int16_t tempValue = (int16_t)(word(serialPayload[((2 * x) + 8)], serialPayload[((2 * x) + 7)])); //Combine the 2 bytes into a single, signed 16-bit value tempValue = div(tempValue, 10).quot; //TS sends values multipled by 10 so divide back to whole degrees. tempValue = ((tempValue - 32) * 5) / 9; //Convert from F to C //Apply the temp offset and check that it results in all values being positive tempValue = tempValue + CALIBRATION_TEMPERATURE_OFFSET; if (tempValue < 0) { tempValue = 0; } ((uint16_t*)pnt_TargetTable_values)[x] = tempValue; //Both temp tables have 16-bit values pnt_TargetTable_bins[x] = (x * 32U); } writeCalibration(); sendSerialReturnCode(SERIAL_RC_OK); } else { sendSerialReturnCode(SERIAL_RC_RANGE_ERR); } } else { sendSerialReturnCode(SERIAL_RC_RANGE_ERR); } break; } case 'U': //User wants to reset the Arduino (probably for FW update) if (resetControl != RESET_CONTROL_DISABLED) { #ifndef SMALL_FLASH_MODE if (!cmdPending) { Serial.println(F("Comms halted. Next byte will reset the Arduino.")); } #endif while (Serial.available() == 0) { } digitalWrite(pinResetControl, LOW); } else { #ifndef SMALL_FLASH_MODE if (!cmdPending) { Serial.println(F("Reset control is currently disabled.")); } #endif } break; case 'w': { #ifdef RTC_ENABLED uint8_t cmd = serialPayload[2]; uint16_t SD_arg1 = word(serialPayload[3], serialPayload[4]); uint16_t SD_arg2 = word(serialPayload[5], serialPayload[6]); if(cmd == SD_READWRITE_PAGE) { if((SD_arg1 == SD_WRITE_DO_ARG1) && (SD_arg2 == SD_WRITE_DO_ARG2)) { /* SD DO command. Single byte of data where the commands are: 0 Reset 1 Reset 2 Stop logging 3 Start logging 4 Load status variable 5 Init SD card */ uint8_t command = serialPayload[7]; if(command == 2) { endSDLogging(); manualLogActive = false; } else if(command == 3) { beginSDLogging(); manualLogActive = true; } else if(command == 4) { setTS_SD_status(); } //else if(command == 5) { initSD(); } sendSerialReturnCode(SERIAL_RC_OK); } else if((SD_arg1 == SD_WRITE_DIR_ARG1) && (SD_arg2 == SD_WRITE_DIR_ARG2)) { //Begin SD directory read. Value in payload represents the directory chunk to read //Directory chunks are each 16 files long SDcurrentDirChunk = word(serialPayload[7], serialPayload[8]); sendSerialReturnCode(SERIAL_RC_OK); } else if((SD_arg1 == SD_WRITE_SEC_ARG1) && (SD_arg2 == SD_WRITE_SEC_ARG2)) { //SD write sector command } else if((SD_arg1 == SD_ERASEFILE_ARG1) && (SD_arg2 == SD_ERASEFILE_ARG2)) { //Erase file command //We just need the 4 ASCII characters of the file name char log1 = serialPayload[7]; char log2 = serialPayload[8]; char log3 = serialPayload[9]; char log4 = serialPayload[10]; deleteLogFile(log1, log2, log3, log4); sendSerialReturnCode(SERIAL_RC_OK); } else if((SD_arg1 == SD_SPD_TEST_ARG1) && (SD_arg2 == SD_SPD_TEST_ARG2)) { //Perform a speed test on the SD card //First 4 bytes are the sector number to write to uint32_t sector; uint8_t sector1 = serialPayload[7]; uint8_t sector2 = serialPayload[8]; uint8_t sector3 = serialPayload[9]; uint8_t sector4 = serialPayload[10]; sector = (sector1 << 24) | (sector2 << 16) | (sector3 << 8) | sector4; //Last 4 bytes are the number of sectors to test uint32_t testSize; uint8_t testSize1 = serialPayload[11]; uint8_t testSize2 = serialPayload[12]; uint8_t testSize3 = serialPayload[13]; uint8_t testSize4 = serialPayload[14]; testSize = (testSize1 << 24) | (testSize2 << 16) | (testSize3 << 8) | testSize4; sendSerialReturnCode(SERIAL_RC_OK); } else if((SD_arg1 == SD_WRITE_COMP_ARG1) && (SD_arg2 == SD_WRITE_COMP_ARG2)) { //Prepare to read a 2024 byte chunk of data from the SD card uint8_t sector1 = serialPayload[7]; uint8_t sector2 = serialPayload[8]; uint8_t sector3 = serialPayload[9]; uint8_t sector4 = serialPayload[10]; //SDreadStartSector = (sector1 << 24) | (sector2 << 16) | (sector3 << 8) | sector4; SDreadStartSector = (sector4 << 24) | (sector3 << 16) | (sector2 << 8) | sector1; //SDreadStartSector = sector4 | (sector3 << 8) | (sector2 << 16) | (sector1 << 24); //Next 4 bytes are the number of sectors to write uint8_t sectorCount1 = serialPayload[11]; uint8_t sectorCount2 = serialPayload[12]; uint8_t sectorCount3 = serialPayload[13]; uint8_t sectorCount4 = serialPayload[14]; SDreadNumSectors = (sectorCount1 << 24) | (sectorCount2 << 16) | (sectorCount3 << 8) | sectorCount4; //Reset the sector counter SDreadCompletedSectors = 0; sendSerialReturnCode(SERIAL_RC_OK); } } else if(cmd == SD_RTC_PAGE) { cmdPending = false; //Used for setting RTC settings if((SD_arg1 == SD_RTC_WRITE_ARG1) && (SD_arg2 == SD_RTC_WRITE_ARG2)) { //Set the RTC date/time byte second = serialPayload[7]; byte minute = serialPayload[8]; byte hour = serialPayload[9]; //byte dow = serialPayload[10]; //Not used byte day = serialPayload[11]; byte month = serialPayload[12]; uint16_t year = word(serialPayload[13], serialPayload[14]); rtc_setTime(second, minute, hour, day, month, year); sendSerialReturnCode(SERIAL_RC_OK); } } #endif break; } default: //Unknown command sendSerialReturnCode(SERIAL_RC_UKWN_ERR); break; } } /** Send a status record back to tuning/logging SW. * This will "live" information from @ref currentStatus struct. * @param offset - Start field number * @param packetLength - Length of actual message (after possible ack/confirm headers) * E.g. tuning sw command 'A' (Send all values) will send data from field number 0, LOG_ENTRY_SIZE fields. */ //void sendValues(int packetlength, byte portNum) void generateLiveValues(uint16_t offset, uint16_t packetLength) { if(requestCount == 0) { currentStatus.secl = 0; } requestCount++; currentStatus.spark ^= (-currentStatus.hasSync ^ currentStatus.spark) & (1U << BIT_SPARK_SYNC); //Set the sync bit of the Spark variable to match the hasSync variable serialPayload[0] = SERIAL_RC_OK; for(byte x=0; x<packetLength; x++) { serialPayload[x+1] = getTSLogEntry(offset+x); } // Reset any flags that are being used to trigger page refreshes BIT_CLEAR(currentStatus.status3, BIT_STATUS3_VSS_REFRESH); } namespace { inline void send_table_values(table_value_iterator it) { while (!it.at_end()) { auto row = *it; Serial.write(&*row, row.size()); ++it; } } inline void send_table_axis(table_axis_iterator it) { while (!it.at_end()) { Serial.write((byte)*it); ++it; } } } /** * */ void sendToothLog(byte startOffset) { //We need TOOTH_LOG_SIZE number of records to send to TunerStudio. If there aren't that many in the buffer then we just return and wait for the next call if (BIT_CHECK(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY)) //Sanity check. Flagging system means this should always be true { uint32_t CRC32_val = 0; if(startOffset == 0) { //Transmit the size of the packet uint16_t totalPayloadLength = (TOOTH_LOG_SIZE * 4) + 1; //Size of the tooth log (uint32_t values) plus the return code Serial.write(totalPayloadLength >> 8); Serial.write(totalPayloadLength); //Begin new CRC hash const uint8_t returnCode = SERIAL_RC_OK; CRC32_val = CRC32.crc32(&returnCode, 1, false); //Send the return code Serial.write(returnCode); } for (int x = startOffset; x < TOOTH_LOG_SIZE; x++) { //Check whether the tx buffer still has space if(Serial.availableForWrite() < 4) { //tx buffer is full. Store the current state so it can be resumed later inProgressOffset = x; toothLogSendInProgress = true; return; } //Transmit the tooth time uint32_t tempToothHistory = toothHistory[x]; uint8_t toothHistory_1 = ((tempToothHistory >> 24) & 255); uint8_t toothHistory_2 = ((tempToothHistory >> 16) & 255); uint8_t toothHistory_3 = ((tempToothHistory >> 8) & 255); uint8_t toothHistory_4 = ((tempToothHistory) & 255); Serial.write(toothHistory_1); Serial.write(toothHistory_2); Serial.write(toothHistory_3); Serial.write(toothHistory_4); //Update the CRC CRC32_val = CRC32.crc32_upd(&toothHistory_1, 1, false); CRC32_val = CRC32.crc32_upd(&toothHistory_2, 1, false); CRC32_val = CRC32.crc32_upd(&toothHistory_3, 1, false); CRC32_val = CRC32.crc32_upd(&toothHistory_4, 1, false); } BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY); cmdPending = false; toothLogSendInProgress = false; toothHistoryIndex = 0; //Apply the CRC reflection CRC32_val = ~CRC32_val; //Send the CRC Serial.write( ((CRC32_val >> 24) & 255) ); Serial.write( ((CRC32_val >> 16) & 255) ); Serial.write( ((CRC32_val >> 8) & 255) ); Serial.write( (CRC32_val & 255) ); } else { sendSerialReturnCode(SERIAL_RC_BUSY_ERR); cmdPending = false; toothLogSendInProgress = false; } } void sendCompositeLog(byte startOffset) { if ( (BIT_CHECK(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY)) || (compositeLogSendInProgress == true) ) //Sanity check. Flagging system means this should always be true { BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY); uint32_t CRC32_val = 0; if(startOffset == 0) { inProgressCompositeTime = 0; //Transmit the size of the packet uint16_t totalPayloadLength = (TOOTH_LOG_SIZE * 5) + 1; //Size of the tooth log (1x uint32_t + 1x uint8_t values) plus the return code Serial.write(totalPayloadLength >> 8); Serial.write(totalPayloadLength); //Begin new CRC hash const uint8_t returnCode = SERIAL_RC_OK; CRC32_val = CRC32.crc32(&returnCode, 1, false); //Send the return code Serial.write(returnCode); } for (int x = startOffset; x < TOOTH_LOG_SIZE; x++) { //Check whether the tx buffer still has space if(Serial.availableForWrite() < 5) { //tx buffer is full. Store the current state so it can be resumed later inProgressOffset = x; compositeLogSendInProgress = true; return; } inProgressCompositeTime = toothHistory[x]; //This combined runtime (in us) that the log was going for by this record uint8_t inProgressCompositeTime_1 = (inProgressCompositeTime >> 24) & 255; uint8_t inProgressCompositeTime_2 = (inProgressCompositeTime >> 16) & 255; uint8_t inProgressCompositeTime_3 = (inProgressCompositeTime >> 8) & 255; uint8_t inProgressCompositeTime_4 = (inProgressCompositeTime) & 255; //Transmit the tooth time Serial.write(inProgressCompositeTime_1); Serial.write(inProgressCompositeTime_2); Serial.write(inProgressCompositeTime_3); Serial.write(inProgressCompositeTime_4); //Update the CRC CRC32_val = CRC32.crc32_upd(&inProgressCompositeTime_1, 1, false); CRC32_val = CRC32.crc32_upd(&inProgressCompositeTime_2, 1, false); CRC32_val = CRC32.crc32_upd(&inProgressCompositeTime_3, 1, false); CRC32_val = CRC32.crc32_upd(&inProgressCompositeTime_4, 1, false); //The status byte (Indicates the trigger edge, whether it was a pri/sec pulse, the sync status) uint8_t statusByte = compositeLogHistory[x]; Serial.write(statusByte); //Update the CRC with the status byte CRC32_val = CRC32.crc32_upd(&statusByte, 1, false); } BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY); toothHistoryIndex = 0; cmdPending = false; compositeLogSendInProgress = false; inProgressCompositeTime = 0; //Apply the CRC reflection CRC32_val = ~CRC32_val; //Send the CRC Serial.write( ((CRC32_val >> 24) & 255) ); Serial.write( ((CRC32_val >> 16) & 255) ); Serial.write( ((CRC32_val >> 8) & 255) ); Serial.write( (CRC32_val & 255) ); } else { sendSerialReturnCode(SERIAL_RC_BUSY_ERR); cmdPending = false; compositeLogSendInProgress = false; } }
38,283
C++
.cpp
922
34.0282
235
0.637975
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,540,000
table3d.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/table3d.cpp
#include <stdlib.h> #include "table3d.h" // =============================== Iterators ========================= table_value_iterator rows_begin(const void *pTable, table_type_t key) { #define CTA_GET_ROW_ITERATOR(size, xDomain, yDomain, pTable) \ return ((TABLE3D_TYPENAME_BASE(size, xDomain, yDomain)*)pTable)->values.begin(); CONCRETE_TABLE_ACTION(key, CTA_GET_ROW_ITERATOR, pTable); } /** * Convert page iterator to table x axis iterator. */ table_axis_iterator x_begin(const void *pTable, table_type_t key) { #define CTA_GET_X_ITERATOR(size, xDomain, yDomain, pTable) \ return ((TABLE3D_TYPENAME_BASE(size, xDomain, yDomain)*)pTable)->axisX.begin(); CONCRETE_TABLE_ACTION(key, CTA_GET_X_ITERATOR, pTable); } /** * Convert page iterator to table y axis iterator. */ table_axis_iterator y_begin(const void *pTable, table_type_t key) { #define CTA_GET_Y_ITERATOR(size, xDomain, yDomain, pTable) \ return ((TABLE3D_TYPENAME_BASE(size, xDomain, yDomain)*)pTable)->axisY.begin(); CONCRETE_TABLE_ACTION(key, CTA_GET_Y_ITERATOR, pTable); }
1,075
C++
.cpp
27
37.37037
86
0.689358
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,540,001
comms.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/comms.cpp
/* Speeduino - Simple engine management for the Arduino Mega 2560 platform Copyright (C) Josh Stewart A full copy of the license may be found in the projects root directory */ /** @file * Process Incoming and outgoing serial communications. */ #include "globals.h" #include "comms.h" #include "cancomms.h" #include "storage.h" #include "maths.h" #include "utilities.h" #include "decoders.h" #include "TS_CommandButtonHandler.h" #include "errors.h" #include "pages.h" #include "page_crc.h" #include "logger.h" #ifdef RTC_ENABLED #include "rtc_common.h" #endif byte currentPage = 1;//Not the same as the speeduino config page numbers bool isMap = true; /**< Whether or not the currentPage contains only a 3D map that would require translation */ unsigned long requestCount = 0; /**< The number of times the A command has been issued. This is used to track whether a reset has recently been performed on the controller */ byte currentCommand; /**< The serial command that is currently being processed. This is only useful when cmdPending=True */ bool cmdPending = false; /**< Whether or not a serial request has only been partially received. This occurs when a command character has been received in the serial buffer, but not all of its arguments have yet been received. If true, the active command will be stored in the currentCommand variable */ bool chunkPending = false; /**< Whether or not the current chunk write is complete or not */ uint16_t chunkComplete = 0; /**< The number of bytes in a chunk write that have been written so far */ uint16_t chunkSize = 0; /**< The complete size of the requested chunk write */ int valueOffset; /**< The memory offset within a given page for a value to be read from or written to. Note that we cannot use 'offset' as a variable name, it is a reserved word for several teensy libraries */ byte tsCanId = 0; // current tscanid requested byte inProgressOffset; byte inProgressLength; uint32_t inProgressCompositeTime; bool serialInProgress = false; bool toothLogSendInProgress = false; bool compositeLogSendInProgress = false; bool legacySerial = false; /** Processes the incoming data on the serial buffer based on the command sent. Can be either data for a new command or a continuation of data for command that is already in progress: - cmdPending = If a command has started but is wairing on further data to complete - chunkPending = Specifically for the new receive value method where TS will send a known number of contiguous bytes to be written to a table Comands are single byte (letter symbol) commands. */ void command() { if ( (cmdPending == false) && (legacySerial == false) ) { currentCommand = Serial.read(); } switch (currentCommand) { case 'a': cmdPending = true; if (Serial.available() >= 2) { Serial.read(); //Ignore the first value, it's always 0 Serial.read(); //Ignore the second value, it's always 6 sendValuesLegacy(); cmdPending = false; } break; case 'A': // send x bytes of realtime values sendValues(0, LOG_ENTRY_SIZE, 0x31, 0); //send values to serial0 break; case 'B': // Burn current values to eeprom writeAllConfig(); break; case 'b': // New EEPROM burn command to only burn a single page at a time cmdPending = true; if (Serial.available() >= 2) { Serial.read(); //Ignore the first table value, it's always 0 writeConfig(Serial.read()); cmdPending = false; } break; case 'C': // test communications. This is used by Tunerstudio to see whether there is an ECU on a given serial port testComm(); break; case 'c': //Send the current loops/sec value Serial.write(lowByte(currentStatus.loopsPerSecond)); Serial.write(highByte(currentStatus.loopsPerSecond)); break; case 'd': // Send a CRC32 hash of a given page cmdPending = true; if (Serial.available() >= 2) { Serial.read(); //Ignore the first byte value, it's always 0 uint32_t CRC32_val = calculatePageCRC32( Serial.read() ); //Split the 4 bytes of the CRC32 value into individual bytes and send Serial.write( ((CRC32_val >> 24) & 255) ); Serial.write( ((CRC32_val >> 16) & 255) ); Serial.write( ((CRC32_val >> 8) & 255) ); Serial.write( (CRC32_val & 255) ); cmdPending = false; } break; case 'E': // receive command button commands cmdPending = true; if(Serial.available() >= 2) { byte cmdGroup = Serial.read(); byte cmdValue = Serial.read(); uint16_t cmdCombined = word(cmdGroup, cmdValue); if ( ((cmdCombined >= TS_CMD_INJ1_ON) && (cmdCombined <= TS_CMD_IGN8_50PC)) || (cmdCombined == TS_CMD_TEST_ENBL) || (cmdCombined == TS_CMD_TEST_DSBL) ) { //Hardware test buttons if (currentStatus.RPM == 0) { TS_CommandButtonsHandler(cmdCombined); } cmdPending = false; } else if( (cmdCombined >= TS_CMD_VSS_60KMH) && (cmdCombined <= TS_CMD_VSS_RATIO6) ) { //VSS Calibration commands TS_CommandButtonsHandler(cmdCombined); cmdPending = false; } else if( (cmdCombined >= TS_CMD_STM32_REBOOT) && (cmdCombined <= TS_CMD_STM32_BOOTLOADER) ) { //STM32 DFU mode button TS_CommandButtonsHandler(cmdCombined); cmdPending = false; } } break; case 'F': // send serial protocol version Serial.print(F("001")); break; case 'H': //Start the tooth logger currentStatus.toothLogEnabled = true; currentStatus.compositeLogEnabled = false; //Safety first (Should never be required) BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY); toothHistoryIndex = 0; //Disconnect the standard interrupt and add the logger version detachInterrupt( digitalPinToInterrupt(pinTrigger) ); attachInterrupt( digitalPinToInterrupt(pinTrigger), loggerPrimaryISR, CHANGE ); detachInterrupt( digitalPinToInterrupt(pinTrigger2) ); attachInterrupt( digitalPinToInterrupt(pinTrigger2), loggerSecondaryISR, CHANGE ); Serial.write(1); //TS needs an acknowledgement that this was received. I don't know if this is the correct response, but it seems to work break; case 'h': //Stop the tooth logger currentStatus.toothLogEnabled = false; //Disconnect the logger interrupts and attach the normal ones detachInterrupt( digitalPinToInterrupt(pinTrigger) ); attachInterrupt( digitalPinToInterrupt(pinTrigger), triggerHandler, primaryTriggerEdge ); detachInterrupt( digitalPinToInterrupt(pinTrigger2) ); attachInterrupt( digitalPinToInterrupt(pinTrigger2), triggerSecondaryHandler, secondaryTriggerEdge ); break; case 'J': //Start the composite logger currentStatus.compositeLogEnabled = true; currentStatus.toothLogEnabled = false; //Safety first (Should never be required) BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY); toothHistoryIndex = 0; //Disconnect the standard interrupt and add the logger version detachInterrupt( digitalPinToInterrupt(pinTrigger) ); attachInterrupt( digitalPinToInterrupt(pinTrigger), loggerPrimaryISR, CHANGE ); detachInterrupt( digitalPinToInterrupt(pinTrigger2) ); attachInterrupt( digitalPinToInterrupt(pinTrigger2), loggerSecondaryISR, CHANGE ); Serial.write(1); //TS needs an acknowledgement that this was received. I don't know if this is the correct response, but it seems to work break; case 'j': //Stop the composite logger currentStatus.compositeLogEnabled = false; //Disconnect the logger interrupts and attach the normal ones detachInterrupt( digitalPinToInterrupt(pinTrigger) ); attachInterrupt( digitalPinToInterrupt(pinTrigger), triggerHandler, primaryTriggerEdge ); detachInterrupt( digitalPinToInterrupt(pinTrigger2) ); attachInterrupt( digitalPinToInterrupt(pinTrigger2), triggerSecondaryHandler, secondaryTriggerEdge ); break; case 'L': // List the contents of current page in human readable form #ifndef SMALL_FLASH_MODE sendPageASCII(); #endif break; case 'm': //Send the current free memory currentStatus.freeRAM = freeRam(); Serial.write(lowByte(currentStatus.freeRAM)); Serial.write(highByte(currentStatus.freeRAM)); break; case 'N': // Displays a new line. Like pushing enter in a text editor Serial.println(); break; case 'P': // set the current page //This is a legacy function and is no longer used by TunerStudio. It is maintained for compatibility with other systems //A 2nd byte of data is required after the 'P' specifying the new page number. cmdPending = true; if (Serial.available() > 0) { currentPage = Serial.read(); //This converts the ascii number char into binary. Note that this will break everyything if there are ever more than 48 pages (48 = asci code for '0') if ((currentPage >= '0') && (currentPage <= '9')) // 0 - 9 { currentPage -= 48; } else if ((currentPage >= 'a') && (currentPage <= 'f')) // 10 - 15 { currentPage -= 87; } else if ((currentPage >= 'A') && (currentPage <= 'F')) { currentPage -= 55; } // Detecting if the current page is a table/map if ( (currentPage == veMapPage) || (currentPage == ignMapPage) || (currentPage == afrMapPage) || (currentPage == fuelMap2Page) || (currentPage == ignMap2Page) ) { isMap = true; } else { isMap = false; } cmdPending = false; } break; /* * New method for sending page values */ case 'p': cmdPending = true; //6 bytes required: //2 - Page identifier //2 - offset //2 - Length if(Serial.available() >= 6) { byte offset1, offset2, length1, length2; int length; byte tempPage; Serial.read(); // First byte of the page identifier can be ignored. It's always 0 tempPage = Serial.read(); //currentPage = 1; offset1 = Serial.read(); offset2 = Serial.read(); valueOffset = word(offset2, offset1); length1 = Serial.read(); length2 = Serial.read(); length = word(length2, length1); for(int i = 0; i < length; i++) { Serial.write( getPageValue(tempPage, valueOffset + i) ); } cmdPending = false; } break; case 'Q': // send code version Serial.print(F("speeduino 202202")); break; case 'r': //New format for the optimised OutputChannels cmdPending = true; byte cmd; if (Serial.available() >= 6) { tsCanId = Serial.read(); //Read the $tsCanId cmd = Serial.read(); // read the command uint16_t offset, length; byte tmp; tmp = Serial.read(); offset = word(Serial.read(), tmp); tmp = Serial.read(); length = word(Serial.read(), tmp); if(cmd == 0x30) //Send output channels command 0x30 is 48dec { sendValues(offset, length, cmd, 0); } else { //No other r/ commands are supported in legacy mode } cmdPending = false; } break; case 'S': // send code version Serial.print(F("Speeduino 2022.02")); currentStatus.secl = 0; //This is required in TS3 due to its stricter timings break; case 'T': //Send 256 tooth log entries to Tuner Studios tooth logger //6 bytes required: //2 - Page identifier //2 - offset //2 - Length cmdPending = true; if(Serial.available() >= 6) { Serial.read(); // First byte of the page identifier can be ignored. It's always 0 Serial.read(); // First byte of the page identifier can be ignored. It's always 0 Serial.read(); // First byte of the page identifier can be ignored. It's always 0 Serial.read(); // First byte of the page identifier can be ignored. It's always 0 Serial.read(); // First byte of the page identifier can be ignored. It's always 0 Serial.read(); // First byte of the page identifier can be ignored. It's always 0 if(currentStatus.toothLogEnabled == true) { sendToothLog_old(0); } //Sends tooth log values as ints else if (currentStatus.compositeLogEnabled == true) { sendCompositeLog_old(0); } cmdPending = false; } break; case 't': // receive new Calibration info. Command structure: "t", <tble_idx> <data array>. byte tableID; //byte canID; //The first 2 bytes sent represent the canID and tableID while (Serial.available() == 0) { } tableID = Serial.read(); //Not currently used for anything receiveCalibration(tableID); //Receive new values and store in memory writeCalibration(); //Store received values in EEPROM break; case 'U': //User wants to reset the Arduino (probably for FW update) if (resetControl != RESET_CONTROL_DISABLED) { #ifndef SMALL_FLASH_MODE if (!cmdPending) { Serial.println(F("Comms halted. Next byte will reset the Arduino.")); } #endif while (Serial.available() == 0) { } digitalWrite(pinResetControl, LOW); } else { #ifndef SMALL_FLASH_MODE if (!cmdPending) { Serial.println(F("Reset control is currently disabled.")); } #endif } break; case 'V': // send VE table and constants in binary sendPage(); break; case 'W': // receive new VE obr constant at 'W'+<offset>+<newbyte> cmdPending = true; if (isMap) { if(Serial.available() >= 3) // 1 additional byte is required on the MAP pages which are larger than 255 bytes { byte offset1, offset2; offset1 = Serial.read(); offset2 = Serial.read(); valueOffset = word(offset2, offset1); setPageValue(currentPage, valueOffset, Serial.read()); cmdPending = false; } } else { if(Serial.available() >= 2) { valueOffset = Serial.read(); setPageValue(currentPage, valueOffset, Serial.read()); cmdPending = false; } } break; case 'M': cmdPending = true; if(chunkPending == false) { //This means it's a new request //7 bytes required: //2 - Page identifier //2 - offset //2 - Length //1 - 1st New value if(Serial.available() >= 7) { byte offset1, offset2, length1, length2; Serial.read(); // First byte of the page identifier can be ignored. It's always 0 currentPage = Serial.read(); //currentPage = 1; offset1 = Serial.read(); offset2 = Serial.read(); valueOffset = word(offset2, offset1); length1 = Serial.read(); length2 = Serial.read(); chunkSize = word(length2, length1); //Regular page data chunkPending = true; chunkComplete = 0; } } //This CANNOT be an else of the above if statement as chunkPending gets set to true above if(chunkPending == true) { while( (Serial.available() > 0) && (chunkComplete < chunkSize) ) { setPageValue(currentPage, (valueOffset + chunkComplete), Serial.read()); chunkComplete++; } if(chunkComplete >= chunkSize) { cmdPending = false; chunkPending = false; } } break; case 'w': //No w commands are supported in legacy mode. This should never be called if(Serial.available() >= 7) { byte offset1, offset2, length1, length2; Serial.read(); // First byte of the page identifier can be ignored. It's always 0 currentPage = Serial.read(); //currentPage = 1; offset1 = Serial.read(); offset2 = Serial.read(); valueOffset = word(offset2, offset1); length1 = Serial.read(); length2 = Serial.read(); chunkSize = word(length2, length1); } break; case 'Z': //Totally non-standard testing function. Will be removed once calibration testing is completed. This function takes 1.5kb of program space! :S #ifndef SMALL_FLASH_MODE Serial.println(F("Coolant")); for (int x = 0; x < 32; x++) { Serial.print(cltCalibration_bins[x]); Serial.print(", "); Serial.println(cltCalibration_values[x]); } Serial.println(F("Inlet temp")); for (int x = 0; x < 32; x++) { Serial.print(iatCalibration_bins[x]); Serial.print(", "); Serial.println(iatCalibration_values[x]); } Serial.println(F("O2")); for (int x = 0; x < 32; x++) { Serial.print(o2Calibration_bins[x]); Serial.print(", "); Serial.println(o2Calibration_values[x]); } Serial.println(F("WUE")); for (int x = 0; x < 10; x++) { Serial.print(configPage4.wueBins[x]); Serial.print(F(", ")); Serial.println(configPage2.wueValues[x]); } Serial.flush(); #endif break; case 'z': //Send 256 tooth log entries to a terminal emulator sendToothLog_old(0); //Sends tooth log values as chars break; case '`': //Custom 16u2 firmware is making its presence known cmdPending = true; if (Serial.available() >= 1) { configPage4.bootloaderCaps = Serial.read(); cmdPending = false; } break; case '?': #ifndef SMALL_FLASH_MODE Serial.println (F( "\n" "===Command Help===\n\n" "All commands are single character and are concatenated with their parameters \n" "without spaces." "Syntax: <command>+<parameter1>+<parameter2>+<parameterN>\n\n" "===List of Commands===\n\n" "A - Displays 31 bytes of currentStatus values in binary (live data)\n" "B - Burn current map and configPage values to eeprom\n" "C - Test COM port. Used by Tunerstudio to see whether an ECU is on a given serial \n" " port. Returns a binary number.\n" "N - Print new line.\n" "P - Set current page. Syntax: P+<pageNumber>\n" "R - Same as A command\n" "S - Display signature number\n" "Q - Same as S command\n" "V - Display map or configPage values in binary\n" "W - Set one byte in map or configPage. Expects binary parameters. \n" " Syntax: W+<offset>+<newbyte>\n" "t - Set calibration values. Expects binary parameters. Table index is either 0, \n" " 1, or 2. Syntax: t+<tble_idx>+<newValue1>+<newValue2>+<newValueN>\n" "Z - Display calibration values\n" "T - Displays 256 tooth log entries in binary\n" "r - Displays 256 tooth log entries\n" "U - Prepare for firmware update. The next byte received will cause the Arduino to reset.\n" "? - Displays this help page" )); #endif break; default: Serial.println(F("Err: Unknown cmd")); cmdPending = false; break; } } /** Send a status record back to tuning/logging SW. * This will "live" information from @ref currentStatus struct. * @param offset - Start field number * @param packetLength - Length of actual message (after possible ack/confirm headers) * @param cmd - ??? - Will be used as some kind of ack on CANSerial * @param portNum - Port number (0=Serial, 3=CANSerial) * E.g. tuning sw command 'A' (Send all values) will send data from field number 0, LOG_ENTRY_SIZE fields. * @return the current values of a fixed group of variables */ //void sendValues(int packetlength, byte portNum) void sendValues(uint16_t offset, uint16_t packetLength, byte cmd, byte portNum) { if (portNum == 3) { //CAN serial #if defined(USE_SERIAL3) if (cmd == 30) { CANSerial.write("r"); //confirm cmd type CANSerial.write(cmd); } else if (cmd == 31) { CANSerial.write("A"); } //confirm cmd type #else UNUSED(cmd); #endif } else { if(requestCount == 0) { currentStatus.secl = 0; } requestCount++; } currentStatus.spark ^= (-currentStatus.hasSync ^ currentStatus.spark) & (1U << BIT_SPARK_SYNC); //Set the sync bit of the Spark variable to match the hasSync variable for(byte x=0; x<packetLength; x++) { if (portNum == 0) { Serial.write(getTSLogEntry(offset+x)); } #if defined(CANSerial_AVAILABLE) else if (portNum == 3){ CANSerial.write(getTSLogEntry(offset+x)); } #endif //Check whether the tx buffer still has space if(Serial.availableForWrite() < 1) { //tx buffer is full. Store the current state so it can be resumed later inProgressOffset = offset + x + 1; inProgressLength = packetLength - x - 1; serialInProgress = true; return; } } serialInProgress = false; // Reset any flags that are being used to trigger page refreshes BIT_CLEAR(currentStatus.status3, BIT_STATUS3_VSS_REFRESH); } void sendValuesLegacy() { uint16_t temp; int bytestosend = 114; bytestosend -= Serial.write(currentStatus.secl>>8); bytestosend -= Serial.write(currentStatus.secl); bytestosend -= Serial.write(currentStatus.PW1>>8); bytestosend -= Serial.write(currentStatus.PW1); bytestosend -= Serial.write(currentStatus.PW2>>8); bytestosend -= Serial.write(currentStatus.PW2); bytestosend -= Serial.write(currentStatus.RPM>>8); bytestosend -= Serial.write(currentStatus.RPM); temp = currentStatus.advance * 10; bytestosend -= Serial.write(temp>>8); bytestosend -= Serial.write(temp); bytestosend -= Serial.write(currentStatus.nSquirts); bytestosend -= Serial.write(currentStatus.engine); bytestosend -= Serial.write(currentStatus.afrTarget); bytestosend -= Serial.write(currentStatus.afrTarget); // send twice so afrtgt1 == afrtgt2 bytestosend -= Serial.write(99); // send dummy data as we don't have wbo2_en1 bytestosend -= Serial.write(99); // send dummy data as we don't have wbo2_en2 temp = currentStatus.baro * 10; bytestosend -= Serial.write(temp>>8); bytestosend -= Serial.write(temp); temp = currentStatus.MAP * 10; bytestosend -= Serial.write(temp>>8); bytestosend -= Serial.write(temp); temp = currentStatus.IAT * 10; bytestosend -= Serial.write(temp>>8); bytestosend -= Serial.write(temp); temp = currentStatus.coolant * 10; bytestosend -= Serial.write(temp>>8); bytestosend -= Serial.write(temp); temp = currentStatus.TPS * 10; bytestosend -= Serial.write(temp>>8); bytestosend -= Serial.write(temp); bytestosend -= Serial.write(currentStatus.battery10>>8); bytestosend -= Serial.write(currentStatus.battery10); bytestosend -= Serial.write(currentStatus.O2>>8); bytestosend -= Serial.write(currentStatus.O2); bytestosend -= Serial.write(currentStatus.O2_2>>8); bytestosend -= Serial.write(currentStatus.O2_2); bytestosend -= Serial.write(99); // knock bytestosend -= Serial.write(99); // knock temp = currentStatus.egoCorrection * 10; bytestosend -= Serial.write(temp>>8); // egocor1 bytestosend -= Serial.write(temp); // egocor1 bytestosend -= Serial.write(temp>>8); // egocor2 bytestosend -= Serial.write(temp); // egocor2 temp = currentStatus.iatCorrection * 10; bytestosend -= Serial.write(temp>>8); // aircor bytestosend -= Serial.write(temp); // aircor temp = currentStatus.wueCorrection * 10; bytestosend -= Serial.write(temp>>8); // warmcor bytestosend -= Serial.write(temp); // warmcor bytestosend -= Serial.write(99); // accelEnrich bytestosend -= Serial.write(99); // accelEnrich bytestosend -= Serial.write(99); // tpsFuelCut bytestosend -= Serial.write(99); // tpsFuelCut bytestosend -= Serial.write(99); // baroCorrection bytestosend -= Serial.write(99); // baroCorrection temp = currentStatus.corrections * 10; bytestosend -= Serial.write(temp>>8); // gammaEnrich bytestosend -= Serial.write(temp); // gammaEnrich temp = currentStatus.VE * 10; bytestosend -= Serial.write(temp>>8); // ve1 bytestosend -= Serial.write(temp); // ve1 temp = currentStatus.VE2 * 10; bytestosend -= Serial.write(temp>>8); // ve2 bytestosend -= Serial.write(temp); // ve2 bytestosend -= Serial.write(99); // iacstep bytestosend -= Serial.write(99); // iacstep bytestosend -= Serial.write(99); // cold_adv_deg bytestosend -= Serial.write(99); // cold_adv_deg temp = currentStatus.tpsDOT * 10; bytestosend -= Serial.write(temp>>8); // TPSdot bytestosend -= Serial.write(temp); // TPSdot temp = currentStatus.mapDOT * 10; bytestosend -= Serial.write(temp >> 8); // MAPdot bytestosend -= Serial.write(temp); // MAPdot temp = currentStatus.dwell * 10; bytestosend -= Serial.write(temp>>8); // dwell bytestosend -= Serial.write(temp); // dwell bytestosend -= Serial.write(99); // MAF bytestosend -= Serial.write(99); // MAF bytestosend -= Serial.write(currentStatus.fuelLoad*10); // fuelload bytestosend -= Serial.write(99); // fuelcor bytestosend -= Serial.write(99); // fuelcor bytestosend -= Serial.write(99); // portStatus temp = currentStatus.advance1 * 10; bytestosend -= Serial.write(temp>>8); bytestosend -= Serial.write(temp); temp = currentStatus.advance2 * 10; bytestosend -= Serial.write(temp>>8); bytestosend -= Serial.write(temp); for(int i = 0; i < bytestosend; i++) { // send dummy data to fill remote's buffer Serial.write(99); } } namespace { void send_raw_entity(const page_iterator_t &entity) { Serial.write((byte *)entity.pData, entity.size); } inline void send_table_values(table_value_iterator it) { while (!it.at_end()) { auto row = *it; Serial.write(&*row, row.size()); ++it; } } inline void send_table_axis(table_axis_iterator it) { while (!it.at_end()) { Serial.write((byte)*it); ++it; } } void send_table_entity(const page_iterator_t &entity) { send_table_values(rows_begin(entity)); send_table_axis(x_begin(entity)); send_table_axis(y_begin(entity)); } void send_entity(const page_iterator_t &entity) { switch (entity.type) { case Raw: return send_raw_entity(entity); break; case Table: return send_table_entity(entity); break; case NoEntity: // No-op break; default: abort(); break; } } } /** Pack the data within the current page (As set with the 'P' command) into a buffer and send it. * * Creates a page iterator by @ref page_begin() (See: pages.cpp). Sends page given in @ref currentPage. * * Note that some translation of the data is required to lay it out in the way Megasqurit / TunerStudio expect it. * Data is sent in binary format, as defined by in each page in the speeduino.ini. */ void sendPage() { page_iterator_t entity = page_begin(currentPage); while (entity.type!=End) { send_entity(entity); entity = advance(entity); } } namespace { /// Prints each element in the memory byte range (*first, *last). void serial_println_range(const byte *first, const byte *last) { while (first!=last) { Serial.println(*first); ++first; } } void serial_println_range(const uint16_t *first, const uint16_t *last) { while (first!=last) { Serial.println(*first); ++first; } } void serial_print_space_delimited(const byte *first, const byte *last) { while (first!=last) { Serial.print(*first);// This displays the values horizantially on the screen Serial.print(F(" ")); ++first; } Serial.println(); } #define serial_print_space_delimited_array(array) serial_print_space_delimited(array, _end_range_address(array)) void serial_print_prepadding(byte value) { if (value < 100) { Serial.print(F(" ")); if (value < 10) { Serial.print(F(" ")); } } } void serial_print_prepadded_value(byte value) { serial_print_prepadding(value); Serial.print(value); Serial.print(F(" ")); } void print_row(const table_axis_iterator &y_it, table_row_iterator row) { serial_print_prepadded_value((byte)*y_it); while (!row.at_end()) { serial_print_prepadded_value(*row); ++row; } Serial.println(); } void print_x_axis(const void *pTable, table_type_t key) { Serial.print(F(" ")); auto x_it = x_begin(pTable, key); while(!x_it.at_end()) { serial_print_prepadded_value((byte)*x_it); ++x_it; } } void serial_print_3dtable(const void *pTable, table_type_t key) { auto y_it = y_begin(pTable, key); auto row_it = rows_begin(pTable, key); while (!row_it.at_end()) { print_row(y_it, *row_it); ++y_it; ++row_it; } print_x_axis(pTable, key); Serial.println(); } } /** Send page as ASCII for debugging purposes. * Similar to sendPage(), however data is sent in human readable format. Sends page given in @ref currentPage. * * This is used for testing only (Not used by TunerStudio) in order to see current map and config data without the need for TunerStudio. */ void sendPageASCII() { switch (currentPage) { case veMapPage: Serial.println(F("\nVE Map")); serial_print_3dtable(&fuelTable, fuelTable.type_key); break; case veSetPage: Serial.println(F("\nPg 2 Cfg")); // The following loop displays in human readable form of all byte values in config page 1 up to but not including the first array. serial_println_range((byte *)&configPage2, configPage2.wueValues); serial_print_space_delimited_array(configPage2.wueValues); // This displays all the byte values between the last array up to but not including the first unsigned int on config page 1 serial_println_range(_end_range_byte_address(configPage2.wueValues), (byte*)&configPage2.injAng); // The following loop displays four unsigned ints serial_println_range(configPage2.injAng, configPage2.injAng + _countof(configPage2.injAng)); // Following loop displays byte values between the unsigned ints serial_println_range(_end_range_byte_address(configPage2.injAng), (byte*)&configPage2.mapMax); Serial.println(configPage2.mapMax); // Following loop displays remaining byte values of the page serial_println_range(&configPage2.fpPrime, (byte *)&configPage2 + sizeof(configPage2)); break; case ignMapPage: Serial.println(F("\nIgnition Map")); serial_print_3dtable(&ignitionTable, ignitionTable.type_key); break; case ignSetPage: Serial.println(F("\nPg 4 Cfg")); Serial.println(configPage4.triggerAngle);// configPage4.triggerAngle is an int so just display it without complication // Following loop displays byte values after that first int up to but not including the first array in config page 2 serial_println_range((byte*)&configPage4.FixAng, configPage4.taeBins); serial_print_space_delimited_array(configPage4.taeBins); serial_print_space_delimited_array(configPage4.taeValues); serial_print_space_delimited_array(configPage4.wueBins); Serial.println(configPage4.dwellLimit);// Little lonely byte stuck between two arrays. No complications just display it. serial_print_space_delimited_array(configPage4.dwellCorrectionValues); serial_println_range(_end_range_byte_address(configPage4.dwellCorrectionValues), (byte *)&configPage4 + sizeof(configPage4)); break; case afrMapPage: Serial.println(F("\nAFR Map")); serial_print_3dtable(&afrTable, afrTable.type_key); break; case afrSetPage: Serial.println(F("\nPg 6 Config")); serial_println_range((byte *)&configPage6, configPage6.voltageCorrectionBins); serial_print_space_delimited_array(configPage6.voltageCorrectionBins); serial_print_space_delimited_array(configPage6.injVoltageCorrectionValues); serial_print_space_delimited_array(configPage6.airDenBins); serial_print_space_delimited_array(configPage6.airDenRates); serial_println_range(_end_range_byte_address(configPage6.airDenRates), configPage6.iacCLValues); serial_print_space_delimited_array(configPage6.iacCLValues); serial_print_space_delimited_array(configPage6.iacOLStepVal); serial_print_space_delimited_array(configPage6.iacOLPWMVal); serial_print_space_delimited_array(configPage6.iacBins); serial_print_space_delimited_array(configPage6.iacCrankSteps); serial_print_space_delimited_array(configPage6.iacCrankDuty); serial_print_space_delimited_array(configPage6.iacCrankBins); // Following loop is for remaining byte value of page serial_println_range(_end_range_byte_address(configPage6.iacCrankBins), (byte *)&configPage6 + sizeof(configPage6)); break; case boostvvtPage: Serial.println(F("\nBoost Map")); serial_print_3dtable(&boostTable, boostTable.type_key); Serial.println(F("\nVVT Map")); serial_print_3dtable(&vvtTable, vvtTable.type_key); break; case seqFuelPage: Serial.println(F("\nTrim 1 Table")); serial_print_3dtable(&trim1Table, trim1Table.type_key); break; case canbusPage: Serial.println(F("\nPage 9 Cfg")); serial_println_range((byte *)&configPage9, (byte *)&configPage9 + sizeof(configPage9)); break; case fuelMap2Page: Serial.println(F("\n2nd Fuel Map")); serial_print_3dtable(&fuelTable2, fuelTable2.type_key); break; case ignMap2Page: Serial.println(F("\n2nd Ignition Map")); serial_print_3dtable(&ignitionTable2, ignitionTable2.type_key); break; case warmupPage: case progOutsPage: default: #ifndef SMALL_FLASH_MODE Serial.println(F("\nPage has not been implemented yet")); #endif break; } } /** Processes an incoming stream of calibration data (for CLT, IAT or O2) from TunerStudio. * Result is store in EEPROM and memory. * * @param tableID - calibration table to process. 0 = Coolant Sensor. 1 = IAT Sensor. 2 = O2 Sensor. */ void receiveCalibration(byte tableID) { void* pnt_TargetTable_values; //Pointer that will be used to point to the required target table values uint16_t* pnt_TargetTable_bins; //Pointer that will be used to point to the required target table bins int OFFSET, DIVISION_FACTOR; switch (tableID) { case 0: //coolant table pnt_TargetTable_values = (uint16_t *)&cltCalibration_values; pnt_TargetTable_bins = (uint16_t *)&cltCalibration_bins; OFFSET = CALIBRATION_TEMPERATURE_OFFSET; // DIVISION_FACTOR = 10; break; case 1: //Inlet air temp table pnt_TargetTable_values = (uint16_t *)&iatCalibration_values; pnt_TargetTable_bins = (uint16_t *)&iatCalibration_bins; OFFSET = CALIBRATION_TEMPERATURE_OFFSET; DIVISION_FACTOR = 10; break; case 2: //O2 table //pnt_TargetTable = (byte *)&o2CalibrationTable; pnt_TargetTable_values = (uint8_t *)&o2Calibration_values; pnt_TargetTable_bins = (uint16_t *)&o2Calibration_bins; OFFSET = 0; DIVISION_FACTOR = 1; break; default: OFFSET = 0; pnt_TargetTable_values = (uint16_t *)&iatCalibration_values; pnt_TargetTable_bins = (uint16_t *)&iatCalibration_bins; DIVISION_FACTOR = 10; break; //Should never get here, but if we do, just fail back to main loop } int16_t tempValue; byte tempBuffer[2]; if(tableID == 2) { //O2 calibration. Comes through as 1024 8-bit values of which we use every 32nd for (int x = 0; x < 1024; x++) { while ( Serial.available() < 1 ) {} tempValue = Serial.read(); if( (x % 32) == 0) { ((uint8_t*)pnt_TargetTable_values)[(x/32)] = (byte)tempValue; //O2 table stores 8 bit values pnt_TargetTable_bins[(x/32)] = (x); } } } else { //Temperature calibrations are sent as 32 16-bit values for (uint16_t x = 0; x < 32; x++) { while ( Serial.available() < 2 ) {} tempBuffer[0] = Serial.read(); tempBuffer[1] = Serial.read(); tempValue = (int16_t)(word(tempBuffer[1], tempBuffer[0])); //Combine the 2 bytes into a single, signed 16-bit value tempValue = div(tempValue, DIVISION_FACTOR).quot; //TS sends values multipled by 10 so divide back to whole degrees. tempValue = ((tempValue - 32) * 5) / 9; //Convert from F to C //Apply the temp offset and check that it results in all values being positive tempValue = tempValue + OFFSET; if (tempValue < 0) { tempValue = 0; } ((uint16_t*)pnt_TargetTable_values)[x] = tempValue; //Both temp tables have 16-bit values pnt_TargetTable_bins[x] = (x * 32U); writeCalibration(); } } writeCalibration(); } /** Send 256 tooth log entries to serial. * if useChar is true, the values are sent as chars to be printed out by a terminal emulator * if useChar is false, the values are sent as a 2 byte integer which is readable by TunerStudios tooth logger */ void sendToothLog_old(byte startOffset) { //We need TOOTH_LOG_SIZE number of records to send to TunerStudio. If there aren't that many in the buffer then we just return and wait for the next call if (BIT_CHECK(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY)) //Sanity check. Flagging system means this should always be true { for (int x = startOffset; x < TOOTH_LOG_SIZE; x++) { //Check whether the tx buffer still has space if(Serial.availableForWrite() < 4) { //tx buffer is full. Store the current state so it can be resumed later inProgressOffset = x; toothLogSendInProgress = true; return; } Serial.write(toothHistory[x] >> 24); Serial.write(toothHistory[x] >> 16); Serial.write(toothHistory[x] >> 8); Serial.write(toothHistory[x]); } BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY); cmdPending = false; toothLogSendInProgress = false; toothHistoryIndex = 0; } else { //TunerStudio has timed out, send a LOG of all 0s for(int x = 0; x < (4*TOOTH_LOG_SIZE); x++) { Serial.write(static_cast<byte>(0x00)); //GCC9 fix } cmdPending = false; } } void sendCompositeLog_old(byte startOffset) { if (BIT_CHECK(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY)) //Sanity check. Flagging system means this should always be true { if(startOffset == 0) { inProgressCompositeTime = 0; } for (int x = startOffset; x < TOOTH_LOG_SIZE; x++) { //Check whether the tx buffer still has space if(Serial.availableForWrite() < 4) { //tx buffer is full. Store the current state so it can be resumed later inProgressOffset = x; compositeLogSendInProgress = true; return; } inProgressCompositeTime = toothHistory[x]; //This combined runtime (in us) that the log was going for by this record) Serial.write(inProgressCompositeTime >> 24); Serial.write(inProgressCompositeTime >> 16); Serial.write(inProgressCompositeTime >> 8); Serial.write(inProgressCompositeTime); Serial.write(compositeLogHistory[x]); //The status byte (Indicates the trigger edge, whether it was a pri/sec pulse, the sync status) } BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY); toothHistoryIndex = 0; cmdPending = false; compositeLogSendInProgress = false; inProgressCompositeTime = 0; } else { //TunerStudio has timed out, send a LOG of all 0s for(int x = 0; x < (5*TOOTH_LOG_SIZE); x++) { Serial.write(static_cast<byte>(0x00)); //GCC9 fix } cmdPending = false; } } void testComm() { Serial.write(1); return; }
40,541
C++
.cpp
1,026
33.330409
302
0.660472
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,540,002
pages.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/pages.cpp
#include "pages.h" #include "globals.h" #include "utilities.h" // Maps from virtual page "addresses" to addresses/bytes of real in memory entities // // For TunerStudio: // 1. Each page has a numeric identifier (0 to N-1) // 2. A single page is a continguous block of data. // So individual bytes are identified by a (page number, offset) // // The TS layout is not what is in memory. E.g. // // TS Page 2 |0123456789ABCD|0123456789ABCDEF| // | | // Arduino In Memory |--- Entity A ---| |--- Entity B -----| // // Further, the in memory entity may also not be contiguous or in the same // order that TS expects // // So there is a 2 stage mapping: // 1. Page # + Offset to entity // 2. Offset to intra-entity byte // Page sizes as defined in the .ini file constexpr const uint16_t PROGMEM ini_page_sizes[] = { 0, 128, 288, 288, 128, 288, 128, 240, 384, 192, 192, 288, 192, 128, 288 }; // ========================= Table size calculations ========================= // Note that these should be computed at compile time, assuming the correct // calling context. template <class table_t> inline constexpr uint16_t get_table_value_end() { return table_t::xaxis_t::length*table_t::yaxis_t::length; } template <class table_t> inline constexpr uint16_t get_table_axisx_end() { return get_table_value_end<table_t>()+table_t::xaxis_t::length; } template <class table_t> inline constexpr uint16_t get_table_axisy_end(const table_t *) { return get_table_axisx_end<table_t>()+table_t::yaxis_t::length; } // ========================= Intra-table offset to byte class ========================= template<class table_t> class offset_to_table { public: // This class encapsulates mapping a linear offset to the various parts of a table // and exposing the linear offset as an mutable byte. // // Tables do not map linearly to the TS page address space, so special // handling is necessary (we do not use the normal array layout for // performance reasons elsewhere) // // We take the offset & map it to a single value, x-axis or y-axis element // // Using a template here is a performance boost - we can call functions that // are specialized per table type, which allows the compiler more optimization // opportunities. See get_table_value(). offset_to_table(table_t *pTable, uint16_t table_offset) : _pTable(pTable), _table_offset(table_offset) { } // Getter inline byte operator*() const { switch (get_table_location()) { case table_location_values: return get_value_value(); case table_location_xaxis: return *get_xaxis_value(); case table_location_yaxis: default: return *get_yaxis_value(); } } // Setter inline offset_to_table &operator=( byte new_value ) { switch (get_table_location()) { case table_location_values: get_value_value() = new_value; break; case table_location_xaxis: get_xaxis_value() = new_value; break; case table_location_yaxis: default: get_yaxis_value() = new_value; } invalidate_cache(&_pTable->get_value_cache); return *this; } private: inline byte& get_value_value() const { return _pTable->values.value_at((uint8_t)_table_offset); } inline int16_ref get_xaxis_value() const { return *_pTable->axisX.begin().advance(_table_offset - get_table_value_end<table_t>()); } inline int16_ref get_yaxis_value() const { return *_pTable->axisY.begin().advance(_table_offset - get_table_axisx_end<table_t>()); } enum table_location { table_location_values, table_location_xaxis, table_location_yaxis }; inline table_location get_table_location() const { if (_table_offset<get_table_value_end<table_t>()) { return table_location_values; } if (_table_offset<get_table_axisx_end<table_t>()) { return table_location_xaxis; } return table_location_yaxis; } table_t *_pTable; uint16_t _table_offset; }; // ========================= Offset to entity byte mapping ========================= inline byte& get_raw_location(page_iterator_t &entity, uint16_t offset) { return *((byte*)entity.pData + (offset-entity.start)); } inline byte get_table_value(page_iterator_t &entity, uint16_t offset) { #define CTA_GET_TABLE_VALUE(size, xDomain, yDomain, pTable, offset) \ return *offset_to_table<TABLE3D_TYPENAME_BASE(size, xDomain, yDomain)>((TABLE3D_TYPENAME_BASE(size, xDomain, yDomain)*)pTable, offset); CONCRETE_TABLE_ACTION(entity.table_key, CTA_GET_TABLE_VALUE, entity.pData, (offset-entity.start)); } inline byte get_value(page_iterator_t &entity, uint16_t offset) { if (Raw==entity.type) { return get_raw_location(entity, offset); } if (Table==entity.type) { return get_table_value(entity, offset); } return 0U; } inline void set_table_value(page_iterator_t &entity, uint16_t offset, byte new_value) { #define CTA_SET_TABLE_VALUE(size, xDomain, yDomain, pTable, offset, new_value) \ offset_to_table<TABLE3D_TYPENAME_BASE(size, xDomain, yDomain)>((TABLE3D_TYPENAME_BASE(size, xDomain, yDomain)*)pTable, offset) = new_value; break; CONCRETE_TABLE_ACTION(entity.table_key, CTA_SET_TABLE_VALUE, entity.pData, (offset-entity.start), new_value); } inline void set_value(page_iterator_t &entity, byte value, uint16_t offset) { if (Raw==entity.type) { get_raw_location(entity, offset) = value; } else if (Table==entity.type) { set_table_value(entity, offset, value); } } // ========================= Static page size computation & checking =================== // This will fail AND print the page number and required size template <uint8_t pageNum, uint16_t min> static inline void check_size() { static_assert(ini_page_sizes[pageNum] >= min, "Size is off!"); } // Since pages are a logical contiguous block, we can automatically compute the // logical start address of every item: the first one starts at zero, following // items must start at the end of the previous. #define _ENTITY_START(entityNum) entity ## entityNum ## Start #define ENTITY_START_VAR(entityNum) _ENTITY_START(entityNum) // Compute the start address of the next entity. We need this to be a constexpr // so we can static assert on it later. So we cannot increment an exiting var. #define DECLARE_NEXT_ENTITY_START(entityIndex, entitySize) \ constexpr uint16_t ENTITY_START_VAR( PP_INC(entityIndex) ) = ENTITY_START_VAR(entityIndex)+entitySize; // ========================= Logical page end processing =================== // The members of all page_iterator_t instances are compile time constants and // thus all page_iterator_t instances *could* be compile time constants. // // If we declare them inline as part of return statements, gcc recognises they // are constants (even without constexpr). Constants need to be stored somewhere: // gcc places them in the .data section, which is placed in SRAM :-(. // // So we would end up using several hundred bytes of SRAM. // // Instead we use this (and other) intermediate factory function(s) - it provides a barrier that // forces GCC to construct the page_iterator_t instance at runtime. inline const page_iterator_t create_end_iterator(uint8_t pageNum, uint16_t start) { return page_iterator_t { .pData = nullptr, .table_key = table_type_None, .page = pageNum, .start = start, .size = start, .type = End, }; } // Signal the end of a page #define END_OF_PAGE(pageNum, entityNum) \ check_size<pageNum, ENTITY_START_VAR(entityNum)>(); \ return create_end_iterator(pageNum, ENTITY_START_VAR(entityNum)); \ // ========================= Table processing =================== inline const page_iterator_t create_table_iterator(void *pTable, table_type_t key, uint8_t pageNum, uint16_t start, uint16_t size) { return page_iterator_t { .pData = pTable, .table_key = key, .page = pageNum, .start = start, .size = size, .type = Table, }; } // If the offset is in range, create a Table entity_t #define CHECK_TABLE(pageNum, offset, pTable, entityNum) \ if (offset < ENTITY_START_VAR(entityNum)+get_table_axisy_end(pTable)) \ { \ return create_table_iterator(pTable, (pTable)->type_key, \ pageNum, \ ENTITY_START_VAR(entityNum), get_table_axisy_end(pTable)); \ } \ DECLARE_NEXT_ENTITY_START(entityNum, get_table_axisy_end(pTable)) // ========================= Raw memory block processing =================== inline const page_iterator_t create_raw_iterator(void *pBuffer, uint8_t pageNum, uint16_t start, uint16_t size) { return page_iterator_t { .pData = pBuffer, .table_key = table_type_None, .page = pageNum, .start = start, .size = size, .type = Raw, }; } // If the offset is in range, create a Raw entity_t #define CHECK_RAW(pageNum, offset, pDataBlock, blockSize, entityNum) \ if (offset < ENTITY_START_VAR(entityNum)+blockSize) \ { \ return create_raw_iterator(pDataBlock, pageNum, ENTITY_START_VAR(entityNum), blockSize);\ } \ DECLARE_NEXT_ENTITY_START(entityNum, blockSize) // =============================================================================== // Does the heavy lifting of mapping page+offset to an entity // // Alternative implementation would be to encode the mapping into data structures // That uses flash memory, which is scarce. And it was too slow. static inline __attribute__((always_inline)) // <-- this is critical for performance page_iterator_t map_page_offset_to_entity(uint8_t pageNumber, uint16_t offset) { // The start address of the 1st entity in any page. static constexpr uint16_t ENTITY_START_VAR(0) = 0U; switch (pageNumber) { case 0: END_OF_PAGE(0, 0) case veMapPage: { CHECK_TABLE(veMapPage, offset, &fuelTable, 0) END_OF_PAGE(veMapPage, 1) } case ignMapPage: //Ignition settings page (Page 2) { CHECK_TABLE(ignMapPage, offset, &ignitionTable, 0) END_OF_PAGE(ignMapPage, 1) } case afrMapPage: //Air/Fuel ratio target settings page { CHECK_TABLE(afrMapPage, offset, &afrTable, 0) END_OF_PAGE(afrMapPage, 1) } case boostvvtPage: //Boost, VVT and staging maps (all 8x8) { CHECK_TABLE(boostvvtPage, offset, &boostTable, 0) CHECK_TABLE(boostvvtPage, offset, &vvtTable, 1) CHECK_TABLE(boostvvtPage, offset, &stagingTable, 2) END_OF_PAGE(boostvvtPage, 3) } case seqFuelPage: { CHECK_TABLE(seqFuelPage, offset, &trim1Table, 0) CHECK_TABLE(seqFuelPage, offset, &trim2Table, 1) CHECK_TABLE(seqFuelPage, offset, &trim3Table, 2) CHECK_TABLE(seqFuelPage, offset, &trim4Table, 3) CHECK_TABLE(seqFuelPage, offset, &trim5Table, 4) CHECK_TABLE(seqFuelPage, offset, &trim6Table, 5) CHECK_TABLE(seqFuelPage, offset, &trim7Table, 6) CHECK_TABLE(seqFuelPage, offset, &trim8Table, 7) END_OF_PAGE(seqFuelPage, 8) } case fuelMap2Page: { CHECK_TABLE(fuelMap2Page, offset, &fuelTable2, 0) END_OF_PAGE(fuelMap2Page, 1) } case wmiMapPage: { CHECK_TABLE(wmiMapPage, offset, &wmiTable, 0) CHECK_TABLE(wmiMapPage, offset, &vvt2Table, 1) CHECK_TABLE(wmiMapPage, offset, &dwellTable, 2) END_OF_PAGE(wmiMapPage, 3) } case ignMap2Page: { CHECK_TABLE(ignMap2Page, offset, &ignitionTable2, 0) END_OF_PAGE(ignMap2Page, 1) } case veSetPage: { CHECK_RAW(veSetPage, offset, &configPage2, sizeof(configPage2), 0) END_OF_PAGE(veSetPage, 1) } case ignSetPage: { CHECK_RAW(ignSetPage, offset, &configPage4, sizeof(configPage4), 0) END_OF_PAGE(ignSetPage, 1) } case afrSetPage: { CHECK_RAW(afrSetPage, offset, &configPage6, sizeof(configPage6), 0) END_OF_PAGE(afrSetPage, 1) } case canbusPage: { CHECK_RAW(canbusPage, offset, &configPage9, sizeof(configPage9), 0) END_OF_PAGE(canbusPage, 1) } case warmupPage: { CHECK_RAW(warmupPage, offset, &configPage10, sizeof(configPage10), 0) END_OF_PAGE(warmupPage, 1) } case progOutsPage: { CHECK_RAW(progOutsPage, offset, &configPage13, sizeof(configPage13), 0) END_OF_PAGE(progOutsPage, 1) } default: abort(); // Unkown page number. Not a lot we can do. break; } } // ====================================== External functions ==================================== uint8_t getPageCount() { return _countof(ini_page_sizes); } uint16_t getPageSize(byte pageNum) { return pgm_read_word(&(ini_page_sizes[pageNum])); } void setPageValue(byte pageNum, uint16_t offset, byte value) { page_iterator_t entity = map_page_offset_to_entity(pageNum, offset); set_value(entity, value, offset); } byte getPageValue(byte pageNum, uint16_t offset) { page_iterator_t entity = map_page_offset_to_entity(pageNum, offset); return get_value(entity, offset); } // Support iteration over a pages entities. // Check for entity.type==End page_iterator_t page_begin(byte pageNum) { return map_page_offset_to_entity(pageNum, 0U); } page_iterator_t advance(const page_iterator_t &it) { return map_page_offset_to_entity(it.page, it.start+it.size); } /** * Convert page iterator to table value iterator. */ table_value_iterator rows_begin(const page_iterator_t &it) { return rows_begin(it.pData, it.table_key); } /** * Convert page iterator to table x axis iterator. */ table_axis_iterator x_begin(const page_iterator_t &it) { return x_begin(it.pData, it.table_key); } /** * Convert page iterator to table y axis iterator. */ table_axis_iterator y_begin(const page_iterator_t &it) { return y_begin(it.pData, it.table_key); }
13,930
C++
.cpp
399
31.115288
152
0.669392
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,540,003
storage.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/storage.cpp
/* Speeduino - Simple engine management for the Arduino Mega 2560 platform Copyright (C) Josh Stewart A full copy of the license may be found in the projects root directory */ /** @file * Lower level ConfigPage*, Table2D, Table3D and EEPROM storage operations. */ #include "globals.h" #include EEPROM_LIB_H //This is defined in the board .h files #include "storage.h" #include "pages.h" //The maximum number of write operations that will be performed in one go. If we try to write to the EEPROM too fast (Each write takes ~3ms) then the rest of the system can hang) #if defined(CORE_STM32) || defined(CORE_TEENSY) & !defined(USE_SPI_EEPROM) #define EEPROM_MAX_WRITE_BLOCK 64 #else #define EEPROM_MAX_WRITE_BLOCK 30 #endif #define EEPROM_DATA_VERSION 0 // Calibration data is stored at the end of the EEPROM (This is in case any further calibration tables are needed as they are large blocks) #define STORAGE_END 0xFFF // Should be E2END? #define EEPROM_CALIBRATION_CLT_VALUES (STORAGE_END-sizeof(cltCalibration_values)) #define EEPROM_CALIBRATION_CLT_BINS (EEPROM_CALIBRATION_CLT_VALUES-sizeof(cltCalibration_bins)) #define EEPROM_CALIBRATION_IAT_VALUES (EEPROM_CALIBRATION_CLT_BINS-sizeof(iatCalibration_values)) #define EEPROM_CALIBRATION_IAT_BINS (EEPROM_CALIBRATION_IAT_VALUES-sizeof(iatCalibration_bins)) #define EEPROM_CALIBRATION_O2_VALUES (EEPROM_CALIBRATION_IAT_BINS-sizeof(o2Calibration_values)) #define EEPROM_CALIBRATION_O2_BINS (EEPROM_CALIBRATION_O2_VALUES-sizeof(o2Calibration_bins)) #define EEPROM_LAST_BARO (EEPROM_CALIBRATION_O2_BINS-1) static bool eepromWritesPending = false; static bool forceBurn = false; bool isEepromWritePending() { return eepromWritesPending; } /** Write all config pages to EEPROM. */ void writeAllConfig() { uint8_t pageCount = getPageCount(); uint8_t page = 1U; writeConfig(page++); while (page<pageCount && ( !eepromWritesPending || forceBurn ) ) { writeConfig(page++); } } void enableForceBurn() { forceBurn = true; } void disableForceBurn() { forceBurn = false; } // ================================= Internal write support =============================== struct write_location { eeprom_address_t address; uint16_t counter; /** Update byte to EEPROM by first comparing content and the need to write it. We only ever write to the EEPROM where the new value is different from the currently stored byte This is due to the limited write life of the EEPROM (Approximately 100,000 writes) */ void update(uint8_t value) { if (EEPROM.read(address)!=value) { EEPROM.write(address, value); ++counter; } } write_location& operator++() { ++address; return *this; } bool can_write() const { return (counter<=EEPROM_MAX_WRITE_BLOCK); } }; static inline write_location write_range(const byte *pStart, const byte *pEnd, write_location location) { while ( (location.can_write() || forceBurn) && pStart!=pEnd) { location.update(*pStart); ++pStart; ++location; } return location; } static inline write_location write(const table_row_iterator &row, write_location location) { return write_range(&*row, row.end(), location); } static inline write_location write(table_value_iterator it, write_location location) { while ((location.can_write() || forceBurn) && !it.at_end()) { location = write(*it, location); ++it; } return location; } static inline write_location write(table_axis_iterator it, write_location location) { while ((location.can_write() || forceBurn) && !it.at_end()) { location.update((byte)*it); ++location; ++it; } return location; } static inline write_location writeTable(const void *pTable, table_type_t key, write_location location) { return write(y_begin(pTable, key).reverse(), write(x_begin(pTable, key), write(rows_begin(pTable, key), location))); } // ================================= End write support =============================== /** Write a table or map to EEPROM storage. Takes the current configuration (config pages and maps) and writes them to EEPROM as per the layout defined in storage.h. */ void writeConfig(uint8_t pageNum) { write_location result = { 0, 0 }; switch(pageNum) { case veMapPage: /*--------------------------------------------------- | Fuel table (See storage.h for data layout) - Page 1 | 16x16 table itself + the 16 values along each of the axis -----------------------------------------------------*/ result = writeTable(&fuelTable, fuelTable.type_key, { EEPROM_CONFIG1_MAP, 0 }); break; case veSetPage: /*--------------------------------------------------- | Config page 2 (See storage.h for data layout) | 64 byte long config table -----------------------------------------------------*/ result = write_range((byte *)&configPage2, (byte *)&configPage2+sizeof(configPage2), { EEPROM_CONFIG2_START, 0 }); break; case ignMapPage: /*--------------------------------------------------- | Ignition table (See storage.h for data layout) - Page 1 | 16x16 table itself + the 16 values along each of the axis -----------------------------------------------------*/ result = writeTable(&ignitionTable, ignitionTable.type_key, { EEPROM_CONFIG3_MAP, 0 }); break; case ignSetPage: /*--------------------------------------------------- | Config page 2 (See storage.h for data layout) | 64 byte long config table -----------------------------------------------------*/ result = write_range((byte *)&configPage4, (byte *)&configPage4+sizeof(configPage4), { EEPROM_CONFIG4_START, 0 }); break; case afrMapPage: /*--------------------------------------------------- | AFR table (See storage.h for data layout) - Page 5 | 16x16 table itself + the 16 values along each of the axis -----------------------------------------------------*/ result = writeTable(&afrTable, afrTable.type_key, { EEPROM_CONFIG5_MAP, 0 }); break; case afrSetPage: /*--------------------------------------------------- | Config page 3 (See storage.h for data layout) | 64 byte long config table -----------------------------------------------------*/ result = write_range((byte *)&configPage6, (byte *)&configPage6+sizeof(configPage6), { EEPROM_CONFIG6_START, 0 }); break; case boostvvtPage: /*--------------------------------------------------- | Boost and vvt tables (See storage.h for data layout) - Page 8 | 8x8 table itself + the 8 values along each of the axis -----------------------------------------------------*/ result = writeTable(&boostTable, boostTable.type_key, { EEPROM_CONFIG7_MAP1, 0 }); result = writeTable(&vvtTable, vvtTable.type_key, { EEPROM_CONFIG7_MAP2, result.counter }); result = writeTable(&stagingTable, stagingTable.type_key, { EEPROM_CONFIG7_MAP3, result.counter }); break; case seqFuelPage: /*--------------------------------------------------- | Fuel trim tables (See storage.h for data layout) - Page 9 | 6x6 tables itself + the 6 values along each of the axis -----------------------------------------------------*/ result = writeTable(&trim1Table, trim1Table.type_key, { EEPROM_CONFIG8_MAP1, 0 }); result = writeTable(&trim2Table, trim2Table.type_key, { EEPROM_CONFIG8_MAP2, result.counter }); result = writeTable(&trim3Table, trim3Table.type_key, { EEPROM_CONFIG8_MAP3, result.counter }); result = writeTable(&trim4Table, trim4Table.type_key, { EEPROM_CONFIG8_MAP4, result.counter }); result = writeTable(&trim5Table, trim5Table.type_key, { EEPROM_CONFIG8_MAP5, result.counter }); result = writeTable(&trim6Table, trim6Table.type_key, { EEPROM_CONFIG8_MAP6, result.counter }); result = writeTable(&trim7Table, trim7Table.type_key, { EEPROM_CONFIG8_MAP7, result.counter }); result = writeTable(&trim8Table, trim8Table.type_key, { EEPROM_CONFIG8_MAP8, result.counter }); break; case canbusPage: /*--------------------------------------------------- | Config page 10 (See storage.h for data layout) | 192 byte long config table -----------------------------------------------------*/ result = write_range((byte *)&configPage9, (byte *)&configPage9+sizeof(configPage9), { EEPROM_CONFIG9_START, 0 }); break; case warmupPage: /*--------------------------------------------------- | Config page 11 (See storage.h for data layout) | 192 byte long config table -----------------------------------------------------*/ result = write_range((byte *)&configPage10, (byte *)&configPage10+sizeof(configPage10), { EEPROM_CONFIG10_START, 0}); break; case fuelMap2Page: /*--------------------------------------------------- | Fuel table 2 (See storage.h for data layout) | 16x16 table itself + the 16 values along each of the axis -----------------------------------------------------*/ result = writeTable(&fuelTable2, fuelTable2.type_key, { EEPROM_CONFIG11_MAP, 0 }); break; case wmiMapPage: /*--------------------------------------------------- | WMI and Dwell tables (See storage.h for data layout) - Page 12 | 8x8 WMI table itself + the 8 values along each of the axis | 8x8 VVT2 table + the 8 values along each of the axis | 4x4 Dwell table itself + the 4 values along each of the axis -----------------------------------------------------*/ result = writeTable(&wmiTable, wmiTable.type_key, { EEPROM_CONFIG12_MAP, 0 }); result = writeTable(&vvt2Table, vvt2Table.type_key, { EEPROM_CONFIG12_MAP2, result.counter }); result = writeTable(&dwellTable, dwellTable.type_key, { EEPROM_CONFIG12_MAP3, result.counter }); break; case progOutsPage: /*--------------------------------------------------- | Config page 13 (See storage.h for data layout) -----------------------------------------------------*/ result = write_range((byte *)&configPage13, (byte *)&configPage13+sizeof(configPage13), { EEPROM_CONFIG13_START, 0}); break; case ignMap2Page: /*--------------------------------------------------- | Ignition table (See storage.h for data layout) - Page 1 | 16x16 table itself + the 16 values along each of the axis -----------------------------------------------------*/ result = writeTable(&ignitionTable2, ignitionTable2.type_key, { EEPROM_CONFIG14_MAP, 0 }); break; default: break; } eepromWritesPending = !result.can_write(); } /** Reset all configPage* structs (2,4,6,9,10,13) and write them full of null-bytes. */ void resetConfigPages() { for (uint8_t page=1; page<getPageCount(); ++page) { page_iterator_t entity = page_begin(page); while (entity.type!=End) { if (entity.type==Raw) { memset(entity.pData, 0, entity.size); } entity = advance(entity); } } } // ================================= Internal read support =============================== /** Load range of bytes form EEPROM offset to memory. * @param address - start offset in EEPROM * @param pFirst - Start memory address * @param pLast - End memory address */ static inline eeprom_address_t load_range(eeprom_address_t address, byte *pFirst, const byte *pLast) { #if defined(CORE_AVR) // The generic code in the #else branch works but this provides a 45% speed up on AVR size_t size = pLast-pFirst; eeprom_read_block(pFirst, (void*)address, size); return address+size; #else for (; pFirst != pLast; ++address, (void)++pFirst) { *pFirst = EEPROM.read(address); } return address; #endif } static inline eeprom_address_t load(table_row_iterator row, eeprom_address_t address) { return load_range(address, &*row, row.end()); } static inline eeprom_address_t load(table_value_iterator it, eeprom_address_t address) { while (!it.at_end()) { address = load(*it, address); ++it; } return address; } static inline eeprom_address_t load(table_axis_iterator it, eeprom_address_t address) { while (!it.at_end()) { *it = EEPROM.read(address); ++address; ++it; } return address; } static inline eeprom_address_t loadTable(void *pTable, table_type_t key, eeprom_address_t address) { return load(y_begin(pTable, key).reverse(), load(x_begin(pTable, key), load(rows_begin(pTable, key), address))); } // ================================= End internal read support =============================== /** Load all config tables from storage. */ void loadConfig() { loadTable(&fuelTable, fuelTable.type_key, EEPROM_CONFIG1_MAP); load_range(EEPROM_CONFIG2_START, (byte *)&configPage2, (byte *)&configPage2+sizeof(configPage2)); //********************************************************************************************************************************************************************************* //IGNITION CONFIG PAGE (2) loadTable(&ignitionTable, ignitionTable.type_key, EEPROM_CONFIG3_MAP); load_range(EEPROM_CONFIG4_START, (byte *)&configPage4, (byte *)&configPage4+sizeof(configPage4)); //********************************************************************************************************************************************************************************* //AFR TARGET CONFIG PAGE (3) loadTable(&afrTable, afrTable.type_key, EEPROM_CONFIG5_MAP); load_range(EEPROM_CONFIG6_START, (byte *)&configPage6, (byte *)&configPage6+sizeof(configPage6)); //********************************************************************************************************************************************************************************* // Boost and vvt tables load loadTable(&boostTable, boostTable.type_key, EEPROM_CONFIG7_MAP1); loadTable(&vvtTable, vvtTable.type_key, EEPROM_CONFIG7_MAP2); loadTable(&stagingTable, stagingTable.type_key, EEPROM_CONFIG7_MAP3); //********************************************************************************************************************************************************************************* // Fuel trim tables load loadTable(&trim1Table, trim1Table.type_key, EEPROM_CONFIG8_MAP1); loadTable(&trim2Table, trim2Table.type_key, EEPROM_CONFIG8_MAP2); loadTable(&trim3Table, trim3Table.type_key, EEPROM_CONFIG8_MAP3); loadTable(&trim4Table, trim4Table.type_key, EEPROM_CONFIG8_MAP4); loadTable(&trim5Table, trim5Table.type_key, EEPROM_CONFIG8_MAP5); loadTable(&trim6Table, trim6Table.type_key, EEPROM_CONFIG8_MAP6); loadTable(&trim7Table, trim7Table.type_key, EEPROM_CONFIG8_MAP7); loadTable(&trim8Table, trim8Table.type_key, EEPROM_CONFIG8_MAP8); //********************************************************************************************************************************************************************************* //canbus control page load load_range(EEPROM_CONFIG9_START, (byte *)&configPage9, (byte *)&configPage9+sizeof(configPage9)); //********************************************************************************************************************************************************************************* //CONFIG PAGE (10) load_range(EEPROM_CONFIG10_START, (byte *)&configPage10, (byte *)&configPage10+sizeof(configPage10)); //********************************************************************************************************************************************************************************* //Fuel table 2 (See storage.h for data layout) loadTable(&fuelTable2, fuelTable2.type_key, EEPROM_CONFIG11_MAP); //********************************************************************************************************************************************************************************* // WMI, VVT2 and Dwell table load loadTable(&wmiTable, wmiTable.type_key, EEPROM_CONFIG12_MAP); loadTable(&vvt2Table, vvt2Table.type_key, EEPROM_CONFIG12_MAP2); loadTable(&dwellTable, dwellTable.type_key, EEPROM_CONFIG12_MAP3); //********************************************************************************************************************************************************************************* //CONFIG PAGE (13) load_range(EEPROM_CONFIG13_START, (byte *)&configPage13, (byte *)&configPage13+sizeof(configPage13)); //********************************************************************************************************************************************************************************* //SECOND IGNITION CONFIG PAGE (14) loadTable(&ignitionTable2, ignitionTable2.type_key, EEPROM_CONFIG14_MAP); //********************************************************************************************************************************************************************************* } /** Read the calibration information from EEPROM. This is separate from the config load as the calibrations do not exist as pages within the ini file for Tuner Studio. */ void loadCalibration() { // If you modify this function be sure to also modify writeCalibration(); // it should be a mirror image of this function. EEPROM.get(EEPROM_CALIBRATION_O2_BINS, o2Calibration_bins); EEPROM.get(EEPROM_CALIBRATION_O2_VALUES, o2Calibration_values); EEPROM.get(EEPROM_CALIBRATION_IAT_BINS, iatCalibration_bins); EEPROM.get(EEPROM_CALIBRATION_IAT_VALUES, iatCalibration_values); EEPROM.get(EEPROM_CALIBRATION_CLT_BINS, cltCalibration_bins); EEPROM.get(EEPROM_CALIBRATION_CLT_VALUES, cltCalibration_values); } /** Write calibration tables to EEPROM. This takes the values in the 3 calibration tables (Coolant, Inlet temp and O2) and saves them to the EEPROM. */ void writeCalibration() { // If you modify this function be sure to also modify loadCalibration(); // it should be a mirror image of this function. EEPROM.put(EEPROM_CALIBRATION_O2_BINS, o2Calibration_bins); EEPROM.put(EEPROM_CALIBRATION_O2_VALUES, o2Calibration_values); EEPROM.put(EEPROM_CALIBRATION_IAT_BINS, iatCalibration_bins); EEPROM.put(EEPROM_CALIBRATION_IAT_VALUES, iatCalibration_values); EEPROM.put(EEPROM_CALIBRATION_CLT_BINS, cltCalibration_bins); EEPROM.put(EEPROM_CALIBRATION_CLT_VALUES, cltCalibration_values); } void writeCalibrationPage(uint8_t pageNum) { if(pageNum == O2_CALIBRATION_PAGE) { EEPROM.put(EEPROM_CALIBRATION_O2_BINS, o2Calibration_bins); EEPROM.put(EEPROM_CALIBRATION_O2_VALUES, o2Calibration_values); } else if(pageNum == IAT_CALIBRATION_PAGE) { EEPROM.put(EEPROM_CALIBRATION_IAT_BINS, iatCalibration_bins); EEPROM.put(EEPROM_CALIBRATION_IAT_VALUES, iatCalibration_values); } else if(pageNum == CLT_CALIBRATION_PAGE) { EEPROM.put(EEPROM_CALIBRATION_CLT_BINS, cltCalibration_bins); EEPROM.put(EEPROM_CALIBRATION_CLT_VALUES, cltCalibration_values); } } static eeprom_address_t compute_crc_address(uint8_t pageNum) { return EEPROM_LAST_BARO-((getPageCount() - pageNum)*sizeof(uint32_t)); } /** Write CRC32 checksum to EEPROM. Takes a page number and CRC32 value then stores it in the relevant place in EEPROM @param pageNum - Config page number @param crcValue - CRC32 checksum */ void storePageCRC32(uint8_t pageNum, uint32_t crcValue) { EEPROM.put(compute_crc_address(pageNum), crcValue); } /** Retrieves and returns the 4 byte CRC32 checksum for a given page from EEPROM. @param pageNum - Config page number */ uint32_t readPageCRC32(uint8_t pageNum) { uint32_t crc32_val; return EEPROM.get(compute_crc_address(pageNum), crc32_val); } // Utility functions. // By having these in this file, it prevents other files from calling EEPROM functions directly. This is useful due to differences in the EEPROM libraries on different devces /// Read last stored barometer reading from EEPROM. byte readLastBaro() { return EEPROM.read(EEPROM_LAST_BARO); } /// Write last acquired arometer reading to EEPROM. void storeLastBaro(byte newValue) { EEPROM.update(EEPROM_LAST_BARO, newValue); } /// Read EEPROM current data format version (from offset EEPROM_DATA_VERSION). byte readEEPROMVersion() { return EEPROM.read(EEPROM_DATA_VERSION); } /// Store EEPROM current data format version (to offset EEPROM_DATA_VERSION). void storeEEPROMVersion(byte newVersion) { EEPROM.update(EEPROM_DATA_VERSION, newVersion); }
20,579
C++
.cpp
435
43.411494
181
0.58463
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,540,004
page_crc.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/page_crc.cpp
#include "globals.h" #include "page_crc.h" #include "pages.h" //#include "src/FastCRC/FastCRC.h" typedef uint32_t (FastCRC32::*pCrcCalc)(const uint8_t *, const uint16_t, bool); static inline uint32_t compute_raw_crc(const page_iterator_t &entity, pCrcCalc calcFunc) { return (CRC32.*calcFunc)((uint8_t*)entity.pData, entity.size, false); } static inline uint32_t compute_row_crc(const table_row_iterator &row, pCrcCalc calcFunc) { return (CRC32.*calcFunc)(&*row, row.size(), false); } static inline uint32_t compute_tablevalues_crc(table_value_iterator it, pCrcCalc calcFunc) { uint32_t crc = compute_row_crc(*it, calcFunc); ++it; while (!it.at_end()) { crc = compute_row_crc(*it, &FastCRC32::crc32_upd); ++it; } return crc; } static inline uint32_t compute_tableaxis_crc(table_axis_iterator it, uint32_t crc) { byte values[32]; // Fingers crossed we don't have a table bigger than 32x32 byte *pValue = values; while (!it.at_end()) { *pValue++ = (byte)*it; ++it; } return pValue-values==0 ? crc : CRC32.crc32_upd(values, pValue-values, false); } static inline uint32_t compute_table_crc(page_iterator_t &entity, pCrcCalc calcFunc) { return compute_tableaxis_crc(y_begin(entity), compute_tableaxis_crc(x_begin(entity), compute_tablevalues_crc(rows_begin(entity), calcFunc))); } static inline uint32_t pad_crc(uint16_t padding, uint32_t crc) { const uint8_t raw_value = 0u; while (padding>0) { crc = CRC32.crc32_upd(&raw_value, 1, false); --padding; } return crc; } static inline uint32_t compute_crc(page_iterator_t &entity, pCrcCalc calcFunc) { switch (entity.type) { case Raw: return compute_raw_crc(entity, calcFunc); break; case Table: return compute_table_crc(entity, calcFunc); break; case NoEntity: return pad_crc(entity.size, 0U); break; default: abort(); break; } } uint32_t calculatePageCRC32(byte pageNum) { page_iterator_t entity = page_begin(pageNum); // Initial CRC calc uint32_t crc = compute_crc(entity, &FastCRC32::crc32); entity = advance(entity); while (entity.type!=End) { crc = compute_crc(entity, &FastCRC32::crc32_upd /* Note that we are *updating* */); entity = advance(entity); } return ~pad_crc(getPageSize(pageNum) - entity.size, crc); }
2,458
C++
.cpp
82
25.390244
90
0.664833
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,540,007
SPIAsEEPROM.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/src/SPIAsEEPROM/SPIAsEEPROM.cpp
/* Speeduino SPIAsEEPROM Library v.2.0.4 * Copyright (C) 2020 by Tjeerd Hoogendijk * Created by Tjeerd Hoogendijk - 21/09/2019 * Updated by Tjeerd Hoogendijk - 19/04/2020 * Updated by Tjeerd Hoogendijk - 21/07/2020 no new version number * * This file is part of the Speeduino project. This library started out for * Winbond SPI flash memory modules. As of version 2.0 it also works with internal * flash memory of the STM32F407. In its current form it enables reading * and writing individual bytes as if it where an AVR EEPROM. When the begin() * fuction is called for the first time it will "format" the flash chip. * !!!!THIS DISTROYS ANY EXISTING DATA ON THE FLASH!!!! * * This Library 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 Library 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 v3.0 * along with the Speeduino SPIAsEEPROM Library. If not, see * <http://www.gnu.org/licenses/>. */ #include "SPIAsEEPROM.h" FLASH_EEPROM_BaseClass::FLASH_EEPROM_BaseClass(EEPROM_Emulation_Config config) { //Class indicating if the emulated EEPROM flash is initialized _EmulatedEEPROMAvailable=false; //Class variable storing number of ones counted in adres translation block _nrOfOnes = 0; //Class variable storing what sector we are working in. _sectorFlash = 0; //Class variable storing what flash address we are working in. _addressFLASH = 0; //Class bool indicating if the flash is initialized and available for use _FlashAvailable=false; //save configuration _config = config; _Flash_Size_Used = _config.Flash_Sectors_Used*_config.Flash_Sector_Size; _Flash_Size_Per_EEPROM_Byte = _config.Flash_Sector_Size/(_config.EEPROM_Bytes_Per_Sector +1); _Addres_Translation_Size = _Flash_Size_Per_EEPROM_Byte/8; _EEPROM_Emulation_Size = _config.Flash_Sectors_Used*_config.EEPROM_Bytes_Per_Sector; } int8_t FLASH_EEPROM_BaseClass::initialize(bool flashavailable) { bool formatted = false; _FlashAvailable = flashavailable; _EmulatedEEPROMAvailable = false; if(_FlashAvailable) { formatted = checkForMagicNumbers(); //If not formatted format flash. This takes 10 seconds or more! if(!formatted){ clear(); //check if format succeeded formatted = checkForMagicNumbers(); } if(formatted){_EmulatedEEPROMAvailable=true;} } return _EmulatedEEPROMAvailable; } byte FLASH_EEPROM_BaseClass::read(uint16_t addressEEPROM){ //version 0.1 does not check magic number byte EEPROMbyte; //Check if address is outside of the maximum. return zero if address is out of range. if (addressEEPROM > _EEPROM_Emulation_Size){addressEEPROM = _EEPROM_Emulation_Size - 1; return 0;} //Check at what flash sector the EEPROM byte information resides _sectorFlash = addressEEPROM/_config.EEPROM_Bytes_Per_Sector; //Check at what flash address the EEPROM byte information resides _addressFLASH = (_sectorFlash*_config.Flash_Sector_Size) + ((addressEEPROM % _config.EEPROM_Bytes_Per_Sector) + 1) * _Flash_Size_Per_EEPROM_Byte; //reset buffer to all 0xFF for (uint32_t i = 0; i < _Flash_Size_Per_EEPROM_Byte; i++) { _ReadWriteBuffer[i] = 0xFF; } //read address translation part readFlashBytes(_addressFLASH, _ReadWriteBuffer, _Addres_Translation_Size); //calculate address of the valid data by couting the bits in the Address translation section _nrOfOnes = count(_ReadWriteBuffer, _Addres_Translation_Size); //Bring number of ones within specification of buffer size. if(_nrOfOnes >=_Flash_Size_Per_EEPROM_Byte){_nrOfOnes =_Flash_Size_Per_EEPROM_Byte;} //If it is the first read after clear (all ones still set), return 0xFF; if (_nrOfOnes==_Flash_Size_Per_EEPROM_Byte){ EEPROMbyte = 0xFF; }else{ byte tempBuf[1]; //read actual eeprom value of flash readFlashBytes(_addressFLASH+_nrOfOnes, tempBuf, 1); EEPROMbyte = tempBuf[0]; //make buffer correct, because write function expects a correct buffer. _ReadWriteBuffer[_nrOfOnes] = EEPROMbyte; } return EEPROMbyte; } int8_t FLASH_EEPROM_BaseClass::write(uint16_t addressEEPROM, byte val){ //Check if address is outside of the maximum. limit to get inside maximum and return an error. if (addressEEPROM > _EEPROM_Emulation_Size){addressEEPROM = _EEPROM_Emulation_Size - 1; return -1;} //read the current value uint8_t readValue = read(addressEEPROM); //After reading the current byte all global variables containing information about the address are set correctly. //only write if value is changed. if (readValue != val){ //Check if section is full and an erase must be performed. if (_nrOfOnes < _Addres_Translation_Size + 1){ //First read all the values in this sector that will get distroyed when erasing byte tempBuf[_config.EEPROM_Bytes_Per_Sector]; for(uint16_t i = 0; i<_config.EEPROM_Bytes_Per_Sector; i++){ uint16_t TempEEPROMaddress = (_sectorFlash*_config.EEPROM_Bytes_Per_Sector) + i; tempBuf[i] = read(TempEEPROMaddress); } //Now erase the sector eraseFlashSector(_sectorFlash*_config.Flash_Sector_Size, _config.Flash_Sector_Size); //Write the magic numbers writeMagicNumbers(_sectorFlash); //write all the values back for(uint16_t i=0; i<_config.EEPROM_Bytes_Per_Sector; i++){ write((_sectorFlash*_config.EEPROM_Bytes_Per_Sector) + i, tempBuf[i]); } //Do not forget to write the new value! write(addressEEPROM, val); //Return we have writen a whole sector. return 0xFF; } //determine the adress of the byte in the address translation section where one bit must be reset when writing new values uint8_t AdressInAddressTranslation = (_nrOfOnes - 1)/8; //write the new adress translation value at the new location in buffer _ReadWriteBuffer[AdressInAddressTranslation] <<= 1; //Write the new EEPROM value at the new location in the buffer. _nrOfOnes--; _ReadWriteBuffer[_nrOfOnes] = val; //Write the buffer to the undelying flash storage. // writeFlashBytes(_addressFLASH, _ReadWriteBuffer, _Flash_Size_Per_EEPROM_Byte); //Write actual value part of the buffer to flash byte tempBuffer[2]; _nrOfOnes &= ~(0x1); //align address with 2 byte (uint16_t) for write to flash for 32bit STM32 MCU memcpy(&tempBuffer, &_ReadWriteBuffer[_nrOfOnes], sizeof(uint16_t)); writeFlashBytes(_addressFLASH +_nrOfOnes, tempBuffer, sizeof(uint16_t)); //Write address translation part of the buffer to flash AdressInAddressTranslation &= ~(0x1); //align address with 2 byte for write to flash for 32bit STM32 MCU memcpy(&tempBuffer, &_ReadWriteBuffer[AdressInAddressTranslation], sizeof(uint16_t)); writeFlashBytes(_addressFLASH+AdressInAddressTranslation, tempBuffer, sizeof(uint16_t)); return 1; } return 0; } int8_t FLASH_EEPROM_BaseClass::update(uint16_t addressEEPROM, uint8_t val){ return write(addressEEPROM, val); } int16_t FLASH_EEPROM_BaseClass::clear(){ uint32_t i; for(i=0; i< _config.Flash_Sectors_Used; i++ ){ eraseFlashSector(i*_config.Flash_Sector_Size, _config.Flash_Sector_Size); writeMagicNumbers(i); } return i; } uint16_t FLASH_EEPROM_BaseClass::length(){ return _EEPROM_Emulation_Size; } bool FLASH_EEPROM_BaseClass::checkForMagicNumbers(){ bool magicnumbers = true; for(uint32_t i=0; i< _config.Flash_Sectors_Used; i++ ){ readFlashBytes(i*_config.Flash_Sector_Size, _ReadWriteBuffer, _Flash_Size_Per_EEPROM_Byte); if((_ReadWriteBuffer[0] != MAGICNUMBER1) | (_ReadWriteBuffer[1] != MAGICNUMBER2) | (_ReadWriteBuffer[2] != MAGICNUMBER3) | (_ReadWriteBuffer[3] != EEPROM_VERSION)){magicnumbers=false;} } return magicnumbers; } int8_t FLASH_EEPROM_BaseClass::writeMagicNumbers(uint32_t sector){ _ReadWriteBuffer[0] = MAGICNUMBER1; _ReadWriteBuffer[1] = MAGICNUMBER2; _ReadWriteBuffer[2] = MAGICNUMBER3; _ReadWriteBuffer[3] = EEPROM_VERSION; writeFlashBytes(sector*_config.Flash_Sector_Size, _ReadWriteBuffer, MAGICNUMBER_OFFSET); return true; } uint16_t FLASH_EEPROM_BaseClass::count(byte* buffer, uint32_t length){ byte tempBuffer[length]; memcpy(&tempBuffer, buffer, length); uint16_t count = _Flash_Size_Per_EEPROM_Byte; //It is faster to count the zeroes for(int8_t j=(length-1); j >= 0; j--) { if (tempBuffer[j] == 0) { count -= 8; } //Skip 8 shifts else if(tempBuffer[j] == 255) { break; }//Next bytes are 0xFF else { while ((tempBuffer[j] & 0x01) == 0) { tempBuffer[j] >>= 1; count--; } } } return count; } int8_t FLASH_EEPROM_BaseClass::readFlashBytes(uint32_t address __attribute__((__unused__)), byte* buffer __attribute__((__unused__)), uint32_t length __attribute__((__unused__))){return -1;} int8_t FLASH_EEPROM_BaseClass::writeFlashBytes(uint32_t address __attribute__((__unused__)), byte* buffer __attribute__((__unused__)), uint32_t length __attribute__((__unused__))){return -1;} int8_t FLASH_EEPROM_BaseClass::eraseFlashSector(uint32_t address __attribute__((__unused__)), uint32_t length __attribute__((__unused__))){return -1;} #if defined(ARDUINO_ARCH_STM32) SPI_EEPROM_Class::SPI_EEPROM_Class(EEPROM_Emulation_Config EmulationConfig, Flash_SPI_Config SPIConfig):FLASH_EEPROM_BaseClass(EmulationConfig) { _configSPI = SPIConfig; } byte SPI_EEPROM_Class::read(uint16_t addressEEPROM){ //Check if emulated EEPROM is available if not yet start it first. if(!_EmulatedEEPROMAvailable){ SPISettings settings(22500000, MSBFIRST, SPI_MODE0); //22.5Mhz is highest it could get with this. But should be ~45Mhz :-(. _configSPI.SPIport.beginTransaction(settings); begin(_configSPI.SPIport, _configSPI.pinChipSelect); } return FLASH_EEPROM_BaseClass::read(addressEEPROM); } int8_t SPI_EEPROM_Class::begin(SPIClass &_spi, uint8_t pinSPIFlash_CS=6){ pinMode(pinSPIFlash_CS, OUTPUT); bool flashavailable; flashavailable = winbondSPIFlash.begin(_W25Q16,_spi, pinSPIFlash_CS); return FLASH_EEPROM_BaseClass::initialize(flashavailable); } int8_t SPI_EEPROM_Class::readFlashBytes(uint32_t address, byte *buf, uint32_t length){ while(winbondSPIFlash.busy()); return winbondSPIFlash.read(address+_config.EEPROM_Flash_BaseAddress, buf, length); } int8_t SPI_EEPROM_Class::writeFlashBytes(uint32_t address, byte *buf, uint32_t length){ winbondSPIFlash.setWriteEnable(true); winbondSPIFlash.writePage(address+_config.EEPROM_Flash_BaseAddress, buf, length); while(winbondSPIFlash.busy()); return 0; } int8_t SPI_EEPROM_Class::eraseFlashSector(uint32_t address, uint32_t length){ winbondSPIFlash.setWriteEnable(true); winbondSPIFlash.eraseSector(address+_config.EEPROM_Flash_BaseAddress); while(winbondSPIFlash.busy()); return 0; } #endif //THIS IS NOT WORKING! FOR STM32F103 YOU CAN ONLY WRITE IN JUST ERASED HALFWORDS(UINT16_T). THE PHILISOPHY IS FLAWWED THERE. //#if defined(STM32F103xB) // InternalSTM32F1_EEPROM_Class::InternalSTM32F1_EEPROM_Class(EEPROM_Emulation_Config config):FLASH_EEPROM_BaseClass(config) // { // } // byte InternalSTM32F1_EEPROM_Class::read(uint16_t addressEEPROM){ // if(!_EmulatedEEPROMAvailable){ // FLASH_EEPROM_BaseClass::initialize(true); // } // return FLASH_EEPROM_BaseClass::read(addressEEPROM); // } // int8_t InternalSTM32F1_EEPROM_Class::readFlashBytes(uint32_t address, byte *buf, uint32_t length){ // memcpy(buf, (uint8_t *)(_config.EEPROM_Flash_BaseAddress + address), length); // return 0; // } // int8_t InternalSTM32F1_EEPROM_Class::writeFlashBytes(uint32_t flashAddress, byte *buf, uint32_t length){ // { // uint32_t translatedAddress = flashAddress+_config.EEPROM_Flash_BaseAddress; // uint32_t data = 0; // uint32_t countaddress = translatedAddress; // HAL_FLASH_Unlock(); // while (countaddress < translatedAddress + length) { // memcpy(&data, buf, sizeof(uint32_t)); // if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, countaddress, data) == HAL_OK) { // countaddress += 4; // offset += 4; // } else { // countaddress = translatedAddress + length + 1; // } // } // } // HAL_FLASH_Lock(); // return 0; // } // int8_t InternalSTM32F1_EEPROM_Class::eraseFlashSector(uint32_t address, uint32_t length){ // FLASH_EraseInitTypeDef EraseInitStruct; // uint32_t pageError = 0; // uint32_t realAddress = _config.EEPROM_Flash_BaseAddress+address; // bool EraseSucceed=false; // /* ERASING page */ // EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; // EraseInitStruct.Banks = 1; // EraseInitStruct.PageAddress = realAddress; // EraseInitStruct.NbPages = 1; // HAL_FLASH_Unlock(); // if (HAL_FLASHEx_Erase(&EraseInitStruct, &pageError) == HAL_OK){EraseSucceed=true;} // HAL_FLASH_Lock(); // return EraseSucceed; // } //#endif #if defined(STM32F4) //Look in the datasheet for more information about flash sectors and sizes //This is the correct sector allocation for the STM32F407 all types #define ADDR_FLASH_SECTOR_0 ((uint32_t)0x08000000) /* Base address of Sector 0, 16 Kbytes */ #define ADDR_FLASH_SECTOR_1 ((uint32_t)0x08004000) /* Base address of Sector 1, 16 Kbytes */ #define ADDR_FLASH_SECTOR_2 ((uint32_t)0x08008000) /* Base address of Sector 2, 16 Kbytes */ #define ADDR_FLASH_SECTOR_3 ((uint32_t)0x0800C000) /* Base address of Sector 3, 16 Kbytes */ #define ADDR_FLASH_SECTOR_4 ((uint32_t)0x08010000) /* Base address of Sector 4, 64 Kbytes */ #define ADDR_FLASH_SECTOR_5 ((uint32_t)0x08020000) /* Base address of Sector 5, 128 Kbytes */ #define ADDR_FLASH_SECTOR_6 ((uint32_t)0x08040000) /* Base address of Sector 6, 128 Kbytes */ #define ADDR_FLASH_SECTOR_7 ((uint32_t)0x08060000) /* Base address of Sector 7, 128 Kbytes */ #define ADDR_FLASH_SECTOR_8 ((uint32_t)0x08080000) /* Base address of Sector 8, 128 Kbytes */ #define ADDR_FLASH_SECTOR_9 ((uint32_t)0x080A0000) /* Base address of Sector 9, 128 Kbytes */ #define ADDR_FLASH_SECTOR_10 ((uint32_t)0x080C0000) /* Base address of Sector 10, 128 Kbytes */ #define ADDR_FLASH_SECTOR_11 ((uint32_t)0x080E0000) /* Base address of Sector 11, 128 Kbytes */ #define FLASH_END_ADDRESS ((uint32_t)0x08100000) /* END address of Sector 11, 128 Kbytes */ InternalSTM32F4_EEPROM_Class::InternalSTM32F4_EEPROM_Class(EEPROM_Emulation_Config config) : FLASH_EEPROM_BaseClass(config) { } byte InternalSTM32F4_EEPROM_Class::read(uint16_t addressEEPROM){ if(!_EmulatedEEPROMAvailable){ FLASH_EEPROM_BaseClass::initialize(true); } return FLASH_EEPROM_BaseClass::read(addressEEPROM); } int8_t InternalSTM32F4_EEPROM_Class::readFlashBytes(uint32_t address, byte *buf, uint32_t length){ memcpy(buf, (uint8_t *)(_config.EEPROM_Flash_BaseAddress + address), length); return 0; } int8_t InternalSTM32F4_EEPROM_Class::writeFlashBytes(uint32_t flashAddress, byte *buf, uint32_t length){ { uint32_t translatedAddress = flashAddress+_config.EEPROM_Flash_BaseAddress; uint16_t data = 0; uint32_t offset = 0; uint32_t countaddress = translatedAddress; HAL_FLASH_Unlock(); while (countaddress < translatedAddress + length) { memcpy(&data, buf + offset, sizeof(uint16_t)); if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, countaddress, data) == HAL_OK) { countaddress += 2; offset += 2; } else { countaddress = translatedAddress + length + 1; } } } HAL_FLASH_Lock(); return 0; } int8_t InternalSTM32F4_EEPROM_Class::eraseFlashSector(uint32_t address, uint32_t length){ FLASH_EraseInitTypeDef EraseInitStruct; // uint32_t offset = 0; uint32_t realAddress = _config.EEPROM_Flash_BaseAddress+address; // uint32_t address_end = FLASH_BASE_ADDRESS + E2END; bool EraseSucceed=false; uint32_t SectorError = 0; uint32_t _Sector = 11; //Look in the datasheet for more information about flash sectors and sizes //This is the correct sector allocation for the STM32F407 all types if((realAddress < ADDR_FLASH_SECTOR_1) && (realAddress >= ADDR_FLASH_SECTOR_0)){_Sector = 0;} if((realAddress < ADDR_FLASH_SECTOR_2) && (realAddress >= ADDR_FLASH_SECTOR_1)){_Sector = 1;} if((realAddress < ADDR_FLASH_SECTOR_3) && (realAddress >= ADDR_FLASH_SECTOR_2)){_Sector = 2;} if((realAddress < ADDR_FLASH_SECTOR_4) && (realAddress >= ADDR_FLASH_SECTOR_3)){_Sector = 3;} if((realAddress < ADDR_FLASH_SECTOR_5) && (realAddress >= ADDR_FLASH_SECTOR_4)){_Sector = 4;} if((realAddress < ADDR_FLASH_SECTOR_6) && (realAddress >= ADDR_FLASH_SECTOR_5)){_Sector = 5;} if((realAddress < ADDR_FLASH_SECTOR_7) && (realAddress >= ADDR_FLASH_SECTOR_6)){_Sector = 6;} if((realAddress < ADDR_FLASH_SECTOR_8) && (realAddress >= ADDR_FLASH_SECTOR_7)){_Sector = 7;} if((realAddress < ADDR_FLASH_SECTOR_9) && (realAddress >= ADDR_FLASH_SECTOR_8)){_Sector = 8;} if((realAddress < ADDR_FLASH_SECTOR_10) && (realAddress >= ADDR_FLASH_SECTOR_9)){_Sector = 9;} if((realAddress < ADDR_FLASH_SECTOR_11) && (realAddress >= ADDR_FLASH_SECTOR_10)){_Sector = 10;} if((realAddress < FLASH_END_ADDRESS) && (realAddress >= ADDR_FLASH_SECTOR_11)){_Sector = 11;} EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS; EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3; EraseInitStruct.Sector = _Sector; EraseInitStruct.NbSectors = 1; HAL_FLASH_Unlock(); if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) == HAL_OK){EraseSucceed=true;} HAL_FLASH_Lock(); return EraseSucceed; } #endif #if defined(STM32F7xx) #if defined(DUAL_BANK) #define ADDR_FLASH_SECTOR_0 ((uint32_t)0x08000000) /* Base address of Sector 0, 16 Kbytes */ #define ADDR_FLASH_SECTOR_1 ((uint32_t)0x08004000) /* Base address of Sector 1, 16 Kbytes */ #define ADDR_FLASH_SECTOR_2 ((uint32_t)0x08008000) /* Base address of Sector 2, 16 Kbytes */ #define ADDR_FLASH_SECTOR_3 ((uint32_t)0x0800C000) /* Base address of Sector 3, 16 Kbytes */ #define ADDR_FLASH_SECTOR_4 ((uint32_t)0x08010000) /* Base address of Sector 4, 64 Kbytes */ #define ADDR_FLASH_SECTOR_5 ((uint32_t)0x08020000) /* Base address of Sector 5, 128 Kbytes */ #define ADDR_FLASH_SECTOR_6 ((uint32_t)0x08040000) /* Base address of Sector 6, 128 Kbytes */ #define ADDR_FLASH_SECTOR_7 ((uint32_t)0x08060000) /* Base address of Sector 7, 128 Kbytes */ #define ADDR_FLASH_SECTOR_8 ((uint32_t)0x08080000) /* Base address of Sector 8, 128 Kbytes */ #define ADDR_FLASH_SECTOR_9 ((uint32_t)0x080A0000) /* Base address of Sector 9, 128 Kbytes */ #define ADDR_FLASH_SECTOR_10 ((uint32_t)0x080C0000) /* Base address of Sector 10, 128 Kbytes */ #define ADDR_FLASH_SECTOR_11 ((uint32_t)0x080E0000) /* Base address of Sector 11, 128 Kbytes */ #define ADDR_FLASH_SECTOR_12 ((uint32_t)0x08100000) /* Base address of Sector 12, 16 Kbytes */ #define ADDR_FLASH_SECTOR_13 ((uint32_t)0x08104000) /* Base address of Sector 13, 16 Kbytes */ #define ADDR_FLASH_SECTOR_14 ((uint32_t)0x08108000) /* Base address of Sector 14, 16 Kbytes */ #define ADDR_FLASH_SECTOR_15 ((uint32_t)0x0810C000) /* Base address of Sector 15, 16 Kbytes */ #define ADDR_FLASH_SECTOR_16 ((uint32_t)0x08110000) /* Base address of Sector 16, 64 Kbytes */ #define ADDR_FLASH_SECTOR_17 ((uint32_t)0x08120000) /* Base address of Sector 17, 128 Kbytes */ #define ADDR_FLASH_SECTOR_18 ((uint32_t)0x08140000) /* Base address of Sector 18, 128 Kbytes */ #define ADDR_FLASH_SECTOR_19 ((uint32_t)0x08160000) /* Base address of Sector 19, 128 Kbytes */ #define ADDR_FLASH_SECTOR_20 ((uint32_t)0x08180000) /* Base address of Sector 20, 128 Kbytes */ #define ADDR_FLASH_SECTOR_21 ((uint32_t)0x081A0000) /* Base address of Sector 21, 128 Kbytes */ #define ADDR_FLASH_SECTOR_22 ((uint32_t)0x081C0000) /* Base address of Sector 22, 128 Kbytes */ #define ADDR_FLASH_SECTOR_23 ((uint32_t)0x081E0000) /* Base address of Sector 23, 128 Kbytes */ #else #define ADDR_FLASH_SECTOR_0 ((uint32_t)0x08000000) /* Base address of Sector 0, 32 Kbytes */ #define ADDR_FLASH_SECTOR_1 ((uint32_t)0x08008000) /* Base address of Sector 1, 32 Kbytes */ #define ADDR_FLASH_SECTOR_2 ((uint32_t)0x08010000) /* Base address of Sector 2, 32 Kbytes */ #define ADDR_FLASH_SECTOR_3 ((uint32_t)0x08018000) /* Base address of Sector 3, 32 Kbytes */ #define ADDR_FLASH_SECTOR_4 ((uint32_t)0x08020000) /* Base address of Sector 4, 128 Kbytes */ #define ADDR_FLASH_SECTOR_5 ((uint32_t)0x08040000) /* Base address of Sector 5, 256 Kbytes */ #define ADDR_FLASH_SECTOR_6 ((uint32_t)0x08080000) /* Base address of Sector 6, 256 Kbytes */ #define ADDR_FLASH_SECTOR_7 ((uint32_t)0x080C0000) /* Base address of Sector 7, 256 Kbytes */ #define ADDR_FLASH_SECTOR_8 ((uint32_t)0x08100000) /* Base address of Sector 8, 256 Kbytes */ #define ADDR_FLASH_SECTOR_9 ((uint32_t)0x08140000) /* Base address of Sector 9, 256 Kbytes */ #define ADDR_FLASH_SECTOR_10 ((uint32_t)0x08180000) /* Base address of Sector 10, 256 Kbytes */ #define ADDR_FLASH_SECTOR_11 ((uint32_t)0x081C0000) /* Base address of Sector 11, 256 Kbytes */ #endif /* DUAL_BANK */ InternalSTM32F7_EEPROM_Class::InternalSTM32F7_EEPROM_Class(EEPROM_Emulation_Config config) : FLASH_EEPROM_BaseClass(config) { } byte InternalSTM32F7_EEPROM_Class::read(uint16_t addressEEPROM){ if(!_EmulatedEEPROMAvailable){ FLASH_EEPROM_BaseClass::initialize(true); } return FLASH_EEPROM_BaseClass::read(addressEEPROM); } int8_t InternalSTM32F7_EEPROM_Class::readFlashBytes(uint32_t address, byte *buf, uint32_t length){ memcpy(buf, (uint8_t *)(_config.EEPROM_Flash_BaseAddress + address), length); return 0; } int8_t InternalSTM32F7_EEPROM_Class::writeFlashBytes(uint32_t flashAddress, byte *buf, uint32_t length){ { uint32_t translatedAddress = flashAddress+_config.EEPROM_Flash_BaseAddress; uint32_t data = 0; uint32_t offset = 0; uint32_t countaddress = translatedAddress; HAL_FLASH_Unlock(); while (countaddress < translatedAddress + length) { memcpy(&data, buf + offset, sizeof(uint32_t)); if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, countaddress, data) == HAL_OK) { countaddress += 4; offset += 4; } else { countaddress = translatedAddress + length + 1; } } } HAL_FLASH_Lock(); return 0; } int8_t InternalSTM32F7_EEPROM_Class::eraseFlashSector(uint32_t address, uint32_t length){ FLASH_EraseInitTypeDef EraseInitStruct; // uint32_t offset = 0; uint32_t realAddress = _config.EEPROM_Flash_BaseAddress+address; // uint32_t address_end = FLASH_BASE_ADDRESS + E2END; bool EraseSucceed=false; uint32_t SectorError = 0; uint32_t _Sector = 11; //Look in the datasheet for more information about flash sectors and sizes //This is the correct sector allocation for the STM32F407 all types if((realAddress < ADDR_FLASH_SECTOR_1) && (realAddress >= ADDR_FLASH_SECTOR_0)){_Sector = 0;} if((realAddress < ADDR_FLASH_SECTOR_2) && (realAddress >= ADDR_FLASH_SECTOR_1)){_Sector = 1;} if((realAddress < ADDR_FLASH_SECTOR_3) && (realAddress >= ADDR_FLASH_SECTOR_2)){_Sector = 2;} if((realAddress < ADDR_FLASH_SECTOR_4) && (realAddress >= ADDR_FLASH_SECTOR_3)){_Sector = 3;} if((realAddress < ADDR_FLASH_SECTOR_5) && (realAddress >= ADDR_FLASH_SECTOR_4)){_Sector = 4;} if((realAddress < ADDR_FLASH_SECTOR_6) && (realAddress >= ADDR_FLASH_SECTOR_5)){_Sector = 5;} if((realAddress < ADDR_FLASH_SECTOR_7) && (realAddress >= ADDR_FLASH_SECTOR_6)){_Sector = 6;} if((realAddress < ADDR_FLASH_SECTOR_8) && (realAddress >= ADDR_FLASH_SECTOR_7)){_Sector = 7;} if((realAddress < ADDR_FLASH_SECTOR_9) && (realAddress >= ADDR_FLASH_SECTOR_8)){_Sector = 8;} if((realAddress < ADDR_FLASH_SECTOR_10) && (realAddress >= ADDR_FLASH_SECTOR_9)){_Sector = 9;} if((realAddress < ADDR_FLASH_SECTOR_11) && (realAddress >= ADDR_FLASH_SECTOR_10)){_Sector = 10;} else /* (Address < FLASH_END_ADDR) && (Address >= ADDR_FLASH_SECTOR_11) */ { {_Sector = 11;} } #if defined(DUAL_BANK) if((realAddress < ADDR_FLASH_SECTOR_13) && (realAddress >= ADDR_FLASH_SECTOR_12)){_Sector = 12;} if((realAddress < ADDR_FLASH_SECTOR_14) && (realAddress >= ADDR_FLASH_SECTOR_13)){_Sector = 13;} if((realAddress < ADDR_FLASH_SECTOR_15) && (realAddress >= ADDR_FLASH_SECTOR_14)){_Sector = 14;} if((realAddress < ADDR_FLASH_SECTOR_16) && (realAddress >= ADDR_FLASH_SECTOR_15)){_Sector = 15;} if((realAddress < ADDR_FLASH_SECTOR_17) && (realAddress >= ADDR_FLASH_SECTOR_16)){_Sector = 16;} if((realAddress < ADDR_FLASH_SECTOR_18) && (realAddress >= ADDR_FLASH_SECTOR_17)){_Sector = 17;} if((realAddress < ADDR_FLASH_SECTOR_19) && (realAddress >= ADDR_FLASH_SECTOR_18)){_Sector = 18;} if((realAddress < ADDR_FLASH_SECTOR_20) && (realAddress >= ADDR_FLASH_SECTOR_19)){_Sector = 19;} if((realAddress < ADDR_FLASH_SECTOR_21) && (realAddress >= ADDR_FLASH_SECTOR_20)){_Sector = 20;} if((realAddress < ADDR_FLASH_SECTOR_22) && (realAddress >= ADDR_FLASH_SECTOR_21)){_Sector = 21;} if((realAddress < ADDR_FLASH_SECTOR_23) && (realAddress >= ADDR_FLASH_SECTOR_22)){_Sector = 22;} else /* (Address < FLASH_END_ADDR) && (Address >= ADDR_FLASH_SECTOR_23) */ { {_Sector = 23;} } #endif /* DUAL_BANK */ EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS; EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3; EraseInitStruct.Sector = _Sector; EraseInitStruct.NbSectors = 1; HAL_FLASH_Unlock(); if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) == HAL_OK){EraseSucceed=true;} HAL_FLASH_Lock(); return EraseSucceed; } #endif
26,467
C++
.cpp
492
49.762195
194
0.706344
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,540,008
PID_v1.cpp
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/src/PID_v1/PID_v1.cpp
/********************************************************************************************** * Arduino PID Library - Version 1.0.1 * by Brett Beauregard <br3ttb@gmail.com> brettbeauregard.com * * This Library is licensed under a GPLv3 License **********************************************************************************************/ #if ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "PID_v1.h" /*Constructor (...)********************************************************* * The parameters specified here are those for for which we can't set up * reliable defaults, so we need to have the user set them. ***************************************************************************/ PID::PID(long* Input, long* Output, long* Setpoint, byte Kp, byte Ki, byte Kd, byte ControllerDirection) { myOutput = Output; myInput = Input; mySetpoint = Setpoint; inAuto = false; PID::SetOutputLimits(0, 255); //default output limit corresponds to //the arduino pwm limits SampleTime = 100; //default Controller Sample Time is 0.1 seconds PID::SetControllerDirection(ControllerDirection); PID::SetTunings(Kp, Ki, Kd); lastTime = millis()-SampleTime; } /* Compute() ********************************************************************** * This, as they say, is where the magic happens. this function should be called * every time "void loop()" executes. the function will decide for itself whether a new * pid Output needs to be computed. returns true when the output is computed, * false when nothing has been done. **********************************************************************************/ bool PID::Compute() { if(!inAuto) return false; unsigned long now = millis(); SampleTime = (now - lastTime); //if(timeChange>=SampleTime) { /*Compute all the working error variables*/ long input = *myInput; long error = *mySetpoint - input; ITerm += (ki * error)/100; if(ITerm > outMax) ITerm= outMax; else if(ITerm < outMin) ITerm= outMin; long dInput = (input - lastInput); /*Compute PID Output*/ long output = (kp * error)/100 + ITerm- (kd * dInput)/100; if(output > outMax) { output = outMax; } else if(output < outMin) { output = outMin; } *myOutput = output; /*Remember some variables for next time*/ lastInput = input; //lastTime = now; return true; } //else return false; } /* SetTunings(...)************************************************************* * This function allows the controller's dynamic performance to be adjusted. * it's called automatically from the constructor, but tunings can also * be adjusted on the fly during normal operation ******************************************************************************/ void PID::SetTunings(byte Kp, byte Ki, byte Kd) { dispKp = Kp; dispKi = Ki; dispKd = Kd; /* double SampleTimeInSec = ((double)SampleTime)/1000; kp = Kp; ki = Ki * SampleTimeInSec; kd = Kd / SampleTimeInSec; */ long InverseSampleTimeInSec = 100000 / SampleTime; kp = Kp; ki = (Ki * 100) / InverseSampleTimeInSec; kd = (Kd * InverseSampleTimeInSec) / 100; if(controllerDirection ==REVERSE) { kp = (0 - kp); ki = (0 - ki); kd = (0 - kd); } } /* SetSampleTime(...) ********************************************************* * sets the period, in Milliseconds, at which the calculation is performed ******************************************************************************/ void PID::SetSampleTime(int NewSampleTime) { if (NewSampleTime > 0) { unsigned long ratioX1000 = (unsigned long)(NewSampleTime * 1000) / (unsigned long)SampleTime; ki = (ki * ratioX1000) / 1000; //kd /= ratio; kd = (kd * 1000) / ratioX1000; SampleTime = (unsigned long)NewSampleTime; } } /* SetOutputLimits(...)**************************************************** * This function will be used far more often than SetInputLimits. while * the input to the controller will generally be in the 0-1023 range (which is * the default already,) the output will be a little different. maybe they'll * be doing a time window and will need 0-8000 or something. or maybe they'll * want to clamp it from 0-125. who knows. at any rate, that can all be done * here. **************************************************************************/ void PID::SetOutputLimits(long Min, long Max) { if(Min >= Max) return; outMin = Min; outMax = Max; if(inAuto) { if(*myOutput > outMax) *myOutput = outMax; else if(*myOutput < outMin) *myOutput = outMin; if(ITerm > outMax) ITerm= outMax; else if(ITerm < outMin) ITerm= outMin; } } /* SetMode(...)**************************************************************** * Allows the controller Mode to be set to manual (0) or Automatic (non-zero) * when the transition from manual to auto occurs, the controller is * automatically initialized ******************************************************************************/ void PID::SetMode(int Mode) { bool newAuto = (Mode == AUTOMATIC); if(newAuto == !inAuto) { /*we just went from manual to auto*/ PID::Initialize(); } inAuto = newAuto; } /* Initialize()**************************************************************** * does all the things that need to happen to ensure a bumpless transfer * from manual to automatic mode. ******************************************************************************/ void PID::Initialize() { ITerm = *myOutput; lastInput = *myInput; if(ITerm > outMax) ITerm = outMax; else if(ITerm < outMin) ITerm = outMin; } /* SetControllerDirection(...)************************************************* * The PID will either be connected to a DIRECT acting process (+Output leads * to +Input) or a REVERSE acting process(+Output leads to -Input.) we need to * know which one, because otherwise we may increase the output when we should * be decreasing. This is called from the constructor. ******************************************************************************/ void PID::SetControllerDirection(byte Direction) { if(inAuto && Direction !=controllerDirection) { kp = (0 - kp); ki = (0 - ki); kd = (0 - kd); } controllerDirection = Direction; } /* Status Funcions************************************************************* * Just because you set the Kp=-1 doesn't mean it actually happened. these * functions query the internal state of the PID. they're here for display * purposes. this are the functions the PID Front-end uses for example ******************************************************************************/ int16_t PID::GetKp(){ return dispKp; } int16_t PID::GetKi(){ return dispKi;} int16_t PID::GetKd(){ return dispKd;} int PID::GetMode(){ return inAuto ? AUTOMATIC : MANUAL;} int PID::GetDirection(){ return controllerDirection;} /*Constructor (...)********************************************************* * The parameters specified here are those for for which we can't set up * reliable defaults, so we need to have the user set them. ***************************************************************************/ /** * @brief A standard integer PID controller. * * @param Input Pointer to the variable holding the current value that is to be controlled. Eg In an idle control this would point to RPM * @param Output The address in the page that should be returned. This is as per the page definition in the ini * * @return byte The current target advance value in degrees */ integerPID::integerPID(long* Input, long* Output, long* Setpoint, int16_t Kp, int16_t Ki, int16_t Kd, byte ControllerDirection) { myOutput = Output; myInput = Input; mySetpoint = Setpoint; inAuto = false; integerPID::SetOutputLimits(0, 255); //default output limit corresponds to the arduino pwm limits SampleTime = 250; //default Controller Sample Time is 0.25 seconds. This is the 4Hz control time for Idle and VVT integerPID::SetControllerDirection(ControllerDirection); integerPID::SetTunings(Kp, Ki, Kd); lastTime = millis()-SampleTime; } /* Compute() ********************************************************************** * This, as they say, is where the magic happens. this function should be called * every time "void loop()" executes. the function will decide for itself whether a new * pid Output needs to be computed. returns true when the output is computed, * false when nothing has been done. **********************************************************************************/ bool integerPID::Compute(bool pOnE, long FeedForwardTerm) { if(!inAuto) return false; unsigned long now = millis(); unsigned long timeChange = (now - lastTime); if(timeChange >= SampleTime) { /*Compute all the working error variables*/ long input = *myInput; if(input > 0) //Fail safe, should never be 0 { long error = *mySetpoint - input; long dInput = (input - lastInput); FeedForwardTerm <<= PID_SHIFTS; if (ki != 0) { outputSum += (ki * error); //integral += error × dt if(outputSum > outMax-FeedForwardTerm) { outputSum = outMax-FeedForwardTerm; } else if(outputSum < outMin-FeedForwardTerm) { outputSum = outMin-FeedForwardTerm; } } /*Compute PID Output*/ long output; if(pOnE) { output = (kp * error); if (ki != 0) { output += outputSum; } } else { outputSum -= (kp * dInput); if(outputSum > outMax) { outputSum = outMax; } else if(outputSum < outMin) { outputSum = outMin; } output = outputSum; } if (kd != 0) { output -= (kd * dInput)>>2; } output += FeedForwardTerm; if(output > outMax) output = outMax; else if(output < outMin) output = outMin; *myOutput = output >> PID_SHIFTS; /*Remember some variables for next time*/ lastInput = input; lastTime = now; return true; } } return false; } bool integerPID::ComputeVVT(uint32_t Sample) { if(!inAuto) return false; /*Compute all the working error variables*/ long pTerm, dTerm; long input = *myInput; long error = *mySetpoint - input; long dInput = error - lastError; long dTime = lastTime - Sample; pTerm = kp * error; if (ki != 0) { outputSum += (ki * error) * dTime; //integral += error × dt if(outputSum > outMax*100) { outputSum = outMax*100; } else if(outputSum < -outMax*100) { outputSum = -outMax*100; } } dTerm = dInput * kd * dTime; /*Compute PID Output*/ long output = (pTerm + outputSum + dTerm) >> 5; if(output > outMax) output = outMax; else if(output < outMin) output = outMin; *myOutput = output; /*Remember some variables for next time*/ lastError = error; lastTime = dTime; return true; } bool integerPID::Compute2(int target, int input, bool pOnE) { if(!inAuto) return false; unsigned long now = millis(); //SampleTime = (now - lastTime); uint16_t timeChange = (now - lastTime); if(timeChange >= SampleTime) { long Kp, Ki, Kd; long PV; long output; long SP1; long error; long pid_deriv; #define pid_divider 1024 #define pid_multiplier 100 //pid_divider = 128; //pid_multiplier = 10; //convert_unitless_percent(min, max, targ, raw_PV, &PV, &SP); PV = (((long)input - outMin) * 10000L) / (outMax - outMin); //125 SP1 = (((long)target - outMin) * 10000L) / (outMax - outMin); //500 error = SP1 - PV; //375 pid_deriv = PV - (2 * lastInput) + lastMinusOneInput; //125 if(!pOnE) { Kp = ((long) ((PV - lastInput) * (long)kp)); //125 * kp } else { Kp = ((long) ((error - lastError) * (long)kp)); } Ki = ((((long) error * timeChange) / (long)pid_divider) * (long)ki); //12*ki Kd = ((long) pid_deriv * (((long) kd * pid_multiplier) / timeChange)); if(!pOnE) { output = Kp - Ki + Kd; } else { output = Kp + Ki - Kd; } if(output > outMax) output = outMax; else if(output < outMin) output = outMin; *myOutput = output; /*Remember some variables for next time*/ lastMinusOneInput = lastInput; lastInput = input; lastError = error; lastTime = now; return true; } else return false; } /* SetTunings(...)************************************************************* * This function allows the controller's dynamic performance to be adjusted. * it's called automatically from the constructor, but tunings can also * be adjusted on the fly during normal operation ******************************************************************************/ void integerPID::SetTunings(int16_t Kp, int16_t Ki, int16_t Kd, byte realTime) { if ( dispKp == Kp && dispKi == Ki && dispKd == Kd ) return; //Only do anything if one of the values has changed dispKp = Kp; dispKi = Ki; dispKd = Kd; /* double SampleTimeInSec = ((double)SampleTime)/1000; kp = Kp; ki = Ki * SampleTimeInSec; kd = Kd / SampleTimeInSec; */ if(realTime == 0) { long InverseSampleTimeInSec = 1000 / SampleTime; //New resolution, 32x to improve ki here | kp 3.125% | ki 3.125% | kd 0.781% kp = Kp * 32; ki = (long)(Ki * 32) / InverseSampleTimeInSec; kd = (long)(Kd * 32) * InverseSampleTimeInSec; } else { kp = Kp; ki = Ki; kd = Kd; } if(controllerDirection == REVERSE) { kp = (0 - kp); ki = (0 - ki); kd = (0 - kd); } } /* SetSampleTime(...) ********************************************************* * sets the period, in Milliseconds, at which the calculation is performed ******************************************************************************/ void integerPID::SetSampleTime(uint16_t NewSampleTime) { if (SampleTime == (unsigned long)NewSampleTime) return; //If new value = old value, no action required. SampleTime = NewSampleTime; //This resets the tuning values with the appropriate new scaling //The +1/-1 is there just so that this doesn't trip the check at the beginning of the SetTunings() function SetTunings(dispKp+1, dispKi+1, dispKd+1); SetTunings(dispKp-1, dispKi-1, dispKd-1); } /* SetOutputLimits(...)**************************************************** * This function will be used far more often than SetInputLimits. while * the input to the controller will generally be in the 0-1023 range (which is * the default already,) the output will be a little different. maybe they'll * be doing a time window and will need 0-8000 or something. or maybe they'll * want to clamp it from 0-125. who knows. at any rate, that can all be done * here. **************************************************************************/ void integerPID::SetOutputLimits(long Min, long Max) { if(Min >= Max) return; outMin = Min << PID_SHIFTS; outMax = Max << PID_SHIFTS; if(inAuto) { if(*myOutput > Max) *myOutput = Max; else if(*myOutput < Min) *myOutput = Min; if(outputSum > outMax) { outputSum = outMax; } else if(outputSum < outMin) { outputSum = outMin; } } } /* SetMode(...)**************************************************************** * Allows the controller Mode to be set to manual (0) or Automatic (non-zero) * when the transition from manual to auto occurs, the controller is * automatically initialized ******************************************************************************/ void integerPID::SetMode(int Mode) { bool newAuto = (Mode == AUTOMATIC); if(newAuto == !inAuto) { /*we just went from manual to auto*/ integerPID::Initialize(); } inAuto = newAuto; } /* Initialize()**************************************************************** * does all the things that need to happen to ensure a bumpless transfer * from manual to automatic mode. ******************************************************************************/ void integerPID::Initialize() { outputSum = *myOutput<<PID_SHIFTS; lastInput = *myInput; lastMinusOneInput = *myInput; if(outputSum > outMax) { outputSum = outMax; } else if(outputSum < outMin) { outputSum = outMin; } } /* SetControllerDirection(...)************************************************* * The PID will either be connected to a DIRECT acting process (+Output leads * to +Input) or a REVERSE acting process(+Output leads to -Input.) we need to * know which one, because otherwise we may increase the output when we should * be decreasing. This is called from the constructor. ******************************************************************************/ void integerPID::SetControllerDirection(byte Direction) { if(inAuto && Direction !=controllerDirection) { kp = (0 - kp); ki = (0 - ki); kd = (0 - kd); } controllerDirection = Direction; } /* Status Funcions************************************************************* * Just because you set the Kp=-1 doesn't mean it actually happened. these * functions query the internal state of the PID. they're here for display * purposes. this are the functions the PID Front-end uses for example ******************************************************************************/ int integerPID::GetMode(){ return inAuto ? AUTOMATIC : MANUAL;} int integerPID::GetDirection(){ return controllerDirection;} void integerPID::ResetIntegeral() { outputSum=0;} //************************************************************************************************************************ #define limitMultiplier 100 //How much outMin and OutMax must be multiplied by to get them in the same scale as the output /*Constructor (...)********************************************************* * The parameters specified here are those for for which we can't set up * reliable defaults, so we need to have the user set them. ***************************************************************************/ integerPID_ideal::integerPID_ideal(long* Input, uint16_t* Output, uint16_t* Setpoint, uint16_t* Sensitivity, byte* SampleTime, byte Kp, byte Ki, byte Kd, byte ControllerDirection) { myOutput = Output; myInput = (long*)Input; mySetpoint = Setpoint; mySensitivity = Sensitivity; mySampleTime = SampleTime; integerPID_ideal::SetOutputLimits(20, 80); //default output limits integerPID_ideal::SetControllerDirection(ControllerDirection); integerPID_ideal::SetTunings(Kp, Ki, Kd); lastTime = millis()- *mySampleTime; lastError = 0; } /* Compute() ********************************************************************** * This, as they say, is where the magic happens. this function should be called * every time "void loop()" executes. the function will decide for itself whether a new * pid Output needs to be computed. returns true when the output is computed, * false when nothing has been done. **********************************************************************************/ bool integerPID_ideal::Compute() { unsigned long now = millis(); //SampleTime = (now - lastTime); unsigned long timeChange = (now - lastTime); if(timeChange >= *mySampleTime) { /*Compute all the working error variables*/ uint16_t sensitivity = 10001 - (*mySensitivity * 2); long unitless_setpoint = (((long)*mySetpoint - 0) * 10000L) / (sensitivity - 0); long unitless_input = (((long)*myInput - 0) * 10000L) / (sensitivity - 0); long error = unitless_setpoint - unitless_input; ITerm += error; uint16_t bias = 50; //Base target DC% long output = 0; if(ki != 0) { output = ((outMax - bias) * limitMultiplier * 100) / (long)ki; if (output < 0) { output = 0; } } if (ITerm > output) { ITerm = output; } if(ki != 0) { output = ((bias - outMin) * limitMultiplier * 100) / (long)ki; if (output < 0) { output = 0; } } else { output = 0; } if (ITerm < -output) { ITerm = -output; } /*Compute PID Output*/ output = (kp * error) + (ki * ITerm) + (kd * (error - lastError)); output = (bias * limitMultiplier) + (output / 10); //output is % multipled by 1000. To get % with 2 decimal places, divide it by 10. Likewise, bias is % in whole numbers. Multiply it by 100 to get it with 2 places. //if(output > (outMax * limitMultiplier)) { output = (outMax * limitMultiplier); } //if(output < (outMin * limitMultiplier)) { output = (outMin * limitMultiplier); } if(output > (outMax * limitMultiplier)) { output = (outMax * limitMultiplier); ITerm -= error; //Prevent the ITerm from growing indefinitely whilst the output is being limited (error was added to ITerm above, so this is simply setting it back to it's original value) } if(output < (outMin * limitMultiplier)) { output = (outMin * limitMultiplier); ITerm -= error; //Prevent the ITerm from growing indefinitely whilst the output is being limited (error was added to ITerm above, so this is simply setting it back to it's original value) } *myOutput = output; /*Remember some variables for next time*/ lastTime = now; lastError = error; return true; } else return false; } /* SetTunings(...)************************************************************* * This function allows the controller's dynamic performance to be adjusted. * it's called automatically from the constructor, but tunings can also * be adjusted on the fly during normal operation ******************************************************************************/ void integerPID_ideal::SetTunings(byte Kp, byte Ki, byte Kd) { if ( dispKp == Kp && dispKi == Ki && dispKd == Kd ) return; //Only do anything if one of the values has changed dispKp = Kp; dispKi = Ki; dispKd = Kd; kp = Kp; ki = Ki; kd = Kd; if(controllerDirection == REVERSE) { kp = (0 - kp); ki = (0 - ki); kd = (0 - kd); } } /* SetOutputLimits(...)**************************************************** * This function will be used far more often than SetInputLimits. while * the input to the controller will generally be in the 0-1023 range (which is * the default already,) the output will be a little different. maybe they'll * be doing a time window and will need 0-8000 or something. or maybe they'll * want to clamp it from 0-125. who knows. at any rate, that can all be done * here. **************************************************************************/ void integerPID_ideal::SetOutputLimits(long Min, long Max) { if(Min < Max) { outMin = Min; outMax = Max; } } /* Initialize()**************************************************************** * does all the things that need to happen to ensure a bumpless transfer * from manual to automatic mode. ******************************************************************************/ void integerPID_ideal::Initialize() { ITerm = 0; lastInput = *myInput; lastError = 0; } /* SetControllerDirection(...)************************************************* * The PID will either be connected to a DIRECT acting process (+Output leads * to +Input) or a REVERSE acting process(+Output leads to -Input.) we need to * know which one, because otherwise we may increase the output when we should * be decreasing. This is called from the constructor. ******************************************************************************/ void integerPID_ideal::SetControllerDirection(byte Direction) { if(Direction != controllerDirection) { kp = (0 - kp); ki = (0 - ki); kd = (0 - kd); } controllerDirection = Direction; } /* Status Funcions************************************************************* * Just because you set the Kp=-1 doesn't mean it actually happened. these * functions query the internal state of the PID. they're here for display * purposes. this are the functions the PID Front-end uses for example ******************************************************************************/ int integerPID_ideal::GetDirection(){ return controllerDirection;}
24,790
C++
.cpp
594
37.274411
220
0.5576
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,540,009
test_ignition_schedule_init.cpp
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_init/test_ignition_schedule_init.cpp
#include <Arduino.h> #include <unity.h> #include "globals.h" #include "init.h" #include "schedule_calcs.h" #include "scheduledIO.h" #include "../test_utils.h" static void assert_ignition_channel(uint16_t angle, uint8_t channel, int channelInjDegrees, voidVoidCallback startFunction, voidVoidCallback endFunction) { char msg[32]; sprintf_P(msg, PSTR("channe%" PRIu8 "1InjDegrees"), channel+1); TEST_ASSERT_EQUAL_MESSAGE(angle, channelInjDegrees, msg); sprintf_P(msg, PSTR("ign%" PRIu8 "StartFunction"), channel+1); TEST_ASSERT_TRUE_MESSAGE(channel>=maxIgnOutputs || (startFunction!=nullCallback), msg); sprintf_P(msg, PSTR("ign%" PRIu8 "EndFunction"), channel+1); TEST_ASSERT_TRUE_MESSAGE(channel>=maxIgnOutputs || (endFunction!=nullCallback), msg); } static void assert_ignition_schedules(uint16_t crankAngle, uint16_t expectedOutputs, const uint16_t angle[]) { char msg[48]; strcpy_P(msg, PSTR("CRANK_ANGLE_MAX_IGN")); TEST_ASSERT_EQUAL_INT16_MESSAGE(crankAngle, CRANK_ANGLE_MAX_IGN, msg); strcpy_P(msg, PSTR("maxIgnOutputs")); TEST_ASSERT_EQUAL_UINT16_MESSAGE(expectedOutputs, maxIgnOutputs, msg); assert_ignition_channel(angle[0], 0, channel1IgnDegrees, ign1StartFunction, ign1EndFunction); assert_ignition_channel(angle[1], 1, channel2IgnDegrees, ign2StartFunction, ign2EndFunction); assert_ignition_channel(angle[2], 2, channel3IgnDegrees, ign3StartFunction, ign3EndFunction); assert_ignition_channel(angle[3], 3, channel4IgnDegrees, ign4StartFunction, ign4EndFunction); #if IGN_CHANNELS>=5 assert_ignition_channel(angle[4], 4, channel5IgnDegrees, ign5StartFunction, ign5EndFunction); #endif #if IGN_CHANNELS>=6 assert_ignition_channel(angle[5], 5, channel6IgnDegrees, ign6StartFunction, ign6EndFunction); #endif #if IGN_CHANNELS>=7 assert_ignition_channel(angle[6], 6, channel7IgnDegrees, ign7StartFunction, ign7EndFunction); #endif #if IGN_CHANNELS>=8 assert_ignition_channel(angle[7], 7, channel8IgnDegrees, ign8StartFunction, ign8EndFunction); #endif } static void cylinder1_stroke4_seq_even(void) { configPage4.sparkMode = IGN_MODE_SEQUENTIAL; configPage2.engineType = EVEN_FIRE; initialiseAll(); //Run the main initialise function const uint16_t angle[] = {0,0,0,0,0,0,0,0}; assert_ignition_schedules(720U, 1U, angle); } static void cylinder1_stroke4_wasted_even(void) { configPage4.sparkMode = IGN_MODE_WASTED; configPage2.engineType = EVEN_FIRE; initialiseAll(); //Run the main initialise function const uint16_t angle[] = {0,0,0,0,0,0,0,0}; assert_ignition_schedules(360U, 1U, angle); } static void cylinder1_stroke4_seq_odd(void) { configPage4.sparkMode = IGN_MODE_SEQUENTIAL; configPage2.engineType = ODD_FIRE; initialiseAll(); //Run the main initialise function const uint16_t angle[] = {0,0,0,0,0,0,0,0}; assert_ignition_schedules(720U, 1U, angle); } static void run_1_cylinder_4stroke_tests(void) { configPage2.nCylinders = 1; configPage2.strokes = FOUR_STROKE; RUN_TEST_P(cylinder1_stroke4_seq_even); RUN_TEST_P(cylinder1_stroke4_wasted_even); RUN_TEST_P(cylinder1_stroke4_seq_odd); } static void cylinder2_stroke4_seq_even(void) { configPage4.sparkMode = IGN_MODE_SEQUENTIAL; configPage2.engineType = EVEN_FIRE; initialiseAll(); //Run the main initialise function const uint16_t angle[] = {0,180,0,0,0,0,0,0}; assert_ignition_schedules(720U, 2U, angle); } static void cylinder2_stroke4_wasted_even(void) { configPage4.sparkMode = IGN_MODE_WASTED; configPage2.engineType = EVEN_FIRE; initialiseAll(); //Run the main initialise function const uint16_t angle[] = {0,180,0,0,0,0,0,0}; assert_ignition_schedules(360U, 2U, angle); } static void cylinder2_stroke4_seq_odd(void) { configPage4.sparkMode = IGN_MODE_SEQUENTIAL; configPage2.engineType = ODD_FIRE; configPage2.oddfire2 = 13; configPage2.oddfire3 = 111; configPage2.oddfire4 = 217; initialiseAll(); //Run the main initialise function const uint16_t angle[] = {0,13,0,0,0,0,0,0}; assert_ignition_schedules(720U, 2U, angle); } static void run_2_cylinder_4stroke_tests(void) { configPage2.nCylinders = 2; configPage2.strokes = FOUR_STROKE; RUN_TEST_P(cylinder2_stroke4_seq_even); RUN_TEST_P(cylinder2_stroke4_wasted_even); RUN_TEST_P(cylinder2_stroke4_seq_odd); } static void cylinder3_stroke4_seq_even(void) { configPage4.sparkMode = IGN_MODE_SEQUENTIAL; configPage2.engineType = EVEN_FIRE; initialiseAll(); //Run the main initialise function const uint16_t angle[] = {0,240,480,0,0,0,0,0}; assert_ignition_schedules(720U, 3U, angle); } static void cylinder3_stroke4_wasted_even(void) { configPage4.sparkMode = IGN_MODE_WASTED; configPage2.engineType = EVEN_FIRE; initialiseAll(); //Run the main initialise function const uint16_t angle[] = {0,120,240,0,0,0,0,0}; assert_ignition_schedules(360U, 3U, angle); } static void cylinder3_stroke4_wasted_odd(void) { configPage4.sparkMode = IGN_MODE_WASTED; configPage2.engineType = ODD_FIRE; configPage2.oddfire2 = 13; configPage2.oddfire3 = 111; configPage2.oddfire4 = 217; initialiseAll(); //Run the main initialise function const uint16_t angle[] = {0,13,111,0,0,0,0,0}; assert_ignition_schedules(360U, 3U, angle); } static void run_3_cylinder_4stroke_tests(void) { configPage2.nCylinders = 3; configPage2.strokes = FOUR_STROKE; RUN_TEST_P(cylinder3_stroke4_seq_even); RUN_TEST_P(cylinder3_stroke4_wasted_even); RUN_TEST_P(cylinder3_stroke4_wasted_odd); } static void cylinder4_stroke4_seq_even(void) { configPage4.sparkMode = IGN_MODE_SEQUENTIAL; configPage2.engineType = EVEN_FIRE; initialiseAll(); //Run the main initialise function const uint16_t angle[] = {0,180,360,540,0,0,0,0}; assert_ignition_schedules(720U, 4U, angle); } static void cylinder4_stroke4_wasted_even(void) { configPage4.sparkMode = IGN_MODE_WASTED; configPage2.engineType = EVEN_FIRE; initialiseAll(); //Run the main initialise function const uint16_t angle[] = {0,180,0,0,0,0,0,0}; assert_ignition_schedules(360U, 2U, angle); } static void cylinder4_stroke4_seq_odd(void) { configPage4.sparkMode = IGN_MODE_SEQUENTIAL; configPage2.engineType = ODD_FIRE; configPage2.oddfire2 = 13; configPage2.oddfire3 = 111; configPage2.oddfire4 = 217; initialiseAll(); //Run the main initialise function const uint16_t angle[] = {0,13,111,217,0,0,0,0}; assert_ignition_schedules(360U, 4U, angle); } static void run_4_cylinder_4stroke_tests(void) { configPage2.nCylinders = 4; configPage2.strokes = FOUR_STROKE; RUN_TEST_P(cylinder4_stroke4_seq_even); RUN_TEST_P(cylinder4_stroke4_wasted_even); RUN_TEST_P(cylinder4_stroke4_seq_odd); } static void cylinder5_stroke4_seq_even(void) { configPage4.sparkMode = IGN_MODE_SEQUENTIAL; configPage2.engineType = EVEN_FIRE; initialiseAll(); //Run the main initialise function const uint16_t angle[] = {0,144,288,432,576,0,0,0}; assert_ignition_schedules(720U, 5U, angle); } static void cylinder5_stroke4_wasted_even(void) { configPage4.sparkMode = IGN_MODE_WASTED; configPage2.engineType = EVEN_FIRE; initialiseAll(); //Run the main initialise function const uint16_t angle[] = {0,72,144,216,288,0,0,0}; assert_ignition_schedules(360U, 5U, angle); } static void run_5_cylinder_4stroke_tests(void) { configPage2.nCylinders = 5; configPage2.strokes = FOUR_STROKE; RUN_TEST_P(cylinder5_stroke4_seq_even); RUN_TEST_P(cylinder5_stroke4_wasted_even); } static void cylinder6_stroke4_seq_even(void) { configPage4.sparkMode = IGN_MODE_SEQUENTIAL; configPage2.engineType = EVEN_FIRE; initialiseAll(); //Run the main initialise function #if IGN_CHANNELS >= 6 const uint16_t angle[] = {0,120,240,360,480,540,0,0}; assert_ignition_schedules(720U, 6U, angle); #else const uint16_t angle[] = {0,120,240,0,0,0,0,0}; assert_ignition_schedules(360U, 3U, angle); #endif } static void cylinder6_stroke4_wasted_even(void) { configPage4.sparkMode = IGN_MODE_WASTED; configPage2.engineType = EVEN_FIRE; initialiseAll(); //Run the main initialise function const uint16_t angle[] = {0,120,240,0,0,0,0,0}; assert_ignition_schedules(360U, 3U, angle); } static void run_6_cylinder_4stroke_tests(void) { configPage2.nCylinders = 6; configPage2.strokes = FOUR_STROKE; RUN_TEST_P(cylinder6_stroke4_seq_even); RUN_TEST_P(cylinder6_stroke4_wasted_even); } static void cylinder8_stroke4_seq_even(void) { configPage4.sparkMode = IGN_MODE_SEQUENTIAL; configPage2.engineType = EVEN_FIRE; initialiseAll(); //Run the main initialise function #if IGN_CHANNELS >= 8 const uint16_t angle[] = {0,90,180,270,360,450,540,630}; assert_ignition_schedules(720U, 8U, angle); #else const uint16_t angle[] = {0,90,180,270,0,0,0,0}; assert_ignition_schedules(360U, 4U, angle); #endif } static void cylinder8_stroke4_wasted_even(void) { configPage4.sparkMode = IGN_MODE_WASTED; configPage2.engineType = EVEN_FIRE; initialiseAll(); //Run the main initialise function const uint16_t angle[] = {0,90,180,270,0,0,0,0}; assert_ignition_schedules(360U, 4U, angle); } static void run_8_cylinder_4stroke_tests(void) { configPage2.nCylinders = 8; configPage2.strokes = FOUR_STROKE; RUN_TEST_P(cylinder8_stroke4_seq_even); RUN_TEST_P(cylinder8_stroke4_wasted_even); } void testIgnitionScheduleInit() { run_1_cylinder_4stroke_tests(); run_2_cylinder_4stroke_tests(); run_3_cylinder_4stroke_tests(); run_4_cylinder_4stroke_tests(); run_5_cylinder_4stroke_tests(); run_6_cylinder_4stroke_tests(); run_8_cylinder_4stroke_tests(); }
9,565
C++
.cpp
267
33.397004
153
0.757075
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,010
main.cpp
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_init/main.cpp
#include <Arduino.h> #include <unity.h> void testInitialisation(void); void testFuelScheduleInit(void); void testIgnitionScheduleInit(void); #define UNITY_EXCLUDE_DETAILS void setup() { pinMode(LED_BUILTIN, OUTPUT); // NOTE!!! Wait for >2 secs // if board doesn't support software reset via Serial.DTR/RTS delay(2000); UNITY_BEGIN(); // IMPORTANT LINE! testInitialisation(); testFuelScheduleInit(); testIgnitionScheduleInit(); UNITY_END(); // stop unit testing } void loop() { // Blink to indicate end of test digitalWrite(LED_BUILTIN, HIGH); delay(250); digitalWrite(LED_BUILTIN, LOW); delay(250); }
667
C++
.cpp
26
22.230769
65
0.711356
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,540,011
test_fuel_schedule_init.cpp
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_init/test_fuel_schedule_init.cpp
#include <Arduino.h> #include <unity.h> #include "globals.h" #include "init.h" #include "schedule_calcs.h" #include "scheduledIO.h" #include "utilities.h" #include "../test_utils.h" extern uint16_t req_fuel_uS; static constexpr uint16_t reqFuel = 86; // ms * 10 static void __attribute__((noinline)) assert_fuel_channel(bool enabled, uint16_t angle, uint8_t cmdBit, int channelInjDegrees, voidVoidCallback startFunction, voidVoidCallback endFunction) { char msg[32]; sprintf_P(msg, PSTR("channel%" PRIu8 "InjDegrees.isEnabled"), cmdBit+1); TEST_ASSERT_EQUAL_MESSAGE(enabled, BIT_CHECK(channelInjEnabled, cmdBit), msg); sprintf_P(msg, PSTR("channe%" PRIu8 "InjDegrees"), cmdBit+1); TEST_ASSERT_EQUAL_MESSAGE(angle, channelInjDegrees, msg); sprintf_P(msg, PSTR("inj%" PRIu8 "StartFunction"), cmdBit+1); TEST_ASSERT_TRUE_MESSAGE(!enabled || (startFunction!=nullCallback), msg); sprintf_P(msg, PSTR("inj%" PRIu8 "EndFunction"), cmdBit+1); TEST_ASSERT_TRUE_MESSAGE(!enabled || (endFunction!=nullCallback), msg); } static void __attribute__((noinline)) assert_fuel_schedules(uint16_t crankAngle, uint16_t reqFuel, const bool enabled[], const uint16_t angle[]) { char msg[32]; strcpy_P(msg, PSTR("CRANK_ANGLE_MAX_INJ")); TEST_ASSERT_EQUAL_INT16_MESSAGE(crankAngle, CRANK_ANGLE_MAX_INJ, msg); strcpy_P(msg, PSTR("req_fuel_uS")); TEST_ASSERT_EQUAL_UINT16_MESSAGE(reqFuel, req_fuel_uS, msg); assert_fuel_channel(enabled[0], angle[0], INJ1_CMD_BIT, channel1InjDegrees, inj1StartFunction, inj1EndFunction); assert_fuel_channel(enabled[1], angle[1], INJ2_CMD_BIT, channel2InjDegrees, inj2StartFunction, inj2EndFunction); assert_fuel_channel(enabled[2], angle[2], INJ3_CMD_BIT, channel3InjDegrees, inj3StartFunction, inj3EndFunction); assert_fuel_channel(enabled[3], angle[3], INJ4_CMD_BIT, channel4InjDegrees, inj4StartFunction, inj4EndFunction); #if INJ_CHANNELS>=5 assert_fuel_channel(enabled[4], angle[4], INJ5_CMD_BIT, channel5InjDegrees, inj5StartFunction, inj5EndFunction); #endif #if INJ_CHANNELS>=6 assert_fuel_channel(enabled[5], angle[5], INJ6_CMD_BIT, channel6InjDegrees, inj6StartFunction, inj6EndFunction); #endif #if INJ_CHANNELS>=7 assert_fuel_channel(enabled[6], angle[6], INJ7_CMD_BIT, channel7InjDegrees, inj7StartFunction, inj7EndFunction); #endif #if INJ_CHANNELS>=8 assert_fuel_channel(enabled[7], angle[7], INJ8_CMD_BIT, channel8InjDegrees, inj8StartFunction, inj8EndFunction); #endif } static void cylinder1_stroke4_seq_nostage(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, false, false, false, false, false, false, false}; const uint16_t angle[] = {0,0,0,0,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle); } static void cylinder1_stroke4_semiseq_nostage(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, false, false, false, false, false, false, false}; const uint16_t angle[] = {0,0,0,0,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle); } static void cylinder1_stroke4_seq_staged(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, false, false, false, false, false, false}; const uint16_t angle[] = {0,0,0,0,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle); } static void cylinder1_stroke4_semiseq_staged(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, false, false, false, false, false, false}; const uint16_t angle[] = {0,0,0,0,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle); } static void run_1_cylinder_4stroke_tests(void) { configPage2.nCylinders = 1; configPage2.strokes = FOUR_STROKE; configPage2.engineType = EVEN_FIRE; configPage2.reqFuel = reqFuel; configPage2.divider = 1; RUN_TEST_P(cylinder1_stroke4_seq_nostage); RUN_TEST_P(cylinder1_stroke4_semiseq_nostage); RUN_TEST_P(cylinder1_stroke4_seq_staged); RUN_TEST_P(cylinder1_stroke4_semiseq_staged); } static void cylinder1_stroke2_seq_nostage(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, false, false, false, false, false, false, false}; const uint16_t angle[] = {0,0,0,0,0,0,0,0}; assert_fuel_schedules(360U, reqFuel * 100U, enabled, angle); } static void cylinder1_stroke2_semiseq_nostage(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, false, false, false, false, false, false, false}; const uint16_t angle[] = {0,0,0,0,0,0,0,0}; assert_fuel_schedules(360U, reqFuel * 100U, enabled, angle); } static void cylinder1_stroke2_seq_staged(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, false, false, false, false, false, false}; const uint16_t angle[] = {0,0,0,0,0,0,0,0}; assert_fuel_schedules(360U, reqFuel * 100U, enabled, angle); } static void cylinder1_stroke2_semiseq_staged(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, false, false, false, false, false, false}; const uint16_t angle[] = {0,0,0,0,0,0,0,0}; assert_fuel_schedules(360U, reqFuel * 100U, enabled, angle); } static void run_1_cylinder_2stroke_tests(void) { configPage2.nCylinders = 1; configPage2.strokes = TWO_STROKE; configPage2.engineType = EVEN_FIRE; configPage2.reqFuel = reqFuel; configPage2.divider = 1; RUN_TEST_P(cylinder1_stroke2_seq_nostage); RUN_TEST_P(cylinder1_stroke2_semiseq_nostage); RUN_TEST_P(cylinder1_stroke2_seq_staged); RUN_TEST_P(cylinder1_stroke2_semiseq_staged); } static void cylinder2_stroke4_seq_nostage(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, false, false, false, false, false, false}; const uint16_t angle[] = {0,180,0,0,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle); } static void cylinder2_stroke4_semiseq_nostage(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, false, false, false, false, false, false}; const uint16_t angle[] = {0,180,0,0,0,0,0,0}; assert_fuel_schedules(360U, reqFuel * 50U, enabled, angle); } static void cylinder2_stroke4_seq_staged(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,180,0,180,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle); } static void cylinder2_stroke4_semiseq_staged(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,180,0,180,0,0,0,0}; assert_fuel_schedules(360U, reqFuel * 50U, enabled, angle); } static void run_2_cylinder_4stroke_tests(void) { configPage2.nCylinders = 2; configPage2.strokes = FOUR_STROKE; configPage2.engineType = EVEN_FIRE; configPage2.reqFuel = reqFuel; configPage2.divider = 1; RUN_TEST_P(cylinder2_stroke4_seq_nostage); RUN_TEST_P(cylinder2_stroke4_semiseq_nostage); RUN_TEST_P(cylinder2_stroke4_seq_staged); RUN_TEST_P(cylinder2_stroke4_semiseq_staged); } static void cylinder2_stroke2_seq_nostage(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, false, false, false, false, false, false}; const uint16_t angle[] = {0,180,0,0,0,0,0,0}; assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle); } static void cylinder2_stroke2_semiseq_nostage(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, false, false, false, false, false, false}; const uint16_t angle[] = {0,180,0,0,0,0,0,0}; assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle); } static void cylinder2_stroke2_seq_staged(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,180,0,180,0,0,0,0}; assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle); } static void cylinder2_stroke2_semiseq_staged(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,180,0,180,0,0,0,0}; assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle); } static void run_2_cylinder_2stroke_tests(void) { configPage2.nCylinders = 2; configPage2.strokes = TWO_STROKE; configPage2.engineType = EVEN_FIRE; configPage2.reqFuel = reqFuel; configPage2.divider = 1; RUN_TEST_P(cylinder2_stroke2_seq_nostage); RUN_TEST_P(cylinder2_stroke2_semiseq_nostage); RUN_TEST_P(cylinder2_stroke2_seq_staged); RUN_TEST_P(cylinder2_stroke2_semiseq_staged); } static void cylinder3_stroke4_seq_nostage(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, true, false, false, false, false, false}; const uint16_t angle[] = {0,240,480,0,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle); } static void cylinder3_stroke4_semiseq_nostage(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, true, false, false, false, false, false}; const uint16_t angle[] = {0,80,160,0,0,0,0,0}; assert_fuel_schedules(240U, reqFuel * 50U, enabled, angle); } static void cylinder3_stroke4_seq_staged(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage2.injTiming = true; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function #if INJ_CHANNELS>=6 const bool enabled[] = {true, true, true, true, true, true, false, false}; const uint16_t angle[] = {0,240,480,0,240,480,0,0}; assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle); #else const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,240,480,0,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle); #endif } static void cylinder3_stroke4_semiseq_staged(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function #if INJ_CHANNELS>=6 const bool enabled[] = {true, true, true, true, true, true, false, false}; const uint16_t angle[] = {0,80,160,0,80,160,0,0}; assert_fuel_schedules(240U, reqFuel * 50U, enabled, angle); #else const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,80,160,0,0,0,0,0}; assert_fuel_schedules(240U, reqFuel * 50U, enabled, angle); #endif } static void run_3_cylinder_4stroke_tests(void) { configPage2.nCylinders = 3; configPage2.strokes = FOUR_STROKE; configPage2.engineType = EVEN_FIRE; configPage2.reqFuel = reqFuel; configPage2.divider = 1; RUN_TEST_P(cylinder3_stroke4_seq_nostage); RUN_TEST_P(cylinder3_stroke4_semiseq_nostage); RUN_TEST_P(cylinder3_stroke4_seq_staged); RUN_TEST_P(cylinder3_stroke4_semiseq_staged); } static void cylinder3_stroke2_seq_nostage(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, true, false, false, false, false, false}; const uint16_t angle[] = {0,80,160,0,0,0,0,0}; assert_fuel_schedules(120U, reqFuel * 100U, enabled, angle); } static void cylinder3_stroke2_semiseq_nostage(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, true, false, false, false, false, false}; const uint16_t angle[] = {0,80,160,0,0,0,0,0}; assert_fuel_schedules(120U, reqFuel * 100U, enabled, angle); } static void cylinder3_stroke2_seq_staged(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function #if INJ_CHANNELS>=6 const bool enabled[] = {true, true, true, true, true, true, false, false}; const uint16_t angle[] = {0,80,160,0,80,160,0,0}; assert_fuel_schedules(120U, reqFuel * 100U, enabled, angle); #else const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,80,160,0,0,0,0,0}; assert_fuel_schedules(120U, reqFuel * 100U, enabled, angle); #endif } static void cylinder3_stroke2_semiseq_staged(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function #if INJ_CHANNELS>=6 const bool enabled[] = {true, true, true, true, true, true, false, false}; const uint16_t angle[] = {0,80,160,0,80,160,0,0}; assert_fuel_schedules(120U, reqFuel * 100U, enabled, angle); #else const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,80,160,0,0,0,0,0}; assert_fuel_schedules(120U, reqFuel * 100U, enabled, angle); #endif } static void run_3_cylinder_2stroke_tests(void) { configPage2.nCylinders = 3; configPage2.strokes = TWO_STROKE; configPage2.engineType = EVEN_FIRE; configPage2.injTiming = true; configPage2.reqFuel = reqFuel; configPage2.divider = 1; RUN_TEST_P(cylinder3_stroke2_seq_nostage); RUN_TEST_P(cylinder3_stroke2_semiseq_nostage); RUN_TEST_P(cylinder3_stroke2_seq_staged); RUN_TEST_P(cylinder3_stroke2_semiseq_staged); } static void cylinder4_stroke4_seq_nostage(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,180,360,540,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle); } static void cylinder4_stroke4_semiseq_nostage(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, false, false, false, false, false, false}; const uint16_t angle[] = {0,180,0,0,0,0,0,0}; assert_fuel_schedules(360U, reqFuel * 50U, enabled, angle); } static void cylinder4_stroke4_seq_staged(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function #if INJ_CHANNELS>=8 const bool enabled[] = {true, true, true, true, true, true, true, true}; const uint16_t angle[] = {0,180,360,540,0,180,36}; assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle); #elif INJ_CHANNELS >= 5 const bool enabled[] = {true, true, true, true, true, false, false, false}; const uint16_t angle[] = {0,180,360,540,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle); #else const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,180,360,540,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle); #endif } static void cylinder4_stroke4_semiseq_staged(void) { configPage2.injLayout = INJ_PAIRED; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,180,0,180,0,0,0,0}; assert_fuel_schedules(360U, reqFuel * 50U, enabled, angle); } void run_4_cylinder_4stroke_tests(void) { configPage2.nCylinders = 4; configPage2.strokes = FOUR_STROKE; configPage2.engineType = EVEN_FIRE; configPage2.injTiming = true; configPage2.reqFuel = reqFuel; configPage2.divider = 2; RUN_TEST_P(cylinder4_stroke4_seq_nostage); RUN_TEST_P(cylinder4_stroke4_semiseq_nostage); RUN_TEST_P(cylinder4_stroke4_seq_staged); RUN_TEST_P(cylinder4_stroke4_semiseq_staged); } static void cylinder4_stroke2_seq_nostage(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, false, false, false, false, false, false}; const uint16_t angle[] = {0,180,0,0,0,0,0,0}; assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle); } static void cylinder4_stroke2_semiseq_nostage(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, false, false, false, false, false, false}; const uint16_t angle[] = {0,180,0,0,0,0,0,0}; assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle); } static void cylinder4_stroke2_seq_staged(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function #if INJ_CHANNELS>=8 const bool enabled[] = {true, true, true, true, true, true, true, true}; const uint16_t angle[] = {0,180,0,0,0,180,0,0}; assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle); #elif INJ_CHANNELS >= 5 const bool enabled[] = {true, true, true, true, true, false, false, false}; const uint16_t angle[] = {0,180,0,0,0,0,0,0}; assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle); #else const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,180,0,0,0,0,0,0}; assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle); #endif } static void cylinder4_stroke2_semiseq_staged(void) { configPage2.injLayout = INJ_PAIRED; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,180,0,180,0,0,0,0}; assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle); } void run_4_cylinder_2stroke_tests(void) { configPage2.nCylinders = 4; configPage2.strokes = TWO_STROKE; configPage2.engineType = EVEN_FIRE; configPage2.injTiming = true; configPage2.reqFuel = reqFuel; configPage2.divider = 2; RUN_TEST_P(cylinder4_stroke2_seq_nostage); RUN_TEST_P(cylinder4_stroke2_semiseq_nostage); RUN_TEST_P(cylinder4_stroke2_seq_staged); RUN_TEST_P(cylinder4_stroke2_semiseq_staged); } static void cylinder5_stroke4_seq_nostage(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function #if INJ_CHANNELS >= 5 const bool enabled[] = {true, true, true, true, true, false, false, false}; const uint16_t angle[] = {0,144,288,432,576,0,0,0}; assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle); #else const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,0,0,0,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle); #endif } static void cylinder5_stroke4_semiseq_nostage(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,72,144,216,288,0,0,0}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle); } static void cylinder5_stroke4_seq_staged(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function #if INJ_CHANNELS >= 6 const bool enabled[] = {true, true, true, true, true, true, false, false}; const uint16_t angle[] = {0,144,288,432,576,0,0,0}; assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle); #else const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,0,0,0,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle); #endif } static void cylinder5_stroke4_semiseq_staged(void) { configPage2.injLayout = INJ_PAIRED; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function #if INJ_CHANNELS >= 5 const bool enabled[] = {true, true, true, true, true, false, false, false}; const uint16_t angle[] = {0,72,144,216,288,0,0,0}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle); #else const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,72,144,216,288,0,0,0}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle); #endif } void run_5_cylinder_4stroke_tests(void) { configPage2.nCylinders = 5; configPage2.strokes = FOUR_STROKE; configPage2.engineType = EVEN_FIRE; configPage2.injTiming = true; configPage2.reqFuel = reqFuel; configPage2.divider = 5; RUN_TEST_P(cylinder5_stroke4_seq_nostage); RUN_TEST_P(cylinder5_stroke4_semiseq_nostage); RUN_TEST_P(cylinder5_stroke4_seq_staged); RUN_TEST_P(cylinder5_stroke4_semiseq_staged); } static void cylinder6_stroke4_seq_nostage(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function #if INJ_CHANNELS >= 6 const bool enabled[] = {true, true, true, true, true, true, false, false}; const uint16_t angle[] = {0,120,240,360,480,600,0}; assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle); #else const bool enabled[] = {true, true, true, false, false, false, false, false}; const uint16_t angle[] = {0,0,0,0,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle); #endif } static void cylinder6_stroke4_semiseq_nostage(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, true, false, false, false, false, false}; const uint16_t angle[] = {0,120,240,0,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle); } static void cylinder6_stroke4_seq_staged(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function #if INJ_CHANNELS >= 8 const bool enabled[] = {true, true, true, true, true, true, false, false}; const uint16_t angle[] = {0,120,240,360,480,600,0,0}; assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle); #else const bool enabled[] = {true, true, true, false, false, false, false, false}; const uint16_t angle[] = {0,0,0,0,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle); #endif } static void cylinder6_stroke4_semiseq_staged(void) { configPage2.injLayout = INJ_SEMISEQUENTIAL; configPage10.stagingEnabled = true; initialiseAll(); //Run the main initialise function #if INJ_CHANNELS >= 8 const bool enabled[] = {true, true, true, true, true, true, true, true}; const uint16_t angle[] = {0,120,240,0,0,120,240,0}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle); #else const bool enabled[] = {true, true, true, false, false, false, false, false}; const uint16_t angle[] = {0,120,240,0,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle); #endif } void run_6_cylinder_4stroke_tests(void) { configPage2.nCylinders = 6; configPage2.strokes = FOUR_STROKE; configPage2.engineType = EVEN_FIRE; configPage2.injTiming = true; configPage2.reqFuel = reqFuel; configPage2.divider = 6; RUN_TEST_P(cylinder6_stroke4_seq_nostage); RUN_TEST_P(cylinder6_stroke4_semiseq_nostage); RUN_TEST_P(cylinder6_stroke4_seq_staged); RUN_TEST_P(cylinder6_stroke4_semiseq_staged); } static void cylinder8_stroke4_seq_nostage(void) { configPage2.injLayout = INJ_SEQUENTIAL; configPage10.stagingEnabled = false; initialiseAll(); //Run the main initialise function #if INJ_CHANNELS >= 8 const bool enabled[] = {true, true, true, true, true, true, true, true}; const uint16_t angle[] = {0,90,180,270,360,450,5}; assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle); #else const bool enabled[] = {true, true, true, true, false, false, false, false}; const uint16_t angle[] = {0,0,0,0,0,0,0,0}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle); #endif } void run_8_cylinder_4stroke_tests(void) { configPage2.nCylinders = 8; configPage2.strokes = FOUR_STROKE; configPage2.engineType = EVEN_FIRE; configPage2.injTiming = true; configPage2.reqFuel = reqFuel; configPage2.divider = 8; // Staging not supported on 8 cylinders RUN_TEST_P(cylinder8_stroke4_seq_nostage); } static constexpr uint16_t zeroAngles[] = {0,0,0,0,0,0,0,0}; static void cylinder_1_NoinjTiming_paired(void) { configPage2.injLayout = INJ_PAIRED; configPage2.nCylinders = 1; configPage2.divider = 1; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, false, false, false, false, false, false, false}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, zeroAngles); } static void cylinder_2_NoinjTiming_paired(void) { configPage2.injLayout = INJ_PAIRED; configPage2.nCylinders = 2; configPage2.divider = 2; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, false, false, false, false, false, false}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, zeroAngles); } static void cylinder_3_NoinjTiming_paired(void) { configPage2.injLayout = INJ_PAIRED; configPage2.nCylinders = 3; configPage2.divider = 3; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, true, false, false, false, false, false}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, zeroAngles); } static void cylinder_4_NoinjTiming_paired(void) { configPage2.injLayout = INJ_PAIRED; configPage2.nCylinders = 4; configPage2.divider = 4; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, false, false, false, false, false, false}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, zeroAngles); } static void cylinder_5_NoinjTiming_paired(void) { configPage2.injLayout = INJ_PAIRED; configPage2.nCylinders = 5; configPage2.divider = 5; initialiseAll(); //Run the main initialise function #if INJ_CHANNELS>=5 const bool enabled[] = {true, true, true, true, true, false, false, false}; #else const bool enabled[] = {true, true, true, true, false, false, false, false}; #endif assert_fuel_schedules(720U, reqFuel * 50U, enabled, zeroAngles); } static void cylinder_6_NoinjTiming_paired(void) { configPage2.injLayout = INJ_PAIRED; configPage2.nCylinders = 6; configPage2.divider = 6; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, true, false, false, false, false, false}; assert_fuel_schedules(720U, reqFuel * 50U, enabled, zeroAngles); } static void cylinder_8_NoinjTiming_paired(void) { configPage2.injLayout = INJ_PAIRED; configPage2.nCylinders = 8; configPage2.divider = 8; initialiseAll(); //Run the main initialise function #if INJ_CHANNELS>=8 const bool enabled[] = {true, true, true, true, true, true, true, true}; #else const bool enabled[] = {true, true, true, true, false, false, false, false}; #endif assert_fuel_schedules(720U, reqFuel * 50U, enabled, zeroAngles); } static void run_no_inj_timing_tests(void) { configPage2.strokes = FOUR_STROKE; configPage2.engineType = EVEN_FIRE; configPage2.injTiming = false; configPage2.reqFuel = reqFuel; configPage10.stagingEnabled = false; RUN_TEST_P(cylinder_1_NoinjTiming_paired); RUN_TEST_P(cylinder_2_NoinjTiming_paired); RUN_TEST_P(cylinder_3_NoinjTiming_paired); RUN_TEST_P(cylinder_4_NoinjTiming_paired); RUN_TEST_P(cylinder_5_NoinjTiming_paired); RUN_TEST_P(cylinder_6_NoinjTiming_paired); RUN_TEST_P(cylinder_8_NoinjTiming_paired); } static void cylinder_2_oddfire(void) { configPage2.injLayout = INJ_PAIRED; configPage2.nCylinders = 2; configPage2.divider = 2; initialiseAll(); //Run the main initialise function const bool enabled[] = {true, true, false, false, false, false, false, false}; const uint16_t angle[] = {0,13,0,0,0,0,0,0}; Serial.println(configPage2.engineType); assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle); } static void run_oddfire_tests() { configPage2.strokes = FOUR_STROKE; configPage2.engineType = ODD_FIRE; configPage2.injTiming = true; configPage2.reqFuel = reqFuel; configPage10.stagingEnabled = false; configPage2.oddfire2 = 13; configPage2.oddfire3 = 111; configPage2.oddfire4 = 217; // Oddfire only affects 2 cylinder configurations configPage2.nCylinders = 1; configPage2.divider = 1; RUN_TEST_P(cylinder1_stroke4_seq_nostage); RUN_TEST_P(cylinder_2_oddfire); configPage2.nCylinders = 3; configPage2.divider = 1; RUN_TEST_P(cylinder3_stroke4_seq_nostage); configPage2.nCylinders = 4; configPage2.divider = 2; RUN_TEST_P(cylinder4_stroke4_seq_nostage); configPage2.nCylinders = 5; configPage2.divider = 5; RUN_TEST_P(cylinder5_stroke4_seq_nostage); configPage2.nCylinders = 6; configPage2.divider = 6; RUN_TEST_P(cylinder6_stroke4_seq_nostage); configPage2.nCylinders = 8; configPage2.divider = 8; RUN_TEST_P(cylinder8_stroke4_seq_nostage); } void testFuelScheduleInit() { run_1_cylinder_4stroke_tests(); run_1_cylinder_2stroke_tests(); run_2_cylinder_4stroke_tests(); run_2_cylinder_2stroke_tests(); run_3_cylinder_4stroke_tests(); run_3_cylinder_2stroke_tests(); run_4_cylinder_4stroke_tests(); run_4_cylinder_2stroke_tests(); run_5_cylinder_4stroke_tests(); run_6_cylinder_4stroke_tests(); run_8_cylinder_4stroke_tests(); run_no_inj_timing_tests(); run_oddfire_tests(); }
31,710
C++
.cpp
794
37.481108
188
0.741462
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,012
tests_init.cpp
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_init/tests_init.cpp
#include <unity.h> #include "globals.h" #include "init.h" #include "../test_utils.h" #define UNKNOWN_PIN 0xFF #if !defined(NOT_A_PIN) #define NOT_A_PIN 0 #endif uint8_t getPinMode(uint8_t pin) { uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); // I don't see an option for mega to return this, but whatever... if (NOT_A_PIN == port) return UNKNOWN_PIN; // Is there a bit we can check? if (0 == bit) return UNKNOWN_PIN; // Is there only a single bit set? if (bit & (bit - 1)) return UNKNOWN_PIN; volatile uint8_t *reg, *out; reg = portModeRegister(port); out = portOutputRegister(port); if (*reg & bit) return OUTPUT; else if (*out & bit) return INPUT_PULLUP; else return INPUT; } void test_initialisation_complete(void) { initialiseAll(); //Run the main initialise function TEST_ASSERT_EQUAL(true, initialisationComplete); } void test_initialisation_ports(void) { //Test that all the port values have been set initialiseAll(); //Run the main initialise function TEST_ASSERT_NOT_EQUAL(0, inj1_pin_port); TEST_ASSERT_NOT_EQUAL(0, inj2_pin_port); TEST_ASSERT_NOT_EQUAL(0, inj3_pin_port); TEST_ASSERT_NOT_EQUAL(0, inj4_pin_port); TEST_ASSERT_NOT_EQUAL(0, ign1_pin_port); TEST_ASSERT_NOT_EQUAL(0, ign2_pin_port); TEST_ASSERT_NOT_EQUAL(0, ign3_pin_port); TEST_ASSERT_NOT_EQUAL(0, ign4_pin_port); } //Test that all mandatory output pins have their mode correctly set to output void test_initialisation_outputs_V03(void) { configPage2.pinMapping = 2; //Set the board number to test initialiseAll(); //Run the main initialise function char msg[32]; strcpy_P(msg, PSTR("Coil1")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil1), msg); strcpy_P(msg, PSTR("Coil2")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil2), msg); strcpy_P(msg, PSTR("Coil3")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil3), msg); strcpy_P(msg, PSTR("Coil4")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil4), msg); strcpy_P(msg, PSTR("Injector 1")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector1), msg); strcpy_P(msg, PSTR("Injector 2")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector2), msg); strcpy_P(msg, PSTR("Injector 3")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector3), msg); strcpy_P(msg, PSTR("Injector 4")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector4), msg); strcpy_P(msg, PSTR("Tacho Out")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinTachOut), msg); strcpy_P(msg, PSTR("Fuel Pump")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinFuelPump), msg); strcpy_P(msg, PSTR("Fan")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinFan), msg); } //Test that all mandatory output pins have their mode correctly set to output void test_initialisation_outputs_V04(void) { configPage2.pinMapping = 3; //Set the board number to test initialiseAll(); //Run the main initialise function char msg[32]; strcpy_P(msg, PSTR("Coil1")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil1), msg); strcpy_P(msg, PSTR("Coil2")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil2), msg); strcpy_P(msg, PSTR("Coil3")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil3), msg); strcpy_P(msg, PSTR("Coil4")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil4), msg); strcpy_P(msg, PSTR("Injector 1")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector1), msg); strcpy_P(msg, PSTR("Injector 2")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector2), msg); strcpy_P(msg, PSTR("Injector 3")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector3), msg); strcpy_P(msg, PSTR("Injector 4")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector4), msg); strcpy_P(msg, PSTR("Tacho Out")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinTachOut), msg); strcpy_P(msg, PSTR("Fuel Pump")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinFuelPump), msg); strcpy_P(msg, PSTR("Fan")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinFan), msg); /* if(isIdlePWM) { TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinIdle1), "Idle 1"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinIdle2), "Idle 2"); } else if (isIdleStepper) { TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinStepperDir), "Stepper Dir"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinStepperStep), "Stepper Step"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinStepperEnable), "Stepper Enable"); } TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinFan), "Fan"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinBoost), "Boost"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinVVT_1), "VVT1"); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinVVT_2), "VVT2"); */ } //Test that all mandatory output pins have their mode correctly set to output void test_initialisation_outputs_MX5_8995(void) { configPage2.pinMapping = 9; //Set the board number to test initialiseAll(); //Run the main initialise function char msg[32]; strcpy_P(msg, PSTR("Coil1")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil1), msg); strcpy_P(msg, PSTR("Coil2")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil2), msg); strcpy_P(msg, PSTR("Coil3")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil3), msg); strcpy_P(msg, PSTR("Coil4")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinCoil4), msg); strcpy_P(msg, PSTR("Injector 1")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector1), msg); strcpy_P(msg, PSTR("Injector 2")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector2), msg); strcpy_P(msg, PSTR("Injector 3")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector3), msg); strcpy_P(msg, PSTR("Injector 4")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinInjector4), msg); strcpy_P(msg, PSTR("Tacho Out")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinTachOut), msg); strcpy_P(msg, PSTR("Fuel Pump")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinFuelPump), msg); strcpy_P(msg, PSTR("Fan")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinFan), msg); } void test_initialisation_outputs_PWM_idle(void) { configPage2.pinMapping = 3; //Set the board number to test (v0.4) //Force 2 channel PWM idle configPage6.iacChannels = 1; configPage6.iacAlgorithm = 2; initialiseAll(); //Run the main initialise function bool isIdlePWM = (configPage6.iacAlgorithm > 0) && ((configPage6.iacAlgorithm <= 3) || (configPage6.iacAlgorithm == 6)); char msg[32]; strcpy_P(msg, PSTR("Is PWM Idle")); TEST_ASSERT_TRUE_MESSAGE(isIdlePWM, msg); strcpy_P(msg, PSTR("Idle 1")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinIdle1), msg); strcpy_P(msg, PSTR("Idle 2")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinIdle2), msg); } void test_initialisation_outputs_stepper_idle(void) { bool isIdleStepper = (configPage6.iacAlgorithm > 3) && (configPage6.iacAlgorithm != 6); char msg[32]; strcpy_P(msg, PSTR("Is Stepper Idle")); TEST_ASSERT_TRUE_MESSAGE(isIdleStepper, msg); strcpy_P(msg, PSTR("Stepper Dir")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinStepperDir), msg); strcpy_P(msg, PSTR("Stepper Step")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinStepperStep), msg); strcpy_P(msg, PSTR("Stepper Enable")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinStepperEnable), msg); } void test_initialisation_outputs_boost(void) { char msg[32]; strcpy_P(msg, PSTR("Boost")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinBoost), msg); } void test_initialisation_outputs_VVT(void) { char msg[32]; strcpy_P(msg, PSTR("VVT1")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinVVT_1), msg); strcpy_P(msg, PSTR("VVT2")); TEST_ASSERT_EQUAL_MESSAGE(OUTPUT, getPinMode(pinVVT_2), msg); } void testInitialisation() { RUN_TEST_P(test_initialisation_complete); RUN_TEST_P(test_initialisation_ports); RUN_TEST_P(test_initialisation_outputs_V03); RUN_TEST_P(test_initialisation_outputs_V04); RUN_TEST_P(test_initialisation_outputs_MX5_8995); RUN_TEST_P(test_initialisation_outputs_PWM_idle); RUN_TEST_P(test_initialisation_outputs_boost); RUN_TEST_P(test_initialisation_outputs_VVT); }
8,303
C++
.cpp
204
37.906863
122
0.735564
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,013
main.cpp
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_tables/main.cpp
#include <Arduino.h> #include <unity.h> #include "tests_tables.h" #include "test_table2d.h" #define UNITY_EXCLUDE_DETAILS void setup() { pinMode(LED_BUILTIN, OUTPUT); // NOTE!!! Wait for >2 secs // if board doesn't support software reset via Serial.DTR/RTS delay(2000); UNITY_BEGIN(); // IMPORTANT LINE! testTables(); testTable2d(); UNITY_END(); // stop unit testing } void loop() { // Blink to indicate end of test digitalWrite(LED_BUILTIN, HIGH); delay(250); digitalWrite(LED_BUILTIN, LOW); delay(250); }
569
C++
.cpp
24
20.25
65
0.672862
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,540,014
tests_tables.cpp
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_tables/tests_tables.cpp
//#include <Arduino.h> #include <string.h> // memcpy #include <unity.h> #include <stdio.h> #include "tests_tables.h" #include "table3d.h" #define _countof(x) (sizeof(x) / sizeof (x[0])) #if defined(PROGMEM) const PROGMEM table3d_value_t values[] = { #else const table3d_value_t values[] = { #endif //0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 34, 34, 34, 34, 34, 34, 34, 34, 34, 35, 35, 35, 35, 35, 35, 35, 34, 35, 36, 37, 39, 41, 42, 43, 43, 44, 44, 44, 44, 44, 44, 44, 35, 36, 38, 41, 44, 46, 47, 48, 48, 49, 49, 49, 49, 49, 49, 49, 36, 39, 42, 46, 50, 51, 52, 53, 53, 53, 53, 53, 53, 53, 53, 53, 38, 43, 48, 52, 55, 56, 57, 58, 58, 58, 58, 58, 58, 58, 58, 58, 42, 49, 54, 58, 61, 62, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 48, 56, 60, 64, 66, 66, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 54, 62, 66, 69, 71, 71, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 61, 69, 72, 74, 76, 76, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 68, 75, 78, 79, 81, 81, 81, 82, 82, 82, 82, 82, 82, 82, 82, 82, 74, 80, 83, 84, 85, 86, 86, 86, 87, 87, 87, 87, 87, 87, 87, 87, 81, 86, 88, 89, 90, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 93, 96, 98, 99, 99, 100, 100, 101, 101, 101, 101, 101, 101, 101, 101, 101, 98, 101, 103, 103, 104, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 104, 106, 107, 108, 109, 109, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 109, 111, 112, 113, 114, 114, 114, 115, 115, 115, 114, 114, 114, 114, 114, 114, }; static const table3d_axis_t tempXAxis[] = {500, 700, 900, 1200, 1600, 2000, 2500, 3100, 3500, 4100, 4700, 5300, 5900, 6500, 6750, 7000}; static const table3d_axis_t xMin = tempXAxis[0]; static const table3d_axis_t xMax = tempXAxis[_countof(tempXAxis)-1]; static const table3d_axis_t tempYAxis[] = { 16, 26, 30, 36, 40, 46, 50, 56, 60, 66, 70, 76, 86, 90, 96, 100}; static const table3d_axis_t yMin = tempYAxis[0]; static const table3d_axis_t yMax = tempYAxis[_countof(tempYAxis)-1]; static table3d16RpmLoad testTable; void setup_TestTable(void) { //Setup the fuel table with some sane values for testing //Table is setup per the below /* 100 | 109 | 111 | 112 | 113 | 114 | 114 | 114 | 115 | 115 | 115 | 114 | 114 | 113 | 112 | 111 | 111 96 | 104 | 106 | 107 | 108 | 109 | 109 | 110 | 110 | 110 | 110 | 110 | 109 | 108 | 107 | 107 | 106 90 | 98 | 101 | 103 | 103 | 104 | 105 | 105 | 105 | 105 | 105 | 105 | 104 | 104 | 103 | 102 | 102 86 | 93 | 96 | 98 | 99 | 99 | 100 | 100 | 101 | 101 | 101 | 100 | 100 | 99 | 98 | 98 | 97 76 | 81 | 86 | 88 | 89 | 90 | 91 | 91 | 91 | 91 | 91 | 91 | 90 | 90 | 89 | 89 | 88 70 | 74 | 80 | 83 | 84 | 85 | 86 | 86 | 86 | 87 | 86 | 86 | 86 | 85 | 84 | 84 | 84 65 | 68 | 75 | 78 | 79 | 81 | 81 | 81 | 82 | 82 | 82 | 82 | 81 | 81 | 80 | 79 | 79 60 | 61 | 69 | 72 | 74 | 76 | 76 | 77 | 77 | 77 | 77 | 77 | 76 | 76 | 75 | 75 | 74 56 | 54 | 62 | 66 | 69 | 71 | 71 | 72 | 72 | 72 | 72 | 72 | 72 | 71 | 71 | 70 | 70 50 | 48 | 56 | 60 | 64 | 66 | 66 | 68 | 68 | 68 | 68 | 67 | 67 | 67 | 66 | 66 | 65 46 | 42 | 49 | 54 | 58 | 61 | 62 | 62 | 63 | 63 | 63 | 63 | 62 | 62 | 61 | 61 | 61 40 | 38 | 43 | 48 | 52 | 55 | 56 | 57 | 58 | 58 | 58 | 58 | 58 | 57 | 57 | 57 | 56 36 | 36 | 39 | 42 | 46 | 50 | 51 | 52 | 53 | 53 | 53 | 53 | 53 | 53 | 52 | 52 | 52 30 | 35 | 36 | 38 | 41 | 44 | 46 | 47 | 48 | 48 | 49 | 48 | 48 | 48 | 48 | 47 | 47 26 | 34 | 35 | 36 | 37 | 39 | 41 | 42 | 43 | 43 | 44 | 44 | 44 | 43 | 43 | 43 | 43 16 | 34 | 34 | 34 | 34 | 34 | 34 | 34 | 34 | 34 | 35 | 34 | 34 | 34 | 34 | 34 | 34 ---------------------------------------------------------------------------------------------------------------- 500 | 700 | 900 | 1200 | 1600 | 2000 | 2500 | 3100 | 3500 | 4100 | 4700 | 5300 | 5900 | 6500 | 6750 | 7000 */ // // NOTE: USE OF ITERATORS HERE IS DELIBERATE. IT INCLUDES THEM IN THE UNIT TESTS, giving // them some coverage // { table_axis_iterator itX = testTable.axisX.begin(); const table3d_axis_t *pXValue = tempXAxis; while (!itX.at_end()) { *itX = *pXValue; ++pXValue; ++itX; } } { table_axis_iterator itY = testTable.axisY.begin(); const table3d_axis_t *pYValue = tempYAxis; while (!itY.at_end()) { *itY = *pYValue; ++pYValue; ++itY; } } { table_value_iterator itZ = testTable.values.begin(); const table3d_value_t *pZValue = values; while (!itZ.at_end()) { table_row_iterator itRow = *itZ; while (!itRow.at_end()) { #if defined(PROGMEM) *itRow = pgm_read_byte(pZValue); #else *itRow = *pZValue; #endif ++pZValue; ++itRow; } ++itZ; } } } void testTables() { RUN_TEST(test_tableLookup_50pct); RUN_TEST(test_tableLookup_exact1Axis); RUN_TEST(test_tableLookup_exact2Axis); RUN_TEST(test_tableLookup_overMaxX); RUN_TEST(test_tableLookup_overMaxY); RUN_TEST(test_tableLookup_underMinX); RUN_TEST(test_tableLookup_underMinY); RUN_TEST(test_tableLookup_roundUp); //RUN_TEST(test_all_incrementing); } void test_tableLookup_50pct(void) { //Tests a lookup that is exactly 50% of the way between cells on both the X and Y axis setup_TestTable(); uint16_t tempVE = get3DTableValue(&testTable, 53, 2250); //Perform lookup into fuel map for RPM vs MAP value TEST_ASSERT_EQUAL(tempVE, 69); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastXBinMax, (table3d_dim_t)9); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastYBinMax, (table3d_dim_t)8); } void test_tableLookup_exact1Axis(void) { //Tests a lookup that exactly matches on the X axis and 50% of the way between cells on the Y axis setup_TestTable(); uint16_t tempVE = get3DTableValue(&testTable, 48, testTable.axisX.axis[6]); //Perform lookup into fuel map for RPM vs MAP value TEST_ASSERT_EQUAL(tempVE, 65); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastXBinMax, (table3d_dim_t)6); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastYBinMax, (table3d_dim_t)9); } void test_tableLookup_exact2Axis(void) { //Tests a lookup that exactly matches on both the X and Y axis setup_TestTable(); uint16_t tempVE = get3DTableValue(&testTable, testTable.axisY.axis[5], testTable.axisX.axis[9]); //Perform lookup into fuel map for RPM vs MAP value TEST_ASSERT_EQUAL(tempVE, 86); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastXBinMax, (table3d_dim_t)9); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastYBinMax, (table3d_dim_t)5); } void test_tableLookup_overMaxX(void) { //Tests a lookup where the RPM exceeds the highest value in the table. The Y value is a 50% match setup_TestTable(); uint16_t tempVE = get3DTableValue(&testTable, 73, xMax+100); //Perform lookup into fuel map for RPM vs MAP value TEST_ASSERT_EQUAL(tempVE, 89); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastXBinMax, (table3d_dim_t)0); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastYBinMax, (table3d_dim_t)4); } void test_tableLookup_overMaxY(void) { //Tests a lookup where the load value exceeds the highest value in the table. The X value is a 50% match setup_TestTable(); uint16_t tempVE = get3DTableValue(&testTable, yMax+10, 600); //Perform lookup into fuel map for RPM vs MAP value TEST_ASSERT_EQUAL(tempVE, 110); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastXBinMax, (table3d_dim_t)14); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastYBinMax, (table3d_dim_t)0); } void test_tableLookup_underMinX(void) { //Tests a lookup where the RPM value is below the lowest value in the table. The Y value is a 50% match setup_TestTable(); uint16_t tempVE = get3DTableValue(&testTable, 38, xMin-100); //Perform lookup into fuel map for RPM vs MAP value TEST_ASSERT_EQUAL(tempVE, 37); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastXBinMax, (table3d_dim_t)14); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastYBinMax, (table3d_dim_t)11); } void test_tableLookup_underMinY(void) { //Tests a lookup where the load value is below the lowest value in the table. The X value is a 50% match setup_TestTable(); uint16_t tempVE = get3DTableValue(&testTable, yMin-5, 600); //Perform lookup into fuel map for RPM vs MAP value TEST_ASSERT_EQUAL(tempVE, 34); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastXBinMax, (table3d_dim_t)14); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastYBinMax, (table3d_dim_t)14); } void test_tableLookup_roundUp(void) { // Tests a lookup where the inputs result in a value that is outside the table range // due to fixed point rounding // Issue #726 setup_TestTable(); uint16_t tempVE = get3DTableValue(&testTable, 17, 600); TEST_ASSERT_EQUAL(tempVE, 34); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastXBinMax, (table3d_dim_t)14); TEST_ASSERT_EQUAL(testTable.get_value_cache.lastYBinMax, (table3d_dim_t)14); } void test_all_incrementing(void) { //Test the when going up both the load and RPM axis that the returned value is always equal or higher to the previous one //Tests all combinations of load/rpm from between 0-200 load and 0-9000 rpm //WARNING: This can take a LONG time to run. It is disabled by default for this reason uint16_t tempVE = 0; for(uint16_t rpm = 0; rpm<xMax+1000; rpm+=100) { tempVE = 0; for(uint8_t load = 0; load<yMax+10; load++) { uint16_t newVE = get3DTableValue(&testTable, load, rpm); // char buffer[256]; // sprintf(buffer, "%d, %d" // ", %d, %d, %d, %d" // ", %d, %d, %d, %d" // ", %d", // rpm, load, // testTable.get_value_cache.lastXMin, testTable.get_value_cache.lastXBinMax, // tempXAxis[testTable.get_value_cache.lastXMin], tempXAxis[testTable.get_value_cache.lastXBinMax], // testTable.get_value_cache.lastYMin, testTable.get_value_cache.lastYBinMax, // tempYAxis[testTable.get_value_cache.lastYMin], tempYAxis[testTable.get_value_cache.lastYBinMax], // newVE); // TEST_MESSAGE(buffer); TEST_ASSERT_GREATER_OR_EQUAL(tempVE, newVE); tempVE = newVE; } } }
10,846
C++
.cpp
220
45.918182
150
0.590145
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false