├── .gitignore ├── docs ├── vanex.png ├── Logic_printscreen.png └── Analyzer_API.md ├── SampleCaptures ├── VAN_knownpacket_0x8c4_8a_21_40.sal ├── VAN_knownpacket_0x8c4_8a_21_40.logicdata ├── VAN_knownpacket_0x524_12356789ABCDE.logicdata └── Radio_and_screen_on_bench_during_boot.logicdata ├── CMakeLists.txt ├── src ├── VanSimulationDataGenerator.h ├── VanAnalyzerSettings.h ├── VanAnalyzerResults.h ├── VanSimulationDataGenerator.cpp ├── VanAnalyzer.h ├── VanAnalyzerSettings.cpp ├── VANAnalyzerResults.cpp └── VANAnalyzer.cpp ├── .clang-format ├── .github └── workflows │ └── build.yml ├── cmake └── ExternalAnalyzerSDK.cmake ├── rename_analyzer.py └── readme.md /.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /docs/vanex.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/morcibacsi/VanAnalyzer/HEAD/docs/vanex.png -------------------------------------------------------------------------------- /docs/Logic_printscreen.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/morcibacsi/VanAnalyzer/HEAD/docs/Logic_printscreen.png -------------------------------------------------------------------------------- /SampleCaptures/VAN_knownpacket_0x8c4_8a_21_40.sal: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/morcibacsi/VanAnalyzer/HEAD/SampleCaptures/VAN_knownpacket_0x8c4_8a_21_40.sal -------------------------------------------------------------------------------- /SampleCaptures/VAN_knownpacket_0x8c4_8a_21_40.logicdata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/morcibacsi/VanAnalyzer/HEAD/SampleCaptures/VAN_knownpacket_0x8c4_8a_21_40.logicdata -------------------------------------------------------------------------------- /SampleCaptures/VAN_knownpacket_0x524_12356789ABCDE.logicdata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/morcibacsi/VanAnalyzer/HEAD/SampleCaptures/VAN_knownpacket_0x524_12356789ABCDE.logicdata -------------------------------------------------------------------------------- /SampleCaptures/Radio_and_screen_on_bench_during_boot.logicdata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/morcibacsi/VanAnalyzer/HEAD/SampleCaptures/Radio_and_screen_on_bench_during_boot.logicdata -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required (VERSION 3.13) 2 | 3 | project(VanAnalyzer) 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/VANAnalyzer.cpp 17 | src/VANAnalyzerResults.cpp 18 | src/VanAnalyzerSettings.cpp 19 | src/VanSimulationDataGenerator.cpp 20 | src/VanAnalyzer.h 21 | src/VanAnalyzerResults.h 22 | src/VanAnalyzerSettings.h 23 | src/VanSimulationDataGenerator.h 24 | ) 25 | 26 | add_analyzer_plugin(${PROJECT_NAME} SOURCES ${SOURCES}) 27 | -------------------------------------------------------------------------------- /src/VanSimulationDataGenerator.h: -------------------------------------------------------------------------------- 1 | #ifndef VAN_SIMULATION_DATA_GENERATOR 2 | #define VAN_SIMULATION_DATA_GENERATOR 3 | 4 | #include 5 | #include 6 | class VanAnalyzerSettings; 7 | 8 | class VanSimulationDataGenerator 9 | { 10 | public: 11 | VanSimulationDataGenerator(); 12 | ~VanSimulationDataGenerator(); 13 | 14 | void Initialize( U32 simulation_sample_rate, VanAnalyzerSettings* settings ); 15 | U32 GenerateSimulationData( U64 newest_sample_requested, U32 sample_rate, SimulationChannelDescriptor** simulation_channel ); 16 | 17 | protected: 18 | VanAnalyzerSettings* mSettings; 19 | U32 mSimulationSampleRateHz; 20 | 21 | protected: 22 | void CreateSerialByte(); 23 | std::string mSerialText; 24 | U32 mStringIndex; 25 | 26 | SimulationChannelDescriptor mSerialSimulationData; 27 | 28 | }; 29 | #endif //VAN_SIMULATION_DATA_GENERATOR -------------------------------------------------------------------------------- /src/VanAnalyzerSettings.h: -------------------------------------------------------------------------------- 1 | #ifndef VAN_ANALYZER_SETTINGS 2 | #define VAN_ANALYZER_SETTINGS 3 | 4 | #include 5 | #include 6 | 7 | class VanAnalyzerSettings : public AnalyzerSettings 8 | { 9 | public: 10 | VanAnalyzerSettings(); 11 | virtual ~VanAnalyzerSettings(); 12 | 13 | virtual bool SetSettingsFromInterfaces(); 14 | void UpdateInterfacesFromSettings(); 15 | virtual void LoadSettings( const char* settings ); 16 | virtual const char* SaveSettings(); 17 | 18 | Channel mInputChannel; 19 | U32 mBitRate; 20 | bool mInverted; 21 | 22 | BitState Recessive(); 23 | BitState Dominant(); 24 | 25 | 26 | protected: 27 | std::auto_ptr< AnalyzerSettingInterfaceChannel > mInputChannelInterface; 28 | std::auto_ptr< AnalyzerSettingInterfaceInteger > mBitRateInterface; 29 | std::auto_ptr< AnalyzerSettingInterfaceBool > mVanChannelInvertedInterface; 30 | }; 31 | 32 | #endif //VAN_ANALYZER_SETTINGS 33 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /src/VanAnalyzerResults.h: -------------------------------------------------------------------------------- 1 | #ifndef VAN_ANALYZER_RESULTS 2 | #define VAN_ANALYZER_RESULTS 3 | 4 | #include 5 | 6 | enum VanFrameType { StartOfFrame, IdentifierField, CommandField, DataField, FCSField, EndOfData, AckField, EndOfFrame, VanError }; 7 | 8 | class VanAnalyzer; 9 | class VanAnalyzerSettings; 10 | 11 | class VanAnalyzerResults : public AnalyzerResults 12 | { 13 | public: 14 | VanAnalyzerResults( VanAnalyzer* analyzer, VanAnalyzerSettings* settings ); 15 | virtual ~VanAnalyzerResults(); 16 | 17 | virtual void GenerateBubbleText( U64 frame_index, Channel& channel, DisplayBase display_base ); 18 | virtual void GenerateExportFile( const char* file, DisplayBase display_base, U32 export_type_user_id ); 19 | 20 | virtual void GenerateFrameTabularText(U64 frame_index, DisplayBase display_base ); 21 | virtual void GeneratePacketTabularText( U64 packet_id, DisplayBase display_base ); 22 | virtual void GenerateTransactionTabularText( U64 transaction_id, DisplayBase display_base ); 23 | 24 | protected: //functions 25 | 26 | protected: //vars 27 | VanAnalyzerSettings* mSettings; 28 | VanAnalyzer* mAnalyzer; 29 | }; 30 | 31 | #endif //VAN_ANALYZER_RESULTS 32 | -------------------------------------------------------------------------------- /.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 -DCMAKE_BUILD_TYPE=Release 32 | cmake --build ${{github.workspace}}/build 33 | - name: Upload MacOS build 34 | uses: actions/upload-artifact@v2 35 | with: 36 | name: macos 37 | path: ${{github.workspace}}/build/Analyzers/*.so 38 | linux: 39 | runs-on: ubuntu-latest 40 | steps: 41 | - uses: actions/checkout@v2 42 | - name: Build 43 | run: | 44 | cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=Release 45 | cmake --build ${{github.workspace}}/build 46 | - name: Upload Linux build 47 | uses: actions/upload-artifact@v2 48 | with: 49 | name: linux 50 | path: ${{github.workspace}}/build/Analyzers/*.so 51 | publish: 52 | needs: [windows, macos, linux] 53 | runs-on: ubuntu-latest 54 | steps: 55 | - name: download individual builds 56 | uses: actions/download-artifact@v2 57 | with: 58 | path: ${{github.workspace}}/artifacts 59 | - name: zip 60 | run: | 61 | cd ${{github.workspace}}/artifacts 62 | zip -r ${{github.workspace}}/analyzer.zip . 63 | - uses: actions/upload-artifact@v2 64 | with: 65 | name: all-platforms 66 | path: ${{github.workspace}}/artifacts/** 67 | - name: create release 68 | uses: softprops/action-gh-release@v1 69 | if: startsWith(github.ref, 'refs/tags/') 70 | with: 71 | files: ${{github.workspace}}/analyzer.zip -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /src/VanSimulationDataGenerator.cpp: -------------------------------------------------------------------------------- 1 | #include "VanSimulationDataGenerator.h" 2 | #include "VanAnalyzerSettings.h" 3 | 4 | #include 5 | 6 | VanSimulationDataGenerator::VanSimulationDataGenerator() 7 | : mSerialText( "My first analyzer, woo hoo!" ), 8 | mStringIndex( 0 ) 9 | { 10 | } 11 | 12 | VanSimulationDataGenerator::~VanSimulationDataGenerator() 13 | { 14 | } 15 | 16 | void VanSimulationDataGenerator::Initialize( U32 simulation_sample_rate, VanAnalyzerSettings* settings ) 17 | { 18 | mSimulationSampleRateHz = simulation_sample_rate; 19 | mSettings = settings; 20 | 21 | mSerialSimulationData.SetChannel( mSettings->mInputChannel ); 22 | mSerialSimulationData.SetSampleRate( simulation_sample_rate ); 23 | mSerialSimulationData.SetInitialBitState( BIT_HIGH ); 24 | } 25 | 26 | U32 VanSimulationDataGenerator::GenerateSimulationData( U64 largest_sample_requested, U32 sample_rate, SimulationChannelDescriptor** simulation_channel ) 27 | { 28 | U64 adjusted_largest_sample_requested = AnalyzerHelpers::AdjustSimulationTargetSample( largest_sample_requested, sample_rate, mSimulationSampleRateHz ); 29 | 30 | while( mSerialSimulationData.GetCurrentSampleNumber() < adjusted_largest_sample_requested ) 31 | { 32 | CreateSerialByte(); 33 | } 34 | 35 | *simulation_channel = &mSerialSimulationData; 36 | return 1; 37 | } 38 | 39 | void VanSimulationDataGenerator::CreateSerialByte() 40 | { 41 | U32 samples_per_bit = mSimulationSampleRateHz / mSettings->mBitRate; 42 | 43 | U8 byte = mSerialText[ mStringIndex ]; 44 | mStringIndex++; 45 | if( mStringIndex == mSerialText.size() ) 46 | mStringIndex = 0; 47 | 48 | //we're currenty high 49 | //let's move forward a little 50 | mSerialSimulationData.Advance( samples_per_bit * 10 ); 51 | 52 | mSerialSimulationData.Transition(); //low-going edge for start bit 53 | mSerialSimulationData.Advance( samples_per_bit ); //add start bit time 54 | 55 | U8 mask = 0x1 << 7; 56 | for( U32 i=0; i<8; i++ ) 57 | { 58 | if( ( byte & mask ) != 0 ) 59 | mSerialSimulationData.TransitionIfNeeded( BIT_HIGH ); 60 | else 61 | mSerialSimulationData.TransitionIfNeeded( BIT_LOW ); 62 | 63 | mSerialSimulationData.Advance( samples_per_bit ); 64 | mask = mask >> 1; 65 | } 66 | 67 | mSerialSimulationData.TransitionIfNeeded( BIT_HIGH ); //we need to end high 68 | 69 | //lets pad the end a bit for the stop bit: 70 | mSerialSimulationData.Advance( samples_per_bit ); 71 | } 72 | -------------------------------------------------------------------------------- /src/VanAnalyzer.h: -------------------------------------------------------------------------------- 1 | #ifndef VAN_ANALYZER_H 2 | #define VAN_ANALYZER_H 3 | 4 | #include 5 | #include "VanAnalyzerResults.h" 6 | #include "VanSimulationDataGenerator.h" 7 | 8 | class VanAnalyzerSettings; 9 | class ANALYZER_EXPORT VanAnalyzer : public Analyzer2 10 | { 11 | private: 12 | char* VanFrameTypeForDisplay[ 9 ] = { "SOF", "IDENT", "COM", "DATA", "FCS", "EOD", "ACK", "EOF", "ERROR" }; 13 | 14 | public: 15 | VanAnalyzer(); 16 | virtual ~VanAnalyzer(); 17 | 18 | virtual void SetupResults(); 19 | virtual void WorkerThread(); 20 | 21 | virtual U32 GenerateSimulationData( U64 newest_sample_requested, U32 sample_rate, SimulationChannelDescriptor** simulation_channels ); 22 | virtual U32 GetMinimumSampleRateHz(); 23 | 24 | virtual const char* GetAnalyzerName() const; 25 | virtual bool NeedsRerun(); 26 | 27 | protected: // vars 28 | std::auto_ptr mSettings; 29 | std::auto_ptr mResults; 30 | AnalyzerChannelData* mSerial; 31 | 32 | U64 mBitPositions[ 6 ] = { 0 }; // used to collect the bit positions so we can draw a good looking IDENT and COM field 33 | U8 mBitPos = 0; // indexer for the mBitPositions array 34 | 35 | U64 mStartOfFieldSampleNumber = 0; 36 | U64 mStartOfIdenFieldSampleNumber = 0; 37 | U64 mPreviousNonManchesterBitPosition = 0; 38 | 39 | U8 mbitCount = 0; // used to determine if a bit is Manchester bit 40 | U8 mbyteCount = 0; // used to determine which part of the message we are processing 41 | U8 mByte = 0; // we are building the VAN byte in this variable bit by bit 42 | U8 mask = 1 << 7; 43 | 44 | bool mFrameStart = true; 45 | bool mEofFound = false; 46 | 47 | VanSimulationDataGenerator mSimulationDataGenerator; 48 | bool mSimulationInitilized; 49 | 50 | void WaitFor8RecessiveBits(); 51 | void AddFrame( const U64 startingPoint, const U64 endingPoint, const U32 data, const U32 type, const U32 indexOfData ); 52 | void ProcessBit( const BitState bitState, const U64 bitPosition ); 53 | 54 | void AddMarker( const U64 inSampleNumber, const AnalyzerResults::MarkerType inMarker ); 55 | 56 | // VAN analysis vars: 57 | U32 mSampleRateHz; 58 | U32 mSamplesPerBit; 59 | 60 | // VAN vars 61 | U32 mNumSamplesIn8Bits = 0; 62 | U16 mIdent = 0; 63 | U8 mCOM = 0; 64 | }; 65 | 66 | extern "C" ANALYZER_EXPORT const char* __cdecl GetAnalyzerName(); 67 | extern "C" ANALYZER_EXPORT Analyzer* __cdecl CreateAnalyzer(); 68 | extern "C" ANALYZER_EXPORT void __cdecl DestroyAnalyzer( Analyzer* analyzer ); 69 | 70 | #endif // VAN_ANALYZER_H 71 | -------------------------------------------------------------------------------- /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 inclide 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/VanAnalyzerSettings.cpp: -------------------------------------------------------------------------------- 1 | #include "VanAnalyzerSettings.h" 2 | #include 3 | 4 | 5 | VanAnalyzerSettings::VanAnalyzerSettings() 6 | : mInputChannel( UNDEFINED_CHANNEL ), 7 | mBitRate( 125000 ) 8 | { 9 | mInputChannelInterface.reset( new AnalyzerSettingInterfaceChannel() ); 10 | mInputChannelInterface->SetTitleAndTooltip( "VAN bus", "Standard VAN" ); 11 | mInputChannelInterface->SetChannel( mInputChannel ); 12 | 13 | mBitRateInterface.reset( new AnalyzerSettingInterfaceInteger() ); 14 | mBitRateInterface->SetTitleAndTooltip( "Bit Rate (Bits/s)", "Specify the bit rate in bits per second." ); 15 | mBitRateInterface->SetMax( 6000000 ); 16 | mBitRateInterface->SetMin( 1 ); 17 | mBitRateInterface->SetInteger( mBitRate ); 18 | 19 | mVanChannelInvertedInterface.reset(new AnalyzerSettingInterfaceBool()); 20 | mVanChannelInvertedInterface->SetTitleAndTooltip("Inverted (VAN High - DATA)", "Use this option when recording VAN High (DATA) directly"); 21 | mVanChannelInvertedInterface->SetValue(mInverted); 22 | 23 | AddInterface(mInputChannelInterface.get()); 24 | AddInterface(mBitRateInterface.get()); 25 | AddInterface(mVanChannelInvertedInterface.get()); 26 | 27 | AddExportOption( 0, "Export as text file" ); 28 | AddExportExtension( 0, "text", "txt" ); 29 | 30 | ClearChannels(); 31 | AddChannel( mInputChannel, "VAN", false ); 32 | } 33 | 34 | VanAnalyzerSettings::~VanAnalyzerSettings() 35 | { 36 | } 37 | 38 | bool VanAnalyzerSettings::SetSettingsFromInterfaces() 39 | { 40 | mInputChannel = mInputChannelInterface->GetChannel(); 41 | 42 | if (mInputChannel == UNDEFINED_CHANNEL) 43 | { 44 | SetErrorText("Please select a channel for the VAN interface"); 45 | return false; 46 | } 47 | 48 | mBitRate = mBitRateInterface->GetInteger(); 49 | mInverted = mVanChannelInvertedInterface->GetValue(); 50 | 51 | ClearChannels(); 52 | AddChannel( mInputChannel, "VAN", true ); 53 | 54 | return true; 55 | } 56 | 57 | void VanAnalyzerSettings::UpdateInterfacesFromSettings() 58 | { 59 | mInputChannelInterface->SetChannel( mInputChannel ); 60 | mBitRateInterface->SetInteger( mBitRate ); 61 | mVanChannelInvertedInterface->SetValue(mInverted); 62 | } 63 | 64 | void VanAnalyzerSettings::LoadSettings( const char* settings ) 65 | { 66 | SimpleArchive text_archive; 67 | text_archive.SetString( settings ); 68 | 69 | const char* name_string; //the first thing in the archive is the name of the protocol analyzer that the data belongs to. 70 | text_archive >> &name_string; 71 | if (strcmp(name_string, "SaleaeVANAnalyzer") != 0) 72 | AnalyzerHelpers::Assert("SaleaeVanAnalyzer: Provided with a settings string that doesn't belong to us;"); 73 | 74 | 75 | text_archive >> mInputChannel; 76 | text_archive >> mBitRate; 77 | text_archive >> mInverted; //SimpleArchive catches exception and returns false if it fails. 78 | 79 | ClearChannels(); 80 | AddChannel( mInputChannel, "VAN", true ); 81 | 82 | UpdateInterfacesFromSettings(); 83 | } 84 | 85 | const char* VanAnalyzerSettings::SaveSettings() 86 | { 87 | SimpleArchive text_archive; 88 | 89 | text_archive << "SaleaeVANAnalyzer"; 90 | text_archive << mInputChannel; 91 | text_archive << mBitRate; 92 | text_archive << mInverted; 93 | 94 | return SetReturnString( text_archive.GetString() ); 95 | } 96 | 97 | BitState VanAnalyzerSettings::Recessive() 98 | { 99 | if (mInverted) 100 | return BIT_LOW; 101 | return BIT_HIGH; 102 | } 103 | BitState VanAnalyzerSettings::Dominant() 104 | { 105 | if (mInverted) 106 | return BIT_HIGH; 107 | return BIT_LOW; 108 | } 109 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Vehicle Area Network (VAN bus) Analyzer for Saleae USB logic analyzer 2 | 3 | This plugin for [Saleae Logic][logic] allows you to analyze [VAN][van_network] bus packets found in cars made by PSA (Peugeot, Citroen) 4 | VAN bus is pretty similar to CAN bus. In the application the **●** are marking the places where the sample was taken and the **⨯** are marking the E-Manchester bits (those must be ignored when decoding the data). 5 | 6 | ![logic analyzer](https://github.com/morcibacsi/VanAnalyzer/raw/master/docs/Logic_printscreen.png) 7 | 8 | ## Exporting 9 | 10 | The analyzer exports to a simple text format with a timestamp, the channel and the bytes in hexadecimal. 11 | At the end of the packet the A stands for ACK required and N is for ACK not required. 12 | The two bytes before the A or N is the Frame Check Sequence (FCS). 13 | The byte after the identifier is the command byte. 14 | 15 | ``` 16 | 08.691351125000001 Ch:0: 5E4 C 20 1F 95 6A N 17 | 08.723351583333333 Ch:0: 8C4 C 8A 22 5A 81 5E A 18 | 08.736818458333332 Ch:0: 8D4 C 12 01 E8 2E A 19 | 08.799568666666666 Ch:0: 8C4 C 8A 21 40 3D 54 A 20 | 08.800854083333334 Ch:0: 4D4 E 85 0C 01 01 31 0E 3F 3F 3F 47 85 12 06 A 21 | 08.807504375000001 Ch:0: 554 E 81 D1 01 80 EE 02 00 04 FF FF A1 00 00 00 00 00 00 00 00 00 00 81 15 2E A 22 | 09.190060833333334 Ch:0: 5E4 C 20 1F 95 6A N 23 | 09.251457750000000 Ch:0: 8C4 C 8A 24 40 9B 32 A 24 | 09.252726958333334 Ch:0: 554 E 81 D1 01 80 EE 02 00 04 FF FF A1 00 00 00 00 00 00 00 00 00 00 81 15 2E A 25 | 09.686664166666667 Ch:0: 5E4 C 20 1F 95 6A N 26 | 09.806916458333333 Ch:0: 4D4 E 86 0C 01 01 31 0E 3F 3F 3F 47 86 55 E4 A 27 | ``` 28 | 29 | ## Protocol 30 | 31 | There is a pretty good description about the protocol on Graham Auld's page [here][graham]. I copied the key part here for a quick reference. 32 | 33 | ### Data Frames 34 | 35 | VAN data is broadcast on the bus in discreete frames of data encoded using E-Manchester that include an Identifier to allow recievers to filter the data they are interested in. Frame marking is made through the use of E-Manchester violations 36 | 37 | This coding of every 4 bits by 5 bits makes length information a little ambiguous unless you remark on the codin (CAN is even more of a pain through the use of data dependant bitstuffing to enable clock recovery). 38 | For this reason I like to refer to Time Slices at this level, a Time Slice (TS) is the time taken to transmit a dominant or recessive bit on the bus in real time. 39 | Hence 4 bits take 5TS to transmit due to the E-Manchester bit being appended. A 125kbps VAN bus results in 1TS=8uS. 40 | 41 | 42 | |Field Name | Length (TS) | Purpose | 43 | |------------|:-------------:|-------- | 44 | |Start of frame | 10 |Marks start of frame, provides edges for clock synchronisation always 0000111101 | 45 | |Identifier | 15 |Identifies the packet for recieve filtering, also provides priority in bus access arbitration, lower identifiers get higher priority bus access. 0x000 and 0xFFF are reserved | 46 | |Command | 5 |These four bits, Extenstion (EXT), Request Acknowledge (RAK), Read/Write(R/W) & Remote Tramsmission Request(RTR) provide instruction to recievers. EXT is reserved and should be 1 (recessive), RAK set to 0 means that no acknowledge should be provided, R/W marks the frame as a read(1) or write(0) request, RTR set to 0 means the frame contains data, 1 means the frame contains no data and is a request to send. | 47 | |Data | 0+ |0-28 bytes usually but potentially up to 224 bytes of data | 48 | |Frame Check Sequence | 18 |This is the CRC-15 of the identifier, command and data fields used to ensure the integrity of recieved data | 49 | |End of Data | 2 |This transmits a pair of zeros which commit an E-Manchester violation marking the end of transmitted data. | 50 | |Acknowledge | 2 |Two recessive states, an acknowledge is given by one or more receivers transmitting a dominant state during the second state | 51 | |End of Frame | 8 |8 successive recessive states (1s) which mark the end of the frame | 52 | |Inter-Frame Spacing | 8 |Not strictly part of the frame but there must be at least 8TS of recessive state between each frame on the bus | 53 | 54 | ### Example data 55 | 56 | ![example](https://github.com/morcibacsi/VanAnalyzer/raw/master/docs/vanex.png) 57 | 58 | This example data was captured with a 'scope from a head unit removed from the car and decoded by hand. 59 | 60 | Some example captures can be found in the SampleCaptures folder. 61 | 62 | ## Building 63 | 64 | On Windows you can run the included **build_analyzer.cmd** file (cmake is required). 65 | 66 | For detailed build instructions please refer to the [SampleAnalyzer repository][sample_analyzer] 67 | 68 | ## Installing 69 | 70 | In the Developer tab in Logic preferences, specify the path for loading new plugins, then copy the built plugin into that location. 71 | 72 | ## Versions 73 | The 1.x and the 2.x versions are basically the same. The only difference is that version 2.x supports the FrameV2 API which was introduced in Logic v2.x therefore it can't run in Logic 1.x (but the 1.x version of the analyzer can be loaded into both Logic versions). Other than that the functions are identical. 74 | 75 | ## TODO 76 | 77 | - Find a way to mark the Frame Check Sequence bytes as FCS instead of DATA 78 | - Show the EOD and ACK bits 79 | - Implement GenerateSimulationData() method (now it has the default from the SampleAnalyzer) 80 | 81 | 82 | [logic]: https://www.saleae.com/downloads 83 | [sample_analyzer]: https://github.com/saleae/SampleAnalyzer 84 | [graham]: http://graham.auld.me.uk/projects/vanbus/lineprotocol.html 85 | [van_network]: https://en.wikipedia.org/wiki/Vehicle_Area_Network -------------------------------------------------------------------------------- /src/VANAnalyzerResults.cpp: -------------------------------------------------------------------------------- 1 | #include "VanAnalyzerResults.h" 2 | #include 3 | #include "VanAnalyzer.h" 4 | #include "VanAnalyzerSettings.h" 5 | #include 6 | #include 7 | #include 8 | 9 | typedef union 10 | { 11 | struct 12 | { 13 | uint8_t RTR : 1; 14 | uint8_t RNW : 1; 15 | uint8_t RAK : 1; 16 | uint8_t EXT : 1; 17 | } data; 18 | uint8_t Value; 19 | } Command; 20 | 21 | 22 | VanAnalyzerResults::VanAnalyzerResults( VanAnalyzer* analyzer, VanAnalyzerSettings* settings ) 23 | : AnalyzerResults(), mSettings( settings ), mAnalyzer( analyzer ) 24 | { 25 | } 26 | 27 | VanAnalyzerResults::~VanAnalyzerResults() 28 | { 29 | } 30 | 31 | void VanAnalyzerResults::GenerateBubbleText( U64 frame_index, Channel& channel, DisplayBase display_base ) 32 | { 33 | ClearResultStrings(); 34 | Frame frame = GetFrame( frame_index ); 35 | U64 frameData1 = frame.mData1; 36 | U64 frameData2 = frame.mData2; 37 | U8 frameType = frame.mType; 38 | 39 | char number_str[ 128 ]; 40 | std::stringstream ss; 41 | char command[ 4 ] = "-R-"; 42 | char ack[ 2 ] = "N"; 43 | 44 | switch( frameType ) 45 | { 46 | case StartOfFrame: 47 | AnalyzerHelpers::GetNumberString( frameData1, display_base, 8, number_str, 128 ); 48 | ss << "SOF: " << number_str; 49 | AddResultString( ss.str().c_str() ); 50 | break; 51 | case IdentifierField: 52 | AnalyzerHelpers::GetNumberString( frameData1, display_base, 12, number_str, 128 ); 53 | ss << "IDEN: " << number_str; 54 | AddResultString( ss.str().c_str() ); 55 | break; 56 | case CommandField: 57 | AnalyzerHelpers::GetNumberString( frameData1, display_base, 4, number_str, 128 ); 58 | // EXT(1), RAK (0-no, 1-yes), RW (0-W,1-R), RTR (0-data, 1-no data) 59 | Command com; 60 | com.Value = frameData1; 61 | if( com.data.RAK == 1 ) 62 | { 63 | command[ 0 ] = 'A'; 64 | } 65 | if( com.data.RNW == 0 ) 66 | { 67 | command[ 1 ] = 'W'; 68 | } 69 | if( com.data.RTR == 0 ) 70 | { 71 | command[ 2 ] = 'D'; 72 | } 73 | 74 | ss << "COM: " << number_str << "(" << command << ")"; 75 | AddResultString( ss.str().c_str() ); 76 | break; 77 | case DataField: 78 | AnalyzerHelpers::GetNumberString( frameData1, display_base, 8, number_str, 128 ); 79 | ss << "DATA(" << frameData2 << "): " << number_str; 80 | AddResultString( ss.str().c_str() ); 81 | break; 82 | case FCSField: 83 | AnalyzerHelpers::GetNumberString( frameData1, display_base, 8, number_str, 128 ); 84 | ss << "FCS(" << frameData2 << "): " << number_str; 85 | AddResultString( ss.str().c_str() ); 86 | break; 87 | case EndOfData: 88 | AnalyzerHelpers::GetNumberString( frameData1, display_base, 2, number_str, 128 ); 89 | ss << "EOD: " << number_str; 90 | AddResultString( ss.str().c_str() ); 91 | break; 92 | case AckField: 93 | AnalyzerHelpers::GetNumberString( frameData1, display_base, 2, number_str, 128 ); 94 | if( frameData1 == 2 ) 95 | { 96 | ack[ 0 ] = 'A'; 97 | } 98 | ss << "ACK: " << number_str << "(" << ack << ")"; 99 | AddResultString( ss.str().c_str() ); 100 | break; 101 | case EndOfFrame: 102 | AnalyzerHelpers::GetNumberString( frameData1, display_base, 8, number_str, 128 ); 103 | ss << "EOF: " << number_str; 104 | AddResultString( ss.str().c_str() ); 105 | break; 106 | default: 107 | AnalyzerHelpers::GetNumberString( frameData1, display_base, 4, number_str, 128 ); 108 | AddResultString( number_str ); 109 | break; 110 | } 111 | } 112 | 113 | void VanAnalyzerResults::GenerateExportFile( const char* file, DisplayBase display_base, U32 export_type_user_id ) 114 | { 115 | // export_type_user_id is only important if we have more than one export type. 116 | std::stringstream ss; 117 | void* f = AnalyzerHelpers::StartFile( file ); 118 | 119 | U64 trigger_sample = mAnalyzer->GetTriggerSample(); 120 | U32 sample_rate = mAnalyzer->GetSampleRate(); 121 | 122 | U64 num_frames = GetNumFrames(); 123 | U64 num_packets = GetNumPackets(); 124 | 125 | for( U32 i = 0; i < num_packets; i++ ) 126 | { 127 | if( i != 0 ) 128 | { 129 | // below, we "continue" the loop rather than run to the end. So we need to save to the file here. 130 | ss << std::endl; 131 | 132 | AnalyzerHelpers::AppendToFile( ( U8* )ss.str().c_str(), ss.str().length(), f ); 133 | ss.str( std::string() ); 134 | 135 | 136 | if( UpdateExportProgressAndCheckForCancel( i, num_packets ) == true ) 137 | { 138 | AnalyzerHelpers::EndFile( f ); 139 | return; 140 | } 141 | } 142 | 143 | U64 first_frame_id; 144 | U64 last_frame_id; 145 | GetFramesContainedInPacket( i, &first_frame_id, &last_frame_id ); 146 | Frame frame = GetFrame( first_frame_id ); 147 | 148 | char time_str[ 128 ]; 149 | AnalyzerHelpers::GetTimeString( frame.mStartingSampleInclusive, trigger_sample, sample_rate, time_str, 128 ); 150 | 151 | ss << time_str << " Ch:0:"; 152 | U64 frame_id = first_frame_id; 153 | 154 | for( U64 i = first_frame_id; i < last_frame_id; i++ ) 155 | { 156 | Frame frame = GetFrame( i ); 157 | U8 numOfBits = 12; 158 | switch( frame.mType ) 159 | { 160 | case StartOfFrame: 161 | numOfBits = 12; 162 | case IdentifierField: 163 | numOfBits = 12; 164 | case CommandField: 165 | numOfBits = 4; 166 | case DataField: 167 | numOfBits = 8; 168 | case FCSField: 169 | numOfBits = 8; 170 | case AckField: 171 | numOfBits = 2; 172 | default: 173 | break; 174 | } 175 | 176 | if( frame.mType != StartOfFrame && frame.mType != EndOfData && frame.mType != AckField && frame.mType != EndOfFrame ) 177 | { 178 | char number_str[ 128 ]; 179 | AnalyzerHelpers::GetNumberString( frame.mData1, Hexadecimal, numOfBits, number_str, 128 ); 180 | memmove( number_str, number_str + 2, strlen( number_str ) ); // remove 0x from hex-string 181 | 182 | if( strlen( number_str ) == 1 && frame.mType != CommandField ) 183 | { 184 | ss << " 0" << number_str; 185 | } 186 | else 187 | { 188 | ss << " " << number_str; 189 | } 190 | } 191 | if( frame.mType == AckField ) 192 | { 193 | if( frame.mData1 == 3 ) 194 | { 195 | ss << " N"; 196 | } 197 | else 198 | { 199 | ss << " A"; 200 | } 201 | } 202 | } 203 | 204 | if( UpdateExportProgressAndCheckForCancel( i, num_frames ) == true ) 205 | { 206 | AnalyzerHelpers::EndFile( f ); 207 | return; 208 | } 209 | } 210 | 211 | AnalyzerHelpers::EndFile( f ); 212 | } 213 | 214 | void VanAnalyzerResults::GenerateFrameTabularText( U64 frame_index, DisplayBase display_base ) 215 | { 216 | #ifdef SUPPORTS_PROTOCOL_SEARCH 217 | Frame frame = GetFrame( frame_index ); 218 | ClearTabularText(); 219 | 220 | char number_str[ 128 ]; 221 | AnalyzerHelpers::GetNumberString( frame.mData1, display_base, 8, number_str, 128 ); 222 | AddTabularText( number_str ); 223 | #endif 224 | } 225 | 226 | void VanAnalyzerResults::GeneratePacketTabularText( U64 packet_id, DisplayBase display_base ) 227 | { 228 | // not supported 229 | } 230 | 231 | void VanAnalyzerResults::GenerateTransactionTabularText( U64 transaction_id, DisplayBase display_base ) 232 | { 233 | // not supported 234 | } -------------------------------------------------------------------------------- /src/VANAnalyzer.cpp: -------------------------------------------------------------------------------- 1 | #include "VanAnalyzer.h" 2 | #include "VanAnalyzerSettings.h" 3 | #include "VanAnalyzerResults.h" 4 | #include 5 | 6 | VanAnalyzer::VanAnalyzer() : Analyzer2(), mSettings( new VanAnalyzerSettings() ), mSimulationInitilized( false ) 7 | { 8 | SetAnalyzerSettings( mSettings.get() ); 9 | 10 | UseFrameV2(); 11 | } 12 | 13 | VanAnalyzer::~VanAnalyzer() 14 | { 15 | KillThread(); 16 | } 17 | 18 | void VanAnalyzer::SetupResults() 19 | { 20 | mResults.reset( new VanAnalyzerResults( this, mSettings.get() ) ); 21 | SetAnalyzerResults( mResults.get() ); 22 | mResults->AddChannelBubblesWillAppearOn( mSettings->mInputChannel ); 23 | } 24 | 25 | void VanAnalyzer::WorkerThread() 26 | { 27 | mSampleRateHz = GetSampleRate(); 28 | 29 | mSerial = GetAnalyzerChannelData( mSettings->mInputChannel ); 30 | 31 | mSamplesPerBit = mSampleRateHz / mSettings->mBitRate; 32 | mNumSamplesIn8Bits = U32( mSamplesPerBit * 16.0 ); 33 | 34 | WaitFor8RecessiveBits(); 35 | 36 | mSerial->AdvanceToNextEdge(); 37 | mFrameStart = true; 38 | 39 | // line is low 40 | U64 startOfFrameSampleNumber = mSerial->GetSampleNumber(); 41 | AddMarker( startOfFrameSampleNumber, AnalyzerResults::Start ); 42 | 43 | while( 1 ) 44 | { 45 | mEofFound = false; 46 | 47 | //--- Loop util the EOF (8 consecutive recessive bits) 48 | do 49 | { 50 | BitState currentBitState = mSerial->GetBitState(); 51 | const U64 start = mSerial->GetSampleNumber(); 52 | 53 | const U64 nextEdge = mSerial->GetSampleOfNextEdge(); 54 | const U64 bitCount = ( nextEdge - start + mSamplesPerBit / 2 ) / mSamplesPerBit; 55 | 56 | if( mFrameStart ) 57 | { 58 | mBitPos = 0; 59 | mbyteCount = 0; 60 | AddMarker( start, AnalyzerResults::Start ); 61 | } 62 | 63 | // new byte 64 | if( mbitCount == 0 ) 65 | { 66 | mStartOfFieldSampleNumber = start + mSamplesPerBit / 2; 67 | } 68 | 69 | // still in the message 70 | if( bitCount < 8 ) 71 | { 72 | mFrameStart = false; 73 | for( U64 i = 0; i < bitCount; i++ ) 74 | { 75 | U64 bitPosition = start + mSamplesPerBit / 2 + i * mSamplesPerBit; 76 | ProcessBit( currentBitState, bitPosition ); 77 | } 78 | } 79 | else 80 | { 81 | // we found the EOF (8 consecutive recessive bits) 82 | AddMarker( start, AnalyzerResults::Stop ); 83 | mEofFound = true; 84 | mFrameStart = true; 85 | mResults->CommitPacketAndStartNewPacket(); 86 | } 87 | mSerial->AdvanceToNextEdge(); 88 | 89 | if( !mSerial->DoMoreTransitionsExistInCurrentData() ) 90 | { 91 | // end of stream 92 | AddMarker( start, AnalyzerResults::Stop ); 93 | mEofFound = true; 94 | mFrameStart = true; 95 | } 96 | 97 | } while( mEofFound != true ); 98 | //--- 99 | mResults->CommitResults(); 100 | } 101 | } 102 | 103 | void VanAnalyzer::ProcessBit( const BitState bitState, const U64 bitPosition ) 104 | { 105 | bool isManchesterBit = ( mbitCount + 1 ) % 5 == 0; 106 | 107 | mBitPositions[ mBitPos ] = bitPosition; 108 | 109 | if( mBitPos >= 5 ) 110 | { 111 | mBitPos = 0; 112 | } 113 | else 114 | { 115 | mBitPos++; 116 | } 117 | 118 | if( !isManchesterBit ) 119 | { 120 | if( bitState == mSettings->Recessive() ) 121 | { 122 | mByte |= mask; 123 | } 124 | mask = mask >> 1; 125 | mPreviousNonManchesterBitPosition = bitPosition; 126 | AddMarker( bitPosition, AnalyzerResults::Dot ); 127 | } 128 | else 129 | { 130 | // if we found the second manchester bit, then we have the full byte 131 | AddMarker( bitPosition, AnalyzerResults::X ); 132 | if( mbitCount == 9 ) 133 | { 134 | mbitCount = -1; 135 | mask = 1 << 7; 136 | switch( mbyteCount ) 137 | { 138 | case 0: 139 | { 140 | mCOM = 0; 141 | mIdent = 0; 142 | AddFrame( mStartOfFieldSampleNumber, mPreviousNonManchesterBitPosition, mByte, StartOfFrame, 0 ); 143 | break; 144 | } 145 | case 1: 146 | { 147 | mIdent = mByte; 148 | mStartOfIdenFieldSampleNumber = mStartOfFieldSampleNumber; 149 | 150 | break; 151 | } 152 | case 2: 153 | { 154 | mIdent = ( mIdent << 8 | mByte ) >> 4; 155 | mCOM = ( U8 )( mByte & 0xF ); 156 | AddFrame( mStartOfIdenFieldSampleNumber, mBitPositions[ 0 ], mIdent, IdentifierField, 0 ); 157 | AddFrame( mBitPositions[ 1 ], bitPosition, mCOM, CommandField, 0 ); 158 | break; 159 | } 160 | default: 161 | AddFrame( mStartOfFieldSampleNumber, mPreviousNonManchesterBitPosition, mByte, DataField, mbyteCount - 2 ); 162 | break; 163 | } 164 | 165 | mStartOfFieldSampleNumber = bitPosition; 166 | mByte = 0; 167 | mbyteCount++; 168 | } 169 | } 170 | 171 | mbitCount++; 172 | } 173 | 174 | bool VanAnalyzer::NeedsRerun() 175 | { 176 | return false; 177 | } 178 | 179 | U32 VanAnalyzer::GenerateSimulationData( U64 minimum_sample_index, U32 device_sample_rate, 180 | SimulationChannelDescriptor** simulation_channels ) 181 | { 182 | if( mSimulationInitilized == false ) 183 | { 184 | mSimulationDataGenerator.Initialize( GetSimulationSampleRate(), mSettings.get() ); 185 | mSimulationInitilized = true; 186 | } 187 | 188 | return mSimulationDataGenerator.GenerateSimulationData( minimum_sample_index, device_sample_rate, simulation_channels ); 189 | } 190 | 191 | U32 VanAnalyzer::GetMinimumSampleRateHz() 192 | { 193 | return mSettings->mBitRate * 4; 194 | } 195 | 196 | const char* VanAnalyzer::GetAnalyzerName() const 197 | { 198 | return "VAN"; 199 | } 200 | 201 | const char* GetAnalyzerName() 202 | { 203 | return "VAN"; 204 | } 205 | 206 | Analyzer* CreateAnalyzer() 207 | { 208 | return new VanAnalyzer(); 209 | } 210 | 211 | void DestroyAnalyzer( Analyzer* analyzer ) 212 | { 213 | delete analyzer; 214 | } 215 | 216 | void VanAnalyzer::WaitFor8RecessiveBits() 217 | { 218 | if( mSerial->GetBitState() != mSettings->Recessive() ) 219 | mSerial->AdvanceToNextEdge(); 220 | 221 | for( ;; ) 222 | { 223 | if( mSerial->WouldAdvancingCauseTransition( mNumSamplesIn8Bits ) == false ) 224 | return; 225 | 226 | mSerial->AdvanceToNextEdge(); 227 | } 228 | } 229 | 230 | void VanAnalyzer::AddMarker( const U64 inSampleNumber, const AnalyzerResults::MarkerType inMarker ) 231 | { 232 | mResults->AddMarker( inSampleNumber, inMarker, mSettings->mInputChannel ); 233 | } 234 | 235 | // Adds a frame to the resultset 236 | void VanAnalyzer::AddFrame( const U64 startingPoint, const U64 endingPoint, const U32 data, const U32 type, const U32 indexOfData ) 237 | { 238 | Frame frame; 239 | frame.mData1 = data; 240 | frame.mData2 = indexOfData; 241 | frame.mFlags = 0; 242 | frame.mType = type; 243 | frame.mStartingSampleInclusive = startingPoint; 244 | frame.mEndingSampleInclusive = endingPoint; 245 | 246 | mResults->AddFrame( frame ); 247 | 248 | FrameV2 frame_v2; 249 | 250 | // you can add any number of key value pairs. Each will get it's own column in the data table. 251 | if( type == IdentifierField ) 252 | { 253 | frame_v2.AddInteger( "Identifier", frame.mData1 ); 254 | } 255 | else if( type == CommandField ) 256 | { 257 | frame_v2.AddByte( "Command", frame.mData1 ); 258 | frame_v2.AddByte( "Data", frame.mData1 ); 259 | } 260 | else 261 | { 262 | frame_v2.AddByte( "Data", frame.mData1 ); 263 | } 264 | 265 | // The second parameter is the frame "type". Any string is allowed. 266 | mResults->AddFrameV2( frame_v2, VanFrameTypeForDisplay[ type ], frame.mStartingSampleInclusive, frame.mEndingSampleInclusive ); 267 | 268 | mResults->CommitResults(); 269 | ReportProgress( frame.mEndingSampleInclusive ); 270 | } 271 | -------------------------------------------------------------------------------- /docs/Analyzer_API.md: -------------------------------------------------------------------------------- 1 | # C++ Analyzer API 2 | 3 | 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. 4 | 5 | Please refer to support, as well as Saleae's other open source protocol analyzers for reference. 6 | 7 | Changes that need to be reflected in this documentation: 8 | 9 | - 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) 10 | - LoadSettings and SaveSettings are no longer used, instead the settings interfaces are serialized automatically by the Logic 2 software. 11 | - The `NeedsRerun` function is no longer used. 12 | - Your analyzer must inherit from `Analyzer2`, not `Analyzer`, and implement an additional virtual function `SetupResults`. See other Saleae analyzers for examples. 13 | 14 | 15 | # Writing your Analyzer’s Code 16 | 17 | This second part of the document deals with writing the code for your analyzer. 18 | 19 | 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. 20 | 21 | Conceptually, the analyzer can be broken into 4 main parts – the 4 c++ files. Working on them in a 22 | particular order is highly recommended, and this document describes the procedure in this order. 23 | 24 | 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. 25 | 26 | 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. 27 | 28 | 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. 29 | 30 | Lastly, you’ll implement your Analyzer-derived class. The main thing you’ll do here is translate data 31 | streams into results, based on your protocol. 32 | 33 | Let’s get started! 34 | 35 | ---------- 36 | 37 | 38 | # Analyzer Settings 39 | 40 | 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. 41 | 42 | **{YourName}AnalyzerSettings.h** 43 | 44 | 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. 45 | 46 | We’ll start with this 47 | 48 | 49 | #ifndef SIMPLESERIAL_ANALYZER_SETTINGS 50 | #define SIMPLESERIAL_ANALYZER_SETTINGS 51 | 52 | #include 53 | #include 54 | 55 | class SimpleSerialAnalyzerSettings : public AnalyzerSettings 56 | { 57 | public: 58 | SimpleSerialAnalyzerSettings(); 59 | virtual ~SimpleSerialAnalyzerSettings(); 60 | virtual bool SetSettingsFromInterfaces(); 61 | void UpdateInterfacesFromSettings(); 62 | virtual void LoadSettings( const char* settings ); 63 | virtual const char* SaveSettings(); 64 | }; 65 | #endif //SIMPLESERIAL_ANALYZER_SETTINGS 66 | 67 | In addition, your header will define two sets of variables: 68 | 69 | ***User-modifiable settings*** 70 | 71 | 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: 72 | 73 | -  Bit rate 74 | -  Bits per transfer 75 | -  Bit ordering (MSb first, LSb first) 76 | -  Clock edge (rising, falling) to use 77 | -  Enable line polarity 78 | -  Etc – anything you need for your specific protocol. If you like, start with just the Channel variable(s), and you can add more later to make your analyzer more flexible. 79 | 80 | The variable types can be whatever you like – *std::string*, *double*, *int*, *enum*, etc. Note that these 81 | variables will need to be serialized (saved for later, to a file) so when in doubt, stick to simple types 82 | (rather than custom classes or structs). The SDK provides a means to serialize and store your variables. 83 | 84 | ***AnalyzerSettingsInterfaces*** 85 | 86 | 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: 87 | 88 | 89 | -  AnalyzerSettingInterfaceChannel: Used exclusively for input channel selection. 90 | -  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) 91 | -  AnalyzerSettingInterfaceInteger: Allows a user to type an integer into a box. 92 | -  AnalyzerSettingInterfaceText: Allows a user to enter some text into a textbox. 93 | -  AnalyzerSettingInterfaceBool: Provides the user with a checkbox. 94 | 95 | *AnalyzerSettingsInterface* types should be declared as pointers. (We’re using the *std::auto_ptr* type, 96 | 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.) 97 | 98 | **{YourName}AnalyzerSettings.cpp** 99 | 100 | ***The Constructor*** 101 | In your constructor, we’ll first initialize all your settings variables to their default values. Second, we’ll setup each variable’s corresponding interface object. 102 | 103 | 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. 104 | 105 | **Setting up each AnalyzerSettingInterface object** 106 | 107 | First, we create the object (call new) and assign the value to the interface’s pointer. Note that we’re 108 | using *std::auto_ptr*, so this means calling the member function *reset*. For standard (raw pointers), you would do something like: 109 | 110 | mInputChannelInterface = new AnalyzerSettingInterfaceChannel(); 111 | 112 | Next, we call the member function *SetTitleAndTooltip*. The title will appear to the left of the input 113 | 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. 114 | 115 | void SetTitleAndTooltip( const char* title, const char* tooltip ); 116 | mInputChannelInterface->SetTitleAndTooltip( "Serial", "Standard Async Serial" ); 117 | 118 | 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. 119 | 120 | void SetChannel( const Channel& channel ); 121 | void SetNumber( double number ); 122 | void SetInteger( int integer ); 123 | void SetText( const char* text ); 124 | void SetValue( bool value ); 125 | 126 | We’ll want to specify the allowable options. This depends on the type of interface. 127 | 128 | *AnalyzerSettingInterfaceChannel* 129 | 130 | 131 | void SetSelectionOfNoneIsAllowed( bool is_allowed ); 132 | 133 | Some channels can be optional , but typically they are not. By default, the user must select a channel. 134 | 135 | *AnalyzerSettingInterfaceNumberList* 136 | 137 | 138 | void AddNumber( double number, const char* str, const char* tooltip ); 139 | 140 | Call AddNumber for every item you want in the dropdown. *number* is the value associated with the 141 | selection; it is not displayed to the user. 142 | 143 | *AnalyzerSettingInterfaceInteger* 144 | 145 | 146 | void SetMax( int max ); 147 | void SetMin( int min ); 148 | 149 | You can set the allowable range for the integer the user can enter. 150 | 151 | *AnalyzerSettingInterfaceText* 152 | 153 | 154 | void SetTextType( TextType text_type ); 155 | 156 | By default, this interface just provides a simple textbox for the user to enter text, but you can also 157 | specify that the text should be a path, which will cause a browse button to appear. The options are 158 | *NormalText*, *FilePath*, or *FolderPath*. 159 | 160 | *AnalyzerSettingInterfaceBool* 161 | 162 | There are only two allowable options for the bool interface (checkbox). 163 | 164 | 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. 165 | 166 | 167 | void AddInterface( AnalyzerSettingInterface* analyzer_setting_interface ); 168 | 169 | **Specifying the export options** 170 | 171 | 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. 172 | 173 | 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). 174 | 175 | 176 | void AddExportOption( U32 user_id, const char* menu_text ); 177 | void AddExportExtension( U32 user_id, const char * extension_description, const char * 178 | extension ); 179 | AddExportOption( 0, "Export as text/csv file" ); 180 | AddExportExtension( 0, "text", "txt" ); 181 | AddExportExtension( 0, "csv", "csv" ); 182 | 183 | **Specifying which channels are in use** 184 | 185 | The analyzer must indicate which channel(s) it is using. This is done with the *AddChannel* function. 186 | 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*. 187 | 188 | 189 | void ClearChannels(); 190 | void AddChannel( Channel& channel, const char* channel_label, bool is_used ); 191 | ClearChannels(); 192 | AddChannel( mInputChannel, "Serial", false ); 193 | 194 | 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 195 | *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. 196 | 197 | ***The Destructor*** 198 | 199 | 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. 200 | 201 | ***bool {YourName}AnalyzerSettings::SetSettingsFromInterfaces()*** 202 | 203 | As the name implies, in this function we will copy the values saved in our interface objects to our 204 | settings variables. This function will be called if the user updates the settings. 205 | 206 | We can also examine the values saved in the interface (the user’s selections) and choose to reject 207 | combinations we don’t want to allow. If you want to reject a particular selection, do not assign the 208 | 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. 209 | 210 | 211 | void SetErrorText( const char* error_text ); 212 | 213 | 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. 214 | 215 | For your analyzer, it’s quite possible that all possible user selections are valid. In that case you can 216 | ignore the above. 217 | 218 | 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*. 219 | 220 | 221 | bool SimpleSerialAnalyzerSettings::SetSettingsFromInterfaces() 222 | { 223 | mInputChannel = mInputChannelInterface->GetChannel(); 224 | mBitRate = mBitRateInterface->GetInteger(); 225 | ClearChannels(); 226 | AddChannel( mInputChannel, "Simple Serial", true ); 227 | return true; 228 | } 229 | 230 | ***void {YourName}AnalyzerSettings::UpdateInterfacesFromSettings()*** 231 | 232 | *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*. 233 | 234 | 235 | void SimpleSerialAnalyzerSettings::UpdateInterfacesFromSettings() 236 | { 237 | mInputChannelInterface->SetChannel( mInputChannel ); 238 | mBitRateInterface->SetInteger( mBitRate ); 239 | } 240 | 241 | ***void {YourName}AnalyzerSettings::LoadSettings( const char* settings )*** 242 | 243 | In the last to functions of your AnalyzerSettings-derived class, you’ll implement serialization 244 | (persistence) of your settings. It’s pretty straightforward. 245 | 246 | Your settings are saved in, and loaded from, a single string. You can technically serialize all of your 247 | 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. 248 | 249 | 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*. 250 | 251 | 252 | class LOGICAPI SimpleArchive 253 | { 254 | public: 255 | SimpleArchive(); 256 | ~SimpleArchive(); 257 | void SetString( const char* archive_string ); 258 | const char* GetString(); 259 | bool operator<<( U64 data ); 260 | bool operator<<( U32 data ); 261 | bool operator<<( S64 data ); 262 | bool operator<<( S32 data ); 263 | bool operator<<( double data ); 264 | bool operator<<( bool data ); 265 | bool operator<<( const char* data ); 266 | bool operator<<( Channel& data ); 267 | bool operator>>( U64& data ); 268 | bool operator>>( U32& data ); 269 | bool operator>>( S64& data ); 270 | bool operator>>( S32& data ); 271 | bool operator>>( double& data ); 272 | bool operator>>( bool& data ); 273 | bool operator>>( char const ** data ); 274 | bool operator>>( Channel& data ); 275 | protected: 276 | struct SimpleArchiveData* mData; 277 | }; 278 | 279 | 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). 280 | 281 | 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. 282 | 283 | Lastly, call *UpdateInterfacesFromSettings.* This will update all our interfaces to reflect the newly loaded values. 284 | 285 | Below is an example from *SimpleSerialAnalyzerSettings*. 286 | 287 | 288 | void SimpleSerialAnalyzerSettings::LoadSettings( const char* settings ) 289 | { 290 | SimpleArchive text_archive; 291 | text_archive.SetString( settings ); 292 | text_archive >> mInputChannel; 293 | text_archive >> mBitRate; 294 | ClearChannels(); 295 | AddChannel( mInputChannel, "Simple Serial", true ); 296 | UpdateInterfacesFromSettings(); 297 | } 298 | 299 | ***const char* {YourName}AnalyzerSettings::SaveSettings()*** 300 | 301 | Our last function will save all of our settings variables into a single string. We’ll use *SimpleArchive* to serialize them. 302 | The order in which we serialize our settings variables must be exactly the same order as we extract them, in *LoadSettings*. 303 | 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. 304 | 305 | Bellow is an example from *SimpleSerialAnalyzerSettings*: 306 | 307 | 308 | const char* SimpleSerialAnalyzerSettings::SaveSettings() 309 | { 310 | SimpleArchive text_archive; 311 | text_archive << mInputChannel; 312 | text_archive << mBitRate; 313 | return SetReturnString( text_archive.GetString() ); 314 | } 315 | 316 | 317 | ## SimulationDataGenerator 318 | 319 | The next step after creating your *{YourName}AnalyzerSettings* files, is to create your 320 | *SimulationDataGenerator*. 321 | 322 | 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. 323 | 324 | That said, fully implementing simulated data is not absolutely required to make an analyzer. 325 | {YourName}SimulationDataGenerator.h 326 | 327 | Besides the constructor and destructor, there are only two required functions, and two required 328 | variables. Other functions and variables can be added, to help implement your simulated data. Here is an example starting point, from *SimpleSerialSimulationDataGenerator.h* 329 | 330 | 331 | #ifndef SIMPLESERIAL_SIMULATION_DATA_GENERATOR 332 | #define SIMPLESERIAL_SIMULATION_DATA_GENERATOR 333 | 334 | #include 335 | 336 | class SimpleSerialAnalyzerSettings; 337 | 338 | class SimpleSerialSimulationDataGenerator 339 | { 340 | public: 341 | SimpleSerialSimulationDataGenerator(); 342 | ~SimpleSerialSimulationDataGenerator(); 343 | void Initialize( U32 simulation_sample_rate, SimpleSerialAnalyzerSettings* 344 | settings ); 345 | U32 GenerateSimulationData( U64 newest_sample_requested, U32 sample_rate, 346 | SimulationChannelDescriptor** simulation_channel ); 347 | protected: 348 | SimpleSerialAnalyzerSettings* mSettings; 349 | U32 mSimulationSampleRateHz; 350 | SimulationChannelDescriptor mSerialSimulationData; 351 | }; 352 | #endif //SIMPLESERIAL_SIMULATION_DATA_GENERATOR 353 | 354 | ***Overview*** 355 | 356 | 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. 357 | We’ll go over this in detail in a minute. 358 | 359 | **{YourName}SimulationDataGenerator.cpp** 360 | 361 | ***Constructor/Destructor*** 362 | 363 | You may or may not need anything in your constructor or destructor. For now at least, leave them 364 | 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. 365 | 366 | **void {YourName}SimulationDataGenerator::Initialize( U32 simulation_sample_rate,** 367 | **{YourName}AnalyzerSettings* settings )** 368 | 369 | This function provides you with the state of things as they are going to be when we start simulating. 370 | We’ll need to save this information. 371 | 372 | First, save *simulation_sample_rate* and *settings* to member variables. Notice that we now have a 373 | 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. 374 | 375 | 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). 376 | 377 | At this point we’ll need to take a step back and discuss some key concepts. 378 | 379 | **BitState** 380 | 381 | *BitState* is a type used often in the SDK. It can be either *BIT_LOW* or BIT_HIGH, and represents a 382 | channel’s logic state. 383 | 384 | **Sample Rate (samples per second)** 385 | 386 | 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. 387 | 388 | **Sample Number** 389 | 390 | 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. 391 | 392 | **SimulationChannelDescriptor** 393 | 394 | 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: 395 | 396 | 397 | - We provide the initial state of the channel (BIT_LOW, or BIT_HIGH) 398 | - We move forward some number of samples, and then toggle the channel. 399 | - We repeatedly do this 400 | 401 | 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). 402 | 403 | Put another way: 404 | 405 | -  In the very beginning, we specify the initial state (BIT_LOW or BIT_HIGH). This is the state of Sample Number 0. 406 | -  Then, we move forward (advance) some number of samples. 20 samples, for example. 407 | -  Then, we toggle the channel (low becomes high, high becomes low). 408 | -  Then we move forward (advance) some more. Maybe 100 samples this time. 409 | -  Then we toggle again. 410 | -  Then we move forward again, and then we toggle again, etc. 411 | 412 | Let’s explore the functions used to do this: 413 | 414 | *void Advance( U32 num_samples_to_advance );* 415 | 416 | As you might guess, this is how we move forward in our simulated waveform. Internally, the object 417 | 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. 418 | 419 | *void Transition();* 420 | 421 | This toggles the channel. *BIT_LOW* becomes *BIT_HIGH* , *BIT_HIGH* becomes *BIT_LOW*. The current 422 | 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. 423 | 424 | *void TransitionIfNeeded( BitState bit_state );* 425 | 426 | Often we don’t want to keep track of the current *BitState* , which toggles every time we call *Transition*. 427 | *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”. 428 | 429 | *BitState GetCurrentBitState();* 430 | 431 | This function lets you directly ask what the current *BitState* is. 432 | 433 | *U64 GetCurrentSampleNumber();* 434 | 435 | This function lets you ask what the current *SampleNumber* is. 436 | 437 | **ClockGenerator** 438 | 439 | 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. 440 | 441 | *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. 442 | 443 | Initially we created *ClockGenerator* to create clock-like signals, but now you can use and time value, any time. Here’s how: 444 | 445 | *void Init( double target_frequency, U32 sample_rate_hz );* 446 | 447 | You’ll need to call this before using the class. For *sample_rate_hz* , enter the sample rate we’ll be 448 | 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. 449 | 450 | *U32 AdvanceByHalfPeriod( double multiple = 1.0 );* 451 | 452 | This function returns how many samples are needed to move forward by one half of the period (for 453 | 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. 454 | 455 | *U32 AdvanceByTimeS( double time_s );* 456 | 457 | 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. 458 | 459 | Note that the number of samples for a specific time period may change slightly every once in a while. 460 | This is so that on average, timing will be exact. 461 | 462 | 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. 463 | 464 | **void {YourName}SimulationDataGenerator::Initialize( U32 simulation_sample_rate,** 465 | **{YourName}AnalyzerSettings* settings )** 466 | 467 | Let’s take another look at the *Initialize* function, now that we have an idea what’s going on. This 468 | example is from *SimpleSerialSimulationDataGenerator.cpp*. 469 | 470 | 471 | void SimpleSerialSimulationDataGenerator::Initialize( U32 simulation_sample_rate, 472 | SimpleSerialAnalyzerSettings* settings ) 473 | { 474 | mSimulationSampleRateHz = simulation_sample_rate; 475 | mSettings = settings; 476 | mSerialSimulationData.SetChannel( mSettings->mInputChannel ); 477 | mSerialSimulationData.SetSampleRate( simulation_sample_rate ); 478 | mSerialSimulationData.SetInitialBitState( BIT_HIGH ); 479 | } 480 | 481 | **U32 {YourName}SimulationDataGenerator::GenerateSimulationData( U64** 482 | **largest_sample_requested, U32 sample_rate, SimulationChannelDescriptor** simulation_channel )** 483 | 484 | This function is repeatedly called to request more simulated data. When it’s called, just keep going 485 | 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. 486 | 487 | 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 488 | *AdjustSimulationTargetSample* to do this, as we’ll see in a moment. 489 | 490 | The parameter *simulation_channels* is to provide the caller with a pointer to an array of your 491 | *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. 492 | 493 | 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. 494 | 495 | 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. 496 | 497 | 498 | SimpleSerialSimulationDataGenerator::SimpleSerialSimulationDataGenerator() 499 | : mSerialText( "My first analyzer, woo hoo!" ), 500 | mStringIndex( 0 ) 501 | { 502 | } 503 | U32 SimpleSerialSimulationDataGenerator::GenerateSimulationData( U64 504 | largest_sample_requested, U32 sample_rate, SimulationChannelDescriptor** 505 | simulation_channel ) 506 | { 507 | U64 adjusted_largest_sample_requested = 508 | AnalyzerHelpers::AdjustSimulationTargetSample( largest_sample_requested, sample_rate, 509 | mSimulationSampleRateHz ); 510 | while( mSerialSimulationData.GetCurrentSampleNumber() < 511 | adjusted_largest_sample_requested ) 512 | { 513 | CreateSerialByte(); 514 | } 515 | *simulation_channel = &mSerialSimulationData; 516 | return 1; 517 | } 518 | void SimpleSerialSimulationDataGenerator::CreateSerialByte() 519 | { 520 | U32 samples_per_bit = mSimulationSampleRateHz / mSettings->mBitRate; 521 | U8 byte = mSerialText[ mStringIndex ]; 522 | mStringIndex++; 523 | if( mStringIndex == mSerialText.size() ) 524 | mStringIndex = 0; 525 | //we're currently high 526 | //let's move forward a little 527 | mSerialSimulationData.Advance( samples_per_bit * 10 ); 528 | mSerialSimulationData.Transition(); //low-going edge for start bit 529 | mSerialSimulationData.Advance( samples_per_bit ); //add start bit time 530 | U8 mask = 0x1 << 7; 531 | for( U32 i=0; i<8; i++ ) 532 | { 533 | if( ( byte & mask ) != 0 ) 534 | mSerialSimulationData.TransitionIfNeeded( BIT_HIGH ); 535 | else 536 | mSerialSimulationData.TransitionIfNeeded( BIT_LOW ); 537 | mSerialSimulationData.Advance( samples_per_bit ); 538 | mask = mask >> 1; 539 | } 540 | mSerialSimulationData.TransitionIfNeeded( BIT_HIGH ); //we need to end high 541 | //lets pad the end a bit for the stop bit: 542 | mSerialSimulationData.Advance( samples_per_bit ); 543 | } 544 | 545 | There are a few things we could do to clean this up. First, we could save the *samples_per_bit* as a 546 | 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. 547 | Another thing we could do is use the *DataExtractor* class to take care of the bit masking/testing. 548 | However, in our simple example what we have works well enough, and it has the advantage of being a bit more transparent. 549 | 550 | **Simulating Multiple Channels** 551 | 552 | 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*. 553 | 554 | Here is an example of I2C (2 channels)—these are the the member variable definitions in 555 | *I2cSimulationDataGenerator.h* : 556 | 557 | 558 | SimulationChannelDescriptorGroup mI2cSimulationChannels; 559 | SimulationChannelDescriptor* mSda; 560 | SimulationChannelDescriptor* mScl; 561 | 562 | Then, in the *Initialize* function: 563 | 564 | 565 | mSda = mI2cSimulationChannels.Add( settings->mSdaChannel, mSimulationSampleRateHz, 566 | BIT_HIGH ); 567 | mScl = mI2cSimulationChannels.Add( settings->mSclChannel, mSimulationSampleRateHz, 568 | BIT_HIGH ); 569 | 570 | And to provide the array to the caller of *GenerateSimulationData* : 571 | 572 | 573 | *simulation_channels = mI2cSimulationChannels.GetArray(); 574 | return mI2cSimulationChannels.GetCount(); 575 | 576 | 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. 577 | 578 | 579 | void AdvanceAll( U32 num_samples_to_advance ); 580 | 581 | Before returning from *GenerateSimulationData* , be sure that the Sample Number of *all* of your 582 | *SimulationChannelDescriptor* objects exceed *adjusted_largest_sample_requested*. 583 | 584 | Examples of generating simulation data 585 | 586 | **void SerialSimulationDataGenerator::CreateSerialByte( U64 value )** 587 | 588 | 589 | void SerialSimulationDataGenerator::CreateSerialByte( U64 value ) 590 | { 591 | // assume we start high 592 | mSerialSimulationData.Transition(); // low-going edge for start bit 593 | mSerialSimulationData.Advance( mClockGenerator.AdvanceByHalfPeriod() ); // add 594 | start bit time if( mSettings->mInverted == true ) value = ~value; 595 | U32 num_bits = mSettings->mBitsPerTransfer; 596 | BitExtractor bit_extractor( value, mSettings->mShiftOrder, num_bits ); 597 | for( U32 i = 0; i < num_bits; i++ ) 598 | { 599 | mSerialSimulationData.TransitionIfNeeded( bit_extractor.GetNextBit() ); 600 | mSerialSimulationData.Advance( mClockGenerator.AdvanceByHalfPeriod() ); 601 | } 602 | if( mSettings->mParity == AnalyzerEnums::Even ) 603 | { 604 | if( AnalyzerHelpers::IsEven( AnalyzerHelpers::GetOnesCount( value ) ) == true ) 605 | mSerialSimulationData.TransitionIfNeeded( mBitLow ); // we want to 606 | add a zero bit else mSerialSimulationData.TransitionIfNeeded( mBitHigh ); // we want to 607 | add a one bit mSerialSimulationData.Advance( mClockGenerator.AdvanceByHalfPeriod() ); 608 | } 609 | else if( mSettings->mParity == AnalyzerEnums::Odd ) 610 | { 611 | if( AnalyzerHelpers::IsOdd( AnalyzerHelpers::GetOnesCount( value ) ) == true ) 612 | mSerialSimulationData.TransitionIfNeeded( mBitLow ); // we want to 613 | add a zero bit else mSerialSimulationData.TransitionIfNeeded( mBitHigh ); 614 | mSerialSimulationData.Advance( mClockGenerator.AdvanceByHalfPeriod() ); 615 | } 616 | mSerialSimulationData.TransitionIfNeeded( mBitHigh ); // we need to end high 617 | // lets pad the end a bit for the stop bit: 618 | mSerialSimulationData.Advance( mClockGenerator.AdvanceByHalfPeriod( mSettings - > mStopBits ) ); 619 | } 620 | 621 | Note that above we use a number of helper functions and classes. Let’s discuss BitExtractor briefly. 622 | 623 | *BitExtractor* 624 | 625 | 626 | BitExtractor( U64 data, AnalyzerEnums::ShiftOrder shift_order, U32 num_bits ); 627 | BitState GetNextBit(); 628 | 629 | 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. 630 | 631 | Similar, but reversed, is the *DataBuilder* class, but as this generally used for collecting data, we’ll talk more about it then. 632 | 633 | *AnalyzerHelpers* 634 | 635 | Some static helper functions that might be helpful, grouped under the class *AnalyzerHelpers*, include: 636 | 637 | 638 | static bool IsEven( U64 value ); 639 | static bool IsOdd( U64 value ); 640 | static U32 GetOnesCount( U64 value ); 641 | static U32 Diff32( U32 a, U32 b ); 642 | 643 | **void I2cSimulationDataGenerator::CreateBit( BitState bit_state )** 644 | 645 | 646 | void I2cSimulationDataGenerator::CreateBit( BitState bit_state ) 647 | { 648 | if( mScl->GetCurrentBitState() != BIT_LOW ) 649 | AnalyzerHelpers::Assert( "CreateBit expects to be entered with scl low" ); 650 | mI2cSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 0.5 ) ); 651 | mSda->TransitionIfNeeded( bit_state ); 652 | mI2cSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 0.5 ) ); 653 | mScl->Transition(); // posedge 654 | mI2cSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 1.0 ) ); 655 | mScl->Transition(); // negedge 656 | } 657 | void I2cSimulationDataGenerator::CreateI2cByte( U8 data, 658 | I2cResponse reply ) void I2cSimulationDataGenerator::CreateI2cByte( U8 data, 659 | I2cResponse reply ) 660 | { 661 | if( mScl->GetCurrentBitState() == BIT_HIGH ) 662 | { 663 | mI2cSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 1.0 ) ); 664 | mScl->Transition(); 665 | mI2cSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 1.0 ) ); 666 | } 667 | BitExtractor bit_extractor( data, AnalyzerEnums::MsbFirst, 8 ); 668 | for( U32 i = 0; i < 8; i++ ) 669 | { 670 | CreateBit( bit_extractor.GetNextBit() ); 671 | } 672 | if( reply == I2C_ACK ) 673 | CreateBit( BIT_LOW ); 674 | else 675 | CreateBit( BIT_HIGH ); 676 | mI2cSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 4.0 ) ); 677 | } 678 | 679 | *void I2cSimulationDataGenerator::CreateI2cTransaction( U8 address, I2cDirection direction, U8 data )* 680 | 681 | 682 | void I2cSimulationDataGenerator::CreateI2cTransaction( U8 address, I2cDirection direction, U8 data ) 683 | { 684 | U8 command = address << 1; 685 | if( direction == I2C_READ ) 686 | command |= 0x1; 687 | CreateStart(); 688 | CreateI2cByte( command, I2C_ACK ); 689 | CreateI2cByte( data, I2C_ACK ); 690 | CreateI2cByte( data, I2C_NAK ); 691 | CreateStop(); 692 | } 693 | U32 I2cSimulationDataGenerator::GenerateSimulationData( U64 largest_sample_requested, U32 sample_rate, 694 | SimulationChannelDescriptor** simulation_channels ) U32 695 | I2cSimulationDataGenerator::GenerateSimulationData( U64 largest_sample_requested, U32 sample_rate, 696 | SimulationChannelDescriptor** simulation_channels ) 697 | { 698 | U64 adjusted_largest_sample_requested = 699 | AnalyzerHelpers::AdjustSimulationTargetSample( largest_sample_requested, sample_rate, mSimulationSampleRateHz ); 700 | while( mScl->GetCurrentSampleNumber() < adjusted_largest_sample_requested ) 701 | { 702 | CreateI2cTransaction( 0xA0, I2C_READ, mValue++ ); 703 | mI2cSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 10 .0 ) ); // insert 10 bit-periods of idle 704 | } 705 | *simulation_channels = mI2cSimulationChannels.GetArray(); 706 | return mI2cSimulationChannels.GetCount(); 707 | } 708 | 709 | *void SpiSimulationDataGenerator::OutputWord_CPHA1( U64 mosi_data, U64 miso_data )* 710 | 711 | 712 | void SpiSimulationDataGenerator::OutputWord_CPHA1( U64 mosi_data, U64 miso_data ) 713 | { 714 | BitExtractor mosi_bits( mosi_data, mSettings->mShiftOrder, mSettings - > mBitsPerTransfer ); 715 | BitExtractor miso_bits( miso_data, mSettings->mShiftOrder, mSettings - > mBitsPerTransfer ); 716 | U32 count = mSettings->mBitsPerTransfer; 717 | for( U32 i = 0; i < count; i++ ) 718 | { 719 | mClock->Transition(); // data invalid 720 | mMosi->TransitionIfNeeded( mosi_bits.GetNextBit() ); 721 | mMiso->TransitionIfNeeded( miso_bits.GetNextBit() ); 722 | mSpiSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( .5 ) ); 723 | mClock->Transition(); // data valid 724 | mSpiSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( .5 ) ); 725 | } 726 | mMosi->TransitionIfNeeded( BIT_LOW ); 727 | mMiso->TransitionIfNeeded( BIT_LOW ); 728 | mSpiSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 2.0 ) ); 729 | } 730 | 731 | *void SpiSimulationDataGenerator::CreateSpiTransaction()* 732 | 733 | 734 | void SpiSimulationDataGenerator::CreateSpiTransaction() 735 | { 736 | if( mEnable != NULL ) 737 | mEnable->Transition(); 738 | mSpiSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 2.0 ) ); 739 | if( mSettings->mDataValidEdge == AnalyzerEnums::LeadingEdge ) 740 | { 741 | OutputWord_CPHA0( mValue, mValue + 1 ); 742 | mValue++; 743 | OutputWord_CPHA0( mValue, mValue + 1 ); 744 | mValue++; 745 | OutputWord_CPHA0( mValue, mValue + 1 ); 746 | mValue++; 747 | if( mEnable != NULL ) 748 | mEnable->Transition(); 749 | OutputWord_CPHA0( mValue, mValue + 1 ); 750 | mValue++; 751 | } 752 | else 753 | { 754 | OutputWord_CPHA1( mValue, mValue + 1 ); 755 | mValue++; 756 | OutputWord_CPHA1( mValue, mValue + 1 ); 757 | mValue++; 758 | OutputWord_CPHA1( mValue, mValue + 1 ); 759 | mValue++; 760 | if( mEnable != NULL ) 761 | mEnable->Transition(); 762 | OutputWord_CPHA1( mValue, mValue + 1 ); 763 | mValue++; 764 | } 765 | } 766 | 767 | *U32 SpiSimulationDataGenerator::GenerateSimulationData( U64 largest_sample_requested, U32* 768 | *sample_rate, SimulationChannelDescriptor** simulation_channels )* 769 | 770 | 771 | U32 SpiSimulationDataGenerator::GenerateSimulationData( U64 largest_sample_requested, U32 sample_rate, SimulationChannelDescriptor** simulation_channels ) 772 | { 773 | U64 adjusted_largest_sample_requested = 774 | AnalyzerHelpers::AdjustSimulationTargetSample( largest_sample_requested, sample_rate, mSimulationSampleRateHz ); 775 | while( mClock->GetCurrentSampleNumber() < adjusted_largest_sample_requested ) 776 | { 777 | CreateSpiTransaction(); 778 | mSpiSimulationChannels.AdvanceAll( mClockGenerator.AdvanceByHalfPeriod( 10.0 ) ); // insert 10 bit-periods of idle 779 | } 780 | *simulation_channels = mSpiSimulationChannels.GetArray(); 781 | return mSpiSimulationChannels.GetCount(); 782 | } 783 | 784 | **AnalyzerResults** 785 | 786 | After creating your *SimulationDataGenerator* class, working on your *{YourName}AnalyzerResults* files is the next step. 787 | 788 | *AnalyzerResults* is what we use to transform our results into text for display and as well as exported files, etc. 789 | 790 | 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. 791 | 792 | **{YourName}AnalyzerResults.h** 793 | 794 | In addition to the constructor and destructor, there are 5 functions we’ll need to implement. 795 | *AnalyzerResults* is fairly straightforward, so typically we won’t need much in the way of helper functions or member variables. 796 | 797 | Here’s the *SimpleSerialAnalyzerResults* header file. Yours will like very similar, with the only difference typically being the *enums* and/or *defines* you need. 798 | 799 | #ifndef SIMPLESERIAL_ANALYZER_RESULTS 800 | #define SIMPLESERIAL_ANALYZER_RESULTS 801 | 802 | #include 803 | 804 | class SimpleSerialAnalyzer; 805 | class SimpleSerialAnalyzerSettings; 806 | 807 | class SimpleSerialAnalyzerResults : public AnalyzerResults 808 | { 809 | public: 810 | SimpleSerialAnalyzerResults( SimpleSerialAnalyzer* analyzer, 811 | SimpleSerialAnalyzerSettings* settings ); 812 | virtual ~SimpleSerialAnalyzerResults(); 813 | virtual void GenerateBubbleText( U64 frame_index, Channel& channel, DisplayBase 814 | display_base ); 815 | virtual void GenerateExportFile( const char* file, DisplayBase display_base, U32 816 | export_type_user_id ); 817 | virtual void GenerateFrameTabularText(U64 frame_index, DisplayBase display_base ); 818 | virtual void GeneratePacketTabularText( U64 packet_id, DisplayBase display_base ); 819 | virtual void GenerateTransactionTabularText( U64 transaction_id, DisplayBase 820 | display_base ); 821 | protected: //functions 822 | protected: //vars 823 | SimpleSerialAnalyzerSettings* mSettings; 824 | SimpleSerialAnalyzer* mAnalyzer; 825 | }; 826 | #endif //SIMPLESERIAL_ANALYZER_RESULTS 827 | 828 | **{YourName}AnalyzerResults.cpp** 829 | 830 | 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 831 | *SimpleSerialAnalyzerResults.cpp:* 832 | 833 | 834 | SimpleSerialAnalyzerResults::SimpleSerialAnalyzerResults( SimpleSerialAnalyzer* analyzer, 835 | SimpleSerialAnalyzerSettings* settings ) 836 | : AnalyzerResults(), 837 | mSettings( settings ), 838 | mAnalyzer( analyzer ) 839 | { 840 | } 841 | 842 | ***Frames, Packets, and Transactions*** 843 | 844 | 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*. 845 | 846 | 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. 847 | 848 | We’ll get into more detail regarding how to save your results when we describe to your *Analyzer* - derived class. 849 | 850 | ***Frame*** 851 | 852 | A *Frame* is an object, with fairly generic member variables which can be used to save results. Here is the definition of a *Frame*: 853 | 854 | class LOGICAPI Frame 855 | { 856 | public: 857 | Frame(); 858 | Frame( const Frame& frame ); 859 | ~Frame(); 860 | S64 mStartingSampleInclusive; 861 | S64 mEndingSampleInclusive; 862 | U64 mData1; 863 | U64 mData2; 864 | U8 mType; 865 | U8 mFlags; 866 | }; 867 | 868 | A *Frame* represents a piece of information conveyed by your protocol over an expanse of time. The 869 | member variables *mStartingSampleInclusive* and *mEndingSampleInclusive* are the sample numbers for the beginning and end of the *Frame*. Note that Frames may not overlap; they cannot even 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. 870 | 871 | In addition, the *Frame* can carry two 64-bit numbers as 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. 872 | 873 | The *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. 874 | 875 | *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 an 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. 876 | 877 | 878 | #define FRAMING_ERROR_FLAG ( 1 << 0 ) 879 | #define PARITY_ERROR_FLAG ( 1 << 1 ) 880 | 881 | Two flags are reserved by the system, and will produce an error or warning indication on the bubble displaying the *Frame*. 882 | 883 | 884 | #define DISPLAY_AS_ERROR_FLAG ( 1 << 7 ) 885 | #define DISPLAY_AS_WARNING_FLAG ( 1 << 6 ) 886 | 887 | ***void {YourName}AnalyzerResults::GenerateBubbleText( U64 frame_index, Channel& channel,*** 888 | ***DisplayBase display_base )*** 889 | 890 | *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. 891 | 892 | The *frame_index* is the index to use to get the Frame itself – for example: 893 | 894 | 895 | Frame frame = GetFrame( frame_index ); 896 | 897 | 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. 898 | 899 | *display_base* specifies the radix (hex, decimal, binary) that any numerical values should be displayed in. 900 | There are some helper functions provided so you should never have to deal directly with this issue. 901 | 902 | 903 | enum DisplayBase { Binary, Decimal, Hexadecimal, ASCII }; 904 | AnalyzerHelpers::GetNumberString( U64 number, DisplayBase display_base, U32 905 | num_data_bits, char* result_string, U32 result_string_max_length ); 906 | 907 | 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. 908 | 909 | 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”). 910 | 911 | 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. 912 | 913 | Note that to easily concatenate multiple strings, simply provide *AddStringResult* with more strings. 914 | 915 | 916 | void ClearResultStrings(); 917 | void AddResultString( const char* str1, const char* str2 = NULL, const char* str3 = NULL, 918 | const char* str4 = NULL, const char* str5 = NULL, const char* str6 = NULL ); //multiple 919 | strings will be concatenated 920 | 921 | Here’s the Serial Analyzer’s *GenerateBubbleText* function: 922 | 923 | 924 | void SerialAnalyzerResults::GenerateBubbleText( U64 frame_index, Channel& /*channel*/, 925 | DisplayBase display_base ) // unreferenced vars commented out to remove warnings. 926 | { 927 | // we only need to pay attention to 'channel' if we're making bubbles for more than 928 | one channel( as set by AddChannelBubblesWillAppearOn ) ClearResultStrings(); 929 | Frame frame = GetFrame( frame_index ); 930 | bool framing_error = false; 931 | if( ( frame.mFlags & FRAMING_ERROR_FLAG ) != 0 ) 932 | framing_error = true; 933 | bool parity_error = false; 934 | if( ( frame.mFlags & PARITY_ERROR_FLAG ) != 0 ) 935 | parity_error = true; 936 | char number_str[ 128 ]; 937 | AnalyzerHelpers::GetNumberString( frame.mData1, display_base, mSettings - > mBitsPerTransfer, number_str, 128 ); 938 | char result_str[ 128 ]; 939 | if( ( parity_error == true ) || ( framing_error == true ) ) 940 | { 941 | AddResultString( "!" ); 942 | sprintf( result_str, "%s (error)", number_str ); 943 | AddResultString( result_str ); 944 | if( parity_error == true && framing_error == false ) 945 | sprintf( result_str, "%s (parity error)", number_str ); 946 | else if( parity_error == false && framing_error == true ) 947 | sprintf( result_str, "%s (framing error)", number_str ); 948 | else 949 | sprintf( result_str, "%s (framing error & parity error)", number_str ); 950 | AddResultString( result_str ); 951 | } 952 | else 953 | { 954 | AddResultString( number_str ); 955 | } 956 | } 957 | 958 | ***void {YourName}AnalyzerResults::GenerateExportFile( const char* file, DisplayBase*** 959 | ***display_base, U32 export_type_user_id )*** 960 | 961 | 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. 962 | The *file* parameter is string containing the full path of the file you should create and write to with the analyzer results. 963 | 964 | 965 | std::ofstream file_stream( file, std::ios::out ); 966 | 967 | The *display_base* parameter contains the radix which should be used to display numerical results. (See *GenerateBubbleText* for more detail) 968 | 969 | The *export_type_user_id* parameter is the id associated with the export-type the user selected. You 970 | 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. 971 | 972 | 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. 973 | 974 | 975 | U64 trigger_sample = mAnalyzer->GetTriggerSample(); 976 | U32 sample_rate = mAnalyzer->GetSampleRate(); 977 | static void AnalyzerHelpers::GetTimeString( U64 sample, U64 trigger_sample, U32 978 | sample_rate_hz, char* result_string, U32 result_string_max_length ); 979 | 980 | Other than that, the implementation is pretty straightforward. Here is an example from 981 | *SerialAnalyzerResults.cpp*: 982 | 983 | 984 | void SerialAnalyzerResults::GenerateExportFile( const char* file, DisplayBase display_base, U32 /*export_type_user_id*/ ) 985 | { 986 | // export_type_user_id is only important if we have more than one export type. 987 | std::ofstream file_stream( file, std::ios::out ); 988 | U64 trigger_sample = mAnalyzer->GetTriggerSample(); 989 | U32 sample_rate = mAnalyzer->GetSampleRate(); 990 | file_stream << "Time [s],Value,Parity Error,Framing Error" << std::endl; 991 | U64 num_frames = GetNumFrames(); 992 | for( U32 i = 0; i < num_frames; i++ ) 993 | { 994 | Frame frame = GetFrame( i ); 995 | // static void GetTimeString( U64 sample, U64 trigger_sample, U32 996 | sample_rate_hz, char* result_string, U32 result_string_max_length ); 997 | char time_str[ 128 ]; 998 | AnalyzerHelpers::GetTimeString( frame.mStartingSampleInclusive, trigger_sample, sample_rate, time_str, 128 ); 999 | char number_str[ 128 ]; 1000 | AnalyzerHelpers::GetNumberString( frame.mData1, display_base, mSettings - > mBitsPerTransfer, number_str, 128 ); 1001 | file_stream << time_str << "," << number_str; 1002 | if( ( frame.mFlags & FRAMING_ERROR_FLAG ) != 0 ) 1003 | file_stream << ",Error,"; 1004 | else 1005 | file_stream << ","; 1006 | if( ( frame.mFlags & FRAMING_ERROR_FLAG ) != 0 ) 1007 | file_stream << "Error"; 1008 | file_stream << std::endl; 1009 | if( UpdateExportProgressAndCheckForCancel( i, num_frames ) == true ) 1010 | { 1011 | file_stream.close(); 1012 | return; 1013 | } 1014 | } 1015 | file_stream.close(); 1016 | } 1017 | 1018 | ***void SerialAnalyzerResults::GenerateFrameTabularText( U64 frame_index, DisplayBase*** 1019 | ***display_base )*** 1020 | 1021 | *GenerateFrameTabularText* is for producing text for tabular display which is not yet implemented as of 1.1.5. You can safely leave it empty. 1022 | 1023 | *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. 1024 | 1025 | Here is an example from *SerialAnalyzerResults.cpp*: 1026 | 1027 | 1028 | void SerialAnalyzerResults::GenerateFrameTabularText( U64 frame_index, DisplayBase display_base ) 1029 | { 1030 | Frame frame = GetFrame( frame_index ); 1031 | ClearResultStrings(); 1032 | bool framing_error = false; 1033 | if( ( frame.mFlags & FRAMING_ERROR_FLAG ) != 0 ) 1034 | framing_error = true; 1035 | bool parity_error = false; 1036 | if( ( frame.mFlags & PARITY_ERROR_FLAG ) != 0 ) 1037 | parity_error = true; 1038 | char number_str[ 128 ]; 1039 | AnalyzerHelpers::GetNumberString( frame.mData1, display_base, mSettings - > mBitsPerTransfer, number_str, 128 ); 1040 | char result_str[ 128 ]; 1041 | if( parity_error == false && framing_error == false ) 1042 | { 1043 | AddResultString( number_str ); 1044 | } 1045 | else if( parity_error == true && framing_error == false ) 1046 | { 1047 | sprintf( result_str, "%s (parity error)", number_str ); 1048 | AddResultString( result_str ); 1049 | } 1050 | else if( parity_error == false && framing_error == true ) 1051 | { 1052 | sprintf( result_str, "%s (framing error)", number_str ); 1053 | AddResultString( result_str ); 1054 | } 1055 | else 1056 | { 1057 | sprintf( result_str, "%s (framing error & parity error)", number_str ); 1058 | AddResultString( result_str ); 1059 | } 1060 | } 1061 | 1062 | ***void SerialAnalyzerResults::GeneratePacketTabularText( U64 packet_id, DisplayBase*** 1063 | ***display_base )*** 1064 | 1065 | 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. 1066 | 1067 | ***void SerialAnalyzerResults::GenerateTransactionTabularText ( U64 transaction_id,*** 1068 | ***DisplayBase display_base )*** 1069 | 1070 | 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. 1071 | 1072 | **Analyzer** 1073 | 1074 | 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. 1075 | 1076 | **{YourName}Analyzer.h** 1077 | 1078 | In addition to the constructor and destructor, here are the functions you’ll need to implement: 1079 | 1080 | 1081 | virtual void WorkerThread(); 1082 | virtual U32 GenerateSimulationData( U64 newest_sample_requested, U32 sample_rate, 1083 | SimulationChannelDescriptor** simulation_channels ); 1084 | virtual U32 GetMinimumSampleRateHz(); 1085 | virtual const char* GetAnalyzerName() const; 1086 | virtual bool NeedsRerun(); 1087 | extern "C" ANALYZER_EXPORT const char* __cdecl GetAnalyzerName(); 1088 | extern "C" ANALYZER_EXPORT Analyzer* __cdecl CreateAnalyzer( ); 1089 | extern "C" ANALYZER_EXPORT void __cdecl DestroyAnalyzer( Analyzer* analyzer ); 1090 | 1091 | You’ll also need these member variables: 1092 | 1093 | 1094 | std::auto_ptr< {YourName}AnalyzerSettings > mSettings; 1095 | std::auto_ptr< {YourName}AnalyzerResults > mResults; 1096 | {YourName}SimulationDataGenerator mSimulationDataGenerator; 1097 | bool mSimulationInitialized; 1098 | 1099 | You’ll also need one *AnalyzerChannelData* raw pointer for each input. For SerialAnalyzer, for example, we need 1100 | 1101 | AnalyzerChannelData* mSerial; 1102 | 1103 | As you develop your analyzer, you’ll add additional member variables and helper functions depending on your analysis needs. 1104 | 1105 | **{YourName}Analyzer.cpp** 1106 | 1107 | ***Constructor*** 1108 | 1109 | Your constructor will look something like this 1110 | 1111 | {YourName}Analyzer::{YourName}Analyzer() 1112 | : Analyzer(), 1113 | mSettings( new {YourName}AnalyzerSettings() ), 1114 | mSimulationInitialized( false ) 1115 | { 1116 | SetAnalyzerSettings( mSettings.get() ); 1117 | } 1118 | 1119 | Note that here you’re calling the base class constructor, *newing* your *AnalyzerSettings* - derived class, and providing the base class with a pointer to your *AnalyzerSettings* - derived object. 1120 | 1121 | ***Destructor*** 1122 | 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. 1123 | 1124 | ***void {YourName}Analyzer::WorkerThread()*** 1125 | 1126 | 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. 1127 | 1128 | ***bool {YourName}Analyzer::NeedsRerun()*** 1129 | 1130 | Generally speaking, just return *false* in this function. For more detail, read on. 1131 | 1132 | This function is called when your analyzer has finished analyzing the collected data (this condition is detected from outside your analyzer.) 1133 | 1134 | 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. 1135 | 1136 | If you return *true* , that’s all there is to do. Your analyzer will be re-run automatically. 1137 | 1138 | ***U32 {YourName}Analyzer::GenerateSimulationData( U64 minimum_sample_index, U32*** 1139 | ***device_sample_rate, SimulationChannelDescriptor***** *simulation_channels )* 1140 | 1141 | 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. 1142 | 1143 | 1144 | U32 {YourName}Analyzer::GenerateSimulationData( U64 minimum_sample_index, U32 device_sample_rate, 1145 | SimulationChannelDescriptor** simulation_channels ) 1146 | { 1147 | if( mSimulationInitialized == false ) 1148 | { 1149 | mSimulationDataGenerator.Initialize( GetSimulationSampleRate(), mSettings.get() ); 1150 | mSimulationInitialized = true; 1151 | } 1152 | return mSimulationDataGenerator.GenerateSimulationData( minimum_sample_index, device_sample_rate, simulation_channels ); 1153 | } 1154 | 1155 | ***U32 SerialAnalyzer::GetMinimumSampleRateHz()*** 1156 | 1157 | This function is called to see if the user’s selected sample rate is sufficient to get good results for this analyzer. 1158 | 1159 | For Serial, for instance, we would like the sample rate to be x4 higher that the serial bit rate. 1160 | 1161 | For other, typically synchronous, protocols, you may not ask the user to enter the data’s bit rate – 1162 | therefore you can’t know ahead of time what sample rate is required. In that case, you can either 1163 | return the smallest sample rate (25000), or return a value that will be fast enough for your simulation. 1164 | 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. 1165 | 1166 | The rule of thumb is to require oversampling by x4 if you know the data’s bit rate, otherwise just return 25000. 1167 | 1168 | Here’s what we do in *SerialAnalyzer.cpp* 1169 | 1170 | 1171 | U32 SerialAnalyzer::GetMinimumSampleRateHz() 1172 | { 1173 | return mSettings->mBitRate * 4; 1174 | } 1175 | 1176 | ***const char* {YourName}Analyzer::GetAnalyzerName() const*** 1177 | 1178 | Simply return the name you would like to see in the “Add Analyzer” drop down. 1179 | 1180 | 1181 | return "Async Serial"; 1182 | 1183 | ***const char* GetAnalyzerName()*** 1184 | 1185 | Return the same string as in the previous function. 1186 | 1187 | 1188 | return "Async Serial"; 1189 | 1190 | ***Analyzer* CreateAnalyzer()*** 1191 | 1192 | Return a pointer to a new instance of your Analyzer-derived class. 1193 | 1194 | 1195 | return new {YourName}Analyzer(); 1196 | 1197 | ***void DestroyAnalyzer( Analyzer* analyzer )*** 1198 | 1199 | Simply call *delete* on the provided pointer. 1200 | 1201 | 1202 | delete analyzer; 1203 | 1204 | ***void {YourName}Analyzer::WorkerThread()*** 1205 | 1206 | Ok, now that everything else is taken care of, let’s look at the most important part of the analyzer in 1207 | detail. 1208 | 1209 | First, we’ll *new* our *AnalyzerResults* - derived object. 1210 | 1211 | 1212 | mResults.reset( new {YourName}AnalyzerResults( this, mSettings.get() ) ); 1213 | 1214 | Well provide a pointer to our results to the base class: 1215 | 1216 | 1217 | SetAnalyzerResults( mResults.get() ); 1218 | 1219 | 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. 1220 | 1221 | 1222 | mResults->AddChannelBubblesWillAppearOn( mSettings->mInputChannel ); 1223 | 1224 | We’ll probably want to know (and save in a member variable) the sample rate. 1225 | 1226 | 1227 | mSampleRateHz = GetSampleRate(); 1228 | 1229 | 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. 1230 | 1231 | 1232 | mSerial = GetAnalyzerChannelData( mSettings->mInputChannel ); 1233 | 1234 | We’ve now ready to start traversing the data, and recording results. We’ll look at each of these tasks in turn. 1235 | 1236 | ***First, a word of advice*** 1237 | 1238 | 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. 1239 | 1240 | ***AnalyzerChannelData*** 1241 | 1242 | *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. 1243 | 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). 1244 | 1245 | ***AnalyzerChannelData – State*** 1246 | 1247 | If we’re not sure where are in the stream, or if the input is currently high or low, we can just ask: 1248 | 1249 | 1250 | U64 GetSampleNumber(); 1251 | BitState GetBitState(); 1252 | 1253 | ***AnalyzerChannelData – Basic Traversal*** 1254 | 1255 | We’ll need some ability to move forward in the stream. We have three basic ways to do this. 1256 | 1257 | *U32 Advance( U32 num_samples );* 1258 | 1259 | We can move forward in the stream by a specific number of samples. This function will return how 1260 | many times the input toggled (changed from a high to a low, or low to a high) to make this move. 1261 | 1262 | *U32 AdvanceToAbsPosition( U64 sample_number );* 1263 | 1264 | 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. 1265 | 1266 | *void AdvanceToNextEdge();* 1267 | 1268 | 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. 1269 | 1270 | ***AnalyzerChannelData – Advanced Traversal (looking ahead without moving)*** 1271 | 1272 | As you develop your analyzer(s) certain tasks may come up that call for more sophisticated traversal. 1273 | Here are some ways of doing it. 1274 | 1275 | *U64 GetSampleOfNextEdge();* 1276 | 1277 | 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. 1278 | 1279 | *bool WouldAdvancingCauseTransition( U32 num_samples );* 1280 | 1281 | 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. 1282 | 1283 | *bool WouldAdvancingToAbsPositionCauseTransition( U64 sample_number );* 1284 | 1285 | This is the same as the prior function, except you provide the absolute position. 1286 | 1287 | ***AnalyzerChannelData – Keeping track of the smallest pulse.*** 1288 | 1289 | 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) 1290 | 1291 | 1292 | void TrackMinimumPulseWidth(); 1293 | U64 GetMinimumPulseWidthSoFar(); 1294 | 1295 | ***Filling in and saving Frames*** 1296 | 1297 | Using the above *AnalyzerChannelData* class, we can now move through a channel’s data and analyze it. 1298 | Now let’s discus how to store results. 1299 | 1300 | We described *Frames* when talking about the *AnalyzerResults* - derived class. A *Frame* is the basic unit results are saved in. *Frames* have: 1301 | 1302 | 1303 | -  starting and ending time (starting and ending sample number), 1304 | -  x2 64-bit values to save results in 1305 | -  an 8-bit type variable – to specify the type of Frame 1306 | -  an 8-bit flags variable – to specify Yes/No types of results. 1307 | 1308 | When we have analyzed far enough, and now have a complete *Frame* we would like to record, we do it like this: 1309 | 1310 | 1311 | Frame frame; 1312 | frame.mStartingSampleInclusive = first_sample_in_frame; 1313 | frame.mEndingSampleInclusive = last_sample_in_frame; 1314 | frame.mData1 = the_data_we_collected; 1315 | //frame.mData2 = some_more_data_we_collected; 1316 | //frame.mType = OurTypeEnum; //unless we only have one type of frame 1317 | frame.mFlags = 0; 1318 | if( such_and_such_error == true ) 1319 | frame.mFlags |= SUCH_AND_SUCH_ERROR_FLAG | DISPLAY_AS_ERROR_FLAG; 1320 | if( such_and_such_warning == true ) 1321 | frame.mFlags |= SUCH_AND_SUCH_WARNING_FLAG | DISPLAY_AS_WARNING_FLAG; 1322 | mResults->AddFrame( frame ); 1323 | mResults->CommitResults(); 1324 | ReportProgress( frame.mEndingSampleInclusive ); 1325 | 1326 | 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* ). 1327 | Part of the *Frame* is expected to be filled in correctly because it’s used automatically by other systems. In particular, 1328 | 1329 | -  mStartingSampleInclusive 1330 | -  mEndingSampleInclusive 1331 | -  mFlags 1332 | 1333 | should be filled in properly. 1334 | 1335 | Other parts of the *Frame* are only there so you can create text descriptions or export the data to a 1336 | desired format. 1337 | 1338 | 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). 1339 | 1340 | Immediately after adding a *Frame* , call *CommitResults*. This makes the *Frame* accessible to the external system. 1341 | 1342 | Also call the *Analyzer* base class *ReportProgress*. Provide it with it the largest sample number you have processed. 1343 | 1344 | ***Adding Markers*** 1345 | 1346 | 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. 1347 | 1348 | 1349 | void AddMarker( U64 sample_number, MarkerType marker_type, Channel& channel ); 1350 | 1351 | For example, from *SerialAnalyzer.cpp* : 1352 | 1353 | mResults->AddMarker( marker_location, AnalyzerResults::Dot, mSettings->mInputChannel ); 1354 | 1355 | Currently, the available graphical artifacts are 1356 | 1357 | 1358 | enum MarkerType { Dot, ErrorDot, Square, ErrorSquare, UpArrow, DownArrow, X, ErrorX, 1359 | Start, Stop, One, Zero }; 1360 | 1361 | Like *Frames* , you must add *Markers* in order. 1362 | 1363 | *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. 1364 | 1365 | ***Packets and Transactions*** 1366 | 1367 | *Packets* and *Transactions* are only moderately supported as of now, but they will be becoming more prominent in the software. 1368 | 1369 | *Packets* are sequential collections of *Frames*. Grouping *Frames* into *Packets* as you create them is easy: 1370 | 1371 | 1372 | U64 CommitPacketAndStartNewPacket(); 1373 | void CancelPacketAndStartNewPacket(); 1374 | 1375 | 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 1376 | *CancelPacketAndStartNewPacket*. 1377 | 1378 | Note that *CommitPacketAndStartNewPacket* returns an packet id. You can use this id to assign a 1379 | particular packet to a transaction. 1380 | 1381 | 1382 | void AddPacketToTransaction( U64 transaction_id, U64 packet_id ); 1383 | 1384 | The *transaction_id* is an ID you generate yourself. 1385 | 1386 | 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. 1387 | 1388 | *Packets* on the other hand tend to be fairly applicable for lower level protocols, although not in entirely the same ways. For example: 1389 | 1390 | -  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) 1391 | -  SPI Analyzer – packets are used to delimit between periods when the enable line is active. 1392 | -  I2C Analyzer – packets are used to delimit periods between a start/restart and a stop. 1393 | -  CAN Analyzer – packets are used to represent, well, CAN packets. 1394 | -  UNI/O – packets are used to group Frames in a UNI/O sequence. 1395 | -  1 - Wire – packets are used to group 1-Wire sequences. 1396 | -  I2S/PCM – packets aren’t used. 1397 | 1398 | 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. 1399 | 1400 | 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. 1401 | 1402 | --------------------------------------------------------------------------------