├── .gitignore ├── src ├── LPCClocklessSimulationDataGenerator.cpp ├── LPCClocklessSimulationDataGenerator.h ├── LPCClocklessAnalyzerSettings.h ├── LPCClocklessAnalyzerResults.h ├── LPCClocklessAnalyzer.h ├── LPCClocklessAnalyzerResults.cpp ├── LPCClocklessAnalyzerSettings.cpp └── LPCClocklessAnalyzer.cpp ├── docs ├── pid.png └── Analyzer_API.md ├── readme.md ├── CMakeLists.txt ├── .clang-format ├── LICENSE ├── cmake └── ExternalAnalyzerSDK.cmake ├── .github └── workflows │ └── build.yml ├── rename_analyzer.py └── sample_readme.md /.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /src/LPCClocklessSimulationDataGenerator.cpp: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/LPCClocklessSimulationDataGenerator.h: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/pid.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stacksmashing/LPCClocklessAnalyzer/HEAD/docs/pid.png -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # LPCClocklessAnalyzer 2 | 3 | This is an analyzer for LPC TPM traffic that does not require the clock signal. 4 | 5 | ## Building this Analyzer 6 | 7 | ### Windows 8 | 9 | ```bat 10 | mkdir build 11 | cd build 12 | cmake .. -A x64 13 | cmake --build . 14 | :: built analyzer will be located at SampleAnalyzer\build\Analyzers\Debug\SimpleSerialAnalyzer.dll 15 | ``` 16 | 17 | ### MacOS 18 | 19 | ```bash 20 | mkdir build 21 | cd build 22 | cmake .. 23 | cmake --build . 24 | # built analyzer will be located at SampleAnalyzer/build/Analyzers/libSimpleSerialAnalyzer.so 25 | ``` 26 | 27 | ### Linux 28 | 29 | ```bash 30 | mkdir build 31 | cd build 32 | cmake .. 33 | cmake --build . 34 | # built analyzer will be located at SampleAnalyzer/build/Analyzers/libSimpleSerialAnalyzer.so 35 | ``` 36 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required (VERSION 3.13) 2 | 3 | project(LPCClocklessAnalyzer) 4 | 5 | add_definitions( -DLOGIC2 ) 6 | 7 | # enable generation of compile_commands.json, helpful for IDEs to locate include files. 8 | set(CMAKE_EXPORT_COMPILE_COMMANDS ON) 9 | 10 | # custom CMake Modules are located in the cmake directory. 11 | set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake) 12 | 13 | include(ExternalAnalyzerSDK) 14 | 15 | set(SOURCES 16 | src/LPCClocklessAnalyzer.cpp 17 | src/LPCClocklessAnalyzer.h 18 | src/LPCClocklessAnalyzerResults.cpp 19 | src/LPCClocklessAnalyzerResults.h 20 | src/LPCClocklessAnalyzerSettings.cpp 21 | src/LPCClocklessAnalyzerSettings.h 22 | src/LPCClocklessSimulationDataGenerator.cpp 23 | src/LPCClocklessSimulationDataGenerator.h 24 | ) 25 | 26 | add_analyzer_plugin(${PROJECT_NAME} SOURCES ${SOURCES}) 27 | -------------------------------------------------------------------------------- /src/LPCClocklessAnalyzerSettings.h: -------------------------------------------------------------------------------- 1 | #ifndef LPCCLOCKLESS_ANALYZER_SETTINGS 2 | #define LPCCLOCKLESS_ANALYZER_SETTINGS 3 | 4 | #include 5 | #include 6 | 7 | class LPCClocklessAnalyzerSettings : public AnalyzerSettings 8 | { 9 | public: 10 | LPCClocklessAnalyzerSettings(); 11 | virtual ~LPCClocklessAnalyzerSettings(); 12 | 13 | virtual bool SetSettingsFromInterfaces(); 14 | void UpdateInterfacesFromSettings(); 15 | virtual void LoadSettings( const char* settings ); 16 | virtual const char* SaveSettings(); 17 | 18 | 19 | // Channel mInputChannel; 20 | Channel mLaddChannel[4]; 21 | Channel mFrameChannel; 22 | U32 mBitRate; 23 | 24 | protected: 25 | // std::unique_ptr< AnalyzerSettingInterfaceChannel > mInputChannelInterface; 26 | std::unique_ptr< AnalyzerSettingInterfaceChannel > mLaddChannelInterface[4]; 27 | std::unique_ptr< AnalyzerSettingInterfaceChannel > mFrameChannelInterface; 28 | std::unique_ptr< AnalyzerSettingInterfaceInteger > mBitRateInterface; 29 | }; 30 | 31 | #endif //LPCCLOCKLESS_ANALYZER_SETTINGS 32 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | # Logic style 2 | Language: Cpp 3 | # manually added flags 4 | FixNamespaceComments: 'false' 5 | SortIncludes: 'false' 6 | 7 | 8 | # flags copied from web editor, https://zed0.co.uk/clang-format-configurator/ 9 | AllowShortBlocksOnASingleLine: 'false' 10 | AllowShortCaseLabelsOnASingleLine: 'false' 11 | AllowShortFunctionsOnASingleLine: None 12 | AllowShortIfStatementsOnASingleLine: 'false' 13 | AllowShortLoopsOnASingleLine: 'false' 14 | AlwaysBreakAfterReturnType: None 15 | AlwaysBreakTemplateDeclarations: 'true' 16 | BreakBeforeBraces: Allman 17 | ColumnLimit: '140' 18 | ConstructorInitializerAllOnOneLineOrOnePerLine: 'true' 19 | ContinuationIndentWidth: '4' 20 | Cpp11BracedListStyle: 'false' 21 | IndentWidth: '4' 22 | KeepEmptyLinesAtTheStartOfBlocks: 'false' 23 | MaxEmptyLinesToKeep: '2' 24 | NamespaceIndentation: All 25 | PointerAlignment: Left 26 | SpaceBeforeParens: Never 27 | SpaceInEmptyParentheses: 'false' 28 | SpacesInCStyleCastParentheses: 'true' 29 | SpacesInParentheses: 'true' 30 | SpacesInSquareBrackets: 'true' 31 | TabWidth: '4' 32 | UseTab: Never 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Saleae 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/LPCClocklessAnalyzerResults.h: -------------------------------------------------------------------------------- 1 | #ifndef LPCCLOCKLESS_ANALYZER_RESULTS 2 | #define LPCCLOCKLESS_ANALYZER_RESULTS 3 | 4 | #include 5 | 6 | class LPCClocklessAnalyzer; 7 | class LPCClocklessAnalyzerSettings; 8 | 9 | // struct LPCFrame : public Frame 10 | // { 11 | // bool is_write; 12 | // uint32_t address; 13 | // uint8_t sync; 14 | // uint8_t data; 15 | // }; 16 | 17 | class LPCClocklessAnalyzerResults : public AnalyzerResults 18 | { 19 | public: 20 | LPCClocklessAnalyzerResults( LPCClocklessAnalyzer* analyzer, LPCClocklessAnalyzerSettings* settings ); 21 | virtual ~LPCClocklessAnalyzerResults(); 22 | 23 | virtual void GenerateBubbleText( U64 frame_index, Channel& channel, DisplayBase display_base ); 24 | virtual void GenerateExportFile( const char* file, DisplayBase display_base, U32 export_type_user_id ); 25 | 26 | virtual void GenerateFrameTabularText(U64 frame_index, DisplayBase display_base ); 27 | virtual void GeneratePacketTabularText( U64 packet_id, DisplayBase display_base ); 28 | virtual void GenerateTransactionTabularText( U64 transaction_id, DisplayBase display_base ); 29 | std::string stringForFrame(DisplayBase display_base, Frame *f); 30 | 31 | protected: //functions 32 | 33 | protected: //vars 34 | LPCClocklessAnalyzerSettings* mSettings; 35 | LPCClocklessAnalyzer* mAnalyzer; 36 | }; 37 | 38 | #endif //LPCCLOCKLESS_ANALYZER_RESULTS 39 | -------------------------------------------------------------------------------- /src/LPCClocklessAnalyzer.h: -------------------------------------------------------------------------------- 1 | #ifndef LPCCLOCKLESS_ANALYZER_H 2 | #define LPCCLOCKLESS_ANALYZER_H 3 | 4 | #include 5 | #include "LPCClocklessAnalyzerResults.h" 6 | #include "LPCClocklessSimulationDataGenerator.h" 7 | 8 | class LPCClocklessAnalyzerSettings; 9 | class ANALYZER_EXPORT LPCClocklessAnalyzer : public Analyzer2 10 | { 11 | public: 12 | LPCClocklessAnalyzer(); 13 | virtual ~LPCClocklessAnalyzer(); 14 | 15 | virtual void SetupResults(); 16 | virtual void WorkerThread(); 17 | 18 | virtual U32 GenerateSimulationData( U64 newest_sample_requested, U32 sample_rate, SimulationChannelDescriptor** simulation_channels ); 19 | virtual U32 GetMinimumSampleRateHz(); 20 | 21 | virtual const char* GetAnalyzerName() const; 22 | virtual bool NeedsRerun(); 23 | 24 | protected: //vars 25 | std::unique_ptr< LPCClocklessAnalyzerSettings > mSettings; 26 | std::unique_ptr< LPCClocklessAnalyzerResults > mResults; 27 | // AnalyzerChannelData* mSerial; 28 | AnalyzerChannelData *mFrame; 29 | AnalyzerChannelData *mLadd[4]; 30 | 31 | // LPCClocklessSimulationDataGenerator mSimulationDataGenerator; 32 | // bool mSimulationInitilized; 33 | 34 | //Serial analysis vars: 35 | U32 mSampleRateHz; 36 | U32 mSamplesPerBit; 37 | U32 mStartOfStopBitOffset; 38 | U32 mEndOfStopBitOffset; 39 | 40 | private: 41 | uint8_t getBits(); 42 | void advanceAllToFrame(); 43 | void addFrameLabel(uint64_t start, uint64_t end, uint64_t label); 44 | uint32_t readAddress(); 45 | void skipTar(); 46 | uint8_t readData(); 47 | uint8_t readSync(); 48 | }; 49 | 50 | extern "C" ANALYZER_EXPORT const char* __cdecl GetAnalyzerName(); 51 | extern "C" ANALYZER_EXPORT Analyzer* __cdecl CreateAnalyzer( ); 52 | extern "C" ANALYZER_EXPORT void __cdecl DestroyAnalyzer( Analyzer* analyzer ); 53 | 54 | #endif //LPCCLOCKLESS_ANALYZER_H 55 | -------------------------------------------------------------------------------- /cmake/ExternalAnalyzerSDK.cmake: -------------------------------------------------------------------------------- 1 | include(FetchContent) 2 | 3 | # Use the C++11 standard 4 | set(CMAKE_CXX_STANDARD 11) 5 | 6 | set(CMAKE_CXX_STANDARD_REQUIRED YES) 7 | 8 | if (NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY OR NOT CMAKE_LIBRARY_OUTPUT_DIRECTORY) 9 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin/) 10 | set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin/) 11 | endif() 12 | 13 | # Fetch the Analyzer SDK if the target does not already exist. 14 | if(NOT TARGET Saleae::AnalyzerSDK) 15 | FetchContent_Declare( 16 | analyzersdk 17 | GIT_REPOSITORY https://github.com/saleae/AnalyzerSDK.git 18 | GIT_TAG master 19 | GIT_SHALLOW True 20 | GIT_PROGRESS True 21 | ) 22 | 23 | FetchContent_GetProperties(analyzersdk) 24 | 25 | if(NOT analyzersdk_POPULATED) 26 | FetchContent_Populate(analyzersdk) 27 | include(${analyzersdk_SOURCE_DIR}/AnalyzerSDKConfig.cmake) 28 | 29 | if(APPLE OR WIN32) 30 | get_target_property(analyzersdk_lib_location Saleae::AnalyzerSDK IMPORTED_LOCATION) 31 | if(CMAKE_LIBRARY_OUTPUT_DIRECTORY) 32 | file(COPY ${analyzersdk_lib_location} DESTINATION ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) 33 | else() 34 | message(WARNING "Please define CMAKE_RUNTIME_OUTPUT_DIRECTORY and CMAKE_LIBRARY_OUTPUT_DIRECTORY if you want unit tests to locate ${analyzersdk_lib_location}") 35 | endif() 36 | endif() 37 | 38 | endif() 39 | endif() 40 | 41 | function(add_analyzer_plugin TARGET) 42 | set(options ) 43 | set(single_value_args ) 44 | set(multi_value_args SOURCES) 45 | cmake_parse_arguments( _p "${options}" "${single_value_args}" "${multi_value_args}" ${ARGN} ) 46 | 47 | 48 | add_library(${TARGET} MODULE ${_p_SOURCES}) 49 | target_link_libraries(${TARGET} PRIVATE Saleae::AnalyzerSDK) 50 | 51 | set(ANALYZER_DESTINATION "Analyzers") 52 | install(TARGETS ${TARGET} RUNTIME DESTINATION ${ANALYZER_DESTINATION} 53 | LIBRARY DESTINATION ${ANALYZER_DESTINATION}) 54 | 55 | set_target_properties(${TARGET} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${ANALYZER_DESTINATION} 56 | LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${ANALYZER_DESTINATION}) 57 | endfunction() -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | tags: 7 | - '*' 8 | pull_request: 9 | branches: [master] 10 | 11 | jobs: 12 | windows: 13 | runs-on: windows-latest 14 | steps: 15 | - uses: actions/checkout@v2 16 | - name: Build 17 | run: | 18 | cmake -B ${{github.workspace}}/build -A x64 19 | cmake --build ${{github.workspace}}/build --config Release 20 | - name: Upload windows build 21 | uses: actions/upload-artifact@v2 22 | with: 23 | name: windows 24 | path: ${{github.workspace}}/build/Analyzers/Release/*.dll 25 | macos: 26 | runs-on: macos-latest 27 | steps: 28 | - uses: actions/checkout@v2 29 | - name: Build 30 | run: | 31 | cmake -B ${{github.workspace}}/build/x86_64 -DCMAKE_BUILD_TYPE=Release -DCMAKE_OSX_ARCHITECTURES=x86_64 32 | cmake --build ${{github.workspace}}/build/x86_64 33 | cmake -B ${{github.workspace}}/build/arm64 -DCMAKE_BUILD_TYPE=Release -DCMAKE_OSX_ARCHITECTURES=arm64 34 | cmake --build ${{github.workspace}}/build/arm64 35 | - name: Upload MacOS x86_64 build 36 | uses: actions/upload-artifact@v2 37 | with: 38 | name: macos_x86_64 39 | path: ${{github.workspace}}/build/x86_64/Analyzers/*.so 40 | - name: Upload MacOS arm64 build 41 | uses: actions/upload-artifact@v2 42 | with: 43 | name: macos_arm64 44 | path: ${{github.workspace}}/build/arm64/Analyzers/*.so 45 | linux: 46 | runs-on: ubuntu-latest 47 | steps: 48 | - uses: actions/checkout@v2 49 | - name: Build 50 | run: | 51 | cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=Release 52 | cmake --build ${{github.workspace}}/build 53 | env: 54 | CC: gcc-10 55 | CXX: g++-10 56 | - name: Upload Linux build 57 | uses: actions/upload-artifact@v2 58 | with: 59 | name: linux 60 | path: ${{github.workspace}}/build/Analyzers/*.so 61 | publish: 62 | needs: [windows, macos, linux] 63 | runs-on: ubuntu-latest 64 | steps: 65 | - name: download individual builds 66 | uses: actions/download-artifact@v2 67 | with: 68 | path: ${{github.workspace}}/artifacts 69 | - name: zip 70 | run: | 71 | cd ${{github.workspace}}/artifacts 72 | zip -r ${{github.workspace}}/analyzer.zip . 73 | - uses: actions/upload-artifact@v2 74 | with: 75 | name: all-platforms 76 | path: ${{github.workspace}}/artifacts/** 77 | - name: create release 78 | uses: softprops/action-gh-release@v1 79 | if: startsWith(github.ref, 'refs/tags/') 80 | with: 81 | files: ${{github.workspace}}/analyzer.zip -------------------------------------------------------------------------------- /rename_analyzer.py: -------------------------------------------------------------------------------- 1 | import os 2 | import glob 3 | import sys 4 | 5 | # Fix Python 2.x. 6 | try: 7 | input = raw_input 8 | except NameError: pass 9 | 10 | print("") 11 | print("") 12 | print("What would you like to call your new analyzer?") 13 | print("") 14 | print(">>The files under '/src' will be modified to use it.") 15 | print(">>Examples include Serial, MySerial, JoesSerial, Gamecube, Wiimote, 2Wire, etc.") 16 | print(">>Do not include the trailing word 'Analyzer' this will be added automatically.") 17 | print("") 18 | print("(press CTRL-C to cancel)") 19 | print("") 20 | 21 | new_analyzer_name = input( "Your new analyzer name: " ) 22 | 23 | print("") 24 | print("") 25 | print("What is the analyzer's title? (as shown in the add new analyzer drop down)") 26 | print("") 27 | print(">>Examples include Async Serial, I2C, Joe's Serial, Gamecube, Wiimote, 2Wire, etc.") 28 | print("") 29 | print("(press CTRL-C to cancel)") 30 | print("") 31 | 32 | new_analyzer_title = input( "Your new analyzer's title: " ) 33 | 34 | original_name = "SimpleSerial" 35 | 36 | #update the CMakeLists.txt project name 37 | 38 | 39 | cmake_file = glob.glob("CMakeLists.txt") 40 | 41 | for file in cmake_file: 42 | contents = open( file, 'r' ).read() 43 | contents = contents.replace( original_name + "Analyzer", new_analyzer_name + "Analyzer" ) 44 | contents = contents.replace( original_name.upper() + "ANALYZER", new_analyzer_name.upper() + "ANALYZER" ) 45 | contents = contents.replace( original_name + "SimulationDataGenerator", new_analyzer_name + "SimulationDataGenerator" ) 46 | open( file, 'w' ).write( contents ) 47 | 48 | 49 | source_path = "src" 50 | os.chdir( source_path ) 51 | 52 | files = dict() 53 | 54 | cpp_files = glob.glob( "*.cpp" ); 55 | h_files = glob.glob( "*.h" ); 56 | 57 | for file in cpp_files: 58 | files[file] = ".cpp" 59 | 60 | for file in h_files: 61 | files[ file ] = ".h" 62 | 63 | new_files = [] 64 | 65 | for file, extension in files.items(): 66 | name_root = file.replace( original_name, "" ) 67 | new_name = new_analyzer_name + name_root 68 | #print "renaming file " + file + " to " + new_name 69 | os.rename( file, new_name ) 70 | new_files.append( new_name ) 71 | 72 | for file in new_files: 73 | contents = open( file, 'r' ).read() 74 | contents = contents.replace( original_name + "Analyzer", new_analyzer_name + "Analyzer" ) 75 | contents = contents.replace( original_name.upper() + "_ANALYZER_", new_analyzer_name.upper() + "_ANALYZER_" ) 76 | contents = contents.replace( original_name.upper() + "_SIMULATION_DATA_GENERATOR", new_analyzer_name.upper() + "_SIMULATION_DATA_GENERATOR" ) 77 | contents = contents.replace( original_name + "SimulationDataGenerator", new_analyzer_name + "SimulationDataGenerator" ) 78 | contents = contents.replace( "Simple Serial", new_analyzer_title ) 79 | open( file, 'w' ).write( contents ) -------------------------------------------------------------------------------- /src/LPCClocklessAnalyzerResults.cpp: -------------------------------------------------------------------------------- 1 | #include "LPCClocklessAnalyzerResults.h" 2 | #include 3 | #include "LPCClocklessAnalyzer.h" 4 | #include "LPCClocklessAnalyzerSettings.h" 5 | #include 6 | #include 7 | 8 | 9 | 10 | LPCClocklessAnalyzerResults::LPCClocklessAnalyzerResults( LPCClocklessAnalyzer* analyzer, LPCClocklessAnalyzerSettings* settings ) 11 | : AnalyzerResults(), 12 | mSettings( settings ), 13 | mAnalyzer( analyzer ) 14 | { 15 | } 16 | 17 | LPCClocklessAnalyzerResults::~LPCClocklessAnalyzerResults() 18 | { 19 | } 20 | 21 | void LPCClocklessAnalyzerResults::GenerateBubbleText( U64 frame_index, Channel& channel, DisplayBase display_base ) 22 | { 23 | ClearResultStrings(); 24 | Frame frame = GetFrame( frame_index ); 25 | 26 | char number_str[128]; 27 | AnalyzerHelpers::GetNumberString( frame.mData1, display_base, 48, number_str, 128 ); 28 | AddResultString( stringForFrame(display_base, &frame).c_str() ); 29 | } 30 | 31 | std::string LPCClocklessAnalyzerResults::stringForFrame(DisplayBase display_base, Frame *f) { 32 | uint64_t data = f->mData1; 33 | std::string ret = ""; 34 | if((data & 0xff0000000000) == 0x020000000000) { 35 | ret += "WRITE "; 36 | } else { 37 | ret += "READ "; 38 | } 39 | char address[128]; 40 | AnalyzerHelpers::GetNumberString((f->mData1 >> 8) & 0xFFFFFFFF, display_base, 32, address, 128); 41 | ret += address; 42 | ret += " DATA "; 43 | char data_str[8]; 44 | AnalyzerHelpers::GetNumberString(f->mData1 & 0xFF, display_base, 8, data_str, 8); 45 | ret += data_str; 46 | return ret; 47 | } 48 | 49 | void LPCClocklessAnalyzerResults::GenerateExportFile( const char* file, DisplayBase display_base, U32 export_type_user_id ) 50 | { 51 | std::ofstream file_stream( file, std::ios::out ); 52 | 53 | U64 trigger_sample = mAnalyzer->GetTriggerSample(); 54 | U32 sample_rate = mAnalyzer->GetSampleRate(); 55 | 56 | file_stream << "Time [s],Value" << std::endl; 57 | 58 | U64 num_frames = GetNumFrames(); 59 | for( U32 i=0; i < num_frames; i++ ) 60 | { 61 | Frame frame = GetFrame( i ); 62 | 63 | char time_str[128]; 64 | AnalyzerHelpers::GetTimeString( frame.mStartingSampleInclusive, trigger_sample, sample_rate, time_str, 128 ); 65 | 66 | char number_str[128]; 67 | AnalyzerHelpers::GetNumberString( frame.mData1, display_base, 8, number_str, 128 ); 68 | 69 | file_stream << time_str << "," << number_str << std::endl; 70 | 71 | if( UpdateExportProgressAndCheckForCancel( i, num_frames ) == true ) 72 | { 73 | file_stream.close(); 74 | return; 75 | } 76 | } 77 | 78 | file_stream.close(); 79 | } 80 | 81 | void LPCClocklessAnalyzerResults::GenerateFrameTabularText( U64 frame_index, DisplayBase display_base ) 82 | { 83 | #ifdef SUPPORTS_PROTOCOL_SEARCH 84 | 85 | Frame frame = GetFrame( frame_index ); 86 | // if(frame.mType == 0x99) { 87 | // LPCFrame& req( ( LPCFrame& )frame); 88 | // if(req.is_write) { 89 | // AddTabularText("WRTE"); 90 | // } else { 91 | // AddTabularText("READ"); 92 | // } 93 | 94 | // char number_str[128]; 95 | // AnalyzerHelpers::GetNumberString( req.address, display_base, 8, number_str, 128 ); 96 | // AddTabularText( number_str ); 97 | 98 | // char number_str2[128]; 99 | // AnalyzerHelpers::GetNumberString( req.data, display_base, 8, number_str2, 128 ); 100 | // AddTabularText( number_str2 ); 101 | 102 | 103 | 104 | // } else { 105 | ClearTabularText(); 106 | 107 | char number_str[128]; 108 | // AnalyzerHelpers::GetNumberString() 109 | AnalyzerHelpers::GetNumberString( frame.mData1, display_base, 48, number_str, 128 ); 110 | AddTabularText( number_str ); 111 | AddResultString( stringForFrame(display_base, &frame).c_str() ); 112 | // AddTabularText("TEST"); 113 | // } 114 | 115 | #endif 116 | } 117 | 118 | void LPCClocklessAnalyzerResults::GeneratePacketTabularText( U64 packet_id, DisplayBase display_base ) 119 | { 120 | //not supported 121 | 122 | } 123 | 124 | void LPCClocklessAnalyzerResults::GenerateTransactionTabularText( U64 transaction_id, DisplayBase display_base ) 125 | { 126 | //not supported 127 | } -------------------------------------------------------------------------------- /src/LPCClocklessAnalyzerSettings.cpp: -------------------------------------------------------------------------------- 1 | #include "LPCClocklessAnalyzerSettings.h" 2 | #include 3 | 4 | 5 | LPCClocklessAnalyzerSettings::LPCClocklessAnalyzerSettings() : 6 | // : mInputChannel( UNDEFINED_CHANNEL ), 7 | mFrameChannel( UNDEFINED_CHANNEL ), 8 | mBitRate( 25000000 ) 9 | { 10 | ClearChannels(); 11 | for(int i=0; i < 4; i++) { 12 | mLaddChannel[i] = Channel(UNDEFINED_CHANNEL); 13 | // } 14 | mLaddChannelInterface[i].reset( new AnalyzerSettingInterfaceChannel() ); 15 | // const char *name = std::string("Ladd" + std::to_string(i)).c_str(); 16 | mLaddChannelInterface[i]->SetTitleAndTooltip(std::string("Ladd" + std::to_string(i)).c_str(), "Signal."); 17 | mLaddChannelInterface[i]->SetChannel( mLaddChannel[i] ); 18 | AddInterface( mLaddChannelInterface[i].get() ); 19 | AddChannel( mLaddChannel[i], std::string("Ladd" + std::to_string(i)).c_str(), false ); 20 | } 21 | 22 | mFrameChannelInterface.reset( new AnalyzerSettingInterfaceChannel() ); 23 | mFrameChannelInterface->SetTitleAndTooltip( "Frame", "Frame signal" ); 24 | mFrameChannelInterface->SetChannel( mFrameChannel ); 25 | AddInterface(mFrameChannelInterface.get()); 26 | // mInputChannelInterface.reset( new AnalyzerSettingInterfaceChannel() ); 27 | // mInputChannelInterface->SetTitleAndTooltip( "Serial", "Standard LPC Clockless" ); 28 | // mInputChannelInterface->SetChannel( mInputChannel ); 29 | 30 | mBitRateInterface.reset( new AnalyzerSettingInterfaceInteger() ); 31 | mBitRateInterface->SetTitleAndTooltip( "Bit Rate (Bits/S)", "Specify the bit rate in bits per second." ); 32 | mBitRateInterface->SetMax( 50000000 ); 33 | mBitRateInterface->SetMin( 1 ); 34 | mBitRateInterface->SetInteger( mBitRate ); 35 | 36 | // AddInterface( mInputChannelInterface.get() ); 37 | AddInterface( mBitRateInterface.get() ); 38 | 39 | AddExportOption( 0, "Export as text/csv file" ); 40 | AddExportExtension( 0, "text", "txt" ); 41 | AddExportExtension( 0, "csv", "csv" ); 42 | 43 | // ClearChannels(); 44 | AddChannel( mFrameChannel, "Frame", false ); 45 | } 46 | 47 | LPCClocklessAnalyzerSettings::~LPCClocklessAnalyzerSettings() 48 | { 49 | } 50 | 51 | bool LPCClocklessAnalyzerSettings::SetSettingsFromInterfaces() 52 | { 53 | // mInputChannel = mInputChannelInterface->GetChannel(); 54 | mFrameChannel = mFrameChannelInterface->GetChannel(); 55 | for(int i=0; i < 4; i++) { 56 | mLaddChannel[i] = mLaddChannelInterface[i]->GetChannel(); 57 | } 58 | mBitRate = mBitRateInterface->GetInteger(); 59 | 60 | ClearChannels(); 61 | for(int i=0; i < 4; i++) { 62 | AddChannel( mLaddChannel[i], std::string("Ladd" + std::to_string(i)).c_str(), true); 63 | } 64 | // AddChannel( mInputChannel, "LPC Clockless", true ); 65 | AddChannel( mFrameChannel, "Frame", true ); 66 | 67 | return true; 68 | } 69 | 70 | void LPCClocklessAnalyzerSettings::UpdateInterfacesFromSettings() 71 | { 72 | for(int i=0; i < 4; i++) { 73 | mLaddChannelInterface[i]->SetChannel( mLaddChannel[i] ); 74 | } 75 | mFrameChannelInterface->SetChannel( mFrameChannel ); 76 | // mInputChannelInterface->SetChannel( mInputChannel ); 77 | mBitRateInterface->SetInteger( mBitRate ); 78 | } 79 | 80 | void LPCClocklessAnalyzerSettings::LoadSettings( const char* settings ) 81 | { 82 | SimpleArchive text_archive; 83 | text_archive.SetString( settings ); 84 | for(int i=0; i < 4; i++) { 85 | text_archive >> mLaddChannel[i]; 86 | } 87 | text_archive >> mFrameChannel; 88 | text_archive >> mBitRate; 89 | 90 | ClearChannels(); 91 | for(int i=0; i < 4; i++) { 92 | AddChannel( mLaddChannel[i], std::string("Ladd" + std::to_string(i)).c_str(), true); 93 | } 94 | // AddChannel( mInputChannel, "LPC Clockless", true ); 95 | AddChannel( mFrameChannel, "Frame", true ); 96 | // AddChannel( mInputChannel, "LPC Clockless", true ); 97 | 98 | UpdateInterfacesFromSettings(); 99 | } 100 | 101 | const char* LPCClocklessAnalyzerSettings::SaveSettings() 102 | { 103 | SimpleArchive text_archive; 104 | 105 | for(int i=0; i < 4; i++) { 106 | text_archive << mLaddChannel[i]; 107 | } 108 | text_archive << mFrameChannel; 109 | // text_archive << mInputChannel; 110 | text_archive << mBitRate; 111 | 112 | return SetReturnString( text_archive.GetString() ); 113 | } 114 | -------------------------------------------------------------------------------- /sample_readme.md: -------------------------------------------------------------------------------- 1 | # Cool 3rd Party Analyzer 2 | 3 | Original Readme Content Here 4 | 5 | Documentation for the Saleae Logic Analyzer SDK can be found here: 6 | https://github.com/saleae/SampleAnalyzer 7 | 8 | That documentation includes: 9 | 10 | - Detailed build instructions 11 | - Debugging instructions 12 | - Documentation for CI builds 13 | - Details on creating your own custom analyzer plugin 14 | 15 | # Installation Instructions 16 | 17 | To use this analyzer, simply download the latest release zip file from this github repository, unzip it, then install using the instructions found here: 18 | 19 | https://support.saleae.com/faq/technical-faq/setting-up-developer-directory 20 | 21 | # Publishing Releases 22 | 23 | This repository is setup with Github Actions to automatically build PRs and commits to the master branch. 24 | 25 | However, these artifacts automatically expire after a time limit. 26 | 27 | To create and publish cross-platform releases, simply push a commit tag. This will automatically trigger the creation of a release, which will include the Windows, Linux, and MacOS builds of the analyzer. 28 | 29 | # A note on downloading the MacOS Analyzer builds 30 | 31 | This section only applies to downloaded pre-built protocol analyzer binaries on MacOS. If you build the protocol analyzer locally, or acquire it in a different way, this section does not apply. 32 | 33 | Any time you download a binary from the internet on a Mac, wether it be an application or a shared library, MacOS will flag that binary for "quarantine". MacOS then requires any quarantined binary to be signed and notarized through the MacOS developer program before it will allow that binary to be executed. 34 | 35 | Because of this, when you download a pre-compiled protocol analyzer plugin from the internet and try to load it in the Saleae software, you will most likely see an error message like this: 36 | 37 | > "libSimpleSerialAnalyzer.so" cannot be opened because th developer cannot be verified. 38 | 39 | Signing and notarizing of open source software can be rare, because it requires an active paid subscription to the MacOS developer program, and the signing and notarization process frequently changes and becomes more restrictive, requiring frequent updates to the build process. 40 | 41 | The quickest solution to this is to simply remove the quarantine flag added by MacOS using a simple command line tool. 42 | 43 | Note - the purpose of code signing and notarization is to help end users be sure that the binary they downloaded did indeed come from the original publisher and hasn't been modified. Saleae does not create, control, or review 3rd party analyzer plugins available on the internet, and thus you must trust the original author and the website where you are downloading the plugin. (This applies to all software you've ever downloaded, essentially.) 44 | 45 | To remove the quarantine flag on MacOS, you can simply open the terminal and navigate to the directory containing the downloaded shared library. 46 | 47 | This will show what flags are present on the binary: 48 | 49 | ```sh 50 | xattr libSimpleSerialAnalyzer.so 51 | # example output: 52 | # com.apple.macl 53 | # com.apple.quarantine 54 | ``` 55 | 56 | This command will remove the quarantine flag: 57 | 58 | ```sh 59 | xattr -r -d com.apple.quarantine libSimpleSerialAnalyzer.so 60 | ``` 61 | 62 | To verify the flag was removed, run the first command again and verify the quarantine flag is no longer present. 63 | 64 | ## Building your Analyzer 65 | 66 | CMake and a C++ compiler are required. Instructions for installing dependencies can be found here: 67 | https://github.com/saleae/SampleAnalyzer 68 | 69 | The fastest way to use this analyzer is to download a release from github. Local building should only be needed for making your own changes to the analyzer source. 70 | 71 | ### Windows 72 | 73 | ```bat 74 | mkdir build 75 | cd build 76 | cmake .. -A x64 77 | cmake --build . 78 | :: built analyzer will be located at SampleAnalyzer\build\Analyzers\Debug\SimpleSerialAnalyzer.dll 79 | ``` 80 | 81 | ### MacOS 82 | 83 | ```bash 84 | mkdir build 85 | cd build 86 | cmake .. 87 | cmake --build . 88 | # built analyzer will be located at SampleAnalyzer/build/Analyzers/libSimpleSerialAnalyzer.so 89 | ``` 90 | 91 | ### Linux 92 | 93 | ```bash 94 | mkdir build 95 | cd build 96 | cmake .. 97 | cmake --build . 98 | # built analyzer will be located at SampleAnalyzer/build/Analyzers/libSimpleSerialAnalyzer.so 99 | ``` 100 | -------------------------------------------------------------------------------- /src/LPCClocklessAnalyzer.cpp: -------------------------------------------------------------------------------- 1 | #include "LPCClocklessAnalyzer.h" 2 | #include "LPCClocklessAnalyzerSettings.h" 3 | #include 4 | #include 5 | LPCClocklessAnalyzer::LPCClocklessAnalyzer() 6 | : Analyzer2(), 7 | mSettings( new LPCClocklessAnalyzerSettings() ) 8 | // mSimulationInitilized( false ) 9 | { 10 | SetAnalyzerSettings( mSettings.get() ); 11 | } 12 | 13 | LPCClocklessAnalyzer::~LPCClocklessAnalyzer() 14 | { 15 | KillThread(); 16 | } 17 | 18 | void LPCClocklessAnalyzer::SetupResults() 19 | { 20 | mResults.reset( new LPCClocklessAnalyzerResults( this, mSettings.get() ) ); 21 | SetAnalyzerResults( mResults.get() ); 22 | mResults->AddChannelBubblesWillAppearOn( mSettings->mFrameChannel ); 23 | // mResults->AddChannelBubblesWillAppearOn( mSettings->mInputChannel ); 24 | } 25 | 26 | uint8_t LPCClocklessAnalyzer::getBits() { 27 | return (mLadd[3]->GetBitState() << 3) | 28 | (mLadd[2]->GetBitState() << 2) | 29 | (mLadd[1]->GetBitState() << 1) | 30 | (mLadd[0]->GetBitState() << 0); 31 | } 32 | 33 | void LPCClocklessAnalyzer::advanceAllToFrame() { 34 | for(int i=0; i < 4; i++) { 35 | mLadd[i]->AdvanceToAbsPosition(mFrame->GetSampleNumber()); 36 | } 37 | } 38 | 39 | void LPCClocklessAnalyzer::addFrameLabel(uint64_t start, uint64_t end, uint64_t label) { 40 | Frame frame; 41 | frame.mData1 = label; 42 | frame.mFlags = 0; 43 | frame.mStartingSampleInclusive = start; 44 | frame.mEndingSampleInclusive = end; 45 | 46 | mResults->AddFrame( frame ); 47 | mResults->CommitResults(); 48 | ReportProgress(end); 49 | } 50 | 51 | uint32_t LPCClocklessAnalyzer::readAddress() { 52 | uint32_t address = 0; 53 | for(int i=0; i < 4; i++) { 54 | mFrame->Advance( mSamplesPerBit ); 55 | advanceAllToFrame(); 56 | 57 | address |= getBits() << 4 * (3-i); 58 | mResults->AddMarker( mFrame->GetSampleNumber(), AnalyzerResults::Dot, mSettings->mFrameChannel ); 59 | } 60 | return address; 61 | } 62 | 63 | void LPCClocklessAnalyzer::skipTar() { 64 | mFrame->Advance( mSamplesPerBit ); 65 | mFrame->Advance( mSamplesPerBit ); 66 | } 67 | 68 | uint8_t LPCClocklessAnalyzer::readData() { 69 | uint8_t data = 0; 70 | mFrame->Advance( mSamplesPerBit ); 71 | advanceAllToFrame(); 72 | data = getBits(); 73 | mFrame->Advance( mSamplesPerBit ); 74 | advanceAllToFrame(); 75 | data |= getBits() << 4; 76 | return data; 77 | } 78 | 79 | uint8_t LPCClocklessAnalyzer::readSync() { 80 | mFrame->Advance( mSamplesPerBit ); 81 | advanceAllToFrame(); 82 | return getBits(); 83 | } 84 | 85 | void LPCClocklessAnalyzer::WorkerThread() 86 | { 87 | mSampleRateHz = GetSampleRate(); 88 | mSamplesPerBit = mSampleRateHz / (mSettings->mBitRate * 1000); 89 | mFrame = GetAnalyzerChannelData( mSettings->mFrameChannel ); 90 | for(int i=0; i < 4; i++) { 91 | mLadd[i] = GetAnalyzerChannelData( mSettings->mLaddChannel[i] ); 92 | } 93 | 94 | // mSerial = GetAnalyzerChannelData( mSettings->mInputChannel ); 95 | 96 | 97 | 98 | // - U32 mSamplesPerBit = mSampleRateHz / mSettings->mBitRate; 99 | 100 | // mSamplesPerBit = mSampleRateHz / (mSettings->mBitRate * 1000); 101 | std::cout << "Samples per bit: " << mSamplesPerBit << std::endl; 102 | // U32 samples_to_first_center_of_first_data_bit = U32( 1.5 * double( mSampleRateHz ) / double( mSettings->mBitRate ) ); 103 | 104 | for( ; ; ) 105 | { 106 | 107 | // Frame f; 108 | // f.mType = 0x99; 109 | 110 | 111 | bool is_write = false; 112 | 113 | U8 data = 0; 114 | U8 mask = 1 << 7; 115 | 116 | 117 | if( mFrame->GetBitState() == BIT_HIGH ) 118 | mFrame->AdvanceToNextEdge(); 119 | 120 | 121 | 122 | uint64_t total_starting_sample = mFrame->GetSampleNumber(); 123 | 124 | mFrame->Advance(mSamplesPerBit/2); 125 | advanceAllToFrame(); 126 | // Check pattern 127 | uint8_t bits = getBits(); 128 | // printf("Bits: %d\n", bits); 129 | if(getBits() == 0b0101) { 130 | mResults->AddMarker( mFrame->GetSampleNumber(), AnalyzerResults::Start, mSettings->mFrameChannel ); 131 | } else { 132 | mResults->AddMarker( mFrame->GetSampleNumber(), AnalyzerResults::ErrorX, mSettings->mFrameChannel ); 133 | mFrame->AdvanceToNextEdge(); 134 | mResults->CommitResults(); 135 | ReportProgress( mFrame->GetSampleNumber() ); 136 | continue; 137 | } 138 | 139 | U64 starting_sample = mFrame->GetSampleNumber(); 140 | 141 | 142 | // Go to CYCTYPE + DIR 143 | // 0000 = read 144 | // 0010 = write 145 | mFrame->Advance( mSamplesPerBit ); 146 | advanceAllToFrame(); 147 | 148 | uint8_t cyctype_dir = getBits(); 149 | if(cyctype_dir == 0x02) { 150 | // printf("Is write\n"); 151 | is_write = true; 152 | // f.is_write = true; 153 | } else { 154 | // f.is_write = false; 155 | } 156 | // addFrameLabel(starting_sample, mFrame->GetSampleNumber(), cyctype_dir); 157 | //let's put a dot exactly where we sample this bit: 158 | mResults->AddMarker( mFrame->GetSampleNumber(), AnalyzerResults::Dot, mSettings->mFrameChannel ); 159 | 160 | starting_sample = mFrame->GetSampleNumber(); 161 | // Iterate over address fields 162 | uint32_t address = readAddress(); 163 | // f.address = address; 164 | // addFrameLabel(starting_sample, mFrame->GetSampleNumber(), address); 165 | 166 | 167 | 168 | // Read data/TAR 169 | if(is_write) { 170 | starting_sample = mFrame->GetSampleNumber(); 171 | data = readData(); 172 | // f.data = data; 173 | // addFrameLabel(starting_sample, mFrame->GetSampleNumber(), data); 174 | skipTar(); 175 | starting_sample = mFrame->GetSampleNumber(); 176 | uint8_t sync = readSync(); 177 | // addFrameLabel(starting_sample, mFrame->GetSampleNumber(), sync); 178 | skipTar(); 179 | } else { 180 | skipTar(); 181 | // sync field 182 | starting_sample = mFrame->GetSampleNumber(); 183 | while(readSync() != 0) { 184 | 185 | } 186 | // uint8_t sync = readSync(); 187 | // addFrameLabel(starting_sample, mFrame->GetSampleNumber(), sync); 188 | 189 | // data field 190 | starting_sample = mFrame->GetSampleNumber(); 191 | data = readData(); 192 | // f.data = data; 193 | // addFrameLabel(starting_sample, mFrame->GetSampleNumber(), data); 194 | 195 | skipTar(); 196 | } 197 | 198 | uint64_t transfer = 199 | ((uint64_t)cyctype_dir << 40) | 200 | ((uint64_t)address << 8) | 201 | (data); 202 | 203 | addFrameLabel(total_starting_sample, mFrame->GetSampleNumber(), transfer); 204 | // f.mFlags = 0; 205 | // f.mStartingSampleInclusive = total_starting_sample; 206 | // f.mEndingSampleInclusive = mFrame->GetSampleNumber(); 207 | // mResults->AddFrame( f ); 208 | 209 | mResults->CommitResults(); 210 | ReportProgress(mFrame->GetSampleNumber()); 211 | mFrame->AdvanceToNextEdge(); 212 | } 213 | } 214 | 215 | bool LPCClocklessAnalyzer::NeedsRerun() 216 | { 217 | return false; 218 | } 219 | 220 | U32 LPCClocklessAnalyzer::GenerateSimulationData( U64 minimum_sample_index, U32 device_sample_rate, SimulationChannelDescriptor** simulation_channels ) 221 | { 222 | return 0; 223 | } 224 | // if( mSimulationInitilized == false ) 225 | // { 226 | // mSimulationDataGenerator.Initialize( GetSimulationSampleRate(), mSettings.get() ); 227 | // mSimulationInitilized = true; 228 | // } 229 | 230 | // return mSimulationDataGenerator.GenerateSimulationData( minimum_sample_index, device_sample_rate, simulation_channels ); 231 | // } 232 | 233 | U32 LPCClocklessAnalyzer::GetMinimumSampleRateHz() 234 | { 235 | return mSettings->mBitRate * 4; 236 | } 237 | 238 | const char* LPCClocklessAnalyzer::GetAnalyzerName() const 239 | { 240 | return "LPC Clockless"; 241 | } 242 | 243 | const char* GetAnalyzerName() 244 | { 245 | return "LPC Clockless"; 246 | } 247 | 248 | Analyzer* CreateAnalyzer() 249 | { 250 | return new LPCClocklessAnalyzer(); 251 | } 252 | 253 | void DestroyAnalyzer( Analyzer* analyzer ) 254 | { 255 | delete analyzer; 256 | } -------------------------------------------------------------------------------- /docs/Analyzer_API.md: -------------------------------------------------------------------------------- 1 | # C++ Analyzer API 2 | 3 | - [C++ Analyzer API](#c---analyzer-api) 4 | * [Writing your Analyzer’s Code](#writing-your-analyzer-s-code) 5 | - [Analyzer Settings](#analyzer-settings) 6 | * [{YourName}AnalyzerSettings.h](#-yourname-analyzersettingsh) 7 | + [User-modifiable Analyzer Settings](#user-modifiable-analyzer-settings) 8 | + [Analyzer Settings Interfaces Objects](#analyzer-settings-interfaces-objects) 9 | * [{YourName}AnalyzerSettings.cpp](#-yourname-analyzersettingscpp) 10 | + [The Constructor](#the-constructor) 11 | + [Setting up each AnalyzerSettingInterface object](#setting-up-each-analyzersettinginterface-object) 12 | - [```AnalyzerSettingInterface``` Object Options](#---analyzersettinginterface----object-options) 13 | * [```AnalyzerSettingInterfaceChannel```](#---analyzersettinginterfacechannel---) 14 | * [```AnalyzerSettingInterfaceNumberList```](#---analyzersettinginterfacenumberlist---) 15 | * [```AnalyzerSettingInterfaceInteger```](#---analyzersettinginterfaceinteger---) 16 | * [```AnalyzerSettingInterfaceText```](#---analyzersettinginterfacetext---) 17 | * [```AnalyzerSettingInterfaceBool```](#---analyzersettinginterfacebool---) 18 | + [Specifying Export Options](#specifying-export-options) 19 | + [Specifying which channels are in use](#specifying-which-channels-are-in-use) 20 | + [AnalyzerSettings Destructor](#analyzersettings-destructor) 21 | + [```{YourName}AnalyzerSettings::SetSettingsFromInterfaces()```](#----yourname-analyzersettings--setsettingsfrominterfaces-----) 22 | + [```{YourName}AnalyzerSettings::UpdateInterfacesFromSettings()```](#----yourname-analyzersettings--updateinterfacesfromsettings-----) 23 | + [```{YourName}AnalyzerSettings::LoadSettings()```](#----yourname-analyzersettings--loadsettings-----) 24 | + [```{YourName}AnalyzerSettings::SaveSettings()```](#----yourname-analyzersettings--savesettings-----) 25 | - [```AnalyzerResults```](#---analyzerresults---) 26 | * [{YourName}AnalyzerResults.h](#-yourname-analyzerresultsh) 27 | * [{YourName}AnalyzerResults.cpp](#-yourname-analyzerresultscpp) 28 | * [Frames, Packets, and Transactions](#frames--packets--and-transactions) 29 | + [Frame](#frame) 30 | - [Frame Member Variables](#frame-member-variables) 31 | + [```{YourName}AnalyzerResults::GenerateBubbleText()```](#----yourname-analyzerresults--generatebubbletext-----) 32 | + [```{YourName}AnalyzerResults::GenerateExportFile()```](#----yourname-analyzerresults--generateexportfile-----) 33 | + [```SerialAnalyzerResults::GenerateFrameTabularText()```](#---serialanalyzerresults--generateframetabulartext-----) 34 | + [```SerialAnalyzerResults::GeneratePacketTabularText()```](#---serialanalyzerresults--generatepackettabulartext-----) 35 | + [```SerialAnalyzerResults::GenerateTransactionTabularText()```](#---serialanalyzerresults--generatetransactiontabulartext-----) 36 | - [Analyzer](#analyzer) 37 | * [{YourName}Analyzer.h](#-yourname-analyzerh) 38 | * [{YourName}Analyzer.cpp](#-yourname-analyzercpp) 39 | * [Constructor](#constructor) 40 | * [Destructor](#destructor) 41 | * [```{YourName}Analyzer::WorkerThread()```](#----yourname-analyzer--workerthread-----) 42 | * [```bool {YourName}Analyzer::NeedsRerun()```](#---bool--yourname-analyzer--needsrerun-----) 43 | * [```Analyzer::GenerateSimulationData()```](#---analyzer--generatesimulationdata-----) 44 | * [```U32 SerialAnalyzer::GetMinimumSampleRateHz()```](#---u32-serialanalyzer--getminimumsampleratehz-----) 45 | * [```{YourName}Analyzer::GetAnalyzerName()```](#----yourname-analyzer--getanalyzername-----) 46 | * [```GetAnalyzerName()```](#---getanalyzername-----) 47 | * [```Analyzer* CreateAnalyzer()```](#---analyzer--createanalyzer-----) 48 | * [```DestroyAnalyzer( Analyzer* analyzer )```](#---destroyanalyzer--analyzer--analyzer-----) 49 | * [```{YourName}Analyzer::WorkerThread()```](#----yourname-analyzer--workerthread------1) 50 | - [Traversing the Data](#traversing-the-data) 51 | * [```AnalyzerChannelData```](#---analyzerchanneldata---) 52 | + [```AnalyzerChannelData ```– State](#---analyzerchanneldata------state) 53 | + [```AnalyzerChannelData ```– Basic Traversal](#---analyzerchanneldata------basic-traversal) 54 | + [```AnalyzerChannelData ```– Advanced Traversal (looking ahead without moving)](#---analyzerchanneldata------advanced-traversal--looking-ahead-without-moving-) 55 | + [```AnalyzerChannelData ```– Keeping track of the smallest pulse.](#---analyzerchanneldata------keeping-track-of-the-smallest-pulse) 56 | * [Filling in Frames](#filling-in-frames) 57 | * [Saving Frames](#saving-frames) 58 | * [Adding Markers](#adding-markers) 59 | * [Packets and Transactions](#packets-and-transactions) 60 | - [Utilities](#utilities) 61 | * [```BitExtractor```](#---bitextractor---) 62 | * [```DataBuilder```](#---databuilder---) 63 | - [```AnalyzerHelpers```](#---analyzerhelpers---) 64 | * [```DisplayBase```](#---displaybase---) 65 | * [```GetNumberString()```](#---getnumberstring-----) 66 | * [```GetTimeString()```](#---gettimestring-----) 67 | - [```SimulationDataGenerator```](#---simulationdatagenerator---) 68 | * [{YourName}SimulationDataGenerator.cpp](#-yourname-simulationdatageneratorcpp) 69 | + [Constructor/Destructor](#constructor-destructor) 70 | + [```{YourName}SimulationDataGenerator::Initialize()```](#----yourname-simulationdatagenerator--initialize-----) 71 | - [```BitState```](#---bitstate---) 72 | - [Sample Rate (samples per second)](#sample-rate--samples-per-second-) 73 | - [Sample Number](#sample-number) 74 | + [```SimulationChannelDescriptor```](#---simulationchanneldescriptor---) 75 | - [```Advance()```](#---advance-----) 76 | - [```Transition()```](#---transition-----) 77 | - [```TransitionIfNeeded()```](#---transitionifneeded-----) 78 | - [```GetCurrentBitState()```](#---getcurrentbitstate-----) 79 | - [```GetCurrentSampleNumber()```](#---getcurrentsamplenumber-----) 80 | - [```ClockGenerator```](#---clockgenerator---) 81 | - [```Init( double target_frequency, U32 sample_rate_hz );```](#---init--double-target-frequency--u32-sample-rate-hz------) 82 | - [```AdvanceByHalfPeriod( double multiple = 1.0 );```](#---advancebyhalfperiod--double-multiple---10------) 83 | - [```AdvanceByTimeS( double time_s );```](#---advancebytimes--double-time-s------) 84 | + [```{YourName}SimulationDataGenerator::Initialize()```](#----yourname-simulationdatagenerator--initialize------1) 85 | + [```{YourName}SimulationDataGenerator::GenerateSimulationData()```](#----yourname-simulationdatagenerator--generatesimulationdata-----) 86 | * [Simulating Multiple Channels](#simulating-multiple-channels) 87 | + [Examples of generating simulation data](#examples-of-generating-simulation-data) 88 | - [```SerialSimulationDataGenerator::CreateSerialByte()```](#---serialsimulationdatagenerator--createserialbyte-----) 89 | - [```I2cSimulationDataGenerator::CreateBit()```](#---i2csimulationdatagenerator--createbit-----) 90 | - [```I2cSimulationDataGenerator::CreateI2cTransaction()```](#---i2csimulationdatagenerator--createi2ctransaction-----) 91 | - [```SpiSimulationDataGenerator::OutputWord_CPHA1()```](#---spisimulationdatagenerator--outputword-cpha1-----) 92 | - [```SpiSimulationDataGenerator::CreateSpiTransaction()```](#---spisimulationdatagenerator--createspitransaction-----) 93 | - [```SpiSimulationDataGenerator::GenerateSimulationData()```](#---spisimulationdatagenerator--generatesimulationdata-----) 94 | 95 | This is the original documentation for the Saleae C++ Analyzer API. It has not been updated since the original release, and some parts are out of date. Please refer to support, as well as Saleae's other open source protocol analyzers for reference. Changes that need to be reflected in this documentation: 96 | 97 | - Packet and Transaction abstraction was not implemented, in favor of [FrameV2 and HLAs.](https://support.saleae.com/saleae-api-and-sdk/protocol-analyzer-sdk/framev2-hla-support-analyzer-sdk) 98 | - LoadSettings and SaveSettings are no longer used, instead the settings interfaces are serialized automatically by the Logic 2 software. 99 | - The `NeedsRerun` function is no longer used. 100 | - Your analyzer must inherit from `Analyzer2`, not `Analyzer`, and implement an additional virtual function `SetupResults`. See other Saleae analyzers for examples. 101 | 102 | 103 | ## Writing your Analyzer’s Code 104 | 105 | This second part of the document deals with writing the code for your analyzer. There are 4 C++ files and 4 header files that you will implement to create your analyzer. If you followed the procedure in the first part, you already have a working analyzer, and will be modifying that code to suit your needs. Conceptually, the analyzer can be broken into 4 main parts – the 4 c++ files. Working on them in a particular order is highly recommended, and this document describes the procedure in this order. 106 | 107 | 1. First you’ll work on the AnalyzerSettings-derived class. You’ll define the settings your analyzer needs, and create interfaces that’ll allow the Logic software to display a GUI for the settings. You’ll also implement serialization for these settings so they can be saved and recalled from disk. 108 | 2. Next you implement the SimulationDataGenerator class. Here you’ll generate simulated data that can be later to test your analyzer, or provide an example of what your analyzer expects. 109 | 3. Third you’ll create your AnalyzerResults-derived class. This class translates saved results into text for a variety of uses. Here you’ll start thinking about the format your results will be saved in. You probably will revisit your this file after implementing your Analyzer. 110 | 4. Lastly, you’ll implement your Analyzer-derived class. The main thing you’ll do here is translate data streams into results, based on your protocol. 111 | 112 | Let’s get started! 113 | 114 | ---------- 115 | 116 | 117 | # Analyzer Settings 118 | 119 | After setting up your analyzer project, and renaming the source files to match your project, the first step is to implement/modify your analyzer’s ```AnalyzerSettings``` - derived class. 120 | 121 | ## {YourName}AnalyzerSettings.h 122 | 123 | In this file, you provide a declaration for your *{YourName}AnalyzerSettings* class. This class must inherit from ```AnalyzerSettings```, and should include the ```AnalyzerSettings.h``` header file. We’ll start with this 124 | 125 | ```c++ 126 | #ifndef SIMPLESERIAL_ANALYZER_SETTINGS 127 | #define SIMPLESERIAL_ANALYZER_SETTINGS 128 | 129 | #include 130 | #include 131 | 132 | class SimpleSerialAnalyzerSettings : public AnalyzerSettings 133 | { 134 | public: 135 | SimpleSerialAnalyzerSettings(); 136 | virtual ~SimpleSerialAnalyzerSettings(); 137 | virtual bool SetSettingsFromInterfaces(); 138 | void UpdateInterfacesFromSettings(); 139 | virtual void LoadSettings( const char* settings ); 140 | virtual const char* SaveSettings(); 141 | }; 142 | #endif //SIMPLESERIAL_ANALYZER_SETTINGS 143 | ``` 144 | In addition, your header will define two sets of variables: 145 | 146 | ### User-modifiable Analyzer Settings 147 | 148 | This will always include at least one variable of the type ```Channel``` so the user can specify which input channel to use. This cannot be hard coded, and must be exposed as a setting. ```Channel``` isn’t just an index, it also specifies which Logic device the channel is from. Other possible settings depend on your protocol, and might include: 149 | 150 | - Bit rate 151 | - Bits per transfer 152 | - Bit ordering (MSb first, LSb first) 153 | - Clock edge (rising, falling) to use 154 | - Enable line polarity 155 | - Etc – anything you need for your specific protocol. 156 | 157 | Start with just the ```Channel``` variable(s), and you can add more later to make your analyzer more flexible. 158 | 159 | The variable types can be whatever you like: 160 | ```c++ 161 | std::string, double, int, enum, etc... 162 | ``` 163 | Note that these variables will need to be serialized (saved for later, to a file) so when in doubt, stick to simple types rather than custom classes or structs. The SDK provides a means to serialize and store your variables. 164 | 165 | ### Analyzer Settings Interfaces Objects 166 | 167 | One of the services the Analyzer SDK provides is a means for users to edit your settings, with a GUI, with minimal work on your part. To make this possible, each of your settings variables must have a corresponding interface object. Here are the available ```AnalyzerSettingsInterface``` types: 168 | 169 | - ```AnalyzerSettingInterfaceChannel``` - Used exclusively for input channel selection. 170 | - ```AnalyzerSettingInterfaceNumberList``` - Used to provide a list of numerical options for the user to choose from. Note that this can be used to select from several enum types as well, as illustrated below. (Each dropdown below is implemented with its own interface object) 171 | - ```AnalyzerSettingInterfaceInteger``` - Allows a user to type an integer into a box. 172 | - ```AnalyzerSettingInterfaceText``` - Allows a user to enter some text into a textbox. 173 | - ```AnalyzerSettingInterfaceBool``` - Provides the user with a checkbox. 174 | 175 | ```AnalyzerSettingsInterface``` types should be declared as pointers. We’re using the ```std::auto_ptr``` type, which largely acts like a standard (raw) pointer. It’s a simple form of what’s called a “smart pointer” and it automatically calls ```delete``` on its contents when it goes out of scope. 176 | 177 | ## {YourName}AnalyzerSettings.cpp 178 | 179 | ### The Constructor 180 | 181 | First, initialize all your settings variables to their default values. Second, we’ll setup each variable’s corresponding interface object. Note that if the user has previously entered values for this analyzer, these will be loaded at a later time. Be sure to initialize the variables to values that you want to be defaults. These will show up when a user adds a new instance of your analyzer. 182 | 183 | ### Setting up each AnalyzerSettingInterface object 184 | 185 | First, we create the object (call new) and assign the value to the interface’s pointer. Note that we’re using ```std::auto_ptr```, so this means calling the member function ```reset()```. For standard (raw pointers), you would do something like: 186 | ```c++ 187 | mInputChannelInterface = new AnalyzerSettingInterfaceChannel(); 188 | ``` 189 | 190 | Next, we call the member function ```SetTitleAndTooltip()```. The title will appear to the left of the input element. Note that often times you won’t need a title, but you should use one for ```Channels```. The tooltip shows up when hovering over the input element. 191 | ```c++ 192 | void SetTitleAndTooltip( const char* title, const char* tooltip ); 193 | mInputChannelInterface->SetTitleAndTooltip( "Serial", "Standard Async Serial" ); 194 | ``` 195 | Finally, We’ll want to set the value. The interface object is, well, an interface to our settings variables. When setting up the interface, we copy the value from our settings variable to the interface. When the user makes a change, we copy the value in the interface to our settings variable. The function names for this differ depending on the type of interface. 196 | ```c++ 197 | void SetChannel( const Channel& channel ); 198 | void SetNumber( double number ); 199 | void SetInteger( int integer ); 200 | void SetText( const char* text ); 201 | void SetValue( bool value ); 202 | ``` 203 | 204 | #### ```AnalyzerSettingInterface``` Object Options 205 | 206 | We’ll want to specify the allowable options. This depends on the type of interface. 207 | 208 | ##### ```AnalyzerSettingInterfaceChannel``` 209 | Some channels can be optional , but typically they are not. By default, the user must select a channel. 210 | ```c++ 211 | void SetSelectionOfNoneIsAllowed( bool is_allowed ); 212 | ``` 213 | ##### ```AnalyzerSettingInterfaceNumberList``` 214 | Call AddNumber for every item you want in the dropdown. ```number``` is the value associated with the selection; it is not displayed to the user. 215 | ```c++ 216 | void AddNumber( double number, const char* str, const char* tooltip ); 217 | ``` 218 | ##### ```AnalyzerSettingInterfaceInteger``` 219 | You can set the allowable range for the integer the user can enter. 220 | ```c++ 221 | void SetMax( int max ); 222 | void SetMin( int min ); 223 | ``` 224 | ##### ```AnalyzerSettingInterfaceText``` 225 | By default, this interface just provides a simple textbox for the user to enter text, but you can also specify that the text should be a path, which will cause a browse button to appear. The options are ```NormalText```, ```FilePath```, or ```FolderPath```. 226 | ```c++ 227 | void SetTextType( TextType text_type ); 228 | ``` 229 | ##### ```AnalyzerSettingInterfaceBool``` 230 | There are only two allowable options for the bool interface (checkbox). 231 | ```c++ 232 | void AddNumber( double number, const char* str, const char* tooltip ); 233 | ``` 234 | After creating our interfaces (with ```new```), giving them a titles, settings their values, and specifying their allowed options, we need to expose them to the API. We do that with function AddInterface. 235 | ```c++ 236 | void AddInterface( AnalyzerSettingInterface* analyzer_setting_interface ); 237 | ``` 238 | ### Specifying Export Options 239 | 240 | Analyzers can offer more than one export type. For example txt or csv, or even a wav file or bitmap. If these need special settings, they can be specified as analyzer variables/interfaces as we’ve discussed. 241 | ```c++ 242 | void AddExportOption( U32 user_id, const char* menu_text ); 243 | void AddExportExtension( U32 user_id, const char * extension_description, const char *extension ); 244 | ``` 245 | 246 | Export options are assigned an ID. Later, when your function for generating export data is called, this ID will be provided. There are two functions you’ll need to call to specify an export type. Be sure to specify at least one export type (typically text/csv). 247 | ```c++ 248 | AddExportOption( 0, "Export as text/csv file" ); 249 | AddExportExtension( 0, "text", "txt" ); 250 | AddExportExtension( 0, "csv", "csv" ); 251 | ``` 252 | 253 | ### Specifying which channels are in use 254 | 255 | The analyzer must indicate which channel(s) it is using. This is done with the ```AddChannel``` function. 256 | Every time the channel changes (such as when the user changes the channel) the reported channel must be updated. To clear any previous channels that have been set, call ```ClearChannels```. 257 | 258 | ```c++ 259 | void ClearChannels(); 260 | void AddChannel( Channel& channel, const char* channel_label, bool is_used ); 261 | ClearChannels(); 262 | AddChannel( mInputChannel, "Serial", false ); 263 | ``` 264 | 265 | Note that in the constructor, we have set ```is_used``` to ```false```. This is because by default our channel is set to ```UNDEFINED_CHANNEL.``` After the user has set the channel to something other than 266 | ```UNDEFINED_CHANNEL``` , we would specify ```true```. It would always be true, unless the channel was optional, in which case you will need to examine the channel value, and specify false if the channel is set to ```UNDEFINED_CHANNEL```. We’ll discuss this later as it comes up. 267 | 268 | ### AnalyzerSettings Destructor 269 | 270 | Generally you won’t need to do anything in your ```AnalyzerSettings``` derived class’s destructor. However, if you are using standard (raw) pointers for your settings interfaces, you’ll need to delete them here. 271 | 272 | ### ```{YourName}AnalyzerSettings::SetSettingsFromInterfaces()``` 273 | 274 | As the name implies, in this function we will copy the values saved in our interface objects to our 275 | settings variables. This function will be called if the user updates the settings. 276 | 277 | We can also examine the values saved in the interface (the user’s selections) and choose to reject 278 | combinations we don’t want to allow. If you want to reject a particular selection, do not assign the 279 | values in the interfaces to your settings variables – use temporary variables so you can choose not to assign them at the last moment. To reject a user’s selections, return ```false``` ; otherwise return ```true```. If you return false (reject the user’s settings), you also need to call ```SetErrorText``` to indicate why. This will be presented to the user in a popup dialog. 280 | 281 | ```c++ 282 | void SetErrorText( const char* error_text ); 283 | ``` 284 | 285 | For example, when using more than one channel, you would typically want to make sure that all the channels are different. You can use the ```AnalyzerHelpers::DoChannelsOverlap``` function to make that easier if you like. 286 | 287 | For your analyzer, it’s quite possible that all possible user selections are valid. In that case you can 288 | ignore the above. 289 | 290 | After assigning the interface values to your settings variables, you also need to update the channel(s) the analyzer will report as being used. Below is an example from ```SimpleSerialAnalyzerSettings```. 291 | 292 | ```c++ 293 | bool SimpleSerialAnalyzerSettings::SetSettingsFromInterfaces() 294 | { 295 | mInputChannel = mInputChannelInterface->GetChannel(); 296 | mBitRate = mBitRateInterface->GetInteger(); 297 | ClearChannels(); 298 | AddChannel( mInputChannel, "Simple Serial", true ); 299 | return true; 300 | } 301 | ``` 302 | 303 | ### ```{YourName}AnalyzerSettings::UpdateInterfacesFromSettings()``` 304 | 305 | ```UpdateInterfacesFromSettings``` goes in the opposite direction. In this function, update all your interfaces with the values from your settings variables. Below is an example from ```SimpleSerialAnalyzerSettings```. 306 | 307 | ```c++ 308 | void SimpleSerialAnalyzerSettings::UpdateInterfacesFromSettings() 309 | { 310 | mInputChannelInterface->SetChannel( mInputChannel ); 311 | mBitRateInterface->SetInteger( mBitRate ); 312 | } 313 | ``` 314 | 315 | ### ```{YourName}AnalyzerSettings::LoadSettings()``` 316 | 317 | In the last to functions of your AnalyzerSettings-derived class, you’ll implement serialization 318 | (persistence) of your settings. It’s pretty straightforward. 319 | 320 | Your settings are saved in, and loaded from, a single string. You can technically serialize all of your 321 | variables into a string anyway you like, including third part libraries like boost, but to keep things simple we provided a mechanism to serialize your variables. We’ll discuss that here. 322 | 323 | First, you’ll need a ```SimpleArchive``` object. This will perform serialization for us. Use ```SetString``` to provide the archive with our settings string. This string is passed in as a parameter to ```LoadSettings```. 324 | 325 | ```c++ 326 | class LOGICAPI SimpleArchive 327 | { 328 | public: 329 | SimpleArchive(); 330 | ~SimpleArchive(); 331 | void SetString( const char* archive_string ); 332 | const char* GetString(); 333 | bool operator<<( U64 data ); 334 | bool operator<<( U32 data ); 335 | bool operator<<( S64 data ); 336 | bool operator<<( S32 data ); 337 | bool operator<<( double data ); 338 | bool operator<<( bool data ); 339 | bool operator<<( const char* data ); 340 | bool operator<<( Channel& data ); 341 | bool operator>>( U64& data ); 342 | bool operator>>( U32& data ); 343 | bool operator>>( S64& data ); 344 | bool operator>>( S32& data ); 345 | bool operator>>( double& data ); 346 | bool operator>>( bool& data ); 347 | bool operator>>( char const ** data ); 348 | bool operator>>( Channel& data ); 349 | protected: 350 | struct SimpleArchiveData* mData; 351 | }; 352 | ``` 353 | 354 | Next we will use the archive to loaf all of our settings variables, using the overloaded ```>>``` operator. This operator returns ```bool``` – it will return ```false``` if the requested type is not exactly in the right place in the archive. This could happen if you change the settings variables over time, and a user tries to load an old settings string. If loading fails, you can simply not update that settings variable (it will retain its default value). 355 | 356 | Since our channel values may have changed, we will also need to update the channels we’re reporting as using. We need to do this every times settings change. 357 | 358 | Lastly, call ```UpdateInterfacesFromSettings.``` This will update all our interfaces to reflect the newly loaded values. 359 | 360 | Below is an example from ```SimpleSerialAnalyzerSettings```. 361 | 362 | ```c++ 363 | void SimpleSerialAnalyzerSettings::LoadSettings( const char* settings ) 364 | { 365 | SimpleArchive text_archive; 366 | text_archive.SetString( settings ); 367 | text_archive >> mInputChannel; 368 | text_archive >> mBitRate; 369 | ClearChannels(); 370 | AddChannel( mInputChannel, "Simple Serial", true ); 371 | UpdateInterfacesFromSettings(); 372 | } 373 | ``` 374 | 375 | ### ```{YourName}AnalyzerSettings::SaveSettings()``` 376 | 377 | Our last function will save all of our settings variables into a single string. We’ll use ```SimpleArchive``` to serialize them. 378 | The order in which we serialize our settings variables must be exactly the same order as we extract them, in ```LoadSettings```. 379 | When returning, use the ```SetReturnString``` function, as this will provide a pointer to a string that will not go out of scope when the function ends. 380 | 381 | Bellow is an example from ```SimpleSerialAnalyzerSettings```: 382 | 383 | ```c++ 384 | const char* SimpleSerialAnalyzerSettings::SaveSettings() 385 | { 386 | SimpleArchive text_archive; 387 | text_archive << mInputChannel; 388 | text_archive << mBitRate; 389 | return SetReturnString( text_archive.GetString() ); 390 | } 391 | ``` 392 | 393 | 394 | 395 | # ```AnalyzerResults``` 396 | 397 | After creating your ```AnalyzerSettings``` class, working on your *{YourName}AnalyzerResults* files is the next step. 398 | 399 | ```AnalyzerResults``` is what we use to transform our results into text for display and as well as exported files, etc. 400 | 401 | Tip: You may end up finalizing may of the details about how your results are saved when you work on your main ```Analyzer``` file – *{YourName}Analyzer.cpp/.h* ; You can simply implement the bare minimum of the functions in your *{YourName}AnalyzerResults.cpp* file, and come back to it later. 402 | 403 | ## {YourName}AnalyzerResults.h 404 | 405 | In addition to the constructor and destructor, there are 5 functions we’ll need to implement. 406 | ```AnalyzerResults``` is fairly straightforward, so typically we won’t need much in the way of helper functions or member variables. 407 | 408 | Here’s the ```SimpleSerialAnalyzerResults``` header file. Yours will like very similar, with the only difference typically being the ```enums``` and/or ```defines``` you need. 409 | 410 | ```c++ 411 | #ifndef SIMPLESERIAL_ANALYZER_RESULTS 412 | #define SIMPLESERIAL_ANALYZER_RESULTS 413 | 414 | #include 415 | 416 | class SimpleSerialAnalyzer; 417 | class SimpleSerialAnalyzerSettings; 418 | 419 | class SimpleSerialAnalyzerResults : public AnalyzerResults 420 | { 421 | public: 422 | SimpleSerialAnalyzerResults( SimpleSerialAnalyzer* analyzer, 423 | SimpleSerialAnalyzerSettings* settings ); 424 | virtual ~SimpleSerialAnalyzerResults(); 425 | virtual void GenerateBubbleText( U64 frame_index, Channel& channel, DisplayBase 426 | display_base ); 427 | virtual void GenerateExportFile( const char* file, DisplayBase display_base, U32 428 | export_type_user_id ); 429 | virtual void GenerateFrameTabularText(U64 frame_index, DisplayBase display_base ); 430 | virtual void GeneratePacketTabularText( U64 packet_id, DisplayBase display_base ); 431 | virtual void GenerateTransactionTabularText( U64 transaction_id, DisplayBase 432 | display_base ); 433 | protected: //functions 434 | protected: //vars 435 | SimpleSerialAnalyzerSettings* mSettings; 436 | SimpleSerialAnalyzer* mAnalyzer; 437 | }; 438 | #endif //SIMPLESERIAL_ANALYZER_RESULTS 439 | ``` 440 | 441 | ## {YourName}AnalyzerResults.cpp 442 | 443 | In your constructor, save copies of the ```Analyzer``` and ```Settings``` raw pointers provided. There’s generally nothing else to do for the constructor or destructor. Below is an example from 444 | *SimpleSerialAnalyzerResults.cpp:* 445 | 446 | ```c++ 447 | SimpleSerialAnalyzerResults::SimpleSerialAnalyzerResults( SimpleSerialAnalyzer* analyzer, 448 | SimpleSerialAnalyzerSettings* settings ) 449 | : AnalyzerResults(), 450 | mSettings( settings ), 451 | mAnalyzer( analyzer ) 452 | { 453 | } 454 | ``` 455 | 456 | ## Frames, Packets, and Transactions 457 | 458 | The basic result an analyzer generates is called a ```Frame```. This could be byte of serial data, the header of a CAN packet, the MOSI and MISO values from 8-bit of SPI, etc. Smaller elements, such the Start and Stop events in I2C can be saved as ```Frames``` , are probably better saved as be graphical elements (called ```Markers``` ) and otherwise ignored. ```Collections``` of Frames make up ```Packets``` , and collections of ```Packets``` make up ```Transactions```. 95% of what you will be concerned about is ```Frames```. What exactly a ```Frame``` represents is your choice, but unless your protocol is fairly complicated (such as USB, CAN, Ethernet) the best bet is to make the Frame your main result element. We’ll get into more detail regarding how to save your results when we describe to your ```Analyzer``` derived class. 459 | 460 | ### Frame 461 | 462 | A ```Frame``` is an object, with fairly generic member variables which can be used to save results. A ```Frame``` represents a piece of information conveyed by your protocol over an expanse of time. Here is the definition of a ```Frame```: 463 | 464 | ```c++ 465 | class LOGICAPI Frame 466 | { 467 | public: 468 | Frame(); 469 | Frame( const Frame& frame ); 470 | ~Frame(); 471 | S64 mStartingSampleInclusive; 472 | S64 mEndingSampleInclusive; 473 | U64 mData1; 474 | U64 mData2; 475 | U8 mType; 476 | U8 mFlags; 477 | }; 478 | ``` 479 | 480 | #### Frame Member Variables 481 | 482 | * ```mStartingSampleInclusive``` and ```mEndingSampleInclusive``` are the sample numbers for the beginning and end of the ```Frame```. Frames may not overlap and they cannot share the same sample. For example, if a single clock edge ends one Frame, and starts a new Frame, then you’ll need to add one (+1) to the ```mStartingSampleInclusive``` of the second frame. A single Frame cannot have ```mStartingSampleInclusive``` and ```mEndingSampleInclusive``` be equal. They must be at least 1 sample apart. 483 | * ```mData1``` and ```mData1``` Two 64-bit numbers to store Frame data data. For example, in SPI, one of these is used for the MISO result, and the other for the MISO result. Often times you’ll only use one of these variables. 484 | * ```mType``` variable is intended to be used to save a custom-defined enum value, representing the type of ```Frame```. For example, CAN can have many different types of frames – header, data, CRC, etc. Serial only has one type, and it doesn’t use this member variable. 485 | * ```mFlags``` is intended to be a holder for custom flags which might apply to frame. Note that this is not intended for use with a custom enum, but rather for individual bits that can be or’ed together. For example, in Serial, there is a flag for framing-error, and a flag for parity error. 486 | ```c++ 487 | #define FRAMING_ERROR_FLAG ( 1 << 0 ) 488 | #define PARITY_ERROR_FLAG ( 1 << 1 ) 489 | ``` 490 | * Two flags are reserved by the system, and will produce an error or warning indication on the bubble displaying the ```Frame```. 491 | ```c++ 492 | #define DISPLAY_AS_ERROR_FLAG ( 1 << 7 ) 493 | #define DISPLAY_AS_WARNING_FLAG ( 1 << 6 ) 494 | ``` 495 | ### ```{YourName}AnalyzerResults::GenerateBubbleText()``` 496 | 497 | ```GenerateBubbleText``` exists to retrieve text to put in a bubble to be displayed on the screen. If you like you can leave this function empty, and return to it after implementing the rest of your analyzer. The ```frame_index``` is the index to use to get the Frame itself – for example: 498 | 499 | ```c++ 500 | Frame frame = GetFrame( frame_index ); 501 | ``` 502 | > Rarely, an analyzer needs to display results on more than one channel (SPI is the only example of this in an analyzer we make). If so, the channel which is requesting the bubble is specified in the ```Channel``` parameter. In most situations, this can simply be ignored. If you need to use it, just compare it to the channels saved in your ```mSettings``` object to see which bubble should be generated – for example, for the MISO or MOSI channel. 503 | 504 | 505 | Bubbles can display different length strings, depending on how much room is available. You should generate several results strings. The simplest might simply indicate the type of contents (‘D’ for data, for example), longer ones might indicate the full number (“0xFF01”), and longer ones might be very verbose (“Left Channel Audio Data: 0xFF01”). 506 | 507 | To provide strings to the caller, use the ```AddStringResult``` function. This will make sure that the strings persist after the function has returned. Always call ```ClearResultStrings``` before adding any string results. 508 | 509 | Note that to easily concatenate multiple strings, simply provide ```AddStringResult``` with more strings. 510 | 511 | ```c++ 512 | void ClearResultStrings(); 513 | void AddResultString( const char* str1, const char* str2 = NULL, const char* str3 = NULL, 514 | const char* str4 = NULL, const char* str5 = NULL, const char* str6 = NULL ); //multiple strings will be concatenated 515 | ``` 516 | 517 | Here’s the Serial Analyzer’s ```GenerateBubbleText``` function: 518 | 519 | ```c++ 520 | void SerialAnalyzerResults::GenerateBubbleText( U64 frame_index, Channel& /```Channel```/, 521 | DisplayBase display_base ) // unreferenced vars commented out to remove warnings. 522 | { 523 | // we only need to pay attention to 'channel' if we're making bubbles for more than 524 | one channel( as set by AddChannelBubblesWillAppearOn ) ClearResultStrings(); 525 | Frame frame = GetFrame( frame_index ); 526 | bool framing_error = false; 527 | if( ( frame.mFlags & FRAMING_ERROR_FLAG ) != 0 ) 528 | framing_error = true; 529 | bool parity_error = false; 530 | if( ( frame.mFlags & PARITY_ERROR_FLAG ) != 0 ) 531 | parity_error = true; 532 | char number_str[ 128 ]; 533 | AnalyzerHelpers::GetNumberString( frame.mData1, display_base, mSettings - > mBitsPerTransfer, number_str, 128 ); 534 | char result_str[ 128 ]; 535 | if( ( parity_error == true ) || ( framing_error == true ) ) 536 | { 537 | AddResultString( "!" ); 538 | sprintf( result_str, "%s (error)", number_str ); 539 | AddResultString( result_str ); 540 | if( parity_error == true && framing_error == false ) 541 | sprintf( result_str, "%s (parity error)", number_str ); 542 | else if( parity_error == false && framing_error == true ) 543 | sprintf( result_str, "%s (framing error)", number_str ); 544 | else 545 | sprintf( result_str, "%s (framing error & parity error)", number_str ); 546 | AddResultString( result_str ); 547 | } 548 | else 549 | { 550 | AddResultString( number_str ); 551 | } 552 | } 553 | ``` 554 | ### ```{YourName}AnalyzerResults::GenerateExportFile()``` 555 | 556 | This function is called when the user tries to export the analyzer results to a file. If you like, you can leave this function empty, and come back to it after finalizing the rest of your analyzer design. 557 | The ```file``` parameter is string containing the full path of the file you should create and write to with the analyzer results. 558 | 559 | ```c++ 560 | std::ofstream file_stream( file, std::ios::out ); 561 | ``` 562 | The ```display_base``` parameter contains the radix which should be used to display numerical results. (See ```DisplayBase``` for more detail) 563 | 564 | The ```export_type_user_id``` parameter is the id associated with the export-type the user selected. You 565 | specify what these options are (there should be at least one) in the constructor of your ```AnalyzerSettings``` - derived class. If you only have one export option you can ignore this parameter. 566 | 567 | 568 | Other than that, the implementation is pretty straightforward. Here is an example from 569 | ```SerialAnalyzerResults.cpp```: 570 | 571 | ```c++ 572 | void SerialAnalyzerResults::GenerateExportFile( const char* file, DisplayBase display_base, U32 /*export_type_user_id*/ ) 573 | { 574 | // export_type_user_id is only important if we have more than one export type. 575 | std::ofstream file_stream( file, std::ios::out ); 576 | U64 trigger_sample = mAnalyzer->GetTriggerSample(); 577 | U32 sample_rate = mAnalyzer->GetSampleRate(); 578 | file_stream << "Time [s],Value,Parity Error,Framing Error" << std::endl; 579 | U64 num_frames = GetNumFrames(); 580 | for( U32 i = 0; i < num_frames; i++ ) 581 | { 582 | Frame frame = GetFrame( i ); 583 | // static void GetTimeString( U64 sample, U64 trigger_sample, U32 584 | sample_rate_hz, char* result_string, U32 result_string_max_length ); 585 | char time_str[ 128 ]; 586 | AnalyzerHelpers::GetTimeString( frame.mStartingSampleInclusive, trigger_sample, sample_rate, time_str, 128 ); 587 | char number_str[ 128 ]; 588 | AnalyzerHelpers::GetNumberString( frame.mData1, display_base, mSettings - > mBitsPerTransfer, number_str, 128 ); 589 | file_stream << time_str << "," << number_str; 590 | if( ( frame.mFlags & FRAMING_ERROR_FLAG ) != 0 ) 591 | file_stream << ",Error,"; 592 | else 593 | file_stream << ","; 594 | if( ( frame.mFlags & FRAMING_ERROR_FLAG ) != 0 ) 595 | file_stream << "Error"; 596 | file_stream << std::endl; 597 | if( UpdateExportProgressAndCheckForCancel( i, num_frames ) == true ) 598 | { 599 | file_stream.close(); 600 | return; 601 | } 602 | } 603 | file_stream.close(); 604 | } 605 | ``` 606 | ### ```{YourName}AnalyzerResults::GenerateFrameTabularText()``` 607 | 608 | ```GenerateFrameTabularText``` is for producing text for tabular display which is not yet implemented as of 1.1.5. You can safely leave it empty. ```GenerateFrameTabularText``` is almost the same as ```GenerateBubbleText``` , except that you should generate only one text result. Ideally the string should be concise, and only be a couple inches long or less under normal (non error) circumstances. 609 | 610 | Here is an example from ```SerialAnalyzerResults.cpp```: 611 | 612 | ```c++ 613 | void SerialAnalyzerResults::GenerateFrameTabularText( U64 frame_index, DisplayBase display_base ) 614 | { 615 | Frame frame = GetFrame( frame_index ); 616 | ClearResultStrings(); 617 | bool framing_error = false; 618 | if( ( frame.mFlags & FRAMING_ERROR_FLAG ) != 0 ) 619 | framing_error = true; 620 | bool parity_error = false; 621 | if( ( frame.mFlags & PARITY_ERROR_FLAG ) != 0 ) 622 | parity_error = true; 623 | char number_str[ 128 ]; 624 | AnalyzerHelpers::GetNumberString( frame.mData1, display_base, mSettings - > mBitsPerTransfer, number_str, 128 ); 625 | char result_str[ 128 ]; 626 | if( parity_error == false && framing_error == false ) 627 | { 628 | AddResultString( number_str ); 629 | } 630 | else if( parity_error == true && framing_error == false ) 631 | { 632 | sprintf( result_str, "%s (parity error)", number_str ); 633 | AddResultString( result_str ); 634 | } 635 | else if( parity_error == false && framing_error == true ) 636 | { 637 | sprintf( result_str, "%s (framing error)", number_str ); 638 | AddResultString( result_str ); 639 | } 640 | else 641 | { 642 | sprintf( result_str, "%s (framing error & parity error)", number_str ); 643 | AddResultString( result_str ); 644 | } 645 | } 646 | ``` 647 | ### ```{YourName}AnalyzerResults::GeneratePacketTabularText()``` 648 | 649 | This function is used to produce strings representing packet results for the tabular view. For now, just leave it empty. We’ll be updating the SDK and software to take advantage of this capability later. 650 | 651 | ### ```{YourName}AnalyzerResults::GenerateTransactionTabularText()``` 652 | 653 | This function is used to produce strings representing packet results for the tabular view. For now, just leave it empty. We’ll be updating the SDK and software to take advantage of this capability later. 654 | 655 | # Analyzer 656 | 657 | Your ```Analyzer``` derived class is the heart of the analyzer. It’s here were we analyze the bits coming in, in real time, and generate analyzer results. Other than a few other housekeeping things, that’s it. Let’s get started. 658 | 659 | ## {YourName}Analyzer.h 660 | In addition to the constructor and destructor, here are the functions you’ll need to implement: 661 | 662 | ```c++ 663 | virtual void WorkerThread(); 664 | virtual U32 GenerateSimulationData( U64 newest_sample_requested, U32 sample_rate, 665 | SimulationChannelDescriptor** simulation_channels ); 666 | virtual U32 GetMinimumSampleRateHz(); 667 | virtual const char* GetAnalyzerName() const; 668 | virtual bool NeedsRerun(); 669 | extern "C" ANALYZER_EXPORT const char* __cdecl GetAnalyzerName(); 670 | extern "C" ANALYZER_EXPORT Analyzer* __cdecl CreateAnalyzer( ); 671 | extern "C" ANALYZER_EXPORT void __cdecl DestroyAnalyzer( Analyzer* analyzer ); 672 | ``` 673 | 674 | You’ll also need these member variables: 675 | ```c++ 676 | std::auto_ptr< {YourName}AnalyzerSettings > mSettings; 677 | std::auto_ptr< {YourName}AnalyzerResults > mResults; 678 | {YourName}SimulationDataGenerator mSimulationDataGenerator; 679 | bool mSimulationInitialized; 680 | ``` 681 | 682 | You’ll also need one ```AnalyzerChannelData``` raw pointer for each input. For SerialAnalyzer, for example, we need 683 | ```c++ 684 | AnalyzerChannelData* mSerial; 685 | ``` 686 | As you develop your analyzer, you’ll add additional member variables and helper functions depending on your analysis needs. 687 | 688 | ## {YourName}Analyzer.cpp 689 | 690 | ## Constructor 691 | Your constructor will look something like this 692 | ```c++ 693 | {YourName}Analyzer::{YourName}Analyzer() 694 | : Analyzer(), 695 | mSettings( new {YourName}AnalyzerSettings() ), 696 | mSimulationInitialized( false ) 697 | { 698 | SetAnalyzerSettings( mSettings.get() ); 699 | } 700 | ``` 701 | Note that here you’re calling the base class constructor, ```new()```'ing your ```AnalyzerSettings``` derived class, and providing the base class with a pointer to your ```AnalyzerSettings``` - derived object. 702 | 703 | ## Destructor 704 | This only thing your destructor must do is call ```KillThread```. This is a base class member function and will make sure your class destructs in the right order. 705 | 706 | ## ```{YourName}Analyzer::WorkerThread()``` 707 | 708 | This function the key to everything – it’s where you’ll decode the incoming data. Let’s leave it empty for now, and we’ll discuss in detail once we complete the other housekeeping functions. 709 | 710 | ## ```bool {YourName}Analyzer::NeedsRerun()``` 711 | 712 | Generally speaking, just return ```false``` in this function. For more detail, read on. 713 | 714 | This function is called when your analyzer has finished analyzing the collected data (this condition is detected from outside your analyzer.) 715 | 716 | This function gives you the opportunity to run the analyzer all over again, on the same data. To do this, simply return ```true```. Otherwise, return ```false```. The only thing this is currently used for is for our Serial analyzer, for “autobaud”. When using autobaud, we don’t know ahead of time what the serial bit rate will be. If the rate turns out to be significantly different from the rate we ran the analysis at, we return ```true``` to re-run the analysis. 717 | 718 | If you return ```true``` , that’s all there is to do. Your analyzer will be re-run automatically. 719 | 720 | ## ```{YourName}Analyzer::GenerateSimulationData()``` 721 | 722 | This is the function that gets called to obtain simulated data. We made a dedicated class for handling this earlier – we just need to do some housekeeping here to hook it up. 723 | 724 | ```c++ 725 | U32 {YourName}Analyzer::GenerateSimulationData( U64 minimum_sample_index, U32 device_sample_rate, 726 | SimulationChannelDescriptor** simulation_channels ) 727 | { 728 | if( mSimulationInitialized == false ) 729 | { 730 | mSimulationDataGenerator.Initialize( GetSimulationSampleRate(), mSettings.get() ); 731 | mSimulationInitialized = true; 732 | } 733 | return mSimulationDataGenerator.GenerateSimulationData( minimum_sample_index, device_sample_rate, simulation_channels ); 734 | } 735 | ``` 736 | ## ```U32 {YourName}Analyzer::GetMinimumSampleRateHz()``` 737 | 738 | This function is called to see if the user’s selected sample rate is sufficient to get good results for this analyzer. For Serial, for instance, we would like the sample rate to be x4 higher that the serial bit rate. For other, typically synchronous, protocols, you may not ask the user to enter the data’s bit rate – therefore you can’t know ahead of time what sample rate is required. In that case, you can either return the smallest sample rate (25000), or return a value that will be fast enough for your simulation. However, your simulation really should adjust its own rate depending on the sample rate – for example, when simulation SPI you should probably make the bit rate something like 4x the sample rate. This will allow the simulation to work perfectly no matter what the sample rate is. The rule of thumb is to require oversampling by x4 if you know the data’s bit rate, otherwise just return 25000. Here’s what we do in ```SerialAnalyzer.cpp``` 739 | 740 | ```c++ 741 | U32 SerialAnalyzer::GetMinimumSampleRateHz() 742 | { 743 | return mSettings->mBitRate * 4; 744 | } 745 | ``` 746 | 747 | ## ```{YourName}Analyzer::GetAnalyzerName()``` 748 | Simply return the name you would like to see in the “Add Analyzer” drop down. 749 | ```c++ 750 | return "Async Serial"; 751 | ``` 752 | 753 | ## ```GetAnalyzerName()``` 754 | Return the same string as in the previous function. 755 | ```c++ 756 | return "Async Serial"; 757 | ``` 758 | 759 | ## ```Analyzer* CreateAnalyzer()``` 760 | Return a pointer to a new instance of your Analyzer-derived class. 761 | ```c++ 762 | return new {YourName}Analyzer(); 763 | ``` 764 | 765 | ## ```DestroyAnalyzer( Analyzer* analyzer )``` 766 | Simply call ```delete``` on the provided pointer. 767 | ```c++ 768 | delete analyzer; 769 | ``` 770 | 771 | ## ```{YourName}Analyzer::WorkerThread()``` 772 | Ok, now that everything else is taken care of, let’s look at the most important part of the analyzer in detail. First, we’ll ```new``` our ```AnalyzerResults``` derived object. 773 | ```c++ 774 | mResults.reset( new {YourName}AnalyzerResults( this, mSettings.get() ) ); 775 | ``` 776 | Well provide a pointer to our results to the base class: 777 | ```c++ 778 | SetAnalyzerResults( mResults.get() ); 779 | ``` 780 | Let’s indicate which channels we’ll be displaying results on (in the form of bubbles). Usually this will only be one channel. (Except in the case of SPI, where we’ll want to put bubbles on both the MISO and MISO lines.) Only indicate where we will display bubbles – other markup, like tick marks, arrows, etc, are not bubbles, and should not be reported here. 781 | ```c++ 782 | mResults->AddChannelBubblesWillAppearOn( mSettings->mInputChannel ); 783 | ``` 784 | We’ll probably want to know (and save in a member variable) the sample rate. 785 | ```c++ 786 | mSampleRateHz = GetSampleRate(); 787 | ``` 788 | Now we need to get access to the data itself. We’ll need to get pointers to ```AnalyzerChannelData``` objects for each channel we’ll need data from. For Serial, we’ll just need one. For SPI, we might need 4. Etc. 789 | ```c++ 790 | mSerial = GetAnalyzerChannelData( mSettings->mInputChannel ); 791 | ``` 792 | 793 | # Traversing the Data 794 | We’ve now ready to start traversing the data, and recording results. We’ll look at each of these tasks in turn. First, a word of advice - A protocol is typically fairly straightforward, when it behaves exactly as it supposed to. The more your analyzer needs to deal with exceptions to the rule, the more sophisticated it’ll need to be. The best bet is probably to start as simple as possible, and add more “gotchas” as they are discovered, rather than to try and design an elaborate, bulletproof analyzer from the start, especially when you’re new to the API. 795 | 796 | ## ```AnalyzerChannelData``` 797 | 798 | ```AnalyzerChannelData``` is the class that will give us access to the data from a particular input. This will provide data in a serialized form – we will not have “random access” to any bit in the saved data. 799 | Rather, we will start at the beginning, and move forward as more data becomes available. In fact we’ll never know when we’re at the “end” of the data or not – attempts to move forward in the stream will block until more data becomes available. This will allow our analyzer to process data in a real-time manner. (It may backlog, of course, if it can’t keep up – although generally the collection will end at some point and we’ll be able to finish). 800 | 801 | ### ```AnalyzerChannelData ```– State 802 | 803 | If we’re not sure where are in the stream, or if the input is currently high or low, we can just ask: 804 | ```c++ 805 | U64 GetSampleNumber(); 806 | BitState GetBitState(); 807 | ``` 808 | 809 | ### ```AnalyzerChannelData ```– Basic Traversal 810 | We’ll need some ability to move forward in the stream. We have three basic ways to do this. 811 | 812 | 1. We can move forward in the stream by a specific number of samples. This function will return how many times the input toggled (changed from a high to a low, or low to a high) to make this move. 813 | ```c++ 814 | U32 Advance( U32 num_samples ); 815 | ``` 816 | 2. If we want to move forward to a particular absolute position, we can use this function. It also returns the number of times the input changed during the move. 817 | ```c++ 818 | U32 AdvanceToAbsPosition( U64 sample_number ); 819 | ``` 820 | 3. We also might want to move forward until the state changes. After calling this function you might want to call ```GetSampleNumber``` to find out how far you’ve come. 821 | ```c++ 822 | void AdvanceToNextEdge(); 823 | ``` 824 | 825 | ### ```AnalyzerChannelData ```– Advanced Traversal (looking ahead without moving) 826 | As you develop your analyzer(s) certain tasks may come up that call for more sophisticated traversal. Here are some ways of doing it. 827 | 828 | This function does not move your position in the stream. Remember, you can not move backward in the stream, so sometimes seeing what’s up ahead without moving can be very important. 829 | ```c++ 830 | U64 GetSampleOfNextEdge(); 831 | ``` 832 | This function does not move your position in the stream. Here you find out if moving forward a given number of samples would cause the bit state (low or high) to change. 833 | ```c++ 834 | bool WouldAdvancingCauseTransition( U32 num_samples ); 835 | ``` 836 | This is the same as the prior function, except you provide the absolute position. 837 | ```c++ 838 | bool WouldAdvancingToAbsPositionCauseTransition( U64 sample_number ); 839 | ``` 840 | 841 | ### ```AnalyzerChannelData ```– Keeping track of the smallest pulse. 842 | When we were implementing Serial’s “autobaud” it was clear that keeping track of the minimum pulse length over the entire stream was overly cumbersome. If you need this capability for some reason, these functions will provide it for you (it’s turned off by default) 843 | ```c++ 844 | void TrackMinimumPulseWidth(); 845 | U64 GetMinimumPulseWidthSoFar(); 846 | ``` 847 | 848 | ## Filling in Frames 849 | Using the above ```AnalyzerChannelData``` class, we can now move through a channel’s data and analyze it. Now lets discus how to store results. We described ```Frames``` when talking about the ```AnalyzerResults``` - derived class. A ```Frame``` is the basic unit results are saved in. ```Frames``` have: 850 | 851 | 852 | - starting and ending time (starting and ending sample number), 853 | - x2 64-bit values to save results in 854 | - an 8-bit type variable – to specify the type of Frame 855 | - an 8-bit flags variable – to specify Yes/No types of results. 856 | 857 | When we have analyzed far enough, and now have a complete ```Frame``` we would like to record, we do it like this: 858 | 859 | ```c++ 860 | Frame frame; 861 | frame.mStartingSampleInclusive = first_sample_in_frame; 862 | frame.mEndingSampleInclusive = last_sample_in_frame; 863 | frame.mData1 = the_data_we_collected; 864 | //frame.mData2 = some_more_data_we_collected; 865 | //frame.mType = OurTypeEnum; //unless we only have one type of frame 866 | frame.mFlags = 0; 867 | if( such_and_such_error == true ) 868 | frame.mFlags |= SUCH_AND_SUCH_ERROR_FLAG | DISPLAY_AS_ERROR_FLAG; 869 | if( such_and_such_warning == true ) 870 | frame.mFlags |= SUCH_AND_SUCH_WARNING_FLAG | DISPLAY_AS_WARNING_FLAG; 871 | mResults->AddFrame( frame ); 872 | mResults->CommitResults(); 873 | ReportProgress( frame.mEndingSampleInclusive ); 874 | ``` 875 | 876 | First we make a ```Frame``` on the stack. Then we fill in all its values. If there’s a value you don’t need, to save time you can skip setting it. ```mFlags``` should always be set to zero, however, because certain pre-defined flags will cause the results bubble to indicate a warning or error ( ```DISPLAY_AS_WARNING_FLAG```, and ```DISPLAY_AS_ERROR_FLAG``` ). 877 | Part of the ```Frame``` is expected to be filled in correctly because it’s used automatically by other systems. In particular, the following should be filled in properly: 878 | 879 | - mStartingSampleInclusive 880 | - mEndingSampleInclusive 881 | - mFlags 882 | 883 | Other parts of the ```Frame``` are only there so you can create text descriptions or export the data to a desired format. 884 | 885 | ## Saving Frames 886 | To save a ```Frame``` , Use ```AddFrame``` from your ```AnalyzerResults``` - derived class. Note that frames must be added in-order, and must not overlap. In other words, you can’t add a ```Frame``` from an earlier time (smaller sample number) after adding a ```Frame``` form a later time (larger sample number). Immediately after adding a ```Frame``` , call ```CommitResults```. This makes the ```Frame``` accessible to the external system. Also call the ```Analyzer``` base class ```ReportProgress```. Provide it with it the largest sample number you have processed. 887 | 888 | ## Adding Markers 889 | Makers are visual elements you can place on the waveform to highlight various waveform features as they relate to your protocol. For example, in our asynchronous serial analyzer, we place little white dots at the locations where we sample the input’s state. You can also use markers to indicate where the protocol falls out of specification, a rising or falling clock edge, etc. You specify where to put the marker (the sample number), which channel to display it on, and which graphical symbol to use. 890 | ```c++ 891 | void AddMarker( U64 sample_number, MarkerType marker_type, Channel& channel ); 892 | ``` 893 | For example, from ```SerialAnalyzer.cpp``` : 894 | ```c++ 895 | mResults->AddMarker( marker_location, AnalyzerResults::Dot, mSettings->mInputChannel ); 896 | ``` 897 | Currently, the available graphical artifacts are 898 | 899 | ```c++ 900 | enum MarkerType { Dot, ErrorDot, Square, ErrorSquare, UpArrow, DownArrow, X, ErrorX, 901 | Start, Stop, One, Zero }; 902 | ``` 903 | Like ```Frames``` , you must add ```Markers``` in order. 904 | 905 | ```Markers``` are strictly for graphical markup, they can not be used to help generate display text, export files, etc. Only ```Frames``` are accessible to do that. 906 | 907 | ## Packets and Transactions 908 | 909 | ```Packets``` and ```Transactions``` are only moderately supported as of now, but they will be becoming more prominent in the software. 910 | 911 | ```Packets``` are sequential collections of ```Frames```. Grouping ```Frames``` into ```Packets``` as you create them is easy: 912 | 913 | ```c++ 914 | U64 CommitPacketAndStartNewPacket(); 915 | void CancelPacketAndStartNewPacket(); 916 | ``` 917 | When you add a ```Frame``` , it will automatically be added to the current ```Packet```. When you’ve added all the ```Frames``` you want in a ```Packet```, call ```CommitPacketAndStartNewPacket```. In some conditions, especially errors, you will want start a new packet without committing the old one. For this, call 918 | ```CancelPacketAndStartNewPacket```. 919 | 920 | Note that ```CommitPacketAndStartNewPacket``` returns an packet id. You can use this id to assign a 921 | particular packet to a transaction. 922 | 923 | ```c++ 924 | void AddPacketToTransaction( U64 transaction_id, U64 packet_id ); 925 | ``` 926 | The ```transaction_id``` is an ID you generate yourself. 927 | 928 | The analyzers created by Saleae do not yet use ```Transactions``` , and the current Analyzer probably never will. ```Transactions``` are provided for higher-level protocols, and you may not want to bother, especially since they aren’t used in the Logic software yet. We will use ```Transactions``` in analyzers for more sophisticated protocols in the future. 929 | 930 | ```Packets``` on the other hand tend to be fairly applicable for lower level protocols, although not in entirely the same ways. For example: 931 | 932 | - Serial Analyzer – no packet support makes sense at this level. (there are many more structured protocols that use asynchronous serial where packets would be applicable) 933 | - SPI Analyzer – packets are used to delimit between periods when the enable line is active. 934 | - I2C Analyzer – packets are used to delimit periods between a start/restart and a stop. 935 | - CAN Analyzer – packets are used to represent, well, CAN packets. 936 | - UNI/O – packets are used to group Frames in a UNI/O sequence. 937 | - 1 - Wire – packets are used to group 1-Wire sequences. 938 | - I2S/PCM – packets aren’t used. 939 | 940 | Currently, ```Packets``` are only used when exporting data to text/csv. In the future, analyzer tabular views will support nesting ```Frames``` into ```Packets``` , and identifying ```Transactions``` (ids) associated with particular ```Packets```. Generating the textual content to support this is provided in your ```AnalyzerResults``` - derived class. 941 | 942 | When using Packet ids when exporting data to text/csv, use the GetPacketContainingFrameSequential function, to avoid searching for the packet every time. The GetPacketContainingFrame will do a full search and be much less efficient. 943 | 944 | # Utilities 945 | 946 | ## ```BitExtractor``` 947 | Note that above we use a number of helper functions and classes. Let’s discuss BitExtractor briefly. Some protocols have variable numbers of bits per word, and settings for if the most significant bit is first or last. This can be a pain to manage, so we made the ```BitExtractor``` class. This can be done by hand of course if you like, but this class tends to tidy up the code quite a bit in our experience. 948 | 949 | ```c++ 950 | BitExtractor( U64 data, AnalyzerEnums::ShiftOrder shift_order, U32 num_bits ); 951 | BitState GetNextBit(); 952 | ``` 953 | 954 | ## ```DataBuilder``` 955 | Similar, but reversed, is the ```DataBuilder``` class, but as this generally used for collecting data, we’ll talk more about it then. 956 | 957 | # ```AnalyzerHelpers``` 958 | 959 | Some static helper functions that might be helpful, grouped under the class ```AnalyzerHelpers```, include: 960 | 961 | ```c++ 962 | static bool IsEven( U64 value ); 963 | static bool IsOdd( U64 value ); 964 | static U32 GetOnesCount( U64 value ); 965 | static U32 Diff32( U32 a, U32 b ); 966 | ``` 967 | ## ```DisplayBase``` 968 | ```display_base``` specifies the radix (hex, decimal, binary) that any numerical values should be displayed in. There are some helper functions provided so you should never have to deal directly with this issue. 969 | 970 | ```c++ 971 | enum DisplayBase { Binary, Decimal, Hexadecimal, ASCII }; 972 | ``` 973 | ## ```GetNumberString()``` 974 | In ```GetNumberString```, above, note that ```num_data_bits``` is the number of bits which are actually part of your result. For sample, for I2C, this is always 8. It will depend on your protocol and possibly on user settings. Providing this will let ```GetNumberString``` produce a well-formatted number with the right amount of zero-padding for the type of value under consideration. 975 | ```c++ 976 | AnalyzerHelpers::GetNumberString( U64 number, DisplayBase display_base, U32 num_data_bits, char* result_string, U32 result_string_max_length ); 977 | ``` 978 | ## ```GetTimeString()``` 979 | Often times you’ll want to print out the time (in seconds) associated with a particular result. To do this, use the ```GetTimeString``` helper function. You’ll need the trigger sample number and the sample rate – which can be obtained from your ```Analyzer``` object pointer. 980 | 981 | ```c++ 982 | U64 trigger_sample = mAnalyzer->GetTriggerSample(); 983 | U32 sample_rate = mAnalyzer->GetSampleRate(); 984 | static void AnalyzerHelpers::GetTimeString( U64 sample, U64 trigger_sample, U32 985 | sample_rate_hz, char* result_string, U32 result_string_max_length ); 986 | ``` 987 | 988 | # ```SimulationDataGenerator``` 989 | 990 | The next step after creating your ```{YourName}AnalyzerSettings``` files, is to create your 991 | ```SimulationDataGenerator```. 992 | 993 | Your ```SimulationDataGenerator``` class provides simulated data so that you can test your analyzer against controlled, predictable waveforms. Generally you should make the simulated data match the user settings, so you can easily test under a variety of expected conditions. In addition, simulated data gives end users an example of what to expect when using your analyzer, as well as examples of what the waveforms should look like. 994 | 995 | That said, fully implementing simulated data is not absolutely required to make an analyzer. 996 | {YourName}SimulationDataGenerator.h 997 | 998 | Besides the constructor and destructor, there are only two required functions, and two required 999 | variables. Other functions and variables can be added, to help implement your simulated data. Here is an example starting point, from ```SimpleSerialSimulationDataGenerator.h``` 1000 | 1001 | ```c++ 1002 | #ifndef SIMPLESERIAL_SIMULATION_DATA_GENERATOR 1003 | #define SIMPLESERIAL_SIMULATION_DATA_GENERATOR 1004 | 1005 | #include 1006 | 1007 | class SimpleSerialAnalyzerSettings; 1008 | 1009 | class SimpleSerialSimulationDataGenerator 1010 | { 1011 | public: 1012 | SimpleSerialSimulationDataGenerator(); 1013 | ~SimpleSerialSimulationDataGenerator(); 1014 | void Initialize( U32 simulation_sample_rate, SimpleSerialAnalyzerSettings* 1015 | settings ); 1016 | U32 GenerateSimulationData( U64 newest_sample_requested, U32 sample_rate, 1017 | SimulationChannelDescriptor** simulation_channel ); 1018 | protected: 1019 | SimpleSerialAnalyzerSettings* mSettings; 1020 | U32 mSimulationSampleRateHz; 1021 | SimulationChannelDescriptor mSerialSimulationData; 1022 | }; 1023 | #endif //SIMPLESERIAL_SIMULATION_DATA_GENERATOR 1024 | ``` 1025 | 1026 | The key to the SimulationDataGenerator is the class ```SimulationChannelDescriptor```. You will need one of these for every channel you will be simulated (serial, for example, only needs to simulate on one channel). When your ```GenerateSimulationData``` function is called, your job will be to generate additional simulated data, up to the amount requested. When complete, you provide the caller with a pointer to an array of your ```SimulationChannelDescriptor``` objects. 1027 | 1028 | ## {YourName}SimulationDataGenerator.cpp 1029 | 1030 | ### Constructor/Destructor 1031 | 1032 | You may or may not need anything in your constructor or destructor. For now at least, leave them 1033 | empty. At the time we’re constructed, we really have no idea what the settings are or anything else, so there’s not much we can do at this point. 1034 | 1035 | ### ```{YourName}SimulationDataGenerator::Initialize()``` 1036 | 1037 | This function provides you with the state of things as they are going to be when we start simulating. 1038 | We’ll need to save this information. 1039 | 1040 | First, save ```simulation_sample_rate``` and ```settings``` to member variables. Notice that we now have a 1041 | pointer to our ```AnalyzerSettings``` - derived class. This is good, now we know what all the settings will be for our simulation – which channel(s) it will be on, as well as any other settings we might need – like if the signal is inverted, etc. 1042 | 1043 | Next, we’ll want to initialize the state of our ```SimulationChannelDescriptor``` objects – we need to set what channel it’s for, the sample rate, and the initial bit state (high or low). 1044 | 1045 | At this point we’ll need to take a step back and discuss some key concepts. 1046 | 1047 | #### ```BitState``` 1048 | 1049 | ```BitState``` is a type used often in the SDK. It can be either ```BIT_LOW``` or BIT_HIGH, and represents a channel’s logic state. 1050 | 1051 | #### Sample Rate (samples per second) 1052 | 1053 | Sample Rate refers to how many samples per second the data is. Typically it refers to how fast we’re collecting data, but for simulation, it refers to how fast we’re generating sample data. 1054 | 1055 | #### Sample Number 1056 | 1057 | This is the absolute sample number, starting at sample 0. When a data collection starts, the first sample collected is Sample Number 0. The next sample collected is Sample Number 1, etc. This is the same in simulation. The first sample we’ll provide is Sample Number 0, and so on. 1058 | 1059 | ### ```SimulationChannelDescriptor``` 1060 | 1061 | We need this object to describe a single channel of data, and what its waveform looks like. We do this in a very simple way: 1062 | - We provide the initial state of the channel (BIT_LOW, or BIT_HIGH) 1063 | - We move forward some number of samples, and then toggle the channel. 1064 | - We repeatedly do this 1065 | 1066 | The initial bit state of the channel never changes. The state (high or low) of a particular sample number can be determined by knowing how many times it has toggled up to that point (an even or odd number of times). Put another way: 1067 | 1068 | - In the very beginning, we specify the initial state (BIT_LOW or BIT_HIGH). This is the state of Sample Number 0. 1069 | - Then, we move forward (advance) some number of samples. 20 samples, for example. 1070 | - Then, we toggle the channel (low becomes high, high becomes low). 1071 | - Then we move forward (advance) some more. Maybe 100 samples this time. 1072 | - Then we toggle again. 1073 | - Then we move forward again, and then we toggle again, etc. 1074 | 1075 | Let’s explore the functions used to do this: 1076 | 1077 | #### ```Advance()``` 1078 | 1079 | As you might guess, this is how we move forward in our simulated waveform. Internally, the object 1080 | keeps track of what its Sample Number is. The Sample Number starts at 0. After calling *Advance( 10 )* x 3 times, the Sample Number will be 30. 1081 | 1082 | #### ```Transition()``` 1083 | 1084 | This toggles the channel. ```BIT_LOW``` becomes ```BIT_HIGH``` , ```BIT_HIGH``` becomes ```BIT_LOW```. The current 1085 | Sample Number will become the new ```BitState``` (BIT_LOW or BIT_HIGH), and all samples after that will also be the new ```BitState``` , until we toggle again. 1086 | 1087 | #### ```TransitionIfNeeded()``` 1088 | 1089 | Often we don’t want to keep track of the current ```BitState``` , which toggles every time we call ```Transition```. 1090 | ```TransitionIfNeeded``` checks the current ```BitState``` , and only transitions if the current ```BitState``` doesn’t match the one we provide. In other words “Change to this ```bit_state``` , if we’re not already”. 1091 | 1092 | #### ```GetCurrentBitState()``` 1093 | 1094 | This function lets you directly ask what the current ```BitState``` is. 1095 | 1096 | #### ```GetCurrentSampleNumber()``` 1097 | 1098 | This function lets you ask what the current ```SampleNumber``` is. 1099 | 1100 | #### ```ClockGenerator``` 1101 | 1102 | A common issue with converting exact timing values into numbers-of-samples, is that you lose some precision. This isn’t always a problem, but it’s nice to have a way to keep track of how much error is building up, and then, just at the right times, add an extra sample in so that on average, the timing is exact. 1103 | 1104 | ```ClockGenerator``` is a class provided in ```AnalyzerHelpers.h``` which will let you enter time values, rather than numbers-of-samples. For example, instead of figuring out how many samples are in 500ns, you can just use ```ClockGenerator``` to both figure it out and manage the error, so that on average, your timing is perfect. 1105 | 1106 | Initially we created ```ClockGenerator``` to create clock-like signals, but now you can use and time value, any time. Here’s how: 1107 | 1108 | #### ```Init( double target_frequency, U32 sample_rate_hz );``` 1109 | 1110 | You’ll need to call this before using the class. For ```sample_rate_hz``` , enter the sample rate we’ll be 1111 | generating data at. For ```target_frequency``` , enter the frequency (in hz) you will most commonly be using. For example, the bit rate of a SPI clock, etc. 1112 | 1113 | #### ```AdvanceByHalfPeriod( double multiple = 1.0 );``` 1114 | 1115 | This function returns how many samples are needed to move forward by one half of the period (for 1116 | example, the low time for a perfect square wave). You can also enter a multiple. For example, to get the number of samples to move forward for a full period, enter 2.0. 1117 | 1118 | #### ```AdvanceByTimeS( double time_s );``` 1119 | 1120 | This functions provides number of samples needed to advance by the arbitrary time, ```time_s```. Note that this is in seconds, so enter 1E-6 for for one microsecond, etc. 1121 | 1122 | Note that the number of samples for a specific time period may change slightly every once in a while. 1123 | This is so that on average, timing will be exact. 1124 | 1125 | You may want to have a ```ClockGenerator``` as a member of you class. This makes it easy to use from any helper functions you might create. 1126 | 1127 | ### ```{YourName}SimulationDataGenerator::Initialize()``` 1128 | 1129 | Let’s take another look at the ```Initialize``` function, now that we have an idea what’s going on. This 1130 | example is from ```SimpleSerialSimulationDataGenerator.cpp```. 1131 | 1132 | ```c++ 1133 | void SimpleSerialSimulationDataGenerator::Initialize( U32 simulation_sample_rate, 1134 | SimpleSerialAnalyzerSettings* settings ) 1135 | { 1136 | mSimulationSampleRateHz = simulation_sample_rate; 1137 | mSettings = settings; 1138 | mSerialSimulationData.SetChannel( mSettings->mInputChannel ); 1139 | mSerialSimulationData.SetSampleRate( simulation_sample_rate ); 1140 | mSerialSimulationData.SetInitialBitState( BIT_HIGH ); 1141 | } 1142 | ``` 1143 | 1144 | ### ```{YourName}SimulationDataGenerator::GenerateSimulationData()``` 1145 | 1146 | This function is repeatedly called to request more simulated data. When it’s called, just keep going 1147 | where you left off. In addition, you can generate more data that requested, to make things easy -- that way you don’t have to stop half way in the middle of something and try to pick it back up later exactly where you left off. 1148 | 1149 | When we leave the function, our Sample Number – in our ```SimulationChannelDescriptor``` object(s) must be equal to or larger than ```largest_sample_requested```. Actually, this number needs to first be adjusted (for technical reasons related to future compatibility). Use the helper function 1150 | ```AdjustSimulationTargetSample``` to do this, as we’ll see in a moment. 1151 | 1152 | The parameter ```simulation_channels``` is to provide the caller with a pointer to an array of your 1153 | ```SimulationChannelDescriptor``` objects. We’ll set this pointer at the end of the function. The return value is the number of elements in the array – the number of channels. 1154 | 1155 | The primary task of the function is to generate the simulation data, which we typically do in a loop – checking until we have generated enough data. A clean way of doing this is to generate a complete piece (possibly a full transaction) of your protocol in a helper function. Then just repeatedly call this function until enough data has been generated. You can also add spacing between the elements of your protocol as you like. 1156 | 1157 | Here is an example from ```SimpleSerialSimulationDataGenerator.cpp```. We’re going to be outputting chars from a string, which we initialized in our constructor as shown. 1158 | 1159 | ```c++ 1160 | SimpleSerialSimulationDataGenerator::SimpleSerialSimulationDataGenerator() 1161 | : mSerialText( "My first analyzer, woo hoo!" ), 1162 | mStringIndex( 0 ) 1163 | { 1164 | } 1165 | U32 SimpleSerialSimulationDataGenerator::GenerateSimulationData( U64 1166 | largest_sample_requested, U32 sample_rate, SimulationChannelDescriptor** 1167 | simulation_channel ) 1168 | { 1169 | U64 adjusted_largest_sample_requested = 1170 | AnalyzerHelpers::AdjustSimulationTargetSample( largest_sample_requested, sample_rate, 1171 | mSimulationSampleRateHz ); 1172 | while( mSerialSimulationData.GetCurrentSampleNumber() < 1173 | adjusted_largest_sample_requested ) 1174 | { 1175 | CreateSerialByte(); 1176 | } 1177 | *simulation_channel = &mSerialSimulationData; 1178 | return 1; 1179 | } 1180 | void SimpleSerialSimulationDataGenerator::CreateSerialByte() 1181 | { 1182 | U32 samples_per_bit = mSimulationSampleRateHz / mSettings->mBitRate; 1183 | U8 byte = mSerialText[ mStringIndex ]; 1184 | mStringIndex++; 1185 | if( mStringIndex == mSerialText.size() ) 1186 | mStringIndex = 0; 1187 | //we're currently high 1188 | //let's move forward a little 1189 | mSerialSimulationData.Advance( samples_per_bit * 10 ); 1190 | mSerialSimulationData.Transition(); //low-going edge for start bit 1191 | mSerialSimulationData.Advance( samples_per_bit ); //add start bit time 1192 | U8 mask = 0x1 << 7; 1193 | for( U32 i=0; i<8; i++ ) 1194 | { 1195 | if( ( byte & mask ) != 0 ) 1196 | mSerialSimulationData.TransitionIfNeeded( BIT_HIGH ); 1197 | else 1198 | mSerialSimulationData.TransitionIfNeeded( BIT_LOW ); 1199 | mSerialSimulationData.Advance( samples_per_bit ); 1200 | mask = mask >> 1; 1201 | } 1202 | mSerialSimulationData.TransitionIfNeeded( BIT_HIGH ); //we need to end high 1203 | //lets pad the end a bit for the stop bit: 1204 | mSerialSimulationData.Advance( samples_per_bit ); 1205 | } 1206 | ``` 1207 | 1208 | There are a few things we could do to clean this up. First, we could save the ```samples_per_bit``` as a 1209 | member variable, and compute it only once, in the ```Initialize``` function. If we wanted to be more accurate, we could use the ```ClockGenerator``` class to pre-populate an array of ```samples_per_bit``` values, so on average the timing would be perfect. We would use this as a lookup each time we ```Advance``` one bit. 1210 | Another thing we could do is use the ```DataExtractor``` class to take care of the bit masking/testing. 1211 | However, in our simple example what we have works well enough, and it has the advantage of being a bit more transparent. 1212 | 1213 | ## Simulating Multiple Channels 1214 | 1215 | Simulating multiple channels requires multiple ```SimulationChannelDescriptors```, and they must be in an array. The best way to this is to use the helper class, ```SimulationChannelDescriptorGroup```. 1216 | 1217 | Here is an example of I2C (2 channels)—these are the the member variable definitions in 1218 | *I2cSimulationDataGenerator.h* : 1219 | 1220 | ```c++ 1221 | SimulationChannelDescriptorGroup mI2cSimulationChannels; 1222 | SimulationChannelDescriptor* mSda; 1223 | SimulationChannelDescriptor* mScl; 1224 | ``` 1225 | Then, in the ```Initialize``` function: 1226 | 1227 | ```c++ 1228 | mSda = mI2cSimulationChannels.Add( settings->mSdaChannel, mSimulationSampleRateHz, 1229 | BIT_HIGH ); 1230 | mScl = mI2cSimulationChannels.Add( settings->mSclChannel, mSimulationSampleRateHz, 1231 | BIT_HIGH ); 1232 | ``` 1233 | And to provide the array to the caller of ```GenerateSimulationData``` : 1234 | 1235 | ```c++ 1236 | *simulation_channels = mI2cSimulationChannels.GetArray(); 1237 | return mI2cSimulationChannels.GetCount(); 1238 | ``` 1239 | You can use each ```SimulationChannelDescriptor``` object pointer separately, calling ```Advance```, ```Transition```, etc. on each one, or you can manipulate them as a group, using the ```AdvanceAll``` method of the ```SimulationChannelDescriptorGroup``` object. 1240 | 1241 | ```c++ 1242 | void AdvanceAll( U32 num_samples_to_advance ); 1243 | ``` 1244 | Before returning from ```GenerateSimulationData``` , be sure that the Sample Number of ```all``` of your 1245 | ```SimulationChannelDescriptor``` objects exceed ```adjusted_largest_sample_requested```. 1246 | 1247 | ### Examples of generating simulation data 1248 | 1249 | #### ```SerialSimulationDataGenerator::CreateSerialByte()``` 1250 | 1251 | ```c++ 1252 | void SerialSimulationDataGenerator::CreateSerialByte( U64 value ) 1253 | { 1254 | // assume we start high 1255 | mSerialSimulationData.Transition(); // low-going edge for start bit 1256 | mSerialSimulationData.Advance( mClockGenerator.AdvanceByHalfPeriod() ); // add 1257 | start bit time if( mSettings->mInverted == true ) value = ~value; 1258 | U32 num_bits = mSettings->mBitsPerTransfer; 1259 | BitExtractor bit_extractor( value, mSettings->mShiftOrder, num_bits ); 1260 | for( U32 i = 0; i < num_bits; i++ ) 1261 | { 1262 | mSerialSimulationData.TransitionIfNeeded( bit_extractor.GetNextBit() ); 1263 | mSerialSimulationData.Advance( mClockGenerator.AdvanceByHalfPeriod() ); 1264 | } 1265 | if( mSettings->mParity == AnalyzerEnums::Even ) 1266 | { 1267 | if( AnalyzerHelpers::IsEven( AnalyzerHelpers::GetOnesCount( value ) ) == true ) 1268 | mSerialSimulationData.TransitionIfNeeded( mBitLow ); // we want to 1269 | add a zero bit else mSerialSimulationData.TransitionIfNeeded( mBitHigh ); // we want to 1270 | add a one bit mSerialSimulationData.Advance( mClockGenerator.AdvanceByHalfPeriod() ); 1271 | } 1272 | else if( mSettings->mParity == AnalyzerEnums::Odd ) 1273 | { 1274 | if( AnalyzerHelpers::IsOdd( AnalyzerHelpers::GetOnesCount( value ) ) == true ) 1275 | mSerialSimulationData.TransitionIfNeeded( mBitLow ); // we want to 1276 | add a zero bit else mSerialSimulationData.TransitionIfNeeded( mBitHigh ); 1277 | mSerialSimulationData.Advance( mClockGenerator.AdvanceByHalfPeriod() ); 1278 | } 1279 | mSerialSimulationData.TransitionIfNeeded( mBitHigh ); // we need to end high 1280 | // lets pad the end a bit for the stop bit: 1281 | mSerialSimulationData.Advance( mClockGenerator.AdvanceByHalfPeriod( mSettings - > mStopBits ) ); 1282 | } 1283 | ``` 1284 | 1285 | #### ```I2cSimulationDataGenerator::CreateBit()``` 1286 | 1287 | ```c++ 1288 | void I2cSimulationDataGenerator::CreateBit( BitState bit_state ) 1289 | { 1290 | if( mScl->GetCurrentBitState() != BIT_LOW ) 1291 | AnalyzerHelpers::Assert( "CreateBit expects to be entered with scl low" ); 1292 | mI2cSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 0.5 ) ); 1293 | mSda->TransitionIfNeeded( bit_state ); 1294 | mI2cSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 0.5 ) ); 1295 | mScl->Transition(); // posedge 1296 | mI2cSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 1.0 ) ); 1297 | mScl->Transition(); // negedge 1298 | } 1299 | void I2cSimulationDataGenerator::CreateI2cByte( U8 data, 1300 | I2cResponse reply ) void I2cSimulationDataGenerator::CreateI2cByte( U8 data, 1301 | I2cResponse reply ) 1302 | { 1303 | if( mScl->GetCurrentBitState() == BIT_HIGH ) 1304 | { 1305 | mI2cSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 1.0 ) ); 1306 | mScl->Transition(); 1307 | mI2cSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 1.0 ) ); 1308 | } 1309 | BitExtractor bit_extractor( data, AnalyzerEnums::MsbFirst, 8 ); 1310 | for( U32 i = 0; i < 8; i++ ) 1311 | { 1312 | CreateBit( bit_extractor.GetNextBit() ); 1313 | } 1314 | if( reply == I2C_ACK ) 1315 | CreateBit( BIT_LOW ); 1316 | else 1317 | CreateBit( BIT_HIGH ); 1318 | mI2cSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 4.0 ) ); 1319 | } 1320 | ``` 1321 | 1322 | #### ```I2cSimulationDataGenerator::CreateI2cTransaction()``` 1323 | 1324 | ```c++ 1325 | void I2cSimulationDataGenerator::CreateI2cTransaction( U8 address, I2cDirection direction, U8 data ) 1326 | { 1327 | U8 command = address << 1; 1328 | if( direction == I2C_READ ) 1329 | command |= 0x1; 1330 | CreateStart(); 1331 | CreateI2cByte( command, I2C_ACK ); 1332 | CreateI2cByte( data, I2C_ACK ); 1333 | CreateI2cByte( data, I2C_NAK ); 1334 | CreateStop(); 1335 | } 1336 | U32 I2cSimulationDataGenerator::GenerateSimulationData( U64 largest_sample_requested, U32 sample_rate, 1337 | SimulationChannelDescriptor** simulation_channels ) U32 1338 | I2cSimulationDataGenerator::GenerateSimulationData( U64 largest_sample_requested, U32 sample_rate, 1339 | SimulationChannelDescriptor** simulation_channels ) 1340 | { 1341 | U64 adjusted_largest_sample_requested = 1342 | AnalyzerHelpers::AdjustSimulationTargetSample( largest_sample_requested, sample_rate, mSimulationSampleRateHz ); 1343 | while( mScl->GetCurrentSampleNumber() < adjusted_largest_sample_requested ) 1344 | { 1345 | CreateI2cTransaction( 0xA0, I2C_READ, mValue++ ); 1346 | mI2cSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 10 .0 ) ); // insert 10 bit-periods of idle 1347 | } 1348 | *simulation_channels = mI2cSimulationChannels.GetArray(); 1349 | return mI2cSimulationChannels.GetCount(); 1350 | } 1351 | ``` 1352 | 1353 | #### ```SpiSimulationDataGenerator::OutputWord_CPHA1()``` 1354 | 1355 | ```c++ 1356 | void SpiSimulationDataGenerator::OutputWord_CPHA1( U64 mosi_data, U64 miso_data ) 1357 | { 1358 | BitExtractor mosi_bits( mosi_data, mSettings->mShiftOrder, mSettings - > mBitsPerTransfer ); 1359 | BitExtractor miso_bits( miso_data, mSettings->mShiftOrder, mSettings - > mBitsPerTransfer ); 1360 | U32 count = mSettings->mBitsPerTransfer; 1361 | for( U32 i = 0; i < count; i++ ) 1362 | { 1363 | mClock->Transition(); // data invalid 1364 | mMosi->TransitionIfNeeded( mosi_bits.GetNextBit() ); 1365 | mMiso->TransitionIfNeeded( miso_bits.GetNextBit() ); 1366 | mSpiSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( .5 ) ); 1367 | mClock->Transition(); // data valid 1368 | mSpiSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( .5 ) ); 1369 | } 1370 | mMosi->TransitionIfNeeded( BIT_LOW ); 1371 | mMiso->TransitionIfNeeded( BIT_LOW ); 1372 | mSpiSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 2.0 ) ); 1373 | } 1374 | ``` 1375 | 1376 | #### ```SpiSimulationDataGenerator::CreateSpiTransaction()``` 1377 | 1378 | ```c++ 1379 | void SpiSimulationDataGenerator::CreateSpiTransaction() 1380 | { 1381 | if( mEnable != NULL ) 1382 | mEnable->Transition(); 1383 | mSpiSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 2.0 ) ); 1384 | if( mSettings->mDataValidEdge == AnalyzerEnums::LeadingEdge ) 1385 | { 1386 | OutputWord_CPHA0( mValue, mValue + 1 ); 1387 | mValue++; 1388 | OutputWord_CPHA0( mValue, mValue + 1 ); 1389 | mValue++; 1390 | OutputWord_CPHA0( mValue, mValue + 1 ); 1391 | mValue++; 1392 | if( mEnable != NULL ) 1393 | mEnable->Transition(); 1394 | OutputWord_CPHA0( mValue, mValue + 1 ); 1395 | mValue++; 1396 | } 1397 | else 1398 | { 1399 | OutputWord_CPHA1( mValue, mValue + 1 ); 1400 | mValue++; 1401 | OutputWord_CPHA1( mValue, mValue + 1 ); 1402 | mValue++; 1403 | OutputWord_CPHA1( mValue, mValue + 1 ); 1404 | mValue++; 1405 | if( mEnable != NULL ) 1406 | mEnable->Transition(); 1407 | OutputWord_CPHA1( mValue, mValue + 1 ); 1408 | mValue++; 1409 | } 1410 | } 1411 | ``` 1412 | 1413 | #### ```SpiSimulationDataGenerator::GenerateSimulationData()``` 1414 | 1415 | ```c++ 1416 | U32 SpiSimulationDataGenerator::GenerateSimulationData( U64 largest_sample_requested, U32 sample_rate, SimulationChannelDescriptor** simulation_channels ) 1417 | { 1418 | U64 adjusted_largest_sample_requested = 1419 | AnalyzerHelpers::AdjustSimulationTargetSample( largest_sample_requested, sample_rate, mSimulationSampleRateHz ); 1420 | while( mClock->GetCurrentSampleNumber() < adjusted_largest_sample_requested ) 1421 | { 1422 | CreateSpiTransaction(); 1423 | mSpiSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 10.0 ) ); // insert 10 bit-periods of idle 1424 | } 1425 | *simulation_channels = mSpiSimulationChannels.GetArray(); 1426 | return mSpiSimulationChannels.GetCount(); 1427 | } 1428 | ``` --------------------------------------------------------------------------------