/* --COPYRIGHT--,TI
 *MSP Source and Object Code Software License Agreement
 *
 *
 *IMPORTANT - PLEASE CAREFULLY READ THE FOLLOWING LICENSE AGREEMENT, WHICH IS LEGALLY BINDING.  AFTER YOU READ IT, YOU WILL BE ASKED WHETHER YOU ACCEPT AND AGREE TO ITS TERMS.  DO NOT CLICK  "I ACCEPT" UNLESS: (1) YOU WILL USE THE LICENSED MATERIALS FOR YOUR OWN BENEFIT AND PERSONALLY ACCEPT, AGREE TO AND INTEND TO BE BOUND BY THESE TERMS; OR (2) YOU ARE AUTHORIZED TO, AND INTEND TO BE BOUND BY, THESE TERMS ON BEHALF OF YOUR COMPANY.
 *
 *
 *Important - Read carefully: This Source and Object Code Software License Agreement ("Agreement") is a legal agreement between you and Texas Instruments Incorporated ("TI").  In this Agreement "you" means you personally if you will exercise the rights granted for your own benefit, but it means your company (or you on behalf of your company) if you will exercise the rights granted for your company's benefit.  The "Licensed Materials" subject to this Agreement include the software programs and any associated electronic documentation (in each case, in whole or in part) that accompany this Agreement, are set forth in the applicable software manifest and you access "on-line", as well as any updates or upgrades to such software programs or documentation, if any, provided to you at TI's sole discretion.  The Licensed Materials are specifically designed and licensed for use solely and exclusively with MSP microcontroller devices manufactured by or for TI ("TI Devices").  By installing, copying or otherwise using the Licensed Materials you agree to abide by the provisions set forth herein.  This Agreement is displayed for you to read prior to using the Licensed Materials.  If you choose not to accept or agree with these provisions, do not download or install the Licensed Materials.  
 *
 *Note Regarding Possible Access to Other Licensed Materials:  The Licensed Materials may be bundled with software and associated electronic documentation, if any, licensed under terms other than the terms of this Agreement (in whole or in part, "Other Licensed Materials"), including, for example Open Source Software and/or TI-owned or third party Proprietary Software licensed under such other terms.  "Open Source Software" means any software licensed under terms requiring that (A) other software ("Proprietary Software") incorporated, combined or distributed with such software or developed using such software: (i) be disclosed or distributed in source code form; or (ii) otherwise be licensed on terms inconsistent with the terms of this Agreement, including but not limited to permitting use of the Proprietary Software on or with devices other than TI Devices, or (B) require the owner of Proprietary Software to license any of its patents to users of the Open Source Software and/or Proprietary Software incorporated, combined or distributed with such Open Source Software or developed using such Open Source Software.  
 *
 *If by accepting this Agreement, you gain access to Other Licensed Materials, they will be listed in the applicable software manifest.  Your use of the Other Licensed Materials is subject to the applicable other licensing terms acknowledgements and disclaimers as specified in the applicable software manifest and/or identified or included with the Other Licensed Materials in the software bundle.  For clarification, this Agreement does not limit your rights under, or grant you rights that supersede, the terms of any applicable Other Licensed Materials license agreement.  If any of the Other Licensed Materials is Open Source Software that has been provided to you in object code only under terms that obligate TI to provide to you or show you where you can access the source code versions of such Open Source Software, TI will provide to you, or show you where you can access, such source code if you contact TI at Texas Instruments Incorporated, 12500 TI Boulevard, Mail Station 8638, Dallas, Texas 75243, Attention: Contracts Manager, Embedded Processing.  In the event you choose not to accept or agree with the terms in any applicable Other Licensed Materials license agreement, you must terminate this Agreement.
 *
 *1.    License Grant and Use Restrictions.
 *
 *a.    Licensed Materials License Grant.  Subject to the terms of this Agreement, TI hereby grants to you a limited, non-transferable, non-exclusive, non-assignable, non-sublicensable, fully paid-up and royalty-free license to:
 *
 *            i.    Limited Source Code License:  make copies, prepare derivative works, display internally and use internally the Licensed Materials provided to you in source code for the sole purpose of developing object and executable versions of such Licensed Materials, or any derivative thereof, that execute solely and exclusively on TI Devices, for end use in Licensee Products, and maintaining and supporting such Licensed Materials, or any derivative thereof, and Licensee Products.  For purposes of this Agreement, "Licensee Product" means a product that consists of both hardware, including one or more TI Devices, and software components, including only executable versions of the Licensed Materials that execute solely and exclusively on such TI Devices.
 *
 *            ii.    Object Code Evaluation, Testing and Use License:  make copies, display internally, distribute internally and use internally the Licensed Materials in object code for the sole purposes of evaluating and testing the Licensed Materials and designing and developing Licensee Products, and maintaining and supporting the Licensee Products;  
 *
 *            iii.    Demonstration License:  demonstrate to third parties the Licensed Materials executing solely and exclusively on TI Devices as they are used in Licensee Products, provided that such Licensed Materials are demonstrated in object or executable versions only and 
 *
 *        iv.    Production and Distribution License:  make, use, import, export and otherwise distribute the Licensed Materials as part of a Licensee Product, provided that such Licensee Products include only embedded executable copies of such Licensed Materials that execute solely and exclusively on TI Devices.
 *
 *    b.    Contractors.  The licenses granted to you hereunder shall include your on-site and off-site contractors (either an individual or entity), while such contractors are performing work for or providing services to you, provided that such contractors have executed work-for-hire agreements with you containing applicable terms and conditions consistent with the terms and conditions set forth in this Agreement and provided further that you shall be liable to TI for any breach by your contractors of this Agreement to the same extent as you would be if you had breached the Agreement yourself. 
 *
 *    c.    No Other License.  Nothing in this Agreement shall be construed as a license to any intellectual property rights of TI other than those rights embodied in the Licensed Materials provided to you by TI.  EXCEPT AS PROVIDED HEREIN, NO OTHER LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY OTHER TI INTELLECTUAL PROPERTY RIGHTS IS GRANTED HEREIN.
 *
 *    d.    Covenant not to Sue.  During the term of this Agreement, you agree not to assert a claim against TI or its licensees that the Licensed Materials infringe your intellectual property rights.
 *
 *    e.    Restrictions.  You shall maintain the source code versions of the Licensed Materials under password control protection and shall not disclose such source code versions of the Licensed Materials, to any person other than your employees and contractors whose job performance requires access.  You shall not use the Licensed Materials with a processing device other than a TI Device, and you agree that any such unauthorized use of the Licensed Materials is a material breach of this Agreement.  You shall not use the Licensed Materials for the purpose of analyzing or proving infringement of any of your patents by either TI or TI's customers.  Except as expressly provided in this Agreement, you shall not copy, publish, disclose, display, provide, transfer or make available the Licensed Materials to any third party and you shall not sublicense, transfer, or assign the Licensed Materials or your rights under this Agreement to any third party.  You shall not mortgage, pledge or encumber the Licensed Materials in any way.  You may use the Licensed Materials with Open Source Software or with software developed using Open Source Software tools provided you do not incorporate, combine or distribute the Licensed Materials in a manner that subjects the Licensed Materials to any license obligations or any other intellectual property related terms of any license governing such Open Source Software. 
 *
 *    f.    Termination.  This Agreement is effective on the date the Licensed Materials are delivered to you together with this Agreement and will remain in full force and effect until terminated.  You may terminate this Agreement at any time by written notice to TI.  Without prejudice to any other rights, if you fail to comply with the terms of this Agreement or you are acquired, TI may terminate your right to use the Licensed Materials upon written notice to you.  Upon termination of this Agreement, you will destroy any and all copies of the Licensed Materials in your possession, custody or control and provide to TI a written statement signed by your authorized representative certifying such destruction. Except for Sections 1(a), 1(b) and 1(d), all provisions of this Agreement shall survive termination of this Agreement. 
 *
 *2.    Licensed Materials Ownership.  The Licensed Materials are licensed, not sold to you, and can only be used in accordance with the terms of this Agreement.  Subject to the licenses granted to you pursuant to this Agreement, TI and its licensors own and shall continue to own all right, title and interest in and to the Licensed Materials, including all copies thereof.  You agree that all fixes, modifications and improvements to the Licensed Materials conceived of or made by TI that are based, either in whole or in part, on your feedback, suggestions or recommendations are the exclusive property of TI and all right, title and interest in and to such fixes, modifications or improvements to the Licensed Materials will vest solely in TI.  Moreover, you acknowledge and agree that when your independently developed software or hardware components are combined, in whole or in part, with the Licensed Materials, your right to use the combined work that includes the Licensed Materials remains subject to the terms and conditions of this Agreement.
 *
 *3.    Intellectual Property Rights.  
 *
 *    a.    The Licensed Materials contain copyrighted material, trade secrets and other proprietary information of TI and its licensors and are protected by copyright laws, international copyright treaties, and trade secret laws, as well as other intellectual property laws.  To protect TI's and its licensors' rights in the Licensed Materials, you agree, except as specifically permitted by statute by a provision that cannot be waived by contract, not to "unlock", decompile, reverse engineer, disassemble or otherwise translate to a human-perceivable form any portions of the Licensed Materials provided to you in object code format only, nor permit any person or entity to do so.  You shall not remove, alter, cover, or obscure any confidentiality, trade secret, trade mark, patent, copyright or other proprietary notice or other identifying marks or designs from any component of the Licensed Materials and you shall reproduce and include in all copies of the Licensed Materials the copyright notice(s) and proprietary legend(s) of TI and its licensors as they appear in the Licensed Materials.  TI reserves all rights not specifically granted under this Agreement.
 *
 *    b.    Certain Licensed Materials may be based on industry recognized standards or software programs published by industry recognized standards bodies and certain third parties may claim to own patents, copyrights, and other intellectual property rights that cover implementation of those standards.  You acknowledge and agree that this Agreement does not convey a license to any such third party patents, copyrights, and other intellectual property rights and that you are solely responsible for any patent, copyright, or other intellectual property right claim that relates to your use or distribution of the Licensed Materials or your use or distribution of your products that include or incorporate the Licensed Materials.  Moreover, you acknowledge that you are responsible for any fees or royalties that may be payable to any third party based on such third party's interests in the Licensed Materials or any intellectual property rights that cover implementation of any industry recognized standard, any software program published by any industry recognized standards bodies or any other proprietary technology.
 *
 *4.    Confidential Information.  You acknowledge and agree that the Licensed Materials contain trade secrets and other confidential information of TI and its licensors.  You agree to use the Licensed Materials solely within the scope of the licenses set forth herein, to maintain the Licensed Materials in strict confidence, to use at least the same procedures and degree of care that you use to prevent disclosure of your own confidential information of like importance but in no instance less than reasonable care, and to prevent disclosure of the Licensed Materials to any third party, except as may be necessary and required in connection with your rights and obligations hereunder; provided, however, that you may not provide the Licensed Materials to any business organization or group within your company or to customers or contractors that design or manufacture semiconductors unless TI gives written consent.  You agree to obtain executed confidentiality agreements with your employees and contractors having access to the Licensed Materials and to diligently take steps to enforce such agreements in this respect.  TI may disclose your contact information to TI's licensors.
 *
 *5.    Warranties and Limitations.  THE LICENSED MATERIALS ARE PROVIDED "AS IS".  FURTHERMORE, YOU ACKNOWLEDGE AND AGREE THAT THE LICENSED MATERIALS HAVE NOT BEEN TESTED OR CERTIFIED BY ANY GOVERNMENT AGENCY OR INDUSTRY REGULATORY ORGANIZATION OR ANY OTHER THIRD PARTY ORGANIZATION.  YOU AGREE THAT PRIOR TO USING, INCORPORATING OR DISTRIBUTING THE LICENSED MATERIALS IN OR WITH ANY COMMERCIAL PRODUCT THAT YOU WILL THOROUGHLY TEST THE PRODUCT AND THE FUNCTIONALITY OF THE LICENSED MATERIALS IN OR WITH THAT PRODUCT AND BE SOLELY RESPONSIBLE FOR ANY PROBLEMS OR FAILURES.
 *
 *TI AND ITS LICENSORS MAKE NO WARRANTY OR REPRESENTATION, EITHER EXPRESS, IMPLIED OR STATUTORY, REGARDING THE LICENSED MATERIALS, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT OF ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADE SECRETS OR OTHER INTELLECTUAL PROPERTY RIGHTS.  YOU AGREE TO USE YOUR INDEPENDENT JUDGMENT IN DEVELOPING YOUR PRODUCTS.  NOTHING CONTAINED IN THIS AGREEMENT WILL BE CONSTRUED AS A WARRANTY OR REPRESENTATION BY TI TO MAINTAIN PRODUCTION OF ANY TI SEMICONDUCTOR DEVICE OR OTHER HARDWARE OR SOFTWARE WITH WHICH THE LICENSED MATERIALS MAY BE USED.  
 *
 *IN NO EVENT SHALL TI OR ITS LICENSORS, BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL, PUNITIVE OR CONSEQUENTIAL DAMAGES, HOWEVER CAUSED, ON ANY THEORY OF LIABILITY, IN CONNECTION WITH OR ARISING OUT OF THIS AGREEMENT OR THE USE OF THE LICENSED MATERIALS REGARDLESS OF WHETHER TI HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.  EXCLUDED DAMAGES INCLUDE, BUT ARE NOT LIMITED TO, COST OF REMOVAL OR REINSTALLATION, OUTSIDE COMPUTER TIME, LABOR COSTS, LOSS OF DATA, LOSS OF GOODWILL, LOSS OF PROFITS, LOSS OF SAVINGS, OR LOSS OF USE OR INTERRUPTION OF BUSINESS.  IN NO EVENT WILL TI'S OR ITS LICENSORS' AGGREGATE LIABILITY UNDER THIS AGREEMENT OR ARISING OUT OF YOUR USE OF THE LICENSED MATERIALS EXCEED FIVE HUNDRED U.S. DOLLARS (US$500).
 *
 *    Because some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages or limitation on how long an implied warranty lasts, the above limitations or exclusions may not apply to you.
 *
 *6.    Indemnification Disclaimer.  YOU ACKNOWLEDGE AND AGREE THAT TI SHALL NOT BE LIABLE FOR AND SHALL NOT DEFEND OR INDEMNIFY YOU AGAINST ANY THIRD PARTY INFRINGEMENT CLAIM THAT RELATES TO OR IS BASED ON YOUR MANUFACTURE, USE, OR DISTRIBUTION OF THE LICENSED MATERIALS OR YOUR MANUFACTURE, USE, OFFER FOR SALE, SALE, IMPORTATION OR DISTRIBUTION OF YOUR PRODUCTS THAT INCLUDE OR INCORPORATE THE LICENSED MATERIALS.
 *
 *7.    No Technical Support.  TI and its licensors are under no obligation to install, maintain or support the Licensed Materials.  
 *
 *8.    Notices.  All notices to TI hereunder shall be delivered to Texas Instruments Incorporated, 12500 TI Boulevard, Mail Station 8638, Dallas, Texas 75243, Attention: Contracts Manager - Embedded Processing, with a copy to Texas Instruments Incorporated, 13588 N. Central Expressway, Mail Station 3999, Dallas, Texas 75243, Attention: Law Department - Embedded Processing.  All notices shall be deemed served when received by TI. 
 *
 *9.    Export Control.  The Licensed Materials are subject to export control under the U.S. Commerce Department's Export Administration Regulations ("EAR").  Unless prior authorization is obtained from the U.S. Commerce Department, neither you nor your subsidiaries shall export, re-export, or release, directly or indirectly (including, without limitation, by permitting the Licensed Materials to be downloaded), any technology, software, or software source code, received from TI, or export, directly or indirectly, any direct product of such technology, software, or software source code, to any person, destination or country to which the export, re-export, or release of the technology, software, or software source code, or direct product is prohibited by the EAR.  You represent and warrant that you (i) are not located in, or under the control of, a national or resident of Cuba, Iran, North Korea, Sudan and Syria or any other country subject to a U.S. goods embargo; (ii) are not on the U.S. Treasury Department's List of Specially Designated Nationals or the U.S. Commerce Department's Denied Persons List or Entity List; and (iii) will not use the Licensed Materials or transfer the Licensed Materials for use in any military, nuclear, chemical or biological weapons, or missile technology end-uses.  Any software export classification made by TI shall not be construed as a representation or warranty regarding the proper export classification for such software or whether an export license or other documentation is required for the exportation of such software.
 *
 *10.    Governing Law and Severability; Waiver.  This Agreement will be governed by and interpreted in accordance with the laws of the State of Texas, without reference to conflict of laws principles.  If for any reason a court of competent jurisdiction finds any provision of the Agreement to be unenforceable, that provision will be enforced to the maximum extent possible to effectuate the intent of the parties, and the remainder of the Agreement shall continue in full force and effect.  This Agreement shall not be governed by the United Nations Convention on Contracts for the International Sale of Goods, or by the Uniform Computer Information Transactions Act (UCITA).  The parties agree that non-exclusive jurisdiction for any dispute arising out of or relating to this Agreement lies within the courts located in the State of Texas.  Notwithstanding the foregoing, any judgment may be enforced in any United States or foreign court, and either party may seek injunctive relief in any United States or foreign court.  Failure by TI to enforce any provision of this Agreement shall not be deemed a waiver of future enforcement of that or any other provision in this Agreement or any other agreement that may be in place between the parties.
 *
 *11.    PRC Provisions.  If you are located in the People's Republic of China ("PRC") or if the Licensed Materials will be sent to the PRC, the following provisions shall apply:  
 *
 *    a.    Registration Requirements.  You shall be solely responsible for performing all acts and obtaining all approvals that may be required in connection with this Agreement by the government of the PRC, including but not limited to registering pursuant to, and otherwise complying with, the PRC Measures on the Administration of Software Products, Management Regulations on Technology Import-Export, and Technology Import and Export Contract Registration Management Rules.  Upon receipt of such approvals from the government authorities, you shall forward evidence of all such approvals to TI for its records.  In the event that you fail to obtain any such approval or registration, you shall be solely responsible for any and all losses, damages or costs resulting therefrom, and shall indemnify TI for all such losses, damages or costs.
 *
 *b.    Governing Language.  This Agreement is written and executed in the English language and shall be authoritative and controlling, whether or not translated into a language other than English to comply with law or for reference purposes.  If a translation of this Agreement is required for any purpose, including but not limited to registration of the Agreement pursuant to any governmental laws, regulations or rules, you shall be solely responsible for creating such translation.  
 *
 *12.    Contingencies.    TI shall not be in breach of this Agreement and shall not be liable for any non-performance or delay in performance if such non-performance or delay is due to a force majeure event or other circumstances beyond TI's reasonable control.
 *
 *13.        Entire Agreement.  This is the entire agreement between you and TI and this Agreement supersedes any prior agreement between the parties related to the subject matter of this Agreement.  Notwithstanding the foregoing, any signed and effective software license agreement relating to the subject matter hereof and stating expressly that such agreement shall control regardless of any subsequent click-wrap, shrink-wrap or web-wrap, shall supersede the terms of this Agreement.  No amendment or modification of this Agreement will be effective unless in writing and signed by a duly authorized representative of TI.  You hereby warrant and represent that you have obtained all authorizations and other applicable consents required empowering you to enter into this Agreement.
 *
 *
 *
 * --/COPYRIGHT--*/
//#############################################################################
//
//! \file   hmi.c
//!
//! \brief  Wrapper for Legacy GUI working with Gas Library
//!
//
//  Group:          MSP
//  Target Device:  Banshee
//
//  (C) Copyright 2015, Texas Instruments, Inc.
//#############################################################################
// TI Release: __PRODUCT_NAME__
// Release Date: __PACKAGE_RELEASE_DATE__
//#############################################################################

#include "hmi.h"
#include "hal.h"
#include "gasMeteringUserConfig.h"

#if defined(__TI_COMPILER_VERSION__)
#pragma PERSISTENT(gHMI)
#define __persistent
#elif defined(__IAR_SYSTEMS_ICC__)
#else
#error "Compiler is not supported by Gas Metering Library"
#endif
/*! HMI structure */
__persistent HMI_Obj_t gHMI =
{
        .status = HMI_STATUS_OK,
        .sampleCounter = 0,
        .errorCounter = 0,
        .errorLog = {0},
        .canUseLPM3 = true,
};

/*! Pointer to the configuration received from GUI */
t_User_Config *GUI_User_Config;

#ifdef HMI_DEBUG_COMMANDS
static void Debug_command_Process(uint8_t cmd);
#endif
static bool HMI_ParameterValidation(void);


void HMI_Init(void)
{
    // Initialize GUI Communication
    GUI_Comm_Init();
    GUI_User_Config = GetUserConfigPtr();
    gHMI.status = HMI_STATUS_OK;
    gHMI.canUseLPM3 = true;
    hMIHAL_Init();
}

void HMI_PreMeasurement_Update(void)
{
    uint8_t received_byte;
    // Prior to start of each measurement, if new configuration is available at GUI,
    //  Receive Configuration parameters from GUI
    if (GUI_Comm_IsNewPacketAvailable(&received_byte) == true)
    {
        hMIHAL_SetLED(HMIHAL_LED2);
        if (received_byte == SERIALCOMM_WAKE_FROM_PC)
        {
            // PC is sending a wake request to update parameters or configuration
            GUI_Comm_RxEnable();
            // Check for GUI changes and update parameters if required
            GUI_Comm_Request_UserSelection();
            if (GUI_User_Config->bParam_Update == true)
            {
                GUI_Comm_Request_Update_Params();
            }
            GUI_Comm_RxDisable();
        }
#ifdef HMI_DEBUG_COMMANDS
        else
        {
            Debug_command_Process(received_byte);
        }
#endif
    }

    if (gHMI.status == HMI_STATUS_OK)
    {
        // Clear LED1 if there are no errors
        hMIHAL_ClearLED(HMIHAL_LED2);
    }


}

void HMI_PostMeasurement_Update(void)
{
    // Update GUI with Waveform if requested
    if (GUI_User_Config->bUps_Dns == true)
    {
        GUI_Comm_Send_UPS_DNS();
        GUI_User_Config->bUps_Dns = false;
    }
}

void HMI_PostAlgorithm_Update(GASMETERING_Algorithms_Results * alg_res)
{
    t_Calc_Results *GUI_Results;

    if (!gHMI.canUseLPM3)
    {
        // Heart-beat for each capture, will be turned off after algorithm
        hMIHAL_SetLED(HMIHAL_LED1);
    }

    // Increment 32-bit counter
    gHMI.sampleCounter++;

    // Update GUI with results
    if (GUI_User_Config->bActive == true)
    {
        GUI_Results = GetCalcResultPtr();

        GUI_Results->dDelta_Std = 0;
        GUI_Results->dDeltaTOF = alg_res->deltaTOF;
        GUI_Results->fAvg_UPS_TotalTOF = alg_res->totalTOF_UPS;
        GUI_Results->fAvg_DNS_TotalTOF = alg_res->totalTOF_DNS;
        GUI_Results->fVolume = alg_res->volumeFlowRate;

        GUI_Comm_Send_Results();
    }


    // Clear the status if it's only a fault
    if (gHMI.status == HMI_STATUS_FAULT)
    {
        gHMI.status = HMI_STATUS_OK;
    }

    if (hMIHAL_getLPMButtonStatus() == true)
    {
        gHMI.canUseLPM3 ^= 1;
        hMIHAL_clearLPMButtonStatus();
        hMIHAL_enableLPMButton();
    }

    // Heart-beat for each capture, is turned on after capture
    hMIHAL_ClearLED(HMIHAL_LED1);

}



void HMI_UpdateParamsFromGUI(void)
{
    GASMETERING_return_code code;
    extern int16_t binaryArray4MSPS[];
    uint16_t i, j, idx4MSPS;

    if (HMI_ParameterValidation() == false)
    {
        return;
    }

    gGasMeteringConfig.pMeasurementConfiguration->txPatternSize = GUI_User_Config->decimalArrayLength;
    gGasMeteringConfig.pMeasurementConfiguration->binTxPatternsize = GUI_User_Config->decimatedBinaryArrayLength;

    // Update the measurement configuration (_GASMETERING_Measurement_Configuration_)
    gGasMeteringConfig.pMeasurementConfiguration->gapPlsSrtandADCCap_usec = (GUI_User_Config->u16GapStartCapt >> 2);
    gGasMeteringConfig.pMeasurementConfiguration->numOfPulses = GUI_User_Config->u16NumPulses;
    // u16GapUpsDns is in 4096Hz cycles. Conversion to us = u16GapUpsDns/4096*1E6 = u16GapUpsDns*~245 (rounding up)
    gGasMeteringConfig.pMeasurementConfiguration->gapUPSandDNS_usec = (GUI_User_Config->u16GapUpsDns*245);
    gGasMeteringConfig.pMeasurementConfiguration->gapDNSandUPS_msec = (GUI_User_Config->u16GapDnsUps);
    gGasMeteringConfig.pMeasurementConfiguration->isGainControlEnabled = GUI_User_Config->u8GainControl;
    gGasMeteringConfig.pMeterConfiguration->meterConstant = GUI_User_Config->fAreaConst;

    // Developer Configuration
    if ( GUI_User_Config->u16AdcSamplingFreq_KHz == 100 )
    {
        gGasMeteringConfig.pMeasurementConfiguration->adcSamplingFreq = GASMETERING_ADC_sampling_freq_100_KHz;
    }
    else
    {
        gGasMeteringConfig.pMeasurementConfiguration->adcSamplingFreq = GASMETERING_ADC_sampling_freq_200_KHz;
    }

    gGasMeteringConfig.pMeasurementConfiguration->captureDuration_usec = GUI_User_Config->u16CaptureDuration_usec;

    switch (GUI_User_Config->u16SigSamplingFreq_KHz)
    {
        case 2000:
            gGasMeteringConfig.pMeasurementConfiguration->signalSampFreq = GASMETERING_Signal_Sampling_frequency_2000_KHz;
        break;
        default:
        case 1000:
            gGasMeteringConfig.pMeasurementConfiguration->signalSampFreq = GASMETERING_Signal_Sampling_frequency_1000_KHz;
        break;
    }

    gGasMeteringConfig.pMeasurementConfiguration->gapAMPandSampFirstCapture_usec = (GUI_User_Config->u16Param6);

    if(GUI_User_Config->u16CrystalFreq_KHz == 8000)
    {
        gGasMeteringConfig.pSystemConfig->hFXTFreq = GASMETERING_HFXT_freq_8MHz;
    }

    gGasMeteringConfig.pAlgorithmConfiguration->deltaToFOfsset_ps = GUI_User_Config->i16DltOffset_psec;
    gGasMeteringConfig.pAlgorithmConfiguration->absToFAddDelay_ns = GUI_User_Config->i16AbsTOFAdditionalDelay_nsec;
    gGasMeteringConfig.pAlgorithmConfiguration->computationMode = (GASMETERING_Algorithm_Computation_Mode) GUI_User_Config->u16Param3;
    gGasMeteringConfig.pAlgorithmConfiguration->envCrossThreshold = GUI_User_Config->u16Param4;
    gGasMeteringConfig.pAlgorithmConfiguration->negRngDeltaTOF_sec = (float)(GUI_User_Config->u16Param7*1e-6);
    gGasMeteringConfig.pAlgorithmConfiguration->posRngDeltaTOF_sec = (float)(GUI_User_Config->u16Param8*1e-6);
    gGasMeteringConfig.pAlgorithmConfiguration->negRngAbsTOF_sec = (float)(GUI_User_Config->u16Param9*1e-6);
    gGasMeteringConfig.pAlgorithmConfiguration->posRngAbsTOF_sec = (float)(GUI_User_Config->u16Param10*1e-6);

    if (GUI_User_Config->u16Param2 == HMI_CMD_LEAVE_TX_HIGH_ENABLE)
    {
        gGasMeteringConfig.pMeasurementConfiguration->txLineState = GASMETERING_TX_line_state_after_firing_high;
    }
    else if (GUI_User_Config->u16Param2 == HMI_CMD_LEAVE_TX_HIGH_DISABLE)
    {
        gGasMeteringConfig.pMeasurementConfiguration->txLineState = GASMETERING_TX_line_state_after_firing_low;
    }

    if ( (GUI_User_Config->u16Param2 >= HMI_CMD_TX_TAIL_0000) &&
         (GUI_User_Config->u16Param2 <= HMI_CMD_TX_TAIL_1111) )
    {
        if ((gGasMeteringConfig.pMeasurementConfiguration->txPatternSize +2) > GUI_User_Config->MaxdecimalArrayLength)
        {
            // Unsupported TX Pattern
            HMI_ReportAppError(HMI_ERROR_NON_FATAL_INVALID_GUICONFIG, 0x0003);
            return;
        }
        // Change last 4 bits of the 2nd to last byte
        gGasMeteringConfig.pMeasurementConfiguration->pTxPattern[gGasMeteringConfig.pMeasurementConfiguration->txPatternSize-2] &= 0xF0;
        gGasMeteringConfig.pMeasurementConfiguration->pTxPattern[gGasMeteringConfig.pMeasurementConfiguration->txPatternSize-2] |= (GUI_User_Config->u16Param2 - HMI_CMD_TX_TAIL_0000);
        // Change the last byte with the contents of Param5 MSB
        gGasMeteringConfig.pMeasurementConfiguration->pTxPattern[gGasMeteringConfig.pMeasurementConfiguration->txPatternSize-1] = ((GUI_User_Config->u16Param5 & 0xFF00)>>8);
        // Change the byte after last with the contents of Param5 LSB
        gGasMeteringConfig.pMeasurementConfiguration->pTxPattern[gGasMeteringConfig.pMeasurementConfiguration->txPatternSize] = (GUI_User_Config->u16Param5 & 0x00FF);

        // Update the Binary pattern
        for (i=gGasMeteringConfig.pMeasurementConfiguration->txPatternSize-2 ; i<= gGasMeteringConfig.pMeasurementConfiguration->txPatternSize; i++)
        {
            for (j=0; j < 8; j++)
            {
                idx4MSPS = ((i-1)*8) + 1 + j;
                if ((idx4MSPS% (GUI_User_Config->u16FRAC_DELAY)) == 0)
                {
                    if (gGasMeteringConfig.pMeasurementConfiguration->pTxPattern[i] & (1<<(7-j)))
                    {
                        // Bit is a '1'
                        gGasMeteringConfig.pMeasurementConfiguration->pBinTxPattern[idx4MSPS/(GUI_User_Config->u16FRAC_DELAY)] = 1;
                    }
                    else
                    {
                        // Bit is a '0'
                        gGasMeteringConfig.pMeasurementConfiguration->pBinTxPattern[idx4MSPS/(GUI_User_Config->u16FRAC_DELAY)] = -1;
                    }
                }
            }
        }

        // Send 2 additional bytes
        gGasMeteringConfig.pMeasurementConfiguration->txPatternSize += 2;
        gGasMeteringConfig.pMeasurementConfiguration->binTxPatternsize = ((gGasMeteringConfig.pMeasurementConfiguration->txPatternSize -2)*8)/GUI_User_Config->u16FRAC_DELAY;
    }

    if (gGasMeteringConfig.pMeasurementConfiguration->txLineState == GASMETERING_TX_line_state_after_firing_high)
    {
        // Change the last byte to leave the pin high
        gGasMeteringConfig.pMeasurementConfiguration->pTxPattern[gGasMeteringConfig.pMeasurementConfiguration->txPatternSize-1] = 0xFF;
    }
    else
    {
        // Change the last byte to leave the pin low
        gGasMeteringConfig.pMeasurementConfiguration->pTxPattern[gGasMeteringConfig.pMeasurementConfiguration->txPatternSize-1] = 0x00;
    }

    code = GASMETERING_updateUltrasonicMeasurement(&gGasMeteringConfig);
    HAL_setParams(HAL_State_ConfigUpdate);
    HAL_configHardware(HAL_State_ConfigUpdate);

    if (code != GASMETERING_return_code_no_error)
    {
        HMI_ReportAppError(HMI_ERROR_FATAL_USS_RECONFIGURATION, (uint16_t) code);
    }
    else
    {
        // Status is cleared by a new working configuration
        gHMI.status = HMI_STATUS_OK;
    }
}


void HMI_ReportAppError(uint16_t error_type, uint16_t info)
{
    if ((error_type & HMI_ERROR_FATAL(0x00)) == HMI_ERROR_FATAL(0x00))
    {
        // This demo prevents future captures and sets both pins when there is a fatal error
        // This error level has maximum priority and overrides other status
        gHMI.status = HMI_STATUS_FATAL_ERROR;
        hMIHAL_SetLED(HMIHAL_LED1);
        hMIHAL_SetLED(HMIHAL_LED2);
    }
    else if ((error_type & HMI_ERROR_NON_FATAL(0x00)) == HMI_ERROR_NON_FATAL(0x00))
    {
        // This demo sets LED1 when there is a non-fatal error
        // This error level has 2nd highest priority
        if (gHMI.status < HMI_STATUS_NON_FATAL_ERROR)
        {
            gHMI.status = HMI_STATUS_NON_FATAL_ERROR;
        }
        hMIHAL_SetLED(HMIHAL_LED2);
    }
    else if ((error_type & HMI_ERROR_FAULT(0x00)) == HMI_ERROR_FAULT(0x00))
    {
        // LED1 will toggle but it will get cleared on next capture
        // This error level has lowest priority
        if (gHMI.status < HMI_STATUS_FAULT)
        {
            gHMI.status = HMI_STATUS_FAULT;
        }
        hMIHAL_SetLED(HMIHAL_LED2);
    }

    if (gHMI.errorCounter < HMI_ERROR_ARRAY_MAX)
    {
        gHMI.errorLog[gHMI.errorCounter].code = error_type;
        gHMI.errorLog[gHMI.errorCounter].info = info;
        gHMI.errorLog[gHMI.errorCounter].sampleNum = gHMI.sampleCounter;
        gHMI.errorCounter++;
    }
    if (gHMI.errorCounter >= HMI_ERROR_ARRAY_MAX)
    {
        gHMI.errorCounter = 0; // Reset to log as a circular buffer
    }

}

HMI_STATUS_t HMI_GetStatus(void)
{
    return gHMI.status;
}

bool HMI_CanUseLPM3(void)
{
    return gHMI.canUseLPM3;
}

//! \brief Validates parameters from the GUI to Gas library
//!
//! \return false if parameters are invalid, true if no error found
static bool HMI_ParameterValidation(void)
{
    /***** Validation of Parameters *****/
    if (GUI_User_Config->bValid == false)
    {
        // Invalid GUI configuration due to TX arrays
        HMI_ReportAppError(HMI_ERROR_NON_FATAL_INVALID_GUICONFIG, HMI_ERROR_GUI_INVALID_CONFIG);
        return false;
    }

    // XT2_FREQ
    //  Only 8,000
    if (GUI_User_Config->u16CrystalFreq_KHz != 8000)
    {
        HMI_ReportAppError(HMI_ERROR_NON_FATAL_INVALID_GUICONFIG, HMI_ERROR_GUI_INVALID_HFXT);
        return false;
    }

    // ADC Sampling Frequency
    // 100Khz and 200Khz
    if ( ( GUI_User_Config->u16AdcSamplingFreq_KHz != 100 ) &&
         ( GUI_User_Config->u16AdcSamplingFreq_KHz != 200 ) )
    {
        HMI_ReportAppError(HMI_ERROR_NON_FATAL_INVALID_GUICONFIG, HMI_ERROR_GUI_INVALID_ADC_SAMP);
        return false;
    }

    // Signal Sampling Frequency
    // Only 1Msps and 2Msps
    if ( ( GUI_User_Config->u16SigSamplingFreq_KHz != 2000 ) &&
         ( GUI_User_Config->u16SigSamplingFreq_KHz != 1000 ) )
    {
        HMI_ReportAppError(HMI_ERROR_NON_FATAL_INVALID_GUICONFIG, HMI_ERROR_GUI_INVALID_SIGNAL_SAMP);
        return false;
    }

    if ( (GUI_User_Config->u16Param2 >= HMI_CMD_TX_TAIL_0000) &&
         (GUI_User_Config->u16Param2 <= HMI_CMD_TX_TAIL_1111) )
    {
        if ((GUI_User_Config->decimalArrayLength +2) > GUI_User_Config->MaxdecimalArrayLength)
        {
            // Unsupported TX Pattern
            HMI_ReportAppError(HMI_ERROR_NON_FATAL_INVALID_GUICONFIG, HMI_ERROR_GUI_INVALID_TXPATTERN);
            return false;
        }
    }

    return true;
}

//! \brief Process debug commands and sends debug information to terminal
//!
//! \return None
#ifdef HMI_DEBUG_COMMANDS
static void Debug_command_Process(uint8_t cmd)
{
    char debugString[100];
    extern const uint8_t app_version[];
    extern const uint8_t lib_version[];
    uint16_t i;

    switch(cmd)
    {
        case '1':
            // Debug command #1: send current version
           TI_SerialComm_TxString("*** MSP430FR5994 Gas Meter Version ***\n\r");
           TI_SerialComm_TxString("App version = ");
           for (i =0; i < 8; i++)
           {
               if ((i<4) || ((i >= 4) && (app_version[i] != 0x00)))
               {
                   TI_SerialComm_TxHexByte(app_version[i]);
                   TI_SerialComm_TxString(".");
               }
           }
           TI_SerialComm_TxString("\n\r");

           TI_SerialComm_TxString("Lib version = ");
           for (i =0; i < 8; i++)
           {
               if ((i<4) || ((i >= 4) && (lib_version[i] != 0x00)))
               {
                   TI_SerialComm_TxHexByte(lib_version[i]);
                   TI_SerialComm_TxString(".");
               }
           }
           TI_SerialComm_TxString("\n\r");
        break;
        case '2':
            // Debug Command #2: send configuration
            TI_SerialComm_TxString("*** MSP430FR5994 Gas Meter Configuration ***\n\r");
            TI_SerialComm_TxString("System Configuration:\n\r");
            sprintf(debugString, "  hFXTFreq(dec) = %d\n\r", gGasMeteringConfig.pSystemConfig->hFXTFreq);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  runDiagnosticFunctions(hex) = %X\n\r", gGasMeteringConfig.pSystemConfig->runDiagnosticFunctions);
            TI_SerialComm_TxString((uint8_t *) debugString);

            TI_SerialComm_TxString("Meter Configuration:\n\r");
            sprintf(debugString, "  meterConstant(float) = %f\n\r", gGasMeteringConfig.pMeterConfiguration->meterConstant);
            TI_SerialComm_TxString((uint8_t *) debugString);

            TI_SerialComm_TxString("Measurement Configuration:\n\r");
            sprintf(debugString, "  pTxPattern(hex) = %X\n\r", ((uint16_t)((uint32_t) &gGasMeteringConfig.pMeasurementConfiguration->pTxPattern)));
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  txPatternSize(dec) = %d\n\r", gGasMeteringConfig.pMeasurementConfiguration->txPatternSize);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  pBinTxPattern(hex) = %X\n\r", (uint16_t)((uint32_t) &gGasMeteringConfig.pMeasurementConfiguration->pBinTxPattern));
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  binTxPatternsize(dec) = %d\n\r", gGasMeteringConfig.pMeasurementConfiguration->binTxPatternsize);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  gapPlsSrtandADCCap_usec(dec) = %d\n\r", gGasMeteringConfig.pMeasurementConfiguration->gapPlsSrtandADCCap_usec);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  numOfPulses(dec) = %d\n\r", gGasMeteringConfig.pMeasurementConfiguration->numOfPulses);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  gapUPSandDNS_usec(dec) = %d\n\r", gGasMeteringConfig.pMeasurementConfiguration->gapUPSandDNS_usec);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  gapDNSandUPS_msec(dec) = %d\n\r", gGasMeteringConfig.pMeasurementConfiguration->gapDNSandUPS_msec);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  isGainControlEnabled(dec) = %d\n\r", gGasMeteringConfig.pMeasurementConfiguration->isGainControlEnabled);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  adcSamplingFreq(dec) = %d\n\r", gGasMeteringConfig.pMeasurementConfiguration->adcSamplingFreq);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  signalSampFreq(dec) = %d\n\r", gGasMeteringConfig.pMeasurementConfiguration->signalSampFreq);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  captureDuration_usec(dec) = %d\n\r", gGasMeteringConfig.pMeasurementConfiguration->captureDuration_usec);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  isDummyFiringEnabled(dec) = %d\n\r", gGasMeteringConfig.pMeasurementConfiguration->isDummyFiringEnabled);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  gapAMPandSampFirstCapture_usec(dec) = %d\n\r", gGasMeteringConfig.pMeasurementConfiguration->gapAMPandSampFirstCapture_usec);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  gapAMPandRestOfCapture_usec(dec) = %d\n\r", gGasMeteringConfig.pMeasurementConfiguration->gapAMPandRestOfCapture_usec);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  minGapAMPandSampFirstCapture_usec(dec) = %d\n\r", gGasMeteringConfig.pMeasurementConfiguration->minGapAMPandSampFirstCapture_usec);
            TI_SerialComm_TxString((uint8_t *) debugString);


            TI_SerialComm_TxString("Algorithm Configuration:\n\r");
            sprintf(debugString, "  computationMode(dec) = %d\n\r", gGasMeteringConfig.pAlgorithmConfiguration->computationMode);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  deltaToFOfsset_ps(dec) = %d\n\r", gGasMeteringConfig.pAlgorithmConfiguration->deltaToFOfsset_ps);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  absToFAddDelay_ns(dec) = %d\n\r", gGasMeteringConfig.pAlgorithmConfiguration->absToFAddDelay_ns);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  negRngDeltaTOF_sec(float) = %f\n\r", gGasMeteringConfig.pAlgorithmConfiguration->negRngDeltaTOF_sec);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  posRngDeltaTOF_sec(float) = %f\n\r", gGasMeteringConfig.pAlgorithmConfiguration->posRngDeltaTOF_sec);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  negRngAbsTOF_sec(float) = %f\n\r", gGasMeteringConfig.pAlgorithmConfiguration->negRngAbsTOF_sec);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  posRngAbsTOF_sec(float) = %f\n\r", gGasMeteringConfig.pAlgorithmConfiguration->posRngAbsTOF_sec);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  envCrossThreshold(float) = %f\n\r", gGasMeteringConfig.pAlgorithmConfiguration->envCrossThreshold);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  isRunAbsToFUpEnabled(dec) = %d\n\r", gGasMeteringConfig.pAlgorithmConfiguration->isRunAbsToFUpEnabled);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  isRunAbsToFDownEnabled(dec) = %d\n\r", gGasMeteringConfig.pAlgorithmConfiguration->isRunAbsToFDownEnabled);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  isRunDeltaToFUpEnabled(dec) = %d\n\r", gGasMeteringConfig.pAlgorithmConfiguration->isRunDeltaToFUpEnabled);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  isRunFlowEnabled(dec) = %d\n\r", gGasMeteringConfig.pAlgorithmConfiguration->isRunFlowEnabled);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  syncThreshold(dec) = %d\n\r", gGasMeteringConfig.pAlgorithmConfiguration->syncThreshold);
            TI_SerialComm_TxString((uint8_t *) debugString);

            TI_SerialComm_TxString("HAL Functions:\n\r");
            sprintf(debugString, "  pGASMETERING_HAL_restoreSysClock(hex) = %X\n\r", ((uint16_t)((uint32_t) &gGasMeteringConfig.pHalFunctions->pGASMETERING_HAL_restoreSysClock)));
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  pGASMETERING_HAL_generateLPMDelay(hex) = %X\n\r", ((uint16_t)((uint32_t) &gGasMeteringConfig.pHalFunctions->pGASMETERING_HAL_generateLPMDelay)));
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  pGASMETERING_HAL_configSysClockForCapture(hex) = %X\n\r", ((uint16_t)((uint32_t) &gGasMeteringConfig.pHalFunctions->pGASMETERING_HAL_configSysClockForCapture)));
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  pGASMETERING_HAL_configUPDNSample(hex) = %X\n\r", ((uint16_t)((uint32_t) &gGasMeteringConfig.pHalFunctions->pGASMETERING_HAL_configUPDNSample)));
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  pGASMETERING_HAL_configIterationSample(hex) = %X\n\r", ((uint16_t)((uint32_t) &gGasMeteringConfig.pHalFunctions->pGASMETERING_HAL_configIterationSample)));
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  pGASMETERING_HAL_finishIterationSample(hex) = %X\n\r", ((uint16_t)((uint32_t) &gGasMeteringConfig.pHalFunctions->pGASMETERING_HAL_finishIterationSample)));
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  pGASMETERING_HAL_configGPIOAfterFiring(hex) = %X\n\r", ((uint16_t)((uint32_t) &gGasMeteringConfig.pHalFunctions->pGASMETERING_HAL_configGPIOAfterFiring)));
            TI_SerialComm_TxString((uint8_t *) debugString);

        break;
        case '3':
            // Debug Command #3: send current Gas meter handle
            TI_SerialComm_TxString("*** MSP430FR5994 Current Gas Meter Handle ***\n\r");
            sprintf(debugString, "  deltaTOF(float) = %f\n\r", gGasMeteringConfig.pHandle->deltaTOF);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  totalTOF_UPS(float) = %f\n\r", gGasMeteringConfig.pHandle->totalTOF_UPS);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  totalTOF_DNS(float) = %f\n\r", gGasMeteringConfig.pHandle->totalTOF_DNS);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  volumeFlowRate(float) = %f\n\r", gGasMeteringConfig.pHandle->volumeFlowRate);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  volumeScaleFactor(float) = %f\n\r", gGasMeteringConfig.pHandle->volumeScaleFactor);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  dcOffset(float) = %f\n\r", gGasMeteringConfig.pHandle->dcOffset);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  ADCSamplePeriod_sec(float) = %f\n\r", gGasMeteringConfig.pHandle->ADCSamplePeriod_sec);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  ADCStartCaptureInstant_sec(float) = %f\n\r", gGasMeteringConfig.pHandle->ADCStartCaptureInstant_sec);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  ADCAdditionalCaptureDelay_sec(float) = %f\n\r", gGasMeteringConfig.pHandle->ADCAdditionalCaptureDelay_sec);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  arrayTXPtr(hex) = %X\n\r", ((uint16_t)((uint32_t) &gGasMeteringConfig.pHandle->arrayTXPtr)));
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  arrayLengthTX(dec) = %d\n\r", gGasMeteringConfig.pHandle->arrayLengthTX);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  arrayTXbPtr(hex) = %X\n\r", ((uint16_t)((uint32_t) &gGasMeteringConfig.pHandle->arrayTXbPtr)));
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  arrayLengthTXb(dec) = %d\n\r", gGasMeteringConfig.pHandle->arrayLengthTXb);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  arrayUPSPtr(hex) = %X\n\r", ((uint16_t)((uint32_t) &gGasMeteringConfig.pHandle->arrayUPSPtr)));
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  arrayDNSPtr(hex) = %X\n\r", ((uint16_t)((uint32_t) &gGasMeteringConfig.pHandle->arrayDNSPtr)));
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  arrayLengthDNUP(dec) = %d\n\r", gGasMeteringConfig.pHandle->arrayLengthDNUP);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  pDMALEARAMADCArray(hex) = %X\n\r", ((uint16_t)((uint32_t) &gGasMeteringConfig.pHandle->pDMALEARAMADCArray)));
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  dMALEARAMADCArraySize(dec) = %d\n\r", gGasMeteringConfig.pHandle->dMALEARAMADCArraySize);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  aDCSamplePeriod(dec) = %d\n\r", gGasMeteringConfig.pHandle->aDCSamplePeriod);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  fracDelay(dec) = %d\n\r", gGasMeteringConfig.pHandle->fracDelay);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  upsampleFactor(dec) = %d\n\r", gGasMeteringConfig.pHandle->upsampleFactor);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  negRngDeltaTOF(float) = %f\n\r", gGasMeteringConfig.pHandle->negRngDeltaTOF);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  posRngDeltaTOF(float) = %f\n\r", gGasMeteringConfig.pHandle->posRngDeltaTOF);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  negRngAbsTOF(float) = %f\n\r", gGasMeteringConfig.pHandle->negRngAbsTOF);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  posRngAbsTOF(float) = %f\n\r", gGasMeteringConfig.pHandle->posRngAbsTOF);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  corrIdxUPS(dec) = %d\n\r", gGasMeteringConfig.pHandle->corrIdxUPS);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  corrIdxDNS(dec) = %d\n\r", gGasMeteringConfig.pHandle->corrIdxDNS);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  Flag_searchForCorrIdxDNS(dec) = %d\n\r", gGasMeteringConfig.pHandle->Flag_searchForCorrIdxDNS);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  Flag_searchForCorrIdxUPS(dec) = %d\n\r", gGasMeteringConfig.pHandle->Flag_searchForCorrIdxUPS);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  envCrossThreshold(float) = %f\n\r", gGasMeteringConfig.pHandle->envCrossThreshold);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  fracIdxUPS(float) = %f\n\r", gGasMeteringConfig.pHandle->fracIdxUPS);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  fracIdxDNS(float) = %f\n\r", gGasMeteringConfig.pHandle->fracIdxDNS);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  burstDelay(dec) = %d\n\r", gGasMeteringConfig.pHandle->burstDelay);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  busrtStartDelay(dec) = %d\n\r", gGasMeteringConfig.pHandle->busrtStartDelay);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  computationMode(dec) = %d\n\r", gGasMeteringConfig.pHandle->computationMode);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  arrayHFIRPtr(hex) = %X\n\r", ((uint16_t)((uint32_t) &gGasMeteringConfig.pHandle->arrayHFIRPtr)));
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  arrayLengthHFIR(dec) = %d\n\r", gGasMeteringConfig.pHandle->arrayLengthHFIR);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  hFIRCoeffPower2Scale(dec) = %d\n\r", gGasMeteringConfig.pHandle->hFIRCoeffPower2Scale);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  corrValPow2Scale(dec) = %d\n\r", gGasMeteringConfig.pHandle->corrValPow2Scale);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  corrPeakSqValue(long) = %ld\n\r", gGasMeteringConfig.pHandle->corrPeakSqValue);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  firstThresCrossIdx(dec) = %d\n\r", gGasMeteringConfig.pHandle->firstThresCrossIdx);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  firstThresCrossing_sec(float) = %f\n\r", gGasMeteringConfig.pHandle->firstThresCrossing_sec);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "  Flag_searchForFirstIdx(dec) = %d\n\r", gGasMeteringConfig.pHandle->Flag_searchForFirstIdx);
            TI_SerialComm_TxString((uint8_t *) debugString);
        break;
        case '4':
            // Debug Command #4: send additional configuration
            TI_SerialComm_TxString("*** MSP430FR5994 Gas Meter Additional Configuration ***\n\r");
            TI_SerialComm_TxString("Measurement Configuration, TX Pattern[0:txPatternSize]\n\r");
            TI_SerialComm_TxHexArray((uint8_t *) gGasMeteringConfig.pMeasurementConfiguration->pTxPattern, gGasMeteringConfig.pMeasurementConfiguration->txPatternSize);
            TI_SerialComm_TxString("\n\r");

            TI_SerialComm_TxString("Measurement Configuration, BinTX Pattern[0:binTxPatternsize]\n\r");
            TI_SerialComm_TxHexArray((uint8_t *) gGasMeteringConfig.pMeasurementConfiguration->pBinTxPattern, gGasMeteringConfig.pMeasurementConfiguration->binTxPatternsize);
            TI_SerialComm_TxString("\n\r");

            TI_SerialComm_TxString("Handle, TXPtr[0:arrayLengthTX]\n\r");
            TI_SerialComm_TxHexArray((uint8_t *) gGasMeteringConfig.pHandle->arrayTXPtr, gGasMeteringConfig.pHandle->arrayLengthTX);
            TI_SerialComm_TxString("\n\r");

            TI_SerialComm_TxString("Handle, arrayTXbPtr[0:arrayLengthTXb]\n\r");
            TI_SerialComm_TxHexArray((uint8_t *) gGasMeteringConfig.pHandle->arrayTXbPtr, gGasMeteringConfig.pHandle->arrayLengthTXb);
            TI_SerialComm_TxString("\n\r");

            TI_SerialComm_TxString("Handle, arrayUPSPtr[0:arrayLengthDNUP]\n\r");
            TI_SerialComm_TxHexArray((uint8_t *) gGasMeteringConfig.pHandle->arrayUPSPtr, gGasMeteringConfig.pHandle->arrayLengthDNUP);
            TI_SerialComm_TxString("\n\r");

            TI_SerialComm_TxString("Handle, arrayDNSPtr[0:arrayLengthDNUP]\n\r");
            TI_SerialComm_TxHexArray((uint8_t *) gGasMeteringConfig.pHandle->arrayDNSPtr, gGasMeteringConfig.pHandle->arrayLengthDNUP);
            TI_SerialComm_TxString("\n\r");

            TI_SerialComm_TxString("Handle, pDMALEARAMADCArray[0:dMALEARAMADCArraySize]\n\r");
            TI_SerialComm_TxHexArray((uint8_t *) gGasMeteringConfig.pHandle->pDMALEARAMADCArray, gGasMeteringConfig.pHandle->dMALEARAMADCArraySize);
            TI_SerialComm_TxString("\n\r");

            TI_SerialComm_TxString("Handle, arrayHFIRPtr[0:arrayLengthHFIR]\n\r");
            TI_SerialComm_TxHexArray((uint8_t *) gGasMeteringConfig.pHandle->arrayHFIRPtr, gGasMeteringConfig.pHandle->arrayLengthHFIR);
            TI_SerialComm_TxString("\n\r");
        break;
        case '5':
            // Debug Command #5: send status and Error log
            TI_SerialComm_TxString("*** MSP430FR5994 Gas Meter Error log ***\n\r");
            sprintf(debugString, "Current Status = %d\n\r", gHMI.status);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "Circular Error counter = %d\n\r", gHMI.errorCounter);
            TI_SerialComm_TxString((uint8_t *) debugString);

            for (i=0; i < HMI_ERROR_ARRAY_MAX; i++)
            {
                if (gHMI.errorLog[i].code != 0x00)
                {
                    sprintf(debugString, "Error entry = %d\n\r", i);
                    TI_SerialComm_TxString((uint8_t *) debugString);
                    sprintf(debugString, "  code(hex) = %X\n\r", gHMI.errorLog[i].code);
                    TI_SerialComm_TxString((uint8_t *) debugString);
                    sprintf(debugString, "  Addl Info(hex) = %X\n\r", gHMI.errorLog[i].info);
                    TI_SerialComm_TxString((uint8_t *) debugString);
                    sprintf(debugString, "  Sample number (long) = %ld\n\r", gHMI.errorLog[i].sampleNum);
                    TI_SerialComm_TxString((uint8_t *) debugString);
                }
            }
        break;
        case '0':
            // Debug Command #0: Clear error log and status
            TI_SerialComm_TxString("*** MSP430FR5994 Gas Meter Clear Error log ***\n\r");
            gHMI.status = HMI_STATUS_OK;
            gHMI.errorCounter = 0;
            for (i=0; i < HMI_ERROR_ARRAY_MAX; i++)
            {
                gHMI.errorLog[i].code = 0x00;
                gHMI.errorLog[i].info = 0x00;
                gHMI.errorLog[i].sampleNum = 0x00;
            }
            sprintf(debugString, "New Status = %d\n\r", gHMI.status);
            TI_SerialComm_TxString((uint8_t *) debugString);
            sprintf(debugString, "New Error counter = %d\n\r", gHMI.errorCounter);
            TI_SerialComm_TxString((uint8_t *) debugString);
        break;
        default:
            //ignored
            break;
    }

}
#endif
