/*
 * Copyright (c) 2018, Linz Center of Mechatronics GmbH (LCM), web: www.lcm.at
 * All rights reserved.
 */
/*
 * This file is licensed according to the BSD 3-clause license as follows:
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the "Linz Center of Mechatronics GmbH" and "LCM" nor
 *       the names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL "Linz Center of Mechatronics GmbH" BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*
 * This file is part of X2C. web: x2c.lcm.at
 * $LastChangedRevision: 4169 $
 * $LastChangedDate:: 2026-03-31 21:46:59 +0200#$
 */
/* USERCODE-BEGIN:Description                                                                                         */
/* Implementation:
 *
 *   A = -w0/2/Q*Ts
 *   B = -w0/2/Q*(sqrt(4*Q^2-1))*Ts
 *   C = w0*Ts
 *   a = [1, -2 * exp(A) * cos(B), exp(2*A)]
 *   b = [1, -2 * cos(C),          1]
 *
 *   K = sum(a) / sum(b)
 *   b = b * K
 */
/* USERCODE-END:Description                                                                                           */
#include <stddef.h>
#include "AdaptiveNotch_FiP32.h"

/* all used update functions to ram for c2000                                                                         */
#if defined(__ALL_UPDATE_FUNC_2_RAM_C2000__)
    #pragma CODE_SECTION(AdaptiveNotch_FiP32_Update, "ramfuncs")
#endif

/* USERCODE-BEGIN:PreProcessor                                                                                        */
#include "Exp_Data.h"
#include "Sin_Data.h"

/* Inputs */
#define IN              (*block->In)
#define N               (*block->n)

/* Outputs */
#define OUT             (block->Out)

/* Parameter */
#define N_THRESH        (block->n_thresh)
#define A_FACT          (block->a_fact)
#define B_FACT          (block->b_fact)
#define C_FACT          (block->c_fact)
#define SFR_A           (block->sfrA)

/* Variables */
#define A2              (block->a2)
#define A1              (block->a1)
#define B1              (block->b1)
#define GAIN            (block->k)
#define IN_OLD          (block->in_old)
#define IN_VERY_OLD     (block->in_very_old)
#define OUT_OLD         (block->out_old)
#define OUT_VERY_OLD    (block->out_very_old)
#define N_OLD           (block->n_old)

/* Constants */
#define A0              ((int32)INT32_MAX)
#define B0              ((int32)INT32_MAX)
#define B2              ((int32)INT32_MAX)
#define PI_HALF         ((int32)0x40000000)     /* Pi/2 [Q31] */

/* USERCODE-END:PreProcessor                                                                                          */

/**********************************************************************************************************************/
/** Update                                                                                                           **/
/**********************************************************************************************************************/
void AdaptiveNotch_FiP32_Update(ADAPTIVENOTCH_FIP32 *block)
{
/* USERCODE-BEGIN:UpdateFnc                                                                                           */
    int64 temp64;
    int32 absN;

    /* calculate absolute value of speed to ensure correct computation of coefficients */
    absN = getAbsValI32(N);

    if (absN > N_THRESH)
    {
        /* current speed is above threshold -> filter the input signal */
        if (N != N_OLD)
        {
            /* speed has changed -> update filter coefficients */
            int32 expA, cosine, temp;

            /* RULECHECKER_comment(1:0, 1:0, check_inappropriate_int, "see X2C MISRA Deviations, DEV0001", true_no_defect) */
            temp64 = ((int64)absN * (int64)A_FACT) >> SFR_A;  /* A = -w0/2/Q*Ts */
            /* limitation */
            if (temp64 > INT32_MAX)
            {
                temp64 = INT32_MAX;
            }
            else
            {
                if (temp64 < -INT32_MAX)
                {
                    temp64 = -INT32_MAX;
                }
            }
            temp = (int32)temp64;

            /* exp(A)   Previous: LOOKUP32(Exp_Table32, temp, expA); */
            expA = lookupTableInt32(Exp_Table32, temp);

            /** - calculate filter coefficients */
            /* RULECHECKER_comment(1:0, 1:0, check_inappropriate_int, "see X2C MISRA Deviations, DEV0002", true_no_defect) */
            temp = (int32)(((int64)absN * (int64)B_FACT) >> 31u);     /* B = -w0/2/Q*(sqrt(4*Q^2-1))*Ts */
            temp = PI_HALF - temp;                          /* cos(temp) = sin(pi/2 - temp) */

            /* cos(B)   Previous: LOOKUP32(Sin_Table32, temp, cosine); */
            cosine = lookupTableInt32(Sin_Table32, temp);

            /* RULECHECKER_comment(1:0, 4:0, check_inappropriate_int, "see X2C MISRA Deviations, DEV0002", true_no_defect) */
            A1 = -(int32)(((int64)expA * (int64)cosine) >> 31u);      /* -2 * exp(A) * cos(B)  [Q30] */
            A2 = (int32)(((int64)expA * (int64)expA) >> 31u);         /* exp(2*A) [Q31] */

            temp = (int32)(((int64)absN * (int64)C_FACT) >> 31u);     /* C = w0 * Ts */
            temp = PI_HALF - temp;                          /* cos(temp) = sin(pi/2 - temp) */

            /* cos(C)   Previous: LOOKUP32(Sin_Table32, temp, cosine); */
            cosine = lookupTableInt32(Sin_Table32, temp);

            B1 = -cosine;                                   /* -2 * cos(C) [Q30] */

            /** - calculate gain correction value */
            /* RULECHECKER_comment(1:0, 1:0, check_inappropriate_int, "see X2C MISRA Deviations, DEV0004", true_no_defect) */
            GAIN = (int32)((((int64)A0 + (((int64)A1)<<1) + (int64)A2) << 31) / ((((int64)B0)) + (((int64)B1) << 1u) + (((int64)B2)))); /* Q62 / Q31 = Q31 */

            N_OLD = N;
        }

        /** - do the filtering */
        /* RULECHECKER_comment(1:0, 6:0, check_inappropriate_int, "see X2C MISRA Deviations, DEV0002", true_no_defect) */
        temp64  = (int64)IN;                                    /* b0*u(k) */
        temp64 += (((int64)B1 * (int64)IN_OLD) >> 30u);          /* b1*u(k-1)*/
        temp64 += ((int64)IN_VERY_OLD);                         /* b2*u(k-2) */
        temp64  = (temp64 * (int64)GAIN) >> 31u;                    /* adjust gain */
        temp64 -= (((int64)A1 * (int64)OUT_OLD) >> 30u);         /* a1*y(k-1)*/
        temp64 -= (((int64)A2 * (int64)OUT_VERY_OLD) >> 31u);    /* a2*y(k-2)*/

        /** - set output */
        /* Data width limitation */
        if (temp64 > INT32_MAX)
        {
            temp64 = INT32_MAX;
        }
        else
        {
            if (temp64 < -INT32_MAX)
            {
                temp64 = -INT32_MAX;
            }
        }
        OUT = (int32)temp64;            /* y(k) = b0*u(k) + b1*u(k-1) + b2*u(k-2) - a1*y(k-1) - a2*y(k-2) */
    }
    else
    {
        /* current speed is below threshold -> do not filter the input signal */
        OUT = IN;
    }

    /** - save in- and output values for next cycle */
    IN_VERY_OLD = IN_OLD;
    IN_OLD = IN;
    OUT_VERY_OLD = OUT_OLD;
    OUT_OLD = OUT;

/* USERCODE-END:UpdateFnc                                                                                             */

}

/**********************************************************************************************************************/
/** Initialization                                                                                                   **/
/**********************************************************************************************************************/
void AdaptiveNotch_FiP32_Init(ADAPTIVENOTCH_FIP32 *block)
{
    block->identifier = ADAPTIVENOTCH_FIP32_ID;
    block->Out = 0;
/* USERCODE-BEGIN:InitFnc                                                                                             */
    A2 = 0;
    A1 = 0;
    B1 = 0;
    IN_VERY_OLD = 0;
    IN_OLD = 0;
    OUT_VERY_OLD = 0;
    OUT_OLD = 0;
    N_OLD = 0;
/* USERCODE-END:InitFnc                                                                                               */
}

/**********************************************************************************************************************/
/** Load block data                                                                                                  **/
/**********************************************************************************************************************/
uint8 AdaptiveNotch_FiP32_Load(const ADAPTIVENOTCH_FIP32 *block, uint8 data[], uint16 *dataLength, uint16 maxSize)
{
    uint8 error = 0u;
    if (maxSize < 17u)
    {
        error = 1u;
    }
    else
    {
        data[0] = (uint8)((uint32)block->n_thresh & 0xFFu);
        data[1] = (uint8)(((uint32)block->n_thresh >> 8) & 0xFFu);
        data[2] = (uint8)(((uint32)block->n_thresh >> 16) & 0xFFu);
        data[3] = (uint8)(((uint32)block->n_thresh >> 24) & 0xFFu);
        data[4] = (uint8)((uint32)block->a_fact & 0xFFu);
        data[5] = (uint8)(((uint32)block->a_fact >> 8) & 0xFFu);
        data[6] = (uint8)(((uint32)block->a_fact >> 16) & 0xFFu);
        data[7] = (uint8)(((uint32)block->a_fact >> 24) & 0xFFu);
        data[8] = (uint8)((uint32)block->b_fact & 0xFFu);
        data[9] = (uint8)(((uint32)block->b_fact >> 8) & 0xFFu);
        data[10] = (uint8)(((uint32)block->b_fact >> 16) & 0xFFu);
        data[11] = (uint8)(((uint32)block->b_fact >> 24) & 0xFFu);
        data[12] = (uint8)((uint32)block->c_fact & 0xFFu);
        data[13] = (uint8)(((uint32)block->c_fact >> 8) & 0xFFu);
        data[14] = (uint8)(((uint32)block->c_fact >> 16) & 0xFFu);
        data[15] = (uint8)(((uint32)block->c_fact >> 24) & 0xFFu);
        data[16] = (uint8)(block->sfrA & 0xFFu);
        *dataLength = 17u;
/* USERCODE-BEGIN:LoadFnc                                                                                             */
/* USERCODE-END:LoadFnc                                                                                               */
    }
    return (error);
}

/**********************************************************************************************************************/
/** Save block data                                                                                                  **/
/**********************************************************************************************************************/
uint8 AdaptiveNotch_FiP32_Save(ADAPTIVENOTCH_FIP32 *block, const uint8 data[], uint16 dataLength)
{
    uint8 error;
    if (dataLength != 17u)
    {
        error = 1u;
    }
    else
    {
        block->n_thresh = castUint32ToInt32((uint32)((uint32)data[0] | ((uint32)data[1] << 8) | ((uint32)data[2] << 16) | ((uint32)data[3] << 24)));
        block->a_fact = castUint32ToInt32((uint32)((uint32)data[4] | ((uint32)data[5] << 8) | ((uint32)data[6] << 16) | ((uint32)data[7] << 24)));
        block->b_fact = castUint32ToInt32((uint32)((uint32)data[8] | ((uint32)data[9] << 8) | ((uint32)data[10] << 16) | ((uint32)data[11] << 24)));
        block->c_fact = castUint32ToInt32((uint32)((uint32)data[12] | ((uint32)data[13] << 8) | ((uint32)data[14] << 16) | ((uint32)data[15] << 24)));
        block->sfrA = data[16];
        error = 0u;
/* USERCODE-BEGIN:SaveFnc                                                                                             */
/* USERCODE-END:SaveFnc                                                                                               */
    }
    return (error);
}

/**********************************************************************************************************************/
/** Get block element address                                                                                        **/
/**********************************************************************************************************************/
#if !defined(ADAPTIVENOTCH_FIP32_ISLINKED)
void* AdaptiveNotch_FiP32_GetAddress(ADAPTIVENOTCH_FIP32* block, uint16 elementId)
{
    void* addr;
    switch (elementId)
    {
        case 1:
            addr = block->In;
            break;
        case 2:
            addr = block->n;
            break;
        case 3:
            addr = &block->Out;
            break;
        default:
            addr = NULL;
            break;
    }
    return (addr);
}
#endif
